dingrtc 3.9.22 → 3.9.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.umd.js CHANGED
@@ -8,6 +8,6 @@ var n,i,o="function"==typeof Symbol?Symbol:{},a=o.iterator||"@@iterator",s=o.toS
8
8
  * compiled thu, 22 aug 2024 20:30:39 utc
9
9
  * licensed under the bsd-3-clause license
10
10
  * see: https://github.com/dcodeio/protobuf.js for details
11
- */(function(module){!function(g){var r,e,i;r={1:[function(e,t,r){t.exports=function(e,t){for(var r=Array(arguments.length-1),n=0,i=2,o=!0;i<arguments.length;)r[n++]=arguments[i++];return new Promise(function(i,a){r[n]=function(e){if(o)if(o=!1,e)a(e);else{for(var t=Array(arguments.length-1),r=0;r<t.length;)t[r++]=arguments[r];i.apply(null,t)}};try{e.apply(t||null,r)}catch(e){o&&(o=!1,a(e))}})}},{}],2:[function(e,t,r){r.length=function(e){var t=e.length;if(!t)return 0;for(var r=0;1<--t%4&&"="==(e[0|t]||"");)++r;return Math.ceil(3*e.length)/4-r};for(var n=Array(64),i=Array(123),o=0;o<64;)i[n[o]=o<26?o+65:o<52?o+71:o<62?o-4:o-59|43]=o++;r.encode=function(e,t,r){for(var i,o=null,a=[],s=0,c=0;t<r;){var u=e[t++];switch(c){case 0:a[s++]=n[u>>2],i=(3&u)<<4,c=1;break;case 1:a[s++]=n[i|u>>4],i=(15&u)<<2,c=2;break;case 2:a[s++]=n[i|u>>6],a[s++]=n[63&u],c=0}8191<s&&((o=o||[]).push(String.fromCharCode.apply(String,a)),s=0)}return c&&(a[s++]=n[i],a[s++]=61,1===c&&(a[s++]=61)),o?(s&&o.push(String.fromCharCode.apply(String,a.slice(0,s))),o.join("")):String.fromCharCode.apply(String,a.slice(0,s))};var a="invalid encoding";r.decode=function(e,t,r){for(var n,o=r,s=0,c=0;c<e.length;){var u=e.charCodeAt(c++);if(61==u&&1<s)break;if((u=i[u])===g)throw Error(a);switch(s){case 0:n=u,s=1;break;case 1:t[r++]=n<<2|(48&u)>>4,n=u,s=2;break;case 2:t[r++]=(15&n)<<4|(60&u)>>2,n=u,s=3;break;case 3:t[r++]=(3&n)<<6|u,s=0}}if(1===s)throw Error(a);return r-o},r.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}},{}],3:[function(e,t,r){(t.exports=function e(t,r){"string"==typeof t&&(r=t,t=g);var n=[];function i(t){if("string"!=typeof t){var r=o();if(e.verbose&&console.log("codegen: "+r),r="return "+r,t){for(var a=Object.keys(t),s=Array(a.length+1),c=Array(a.length),u=0;u<a.length;)s[u]=a[u],c[u]=t[a[u++]];return s[u]=r,Function.apply(null,s).apply(null,c)}return Function(r)()}for(var l=Array(arguments.length-1),d=0;d<l.length;)l[d]=arguments[++d];if(d=0,t=t.replace(/%([%dfijs])/g,function(e,t){var r=l[d++];switch(t){case"d":case"f":return""+ +(""+r);case"i":return""+Math.floor(r);case"j":return JSON.stringify(r);case"s":return""+r}return"%"}),d!==l.length)throw Error("parameter count mismatch");return n.push(t),i}function o(e){return"function "+(e||r||"")+"("+(t&&t.join(",")||"")+"){\n "+n.join("\n ")+"\n}"}return i.toString=o,i}).verbose=!1},{}],4:[function(e,t,r){function n(){this.t={}}(t.exports=n).prototype.on=function(e,t,r){return(this.t[e]||(this.t[e]=[])).push({fn:t,ctx:r||this}),this},n.prototype.off=function(e,t){if(e===g)this.t={};else if(t===g)this.t[e]=[];else for(var r=this.t[e],n=0;n<r.length;)r[n].fn===t?r.splice(n,1):++n;return this},n.prototype.emit=function(e){var t=this.t[e];if(t){for(var r=[],n=1;n<arguments.length;)r.push(arguments[n++]);for(n=0;n<t.length;)t[n].fn.apply(t[n++].ctx,r)}return this}},{}],5:[function(e,t,r){t.exports=o;var n=e(1),i=e(7)("fs");function o(e,t,r){return t="function"==typeof t?(r=t,{}):t||{},r?!t.xhr&&i&&i.readFile?i.readFile(e,function(n,i){return n&&"undefined"!=typeof XMLHttpRequest?o.xhr(e,t,r):n?r(n):r(null,t.binary?i:i.toString("utf8"))}):o.xhr(e,t,r):n(o,this,e,t)}o.xhr=function(e,t,r){var n=new XMLHttpRequest;n.onreadystatechange=function(){if(4!==n.readyState)return g;if(0!==n.status&&200!==n.status)return r(Error("status "+n.status));if(t.binary){if(!(e=n.response))for(var e=[],i=0;i<n.responseText.length;++i)e.push(255&n.responseText.charCodeAt(i));return r(null,"undefined"!=typeof Uint8Array?new Uint8Array(e):e)}return r(null,n.responseText)},t.binary&&("overrideMimeType"in n&&n.overrideMimeType("text/plain; charset=x-user-defined"),n.responseType="arraybuffer"),n.open("GET",e),n.send()}},{1:1,7:7}],6:[function(e,t,r){function n(e){function t(e,t,r,n){var i=t<0?1:0;e(0===(t=i?-t:t)?0<1/t?0:2147483648:isNaN(t)?2143289344:34028234663852886e22<t?(i<<31|2139095040)>>>0:t<11754943508222875e-54?(i<<31|Math.round(t/1401298464324817e-60))>>>0:(i<<31|127+(e=Math.floor(Math.log(t)/Math.LN2))<<23|8388607&Math.round(t*Math.pow(2,-e)*8388608))>>>0,r,n)}function r(e,t,r){return t=2*((e=e(t,r))>>31)+1,r=e>>>23&255,e&=8388607,255==r?e?NaN:1/0*t:0==r?1401298464324817e-60*t*e:t*Math.pow(2,r-150)*(8388608+e)}function n(e,t,r){d[0]=e,t[r]=p[0],t[r+1]=p[1],t[r+2]=p[2],t[r+3]=p[3]}function c(e,t,r){d[0]=e,t[r]=p[3],t[r+1]=p[2],t[r+2]=p[1],t[r+3]=p[0]}function u(e,t){return p[0]=e[t],p[1]=e[t+1],p[2]=e[t+2],p[3]=e[t+3],d[0]}function l(e,t){return p[3]=e[t],p[2]=e[t+1],p[1]=e[t+2],p[0]=e[t+3],d[0]}var d,p,f,h,g;function m(e,t,r,n,i,o){var a,s=n<0?1:0;0===(n=s?-n:n)?(e(0,i,o+t),e(0<1/n?0:2147483648,i,o+r)):isNaN(n)?(e(0,i,o+t),e(2146959360,i,o+r)):17976931348623157e292<n?(e(0,i,o+t),e((s<<31|2146435072)>>>0,i,o+r)):n<22250738585072014e-324?(e((a=n/5e-324)>>>0,i,o+t),e((s<<31|a/4294967296)>>>0,i,o+r)):(e(4503599627370496*(a=n*Math.pow(2,-(n=1024===(n=Math.floor(Math.log(n)/Math.LN2))?1023:n)))>>>0,i,o+t),e((s<<31|n+1023<<20|1048576*a&1048575)>>>0,i,o+r))}function v(e,t,r,n,i){return t=e(n,i+t),n=2*((e=e(n,i+r))>>31)+1,r=4294967296*(1048575&e)+t,2047==(i=e>>>20&2047)?r?NaN:1/0*n:0==i?5e-324*n*r:n*Math.pow(2,i-1075)*(r+4503599627370496)}function y(e,t,r){f[0]=e,t[r]=h[0],t[r+1]=h[1],t[r+2]=h[2],t[r+3]=h[3],t[r+4]=h[4],t[r+5]=h[5],t[r+6]=h[6],t[r+7]=h[7]}function b(e,t,r){f[0]=e,t[r]=h[7],t[r+1]=h[6],t[r+2]=h[5],t[r+3]=h[4],t[r+4]=h[3],t[r+5]=h[2],t[r+6]=h[1],t[r+7]=h[0]}function S(e,t){return h[0]=e[t],h[1]=e[t+1],h[2]=e[t+2],h[3]=e[t+3],h[4]=e[t+4],h[5]=e[t+5],h[6]=e[t+6],h[7]=e[t+7],f[0]}function _(e,t){return h[7]=e[t],h[6]=e[t+1],h[5]=e[t+2],h[4]=e[t+3],h[3]=e[t+4],h[2]=e[t+5],h[1]=e[t+6],h[0]=e[t+7],f[0]}return"undefined"!=typeof Float32Array?(d=new Float32Array([-0]),g=128===(p=new Uint8Array(d.buffer))[3],e.writeFloatLE=g?n:c,e.writeFloatBE=g?c:n,e.readFloatLE=g?u:l,e.readFloatBE=g?l:u):(e.writeFloatLE=t.bind(null,i),e.writeFloatBE=t.bind(null,o),e.readFloatLE=r.bind(null,a),e.readFloatBE=r.bind(null,s)),"undefined"!=typeof Float64Array?(f=new Float64Array([-0]),g=128===(h=new Uint8Array(f.buffer))[7],e.writeDoubleLE=g?y:b,e.writeDoubleBE=g?b:y,e.readDoubleLE=g?S:_,e.readDoubleBE=g?_:S):(e.writeDoubleLE=m.bind(null,i,0,4),e.writeDoubleBE=m.bind(null,o,4,0),e.readDoubleLE=v.bind(null,a,0,4),e.readDoubleBE=v.bind(null,s,4,0)),e}function i(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function o(e,t,r){t[r]=e>>>24,t[r+1]=e>>>16&255,t[r+2]=e>>>8&255,t[r+3]=255&e}function a(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function s(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}t.exports=n(n)},{}],7:[function(t,i,n){function r(t){try{var i=eval("require")(t);if(i&&(i.length||Object.keys(i).length))return i}catch(t){}return null}i.exports=r},{}],8:[function(e,t,r){var n=r.isAbsolute=function(e){return/^(?:\/|\w+:)/.test(e)},i=r.normalize=function(e){var t=(e=e.replace(/\\/g,"/").replace(/\/{2,}/g,"/")).split("/"),r=n(e);e="",r&&(e=t.shift()+"/");for(var i=0;i<t.length;)".."===t[i]?0<i&&".."!==t[i-1]?t.splice(--i,2):r?t.splice(i,1):++i:"."===t[i]?t.splice(i,1):++i;return e+t.join("/")};r.resolve=function(e,t,r){return r||(t=i(t)),!n(t)&&(e=(e=r?e:i(e)).replace(/(?:\/|^)[^/]+$/,"")).length?i(e+"/"+t):t}},{}],9:[function(e,t,r){t.exports=function(e,t,r){var n=r||8192,i=n>>>1,o=null,a=n;return function(r){return r<1||i<r?e(r):(n<a+r&&(o=e(n),a=0),r=t.call(o,a,a+=r),7&a&&(a=1+(7|a)),r)}}},{}],10:[function(e,t,r){r.length=function(e){for(var t,r=0,n=0;n<e.length;++n)(t=e.charCodeAt(n))<128?r+=1:t<2048?r+=2:55296==(64512&t)&&56320==(64512&e.charCodeAt(n+1))?(++n,r+=4):r+=3;return r},r.read=function(e,t,r){if(r-t<1)return"";for(var n,i=null,o=[],a=0;t<r;)(n=e[t++])<128?o[a++]=n:191<n&&n<224?o[a++]=(31&n)<<6|63&e[t++]:239<n&&n<365?(n=((7&n)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,o[a++]=55296+(n>>10),o[a++]=56320+(1023&n)):o[a++]=(15&n)<<12|(63&e[t++])<<6|63&e[t++],8191<a&&((i=i||[]).push(String.fromCharCode.apply(String,o)),a=0);return i?(a&&i.push(String.fromCharCode.apply(String,o.slice(0,a))),i.join("")):String.fromCharCode.apply(String,o.slice(0,a))},r.write=function(e,t,r){for(var n,i,o=r,a=0;a<e.length;++a)(n=e.charCodeAt(a))<128?t[r++]=n:(n<2048?t[r++]=n>>6|192:(55296==(64512&n)&&56320==(64512&(i=e.charCodeAt(a+1)))?(++a,t[r++]=(n=65536+((1023&n)<<10)+(1023&i))>>18|240,t[r++]=n>>12&63|128):t[r++]=n>>12|224,t[r++]=n>>6&63|128),t[r++]=63&n|128);return r-o}},{}],11:[function(e,t,r){var n=e(14),i=e(33);function o(e,t,r,i){var o=!1;if(t.resolvedType)if(t.resolvedType instanceof n){e("switch(d%s){",i);for(var a=t.resolvedType.values,s=Object.keys(a),c=0;c<s.length;++c)a[s[c]]!==t.typeDefault||o||(e("default:")('if(typeof(d%s)==="number"){m%s=d%s;break}',i,i,i),t.repeated||e("break"),o=!0),e("case%j:",s[c])("case %i:",a[s[c]])("m%s=%j",i,a[s[c]])("break");e("}")}else e('if(typeof d%s!=="object")',i)("throw TypeError(%j)",t.fullName+": object expected")("m%s=types[%i].fromObject(d%s)",i,r,i);else{var u=!1;switch(t.type){case"double":case"float":e("m%s=Number(d%s)",i,i);break;case"uint32":case"fixed32":e("m%s=d%s>>>0",i,i);break;case"int32":case"sint32":case"sfixed32":e("m%s=d%s|0",i,i);break;case"uint64":u=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":e("if(util.Long)")("(m%s=util.Long.fromValue(d%s)).unsigned=%j",i,i,u)('else if(typeof d%s==="string")',i)("m%s=parseInt(d%s,10)",i,i)('else if(typeof d%s==="number")',i)("m%s=d%s",i,i)('else if(typeof d%s==="object")',i)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)",i,i,i,u?"true":"");break;case"bytes":e('if(typeof d%s==="string")',i)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)",i,i,i)("else if(d%s.length >= 0)",i)("m%s=d%s",i,i);break;case"string":e("m%s=String(d%s)",i,i);break;case"bool":e("m%s=Boolean(d%s)",i,i)}}return e}function a(e,t,r,i){if(t.resolvedType)t.resolvedType instanceof n?e("d%s=o.enums===String?(types[%i].values[m%s]===undefined?m%s:types[%i].values[m%s]):m%s",i,r,i,i,r,i,i):e("d%s=types[%i].toObject(m%s,o)",i,r,i);else{var o=!1;switch(t.type){case"double":case"float":e("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s",i,i,i,i);break;case"uint64":o=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":e('if(typeof m%s==="number")',i)("d%s=o.longs===String?String(m%s):m%s",i,i,i)("else")("d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s",i,i,i,i,o?"true":"",i);break;case"bytes":e("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s",i,i,i,i,i);break;default:e("d%s=m%s",i,i)}}return e}r.fromObject=function(e){var t=e.fieldsArray,r=i.codegen(["d"],e.name+"$fromObject")("if(d instanceof this.ctor)")("return d");if(!t.length)return r("return new this.ctor");r("var m=new this.ctor");for(var a=0;a<t.length;++a){var s=t[a].resolve(),c=i.safeProp(s.name);s.map?(r("if(d%s){",c)('if(typeof d%s!=="object")',c)("throw TypeError(%j)",s.fullName+": object expected")("m%s={}",c)("for(var ks=Object.keys(d%s),i=0;i<ks.length;++i){",c),o(r,s,a,c+"[ks[i]]")("}")("}")):s.repeated?(r("if(d%s){",c)("if(!Array.isArray(d%s))",c)("throw TypeError(%j)",s.fullName+": array expected")("m%s=[]",c)("for(var i=0;i<d%s.length;++i){",c),o(r,s,a,c+"[i]")("}")("}")):(s.resolvedType instanceof n||r("if(d%s!=null){",c),o(r,s,a,c),s.resolvedType instanceof n||r("}"))}return r("return m")},r.toObject=function(e){var t=e.fieldsArray.slice().sort(i.compareFieldsById);if(!t.length)return i.codegen()("return {}");for(var r=i.codegen(["m","o"],e.name+"$toObject")("if(!o)")("o={}")("var d={}"),o=[],s=[],c=[],u=0;u<t.length;++u)t[u].partOf||(t[u].resolve().repeated?o:t[u].map?s:c).push(t[u]);if(o.length){for(r("if(o.arrays||o.defaults){"),u=0;u<o.length;++u)r("d%s=[]",i.safeProp(o[u].name));r("}")}if(s.length){for(r("if(o.objects||o.defaults){"),u=0;u<s.length;++u)r("d%s={}",i.safeProp(s[u].name));r("}")}if(c.length){for(r("if(o.defaults){"),u=0;u<c.length;++u){var l,d=c[u],p=i.safeProp(d.name);d.resolvedType instanceof n?r("d%s=o.enums===String?%j:%j",p,d.resolvedType.valuesById[d.typeDefault],d.typeDefault):d.long?r("if(util.Long){")("var n=new util.Long(%i,%i,%j)",d.typeDefault.low,d.typeDefault.high,d.typeDefault.unsigned)("d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n",p)("}else")("d%s=o.longs===String?%j:%i",p,d.typeDefault.toString(),d.typeDefault.toNumber()):d.bytes?(l="["+Array.prototype.slice.call(d.typeDefault).join(",")+"]",r("if(o.bytes===String)d%s=%j",p,String.fromCharCode.apply(String,d.typeDefault))("else{")("d%s=%s",p,l)("if(o.bytes!==Array)d%s=util.newBuffer(d%s)",p,p)("}")):r("d%s=%j",p,d.typeDefault)}r("}")}var f=!1;for(u=0;u<t.length;++u){d=t[u];var h=e.i.indexOf(d);p=i.safeProp(d.name),d.map?(f||(f=!0,r("var ks2")),r("if(m%s&&(ks2=Object.keys(m%s)).length){",p,p)("d%s={}",p)("for(var j=0;j<ks2.length;++j){"),a(r,d,h,p+"[ks2[j]]")("}")):d.repeated?(r("if(m%s&&m%s.length){",p,p)("d%s=[]",p)("for(var j=0;j<m%s.length;++j){",p),a(r,d,h,p+"[j]")("}")):(r("if(m%s!=null&&m.hasOwnProperty(%j)){",p,d.name),a(r,d,h,p),d.partOf&&r("if(o.oneofs)")("d%s=%j",i.safeProp(d.partOf.name),d.name)),r("}")}return r("return d")}},{14:14,33:33}],12:[function(e,t,r){t.exports=function(e){var t=o.codegen(["r","l"],e.name+"$decode")("if(!(r instanceof Reader))")("r=Reader.create(r)")("var c=l===undefined?r.len:r.pos+l,m=new this.ctor"+(e.fieldsArray.filter(function(e){return e.map}).length?",k,value":""))("while(r.pos<c){")("var t=r.uint32()");e.group&&t("if((t&7)===4)")("break"),t("switch(t>>>3){");for(var r=0;r<e.fieldsArray.length;++r){var a=e.i[r].resolve(),s=a.resolvedType instanceof n?"int32":a.type,c="m"+o.safeProp(a.name);t("case %i: {",a.id),a.map?(t("if(%s===util.emptyObject)",c)("%s={}",c)("var c2 = r.uint32()+r.pos"),i.defaults[a.keyType]!==g?t("k=%j",i.defaults[a.keyType]):t("k=null"),i.defaults[s]!==g?t("value=%j",i.defaults[s]):t("value=null"),t("while(r.pos<c2){")("var tag2=r.uint32()")("switch(tag2>>>3){")("case 1: k=r.%s(); break",a.keyType)("case 2:"),i.basic[s]===g?t("value=types[%i].decode(r,r.uint32())",r):t("value=r.%s()",s),t("break")("default:")("r.skipType(tag2&7)")("break")("}")("}"),i.long[a.keyType]!==g?t('%s[typeof k==="object"?util.longToHash(k):k]=value',c):t("%s[k]=value",c)):a.repeated?(t("if(!(%s&&%s.length))",c,c)("%s=[]",c),i.packed[s]!==g&&t("if((t&7)===2){")("var c2=r.uint32()+r.pos")("while(r.pos<c2)")("%s.push(r.%s())",c,s)("}else"),i.basic[s]===g?t(a.resolvedType.group?"%s.push(types[%i].decode(r))":"%s.push(types[%i].decode(r,r.uint32()))",c,r):t("%s.push(r.%s())",c,s)):i.basic[s]===g?t(a.resolvedType.group?"%s=types[%i].decode(r)":"%s=types[%i].decode(r,r.uint32())",c,r):t("%s=r.%s()",c,s),t("break")("}")}for(t("default:")("r.skipType(t&7)")("break")("}")("}"),r=0;r<e.i.length;++r){var u=e.i[r];u.required&&t("if(!m.hasOwnProperty(%j))",u.name)("throw util.ProtocolError(%j,{instance:m})","missing required '"+u.name+"'")}return t("return m")};var n=e(14),i=e(32),o=e(33)},{14:14,32:32,33:33}],13:[function(e,t,r){t.exports=function(e){for(var t,r=o.codegen(["m","w"],e.name+"$encode")("if(!w)")("w=Writer.create()"),s=e.fieldsArray.slice().sort(o.compareFieldsById),c=0;c<s.length;++c){var u=s[c].resolve(),l=e.i.indexOf(u),d=u.resolvedType instanceof n?"int32":u.type,p=i.basic[d];t="m"+o.safeProp(u.name),u.map?(r("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){",t,u.name)("for(var ks=Object.keys(%s),i=0;i<ks.length;++i){",t)("w.uint32(%i).fork().uint32(%i).%s(ks[i])",(u.id<<3|2)>>>0,8|i.mapKey[u.keyType],u.keyType),p===g?r("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()",l,t):r(".uint32(%i).%s(%s[ks[i]]).ldelim()",16|p,d,t),r("}")("}")):u.repeated?(r("if(%s!=null&&%s.length){",t,t),u.packed&&i.packed[d]!==g?r("w.uint32(%i).fork()",(u.id<<3|2)>>>0)("for(var i=0;i<%s.length;++i)",t)("w.%s(%s[i])",d,t)("w.ldelim()"):(r("for(var i=0;i<%s.length;++i)",t),p===g?a(r,u,l,t+"[i]"):r("w.uint32(%i).%s(%s[i])",(u.id<<3|p)>>>0,d,t)),r("}")):(u.optional&&r("if(%s!=null&&Object.hasOwnProperty.call(m,%j))",t,u.name),p===g?a(r,u,l,t):r("w.uint32(%i).%s(%s)",(u.id<<3|p)>>>0,d,t))}return r("return w")};var n=e(14),i=e(32),o=e(33);function a(e,t,r,n){t.resolvedType.group?e("types[%i].encode(%s,w.uint32(%i)).uint32(%i)",r,n,(t.id<<3|3)>>>0,(t.id<<3|4)>>>0):e("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()",r,n,(t.id<<3|2)>>>0)}},{14:14,32:32,33:33}],14:[function(e,t,r){t.exports=a;var n=e(22),i=(((a.prototype=Object.create(n.prototype)).constructor=a).className="Enum",e(21)),o=e(33);function a(e,t,r,i,o,a){if(n.call(this,e,r),t&&"object"!=typeof t)throw TypeError("values must be an object");if(this.valuesById={},this.values=Object.create(this.valuesById),this.comment=i,this.comments=o||{},this.valuesOptions=a,this.reserved=g,t)for(var s=Object.keys(t),c=0;c<s.length;++c)"number"==typeof t[s[c]]&&(this.valuesById[this.values[s[c]]=t[s[c]]]=s[c])}a.fromJSON=function(e,t){return(e=new a(e,t.values,t.options,t.comment,t.comments)).reserved=t.reserved,e},a.prototype.toJSON=function(e){return e=!!e&&!!e.keepComments,o.toObject(["options",this.options,"valuesOptions",this.valuesOptions,"values",this.values,"reserved",this.reserved&&this.reserved.length?this.reserved:g,"comment",e?this.comment:g,"comments",e?this.comments:g])},a.prototype.add=function(e,t,r,n){if(!o.isString(e))throw TypeError("name must be a string");if(!o.isInteger(t))throw TypeError("id must be an integer");if(this.values[e]!==g)throw Error("duplicate name '"+e+"' in "+this);if(this.isReservedId(t))throw Error("id "+t+" is reserved in "+this);if(this.isReservedName(e))throw Error("name '"+e+"' is reserved in "+this);if(this.valuesById[t]!==g){if(!this.options||!this.options.allow_alias)throw Error("duplicate id "+t+" in "+this);this.values[e]=t}else this.valuesById[this.values[e]=t]=e;return n&&(this.valuesOptions===g&&(this.valuesOptions={}),this.valuesOptions[e]=n||null),this.comments[e]=r||null,this},a.prototype.remove=function(e){if(!o.isString(e))throw TypeError("name must be a string");var t=this.values[e];if(null==t)throw Error("name '"+e+"' does not exist in "+this);return delete this.valuesById[t],delete this.values[e],delete this.comments[e],this.valuesOptions&&delete this.valuesOptions[e],this},a.prototype.isReservedId=function(e){return i.isReservedId(this.reserved,e)},a.prototype.isReservedName=function(e){return i.isReservedName(this.reserved,e)}},{21:21,22:22,33:33}],15:[function(e,t,r){t.exports=u;var n,i=e(22),o=(((u.prototype=Object.create(i.prototype)).constructor=u).className="Field",e(14)),a=e(32),s=e(33),c=/^required|optional|repeated$/;function u(e,t,r,n,o,u,l){if(s.isObject(n)?(l=o,u=n,n=o=g):s.isObject(o)&&(l=u,u=o,o=g),i.call(this,e,u),!s.isInteger(t)||t<0)throw TypeError("id must be a non-negative integer");if(!s.isString(r))throw TypeError("type must be a string");if(n!==g&&!c.test(n=n.toString().toLowerCase()))throw TypeError("rule must be a string rule");if(o!==g&&!s.isString(o))throw TypeError("extend must be a string");this.rule=(n="proto3_optional"===n?"optional":n)&&"optional"!==n?n:g,this.type=r,this.id=t,this.extend=o||g,this.required="required"===n,this.optional=!this.required,this.repeated="repeated"===n,this.map=!1,this.message=null,this.partOf=null,this.typeDefault=null,this.defaultValue=null,this.long=!!s.Long&&a.long[r]!==g,this.bytes="bytes"===r,this.resolvedType=null,this.extensionField=null,this.declaringField=null,this.n=null,this.comment=l}u.fromJSON=function(e,t){return new u(e,t.id,t.type,t.rule,t.extend,t.options,t.comment)},Object.defineProperty(u.prototype,"packed",{get:function(){return null===this.n&&(this.n=!1!==this.getOption("packed")),this.n}}),u.prototype.setOption=function(e,t,r){return"packed"===e&&(this.n=null),i.prototype.setOption.call(this,e,t,r)},u.prototype.toJSON=function(e){return e=!!e&&!!e.keepComments,s.toObject(["rule","optional"!==this.rule&&this.rule||g,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",e?this.comment:g])},u.prototype.resolve=function(){var e;return this.resolved?this:((this.typeDefault=a.defaults[this.type])===g?(this.resolvedType=(this.declaringField||this).parent.lookupTypeOrEnum(this.type),this.resolvedType instanceof n?this.typeDefault=null:this.typeDefault=this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]):this.options&&this.options.proto3_optional&&(this.typeDefault=null),this.options&&null!=this.options.default&&(this.typeDefault=this.options.default,this.resolvedType instanceof o&&"string"==typeof this.typeDefault&&(this.typeDefault=this.resolvedType.values[this.typeDefault])),this.options&&(!0!==this.options.packed&&(this.options.packed===g||!this.resolvedType||this.resolvedType instanceof o)||delete this.options.packed,Object.keys(this.options).length||(this.options=g)),this.long?(this.typeDefault=s.Long.fromNumber(this.typeDefault,"u"==(this.type[0]||"")),Object.freeze&&Object.freeze(this.typeDefault)):this.bytes&&"string"==typeof this.typeDefault&&(s.base64.test(this.typeDefault)?s.base64.decode(this.typeDefault,e=s.newBuffer(s.base64.length(this.typeDefault)),0):s.utf8.write(this.typeDefault,e=s.newBuffer(s.utf8.length(this.typeDefault)),0),this.typeDefault=e),this.map?this.defaultValue=s.emptyObject:this.repeated?this.defaultValue=s.emptyArray:this.defaultValue=this.typeDefault,this.parent instanceof n&&(this.parent.ctor.prototype[this.name]=this.defaultValue),i.prototype.resolve.call(this))},u.d=function(e,t,r,n){return"function"==typeof t?t=s.decorateType(t).name:t&&"object"==typeof t&&(t=s.decorateEnum(t).name),function(i,o){s.decorateType(i.constructor).add(new u(o,e,t,r,{default:n}))}},u.r=function(e){n=e}},{14:14,22:22,32:32,33:33}],16:[function(e,t,r){var n=t.exports=e(17);n.build="light",n.load=function(e,t,r){return(t="function"==typeof t?(r=t,new n.Root):t||new n.Root).load(e,r)},n.loadSync=function(e,t){return(t=t||new n.Root).loadSync(e)},n.encoder=e(13),n.decoder=e(12),n.verifier=e(36),n.converter=e(11),n.ReflectionObject=e(22),n.Namespace=e(21),n.Root=e(26),n.Enum=e(14),n.Type=e(31),n.Field=e(15),n.OneOf=e(23),n.MapField=e(18),n.Service=e(30),n.Method=e(20),n.Message=e(19),n.wrappers=e(37),n.types=e(32),n.util=e(33),n.ReflectionObject.r(n.Root),n.Namespace.r(n.Type,n.Service,n.Enum),n.Root.r(n.Type),n.Field.r(n.Type)},{11:11,12:12,13:13,14:14,15:15,17:17,18:18,19:19,20:20,21:21,22:22,23:23,26:26,30:30,31:31,32:32,33:33,36:36,37:37}],17:[function(e,t,r){var n=r;function i(){n.util.r(),n.Writer.r(n.BufferWriter),n.Reader.r(n.BufferReader)}n.build="minimal",n.Writer=e(38),n.BufferWriter=e(39),n.Reader=e(24),n.BufferReader=e(25),n.util=e(35),n.rpc=e(28),n.roots=e(27),n.configure=i,i()},{24:24,25:25,27:27,28:28,35:35,38:38,39:39}],18:[function(e,t,r){t.exports=a;var n=e(15),i=(((a.prototype=Object.create(n.prototype)).constructor=a).className="MapField",e(32)),o=e(33);function a(e,t,r,i,a,s){if(n.call(this,e,t,i,g,g,a,s),!o.isString(r))throw TypeError("keyType must be a string");this.keyType=r,this.resolvedKeyType=null,this.map=!0}a.fromJSON=function(e,t){return new a(e,t.id,t.keyType,t.type,t.options,t.comment)},a.prototype.toJSON=function(e){return e=!!e&&!!e.keepComments,o.toObject(["keyType",this.keyType,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",e?this.comment:g])},a.prototype.resolve=function(){if(this.resolved)return this;if(i.mapKey[this.keyType]===g)throw Error("invalid key type: "+this.keyType);return n.prototype.resolve.call(this)},a.d=function(e,t,r){return"function"==typeof r?r=o.decorateType(r).name:r&&"object"==typeof r&&(r=o.decorateEnum(r).name),function(n,i){o.decorateType(n.constructor).add(new a(i,e,t,r))}}},{15:15,32:32,33:33}],19:[function(e,t,r){t.exports=i;var n=e(35);function i(e){if(e)for(var t=Object.keys(e),r=0;r<t.length;++r)this[t[r]]=e[t[r]]}i.create=function(e){return this.$type.create(e)},i.encode=function(e,t){return this.$type.encode(e,t)},i.encodeDelimited=function(e,t){return this.$type.encodeDelimited(e,t)},i.decode=function(e){return this.$type.decode(e)},i.decodeDelimited=function(e){return this.$type.decodeDelimited(e)},i.verify=function(e){return this.$type.verify(e)},i.fromObject=function(e){return this.$type.fromObject(e)},i.toObject=function(e,t){return this.$type.toObject(e,t)},i.prototype.toJSON=function(){return this.$type.toObject(this,n.toJSONOptions)}},{35:35}],20:[function(e,t,r){t.exports=o;var n=e(22),i=(((o.prototype=Object.create(n.prototype)).constructor=o).className="Method",e(33));function o(e,t,r,o,a,s,c,u,l){if(i.isObject(a)?(c=a,a=s=g):i.isObject(s)&&(c=s,s=g),t!==g&&!i.isString(t))throw TypeError("type must be a string");if(!i.isString(r))throw TypeError("requestType must be a string");if(!i.isString(o))throw TypeError("responseType must be a string");n.call(this,e,c),this.type=t||"rpc",this.requestType=r,this.requestStream=!!a||g,this.responseType=o,this.responseStream=!!s||g,this.resolvedRequestType=null,this.resolvedResponseType=null,this.comment=u,this.parsedOptions=l}o.fromJSON=function(e,t){return new o(e,t.type,t.requestType,t.responseType,t.requestStream,t.responseStream,t.options,t.comment,t.parsedOptions)},o.prototype.toJSON=function(e){return e=!!e&&!!e.keepComments,i.toObject(["type","rpc"!==this.type&&this.type||g,"requestType",this.requestType,"requestStream",this.requestStream,"responseType",this.responseType,"responseStream",this.responseStream,"options",this.options,"comment",e?this.comment:g,"parsedOptions",this.parsedOptions])},o.prototype.resolve=function(){return this.resolved?this:(this.resolvedRequestType=this.parent.lookupType(this.requestType),this.resolvedResponseType=this.parent.lookupType(this.responseType),n.prototype.resolve.call(this))}},{22:22,33:33}],21:[function(e,t,r){t.exports=d;var n,i,o,a=e(22),s=(((d.prototype=Object.create(a.prototype)).constructor=d).className="Namespace",e(15)),c=e(33),u=e(23);function l(e,t){if(!e||!e.length)return g;for(var r={},n=0;n<e.length;++n)r[e[n].name]=e[n].toJSON(t);return r}function d(e,t){a.call(this,e,t),this.nested=g,this.e=null}function p(e){return e.e=null,e}d.fromJSON=function(e,t){return new d(e,t.options).addJSON(t.nested)},d.arrayToJSON=l,d.isReservedId=function(e,t){if(e)for(var r=0;r<e.length;++r)if("string"!=typeof e[r]&&e[r][0]<=t&&e[r][1]>t)return!0;return!1},d.isReservedName=function(e,t){if(e)for(var r=0;r<e.length;++r)if(e[r]===t)return!0;return!1},Object.defineProperty(d.prototype,"nestedArray",{get:function(){return this.e||(this.e=c.toArray(this.nested))}}),d.prototype.toJSON=function(e){return c.toObject(["options",this.options,"nested",l(this.nestedArray,e)])},d.prototype.addJSON=function(e){if(e)for(var t,r=Object.keys(e),a=0;a<r.length;++a)t=e[r[a]],this.add((t.fields!==g?n:t.values!==g?o:t.methods!==g?i:t.id!==g?s:d).fromJSON(r[a],t));return this},d.prototype.get=function(e){return this.nested&&this.nested[e]||null},d.prototype.getEnum=function(e){if(this.nested&&this.nested[e]instanceof o)return this.nested[e].values;throw Error("no such enum: "+e)},d.prototype.add=function(e){if(!(e instanceof s&&e.extend!==g||e instanceof n||e instanceof u||e instanceof o||e instanceof i||e instanceof d))throw TypeError("object must be a valid nested object");if(this.nested){var t=this.get(e.name);if(t){if(!(t instanceof d&&e instanceof d)||t instanceof n||t instanceof i)throw Error("duplicate name '"+e.name+"' in "+this);for(var r=t.nestedArray,a=0;a<r.length;++a)e.add(r[a]);this.remove(t),this.nested||(this.nested={}),e.setOptions(t.options,!0)}}else this.nested={};return(this.nested[e.name]=e).onAdd(this),p(this)},d.prototype.remove=function(e){if(!(e instanceof a))throw TypeError("object must be a ReflectionObject");if(e.parent!==this)throw Error(e+" is not a member of "+this);return delete this.nested[e.name],Object.keys(this.nested).length||(this.nested=g),e.onRemove(this),p(this)},d.prototype.define=function(e,t){if(c.isString(e))e=e.split(".");else if(!Array.isArray(e))throw TypeError("illegal path");if(e&&e.length&&""===e[0])throw Error("path must be relative");for(var r=this;0<e.length;){var n=e.shift();if(r.nested&&r.nested[n]){if(!((r=r.nested[n])instanceof d))throw Error("path conflicts with non-namespace objects")}else r.add(r=new d(n))}return t&&r.addJSON(t),r},d.prototype.resolveAll=function(){for(var e=this.nestedArray,t=0;t<e.length;)e[t]instanceof d?e[t++].resolveAll():e[t++].resolve();return this.resolve()},d.prototype.lookup=function(e,t,r){if("boolean"==typeof t?(r=t,t=g):t&&!Array.isArray(t)&&(t=[t]),c.isString(e)&&e.length){if("."===e)return this.root;e=e.split(".")}else if(!e.length)return this;if(""===e[0])return this.root.lookup(e.slice(1),t);var n=this.get(e[0]);if(n){if(1===e.length){if(!t||~t.indexOf(n.constructor))return n}else if(n instanceof d&&(n=n.lookup(e.slice(1),t,!0)))return n}else for(var i=0;i<this.nestedArray.length;++i)if(this.e[i]instanceof d&&(n=this.e[i].lookup(e,t,!0)))return n;return null===this.parent||r?null:this.parent.lookup(e,t)},d.prototype.lookupType=function(e){var t=this.lookup(e,[n]);if(t)return t;throw Error("no such type: "+e)},d.prototype.lookupEnum=function(e){var t=this.lookup(e,[o]);if(t)return t;throw Error("no such Enum '"+e+"' in "+this)},d.prototype.lookupTypeOrEnum=function(e){var t=this.lookup(e,[n,o]);if(t)return t;throw Error("no such Type or Enum '"+e+"' in "+this)},d.prototype.lookupService=function(e){var t=this.lookup(e,[i]);if(t)return t;throw Error("no such Service '"+e+"' in "+this)},d.r=function(e,t,r){n=e,i=t,o=r}},{15:15,22:22,23:23,33:33}],22:[function(e,t,r){(t.exports=o).className="ReflectionObject";var n,i=e(33);function o(e,t){if(!i.isString(e))throw TypeError("name must be a string");if(t&&!i.isObject(t))throw TypeError("options must be an object");this.options=t,this.parsedOptions=null,this.name=e,this.parent=null,this.resolved=!1,this.comment=null,this.filename=null}Object.defineProperties(o.prototype,{root:{get:function(){for(var e=this;null!==e.parent;)e=e.parent;return e}},fullName:{get:function(){for(var e=[this.name],t=this.parent;t;)e.unshift(t.name),t=t.parent;return e.join(".")}}}),o.prototype.toJSON=function(){throw Error()},o.prototype.onAdd=function(e){this.parent&&this.parent!==e&&this.parent.remove(this),this.parent=e,this.resolved=!1,(e=e.root)instanceof n&&e.u(this)},o.prototype.onRemove=function(e){(e=e.root)instanceof n&&e.o(this),this.parent=null,this.resolved=!1},o.prototype.resolve=function(){return this.resolved||this.root instanceof n&&(this.resolved=!0),this},o.prototype.getOption=function(e){return this.options?this.options[e]:g},o.prototype.setOption=function(e,t,r){return r&&this.options&&this.options[e]!==g||((this.options||(this.options={}))[e]=t),this},o.prototype.setParsedOption=function(e,t,r){this.parsedOptions||(this.parsedOptions=[]);var n,o,a=this.parsedOptions;return r?(n=a.find(function(t){return Object.prototype.hasOwnProperty.call(t,e)}))?(o=n[e],i.setProperty(o,r,t)):((n={})[e]=i.setProperty({},r,t),a.push(n)):((o={})[e]=t,a.push(o)),this},o.prototype.setOptions=function(e,t){if(e)for(var r=Object.keys(e),n=0;n<r.length;++n)this.setOption(r[n],e[r[n]],t);return this},o.prototype.toString=function(){var e=this.constructor.className,t=this.fullName;return t.length?e+" "+t:e},o.r=function(e){n=e}},{33:33}],23:[function(e,t,r){t.exports=a;var n=e(22),i=(((a.prototype=Object.create(n.prototype)).constructor=a).className="OneOf",e(15)),o=e(33);function a(e,t,r,i){if(Array.isArray(t)||(r=t,t=g),n.call(this,e,r),t!==g&&!Array.isArray(t))throw TypeError("fieldNames must be an Array");this.oneof=t||[],this.fieldsArray=[],this.comment=i}function s(e){if(e.parent)for(var t=0;t<e.fieldsArray.length;++t)e.fieldsArray[t].parent||e.parent.add(e.fieldsArray[t])}a.fromJSON=function(e,t){return new a(e,t.oneof,t.options,t.comment)},a.prototype.toJSON=function(e){return e=!!e&&!!e.keepComments,o.toObject(["options",this.options,"oneof",this.oneof,"comment",e?this.comment:g])},a.prototype.add=function(e){if(e instanceof i)return e.parent&&e.parent!==this.parent&&e.parent.remove(e),this.oneof.push(e.name),this.fieldsArray.push(e),s(e.partOf=this),this;throw TypeError("field must be a Field")},a.prototype.remove=function(e){if(!(e instanceof i))throw TypeError("field must be a Field");var t=this.fieldsArray.indexOf(e);if(t<0)throw Error(e+" is not a member of "+this);return this.fieldsArray.splice(t,1),-1<(t=this.oneof.indexOf(e.name))&&this.oneof.splice(t,1),e.partOf=null,this},a.prototype.onAdd=function(e){n.prototype.onAdd.call(this,e);for(var t=0;t<this.oneof.length;++t){var r=e.get(this.oneof[t]);r&&!r.partOf&&(r.partOf=this).fieldsArray.push(r)}s(this)},a.prototype.onRemove=function(e){for(var t,r=0;r<this.fieldsArray.length;++r)(t=this.fieldsArray[r]).parent&&t.parent.remove(t);n.prototype.onRemove.call(this,e)},a.d=function(){for(var e=Array(arguments.length),t=0;t<arguments.length;)e[t]=arguments[t++];return function(t,r){o.decorateType(t.constructor).add(new a(r,e)),Object.defineProperty(t,r,{get:o.oneOfGetter(e),set:o.oneOfSetter(e)})}}},{15:15,22:22,33:33}],24:[function(e,t,r){t.exports=c;var n,i=e(35),o=i.LongBits,a=i.utf8;function s(e,t){return RangeError("index out of range: "+e.pos+" + "+(t||1)+" > "+e.len)}function c(e){this.buf=e,this.pos=0,this.len=e.length}function u(){return i.Buffer?function(e){return(c.create=function(e){return i.Buffer.isBuffer(e)?new n(e):d(e)})(e)}:d}var l,d="undefined"!=typeof Uint8Array?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new c(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new c(e);throw Error("illegal buffer")};function p(){var e=new o(0,0),t=0;if(!(4<this.len-this.pos)){for(;t<3;++t){if(this.pos>=this.len)throw s(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,4<this.len-this.pos){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw s(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}function f(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}function h(){if(this.pos+8>this.len)throw s(this,8);return new o(f(this.buf,this.pos+=4),f(this.buf,this.pos+=4))}c.create=u(),c.prototype.h=i.Array.prototype.subarray||i.Array.prototype.slice,c.prototype.uint32=(l=4294967295,function(){if(l=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128||(l=(l|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128||(l=(l|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128||(l=(l|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128||(l=(l|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128||!((this.pos+=5)>this.len))))))return l;throw this.pos=this.len,s(this,10)}),c.prototype.int32=function(){return 0|this.uint32()},c.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(1&e)},c.prototype.bool=function(){return 0!==this.uint32()},c.prototype.fixed32=function(){if(this.pos+4>this.len)throw s(this,4);return f(this.buf,this.pos+=4)},c.prototype.sfixed32=function(){if(this.pos+4>this.len)throw s(this,4);return 0|f(this.buf,this.pos+=4)},c.prototype.float=function(){if(this.pos+4>this.len)throw s(this,4);var e=i.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e},c.prototype.double=function(){if(this.pos+8>this.len)throw s(this,4);var e=i.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e},c.prototype.bytes=function(){var e=this.uint32(),t=this.pos,r=this.pos+e;if(r>this.len)throw s(this,e);return this.pos+=e,Array.isArray(this.buf)?this.buf.slice(t,r):t===r?(e=i.Buffer)?e.alloc(0):new this.buf.constructor(0):this.h.call(this.buf,t,r)},c.prototype.string=function(){var e=this.bytes();return a.read(e,0,e.length)},c.prototype.skip=function(e){if("number"==typeof e){if(this.pos+e>this.len)throw s(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw s(this)}while(128&this.buf[this.pos++]);return this},c.prototype.skipType=function(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+e+" at offset "+this.pos)}return this},c.r=function(e){n=e,c.create=u(),n.r();var t=i.Long?"toLong":"toNumber";i.merge(c.prototype,{int64:function(){return p.call(this)[t](!1)},uint64:function(){return p.call(this)[t](!0)},sint64:function(){return p.call(this).zzDecode()[t](!1)},fixed64:function(){return h.call(this)[t](!0)},sfixed64:function(){return h.call(this)[t](!1)}})}},{35:35}],25:[function(e,t,r){t.exports=o;var n=e(24),i=((o.prototype=Object.create(n.prototype)).constructor=o,e(35));function o(e){n.call(this,e)}o.r=function(){i.Buffer&&(o.prototype.h=i.Buffer.prototype.slice)},o.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))},o.r()},{24:24,35:35}],26:[function(e,t,r){t.exports=d;var n,i,o,a=e(21),s=(((d.prototype=Object.create(a.prototype)).constructor=d).className="Root",e(15)),c=e(14),u=e(23),l=e(33);function d(e){a.call(this,"",e),this.deferred=[],this.files=[]}function p(){}d.fromJSON=function(e,t){return t=t||new d,e.options&&t.setOptions(e.options),t.addJSON(e.nested)},d.prototype.resolvePath=l.path.resolve,d.prototype.fetch=l.fetch,d.prototype.load=function e(t,r,n){"function"==typeof r&&(n=r,r=g);var a=this;if(!n)return l.asPromise(e,a,t,r);var s=n===p;function c(e,t){if(n){if(s)throw e;var r=n;n=null,r(e,t)}}function u(e){var t=e.lastIndexOf("google/protobuf/");return-1<t&&(e=e.substring(t))in o?e:null}function d(e,t){try{if(l.isString(t)&&"{"==(t[0]||"")&&(t=JSON.parse(t)),l.isString(t)){i.filename=e;var n,o=i(t,a,r),d=0;if(o.imports)for(;d<o.imports.length;++d)(n=u(o.imports[d])||a.resolvePath(e,o.imports[d]))&&f(n);if(o.weakImports)for(d=0;d<o.weakImports.length;++d)(n=u(o.weakImports[d])||a.resolvePath(e,o.weakImports[d]))&&f(n,!0)}else a.setOptions(t.options).addJSON(t.nested)}catch(e){c(e)}s||h||c(null,a)}function f(e,t){if(e=u(e)||e,!~a.files.indexOf(e))if(a.files.push(e),e in o)s?d(e,o[e]):(++h,setTimeout(function(){--h,d(e,o[e])}));else if(s){var r;try{r=l.fs.readFileSync(e).toString("utf8")}catch(r){return void(t||c(r))}d(e,r)}else++h,a.fetch(e,function(r,i){--h,n&&(r?t?h||c(null,a):c(r):d(e,i))})}var h=0;l.isString(t)&&(t=[t]);for(var m,v=0;v<t.length;++v)(m=a.resolvePath("",t[v]))&&f(m);return s?a:(h||c(null,a),g)},d.prototype.loadSync=function(e,t){if(l.isNode)return this.load(e,t,p);throw Error("not supported")},d.prototype.resolveAll=function(){if(this.deferred.length)throw Error("unresolvable extensions: "+this.deferred.map(function(e){return"'extend "+e.extend+"' in "+e.parent.fullName}).join(", "));return a.prototype.resolveAll.call(this)};var f=/^[A-Z]/;function h(e,t){var r,n=t.parent.lookup(t.extend);if(n)return r=new s(t.fullName,t.id,t.type,t.rule,g,t.options),n.get(r.name)||((r.declaringField=t).extensionField=r,n.add(r)),1}d.prototype.u=function(e){if(e instanceof s)e.extend===g||e.extensionField||h(0,e)||this.deferred.push(e);else if(e instanceof c)f.test(e.name)&&(e.parent[e.name]=e.values);else if(!(e instanceof u)){if(e instanceof n)for(var t=0;t<this.deferred.length;)h(0,this.deferred[t])?this.deferred.splice(t,1):++t;for(var r=0;r<e.nestedArray.length;++r)this.u(e.e[r]);f.test(e.name)&&(e.parent[e.name]=e)}},d.prototype.o=function(e){var t;if(e instanceof s)e.extend!==g&&(e.extensionField?(e.extensionField.parent.remove(e.extensionField),e.extensionField=null):-1<(t=this.deferred.indexOf(e))&&this.deferred.splice(t,1));else if(e instanceof c)f.test(e.name)&&delete e.parent[e.name];else if(e instanceof a){for(var r=0;r<e.nestedArray.length;++r)this.o(e.e[r]);f.test(e.name)&&delete e.parent[e.name]}},d.r=function(e,t,r){n=e,i=t,o=r}},{14:14,15:15,21:21,23:23,33:33}],27:[function(e,t,r){t.exports={}},{}],28:[function(e,t,r){r.Service=e(29)},{29:29}],29:[function(e,t,r){t.exports=i;var n=e(35);function i(e,t,r){if("function"!=typeof e)throw TypeError("rpcImpl must be a function");n.EventEmitter.call(this),this.rpcImpl=e,this.requestDelimited=!!t,this.responseDelimited=!!r}((i.prototype=Object.create(n.EventEmitter.prototype)).constructor=i).prototype.rpcCall=function e(t,r,i,o,a){if(!o)throw TypeError("request must be specified");var s=this;if(!a)return n.asPromise(e,s,t,r,i,o);if(!s.rpcImpl)return setTimeout(function(){a(Error("already ended"))},0),g;try{return s.rpcImpl(t,r[s.requestDelimited?"encodeDelimited":"encode"](o).finish(),function(e,r){if(e)return s.emit("error",e,t),a(e);if(null===r)return s.end(!0),g;if(!(r instanceof i))try{r=i[s.responseDelimited?"decodeDelimited":"decode"](r)}catch(e){return s.emit("error",e,t),a(e)}return s.emit("data",r,t),a(null,r)})}catch(e){return s.emit("error",e,t),setTimeout(function(){a(e)},0),g}},i.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}},{35:35}],30:[function(e,t,r){t.exports=s;var n=e(21),i=(((s.prototype=Object.create(n.prototype)).constructor=s).className="Service",e(20)),o=e(33),a=e(28);function s(e,t){n.call(this,e,t),this.methods={},this.f=null}function c(e){return e.f=null,e}s.fromJSON=function(e,t){var r=new s(e,t.options);if(t.methods)for(var n=Object.keys(t.methods),o=0;o<n.length;++o)r.add(i.fromJSON(n[o],t.methods[n[o]]));return t.nested&&r.addJSON(t.nested),r.comment=t.comment,r},s.prototype.toJSON=function(e){var t=n.prototype.toJSON.call(this,e),r=!!e&&!!e.keepComments;return o.toObject(["options",t&&t.options||g,"methods",n.arrayToJSON(this.methodsArray,e)||{},"nested",t&&t.nested||g,"comment",r?this.comment:g])},Object.defineProperty(s.prototype,"methodsArray",{get:function(){return this.f||(this.f=o.toArray(this.methods))}}),s.prototype.get=function(e){return this.methods[e]||n.prototype.get.call(this,e)},s.prototype.resolveAll=function(){for(var e=this.methodsArray,t=0;t<e.length;++t)e[t].resolve();return n.prototype.resolve.call(this)},s.prototype.add=function(e){if(this.get(e.name))throw Error("duplicate name '"+e.name+"' in "+this);return e instanceof i?c((this.methods[e.name]=e).parent=this):n.prototype.add.call(this,e)},s.prototype.remove=function(e){if(e instanceof i){if(this.methods[e.name]!==e)throw Error(e+" is not a member of "+this);return delete this.methods[e.name],e.parent=null,c(this)}return n.prototype.remove.call(this,e)},s.prototype.create=function(e,t,r){for(var n,i=new a.Service(e,t,r),s=0;s<this.methodsArray.length;++s){var c=o.lcFirst((n=this.f[s]).resolve().name).replace(/[^$\w_]/g,"");i[c]=o.codegen(["r","c"],o.isReserved(c)?c+"_":c)("return this.rpcCall(m,q,s,r,c)")({m:n,q:n.resolvedRequestType.ctor,s:n.resolvedResponseType.ctor})}return i}},{20:20,21:21,28:28,33:33}],31:[function(e,t,r){t.exports=b;var n=e(21),i=(((b.prototype=Object.create(n.prototype)).constructor=b).className="Type",e(14)),o=e(23),a=e(15),s=e(18),c=e(30),u=e(19),l=e(24),d=e(38),p=e(33),f=e(13),h=e(12),m=e(36),v=e(11),y=e(37);function b(e,t){n.call(this,e,t),this.fields={},this.oneofs=g,this.extensions=g,this.reserved=g,this.group=g,this.c=null,this.i=null,this.a=null,this.l=null}function S(e){return e.c=e.i=e.a=null,delete e.encode,delete e.decode,delete e.verify,e}Object.defineProperties(b.prototype,{fieldsById:{get:function(){if(!this.c){this.c={};for(var e=Object.keys(this.fields),t=0;t<e.length;++t){var r=this.fields[e[t]],n=r.id;if(this.c[n])throw Error("duplicate id "+n+" in "+this);this.c[n]=r}}return this.c}},fieldsArray:{get:function(){return this.i||(this.i=p.toArray(this.fields))}},oneofsArray:{get:function(){return this.a||(this.a=p.toArray(this.oneofs))}},ctor:{get:function(){return this.l||(this.ctor=b.generateConstructor(this)())},set:function(e){for(var t=e.prototype,r=(t instanceof u||((e.prototype=new u).constructor=e,p.merge(e.prototype,t)),e.$type=e.prototype.$type=this,p.merge(e,u,!0),this.l=e,0);r<this.fieldsArray.length;++r)this.i[r].resolve();var n={};for(r=0;r<this.oneofsArray.length;++r)n[this.a[r].resolve().name]={get:p.oneOfGetter(this.a[r].oneof),set:p.oneOfSetter(this.a[r].oneof)};r&&Object.defineProperties(e.prototype,n)}}}),b.generateConstructor=function(e){for(var t,r=p.codegen(["p"],e.name),n=0;n<e.fieldsArray.length;++n)(t=e.i[n]).map?r("this%s={}",p.safeProp(t.name)):t.repeated&&r("this%s=[]",p.safeProp(t.name));return r("if(p)for(var ks=Object.keys(p),i=0;i<ks.length;++i)if(p[ks[i]]!=null)")("this[ks[i]]=p[ks[i]]")},b.fromJSON=function(e,t){for(var r=new b(e,t.options),u=(r.extensions=t.extensions,r.reserved=t.reserved,Object.keys(t.fields)),l=0;l<u.length;++l)r.add((void 0!==t.fields[u[l]].keyType?s:a).fromJSON(u[l],t.fields[u[l]]));if(t.oneofs)for(u=Object.keys(t.oneofs),l=0;l<u.length;++l)r.add(o.fromJSON(u[l],t.oneofs[u[l]]));if(t.nested)for(u=Object.keys(t.nested),l=0;l<u.length;++l){var d=t.nested[u[l]];r.add((d.id!==g?a:d.fields!==g?b:d.values!==g?i:d.methods!==g?c:n).fromJSON(u[l],d))}return t.extensions&&t.extensions.length&&(r.extensions=t.extensions),t.reserved&&t.reserved.length&&(r.reserved=t.reserved),t.group&&(r.group=!0),t.comment&&(r.comment=t.comment),r},b.prototype.toJSON=function(e){var t=n.prototype.toJSON.call(this,e),r=!!e&&!!e.keepComments;return p.toObject(["options",t&&t.options||g,"oneofs",n.arrayToJSON(this.oneofsArray,e),"fields",n.arrayToJSON(this.fieldsArray.filter(function(e){return!e.declaringField}),e)||{},"extensions",this.extensions&&this.extensions.length?this.extensions:g,"reserved",this.reserved&&this.reserved.length?this.reserved:g,"group",this.group||g,"nested",t&&t.nested||g,"comment",r?this.comment:g])},b.prototype.resolveAll=function(){for(var e=this.fieldsArray,t=0;t<e.length;)e[t++].resolve();var r=this.oneofsArray;for(t=0;t<r.length;)r[t++].resolve();return n.prototype.resolveAll.call(this)},b.prototype.get=function(e){return this.fields[e]||this.oneofs&&this.oneofs[e]||this.nested&&this.nested[e]||null},b.prototype.add=function(e){if(this.get(e.name))throw Error("duplicate name '"+e.name+"' in "+this);if(e instanceof a&&e.extend===g){if((this.c||this.fieldsById)[e.id])throw Error("duplicate id "+e.id+" in "+this);if(this.isReservedId(e.id))throw Error("id "+e.id+" is reserved in "+this);if(this.isReservedName(e.name))throw Error("name '"+e.name+"' is reserved in "+this);return e.parent&&e.parent.remove(e),(this.fields[e.name]=e).message=this,e.onAdd(this),S(this)}return e instanceof o?(this.oneofs||(this.oneofs={}),(this.oneofs[e.name]=e).onAdd(this),S(this)):n.prototype.add.call(this,e)},b.prototype.remove=function(e){if(e instanceof a&&e.extend===g){if(this.fields&&this.fields[e.name]===e)return delete this.fields[e.name],e.parent=null,e.onRemove(this),S(this);throw Error(e+" is not a member of "+this)}if(e instanceof o){if(this.oneofs&&this.oneofs[e.name]===e)return delete this.oneofs[e.name],e.parent=null,e.onRemove(this),S(this);throw Error(e+" is not a member of "+this)}return n.prototype.remove.call(this,e)},b.prototype.isReservedId=function(e){return n.isReservedId(this.reserved,e)},b.prototype.isReservedName=function(e){return n.isReservedName(this.reserved,e)},b.prototype.create=function(e){return new this.ctor(e)},b.prototype.setup=function(){for(var e=this.fullName,t=[],r=0;r<this.fieldsArray.length;++r)t.push(this.i[r].resolve().resolvedType);var n;return this.encode=f(this)({Writer:d,types:t,util:p}),this.decode=h(this)({Reader:l,types:t,util:p}),this.verify=m(this)({types:t,util:p}),this.fromObject=v.fromObject(this)({types:t,util:p}),this.toObject=v.toObject(this)({types:t,util:p}),(e=y[e])&&((n=Object.create(this)).fromObject=this.fromObject,this.fromObject=e.fromObject.bind(n),n.toObject=this.toObject,this.toObject=e.toObject.bind(n)),this},b.prototype.encode=function(e,t){return this.setup().encode(e,t)},b.prototype.encodeDelimited=function(e,t){return this.encode(e,t&&t.len?t.fork():t).ldelim()},b.prototype.decode=function(e,t){return this.setup().decode(e,t)},b.prototype.decodeDelimited=function(e){return e instanceof l||(e=l.create(e)),this.decode(e,e.uint32())},b.prototype.verify=function(e){return this.setup().verify(e)},b.prototype.fromObject=function(e){return this.setup().fromObject(e)},b.prototype.toObject=function(e,t){return this.setup().toObject(e,t)},b.d=function(e){return function(t){p.decorateType(t,e)}}},{11:11,12:12,13:13,14:14,15:15,18:18,19:19,21:21,23:23,24:24,30:30,33:33,36:36,37:37,38:38}],32:[function(e,t,r){e=e(33);var n=["double","float","int32","uint32","sint32","fixed32","sfixed32","int64","uint64","sint64","fixed64","sfixed64","bool","string","bytes"];function i(e,t){var r=0,i={};for(t|=0;r<e.length;)i[n[r+t]]=e[r++];return i}r.basic=i([1,5,0,0,0,5,5,0,0,0,1,1,0,2,2]),r.defaults=i([0,0,0,0,0,0,0,0,0,0,0,0,!1,"",e.emptyArray,null]),r.long=i([0,0,0,1,1],7),r.mapKey=i([0,0,0,5,5,0,0,0,1,1,0,2],2),r.packed=i([1,5,0,0,0,5,5,0,0,0,1,1,0])},{33:33}],33:[function(e,t,r){var n,i,o=t.exports=e(35),a=e(27),s=(o.codegen=e(3),o.fetch=e(5),o.path=e(8),o.fs=o.inquire("fs"),o.toArray=function(e){if(e){for(var t=Object.keys(e),r=Array(t.length),n=0;n<t.length;)r[n]=e[t[n++]];return r}return[]},o.toObject=function(e){for(var t={},r=0;r<e.length;){var n=e[r++],i=e[r++];i!==g&&(t[n]=i)}return t},/\\/g),c=/"/g,u=(o.isReserved=function(e){return/^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(e)},o.safeProp=function(e){return!/^[$\w_]+$/.test(e)||o.isReserved(e)?'["'+e.replace(s,"\\\\").replace(c,'\\"')+'"]':"."+e},o.ucFirst=function(e){return(e[0]||"").toUpperCase()+e.substring(1)},/_([a-z])/g),l=(o.camelCase=function(e){return e.substring(0,1)+e.substring(1).replace(u,function(e,t){return t.toUpperCase()})},o.compareFieldsById=function(e,t){return e.id-t.id},o.decorateType=function(t,r){return t.$type?(r&&t.$type.name!==r&&(o.decorateRoot.remove(t.$type),t.$type.name=r,o.decorateRoot.add(t.$type)),t.$type):(r=new(n=n||e(31))(r||t.name),o.decorateRoot.add(r),r.ctor=t,Object.defineProperty(t,"$type",{value:r,enumerable:!1}),Object.defineProperty(t.prototype,"$type",{value:r,enumerable:!1}),r)},0);o.decorateEnum=function(t){var r;return t.$type||(r=new(i=i||e(14))("Enum"+l++,t),o.decorateRoot.add(r),Object.defineProperty(t,"$type",{value:r,enumerable:!1}),r)},o.setProperty=function(e,t,r){if("object"!=typeof e)throw TypeError("dst must be an object");if(t)return function e(t,r,n){var i=r.shift();return"__proto__"!==i&&"prototype"!==i&&(0<r.length?t[i]=e(t[i]||{},r,n):((r=t[i])&&(n=[].concat(r).concat(n)),t[i]=n)),t}(e,t=t.split("."),r);throw TypeError("path must be specified")},Object.defineProperty(o,"decorateRoot",{get:function(){return a.decorated||(a.decorated=new(e(26)))}})},{14:14,26:26,27:27,3:3,31:31,35:35,5:5,8:8}],34:[function(e,t,r){t.exports=i;var n=e(35);function i(e,t){this.lo=e>>>0,this.hi=t>>>0}var o=i.zero=new i(0,0),a=(o.toNumber=function(){return 0},o.zzEncode=o.zzDecode=function(){return this},o.length=function(){return 1},i.zeroHash="\0\0\0\0\0\0\0\0",i.fromNumber=function(e){var t,r;return 0===e?o:(r=(e=(t=e<0)?-e:e)>>>0,e=(e-r)/4294967296>>>0,t&&(e=~e>>>0,r=~r>>>0,4294967295<++r&&(r=0,4294967295<++e&&(e=0))),new i(r,e))},i.from=function(e){if("number"==typeof e)return i.fromNumber(e);if(n.isString(e)){if(!n.Long)return i.fromNumber(parseInt(e,10));e=n.Long.fromString(e)}return e.low||e.high?new i(e.low>>>0,e.high>>>0):o},i.prototype.toNumber=function(e){var t;return!e&&this.hi>>>31?(e=1+~this.lo>>>0,t=~this.hi>>>0,-(e+4294967296*(t=e?t:t+1>>>0))):this.lo+4294967296*this.hi},i.prototype.toLong=function(e){return n.Long?new n.Long(0|this.lo,0|this.hi,!!e):{low:0|this.lo,high:0|this.hi,unsigned:!!e}},String.prototype.charCodeAt);i.fromHash=function(e){return"\0\0\0\0\0\0\0\0"===e?o:new i((a.call(e,0)|a.call(e,1)<<8|a.call(e,2)<<16|a.call(e,3)<<24)>>>0,(a.call(e,4)|a.call(e,5)<<8|a.call(e,6)<<16|a.call(e,7)<<24)>>>0)},i.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},i.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this},i.prototype.zzDecode=function(){var e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this},i.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return 0==r?0==t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:r<128?9:10}},{35:35}],35:[function(e,t,r){var n=r;function i(e,t,r){for(var n=Object.keys(t),i=0;i<n.length;++i)e[n[i]]!==g&&r||(e[n[i]]=t[n[i]]);return e}function o(e){function t(e,r){if(!(this instanceof t))return new t(e,r);Object.defineProperty(this,"message",{get:function(){return e}}),Error.captureStackTrace?Error.captureStackTrace(this,t):Object.defineProperty(this,"stack",{value:Error().stack||""}),r&&i(this,r)}return t.prototype=Object.create(Error.prototype,{constructor:{value:t,writable:!0,enumerable:!1,configurable:!0},name:{get:function(){return e},set:g,enumerable:!1,configurable:!0},toString:{value:function(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),t}n.asPromise=e(1),n.base64=e(2),n.EventEmitter=e(4),n.float=e(6),n.inquire=e(7),n.utf8=e(10),n.pool=e(9),n.LongBits=e(34),n.isNode=!!(void 0!==commonjsGlobal&&commonjsGlobal&&commonjsGlobal.process&&commonjsGlobal.process.versions&&commonjsGlobal.process.versions.node),n.global=n.isNode&&commonjsGlobal||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||this,n.emptyArray=Object.freeze?Object.freeze([]):[],n.emptyObject=Object.freeze?Object.freeze({}):{},n.isInteger=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e},n.isString=function(e){return"string"==typeof e||e instanceof String},n.isObject=function(e){return e&&"object"==typeof e},n.isset=n.isSet=function(e,t){var r=e[t];return null!=r&&e.hasOwnProperty(t)&&("object"!=typeof r||0<(Array.isArray(r)?r:Object.keys(r)).length)},n.Buffer=function(){try{var e=n.inquire("buffer").Buffer;return e.prototype.utf8Write?e:null}catch(e){return null}}(),n.v=null,n.b=null,n.newBuffer=function(e){return"number"==typeof e?n.Buffer?n.b(e):new n.Array(e):n.Buffer?n.v(e):"undefined"==typeof Uint8Array?e:new Uint8Array(e)},n.Array="undefined"!=typeof Uint8Array?Uint8Array:Array,n.Long=n.global.dcodeIO&&n.global.dcodeIO.Long||n.global.Long||n.inquire("long"),n.key2Re=/^true|false|0|1$/,n.key32Re=/^-?(?:0|[1-9][0-9]*)$/,n.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,n.longToHash=function(e){return e?n.LongBits.from(e).toHash():n.LongBits.zeroHash},n.longFromHash=function(e,t){return e=n.LongBits.fromHash(e),n.Long?n.Long.fromBits(e.lo,e.hi,t):e.toNumber(!!t)},n.merge=i,n.lcFirst=function(e){return(e[0]||"").toLowerCase()+e.substring(1)},n.newError=o,n.ProtocolError=o("ProtocolError"),n.oneOfGetter=function(e){for(var t={},r=0;r<e.length;++r)t[e[r]]=1;return function(){for(var e=Object.keys(this),r=e.length-1;-1<r;--r)if(1===t[e[r]]&&this[e[r]]!==g&&null!==this[e[r]])return e[r]}},n.oneOfSetter=function(e){return function(t){for(var r=0;r<e.length;++r)e[r]!==t&&delete this[e[r]]}},n.toJSONOptions={longs:String,enums:String,bytes:String,json:!0},n.r=function(){var e=n.Buffer;e?(n.v=e.from!==Uint8Array.from&&e.from||function(t,r){return new e(t,r)},n.b=e.allocUnsafe||function(t){return new e(t)}):n.v=n.b=null}},{1:1,10:10,2:2,34:34,4:4,6:6,7:7,9:9}],36:[function(e,t,r){t.exports=function(e){var t=i.codegen(["m"],e.name+"$verify")('if(typeof m!=="object"||m===null)')("return%j","object expected"),r={};e.oneofsArray.length&&t("var p={}");for(var n=0;n<e.fieldsArray.length;++n){var s,c=e.i[n].resolve(),u="m"+i.safeProp(c.name);c.optional&&t("if(%s!=null&&m.hasOwnProperty(%j)){",u,c.name),c.map?(t("if(!util.isObject(%s))",u)("return%j",o(c,"object"))("var k=Object.keys(%s)",u)("for(var i=0;i<k.length;++i){"),function(e,t,r){switch(t.keyType){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":e("if(!util.key32Re.test(%s))",r)("return%j",o(t,"integer key"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":e("if(!util.key64Re.test(%s))",r)("return%j",o(t,"integer|Long key"));break;case"bool":e("if(!util.key2Re.test(%s))",r)("return%j",o(t,"boolean key"))}}(t,c,"k[i]"),a(t,c,n,u+"[k[i]]")("}")):c.repeated?(t("if(!Array.isArray(%s))",u)("return%j",o(c,"array"))("for(var i=0;i<%s.length;++i){",u),a(t,c,n,u+"[i]")("}")):(c.partOf&&(s=i.safeProp(c.partOf.name),1===r[c.partOf.name]&&t("if(p%s===1)",s)("return%j",c.partOf.name+": multiple values"),r[c.partOf.name]=1,t("p%s=1",s)),a(t,c,n,u)),c.optional&&t("}")}return t("return null")};var n=e(14),i=e(33);function o(e,t){return e.name+": "+t+(e.repeated&&"array"!==t?"[]":e.map&&"object"!==t?"{k:"+e.keyType+"}":"")+" expected"}function a(e,t,r,i){if(t.resolvedType)if(t.resolvedType instanceof n){e("switch(%s){",i)("default:")("return%j",o(t,"enum value"));for(var a=Object.keys(t.resolvedType.values),s=0;s<a.length;++s)e("case %i:",t.resolvedType.values[a[s]]);e("break")("}")}else e("{")("var e=types[%i].verify(%s);",r,i)("if(e)")("return%j+e",t.name+".")("}");else switch(t.type){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":e("if(!util.isInteger(%s))",i)("return%j",o(t,"integer"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":e("if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))",i,i,i,i)("return%j",o(t,"integer|Long"));break;case"float":case"double":e('if(typeof %s!=="number")',i)("return%j",o(t,"number"));break;case"bool":e('if(typeof %s!=="boolean")',i)("return%j",o(t,"boolean"));break;case"string":e("if(!util.isString(%s))",i)("return%j",o(t,"string"));break;case"bytes":e('if(!(%s&&typeof %s.length==="number"||util.isString(%s)))',i,i,i)("return%j",o(t,"buffer"))}return e}},{14:14,33:33}],37:[function(e,t,r){var n=e(19);r[".google.protobuf.Any"]={fromObject:function(e){if(e&&e["@type"]){var t,r=e["@type"].substring(1+e["@type"].lastIndexOf("/"));if(r=this.lookup(r))return~(t="."==(e["@type"][0]||"")?e["@type"].slice(1):e["@type"]).indexOf("/")||(t="/"+t),this.create({type_url:t,value:r.encode(r.fromObject(e)).finish()})}return this.fromObject(e)},toObject:function(e,t){var r,i,o="",a="";return t&&t.json&&e.type_url&&e.value&&(a=e.type_url.substring(1+e.type_url.lastIndexOf("/")),o=e.type_url.substring(0,1+e.type_url.lastIndexOf("/")),(r=this.lookup(a))&&(e=r.decode(e.value))),!(e instanceof this.ctor)&&e instanceof n?(r=e.$type.toObject(e,t),i="."===e.$type.fullName[0]?e.$type.fullName.slice(1):e.$type.fullName,r["@type"]=a=(o=""===o?"type.googleapis.com/":o)+i,r):this.toObject(e,t)}}},{19:19}],38:[function(e,t,r){t.exports=d;var n,i=e(35),o=i.LongBits,a=i.base64,s=i.utf8;function c(e,t,r){this.fn=e,this.len=t,this.next=g,this.val=r}function u(){}function l(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}function d(){this.len=0,this.head=new c(u,0,0),this.tail=this.head,this.states=null}function p(){return i.Buffer?function(){return(d.create=function(){return new n})()}:function(){return new d}}function f(e,t,r){t[r]=255&e}function h(e,t){this.len=e,this.next=g,this.val=t}function m(e,t,r){for(;e.hi;)t[r++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;127<e.lo;)t[r++]=127&e.lo|128,e.lo=e.lo>>>7;t[r++]=e.lo}function v(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}d.create=p(),d.alloc=function(e){return new i.Array(e)},i.Array!==Array&&(d.alloc=i.pool(d.alloc,i.Array.prototype.subarray)),d.prototype.p=function(e,t,r){return this.tail=this.tail.next=new c(e,t,r),this.len+=t,this},(h.prototype=Object.create(c.prototype)).fn=function(e,t,r){for(;127<e;)t[r++]=127&e|128,e>>>=7;t[r]=e},d.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new h((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this},d.prototype.int32=function(e){return e<0?this.p(m,10,o.fromNumber(e)):this.uint32(e)},d.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)},d.prototype.int64=d.prototype.uint64=function(e){return e=o.from(e),this.p(m,e.length(),e)},d.prototype.sint64=function(e){return e=o.from(e).zzEncode(),this.p(m,e.length(),e)},d.prototype.bool=function(e){return this.p(f,1,e?1:0)},d.prototype.sfixed32=d.prototype.fixed32=function(e){return this.p(v,4,e>>>0)},d.prototype.sfixed64=d.prototype.fixed64=function(e){return e=o.from(e),this.p(v,4,e.lo).p(v,4,e.hi)},d.prototype.float=function(e){return this.p(i.float.writeFloatLE,4,e)},d.prototype.double=function(e){return this.p(i.float.writeDoubleLE,8,e)};var y=i.Array.prototype.set?function(e,t,r){t.set(e,r)}:function(e,t,r){for(var n=0;n<e.length;++n)t[r+n]=e[n]};d.prototype.bytes=function(e){var t,r=e.length>>>0;return r?(i.isString(e)&&(t=d.alloc(r=a.length(e)),a.decode(e,t,0),e=t),this.uint32(r).p(y,r,e)):this.p(f,1,0)},d.prototype.string=function(e){var t=s.length(e);return t?this.uint32(t).p(s.write,t,e):this.p(f,1,0)},d.prototype.fork=function(){return this.states=new l(this),this.head=this.tail=new c(u,0,0),this.len=0,this},d.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new c(u,0,0),this.len=0),this},d.prototype.ldelim=function(){var e=this.head,t=this.tail,r=this.len;return this.reset().uint32(r),r&&(this.tail.next=e.next,this.tail=t,this.len+=r),this},d.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),r=0;e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t},d.r=function(e){n=e,d.create=p(),n.r()}},{35:35}],39:[function(e,t,r){t.exports=o;var n=e(38),i=((o.prototype=Object.create(n.prototype)).constructor=o,e(35));function o(){n.call(this)}function a(e,t,r){e.length<40?i.utf8.write(e,t,r):t.utf8Write?t.utf8Write(e,r):t.write(e,r)}o.r=function(){o.alloc=i.b,o.writeBytesBuffer=i.Buffer&&i.Buffer.prototype instanceof Uint8Array&&"set"===i.Buffer.prototype.set.name?function(e,t,r){t.set(e,r)}:function(e,t,r){if(e.copy)e.copy(t,r,0,e.length);else for(var n=0;n<e.length;)t[r++]=e[n++]}},o.prototype.bytes=function(e){var t=(e=i.isString(e)?i.v(e,"base64"):e).length>>>0;return this.uint32(t),t&&this.p(o.writeBytesBuffer,t,e),this},o.prototype.string=function(e){var t=i.Buffer.byteLength(e);return this.uint32(t),t&&this.p(a,t,e),this},o.r()},{35:35,38:38}]},e={},i=function t(n){var i=e[n];return i||r[n][0].call(i=e[n]={exports:{}},t,i,i.exports),i.exports}(16),i.util.global.protobuf=i,module&&module.exports&&(module.exports=i)}()})(protobuf);var protobufExports=protobuf.exports,fakeIdToCallback={},lastFakeId=0,addTimer=function(e,t){return"interval"===(arguments.length>2&&void 0!==arguments[2]?arguments[2]:"timeout")?window.setInterval(e,t):window.setTimeout(e,t)},removeTimer=function(e){return"interval"===(arguments.length>1&&void 0!==arguments[1]?arguments[1]:"timeout")?window.clearInterval(e):window.clearTimeout(e)};function commonjsRequire(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}!function(e){var t,r;if(!/MSIE 10/i.test(navigator.userAgent))try{t=new Blob(["\nconst fakeIdToId = {};\nonmessage = (event) => {\n const { fakeId, name, time } = event.data;\n switch (name) {\n case 'setInterval':\n fakeIdToId[fakeId] = setInterval(() => {\n postMessage({ fakeId });\n }, time);\n break;\n case 'clearInterval':\n if (fakeIdToId[fakeId] !== undefined) {\n clearInterval(fakeIdToId[fakeId]);\n delete fakeIdToId[fakeId];\n }\n break;\n case 'setTimeout':\n fakeIdToId[fakeId] = setTimeout(() => {\n postMessage({ fakeId });\n if (fakeIdToId[fakeId] !== undefined) {\n delete fakeIdToId[fakeId];\n }\n }, time);\n break;\n case 'clearTimeout':\n if (fakeIdToId[fakeId] !== undefined) {\n clearTimeout(fakeIdToId[fakeId]);\n delete fakeIdToId[fakeId];\n }\n break;\n }\n}\n"]),e=window.URL.createObjectURL(t)}catch(e){}if("undefined"!=typeof Worker)try{r=new Worker(e),addTimer=function(e,t,n){var i=lastFakeId++;return fakeIdToCallback[i]={callback:e,time:t,isTimeout:"timeout"===n},r.postMessage({name:"interval"===n?"setInterval":"setTimeout",fakeId:i,time:t}),i},removeTimer=function(e,t){fakeIdToCallback[e]&&(delete fakeIdToCallback[e],r.postMessage({name:"timeout"===t?"clearInterval":"clearTimeout",fakeId:e}))},r.onmessage=function(e){var t,r,n=e.data.fakeId;fakeIdToCallback[n]&&(r=(t=fakeIdToCallback[n]).callback,t.isTimeout&&t.isTimeout&&delete fakeIdToCallback[n]),r&&r()},r.onerror=function(e){console.error(e)}}catch(e){console.error("Initialisation failed")}}("timerWorker.js");var base64={exports:{}};base64.exports=function e(t,r,n){function i(a,s){if(!r[a]){if(!t[a]){var c="function"==typeof commonjsRequire&&commonjsRequire;if(!s&&c)return c(a,!0);if(o)return o(a,!0);var u=new Error("Cannot find module '"+a+"'");throw u.code="MODULE_NOT_FOUND",u}var l=r[a]={exports:{}};t[a][0].call(l.exports,function(e){return i(t[a][1][e]||e)},l,l.exports,e,t,r,n)}return r[a].exports}for(var o="function"==typeof commonjsRequire&&commonjsRequire,a=0;a<n.length;a++)i(n[a]);return i}({"/":[function(e,t,r){function n(e){var t=e.length;if(0<t%4)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function i(e){return a[63&e>>18]+a[63&e>>12]+a[63&e>>6]+a[63&e]}function o(e,t,r){for(var n,o=[],a=t;a<r;a+=3)n=(16711680&e[a]<<16)+(65280&e[a+1]<<8)+(255&e[a+2]),o.push(i(n));return o.join("")}r.byteLength=function(e){var t=n(e),r=t[0],i=t[1];return 3*(r+i)/4-i},r.toByteArray=function(e){var t,r,i=n(e),o=i[0],a=i[1],u=new c(function(e,t,r){return 3*(t+r)/4-r}(0,o,a)),l=0,d=0<a?o-4:o;for(r=0;r<d;r+=4)t=s[e.charCodeAt(r)]<<18|s[e.charCodeAt(r+1)]<<12|s[e.charCodeAt(r+2)]<<6|s[e.charCodeAt(r+3)],u[l++]=255&t>>16,u[l++]=255&t>>8,u[l++]=255&t;return 2===a&&(t=s[e.charCodeAt(r)]<<2|s[e.charCodeAt(r+1)]>>4,u[l++]=255&t),1===a&&(t=s[e.charCodeAt(r)]<<10|s[e.charCodeAt(r+1)]<<4|s[e.charCodeAt(r+2)]>>2,u[l++]=255&t>>8,u[l++]=255&t),u},r.fromByteArray=function(e){for(var t,r=e.length,n=r%3,i=[],s=16383,c=0,u=r-n;c<u;c+=s)i.push(o(e,c,c+s>u?u:c+s));return 1===n?(t=e[r-1],i.push(a[t>>2]+a[63&t<<4]+"==")):2===n&&(t=(e[r-2]<<8)+e[r-1],i.push(a[t>>10]+a[63&t>>4]+a[63&t<<2]+"=")),i.join("")};for(var a=[],s=[],c="undefined"==typeof Uint8Array?Array:Uint8Array,u="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",l=0;l<64;++l)a[l]=u[l],s[u.charCodeAt(l)]=l;s[45]=62,s[95]=63},{}]},{},[])("/");var base64Exports=base64.exports;function _createForOfIteratorHelper$d(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$1$1(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$1$1(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$1$1(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_arrayLikeToArray$1$1(e,t):void 0}}function _arrayLikeToArray$1$1(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}var updateProtobuf=function(e){protobufExports.util.Long=e,protobufExports.util.LongBits.prototype.toLong=function(t){return 0===this.hi?this.lo:new e(this.lo,this.hi,t)},protobufExports.configure()},encoder$1=new TextEncoder,decoder=new TextDecoder,toBase64=function(e){return base64Exports.fromByteArray(encoder$1.encode(e))},fromBase64=function(e){return decoder.decode(base64Exports.toByteArray(e))},type=function(e){return Object.prototype.toString.call(e).match(/\[object (.*?)\]/)[1].toLowerCase()},isNumber=function(e){return"number"===type(e)},isString=function(e){return"string"===type(e)},isObject=function(e){return"object"===type(e)},uniqBy=function(){var e,t=arguments.length>1?arguments[1]:void 0,r=[],n={},i=_createForOfIteratorHelper$d(arguments.length>0&&void 0!==arguments[0]?arguments[0]:[]);try{for(i.s();!(e=i.n()).done;){var o=e.value;n[o[t]]||(r.push(o),n[o[t]]=1)}}catch(e){i.e(e)}finally{i.f()}return r},createUuid=function(e){var t="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)});return t.substring(0,e||t.length)},ensureDigits=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:2;if(2===t)return e<10?"0".concat(e):"".concat(e);if(3===t){if(e<10)return"00".concat(e);if(e<100)return"0".concat(e)}return"".concat(e)},formatToBeijingTime=function(e){if(!(e instanceof Date))return"[not a Date]";var t=e.getTime()+288e5,r=new Date(t),n="";try{n="".concat(r.getUTCFullYear(),"-").concat(ensureDigits(r.getUTCMonth()+1),"-").concat(ensureDigits(r.getUTCDate())," ").concat(ensureDigits(r.getUTCHours()),":").concat(ensureDigits(r.getUTCMinutes()),":").concat(ensureDigits(r.getUTCSeconds()),".").concat(ensureDigits(r.getUTCMilliseconds(),3))}catch(e){}return n},tryJsonStringify=function(e){if(void 0===e)return"[undefined]";try{if(e instanceof Set||e instanceof Map)return JSON.stringify(Array.from(e));if(e instanceof Error){var t={name:e.name,message:e.message,stack:e.stack};return e.log&&(t.log=e.log),e.code&&(t.code=e.code),JSON.stringify(t)}return JSON.stringify(e)}catch(e){return"[tryJsonStringify failed]"}},Debouncer=_createClass(function e(){_classCallCheck(this,e),Object.defineProperty(this,"timer",{enumerable:!0,configurable:!0,writable:!0,value:void 0})},[{key:"debounce",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:500;clearTimeout(this.timer),this.timer=setTimeout(function(){e&&e(),t.timer=null},r)}}]),getPlainMediaTrackInfo=function(e){var t={};return e?(t.kind=e.kind,t.label=e.label,t.id=e.id,t.contentHint=e.contentHint,t.enabled=e.enabled,t.muted=e.muted,t.readyState=e.readyState,t.settings=e.getSettings(),t.constraints=e.getConstraints(),t):t},getPlainMediaStreamInfo=function(e){if(!e)return{};var t={id:e.id,active:e.active},r=e.getTracks().map(function(e){return getPlainMediaTrackInfo(e)});return t.trackInfos=r,t},isPrivateIP=function(e){var t=e.split(".").reduce(function(e,t,r){return e+Number(t)*Math.pow(256,3-r)},0);return t>=167772160&&t<=184549375||t>=2886729728&&t<=2887778303||t>=3232235520&&t<=3232301055},getProtobufRoot=function(e){return protobufExports.Root.fromJSON(e)},diffTime=0,setDiffTime=function(e){diffTime=e},getTime=function(){return Date.now()+diffTime},taskQueue$1=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1,t=[],r=0,n=!1,i=function(){var n=_asyncToGenerator(_regeneratorRuntime.mark(function n(){var o,a;return _regeneratorRuntime.wrap(function(n){for(;;)switch(n.prev=n.next){case 0:if(!(r<e&&t.length)){n.next=6;break}if(r++,!(o=t.shift())){n.next=5;break}return n.prev=1,n.next=2,o();case 2:n.next=4;break;case 3:n.prev=3,a=n.catch(1),console.log(a);case 4:r--,i();case 5:n.next=0;break;case 6:case"end":return n.stop()}},n,null,[[1,3]])}));return function(){return n.apply(this,arguments)}}();return{add:function(e){t.push(e),n&&i()},start:function(){n=!0,i()}}},awaitTime$1=function(e){return new Promise(function(t){addTimer(t,1e3*e)})},uaParser={exports:{}};!function(e,t){!function(r,n){var i="function",o="undefined",a="object",s="string",c="major",u="model",l="name",d="type",p="vendor",f="version",h="architecture",g="console",m="mobile",v="tablet",y="smarttv",b="wearable",S="embedded",_="Amazon",E="Apple",T="ASUS",R="BlackBerry",C="Browser",k="Chrome",P="Firefox",w="Google",O="Huawei",I="LG",A="Microsoft",M="Motorola",N="Opera",D="Samsung",x="Sharp",L="Sony",j="Xiaomi",$="Zebra",U="Facebook",F="Chromium OS",V="macOS",G=" Browser",B=function(e){for(var t={},r=0;r<e.length;r++)t[e[r].toUpperCase()]=e[r];return t},H=function(e,t){return typeof e===s&&-1!==q(t).indexOf(q(e))},q=function(e){return e.toLowerCase()},K=function(e,t){if(typeof e===s)return e=e.replace(/^\s\s*/,""),typeof t===o?e:e.substring(0,500)},W=function(e,t){for(var r,o,s,c,u,l,d=0;d<t.length&&!u;){var p=t[d],f=t[d+1];for(r=o=0;r<p.length&&!u&&p[r];)if(u=p[r++].exec(e))for(s=0;s<f.length;s++)l=u[++o],typeof(c=f[s])===a&&c.length>0?2===c.length?typeof c[1]==i?this[c[0]]=c[1].call(this,l):this[c[0]]=c[1]:3===c.length?typeof c[1]!==i||c[1].exec&&c[1].test?this[c[0]]=l?l.replace(c[1],c[2]):n:this[c[0]]=l?c[1].call(this,l,c[2]):n:4===c.length&&(this[c[0]]=l?c[3].call(this,l.replace(c[1],c[2])):n):this[c]=l||n;d+=2}},Y=function(e,t){for(var r in t)if(typeof t[r]===a&&t[r].length>0){for(var i=0;i<t[r].length;i++)if(H(t[r][i],e))return"?"===r?n:r}else if(H(t[r],e))return"?"===r?n:r;return t.hasOwnProperty("*")?t["*"]:e},J={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"},z={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[f,[l,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[f,[l,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[l,f],[/opios[\/ ]+([\w\.]+)/i],[f,[l,N+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[f,[l,N+" GX"]],[/\bopr\/([\w\.]+)/i],[f,[l,N]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[f,[l,"Baidu"]],[/\b(?:mxbrowser|mxios|myie2)\/?([-\w\.]*)\b/i],[f,[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,f],[/quark(?:pc)?\/([-\w\.]+)/i],[f,[l,"Quark"]],[/\bddg\/([\w\.]+)/i],[f,[l,"DuckDuckGo"]],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[f,[l,"UC"+C]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[f,[l,"WeChat"]],[/konqueror\/([\w\.]+)/i],[f,[l,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[f,[l,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[f,[l,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[f,[l,"Smart Lenovo "+C]],[/(avast|avg)\/([\w\.]+)/i],[[l,/(.+)/,"$1 Secure "+C],f],[/\bfocus\/([\w\.]+)/i],[f,[l,P+" Focus"]],[/\bopt\/([\w\.]+)/i],[f,[l,N+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[f,[l,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[f,[l,"Dolphin"]],[/coast\/([\w\.]+)/i],[f,[l,N+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[f,[l,"MIUI"+G]],[/fxios\/([\w\.-]+)/i],[f,[l,P]],[/\bqihoobrowser\/?([\w\.]*)/i],[f,[l,"360"]],[/\b(qq)\/([\w\.]+)/i],[[l,/(.+)/,"$1Browser"],f],[/(oculus|sailfish|huawei|vivo|pico)browser\/([\w\.]+)/i],[[l,/(.+)/,"$1"+G],f],[/samsungbrowser\/([\w\.]+)/i],[f,[l,D+" Internet"]],[/metasr[\/ ]?([\d\.]+)/i],[f,[l,"Sogou Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[l,"Sogou Mobile"],f],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345(?=browser|chrome|explorer))\w*[\/ ]?v?([\w\.]+)/i],[l,f],[/(lbbrowser|rekonq)/i,/\[(linkedin)app\]/i],[l],[/ome\/([\w\.]+) \w* ?(iron) saf/i,/ome\/([\w\.]+).+qihu (360)[es]e/i],[f,l],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[l,U],f],[/(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,f],[/\bgsa\/([\w\.]+) .*safari\//i],[f,[l,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[f,[l,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[f,[l,k+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[l,k+" WebView"],f],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[f,[l,"Android "+C]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[l,f],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[f,[l,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[f,l],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[l,[f,Y,{"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,f],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[l,"Netscape"],f],[/(wolvic|librewolf)\/([\w\.]+)/i],[l,f],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[f,[l,P+" 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,[f,/_/g,"."]],[/(cobalt)\/([\w\.]+)/i],[l,[f,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[h,"amd64"]],[/(ia32(?=;))/i],[[h,q]],[/((?:i[346]|x)86)[;\)]/i],[[h,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[h,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[h,"armhf"]],[/windows (ce|mobile); ppc;/i],[[h,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[h,/ower/,"",q]],[/(sun4\w)[;\)]/i],[[h,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[h,q]]],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],[u,[p,D],[d,v]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]((?!sm-[lr])[-\w]+)/i,/sec-(sgh\w+)/i],[u,[p,D],[d,m]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[u,[p,E],[d,m]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[u,[p,E],[d,v]],[/(macintosh);/i],[u,[p,E]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[u,[p,x],[d,m]],[/(?:honor)([-\w ]+)[;\)]/i],[u,[p,"Honor"],[d,m]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[u,[p,O],[d,v]],[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[u,[p,O],[d,m]],[/\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],[[u,/_/g," "],[p,j],[d,m]],[/oid[^\)]+; (2\d{4}(283|rpbf)[cgl])( bui|\))/i,/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[u,/_/g," "],[p,j],[d,v]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[u,[p,"OPPO"],[d,m]],[/\b(opd2\d{3}a?) bui/i],[u,[p,"OPPO"],[d,v]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[u,[p,"Vivo"],[d,m]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[u,[p,"Realme"],[d,m]],[/\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],[u,[p,M],[d,m]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[u,[p,M],[d,v]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[u,[p,I],[d,v]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[u,[p,I],[d,m]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[u,[p,"Lenovo"],[d,v]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[u,/_/g," "],[p,"Nokia"],[d,m]],[/(pixel c)\b/i],[u,[p,w],[d,v]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[u,[p,w],[d,m]],[/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],[u,[p,L],[d,m]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[u,"Xperia Tablet"],[p,L],[d,v]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[u,[p,"OnePlus"],[d,m]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[u,[p,_],[d,v]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[u,/(.+)/g,"Fire Phone $1"],[p,_],[d,m]],[/(playbook);[-\w\),; ]+(rim)/i],[u,p,[d,v]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[u,[p,R],[d,m]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[u,[p,T],[d,v]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[u,[p,T],[d,m]],[/(nexus 9)/i],[u,[p,"HTC"],[d,v]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[p,[u,/_/g," "],[d,m]],[/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],[u,[p,"TCL"],[d,v]],[/(itel) ((\w+))/i],[[p,q],u,[d,Y,{tablet:["p10001l","w7001"],"*":"mobile"}]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[u,[p,"Acer"],[d,v]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[u,[p,"Meizu"],[d,m]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[u,[p,"Ulefone"],[d,m]],[/; (energy ?\w+)(?: bui|\))/i,/; energizer ([\w ]+)(?: bui|\))/i],[u,[p,"Energizer"],[d,m]],[/; cat (b35);/i,/; (b15q?|s22 flip|s48c|s62 pro)(?: bui|\))/i],[u,[p,"Cat"],[d,m]],[/((?:new )?andromax[\w- ]+)(?: bui|\))/i],[u,[p,"Smartfren"],[d,m]],[/droid.+; (a(?:015|06[35]|142p?))/i],[u,[p,"Nothing"],[d,m]],[/(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],[p,u,[d,m]],[/(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],[p,u,[d,v]],[/(surface duo)/i],[u,[p,A],[d,v]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[u,[p,"Fairphone"],[d,m]],[/(u304aa)/i],[u,[p,"AT&T"],[d,m]],[/\bsie-(\w*)/i],[u,[p,"Siemens"],[d,m]],[/\b(rct\w+) b/i],[u,[p,"RCA"],[d,v]],[/\b(venue[\d ]{2,7}) b/i],[u,[p,"Dell"],[d,v]],[/\b(q(?:mv|ta)\w+) b/i],[u,[p,"Verizon"],[d,v]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[u,[p,"Barnes & Noble"],[d,v]],[/\b(tm\d{3}\w+) b/i],[u,[p,"NuVision"],[d,v]],[/\b(k88) b/i],[u,[p,"ZTE"],[d,v]],[/\b(nx\d{3}j) b/i],[u,[p,"ZTE"],[d,m]],[/\b(gen\d{3}) b.+49h/i],[u,[p,"Swiss"],[d,m]],[/\b(zur\d{3}) b/i],[u,[p,"Swiss"],[d,v]],[/\b((zeki)?tb.*\b) b/i],[u,[p,"Zeki"],[d,v]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[p,"Dragon Touch"],u,[d,v]],[/\b(ns-?\w{0,9}) b/i],[u,[p,"Insignia"],[d,v]],[/\b((nxa|next)-?\w{0,9}) b/i],[u,[p,"NextBook"],[d,v]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[p,"Voice"],u,[d,m]],[/\b(lvtel\-)?(v1[12]) b/i],[[p,"LvTel"],u,[d,m]],[/\b(ph-1) /i],[u,[p,"Essential"],[d,m]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[u,[p,"Envizen"],[d,v]],[/\b(trio[-\w\. ]+) b/i],[u,[p,"MachSpeed"],[d,v]],[/\btu_(1491) b/i],[u,[p,"Rotor"],[d,v]],[/(shield[\w ]+) b/i],[u,[p,"Nvidia"],[d,v]],[/(sprint) (\w+)/i],[p,u,[d,m]],[/(kin\.[onetw]{3})/i],[[u,/\./g," "],[p,A],[d,m]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[u,[p,$],[d,v]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[u,[p,$],[d,m]],[/smart-tv.+(samsung)/i],[p,[d,y]],[/hbbtv.+maple;(\d+)/i],[[u,/^/,"SmartTV"],[p,D],[d,y]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[p,I],[d,y]],[/(apple) ?tv/i],[p,[u,E+" TV"],[d,y]],[/crkey/i],[[u,k+"cast"],[p,w],[d,y]],[/droid.+aft(\w+)( bui|\))/i],[u,[p,_],[d,y]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[u,[p,x],[d,y]],[/(bravia[\w ]+)( bui|\))/i],[u,[p,L],[d,y]],[/(mitv-\w{5}) bui/i],[u,[p,j],[d,y]],[/Hbbtv.*(technisat) (.*);/i],[p,u,[d,y]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[p,K],[u,K],[d,y]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[d,y]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[p,u,[d,g]],[/droid.+; (shield) bui/i],[u,[p,"Nvidia"],[d,g]],[/(playstation [345portablevi]+)/i],[u,[p,L],[d,g]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[u,[p,A],[d,g]],[/\b(sm-[lr]\d\d[05][fnuw]?s?)\b/i],[u,[p,D],[d,b]],[/((pebble))app/i],[p,u,[d,b]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[u,[p,E],[d,b]],[/droid.+; (glass) \d/i],[u,[p,w],[d,b]],[/droid.+; (wt63?0{2,3})\)/i],[u,[p,$],[d,b]],[/droid.+; (glass) \d/i],[u,[p,w],[d,b]],[/(pico) (4|neo3(?: link|pro)?)/i],[p,u,[d,b]],[/; (quest( \d| pro)?)/i],[u,[p,U],[d,b]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[p,[d,S]],[/(aeobc)\b/i],[u,[p,_],[d,S]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i],[u,[d,m]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[u,[d,v]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[d,v]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[d,m]],[/(android[-\w\. ]{0,9});.+buil/i],[u,[p,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[f,[l,"EdgeHTML"]],[/(arkweb)\/([\w\.]+)/i],[l,f],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[f,[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,f],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[f,l]],os:[[/microsoft (windows) (vista|xp)/i],[l,f],[/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i],[l,[f,Y,J]],[/windows nt 6\.2; (arm)/i,/windows[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i,/(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[f,Y,J],[l,"Windows"]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[f,/_/g,"."],[l,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[l,V],[f,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[f,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,f],[/\(bb(10);/i],[f,[l,R]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[f,[l,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[f,[l,P+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[f,[l,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[f,[l,"watchOS"]],[/crkey\/([\d\.]+)/i],[f,[l,k+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[l,F],f],[/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,f],[/(sunos) ?([\w\.\d]*)/i],[[l,"Solaris"],f],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[l,f]]},Q=function(e,t){if(typeof e===a&&(t=e,e=n),!(this instanceof Q))return new Q(e,t).getResult();var g=typeof r!==o&&r.navigator?r.navigator:n,y=e||(g&&g.userAgent?g.userAgent:""),b=g&&g.userAgentData?g.userAgentData:n,S=t?function(e,t){var r={};for(var n in e)t[n]&&t[n].length%2==0?r[n]=t[n].concat(e[n]):r[n]=e[n];return r}(z,t):z,_=g&&g.userAgent==y;return this.getBrowser=function(){var e,t={};return t[l]=n,t[f]=n,W.call(t,y,S.browser),t[c]=typeof(e=t[f])===s?e.replace(/[^\d\.]/g,"").split(".")[0]:n,_&&g&&g.brave&&typeof g.brave.isBrave==i&&(t[l]="Brave"),t},this.getCPU=function(){var e={};return e[h]=n,W.call(e,y,S.cpu),e},this.getDevice=function(){var e={};return e[p]=n,e[u]=n,e[d]=n,W.call(e,y,S.device),_&&!e[d]&&b&&b.mobile&&(e[d]=m),_&&"Macintosh"==e[u]&&g&&typeof g.standalone!==o&&g.maxTouchPoints&&g.maxTouchPoints>2&&(e[u]="iPad",e[d]=v),e},this.getEngine=function(){var e={};return e[l]=n,e[f]=n,W.call(e,y,S.engine),e},this.getOS=function(){var e={};return e[l]=n,e[f]=n,W.call(e,y,S.os),_&&!e[l]&&b&&b.platform&&"Unknown"!=b.platform&&(e[l]=b.platform.replace(/chrome os/i,F).replace(/macos/i,V)),e},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return y},this.setUA=function(e){return y=typeof e===s&&e.length>500?K(e,500):e,this},this.setUA(y),this};Q.VERSION="1.0.40",Q.BROWSER=B([l,f,c]),Q.CPU=B([h]),Q.DEVICE=B([u,p,d,g,m,y,v,b,S]),Q.ENGINE=Q.OS=B([l,f]),e.exports&&(t=e.exports=Q),t.UAParser=Q;var Z=typeof r!==o&&(r.jQuery||r.Zepto);if(Z&&!Z.ua){var X=new Q;Z.ua=X.getResult(),Z.ua.get=function(){return X.getUA()},Z.ua.set=function(e){X.setUA(e);var t=X.getResult();for(var r in t)Z.ua[r]=t[r]}}}("object"==typeof window?window:commonjsGlobal)}(uaParser,uaParser.exports);var uaParserExports=uaParser.exports,BrowserType,OSType,_device$vendor,_a;!function(e){e._2345_EXPLORER="2345Explorer",e._360="360 Browser",e.ALIPAY="Alipay",e.AMAYA="Amaya",e.ANDROID="Android Browser",e.ARORA="Arora",e.AVANT="Avant",e.AVAST="Avast Secure Browser",e.AVG="AVG Secure Browser",e.BAIDU="Baidu Browser",e.BASILISK="Basilisk",e.BLAZER="Blazer",e.BOLT="Bolt",e.BOWSER="Bowser",e.BRAVE="Brave",e.CAMINO="Camino",e.CHIMERA="Chimera",e.CHROME="Chrome",e.CHROME_HEADLESS="Chrome Headless",e.CHROME_MOBILE="Mobile Chrome",e.CHROME_WEBVIEW="Chrome WebView",e.CHROMIUM="Chromium",e.COBALT="Cobalt",e.COC_COC="Coc Coc",e.COMODO_DRAGON="Comodo Dragon",e.CONKEROR="Conkeror",e.DILLO="Dillo",e.DOLPHIN="Dolphin",e.DORIS="Doris",e.DUCKDUCKGO="DuckDuckGo",e.EDGE="Edge",e.EPIPHANY="Epiphany",e.FACEBOOK="Facebook",e.FALKON="Falkon",e.FIREBIRD="Firebird",e.FIREFOX="Firefox",e.FIREFOX_FOCUS="Firefox Focus",e.FIREFOX_MOBILE="Mobile Firefox",e.FIREFOX_REALITY="Firefox Reality",e.FENNEC="Fennec",e.FLOCK="Flock",e.FLOW="Flow",e.GO="Go Browser",e.GOOGLE_SEARCH="GSA",e.HEYTAP="HeyTap",e.HUAWEI="Huawei Browser",e.ICAB="iCab",e.ICE="ICE Browser",e.ICEAPE="IceApe",e.ICECAT="IceCat",e.ICEDRAGON="IceDragon",e.ICEWEASEL="IceWeasel",e.IE="IE",e.INSTAGRAM="Instagram",e.IRIDIUM="Iridium",e.IRON="Iron",e.JASMINE="Jasmine",e.KONQUEROR="Konqueror",e.KAKAO="KakaoTalk",e.KHTML="KHTML",e.K_MELEON="K-Meleon",e.KLAR="Klar",e.KLARNA="Klarna",e.KINDLE="Kindle",e.LENOVO="Smart Lenovo Browser",e.LIEBAO="LBBROWSER",e.LINE="Line",e.LINKEDIN="LinkedIn",e.LINKS="Links",e.LUNASCAPE="Lunascape",e.LYNX="Lynx",e.MAEMO="Maemo Browser",e.MAXTHON="Maxthon",e.MIDORI="Midori",e.MINIMO="Minimo",e.MIUI="MIUI Browser",e.MOZILLA="Mozilla",e.MOSAIC="Mosaic",e.NAVER="Naver",e.NETFRONT="NetFront",e.NETSCAPE="Netscape",e.NETSURF="Netsurf",e.NOKIA="Nokia Browser",e.OBIGO="Obigo",e.OCULUS="Oculus Browser",e.OMNIWEB="OmniWeb",e.OPERA="Opera",e.OPERA_COAST="Opera Coast",e.OPERA_MINI="Opera Mini",e.OPERA_MOBI="Opera Mobi",e.OPERA_TABLET="Opera Tablet",e.OPERA_TOUCH="Opera Touch",e.OVI="OviBrowser",e.PALEMOON="PaleMoon",e.PHANTOMJS="PhantomJS",e.PHOENIX="Phoenix",e.POLARIS="Polaris",e.PUFFIN="Puffin",e.QQ="QQBrowser",e.QQ_LITE="QQBrowserLite",e.QUARK="Quark",e.QUPZILLA="QupZilla",e.REKONQ="rekonq",e.ROCKMELT="Rockmelt",e.SAFARI="Safari",e.SAFARI_MOBILE="Mobile Safari",e.SAILFISH="Sailfish Browser",e.SAMSUNG="Samsung Internet",e.SEAMONKEY="SeaMonkey",e.SILK="Silk",e.SKYFIRE="Skyfire",e.SLEIPNIR="Sleipnir",e.SLIMBROWSER="SlimBrowser",e.SNAPCHAT="Snapchat",e.SOGOU_EXPLORER="Sogou Explorer",e.SOGOU_MOBILE="Sogou Mobile",e.SWIFTFOX="Swiftfox",e.TESLA="Tesla",e.TIKTOK="TikTok",e.TIZEN="Tizen Browser",e.UC="UCBrowser",e.UP="UP.Browser",e.VIERA="Viera",e.VIVALDI="Vivaldi",e.VIVO="Vivo Browser",e.W3M="w3m",e.WATERFOX="Waterfox",e.WEBKIT="WebKit",e.WECHAT="WeChat",e.WEIBO="Weibo",e.WHALE="Whale",e.YANDEX="Yandex",e.ELECTRON="Electron"}(BrowserType||(BrowserType={})),function(e){e.AIX="AIX",e.AMIGA_OS="Amiga OS",e.ANDROID="Android",e.ANDROID_X86="Android-x86",e.ARCH="Arch",e.BADA="Bada",e.BEOS="BeOS",e.BLACKBERRY="BlackBerry",e.CENTOS="CentOS",e.CHROME_OS="Chrome OS",e.CHROMECAST="Chromecast",e.CONTIKI="Contiki",e.DEBIAN="Debian",e.DEEPIN="Deepin",e.DRAGONFLY="DragonFly",e.ELEMENTARY_OS="elementary OS",e.FEDORA="Fedora",e.FIREFOX_OS="Firefox OS",e.FREEBSD="FreeBSD",e.FUCHSIA="Fuchsia",e.GENTOO="Gentoo",e.GHOSTBSD="GhostBSD",e.GNU="GNU",e.HAIKU="Haiku",e.HARMONYOS="HarmonyOS",e.HP_UX="HP-UX",e.HURD="Hurd",e.IOS="iOS",e.JOLI="Joli",e.KAIOS="KaiOS",e.LINPUS="Linpus",e.LINSPIRE="Linspire",e.LINUX="Linux",e.MACOS="macOS",e.MAEMO="Maemo",e.MAGEIA="Mageia",e.MANDRIVA="Mandriva",e.MANJARO="Manjaro",e.MEEGO="MeeGo",e.MINIX="Minix",e.MINT="Mint",e.MORPH_OS="Morph OS",e.NETBSD="NetBSD",e.NETRANGE="NetRange",e.NETTV="NetTV",e.NINTENDO="Nintendo",e.OPENBSD="OpenBSD",e.OPENVMS="OpenVMS",e.OS2="OS/2",e.PALM="Palm",e.PC_BSD="PC-BSD",e.PCLINUXOS="PCLinuxOS",e.PLAN9="Plan9",e.PLAYSTATION="PlayStation",e.QNX="QNX",e.RASPBIAN="Raspbian",e.REDHAT="RedHat",e.RIM_TABLET_OS="RIM Tablet OS",e.RISC_OS="RISC OS",e.SABAYON="Sabayon",e.SAILFISH="Sailfish",e.SERENITYOS="SerenityOS",e.SERIES40="Series40",e.SLACKWARE="Slackware",e.SOLARIS="Solaris",e.SUSE="SUSE",e.SYMBIAN="Symbian",e.TIZEN="Tizen",e.UBUNTU="Ubuntu",e.UNIX="Unix",e.VECTORLINUX="VectorLinux",e.VIERA="Viera",e.WATCHOS="watchOS",e.WEBOS="WebOS",e.WINDOWS="Windows",e.WINDOWS_MOBILE="Windows Mobile",e.WINDOWS_PHONE="Windows Phone",e.XBOX="Xbox",e.ZENWALK="Zenwalk"}(OSType||(OSType={}));var parser$2=new uaParserExports.UAParser(navigator.userAgent),_parser$getResult=parser$2.getResult(),os=_parser$getResult.os,cpu=_parser$getResult.cpu,browser=_parser$getResult.browser,device=_parser$getResult.device,TerminalType$1,SdkType$1;"HarmonyOS"===os.name&&(os.name="Android"),function(e){e[e.Windows=1]="Windows",e[e.Android=2]="Android",e[e.Mac=3]="Mac",e[e.iOS=4]="iOS",e[e.Linux=5]="Linux",e[e.Others=6]="Others"}(TerminalType$1||(TerminalType$1={})),function(e){e[e.Native=1]="Native",e[e.Web=2]="Web",e[e.MiniProgram=3]="MiniProgram"}(SdkType$1||(SdkType$1={}));var clientDeviceId="";try{clientDeviceId=localStorage.getItem(DEVICEID)}catch(e){}if(!clientDeviceId){clientDeviceId=createUuid();try{localStorage.setItem(DEVICEID,clientDeviceId)}catch(e){}}var deviceId=clientDeviceId;window._dingrtc_js_load_tab_id=window._dingrtc_js_load_tab_id||createUuid(8);var browserTabId=window._dingrtc_js_load_tab_id,getTerminalType=function(){var e=TerminalType$1.Others;return os.name===OSType.WINDOWS?e=TerminalType$1.Windows:os.name===OSType.MACOS?e=TerminalType$1.Mac:os.name.includes(OSType.ANDROID)?e=TerminalType$1.Android:os.name===OSType.IOS?e=TerminalType$1.iOS:os.name===OSType.LINUX&&(e=TerminalType$1.Linux),e},Environment=_createClass(function e(){_classCallCheck(this,e)});function ownKeys$2$1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function _objectSpread$2$1(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$2$1(Object(r),!0).forEach(function(t){_defineProperty$1(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$2$1(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}_a=Environment,Object.defineProperty(Environment,"browserType",{enumerable:!0,configurable:!0,writable:!0,value:browser.name}),Object.defineProperty(Environment,"browserVersion",{enumerable:!0,configurable:!0,writable:!0,value:browser.version}),Object.defineProperty(Environment,"system",{enumerable:!0,configurable:!0,writable:!0,value:os.name}),Object.defineProperty(Environment,"terminalType",{enumerable:!0,configurable:!0,writable:!0,value:getTerminalType()}),Object.defineProperty(Environment,"sdkType",{enumerable:!0,configurable:!0,writable:!0,value:SdkType$1.Web}),Object.defineProperty(Environment,"systemVersion",{enumerable:!0,configurable:!0,writable:!0,value:os.version}),Object.defineProperty(Environment,"deviceId",{enumerable:!0,configurable:!0,writable:!0,value:deviceId}),Object.defineProperty(Environment,"browserTabId",{enumerable:!0,configurable:!0,writable:!0,value:browserTabId}),Object.defineProperty(Environment,"networkType",{enumerable:!0,configurable:!0,writable:!0,value:"unknown"}),Object.defineProperty(Environment,"manu",{enumerable:!0,configurable:!0,writable:!0,value:null===(_device$vendor=device.vendor)||void 0===_device$vendor?void 0:_device$vendor.toLocaleLowerCase()}),Object.defineProperty(Environment,"model",{enumerable:!0,configurable:!0,writable:!0,value:device.model}),Object.defineProperty(Environment,"cpu",{enumerable:!0,configurable:!0,writable:!0,value:cpu.architecture}),Object.defineProperty(Environment,"isAndroid",{enumerable:!0,configurable:!0,writable:!0,value:function(){return _a.system.includes(OSType.ANDROID)}}),Object.defineProperty(Environment,"isIOS",{enumerable:!0,configurable:!0,writable:!0,value:function(){return _a.system===OSType.IOS}}),Object.defineProperty(Environment,"isWeixin",{enumerable:!0,configurable:!0,writable:!0,value:function(){return _a.browserType===BrowserType.WECHAT}}),Object.defineProperty(Environment,"isChrome",{enumerable:!0,configurable:!0,writable:!0,value:function(){return _a.browserType.includes(BrowserType.CHROME)}}),Object.defineProperty(Environment,"isSafari",{enumerable:!0,configurable:!0,writable:!0,value:function(){return _a.browserType.includes(BrowserType.SAFARI)}}),Object.defineProperty(Environment,"isFirefox",{enumerable:!0,configurable:!0,writable:!0,value:function(){return _a.browserType.includes(BrowserType.FIREFOX)}}),Object.defineProperty(Environment,"isOpera",{enumerable:!0,configurable:!0,writable:!0,value:function(){return _a.browserType.includes(BrowserType.OPERA)}}),Object.defineProperty(Environment,"isQQBrowser",{enumerable:!0,configurable:!0,writable:!0,value:function(){return _a.browserType===BrowserType.QQ}}),Object.defineProperty(Environment,"isElectron",{enumerable:!0,configurable:!0,writable:!0,value:function(){return _a.browserType===BrowserType.ELECTRON}});var iFetch=function(e,t,r){var n=_objectSpread$2$1(_objectSpread$2$1({},arguments.length>3&&void 0!==arguments[3]?arguments[3]:{}),{},{"Content-Type":"application/json",Accept:"application/json"});return new Promise(function(i,o){var a;fetch(t,{method:e,body:r,headers:n}).then(function(e){return a=e,e.ok?e.json():e.text()}).then(function(e){var t;null!==(t=a)&&void 0!==t&&t.ok?e.code?o(e):i(e):o(a)}).catch(function(e){o(e)})})},post$1=function(e,t,r){return iFetch("POST",e,t,r)},logService=function(e){var t=e.userId;delete e.userId;var r="/v1/users/".concat(t,"/log-service");return post$1("".concat(getGslb()).concat(r),JSON.stringify(e))},EventEmitter=_createClass(function e(){_classCallCheck(this,e),Object.defineProperty(this,"eventMap",{enumerable:!0,configurable:!0,writable:!0,value:{}})},[{key:"listenerCount",value:function(e){return this.eventMap[e].length||0}},{key:"emit",value:function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];var i=this.eventMap[e];return!(!i||0===i.length||(i.forEach(function(t){try{t.fn.apply(t,r)}catch(t){console.error(e,"event callback execute error:",t)}}),this.eventMap[e]=i.filter(function(e){return!e.once}),0))}},{key:"on",value:function(e,t){return this.eventMap[e]||(this.eventMap[e]=[]),this.eventMap[e].some(function(e){return e.fn===t&&!e.once})||this.eventMap[e].push({fn:t,once:!1}),this}},{key:"once",value:function(e,t){return this.eventMap[e]||(this.eventMap[e]=[]),this.eventMap[e].some(function(e){return e.fn===t&&e.once})||this.eventMap[e].push({fn:t,once:!0}),this}},{key:"off",value:function(e,t){if(t){var r=this.eventMap[e];if(r&&r.length>0){var n=r.findIndex(function(e){return e.fn===t});n>-1&&r.splice(n,1)}}else this.eventMap[e]=[]}},{key:"removeAllListeners",value:function(e){e?this.eventMap[e]=[]:this.eventMap={}}}]),EventBus=new EventEmitter;function _callSuper$1$1(e,t,r){return t=_getPrototypeOf(t),_possibleConstructorReturn(e,_isNativeReflectConstruct$1$1()?Reflect.construct(t,[],_getPrototypeOf(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$1$1(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$1$1=function(){return!!e})()}var STSTokenManager=function(e){function t(e,r,n){var i;return _classCallCheck(this,t),i=_callSuper$1$1(this,t),Object.defineProperty(i,"credential",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"updating",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"requesting",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"commonInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"securityToken",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"delayTimerId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"checkTokenTimerId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"startTime",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),i.commonInfo=r,i.securityToken=e,i.updating=!0,i.delayTimerId=0,i.checkTokenTimerId=0,i.requesting=!1,i.updateCredential(n),i}return _inherits(t,EventEmitter),_createClass(t,[{key:"stopUpdateToken",value:function(){this.updating=!1,this.stopDelayTimer(),this.stopCheckTokenTimer()}},{key:"requestStsToken",value:function(){var e=this;if(!this.requesting&&this.updating){this.requesting=!0;var t=this.commonInfo,r=t.usrid,n=t.roomName,i=t.apid;logService({userId:r,channelId:n,appId:i,securityToken:this.securityToken.securityToken}).then(function(t){if(t&&t.logService)return e.updateCredential(t.logService.credentials),e.emit("update",t.logService),e.securityToken=t.securityToken,e.requesting=!1,!0;e.updating&&e.delayRequest()}).catch(function(){e.updating&&e.delayRequest()})}}},{key:"delayRequest",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:3e4;this.delayTimerId||(this.delayTimerId=window.setTimeout(function(){e.requestStsToken()},t))}},{key:"stopDelayTimer",value:function(){this.delayTimerId&&(clearTimeout(this.delayTimerId),this.delayTimerId=null)}},{key:"updateSecurityToken",value:function(e){this.stopDelayTimer(),this.securityToken=e,this.delayRequest()}},{key:"updateCredential",value:function(e){this.credential=e,this.startTime=Date.now(),this.checkToken()}},{key:"checkToken",value:function(){var e=this;if(this.updating)if(this.credential.durationSeconds){var t=Math.round((Date.now()-this.startTime)/1e3);this.credential.durationSeconds-t<=0?this.requestStsToken():this.checkTokenTimerId||(this.checkTokenTimerId=window.setTimeout(function(){e.stopCheckTokenTimer(),e.checkToken()},3e5))}else this.requestStsToken()}},{key:"stopCheckTokenTimer",value:function(){this.checkTokenTimerId&&(clearTimeout(this.checkTokenTimerId),this.checkTokenTimerId=null)}}])}();function _arrayLikeToArray$e(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _arrayWithoutHoles$1(e){if(Array.isArray(e))return _arrayLikeToArray$e(e)}function _iterableToArray$1(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}function _unsupportedIterableToArray$e(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$e(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_arrayLikeToArray$e(e,t):void 0}}function _nonIterableSpread$1(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _toConsumableArray$1(e){return _arrayWithoutHoles$1(e)||_iterableToArray$1(e)||_unsupportedIterableToArray$e(e)||_nonIterableSpread$1()}var pakoDeflate={exports:{}};!function(e){function t(e){for(var t=e.length;--t>=0;)e[t]=0}var r=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]),n=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]),i=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),o=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),a=new Array(576);t(a);var s=new Array(60);t(s);var c=new Array(512);t(c);var u=new Array(256);t(u);var l=new Array(29);t(l);var d,p,f,h=new Array(30);function g(e,t,r,n,i){this.static_tree=e,this.extra_bits=t,this.extra_base=r,this.elems=n,this.max_length=i,this.has_stree=e&&e.length}function m(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}t(h);var v=function(e){return e<256?c[e]:c[256+(e>>>7)]},y=function(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255},b=function(e,t,r){e.bi_valid>16-r?(e.bi_buf|=t<<e.bi_valid&65535,y(e,e.bi_buf),e.bi_buf=t>>16-e.bi_valid,e.bi_valid+=r-16):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=r)},S=function(e,t,r){b(e,r[2*t],r[2*t+1])},_=function(e,t){var r=0;do{r|=1&e,e>>>=1,r<<=1}while(--t>0);return r>>>1},E=function(e,t,r){var n,i,o=new Array(16),a=0;for(n=1;n<=15;n++)a=a+r[n-1]<<1,o[n]=a;for(i=0;i<=t;i++){var s=e[2*i+1];0!==s&&(e[2*i]=_(o[s]++,s))}},T=function(e){var t;for(t=0;t<286;t++)e.dyn_ltree[2*t]=0;for(t=0;t<30;t++)e.dyn_dtree[2*t]=0;for(t=0;t<19;t++)e.bl_tree[2*t]=0;e.dyn_ltree[512]=1,e.opt_len=e.static_len=0,e.sym_next=e.matches=0},R=function(e){e.bi_valid>8?y(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0},C=function(e,t,r,n){var i=2*t,o=2*r;return e[i]<e[o]||e[i]===e[o]&&n[t]<=n[r]},k=function(e,t,r){for(var n=e.heap[r],i=r<<1;i<=e.heap_len&&(i<e.heap_len&&C(t,e.heap[i+1],e.heap[i],e.depth)&&i++,!C(t,n,e.heap[i],e.depth));)e.heap[r]=e.heap[i],r=i,i<<=1;e.heap[r]=n},P=function(e,t,i){var o,a,s,c,d=0;if(0!==e.sym_next)do{o=255&e.pending_buf[e.sym_buf+d++],o+=(255&e.pending_buf[e.sym_buf+d++])<<8,a=e.pending_buf[e.sym_buf+d++],0===o?S(e,a,t):(s=u[a],S(e,s+256+1,t),0!==(c=r[s])&&(a-=l[s],b(e,a,c)),o--,s=v(o),S(e,s,i),0!==(c=n[s])&&(o-=h[s],b(e,o,c)))}while(d<e.sym_next);S(e,256,t)},w=function(e,t){var r,n,i,o=t.dyn_tree,a=t.stat_desc.static_tree,s=t.stat_desc.has_stree,c=t.stat_desc.elems,u=-1;for(e.heap_len=0,e.heap_max=573,r=0;r<c;r++)0!==o[2*r]?(e.heap[++e.heap_len]=u=r,e.depth[r]=0):o[2*r+1]=0;for(;e.heap_len<2;)o[2*(i=e.heap[++e.heap_len]=u<2?++u:0)]=1,e.depth[i]=0,e.opt_len--,s&&(e.static_len-=a[2*i+1]);for(t.max_code=u,r=e.heap_len>>1;r>=1;r--)k(e,o,r);i=c;do{r=e.heap[1],e.heap[1]=e.heap[e.heap_len--],k(e,o,1),n=e.heap[1],e.heap[--e.heap_max]=r,e.heap[--e.heap_max]=n,o[2*i]=o[2*r]+o[2*n],e.depth[i]=(e.depth[r]>=e.depth[n]?e.depth[r]:e.depth[n])+1,o[2*r+1]=o[2*n+1]=i,e.heap[1]=i++,k(e,o,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],function(e,t){var r,n,i,o,a,s,c=t.dyn_tree,u=t.max_code,l=t.stat_desc.static_tree,d=t.stat_desc.has_stree,p=t.stat_desc.extra_bits,f=t.stat_desc.extra_base,h=t.stat_desc.max_length,g=0;for(o=0;o<=15;o++)e.bl_count[o]=0;for(c[2*e.heap[e.heap_max]+1]=0,r=e.heap_max+1;r<573;r++)(o=c[2*c[2*(n=e.heap[r])+1]+1]+1)>h&&(o=h,g++),c[2*n+1]=o,n>u||(e.bl_count[o]++,a=0,n>=f&&(a=p[n-f]),s=c[2*n],e.opt_len+=s*(o+a),d&&(e.static_len+=s*(l[2*n+1]+a)));if(0!==g){do{for(o=h-1;0===e.bl_count[o];)o--;e.bl_count[o]--,e.bl_count[o+1]+=2,e.bl_count[h]--,g-=2}while(g>0);for(o=h;0!==o;o--)for(n=e.bl_count[o];0!==n;)(i=e.heap[--r])>u||(c[2*i+1]!==o&&(e.opt_len+=(o-c[2*i+1])*c[2*i],c[2*i+1]=o),n--)}}(e,t),E(o,u,e.bl_count)},O=function(e,t,r){var n,i,o=-1,a=t[1],s=0,c=7,u=4;for(0===a&&(c=138,u=3),t[2*(r+1)+1]=65535,n=0;n<=r;n++)i=a,a=t[2*(n+1)+1],++s<c&&i===a||(s<u?e.bl_tree[2*i]+=s:0!==i?(i!==o&&e.bl_tree[2*i]++,e.bl_tree[32]++):s<=10?e.bl_tree[34]++:e.bl_tree[36]++,s=0,o=i,0===a?(c=138,u=3):i===a?(c=6,u=3):(c=7,u=4))},I=function(e,t,r){var n,i,o=-1,a=t[1],s=0,c=7,u=4;for(0===a&&(c=138,u=3),n=0;n<=r;n++)if(i=a,a=t[2*(n+1)+1],!(++s<c&&i===a)){if(s<u)do{S(e,i,e.bl_tree)}while(0!=--s);else 0!==i?(i!==o&&(S(e,i,e.bl_tree),s--),S(e,16,e.bl_tree),b(e,s-3,2)):s<=10?(S(e,17,e.bl_tree),b(e,s-3,3)):(S(e,18,e.bl_tree),b(e,s-11,7));s=0,o=i,0===a?(c=138,u=3):i===a?(c=6,u=3):(c=7,u=4)}},A=!1,M=function(e,t,r,n){b(e,0+(n?1:0),3),R(e),y(e,r),y(e,~r),r&&e.pending_buf.set(e.window.subarray(t,t+r),e.pending),e.pending+=r},N=function(e){A||(function(){var e,t,o,m,v,y=new Array(16);for(o=0,m=0;m<28;m++)for(l[m]=o,e=0;e<1<<r[m];e++)u[o++]=m;for(u[o-1]=m,v=0,m=0;m<16;m++)for(h[m]=v,e=0;e<1<<n[m];e++)c[v++]=m;for(v>>=7;m<30;m++)for(h[m]=v<<7,e=0;e<1<<n[m]-7;e++)c[256+v++]=m;for(t=0;t<=15;t++)y[t]=0;for(e=0;e<=143;)a[2*e+1]=8,e++,y[8]++;for(;e<=255;)a[2*e+1]=9,e++,y[9]++;for(;e<=279;)a[2*e+1]=7,e++,y[7]++;for(;e<=287;)a[2*e+1]=8,e++,y[8]++;for(E(a,287,y),e=0;e<30;e++)s[2*e+1]=5,s[2*e]=_(e,5);d=new g(a,r,257,286,15),p=new g(s,n,0,30,15),f=new g(new Array(0),i,0,19,7)}(),A=!0),e.l_desc=new m(e.dyn_ltree,d),e.d_desc=new m(e.dyn_dtree,p),e.bl_desc=new m(e.bl_tree,f),e.bi_buf=0,e.bi_valid=0,T(e)},D=M,x=function(e,t,r,n){var i,c,u=0;e.level>0?(2===e.strm.data_type&&(e.strm.data_type=function(e){var t,r=4093624447;for(t=0;t<=31;t++,r>>>=1)if(1&r&&0!==e.dyn_ltree[2*t])return 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t<256;t++)if(0!==e.dyn_ltree[2*t])return 1;return 0}(e)),w(e,e.l_desc),w(e,e.d_desc),u=function(e){var t;for(O(e,e.dyn_ltree,e.l_desc.max_code),O(e,e.dyn_dtree,e.d_desc.max_code),w(e,e.bl_desc),t=18;t>=3&&0===e.bl_tree[2*o[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t}(e),i=e.opt_len+3+7>>>3,(c=e.static_len+3+7>>>3)<=i&&(i=c)):i=c=r+5,r+4<=i&&-1!==t?M(e,t,r,n):4===e.strategy||c===i?(b(e,2+(n?1:0),3),P(e,a,s)):(b(e,4+(n?1:0),3),function(e,t,r,n){var i;for(b(e,t-257,5),b(e,r-1,5),b(e,n-4,4),i=0;i<n;i++)b(e,e.bl_tree[2*o[i]+1],3);I(e,e.dyn_ltree,t-1),I(e,e.dyn_dtree,r-1)}(e,e.l_desc.max_code+1,e.d_desc.max_code+1,u+1),P(e,e.dyn_ltree,e.dyn_dtree)),T(e),n&&R(e)},L=function(e,t,r){return e.pending_buf[e.sym_buf+e.sym_next++]=t,e.pending_buf[e.sym_buf+e.sym_next++]=t>>8,e.pending_buf[e.sym_buf+e.sym_next++]=r,0===t?e.dyn_ltree[2*r]++:(e.matches++,t--,e.dyn_ltree[2*(u[r]+256+1)]++,e.dyn_dtree[2*v(t)]++),e.sym_next===e.sym_end},j=function(e){b(e,2,3),S(e,256,a),function(e){16===e.bi_valid?(y(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}(e)},$=function(e,t,r,n){for(var i=65535&e,o=e>>>16&65535,a=0;0!==r;){r-=a=r>2e3?2e3:r;do{o=o+(i=i+t[n++]|0)|0}while(--a);i%=65521,o%=65521}return i|o<<16},U=new Uint32Array(function(){for(var e,t=[],r=0;r<256;r++){e=r;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[r]=e}return t}()),F=function(e,t,r,n){var i=U,o=n+r;e^=-1;for(var a=n;a<o;a++)e=e>>>8^i[255&(e^t[a])];return-1^e},V={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"},G={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},B=N,H=D,q=x,K=L,W=j,Y=G.Z_NO_FLUSH,J=G.Z_PARTIAL_FLUSH,z=G.Z_FULL_FLUSH,Q=G.Z_FINISH,Z=G.Z_BLOCK,X=G.Z_OK,ee=G.Z_STREAM_END,te=G.Z_STREAM_ERROR,re=G.Z_DATA_ERROR,ne=G.Z_BUF_ERROR,ie=G.Z_DEFAULT_COMPRESSION,oe=G.Z_FILTERED,ae=G.Z_HUFFMAN_ONLY,se=G.Z_RLE,ce=G.Z_FIXED,ue=G.Z_UNKNOWN,le=G.Z_DEFLATED,de=258,pe=262,fe=42,he=113,ge=666,me=function(e,t){return e.msg=V[t],t},ve=function(e){return 2*e-(e>4?9:0)},ye=function(e){for(var t=e.length;--t>=0;)e[t]=0},be=function(e){var t,r,n,i=e.w_size;n=t=e.hash_size;do{r=e.head[--n],e.head[n]=r>=i?r-i:0}while(--t);n=t=i;do{r=e.prev[--n],e.prev[n]=r>=i?r-i:0}while(--t)},Se=function(e,t,r){return(t<<e.hash_shift^r)&e.hash_mask},_e=function(e){var t=e.state,r=t.pending;r>e.avail_out&&(r=e.avail_out),0!==r&&(e.output.set(t.pending_buf.subarray(t.pending_out,t.pending_out+r),e.next_out),e.next_out+=r,t.pending_out+=r,e.total_out+=r,e.avail_out-=r,t.pending-=r,0===t.pending&&(t.pending_out=0))},Ee=function(e,t){q(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,_e(e.strm)},Te=function(e,t){e.pending_buf[e.pending++]=t},Re=function(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t},Ce=function(e,t,r,n){var i=e.avail_in;return i>n&&(i=n),0===i?0:(e.avail_in-=i,t.set(e.input.subarray(e.next_in,e.next_in+i),r),1===e.state.wrap?e.adler=$(e.adler,t,i,r):2===e.state.wrap&&(e.adler=F(e.adler,t,i,r)),e.next_in+=i,e.total_in+=i,i)},ke=function(e,t){var r,n,i=e.max_chain_length,o=e.strstart,a=e.prev_length,s=e.nice_match,c=e.strstart>e.w_size-pe?e.strstart-(e.w_size-pe):0,u=e.window,l=e.w_mask,d=e.prev,p=e.strstart+de,f=u[o+a-1],h=u[o+a];e.prev_length>=e.good_match&&(i>>=2),s>e.lookahead&&(s=e.lookahead);do{if(u[(r=t)+a]===h&&u[r+a-1]===f&&u[r]===u[o]&&u[++r]===u[o+1]){o+=2,r++;do{}while(u[++o]===u[++r]&&u[++o]===u[++r]&&u[++o]===u[++r]&&u[++o]===u[++r]&&u[++o]===u[++r]&&u[++o]===u[++r]&&u[++o]===u[++r]&&u[++o]===u[++r]&&o<p);if(n=de-(p-o),o=p-de,n>a){if(e.match_start=t,a=n,n>=s)break;f=u[o+a-1],h=u[o+a]}}}while((t=d[t&l])>c&&0!=--i);return a<=e.lookahead?a:e.lookahead},Pe=function(e){var t,r,n,i=e.w_size;do{if(r=e.window_size-e.lookahead-e.strstart,e.strstart>=i+(i-pe)&&(e.window.set(e.window.subarray(i,i+i-r),0),e.match_start-=i,e.strstart-=i,e.block_start-=i,e.insert>e.strstart&&(e.insert=e.strstart),be(e),r+=i),0===e.strm.avail_in)break;if(t=Ce(e.strm,e.window,e.strstart+e.lookahead,r),e.lookahead+=t,e.lookahead+e.insert>=3)for(n=e.strstart-e.insert,e.ins_h=e.window[n],e.ins_h=Se(e,e.ins_h,e.window[n+1]);e.insert&&(e.ins_h=Se(e,e.ins_h,e.window[n+3-1]),e.prev[n&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=n,n++,e.insert--,!(e.lookahead+e.insert<3)););}while(e.lookahead<pe&&0!==e.strm.avail_in)},we=function(e,t){var r,n,i,o=e.pending_buf_size-5>e.w_size?e.w_size:e.pending_buf_size-5,a=0,s=e.strm.avail_in;do{if(r=65535,i=e.bi_valid+42>>3,e.strm.avail_out<i)break;if(i=e.strm.avail_out-i,r>(n=e.strstart-e.block_start)+e.strm.avail_in&&(r=n+e.strm.avail_in),r>i&&(r=i),r<o&&(0===r&&t!==Q||t===Y||r!==n+e.strm.avail_in))break;a=t===Q&&r===n+e.strm.avail_in?1:0,H(e,0,0,a),e.pending_buf[e.pending-4]=r,e.pending_buf[e.pending-3]=r>>8,e.pending_buf[e.pending-2]=~r,e.pending_buf[e.pending-1]=~r>>8,_e(e.strm),n&&(n>r&&(n=r),e.strm.output.set(e.window.subarray(e.block_start,e.block_start+n),e.strm.next_out),e.strm.next_out+=n,e.strm.avail_out-=n,e.strm.total_out+=n,e.block_start+=n,r-=n),r&&(Ce(e.strm,e.strm.output,e.strm.next_out,r),e.strm.next_out+=r,e.strm.avail_out-=r,e.strm.total_out+=r)}while(0===a);return(s-=e.strm.avail_in)&&(s>=e.w_size?(e.matches=2,e.window.set(e.strm.input.subarray(e.strm.next_in-e.w_size,e.strm.next_in),0),e.strstart=e.w_size,e.insert=e.strstart):(e.window_size-e.strstart<=s&&(e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,e.insert>e.strstart&&(e.insert=e.strstart)),e.window.set(e.strm.input.subarray(e.strm.next_in-s,e.strm.next_in),e.strstart),e.strstart+=s,e.insert+=s>e.w_size-e.insert?e.w_size-e.insert:s),e.block_start=e.strstart),e.high_water<e.strstart&&(e.high_water=e.strstart),a?4:t!==Y&&t!==Q&&0===e.strm.avail_in&&e.strstart===e.block_start?2:(i=e.window_size-e.strstart,e.strm.avail_in>i&&e.block_start>=e.w_size&&(e.block_start-=e.w_size,e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,i+=e.w_size,e.insert>e.strstart&&(e.insert=e.strstart)),i>e.strm.avail_in&&(i=e.strm.avail_in),i&&(Ce(e.strm,e.window,e.strstart,i),e.strstart+=i,e.insert+=i>e.w_size-e.insert?e.w_size-e.insert:i),e.high_water<e.strstart&&(e.high_water=e.strstart),i=e.bi_valid+42>>3,o=(i=e.pending_buf_size-i>65535?65535:e.pending_buf_size-i)>e.w_size?e.w_size:i,((n=e.strstart-e.block_start)>=o||(n||t===Q)&&t!==Y&&0===e.strm.avail_in&&n<=i)&&(r=n>i?i:n,a=t===Q&&0===e.strm.avail_in&&r===n?1:0,H(e,e.block_start,r,a),e.block_start+=r,_e(e.strm)),a?3:1)},Oe=function(e,t){for(var r,n;;){if(e.lookahead<pe){if(Pe(e),e.lookahead<pe&&t===Y)return 1;if(0===e.lookahead)break}if(r=0,e.lookahead>=3&&(e.ins_h=Se(e,e.ins_h,e.window[e.strstart+3-1]),r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==r&&e.strstart-r<=e.w_size-pe&&(e.match_length=ke(e,r)),e.match_length>=3)if(n=K(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){e.match_length--;do{e.strstart++,e.ins_h=Se(e,e.ins_h,e.window[e.strstart+3-1]),r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart}while(0!=--e.match_length);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=Se(e,e.ins_h,e.window[e.strstart+1]);else n=K(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(n&&(Ee(e,!1),0===e.strm.avail_out))return 1}return e.insert=e.strstart<2?e.strstart:2,t===Q?(Ee(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(Ee(e,!1),0===e.strm.avail_out)?1:2},Ie=function(e,t){for(var r,n,i;;){if(e.lookahead<pe){if(Pe(e),e.lookahead<pe&&t===Y)return 1;if(0===e.lookahead)break}if(r=0,e.lookahead>=3&&(e.ins_h=Se(e,e.ins_h,e.window[e.strstart+3-1]),r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=2,0!==r&&e.prev_length<e.max_lazy_match&&e.strstart-r<=e.w_size-pe&&(e.match_length=ke(e,r),e.match_length<=5&&(e.strategy===oe||3===e.match_length&&e.strstart-e.match_start>4096)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){i=e.strstart+e.lookahead-3,n=K(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=i&&(e.ins_h=Se(e,e.ins_h,e.window[e.strstart+3-1]),r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart)}while(0!=--e.prev_length);if(e.match_available=0,e.match_length=2,e.strstart++,n&&(Ee(e,!1),0===e.strm.avail_out))return 1}else if(e.match_available){if((n=K(e,0,e.window[e.strstart-1]))&&Ee(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return 1}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(n=K(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<2?e.strstart:2,t===Q?(Ee(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(Ee(e,!1),0===e.strm.avail_out)?1:2};function Ae(e,t,r,n,i){this.good_length=e,this.max_lazy=t,this.nice_length=r,this.max_chain=n,this.func=i}var Me=[new Ae(0,0,0,0,we),new Ae(4,4,8,4,Oe),new Ae(4,5,16,8,Oe),new Ae(4,6,32,32,Oe),new Ae(4,4,16,16,Ie),new Ae(8,16,32,32,Ie),new Ae(8,16,128,128,Ie),new Ae(8,32,128,256,Ie),new Ae(32,128,258,1024,Ie),new Ae(32,258,258,4096,Ie)];function Ne(){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=le,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(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),ye(this.dyn_ltree),ye(this.dyn_dtree),ye(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),ye(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),ye(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}var De=function(e){if(!e)return 1;var t=e.state;return!t||t.strm!==e||t.status!==fe&&57!==t.status&&69!==t.status&&73!==t.status&&91!==t.status&&103!==t.status&&t.status!==he&&t.status!==ge?1:0},xe=function(e){if(De(e))return me(e,te);e.total_in=e.total_out=0,e.data_type=ue;var t=e.state;return t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=2===t.wrap?57:t.wrap?fe:he,e.adler=2===t.wrap?0:1,t.last_flush=-2,B(t),X},Le=function(e){var t,r=xe(e);return r===X&&((t=e.state).window_size=2*t.w_size,ye(t.head),t.max_lazy_match=Me[t.level].max_lazy,t.good_match=Me[t.level].good_length,t.nice_match=Me[t.level].nice_length,t.max_chain_length=Me[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=2,t.match_available=0,t.ins_h=0),r},je=function(e,t,r,n,i,o){if(!e)return te;var a=1;if(t===ie&&(t=6),n<0?(a=0,n=-n):n>15&&(a=2,n-=16),i<1||i>9||r!==le||n<8||n>15||t<0||t>9||o<0||o>ce||8===n&&1!==a)return me(e,te);8===n&&(n=9);var s=new Ne;return e.state=s,s.strm=e,s.status=fe,s.wrap=a,s.gzhead=null,s.w_bits=n,s.w_size=1<<s.w_bits,s.w_mask=s.w_size-1,s.hash_bits=i+7,s.hash_size=1<<s.hash_bits,s.hash_mask=s.hash_size-1,s.hash_shift=~~((s.hash_bits+3-1)/3),s.window=new Uint8Array(2*s.w_size),s.head=new Uint16Array(s.hash_size),s.prev=new Uint16Array(s.w_size),s.lit_bufsize=1<<i+6,s.pending_buf_size=4*s.lit_bufsize,s.pending_buf=new Uint8Array(s.pending_buf_size),s.sym_buf=s.lit_bufsize,s.sym_end=3*(s.lit_bufsize-1),s.level=t,s.strategy=o,s.method=r,Le(e)},$e=je,Ue=function(e,t){return De(e)||2!==e.state.wrap?te:(e.state.gzhead=t,X)},Fe=function(e,t){if(De(e)||t>Z||t<0)return e?me(e,te):te;var r=e.state;if(!e.output||0!==e.avail_in&&!e.input||r.status===ge&&t!==Q)return me(e,0===e.avail_out?ne:te);var n=r.last_flush;if(r.last_flush=t,0!==r.pending){if(_e(e),0===e.avail_out)return r.last_flush=-1,X}else if(0===e.avail_in&&ve(t)<=ve(n)&&t!==Q)return me(e,ne);if(r.status===ge&&0!==e.avail_in)return me(e,ne);if(r.status===fe&&0===r.wrap&&(r.status=he),r.status===fe){var i=le+(r.w_bits-8<<4)<<8;if(i|=(r.strategy>=ae||r.level<2?0:r.level<6?1:6===r.level?2:3)<<6,0!==r.strstart&&(i|=32),Re(r,i+=31-i%31),0!==r.strstart&&(Re(r,e.adler>>>16),Re(r,65535&e.adler)),e.adler=1,r.status=he,_e(e),0!==r.pending)return r.last_flush=-1,X}if(57===r.status)if(e.adler=0,Te(r,31),Te(r,139),Te(r,8),r.gzhead)Te(r,(r.gzhead.text?1:0)+(r.gzhead.hcrc?2:0)+(r.gzhead.extra?4:0)+(r.gzhead.name?8:0)+(r.gzhead.comment?16:0)),Te(r,255&r.gzhead.time),Te(r,r.gzhead.time>>8&255),Te(r,r.gzhead.time>>16&255),Te(r,r.gzhead.time>>24&255),Te(r,9===r.level?2:r.strategy>=ae||r.level<2?4:0),Te(r,255&r.gzhead.os),r.gzhead.extra&&r.gzhead.extra.length&&(Te(r,255&r.gzhead.extra.length),Te(r,r.gzhead.extra.length>>8&255)),r.gzhead.hcrc&&(e.adler=F(e.adler,r.pending_buf,r.pending,0)),r.gzindex=0,r.status=69;else if(Te(r,0),Te(r,0),Te(r,0),Te(r,0),Te(r,0),Te(r,9===r.level?2:r.strategy>=ae||r.level<2?4:0),Te(r,3),r.status=he,_e(e),0!==r.pending)return r.last_flush=-1,X;if(69===r.status){if(r.gzhead.extra){for(var o=r.pending,a=(65535&r.gzhead.extra.length)-r.gzindex;r.pending+a>r.pending_buf_size;){var s=r.pending_buf_size-r.pending;if(r.pending_buf.set(r.gzhead.extra.subarray(r.gzindex,r.gzindex+s),r.pending),r.pending=r.pending_buf_size,r.gzhead.hcrc&&r.pending>o&&(e.adler=F(e.adler,r.pending_buf,r.pending-o,o)),r.gzindex+=s,_e(e),0!==r.pending)return r.last_flush=-1,X;o=0,a-=s}var c=new Uint8Array(r.gzhead.extra);r.pending_buf.set(c.subarray(r.gzindex,r.gzindex+a),r.pending),r.pending+=a,r.gzhead.hcrc&&r.pending>o&&(e.adler=F(e.adler,r.pending_buf,r.pending-o,o)),r.gzindex=0}r.status=73}if(73===r.status){if(r.gzhead.name){var u,l=r.pending;do{if(r.pending===r.pending_buf_size){if(r.gzhead.hcrc&&r.pending>l&&(e.adler=F(e.adler,r.pending_buf,r.pending-l,l)),_e(e),0!==r.pending)return r.last_flush=-1,X;l=0}u=r.gzindex<r.gzhead.name.length?255&r.gzhead.name.charCodeAt(r.gzindex++):0,Te(r,u)}while(0!==u);r.gzhead.hcrc&&r.pending>l&&(e.adler=F(e.adler,r.pending_buf,r.pending-l,l)),r.gzindex=0}r.status=91}if(91===r.status){if(r.gzhead.comment){var d,p=r.pending;do{if(r.pending===r.pending_buf_size){if(r.gzhead.hcrc&&r.pending>p&&(e.adler=F(e.adler,r.pending_buf,r.pending-p,p)),_e(e),0!==r.pending)return r.last_flush=-1,X;p=0}d=r.gzindex<r.gzhead.comment.length?255&r.gzhead.comment.charCodeAt(r.gzindex++):0,Te(r,d)}while(0!==d);r.gzhead.hcrc&&r.pending>p&&(e.adler=F(e.adler,r.pending_buf,r.pending-p,p))}r.status=103}if(103===r.status){if(r.gzhead.hcrc){if(r.pending+2>r.pending_buf_size&&(_e(e),0!==r.pending))return r.last_flush=-1,X;Te(r,255&e.adler),Te(r,e.adler>>8&255),e.adler=0}if(r.status=he,_e(e),0!==r.pending)return r.last_flush=-1,X}if(0!==e.avail_in||0!==r.lookahead||t!==Y&&r.status!==ge){var f=0===r.level?we(r,t):r.strategy===ae?function(e,t){for(var r;;){if(0===e.lookahead&&(Pe(e),0===e.lookahead)){if(t===Y)return 1;break}if(e.match_length=0,r=K(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,r&&(Ee(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===Q?(Ee(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(Ee(e,!1),0===e.strm.avail_out)?1:2}(r,t):r.strategy===se?function(e,t){for(var r,n,i,o,a=e.window;;){if(e.lookahead<=de){if(Pe(e),e.lookahead<=de&&t===Y)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=3&&e.strstart>0&&(n=a[i=e.strstart-1])===a[++i]&&n===a[++i]&&n===a[++i]){o=e.strstart+de;do{}while(n===a[++i]&&n===a[++i]&&n===a[++i]&&n===a[++i]&&n===a[++i]&&n===a[++i]&&n===a[++i]&&n===a[++i]&&i<o);e.match_length=de-(o-i),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=3?(r=K(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(r=K(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),r&&(Ee(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===Q?(Ee(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(Ee(e,!1),0===e.strm.avail_out)?1:2}(r,t):Me[r.level].func(r,t);if(3!==f&&4!==f||(r.status=ge),1===f||3===f)return 0===e.avail_out&&(r.last_flush=-1),X;if(2===f&&(t===J?W(r):t!==Z&&(H(r,0,0,!1),t===z&&(ye(r.head),0===r.lookahead&&(r.strstart=0,r.block_start=0,r.insert=0))),_e(e),0===e.avail_out))return r.last_flush=-1,X}return t!==Q?X:r.wrap<=0?ee:(2===r.wrap?(Te(r,255&e.adler),Te(r,e.adler>>8&255),Te(r,e.adler>>16&255),Te(r,e.adler>>24&255),Te(r,255&e.total_in),Te(r,e.total_in>>8&255),Te(r,e.total_in>>16&255),Te(r,e.total_in>>24&255)):(Re(r,e.adler>>>16),Re(r,65535&e.adler)),_e(e),r.wrap>0&&(r.wrap=-r.wrap),0!==r.pending?X:ee)},Ve=function(e){if(De(e))return te;var t=e.state.status;return e.state=null,t===he?me(e,re):X},Ge=function(e,t){var r=t.length;if(De(e))return te;var n=e.state,i=n.wrap;if(2===i||1===i&&n.status!==fe||n.lookahead)return te;if(1===i&&(e.adler=$(e.adler,t,r,0)),n.wrap=0,r>=n.w_size){0===i&&(ye(n.head),n.strstart=0,n.block_start=0,n.insert=0);var o=new Uint8Array(n.w_size);o.set(t.subarray(r-n.w_size,r),0),t=o,r=n.w_size}var a=e.avail_in,s=e.next_in,c=e.input;for(e.avail_in=r,e.next_in=0,e.input=t,Pe(n);n.lookahead>=3;){var u=n.strstart,l=n.lookahead-2;do{n.ins_h=Se(n,n.ins_h,n.window[u+3-1]),n.prev[u&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=u,u++}while(--l);n.strstart=u,n.lookahead=2,Pe(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,e.next_in=s,e.input=c,e.avail_in=a,n.wrap=i,X};function Be(e){return Be="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Be(e)}var He=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)};try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){}for(var qe=new Uint8Array(256),Ke=0;Ke<256;Ke++)qe[Ke]=Ke>=252?6:Ke>=248?5:Ke>=240?4:Ke>=224?3:Ke>=192?2:1;qe[254]=qe[254]=1;var We=function(e){if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(e);var t,r,n,i,o,a=e.length,s=0;for(i=0;i<a;i++)55296==(64512&(r=e.charCodeAt(i)))&&i+1<a&&56320==(64512&(n=e.charCodeAt(i+1)))&&(r=65536+(r-55296<<10)+(n-56320),i++),s+=r<128?1:r<2048?2:r<65536?3:4;for(t=new Uint8Array(s),o=0,i=0;o<s;i++)55296==(64512&(r=e.charCodeAt(i)))&&i+1<a&&56320==(64512&(n=e.charCodeAt(i+1)))&&(r=65536+(r-55296<<10)+(n-56320),i++),r<128?t[o++]=r:r<2048?(t[o++]=192|r>>>6,t[o++]=128|63&r):r<65536?(t[o++]=224|r>>>12,t[o++]=128|r>>>6&63,t[o++]=128|63&r):(t[o++]=240|r>>>18,t[o++]=128|r>>>12&63,t[o++]=128|r>>>6&63,t[o++]=128|63&r);return t},Ye=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},Je=Object.prototype.toString,ze=G.Z_NO_FLUSH,Qe=G.Z_SYNC_FLUSH,Ze=G.Z_FULL_FLUSH,Xe=G.Z_FINISH,et=G.Z_OK,tt=G.Z_STREAM_END,rt=G.Z_DEFAULT_COMPRESSION,nt=G.Z_DEFAULT_STRATEGY,it=G.Z_DEFLATED;function ot(e){this.options=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var r=t.shift();if(r){if("object"!==Be(r))throw new TypeError(r+"must be non-object");for(var n in r)He(r,n)&&(e[n]=r[n])}}return e}({level:rt,method:it,chunkSize:16384,windowBits:15,memLevel:8,strategy:nt},e||{});var t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Ye,this.strm.avail_out=0;var r=$e(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(r!==et)throw new Error(V[r]);if(t.header&&Ue(this.strm,t.header),t.dictionary){var n;if(n="string"==typeof t.dictionary?We(t.dictionary):"[object ArrayBuffer]"===Je.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,(r=Ge(this.strm,n))!==et)throw new Error(V[r]);this._dict_set=!0}}function at(e,t){var r=new ot(t);if(r.push(e,!0),r.err)throw r.msg||V[r.err];return r.result}ot.prototype.push=function(e,t){var r,n,i=this.strm,o=this.options.chunkSize;if(this.ended)return!1;for(n=t===~~t?t:!0===t?Xe:ze,"string"==typeof e?i.input=We(e):"[object ArrayBuffer]"===Je.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;;)if(0===i.avail_out&&(i.output=new Uint8Array(o),i.next_out=0,i.avail_out=o),(n===Qe||n===Ze)&&i.avail_out<=6)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else{if((r=Fe(i,n))===tt)return i.next_out>0&&this.onData(i.output.subarray(0,i.next_out)),r=Ve(this.strm),this.onEnd(r),this.ended=!0,r===et;if(0!==i.avail_out){if(n>0&&i.next_out>0)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else if(0===i.avail_in)break}else this.onData(i.output)}return!0},ot.prototype.onData=function(e){this.chunks.push(e)},ot.prototype.onEnd=function(e){e===et&&(this.result=function(e){for(var t=0,r=0,n=e.length;r<n;r++)t+=e[r].length;for(var i=new Uint8Array(t),o=0,a=0,s=e.length;o<s;o++){var c=e[o];i.set(c,a),a+=c.length}return i}(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var st=ot,ct=at,ut=function(e,t){return(t=t||{}).raw=!0,at(e,t)},lt=function(e,t){return(t=t||{}).gzip=!0,at(e,t)},dt=G,pt={Deflate:st,deflate:ct,deflateRaw:ut,gzip:lt,constants:dt};e.Deflate=st,e.constants=dt,e.default=pt,e.deflate=ct,e.deflateRaw=ut,e.gzip=lt,Object.defineProperty(e,"__esModule",{value:!0})}(pakoDeflate.exports);var pakoDeflateExports=pakoDeflate.exports,pako=getDefaultExportFromCjs(pakoDeflateExports),SLS_PROTO={nested:{sls:{nested:{Log:{fields:{Time:{rule:"required",type:"uint32",id:1},Contents:{rule:"repeated",type:"Content",id:2}},nested:{Content:{fields:{Key:{rule:"required",type:"string",id:1},Value:{rule:"required",type:"string",id:2}}}}},LogTag:{fields:{Key:{rule:"required",type:"string",id:1},Value:{rule:"required",type:"string",id:2}}},LogGroup:{fields:{Logs:{rule:"repeated",type:"Log",id:1},Reserved:{type:"string",id:2},Topic:{type:"string",id:3},Source:{type:"string",id:4},LogTags:{rule:"repeated",type:"LogTag",id:6}}},LogGroupList:{fields:{logGroupList:{rule:"repeated",type:"LogGroup",id:1}}}}}}},md5$1={exports:{}},core={exports:{}},_nodeResolve_empty={},_nodeResolve_empty$1=Object.freeze({__proto__:null,default:_nodeResolve_empty}),require$$0=getAugmentedNamespace(_nodeResolve_empty$1),hasRequiredCore,CryptoJS;function requireCore(){return hasRequiredCore||(hasRequiredCore=1,core.exports=(e=e||function(e){var t;if("undefined"!=typeof window&&window.crypto&&(t=window.crypto),"undefined"!=typeof self&&self.crypto&&(t=self.crypto),"undefined"!=typeof globalThis&&globalThis.crypto&&(t=globalThis.crypto),!t&&"undefined"!=typeof window&&window.msCrypto&&(t=window.msCrypto),!t&&void 0!==commonjsGlobal&&commonjsGlobal.crypto&&(t=commonjsGlobal.crypto),!t&&"function"==typeof commonjsRequire)try{t=require$$0}catch(e){}var r=function(){if(t){if("function"==typeof t.getRandomValues)try{return t.getRandomValues(new Uint32Array(1))[0]}catch(e){}if("function"==typeof t.randomBytes)try{return t.randomBytes(4).readInt32LE()}catch(e){}}throw new Error("Native crypto module could not be used to get secure random number.")},n=Object.create||function(){function e(){}return function(t){var r;return e.prototype=t,r=new e,e.prototype=null,r}}(),i={},o=i.lib={},a=o.Base={extend:function(e){var t=n(this);return e&&t.mixIn(e),t.hasOwnProperty("init")&&this.init!==t.init||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},s=o.WordArray=a.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||u).stringify(this)},concat:function(e){var t=this.words,r=e.words,n=this.sigBytes,i=e.sigBytes;if(this.clamp(),n%4)for(var o=0;o<i;o++){var a=r[o>>>2]>>>24-o%4*8&255;t[n+o>>>2]|=a<<24-(n+o)%4*8}else for(var s=0;s<i;s+=4)t[n+s>>>2]=r[s>>>2];return this.sigBytes+=i,this},clamp:function(){var t=this.words,r=this.sigBytes;t[r>>>2]&=4294967295<<32-r%4*8,t.length=e.ceil(r/4)},clone:function(){var e=a.clone.call(this);return e.words=this.words.slice(0),e},random:function(e){for(var t=[],n=0;n<e;n+=4)t.push(r());return new s.init(t,e)}}),c=i.enc={},u=c.Hex={stringify:function(e){for(var t=e.words,r=e.sigBytes,n=[],i=0;i<r;i++){var o=t[i>>>2]>>>24-i%4*8&255;n.push((o>>>4).toString(16)),n.push((15&o).toString(16))}return n.join("")},parse:function(e){for(var t=e.length,r=[],n=0;n<t;n+=2)r[n>>>3]|=parseInt(e.substr(n,2),16)<<24-n%8*4;return new s.init(r,t/2)}},l=c.Latin1={stringify:function(e){for(var t=e.words,r=e.sigBytes,n=[],i=0;i<r;i++){var o=t[i>>>2]>>>24-i%4*8&255;n.push(String.fromCharCode(o))}return n.join("")},parse:function(e){for(var t=e.length,r=[],n=0;n<t;n++)r[n>>>2]|=(255&e.charCodeAt(n))<<24-n%4*8;return new s.init(r,t)}},d=c.Utf8={stringify:function(e){try{return decodeURIComponent(escape(l.stringify(e)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(e){return l.parse(unescape(encodeURIComponent(e)))}},p=o.BufferedBlockAlgorithm=a.extend({reset:function(){this._data=new s.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=d.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var r,n=this._data,i=n.words,o=n.sigBytes,a=this.blockSize,c=o/(4*a),u=(c=t?e.ceil(c):e.max((0|c)-this._minBufferSize,0))*a,l=e.min(4*u,o);if(u){for(var d=0;d<u;d+=a)this._doProcessBlock(i,d);r=i.splice(0,u),n.sigBytes-=l}return new s.init(r,l)},clone:function(){var e=a.clone.call(this);return e._data=this._data.clone(),e},_minBufferSize:0});o.Hasher=p.extend({cfg:a.extend(),init:function(e){this.cfg=this.cfg.extend(e),this.reset()},reset:function(){p.reset.call(this),this._doReset()},update:function(e){return this._append(e),this._process(),this},finalize:function(e){return e&&this._append(e),this._doFinalize()},blockSize:16,_createHelper:function(e){return function(t,r){return new e.init(r).finalize(t)}},_createHmacHelper:function(e){return function(t,r){return new f.HMAC.init(e,r).finalize(t)}}});var f=i.algo={};return i}(Math),e)),core.exports;var e}md5$1.exports=(CryptoJS=requireCore(),function(e){var t=CryptoJS,r=t.lib,n=r.WordArray,i=r.Hasher,o=t.algo,a=[];!function(){for(var t=0;t<64;t++)a[t]=4294967296*e.abs(e.sin(t+1))|0}();var s=o.MD5=i.extend({_doReset:function(){this._hash=new n.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(e,t){for(var r=0;r<16;r++){var n=t+r,i=e[n];e[n]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8)}var o=this._hash.words,s=e[t+0],p=e[t+1],f=e[t+2],h=e[t+3],g=e[t+4],m=e[t+5],v=e[t+6],y=e[t+7],b=e[t+8],S=e[t+9],_=e[t+10],E=e[t+11],T=e[t+12],R=e[t+13],C=e[t+14],k=e[t+15],P=o[0],w=o[1],O=o[2],I=o[3];P=c(P,w,O,I,s,7,a[0]),I=c(I,P,w,O,p,12,a[1]),O=c(O,I,P,w,f,17,a[2]),w=c(w,O,I,P,h,22,a[3]),P=c(P,w,O,I,g,7,a[4]),I=c(I,P,w,O,m,12,a[5]),O=c(O,I,P,w,v,17,a[6]),w=c(w,O,I,P,y,22,a[7]),P=c(P,w,O,I,b,7,a[8]),I=c(I,P,w,O,S,12,a[9]),O=c(O,I,P,w,_,17,a[10]),w=c(w,O,I,P,E,22,a[11]),P=c(P,w,O,I,T,7,a[12]),I=c(I,P,w,O,R,12,a[13]),O=c(O,I,P,w,C,17,a[14]),P=u(P,w=c(w,O,I,P,k,22,a[15]),O,I,p,5,a[16]),I=u(I,P,w,O,v,9,a[17]),O=u(O,I,P,w,E,14,a[18]),w=u(w,O,I,P,s,20,a[19]),P=u(P,w,O,I,m,5,a[20]),I=u(I,P,w,O,_,9,a[21]),O=u(O,I,P,w,k,14,a[22]),w=u(w,O,I,P,g,20,a[23]),P=u(P,w,O,I,S,5,a[24]),I=u(I,P,w,O,C,9,a[25]),O=u(O,I,P,w,h,14,a[26]),w=u(w,O,I,P,b,20,a[27]),P=u(P,w,O,I,R,5,a[28]),I=u(I,P,w,O,f,9,a[29]),O=u(O,I,P,w,y,14,a[30]),P=l(P,w=u(w,O,I,P,T,20,a[31]),O,I,m,4,a[32]),I=l(I,P,w,O,b,11,a[33]),O=l(O,I,P,w,E,16,a[34]),w=l(w,O,I,P,C,23,a[35]),P=l(P,w,O,I,p,4,a[36]),I=l(I,P,w,O,g,11,a[37]),O=l(O,I,P,w,y,16,a[38]),w=l(w,O,I,P,_,23,a[39]),P=l(P,w,O,I,R,4,a[40]),I=l(I,P,w,O,s,11,a[41]),O=l(O,I,P,w,h,16,a[42]),w=l(w,O,I,P,v,23,a[43]),P=l(P,w,O,I,S,4,a[44]),I=l(I,P,w,O,T,11,a[45]),O=l(O,I,P,w,k,16,a[46]),P=d(P,w=l(w,O,I,P,f,23,a[47]),O,I,s,6,a[48]),I=d(I,P,w,O,y,10,a[49]),O=d(O,I,P,w,C,15,a[50]),w=d(w,O,I,P,m,21,a[51]),P=d(P,w,O,I,T,6,a[52]),I=d(I,P,w,O,h,10,a[53]),O=d(O,I,P,w,_,15,a[54]),w=d(w,O,I,P,p,21,a[55]),P=d(P,w,O,I,b,6,a[56]),I=d(I,P,w,O,k,10,a[57]),O=d(O,I,P,w,v,15,a[58]),w=d(w,O,I,P,R,21,a[59]),P=d(P,w,O,I,g,6,a[60]),I=d(I,P,w,O,E,10,a[61]),O=d(O,I,P,w,f,15,a[62]),w=d(w,O,I,P,S,21,a[63]),o[0]=o[0]+P|0,o[1]=o[1]+w|0,o[2]=o[2]+O|0,o[3]=o[3]+I|0},_doFinalize:function(){var t=this._data,r=t.words,n=8*this._nDataBytes,i=8*t.sigBytes;r[i>>>5]|=128<<24-i%32;var o=e.floor(n/4294967296),a=n;r[15+(i+64>>>9<<4)]=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8),r[14+(i+64>>>9<<4)]=16711935&(a<<8|a>>>24)|4278255360&(a<<24|a>>>8),t.sigBytes=4*(r.length+1),this._process();for(var s=this._hash,c=s.words,u=0;u<4;u++){var l=c[u];c[u]=16711935&(l<<8|l>>>24)|4278255360&(l<<24|l>>>8)}return s},clone:function(){var e=i.clone.call(this);return e._hash=this._hash.clone(),e}});function c(e,t,r,n,i,o,a){var s=e+(t&r|~t&n)+i+a;return(s<<o|s>>>32-o)+t}function u(e,t,r,n,i,o,a){var s=e+(t&n|r&~n)+i+a;return(s<<o|s>>>32-o)+t}function l(e,t,r,n,i,o,a){var s=e+(t^r^n)+i+a;return(s<<o|s>>>32-o)+t}function d(e,t,r,n,i,o,a){var s=e+(r^(t|~n))+i+a;return(s<<o|s>>>32-o)+t}t.MD5=i._createHelper(s),t.HmacMD5=i._createHmacHelper(s)}(Math),CryptoJS.MD5);var md5Exports=md5$1.exports,md5=getDefaultExportFromCjs(md5Exports),libTypedarrays={exports:{}};libTypedarrays.exports=function(e){return function(){if("function"==typeof ArrayBuffer){var t=e.lib.WordArray,r=t.init,n=t.init=function(e){if(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),(e instanceof Int8Array||"undefined"!=typeof Uint8ClampedArray&&e instanceof Uint8ClampedArray||e instanceof Int16Array||e instanceof Uint16Array||e instanceof Int32Array||e instanceof Uint32Array||e instanceof Float32Array||e instanceof Float64Array)&&(e=new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),e instanceof Uint8Array){for(var t=e.byteLength,n=[],i=0;i<t;i++)n[i>>>2]|=e[i]<<24-i%4*8;r.call(this,n,t)}else r.apply(this,arguments)};n.prototype=t}}(),e.lib.WordArray}(requireCore());var libTypedarraysExports=libTypedarrays.exports,WordArray=getDefaultExportFromCjs(libTypedarraysExports),builder=getProtobufRoot(SLS_PROTO),LogContentProto=builder.lookupType("sls.Log.Content"),LogGroupProto=builder.lookupType("sls.LogGroup"),encoder=new TextEncoder,getCanonicalizedHeaders=function(e){for(var t=Object.keys(e),r=[],n=0;n<t.length;n++){var i=t[n];(i.startsWith("x-log-")||i.startsWith("x-acs-"))&&r.push(i)}r.sort();for(var o="",a=0;a<r.length;a++){var s=r[a];o+="".concat(s,":").concat(String(e[s]).trim(),"\n")}return o},getCanonicalizedResource=function(e,t){for(var r="".concat(e),n=Object.keys(t),i=new Array(n.length),o=0;o<n.length;o++){var a=n[o];i[o]="".concat(a,"=").concat(t[a]||"")}i.sort();var s=i.join("&");return s&&(r+="?".concat(s)),r},sign=function(){var e=_asyncToGenerator(_regeneratorRuntime.mark(function e(t,r,n,i){var o,a,s,c,u,l,d,p,f,h,g;return _regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return o=n["Content-MD5"]||"",a=n["Content-Type"]||"",s=n.Date,c=getCanonicalizedHeaders(n),u=getCanonicalizedResource(t,r),l=encoder.encode(["POST",o,a,s,"".concat(c).concat(u)].join("\n")),e.next=1,window.crypto.subtle.importKey("raw",encoder.encode(i.credentials.accessKeySecret),{name:"HMAC",hash:"SHA-1"},!1,["sign"]);case 1:return d=e.sent,h=Uint8Array,e.next=2,window.crypto.subtle.sign("HMAC",d,l);case 2:return g=e.sent,p=new h(g),f=window.btoa(String.fromCharCode.apply(String,_toConsumableArray$1(p))),e.abrupt("return","LOG ".concat(i.credentials.accessKeyId,":").concat(f));case 3:case"end":return e.stop()}},e)}));return function(t,r,n,i){return e.apply(this,arguments)}}(),postLog=function(){var e=_asyncToGenerator(_regeneratorRuntime.mark(function e(t,r,n,i){var o,a,s,c,u,l,d,p,f,h,g;return _regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return o=t.logstore,a=t.project,s=t.endpoint,c=t.credentials,u="/logstores/".concat(o,"/shards/lb"),l=a?a+".":"",d=(r?"?".concat(new URLSearchParams(r)):"").replace(/\?$/,""),p=window.location.href.indexOf("file://")>-1?"http://":"//",f="".concat(p).concat(l).concat(s.replace(/https?:\/\//,"")).concat(u).concat(d),h=new Date(getTime()).toUTCString(),g={"Content-Type":"application/x-protobuf","x-log-compresstype":"deflate","x-log-bodyrawsize":i,Date:h,Host:"".concat(l).concat(s),"x-log-apiversion":"0.6.0","x-log-signaturemethod":"hmac-sha1",Authorization:"","x-acs-security-token":c.securityToken},n&&(g["Content-MD5"]=md5(WordArray.create(n)).toString().toUpperCase(),g["Content-Length"]=n.length),e.next=1,sign(u,r,g,t);case 1:return g.Authorization=e.sent,g["x-log-date"]=h,e.abrupt("return",{url:f,param:{method:"POST",body:n,headers:g}});case 2:case"end":return e.stop()}},e)}));return function(t,r,n,i){return e.apply(this,arguments)}}(),getUploadParam=function(){var e=_asyncToGenerator(_regeneratorRuntime.mark(function e(t,r){var n,i,o,a,s,c,u;return _regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(i=parseInt(String(getTime()).substr(0,10)),o={Logs:[],Topic:"Event Track"},t.forEach(function(e){o.Logs.push({Time:i,Contents:Object.keys(e).map(function(t){var r={Key:t,Value:String(e[t])},n=LogContentProto.verify(r);if(n)throw n;return r})})}),!(n=LogGroupProto.verify(o))){e.next=1;break}throw new Error(n);case 1:return a=LogGroupProto.create(o),s=LogGroupProto.encode(a).finish(),c=pako.deflate(s),u=s.byteLength,e.next=2,postLog(r,{},c,u);case 2:return e.abrupt("return",e.sent);case 3:case"end":return e.stop()}},e)}));return function(t,r){return e.apply(this,arguments)}}(),_excute=function(e,t,r){return new Promise(function(n,i){fetch(e,t).then(n).catch(function(n){++r<=3?setTimeout(function(){_excute(e,t,r)},500*(r+1)):i(n)})})},post=function(){var e=_asyncToGenerator(_regeneratorRuntime.mark(function e(t,r){var n,i,o;return _regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(t.length){e.next=1;break}return e.abrupt("return");case 1:return e.next=2,getUploadParam(t,r);case 2:return n=e.sent,i=n.url,o=n.param,e.abrupt("return",_excute(i,o,0));case 3:case"end":return e.stop()}},e)}));return function(t,r){return e.apply(this,arguments)}}(),UPLOADTIMER=5e3,UPLOADITEMMAX=10,SlsClient=_createClass(function e(t,r){var n=this;_classCallCheck(this,e),Object.defineProperty(this,"logService",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"statsCache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tokenManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"eventTriggedTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cycleStatsTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cycleStatsInterval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"eventTriggedInterval",{enumerable:!0,configurable:!0,writable:!0,value:void 0});var i=t.securityToken,o=t.logService,a=t.cycleStatsConfig;this.logService=o,this.cache=[],this.statsCache=[],this.cycleStatsInterval=a.uploadIntervalMs||UPLOAD_LOG_INTERVAL,this.eventTriggedInterval=UPLOADTIMER,this.tokenManager=new STSTokenManager(i,r,this.logService.credentials),this.tokenManager.on("update",function(e){n.logService=e}),this.upload(!1,"eventTrigged"),this.cycleStatsTimer=addTimer(function(){n.upload(!0,"cycleStats")},this.cycleStatsInterval,"interval"),this.eventTriggedTimer=addTimer(function(){n.upload(!1,"eventTrigged")},this.eventTriggedInterval,"interval")},[{key:"securityToken",get:function(){var e;return null===(e=this.tokenManager)||void 0===e||null===(e=e.securityToken)||void 0===e?void 0:e.securityToken}},{key:"stopUpdateToken",value:function(){this.tokenManager.stopUpdateToken()}},{key:"send",value:function(e){var t=e.cycleStats;delete e.serverDiffTime,t?(delete e.cycleStats,this.sendStats(e)):this.cache.push(e)}},{key:"sendStats",value:function(e){this.statsCache.push(e)}},{key:"flush",value:function(){this.upload(!0,"eventTrigged"),this.upload(!0,"cycleStats")}},{key:"upload",value:function(){var e;return e="eventTrigged"===(arguments.length>1&&void 0!==arguments[1]?arguments[1]:"eventTrigged")?arguments.length>0&&void 0!==arguments[0]&&arguments[0]?this.cache.splice(0):this.cache.splice(0,UPLOADITEMMAX):this.statsCache.splice(0),post(e,this.logService)}},{key:"clear",value:function(){this.eventTriggedTimer&&(removeTimer(this.eventTriggedTimer,"interval"),this.eventTriggedTimer=null),this.cycleStatsTimer&&(removeTimer(this.cycleStatsTimer,"interval"),this.cycleStatsTimer=null)}}]),Logging=_createClass(function e(){_classCallCheck(this,e),Object.defineProperty(this,"commonInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"buffer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"slsClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.buffer=[],this.slsClient=null,this.commonInfo={udid:Environment.deviceId,tabId:Environment.browserTabId}},[{key:"updateCommonInfo",value:function(e){this.commonInfo=Object.assign({},this.commonInfo,e)}},{key:"start",value:function(e){this.slsClient=new SlsClient(e,this.commonInfo),this.flushLogBuffer()}},{key:"stop",value:function(){var e,t;this.flushLogBuffer(),null===(e=this.slsClient)||void 0===e||e.stopUpdateToken(),null===(t=this.slsClient)||void 0===t||t.clear()}},{key:"send",value:function(e){var t=new Date(getTime());e.date=t.getTime(),e.timeStr="".concat(t.toLocaleString(),":").concat(t.getMilliseconds()),e.acs=Environment.networkType||"unknown",this.commonInfo.apid?(this.realSend(e),this.buffer.length&&this.flushLogBuffer()):this.buffer.push(e)}},{key:"flushLogBuffer",value:function(){var e=this;this.buffer.length&&this.slsClient&&this.buffer.splice(0).forEach(function(t){e.realSend(t)}),this.slsClient&&this.slsClient.flush()}},{key:"realSend",value:function(e){var t=Object.assign({},this.commonInfo,e);this.slsClient&&this.slsClient.send(t)}}]);function ownKeys$1$1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function _objectSpread$1$1(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$1$1(Object(r),!0).forEach(function(t){_defineProperty$1(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$1$1(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}var WebTrackingClient=_createClass(function e(t){_classCallCheck(this,e),Object.defineProperty(this,"commonInfo",{enumerable:!0,configurable:!0,writable:!0,value:{}}),this.commonInfo=Object.assign({},this.commonInfo,t)},[{key:"updateCommonInfo",value:function(e){this.commonInfo=Object.assign({},this.commonInfo,e)}},{key:"gslbAccess",value:function(e,t){this.send({event:"gslbAccess",success:e,message:t})}},{key:"send",value:function(e){var t=new Date(getTime());e.date=t.getTime(),e.timeStr="".concat(t.toLocaleString(),":").concat(t.getMilliseconds());var r=_objectSpread$1$1(_objectSpread$1$1({},this.commonInfo),{},{tm:e.date},e);(new Image).src="".concat(BaseWebTrackingURL,"&").concat(new URLSearchParams(r))}}]);function ownKeys$b(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function _objectSpread$b(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$b(Object(r),!0).forEach(function(t){_defineProperty$1(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$b(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}var SLSSender=_createClass(function e(){_classCallCheck(this,e),Object.defineProperty(this,"logging",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"statsConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"started",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.logging=new Logging},[{key:"start",value:function(e){var t=e.cycleStatsConfig;this.logging.start(e),this.statsConfig=t,this.started=!0}},{key:"stop",value:function(){this.logging.stop(),this.started=!1}},{key:"securityToken",get:function(){var e;return null===(e=this.logging)||void 0===e||null===(e=e.slsClient)||void 0===e?void 0:e.securityToken}},{key:"updateSecurityToken",value:function(e){var t;return null===(t=this.logging)||void 0===t?void 0:t.slsClient.tokenManager.updateSecurityToken(e)}},{key:"sendMetric",value:function(e){return this.logging.send(_objectSpread$b(_objectSpread$b({},e),{},{cycleStats:!0}))}},{key:"sendEvent",value:function(e){return this.logging.send(_objectSpread$b({},e))}},{key:"exception",value:function(e){this.logging.send(_objectSpread$b(_objectSpread$b({},TraceEvent$1.EXCEPTION),{},{code:e.code,message:e.message,name:e.name}))}}]),MAX_LOG_COUNT=5e3,ONE_FLUSH_LIMIT=500,ONE_FLUSH_CHAR_COUNT_LIMIT=5e5,LOG_LEVEL_NUM={debug:1,info:10,warn:20,error:30,none:99},Logger=function(){function e(){var t,r=this,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";_classCallCheck(this,e),Object.defineProperty(this,"logBuffer",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"metricBuffer",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"envInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"isFlushing",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"logSendFunction",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"afterPrinter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"loggerPrefix",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"flushLog",{enumerable:!0,configurable:!0,writable:!0,value:(t=_asyncToGenerator(_regeneratorRuntime.mark(function e(){var t,n,i,o,a;return _regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(!r.logBuffer.length||r.isFlushing){e.next=2;break}if(r.isFlushing=!0,t=r.logBuffer.length,r.logBuffer.length>ONE_FLUSH_LIMIT&&(t=ONE_FLUSH_LIMIT),r.logSendFunction){e.next=1;break}return r.isFlushing=!1,e.abrupt("return",Promise.reject("no log sender"));case 1:for(n=r.logBuffer.slice(0,t),i=n.map(function(e){return JSON.stringify(e)}),o=i.length?i.reduce(function(e,t){return e+t.length},0):0;o>ONE_FLUSH_CHAR_COUNT_LIMIT&&n.length>=2;)n=n.slice(0,n.length/2),i=n.map(function(e){return JSON.stringify(e)}),o=i.length?i.reduce(function(e,t){return e+t.length},0):0;return o>ONE_FLUSH_CHAR_COUNT_LIMIT&&(console.error("error: truncated logs for flushing log size is too large",n),i=["error: truncated logs for flushing log size is too large"]),a=r.logSendFunction,e.abrupt("return",a(i).then(function(e){e&&e.success&&r.logBuffer.splice(0,t)}).catch(function(e){console.warn("caught flushLogs error",e)}).finally(function(){r.isFlushing=!1}));case 2:return e.abrupt("return",Promise.resolve());case 3:case"end":return e.stop()}},e)})),function(){return t.apply(this,arguments)})}),this.loggerPrefix=n}return _createClass(e,[{key:"getLogger",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",n=function(){var e=_asyncToGenerator(_regeneratorRuntime.mark(function e(){return _regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return");case 1:case"end":return e.stop()}},e)}));return function(){return e.apply(this,arguments)}}(),i={debug:n,info:n,warn:n,error:n};return["debug","info","warn","error"].forEach(function(n){return i[n]=t.log(n,"".concat(e,":"),r)}),i}},{key:"pushToMetricBuffer",value:function(e){this.metricBuffer.length>=MAX_LOG_COUNT?console.error("drop metric for log buffer is full: ",e):this.metricBuffer.push(e)}},{key:"pushToLogBuffer",value:function(e){this.logBuffer.length>=MAX_LOG_COUNT?console.error("drop log for log buffer is full: ",e):this.logBuffer.push(e)}},{key:"log",value:function(t){for(var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.loggerPrefix,i=arguments.length,o=new Array(i>2?i-2:0),a=2;a<i;a++)o[a-2]=arguments[a];var s=[formatToBeijingTime(new Date(getTime())),t.toLocaleUpperCase(),n].concat(o),c=this.stringifyArgs(s);"none"!==t&&LOG_LEVEL_NUM[t]>=e.levelThreshold&&Function.apply.call(console[t],console,[c]),null===(r=this.afterPrinter)||void 0===r||r.call(this,c),this.logSendFunction&&this.pushToLogBuffer(c)}},{key:"stringifyArgs",value:function(e){var t=_toConsumableArray$1(e).map(function(e){var t=e;return"string"!=typeof e&&(t=tryJsonStringify(e)),t}).join(" ");return"".concat(t)}},{key:"debug",value:function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return this.log.apply(this,["debug",void 0,""].concat(t))}},{key:"info",value:function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return this.log.apply(this,["info",void 0,""].concat(t))}},{key:"warn",value:function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return this.log.apply(this,["warn",void 0,""].concat(t))}},{key:"error",value:function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return this.log.apply(this,["error",void 0,""].concat(t))}},{key:"injectLogSender",value:function(e){this.logSendFunction=e}},{key:"injectLogPrint",value:function(e){this.afterPrinter=e}}],[{key:"setLogLevel",value:function(t){e.levelThreshold=LOG_LEVEL_NUM[t]}}])}();Object.defineProperty(Logger,"levelThreshold",{enumerable:!0,configurable:!0,writable:!0,value:LOG_LEVEL_NUM.warn});var getAndIncLogSeq=function(){return Reporter._dingrtc_log_seq++},Reporter=_createClass(function e(){var t=this,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";_classCallCheck(this,e),Object.defineProperty(this,"trace",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metric",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"log",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sender",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webtracking",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"commonInfo",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"getLoggerWithPrefix",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var r={debug:function(){for(var r,n=arguments.length,i=new Array(n),o=0;o<n;o++)i[o]=arguments[o];return(r=t.log).debug.apply(r,[e].concat(i))},info:function(){for(var r,n=arguments.length,i=new Array(n),o=0;o<n;o++)i[o]=arguments[o];return(r=t.log).info.apply(r,[e].concat(i))},warn:function(){for(var r,n=arguments.length,i=new Array(n),o=0;o<n;o++)i[o]=arguments[o];return(r=t.log).warn.apply(r,[e].concat(i))},error:function(){for(var r,n=arguments.length,i=new Array(n),o=0;o<n;o++)i[o]=arguments[o];return(r=t.log).error.apply(r,[e].concat(i))}};return r}}),this.commonInfo={bt:Environment.browserType,bv:Environment.browserVersion,osn:Environment.system,osv:Environment.systemVersion,udid:Environment.deviceId,tabId:Environment.browserTabId},this.sender=new SLSSender,this.webtracking=new WebTrackingClient(this.commonInfo),this.trace=new Trace(this.webtracking,this.sender),this.metric=new Metric(this.sender),this.log=new Logger,this.setId(r),this.log.injectLogPrint(function(e){t.trace.simpleLogger(e)})},[{key:"setId",value:function(e){this.id=e,this.log.loggerPrefix="clientId ".concat(this.id)}},{key:"securityToken",get:function(){return this.sender.securityToken}},{key:"statsConfig",get:function(){return this.sender.statsConfig}},{key:"updateCommonInfo",value:function(e){this.commonInfo=Object.assign({},this.commonInfo,e),this.webtracking.updateCommonInfo(this.commonInfo),this.sender.logging.updateCommonInfo(this.commonInfo),e.serverDiffTime&&setDiffTime(e.serverDiffTime)}},{key:"updateSecurityToken",value:function(e){this.sender.updateSecurityToken(e)}},{key:"start",value:function(e){this.sender.start(e)}},{key:"stop",value:function(){this.sender.stop()}}]);Object.defineProperty(Reporter,"_dingrtc_log_seq",{enumerable:!0,configurable:!0,writable:!0,value:0});var clientIdToReportMap=new Map,defaultReport,registerReporter=function(e){var t;return defaultReport?defaultReport&&!defaultReport.id?(defaultReport.setId(e),t=defaultReport):t=new Reporter(e):t=defaultReport=new Reporter(e),clientIdToReportMap.set(e,t),t},getReporter=function(e){return defaultReport||(defaultReport=new Reporter),defaultReport},setLogLevel=function(e){Logger.setLogLevel(e)},_ErrorCodeAndMsgMap,DeviceErrorDescription={MESSAGE_DEVICENOTFOUND:"Requested device not found",MESSAGE_DEVICENOTALLOWED:"Permission denied",MESSAGE_MACCHROMEDEVICENOTREADABLE:"Permission denied by system",MESSAGE_MACSAFARIDEVICENOTALLOWED:"The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.",MESSAGE_MOBILEDEVICE_NOTALLOWED:"video device not allowed",MESSAGE_AUDIODEVICENOTREADABLE:"Could not start audio source",MESSAGE_VIDEODEVICENOTREADABLE:"Could not start video source",NAME_ABORTEERROR:"AbortError",NAME_INVALIDSTATEERROR:"InvalidStateError",NAME_DEVICENOTALLOWED:"NotAllowedError",NAME_DEVICENOTFOUND:"NotFoundError",NAME_DEVICENOTREADABLE:"NotReadableError",NAME_DEVICEOVERCONSTRAINED:"OverconstrainedError",NAME_INVALID_ACCESS:"InvalidAccessError",NAME_TYPEERROR:"TypeError"},GSLBErrorCode,ErrorCode;!function(e){e.CLIENT_ERROR_INVALID_AUTHORIZATION="invalid authorization",e.CLIENT_ERROR_NOT_FOUND_APP="app not found",e.CLIENT_ERROR_INVALID_APP_STATUS="invalid app status",e.CLIENT_ERROR_MISSING_CHANNEL_NAME="channel missing",e.CLIENT_ERROR_INVALID_TOKEN_TIMESTAMP="invalid token timestamp",e.CLIENT_ERROR_INVALID_APP_ID="invalid appId",e.CLIENT_ERROR_MISSING_REQUEST="request missing",e.CLIENT_ERROR_MISSING_DEVICE_ID="deviceId missing",e.CLIENT_ERROR_MISSING_UA="ua missing",e.CLIENT_ERROR_MISSING_CLIENT_IP="clientIp missing",e.CLIENT_ERROR_INVALID_USER_ID="invalid userId",e.CLIENT_ERROR_MISSING_SERVIC="service missing",e.CLIENT_ERROR_MISSING_TASK_ID="taskId missing",e.CLIENT_ERROR_MISSING_APP_ID="appId missing",e.CLIENT_ERROR_MISSING_USER_ID="userId missing",e.CLIENT_ERROR_MISSING_USER="user missing",e.CLIENT_ERROR_MISSING_CHANNEL_ID="channel missing",e.CLIENT_ERROR_MISSING_PARTICIPANT_ID="participantId missing",e.CLIENT_ERROR_INVALID_REQUEST="invalid request",e.CLIENT_ERROR_NOT_FOUND_GSLB_CHANNEL="gslb channel not found",e.SERVER_ERROR_GSLB_NOT_FOUND_CHANNEL_ID_ERROR="gslb not found channelId error",e.SERVER_ERROR_INTERNAL_ERROR="internal error",e.SERVER_ERROR_MEDIA_ENGINE_ACCESS_ERROR="media-engine access error",e.SERVER_ERROR_MEDIA_ENGINE_SCHEDULE_AND_CREATE_ERROR="media-engine scheduleAndCreate error",e.SERVER_ERROR_SECURITY_TOKEN_NOT_FOUND_ERROR="security token not found error",e.SERVER_ERROR_GSLB_ACCESS_ERROR="gslb access error",e.SERVER_ERROR_GSLB_DISPATCH_ERROR="gslb dispatch error",e.SERVER_ERROR_GSLB_MAPI_ERROR="gslb mapi error"}(GSLBErrorCode||(GSLBErrorCode={})),function(e){e[e.NetworkError=40001]="NetworkError",e[e.JoinTimeout=16908804]="JoinTimeout",e[e.JoinChannelFailed=16974338]="JoinChannelFailed",e[e.CLIENT_ERROR_INVALID_AUTHORIZATION=33620485]="CLIENT_ERROR_INVALID_AUTHORIZATION",e[e.CLIENT_ERROR_NOT_FOUND_APP=33620481]="CLIENT_ERROR_NOT_FOUND_APP",e[e.CLIENT_ERROR_INVALID_APP_STATUS=33620486]="CLIENT_ERROR_INVALID_APP_STATUS",e[e.JoinBadParam=16974081]="JoinBadParam",e[e.CLIENT_ERROR_MISSING_CHANNEL_NAME=16974081]="CLIENT_ERROR_MISSING_CHANNEL_NAME",e[e.CLIENT_ERROR_INVALID_TOKEN_TIMESTAMP=33620483]="CLIENT_ERROR_INVALID_TOKEN_TIMESTAMP",e[e.CLIENT_ERROR_INVALID_APP_ID=33620482]="CLIENT_ERROR_INVALID_APP_ID",e[e.CLIENT_ERROR_MISSING_REQUEST=16974081]="CLIENT_ERROR_MISSING_REQUEST",e[e.CLIENT_ERROR_MISSING_CLIENT_IP=16974081]="CLIENT_ERROR_MISSING_CLIENT_IP",e[e.CLIENT_ERROR_INVALID_USER_ID=33622278]="CLIENT_ERROR_INVALID_USER_ID",e[e.CLIENT_ERROR_MISSING_SERVIC=16974081]="CLIENT_ERROR_MISSING_SERVIC",e[e.CLIENT_ERROR_MISSING_TASK_ID=16974081]="CLIENT_ERROR_MISSING_TASK_ID",e[e.CLIENT_ERROR_MISSING_APP_ID=16974081]="CLIENT_ERROR_MISSING_APP_ID",e[e.CLIENT_ERROR_MISSING_USER_ID=16974081]="CLIENT_ERROR_MISSING_USER_ID",e[e.CLIENT_ERROR_MISSING_USER=16974081]="CLIENT_ERROR_MISSING_USER",e[e.CLIENT_ERROR_MISSING_CHANNEL_ID=16974081]="CLIENT_ERROR_MISSING_CHANNEL_ID",e[e.CLIENT_ERROR_MISSING_PARTICIPANT_ID=16974081]="CLIENT_ERROR_MISSING_PARTICIPANT_ID",e[e.CLIENT_ERROR_INVALID_REQUEST=16974082]="CLIENT_ERROR_INVALID_REQUEST",e[e.CLIENT_ERROR_NOT_FOUND_GSLB_CHANNEL=33620484]="CLIENT_ERROR_NOT_FOUND_GSLB_CHANNEL",e[e.ServerResponseInvalid=16974354]="ServerResponseInvalid",e[e.SERVER_ERROR_GSLB_NOT_FOUND_CHANNEL_ID_ERROR=33620496]="SERVER_ERROR_GSLB_NOT_FOUND_CHANNEL_ID_ERROR",e[e.SERVER_ERROR_INTERNAL_ERROR=33620497]="SERVER_ERROR_INTERNAL_ERROR",e[e.SERVER_ERROR_MEDIA_ENGINE_ACCESS_ERROR=33620498]="SERVER_ERROR_MEDIA_ENGINE_ACCESS_ERROR",e[e.SERVER_ERROR_MEDIA_ENGINE_SCHEDULE_AND_CREATE_ERROR=33620499]="SERVER_ERROR_MEDIA_ENGINE_SCHEDULE_AND_CREATE_ERROR",e[e.SERVER_ERROR_SECURITY_TOKEN_NOT_FOUND_ERROR=33620500]="SERVER_ERROR_SECURITY_TOKEN_NOT_FOUND_ERROR",e[e.SERVER_ERROR_GSLB_ACCESS_ERROR=33622281]="SERVER_ERROR_GSLB_ACCESS_ERROR",e[e.SERVER_ERROR_GSLB_DISPATCH_ERROR=33620501]="SERVER_ERROR_GSLB_DISPATCH_ERROR",e[e.SERVER_ERROR_GSLB_MAPI_ERROR=33620502]="SERVER_ERROR_GSLB_MAPI_ERROR",e[e.MicOpenFail=17040388]="MicOpenFail",e[e.SpeakerOpenFail=17040389]="SpeakerOpenFail",e[e.MicInterrupt=17040390]="MicInterrupt",e[e.SpeakerSetNotSupported=17040416]="SpeakerSetNotSupported",e[e.SpeakerInterrupt=17040391]="SpeakerInterrupt",e[e.MicAuthFail=17040392]="MicAuthFail",e[e.MicNotAvailable=17040393]="MicNotAvailable",e[e.SpeakerNotAvailable=17040400]="SpeakerNotAvailable",e[e.SpecifiedAudioDeviceNotFound=17040401]="SpecifiedAudioDeviceNotFound",e[e.AudioMixingUnknownError=17040896]="AudioMixingUnknownError",e[e.LoadAudioFailed=17040897]="LoadAudioFailed",e[e.AudioMixingStateInvalid=17040898]="AudioMixingStateInvalid",e[e.AudioContextNotSupported=17040899]="AudioContextNotSupported",e[e.NotArrayBuffer=17040900]="NotArrayBuffer",e[e.AudioMixingMissingParam=17040901]="AudioMixingMissingParam",e[e.AudioMixingStartFailed=17040902]="AudioMixingStartFailed",e[e.AudioMixingResumeFailed=17040903]="AudioMixingResumeFailed",e[e.AudioPlayTimeError=17040912]="AudioPlayTimeError",e[e.AutoPlayFailed=17040928]="AutoPlayFailed",e[e.CameraOpenFail=17039620]="CameraOpenFail",e[e.CameraInterrupt=17039622]="CameraInterrupt",e[e.SpecifiedCameraDeviceNotFound=17039623]="SpecifiedCameraDeviceNotFound",e[e.CameraNotAvailable=17039673]="CameraNotAvailable",e[e.CameraAuthFail=17039680]="CameraAuthFail",e[e.ScreenShareOpenFail=17039624]="ScreenShareOpenFail",e[e.VideoDisplayOpenFail=17039873]="VideoDisplayOpenFail",e[e.VideoDisplayInterrupt=17039874]="VideoDisplayInterrupt",e[e.DeviceUnknownError=17040537]="DeviceUnknownError",e[e.OverConstrainedError=17040536]="OverConstrainedError",e[e.ScreenShareUnknownError=17040640]="ScreenShareUnknownError",e[e.ScreenShareNotAllowed=17040641]="ScreenShareNotAllowed",e[e.ScreenShareEnded=17040642]="ScreenShareEnded",e[e.ScreenShareNotAuthed=17040643]="ScreenShareNotAuthed",e[e.ScreenShareInvalidAccess=17040644]="ScreenShareInvalidAccess",e[e.ScreenShareAbortError=17040645]="ScreenShareAbortError",e[e.ScreenShareStateError=17040646]="ScreenShareStateError",e[e.ScreenShareTypeError=17040647]="ScreenShareTypeError",e[e.IceConnectionConnectFail=17105409]="IceConnectionConnectFail",e[e.IceConnectionReconnectFail=17105410]="IceConnectionReconnectFail",e[e.IceConnectionAnswerFail=17105426]="IceConnectionAnswerFail",e[e.IceConnectionNoCandidate=17105427]="IceConnectionNoCandidate",e[e.IceConnectionDisconnected=17105428]="IceConnectionDisconnected",e[e.IceConnectionSetLocalDescFail=17105429]="IceConnectionSetLocalDescFail",e[e.ConnectionHeartbeatTimeout=17105411]="ConnectionHeartbeatTimeout",e[e.ConnectionConnectFail=17105665]="ConnectionConnectFail",e[e.APICallTimeOut=17105681]="APICallTimeOut",e[e.PublishNoStream=16974596]="PublishNoStream",e[e.PublishInvaild=16974597]="PublishInvaild",e[e.PublishNotJoinChannel=16843782]="PublishNotJoinChannel",e[e.PublishAudioStreamFailed=16843856]="PublishAudioStreamFailed",e[e.PublishVideoStreamFailed=16843857]="PublishVideoStreamFailed",e[e.PublishScreenShareFailed=16843859]="PublishScreenShareFailed",e[e.PublishScreenShareConfigError=16843860]="PublishScreenShareConfigError",e[e.SubscribeStreamNotExisted=16974851]="SubscribeStreamNotExisted",e[e.SubscribeInvaild=16974852]="SubscribeInvaild",e[e.SubscribeNotJoinChannel=16844112]="SubscribeNotJoinChannel",e[e.SubscribeAudioStreamFailed=16844113]="SubscribeAudioStreamFailed",e[e.SubscribeVideoStreamFailed=16844114]="SubscribeVideoStreamFailed",e[e.SubscribeScreenShareFailed=16844116]="SubscribeScreenShareFailed",e[e.LogAlreadyInit=16974085]="LogAlreadyInit",e[e.LogRootPathError=16974086]="LogRootPathError",e[e.QuotaLimitExceed=16974096]="QuotaLimitExceed",e[e.BrowserNotSupported=16974101]="BrowserNotSupported",e[e.InvaildState=16974340]="InvaildState",e[e.InvaildArgument=16974083]="InvaildArgument",e[e.SessionRemoved=33620229]="SessionRemoved",e[e.AudioBufferFull=17236225]="AudioBufferFull",e[e.VideoBufferFull=17236226]="VideoBufferFull",e[e.AudioStreamError=17301761]="AudioStreamError",e[e.AudioFileOpenFail=17301762]="AudioFileOpenFail",e[e.AudioFormatNotSupported=17301763]="AudioFormatNotSupported",e[e.UpdateRoleChannel=16908801]="UpdateRoleChannel",e[e.Inner=-1]="Inner"}(ErrorCode||(ErrorCode={}));var ErrorCodeAndMsgMap=(_ErrorCodeAndMsgMap={},_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_ErrorCodeAndMsgMap,ErrorCode.NetworkError,"Network error, please check your network connectivity or dns, proxy, firewall etc."),ErrorCode.SERVER_ERROR_GSLB_ACCESS_ERROR,"GSLB access error"),ErrorCode.CLIENT_ERROR_NOT_FOUND_APP,"AppId is not exist"),ErrorCode.CLIENT_ERROR_INVALID_APP_ID,"AppId is invalid"),ErrorCode.CLIENT_ERROR_NOT_FOUND_GSLB_CHANNEL,"channel is not exist"),ErrorCode.CLIENT_ERROR_INVALID_TOKEN_TIMESTAMP,"channel is invalid"),ErrorCode.CLIENT_ERROR_INVALID_AUTHORIZATION,"token is invalid"),ErrorCode.JoinTimeout,"join timeout"),ErrorCode.JoinBadParam,"join with invalid parameter"),ErrorCode.JoinChannelFailed,"join channel failed"),_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_ErrorCodeAndMsgMap,ErrorCode.CLIENT_ERROR_INVALID_APP_STATUS,"invalid app status"),ErrorCode.CLIENT_ERROR_INVALID_USER_ID,"invalid userId"),ErrorCode.CLIENT_ERROR_INVALID_REQUEST,"invalid request"),ErrorCode.SERVER_ERROR_GSLB_NOT_FOUND_CHANNEL_ID_ERROR,"gslb not found channelId error"),ErrorCode.SERVER_ERROR_INTERNAL_ERROR,"internal error"),ErrorCode.SERVER_ERROR_MEDIA_ENGINE_ACCESS_ERROR,"media-engine access error"),ErrorCode.SERVER_ERROR_MEDIA_ENGINE_SCHEDULE_AND_CREATE_ERROR,"media-engine scheduleAndCreate error"),ErrorCode.SERVER_ERROR_SECURITY_TOKEN_NOT_FOUND_ERROR,"security token not found error"),ErrorCode.SERVER_ERROR_GSLB_DISPATCH_ERROR,"gslb dispatch error"),ErrorCode.SERVER_ERROR_GSLB_MAPI_ERROR,"gslb mapi error"),_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_ErrorCodeAndMsgMap,ErrorCode.ScreenShareUnknownError,"unknown screenShare error"),ErrorCode.ScreenShareNotAllowed,"screenShare not allowned"),ErrorCode.ScreenShareEnded,"screenShare ended"),ErrorCode.ScreenShareNotAuthed,"screenShare no permission"),ErrorCode.ScreenShareInvalidAccess,"screenShare invalid access"),ErrorCode.ScreenShareAbortError,"screenShare abort access"),ErrorCode.ScreenShareStateError,"screenShare state error"),ErrorCode.ScreenShareTypeError,"screenShare type error"),ErrorCode.AutoPlayFailed,"auto play failed"),ErrorCode.OverConstrainedError,"Overconstrained error"),_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_ErrorCodeAndMsgMap,ErrorCode.DeviceUnknownError,"unknown device error"),ErrorCode.MicOpenFail,"failed to open audio record device or audio device occupied"),ErrorCode.MicInterrupt,"audio recording error or audio device occupied"),ErrorCode.SpeakerInterrupt,"audio playing error or audio device occupied"),ErrorCode.SpeakerOpenFail,"failed to open playback device"),ErrorCode.SpeakerSetNotSupported,"not support set output device"),ErrorCode.MicAuthFail,"no audio recording permission or audio device occupied"),ErrorCode.MicNotAvailable,"no audio record device found"),ErrorCode.SpeakerNotAvailable,"no audio play device found"),ErrorCode.SpecifiedAudioDeviceNotFound,"specified audio device not found"),_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_ErrorCodeAndMsgMap,ErrorCode.CameraOpenFail,"failed to open camera due to no permission or camera device occupied"),ErrorCode.CameraInterrupt,"camera capturing happens error"),ErrorCode.SpecifiedCameraDeviceNotFound,"specified camera device not found"),ErrorCode.VideoDisplayOpenFail,"failed to open render device"),ErrorCode.VideoDisplayInterrupt,"render happens error"),ErrorCode.ScreenShareOpenFail,"failed to start shareScreen"),ErrorCode.CameraNotAvailable,"no camera device found"),ErrorCode.CameraAuthFail,"no camera permission"),ErrorCode.IceConnectionConnectFail,"ICE connection failed"),ErrorCode.IceConnectionAnswerFail,"failed to answer ICE connection"),_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_ErrorCodeAndMsgMap,ErrorCode.IceConnectionDisconnected,"ICE connection disconnected"),ErrorCode.IceConnectionNoCandidate,"ICE connection has no candidates"),ErrorCode.IceConnectionSetLocalDescFail,"failed to set local SDP"),ErrorCode.ConnectionHeartbeatTimeout,"signal heartbeat timeout"),ErrorCode.ConnectionConnectFail,"signal connection failed"),ErrorCode.APICallTimeOut,"api call is timeout"),ErrorCode.IceConnectionReconnectFail,"failed to reconnect ICE connection"),ErrorCode.PublishVideoStreamFailed,"failed to publish video"),ErrorCode.PublishNoStream,"publish stream is not exist\t"),ErrorCode.PublishInvaild,"already unpublish or not publish for now"),_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_ErrorCodeAndMsgMap,ErrorCode.PublishNotJoinChannel,"can not publish before join channel"),ErrorCode.PublishAudioStreamFailed,"failed to publish audio"),ErrorCode.PublishScreenShareFailed,"failed to publish ScreenShare"),ErrorCode.PublishScreenShareConfigError,"failed to publish ScreenShare due to config error"),ErrorCode.SubscribeStreamNotExisted,"subscribe stream is not exist"),ErrorCode.SubscribeInvaild,"already unsubscribe or not subscribe for now"),ErrorCode.SubscribeNotJoinChannel,"can not subscribe before join channel"),ErrorCode.SubscribeAudioStreamFailed,"failed to subscribe audio"),ErrorCode.SubscribeScreenShareFailed,"failed to subscribe ScreenShare"),ErrorCode.SubscribeVideoStreamFailed,"failed to subscribe video"),_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_ErrorCodeAndMsgMap,ErrorCode.AudioMixingUnknownError,"audio mixing unknown error"),ErrorCode.LoadAudioFailed,"load audio source failed"),ErrorCode.AudioMixingStateInvalid,"invalid audio mixing state"),ErrorCode.AudioContextNotSupported,"audio context is not supported"),ErrorCode.NotArrayBuffer,"source type is not array buffer"),ErrorCode.AudioMixingMissingParam,"audio mixing is missing param"),ErrorCode.AudioMixingStartFailed,"audio mixing start failed"),ErrorCode.AudioMixingResumeFailed,"audio mixing resume failed"),ErrorCode.AudioPlayTimeError,"time out of range"),ErrorCode.QuotaLimitExceed,"task exceed limit"),_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_ErrorCodeAndMsgMap,ErrorCode.InvaildState,"the operation is rejected in current state"),ErrorCode.InvaildArgument,"invalid argument"),ErrorCode.AudioBufferFull,"external audio input buffer is full"),ErrorCode.VideoBufferFull,"external video input buffer is full"),ErrorCode.AudioStreamError,"auido stream has error"),ErrorCode.AudioFileOpenFail,"failed to open audio file"),ErrorCode.AudioFormatNotSupported,"no support the audio format"),ErrorCode.UpdateRoleChannel,"failed to update role"),ErrorCode.BrowserNotSupported,"failed to update role"),ErrorCode.Inner,"sdk internel error occured"),_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_ErrorCodeAndMsgMap,ErrorCode.LogAlreadyInit,"log already init"),ErrorCode.LogRootPathError,"log root path error"),ErrorCode.SessionRemoved,"session has been removed"),ErrorCode.ServerResponseInvalid,"Server response invalid")),converToRtcErrorFromGslbCode=function(e,t){return new DingRTCError(e?ErrorCode[e]:ErrorCode.NetworkError,ErrorCodeAndMsgMap[e]||GSLBErrorCode[e]||t)},NAME_TYPEERROR=DeviceErrorDescription.NAME_TYPEERROR,NAME_ABORTEERROR=DeviceErrorDescription.NAME_ABORTEERROR,NAME_INVALID_ACCESS=DeviceErrorDescription.NAME_INVALID_ACCESS,NAME_DEVICENOTFOUND=DeviceErrorDescription.NAME_DEVICENOTFOUND,NAME_DEVICENOTALLOWED=DeviceErrorDescription.NAME_DEVICENOTALLOWED,NAME_INVALIDSTATEERROR=DeviceErrorDescription.NAME_INVALIDSTATEERROR,MESSAGE_DEVICENOTFOUND=DeviceErrorDescription.MESSAGE_DEVICENOTFOUND,NAME_DEVICENOTREADABLE=DeviceErrorDescription.NAME_DEVICENOTREADABLE,MESSAGE_DEVICENOTALLOWED=DeviceErrorDescription.MESSAGE_DEVICENOTALLOWED,NAME_DEVICEOVERCONSTRAINED=DeviceErrorDescription.NAME_DEVICEOVERCONSTRAINED,MESSAGE_VIDEODEVICENOTREADABLE=DeviceErrorDescription.MESSAGE_VIDEODEVICENOTREADABLE,MESSAGE_AUDIODEVICENOTREADABLE=DeviceErrorDescription.MESSAGE_AUDIODEVICENOTREADABLE,MESSAGE_MOBILEDEVICE_NOTALLOWED=DeviceErrorDescription.MESSAGE_MOBILEDEVICE_NOTALLOWED,MESSAGE_MACSAFARIDEVICENOTALLOWED=DeviceErrorDescription.MESSAGE_MACSAFARIDEVICENOTALLOWED,MESSAGE_MACCHROMEDEVICENOTREADABLE=DeviceErrorDescription.MESSAGE_MACCHROMEDEVICENOTREADABLE,parseAudioDeviceError=function(e){if(e){var t=e.message,r=e.name;if(t===MESSAGE_DEVICENOTFOUND||r===NAME_DEVICENOTFOUND)return new DingRTCError(ErrorCode.MicNotAvailable);if([MESSAGE_DEVICENOTALLOWED,MESSAGE_MACSAFARIDEVICENOTALLOWED].includes(t))return new DingRTCError(ErrorCode.MicAuthFail);if([MESSAGE_MACCHROMEDEVICENOTREADABLE,MESSAGE_AUDIODEVICENOTREADABLE].includes(t)||r===NAME_DEVICENOTREADABLE)return new DingRTCError(ErrorCode.MicOpenFail);if(e instanceof TypeError)return new DingRTCError(ErrorCode.InvaildArgument,t)}return new DingRTCError(ErrorCode.DeviceUnknownError,e.message)},parseVideoDeviceError=function(e){if(e){var t=e.message,r=e.name;if(t===MESSAGE_DEVICENOTFOUND||r===NAME_DEVICENOTFOUND)return new DingRTCError(ErrorCode.CameraNotAvailable);if(t==MESSAGE_DEVICENOTALLOWED||t==MESSAGE_MOBILEDEVICE_NOTALLOWED||t==MESSAGE_MACSAFARIDEVICENOTALLOWED)return new DingRTCError(ErrorCode.CameraAuthFail);if(t==MESSAGE_MACCHROMEDEVICENOTREADABLE||t==MESSAGE_VIDEODEVICENOTREADABLE||r==NAME_DEVICENOTREADABLE)return new DingRTCError(ErrorCode.CameraOpenFail);if(r==NAME_DEVICEOVERCONSTRAINED)return new DingRTCError(ErrorCode.OverConstrainedError);if(e instanceof TypeError)return new DingRTCError(ErrorCode.InvaildArgument,t)}return new DingRTCError(ErrorCode.DeviceUnknownError,e.message)},parseScreenShareError=function(e){if(e){var t=e.name,r=e.message;if("ended"==e.type)return new DingRTCError(ErrorCode.ScreenShareEnded);if(NAME_DEVICENOTALLOWED===t)return new DingRTCError(r==MESSAGE_DEVICENOTALLOWED?ErrorCode.ScreenShareNotAllowed:ErrorCode.ScreenShareNotAuthed,r);if(NAME_INVALID_ACCESS===t)return new DingRTCError(ErrorCode.ScreenShareInvalidAccess,r);if(NAME_ABORTEERROR===t)return new DingRTCError(ErrorCode.ScreenShareAbortError,r);if(NAME_INVALIDSTATEERROR===t)return new DingRTCError(ErrorCode.ScreenShareStateError,r);if(NAME_TYPEERROR===t)return new DingRTCError(ErrorCode.ScreenShareTypeError,r);if(e instanceof TypeError)return new DingRTCError(ErrorCode.InvaildArgument,r)}return new DingRTCError(ErrorCode.ScreenShareUnknownError,"name: ".concat(e.name," message: ").concat(e.message))};function _callSuper$n(e,t,r){return t=_getPrototypeOf(t),_possibleConstructorReturn(e,_isNativeReflectConstruct$n()?Reflect.construct(t,r||[],_getPrototypeOf(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$n(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$n=function(){return!!e})()}var DingRTCError=function(e){function t(e,r){var n;return _classCallCheck(this,t),n=_callSuper$n(this,t,[r=r||ErrorCodeAndMsgMap[e]]),Object.defineProperty(n,"code",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(n,"reason",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),n.code=e,n.reason=r,getReporter().trace.exception(n),n}return _inherits(t,_wrapNativeSuper(Error)),_createClass(t)}(),AudioCodec,VideoCodec,AudioSourceInfo,TaskType,NetworkQualityType,SdkType,TerminalType,DropType,PubSubStates,PeerConnectionState,SubPubFailReason,ClientUserStats,VideoProfileType;function _defineProperty(e,t,r){return(t=toPropertyKey$1(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function _arrayLikeToArray$d(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _arrayWithoutHoles(e){if(Array.isArray(e))return _arrayLikeToArray$d(e)}function _iterableToArray(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}function _unsupportedIterableToArray$d(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$d(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_arrayLikeToArray$d(e,t):void 0}}function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _toConsumableArray(e){return _arrayWithoutHoles(e)||_iterableToArray(e)||_unsupportedIterableToArray$d(e)||_nonIterableSpread()}function _superPropBase(e,t){for(;!{}.hasOwnProperty.call(e,t)&&null!==(e=_getPrototypeOf$1(e)););return e}function _get(){return _get="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(e,t,r){var n=_superPropBase(e,t);if(n){var i=Object.getOwnPropertyDescriptor(n,t);return i.get?i.get.call(arguments.length<3?e:r):i.value}},_get.apply(null,arguments)}!function(e){e.PCMU="pcmu",e.PCMA="pcma",e.OPUS="opus",e.G722="g722",e.ISAC="iSAC",e.ILBC="iLBC",e.AAC="aac",e.AC3="ac3",e.NELLYMOSER="nellymoser"}(AudioCodec||(AudioCodec={})),function(e){e.VP8="vp8",e.VP9="vp9",e.H264="h264",e.H265="h265",e.AV1="av1",e.AV1X="av1x"}(VideoCodec||(VideoCodec={})),exports.AudioSourceInfo=void 0,AudioSourceInfo=exports.AudioSourceInfo||(exports.AudioSourceInfo={}),AudioSourceInfo.MIC="mic",AudioSourceInfo.SCREENCAST="screen-cast",AudioSourceInfo.MIXED="mixed",exports.VideoSourceInfo=void 0,function(e){e.CAMERA="camera",e.SCREENCAST="screen-cast",e.MIXED="mixed"}(exports.VideoSourceInfo||(exports.VideoSourceInfo={})),function(e){e.PUBLISH="publish",e.SUBSCRIBE="subscribe"}(TaskType||(TaskType={})),function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.GREAT=1]="GREAT",e[e.GOOD=2]="GOOD",e[e.NORMAL=3]="NORMAL",e[e.POOR=4]="POOR",e[e.BAD=5]="BAD",e[e.DISCONNECTED=6]="DISCONNECTED"}(NetworkQualityType||(NetworkQualityType={})),function(e){e[e.Native=1]="Native",e[e.Web=2]="Web",e[e.MiniProgram=3]="MiniProgram"}(SdkType||(SdkType={})),function(e){e[e.Windows=1]="Windows",e[e.Android=2]="Android",e[e.Mac=3]="Mac",e[e.iOS=4]="iOS",e[e.Linux=5]="Linux",e[e.Others=6]="Others"}(TerminalType||(TerminalType={})),function(e){e[e.UserKickOut=2011]="UserKickOut",e[e.UserReplaced=2012]="UserReplaced"}(DropType||(DropType={})),function(e){e[e.Idle=0]="Idle",e[e.Processing=1]="Processing",e[e.End=2]="End"}(PubSubStates||(PubSubStates={})),function(e){e[e.New=0]="New",e[e.Idle=1]="Idle",e[e.Processing=2]="Processing",e[e.Ended=3]="Ended"}(PeerConnectionState||(PeerConnectionState={})),function(e){e.QuotaLimit="task exceed limit",e.PCNotExisted="connection does NOT exist",e.RoomClosed="room_already_closed:30107",e.RoomNotExisted="room does not exist",e.RoomBusy="RoomBusy",e.RoomNotJoined="participant has not joined",e.FailOver="Session has been aborted"}(SubPubFailReason||(SubPubFailReason={})),function(e){e[e.MIC_OPEN=0]="MIC_OPEN",e[e.MIC_INTERRUPTED=1]="MIC_INTERRUPTED",e[e.CAMERA_OPEN=2]="CAMERA_OPEN",e[e.BACKGROUND_MODE=3]="BACKGROUND_MODE",e[e.DOWNLINK=4]="DOWNLINK",e[e.UPLINK=5]="UPLINK"}(ClientUserStats||(ClientUserStats={})),function(e){e[e.None=0]="None",e[e.LD=2]="LD",e[e.SD=4]="SD",e[e.HD=8]="HD",e[e.FHD=16]="FHD",e[e.QHD=32]="QHD",e[e.UHD=64]="UHD"}(VideoProfileType||(VideoProfileType={}));var version="3.9.22",pkg={version:version},VideoDimensions={VD_120x120:[120,120],VD_160x120:[160,120],VD_180x180:[180,180],VD_240x180:[240,180],VD_320x180:[320,180],VD_240x240:[240,240],VD_320x240:[320,240],VD_424x240:[424,240],VD_360x360:[360,360],VD_480x360:[480,360],VD_640x360:[640,360],VD_480x480:[480,480],VD_640x480:[640,480],VD_840x480:[840,480],VD_960x540:[960,540],VD_960x720:[960,720],VD_1280x720:[1280,720],VD_1920x1080:[1920,1080],VD_2560x1440:[2560,1440]};exports.AudioSourceState=void 0,function(e){e.Playing="playing",e.Paused="paused",e.Stopped="stopped"}(exports.AudioSourceState||(exports.AudioSourceState={}));var SDK_VERSION=pkg.version,DEFAULT_GSLB_DOMAIN="https://gslb.dingrtc.com",IGNOGRED_VERSION=-999,SIGNAL_CALL_TIMEOUT=1e3,NETWORK_QUALITY_TIMEOUT=2e3,METRIC_STATS_INTERVAL=2e3,DEFAULT_CREATE_PC_TIMEOUT=4e3,MEDIA_ELEMENT_LABEL_ATTR="rtc-label",STUCK_JUDGE_RECV_BYTES=3e4;JSON.stringify({needPersonalityAudioStream:!0,outPeerConnectionNotReuse:!0}),Environment.browserType,Environment.browserVersion,Environment.system,Environment.systemVersion;var USER_STATS_SYNC="onertc_state_sync",TRACK_EVENT_NAME="onertc_internal_track_event",RTC_SDK_EL_DATA_ATTR_NAME="rtc_sdk_el_data",RTC_SDK_PLAYER_CONTAINER_LABEL_ATTR_NAME="rtc_sdk_player_container_label",CONST_DEVELOPER_TODO_LOG_TAG="_DEV_TODO_",logger$a=getReporter().getLoggerWithPrefix("rtc-support"),Support=function(){return _createClass$1(function e(){_classCallCheck$1(this,e),Object.defineProperty(this,"system",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"browser",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"browserVersion",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.system=Environment.system,this.browser=Environment.browserType,this.browserVersion=Environment.browserVersion},[{key:"getSupportedCodec",value:(e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){var t,r,n;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t={audio:[],video:[]},e.prev=1,(r=new RTCPeerConnection).addTransceiver("video",{direction:"recvonly"}),r.addTransceiver("audio",{direction:"recvonly"}),e.next=2,r.createOffer();case 2:if(n=e.sent.sdp){e.next=3;break}return e.abrupt("return",t);case 3:return r.close(),r=null,n.match(/ VP8/i)&&t.video.push("VP8"),n.match(/ VP9/i)&&t.video.push("VP9"),n.match(/ AV1/i)&&t.video.push("AV1"),n.match(/ H264/i)&&t.video.push("H264"),n.match(/ H265/i)&&t.video.push("H265"),n.match(/ opus/i)&&t.audio.push("OPUS"),n.match(/ PCMU/i)&&t.audio.push("PCMU"),n.match(/ PCMA/i)&&t.audio.push("PCMA"),n.match(/ G722/i)&&t.audio.push("G722"),e.abrupt("return",t);case 4:throw e.prev=4,e.catch(1),logger$a.error("get supportedCodecs failed"),new DingRTCError(ErrorCode.IceConnectionSetLocalDescFail,"get supportedCodecs failed");case 5:case"end":return e.stop()}},e,null,[[1,4]])})),function(){return e.apply(this,arguments)})},{key:"checkSupported",value:function(){var e=!1;try{var t=window.RTCPeerConnection,r=navigator.mediaDevices&&navigator.mediaDevices.getUserMedia,n=window.WebSocket;e=!!(t&&r&&n)}catch(e){return logger$a.error("checkSystemRequirements error",e),!1}var i=!1;i=Environment.isChrome()||Environment.isFirefox()?parseInt(Environment.browserVersion,10)>=69:Environment.isOpera()?parseInt(Environment.browserVersion,10)>=45:Environment.isSafari()?parseInt(Environment.browserVersion,10)>=11:(Environment.isWeixin()||Environment.isQQBrowser(),!0);var o=e&&i;return logger$a.info("checkSystemRequirements, api:",e,"browser",i),o}},{key:"isSupportScreenShare",value:function(){return!this.system.includes(OSType.ANDROID)&&this.system!==OSType.IOS&&(!(this.browser===BrowserType.SAFARI&&parseInt(this.browserVersion)<13)&&(!(this.browser===BrowserType.FIREFOX&&parseInt(this.browserVersion)<66)&&!!(navigator&&navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)))}}]);var e}(),support=new Support,isSupportSimulcast=function(){var e,t=(null===(e=window.RTCRtpSender)||void 0===e?void 0:e.prototype)||{},r=t.setParameters,n=t.getParameters;return!(!r||!n)&&(!Environment.isFirefox()&&(Environment.isSafari()?parseInt(Environment.browserVersion)>=14:Environment.isChrome()?parseInt(Environment.browserVersion)>=81:!Environment.isAndroid()))};function _callSuper$m(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$m()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$m(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$m=function(){return!!e})()}var logger$9=getReporter().getLoggerWithPrefix("[rtc-config]"),ClientConfig=function(e){function t(){var e;return _classCallCheck$1(this,t),e=_callSuper$m(this,t),Object.defineProperty(e,"gslb",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(e,"simulcast",{enumerable:!0,configurable:!0,writable:!0,value:isSupportSimulcast()}),Object.defineProperty(e,"audioSFU",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(e,"republish",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(e,"disableTransportCC",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(e,"preferH264CbProfile",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(e,"downlinkForbidHighProfile",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(e,"highStartBitrate",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(e,"_holdVideoLastFrame",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(e,"_consoleLogLevel",{enumerable:!0,configurable:!0,writable:!0,value:"warn"}),Object.defineProperty(e,"connectPcTimeoutMs",{enumerable:!0,configurable:!0,writable:!0,value:DEFAULT_CREATE_PC_TIMEOUT}),e.setClientConfig({gslb:[DEFAULT_GSLB_DOMAIN]}),e}return _inherits$1(t,e),_createClass$1(t,[{key:"setClientConfig",value:function(e){logger$9.info("setClientConfig",e);var t=e||{},r=t.gslb,n=t.simulcast,i=t.audioSFU,o=t.republish,a=t.disableTransportCC,s=t.highStartBitrate;"string"==typeof r&&(this.gslb=[r],setGslb(r)),Array.isArray(r)&&isString(r[0])&&(this.gslb=r,setGslb(r[0])),null!=n&&isSupportSimulcast()&&(this.simulcast=Boolean(n)),null!=i&&(this.audioSFU=Boolean(i)),null!=a&&(this.disableTransportCC=Boolean(a)),null!=o&&(this.republish=Boolean(o)),null!=s&&(this.highStartBitrate=!!s),null!=e&&e._consoleLogLevel&&(this._consoleLogLevel=null==e?void 0:e._consoleLogLevel),"boolean"==typeof(null==e?void 0:e.preferH264CbProfile)&&(this.preferH264CbProfile=e.preferH264CbProfile),(null==e?void 0:e.connectPcTimeoutMs)>=0&&e.connectPcTimeoutMs<=Number.MAX_SAFE_INTEGER?this.connectPcTimeoutMs=e.connectPcTimeoutMs:void 0!==(null==e?void 0:e.connectPcTimeoutMs)&&null!==(null==e?void 0:e.connectPcTimeoutMs)&&console.error("connectPcTimeoutMs should be a non-negative number")}}])}(EventEmitter),clientConfig=new ClientConfig,sortResolutions=function(e,t){return e.width!==t.width?e.width-t.width:e.height-t.height},getStreamSupportedResoArr=function(e){var t;if(!e)return[];var r=e.media.video;if(!r)return[];var n=[],i=r.optional,o=r.parameters;return null!=o&&o.resolution&&n.push(o.resolution),null!=i&&null!==(t=i.parameters)&&void 0!==t&&null!==(t=t.resolution)&&void 0!==t&&t.length&&n.push.apply(n,_toConsumableArray(i.parameters.resolution)),n.sort(sortResolutions),n},parseSubscribeError=function(e,t){var r,n=e.media,i=n.audio,o=n.video;if(t===SubPubFailReason.QuotaLimit)return r=new DingRTCError(ErrorCode.QuotaLimitExceed);if(i)r=new DingRTCError(ErrorCode.SubscribeAudioStreamFailed,t);else if(o){var a=o.source;a===exports.VideoSourceInfo.CAMERA?r=new DingRTCError(ErrorCode.SubscribeVideoStreamFailed,t):a===exports.VideoSourceInfo.SCREENCAST&&(r=new DingRTCError(ErrorCode.SubscribeScreenShareFailed,t))}return r},parsePublishError=function(e,t){var r,n=e.trackMediaType;if(t===SubPubFailReason.QuotaLimit)return r=new DingRTCError(ErrorCode.QuotaLimitExceed);if("audio"===n)r=new DingRTCError(ErrorCode.PublishAudioStreamFailed,t);else{var i=e.source;i===exports.VideoSourceInfo.CAMERA?r=new DingRTCError(ErrorCode.PublishVideoStreamFailed,t):i===exports.VideoSourceInfo.SCREENCAST&&(r=new DingRTCError(ErrorCode.PublishScreenShareFailed,t))}return r},updateRemoteTrack=function(e,t,r,n){var i=n,o=e.getVideoTracks(),a=e.getAudioTracks();return"audio"===t&&a.length?clientConfig.audioSFU?n?n.replaceStream(e):i=new RemoteAudioTrack(null,r,e):n?n.replaceTrack(a[0]):i=new RemoteAudioTrack(a[0],r):"video"===t&&o.length&&(n?n.replaceTrack(o[0]):i=new RemoteVideoTrack(o[0],r)),i},isScreenCast=function(e){return"object"===_typeof$3(e.video)&&e.video.source===exports.VideoSourceInfo.SCREENCAST};function ownKeys$a(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function _objectSpread$a(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$a(Object(r),!0).forEach(function(t){_defineProperty(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$a(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function _createForOfIteratorHelper$c(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$c(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$c(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$c(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_arrayLikeToArray$c(e,t):void 0}}function _arrayLikeToArray$c(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _callSuper$l(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$l()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$l(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$l=function(){return!!e})()}var logger$8=getReporter().getLoggerWithPrefix("[rtc-device]"),DeviceManager=function(e){function t(){var e,r;return _classCallCheck$1(this,t),e=_callSuper$l(this,t),Object.defineProperty(e,"deviceList",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(e,"checking",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(e,"checkDeviceUpdate",{enumerable:!0,configurable:!0,writable:!0,value:(r=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function r(){var n;return _regeneratorRuntime$1.wrap(function(r){for(;;)switch(r.prev=r.next){case 0:if(!e.checking){r.next=1;break}return r.abrupt("return");case 1:return e.checking=!0,r.next=2,t.getDevices();case 2:n=r.sent,e.compareDevices(n,"audiooutput"),e.compareDevices(n,"videoinput"),e.compareDevices(n,"audioinput"),e.deviceList=n,e.checking=!1;case 3:case"end":return r.stop()}},r)})),function(){return r.apply(this,arguments)})}),Object.defineProperty(e,"compareDevices",{enumerable:!0,configurable:!0,writable:!0,value:function(t,r){var n,i=t.filter(function(e){return e.kind===r}),o=e.deviceList.filter(function(e){return e.kind===r}),a=i.map(function(e){return e.deviceId}),s=o.map(function(e){return e.deviceId}),c=i.filter(function(e){var t=e.deviceId;return!s.includes(t)}),u=o.filter(function(e){var t=e.deviceId;return!a.includes(t)}),l={audioinput:"microphone-changed",audiooutput:"playback-device-changed",videoinput:"camera-changed"},d=_createForOfIteratorHelper$c(c);try{for(d.s();!(n=d.n()).done;){var p=n.value;e.emit(l[r],{device:p,state:"active"})}}catch(e){d.e(e)}finally{d.f()}var f,h=_createForOfIteratorHelper$c(u);try{for(h.s();!(f=h.n()).done;){var g=f.value;e.emit(l[r],{device:g,state:"inactive"})}}catch(e){h.e(e)}finally{h.f()}}}),t._instance?_possibleConstructorReturn$1(e,t._instance):(e.deviceList=[],support.checkSupported()?(t.getDevices({audio:!0,video:!0},!0).then(function(t){e.deviceList=t,e.addEventListeners()}),e):_possibleConstructorReturn$1(e))}return _inherits$1(t,e),_createClass$1(t,[{key:"addEventListeners",value:function(){"ondevicechange"in navigator.mediaDevices?navigator.mediaDevices.addEventListener("devicechange",this.checkDeviceUpdate):addTimer(this.checkDeviceUpdate,1e3,"interval")}}],[{key:"getInstance",value:function(){return t._instance}},{key:"getMedias",value:(r=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(r,n){var i,o,a,s,c,u,l,d,p,f,h;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(t.accGetMedia++,i=t.accGetMedia,!isScreenCast(r)){e.next=6;break}if(logger$8.info("getDisplayMedia with",i,r,n),!Environment.isElectron()){e.next=3;break}if(n.video){e.next=1;break}throw new DingRTCError(ErrorCode.ScreenShareOpenFail,"only video screen cast is supported, but got no video parameters");case 1:return e.next=2,navigator.mediaDevices.getUserMedia({audio:!1,video:{mandatory:{chromeMediaSource:"screen",minWidth:(null===(a=n.video)||void 0===a?void 0:a.width)||1280,maxWidth:(null===(s=n.video)||void 0===s?void 0:s.width)||1280,minHeight:(null===(c=n.video)||void 0===c?void 0:c.height)||720,maxHeight:(null===(u=n.video)||void 0===u?void 0:u.height)||720,minFrameRate:(null===(l=n.video)||void 0===l?void 0:l.frameRate)||5,maxFrameRate:(null===(d=n.video)||void 0===d?void 0:d.frameRate)||5}}});case 2:o=e.sent,e.next=5;break;case 3:return e.next=4,null===(p=navigator.mediaDevices)||void 0===p?void 0:p.getDisplayMedia(n);case 4:o=e.sent;case 5:return logger$8.info("succ getDisplayMedia with",i),e.abrupt("return",o);case 6:return logger$8.info("getUserMedia with",i,r,n),e.next=7,null===(f=navigator.mediaDevices)||void 0===f?void 0:f.getUserMedia(n);case 7:return h=e.sent,logger$8.info("succ getUserMedia with",i),r.audio&&(this.audioPermitted=!0),r.video&&(this.videoPermitted=!0),e.abrupt("return",h);case 8:case"end":return e.stop()}},e,this)})),function(e,t){return r.apply(this,arguments)})},{key:"getDevices",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{audio:!0,video:!0},r=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return new Promise(function(n,i){var o;if(null!==(o=navigator.mediaDevices)&&void 0!==o&&o.enumerateDevices){var a=!1;t.audio&&t.video?a=e.audioPermitted&&e.videoPermitted:t.audio?a=e.audioPermitted:t.video&&(a=e.videoPermitted),navigator.mediaDevices.enumerateDevices().then(function(o){var s=o.filter(function(e){return e.deviceId}),c=s.filter(function(e){return"videoinput"===e.kind}),u=s.filter(function(e){return"audioinput"===e.kind}),l=s.filter(function(e){return"audiooutput"===e.kind}),d=[];t.audio&&(d=d.concat(u,l)),t.video&&(d=d.concat(c)),0!==d.length||a||r?d.length?(t.audio&&(e.audioPermitted=!0),t.video&&(e.videoPermitted=!0),n(d)):n(d):(logger$8.info("getUserMedia with",t),navigator.mediaDevices.getUserMedia(t).then(function(r){t.audio&&(e.audioPermitted=!0),t.video&&(e.videoPermitted=!0),r.getTracks().forEach(function(e){e.stop()}),navigator.mediaDevices.enumerateDevices().then(function(e){n(e)},i)},i)),n(s)})}else i(new DingRTCError(ErrorCode.BrowserNotSupported,"enumerateDevices is not supported"))})}}]);var r}(EventEmitter);Object.defineProperty(DeviceManager,"videoPermitted",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(DeviceManager,"audioPermitted",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(DeviceManager,"_instance",{enumerable:!0,configurable:!0,writable:!0,value:new DeviceManager}),Object.defineProperty(DeviceManager,"accGetMedia",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(DeviceManager,"getPlaybackDevices",{enumerable:!0,configurable:!0,writable:!0,value:function(){return DeviceManager.getDevices({audio:!0}).then(function(e){return e.filter(function(e){return"audiooutput"===e.kind})}).catch(function(e){throw parseAudioDeviceError(e)})}}),Object.defineProperty(DeviceManager,"getCameras",{enumerable:!0,configurable:!0,writable:!0,value:function(){return DeviceManager.getDevices({video:!0}).then(function(e){return logger$8.info("getCameras",e),e.filter(function(e){return"videoinput"===e.kind}).map(function(e,t){var r={deviceId:e.deviceId,kind:e.kind,groupId:e.groupId,label:e.label||"camera ".concat(t)};return _objectSpread$a(_objectSpread$a({},r),{},{toJSON:function(){return r}})})}).catch(function(e){throw logger$8.error("getCameras error",e),parseVideoDeviceError(e)})}}),Object.defineProperty(DeviceManager,"getMicrophones",{enumerable:!0,configurable:!0,writable:!0,value:function(){return DeviceManager.getDevices({audio:!0}).then(function(e){return logger$8.info("getMicrophones",e),e.filter(function(e){return"audioinput"===e.kind})}).catch(function(e){throw logger$8.error("getMicrophones error",e),parseAudioDeviceError(e)})}});var parseVideoDimension=function(e){return{width:VideoDimensions[e][0],height:VideoDimensions[e][1]}},addAudioTrackAttribute=function(e){var t,r=Object.create({}),n={};null!==(t=navigator)&&void 0!==t&&null!==(t=t.mediaDevices)&&void 0!==t&&t.getSupportedConstraints&&(n=navigator.mediaDevices.getSupportedConstraints(),console.log(n));var i=e.AEC,o=e.AGC,a=e.ANS;return e.deviceId&&(Environment.isSafari()?r.deviceId=e.deviceId:r.deviceId={exact:e.deviceId}),n.autoGainControl&&(r.autoGainControl={ideal:null==o||o}),n.echoCancellation&&(r.echoCancellation={ideal:null==i||i}),n.noiseSuppression&&(r.noiseSuppression={ideal:null==a||a}),r},createMediaStream=function(e){if(!isObject(e)||!e.audio&&!e.video)return Promise.reject(new TypeError("Invalid constrains"));var t=e.audio,r=e.video;if(!isScreenCast(e)&&"object"===_typeof$3(t)&&t.source===exports.AudioSourceInfo.SCREENCAST)return Promise.reject(new TypeError("Cannot share screen without video."));if(isScreenCast(e)&&"object"===_typeof$3(t)&&t.source!==exports.AudioSourceInfo.SCREENCAST)return Promise.reject(new TypeError("Cannot capture video from screen cast while capture audio from other source."));if(!t&&!r)return Promise.reject(new TypeError("At least one of audio and video must be requested."));var n={};if("object"===_typeof$3(t)&&t.source===exports.AudioSourceInfo.MIC||"object"===_typeof$3(t)&&t.source===exports.AudioSourceInfo.SCREENCAST?n.audio=addAudioTrackAttribute(t):n.audio=e.audio,"object"===_typeof$3(r)){var i,o=r.frameRate,a=r.deviceId,s=r.source,c=r.facingMode,u=r.displaySurface,l=r.dimension;n.video={},isNumber(o)&&(n.video.frameRate=Math.min(r.frameRate,30)),l&&(i=parseVideoDimension(l)),i&&i.width&&i.height&&(s===exports.VideoSourceInfo.SCREENCAST||Environment.isFirefox()?(n.video.width=i.width,n.video.height=i.height):(n.video.width={ideal:i.width,max:i.width},n.video.height={ideal:i.height,max:i.height})),isString(a)&&a&&(n.video.deviceId={exact:a}),s===exports.VideoSourceInfo.SCREENCAST&&(Environment.isFirefox()&&(n.video.mediaSource="screen"),u&&["browser","window","monitor"].includes(u)&&(n.video.displaySurface=u)),c&&["user","environment"].includes(c)&&(n.video.facingMode=c)}else n.video=r;return DeviceManager.getMedias(e,n)},isVideoStreamPlayable=function(e){if(!e)return!1;var t=e.getVideoTracks()[0];return t&&t.enabled&&!t.muted},getDeltaDurationInSeconds=function(e,t){var r=(e.timestamp-((null==t?void 0:t.timestamp)||e.timestamp))/1e3;return r<=0&&(r=1),r},transNativeAndWebNetworkRank=function(e,t){return null!=e?[2,4,6,0][e]:null!==t?[3,0,0,0,1,1,2][t]:void 0},getDelta=function(e,t){isNaN(e)&&(e=0),isNaN(t)&&(t=0);var r=e-t;return r<0&&(r=e),r},multiTryExecute=function(e){var t=e.fn,r=e.times,n=e.interval,i=void 0===n?0:n,o=e.resolve,a=e.reject,s=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){var n,s,c;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:s=0;case 1:if(!(s<r)){e.next=7;break}return e.prev=2,e.next=3,t();case 3:return n=e.sent,null==o||o(n),e.abrupt("continue",7);case 4:if(e.prev=4,c=e.catch(2),s!==r-1){e.next=5;break}return null==a||a(c),e.abrupt("return",c);case 5:return e.next=6,asyncDelayMs(i);case 6:s++,e.next=1;break;case 7:return e.abrupt("return",n);case 8:case"end":return e.stop()}},e,null,[[2,4]])}));return function(){return e.apply(this,arguments)}}();return s()},asyncDelayMs=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(!(t>0)){e.next=1;break}return e.next=1,new Promise(function(e){setTimeout(e,t)});case 1:case"end":return e.stop()}},e)}));return function(t){return e.apply(this,arguments)}}(),taskQueue=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1,t=[],r=0,n=!1,i=function(){for(;r<e&&t.length;){r++;var n=t.shift();n&&n().finally(function(){r--,i()})}};return{add:function(e){t.push(e),n&&i()},start:function(){n=!0,i()}}},awaitTime=function(e){return new Promise(function(t){addTimer(t,1e3*e)})},candidateToPlainObj=function(e){return e?{address:e.address,candidate:e.candidate,component:e.component,foundation:e.foundation,port:e.port,priority:e.priority,protocol:e.protocol,relatedAddress:e.relatedAddress,relatedPort:e.relatedPort,relayProtocol:e.relayProtocol,sdpMLineIndex:e.sdpMLineIndex,sdpMid:e.sdpMid,tcpType:e.tcpType,type:e.type,usernameFragment:e.usernameFragment}:e},logger$7=getReporter().getLoggerWithPrefix("[rtc-mediaElPool]"),MEDIA_ELEMENT_INTERSECTING_ATTR="rtc-intersecting",MEDIA_ELEMENT_INTERSECTING_ATTR_VALUES={visible:"visible",invisible:"invisible"},MEDIA_ELEMENT_EVENT_NAMES=["abort","canplay","canplaythrough","durationchange","emptied","ended","error","loadeddata","loadedmetadata","loadstart","pause","play","playing","ratechange","seeked","seeking","stalled","suspend","volumechange","waiting"],MEDIA_PLAYBACK_CHECK_PERIOD_MS=4e3,getLabel=function(e){return"".concat(null==e?void 0:e.getAttribute(MEDIA_ELEMENT_LABEL_ATTR),"-").concat(null==e?void 0:e.rtcPurpose)},isVideoTagIntersectingVisible=function(e){return e&&e.getAttribute(MEDIA_ELEMENT_INTERSECTING_ATTR)===MEDIA_ELEMENT_INTERSECTING_ATTR_VALUES.visible},MediaElementPool=function(){return _createClass$1(function e(t,r){var n=this;_classCallCheck$1(this,e),Object.defineProperty(this,"mediaElementCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"mediaElementPool",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"mediaElementsInUse",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"allElements",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"hasActivated",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"mediaKind",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"mediaPlaybackCheckInterval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"debouncer",{enumerable:!0,configurable:!0,writable:!0,value:new Debouncer}),Object.defineProperty(this,"currentTimeOfLastCheckMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"observer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_activatedListener",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"destroy",{enumerable:!0,configurable:!0,writable:!0,value:function(){n.mediaElementPool.forEach(function(e){return n._resetMediaElement(e)}),n.mediaElementPool=[],n.allElements.clear(),n.mediaElementsInUse.forEach(function(e){return n._resetMediaElement(e)}),n.mediaElementsInUse=[],document.removeEventListener("click",n._onUserInteraction),document.removeEventListener("touchstart",n._onUserInteraction),document.removeEventListener("visibilitychange",n._tryReloadOnPauseAndErrorWhenVisibleTriggerByVisible),n.mediaPlaybackCheckInterval&&(removeTimer(n.mediaPlaybackCheckInterval,"interval"),n.mediaPlaybackCheckInterval=null),[].concat(_toConsumableArray(n.mediaElementPool),_toConsumableArray(n.mediaElementsInUse)).forEach(function(e){var t;return null===(t=n.observer)||void 0===t?void 0:t.unobserve(e)})}}),Object.defineProperty(this,"_tryReloadOnPauseAndErrorWhenVisible",{enumerable:!0,configurable:!0,writable:!0,value:function(e){n.mediaElementsInUse.forEach(function(t){if(t.srcObject){var r=t.srcObject;if(t.error&&(logger$7.debug("".concat(e,": tag=").concat(t.tagName," ").concat(getLabel(t)," has error, error=").concat(t.error,", doc.visibilityState=").concat(document.visibilityState,", mediaStream="),getPlainMediaStreamInfo(r)),"visible"===document.visibilityState&&isVideoStreamPlayable(r)&&t.load()),t.paused){var i=!1;if(n.hasActivated&&"video"===n.mediaKind?isVideoTagIntersectingVisible(t)&&"visible"===document.visibilityState&&"visible"===getComputedStyle(t).visibility&&(i=!0):i=!0,i){var o="".concat(e,": ").concat(getLabel(t)," paused, doc.visibilityState=").concat(document.visibilityState,", intersecting=").concat(t.getAttribute(MEDIA_ELEMENT_INTERSECTING_ATTR),", mediaStream="),a=getPlainMediaStreamInfo(r);logger$7.error(o,a),isVideoStreamPlayable(r)&&t.load(),t.paused&&t.play().catch(function(e){console.error("inPoll",e)})}}}}),n.debouncer.debounce(n._tryReloadOnCurrentTimeFreeze.bind(n,e),1e3)}}),Object.defineProperty(this,"_tryReloadOnCurrentTimeFreeze",{enumerable:!0,configurable:!0,writable:!0,value:function(e){n.mediaElementsInUse.forEach(function(t){if(t.srcObject){var r=t.srcObject,i="video"===n.mediaKind?r.getVideoTracks()[0]:void 0;if(!t.paused&&n.currentTimeOfLastCheckMap.get(t)===t.currentTime&&"video"===n.mediaKind&&!0!==(null==i?void 0:i.muted))return logger$7.error("".concat(e,": tag=").concat(t.tagName," label=").concat(getLabel(t),", currentTime Stop, doc.visibilityState=").concat(document.visibilityState,", curTime=").concat(t.currentTime,", mediaStream="),getPlainMediaStreamInfo(r)),void("visible"===document.visibilityState&&isVideoStreamPlayable(r)&&t.load());n.currentTimeOfLastCheckMap.set(t,t.currentTime)}})}}),Object.defineProperty(this,"_tryReloadOnPauseAndErrorWhenVisibleTriggerByVisible",{enumerable:!0,configurable:!0,writable:!0,value:function(){n._tryReloadOnPauseAndErrorWhenVisible("visibilityChange")}}),Object.defineProperty(this,"_elementDefaultErrorHandler",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t=e.target,r="error event on ".concat(n.mediaKind," playback, mediaStream="),i=getPlainMediaStreamInfo(null==t?void 0:t.srcObject),o=null==t?void 0:t.error;logger$7.error(r,i,o&&{code:null==o?void 0:o.code,message:null==o?void 0:o.message})}}),Object.defineProperty(this,"_elementDefaultPauseHandler",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t=e.target,r="pause event on ".concat(n.mediaKind," playback, mediaStream="),i=getPlainMediaStreamInfo(null==t?void 0:t.srcObject),o=null==t?void 0:t.error;logger$7.debug(r,i,o&&{code:null==o?void 0:o.code,message:null==o?void 0:o.message})}}),Object.defineProperty(this,"_elementDefaultPlayHandler",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t=e.target,r="play event on ".concat(n.mediaKind," playback, mediaStream="),i=getPlainMediaStreamInfo(null==t?void 0:t.srcObject);logger$7.debug(r,i)}}),Object.defineProperty(this,"_onUserInteraction",{enumerable:!0,configurable:!0,writable:!0,value:function(){var e=[].concat(_toConsumableArray(n.mediaElementPool),_toConsumableArray(n.mediaElementsInUse));if(!n.hasActivated){n.hasActivated=!0;var t="".concat(n.mediaKind," good! media elements activated by click");if(logger$7.debug(t),e.forEach(function(e){e.load()}),logger$7.info("load all for activate"),n._activatedListener)try{n._activatedListener()}catch(e){logger$7.error("error occurred when exec activatedListener",tryJsonStringify(e))}else logger$7.debug("ignore activatedListener for there is no one")}n._tryReloadOnPauseAndErrorWhenVisible("userInteract")}}),logger$7.debug("build ".concat(t," pool size"),r),this.mediaElementCount=r,this.mediaElementsInUse=[],this.mediaElementPool=[],this.mediaKind=t,window.IntersectionObserver&&(this.observer=new IntersectionObserver(function(e){e.forEach(function(e){var t,r;e.isIntersecting?null===(t=e.target)||void 0===t||t.setAttribute(MEDIA_ELEMENT_INTERSECTING_ATTR,MEDIA_ELEMENT_INTERSECTING_ATTR_VALUES.visible):null===(r=e.target)||void 0===r||r.setAttribute(MEDIA_ELEMENT_INTERSECTING_ATTR,MEDIA_ELEMENT_INTERSECTING_ATTR_VALUES.invisible)})}));for(var i=1;i<=r;i++){var o=this._createElement("".concat(t,"-").concat(i));this.mediaElementPool.push(o),this.allElements.add(o)}document.addEventListener("click",this._onUserInteraction,!0),document.addEventListener("touchstart",this._onUserInteraction,!0),document.addEventListener("visibilitychange",this._tryReloadOnPauseAndErrorWhenVisibleTriggerByVisible,!0),this.mediaPlaybackCheckInterval=addTimer(function(){n.hasActivated&&n._tryReloadOnPauseAndErrorWhenVisible("intervalCheck")},MEDIA_PLAYBACK_CHECK_PERIOD_MS,"interval")},[{key:"addAtttribute",value:function(e){if(e.autoplay=!0,e.setAttribute(MEDIA_ELEMENT_LABEL_ATTR,"toReused"),e instanceof HTMLVideoElement)e.muted=!0,e.playsInline=!0,e.controls=!1,e.setAttribute("webkit-playsinline","true"),e.setAttribute("x5-video-player-type","h5"),e.setAttribute("x5-playsinline","true");else{var t,r=e;r.volume=1,null===(t=r.setSinkId)||void 0===t||t.call(r,"")}}},{key:"popElement",value:function(e){var t;return(t=this.mediaElementPool.shift())?logger$7.info("".concat(this.mediaKind," pop label=").concat(getLabel(t)," for ").concat(e)):(t=this._createElement("".concat(this.mediaKind,"-").concat(++this.mediaElementCount)),logger$7.info("".concat(this.mediaKind," create new videoEl for no more video element in pool"))),this.mediaElementsInUse.push(t),this._resetMediaElement(t),t.addEventListener("error",this._elementDefaultErrorHandler),t.addEventListener("pause",this._elementDefaultPauseHandler),t.addEventListener("play",this._elementDefaultPlayHandler),t.rtcPurpose=e||"",t}},{key:"pushElement",value:function(e){if(this.allElements.has(e)){var t=this.mediaElementsInUse;this.mediaElementsInUse=this.mediaElementsInUse.filter(function(t){return t!==e}),t.length!==this.mediaElementsInUse.length&&(logger$7.debug("".concat(this.mediaKind," pushed"),getLabel(e)),this.mediaElementPool.push(e),this._resetMediaElement(e))}}},{key:"isMediaElementActivated",value:function(){return this.hasActivated}},{key:"setActivateListener",value:function(e){this._activatedListener=e}},{key:"_createElement",value:function(e){var t,r=document.createElement(this.mediaKind);return null===(t=this.observer)||void 0===t||t.observe(r),this.addAtttribute(r),r.setAttribute(MEDIA_ELEMENT_LABEL_ATTR,e),r}},{key:"_resetMediaElement",value:function(e){MEDIA_ELEMENT_EVENT_NAMES.forEach(function(t){e["on".concat(t)]=null}),e.removeEventListener("error",this._elementDefaultErrorHandler),e.removeEventListener("pause",this._elementDefaultPauseHandler),e.removeEventListener("play",this._elementDefaultPlayHandler),e.style.cssText="",e.className="",this.addAtttribute(e),e.srcObject=null}}])}(),audioElementMgr,videoElementMgr,getAudioElementPool=function(){return audioElementMgr||initMediaElementPool(),audioElementMgr},getVideoElementPool=function(){return videoElementMgr||initMediaElementPool(),videoElementMgr};window.getAudioElementPool=getAudioElementPool,window.getVideoElementPool=getVideoElementPool;var INIT_AUDIO_TAG_COUNT=2,INIT_VIDEO_TAG_COUNT=Environment.isIOS()||Environment.isAndroid()?9:25,initMediaElementPool=function(){audioElementMgr||(audioElementMgr=new MediaElementPool("audio",INIT_AUDIO_TAG_COUNT)),videoElementMgr||(videoElementMgr=new MediaElementPool("video",INIT_VIDEO_TAG_COUNT))},logger$6=getReporter().getLoggerWithPrefix("[rtc-actx]"),audioContext=null,getAudioContext=function(){if(audioContext||(audioContext=new AudioContext),"running"!==audioContext.state){var e=setTimeout(function(){var e="timeout for resume audioContext, probably page still has no user gesture like click or touch";console.error(e),logger$6.error(e)},2e3);audioContext.resume().finally(function(){clearTimeout(e)})}return audioContext},mergeAudioTracks=function(e){var t=e.getAudioTracks(),r=getAudioContext().createMediaStreamDestination();return t.forEach(function(e){getAudioContext().createMediaStreamSource(new MediaStream([e])).connect(r)}),r.stream.getAudioTracks()[0]},setVideoElementStyle=function(e,t){if(e.style.width="100%",e.style.height="100%",t){var r=t.mirror,n=t.fit;!0===r&&(e.style.transform="scaleX(-1)"),n&&(e.style.objectFit=n)}},getAudioVolumeLevel=function(e,t){t.connect(e),e.fftSize=2048,e.smoothingTimeConstant=.4;var r=new Float32Array(e.fftSize);if(e.getFloatTimeDomainData)e.getFloatTimeDomainData(r);else{var n=new Uint8Array(e.fftSize);e.getByteTimeDomainData(n);for(var i=0;i<r.length;++i)r[i]=n[i]/128-1}for(var o=0,a=0;a<r.length;a++)o+=r[a]*r[a];return Math.max(10*Math.log10(o/r.length)+100,0)/100},getCurrentFrame=function(e){var t=document.createElement("canvas"),r=t.getContext("2d"),n=e.videoHeight,i=e.videoWidth;return t.width=i,t.height=n,r.drawImage(e,0,0,i,n),t.toDataURL("image/png")},audioElementPool=getAudioElementPool(),videoElementPool=getVideoElementPool(),logger$5=getReporter().getLoggerWithPrefix("[rtc-playerMgr]"),PlayController=_createClass$1(function e(t,r,n,i){var o=this;_classCallCheck$1(this,e),Object.defineProperty(this,"mediaEl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"playerConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"mediaWrapperEl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"track",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"snapshotMediaStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"canvas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"snapshotInterval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"checkSwitchSnapshotInterval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lastCheckResult",{enumerable:!0,configurable:!0,writable:!0,value:{msTrackPlayable:!1,elPlaying:!1}}),Object.defineProperty(this,"isPlayerPlaying",{enumerable:!0,configurable:!0,writable:!0,value:function(){return o.mediaEl&&o.mediaEl.currentTime>0&&!o.mediaEl.paused&&!o.mediaEl.ended&&o.mediaEl.readyState>=2}}),Object.defineProperty(this,"snapshot",{enumerable:!0,configurable:!0,writable:!0,value:function(){var e,t,r=o.track.getMediaStreamTrack(),n="live"===(null==r?void 0:r.readyState)&&(null==r?void 0:r.enabled)&&!(null!=r&&r.muted);if(clientConfig._holdVideoLastFrame&&(n&&(null===(e=o.mediaEl)||void 0===e||null===(e=e.srcObject)||void 0===e||null===(t=e.getVideoTracks)||void 0===t||null===(t=t.call(e))||void 0===t?void 0:t[0])===r)){var i=o.canvas.getContext("2d");i.clearRect(0,0,o.canvas.width,o.canvas.height);var a=o.mediaEl.videoHeight,s=o.mediaEl.videoWidth;o.canvas.width===s&&o.canvas.height===a||(o.canvas.width=s,o.canvas.height=a),i.drawImage(o.mediaEl,0,0,s,a)}}}),Object.defineProperty(this,"checkSwitchSnapshot",{enumerable:!0,configurable:!0,writable:!0,value:function(){var e,t,r,n,i,a,s=o.track.getMediaStreamTrack(),c="live"===(null==s?void 0:s.readyState)&&(null==s?void 0:s.enabled)&&!(null!=s&&s.muted);c===o.lastCheckResult.msTrackPlayable&&o.isPlayerPlaying()===o.lastCheckResult.elPlaying||logger$5.info("rtcTrackId=".concat(o.track.getTrackId()," play change trackPlayable=").concat(c," isPlaying=").concat(o.isPlayerPlaying()),{msTrackReadyState:null==s?void 0:s.readyState,msTrackEnabled:null==s?void 0:s.enabled,msTrackMuted:null==s?void 0:s.muted,elCurrentTime:null===(e=o.mediaEl)||void 0===e?void 0:e.currentTime,elPaused:null===(t=o.mediaEl)||void 0===t?void 0:t.paused,elEnded:null===(r=o.mediaEl)||void 0===r?void 0:r.ended,elReadyState:null===(n=o.mediaEl)||void 0===n?void 0:n.readyState});(o.lastCheckResult={msTrackPlayable:c,elPlaying:o.isPlayerPlaying()},clientConfig._holdVideoLastFrame)&&(c&&(null===(i=o.mediaEl)||void 0===i||null===(i=i.srcObject)||void 0===i||null===(a=i.getVideoTracks)||void 0===a||null===(a=a.call(i))||void 0===a?void 0:a[0])!==s?o.switchOriginVideo():c||o.mediaEl.srcObject===o.snapshotMediaStream||o.switchSnapshot())}}),Object.defineProperty(this,"startCheckPlayState",{enumerable:!0,configurable:!0,writable:!0,value:function(){"video"===o.track.trackMediaType&&(logger$5.info("startCheckPlayState trackid=",o.track.getTrackId()),o.snapshotInterval=setInterval(o.snapshot,300),o.checkSwitchSnapshotInterval=setInterval(o.checkSwitchSnapshot,150))}}),Object.defineProperty(this,"stopCheckPlayState",{enumerable:!0,configurable:!0,writable:!0,value:function(){var e,t;logger$5.info("stopCheckPlayState trackid=",null===(e=o.track)||void 0===e||null===(t=e.getTrackId)||void 0===t?void 0:t.call(e)),clearInterval(o.snapshotInterval),clearInterval(o.checkSwitchSnapshotInterval)}}),Object.defineProperty(this,"playVideo",{enumerable:!0,configurable:!0,writable:!0,value:function(){var e;logger$5.info("playVideo",o.track.getTrackId(),null===(e=o.mediaWrapperEl)||void 0===e?void 0:e.getAttribute(RTC_SDK_PLAYER_CONTAINER_LABEL_ATTR_NAME)),o.mediaWrapperEl.appendChild(o.mediaEl),o.mediaEl.pause();var t=o.track.sfuStream||new MediaStream([o.track.getMediaStreamTrack()]);o.mediaEl.srcObject=t,o.mediaEl.play().catch(function(e){var t,r;"AbortError"!==e.name&&logger$5.error("play video error trackid=",null===(t=o.track)||void 0===t||null===(r=t.getTrackId)||void 0===r?void 0:r.call(t),tryJsonStringify(e))}),o.stopCheckPlayState(),o.startCheckPlayState()}}),Object.defineProperty(this,"playAudio",{enumerable:!0,configurable:!0,writable:!0,value:function(){var e=o.track.sfuStream||new MediaStream([o.track.getMediaStreamTrack()]);o.mediaEl.srcObject=e,o.mediaEl.play().catch(function(e){var t,r;"AbortError"!==e.name&&logger$5.error("play audio error trackid=",null===(t=o.track)||void 0===t||null===(r=t.getTrackId)||void 0===r?void 0:r.call(t),tryJsonStringify(e))}),o.stopCheckPlayState(),o.startCheckPlayState()}}),Object.defineProperty(this,"stopPlay",{enumerable:!0,configurable:!0,writable:!0,value:function(){var e,t;if(logger$5.info("stopPlay",o.track.getTrackId(),null===(e=o.mediaWrapperEl)||void 0===e?void 0:e.getAttribute(RTC_SDK_PLAYER_CONTAINER_LABEL_ATTR_NAME)),o.stopCheckPlayState(),o.mediaEl&&o.track){var r,n;if(o.mediaEl.pause(),null!==(t=o.mediaWrapperEl)&&void 0!==t&&t.contains(o.mediaEl))null===(r=o.mediaWrapperEl)||void 0===r||null===(n=r.removeChild)||void 0===n||n.call(r,o.mediaEl);o.mediaEl.srcObject=null,o.canvas=null,"audio"===o.track.trackMediaType?audioElementPool.pushElement(o.mediaEl):videoElementPool.pushElement(o.mediaEl)}}}),Object.defineProperty(this,"switchSnapshot",{enumerable:!0,configurable:!0,writable:!0,value:function(){logger$5.info("switchSnapshot trackid",o.track.getTrackId()),o.mediaEl.srcObject=o.snapshotMediaStream,o.mediaEl.play().catch(function(e){logger$5.info("snapshot play error, trackid",o.track.getTrackId(),tryJsonStringify(e))})}}),Object.defineProperty(this,"switchOriginVideo",{enumerable:!0,configurable:!0,writable:!0,value:function(){setTimeout(function(){var e,t,r=o.track.getMediaStreamTrack();if("live"===(null==r?void 0:r.readyState)&&(null==r?void 0:r.enabled)&&!(null!=r&&r.muted)&&(null===(e=o.mediaEl)||void 0===e||null===(e=e.srcObject)||void 0===e||null===(t=e.getVideoTracks)||void 0===t||null===(t=t.call(e))||void 0===t?void 0:t[0])!==r){logger$5.info("switchOriginVideo trackid",o.track.getTrackId());var n=o.track.sfuStream||new MediaStream([o.track.getMediaStreamTrack()]);o.mediaEl.srcObject=n,o.mediaEl.play().catch(function(e){logger$5.info("switchOriginVideo play error, trackid",o.track.getTrackId(),tryJsonStringify(e))})}},1e3)}}),this.mediaWrapperEl=i,this.mediaWrapperEl&&!this.mediaWrapperEl.getAttribute(RTC_SDK_PLAYER_CONTAINER_LABEL_ATTR_NAME)&&this.mediaWrapperEl.setAttribute(RTC_SDK_PLAYER_CONTAINER_LABEL_ATTR_NAME,"container_".concat(e.containerRtcLabelAcc++)),this.track=t,this.playerConfig=r,this.mediaEl=n,this.mediaEl.setAttribute(RTC_SDK_EL_DATA_ATTR_NAME,this.track.getTrackId()),this.canvas=document.createElement("canvas"),this.canvas.setAttribute(RTC_SDK_EL_DATA_ATTR_NAME,this.track.getTrackId()),this.snapshotMediaStream=this.canvas.captureStream(4)});Object.defineProperty(PlayController,"containerRtcLabelAcc",{enumerable:!0,configurable:!0,writable:!0,value:0});var PlayerManager=function(){return _createClass$1(function e(){_classCallCheck$1(this,e),Object.defineProperty(this,"playControllerArr",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.playControllerArr=[]},[{key:"getElement",value:function(e){return this.playControllerArr.filter(function(t){var r;return(null===(r=t.track)||void 0===r?void 0:r.getTrackId())===e.getTrackId()}).map(function(e){return e.mediaEl})}},{key:"getPlayCtrls",value:function(e){return this.playControllerArr.filter(function(t){var r;return(null===(r=t.track)||void 0===r?void 0:r.getTrackId())===e.getTrackId()})}},{key:"play",value:function(e,t,r){var n,i=this;logger$5.info("call play",e.getTrackId(),t instanceof HTMLElement?t.tagName:t,r);var o=e.getTrackId(),a=e.sfuStream||new MediaStream([e.getMediaStreamTrack()]);if("video"===e.trackMediaType){var s,c=this.findDom(t);if(!c)throw new DingRTCError(ErrorCode.InvaildArgument,"wrapper dom not found");var u=r||{},l=u.mirror,d=u.fit;if((n=this.playControllerArr.find(function(e){return e.mediaWrapperEl===c}))&&(null===(s=n.track)||void 0===s?void 0:s.getTrackId())!==(null==e?void 0:e.getTrackId()))return this.stopPlay(n.track,t),void this.play(e,t,r);if(n)n.mediaEl.pause(),!e.sourceMirror!=!l?n.mediaEl.style.transform="scaleX(-1)":n.mediaEl.style.transform="",d&&(n.mediaEl.style.objectFit=d),n.mediaEl.srcObject=a,n.mediaEl.play().catch(function(e){var t,r;"AbortError"!==e.name&&logger$5.error("play video error trackid=",null===(t=n.track)||void 0===t||null===(r=t.getTrackId)||void 0===r?void 0:r.call(t),tryJsonStringify(e))});else{var p,f=null===(p=this.getPlayCtrls(e))||void 0===p?void 0:p.length;if(f>3){var h,g=["DingRTC WARN: possible memory leak. More than 3 HTMLElement containers are playing the same track.","Please call track.stop to stop playing HTMLElements that will unmount in DOM.","TrackId:",e.getTrackId()];(h=console).warn.apply(h,g),logger$5.info.apply(logger$5,g.concat([f]))}n=new PlayController(e,r,getVideoElementPool().popElement(),c),setVideoElementStyle(n.mediaEl,{mirror:!e.sourceMirror!=!l,fit:d}),n.playVideo(),this.playControllerArr.push(n)}}else(n=this.playControllerArr.find(function(t){var r;return(null===(r=t.track)||void 0===r?void 0:r.getTrackId())===e.getTrackId()}))?(n.mediaEl.pause(),n.mediaEl.srcObject=a,logger$5.info("element loaded",e.getTrackId()),n.mediaEl.load()):((n=new PlayController(e,null,getAudioElementPool().popElement(),null)).playAudio(),this.playControllerArr.push(n));n.mediaEl.paused&&n.mediaEl.play().catch(function(e){"NotAllowedError"===e.name?(logger$5.error("autoplay failed",tryJsonStringify(e)),EventBus.emit("autoplay-failed",i)):"AbortError"!==e.name&&logger$5.warn("".concat(o," play error"),tryJsonStringify(e))})}},{key:"isPlaying",value:function(e){return this.playControllerArr.filter(function(t){var r;return(null===(r=t.track)||void 0===r?void 0:r.getTrackId())===(null==e?void 0:e.getTrackId())}).some(function(e){return e.isPlayerPlaying()})}},{key:"stopPlay",value:function(e,t){var r;logger$5.info("call stop play",e.getTrackId());var n=this.findDom(t),i=this.playControllerArr.filter(function(r){var i;return(null===(i=r.track)||void 0===i?void 0:i.getTrackId())===(null==e?void 0:e.getTrackId())&&(!t||r.mediaWrapperEl===n)});if(i.length){i.forEach(function(e){e.stopPlay()});var o=this.playControllerArr.filter(function(e){return!i.includes(e)});(r=this.playControllerArr).splice.apply(r,[0,this.playControllerArr.length].concat(_toConsumableArray(o)))}}},{key:"findDom",value:function(e){if(!e)return null;var t="string"==typeof e?document.querySelector(e):e;return document.contains(t)?t:null}}])}(),playerMgr$2=new PlayerManager,getPlayerManager=function(){return playerMgr$2};function _callSuper$k(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$k()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$k(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$k=function(){return!!e})()}function _superPropGet$4(e,t,r,n){var i=_get(_getPrototypeOf$1(e.prototype),t,r);return 2&n&&"function"==typeof i?function(e){return i.apply(r,e)}:i}window.playerMgr=playerMgr$2;var reporter=getReporter(),trace=reporter.trace,logger$4=reporter.getLoggerWithPrefix("[rtc-track]"),simpleLogger$2=logger$4,playerManager=getPlayerManager(),Track=function(e){function t(e,r){var n;return _classCallCheck$1(this,t),n=_callSuper$k(this,t),Object.defineProperty(n,"trackMediaType",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"source",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"logger",{enumerable:!0,configurable:!0,writable:!0,value:trace}),Object.defineProperty(n,"sourceNode",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"analyser",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"trackSettings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"sfuStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"mediaStreamTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"trackId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"sourceMirror",{enumerable:!0,configurable:!0,writable:!0,value:!1}),e?(n.trackMediaType=e.kind,n.trackSettings=e.getSettings()):r&&(n.trackMediaType="audio"),"audio"===n.trackMediaType&&(n.analyser=getAudioContext().createAnalyser()),n.trackId="".concat(n.trackMediaType,"_").concat(createUuid(6)),n.setMediaStreamTrack(e,r),n}return _inherits$1(t,e),_createClass$1(t,[{key:"isPlaying",get:function(){return playerManager.isPlaying(this)}},{key:"emit",value:function(e){for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];return logger$4.info("track emit event",e,null==n?void 0:n[0]),_superPropGet$4(t,"emit",this,3)([e].concat(n))}},{key:"getTrackId",value:function(){return this.trackId}},{key:"setMediaStreamTrack",value:function(e,t){var r=this,n=this.mediaStreamTrack;if(n&&(n.onended=null),e||t){var i;if(n&&e&&(e.enabled=n.enabled),"audio"===this.trackMediaType)if(this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),e)this.sourceNode=null===(i=getAudioContext())||void 0===i?void 0:i.createMediaStreamSource(new MediaStream([e]));else if(t){var o,a=mergeAudioTracks(t);this.sourceNode=null===(o=getAudioContext())||void 0===o?void 0:o.createMediaStreamSource(new MediaStream([a]))}e?(this.mediaStreamTrack=e,this.mediaStreamTrack.onended=function(){r.source===exports.VideoSourceInfo.SCREENCAST?r.logger.sendEvent("SCREEN_DEVICE_STOP"):r.source===exports.AudioSourceInfo.MIC?new DingRTCError(ErrorCode.MicInterrupt):r.source===exports.VideoSourceInfo.CAMERA&&new DingRTCError(ErrorCode.CameraInterrupt)}):t&&(this.sfuStream=t)}}},{key:"replaceTrack",value:function(e,t){simpleLogger$2.info("replaceTrack",e,t),t&&this.isPlaying&&this.stopPlay(),this.replaceTrackInner(e,null,!0)}},{key:"replaceTrackInner",value:function(e,t,r){this.setMediaStreamTrack(e,t),this.emit(TRACK_EVENT_NAME,"replace",this),this.innnerPlay({updated:!0})}},{key:"setSource",value:function(e){e===exports.VideoSourceInfo.CAMERA?this.logger.sendEvent("VIDEO_DEVICE_START"):e===exports.VideoSourceInfo.SCREENCAST?this.logger.sendEvent("SCREEN_DEVICE_START"):e===exports.AudioSourceInfo.MIC&&this.logger.sendEvent("AUDIO_DEVICE_START"),this.source=e}},{key:"stop",value:function(e){console.error("The API stop is deprecated. Use stopPlay to stop playing or use close to destroy mediaStream track"),simpleLogger$2.info("stop play track ".concat(this.getTrackId()),e instanceof HTMLElement?e.tagName:e),playerManager.stopPlay(this,e)}},{key:"stopPlay",value:function(e){simpleLogger$2.info("stop play track ".concat(this.getTrackId()),e instanceof HTMLElement?e.tagName:e),playerManager.stopPlay(this,e)}},{key:"innnerPlay",value:function(e){var t=this,r=e.mediaWrapperElement,n=e.config;e.updated?playerManager.getPlayCtrls(this).forEach(function(e){e.mediaWrapperEl?playerManager.findDom(e.mediaWrapperEl)?playerManager.play(t,e.mediaWrapperEl,e.playerConfig):playerManager.stopPlay(t,e.mediaWrapperEl):playerManager.play(t,e.mediaWrapperEl,e.playerConfig)}):playerManager.play(this,r,n);if("audio"===this.trackMediaType){var i=getAudioContext();"running"!==i.state&&simpleLogger$2.error("audioContext not running",i.state)}}},{key:"getMediaStreamTrack",value:function(){return this.mediaStreamTrack}}])}(EventEmitter);function _arrayWithHoles(e){if(Array.isArray(e))return e}function _iterableToArrayLimit(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,i,o,a,s=[],c=!0,u=!1;try{if(o=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;c=!1}else for(;!(c=(n=o.call(r)).done)&&(s.push(n.value),s.length!==t);c=!0);}catch(e){u=!0,i=e}finally{try{if(!c&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(u)throw i}}return s}}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _slicedToArray(e,t){return _arrayWithHoles(e)||_iterableToArrayLimit(e,t)||_unsupportedIterableToArray$d(e,t)||_nonIterableRest()}var is2K=function(e){return e.width>1920&&e.height>1080},simulcastEnabledFinally=function(e){var t;if(!e)return clientConfig.simulcast;var r=null===(t=e.getMediaStreamTrack())||void 0===t?void 0:t.getSettings(),n=(null==r?void 0:r.width)||e.trackSettings.width,i=(null==r?void 0:r.height)||e.trackSettings.height;return clientConfig.simulcast&&e.source===exports.VideoSourceInfo.CAMERA&&!is2K({width:n,height:i})},ResolutionProfile;function ownKeys$9(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function _objectSpread$9(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$9(Object(r),!0).forEach(function(t){_defineProperty(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$9(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}!function(e){e[e.LLD=0]="LLD",e[e.LD=1]="LD",e[e.SD=2]="SD",e[e.HD=3]="HD",e[e.FHD=4]="FHD",e[e.QHD=5]="QHD"}(ResolutionProfile||(ResolutionProfile={}));var ResolutionProfileMap=_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},ResolutionProfile.LLD,"lld"),ResolutionProfile.LD,"ld"),ResolutionProfile.SD,"sd"),ResolutionProfile.HD,"hd"),ResolutionProfile.FHD,"fhd"),ResolutionProfile.QHD,"qhd"),ResolutionRange={high:[2764800,4915200],QHD:[2764800,4915200],FHD:[1228800,2764800],HD:[307200,1228800],SD:[76800,307200],LD:[0,76800],low:[0,76800]},getResolutionLevel=function(e,t){var r={high:VideoProfileType.QHD,low:VideoProfileType.LD,QHD:VideoProfileType.QHD,FHD:VideoProfileType.FHD,HD:VideoProfileType.HD,SD:VideoProfileType.SD,LD:VideoProfileType.LD},n=r[e]||VideoProfileType.None,i=ResolutionRange[e],o=t[t.length-1].width*t[t.length-1].height;if(o<i[0]){var a=Object.entries(ResolutionRange).find(function(e){var t=_slicedToArray(e,2);t[0];var r=t[1];return o>r[0]&&o<=r[1]});n=r[_slicedToArray(a,1)[0]]}return n},calcResolutionInfo=function(e,t){return{resolution:getResolution(e,t),resolutionLevel:getResolutionLevel(e,t)}},getResoLevelNameByResoLevelNum=function(e){return{0:"LLD",1:"LD",2:"LD",4:"SD",8:"HD",16:"FHD",32:"QHD"}[e]},getResolution=function(e,t){var r=ResolutionRange[e],n=t.length,i=t[t.length-1];if(("FHD"===e||"high"===e)&&is2K(i))return i;if(t[0].width*t[0].height>ResolutionRange.FHD[1])return t[0];for(var o=0;n>o;o++){var a=t[o].width*t[o].height;if(a>=r[0]&&r[1]>=a)return t[o]}for(var s=n-1;s>=0;s--){var c=t[s].width*t[s].height;if(r[1]>c)return t[s]}return t[0]},DefaultVideoMaxPixelCount=[49152,76800,307200,1228800,2764800,4915200],DefaultMaxBitrateKbps=[200,350,1e3,1800,2828,5600],DefaultResolution_16_9=[[256,144],[320,180],[640,360],[1280,720],[1920,1080],[2560,1440]],DefaultResolution_4_3=[[256,192],[320,240],[640,480],[1280,960],[1920,1440],[2560,1920]],computeResoLevelName=function(e,t){var r=ResolutionProfile.FHD,n=e*t;return n<=DefaultVideoMaxPixelCount[ResolutionProfile.LLD]?r=ResolutionProfile.LLD:n<=DefaultVideoMaxPixelCount[ResolutionProfile.LD]?r=ResolutionProfile.LD:n<=DefaultVideoMaxPixelCount[ResolutionProfile.SD]?r=ResolutionProfile.SD:n<=DefaultVideoMaxPixelCount[ResolutionProfile.HD]?r=ResolutionProfile.HD:n<=DefaultVideoMaxPixelCount[ResolutionProfile.FHD]?r=ResolutionProfile.FHD:n<=DefaultVideoMaxPixelCount[ResolutionProfile.QHD]&&(r=ResolutionProfile.QHD),r},getTargetResolution=function(e,t,r,n){var i=0,o=0;if(n<=r)return[i=e,o=t];if(t>e){var a=[e,t];t=a[0],e=a[1]}if(16*t==9*e)i=DefaultResolution_16_9[r][0],o=DefaultResolution_16_9[r][1];else if(4*t==3*e)i=DefaultResolution_4_3[r][0],o=DefaultResolution_4_3[r][1];else{var s=Math.sqrt(1*DefaultResolution_16_9[r][0]*DefaultResolution_16_9[r][1]/e/t);s=1*(i=(i=Math.round(e*s))+15&-16)/e,o=Math.round(t*s)}return[i,o]},getVideoMaxbitrate=function(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(!n){var i=1;30!==r&&(i=Math.sqrt(r/30));var o=DefaultMaxBitrateKbps[computeResoLevelName(e,t)];n=Math.round(Math.max(i*o,50))}return n},getDownByScales=function(e,t){var r=computeResoLevelName(e,t),n=function(n){var i=_slicedToArray(getTargetResolution(e,t,n,r),2);i[0];var o=1/(i[1]/t);return Math.max(o,1)};return{ld:n(ResolutionProfile.LD),sd:n(ResolutionProfile.SD),fhd:n(r)}},getSimulcastSenderEncodings=function(e){var t=e.width,r=e.height,n=e.frameRate,i=e.maxBitrate,o=e.resolutionLevel,a=computeResoLevelName(t,r),s=[],c=a>=ResolutionProfile.HD?3:2,u=function(e){var o=_slicedToArray(getTargetResolution(t,r,e,a),2),s=o[0],c=o[1],u=DefaultMaxBitrateKbps[e]/DefaultMaxBitrateKbps[a],l=1/(c/r);return{targetWidth:s,rid:ResolutionProfileMap[e],targetHeight:c,minBitrate:50,maxFramerate:n,maxBitrate:Math.round(Math.max(30,i*u)),scaleResolutionDownBy:l}};a>ResolutionProfile.LLD&&s.push(_objectSpread$9({activeForBitrateMap:!1,activeForRealuse:Math.pow(2,ResolutionProfile.LLD)===o},u(ResolutionProfile.LLD))),a>ResolutionProfile.LD&&s.push(_objectSpread$9({activeForBitrateMap:c>1,activeForRealuse:Math.pow(2,ResolutionProfile.LD)===o},u(ResolutionProfile.LD))),a>ResolutionProfile.SD&&s.push(_objectSpread$9({activeForBitrateMap:c>2,activeForRealuse:Math.pow(2,ResolutionProfile.SD)===o},u(ResolutionProfile.SD))),a===ResolutionProfile.FHD?(s.push(_objectSpread$9({activeForBitrateMap:!1,activeForRealuse:!1},u(ResolutionProfile.HD))),s.push(_objectSpread$9({activeForBitrateMap:!0,activeForRealuse:clientConfig.republish?Math.pow(2,4)===o||o===Math.pow(2,3):Math.pow(2,4)===o},u(ResolutionProfile.FHD)))):s.push(_objectSpread$9({activeForBitrateMap:!0,activeForRealuse:Math.pow(2,a)===o},u(a)));for(var l=0,d=0;d<s.length;++d)0!=d&&(s[d].minBitrate=l),l=Math.round(Math.max((s[d].maxBitrate+s[d].minBitrate)/2,s[d].maxBitrate-400));return s.shift(),s},getHighestResoLevelNum=function(e,t){var r=computeResoLevelName(e,t);return Math.pow(2,r)},getSenderEncodingArrAndResoLevel=function(e){var t,r=e.getMaxBitrate(),n=null===(t=e.getMediaStreamTrack())||void 0===t?void 0:t.getSettings(),i=(null==n?void 0:n.width)||e.trackSettings.width,o=(null==n?void 0:n.height)||e.trackSettings.height,a=(null==n?void 0:n.frameRate)||e.trackSettings.frameRate,s=!simulcastEnabledFinally(e),c={resolutionLevel:getHighestResoLevelNum(i,o),encodings:[]};return s?c.encodings=[{maxFramerate:a,maxBitrate:r,scaleResolutionDownBy:1,activeForBitrateMap:!0,activeForRealuse:!0,rid:"",minBitrate:Math.round((r+30)/2),targetWidth:i,targetHeight:o}]:clientConfig.republish?c.encodings=getSimulcastSenderEncodings({width:1920,height:1080,frameRate:30,maxBitrate:getVideoMaxbitrate(1920,1080,30),resolutionLevel:c.resolutionLevel}):c.encodings=getSimulcastSenderEncodings({width:i,height:o,frameRate:a,maxBitrate:r,resolutionLevel:c.resolutionLevel}),c};function ownKeys$8(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function _objectSpread$8(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$8(Object(r),!0).forEach(function(t){_defineProperty(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$8(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function _callSuper$j(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$j()?Reflect.construct(t,r||[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$j(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$j=function(){return!!e})()}function _superPropGet$3(e,t,r,n){var i=_get(_getPrototypeOf$1(e.prototype),t,r);return 2&n&&"function"==typeof i?function(e){return i.apply(r,e)}:i}var playerMgr$1=getPlayerManager(),logger$3=getReporter().getLoggerWithPrefix("[rtc-localtrack]"),LocalTrack=function(e){function t(e){var r;if(_classCallCheck$1(this,t),r=_callSuper$j(this,t,[e]),Object.defineProperty(r,"muted",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"maxBitrate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"enabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"isClosed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),e){var n=e.muted;r.muted=n}return r.enabled=!0,r}return _inherits$1(t,e),_createClass$1(t,[{key:"setMediaStreamTrack",value:function(e){var r=this;_superPropGet$3(t,"setMediaStreamTrack",this,3)([e]),e&&(this.trackSettings=e.getSettings(),e.onended=function(){r.stopPlay(),r.close&&setTimeout(function(){return r.close()},200),r.emit("track-ended")})}},{key:"play",value:function(e,t){logger$3.info("play track ".concat(this.getTrackId()),(null==e?void 0:e.tagName)||e,t),this.innnerPlay({mediaWrapperElement:e,config:t})}},{key:"setEnabled",value:function(e){var t,r=this;return logger$3.info("setEnabled",e),this.isClosed?Promise.reject(new DingRTCError(ErrorCode.InvaildState)):(this.enabled=e,e?this.updateNewTrack().then(function(e){return r.emit(TRACK_EVENT_NAME,"unmute"),e}):(null===(t=this.mediaStreamTrack)||void 0===t||t.stop(),this.setMediaStreamTrack(null),this.source===exports.VideoSourceInfo.CAMERA?this.logger.sendEvent("VIDEO_DEVICE_STOP"):this.source===exports.VideoSourceInfo.SCREENCAST&&this.logger.sendEvent("SCREEN_DEVICE_STOP"),this.emit(TRACK_EVENT_NAME,"mute"),Promise.resolve()))}},{key:"close",value:function(){var e;logger$3.info("".concat(this.source," track:").concat(this.getTrackId()," close")),this.isClosed||(this.isClosed=!0,this.isPlaying&&this.stopPlay(),this.emit(TRACK_EVENT_NAME,"stop",this),null===(e=this.mediaStreamTrack)||void 0===e||e.stop(),this.setMediaStreamTrack(null),this.sourceNode=null,this.analyser=null,this.source===exports.VideoSourceInfo.CAMERA?this.logger.sendEvent("VIDEO_DEVICE_STOP"):this.source===exports.VideoSourceInfo.SCREENCAST&&this.logger.sendEvent("SCREEN_DEVICE_STOP"))}},{key:"setMuted",value:function(e){return logger$3.info("setMuted",e),this.isClosed?Promise.reject(new DingRTCError(ErrorCode.InvaildState)):(this.muted=e,this.mediaStreamTrack.enabled=!e,this.emit(TRACK_EVENT_NAME,e?"mute":"unmute"),Promise.resolve())}},{key:"getAudioTrack",value:function(){var e=this;return logger$3.debug("gengrate new audioTrack"),new Promise(function(t,r){var n;createMediaStream({audio:_objectSpread$8({source:e.source},e.config)}).then(function(e){n=e.getAudioTracks()[0]}).catch(function(e){try{var t=getAudioContext().createOscillator(),i=getAudioContext().createMediaStreamDestination();t.connect(i),n=i.stream.getAudioTracks()[0]}catch(t){logger$3.error("gengrate new audioTrack error",parseAudioDeviceError(e)),r(parseAudioDeviceError(e))}}).finally(function(){n&&t(n)})})}},{key:"getVideoTrack",value:function(){var e=this;return logger$3.info("gengrate new videoTrack",this.config),new Promise(function(t,r){var n,i=_objectSpread$8({source:e.source},e.config);e.config.facingMode&&e.config.deviceId&&(logger$3.info("ignore deviceId param to create videoTrack because facingMode is",e.config.facingMode),delete i.deviceId),createMediaStream({video:i,audio:!1}).then(function(e){n=e.getVideoTracks()[0],t(n)}).catch(function(e){logger$3.error("gengrate new videoTrack error",parseVideoDeviceError(e)),r(parseVideoDeviceError(e))})})}},{key:"updateNewTrack",value:function(){var e=this,t=this.getMediaStreamTrack();return t.onended=null,logger$3.info("stop oldTrack first"),t.stop(),"audio"===this.trackMediaType?this.getAudioTrack().then(function(t){return e.replaceTrackInner(t,null,!0),e.emit(TRACK_EVENT_NAME,"localMixedAudioReplaceTrack",e)}):"video"===this.trackMediaType?this.getVideoTrack().then(function(t){return e.replaceTrackInner(t,null,!0)}):void 0}},{key:"setDevice",value:(r=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n,i;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(logger$3.info("setDevice",t),!this.isClosed){e.next=1;break}return e.abrupt("return");case 1:if(!(this instanceof CameraVideoTrack)||"user"!==t&&"environment"!==t){e.next=2;break}this.config.facingMode=t,e.next=4;break;case 2:if((this.config.deviceId||(null===(r=this.mediaStreamTrack)||void 0===r||null===(r=r.getSettings())||void 0===r?void 0:r.deviceId)||(null===(n=this.mediaStreamTrack)||void 0===n||null===(i=n.getConstraints)||void 0===i||null===(i=i.call(n))||void 0===i?void 0:i.deviceId))!==t){e.next=3;break}return e.abrupt("return");case 3:this.config.deviceId=t;case 4:return e.abrupt("return",this.updateNewTrack());case 5:case"end":return e.stop()}},e,this)})),function(e){return r.apply(this,arguments)})},{key:"getTrackLabel",value:function(){if(logger$3.info("getTrackLabel"),!this.isClosed)return this.mediaStreamTrack.label}},{key:"getMaxBitrate",value:function(){if(!this.isClosed)return this.maxBitrate}}]);var r}(Track),LocalVideoTrack=function(e){function t(e,r){var n;if(_classCallCheck$1(this,t),(n=_callSuper$j(this,t,[e])).config=r,e){var i=e.getSettings(),o=i.width,a=i.height;n.maxBitrate=getVideoMaxbitrate(o,a,r.frameRate,r.maxBitrate)}return n}return _inherits$1(t,e),_createClass$1(t,[{key:"optimizationMode",get:function(){return this.config.optimizationMode}},{key:"setEncoderConfiguration",value:(r=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n,i,o,a,s,c,u,l,d,p,f,h,g;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(logger$3.info("videoTrack ".concat(this.getTrackId()," setEncoderConfiguration"),t),r=t.dimension,n=t.frameRate,i=t.maxBitrate,o=t.optimizationMode,a=t.mirror,!n||!Number.isNaN(n)){e.next=1;break}return e.abrupt("return",Promise.reject(new DingRTCError(ErrorCode.InvaildArgument,"invalid frameRate")));case 1:if(!r||VideoDimensions[r]){e.next=2;break}return e.abrupt("return",Promise.reject(new DingRTCError(ErrorCode.InvaildArgument,"invalid dimension")));case 2:if(!a!=!this.config.mirror&&(this.emit(TRACK_EVENT_NAME,"mirror",a),this.config.mirror=a),o&&o!==this.optimizationMode&&(this.config.optimizationMode=o,this.emit(TRACK_EVENT_NAME,"optimizationMode")),s=!1,r&&this.config.dimension!==r&&(this.config.dimension=r,s=!0),n&&this.config.frameRate!==Math.min(30,n)&&(this.config.frameRate=Math.min(30,n),s=!0),i&&this.maxBitrate!==i&&(s=!0),s){e.next=3;break}return e.abrupt("return",Promise.resolve());case 3:return c=_objectSpread$8({frameRate:this.config.frameRate},parseVideoDimension(this.config.dimension)),u=this.getMediaStreamTrack(),e.prev=4,e.next=5,null==u?void 0:u.applyConstraints(c);case 5:d=null===(l=this.getMediaStreamTrack())||void 0===l?void 0:l.getSettings(),p=d.width,f=d.height,this.maxBitrate=getVideoMaxbitrate(p,f,this.config.frameRate,i),logger$3.info("after applyConstraints",c,this.maxBitrate,getPlainMediaTrackInfo(u)),this.emit(TRACK_EVENT_NAME,"republish",this),e.next=7;break;case 6:throw e.prev=6,g=e.catch(4),h=parseVideoDeviceError(g),logger$3.error("videoTrack ".concat(this.getTrackId()," setEncoderConfiguration error"),h),h;case 7:case"end":return e.stop()}},e,this,[[4,6]])})),function(e){return r.apply(this,arguments)})},{key:"getCurrentFrameData",value:function(){return logger$3.info("getCurrentFrameData"),this.isClosed||!this.isPlaying?null:getCurrentFrame(playerMgr$1.getElement(this)[0])}},{key:"play",value:function(e,r){return logger$3.info("play track ".concat(this.getTrackId()),(null==e?void 0:e.tagName)||e,r),_superPropGet$3(t,"play",this,3)([e,r])}}]);var r}(LocalTrack),LocalAudioTrack=function(e){function t(e){return _classCallCheck$1(this,t),_callSuper$j(this,t,[e])}return _inherits$1(t,e),_createClass$1(t,[{key:"setVolume",value:function(e){logger$3.info("setVolume",e),this.isClosed||playerMgr$1.getElement(this)[0]&&(playerMgr$1.getElement(this)[0].volume=e)}},{key:"getVolume",value:function(){if(logger$3.info("getVolume"),!this.isClosed)return playerMgr$1.getElement(this)[0]?playerMgr$1.getElement(this)[0].volume:void 0}},{key:"getVolumeLevel",value:function(){return this.isClosed?0:getAudioVolumeLevel(this.analyser,this.sourceNode)}},{key:"play",value:function(){return logger$3.info("local audio play"),_superPropGet$3(t,"play",this,3)([])}},{key:"replaceTrack",value:function(e,t){logger$3.info("replaceTrack",e,t),t&&this.isPlaying&&this.stopPlay(),this.replaceTrackInner(e,null,!0),this.emit(TRACK_EVENT_NAME,"localMixedAudioReplaceTrack",this)}}])}(LocalTrack),CameraVideoTrack=function(e){function t(e,r){var n;return _classCallCheck$1(this,t),(n=_callSuper$j(this,t,[e,r])).setSource(exports.VideoSourceInfo.CAMERA),n}return _inherits$1(t,e),_createClass$1(t)}(LocalVideoTrack),MicrophoneAudioTrack=function(e){function t(e,r){var n;return _classCallCheck$1(this,t),(n=_callSuper$j(this,t,[e])).config=r,n.setSource(exports.AudioSourceInfo.MIC),n.analyser=getAudioContext().createAnalyser(),n}return _inherits$1(t,e),_createClass$1(t,[{key:"setVolume",value:function(e){logger$3.info("setVolume",e),this.isClosed||playerMgr$1.getElement(this)[0]&&(playerMgr$1.getElement(this)[0].volume=e)}},{key:"getVolume",value:function(){if(logger$3.info("getVolume"),!this.isClosed)return playerMgr$1.getElement(this)[0]?playerMgr$1.getElement(this)[0].volume:void 0}}])}(LocalAudioTrack),createMicrophoneAudioTrack=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n,i,o,a,s,c,u,l,d,p;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return logger$3.info("createMicrophoneAudioTrack",t),r={AEC:!0,AGC:!0,ANS:!0},i=(n=t||r).AEC,o=void 0===i||i,a=n.AGC,s=void 0===a||a,c=n.ANS,u=void 0===c||c,e.prev=1,e.next=2,createMediaStream({video:!1,audio:{deviceId:null==t?void 0:t.deviceId,source:exports.AudioSourceInfo.MIC,AEC:o,AGC:s,ANS:u}});case 2:return l=e.sent,d=l.getAudioTracks()[0],logger$3.info("MicrophoneAudioTrack created",getPlainMediaTrackInfo(d)),e.abrupt("return",new MicrophoneAudioTrack(d,Object.assign({},t,{AEC:o,AGC:s,ANS:u})));case 3:throw e.prev=3,p=e.catch(1),parseAudioDeviceError(p);case 4:case"end":return e.stop()}},e,null,[[1,3]])}));return function(t){return e.apply(this,arguments)}}(),createCameraVideoTrack=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n,i,o,a,s,c,u,l,d;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return logger$3.info("createCameraVideoTrack",t),r=t.deviceId,n=t.facingMode,i=t.dimension,o=void 0===i?"VD_640x480":i,a=t.optimizationMode,s=void 0===a?"balanced":a,c=Math.min(30,t.frameRate||15),e.prev=1,e.next=2,createMediaStream({video:{deviceId:r,source:exports.VideoSourceInfo.CAMERA,frameRate:c,dimension:o,facingMode:n},audio:!1});case 2:return u=e.sent,l=u.getVideoTracks()[0],logger$3.info("CameraVideoTrack created",getPlainMediaTrackInfo(l)),l.addEventListener("ended",function(){return logger$3.info("cam track ended",l.id)}),l.addEventListener("unmute",function(){return logger$3.info("cam track unmute",l.id)}),l.addEventListener("mute",function(){return logger$3.info("cam track mute",l.id)}),e.abrupt("return",new CameraVideoTrack(l,Object.assign({},t,{frameRate:c,dimension:o,optimizationMode:s})));case 3:throw e.prev=3,d=e.catch(1),parseVideoDeviceError(d);case 4:case"end":return e.stop()}},e,null,[[1,3]])}));return function(t){return e.apply(this,arguments)}}(),createScreenVideoTrack=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return logger$3.info("createScreenVideoTrack config",t),e.abrupt("return",_createScreenTracks(t,"noAudio"));case 1:case"end":return e.stop()}},e)}));return function(t){return e.apply(this,arguments)}}(),_createScreenTracks=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t,r){var n,i,o,a,s,c,u,l,d,p,f,h,g,m;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return logger$3.info("_createScreenVideoTrack",t,r),n=t.displaySurface,i=void 0===n?"monitor":n,o=t.dimension,a=void 0===o?"VD_1920x1080":o,s=t.optimizationMode,c=void 0===s?"detail":s,u=Math.min(t.frameRate||5,30),e.prev=1,e.next=2,createMediaStream({video:{source:exports.VideoSourceInfo.SCREENCAST,displaySurface:i,frameRate:u,dimension:a},audio:"withAudio"===r});case 2:return l=e.sent,p=l.getVideoTracks()[0],logger$3.info("ScreenVideoTrack created",getPlainMediaTrackInfo(p)),p.addEventListener("ended",function(){return logger$3.info("screen video track ended",p.id)}),p.addEventListener("unmute",function(){return logger$3.info("screen video track unmute",p.id)}),p.addEventListener("mute",function(){return logger$3.info("screen video track mute",p.id)}),(f=new LocalVideoTrack(p,Object.assign({},t,{frameRate:u,dimension:a,optimizationMode:c}))).setSource(exports.VideoSourceInfo.SCREENCAST),(g=null===(d=l.getAudioTracks())||void 0===d?void 0:d[0])&&((h=new LocalAudioTrack(g)).setSource(exports.AudioSourceInfo.SCREENCAST),logger$3.info("ScreenAudioTrack created",getPlainMediaTrackInfo(g)),g.addEventListener("ended",function(){return logger$3.info("screen audio track ended",g.id)}),g.addEventListener("unmute",function(){return logger$3.info("screen audio track unmute",g.id)}),g.addEventListener("mute",function(){return logger$3.info("screen audio track mute",g.id)})),e.abrupt("return",h?[f,h]:[f]);case 3:throw e.prev=3,m=e.catch(1),parseScreenShareError(m);case 4:case"end":return e.stop()}},e,null,[[1,3]])}));return function(t,r){return e.apply(this,arguments)}}(),createScreenVideoAndAudioTrack=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return logger$3.info("createScreenVideoAndAudioTrack",t),e.abrupt("return",_createScreenTracks(t,"withAudio"));case 1:case"end":return e.stop()}},e)}));return function(t){return e.apply(this,arguments)}}(),createMicrophoneAndCameraTracks=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t,r){var n,i,o,a,s,c,u,l,d,p,f,h,g,m,v,y,b,S,_,E,T;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return logger$3.info("createMicrophoneAndCameraTracks",t,r),n=Math.min(t.frameRate||15,30),i=t.deviceId,o=t.facingMode,a=t.dimension,s=void 0===a?"VD_640x480":a,c=t.optimizationMode,u=void 0===c?"balanced":c,l={AEC:!0,AGC:!0,ANS:!0},p=(d=r||l).AEC,f=void 0===p||p,h=d.AGC,g=void 0===h||h,m=d.ANS,v=void 0===m||m,e.prev=1,e.next=2,createMediaStream({video:{deviceId:i,source:exports.VideoSourceInfo.CAMERA,frameRate:n,dimension:s,facingMode:o},audio:{deviceId:null==r?void 0:r.deviceId,source:exports.AudioSourceInfo.MIC,AEC:f,AGC:g,ANS:v}});case 2:return y=e.sent,b=y.getVideoTracks()[0],S=y.getAudioTracks()[0],logger$3.info("CameraVideoTrack and MicrophoneTrack created",getPlainMediaStreamInfo(y)),b.addEventListener("ended",function(){return logger$3.info("cam track ended",b.id)}),b.addEventListener("unmute",function(){return logger$3.info("cam track unmute",b.id)}),b.addEventListener("mute",function(){return logger$3.info("cam track mute",b.id)}),S.addEventListener("ended",function(){return logger$3.info("mic track ended",S.id)}),S.addEventListener("unmute",function(){return logger$3.info("mic track unmute",S.id)}),S.addEventListener("mute",function(){return logger$3.info("mic track mute",S.id)}),_=new CameraVideoTrack(b,Object.assign({},t,{frameRate:n,dimension:s,optimizationMode:u})),E=new MicrophoneAudioTrack(S,Object.assign({},Object.assign({},r,{AEC:f,AGC:g,ANS:v}))),e.abrupt("return",[_,E]);case 3:throw e.prev=3,T=e.catch(1),parseVideoDeviceError(T);case 4:case"end":return e.stop()}},e,null,[[1,3]])}));return function(t,r){return e.apply(this,arguments)}}(),createCustomVideoTrack=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n,i,o,a,s,c,u,l,d=arguments;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(r=d.length>1&&void 0!==d[1]?d[1]:exports.VideoSourceInfo.CAMERA,logger$3.info("createCustomVideoTrack",t,r,getPlainMediaTrackInfo(t.mediaStreamTrack)),i=(n=t||{}).mediaStreamTrack,o=n.dimension,a=void 0===o?"VD_640x480":o,s=n.optimizationMode,c=void 0===s?"balanced":s,u=Math.min(t.frameRate||15,30),i instanceof MediaStreamTrack&&"video"===i.kind){e.next=1;break}throw new DingRTCError(ErrorCode.InvaildArgument,"missing video mediaStreamTrack");case 1:return logger$3.info("createCustomVideoTrack for",getPlainMediaTrackInfo(i)),i.addEventListener("ended",function(){return logger$3.info("custom video track ended",i.id)}),i.addEventListener("unmute",function(){return logger$3.info("custom video track unmute",i.id)}),i.addEventListener("mute",function(){return logger$3.info("custom video track mute",i.id)}),(l=new LocalVideoTrack(i,Object.assign({},t,{frameRate:u,dimension:a,optimizationMode:c}))).setSource(r),e.abrupt("return",l);case 2:case"end":return e.stop()}},e)}));return function(t){return e.apply(this,arguments)}}(),createCustomAudioTrack=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n,i,o=arguments;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(r=o.length>1&&void 0!==o[1]?o[1]:"mic",logger$3.info("createCustomAudioTrack",t,r,getPlainMediaTrackInfo(t.mediaStreamTrack)),(n=(t||{}).mediaStreamTrack)instanceof MediaStreamTrack&&"audio"===n.kind){e.next=1;break}throw new DingRTCError(ErrorCode.InvaildArgument,"missing audio mediaStreamTrack");case 1:return logger$3.info("createCustomAudioTrack succeed"),n.addEventListener("ended",function(){return logger$3.info("custom audio track ended",n.id)}),n.addEventListener("unmute",function(){return logger$3.info("custom audio track unmute",n.id)}),n.addEventListener("mute",function(){return logger$3.info("custom audio track mute",n.id)}),(i=new LocalAudioTrack(n)).setSource(r),e.abrupt("return",i);case 2:case"end":return e.stop()}},e)}));return function(t){return e.apply(this,arguments)}}();function _superPropGet$2(e,t,r,n){var i=_get(_getPrototypeOf$1(e.prototype),t,r);return 2&n&&"function"==typeof i?function(e){return i.apply(r,e)}:i}function _callSuper$i(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$i()?Reflect.construct(t,r||[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$i(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$i=function(){return!!e})()}var simpleLogger$1=getReporter().getLoggerWithPrefix("[rtc-remotetrack]"),playerMgr=getPlayerManager(),RemoteTrack=function(e){function t(e,r,n){var i;return _classCallCheck$1(this,t),i=_callSuper$i(this,t,[e,n]),Object.defineProperty(i,"userId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"subscription",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),i.userId=r,i}return _inherits$1(t,e),_createClass$1(t,[{key:"getUserId",value:function(){return simpleLogger$1.info("getUserId"),this.userId}},{key:"onFirstFrame",value:function(){this.emit("first-frame-decoded")}},{key:"attachSubscription",value:function(e){this.subscription&&this.subscription.off("audio-first-frame",this.onFirstFrame),this.subscription=e,null==e||e.on("audio-first-frame",this.onFirstFrame)}}])}(Track),RemoteAudioTrack=function(e){function t(e,r,n){var i;return _classCallCheck$1(this,t),i=_callSuper$i(this,t,[e,r,n]),Object.defineProperty(i,"deviceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),i.deviceId="",i}return _inherits$1(t,e),_createClass$1(t,[{key:"getMediaStreamTrack",value:function(){return clientConfig.audioSFU?mergeAudioTracks(this.sfuStream):_superPropGet$2(t,"getMediaStreamTrack",this,3)([])}},{key:"replaceStream",value:function(e,t){simpleLogger$1.info("replaceRemote Audio",e,t),t&&this.isPlaying&&this.stopPlay(),this.replaceTrackInner(null,e)}},{key:"setVolume",value:function(e){simpleLogger$1.info("setVolume",e),playerMgr.getElement(this)[0]&&(playerMgr.getElement(this)[0].volume=e)}},{key:"getVolume",value:function(){if(simpleLogger$1.info("getVolume"),playerMgr.getElement(this)[0])return playerMgr.getElement(this)[0].volume}},{key:"setSpeaker",value:function(e){var t=this;return simpleLogger$1.info("setSpeaker",e),new Promise(function(r,n){var i,o=playerMgr.getElement(t)[0];o||n(new DingRTCError(ErrorCode.InvaildState,"please playout audio first")),o.setSinkId||n(new DingRTCError(ErrorCode.SpeakerSetNotSupported)),null===(i=o.setSinkId)||void 0===i||i.call(o,e).then(function(){t.deviceId=e,r()}).catch(function(e){n(parseAudioDeviceError(e))})})}},{key:"getVolumeLevel",value:function(){return getAudioVolumeLevel(this.analyser,this.sourceNode)}},{key:"play",value:function(){return simpleLogger$1.info("remote audio play"),_superPropGet$2(t,"innnerPlay",this,3)([{}])}}])}(RemoteTrack),RemoteVideoTrack=function(e){function t(e,r){return _classCallCheck$1(this,t),_callSuper$i(this,t,[e,r])}return _inherits$1(t,e),_createClass$1(t,[{key:"play",value:function(e,r){return simpleLogger$1.info("remote video play",this.getTrackId()),_superPropGet$2(t,"innnerPlay",this,3)([{mediaWrapperElement:e,config:r}])}},{key:"setSourceMirror",value:function(e){e!==this.sourceMirror&&(simpleLogger$1.info("remote video track set Mirror",e),this.sourceMirror=e,this.isPlaying&&_superPropGet$2(t,"innnerPlay",this,3)([{updated:!0}]))}},{key:"getCurrentFrameData",value:function(){return simpleLogger$1.info("getCurrentFrameData"),this.isPlaying?getCurrentFrame(playerMgr.getElement(this)[0]):null}}])}(RemoteTrack),signal_msg;!function(e){var t,r,n,i,o,a,s,c;(t=e.DataType||(e.DataType={}))[t.DATA_TYPE_STREAM=0]="DATA_TYPE_STREAM",t[t.DATA_TYPE_PARTICIPANTS=1]="DATA_TYPE_PARTICIPANTS",t[t.DATA_TYPE_CONFERENCE=2]="DATA_TYPE_CONFERENCE",t[t.DATA_TYPE_GROUP_LIST=3]="DATA_TYPE_GROUP_LIST",t[t.DATA_TYPE_GROUP=4]="DATA_TYPE_GROUP",(r=e.OptType||(e.OptType={}))[r.OPT_TYPE_ADD=0]="OPT_TYPE_ADD",r[r.OPT_TYPE_REMOVE=1]="OPT_TYPE_REMOVE",r[r.OPT_TYPE_UPDATE=2]="OPT_TYPE_UPDATE",(n=e.SyncResponseCode||(e.SyncResponseCode={}))[n.SYNC_OK=0]="SYNC_OK",n[n.SYNC_PART_SUC=10]="SYNC_PART_SUC",n[n.SYNC_DATA_SIZE_LIMITED=11]="SYNC_DATA_SIZE_LIMITED",n[n.SYNC_NOT_SUPPORT_TYPE=12]="SYNC_NOT_SUPPORT_TYPE",n[n.SYNC_NOT_FOUND=13]="SYNC_NOT_FOUND",n[n.SYNC_CHANNEL_NOT_EXIST=14]="SYNC_CHANNEL_NOT_EXIST",n[n.SYNC_INTERNAL_ERROR=15]="SYNC_INTERNAL_ERROR",(i=e.GroupUpdate||(e.GroupUpdate={}))[i.GROUP_UPDATE_AUDIO_STREAM_LOST=0]="GROUP_UPDATE_AUDIO_STREAM_LOST",i[i.GROUP_UPDATE_AUDIO_STREAM_RECOVER=1]="GROUP_UPDATE_AUDIO_STREAM_RECOVER",i[i.GROUP_UPDATE_ADD_PARTICIPANTS=2]="GROUP_UPDATE_ADD_PARTICIPANTS",i[i.GROUP_UPDATE_REMOVE_PARTICIPANTS=3]="GROUP_UPDATE_REMOVE_PARTICIPANTS",i[i.GROUP_UPDATE_SET_PROPERTIES=4]="GROUP_UPDATE_SET_PROPERTIES",i[i.GROUP_UPDATE_REMOVE_PROPERTIES=5]="GROUP_UPDATE_REMOVE_PROPERTIES",(o=e.GroupListUpdate||(e.GroupListUpdate={}))[o.GROUP_LIST_UPDATE_ADD_ID=0]="GROUP_LIST_UPDATE_ADD_ID",o[o.GROUP_LIST_UPDATE_REMOVE_ID=1]="GROUP_LIST_UPDATE_REMOVE_ID",(a=e.LEAVE_GROUP_REASON_CODE||(e.LEAVE_GROUP_REASON_CODE={}))[a.NORMAL_LEAVE=0]="NORMAL_LEAVE",(s=e.DismissGroupReasonCode||(e.DismissGroupReasonCode={}))[s.NORMAL_DISMISS=0]="NORMAL_DISMISS",(c=e.Result||(e.Result={}))[c.Ok=0]="Ok",c[c.Error=1]="Error"}(signal_msg||(signal_msg={}));var options={syntax:"proto3"},nested={signal_msg:{nested:{AudioSsrcSpec:{fields:{ssrc:{type:"uint32",id:1},rtxSsrc:{type:"uint32",id:2}}},VideoSsrcSpec:{fields:{ssrc:{type:"uint32",id:1},rtxSsrc:{type:"uint32",id:2},fecSsrc:{type:"uint32",id:3}}},MultiPcAdaptRequestInfo:{fields:{audioSsrcSpec:{rule:"repeated",type:"AudioSsrcSpec",id:1},videoSsrcSpec:{rule:"repeated",type:"VideoSsrcSpec",id:2}}},AudioStreamFormat:{fields:{codec:{type:"string",id:1},sampleRate:{type:"int64",id:2},channelNum:{type:"int64",id:3}}},AudioFormatPreference:{fields:{preferred:{type:"AudioStreamFormat",id:1},optional:{rule:"repeated",type:"AudioStreamFormat",id:2}}},AudioStreamOptional:{fields:{format:{rule:"repeated",type:"AudioStreamFormat",id:1}}},VideoStreamFormat:{fields:{codec:{type:"string",id:1},profile:{type:"string",id:2}}},VideoFormatPreference:{fields:{preferred:{type:"VideoStreamFormat",id:1},optional:{rule:"repeated",type:"VideoStreamFormat",id:2}}},FormatPreference:{fields:{audio:{type:"AudioFormatPreference",id:1},video:{type:"VideoFormatPreference",id:2}}},Resolution:{fields:{width:{type:"uint32",id:1},height:{type:"uint32",id:2}}},VideoSsrcParameters:{fields:{ssrc:{type:"uint32",id:1},framerate:{type:"int32",id:2},resolution:{type:"Resolution",id:3},maxBitrate:{type:"int32",id:4},minBitrate:{type:"int32",id:5},active:{type:"bool",id:6},bitrate:{type:"int64",id:7},tlayer:{type:"int64",id:8},multiSlice:{type:"int64",id:9},keyFrameInterval:{type:"int64",id:10},constantPpsid:{type:"int64",id:11},rid:{type:"string",id:12}}},VideoParameters:{oneofs:{_resolutionLevel:{oneof:["resolutionLevel"]}},fields:{ssrc:{type:"uint32",id:1},resolution:{type:"Resolution",id:2},framerate:{type:"int32",id:3},bitrate:{type:"string",id:4},multiSlice:{type:"int32",id:5},keyFrameInterval:{type:"int64",id:6},constantPpsid:{type:"int64",id:7},resolutionLevel:{type:"uint32",id:8,options:{proto3_optional:!0}}}},GroupVersion:{fields:{id:{type:"string",id:1},ver:{type:"int64",id:2}}},StreamInfo:{fields:{type:{type:"string",id:1},owner:{type:"string",id:2},attributesJsonStr:{type:"string",id:3},label:{type:"string",id:4},createTime:{type:"int64",id:7}}},StreamVideoParameters:{fields:{resolution:{type:"Resolution",id:1},framerate:{type:"int64",id:2},bitrate:{type:"int64",id:3},keyFrameInterval:{type:"int64",id:4},multiSlice:{type:"int64",id:5},constantPpsid:{type:"int64",id:6}}},VideoStreamPara:{fields:{specs:{rule:"repeated",type:"string",id:1},resolution:{rule:"repeated",type:"Resolution",id:2},framerate:{rule:"repeated",type:"int32",id:3},bitrate:{rule:"repeated",type:"string",id:4},keyFrameInterval:{rule:"repeated",type:"int32",id:5}}},VideoStreamOptional:{fields:{format:{rule:"repeated",type:"VideoStreamFormat",id:1},parameters:{type:"VideoStreamPara",id:2}}},StreamAudioDesc:{fields:{trackId:{type:"string",id:1},msid:{type:"string",id:2},status:{type:"string",id:3},format:{type:"AudioStreamFormat",id:4},source:{type:"string",id:5},ssrc:{rule:"repeated",type:"uint32",id:6},ssrcGroup:{rule:"repeated",type:"AudioSsrcSpec",id:7},optional:{type:"AudioStreamOptional",id:8}}},StreamVideoDesc:{fields:{trackId:{type:"string",id:1},msid:{type:"string",id:2},status:{type:"string",id:3},source:{type:"string",id:4},format:{type:"VideoStreamFormat",id:5},ssrc:{rule:"repeated",type:"uint32",id:6},ssrcGroup:{rule:"repeated",type:"VideoSsrcSpec",id:7},parameters:{type:"StreamVideoParameters",id:8},optional:{type:"VideoStreamOptional",id:9},highestResolutionLevel:{type:"int32",id:10}}},StreamMediaDesc:{fields:{audio:{type:"StreamAudioDesc",id:1},video:{type:"StreamVideoDesc",id:2}}},Stream:{fields:{id:{type:"string",id:1},type:{type:"string",id:2},media:{type:"StreamMediaDesc",id:3},info:{type:"StreamInfo",id:4},version:{type:"int64",id:5}}},OriginMsg:{fields:{type:{type:"string",id:1},id:{type:"string",id:2}}},ErrorMsg:{fields:{id:{type:"string",id:1},code:{type:"int32",id:2},msg:{type:"string",id:3},origin:{type:"OriginMsg",id:4}}},ErrorMsgs:{fields:{globalStatus:{type:"string",id:1},detailStatus:{rule:"repeated",type:"ErrorMsg",id:2}}},DataType:{values:{DATA_TYPE_STREAM:0,DATA_TYPE_PARTICIPANTS:1,DATA_TYPE_CONFERENCE:2,DATA_TYPE_GROUP_LIST:3,DATA_TYPE_GROUP:4}},OptType:{values:{OPT_TYPE_ADD:0,OPT_TYPE_REMOVE:1,OPT_TYPE_UPDATE:2}},SyncResponseCode:{values:{SYNC_OK:0,SYNC_PART_SUC:10,SYNC_DATA_SIZE_LIMITED:11,SYNC_NOT_SUPPORT_TYPE:12,SYNC_NOT_FOUND:13,SYNC_CHANNEL_NOT_EXIST:14,SYNC_INTERNAL_ERROR:15}},GroupParticipant:{fields:{uid:{type:"string",id:1},pid:{type:"string",id:2},userData:{type:"string",id:3}}},GroupAudioInfo:{fields:{label:{type:"string",id:1},audio:{type:"Stream",id:2}}},GroupInfo:{fields:{id:{type:"string",id:1},ver:{type:"int64",id:2},participants:{rule:"repeated",type:"GroupParticipant",id:3},audioInfo:{type:"GroupAudioInfo",id:4},properties:{rule:"repeated",type:"GroupProperty",id:5}}},GroupProperty:{fields:{key:{type:"string",id:1},value:{type:"string",id:2}}},SyncFullData:{oneofs:{_ver:{oneof:["ver"]},_totalPages:{oneof:["totalPages"]},_pagingSeq:{oneof:["pagingSeq"]}},fields:{ver:{type:"int64",id:1,options:{proto3_optional:!0}},totalPages:{type:"int32",id:2,options:{proto3_optional:!0}},pagingSeq:{type:"int64",id:3,options:{proto3_optional:!0}},groupData:{type:"GroupPagingData",id:10},groupListData:{type:"GroupListPagingData",id:11}}},GroupPagingData:{fields:{pagingSeq:{type:"int64",id:1},curPage:{type:"int32",id:2},groupInfos:{rule:"repeated",type:"GroupInfo",id:3}}},GroupListPagingData:{fields:{pagingSeq:{type:"int64",id:1},curPage:{type:"int32",id:2},groupIds:{rule:"repeated",type:"string",id:3}}},SyncChangeLog:{fields:{groupListChangeLogs:{rule:"repeated",type:"GroupListChangeLog",id:1},groupChangeLogs:{rule:"repeated",type:"GroupChangeLog",id:2}}},SyncDataRequest:{oneofs:{_id:{oneof:["id"]}},fields:{type:{type:"DataType",id:1},id:{type:"string",id:2,options:{proto3_optional:!0}},ver:{type:"int64",id:3},forceFullSync:{type:"bool",id:4},supportPagingSync:{type:"bool",id:5}}},SyncDataResponse:{fields:{code:{type:"SyncResponseCode",id:1},errMsg:{type:"string",id:2},fullSync:{type:"SyncFullData",id:3},changeLogs:{rule:"repeated",type:"SyncChangeLog",id:4}}},SyncIds:{fields:{id:{type:"string",id:1},ver:{type:"int64",id:2}}},SyncDataByIdsRequest:{fields:{type:{type:"DataType",id:1},ids:{rule:"repeated",type:"SyncIds",id:2},forceFullSync:{type:"bool",id:3},supportPagingSync:{type:"bool",id:4}}},SyncDataByIdsResponse:{fields:{code:{type:"SyncResponseCode",id:1},errMsg:{type:"string",id:2},notFoundIds:{rule:"repeated",type:"string",id:3},fullSync:{type:"SyncFullData",id:4},changeLogs:{rule:"repeated",type:"SyncChangeLog",id:5}}},GroupUpdate:{values:{GROUP_UPDATE_AUDIO_STREAM_LOST:0,GROUP_UPDATE_AUDIO_STREAM_RECOVER:1,GROUP_UPDATE_ADD_PARTICIPANTS:2,GROUP_UPDATE_REMOVE_PARTICIPANTS:3,GROUP_UPDATE_SET_PROPERTIES:4,GROUP_UPDATE_REMOVE_PROPERTIES:5}},GroupUpdateOpt:{fields:{updateAction:{type:"GroupUpdate",id:1},participants:{rule:"repeated",type:"GroupParticipant",id:2},properties:{rule:"repeated",type:"GroupProperty",id:3}}},GroupChangeLog:{oneofs:{_groupInfo:{oneof:["groupInfo"]},_updateOpt:{oneof:["updateOpt"]},_msgId:{oneof:["msgId"]}},fields:{ver:{type:"int64",id:1},type:{type:"OptType",id:2},id:{type:"string",id:3},groupInfo:{type:"GroupInfo",id:4,options:{proto3_optional:!0}},updateOpt:{type:"GroupUpdateOpt",id:5,options:{proto3_optional:!0}},msgId:{type:"string",id:6,options:{proto3_optional:!0}}}},GroupListUpdate:{values:{GROUP_LIST_UPDATE_ADD_ID:0,GROUP_LIST_UPDATE_REMOVE_ID:1}},GroupListUpdateOpt:{fields:{updateAction:{type:"GroupListUpdate",id:1},id:{type:"string",id:2}}},GroupListChangeLog:{oneofs:{_msgId:{oneof:["msgId"]}},fields:{ver:{type:"int64",id:1},type:{type:"OptType",id:2},updateOpt:{type:"GroupListUpdateOpt",id:3},msgId:{type:"string",id:4,options:{proto3_optional:!0}}}},JoinGroupRequest:{fields:{groupId:{type:"string",id:1},userData:{type:"string",id:2},autoJoinGroupAudio:{type:"bool",id:3},autoLeaveChannelAudio:{type:"bool",id:4}}},JoinGroupResponse:{oneofs:{_joinGroupAudioSuccess:{oneof:["joinGroupAudioSuccess"]}},fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2},group:{type:"GroupInfo",id:3},joinGroupAudioSuccess:{type:"bool",id:4,options:{proto3_optional:!0}}}},LEAVE_GROUP_REASON_CODE:{values:{NORMAL_LEAVE:0}},LeaveGroupRequest:{fields:{groupId:{type:"string",id:1},reasonCode:{type:"LEAVE_GROUP_REASON_CODE",id:2},autoJoinChannelAudio:{type:"bool",id:3}}},LeaveGroupResponse:{oneofs:{_joinChannelAudioSuccess:{oneof:["joinChannelAudioSuccess"]}},fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2},joinChannelAudioSuccess:{type:"bool",id:3,options:{proto3_optional:!0}}}},DismissGroupReasonCode:{values:{NORMAL_DISMISS:0}},DismissGroupRequest:{fields:{groupId:{type:"string",id:1},reasonCode:{type:"DismissGroupReasonCode",id:2}}},DismissGroupResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}},ObserveAllGroupsRequest:{fields:{}},ObserveAllGroupsResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}},UnobserveAllGroupsRequest:{fields:{}},UnobserveAllGroupsResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}},SetGroupPropertiesRequest:{fields:{groupId:{type:"string",id:1},properties:{rule:"repeated",type:"GroupProperty",id:2}}},SetGroupPropertiesResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}},RemoveGroupPropertiesRequest:{fields:{groupId:{type:"string",id:1},keys:{rule:"repeated",type:"string",id:2}}},RemoveGroupPropertiesResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}},SetParticipantPropertiesRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},propertiesJsonStr:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},RemoveParticipantPropertiesRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},propertiesJsonStr:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},Result:{values:{Ok:0,Error:1}},Response:{oneofs:{data:{oneof:["reason","createPeerConnectionResponse","errorMsg","queryStreamsVerResponse","queryStreamsResponse","publishResponse","subscribeResponse","joinGroupResponse","leaveGroupResponse","dismissGroupResponse","observeAllGroupsResponse","unobserveAllGroupsResponse","syncDataResponse","syncDataByIdsResponse","setGroupPropertiesResponse","removeGroupPropertiesResponse"]}},fields:{result:{type:"Result",id:1},tid:{type:"string",id:2},traceId:{type:"string",id:3},code:{type:"int32",id:4},reason:{type:"string",id:11},createPeerConnectionResponse:{type:"CreatePeerConnectionResponse",id:15},errorMsg:{type:"ErrorMsgs",id:16},queryStreamsVerResponse:{type:"QueryStreamsVerResponse",id:17},queryStreamsResponse:{type:"QueryStreamsResponse",id:18},publishResponse:{type:"PublishResponse",id:21},subscribeResponse:{type:"SubscribeResponse",id:22},joinGroupResponse:{type:"JoinGroupResponse",id:24},leaveGroupResponse:{type:"LeaveGroupResponse",id:25},dismissGroupResponse:{type:"DismissGroupResponse",id:26},observeAllGroupsResponse:{type:"ObserveAllGroupsResponse",id:27},unobserveAllGroupsResponse:{type:"UnobserveAllGroupsResponse",id:28},syncDataResponse:{type:"SyncDataResponse",id:29},syncDataByIdsResponse:{type:"SyncDataByIdsResponse",id:30},setGroupPropertiesResponse:{type:"SetGroupPropertiesResponse",id:31},removeGroupPropertiesResponse:{type:"RemoveGroupPropertiesResponse",id:32}}},NotificationItem:{oneofs:{notification:{oneof:["streamNotification","serverFailoverNotification","progressNotification","groupNotification","groupListNotification"]}},fields:{event:{type:"string",id:1},streamNotification:{type:"StreamNotification",id:11},serverFailoverNotification:{type:"ServerFailoverNotification",id:13},progressNotification:{type:"ProgressNotification",id:14},groupNotification:{type:"GroupChangeLog",id:17},groupListNotification:{type:"GroupListChangeLog",id:18}}},BatchNotification:{fields:{notificationItem:{rule:"repeated",type:"NotificationItem",id:1},tid:{type:"string",id:2},traceId:{type:"string",id:3}}},MediaMessage:{fields:{payload:{type:"string",id:1}}},AudioStreamTrackDesc:{fields:{streamId:{type:"string",id:1},trackId:{type:"string",id:2},msid:{type:"string",id:3},source:{type:"string",id:4},uplinkSsrcGroup:{rule:"repeated",type:"AudioSsrcSpec",id:5},format:{type:"AudioStreamFormat",id:6},autoMix:{rule:"repeated",type:"string",id:7},attributesJsonString:{type:"string",id:8}}},VideoStreamTrackDesc:{fields:{streamId:{type:"string",id:1},trackId:{type:"string",id:2},msid:{type:"string",id:3},source:{type:"string",id:4},logicSsrc:{rule:"repeated",type:"uint32",id:5},uplinkSsrcGroup:{rule:"repeated",type:"VideoSsrcSpec",id:6},ssrcParameters:{rule:"repeated",type:"VideoSsrcParameters",id:7},streamParameters:{type:"VideoParameters",id:8},attributesJsonString:{type:"string",id:9},forwardOnly:{type:"bool",id:10},mid:{type:"string",id:11},highestResolutionLevel:{type:"int32",id:12}}},MediaStreamTrackDesc:{fields:{audio:{rule:"repeated",type:"AudioStreamTrackDesc",id:1},video:{rule:"repeated",type:"VideoStreamTrackDesc",id:2}}},StreamVersion:{fields:{streamId:{type:"string",id:1},streamVer:{type:"int64",id:2}}},StreamData:{fields:{id:{type:"string",id:1},stream:{type:"Stream",id:2}}},AudioPubOptions:{fields:{source:{type:"string",id:1},format:{type:"AudioStreamFormat",id:2},autoMix:{rule:"repeated",type:"string",id:3}}},VideoPubOptions:{fields:{source:{type:"string",id:1},format:{type:"VideoStreamFormat",id:2},parameters:{type:"VideoParameters",id:3},forwardOnly:{type:"bool",id:4}}},MediaPubOptionsSpecify:{fields:{audio:{type:"AudioPubOptions",id:1},video:{type:"VideoPubOptions",id:2}}},BatchPublishRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},type:{type:"string",id:4},simulcast:{type:"bool",id:5},simulcastVersion:{type:"string",id:6},supportTemporalLayer:{type:"bool",id:7},clientType:{type:"string",id:8},clientVersion:{type:"string",id:9},media:{type:"MediaStreamTrackDesc",id:10},event:{type:"string",id:11},tid:{type:"string",id:12},traceId:{type:"string",id:13}}},BatchUnpublishRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},audio:{rule:"repeated",type:"string",id:4},video:{rule:"repeated",type:"string",id:5},tid:{type:"string",id:6},traceId:{type:"string",id:7}}},QueryStreamsVerRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},streamIds:{rule:"repeated",type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},QueryStreamsVerResponse:{fields:{streamVersions:{rule:"repeated",type:"StreamVersion",id:1},totalVer:{type:"int32",id:2},msg:{type:"string",id:3}}},StreamControlRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},streamId:{type:"string",id:3},operation:{type:"string",id:4},data:{type:"string",id:5},tid:{type:"string",id:6},traceId:{type:"string",id:7},highestResolutionLevel:{type:"int32",id:8}}},QueryStreamsRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},streamIds:{rule:"repeated",type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},QueryStreamsResponse:{fields:{totalVer:{type:"int64",id:1},msg:{type:"string",id:2},streams:{rule:"repeated",type:"StreamData",id:3}}},SetStreamPropertiesRequest:{fields:{roomId:{type:"string",id:1},streamId:{type:"string",id:2},propertiesJsonStr:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},PublishRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},type:{type:"string",id:3},event:{type:"string",id:4},media:{type:"MediaPubOptionsSpecify",id:5},attributesJsonStr:{type:"string",id:6},tid:{type:"string",id:7},traceId:{type:"string",id:8}}},PublishResponse:{fields:{id:{type:"string",id:1}}},UnpublishRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},streamId:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},NetworkHealth:{fields:{receiving:{type:"bool",id:1},lossRate:{type:"int32",id:2},timestamp:{type:"int64",id:3},cutoff:{type:"bool",id:4},tid:{type:"string",id:5}}},StreamMsg:{oneofs:{value:{oneof:["networkHealth","streamStatus","stream","activeStream","propertiesJsonStr","highestResolutionLevel"]}},fields:{field:{type:"string",id:1},streamVer:{type:"int64",id:2},expiredMs:{type:"int64",id:3},extraValue:{rule:"repeated",type:"string",id:4},tid:{type:"string",id:5},networkHealth:{type:"NetworkHealth",id:10},streamStatus:{type:"string",id:11},stream:{type:"Stream",id:12},activeStream:{type:"string",id:13},propertiesJsonStr:{type:"string",id:14},highestResolutionLevel:{type:"int32",id:15}}},StreamNotification:{oneofs:{data:{oneof:["stream","msg"]}},fields:{streamId:{type:"string",id:1},status:{type:"string",id:2},totalVer:{type:"int64",id:3},msgId:{type:"string",id:4},ts:{type:"int64",id:5},tid:{type:"string",id:6},traceId:{type:"string",id:7},stream:{type:"Stream",id:10},msg:{type:"StreamMsg",id:11}}},Candidate:{fields:{candidate:{type:"string",id:1},sdpMlineIndex:{type:"int32",id:2},sdpMid:{type:"string",id:3}}},SessionSignaling:{fields:{type:{type:"string",id:1},sdp:{type:"string",id:2},candidate:{type:"Candidate",id:3},optionsJsonStr:{type:"string",id:4}}},SignalingData:{fields:{type:{type:"string",id:1},sdp:{type:"string",id:2}}},CreatePeerConnectionRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},tid:{type:"string",id:4},event:{type:"string",id:5},direction:{type:"string",id:6},sdpOffer:{type:"string",id:7},type:{type:"string",id:8},isOca:{type:"bool",id:9},isFailover:{type:"bool",id:10},multiPcAdaptInfo:{type:"MultiPcAdaptRequestInfo",id:11},pcFormatPreference:{type:"FormatPreference",id:12},optionsJsonStr:{type:"string",id:13},traceId:{type:"string",id:14},sfuSsrcGroup:{rule:"repeated",type:"AudioSsrcSpec",id:15}}},CreatePeerConnectionResponse:{fields:{connectionId:{type:"string",id:1},sdpAnswer:{type:"string",id:2}}},ClosePeerConnectionRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},direction:{type:"string",id:4},tid:{type:"string",id:5},traceId:{type:"string",id:6}}},SoacRequest:{fields:{id:{type:"string",id:1},signaling:{type:"SessionSignaling",id:2},tid:{type:"string",id:3},traceId:{type:"string",id:4}}},NotifyAction:{fields:{actionName:{type:"string",id:1},connectionId:{type:"string",id:2},traceId:{type:"string",id:3}}},ServerFailoverNotification:{fields:{actions:{rule:"repeated",type:"NotifyAction",id:1},msgId:{type:"string",id:2},tid:{type:"string",id:3},traceId:{type:"string",id:4}}},ProgressNotification:{fields:{id:{type:"string",id:1},status:{type:"string",id:2},data:{type:"SignalingData",id:3},msgId:{type:"string",id:4},tid:{type:"string",id:5},traceId:{type:"string",id:6}}},AudioBatchSubOptions:{fields:{subscriptionId:{type:"string",id:1},from:{type:"string",id:2},trackId:{type:"string",id:3},ssrcGroup:{rule:"repeated",type:"AudioSsrcSpec",id:4},format:{type:"AudioStreamFormat",id:5}}},VideoBatchSubOptions:{fields:{subscriptionId:{type:"string",id:1},from:{type:"string",id:2},trackId:{type:"string",id:3},ssrcGroup:{rule:"repeated",type:"VideoSsrcSpec",id:4},parameters:{type:"VideoParameters",id:5},format:{type:"VideoStreamFormat",id:6},subSsrcGroup:{type:"VideoSsrcSpec",id:7}}},MediaBatchSubOptions:{fields:{audio:{rule:"repeated",type:"AudioBatchSubOptions",id:1},video:{rule:"repeated",type:"VideoBatchSubOptions",id:2}}},Audio:{fields:{from:{type:"string",id:1}}},Video:{fields:{from:{type:"string",id:1},params:{type:"VideoParameters",id:2}}},MediaUpdateDesc:{fields:{audio:{type:"Audio",id:1},video:{type:"Video",id:2}}},AudioSubOptions:{fields:{from:{type:"string",id:1},format:{type:"AudioStreamFormat",id:2}}},VideoSubOptions:{fields:{from:{type:"string",id:1},format:{type:"VideoStreamFormat",id:2},parameters:{type:"VideoParameters",id:3}}},MediaSubOptionsSpecify:{fields:{audio:{type:"AudioSubOptions",id:1},video:{type:"VideoSubOptions",id:2}}},SubscribeRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},tid:{type:"string",id:3},event:{type:"string",id:4},media:{type:"MediaSubOptionsSpecify",id:5},type:{type:"string",id:6},propertiesJsonStr:{type:"string",id:7},traceId:{type:"string",id:8}}},SubscribeResponse:{fields:{id:{type:"string",id:1}}},UnsubscribeRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},subscriptionId:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},BatchSubscribeRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},supportTemporalLayer:{type:"bool",id:4},clientType:{type:"string",id:5},clientVersion:{type:"string",id:6},media:{type:"MediaBatchSubOptions",id:7},tid:{type:"string",id:8},type:{type:"string",id:9},event:{type:"string",id:10},propertiesJsonStr:{type:"string",id:11},traceId:{type:"string",id:12}}},BatchUnsubscribeRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},audio:{rule:"repeated",type:"string",id:4},video:{rule:"repeated",type:"string",id:5},tid:{type:"string",id:6},traceId:{type:"string",id:7}}},SubscriptionControlRequest:{oneofs:{data:{oneof:["updateDesc","track"]}},fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},subscriptionId:{type:"string",id:3},operation:{type:"string",id:4},updateDesc:{type:"MediaUpdateDesc",id:6},track:{type:"string",id:7},tid:{type:"string",id:8},traceId:{type:"string",id:9}}}}}},SIGNAL_PROTO={options:options,nested:nested},root=getProtobufRoot(SIGNAL_PROTO),Response=root.lookupType("signal_msg.Response"),BatchNotification=root.lookupType("signal_msg.BatchNotification"),MediaMessage=root.lookupType("signal_msg.MediaMessage"),StreamNotification=root.lookupType("signal_msg.StreamNotification");root.lookupType("signal_msg.ProgressNotification");var ServerFailoverNotification=root.lookupType("signal_msg.ServerFailoverNotification"),PublishRequest=root.lookupType("signal_msg.PublishRequest"),SoacRequest=root.lookupType("signal_msg.SoacRequest"),UnpublishRequest=root.lookupType("signal_msg.UnpublishRequest"),StreamControlRequest=root.lookupType("signal_msg.StreamControlRequest"),SubscribeRequest=root.lookupType("signal_msg.SubscribeRequest"),SetStreamPropertiesRequest=root.lookupType("signal_msg.SetStreamPropertiesRequest"),UnsubscribeRequest=root.lookupType("signal_msg.UnsubscribeRequest"),SubscriptionControlRequest=root.lookupType("signal_msg.SubscriptionControlRequest"),CreatePeerConnectionRequest=root.lookupType("signal_msg.CreatePeerConnectionRequest"),ClosePeerConnectionRequest=root.lookupType("signal_msg.ClosePeerConnectionRequest"),BatchPublishRequest=root.lookupType("signal_msg.BatchPublishRequest"),BatchUnpublishRequest=root.lookupType("signal_msg.BatchUnpublishRequest"),BatchSubscribeRequest=root.lookupType("signal_msg.BatchSubscribeRequest"),BatchUnsubscribeRequest=root.lookupType("signal_msg.BatchUnsubscribeRequest"),JoinGroupRequest=root.lookupType("signal_msg.JoinGroupRequest"),SetGroupPropertiesRequest=root.lookupType("signal_msg.SetGroupPropertiesRequest"),DismissGroupRequest=root.lookupType("signal_msg.DismissGroupRequest"),LeaveGroupRequest=root.lookupType("signal_msg.LeaveGroupRequest"),SyncDataRequest=root.lookupType("signal_msg.SyncDataRequest"),SyncDataByIdsRequest=root.lookupType("signal_msg.SyncDataByIdsRequest"),GroupChangeLog=root.lookupType("signal_msg.GroupChangeLog"),GroupListChangeLog=root.lookupType("signal_msg.GroupListChangeLog"),SetParticipantPropertiesRequest=root.lookupType("signal_msg.SetParticipantPropertiesRequest"),QueryStreamsVerRequest=root.lookupType("signal_msg.QueryStreamsVerRequest"),QueryStreamsRequest=root.lookupType("signal_msg.QueryStreamsRequest");function _callSuper$h(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$h()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$h(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$h=function(){return!!e})()}var RtcSignaling=function(e){function t(e){var r;return _classCallCheck$1(this,t),r=_callSuper$h(this,t),Object.defineProperty(r,"loggedIn",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"channel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"rpcId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.channel=e,r.rpcId=0,r.reporter=e.reporter,r.logger=r.reporter.getLoggerWithPrefix("[rtc-signal]"),r.handleBatchNotifyEvent=r.handleBatchNotifyEvent.bind(r),r.handleNotifyEvent=r.handleNotifyEvent.bind(r),r.handleConnectionStateChangeEvent=r.handleConnectionStateChangeEvent.bind(r),r.handleSyncEvent=r.handleSyncEvent.bind(r),r.handleUserEvent=r.handleUserEvent.bind(r),r.channel.on("connection-state-change",r.handleConnectionStateChangeEvent),r.channel.on("sync",r.handleSyncEvent),r.channel.on("batch-notify",r.handleBatchNotifyEvent),r.channel.on("notify",r.handleNotifyEvent),r.channel.on("user",r.handleUserEvent),r}return _inherits$1(t,e),_createClass$1(t,[{key:"join",value:function(e,t){return this.channel.join(e,t).then(function(e){return{joinResponse:e.joinResponse,iceConfig:e.iceConfig}})}},{key:"leave",value:function(){return this.channel.leave()}},{key:"handleUserEvent",value:function(e,t){this.emit("user",e,t)}},{key:"handleSyncEvent",value:function(e){this.emit("sync",e)}},{key:"handleConnectionStateChangeEvent",value:function(e,t,r){this.emit("connection-state-change",e,t,r)}},{key:"handleNotifyEvent",value:function(e,t){"stream"===e?this.emit("stream",StreamNotification.decode(t)):"serverFailover"===e?this.emit("serverFailover",ServerFailoverNotification.decode(t)):"media-message"===e?this.emit("media-message",MediaMessage.decode(t)):"group"===e?this.emit("group",GroupChangeLog.decode(t)):"group-list"===e&&this.emit("group-list",GroupListChangeLog.decode(t))}},{key:"handleBatchNotifyEvent",value:function(e){var t=this;BatchNotification.decode(e).notificationItem.forEach(function(e){"stream"===e.event?t.emit("stream",e.streamNotification):"serverFailover"===e.event?t.emit("serverFailover",e.serverFailoverNotification):"group"===e.event?t.emit("group",e.groupNotification):"group-list"===e.event&&t.emit("group-list",e.groupListNotification)})}},{key:"createPeerConnection",value:function(e){var t=CreatePeerConnectionRequest.encode(e).finish();return this.rpc("create-peer-connection",t,e).then(function(e){return e.createPeerConnectionResponse})}},{key:"closePeerConnection",value:function(e){var t=ClosePeerConnectionRequest.encode(e).finish();return this.rpc("close-peer-connection",t,e)}},{key:"batchSubscribe",value:function(e){var t=BatchSubscribeRequest.encode(e).finish();return this.rpc("batch-subscribe",t,e).then(function(e){return e.errorMsg})}},{key:"setGroupProperties",value:function(e){var t=SetGroupPropertiesRequest.encode(e).finish();return this.rpc("set-group-properties",t,e).then(function(e){return e.setGroupPropertiesResponse})}},{key:"batchUnSubscribe",value:function(e){var t=BatchUnsubscribeRequest.encode(e).finish();return this.rpc("batch-unsubscribe",t,e)}},{key:"batchPublish",value:function(e){var t=BatchPublishRequest.encode(e).finish();return this.rpc("batch-publish",t,e).then(function(e){return e.errorMsg})}},{key:"batchUnPublish",value:function(e){var t=BatchUnpublishRequest.encode(e).finish();return this.rpc("batch-unpublish",t,e)}},{key:"publish",value:function(e){var t=PublishRequest.encode(e).finish();return this.rpc("publish",t,e).then(function(e){return e.publishResponse})}},{key:"setParticipantProperties",value:function(e){var t=SetParticipantPropertiesRequest.encode(e).finish();return this.rpc("set-participant-properties",t,e)}},{key:"soac",value:function(e){var t=SoacRequest.encode(e).finish();return this.rpc("soac",t,e)}},{key:"unpublish",value:function(e){var t=UnpublishRequest.encode(e).finish();return this.rpc("unpublish",t,e)}},{key:"streamControl",value:function(e){var t=StreamControlRequest.encode(e).finish();return this.rpc("stream-control",t,e)}},{key:"setStreamProperties",value:function(e){var t=SetStreamPropertiesRequest.encode(e).finish();return this.rpc("set-stream-properties",t,e)}},{key:"subscribe",value:function(e){var t=SubscribeRequest.encode(e).finish();return this.rpc("subscribe",t,e).then(function(e){return e.subscribeResponse})}},{key:"unsubscribe",value:function(e){var t=UnsubscribeRequest.encode(e).finish();return this.rpc("unsubscribe",t,e)}},{key:"subscriptionControl",value:function(e){var t=SubscriptionControlRequest.encode(e).finish();return this.rpc("subscription-control",t,e)}},{key:"getStreamsVer",value:function(e){var t=QueryStreamsVerRequest.encode(e).finish();return this.rpc("query-streams-ver",t,e).then(function(e){return e.queryStreamsVerResponse})}},{key:"getStreams",value:function(e){var t=QueryStreamsRequest.encode(e).finish();return this.rpc("query-streams",t,e).then(function(e){return e.queryStreamsResponse})}},{key:"joinGroup",value:function(e){var t=JoinGroupRequest.encode(e).finish();return this.rpc("join-group",t,e).then(function(e){return e.joinGroupResponse})}},{key:"leaveGroup",value:function(e){var t=LeaveGroupRequest.encode(e).finish();return this.rpc("leave-group",t,e).then(function(e){return e.leaveGroupResponse})}},{key:"dismissGroup",value:function(e){var t=DismissGroupRequest.encode(e).finish();return this.rpc("dismiss-group",t,e).then(function(e){return e.dismissGroupResponse})}},{key:"syncData",value:function(e){var t=SyncDataRequest.encode(e).finish();return this.rpc("sync-data",t,e).then(function(e){return e.syncDataResponse})}},{key:"syncDataByIds",value:function(e){var t=SyncDataByIdsRequest.encode(e).finish();return this.rpc("sync-data-by-ids",t,e).then(function(e){return e.syncDataByIdsResponse})}},{key:"observeAllGroups",value:function(){return this.rpc("observe-all-groups",null).then(function(e){return e.observeAllGroupsResponse})}},{key:"unobserveAllGroups",value:function(){return this.rpc("unobserve-all-groups",null).then(function(e){return e.unobserveAllGroupsResponse})}},{key:"rpc",value:function(e,t){var r=this,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0;return new Promise(function(i,o){var a=r.rpcId++;r.logger.info("rtc rpcId ".concat(a,":").concat(e," param"),n),r.channel.signaling.rpc(e,t,n).then(function(t){var n=Response.decode(t);n.code===signal_msg.Result.Ok?(r.logger.info("rtc rpcId ".concat(a,":").concat(e," result====>"),n),i(n)):(r.logger.error("rtc rpcId ".concat(a,":").concat(e," error====>"),n),o(n))}).catch(function(t){r.logger.error("rtc rpcId ".concat(a,":").concat(e," error====>"),t),o(t)})})}}])}(EventEmitter);function _callSuper$g(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$g()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$g(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$g=function(){return!!e})()}var Monitor=function(e){function t(){var e;_classCallCheck$1(this,t),e=_callSuper$g(this,t),Object.defineProperty(e,"interval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(e,"timer",{enumerable:!0,configurable:!0,writable:!0,value:void 0});var r=getReporter().statsConfig;return e.interval=(null==r?void 0:r.statsIntervalMs)||METRIC_STATS_INTERVAL,e.start(),e}return _inherits$1(t,e),_createClass$1(t,[{key:"start",value:function(){var e=this;this.stop(),this.makeReport&&this.makeReport(),this.timer=addTimer(function(){e.makeReport()},this.interval,"interval")}},{key:"stop",value:function(){this.timer&&(removeTimer(this.timer,"interval"),this.timer=null)}}])}(EventEmitter);function ownKeys$7(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function _objectSpread$7(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$7(Object(r),!0).forEach(function(t){_defineProperty(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$7(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function _createForOfIteratorHelper$b(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$b(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$b(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$b(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_arrayLikeToArray$b(e,t):void 0}}function _arrayLikeToArray$b(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _callSuper$f(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$f()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$f(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$f=function(){return!!e})()}var initAudioSendInfo={timestamp:0,audioLevel:0,bytesSent:0,packetsSent:0,packetsLost:0,roundTripTime:0},initVideoSendInfo={totalFramesSent:0,totalBytesSent:0,totalPacketsLost:0,totalPacketsSent:0,totalFramesEncoded:0,timestamp:0,totalQpSum:0,maxSendFrameHeight:0,maxSendFrameWidth:0,captureFrameHeight:0,captureFrameWidth:0,captureFramesPerSecond:0,sendFramesPerSecond:0,availableOutgoingBitrate:0,targetBitrate:0,roundTripTime:0,encodeFramesPerSecond:0,totalEncodedTime:0,trackStats:new Map},PublishMonitor=function(e){function t(e){var r;_classCallCheck$1(this,t),r=_callSuper$f(this,t),Object.defineProperty(r,"videoSendReport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"audioSendReport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"bweReport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"lastVideoSendInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"lastAudioSendInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"track",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"source",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"pc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"tranceiver",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"connection",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.connection=e.connection,r.pc=e.connection.pc;var n=e.tracks.filter(function(e){return"video"===e.trackMediaType})[0];return r.source=null==n?void 0:n.source,r.track=e.tracks[0],r.tranceiver=e.transceiver,r.lastVideoSendInfo=Object.assign({},initVideoSendInfo),r.videoSendReport={attr_bitrate:0,attr_capture_frames:0,attr_enc_average_elapsed_ms:0,attr_encode_qp_sim:"",attr_encoded_framerate_sim:"",attr_resolution_sim:"",attr_stream_options:"",attr_duration_ms:0},r.lastAudioSendInfo=Object.assign({},initAudioSendInfo),r.audioSendReport={attr_duration_ms:0,attr_bitrate:0},r.bweReport={attr_rtt:0,attr_lossrate:0,attr_reported_bitrate:0,attr_duration_ms:0},r}return _inherits$1(t,e),_createClass$1(t,[{key:"extractVideoMetrics",value:function(e){var t=this,r=Object.assign({source:this.source,trackStats:[]},initVideoSendInfo,this.connection.peerConnectionStats);if(r.timestamp=Date.now(),this.track){var n=this.track.getMediaStreamTrack().getSettings(),i=n.width,o=n.height,a=n.frameRate;r.captureFramesPerSecond=a===1/0?0:a||0,r.captureFrameWidth=i||0,r.captureFrameHeight=o||0}var s=new Map,c=getDeltaDurationInSeconds(r,this.lastVideoSendInfo);return e.forEach(function(e){if(/outboundrtp|outbound-rtp/i.test(e.type)){var n=s.get(e.ssrc)||{},i=t.lastVideoSendInfo.trackStats.get(e.ssrc)||{};if(n.sendFrameWidth=e.frameWidth||0,n.sendFrameHeight=e.frameHeight||0,n.framesSent=e.framesSent||0,n.framesEncoded=e.framesEncoded||0,n.targetBitrate=e.targetBitrate||0,n.qpSum=e.qpSum||0,n.bytesSent=e.bytesSent||0,n.packetsSent=e.packetsSent||0,n.packetsSentForLost=n.packetsSent||0,n.sentTimestamp=e.timestamp||0,n.totalEncodeTime=e.totalEncodeTime||0,n.keyFramesEncoded=e.keyFramesEncoded||0,n.firCount=e.firCount||0,n.pliCount=e.pliCount||0,n.retransmittedBytesSent=e.retransmittedBytesSent||0,n.retransmittedPacketsSent=e.retransmittedPacketsSent||0,n.qualityLimitationReason=e.qualityLimitationReason||"",n.web_powerEfficientEncoder=e.powerEfficientEncoder||"",n.web_encoderImplementation=e.encoderImplementation||"",n.web_qualityLimitationResolutionChanges=e.qualityLimitationResolutionChanges>=0?e.qualityLimitationResolutionChanges:-1,n.web_codecId=e.codecId||"",n.sendFramesPerSecond=e.framesPerSecond||0,n.sendFrameWidth>r.maxSendFrameWidth){if(r.maxSendFrameWidth=n.sendFrameWidth,!n.sendFramesPerSecond&&i){var o=getDelta(n.framesSent||n.framesEncoded,i.framesSent||i.framesEncoded);n.sendFramesPerSecond=Math.round(o/c)}if(n.framesEncoded){var a=getDelta(n.framesEncoded,null==i?void 0:i.framesEncoded);r.encodeFramesPerSecond=Math.round(a/c)}r.sendFramesPerSecond=n.sendFramesPerSecond}s.set(e.ssrc,n),r.targetBitrate=n.targetBitrate,r.totalBytesSent+=n.bytesSent,r.totalPacketsSent+=n.packetsSent,r.totalEncodedTime+=n.totalEncodeTime,r.totalFramesEncoded+=n.framesEncoded,r.totalFramesSent+=n.framesSent,r.totalQpSum+=n.qpSum,r.maxSendFrameHeight=Math.max(n.sendFrameHeight,r.maxSendFrameHeight),s.set(e.ssrc,n)}else if(/track/i.test(e.type)&&!1===e.remoteSource){if(Environment.isSafari()){var u=s.get(e.ssrc)||{};u.sendFrameHeight>0||(u.sendFrameWidth=e.frameWidth||0,u.sendFrameHeight=e.frameHeight||0),u.framesSent=e.framesSent||0,u.totalEncodeTime=e.totalEncodeTime||0,s.set(e.ssrc,u),r.totalFramesEncoded+=u.framesEncoded,r.totalEncodedTime+=u.totalEncodeTime,r.totalFramesSent+=u.framesSent,s.set(e.ssrc,u)}}else if(/remote-inbound-rtp/i.test(e.type)){var l=s.get(e.ssrc)||{},d=t.lastVideoSendInfo.trackStats.get(e.ssrc)||{};l.packetsLost=e.packetsLost||0,l.lostTimestamp=e.timestamp,r.totalPacketsLost+=l.packetsLost,l.packetsLost===(d.packetsLost||0)&&(l.packetsSentForLost=d.packetsSentForLost||0,l.lostTimestamp=d.lostTimestamp||0),s.set(e.ssrc,l)}}),r.trackStats=s,r}},{key:"getLayersMetricInfo",value:function(e){var t,r=[],n=_createForOfIteratorHelper$b(e.trackStats.entries());try{for(n.s();!(t=n.n()).done;){var i=_slicedToArray(t.value,2),o=i[0],a=i[1],s=this.lastVideoSendInfo.trackStats.get(o)||{},c=getDelta(a.framesSent,s.framesSent),u=getDelta(a.framesEncoded,s.framesEncoded),l=getDelta(a.keyFramesEncoded,s.keyFramesEncoded),d=getDelta(a.retransmittedBytesSent,s.retransmittedBytesSent),p=getDelta(a.retransmittedPacketsSent,s.retransmittedPacketsSent),f=getDelta(a.firCount,s.firCount),h=getDelta(a.pliCount,s.pliCount),g=getDelta(a.packetsSent,s.packetsSent),m=getDelta(a.packetsSentForLost,s.packetsSentForLost),v=getDelta(a.lostTimestamp,s.lostTimestamp),y=getDelta(a.sentTimestamp,s.sentTimestamp),b=getDelta(a.packetsLost,s.packetsLost),S=getDelta(a.totalEncodeTime,s.totalEncodeTime),_=getDelta(a.qpSum,s.qpSum),E=a.qualityLimitationReason,T=a.sendFrameWidth,R=_objectSpread$7(_objectSpread$7({sendFrameHeight:a.sendFrameHeight,sendFrameWidth:T,qualityLimitationReason:E,web_powerEfficientEncoder:a.web_powerEfficientEncoder,web_encoderImplementation:a.web_encoderImplementation,web_qualityLimitationResolutionChanges:a.web_qualityLimitationResolutionChanges,web_codecId:a.web_codecId},a),{},{deltaQbSum:_,deltaPacketsSent:g,deltaPacketsLost:b,deltaFramesSent:c,deltaTimestampForLost:v,deltaFramesEncoded:u,deltaKeyFramesEncoded:l,deltaFirCount:f,deltaEncodedTime:S,deltaPliCount:h,deltaTimestampForSent:y,deltaPacketsSentForLost:m,deltaRetransmittedBytesSent:d,deltaRetransmittedPacketsSent:p});r.push(R)}}catch(e){n.e(e)}finally{n.f()}return{tracksStatInfo:r,totalBytesSent:e.totalBytesSent,totalFramesEncoded:e.totalFramesEncoded||e.totalFramesSent,totalPacketsSent:e.totalPacketsSent,totalEncodedTime:e.totalEncodedTime,totalQpSum:e.totalQpSum,totalPacketsLost:e.totalPacketsLost}}},{key:"makeVideoReport",value:function(e,t){var r={attr_capture_frames:Math.round(e.captureFramesPerSecond),attr_stream_options:"audio:false/video:".concat(this.source,"/resolution:").concat(e.captureFrameWidth,"*").concat(e.captureFrameHeight,"/")};if(this.lastVideoSendInfo.timestamp){var n,i=this.getLayersMetricInfo(e),o=i.tracksStatInfo,a=i.totalBytesSent,s=i.totalFramesEncoded,c=i.totalEncodedTime;o.length>1&&(r.attr_stream_options+="sim:".concat(o.length,"/"));for(var u={attr_encoded_framerate_sim:[],attr_enc_key_frames_sim:[],attr_fir_count_sim:[],attr_pli_count_sim:[],attr_quality_limitation_reason_sim:[],web_powerEfficientEncoder_sim:[],web_encoderImplementation_sim:[],web_qualityLimitationResolutionChanges_sim:[],web_codecId_sim:[],attr_retx_bytes_sim:[],attr_retx_packets_sim:[],attr_resolution_sim:[],attr_encode_qp_sim:[]},l=[],d=0,p=getDelta(e.timestamp,this.lastVideoSendInfo.timestamp),f=!0,h=0;h<o.length;h++){var g=o[h];u.attr_enc_key_frames_sim.push(g.deltaKeyFramesEncoded),u.attr_fir_count_sim.push(g.deltaFirCount),u.attr_pli_count_sim.push(g.deltaPliCount),u.attr_quality_limitation_reason_sim.push(g.qualityLimitationReason),u.web_powerEfficientEncoder_sim.push(g.web_powerEfficientEncoder),u.web_encoderImplementation_sim.push(g.web_encoderImplementation),u.web_qualityLimitationResolutionChanges_sim.push(g.web_qualityLimitationResolutionChanges),u.web_codecId_sim.push(g.web_codecId),u.attr_retx_bytes_sim.push(g.deltaRetransmittedBytesSent),u.attr_retx_packets_sim.push(g.deltaRetransmittedPacketsSent),u.attr_resolution_sim.push({count:g.deltaFramesSent||g.deltaFramesEncoded,index:h,resolution:"".concat(g.sendFrameWidth,"*").concat(g.sendFrameHeight)});var m=g.deltaFramesEncoded||g.deltaFramesSent;f&&(f=0===m),u.attr_encoded_framerate_sim.push(_defineProperty({},h,Math.round(1e3*m/p))),u.attr_encode_qp_sim.push(_defineProperty({},h,Math.round((g.deltaQbSum||0)/(m||Number.EPSILON))));var v=g.deltaTimestampForLost,y=g.deltaTimestampForSent,b=g.deltaPacketsLost,S=g.deltaPacketsSentForLost;if(b&&S&&v&&y){var _=b/v/(S/y);l.push(Math.max(Math.min(_,1),0))}}for(var E=0,T=Object.entries(u);E<T.length;E++){var R=_slicedToArray(T[E],2),C=R[0],k=R[1];r[C]=k.length?JSON.stringify(k):""}var P=0,w=getDelta(s,this.lastVideoSendInfo.totalFramesEncoded),O=getDelta(c,this.lastVideoSendInfo.totalEncodedTime);w&&O&&(P=Math.round(1e3*O/w));var I=getDelta(a,this.lastVideoSendInfo.totalBytesSent);r.attr_duration_ms=p,r.attr_bitrate=p>0?Math.min(Math.round(8*I*1e3/p),2e7):0,r.attr_enc_average_elapsed_ms=P,this.videoSendReport=r,f&&(r.attr_resolution_sim="null",r.attr_encoded_framerate_sim="null");var A={web_dtlsState:(null===(n=_toConsumableArray(t.values()).find(function(e){return"transport"===e.type}))||void 0===n?void 0:n.dtlsState)||""};this.emit("video-send-stream",Object.assign(A,this.videoSendReport)),l.length&&(d=Math.min(Math.round(l.reduce(function(e,t){return t+e},0)/l.length*255),255)),this.bweReport={attr_duration_ms:p,attr_rtt:Math.round(e.roundTripTime||0),attr_reported_bitrate:Math.max(0,Math.min(e.availableOutgoingBitrate||0,2e7)),attr_lossrate:d},this.emit("bwe",Object.assign({},this.bweReport))}this.lastVideoSendInfo=e}},{key:"extractAudioMetrics",value:function(e){var t=this,r=Object.assign({},initAudioSendInfo,this.connection.peerConnectionStats);return e.forEach(function(e){if(/outboundrtp|outbound-rtp/i.test(e.type)?(r.timestamp=e.timestamp,r.bytesSent=e.bytesSent||0,r.packetsSent=e.packetsSent):/remote-inbound-rtp|remoteinboundrt/i.test(e.type)?void 0!==e.packetsLost&&(r.packetsLost=e.packetsLost):/media-source/i.test(e.type)&&e.audioLevel&&(r.audioLevel=e.audioLevel),t.track){var n=t.track.getMediaStreamTrack().getSettings(),i=n.channelCount,o=n.sampleRate;r.channels=i,r.sampleRate=o}}),r}},{key:"makeAudioReport",value:function(e){this.lastAudioSendInfo.timestamp>0&&e.timestamp&&(this.audioSendReport={attr_duration_ms:Math.round(getDelta(e.timestamp,this.lastAudioSendInfo.timestamp)),attr_bitrate:Math.round(8*getDelta(e.bytesSent,this.lastAudioSendInfo.bytesSent)*1e3/getDelta(e.timestamp,this.lastAudioSendInfo.timestamp))},this.emit("audio-send-stream",Object.assign({},this.audioSendReport))),this.lastAudioSendInfo=e}},{key:"makeReport",value:function(){var e=this;this.getStats().then(function(t){null!=t&&t.audioMetrics&&e.makeAudioReport(t.audioMetrics),null!=t&&t.videoMetrics&&e.makeVideoReport(t.videoMetrics,t.originStats)})}},{key:"getStats",value:function(){var e,t,r=this,n=this.tranceiver,i=this.pc;if(!i||null==n||null===(e=n.sender)||void 0===e||!e.track)return Promise.resolve({});if(null==i||!i.getStats)throw new DingRTCError(ErrorCode.BrowserNotSupported,"getStats is not supported");return null===(t=this.pc.getStats(n.sender.track))||void 0===t?void 0:t.then(function(e){return{videoMetrics:r.source?r.extractVideoMetrics(e):void 0,audioMetrics:r.source?void 0:r.extractAudioMetrics(e),originStats:e}})}}])}(Monitor);function _createForOfIteratorHelper$a(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$a(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$a(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$a(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_arrayLikeToArray$a(e,t):void 0}}function _arrayLikeToArray$a(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _callSuper$e(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$e()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$e(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$e=function(){return!!e})()}function _superPropGet$1(e,t,r,n){var i=_get(_getPrototypeOf$1(e.prototype),t,r);return"function"==typeof i?function(e){return i.apply(r,e)}:i}var initAudioReceiveInfo={timestamp:0,packetsLost:0,packetsReceived:0,bytesReceived:0,audioLevel:0,decodingNormal:0,roundTripTime:0},initVideoReciveInfo={packetsLost:0,packetsReceived:0,framesDropped:0,frameHeight:0,frameWidth:0,framesDecoded:0,framesReceived:0,timestamp:0,framesPerSecond:0,bytesReceived:0,roundTripTime:0},SubscribeMonitor=function(e){function t(e){var r,n;_classCallCheck$1(this,t),n=_callSuper$e(this,t),Object.defineProperty(n,"videoReceiveReport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"audioReceiveReport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"lastVideoReceiveInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"lastAudioReceiveInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"source",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"firstReportFlag",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"firstReportTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"pc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"tranceiver",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"tranceivers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"connection",{enumerable:!0,configurable:!0,writable:!0,value:void 0});var i=e.connection,o=e.transceiver,a=e.uid,s=e.stream,c=e.transceivers;return n.connection=i,n.pc=i.pc,n.tranceiver=o,n.tranceivers=c,n.firstReportTimer=addTimer(function(){n.getStats().then(function(e){n.makeFirstReport(e)})},400,"interval"),n.source="mcu"!==a&&(null===(r=s.media)||void 0===r||null===(r=r.video)||void 0===r?void 0:r.source),n.videoReceiveReport={attr_duration_ms:0,attr_bitrate:0,attr_current_delay:0,attr_stream_options:"",attr_resolution:"",attr_dec_frames:0,attr_decode_qp:0,attr_fraction_lost:0,attr_network_framerate:0,attr_render_delay:0,attr_dec_key_frames:-1},n.lastVideoReceiveInfo=Object.assign({},initVideoReciveInfo),n.firstReportFlag={audioFirstPacket:!1,videoFirstPacket:!1,audioFirstFrame:!1},n.lastAudioReceiveInfo=Object.assign({},initAudioReceiveInfo),n.audioReceiveReport={attr_duration_ms:0,attr_delay_estimate:0,attr_bitrate:0},n}return _inherits$1(t,e),_createClass$1(t,[{key:"extractAudioMetrics",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=Object.assign({},initAudioReceiveInfo,this.connection.peerConnectionStats);return n.timestamp=Date.now(),e.forEach(function(e){e.isRemote||(/inboundrtp|inbound-rtp/i.test(e.type)?(n.bytesReceived=e.bytesReceived||0,n.packetsReceived=e.packetsReceived||0,r||(n.packetsLost===(t.lastAudioReceiveInfo.packetsLost||0)?n.packetsReceivedForLost=t.lastAudioReceiveInfo.packetsReceived||0:n.packetsReceivedForLost=n.packetsReceived||0),n.packetsLost=e.packetsLost||0,n.audioLevel=e.audioLevel||0,n.decodingNormal=Number(e.googDecodingNormal||0)):/track/i.test(e.type)&&(n.audioLevel=e.audioLevel))}),n}},{key:"extractMultipleAudioMetrics",value:function(e){var t=this,r=e.map(function(e){return t.extractAudioMetrics(e,!0)}),n=Object.assign({},initAudioReceiveInfo,this.connection.peerConnectionStats);n.timestamp=Date.now();var i,o=_createForOfIteratorHelper$a(r);try{for(o.s();!(i=o.n()).done;){var a=i.value;n.bytesReceived+=a.bytesReceived||0,n.packetsLost+=a.packetsLost||0,n.packetsReceived+=a.packetsReceived||0,n.audioLevel=Math.max(n.audioLevel,a.audioLevel||0),n.decodingNormal=Math.max(n.decodingNormal,a.decodingNormal||0)}}catch(e){o.e(e)}finally{o.f()}return n.packetsLost===(this.lastAudioReceiveInfo.packetsLost||0)?n.packetsReceivedForLost=this.lastAudioReceiveInfo.packetsReceived||0:n.packetsReceivedForLost=n.packetsReceived||0,n}},{key:"extractVideoMetrics",value:function(e){var t=this,r=Object.assign({source:this.source},initVideoReciveInfo,this.connection.peerConnectionStats);return r.timestamp=Date.now(),e.forEach(function(e){if(!e.isRemote)if(/inboundrtp|inbound-rtp/i.test(e.type))r.framesDecoded=e.framesDecoded,r.packetsReceived=e.packetsReceived||0,r.framesReceived=e.framesReceived,r.keyFramesDecoded=e.keyFramesDecoded||0,r.packetsLost=e.packetsLost||0,r.packetsLost===(t.lastVideoReceiveInfo.packetsLost||0)?r.packetsReceivedForLost=t.lastVideoReceiveInfo.packetsReceived||0:r.packetsReceivedForLost=r.packetsReceived||0,r.bytesReceived=e.bytesReceived||0,r.firCount=e.firCount||0,r.pliCount=e.pliCount||0,r.freezeCount=e.freezeCount||0,r.retransmittedBytesReceived=e.retransmittedBytesReceived||0,r.retransmittedPacketsReceived=e.retransmittedPacketsReceived||0,void 0!==e.frameHeight&&(r.frameWidth=e.frameWidth||0,r.frameHeight=e.frameHeight||0);else if(/track/i.test(e.type))r.frameWidth=e.frameWidth||0,r.frameHeight=e.frameHeight||0;else if(/codec/i.test(e.type)){var n;null!==(n=e.mimeType)&&void 0!==n&&n.includes("video")&&(r.sdpFmtpLine=e.sdpFmtpLine)}}),r}},{key:"makeAudioReport",value:function(e){if(this.lastAudioReceiveInfo.timestamp>0&&e.timestamp){var t=Math.round(getDelta(e.timestamp,this.lastAudioReceiveInfo.timestamp)),r=getDelta(e.packetsLost,this.lastAudioReceiveInfo.packetsLost),n=getDelta(e.packetsReceivedForLost,this.lastAudioReceiveInfo.packetsReceivedForLost),i=getDelta(e.bytesReceived,this.lastAudioReceiveInfo.bytesReceived),o=0;try{o=Math.max(r/n,0)}catch(e){o=0}isNaN(o)&&(o=0),this.audioReceiveReport={attr_delay_estimate:0,attr_duration_ms:t,attr_bitrate:Math.round(8*i/(t/1e3))},this.emit("audio-net-eq",{attr_speech_expand_rate:0,attr_duration_ms:this.audioReceiveReport.attr_duration_ms,attr_packet_lossrate:Math.round(Math.min(16384*o,16384))}),this.emit("audio-recv-stream",Object.assign({},this.audioReceiveReport))}this.lastAudioReceiveInfo=e}},{key:"makeVideoReport",value:function(e){var t=this.lastVideoReceiveInfo,r=t.firCount,n=t.pliCount,i=t.timestamp,o=t.freezeCount,a=t.packetsLost,s=t.framesDecoded,c=t.framesDropped,u=t.bytesReceived,l=t.packetsReceivedForLost,d=t.retransmittedBytesReceived,p=t.retransmittedPacketsReceived;if(i>0&&e.timestamp){var f=getDelta(e.timestamp,i);if(e.bytesReceived-u>=0){var h=getDelta(e.packetsLost,a),g=getDelta(e.packetsReceivedForLost,l),m=0;try{m=Math.round(h/g*255)}catch(e){m=0}isNaN(m)&&(m=0);var v=getDelta(e.framesDecoded,s);this.videoReceiveReport={attr_network_framerate:Math.round(1e3*v/f),attr_dec_frames:v,attr_dec_key_frames:e.keyFramesDecoded,attr_decode_qp:0,attr_render_delay:0,attr_current_delay:0,attr_dropped_count:getDelta(e.framesDropped,c),attr_fir_count:getDelta(e.firCount,r),attr_freeze_count:getDelta(e.freezeCount,o),attr_pli_count:getDelta(e.pliCount,n),attr_retx_bytes:getDelta(e.retransmittedBytesReceived,d),attr_retx_packets:getDelta(e.retransmittedPacketsReceived,p),attr_bitrate:Math.round(8*getDelta(e.bytesReceived,u)*1e3/f),attr_stream_options:"audio:false/video:".concat(this.source,"/resolution:").concat(e.frameWidth,"*").concat(e.frameHeight,"/"),attr_fraction_lost:Math.max(0,Math.min(m,255)),attr_resolution:JSON.stringify([{count:v,resolution:"".concat(e.frameWidth,"*").concat(e.frameHeight)}]),attr_duration_ms:Math.round(f)},this.emit("video-recv-stream",Object.assign({},this.videoReceiveReport))}}this.lastVideoReceiveInfo=e}},{key:"makeReport",value:function(){var e=this;this.getStats().then(function(t){t.audioMetrics&&e.makeAudioReport(t.audioMetrics),t.videoMetrics&&e.makeVideoReport(t.videoMetrics)})}},{key:"makeFirstReport",value:function(e){var t=this.firstReportFlag,r=t.audioFirstFrame,n=t.audioFirstPacket,i=t.videoFirstPacket,o=e.audioMetrics,a=e.videoMetrics;if(o&&a){if((r||-1===(null==o?void 0:o.decodingNormal))&&n&&i)return void(this.firstReportTimer&&(removeTimer(this.firstReportTimer,"interval"),this.firstReportTimer=null))}else if(o){if((r||-1===(null==o?void 0:o.decodingNormal))&&n)return void(this.firstReportTimer&&(removeTimer(this.firstReportTimer,"interval"),this.firstReportTimer=null))}else if(a&&i)return void(this.firstReportTimer&&(removeTimer(this.firstReportTimer,"interval"),this.firstReportTimer=null));null!=o&&o.packetsReceived&&!n&&(this.emit("audio-first-packet"),this.firstReportFlag.audioFirstPacket=!0),Number(null==o?void 0:o.decodingNormal)>0&&!r&&(this.emit("audio-first-frame"),this.firstReportFlag.audioFirstPacket=!0),null!=a&&a.packetsReceived&&!i&&(this.emit("video-first-packet"),this.firstReportFlag.videoFirstPacket=!0)}},{key:"getStats",value:function(){var e,t=this,r=this.tranceiver,n=this.tranceivers,i=this.pc;if(!(i&&(null!=n&&n.length||null!=r&&r.receiver.track)))return Promise.resolve({});if(null==i||!i.getStats)throw new DingRTCError(ErrorCode.BrowserNotSupported,"getStats is not supported");if(n&&n.length){var o=n.map(function(e){return e.receiver.track}).filter(function(e){return!!e});return Promise.all(o.map(function(e){return i.getStats(e)})).then(function(e){return{audioMetrics:t.extractMultipleAudioMetrics(e)}})}return null!=r&&null!==(e=r.receiver)&&void 0!==e&&e.track?i.getStats(r.receiver.track).then(function(e){return{videoMetrics:t.source?t.extractVideoMetrics(e):void 0,audioMetrics:t.source?void 0:t.extractAudioMetrics(e)}}):void 0}},{key:"stop",value:function(){_superPropGet$1(t,"stop",this)([]),this.firstReportTimer&&(removeTimer(this.firstReportTimer,"interval"),this.firstReportTimer=null)}}])}(Monitor),lib={},parser$1={},grammar$3={exports:{}},grammar$2=grammar$3.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(grammar$2).forEach(function(e){grammar$2[e].forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})});var grammarExports=grammar$3.exports;!function(e){var t=function(e){return String(Number(e))===e?Number(e):e},r=function(e,r,n){var i=e.name&&e.names;e.push&&!r[e.push]?r[e.push]=[]:i&&!r[e.name]&&(r[e.name]={});var o=e.push?{}:i?r[e.name]:r;!function(e,r,n,i){if(i&&!n)r[i]=t(e[1]);else for(var o=0;o<n.length;o+=1)null!=e[o+1]&&(r[n[o]]=t(e[o+1]))}(n.match(e.reg),o,e.names,e.name),e.push&&r[e.push].push(o)},n=grammarExports,i=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},o=[],a=t;return e.split(/(\r\n|\r|\n)/).filter(i).forEach(function(e){var t=e[0],i=e.slice(2);"m"===t&&(o.push({rtp:[],fmtp:[]}),a=o[o.length-1]);for(var s=0;s<(n[t]||[]).length;s+=1){var c=n[t][s];if(c.reg.test(i))return r(c,a,i)}}),t.media=o,t};var o=function(e,r){var n=r.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&r.length>1&&(e[n[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var r=[],n=e.split(" ").map(t),i=0;i<n.length;i+=3)r.push({component:n[i],ip:n[i+1],port:n[i+2]});return r},e.parseImageAttributes=function(e){return e.split(" ").map(function(e){return e.substring(1,e.length-1).split(",").reduce(o,{})})},e.parseSimulcastStreamList=function(e){return e.split(";").map(function(e){return e.split(",").map(function(e){var r,n=!1;return"~"!==e[0]?r=t(e):(r=t(e.substring(1,e.length)),n=!0),{scid:r,paused:n}})})}}(parser$1);var grammar$1=grammarExports,formatRegExp=/%[sdv%]/g,format=function(e){var t=1,r=arguments,n=r.length;return e.replace(formatRegExp,function(e){if(t>=n)return e;var i=r[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(i);case"%d":return Number(i);case"%v":return""}})},makeLine=function(e,t,r){var n=[e+"="+(t.format instanceof Function?t.format(t.push?r:r[t.name]):t.format)];if(t.names)for(var i=0;i<t.names.length;i+=1){var o=t.names[i];t.name?n.push(r[t.name][o]):n.push(r[t.names[i]])}else n.push(r[t.name]);return format.apply(null,n)},defaultOuterOrder=["v","o","s","i","u","e","p","c","b","t","r","z","a"],defaultInnerOrder=["i","c","b","a"],writer$1=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach(function(e){null==e.payloads&&(e.payloads="")});var r=t.outerOrder||defaultOuterOrder,n=t.innerOrder||defaultInnerOrder,i=[];return r.forEach(function(t){grammar$1[t].forEach(function(r){r.name in e&&null!=e[r.name]?i.push(makeLine(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach(function(e){i.push(makeLine(t,r,e))})})}),e.media.forEach(function(e){i.push(makeLine("m",grammar$1.m[0],e)),n.forEach(function(t){grammar$1[t].forEach(function(r){r.name in e&&null!=e[r.name]?i.push(makeLine(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach(function(e){i.push(makeLine(t,r,e))})})})}),i.join("\r\n")+"\r\n"},parser=parser$1,writer=writer$1,grammar=grammarExports;function _createForOfIteratorHelper$9(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$9(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$9(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$9(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_arrayLikeToArray$9(e,t):void 0}}function _arrayLikeToArray$9(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function ownKeys$6(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function _objectSpread$6(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$6(Object(r),!0).forEach(function(t){_defineProperty(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$6(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function _callSuper$d(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$d()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$d(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$d=function(){return!!e})()}lib.grammar=grammar,lib.write=writer,lib.parse=parser.parse,lib.parseParams=parser.parseParams,lib.parseFmtpConfig=parser.parseFmtpConfig,lib.parsePayloads=parser.parsePayloads,lib.parseRemoteCandidates=parser.parseRemoteCandidates,lib.parseImageAttributes=parser.parseImageAttributes,lib.parseSimulcastStreamList=parser.parseSimulcastStreamList;var logger$2=getReporter().getLoggerWithPrefix("[rtc-subs]"),Subscription=function(e){function t(e){var r;_classCallCheck$1(this,t),r=_callSuper$d(this,t),Object.defineProperty(r,"stream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"resolutionInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"ssrc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"startTime",{enumerable:!0,configurable:!0,writable:!0,value:Date.now()}),Object.defineProperty(r,"uid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"subIdAcc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"state",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"monitor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"userConfigResolution",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"connection",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"rtcSignaling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"_stream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"stucked",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"metricsMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"audioStatsMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"videoStatsMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"transceiver",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"transceivers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"targetMediaType",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"logTrackEnded",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t;r.state===PubSubStates.Processing&&r.logger.info("sub track ended",null==e||null===(t=e.target)||void 0===t?void 0:t.id,r.subIdAcc)}}),Object.defineProperty(r,"logTrackUnmute",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t;r.state===PubSubStates.Processing&&r.logger.info("sub track unmute",null==e||null===(t=e.target)||void 0===t?void 0:t.id,r.subIdAcc)}}),Object.defineProperty(r,"logTrackMute",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t;r.state===PubSubStates.Processing&&r.logger.info("sub track mute",null==e||null===(t=e.target)||void 0===t?void 0:t.id,r.subIdAcc)}}),Object.defineProperty(r,"updateTransceiverListeners",{enumerable:!0,configurable:!0,writable:!0,value:function(){var e,t;null!==(e=r.transceiver)&&void 0!==e&&null!==(e=e.receiver)&&void 0!==e&&e.transport?(r.transceiver.receiver.transport.onerror=r._onDtlsError,r.transceiver.receiver.transport.onstatechange=r._onDtlsStateChange,null!==(t=r.transceiver)&&void 0!==t&&null!==(t=t.receiver)&&void 0!==t&&t.transport.iceTransport&&(r.transceiver.receiver.transport.iceTransport.onselectedcandidatepairchange=r._onSelectedCandidatePairChange.bind(r,r.transceiver.receiver))):r.logger.info("browser version low, no dtls transport to watch")}}),Object.defineProperty(r,"_onDtlsError",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t;r.logger.error("".concat(r.id," ").concat(r.uid," ").concat(r.subIdAcc," dtls_error"),null==e||null===(t=e.error)||void 0===t?void 0:t.errorDetail)}}),Object.defineProperty(r,"_onDtlsStateChange",{enumerable:!0,configurable:!0,writable:!0,value:function(){r.logger.info("".concat(r.id," ").concat(r.uid," ").concat(r.subIdAcc," dtls_state_change"),r.transceiver.receiver.transport.state)}}),Object.defineProperty(r,"_onSelectedCandidatePairChange",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t,n=null==e||null===(t=e.transport)||void 0===t||null===(t=t.iceTransport)||void 0===t?void 0:t.getSelectedCandidatePair();r.logger.info("".concat(r.id," ").concat(r.uid," ").concat(r.subIdAcc," selected_candidate_pair_change"),n)}}),r.subIdAcc="subIdAcc-".concat(t.subIdAcc++);var n=e.connection,i=e.stream,o=e.uid,a=e.resolutionInfo,s=e.userConfigResolution,c=e.targetMediaType;return r.connection=n,r.targetMediaType=c,r.resolutionInfo=a,r.userConfigResolution=s,r.rtcSignaling=n.rtcSignaling,r.stream=i,r.uid=o,r.reporter=n.reporter,r.logger=r.reporter.getLoggerWithPrefix("[rtc-subs]"),r.connection.once("ended",function(){r.clear()}),r.videoStatsMap=new Map,r.audioStatsMap=new Map,r.metricsMap=new Map,r.state=PubSubStates.Processing,r.handleStreamAdd=r.handleStreamAdd.bind(r),r.connection.on("track",r.handleStreamAdd),r}return _inherits$1(t,e),_createClass$1(t,[{key:"handleStreamAdd",value:function(e,t){var r,n=this;if(clientConfig.audioSFU&&"audio"===e.kind){var i,o=null===(i=this.transceivers)||void 0===i?void 0:i.map(function(e){var t;return null===(t=e.receiver)||void 0===t||null===(t=t.track)||void 0===t?void 0:t.id});null!=o&&o.includes(e.id)&&(e.removeEventListener("ended",this.logTrackEnded),e.removeEventListener("unmute",this.logTrackUnmute),e.removeEventListener("mute",this.logTrackMute),e.addEventListener("ended",this.logTrackEnded),e.addEventListener("unmute",this.logTrackUnmute),e.addEventListener("mute",this.logTrackMute)),this._stream=this._stream||new MediaStream([]),this._stream.addTrack(e)}else if(e.id===(null===(r=this.transceiver)||void 0===r||null===(r=r.receiver)||void 0===r||null===(r=r.track)||void 0===r?void 0:r.id)){e.removeEventListener("ended",this.logTrackEnded),e.removeEventListener("unmute",this.logTrackUnmute),e.removeEventListener("mute",this.logTrackMute),e.addEventListener("ended",this.logTrackEnded),e.addEventListener("unmute",this.logTrackUnmute),e.addEventListener("mute",this.logTrackMute),this._stream=new MediaStream([e]);var a=document.createElement("video");a.onloadeddata=function(){a.srcObject=null,n.handleVideoFirstFrame()},a.srcObject=this._stream}}},{key:"mediaStream",get:function(){return this._stream||this.connection.mcuAudioStream}},{key:"stop",value:function(){var e=this;if(this.state===PubSubStates.Processing)return this.clear(),this.rtcSignaling.unsubscribe({subscriptionId:this.id}).catch(function(t){e.logger.warn("negative ack for unsubscribing, ".concat(t))})}},{key:"mute",value:function(e){return this.rtcSignaling.subscriptionControl({subscriptionId:this.id,operation:"pause",track:e})}},{key:"unmute",value:function(e){return this.rtcSignaling.subscriptionControl({subscriptionId:this.id,operation:"play",track:e})}},{key:"applyOptions",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=this.stream.id;return this.resolutionInfo=getResoParamToSend(this.stream,e),t||(this.userConfigResolution=e),this.rtcSignaling.subscriptionControl({subscriptionId:this.id,operation:"update",updateDesc:{video:{from:r,params:this.resolutionInfo}}})}},{key:"reset",value:function(){this.connection.off("track",this.handleStreamAdd),this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.metricsMap.clear(),this.audioStatsMap.clear(),this.videoStatsMap.clear()}},{key:"clear",value:function(){this.state!==PubSubStates.End&&(this.reset(),this.state=PubSubStates.End,this.emit("ended"))}},{key:"addTransceiver",value:function(e){this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.metricsMap.clear(),this.audioStatsMap.clear(),this.videoStatsMap.clear(),this.transceiver=e,this.monitor=new SubscribeMonitor(this),this.onMonitor()}},{key:"addTransceivers",value:function(e){this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.transceivers=e,this.monitor=new SubscribeMonitor(this),this.onMonitor()}},{key:"handleVideoFirstFrame",value:function(){this.reporter.trace.videoFirstFrame({sessionId:this.id,remoteStreamId:this.stream.id,attr_elapse_time:Date.now()-this.startTime,remoteUserId:this.uid}),this.logger.info("video-first-frame sessionId=".concat(this.id))}},{key:"handleMetrics",value:function(e,t){var r=e.audioMetrics,n=e.videoMetrics;if(r){var i,o=(null===(i=this.metricsMap.get(t))||void 0===i?void 0:i.audioMetrics)||{},a=getDeltaDurationInSeconds(r,o),s=getDelta(r.bytesReceived,o.bytesReceived),c={codec:this.connection.peerConnectionStats.audioCodec||r.codec,receiveBytes:r.bytesReceived,receivePackets:r.packetsReceived,receivePacketsLost:r.packetsLost,rtt:r.roundTripTime,audioLevel:Math.max(r.audioLevel,0),timestamp:r.timestamp,receiveBitrate:8*s/a};this.audioStatsMap.set(t,c)}else if(n){var u,l,d=(null===(u=this.metricsMap.get(t))||void 0===u?void 0:u.videoMetrics)||{},p=getDeltaDurationInSeconds(n,d),f=getDelta(n.bytesReceived,d.bytesReceived),h={codec:this.connection.peerConnectionStats.videoCodec||n.codec,receiveResolution:{width:n.frameWidth,height:n.frameHeight},receiveBitrate:8*f/p,decodeFrameRate:Math.round(getDelta(null==n?void 0:n.framesDecoded,d.framesDecoded)/p),receiveFrameRate:Math.round(getDelta(null==n?void 0:n.framesReceived,d.framesReceived)/p),keyFramesDecoded:null==n?void 0:n.keyFramesDecoded,receiveFramesDropped:getDelta(null==n?void 0:n.framesDropped,d.framesDropped),receiveBytes:n.bytesReceived,receivePackets:n.packetsReceived,receivePacketsLost:n.packetsLost,rtt:n.roundTripTime,timestamp:n.timestamp},g=this.connection.subSdpFmtpLines.some(function(e){return e.includes("64")}),m=(null===(l=this.stream.media)||void 0===l||null===(l=l.video)||void 0===l?void 0:l.source)===exports.VideoSourceInfo.CAMERA&&f>STUCK_JUDGE_RECV_BYTES&&0===h.decodeFrameRate;"network"===t&&(this.stucked&&m?g&&h.receiveFramesDropped>0&&!clientConfig.downlinkForbidHighProfile&&this.connection.handleHighProfileFallback():this.stucked=m),this.videoStatsMap.set(t,h)}this.metricsMap.set(t,e)}},{key:"getMetrics",value:function(e){var t,r=this;return null===(t=this.connection)||void 0===t?void 0:t.getStats().then(function(){var t;null===(t=r.monitor)||void 0===t||t.getStats().then(function(t){return r.handleMetrics(t,e)})})}},{key:"onMonitor",value:function(){var e=this;"mcu"===this.uid?(this.monitor.on("audio-net-eq",function(t){e.reporter.metric.audioNetEQ(_objectSpread$6({sessionId:e.id,remoteStreamId:e.stream.id,remoteUserId:e.uid},t))}),this.monitor.on("audio-recv-stream",function(t){e.reporter.metric.audioRecvStream(_objectSpread$6({sessionId:e.id,remoteStreamId:e.stream.id,remoteUserId:e.uid},t))}),this.monitor.on("audio-first-packet",function(){e.reporter.trace.audioFirstPacket({sessionId:e.id,remoteStreamId:e.stream.id,remoteUserId:e.uid})}),this.monitor.on("audio-first-frame",function(){e.emit("audio-first-frame")})):(this.monitor.on("video-first-packet",function(){e.reporter.trace.videoFirstPacket({sessionId:e.id,remoteStreamId:e.stream.id,remoteUserId:e.uid}),e.logger.info("video-first-packet sessionId=".concat(e.id))}),this.monitor.on("video-recv-stream",function(t){e.reporter.metric.videoRecvStream(_objectSpread$6({sessionId:e.id,remoteStreamId:e.stream.id,remoteUserId:e.uid},t))}))}}])}(EventEmitter);Object.defineProperty(Subscription,"subIdAcc",{enumerable:!0,configurable:!0,writable:!0,value:0});var getResoParamToSend=function(e,t){if(!t)return null;var r=t.resolutionLevel,n=e.media.video.highestResolutionLevel;if(n&&n<r){var i=getResoLevelNameByResoLevelNum(n);return calcResolutionInfo(i,getStreamSupportedResoArr(e))}return t},prepareForBatchSubscribe=function(e){var t,r={audio:[],video:[]},n=_createForOfIteratorHelper$9(e);try{for(n.s();!(t=n.n()).done;){var i=t.value,o=i.stream,a=i.error,s=i.resolutionInfo,c=i.targetMediaType;if(a)logger$2.error("skip subscribe",o,a);else{var u=getSingleMediaOption(o,s,c),l=u.audio,d=u.video;if("audio"===c&&l){var p=_objectSpread$6(_objectSpread$6({},l),{},{trackId:o.media.audio.trackId,ssrcGroup:[{ssrc:generateSubSsrc()}]});clientConfig.audioSFU&&(p.ssrcGroup=new Array(6).fill(0).map(function(){return{ssrc:generateSubSsrc()}})),r.audio.push(p)}else if("video"===c&&d){var f,h;r.video.push(_objectSpread$6(_objectSpread$6({},d),{},{trackId:null===(f=o.media)||void 0===f||null===(f=f.video)||void 0===f?void 0:f.trackId,ssrcGroup:null===(h=o.media)||void 0===h||null===(h=h.video)||void 0===h?void 0:h.ssrcGroup,subSsrcGroup:{ssrc:generateSubSsrc(),rtxSsrc:generateSubSsrc()}}))}}}}catch(e){n.e(e)}finally{n.f()}return r},getSingleMediaOption=function(e,t,r){var n=e.id,i=e.media,o=i.audio,a=i.video,s={};if(o&&"audio"===r)s.audio={from:n};else if(a&&"video"===r){var c;s.video={from:n,format:null===(c=i.video)||void 0===c?void 0:c.format,parameters:getResoParamToSend(e,t)}}return s},batchSubscribeStart=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t,r){var n,i,o,a;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return n=[],i={},t.forEach(function(e,t){var o=e.stream,a=e.error,s=e.uid,c=e.resolutionInfo,u=e.targetMediaType;if(n[t]={stream:o,error:a,uid:s,resolutionInfo:c},!a){var l=new Subscription({connection:r,uid:s,userConfigResolution:c,resolutionInfo:c&&getResoParamToSend(o,c),stream:o,targetMediaType:u});i[o.id]=l}}),a=new Promise(function(e,a){o=function(){var o=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function o(){var s;return _regeneratorRuntime$1.wrap(function(o){for(;;)switch(o.prev=o.next){case 0:if((s=prepareForBatchSubscribe(t)).audio.length||s.video.length){o.next=1;break}return logger$2.info("batchSubscribe no valid media to sub"),o.abrupt("return",e(n));case 1:return o.next=2,adjustDownlinkSDPWhenSubscribe(r,s,i);case 2:r.rtcSignaling.batchSubscribe({connectionId:r.id,propertiesJsonStr:JSON.stringify({opusExtendInbandFec:!0,type:clientConfig.audioSFU?"selective":"mixed"}),supportTemporalLayer:!1,media:s}).then(function(){var r=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function r(o){var a,s,c,u,l,d;return _regeneratorRuntime$1.wrap(function(r){for(;;)switch(r.prev=r.next){case 0:if(a=o.detailStatus,"ok"===(s=o.globalStatus)){r.next=1;break}return n.forEach(function(e){e.error=e.error||parseSubscribeError(e.stream,s)}),r.abrupt("return",e(n));case 1:c=_createForOfIteratorHelper$9(a),r.prev=2,l=_regeneratorRuntime$1.mark(function e(){var r,o,a,s,c,l;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:r=u.value,o=r.id,a=r.msg,s=r.origin,c=i[s.id],l=t.findIndex(function(e){return e.stream.id===s.id}),"ok"===a&&c?(c.id=o,n[l].id=o,n[l].subscription=c):"ok"!==a&&(n[l].error=parseSubscribeError(c.stream,a));case 1:case"end":return e.stop()}},e)}),c.s();case 3:if((u=c.n()).done){r.next=5;break}return r.delegateYield(l(),"t0",4);case 4:r.next=3;break;case 5:r.next=7;break;case 6:r.prev=6,d=r.catch(2),c.e(d);case 7:return r.prev=7,c.f(),r.finish(7);case 8:e(n);case 9:case"end":return r.stop()}},r,null,[[2,6,7,8]])}));return function(e){return r.apply(this,arguments)}}()).catch(a);case 3:case"end":return o.stop()}},o)}));return function(){return o.apply(this,arguments)}}()}),r.addTask(o),e.abrupt("return",a);case 1:case"end":return e.stop()}},e)}));return function(t,r){return e.apply(this,arguments)}}(),batchSubscribeStop=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t,r){var n,i;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return i=new Promise(function(e,i){n=function(){var n=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function n(){var o,a;return _regeneratorRuntime$1.wrap(function(n){for(;;)switch(n.prev=n.next){case 0:return o=t.filter(function(e){var t;return!(null===(t=e.stream)||void 0===t||null===(t=t.media)||void 0===t||!t.audio)}).map(function(e){return e.id}),a=t.filter(function(e){var t;return!(null===(t=e.stream)||void 0===t||null===(t=t.media)||void 0===t||!t.video)}).map(function(e){return e.id}),n.next=1,adjustDownlinkSDPWhenUnsubscribe(r,t);case 1:r.rtcSignaling.batchUnSubscribe({connectionId:r.id,audio:o,video:a}).then(function(){t.forEach(function(e){e.clear()}),e(void 0)}).catch(i);case 2:case"end":return n.stop()}},n)}));return function(){return n.apply(this,arguments)}}()}),r.addTask(n),e.abrupt("return",i);case 1:case"end":return e.stop()}},e)}));return function(t,r){return e.apply(this,arguments)}}();function ownKeys$5(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function _objectSpread$5(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$5(Object(r),!0).forEach(function(t){_defineProperty(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$5(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function _createForOfIteratorHelper$8(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$8(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$8(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$8(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_arrayLikeToArray$8(e,t):void 0}}function _arrayLikeToArray$8(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}var logger$1=getReporter().getLoggerWithPrefix("[rtc-sdp]"),optionzationMap={motion:"maintain-framerate",detail:"maintain-resolution",balanced:"balanced"},ssrcPrefix=0,ssrcMask=0,ssrcSeed=0,inUseSsrcSet=new Set,parseSubSsrcInfo=function(e,t){var r=Math.log2(e+1);t>2147483647>>r||(ssrcMask=e,ssrcPrefix=(t<<r|2147483648)>>>0)},generateSubSsrc=function(){if(0==ssrcPrefix||0==ssrcMask)return 0;var e=Math.min(ssrcMask+1,1e4);do{var t=ssrcPrefix+(ssrcMask&ssrcSeed++);if(0!=t&&!inUseSsrcSet.has(t))return t}while(--e>0);return 0},useSubSsrcGroup=function(e){e.ssrc&&inUseSsrcSet.add(e.ssrc),e.rtxSsrc&&inUseSsrcSet.add(e.rtxSsrc)},addRidsToMline=function(e,t){var r,n;if((null===(r=e.rids)||void 0===r?void 0:r.length)>1)return Environment.isFirefox()&&(t=addRidExtForFirefox(t)),t.rids=null===(n=e.rids)||void 0===n?void 0:n.map(function(e){return{direction:"recv",id:e.id}}),t.simulcast={dir1:"recv",list1:e.simulcast.list1},t},adjustUplinkSDPWhenApplyOptions=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n,i,o,a,s,c;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return r=t.connection,n=t.transceiver,i=r.remoteSDP,o=r.pc,e.next=1,o.createOffer();case 1:return a=e.sent,e.next=2,o.setLocalDescription(a);case 2:return r.localSDP=lib.parse(a.sdp),s=r.localSDP.media.find(function(e){return e.mid==n.mid}),c=i.media.find(function(e){return e.mid==n.mid}),addRidsToMline(s,c),e.next=3,o.setRemoteDescription({type:"answer",sdp:lib.write(i)});case 3:r.remoteSDP=i;case 4:case"end":return e.stop()}},e)}));return function(t){return e.apply(this,arguments)}}(),addTransceiversAndSetSdpToPC=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t,r){var n,i,o,a,s,c,u,l,d,p,f;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return n=t.pc,i=t.idToTransceiverMap,o=t.remoteSDP,a=new MediaStream(r.map(function(e){return e.getMediaStreamTrack()})),s=r.map(function(e){var r={direction:"sendonly"};if(e instanceof LocalVideoTrack){var n=getSenderEncodingArrAndResoLevel(e).encodings;r.sendEncodings=n.filter(function(e){return e.activeForBitrateMap}).map(function(e){return{rid:e.rid||void 0,maxBitrate:1e3*e.maxBitrate,maxFramerate:e.maxFramerate,active:e.activeForRealuse,scaleResolutionDownBy:e.scaleResolutionDownBy}})}var o=t.pc.addTransceiver(e.getMediaStreamTrack()||e.trackMediaType,r);if(e instanceof LocalVideoTrack&&o.sender.setParameters){var a=e.optimizationMode,s=o.sender.getParameters();s.degradationPreference=optionzationMap[a]||"balanced";var c=parseFloat(new URLSearchParams(location.search).get("times"))||0;c&&(logger$1.info("adjustUplinkSDPWhenPublish maxBitrate times",c),s.encodings.forEach(function(e){if(e.maxBitrate){var t=e.maxBitrate;e.maxBitrate=e.maxBitrate*c,logger$1.info("adjustUplinkSDPWhenPublish update maxBitrate",t,e.maxBitrate,e)}})),logger$1.info("adjustUplinkSDPWhenPublish setParameters",s),o.sender.setParameters(s)}return i.set(e.getTrackId(),o),o}),e.next=1,n.createOffer();case 1:return c=e.sent,u=lib.parse(c.sdp),e.next=2,n.setLocalDescription(c);case 2:t.localSDP=u,o.groups[0].mids=t.localSDP.groups[0].mids,l=_createForOfIteratorHelper$8(s),e.prev=3,p=_regeneratorRuntime$1.mark(function e(){var t,r,n,i,a,s,c;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:t=d.value,r=o.media.find(function(e){return e.type===t.sender.track.kind}),Environment.isFirefox()&&"video"===r.type&&(delete r.rids,delete r.simulcast),n=_objectSpread$5(_objectSpread$5({},r),{},{ext:_toConsumableArray(r.ext),mid:t.mid}),i=u.media.find(function(e){return e.mid==t.mid}),a=new URLSearchParams(location.search).get("startkbs")||2e3,s=new URLSearchParams(location.search).get("minkbs"),c=new URLSearchParams(location.search).get("maxkbs"),logger$1.info("startkbs, minkbs, maxkbs",a,s,c),n.fmtp.map(function(e){if(/profile-level-id/i.test(e.config)){var t=e.config.split(";").filter(function(e){return!/x-google-start-bitrate/i.test(e)});a&&clientConfig.highStartBitrate?t.push("x-google-start-bitrate=".concat(a)):t.push("x-google-start-bitrate=500"),s&&t.push("x-google-min-bitrate=".concat(s)),c&&t.push("x-google-max-bitrate=".concat(c)),e.config=t.join(";")}}),addRidsToMline(i,n),o.media.push(n);case 1:case"end":return e.stop()}},e)}),l.s();case 4:if((d=l.n()).done){e.next=6;break}return e.delegateYield(p(),"t0",5);case 5:e.next=4;break;case 6:e.next=8;break;case 7:e.prev=7,f=e.catch(3),l.e(f);case 8:return e.prev=8,l.f(),e.finish(8);case 9:return window.remoteSDP=o,e.next=10,n.setRemoteDescription({type:"answer",sdp:lib.write(o)});case 10:return t.remoteSDP=o,e.abrupt("return",{localSDP:t.localSDP,stream:a});case 11:case"end":return e.stop()}},e,null,[[3,7,8,9]])}));return function(t,r){return e.apply(this,arguments)}}(),adjustUplinkSDPWhenUnpublish=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t,r){var n,i,o,a;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return n=t.pc,i=t.remoteSDP,r.map(function(e){return e.transceiver}).forEach(function(e){if(e){n.removeTrack(e.sender);var t=i.media.find(function(t){return t.mid==(null==e?void 0:e.mid)});e.direction="inactive",t.direction="inactive"}}),e.next=1,n.createOffer();case 1:return o=e.sent,a=lib.parse(o.sdp),e.next=2,n.setLocalDescription(o);case 2:return t.localSDP=a,i.groups[0].mids=a.groups[0].mids,t.remoteSDP=i,e.next=3,n.setRemoteDescription({type:"answer",sdp:lib.write(i)});case 3:case"end":return e.stop()}},e)}));return function(t,r){return e.apply(this,arguments)}}(),addSSRC=function(e,t,r){var n=e.ssrc,i=e.rtxSsrc;useSubSsrcGroup(e),t.ssrcGroups=[],i&&t.ssrcGroups.push({semantics:"FID",ssrcs:"".concat(n," ").concat(i)}),t.ssrcs=[],[n,i].filter(function(e){return void 0!==e}).forEach(function(e){t.ssrcs.push({attribute:"msid",value:"".concat(r," v").concat(n),id:e},{attribute:"cname",value:createUuid(),id:e})})},addRidExtForFirefox=function(e){var t;return null!=e&&null!==(t=e.ext)&&void 0!==t&&t.some(function(e){return e.uri.includes("rtp-stream-id")})||e.ext.push({value:8,uri:"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id"},{value:9,uri:"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"}),e},adjustDownlinkSDPWhenSubscribe=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t,r,n){var i,o,a,s,c,u,l,d,p,f,h,g,m,v,y,b,S,_,E,T,R,C,k,P,w,O,I,A,M,N,D,x,L,j,$,U,F,V,G,B;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(s=t.pc,c=t.idToTransceiverMap,u=t.remoteSDP,l=t.idToTransceiversMap,d=u.media.find(function(e){return"video"===e.type}),p=u.media.find(function(e){return"audio"===e.type}),f=null===(i=d.ssrcs)||void 0===i?void 0:i.find(function(e){return"msid"===e.attribute}).value.split(" ")[0],null!==(o=r.audio)&&void 0!==o&&o[0])if(g=null===(h=r.audio)||void 0===h?void 0:h[0],m=g.from,clientConfig.audioSFU){if(l.get(m)){v=_createForOfIteratorHelper$8(l.get(m));try{for(v.s();!(y=v.n()).done;)y.value.direction="recvonly"}catch(e){v.e(e)}finally{v.f()}b=u.media.filter(function(e){return"audio"===e.type}),S=_createForOfIteratorHelper$8(b);try{for(S.s();!(_=S.n()).done;)_.value.direction="sendonly"}catch(e){S.e(e)}finally{S.f()}}else t.mcuAudioTranceivers=new Array(6).fill(0).map(function(e){return t.pc.addTransceiver("audio",{direction:"recvonly"})}),l.set(m,t.mcuAudioTranceivers);n[m].addTransceivers(l.get(m))}else c.get(m)||c.set(m,t.mcuAudioTranceiver),c.get(m).direction="recvonly",p.direction="sendonly",n[m].addTransceiver(c.get(m));E=_createForOfIteratorHelper$8(r.video),e.prev=1,R=_regeneratorRuntime$1.mark(function e(){var t,r,i,o;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(t=T.value,r=t.from,i=c.get(r)){e.next=1;break}c.set(r,s.addTransceiver("video",{direction:"recvonly"})),e.next=5;break;case 1:if("inactive"===i.direction){e.next=4;break}return i.direction="inactive",e.next=2,s.createOffer();case 2:return o=e.sent,e.next=3,s.setLocalDescription(o);case 3:return u.media.find(function(e){return e.mid==i.mid}).direction="inactive",e.next=4,s.setRemoteDescription({type:"answer",sdp:lib.write(u)});case 4:c.get(r).direction="recvonly";case 5:n[r].addTransceiver(c.get(r));case 6:case"end":return e.stop()}},e)}),E.s();case 2:if((T=E.n()).done){e.next=4;break}return e.delegateYield(R(),"t0",3);case 3:e.next=2;break;case 4:e.next=6;break;case 5:e.prev=5,G=e.catch(1),E.e(G);case 6:return e.prev=6,E.f(),e.finish(6);case 7:return e.next=8,s.createOffer();case 8:return C=e.sent,k=lib.parse(C.sdp),u.groups[0].mids=k.groups[0].mids,e.next=9,s.setLocalDescription(C);case 9:t.localSDP=k,clientConfig.audioSFU&&r.audio[0]&&(P=r.audio[0],w=P.ssrcGroup,O=P.from,l.get(O).forEach(function(e,t){var r,n=null===(r=w[t])||void 0===r?void 0:r.ssrc,i=u.media.find(function(t){var r=t.mid,n=t.type;return r==e.mid&&"audio"===n});i||(i=_objectSpread$5(_objectSpread$5({},p),{},{mid:e.mid}),u.media.push(i)),i.ssrcs=getSsrcInfo(n,f),i.direction="sendonly"})),I=_createForOfIteratorHelper$8(r.video),e.prev=10,M=_regeneratorRuntime$1.mark(function e(){var t,r,i,o,a;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:t=A.value,r=t.from,i=t.subSsrcGroup,o=c.get(r),a=u.media.find(function(e){var t=e.mid,r=e.type;return t==o.mid&&"video"===r}),a||((a=_objectSpread$5({},d)).mid=o.mid,u.media.push(a)),a.direction="sendonly",n[r].ssrc=null==i?void 0:i.ssrc,addSSRC(i,a,f);case 1:case"end":return e.stop()}},e)}),I.s();case 11:if((A=I.n()).done){e.next=13;break}return e.delegateYield(M(),"t1",12);case 12:e.next=11;break;case 13:e.next=15;break;case 14:e.prev=14,B=e.catch(10),I.e(B);case 15:return e.prev=15,I.f(),e.finish(15);case 16:return logger$1.info("sub remoteSDP before remove high profile",lib.write(u)),removeHighProfileH264(u),t.remoteSDP=u,N=lib.write(u),logger$1.info("sub remoteSDP after remove high profile",N),e.next=17,s.setRemoteDescription({type:"answer",sdp:N});case 17:null!==(a=r.audio)&&void 0!==a&&a[0]&&(x=null===(D=r.audio)||void 0===D?void 0:D[0],L=x.from,clientConfig.audioSFU||n[L].addTransceiver(c.get(L))),j=_createForOfIteratorHelper$8(r.video);try{for(j.s();!($=j.n()).done;)F=$.value,V=F.from,null===(U=n[V])||void 0===U||U.updateTransceiverListeners()}catch(e){j.e(e)}finally{j.f()}case 18:case"end":return e.stop()}},e,null,[[1,5,6,7],[10,14,15,16]])}));return function(t,r,n){return e.apply(this,arguments)}}(),keepH264CbProfileOnly=function(e){removeSpecificH264ProfileCodec(e,function(e){return!/profile-level-id=42e01f/i.test(e)&&/profile-level-id/i.test(e)})},removeHighProfileH264=function(e){removeSpecificH264ProfileCodec(e,function(e){return/profile-level-id=64/i.test(e)&&/profile-level-id/i.test(e)})},removeSpecificH264ProfileCodec=function(e,t){e.media.forEach(function(e){if("video"===e.type){var r=e.rtp.filter(function(e){return"H264"===e.codec}).filter(function(r){return e.fmtp.find(function(e){return e.payload===r.payload&&t((null==e?void 0:e.config)||"")})}),n=new Map;e.fmtp.forEach(function(e){/apt=\d+/i.test(e.config)&&n.set(e.payload,e.config.split("=")[1])}),logger$1.info("rtxPayloadMap",Array.from(n.entries())),e.rtp=e.rtp.filter(function(e){return!r.find(function(t){return t.payload===e.payload||"".concat(t.payload)===n.get(e.payload)})}),e.fmtp=e.fmtp.filter(function(e){return!r.find(function(t){return t.payload===e.payload||"".concat(t.payload)===n.get(e.payload)})}),e.payloads=e.payloads.split(" ").map(function(e){return e.trim()}).filter(function(e){return!r.find(function(t){return"".concat(t.payload)===e||"".concat(t.payload)===n.get(parseInt(e))})}).join(" "),e.rtcpFb=e.rtcpFb.filter(function(e){return!r.find(function(t){return parseInt("".concat(t.payload))===parseInt("".concat(e.payload))||"".concat(t.payload)===n.get(parseInt("".concat(e.payload)))})})}})},adjustDownlinkSDPWhenUnsubscribe=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t,r){var n,i,o,a,s,c,u,l,d,p,f,h;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:n=t.pc,i=t.remoteSDP,o=[],a=_createForOfIteratorHelper$8(r);try{for(a.s();!(s=a.n()).done;)c=s.value,u=c.transceiver,l=c.transceivers,u?o.push(u):l&&o.push.apply(o,_toConsumableArray(l))}catch(e){a.e(e)}finally{a.f()}return o.forEach(function(e){e.direction="inactive"}),e.next=1,n.createOffer();case 1:return d=e.sent,e.next=2,n.setLocalDescription(d);case 2:t.localSDP=lib.parse(d.sdp),p=_regeneratorRuntime$1.mark(function e(){var t;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:t=h[f],i.media.find(function(e){return e.mid==t.mid}).direction="inactive";case 1:case"end":return e.stop()}},e)}),f=0,h=o;case 3:if(!(f<h.length)){e.next=5;break}return e.delegateYield(p(),"t0",4);case 4:f++,e.next=3;break;case 5:return t.remoteSDP=i,e.next=6,n.setRemoteDescription({type:"answer",sdp:lib.write(i)});case 6:case"end":return e.stop()}},e)}));return function(t,r){return e.apply(this,arguments)}}(),adjustRemoteSDPWhenFailover=function(e,t){var r=t.media.find(function(e){return"audio"===e.type}),n=t.media.find(function(e){return"video"===e.type});return e.media.forEach(function(t,i){var o=t.mid,a=t.ssrcGroups,s=void 0===a?[]:a,c=t.ssrcs,u=void 0===c?[]:c,l=t.rids,d=void 0===l?[]:l;"audio"===t.type?e.media[i]=_objectSpread$5(_objectSpread$5({},r),{},{mid:o,ssrcs:u}):"video"===t.type&&(e.media[i]=_objectSpread$5(_objectSpread$5({},n),{},{mid:o,ssrcGroups:s,ssrcs:u}),d.length&&(e.media[i].rids=d,e.media[i].simulcast={dir1:"recv",list1:d.map(function(e){return"~".concat(e.id)}).join(";")}))}),e},adjustLocalSDPWhenFailover=function(e,t){var r=t.media;return e.media.forEach(function(e){var t=e.mid,n=e.ssrcGroups,i=void 0===n?[]:n,o=e.ssrcs,a=void 0===o?[]:o,s=e.type,c=r.findIndex(function(e){return e.mid==t&&e.type===s});c>-1&&(r[c]=_objectSpread$5(_objectSpread$5({},r[c]),{},{ssrcGroups:i,ssrcs:a}))}),t},getSsrcInfo=function(e,t){return[{attribute:"msid",value:"".concat(t," v").concat(e),id:e},{attribute:"cname",value:createUuid(),id:e}]},changeRemoteSdpForCreatePc=function(e,t,r){var n=t.direction,i=t.remoteSDP;logger$1.info("origin answer for createpc",t.id,e);var o=lib.parse(e);o.media.forEach(function(e){e.candidates.forEach(function(e){e.generation=0,e["network-cost"]=isPrivateIP(e.ip)?10:1e3})}),r&&(o=adjustRemoteSDPWhenFailover(i,o));var a=o.media.find(function(e){return"video"===e.type});if("uplink"===n&&Environment.isFirefox()&&clientConfig.simulcast&&(a.ext=a.ext.filter(function(e){return!e.uri.includes("rtp-stream-id")})),!a.ssrcs&&"downlink"===n){var s=generateSubSsrc(),c=o.msidSemantic.token;a.ssrcs=getSsrcInfo(s,c)}clientConfig.preferH264CbProfile&&keepH264CbProfileOnly(o),t.remoteSDP=o;var u=lib.write(o);return logger$1.info("final answer for createpc",t.id,u),u},removeTransportCC=function(e){e.media.forEach(function(e){e.ext=e.ext.filter(function(e){return!e.uri.includes("transport-wide-cc")}),e.rtcpFb=e.rtcpFb.filter(function(e){return"transport-cc"!==e.type})})},changeLocalSdpForCreatePc=function(e,t){var r=t.direction,n=lib.parse(e);if(removeHighProfileH264(n),clientConfig.preferH264CbProfile&&keepH264CbProfileOnly(n),clientConfig.disableTransportCC&&"uplink"===r&&removeTransportCC(n),"downlink"===r&&!clientConfig.downlinkForbidHighProfile){var i=[];n.media.find(function(e){return"video"===e.type}).fmtp.forEach(function(e){var t=e.config;t.includes("profile-level-id")&&i.push(t)}),t.subSdpFmtpLines=i}if(Environment.isFirefox()&&(n=removeProfileOfUnsetPacketzationMode(n)),"uplink"===r&&Environment.isFirefox()&&clientConfig.simulcast){var o=n.media.find(function(e){return"video"===e.type});addRidExtForFirefox(o)}return t.localSDP=n,n},adjustOfferWhenFailover=function(e){var t=e.localSDP,r=e.remoteSDP,n=e.sessionManager,i=e.mcuAudioTranceiver,o=e.pc,a=e.idToTransceiverMap,s=e.idToTransceiversMap,c=e.direction,u=t.media.slice(2),l=_toConsumableArray(n.sessions.values());if("downlink"===c){var d=r.media.slice(2),p=l.filter(function(e){return e instanceof Subscription}),f=p.find(function(e){var t;return"admin"===(null===(t=e.stream)||void 0===t||null===(t=t.info)||void 0===t?void 0:t.owner)});f&&!clientConfig.audioSFU&&(a.set(f.id,i),f.addTransceiver(i));var h=[];u.forEach(function(e){var t={direction:e.direction},r=d.find(function(t){return t.type===e.type&&e.mid==t.mid}),n=p.find(function(e){return(null==e?void 0:e.ssrc)===(null==r?void 0:r.ssrcs[0].id)}),i=o.addTransceiver(e.type,t);"recvonly"===e.direction&&("video"===e.type&&n?(a.set(n.stream.id,i),n.addTransceiver(i)):"audio"===e.type&&h.push(i))}),h.length&&f&&(e.mcuAudioTranceivers=h,s.set(f.id,h),f.addTransceivers(h))}else{var g=l.filter(function(e){return e instanceof Publication});u.forEach(function(e){var t={direction:e.direction},r=g.find(function(t){return t.mid==e.mid});if("sendonly"===e.direction&&r){var n=r.tracks[0],i=(null==n?void 0:n.getMediaStreamTrack())||(null==n?void 0:n.trackMediaType);if(n instanceof LocalVideoTrack){var s=getSenderEncodingArrAndResoLevel(n).encodings;t.sendEncodings=s.filter(function(e){return e.activeForBitrateMap}).map(function(e){return{rid:e.rid||void 0,maxBitrate:1e3*e.maxBitrate,maxFramerate:e.maxFramerate,active:e.activeForRealuse,scaleResolutionDownBy:e.scaleResolutionDownBy}})}var c=o.addTransceiver(i,t);a.set(n.getTrackId(),c),r.addTransceiver(c)}else o.addTransceiver(e.type,t)})}},removePayloadTypes=function(e,t){if(e){var r,n=e.fmtp,i=e.payloads,o=e.rtp,a=e.rtcpFb,s=[],c={},u=_createForOfIteratorHelper$8(n);try{for(u.s();!(r=u.n()).done;){var l=r.value,d=l.config,p=l.payload,f=d.split(";");c[p]={};var h,g=_createForOfIteratorHelper$8(f);try{for(g.s();!(h=g.n()).done;){var m=_slicedToArray(h.value.split("="),2),v=m[0],y=m[1];c[p][v]=y}}catch(e){g.e(e)}finally{g.f()}}}catch(e){u.e(e)}finally{u.f()}for(var b in c){var S=c[b];(t(S)||s.includes(+S.apt))&&s.push(parseInt(b))}if(s.length){for(var _=n.length-1;_>=0;_--){var E=n[_].payload;s.includes(E)&&n.splice(_,1)}for(var T=o.length-1;T>=0;T--)s.includes(o[T].payload)&&o.splice(T,1);for(var R=a.length-1;R>=0;R--)s.includes(parseInt("".concat(a[R].payload)))&&a.splice(R,1);e.payloads=i.split(" ").map(Number).filter(function(e){return!s.includes(e)}).join(" ")}}},removeProfileOfUnsetPacketzationMode=function(e){var t=e.media.find(function(e){return"video"===e.type});return removePayloadTypes(t,function(e){return e["profile-level-id"]&&!e["packetization-mode"]}),e};function ownKeys$4(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function _objectSpread$4(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$4(Object(r),!0).forEach(function(t){_defineProperty(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$4(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function _createForOfIteratorHelper$7(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$7(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$7(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$7(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_arrayLikeToArray$7(e,t):void 0}}function _arrayLikeToArray$7(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _callSuper$c(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$c()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$c(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$c=function(){return!!e})()}var logger=getReporter().getLoggerWithPrefix("[publication]"),Publication=function(e){function t(e){var r;_classCallCheck$1(this,t),r=_callSuper$c(this,t),Object.defineProperty(r,"uid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"connection",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"tracks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"rtcSignaling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"transceiver",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"metricsMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"audioStatsMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"videoStatsMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"state",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"mid",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(r,"encodings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"rtcStreamMuted",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"feedbackIndex",{enumerable:!0,configurable:!0,writable:!0,value:-1}),Object.defineProperty(r,"monitor",{enumerable:!0,configurable:!0,writable:!0,value:void 0});var n=e.connection,i=e.uid,o=e.tracks,a=void 0===o?[]:o;return r.tracks=a,r.connection=n,r.rtcSignaling=n.rtcSignaling,r.uid=i,r.reporter=n.reporter,r.logger=r.reporter.getLoggerWithPrefix("[rtp-publication]"),r.state=PubSubStates.Idle,r.videoStatsMap=new Map,r.audioStatsMap=new Map,r.metricsMap=new Map,r.handleTracEvent=r.handleTracEvent.bind(r),r.applyOptions=r.applyOptions.bind(r),a.forEach(function(e){e.on(TRACK_EVENT_NAME,r.handleTracEvent)}),a[0]instanceof LocalVideoTrack&&(r.encodings=getSenderEncodingArrAndResoLevel(a[0]).encodings),r.state=PubSubStates.Processing,r.connection.once("ended",function(){r.clear()}),r}return _inherits$1(t,e),_createClass$1(t,[{key:"stop",value:function(){var e=this;return this.state!==PubSubStates.Processing?Promise.resolve():batchPublishStop([this],{connection:this.connection}).catch(function(t){e.clear(),e.logger.warn("negative ack for unpublish, ".concat(tryJsonStringify(t)))})}},{key:"mute",value:(n=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){var t,r,n;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(this.tracks.length&&this.state===PubSubStates.Processing&&"muted"!==this.rtcStreamMuted){e.next=1;break}return this.logger.info("ignore mute for tracks=".concat(this.tracks.length," state=").concat(this.state," curRtcStreamMuted=").concat(this.rtcStreamMuted)),e.abrupt("return");case 1:return t=this.tracks[0].trackMediaType,this.reporter.trace.localControl(t,!0,this.id),this.rtcStreamMuted="muted",e.prev=2,e.next=3,this.rtcSignaling.streamControl({streamId:this.id,operation:"pause",data:t});case 3:return r=e.sent,e.abrupt("return",r);case 4:e.prev=4,n=e.catch(2),this.logger.error("mute error",this.id,n),this.rtcStreamMuted="unmuted";case 5:case"end":return e.stop()}},e,this,[[2,4]])})),function(){return n.apply(this,arguments)})},{key:"unmute",value:(r=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){var t,r,n;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(this.tracks.length&&this.state===PubSubStates.Processing&&"unmuted"!==this.rtcStreamMuted){e.next=1;break}return this.logger.info("ignore unmute for tracks=".concat(this.tracks.length," state=").concat(this.state," curRtcStreamMuted=").concat(this.rtcStreamMuted)),e.abrupt("return");case 1:return t=this.tracks[0].trackMediaType,this.reporter.trace.localControl(t,!1,this.id),this.rtcStreamMuted="unmuted",e.prev=2,e.next=3,this.rtcSignaling.streamControl({streamId:this.id,operation:"play",data:t});case 3:return r=e.sent,e.abrupt("return",r);case 4:e.prev=4,n=e.catch(2),this.logger.error("unmute error",this.id,n),this.rtcStreamMuted="muted";case 5:case"end":return e.stop()}},e,this,[[2,4]])})),function(){return r.apply(this,arguments)})},{key:"initInner",value:function(e){this.id=e;var t=this.tracks[0],r=this.connection.idToTransceiverMap.get(t.getTrackId());this.addTransceiver(r),"video"===t.trackMediaType&&t.config.mirror&&this.handleMirror(t.config.mirror)}},{key:"handleMirror",value:function(e){return this.rtcSignaling.setStreamProperties({streamId:this.id,propertiesJsonStr:JSON.stringify({mirror:!!e})})}},{key:"handleRepublish",value:function(e){var t=this,r=this.connection,n=this.transceiver,i=e.getMediaStreamTrack().getSettings(),o=i.width,a=i.height,s=getHighestResoLevelNum(o,a);this.rtcSignaling.streamControl({streamId:this.id,operation:"updateResolution",highestResolutionLevel:s});var c=getDownByScales(o,a);r.addTask(_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){var r;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t.logger.info("scales",c),(r=n.sender.getParameters()).encodings.forEach(function(e){e.scaleResolutionDownBy=c[e.rid]}),t.logger.info("handleRepublish setParameters",r),e.abrupt("return",n.sender.setParameters(r).then(function(){console.log(n.sender.getParameters().encodings)}));case 1:case"end":return e.stop()}},e)})))}},{key:"handleTracEvent",value:function(e,t){var r,n=this,i={replace:function(){return n.replaceTrack(t.getMediaStreamTrack())},mute:function(){return n.mute()},unmute:function(){return n.unmute()},republish:function(){clientConfig.republish?n.handleRepublish(t):n.stop().then(function(){n.connection.sessionManager.serviceManager.client.publish([t])})},stop:function(){return n.stop()},optimizationMode:function(){return n.updateOptionzationMode()},mirror:function(){return n.handleMirror(t)}};return null===(r=i[e])||void 0===r?void 0:r.call(i)}},{key:"clear",value:function(){var e=this;this.state!==PubSubStates.End&&(this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.tracks.forEach(function(t){t.off(TRACK_EVENT_NAME,e.handleTracEvent)}),this.tracks=[],this.metricsMap.clear(),this.audioStatsMap.clear(),this.videoStatsMap.clear(),this.state=PubSubStates.End,this.emit("ended"))}},{key:"applyOptions",value:function(e){var t=this,r=e[0],n=r.index,i=r.bitrate;if(this.logger.debug("applyOptions",e),!(n<this.feedbackIndex||this.state!==PubSubStates.Processing)){this.feedbackIndex=n;var o=this.transceiver;this.connection.addTask(function(){return new Promise(function(r){var n,a=0===i,s=!1,c=o.sender.getParameters(),u=e.map(function(e){return e.rid}),l=_createForOfIteratorHelper$7(c.encodings);try{for(l.s();!(n=l.n()).done;){var d,p=n.value,f=_createForOfIteratorHelper$7(e);try{for(f.s();!(d=f.n()).done;){d.value.rid!==p.rid&&p.rid||p.active||a||(p.active=!0,s=!0)}}catch(e){f.e(e)}finally{f.f()}!p.active||u.includes(p.rid)&&!a||(p.active=!1,s=!0)}}catch(e){l.e(e)}finally{l.f()}return t.logger.info("encodings",c.encodings),s&&t.logger.info("applyOptions setParameters",c),o.sender.setParameters(c).then(function(){return adjustUplinkSDPWhenApplyOptions(t).then(r)})})})}}},{key:"updateOptionzationMode",value:function(){var e,t=this,r=this.tracks,n=this.transceiver,i=this.connection;if(r[0]instanceof LocalVideoTrack&&null!=n&&null!==(e=n.sender)&&void 0!==e&&e.setParameters){var o=r[0].optimizationMode;i.addTask(function(){var e=n.sender.getParameters();return e.degradationPreference=optionzationMap[o]||"balanced",t.logger.info("updateOptionzationMode setParameters",e),n.sender.setParameters(e),adjustUplinkSDPWhenApplyOptions(t)})}}},{key:"addTransceiver",value:function(e){this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.metricsMap.clear(),this.audioStatsMap.clear(),this.videoStatsMap.clear(),this.transceiver=e,this.mid||(this.mid=null==e?void 0:e.mid),this.state=PubSubStates.Processing,this.feedbackIndex=-1,this.monitor=new PublishMonitor(this),this.onMonitor()}},{key:"replaceTrack",value:function(e){var t;if(this.transceiver){null===(t=this.transceiver.sender.track)||void 0===t||t.stop();try{this.transceiver.sender.replaceTrack(e)}catch(e){this.logger.error(CONST_DEVELOPER_TODO_LOG_TAG,"sender replaceTrack error",e)}}}},{key:"handleMetrics",value:function(e,t){var r=e.audioMetrics,n=e.videoMetrics;if(r){var i,o=(null===(i=this.metricsMap.get(t))||void 0===i?void 0:i.audioMetrics)||{},a=getDeltaDurationInSeconds(r,o),s=getDelta(r.bytesSent,o.bytesSent),c={codec:this.connection.peerConnectionStats.audioCodec||r.codec,sendBytes:r.bytesSent,audioLevel:Math.max(r.audioLevel,0),sendPackets:r.packetsSent,sendPacketsLost:r.packetsLost,sampleRate:r.sampleRate,channelCount:r.channels,rtt:this.connection.peerConnectionStats.roundTripTime||r.roundTripTime,timestamp:r.timestamp,sendBitrate:8*s/a};this.audioStatsMap.set(t,c)}else if(n){var u,l,d=((null===(u=this.transceiver)||void 0===u||null===(u=u.sender)||void 0===u?void 0:u.getParameters())||{}).encodings,p=void 0===d?[]:d,f=(null===(l=this.metricsMap.get(t))||void 0===l?void 0:l.videoMetrics)||{},h=getDeltaDurationInSeconds(n,f),g=getDelta(n.totalBytesSent,f.totalBytesSent),m={codec:this.connection.peerConnectionStats.videoCodec||n.codec,sendFrameRate:Math.round(n.sendFramesPerSecond),captureFrameRate:n.captureFramesPerSecond,encodeFrameRate:n.encodeFramesPerSecond,qpSum:n.totalQpSum||0,targetBitrate:n.targetBitrate,encodeLayers:p.length,sendLayers:p.filter(function(e){return e.active}).length,outgingBitrate:n.availableOutgoingBitrate,sendResolution:{width:n.maxSendFrameWidth,height:n.maxSendFrameHeight},captureResolution:{width:n.captureFrameWidth,height:n.captureFrameHeight},sendBytes:n.totalBytesSent,sendPackets:n.totalPacketsSent,sendPacketsLost:n.totalPacketsLost,timestamp:n.timestamp,rtt:this.connection.peerConnectionStats.roundTripTime||n.roundTripTime,sendBitrate:8*g/h};this.videoStatsMap.set(t,m)}this.metricsMap.set(t,e)}},{key:"getMetrics",value:function(e){var t,r=this;return null===(t=this.connection)||void 0===t?void 0:t.getStats().then(function(){var t;return null===(t=r.monitor)||void 0===t?void 0:t.getStats().then(function(t){return r.handleMetrics(t,e)})})}},{key:"onMonitor",value:function(){var e=this;this.monitor.on("audio-send-stream",function(t){e.reporter.metric.audioSendStream(_objectSpread$4({sessionId:e.id},t))}),this.monitor.on("video-send-stream",function(t){e.reporter.metric.videoSendStream(_objectSpread$4({sessionId:e.id},t))}),this.monitor.on("bwe",function(t){e.reporter.metric.bwe(_objectSpread$4({sessionId:e.id},t))})}}]);var r,n}(EventEmitter),updatePcAndBuildPubMediaSigInfo=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t,r){var n,i,o,a,s,c=arguments;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return n=c.length>2&&void 0!==c[2]?c[2]:["common"],i={},e.next=1,addTransceiversAndSetSdpToPC(r,t);case 1:return o=e.sent,a=o.localSDP,s=o.stream,t.forEach(function(e){var t=e.getTrackId(),o=a.media.find(function(e){return e.mid==r.idToTransceiverMap.get(t).mid});if("audio"===e.trackMediaType)i.audio=[{source:"mic",autoMix:n,trackId:t,msid:s.id,uplinkSsrcGroup:[{ssrc:Number(o.ssrcs[0].id)}]}];else if(e instanceof LocalVideoTrack){var c;i.video=i.video||[];var u=o.ssrcGroups,l=void 0===u?[]:u,d=getSenderEncodingArrAndResoLevel(e),p=d.encodings,f=d.resolutionLevel;p.length>1&&(l=p.map(function(){return{semantics:"FID",ssrcs:"".concat(generateSubSsrc()," ").concat(generateSubSsrc())}}));var h=l.filter(function(e){return"FID"===e.semantics}).map(function(e){return{ssrc:Number(e.ssrcs.split(" ")[0]),rtxSsrc:Number(e.ssrcs.split(" ")[1])}}),g=p[p.length-1],m={trackId:e.getTrackId(),forwardOnly:e.source===exports.VideoSourceInfo.SCREENCAST,msid:s.id,mid:"".concat(o.mid),highestResolutionLevel:f,uplinkSsrcGroup:h,source:e.source||exports.VideoSourceInfo.CAMERA,streamParameters:{ssrc:null==h||null===(c=h[0])||void 0===c?void 0:c.ssrc,bitrate:"".concat(g.maxBitrate),resolution:{width:g.targetWidth,height:g.targetHeight},framerate:g.maxFramerate},ssrcParameters:h.map(function(e,t){var r;return{ssrc:e.ssrc,active:p[t].activeForBitrateMap,tlayer:1,bitrate:p[t].maxBitrate,rid:(null===(r=p[t])||void 0===r?void 0:r.rid)||void 0,maxBitrate:p[t].maxBitrate,minBitrate:p[t].minBitrate,framerate:p[t].maxFramerate,resolution:{width:p[t].targetWidth,height:p[t].targetHeight}}})};i.video.push(m)}}),e.abrupt("return",i);case 2:case"end":return e.stop()}},e)}));return function(t,r){return e.apply(this,arguments)}}(),execBatchPublish=function(e){var t=e.tracks,r=e.connection,n=e.labels,i=e.existedPublications,o=void 0===i?[]:i,a=e.mixedLocalAudioTrack,s={videoPubResultArr:[]},c=[];t.forEach(function(t){var r;if("audio"!==t.trackMediaType||t.source!==exports.AudioSourceInfo.MIC&&t.source!==exports.AudioSourceInfo.SCREENCAST)s.videoPubResultArr.push({publication:new Publication(_objectSpread$4(_objectSpread$4({},e),{},{tracks:[t]})),track:t});else{var n=o.find(function(e){var t,r,n;return"audio"===(null===(t=e.tracks)||void 0===t?void 0:t[0].trackMediaType)&&((null===(r=e.tracks)||void 0===r?void 0:r[0].source)===exports.AudioSourceInfo.MIC||(null===(n=e.tracks)||void 0===n?void 0:n[0].source)===exports.AudioSourceInfo.SCREENCAST)}),i=c.find(function(e){var t,r,n;return"audio"===(null===(t=e.tracks)||void 0===t?void 0:t[0].trackMediaType)&&((null===(r=e.tracks)||void 0===r?void 0:r[0].source)===exports.AudioSourceInfo.MIC||(null===(n=e.tracks)||void 0===n?void 0:n[0].source)===exports.AudioSourceInfo.SCREENCAST)});n?(n.tracks.push(t),r=n):i?(i.tracks.push(t),r=i):r=new Publication(_objectSpread$4(_objectSpread$4({},e),{},{tracks:[a]})),s.audioPubResult={publication:r,track:t}}});var u=t.filter(function(e){return"audio"===e.trackMediaType&&(e.source===exports.AudioSourceInfo.MIC||e.source===exports.AudioSourceInfo.SCREENCAST)});u.forEach(function(e){(null==e?void 0:e.source)===exports.AudioSourceInfo.MIC?a.setMicAudioTrack(e):a.setScreenAudioTrack(e)});var l=[],d=t.filter(function(e){return!("audio"===e.trackMediaType&&(e.source===exports.AudioSourceInfo.MIC||e.source===exports.AudioSourceInfo.SCREENCAST))});if(l.push.apply(l,_toConsumableArray(d)),u.length&&(null==a||a.updateMixedAudioTrackToPub(),a.isPublished()||l.push(a)),l.length){var p,f=new Promise(function(e,t){p=function(){var i=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function i(){var o,c;return _regeneratorRuntime$1.wrap(function(i){for(;;)switch(i.prev=i.next){case 0:return i.next=1,updatePcAndBuildPubMediaSigInfo(l,r,n);case 1:return o=i.sent,c={connectionId:r.id,media:o,simulcast:simulcastEnabledFinally(l.find(function(e){return e.source===exports.VideoSourceInfo.CAMERA})),simulcastVersion:"1.0",clientType:"web",supportTemporalLayer:!1,type:"webrtc"},i.abrupt("return",r.rtcSignaling.batchPublish(c).then(function(){var t=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function t(r){var n,i,o,c,l,d;return _regeneratorRuntime$1.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(n=r.detailStatus,"ok"===(i=r.globalStatus)){t.next=1;break}return s.videoPubResultArr.forEach(function(e){e.error=parsePublishError(e.track,i)}),s.audioPubResult&&(s.audioPubResult.error=parsePublishError(s.audioPubResult.track,i)),t.abrupt("return",e(s));case 1:o=_createForOfIteratorHelper$7(n),t.prev=2,l=_regeneratorRuntime$1.mark(function e(){var t,r,n,i,o,l,d;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:t=c.value,r=t.id,n=t.origin,i=t.msg,a.getTrackId()===n.id?s.audioPubResult&&(o=s.audioPubResult.publication,"ok"===i&&o?(o.initInner(r),a.setPublication(o),u.forEach(function(e){(null==e?void 0:e.source)===exports.AudioSourceInfo.MIC&&e.muted&&e.emit(TRACK_EVENT_NAME,"mute")})):"ok"!==i&&(s.audioPubResult.error=parsePublishError(s.audioPubResult.track,i))):(l=s.videoPubResultArr.find(function(e){return e.track.getTrackId()===n.id}),d=(l||{}).publication,"ok"===i&&d?d.initInner(r):"ok"!==i&&(l.error=parsePublishError(l.track,i)));case 1:case"end":return e.stop()}},e)}),o.s();case 3:if((c=o.n()).done){t.next=5;break}return t.delegateYield(l(),"t0",4);case 4:t.next=3;break;case 5:t.next=7;break;case 6:t.prev=6,d=t.catch(2),o.e(d);case 7:return t.prev=7,o.f(),t.finish(7);case 8:e(s);case 9:case"end":return t.stop()}},t,null,[[2,6,7,8]])}));return function(e){return t.apply(this,arguments)}}()).catch(function(e){logger.info("batchPublishStart error",e),t(e)}));case 2:case"end":return i.stop()}},i)}));return function(){return i.apply(this,arguments)}}()});return r.addTask(p),f}return Promise.resolve({videoPubResultArr:[],audioPubResult:void 0})},batchPublishStop=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t,r){var n,i;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return i=new Promise(function(e,i){n=function(){var n=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function n(){var o,a;return _regeneratorRuntime$1.wrap(function(n){for(;;)switch(n.prev=n.next){case 0:return o=t.filter(function(e){var t;return"audio"===(null===(t=e.tracks)||void 0===t||null===(t=t[0])||void 0===t?void 0:t.trackMediaType)}).map(function(e){return e.id}),a=t.filter(function(e){var t;return"video"===(null===(t=e.tracks)||void 0===t||null===(t=t[0])||void 0===t?void 0:t.trackMediaType)}).map(function(e){return e.id}),n.next=1,adjustUplinkSDPWhenUnpublish(r.connection,t);case 1:r.connection.rtcSignaling.batchUnPublish({connectionId:r.connection.id,audio:o,video:a}).then(function(){t.forEach(function(e){e.clear()}),e(void 0)}).catch(i);case 2:case"end":return n.stop()}},n)}));return function(){return n.apply(this,arguments)}}()}),r.connection.addTask(n),e.abrupt("return",i);case 1:case"end":return e.stop()}},e)}));return function(t,r){return e.apply(this,arguments)}}();function _callSuper$b(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$b()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$b(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$b=function(){return!!e})()}var initPeerConnectionMetrics={audioCodec:"",videoCodec:"",roundTripTime:-1,availableOutgoingBitrate:-1},PeerConnectionMonitor=function(e){function t(e){var r;return _classCallCheck$1(this,t),r=_callSuper$b(this,t),Object.defineProperty(r,"connectionMetrics",{enumerable:!0,configurable:!0,writable:!0,value:Object.assign({},initPeerConnectionMetrics)}),Object.defineProperty(r,"pc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.pc=e.pc,r}return _inherits$1(t,e),_createClass$1(t,[{key:"extractMetrics",value:function(e){var t=Object.assign({},this.connectionMetrics),r="";return e.forEach(function(e){var n;if(!e.isRemote)if(/local-candidate/i.test(e.type)&&e.id===r)Environment.networkType=(null!==(n=e.networkType)&&void 0!==n?n:Environment.networkType).replace("vpn","unknown");else if(/candidate-pair/i.test(e.type)&&"succeeded"===e.state)r=e.localCandidateId,Environment.isFirefox()||(t.roundTripTime=1e3*(e.currentRoundTripTime||e.totalRoundTripTime/e.responsesReceived)),void 0!==e.availableOutgoingBitrate&&(t.availableOutgoingBitrate=e.availableOutgoingBitrate);else if(/codec/i.test(e.type)){var i,o;null!==(i=e.mimeType)&&void 0!==i&&i.includes("audio")?t.audioCodec=e.mimeType.replace("audio/",""):null!==(o=e.mimeType)&&void 0!==o&&o.includes("video")&&(t.videoCodec=e.mimeType.replace("video/",""),t.sdpFmtpLine=e.sdpFmtpLine)}}),this.connectionMetrics=Object.assign({},t),this.connectionMetrics}},{key:"makeReport",value:function(){var e=this;this.getStats().then(function(t){e.emit("metrics",t)})}},{key:"getStats",value:function(){var e=this;if(!this.pc)return Promise.resolve({});if(!this.pc.getStats)throw new DingRTCError(ErrorCode.BrowserNotSupported,"getStats is not supported");return this.pc.getStats(null).then(function(t){return e.extractMetrics(t)})}}])}(Monitor);function _createForOfIteratorHelper$6(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$6(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$6(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$6(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_arrayLikeToArray$6(e,t):void 0}}function _arrayLikeToArray$6(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _callSuper$a(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$a()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$a(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$a=function(){return!!e})()}var PeerConnection=function(e){function t(e){var r,n,i;_classCallCheck$1(this,t),r=_callSuper$a(this,t),Object.defineProperty(r,"pc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"rtcSignaling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"state",{enumerable:!0,configurable:!0,writable:!0,value:PeerConnectionState.New}),Object.defineProperty(r,"processingExchangeSdp",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"monitor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"peerConnectionTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"createPeerConnectionPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"peerConnectionStats",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"createPeerConnectionTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"mcuAudioStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"idToTransceiverMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"mcuAudioTranceiver",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"idToTransceiversMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"mcuAudioTranceivers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"localSDP",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"remoteSDP",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"subSdpFmtpLines",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"sessionManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"prevId",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(r,"offerSDP",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"clientFailoverTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"audioSfuSsrcs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"enquenTask",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"direction",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"startSinglePC",{enumerable:!0,configurable:!0,writable:!0,value:(n=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){var t,n=arguments;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t=n.length>0&&void 0!==n[0]&&n[0],"uplink"===r.direction?(r.pc.addTransceiver("audio",{direction:"sendonly"}),r.pc.addTransceiver("video",{direction:"sendonly"})):(r.mcuAudioStream=null,r.mcuAudioTranceiver=r.pc.addTransceiver("audio",{direction:"recvonly"}),r.pc.addTransceiver("video",{direction:"recvonly"})),t&&adjustOfferWhenFailover(r),e.next=1,r.exchangeSdpForCreatePc(t);case 1:r.state=PeerConnectionState.Idle,r.enquenTask.start();case 2:case"end":return e.stop()}},e)})),function(){return n.apply(this,arguments)})}),Object.defineProperty(r,"onIceGatheringStateChange",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t=e.target.iceGatheringState;r.logger.info("connectionId:".concat(r.id," ice gathering state: ").concat(t))}}),Object.defineProperty(r,"exchangeSdpForCreatePc",{enumerable:!0,configurable:!0,writable:!0,value:(i=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){var t,n,i,o,a,s,c,u,l,d=arguments;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t=d.length>0&&void 0!==d[0]&&d[0],r.processingExchangeSdp=!0,e.prev=1,e.next=2,r.pc.createOffer();case 2:return n=e.sent,r.logger.info("connectionId:".concat(r.id," origin offer"),n),t&&(n.sdp=lib.write(adjustLocalSDPWhenFailover(r.localSDP,lib.parse(n.sdp)))),i=changeLocalSdpForCreatePc(n.sdp,r),r.offerSDP=i,n={type:"offer",sdp:lib.write(i)},e.next=3,r.pc.setLocalDescription(n);case 3:return r.logger.info("connectionId:".concat(r.id," set local sdp success")),o={direction:"downlink"!==r.direction?"in":"out",sdpOffer:n.sdp,connectionId:r.id,isFailover:t,optionsJsonStr:JSON.stringify({supportCVO:1})},t&&((a=lib.parse(n.sdp)).media=a.media.slice(0,2),a.groups=[{mids:"0 1",type:"BUNDLE"}],o.sdpOffer=lib.write(a)),s=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){var t,n,i,a;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(e.prev=0,"connected"===(null===(t=r.sessionManager)||void 0===t||null===(t=t.serviceManager)||void 0===t||null===(t=t.client)||void 0===t?void 0:t.connectionState)){e.next=1;break}throw new Error("signaling disconnected");case 1:if(o.isFailover||!r.prevId){e.next=3;break}return e.next=2,r.stopSinglePC(!0);case 2:r.id="".concat(r.direction,"_").concat(createUuid()),o.connectionId=r.id;case 3:return r.prevId=r.id,e.next=4,r.rtcSignaling.createPeerConnection(o);case 4:return n=e.sent,i=n.sdpAnswer,r.logger.info("connectionId:".concat(r.id," receive answer success")),e.abrupt("return",i);case 5:throw e.prev=5,a=e.catch(0),r.logger.error("connectionId:".concat(r.id," signal createpc failed: ").concat(a)),a;case 6:case"end":return e.stop()}},e,null,[[0,5]])}));return function(){return e.apply(this,arguments)}}(),e.next=4,multiTryExecute({fn:s,times:3,interval:2e3});case 4:return c=e.sent,u=changeRemoteSdpForCreatePc(c,r,t),e.next=5,r.pc.setRemoteDescription({sdp:u,type:"answer"});case 5:e.next=7;break;case 6:return e.prev=6,l=e.catch(1),r.logger.error("connectionId:".concat(r.id," Failed to exchangeSDP. Message: ").concat(l.message)),r.fireEndedEvent(),e.abrupt("return",Promise.reject(l));case 7:return e.prev=7,r.processingExchangeSdp=!1,e.finish(7);case 8:case"end":return e.stop()}},e,null,[[1,6,7,8]])})),function(){return i.apply(this,arguments)})}),r.pc=null;var o=e.direction,a=e.sessionManager;return r.rtcSignaling=a.serviceManager.rtcSignaling,r.sessionManager=a,r.reporter=a.reporter,r.logger=r.reporter.getLoggerWithPrefix("[rtc-peerconn]"),r.enquenTask=taskQueue(),r.subSdpFmtpLines=[],r.direction=o,r.idToTransceiverMap=new Map,r.idToTransceiversMap=new Map,r.createPeerConnection(),r.id="".concat(r.direction,"_").concat(createUuid()),r}return _inherits$1(t,e),_createClass$1(t,[{key:"stopSinglePC",value:function(){return arguments.length>0&&void 0!==arguments[0]&&arguments[0]||this.emit("ended"),this.rtcSignaling.closePeerConnection({connectionId:this.id,direction:"downlink"===this.direction?"out":"in"})}},{key:"closePeerConnection",value:function(){this.pc&&(this.logger.info("connectionId:".concat(this.id," clear RTC PeerConnection.")),this.detachEvents(),"closed"!==this.pc.signalingState&&this.pc.close(),this.pc=null)}},{key:"onTrack",value:function(e){var t=e.track,r=e.streams;"audio"===t.kind?clientConfig.audioSFU?this.emit("track",t,r[0]):this.mcuAudioStream=new MediaStream([t]):this.emit("track",t)}},{key:"fireEndedEvent",value:function(){this.state!==PeerConnectionState.Ended&&(this.state=PeerConnectionState.Ended,this.emit("ended"))}},{key:"onIceConnectionStateChange",value:function(){var e=this.pc.iceConnectionState;this.logger.info("connectionId:".concat(this.id," ICE connection state changed to ").concat(e))}},{key:"onIceCandidate",value:function(e){var t=candidateToPlainObj(null==e?void 0:e.candidate);this.logger.info("connectionId:".concat(this.id," onIceCandidate"),t)}},{key:"clearPcForReoffer",value:(r=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){var t;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(this.state!==PeerConnectionState.New){e.next=1;break}return e.abrupt("return",Promise.reject());case 1:return this.logger.info("connectionId:".concat(this.id,": start client reoffer")),e.prev=2,e.next=3,this.stopSinglePC(!0);case 3:this.removeAllListeners(),e.next=5;break;case 4:e.prev=4,t=e.catch(2),this.logger.info("connectionId:".concat(this.id," client reoffer close failed ").concat(tryJsonStringify(t)));case 5:this.closePeerConnection();case 6:case"end":return e.stop()}},e,this,[[2,4]])})),function(){return r.apply(this,arguments)})},{key:"addTask",value:function(e){this.enquenTask.add(e)}},{key:"onConnectionStateChange",value:function(){var e=this,t=this.pc.connectionState;this.reporter.trace.connectionsEvent(this.id,t),this.logger.info("connectionId:".concat(this.id," connection state changed to ").concat(t)),"failed"===t||"closed"===t?(this.clientFailoverTimer&&removeTimer(this.clientFailoverTimer),this.clientFailoverTimer=addTimer(function(){e.state!==PeerConnectionState.New&&(e.logger.info("connectionId:".concat(e.id,": emit reoffer")),e.emit("reoffer"))},SIGNAL_CALL_TIMEOUT)):"connected"===t&&(this.clientFailoverTimer&&(removeTimer(this.clientFailoverTimer),this.clientFailoverTimer=null),this.createPeerConnectionTimer&&(removeTimer(this.createPeerConnectionTimer),this.createPeerConnectionTimer=null))}},{key:"getPeerConnectionConfig",value:function(){var e=this.sessionManager.serviceManager.iceConfig,t=e.username,r=e.password,n=e.port,i=e.iceServerList,o={bundlePolicy:"max-bundle",iceTransportPolicy:"all",sdpSemantics:"unified-plan"};if(i.length){var a,s=[],c=_createForOfIteratorHelper$6(i);try{for(c.s();!(a=c.n()).done;){var u=a.value;s.push("turn:".concat(u,":").concat(n,"?transport=udp"),"turn:".concat(u,":").concat(n,"?transport=tcp"))}}catch(e){c.e(e)}finally{c.f()}Environment.isFirefox()&&s.splice(4,2),o.iceServers=[{urls:s,username:t,credential:r}]}return this.logger.info("PeerConnectionConfig",o),o}},{key:"createPeerConnection",value:function(){var e=this;this.pc?this.logger.warn("connectionId:".concat(this.id," A PeerConnection was created. Cannot create again for the same PeerConnectionChannel.")):(this.pc=new RTCPeerConnection(this.getPeerConnectionConfig()),this.attachEvents(),this.createPeerConnectionTimer=addTimer(function(){var t;"connected"===(null===(t=e.pc)||void 0===t?void 0:t.connectionState)||e.processingExchangeSdp||(e.logger.info("connectionId:".concat(e.id,": emit reoffer")),e.emit("reoffer"))},clientConfig.connectPcTimeoutMs))}},{key:"attachEvents",value:function(){var e=this;this.pc&&(this.pc.ontrack=function(t){e.onTrack(t)},this.pc.oniceconnectionstatechange=function(){e.onIceConnectionStateChange()},this.pc.onicecandidate=function(t){e.onIceCandidate(t)},this.pc.onconnectionstatechange=function(){e.onConnectionStateChange()},this.pc.onicegatheringstatechange=function(t){e.onIceGatheringStateChange(t)},this.monitor=new PeerConnectionMonitor(this),this.monitor.on("metrics",function(t){e.peerConnectionStats=t}))}},{key:"getStats",value:function(){var e,t,r=this;return this.monitor?null===(e=this.monitor)||void 0===e||null===(t=e.getStats)||void 0===t?void 0:t.call(e).then(function(e){r.peerConnectionStats=e}):Promise.resolve()}},{key:"detachEvents",value:function(){this.createPeerConnectionTimer&&removeTimer(this.createPeerConnectionTimer),this.clientFailoverTimer&&removeTimer(this.clientFailoverTimer),this.pc&&(this.pc.ontrack=null,this.pc.oniceconnectionstatechange=null,this.pc.onconnectionstatechange=null,this.pc.onicegatheringstatechange=null,this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null)}},{key:"reoffer",value:function(){return this.state===PeerConnectionState.New?Promise.reject():(this.logger.info("connectionId:".concat(this.id," start reoffer")),this.closePeerConnection(),this.idToTransceiverMap=new Map,this.idToTransceiversMap=new Map,this.createPeerConnection(),this.state=PeerConnectionState.New,this.startSinglePC(!0))}},{key:"handleHighProfileFallback",value:function(){clientConfig.downlinkForbidHighProfile=!0,this.logger.info("connectionId:".concat(this.id," start reoffer for disable highProfile")),this.emit("reoffer")}},{key:"handleVideoSubStucked",value:function(e){this.logger.info("connectionId".concat(this.id,": start reoffer for sub:").concat(e.id," video stucked")),this.idToTransceiverMap.delete(e.stream.id),this.sessionManager.handleStuckResubscribe([e])}}]);var r}(EventEmitter);function _callSuper$9(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$9()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$9(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$9=function(){return!!e})()}var MixedLocalAudioTrack=function(e){function t(e){var r;return _classCallCheck$1(this,t),r=_callSuper$9(this,t),Object.defineProperty(r,"_micAudioTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"_screenAudioTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"mixedAudioTrackResult",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(r,"publication",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"serviceManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"_trackId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"trackMediaType",{enumerable:!0,configurable:!0,writable:!0,value:"audio"}),Object.defineProperty(r,"audioContext",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"selfMicMutedProperty",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"isPublished",{enumerable:!0,configurable:!0,writable:!0,value:function(){return!!r.publication}}),Object.defineProperty(r,"setPublication",{enumerable:!0,configurable:!0,writable:!0,value:function(e){r.logger.info("setPublication",null==e?void 0:e.id),r.publication=e}}),Object.defineProperty(r,"getPublication",{enumerable:!0,configurable:!0,writable:!0,value:function(){return r.publication}}),Object.defineProperty(r,"micTrackEventHandler",{enumerable:!0,configurable:!0,writable:!0,value:r._audioTrackInnerEventHandler.bind(r,exports.AudioSourceInfo.MIC)}),Object.defineProperty(r,"screenAudioTrackEventHandler",{enumerable:!0,configurable:!0,writable:!0,value:r._audioTrackInnerEventHandler.bind(r,exports.AudioSourceInfo.SCREENCAST)}),Object.defineProperty(r,"updateMixedAudioTrackToPub",{enumerable:!0,configurable:!0,writable:!0,value:function(){var e,t,n,i,o,a,s;r.logger.info("updateMixTrack",null===(e=r._micAudioTrack)||void 0===e?void 0:e.getTrackId(),null===(t=r._screenAudioTrack)||void 0===t?void 0:t.getTrackId()),null===(n=r.mixedAudioTrackResult)||void 0===n||null===(n=n.mixedTrack)||void 0===n||n.stop(),r.mixedAudioTrackResult=r.mixAudioTracks(null===(i=r._micAudioTrack)||void 0===i?void 0:i.getMediaStreamTrack(),null===(o=r._screenAudioTrack)||void 0===o?void 0:o.getMediaStreamTrack()),null===(a=r.publication)||void 0===a||a.replaceTrack(null===(s=r.mixedAudioTrackResult)||void 0===s?void 0:s.mixedTrack)}}),Object.defineProperty(r,"clear",{enumerable:!0,configurable:!0,writable:!0,value:function(){var e;r.logger.info("clear"),null===(e=r.mixedAudioTrackResult)||void 0===e||null===(e=e.mixedTrack)||void 0===e||e.stop(),r._micAudioTrack=null,r._screenAudioTrack=null,r.publication=void 0}}),Object.defineProperty(r,"getMediaStreamTrack",{enumerable:!0,configurable:!0,writable:!0,value:function(){var e;return(null===(e=r.mixedAudioTrackResult)||void 0===e?void 0:e.mixedTrack)||null}}),r.logger=e.reporter.getLoggerWithPrefix("[rtc-mixedAudioTrack]"),r.serviceManager=e,r._trackId="audio_".concat(createUuid(6)),r}return _inherits$1(t,e),_createClass$1(t,[{key:"getTrackId",value:function(){return this._trackId}},{key:"getScreenAudioTrack",value:function(){return this._screenAudioTrack}},{key:"setScreenAudioTrack",value:function(e){var t,r,n;(this.logger.info("setScreenAudioTrack",null==e?void 0:e.getTrackId()),null===(t=this._screenAudioTrack)||void 0===t||t.off(TRACK_EVENT_NAME,this.screenAudioTrackEventHandler),this._screenAudioTrack=e,null===(r=this._screenAudioTrack)||void 0===r||r.on(TRACK_EVENT_NAME,this.screenAudioTrackEventHandler),e)?e.muted||(this.notifyScreenAudioEnabled(!0),null===(n=this.publication)||void 0===n||n.unmute()):this.notifyScreenAudioEnabled(!1)}},{key:"getMicAudioTrack",value:function(){return this._micAudioTrack}},{key:"setMicAudioTrack",value:function(e){var t,r;this.logger.info("setMicAudioTrack",null==e?void 0:e.getTrackId()),null===(t=this._micAudioTrack)||void 0===t||t.off(TRACK_EVENT_NAME,this.micTrackEventHandler),this._micAudioTrack=e,null===(r=this._micAudioTrack)||void 0===r||r.on(TRACK_EVENT_NAME,this.micTrackEventHandler),this._micAudioTrack&&(this._micAudioTrack.muted&&!this.selfMicMutedProperty?(this.setSelfMicMutedProperty(!0),this.notifyMicDeviceMuted(!0)):!this._micAudioTrack.muted&&this.selfMicMutedProperty&&(this.setSelfMicMutedProperty(!1),this.notifyMicDeviceMuted(!1)))}},{key:"_audioTrackInnerEventHandler",value:function(e,t){if("localMixedAudioReplaceTrack"===t)this.updateMixedAudioTrackToPub();else if("stop"===t){var r,n,i;if(e===exports.AudioSourceInfo.MIC?this.setMicAudioTrack(null):this.setScreenAudioTrack(null),this.updateMixedAudioTrackToPub(),null===(r=this.mixedAudioTrackResult)||void 0===r||!r.mixedTrack)if(this.logger.warn("mixedAudioTrackResult is null, stop pub audio, pubid=",null===(n=this.publication)||void 0===n?void 0:n.id),this.publication)null===(i=this.publication)||void 0===i||i.stop(),this.publication=null}else if("mute"===t){e===exports.AudioSourceInfo.SCREENCAST?this.notifyScreenAudioEnabled(!1):this.selfMicMutedProperty||(this.setSelfMicMutedProperty(!0),this.notifyMicDeviceMuted(!0));var o=e===exports.AudioSourceInfo.MIC?this._screenAudioTrack:this._micAudioTrack;o&&!o.muted&&o.enabled||this.publication.mute()}else"unmute"===t?(e===exports.AudioSourceInfo.SCREENCAST?this.notifyScreenAudioEnabled(!0):this.selfMicMutedProperty&&(this.setSelfMicMutedProperty(!1),this.notifyMicDeviceMuted(!1)),this.publication.unmute()):this.logger.info("unhandled action",t)}},{key:"setSelfMicMutedProperty",value:function(e){this.selfMicMutedProperty=e}},{key:"notifyMicDeviceMuted",value:function(e){return this.serviceManager.rtcUserManager.notifyParticipantProperties(JSON.stringify({mute_audio_record:e?1:0}))}},{key:"notifyScreenAudioEnabled",value:function(e){return this.serviceManager.rtcUserManager.notifyParticipantProperties(JSON.stringify({enable_sys_audio:e?1:0}))}},{key:"mixAudioTracks",value:function(e,t){var r;if(!e&&!t)return null;var n=getAudioContext();this.audioContext=n;var i=n.createMediaStreamDestination();return e&&n.createMediaStreamSource(new MediaStream([e])).connect(i),t&&n.createMediaStreamSource(new MediaStream([t])).connect(i),{mixedTrack:null===(r=i.stream.getAudioTracks())||void 0===r?void 0:r[0],isOriginTrack:!1}}}])}(EventEmitter);function ownKeys$3(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function _objectSpread$3(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$3(Object(r),!0).forEach(function(t){_defineProperty(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$3(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function _createForOfIteratorHelper$5(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$5(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$5(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$5(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_arrayLikeToArray$5(e,t):void 0}}function _arrayLikeToArray$5(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _callSuper$8(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$8()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$8(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$8=function(){return!!e})()}var media_reconnect_duration_ms=45e3,media_reconnect_single_round_min_duration_ms=2e3,SessionManager=function(e){function t(e,r){var n,i,o,a;return _classCallCheck$1(this,t),n=_callSuper$8(this,t),Object.defineProperty(n,"client",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(n,"sessions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"networkQualityInterval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"lastChannelNetworkQuality",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"uplink",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"downlink",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"streamIdToSessionId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"serviceManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"mixedLocalAudioTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"republishPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"resubscribePromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"handleRepublish",{enumerable:!0,configurable:!0,writable:!0,value:(i=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:n.republishPromise=n._handleRepub(),n.republishPromise.finally(function(){n.republishPromise=null});case 1:case"end":return e.stop()}},e)})),function(){return i.apply(this,arguments)})}),Object.defineProperty(n,"handleResubscribe",{enumerable:!0,configurable:!0,writable:!0,value:(o=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){var t,r=arguments;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:t=r.length>0&&void 0!==r[0]&&r[0],n.resubscribePromise=n._handleResubscribe(t),n.resubscribePromise.finally(function(){n.resubscribePromise=null});case 1:case"end":return e.stop()}},e)})),function(){return o.apply(this,arguments)})}),Object.defineProperty(n,"_handleResubscribe",{enumerable:!0,configurable:!0,writable:!0,value:(a=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){var t,r,i,o,a,s,c,u,l,d,p,f,h,g,m,v,y,b,S,_,E,T,R,C,k,P,w,O,I,A,M,N,D,x,L,j,$,U,F,V,G=arguments;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:r=G.length>0&&void 0!==G[0]&&G[0],n.logger.info("handle resub fromServer=",r),i=r?"server":"client",o=[],a=_createForOfIteratorHelper$5(n.sessions.values());try{for(a.s();!(s=a.n()).done;)(c=s.value)instanceof Subscription&&c.state===PubSubStates.Processing&&(u=null,c.stream.media.video?(l=n.serviceManager.rtcUserManager.users.get(c.uid),u="camera"===c.stream.media.video.source?null==l?void 0:l.videoTrack:null==l?void 0:l.auxiliaryTrack):c.stream.media.audio?u=n.serviceManager.remoteAudioTrack:n.logger.error("unknown media type for resub",c.stream),o.push({stream:c.stream,uid:c.uid,targetMediaType:c.targetMediaType,resolutionInfo:c.userConfigResolution,session:c,track:u}))}catch(e){a.e(e)}finally{a.f()}if(d=o.map(function(e){return e.uid}).join(),o.length){n.logger.info("resubscribe start ".concat(d)),n.client.emit("media-reconnect-start",n.client.userId),p=_createForOfIteratorHelper$5(o);try{for(p.s();!(f=p.n()).done;)m=f.value,n.logger.info("emitted sub-media-reconnect-started",null===(h=m.track)||void 0===h?void 0:h.getTrackId()),n.client.emit("sub-media-reconnect-started",null===(g=m.track)||void 0===g?void 0:g.getTrackId())}catch(e){p.e(e)}finally{p.f()}}v=null===(t=n.downlink)||void 0===t?void 0:t.id,y=Date.now(),b=y+media_reconnect_duration_ms,S=!1,_=n.serviceManager.rtcUserManager.currentSelfPid,E=0;case 1:if(!(E<23&&Date.now()<=b)){e.next=10;break}if(!((T=Date.now())<y+E*media_reconnect_single_round_min_duration_ms)){e.next=2;break}return e.next=2,asyncDelayMs(y+E*media_reconnect_single_round_min_duration_ms-T);case 2:if(n.logger.debug("resub round=".concat(E,", channelconnect=").concat(n.serviceManager.internalChannel.connectionState)),"connected"===n.serviceManager.internalChannel.connectionState){e.next=3;break}return e.abrupt("continue",9);case 3:return e.prev=3,n.reporter.trace.connectionsEvent(v,"".concat(i,"ReofferStart")),e.next=4,null===(R=n.downlink)||void 0===R?void 0:R.clearPcForReoffer();case 4:if(n.downlink=null,!o.length){e.next=7;break}return e.next=5,n.batchSubscribe(o);case 5:if(C=e.sent,n.serviceManager.rtcUserManager.currentSelfPid===_){e.next=6;break}return n.logger.error("abort resubscribe for selfCurrentPid changed from to",_,n.serviceManager.rtcUserManager.currentSelfPid),e.abrupt("return");case 6:k=_createForOfIteratorHelper$5(C);try{for(k.s();!(P=k.n()).done;)w=P.value,O=w.subscription,I=w.error,O&&!I&&n.handleResubSuccess(O)}catch(e){k.e(e)}finally{k.f()}n.reporter.trace.connectionsEvent(v,"".concat(i,"ReofferSuccess")),n.logger.debug("resub round=".concat(E," resubscribe ").concat(d," success")),n.client.emit("media-reconnect-end",d),A=_createForOfIteratorHelper$5(o);try{for(A.s();!(M=A.n()).done;)x=M.value,n.logger.info("emitted sub-media-reconnect-succeeded",null===(N=x.track)||void 0===N?void 0:N.getTrackId()),n.client.emit("sub-media-reconnect-succeeded",null===(D=x.track)||void 0===D?void 0:D.getTrackId())}catch(e){A.e(e)}finally{A.f()}case 7:return S=!0,e.abrupt("continue",10);case 8:if(e.prev=8,V=e.catch(3),n.logger.debug("resub round=".concat(E," resubscribe failed for"),V),n.serviceManager.rtcUserManager.currentSelfPid===_){e.next=9;break}return n.logger.error("abort resubscribe for selfCurrentPid changed from to",_,n.serviceManager.rtcUserManager.currentSelfPid),e.abrupt("return");case 9:E++,e.next=1;break;case 10:if(!S){if(n.reporter.trace.connectionsEvent(v,"".concat(i,"ReofferFailed")),n.downlink.clearPcForReoffer(),n.downlink=null,o.length){n.client.emit("media-reconnect-end",d),L=_createForOfIteratorHelper$5(o);try{for(L.s();!(j=L.n()).done;)F=j.value,n.logger.info("emitted sub-media-reconnect-failed",null===($=F.track)||void 0===$?void 0:$.getTrackId()),n.client.emit("sub-media-reconnect-failed",null===(U=F.track)||void 0===U?void 0:U.getTrackId())}catch(e){L.e(e)}finally{L.f()}}o.forEach(function(e){if(n.removeSession(e.session.id),"audio"===e.session.targetMediaType){var t,r;null===(t=n.serviceManager.remoteAudioTrack)||void 0===t||t.stopPlay(),null===(r=n.serviceManager.remoteAudioTrack)||void 0===r||null===(r=r.getMediaStreamTrack())||void 0===r||r.stop(),n.serviceManager.remoteAudioTrack=null}else{var i,o,a,s,c=n.serviceManager.rtcUserManager.users.get(e.session.uid);"camera"===e.session.stream.media.video.source?(null===(i=c.videoTrack)||void 0===i||i.stopPlay(),null===(o=c.videoTrack)||void 0===o||null===(o=o.getMediaStreamTrack())||void 0===o||o.stop(),c.videoTrack=null):(null===(a=c.auxiliaryTrack)||void 0===a||a.stopPlay(),null===(s=c.auxiliaryTrack)||void 0===s||null===(s=s.getMediaStreamTrack())||void 0===s||s.stop(),c.auxiliaryTrack=null)}})}case 11:case"end":return e.stop()}},e,null,[[3,8]])})),function(){return a.apply(this,arguments)})}),n.serviceManager=r,n.client=e,n.reporter=r.reporter,n.logger=n.reporter.getLoggerWithPrefix("[rtc-sessionMgr]"),n.streamIdToSessionId=new Map,n.sessions=new Map,n.mixedLocalAudioTrack=new MixedLocalAudioTrack(r),n.handleMediaMessage=n.handleMediaMessage.bind(n),n.handleServerFailover=n.handleServerFailover.bind(n),n}return _inherits$1(t,e),_createClass$1(t,[{key:"getOrCreatePeerConnection",value:(h=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r=this;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if("uplink"!==t){e.next=3;break}if(this.uplink){e.next=2;break}return this.uplink=new PeerConnection({direction:t,sessionManager:this}),e.next=1,this.uplink.startSinglePC();case 1:this.uplink.on("reoffer",this.handleRepublish),this.uplink.on("ended",function(){r.uplink=null});case 2:return e.abrupt("return",this.uplink);case 3:if(this.downlink){e.next=5;break}return this.downlink=new PeerConnection({direction:t,sessionManager:this}),e.next=4,this.downlink.startSinglePC();case 4:this.downlink.on("reoffer",this.handleResubscribe),this.downlink.on("ended",function(){r.downlink=null});case 5:return e.abrupt("return",this.downlink);case 6:case"end":return e.stop()}},e,this)})),function(e){return h.apply(this,arguments)})},{key:"_handleRepub",value:(f=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){var t,r,n,i,o,a,s,c,u,l,d,p,f,h,g,m,v,y,b,S,_,E,T;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(this.logger.info("handle repub"),r=_toConsumableArray(this.client.localTracks),this.mixedLocalAudioTrack.clear(),r.length){this.client.emit("media-reconnect-start",this.client.userId),n=_createForOfIteratorHelper$5(r);try{for(n.s();!(i=n.n()).done;)o=i.value,this.logger.info("emitted pub-media-reconnect-started",o.getTrackId()),this.client.emit("pub-media-reconnect-started",o.getTrackId())}catch(e){n.e(e)}finally{n.f()}}a=null===(t=this.uplink)||void 0===t?void 0:t.id,s=Date.now(),c=s+media_reconnect_duration_ms,u=!1,l=0,l=0;case 1:if(!(l<23&&Date.now()<=c||"disconnected"!==this.serviceManager.internalChannel.connectionState)){e.next=9;break}if(!((d=Date.now())<s+l*media_reconnect_single_round_min_duration_ms)){e.next=2;break}return e.next=2,asyncDelayMs(s+l*media_reconnect_single_round_min_duration_ms-d);case 2:if(this.logger.debug("repub round=".concat(l,", channelconnect=").concat(this.serviceManager.internalChannel.connectionState)),"connected"===this.serviceManager.internalChannel.connectionState){e.next=3;break}return e.abrupt("continue",8);case 3:return e.prev=3,this.reporter.trace.connectionsEvent(a,"clientReofferStart"),this.logger.info("repub round=".concat(l,", clearPcForReoffer start ").concat(r.map(function(e){return e.trackMediaType}).join())),e.next=4,null===(p=this.uplink)||void 0===p?void 0:p.clearPcForReoffer();case 4:if(this.uplink=null,this.logger.info("repub round=".concat(l,", batchPublish start ").concat(r.map(function(e){return e.trackMediaType}).join())),!r.length){e.next=6;break}return e.next=5,this.batchPublish(r);case 5:this.logger.info("".concat(this.client.userId," batchPublish finished for repub")),this.logger.info("emitted media-reconnect-end",this.client.userId),this.client.emit("media-reconnect-end",this.client.userId),f=_createForOfIteratorHelper$5(r);try{for(f.s();!(h=f.n()).done;)g=h.value,this.logger.info("emitted pub-media-reconnect-succeeded",g.getTrackId()),this.client.emit("pub-media-reconnect-succeeded",g.getTrackId())}catch(e){f.e(e)}finally{f.f()}case 6:return this.reporter.trace.connectionsEvent(a,"clientReofferSuccess"),u=!0,e.abrupt("continue",9);case 7:e.prev=7,E=e.catch(3),this.logger.error("".concat(this.client.userId," republish failed for"),E);case 8:l++,e.next=1;break;case 9:if(this.logger.info("break from repub loop roundNum, connectionstate",l,this.serviceManager.internalChannel.connectionState),u){e.next=14;break}if(this.reporter.trace.connectionsEvent(a,"clientReofferFailed"),"connected"!==this.serviceManager.internalChannel.connectionState){e.next=13;break}return e.prev=10,this.logger.info("unpub all tracks after repub failed"),e.next=11,this.serviceManager.unpublish(r);case 11:e.next=13;break;case 12:e.prev=12,T=e.catch(10),this.logger.info("err for unpub after repub failed",T);case 13:if(null===(m=this.uplink)||void 0===m||m.clearPcForReoffer(),this.uplink=null,r.length){this.client.emit("media-reconnect-end",this.client.userId),v=_createForOfIteratorHelper$5(r);try{for(v.s();!(y=v.n()).done;)b=y.value,(S=this.streamIdToSessionId.get(b.getTrackId()))&&(this.logger.info("clear old publication for repub failed",S),null===(_=this.sessions.get(S))||void 0===_||_.clear(),this.sessions.delete(S)),this.logger.info("emitted pub-media-reconnect-failed",b.getTrackId()),this.client.emit("pub-media-reconnect-failed",b.getTrackId())}catch(e){v.e(e)}finally{v.f()}}case 14:case"end":return e.stop()}},e,this,[[3,7],[10,12]])})),function(){return f.apply(this,arguments)})},{key:"handleStuckResubscribe",value:(p=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n,i,o,a,s,c,u,l,d,p,f;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if("connected"===this.serviceManager.internalChannel.connectionState){e.next=1;break}return this.logger.info("ignore for inner not connected"),e.abrupt("return");case 1:r=[],n=_createForOfIteratorHelper$5(t);try{for(n.s();!(i=n.n()).done;)(o=i.value)instanceof Subscription&&o.state===PubSubStates.Processing&&(r.push({stream:o.stream,uid:o.uid,targetMediaType:o.targetMediaType,resolutionInfo:o.userConfigResolution,session:o,profileFallback:!0}),this.removeSession(o.id))}catch(e){n.e(e)}finally{n.f()}return a=r.map(function(e){return e.uid}).join(),this.client.emit("media-reconnect-start",a),this.logger.info("resubscribe ".concat(a," start")),e.prev=2,e.next=3,this.batchUnscribe(r);case 3:return e.next=4,this.batchSubscribe(r);case 4:s=e.sent,c=_createForOfIteratorHelper$5(s);try{for(c.s();!(u=c.n()).done;)l=u.value,d=l.subscription,p=l.error,d&&!p&&this.handleResubSuccess(d)}catch(e){c.e(e)}finally{c.f()}this.client.emit("media-reconnect-end",a),e.next=6;break;case 5:e.prev=5,f=e.catch(2),this.logger.debug("".concat(this.client.userId," resubscribe failed for"),f),this.client.emit("media-reconnect-end",a),this.serviceManager.rtcSignaling.emit("connection-state-change","disconnected",this.client.connectionState,"network_error");case 6:case"end":return e.stop()}},e,this,[[2,5]])})),function(e){return p.apply(this,arguments)})},{key:"getSessionByStreamId",value:function(e){return e?this.sessions.get(this.streamIdToSessionId.get(e)):null}},{key:"handleResubSuccess",value:function(e){var t,r=e.uid,n=e.mediaStream,i=(null===(t=e.stream.media.video)||void 0===t?void 0:t.source)===exports.VideoSourceInfo.SCREENCAST,o=n.getAudioTracks()[0],a=n.getVideoTracks()[0],s=o?"audio":i?"screen":"camera";if(this.logger.debug("".concat(r," resubscribe ").concat(s," success")),o&&this.serviceManager.remoteAudioTrack){var c,u;if(clientConfig.audioSFU)null===(c=(u=this.serviceManager.remoteAudioTrack).replaceStream)||void 0===c||c.call(u,n);else this.serviceManager.remoteAudioTrack.replaceTrack(o)}else{var l=this.serviceManager.rtcUserManager.remoteUsers.find(function(e){return e.userId===r});a&&null!=l&&l.auxiliaryTrack&&i?l.auxiliaryTrack.replaceTrack(a):a&&null!=l&&l.videoTrack&&!i&&l.videoTrack.replaceTrack(a)}}},{key:"handleServerFailover",value:function(e){var t=this;this.logger.debug("serverFailover",e);var r,n=e.actions,i=_createForOfIteratorHelper$5(void 0===n?[]:n);try{var o=function(){var e,n,i=r.value,o=i.actionName,a=i.connectionId;if("reoffer"!==o)return 1;if(a===(null===(e=t.uplink)||void 0===e?void 0:e.id)){var s=t.uplink,c=t.client,u=c.userId,l=c.localTracks;t.client.emit("media-reconnect-start",u),t.reporter.trace.connectionsEvent(a,"serverReofferStart"),s.reoffer().then(function(){t.logger.info("".concat(u," republish ").concat(l.map(function(e){return e.trackMediaType}).join()," success")),t.reporter.trace.connectionsEvent(a,"serverReofferSuccess"),t.client.emit("media-reconnect-end",u)}).catch(function(e){t.logger.debug("".concat(t.client.userId," republish failed for"),e),t.reporter.trace.connectionsEvent(a,"serverReofferFailed"),t.serviceManager.rtcSignaling.emit("connection-state-change","disconnected",t.client.connectionState,"network_error")})}else a===(null===(n=t.downlink)||void 0===n?void 0:n.id)&&t.handleResubscribe(!0)};for(i.s();!(r=i.n()).done;)o()}catch(e){i.e(e)}finally{i.f()}}},{key:"addSession",value:function(e,t){this.sessions.set(t.id,t),this.streamIdToSessionId.set(e,t.id)}},{key:"getNetworkQuality",value:function(e,t){return e>50||t>600?NetworkQualityType.BAD:e>30||t>450?NetworkQualityType.POOR:e>20||t>300?NetworkQualityType.NORMAL:e>10||t>200?NetworkQualityType.GOOD:e>=0||t>=0?NetworkQualityType.GREAT:NetworkQualityType.UNKNOWN}},{key:"checkChannelNetworkQuality",value:(d=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){var t,r=this;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(0!==(t=_toConsumableArray(this.sessions.values())).length){e.next=1;break}return this.emit("network-quality",NetworkQualityType.UNKNOWN,NetworkQualityType.UNKNOWN),e.abrupt("return");case 1:if(0!==t.filter(function(e){var t,r=e.connection;return"connected"===(null==r||null===(t=r.pc)||void 0===t?void 0:t.connectionState)}).length){e.next=2;break}return this.emit("network-quality",NetworkQualityType.DISCONNECTED,NetworkQualityType.DISCONNECTED),e.abrupt("return");case 2:Promise.all([this.getLocalVideoStats(),this.getLocalAudioStats(),this.getRemoteAudioStats(),this.getRemoteVideoStats()]).then(function(e){var t=_slicedToArray(e,4),n=t[0],i=t[1],o=t[2],a=t[3],s=0,c=0,u=0,l=0,d=0,p=0;if(n){var f=n.camera,h=n.auxiliary;f&&(c+=f.sendPacketsLost,s+=f.sendPackets,d=Math.max(d,f.rtt||0)),h&&(c+=h.sendPacketsLost,s+=h.sendPackets,d=Math.max(d,h.rtt||0))}for(var g in i&&(c+=i.sendPacketsLost||0,s+=i.sendPackets||0,d=Math.max(d,i.rtt||0)),o&&(u+=o.receivePacketsLost||0,l+=o.receivePackets||0,p=Math.max(p,o.rtt||0)),a){var m=a[g],v=m.camera,y=m.auxiliary;v&&(u+=v.receivePacketsLost,l+=v.receivePackets,p=Math.max(p,v.rtt||0)),y&&(u+=y.receivePacketsLost,l+=y.receivePackets,p=Math.max(p,y.rtt||0))}var b=-1,S=-1,_={timestamp:Date.now(),totalUplinkPacketsLost:c,totalUplinkPacketsSent:s,totalDownlinkPacketsLost:u,totalDownlinkPacketsRecv:l};if(s){var E,T,R=c-((null===(E=r.lastChannelNetworkQuality)||void 0===E?void 0:E.totalUplinkPacketsLost)||0);if(R<0&&(R=c),_.totalUplinkPacketsSentForLost=(null===(T=r.lastChannelNetworkQuality)||void 0===T?void 0:T.totalUplinkPacketsSentForLost)||0,0!==R){var C;_.totalUplinkPacketsSentForLost=s;var k=s-((null===(C=r.lastChannelNetworkQuality)||void 0===C?void 0:C.totalUplinkPacketsSentForLost)||0);k<0&&(k=s),b=R/k}}if(l){var P,w,O,I,A=u-((null===(P=r.lastChannelNetworkQuality)||void 0===P?void 0:P.totalDownlinkPacketsLost)||0);A<0&&(A=u),_.totalDownlinkPacketsRecvForLost=(null===(w=r.lastChannelNetworkQuality)||void 0===w?void 0:w.totalDownlinkPacketsRecvForLost)||0,null===(O=r.lastChannelNetworkQuality)||void 0===O||O.totalDownlinkPacketsRecvForLost,A&&(u!==((null===(I=r.lastChannelNetworkQuality)||void 0===I?void 0:I.totalDownlinkPacketsLost)||0)&&(_.totalDownlinkPacketsRecvForLost=l),S=A/l)}r.emit("network-quality",r.getNetworkQuality(Math.min(100*b,100),d),r.getNetworkQuality(Math.min(100*S,100),p)),r.lastChannelNetworkQuality=_});case 3:case"end":return e.stop()}},e,this)})),function(){return d.apply(this,arguments)})},{key:"removeSession",value:function(e,t){t&&(e=this.streamIdToSessionId.get(t),this.streamIdToSessionId.delete(t));var r=this.sessions.get(e);r&&(r.clear(),this.sessions.delete(e),this.mixedLocalAudioTrack.getPublication()===r&&this.mixedLocalAudioTrack.clear())}},{key:"batchPublish",value:(l=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t,r){var n,i,o,a,s,c,u,l,d,p=this;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return n=Date.now(),e.next=1,this.getOrCreatePeerConnection("uplink");case 1:return i=e.sent,o=_toConsumableArray(this.sessions.values()).filter(function(e){return e instanceof Publication}),e.next=2,execBatchPublish({uid:this.client.userId,tracks:t,connection:i,labels:r,existedPublications:o,mixedLocalAudioTrack:this.mixedLocalAudioTrack});case 2:a=e.sent,s=_toConsumableArray(a.videoPubResultArr),a.audioPubResult&&s.push(a.audioPubResult),c=_createForOfIteratorHelper$5(s),e.prev=3,l=_regeneratorRuntime$1.mark(function e(){var t,r,i,o,a,s;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:t=u.value,r=t.error,i=t.publication,o=t.track,r?p.reporter.trace.publish(!1,o,"",Date.now()-n):((a=p.streamIdToSessionId.get(o.getTrackId()))&&(p.logger.info("clear old publication before set new one",a),null===(s=p.sessions.get(a))||void 0===s||s.clear(),p.sessions.delete(a)),p.addSession(o.getTrackId(),i),p.reporter.trace.publish(!0,o,i.id,Date.now()-n),p.reporter.trace.publish(!1,o,i.id,Date.now()-n),i.on("ended",function(){p.removeSession(i.id)}));case 1:case"end":return e.stop()}},e)}),c.s();case 4:if((u=c.n()).done){e.next=6;break}return e.delegateYield(l(),"t0",5);case 5:e.next=4;break;case 6:e.next=8;break;case 7:e.prev=7,d=e.catch(3),c.e(d);case 8:return e.prev=8,c.f(),e.finish(8);case 9:case"end":return e.stop()}},e,this,[[3,7,8,9]])})),function(e,t){return l.apply(this,arguments)})},{key:"batchUnPublish",value:(u=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n=this;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(t.length){e.next=1;break}return this.logger.info("batchUnPublish sessions is empty"),e.abrupt("return",Promise.resolve());case 1:return e.next=2,this.getOrCreatePeerConnection("uplink");case 2:return r=e.sent,e.abrupt("return",batchPublishStop(t,{connection:r}).then(function(){var e,r=_createForOfIteratorHelper$5(t);try{for(r.s();!(e=r.n()).done;){var i,o,a=e.value;n.streamIdToSessionId.delete(null===(i=a.tracks)||void 0===i||null===(i=i[0])||void 0===i||null===(o=i.getTrackId)||void 0===o?void 0:o.call(i)),n.removeSession(a.id)}}catch(e){r.e(e)}finally{r.f()}}));case 3:case"end":return e.stop()}},e,this)})),function(e){return u.apply(this,arguments)})},{key:"batchSubscribe",value:function(e){var t,r=this,n=Date.now(),i=0,o=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var n;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=1,r.getOrCreatePeerConnection("downlink");case 1:return n=e.sent,e.abrupt("return",batchSubscribeStart(t,n).then(function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(n){var a,s,c,u;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:for(a=new Map,s=[],c=0;c<n.length;c++)"RoomBusy"===(null===(u=n[c].error)||void 0===u?void 0:u.message)&&(s.push(t[c]),a.set(s.length-1,c));if(!(s.length&&i<=3)){e.next=3;break}return i++,e.next=1,awaitTime(1);case 1:if("connected"!==r.client.connectionState){e.next=3;break}return e.next=2,o(s);case 2:e.sent.forEach(function(e,t){var r=a.get(t);n[r]=e});case 3:return e.abrupt("return",n);case 4:case"end":return e.stop()}},e)}));return function(t){return e.apply(this,arguments)}}()));case 2:case"end":return e.stop()}},e)}));return function(t){return e.apply(this,arguments)}}(),a=_createForOfIteratorHelper$5(e);try{for(a.s();!(t=a.n()).done;){var s=t.value,c=s.stream,u=s.uid,l=s.resolutionInfo;(null==c?void 0:c.id)&&this.reporter.trace.subscribe({subPhase:"init",capabilities:null==c?void 0:c.media,remoteStreamId:null==c?void 0:c.id,remoteUserId:u,elapse:0,sessionId:"",resolutionInfo:l})}}catch(e){a.e(e)}finally{a.f()}return o(e).then(function(e){var t,i=_createForOfIteratorHelper$5(e);try{var o=function(){var e=t.value,i=e.error,o=e.subscription,a=e.id,s=e.stream,c=e.uid,u=e.resolutionInfo;if(o){r.reporter.trace.subscribe({subPhase:"success",capabilities:s.media,remoteStreamId:s.id,remoteUserId:c,elapse:Date.now()-n,sessionId:a,resolutionInfo:u});var l,d=r.streamIdToSessionId.get(s.id);if(d)r.logger.info("clear old subscription before set new one",d),null===(l=r.sessions.get(d))||void 0===l||l.clear(),r.sessions.delete(d);r.addSession(s.id,o),o.on("ended",function(){r.logger.info("remove subscription for ended",a),r.removeSession(a)})}i&&(r.logger.error("batchSubscribe error",s,i),(null==s?void 0:s.id)&&r.reporter.trace.subscribe({subPhase:"failed",capabilities:(null==s?void 0:s.media)||{},remoteStreamId:null==s?void 0:s.id,remoteUserId:c,elapse:Date.now()-n,sessionId:"",resolutionInfo:u}))};for(i.s();!(t=i.n()).done;)o()}catch(e){i.e(e)}finally{i.f()}return r.logger.info("batchSubscribe result",null==e?void 0:e.map(function(e){var t,r;return{error:null==e?void 0:e.error,uid:null==e?void 0:e.uid,streamId:null==e||null===(t=e.stream)||void 0===t?void 0:t.id,sessionId:null==e||null===(r=e.subscription)||void 0===r?void 0:r.id}})),e})}},{key:"batchUnscribe",value:(c=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n,i,o,a=this;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return r=new Array(t.length),n=[],i={},t.forEach(function(e,t){var o=e.error,s=e.stream,c=e.session;r[t]={},o?(r[t].error=o,a.logger.error("batchUnscribe error",o,s)):(i[null==s?void 0:s.id]=t,n.push(c))}),e.next=1,this.getOrCreatePeerConnection("downlink");case 1:return o=e.sent,e.abrupt("return",batchSubscribeStop(n,o).then(function(){for(var e=0,t=n;e<t.length;e++){var i=t[e];a.removeSession(i.id)}return r}));case 2:case"end":return e.stop()}},e,this)})),function(e){return c.apply(this,arguments)})},{key:"clear",value:function(){var e,t,r=this;this.sessions.forEach(function(e){r.removeSession(e.id)}),this.mixedLocalAudioTrack.clear(),null===(e=this.uplink)||void 0===e||e.closePeerConnection(),this.uplink=null,null===(t=this.downlink)||void 0===t||t.closePeerConnection(),this.downlink=null,this.streamIdToSessionId.clear(),this.networkQualityInterval&&(removeTimer(this.networkQualityInterval,"interval"),this.networkQualityInterval=null),this.serviceManager.rtcSignaling.off("media-message",this.handleMediaMessage),this.serviceManager.rtcSignaling.off("serverFailover",this.handleServerFailover)}},{key:"start",value:(s=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return this.startNetworkQualityTimer(),e.next=1,this.getOrCreatePeerConnection("uplink");case 1:return this.uplink=e.sent,e.next=2,this.getOrCreatePeerConnection("downlink");case 2:this.downlink=e.sent,this.serviceManager.rtcSignaling.on("media-message",this.handleMediaMessage),this.serviceManager.rtcSignaling.on("serverFailover",this.handleServerFailover);case 3:case"end":return e.stop()}},e,this)})),function(){return s.apply(this,arguments)})},{key:"startNetworkQualityTimer",value:function(){var e=this;this.networkQualityInterval=addTimer(function(){navigator&&void 0!==navigator.onLine&&!navigator.onLine?e.emit("network-quality",NetworkQualityType.DISCONNECTED,NetworkQualityType.DISCONNECTED):"connected"!==e.client.connectionState?e.emit("network-quality",NetworkQualityType.BAD,NetworkQualityType.BAD):"connected"===e.client.connectionState?e.checkChannelNetworkQuality():e.emit("network-quality",NetworkQualityType.UNKNOWN,NetworkQualityType.UNKNOWN)},NETWORK_QUALITY_TIMEOUT,"interval")}},{key:"getLocalAudioStats",value:(a=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){var t,r,n,i=arguments;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return r=i.length>0&&void 0!==i[0]?i[0]:"network",n=_toConsumableArray(this.sessions.values()).filter(function(e){var t,r;return e instanceof Publication&&"connected"===(null===(t=e.connection)||void 0===t||null===(t=t.pc)||void 0===t?void 0:t.connectionState)&&"audio"===(null===(r=e.tracks)||void 0===r||null===(r=r[0])||void 0===r?void 0:r.trackMediaType)}),e.next=1,Promise.all(n.map(function(e){return e.getMetrics(r)}));case 1:return e.abrupt("return",(null===(t=n[0])||void 0===t?void 0:t.audioStatsMap.get(r))||{});case 2:case"end":return e.stop()}},e,this)})),function(){return a.apply(this,arguments)})},{key:"getLocalVideoStats",value:(o=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){var t,r,n,i,o,a,s,c,u,l,d,p,f,h,g,m=arguments;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return n=m.length>0&&void 0!==m[0]?m[0]:"network",i=_toConsumableArray(this.sessions.values()).filter(function(e){var t;return e instanceof Publication&&"connected"===(null===(t=e.connection)||void 0===t||null===(t=t.pc)||void 0===t?void 0:t.connectionState)&&"video"===e.tracks[0].trackMediaType}),e.next=1,Promise.all(i.map(function(e){return e.getMetrics(n)}));case 1:o=function(e){var t;return(null==e||null===(t=e.fmtp)||void 0===t?void 0:t.filter(function(e){var t;return null==e||null===(t=e.config)||void 0===t?void 0:t.includes("profile-level-id")}).map(function(e){var t,r=(null==e||null===(t=e.config)||void 0===t?void 0:t.split(";"))||[],n=r.findIndex(function(e){return e.includes("profile-level-id")});return r[n].split("=")[1]}))||[]},a=null===(t=this.uplink)||void 0===t||null===(t=t.offerSDP)||void 0===t||null===(t=t.media)||void 0===t?void 0:t.find(function(e){return"video"===e.type}),s=null===(r=this.downlink)||void 0===r||null===(r=r.offerSDP)||void 0===r||null===(r=r.media)||void 0===r?void 0:r.find(function(e){return"video"===e.type}),c={uplinkProfile:_toConsumableArray(new Set(o(a))),downlinkProfile:_toConsumableArray(new Set(o(s)))},u=_createForOfIteratorHelper$5(i),e.prev=2,u.s();case 3:if((l=u.n()).done){e.next=6;break}if(d=l.value,p=d.videoStatsMap.get(n)){e.next=4;break}return e.abrupt("continue",5);case 4:f=d.tracks,h=f[0].source===exports.VideoSourceInfo.SCREENCAST,c[h?"auxiliary":"camera"]=p;case 5:e.next=3;break;case 6:e.next=8;break;case 7:e.prev=7,g=e.catch(2),u.e(g);case 8:return e.prev=8,u.f(),e.finish(8);case 9:return e.abrupt("return",c);case 10:case"end":return e.stop()}},e,this,[[2,7,8,9]])})),function(){return o.apply(this,arguments)})},{key:"getRemoteVideoStats",value:(i=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){var t,r,n,i,o,a,s,c,u,l,d,p,f,h=arguments;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t=h.length>0&&void 0!==h[0]?h[0]:"network",r=_toConsumableArray(this.sessions.values()).filter(function(e){var t;return e instanceof Subscription&&"connected"===(null===(t=e.connection)||void 0===t||null===(t=t.pc)||void 0===t?void 0:t.connectionState)&&e.stream.media.video}),e.next=1,Promise.all(r.map(function(e){return e.getMetrics(t)}));case 1:n={},i=_createForOfIteratorHelper$5(r),e.prev=2,i.s();case 3:if((o=i.n()).done){e.next=6;break}if(s=o.value,c=s.videoStatsMap,u=s.uid,l=s.stream,d=c.get(t)){e.next=4;break}return e.abrupt("continue",5);case 4:p=(null===(a=l.media.video)||void 0===a?void 0:a.source)===exports.VideoSourceInfo.SCREENCAST?"auxiliary":"camera",n[u]=_objectSpread$3(_objectSpread$3({},n[u]||{}),{},_defineProperty({},p,d));case 5:e.next=3;break;case 6:e.next=8;break;case 7:e.prev=7,f=e.catch(2),i.e(f);case 8:return e.prev=8,i.f(),e.finish(8);case 9:return e.abrupt("return",n);case 10:case"end":return e.stop()}},e,this,[[2,7,8,9]])})),function(){return i.apply(this,arguments)})},{key:"getRemoteAudioStats",value:(n=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){var t,r,n,i=arguments;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return r=i.length>0&&void 0!==i[0]?i[0]:"network",n=_toConsumableArray(this.sessions.values()).filter(function(e){var t;return e instanceof Subscription&&"connected"===(null===(t=e.connection)||void 0===t||null===(t=t.pc)||void 0===t?void 0:t.connectionState)&&e.stream.media.audio}),e.next=1,Promise.all(n.map(function(e){return e.getMetrics(r)}));case 1:return e.abrupt("return",(null===(t=n[0])||void 0===t?void 0:t.audioStatsMap.get(r))||{});case 2:case"end":return e.stop()}},e,this)})),function(){return n.apply(this,arguments)})},{key:"handleMediaMessage",value:(r=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n,i,o,a,s;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(this.logger.debug("remote feedback: ",t.payload),r=JSON.parse(t.payload),Array.isArray(r)&&0!==r.length){e.next=1;break}return e.abrupt("return");case 1:n=_toConsumableArray(this.sessions.values()).filter(function(e){return e instanceof Publication&&e.state===PubSubStates.Processing&&e.tracks[0].source===exports.VideoSourceInfo.CAMERA}),i=_createForOfIteratorHelper$5(n),e.prev=2,a=_regeneratorRuntime$1.mark(function e(){var t,n;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:t=o.value,(n=r.filter(function(e){return e.mid==t.transceiver.mid})).length&&t.applyOptions(n);case 1:case"end":return e.stop()}},e)}),i.s();case 3:if((o=i.n()).done){e.next=5;break}return e.delegateYield(a(),"t0",4);case 4:e.next=3;break;case 5:e.next=7;break;case 6:e.prev=6,s=e.catch(2),i.e(s);case 7:return e.prev=7,i.f(),e.finish(7);case 8:case"end":return e.stop()}},e,this,[[2,6,7,8]])})),function(e){return r.apply(this,arguments)})}]);var r,n,i,o,a,s,c,u,l,d,p,f,h}(EventEmitter);function _createForOfIteratorHelper$4(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$4(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$4(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$4(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_arrayLikeToArray$4(e,t):void 0}}function _arrayLikeToArray$4(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _callSuper$7(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$7()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$7(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$7=function(){return!!e})()}var PropertyNameMap={name:"name"},GroupManager=function(e){function t(e){var r;return _classCallCheck$1(this,t),r=_callSuper$7(this,t),Object.defineProperty(r,"serviceManager",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(r,"groupIds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"groups",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"default",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"listVer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.serviceManager=e,r.logger=r.serviceManager.reporter.getLoggerWithPrefix("[rtc-groupMgr]"),r.groups=new Map,r.listVer=0,r.groupIds=new Set,r.handleGroupListEvents=r.handleGroupListEvents.bind(r),r.handleGroupEvents=r.handleGroupEvents.bind(r),r.handleSyncEvent=r.handleSyncEvent.bind(r),r}return _inherits$1(t,e),_createClass$1(t,[{key:"joinedIds",get:function(){var e=this.serviceManager.rtcUserManager.currentSelfPid,t=new Set;return this.groups.forEach(function(r){var n=r.participants,i=r.id;n.some(function(t){return t.pid===e})&&t.add(i)}),t}},{key:"parseGroup",value:function(e){var t,r=this,n=e.id,i=e.properties,o=e.participants;return{id:n,name:(null==i||null===(t=i.find(function(e){return"name"===e.key}))||void 0===t?void 0:t.value)||"",joined:o.some(function(e){return e.pid===r.serviceManager.rtcUserManager.currentSelfPid}),users:o.map(function(e){return{userId:e.uid,userData:e.userData}})}}},{key:"groupList",get:function(){var e=this,t=[];return this.groups.forEach(function(r){t.push(e.parseGroup(r))}),t}},{key:"init",value:function(e,t){this.listVer=t,this.groupIds=new Set(e),this.batchSyncGroup(e),this.observerAllGroup(),this.serviceManager.rtcSignaling.on("group-list",this.handleGroupListEvents),this.serviceManager.rtcSignaling.on("group",this.handleGroupEvents),this.serviceManager.rtcSignaling.on("sync",this.handleSyncEvent)}},{key:"clear",value:function(){this.listVer=0,this.serviceManager.rtcSignaling.off("group",this.handleGroupEvents),this.serviceManager.rtcSignaling.off("group-list",this.handleGroupListEvents),this.serviceManager.rtcSignaling.off("sync",this.handleSyncEvent),this.groupIds.clear(),this.groups.clear()}},{key:"join",value:function(e){var t=e.publishAudioToGroup,r=void 0===t||t,n=e.groupId,i=e.userData;if(this.joinedIds.has(n))throw new DingRTCError(ErrorCode.InvaildArgument,"you were in group already");return this.serviceManager.rtcSignaling.joinGroup({groupId:n,userData:i,autoJoinGroupAudio:!!r,autoLeaveChannelAudio:!0})}},{key:"leave",value:function(e){var t=e.groupId,r=e.publishAudioToChannel,n=void 0===r||r;if(!this.joinedIds.has(t))throw new DingRTCError(ErrorCode.InvaildArgument,"you are not in the group");return this.serviceManager.rtcSignaling.leaveGroup({groupId:t,reasonCode:signal_msg.LEAVE_GROUP_REASON_CODE.NORMAL_LEAVE,autoJoinChannelAudio:n})}},{key:"dismiss",value:function(e){if(!this.groupIds.has(e))throw new DingRTCError(ErrorCode.InvaildArgument,"group not existed");return this.serviceManager.rtcSignaling.dismissGroup({groupId:e})}},{key:"addUser",value:function(e,t){var r,n=null===(r=this.groups.get(t))||void 0===r?void 0:r.participants;n&&!n.find(function(t){return t.pid===e.pid})&&n.push(e)}},{key:"removeUser",value:function(e,t){var r,n=null===(r=this.groups.get(t))||void 0===r?void 0:r.participants;if(n){var i=n.findIndex(function(t){return t.pid===e.pid});i>-1&&n.splice(i,1)}}},{key:"observerAllGroup",value:function(){return this.serviceManager.rtcSignaling.observeAllGroups()}},{key:"unobserverAllGroup",value:function(){return this.serviceManager.rtcSignaling.unobserveAllGroups()}},{key:"setProperties",value:function(e,t){return this.serviceManager.rtcSignaling.setGroupProperties({groupId:e,properties:[t]})}},{key:"handleGroupListEvents",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=e.ver,n=e.type,i=e.updateOpt;if(this.logger.info("on groupList event:",e),r!==this.listVer+1&&!t||n!==signal_msg.OptType.OPT_TYPE_UPDATE)r>this.listVer+1&&this.syncGroupList();else{var o=i.updateAction,a=i.id;o===signal_msg.GroupListUpdate.GROUP_LIST_UPDATE_ADD_ID?this.groupIds.add(a):o===signal_msg.GroupListUpdate.GROUP_LIST_UPDATE_REMOVE_ID&&this.groupIds.delete(a),this.listVer=r}}},{key:"handleGroupEvents",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this.logger.info("on group event:",e);var n,i=e.id,o=e.ver,a=e.groupInfo,s=e.type,c=e.updateOpt,u=this.groups.get(i);if(s!==signal_msg.OptType.OPT_TYPE_ADD||u){if(s===signal_msg.OptType.OPT_TYPE_REMOVE&&u)this.groups.delete(i),this.emit("group","remove",this.parseGroup(u),u.audioInfo);else if(s===signal_msg.OptType.OPT_TYPE_UPDATE){var l=c.updateAction,d=c.participants;if(u&&(u.ver+1===o||r)){if(l===signal_msg.GroupUpdate.GROUP_UPDATE_ADD_PARTICIPANTS){var p,f=u.participants.map(function(e){return e.pid}),h=_createForOfIteratorHelper$4(d);try{for(h.s();!(p=h.n()).done;){var g=p.value;f.includes(g.pid)||(u.participants.push(g),this.emit("group","user-join",i,{userId:g.uid,userData:g.userData}))}}catch(e){h.e(e)}finally{h.f()}}else if(l===signal_msg.GroupUpdate.GROUP_UPDATE_REMOVE_PARTICIPANTS){var m=d.map(function(e){return e.pid}),v=_toConsumableArray(u.participants);u.participants=u.participants.filter(function(e){return!m.includes(e.pid)}),v.forEach(function(e){m.includes(e.pid)&&t.emit("group","user-leave",i,{userId:e.uid,userData:e.userData})})}else if(l===signal_msg.GroupUpdate.GROUP_UPDATE_AUDIO_STREAM_LOST)this.logger.info("group ".concat(i," audioStream lost"));else if(l===signal_msg.GroupUpdate.GROUP_UPDATE_AUDIO_STREAM_RECOVER)this.logger.debug("group ".concat(i," audioStream recover"));else if(l===signal_msg.GroupUpdate.GROUP_UPDATE_SET_PROPERTIES)c.properties.forEach(function(e){var r=!0;u.properties||(u.properties=[]),u.properties.forEach(function(t){t.key===e.key&&(t.value=e.value,r=!1)}),r&&u.properties.push(e),t.emit("group","info-updated",i,{key:"set-".concat(PropertyNameMap[e.key]),value:e.value})});else if(l===signal_msg.GroupUpdate.GROUP_UPDATE_REMOVE_PROPERTIES){var y,b=c.properties.map(function(e){return e.key});u.properties=null===(y=u.properties)||void 0===y?void 0:y.filter(function(e){var t=e.key;return!b.includes(t)}),c.properties.forEach(function(e){t.emit("group","info-updated",i,{key:"remove-".concat(PropertyNameMap[e.key])})})}u.ver=o}else u&&o>u.ver+1&&this.syncGroup(u.id)}}else null==a||null===(n=a.audioInfo)||void 0===n||null===(n=n.audio)||void 0===n||null===(n=n.media)||void 0===n||delete n.video,null==a.ver&&(a.ver=o),this.groups.set(i,a),this.emit("group","add",this.parseGroup(a))}},{key:"syncGroup",value:function(e){var t=this,r=this.groups.get(e);return this.serviceManager.rtcSignaling.syncData({type:signal_msg.DataType.DATA_TYPE_GROUP,id:e,ver:null==r?void 0:r.ver}).then(function(n){var i=n.fullSync.groupData.groupInfos,o=(void 0===i?[]:i)[0];if(o){var a=o.participants,s=o.properties,c=void 0===s?[]:s,u=(null==r?void 0:r.participants)||[],l=new Map(((null==r?void 0:r.properties)||[]).map(function(e){return[e.key,e.value]})),d=u.map(function(e){return e.pid}),p=a.map(function(e){return e.pid}),f=c.filter(function(e){return e.value!==l[e.key]}),h=c.filter(function(e){return!l.has(e.key)}),g=a.filter(function(e){return!d.includes(e.pid)}),m=u.filter(function(e){return!p.includes(e.pid)});g.length&&t.handleGroupEvents({id:e,type:signal_msg.OptType.OPT_TYPE_REMOVE,ver:o.ver,updateOpt:{updateAction:signal_msg.GroupUpdate.GROUP_UPDATE_ADD_PARTICIPANTS,participants:g}},!0),m.length&&t.handleGroupEvents({id:e,ver:o.ver,type:signal_msg.OptType.OPT_TYPE_REMOVE,updateOpt:{updateAction:signal_msg.GroupUpdate.GROUP_UPDATE_REMOVE_PARTICIPANTS,participants:m}},!0),f.length&&t.handleGroupEvents({id:e,ver:o.ver,type:signal_msg.OptType.OPT_TYPE_UPDATE,updateOpt:{updateAction:signal_msg.GroupUpdate.GROUP_UPDATE_SET_PROPERTIES,properties:f}},!0),h.length&&t.handleGroupEvents({id:e,ver:o.ver,type:signal_msg.OptType.OPT_TYPE_UPDATE,updateOpt:{updateAction:signal_msg.GroupUpdate.GROUP_UPDATE_REMOVE_PROPERTIES,properties:h}},!0)}else t.handleGroupEvents({id:e,type:signal_msg.OptType.OPT_TYPE_REMOVE})})}},{key:"batchSyncGroup",value:function(e){var t=this;if(e.length)return this.serviceManager.rtcSignaling.syncDataByIds({type:signal_msg.DataType.DATA_TYPE_GROUP,ids:e.map(function(e){return{id:e}})}).then(function(e){e.fullSync.groupData.groupInfos.forEach(function(e){t.groupIds.add(e.id),t.groups.set(e.id,e)})})}},{key:"syncGroupList",value:function(){var e=this;this.serviceManager.rtcSignaling.syncData({type:signal_msg.DataType.DATA_TYPE_GROUP_LIST,forceFullSync:!0,ver:this.listVer}).then(function(t){var r=t.fullSync,n=r.ver,i=r.groupListData.groupIds,o=void 0===i?[]:i,a=o.filter(function(t){return!e.groupIds.has(t)}),s=_toConsumableArray(e.groupIds).filter(function(e){return!o.includes(e)});a.length&&a.forEach(function(t){e.handleGroupListEvents({ver:n,updateOpt:{updateAction:signal_msg.GroupListUpdate.GROUP_LIST_UPDATE_ADD_ID,id:t}},!0)}),s.length&&s.forEach(function(t){e.handleGroupListEvents({ver:n,updateOpt:{updateAction:signal_msg.GroupListUpdate.GROUP_LIST_UPDATE_REMOVE_ID,id:t}},!0)})})}},{key:"handleSyncEvent",value:function(e){var t=this,r=e.groupListVer,n=e.groupVer,i=void 0===n?[]:n;this.listVer<r&&(this.syncGroupList(),this.listVer=r),i.forEach(function(e){var r=e.id,n=e.ver,i=t.groups.get(r);(null==i?void 0:i.ver)<n&&(t.syncGroup(r),i.ver=n)})}}])}(EventEmitter);function _callSuper$6(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$6()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$6(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$6=function(){return!!e})()}var User=function(e){function t(e,r){var n;_classCallCheck$1(this,t),n=_callSuper$6(this,t),Object.defineProperty(n,"serviceManager",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(n,"userId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"userName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"streamMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"videoTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"auxiliaryTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"audioTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"joinedTime",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"properties",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"toJSON",{enumerable:!0,configurable:!0,writable:!0,value:function(){return{userId:n.userId,userName:n.userName,hasAuxiliary:n.hasAuxiliary,hasVideo:n.hasVideo,hasAudio:n.hasAudio,joinedTime:n.joinedTime,properties:n.properties,audioMuted:n.audioMuted,auxiliaryMuted:n.auxiliaryMuted,videoMuted:n.videoMuted}}});var i=e.user;return n.userId=i,n.videoTrack=null,n.audioTrack=null,n.auxiliaryTrack=null,n.serviceManager=r,n.joinedTime=Date.now(),n.update(e),n}return _inherits$1(t,e),_createClass$1(t,[{key:"relatedStreams",get:function(){var e=this;return _toConsumableArray(this.serviceManager.streamManager.streams.values()).filter(function(t){var r;return(null==t||null===(r=t.info)||void 0===r?void 0:r.owner)===e.id})}},{key:"hasAuxiliary",get:function(){return this.relatedStreams.some(function(e){var t;return(null===(t=e.media)||void 0===t||null===(t=t.video)||void 0===t?void 0:t.source)===exports.VideoSourceInfo.SCREENCAST})}},{key:"hasVideo",get:function(){return this.relatedStreams.some(function(e){var t,r=e.media;return(null==r||null===(t=r.video)||void 0===t?void 0:t.source)===exports.VideoSourceInfo.CAMERA})}},{key:"hasAudio",get:function(){return this.relatedStreams.some(function(e){var t,r=e.media;return(null==r||null===(t=r.audio)||void 0===t?void 0:t.source)===exports.AudioSourceInfo.MIC})}},{key:"audioMuted",get:function(){return this.relatedStreams.some(function(e){var t,r,n=e.media;return"active"!==(null==n||null===(t=n.audio)||void 0===t?void 0:t.status)&&(null==n||null===(r=n.audio)||void 0===r?void 0:r.source)===exports.AudioSourceInfo.MIC})}},{key:"auxiliaryMuted",get:function(){return this.relatedStreams.some(function(e){var t,r,n=e.media;return"active"!==(null==n||null===(t=n.video)||void 0===t?void 0:t.status)&&(null==n||null===(r=n.video)||void 0===r?void 0:r.source)===exports.VideoSourceInfo.SCREENCAST})}},{key:"videoMuted",get:function(){return this.relatedStreams.some(function(e){var t,r,n=e.media;return"active"!==(null==n||null===(t=n.video)||void 0===t?void 0:t.status)&&(null==n||null===(r=n.video)||void 0===r?void 0:r.source)===exports.VideoSourceInfo.CAMERA})}},{key:"updateNetworkOfUser",value:function(e){var t;if(this.properties.SdkType!==SdkType$1.Web&&e){var r=e.split("");r[ClientUserStats.UPLINK]=transNativeAndWebNetworkRank(r[ClientUserStats.UPLINK]),r[ClientUserStats.DOWNLINK]=transNativeAndWebNetworkRank(r[ClientUserStats.DOWNLINK]),e=r.join("")}e!==(null===(t=this.properties)||void 0===t?void 0:t[USER_STATS_SYNC])&&(this.properties[USER_STATS_SYNC]=e)}},{key:"update",value:function(e){var t=e.id,r=e.propertiesJsonStr,n=e.ver,i=JSON.parse(r||"{}");this.id=t,this.userName=i.__nick,this.version=n;var o=this.properties||{};this.properties=i,this.updateNetworkOfUser(i[USER_STATS_SYNC]),!i.hasOwnProperty("mute_audio_record")||void 0!==o.mute_audio_record&&i.mute_audio_record===o.mute_audio_record||this.serviceManager.client.emit("user-mic-audio-muted",this.userId,!!i.mute_audio_record),!i.hasOwnProperty("enable_sys_audio")||void 0!==o.enable_sys_audio&&i.enable_sys_audio===o.enable_sys_audio||this.serviceManager.client.emit("user-screencast-audio-mixed",this.userId,!!i.enable_sys_audio)}},{key:"updateSubbedVideoTrack",value:function(e,t){var r=t?this.auxiliaryTrack:this.videoTrack,n=JSON.parse(e.stream.info.attributesJsonStr),i=updateRemoteTrack(e.mediaStream,"video",this.userId,r);return t?this.auxiliaryTrack=i:this.videoTrack=i,n.mirror&&i.setSourceMirror(n.mirror),i}}])}(EventEmitter);function _createForOfIteratorHelper$3(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$3(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$3(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$3(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_arrayLikeToArray$3(e,t):void 0}}function _arrayLikeToArray$3(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _callSuper$5(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$5()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$5(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$5=function(){return!!e})()}var RtcUserManager=function(e){function t(e,r){var n;return _classCallCheck$1(this,t),n=_callSuper$5(this,t),Object.defineProperty(n,"serviceManager",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(n,"users",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"currentUid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"currentSelfPid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"streamManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),n.users=new Map,n.serviceManager=e,n.reporter=e.reporter,n.logger=n.reporter.getLoggerWithPrefix("[rtc-userMgr]"),n.handleEvent=n.handleEvent.bind(n),n.streamManager=r,n}return _inherits$1(t,e),_createClass$1(t,[{key:"remoteUsers",get:function(){var e=this;return uniqBy(_toConsumableArray(this.users.values()).sort(function(e,t){return e.joinedTime-t.joinedTime}),"userId").filter(function(t){return t.userId&&t.id!==e.currentSelfPid})}},{key:"init",value:function(e,t){var r,n=_createForOfIteratorHelper$3(e);try{for(n.s();!(r=n.n()).done;){var i=r.value,o=new User(i,this.serviceManager);this.users.set(i.user,o),t===i.user&&(this.currentUid=i.user)}}catch(e){n.e(e)}finally{n.f()}this.currentSelfPid=t,this.serviceManager.internalChannel.on("user",this.handleEvent)}},{key:"clear",value:function(){this.currentSelfPid="",this.currentUid="",this.users.clear(),this.serviceManager.internalChannel.off("user",this.handleEvent)}},{key:"handleEvent",value:function(e,t,r){var n=this;if(this.logger.info("userEvent ".concat(e," ").concat(JSON.stringify(t))),"join"===e){var i=new User(t,this.serviceManager);this.users.set(t.user,i),this.emit("user","join",i)}else if("leave"===e){var o=this.users.get(t.user);this.users.delete(t.user),this.emit("user","leave",o)}else if("update"===e){var a=this.users.get(t.user);null==a||a.update(t)}else if("participant-replace"===e){var s=new Set(null==r?void 0:r.map(function(e){return e.id}));_toConsumableArray(this.streamManager.streams.values()).filter(function(e){var t;return s.has(null==e||null===(t=e.info)||void 0===t?void 0:t.owner)}).map(function(e){return e.id}).forEach(function(e){return n.streamManager.remove(e,!0)});var c=this.users.get(t.user);this.users.delete(t.user),this.emit("user","leave",c);var u=new User(t,this.serviceManager);this.users.set(t.user,u),this.emit("user","join",u)}}},{key:"setParticipantProperties",value:function(e){return this.serviceManager.rtcSignaling.setParticipantProperties({participantId:this.currentSelfPid,roomId:this.serviceManager.roomId,propertiesJsonStr:JSON.stringify(_defineProperty({},USER_STATS_SYNC,e))})}},{key:"notifyParticipantProperties",value:function(e){return this.serviceManager.rtcSignaling.setParticipantProperties({participantId:this.currentSelfPid,roomId:this.serviceManager.roomId,propertiesJsonStr:e})}}])}(EventEmitter);function _createForOfIteratorHelper$2(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$2(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$2(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$2(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_arrayLikeToArray$2(e,t):void 0}}function _arrayLikeToArray$2(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function ownKeys$2(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function _objectSpread$2(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$2(Object(r),!0).forEach(function(t){_defineProperty(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$2(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function _callSuper$4(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$4()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$4(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$4=function(){return!!e})()}var debounce=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:50,r=null;return function(){for(var n=this,i=arguments.length,o=new Array(i),a=0;a<i;a++)o[a]=arguments[a];r&&clearTimeout(r),r=setTimeout(function(){e.apply(n,o)},t)}},StreamManager=function(e){function t(e){var r;_classCallCheck$1(this,t),r=_callSuper$4(this,t),Object.defineProperty(r,"streams",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"totalVer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"rtcSignaling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"debounceSyncRpc",{enumerable:!0,configurable:!0,writable:!0,value:debounce(r.doSyncRpc,1e3)}),r.streams=new Map;var n=e.rtcSignaling,i=e.reporter;return r.rtcSignaling=n,r.reporter=i,r.logger=r.reporter.getLoggerWithPrefix("[rtc-streamMgr]"),r.handleEvent=r.handleEvent.bind(r),r.handleSyncEvent=r.handleSyncEvent.bind(r),r.debounceSyncRpc=r.debounceSyncRpc.bind(r),r}return _inherits$1(t,e),_createClass$1(t,[{key:"clear",value:function(){this.streams.clear(),this.totalVer=0,this.rtcSignaling.off("stream",this.handleEvent),this.rtcSignaling.off("sync",this.handleSyncEvent)}},{key:"init",value:function(e,t){var r,n=e.find(function(e){return"admin"===e.info.owner&&"mixed"===e.type});null==n||null===(r=n.media)||void 0===r||delete r.video,this.streams=new Map(e.map(function(e){return[e.id,e]})),this.totalVer=t,this.rtcSignaling.on("stream",this.handleEvent),this.rtcSignaling.on("sync",this.handleSyncEvent)}},{key:"add",value:function(e){var t,r=e.id,n=e.info.owner,i=e.media,o=i.video,a=i.audio;if(!this.streams.get(r)){var s=null===(t=e.media)||void 0===t||null===(t=t.video)||void 0===t?void 0:t.source,c=_toConsumableArray(this.streams.values()).find(function(e){var t;return e.info.owner===n&&(null===(t=e.media)||void 0===t||null===(t=t.video)||void 0===t?void 0:t.source)===s});c&&s&&this.remove(c.id),this.reporter.trace.streamsEvent(r,"add"),this.streams.set(e.id,e);var u=(null==o?void 0:o.source)===VideoSourceInfo.SCREENCAST;if((null==o?void 0:o.source)===VideoSourceInfo.CAMERA||u){this.emit("stream","add",{id:r,owner:n,mediaType:"video",auxiliary:u});var l="active"===o.status?"unmute":"mute";this.emit("stream","update",{owner:n,id:r,auxiliary:u,updateStatus:"".concat(l,"-video")})}if((null==a?void 0:a.source)===exports.AudioSourceInfo.MIC||(null==a?void 0:a.source)===exports.AudioSourceInfo.MIXED){this.emit("stream","add",{id:r,owner:n,mediaType:"audio"});var d="active"===a.status?"unmute":"mute";this.emit("stream","update",{owner:n,id:r,auxiliary:!1,updateStatus:"".concat(d,"-audio")})}}}},{key:"remove",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=this.streams.get(e);if(r&&(this.streams.delete(e),t)){this.reporter.trace.streamsEvent(e,"remove");var n=r.media,i=n.video,o=n.audio,a=r.info.owner,s=(null==i?void 0:i.source)===VideoSourceInfo.SCREENCAST;((null==i?void 0:i.source)===VideoSourceInfo.CAMERA||s)&&this.emit("stream","remove",{id:e,owner:a,mediaType:"video",auxiliary:s}),(null==o?void 0:o.source)!==exports.AudioSourceInfo.MIC&&(null==o?void 0:o.source)!==exports.AudioSourceInfo.MIXED||this.emit("stream","remove",{id:e,owner:a,mediaType:"audio"})}}},{key:"getStreamByTrackId",value:function(e){return _toConsumableArray(this.streams.values()).find(function(t){var r,n;return(null===(r=t.media.audio)||void 0===r?void 0:r.trackId)===e||(null===(n=t.media.video)||void 0===n?void 0:n.trackId)===e})}},{key:"handleEvent",value:function(e,t){var r=this,n=e.streamId,i=e.status,o=e.stream,a=e.msg,s=e.totalVer,c={add:[],remove:[],update:["audio.status","video.status","properties","highestResolutionLevel"]}[i];c.length&&!c.includes(a.field)||this.logger.info("streamEvent",e);var u=this.totalVer;if(s===u+1||s==IGNOGRED_VERSION||t)if("add"===i){if(!o||!o.media||!o.info)return;this.add(o)}else if("remove"===i)this.remove(n,!0);else if("update"===i){var l=a.field,d=a.streamStatus,p=a.activeStream,f=a.extraValue,h=a.streamVer,g=a.propertiesJsonStr,m=a.highestResolutionLevel,v=this.streams.get(n);if(v){h!==IGNOGRED_VERSION&&(v.version=h);var y=v.media,b=y.audio,S=y.video,_=v.info.owner;if("audio.status"===l||"video.status"===l){var E,T;"audio.status"===l?(T="audio",b.status=d):"video.status"===l&&(T="video",S.status=d),this.reporter.trace.streamsEvent(n,"".concat(T," ").concat(d));var R="active"===d?"unmute":"mute",C=(null===(E=v.media)||void 0===E||null===(E=E.video)||void 0===E?void 0:E.source)===VideoSourceInfo.SCREENCAST;this.emit("stream","update",{owner:_,id:n,updateStatus:"".concat(R,"-").concat(T),auxiliary:C})}else if("activeInput"===l){var k=[p].concat(f||[]).map(function(e){var t;return null===(t=r.streams.get(e))||void 0===t||null===(t=t.info)||void 0===t?void 0:t.owner}).filter(function(e){return!!e});this.reporter.trace.streamsEvent(JSON.stringify(k),l),this.emit("stream","volumeActive",{owners:k})}else if("properties"==l){var P,w={};try{w=JSON.parse(g)}catch(e){}v.info.attributesJsonStr=JSON.stringify(_objectSpread$2(_objectSpread$2({},JSON.parse(v.info.attributesJsonStr)),w));var O=(null===(P=v.media)||void 0===P||null===(P=P.video)||void 0===P?void 0:P.source)===VideoSourceInfo.SCREENCAST;this.emit("stream","update",{owner:_,id:n,properties:w,auxiliary:O})}else"highestResolutionLevel"===l&&(v.media.video.highestResolutionLevel=m,this.emit("stream","update",{owner:_,id:n,highestResolutionLevel:m}))}}t||s<=this.totalVer&&s!==IGNOGRED_VERSION||(s===u+1&&(this.totalVer=s),s>u+1&&!t&&(this.logger.info("debounceSyncRpc by stream event"),this.debounceSyncRpc()))}},{key:"doSyncRpc",value:(r=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){var t,r,n,i,o,a,s,c,u,l,d,p,f,h,g=this;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t=[],r=[],e.next=1,this.rtcSignaling.getStreamsVer({});case 1:n=e.sent,i=n.streamVersions,o=n.totalVer,a=_toConsumableArray(this.streams.keys()).filter(function(e){return!e.includes("vad")}),s=_createForOfIteratorHelper$2(i),e.prev=2,s.s();case 3:if((c=s.n()).done){e.next=6;break}if(u=c.value,l=u.streamId,d=u.streamVer,!l.includes("vad")){e.next=4;break}return e.abrupt("continue",5);case 4:(p=this.streams.get(l))?p&&p.version!==d&&t.push(l):(r.push(l),t.push(l));case 5:e.next=3;break;case 6:e.next=8;break;case 7:e.prev=7,h=e.catch(2),s.e(h);case 8:return e.prev=8,s.f(),e.finish(8);case 9:if(f=i.map(function(e){return e.streamId}),a.filter(function(e){return!f.includes(e)}).forEach(function(e){g.handleEvent({status:"remove",streamId:e,stream:g.streams.get(e),totalVer:o},!0)}),this.reporter.trace.syncEvent("stream",a,f),this.totalVer=o,0!==t.length){e.next=10;break}return e.abrupt("return");case 10:this.rtcSignaling.getStreams({streamIds:t}).then(function(e){var n,i=e.totalVer,o=e.streams,a=new Map,s=_createForOfIteratorHelper$2(g.streams.values());try{for(s.s();!(n=s.n()).done;){var c=n.value;a.set(c.id,c)}}catch(e){s.e(e)}finally{s.f()}var u,l=_createForOfIteratorHelper$2(o);try{for(l.s();!(u=l.n()).done;){var d,p,f,h,m,v,y,b,S,_,E,T,R=u.value,C=g.streams.get(R.id);if(C)["active","inactive"].includes(null===(d=R.stream.media)||void 0===d||null===(d=d.video)||void 0===d?void 0:d.status)&&(null===(p=R.stream.media)||void 0===p||null===(p=p.video)||void 0===p?void 0:p.status)!==(null===(f=C.media)||void 0===f||null===(f=f.video)||void 0===f?void 0:f.status)&&g.handleEvent({streamId:C.id,status:"update",stream:R.stream,msg:{field:"video.status",streamStatus:null===(S=R.stream.media)||void 0===S||null===(S=S.video)||void 0===S?void 0:S.status,streamVer:R.stream.version},totalVer:i},!0),["active","inactive"].includes(null===(h=R.stream.media)||void 0===h||null===(h=h.audio)||void 0===h?void 0:h.status)&&(null===(m=R.stream.media)||void 0===m||null===(m=m.audio)||void 0===m?void 0:m.status)!==(null===(v=C.media)||void 0===v||null===(v=v.audio)||void 0===v?void 0:v.status)&&g.handleEvent({streamId:C.id,status:"update",stream:R.stream,msg:{field:"audio.status",streamStatus:null===(_=R.stream.media)||void 0===_||null===(_=_.audio)||void 0===_?void 0:_.status,activeStream:null,extraValue:null,streamVer:R.stream.version,propertiesJsonStr:"",highestResolutionLevel:void 0},totalVer:i},!0),null!==(y=R.stream.info)&&void 0!==y&&y.attributesJsonStr&&g.handleEvent({streamId:C.id,status:"update",stream:R.stream,msg:{field:"properties",streamVer:R.stream.version,propertiesJsonStr:(null===(E=R.stream.info)||void 0===E?void 0:E.attributesJsonStr)||"{}"},totalVer:i},!0),null!==(b=R.stream.media)&&void 0!==b&&null!==(b=b.video)&&void 0!==b&&b.highestResolutionLevel&&g.handleEvent({streamId:C.id,status:"update",stream:R.stream,msg:{field:"highestResolutionLevel",streamVer:R.stream.version,highestResolutionLevel:null===(T=R.stream.media)||void 0===T||null===(T=T.video)||void 0===T?void 0:T.highestResolutionLevel},totalVer:i},!0);else a.set(R.id,R.stream)}}catch(e){l.e(e)}finally{l.f()}for(var k=t.map(function(e){return a.get(e)}).filter(function(e){return!!e}).sort(function(e,t){return e.version-t.version}),P=0;P<k.length;P++){var w=k[P];r.includes(w.id)&&g.handleEvent({status:"add",streamId:w.id,stream:w,totalVer:i},!0)}a.clear(),g.totalVer=i});case 11:case"end":return e.stop()}},e,this,[[2,7,8,9]])})),function(){return r.apply(this,arguments)})},{key:"handleSyncEvent",value:function(e){var t=e.streamsVer;this.totalVer<t&&(this.logger.info("debounceSyncRpc by sync event"),this.debounceSyncRpc())}}]);var r}(EventEmitter),wasm=null;try{wasm=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function Long(e,t,r){this.low=0|e,this.high=0|t,this.unsigned=!!r}function isLong(e){return!0===(e&&e.__isLong__)}function ctz32(e){var t=Math.clz32(e&-e);return e?31-t:t}Long.prototype.__isLong__,Object.defineProperty(Long.prototype,"__isLong__",{value:!0}),Long.isLong=isLong;var INT_CACHE={},UINT_CACHE={};function fromInt(e,t){var r,n,i;return t?(i=0<=(e>>>=0)&&e<256)&&(n=UINT_CACHE[e])?n:(r=fromBits(e,0,!0),i&&(UINT_CACHE[e]=r),r):(i=-128<=(e|=0)&&e<128)&&(n=INT_CACHE[e])?n:(r=fromBits(e,e<0?-1:0,!1),i&&(INT_CACHE[e]=r),r)}function fromNumber(e,t){if(isNaN(e))return t?UZERO:ZERO;if(t){if(e<0)return UZERO;if(e>=TWO_PWR_64_DBL)return MAX_UNSIGNED_VALUE}else{if(e<=-TWO_PWR_63_DBL)return MIN_VALUE;if(e+1>=TWO_PWR_63_DBL)return MAX_VALUE}return e<0?fromNumber(-e,t).neg():fromBits(e%TWO_PWR_32_DBL|0,e/TWO_PWR_32_DBL|0,t)}function fromBits(e,t,r){return new Long(e,t,r)}Long.fromInt=fromInt,Long.fromNumber=fromNumber,Long.fromBits=fromBits;var pow_dbl=Math.pow;function fromString(e,t,r){if(0===e.length)throw Error("empty string");if("number"==typeof t?(r=t,t=!1):t=!!t,"NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return t?UZERO:ZERO;if((r=r||10)<2||36<r)throw RangeError("radix");var n;if((n=e.indexOf("-"))>0)throw Error("interior hyphen");if(0===n)return fromString(e.substring(1),t,r).neg();for(var i=fromNumber(pow_dbl(r,8)),o=ZERO,a=0;a<e.length;a+=8){var s=Math.min(8,e.length-a),c=parseInt(e.substring(a,a+s),r);if(s<8){var u=fromNumber(pow_dbl(r,s));o=o.mul(u).add(fromNumber(c))}else o=(o=o.mul(i)).add(fromNumber(c))}return o.unsigned=t,o}function fromValue(e,t){return"number"==typeof e?fromNumber(e,t):"string"==typeof e?fromString(e,t):fromBits(e.low,e.high,"boolean"==typeof t?t:e.unsigned)}Long.fromString=fromString,Long.fromValue=fromValue;var TWO_PWR_16_DBL=65536,TWO_PWR_24_DBL=1<<24,TWO_PWR_32_DBL=TWO_PWR_16_DBL*TWO_PWR_16_DBL,TWO_PWR_64_DBL=TWO_PWR_32_DBL*TWO_PWR_32_DBL,TWO_PWR_63_DBL=TWO_PWR_64_DBL/2,TWO_PWR_24=fromInt(TWO_PWR_24_DBL),ZERO=fromInt(0);Long.ZERO=ZERO;var UZERO=fromInt(0,!0);Long.UZERO=UZERO;var ONE=fromInt(1);Long.ONE=ONE;var UONE=fromInt(1,!0);Long.UONE=UONE;var NEG_ONE=fromInt(-1);Long.NEG_ONE=NEG_ONE;var MAX_VALUE=fromBits(-1,2147483647,!1);Long.MAX_VALUE=MAX_VALUE;var MAX_UNSIGNED_VALUE=fromBits(-1,-1,!0);Long.MAX_UNSIGNED_VALUE=MAX_UNSIGNED_VALUE;var MIN_VALUE=fromBits(0,-2147483648,!1);Long.MIN_VALUE=MIN_VALUE;var LongPrototype=Long.prototype;function I(e,t,r,n,i,o,a){try{var s=e[o](a),c=s.value}catch(e){return void r(e)}s.done?t(c):Promise.resolve(c).then(n,i)}function C(e){return function(){var t=this,r=arguments;return new Promise(function(n,i){var o=e.apply(t,r);function a(e){I(o,n,i,a,s,"next",e)}function s(e){I(o,n,i,a,s,"throw",e)}a(void 0)})}}function O(e){return O="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},O(e)}function P(e){var t=function(e,t){if("object"!=O(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t);if("object"!=O(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e,"string");return"symbol"==O(t)?t:t+""}function R(e,t,r){return(t=P(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function _(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function N(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,P(n.key),n)}}function k(e,t,r){return t&&N(e.prototype,t),r&&N(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function M(e,t){if(t&&("object"==O(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}function w(e){return w=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},w(e)}function D(e,t){return D=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},D(e,t)}function j(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&D(e,t)}function A(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}LongPrototype.toInt=function(){return this.unsigned?this.low>>>0:this.low},LongPrototype.toNumber=function(){return this.unsigned?(this.high>>>0)*TWO_PWR_32_DBL+(this.low>>>0):this.high*TWO_PWR_32_DBL+(this.low>>>0)},LongPrototype.toString=function(e){if((e=e||10)<2||36<e)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(MIN_VALUE)){var t=fromNumber(e),r=this.div(t),n=r.mul(t).sub(this);return r.toString(e)+n.toInt().toString(e)}return"-"+this.neg().toString(e)}for(var i=fromNumber(pow_dbl(e,6),this.unsigned),o=this,a="";;){var s=o.div(i),c=(o.sub(s.mul(i)).toInt()>>>0).toString(e);if((o=s).isZero())return c+a;for(;c.length<6;)c="0"+c;a=""+c+a}},LongPrototype.getHighBits=function(){return this.high},LongPrototype.getHighBitsUnsigned=function(){return this.high>>>0},LongPrototype.getLowBits=function(){return this.low},LongPrototype.getLowBitsUnsigned=function(){return this.low>>>0},LongPrototype.getNumBitsAbs=function(){if(this.isNegative())return this.eq(MIN_VALUE)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&!(e&1<<t);t--);return 0!=this.high?t+33:t+1},LongPrototype.isSafeInteger=function(){var e=this.high>>21;return!e||!this.unsigned&&(-1===e&&!(0===this.low&&-2097152===this.high))},LongPrototype.isZero=function(){return 0===this.high&&0===this.low},LongPrototype.eqz=LongPrototype.isZero,LongPrototype.isNegative=function(){return!this.unsigned&&this.high<0},LongPrototype.isPositive=function(){return this.unsigned||this.high>=0},LongPrototype.isOdd=function(){return!(1&~this.low)},LongPrototype.isEven=function(){return!(1&this.low)},LongPrototype.equals=function(e){return isLong(e)||(e=fromValue(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&(this.high===e.high&&this.low===e.low)},LongPrototype.eq=LongPrototype.equals,LongPrototype.notEquals=function(e){return!this.eq(e)},LongPrototype.neq=LongPrototype.notEquals,LongPrototype.ne=LongPrototype.notEquals,LongPrototype.lessThan=function(e){return this.comp(e)<0},LongPrototype.lt=LongPrototype.lessThan,LongPrototype.lessThanOrEqual=function(e){return this.comp(e)<=0},LongPrototype.lte=LongPrototype.lessThanOrEqual,LongPrototype.le=LongPrototype.lessThanOrEqual,LongPrototype.greaterThan=function(e){return this.comp(e)>0},LongPrototype.gt=LongPrototype.greaterThan,LongPrototype.greaterThanOrEqual=function(e){return this.comp(e)>=0},LongPrototype.gte=LongPrototype.greaterThanOrEqual,LongPrototype.ge=LongPrototype.greaterThanOrEqual,LongPrototype.compare=function(e){if(isLong(e)||(e=fromValue(e)),this.eq(e))return 0;var t=this.isNegative(),r=e.isNegative();return t&&!r?-1:!t&&r?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1},LongPrototype.comp=LongPrototype.compare,LongPrototype.negate=function(){return!this.unsigned&&this.eq(MIN_VALUE)?MIN_VALUE:this.not().add(ONE)},LongPrototype.neg=LongPrototype.negate,LongPrototype.add=function(e){isLong(e)||(e=fromValue(e));var t=this.high>>>16,r=65535&this.high,n=this.low>>>16,i=65535&this.low,o=e.high>>>16,a=65535&e.high,s=e.low>>>16,c=0,u=0,l=0,d=0;return l+=(d+=i+(65535&e.low))>>>16,u+=(l+=n+s)>>>16,c+=(u+=r+a)>>>16,c+=t+o,fromBits((l&=65535)<<16|(d&=65535),(c&=65535)<<16|(u&=65535),this.unsigned)},LongPrototype.subtract=function(e){return isLong(e)||(e=fromValue(e)),this.add(e.neg())},LongPrototype.sub=LongPrototype.subtract,LongPrototype.multiply=function(e){if(this.isZero())return this;if(isLong(e)||(e=fromValue(e)),wasm)return fromBits(wasm.mul(this.low,this.high,e.low,e.high),wasm.get_high(),this.unsigned);if(e.isZero())return this.unsigned?UZERO:ZERO;if(this.eq(MIN_VALUE))return e.isOdd()?MIN_VALUE:ZERO;if(e.eq(MIN_VALUE))return this.isOdd()?MIN_VALUE:ZERO;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(TWO_PWR_24)&&e.lt(TWO_PWR_24))return fromNumber(this.toNumber()*e.toNumber(),this.unsigned);var t=this.high>>>16,r=65535&this.high,n=this.low>>>16,i=65535&this.low,o=e.high>>>16,a=65535&e.high,s=e.low>>>16,c=65535&e.low,u=0,l=0,d=0,p=0;return d+=(p+=i*c)>>>16,l+=(d+=n*c)>>>16,d&=65535,l+=(d+=i*s)>>>16,u+=(l+=r*c)>>>16,l&=65535,u+=(l+=n*s)>>>16,l&=65535,u+=(l+=i*a)>>>16,u+=t*c+r*s+n*a+i*o,fromBits((d&=65535)<<16|(p&=65535),(u&=65535)<<16|(l&=65535),this.unsigned)},LongPrototype.mul=LongPrototype.multiply,LongPrototype.divide=function(e){if(isLong(e)||(e=fromValue(e)),e.isZero())throw Error("division by zero");var t,r,n;if(wasm)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?fromBits((this.unsigned?wasm.div_u:wasm.div_s)(this.low,this.high,e.low,e.high),wasm.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?UZERO:ZERO;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return UZERO;if(e.gt(this.shru(1)))return UONE;n=UZERO}else{if(this.eq(MIN_VALUE))return e.eq(ONE)||e.eq(NEG_ONE)?MIN_VALUE:e.eq(MIN_VALUE)?ONE:(t=this.shr(1).div(e).shl(1)).eq(ZERO)?e.isNegative()?ONE:NEG_ONE:(r=this.sub(e.mul(t)),n=t.add(r.div(e)));if(e.eq(MIN_VALUE))return this.unsigned?UZERO:ZERO;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();n=ZERO}for(r=this;r.gte(e);){t=Math.max(1,Math.floor(r.toNumber()/e.toNumber()));for(var i=Math.ceil(Math.log(t)/Math.LN2),o=i<=48?1:pow_dbl(2,i-48),a=fromNumber(t),s=a.mul(e);s.isNegative()||s.gt(r);)s=(a=fromNumber(t-=o,this.unsigned)).mul(e);a.isZero()&&(a=ONE),n=n.add(a),r=r.sub(s)}return n},LongPrototype.div=LongPrototype.divide,LongPrototype.modulo=function(e){return isLong(e)||(e=fromValue(e)),wasm?fromBits((this.unsigned?wasm.rem_u:wasm.rem_s)(this.low,this.high,e.low,e.high),wasm.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},LongPrototype.mod=LongPrototype.modulo,LongPrototype.rem=LongPrototype.modulo,LongPrototype.not=function(){return fromBits(~this.low,~this.high,this.unsigned)},LongPrototype.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32},LongPrototype.clz=LongPrototype.countLeadingZeros,LongPrototype.countTrailingZeros=function(){return this.low?ctz32(this.low):ctz32(this.high)+32},LongPrototype.ctz=LongPrototype.countTrailingZeros,LongPrototype.and=function(e){return isLong(e)||(e=fromValue(e)),fromBits(this.low&e.low,this.high&e.high,this.unsigned)},LongPrototype.or=function(e){return isLong(e)||(e=fromValue(e)),fromBits(this.low|e.low,this.high|e.high,this.unsigned)},LongPrototype.xor=function(e){return isLong(e)||(e=fromValue(e)),fromBits(this.low^e.low,this.high^e.high,this.unsigned)},LongPrototype.shiftLeft=function(e){return isLong(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?fromBits(this.low<<e,this.high<<e|this.low>>>32-e,this.unsigned):fromBits(0,this.low<<e-32,this.unsigned)},LongPrototype.shl=LongPrototype.shiftLeft,LongPrototype.shiftRight=function(e){return isLong(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?fromBits(this.low>>>e|this.high<<32-e,this.high>>e,this.unsigned):fromBits(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},LongPrototype.shr=LongPrototype.shiftRight,LongPrototype.shiftRightUnsigned=function(e){return isLong(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?fromBits(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):fromBits(32===e?this.high:this.high>>>e-32,0,this.unsigned)},LongPrototype.shru=LongPrototype.shiftRightUnsigned,LongPrototype.shr_u=LongPrototype.shiftRightUnsigned,LongPrototype.rotateLeft=function(e){var t;return isLong(e)&&(e=e.toInt()),0==(e&=63)?this:32===e?fromBits(this.high,this.low,this.unsigned):e<32?(t=32-e,fromBits(this.low<<e|this.high>>>t,this.high<<e|this.low>>>t,this.unsigned)):(t=32-(e-=32),fromBits(this.high<<e|this.low>>>t,this.low<<e|this.high>>>t,this.unsigned))},LongPrototype.rotl=LongPrototype.rotateLeft,LongPrototype.rotateRight=function(e){var t;return isLong(e)&&(e=e.toInt()),0==(e&=63)?this:32===e?fromBits(this.high,this.low,this.unsigned):e<32?(t=32-e,fromBits(this.high<<t|this.low>>>e,this.low<<t|this.high>>>e,this.unsigned)):(t=32-(e-=32),fromBits(this.low<<t|this.high>>>e,this.high<<t|this.low>>>e,this.unsigned))},LongPrototype.rotr=LongPrototype.rotateRight,LongPrototype.toSigned=function(){return this.unsigned?fromBits(this.low,this.high,!1):this},LongPrototype.toUnsigned=function(){return this.unsigned?this:fromBits(this.low,this.high,!0)},LongPrototype.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},LongPrototype.toBytesLE=function(){var e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]},LongPrototype.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,255&e,t>>>24,t>>>16&255,t>>>8&255,255&t]},Long.fromBytes=function(e,t,r){return r?Long.fromBytesLE(e,t):Long.fromBytesBE(e,t)},Long.fromBytesLE=function(e,t){return new Long(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},Long.fromBytesBE=function(e,t){return new Long(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)},"function"==typeof BigInt&&(Long.fromBigInt=function(e,t){return fromBits(Number(BigInt.asIntN(32,e)),Number(BigInt.asIntN(32,e>>BigInt(32))),t)},Long.fromValue=function(e,t){return"bigint"==typeof e?Long.fromBigInt(e,t):fromValue(e,t)},LongPrototype.toBigInt=function(){var e=BigInt(this.low>>>0);return BigInt(this.unsigned?this.high>>>0:this.high)<<BigInt(32)|e});var L,U={exports:{}},x={exports:{}};(L=x).exports=function(e,t){this.v=e,this.k=t},L.exports.__esModule=!0,L.exports.default=L.exports;var Y=x.exports,q={exports:{}},V={exports:{}};!function(e){function t(r,n,i,o){var a=Object.defineProperty;try{a({},"",{})}catch(r){a=0}e.exports=t=function(e,r,n,i){function o(r,n){t(e,r,function(e){return this._invoke(r,n,e)})}r?a?a(e,r,{value:n,enumerable:!i,configurable:!i,writable:!i}):e[r]=n:(o("next",0),o("throw",1),o("return",2))},e.exports.__esModule=!0,e.exports.default=e.exports,t(r,n,i,o)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}(V);var G=V.exports;!function(e){var t=G;function r(){
11
+ */(function(module){!function(g){var r,e,i;r={1:[function(e,t,r){t.exports=function(e,t){for(var r=Array(arguments.length-1),n=0,i=2,o=!0;i<arguments.length;)r[n++]=arguments[i++];return new Promise(function(i,a){r[n]=function(e){if(o)if(o=!1,e)a(e);else{for(var t=Array(arguments.length-1),r=0;r<t.length;)t[r++]=arguments[r];i.apply(null,t)}};try{e.apply(t||null,r)}catch(e){o&&(o=!1,a(e))}})}},{}],2:[function(e,t,r){r.length=function(e){var t=e.length;if(!t)return 0;for(var r=0;1<--t%4&&"="==(e[0|t]||"");)++r;return Math.ceil(3*e.length)/4-r};for(var n=Array(64),i=Array(123),o=0;o<64;)i[n[o]=o<26?o+65:o<52?o+71:o<62?o-4:o-59|43]=o++;r.encode=function(e,t,r){for(var i,o=null,a=[],s=0,c=0;t<r;){var u=e[t++];switch(c){case 0:a[s++]=n[u>>2],i=(3&u)<<4,c=1;break;case 1:a[s++]=n[i|u>>4],i=(15&u)<<2,c=2;break;case 2:a[s++]=n[i|u>>6],a[s++]=n[63&u],c=0}8191<s&&((o=o||[]).push(String.fromCharCode.apply(String,a)),s=0)}return c&&(a[s++]=n[i],a[s++]=61,1===c&&(a[s++]=61)),o?(s&&o.push(String.fromCharCode.apply(String,a.slice(0,s))),o.join("")):String.fromCharCode.apply(String,a.slice(0,s))};var a="invalid encoding";r.decode=function(e,t,r){for(var n,o=r,s=0,c=0;c<e.length;){var u=e.charCodeAt(c++);if(61==u&&1<s)break;if((u=i[u])===g)throw Error(a);switch(s){case 0:n=u,s=1;break;case 1:t[r++]=n<<2|(48&u)>>4,n=u,s=2;break;case 2:t[r++]=(15&n)<<4|(60&u)>>2,n=u,s=3;break;case 3:t[r++]=(3&n)<<6|u,s=0}}if(1===s)throw Error(a);return r-o},r.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}},{}],3:[function(e,t,r){(t.exports=function e(t,r){"string"==typeof t&&(r=t,t=g);var n=[];function i(t){if("string"!=typeof t){var r=o();if(e.verbose&&console.log("codegen: "+r),r="return "+r,t){for(var a=Object.keys(t),s=Array(a.length+1),c=Array(a.length),u=0;u<a.length;)s[u]=a[u],c[u]=t[a[u++]];return s[u]=r,Function.apply(null,s).apply(null,c)}return Function(r)()}for(var l=Array(arguments.length-1),d=0;d<l.length;)l[d]=arguments[++d];if(d=0,t=t.replace(/%([%dfijs])/g,function(e,t){var r=l[d++];switch(t){case"d":case"f":return""+ +(""+r);case"i":return""+Math.floor(r);case"j":return JSON.stringify(r);case"s":return""+r}return"%"}),d!==l.length)throw Error("parameter count mismatch");return n.push(t),i}function o(e){return"function "+(e||r||"")+"("+(t&&t.join(",")||"")+"){\n "+n.join("\n ")+"\n}"}return i.toString=o,i}).verbose=!1},{}],4:[function(e,t,r){function n(){this.t={}}(t.exports=n).prototype.on=function(e,t,r){return(this.t[e]||(this.t[e]=[])).push({fn:t,ctx:r||this}),this},n.prototype.off=function(e,t){if(e===g)this.t={};else if(t===g)this.t[e]=[];else for(var r=this.t[e],n=0;n<r.length;)r[n].fn===t?r.splice(n,1):++n;return this},n.prototype.emit=function(e){var t=this.t[e];if(t){for(var r=[],n=1;n<arguments.length;)r.push(arguments[n++]);for(n=0;n<t.length;)t[n].fn.apply(t[n++].ctx,r)}return this}},{}],5:[function(e,t,r){t.exports=o;var n=e(1),i=e(7)("fs");function o(e,t,r){return t="function"==typeof t?(r=t,{}):t||{},r?!t.xhr&&i&&i.readFile?i.readFile(e,function(n,i){return n&&"undefined"!=typeof XMLHttpRequest?o.xhr(e,t,r):n?r(n):r(null,t.binary?i:i.toString("utf8"))}):o.xhr(e,t,r):n(o,this,e,t)}o.xhr=function(e,t,r){var n=new XMLHttpRequest;n.onreadystatechange=function(){if(4!==n.readyState)return g;if(0!==n.status&&200!==n.status)return r(Error("status "+n.status));if(t.binary){if(!(e=n.response))for(var e=[],i=0;i<n.responseText.length;++i)e.push(255&n.responseText.charCodeAt(i));return r(null,"undefined"!=typeof Uint8Array?new Uint8Array(e):e)}return r(null,n.responseText)},t.binary&&("overrideMimeType"in n&&n.overrideMimeType("text/plain; charset=x-user-defined"),n.responseType="arraybuffer"),n.open("GET",e),n.send()}},{1:1,7:7}],6:[function(e,t,r){function n(e){function t(e,t,r,n){var i=t<0?1:0;e(0===(t=i?-t:t)?0<1/t?0:2147483648:isNaN(t)?2143289344:34028234663852886e22<t?(i<<31|2139095040)>>>0:t<11754943508222875e-54?(i<<31|Math.round(t/1401298464324817e-60))>>>0:(i<<31|127+(e=Math.floor(Math.log(t)/Math.LN2))<<23|8388607&Math.round(t*Math.pow(2,-e)*8388608))>>>0,r,n)}function r(e,t,r){return t=2*((e=e(t,r))>>31)+1,r=e>>>23&255,e&=8388607,255==r?e?NaN:1/0*t:0==r?1401298464324817e-60*t*e:t*Math.pow(2,r-150)*(8388608+e)}function n(e,t,r){d[0]=e,t[r]=p[0],t[r+1]=p[1],t[r+2]=p[2],t[r+3]=p[3]}function c(e,t,r){d[0]=e,t[r]=p[3],t[r+1]=p[2],t[r+2]=p[1],t[r+3]=p[0]}function u(e,t){return p[0]=e[t],p[1]=e[t+1],p[2]=e[t+2],p[3]=e[t+3],d[0]}function l(e,t){return p[3]=e[t],p[2]=e[t+1],p[1]=e[t+2],p[0]=e[t+3],d[0]}var d,p,f,h,g;function m(e,t,r,n,i,o){var a,s=n<0?1:0;0===(n=s?-n:n)?(e(0,i,o+t),e(0<1/n?0:2147483648,i,o+r)):isNaN(n)?(e(0,i,o+t),e(2146959360,i,o+r)):17976931348623157e292<n?(e(0,i,o+t),e((s<<31|2146435072)>>>0,i,o+r)):n<22250738585072014e-324?(e((a=n/5e-324)>>>0,i,o+t),e((s<<31|a/4294967296)>>>0,i,o+r)):(e(4503599627370496*(a=n*Math.pow(2,-(n=1024===(n=Math.floor(Math.log(n)/Math.LN2))?1023:n)))>>>0,i,o+t),e((s<<31|n+1023<<20|1048576*a&1048575)>>>0,i,o+r))}function v(e,t,r,n,i){return t=e(n,i+t),n=2*((e=e(n,i+r))>>31)+1,r=4294967296*(1048575&e)+t,2047==(i=e>>>20&2047)?r?NaN:1/0*n:0==i?5e-324*n*r:n*Math.pow(2,i-1075)*(r+4503599627370496)}function y(e,t,r){f[0]=e,t[r]=h[0],t[r+1]=h[1],t[r+2]=h[2],t[r+3]=h[3],t[r+4]=h[4],t[r+5]=h[5],t[r+6]=h[6],t[r+7]=h[7]}function b(e,t,r){f[0]=e,t[r]=h[7],t[r+1]=h[6],t[r+2]=h[5],t[r+3]=h[4],t[r+4]=h[3],t[r+5]=h[2],t[r+6]=h[1],t[r+7]=h[0]}function S(e,t){return h[0]=e[t],h[1]=e[t+1],h[2]=e[t+2],h[3]=e[t+3],h[4]=e[t+4],h[5]=e[t+5],h[6]=e[t+6],h[7]=e[t+7],f[0]}function _(e,t){return h[7]=e[t],h[6]=e[t+1],h[5]=e[t+2],h[4]=e[t+3],h[3]=e[t+4],h[2]=e[t+5],h[1]=e[t+6],h[0]=e[t+7],f[0]}return"undefined"!=typeof Float32Array?(d=new Float32Array([-0]),g=128===(p=new Uint8Array(d.buffer))[3],e.writeFloatLE=g?n:c,e.writeFloatBE=g?c:n,e.readFloatLE=g?u:l,e.readFloatBE=g?l:u):(e.writeFloatLE=t.bind(null,i),e.writeFloatBE=t.bind(null,o),e.readFloatLE=r.bind(null,a),e.readFloatBE=r.bind(null,s)),"undefined"!=typeof Float64Array?(f=new Float64Array([-0]),g=128===(h=new Uint8Array(f.buffer))[7],e.writeDoubleLE=g?y:b,e.writeDoubleBE=g?b:y,e.readDoubleLE=g?S:_,e.readDoubleBE=g?_:S):(e.writeDoubleLE=m.bind(null,i,0,4),e.writeDoubleBE=m.bind(null,o,4,0),e.readDoubleLE=v.bind(null,a,0,4),e.readDoubleBE=v.bind(null,s,4,0)),e}function i(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function o(e,t,r){t[r]=e>>>24,t[r+1]=e>>>16&255,t[r+2]=e>>>8&255,t[r+3]=255&e}function a(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function s(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}t.exports=n(n)},{}],7:[function(t,i,n){function r(t){try{var i=eval("require")(t);if(i&&(i.length||Object.keys(i).length))return i}catch(t){}return null}i.exports=r},{}],8:[function(e,t,r){var n=r.isAbsolute=function(e){return/^(?:\/|\w+:)/.test(e)},i=r.normalize=function(e){var t=(e=e.replace(/\\/g,"/").replace(/\/{2,}/g,"/")).split("/"),r=n(e);e="",r&&(e=t.shift()+"/");for(var i=0;i<t.length;)".."===t[i]?0<i&&".."!==t[i-1]?t.splice(--i,2):r?t.splice(i,1):++i:"."===t[i]?t.splice(i,1):++i;return e+t.join("/")};r.resolve=function(e,t,r){return r||(t=i(t)),!n(t)&&(e=(e=r?e:i(e)).replace(/(?:\/|^)[^/]+$/,"")).length?i(e+"/"+t):t}},{}],9:[function(e,t,r){t.exports=function(e,t,r){var n=r||8192,i=n>>>1,o=null,a=n;return function(r){return r<1||i<r?e(r):(n<a+r&&(o=e(n),a=0),r=t.call(o,a,a+=r),7&a&&(a=1+(7|a)),r)}}},{}],10:[function(e,t,r){r.length=function(e){for(var t,r=0,n=0;n<e.length;++n)(t=e.charCodeAt(n))<128?r+=1:t<2048?r+=2:55296==(64512&t)&&56320==(64512&e.charCodeAt(n+1))?(++n,r+=4):r+=3;return r},r.read=function(e,t,r){if(r-t<1)return"";for(var n,i=null,o=[],a=0;t<r;)(n=e[t++])<128?o[a++]=n:191<n&&n<224?o[a++]=(31&n)<<6|63&e[t++]:239<n&&n<365?(n=((7&n)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,o[a++]=55296+(n>>10),o[a++]=56320+(1023&n)):o[a++]=(15&n)<<12|(63&e[t++])<<6|63&e[t++],8191<a&&((i=i||[]).push(String.fromCharCode.apply(String,o)),a=0);return i?(a&&i.push(String.fromCharCode.apply(String,o.slice(0,a))),i.join("")):String.fromCharCode.apply(String,o.slice(0,a))},r.write=function(e,t,r){for(var n,i,o=r,a=0;a<e.length;++a)(n=e.charCodeAt(a))<128?t[r++]=n:(n<2048?t[r++]=n>>6|192:(55296==(64512&n)&&56320==(64512&(i=e.charCodeAt(a+1)))?(++a,t[r++]=(n=65536+((1023&n)<<10)+(1023&i))>>18|240,t[r++]=n>>12&63|128):t[r++]=n>>12|224,t[r++]=n>>6&63|128),t[r++]=63&n|128);return r-o}},{}],11:[function(e,t,r){var n=e(14),i=e(33);function o(e,t,r,i){var o=!1;if(t.resolvedType)if(t.resolvedType instanceof n){e("switch(d%s){",i);for(var a=t.resolvedType.values,s=Object.keys(a),c=0;c<s.length;++c)a[s[c]]!==t.typeDefault||o||(e("default:")('if(typeof(d%s)==="number"){m%s=d%s;break}',i,i,i),t.repeated||e("break"),o=!0),e("case%j:",s[c])("case %i:",a[s[c]])("m%s=%j",i,a[s[c]])("break");e("}")}else e('if(typeof d%s!=="object")',i)("throw TypeError(%j)",t.fullName+": object expected")("m%s=types[%i].fromObject(d%s)",i,r,i);else{var u=!1;switch(t.type){case"double":case"float":e("m%s=Number(d%s)",i,i);break;case"uint32":case"fixed32":e("m%s=d%s>>>0",i,i);break;case"int32":case"sint32":case"sfixed32":e("m%s=d%s|0",i,i);break;case"uint64":u=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":e("if(util.Long)")("(m%s=util.Long.fromValue(d%s)).unsigned=%j",i,i,u)('else if(typeof d%s==="string")',i)("m%s=parseInt(d%s,10)",i,i)('else if(typeof d%s==="number")',i)("m%s=d%s",i,i)('else if(typeof d%s==="object")',i)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)",i,i,i,u?"true":"");break;case"bytes":e('if(typeof d%s==="string")',i)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)",i,i,i)("else if(d%s.length >= 0)",i)("m%s=d%s",i,i);break;case"string":e("m%s=String(d%s)",i,i);break;case"bool":e("m%s=Boolean(d%s)",i,i)}}return e}function a(e,t,r,i){if(t.resolvedType)t.resolvedType instanceof n?e("d%s=o.enums===String?(types[%i].values[m%s]===undefined?m%s:types[%i].values[m%s]):m%s",i,r,i,i,r,i,i):e("d%s=types[%i].toObject(m%s,o)",i,r,i);else{var o=!1;switch(t.type){case"double":case"float":e("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s",i,i,i,i);break;case"uint64":o=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":e('if(typeof m%s==="number")',i)("d%s=o.longs===String?String(m%s):m%s",i,i,i)("else")("d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s",i,i,i,i,o?"true":"",i);break;case"bytes":e("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s",i,i,i,i,i);break;default:e("d%s=m%s",i,i)}}return e}r.fromObject=function(e){var t=e.fieldsArray,r=i.codegen(["d"],e.name+"$fromObject")("if(d instanceof this.ctor)")("return d");if(!t.length)return r("return new this.ctor");r("var m=new this.ctor");for(var a=0;a<t.length;++a){var s=t[a].resolve(),c=i.safeProp(s.name);s.map?(r("if(d%s){",c)('if(typeof d%s!=="object")',c)("throw TypeError(%j)",s.fullName+": object expected")("m%s={}",c)("for(var ks=Object.keys(d%s),i=0;i<ks.length;++i){",c),o(r,s,a,c+"[ks[i]]")("}")("}")):s.repeated?(r("if(d%s){",c)("if(!Array.isArray(d%s))",c)("throw TypeError(%j)",s.fullName+": array expected")("m%s=[]",c)("for(var i=0;i<d%s.length;++i){",c),o(r,s,a,c+"[i]")("}")("}")):(s.resolvedType instanceof n||r("if(d%s!=null){",c),o(r,s,a,c),s.resolvedType instanceof n||r("}"))}return r("return m")},r.toObject=function(e){var t=e.fieldsArray.slice().sort(i.compareFieldsById);if(!t.length)return i.codegen()("return {}");for(var r=i.codegen(["m","o"],e.name+"$toObject")("if(!o)")("o={}")("var d={}"),o=[],s=[],c=[],u=0;u<t.length;++u)t[u].partOf||(t[u].resolve().repeated?o:t[u].map?s:c).push(t[u]);if(o.length){for(r("if(o.arrays||o.defaults){"),u=0;u<o.length;++u)r("d%s=[]",i.safeProp(o[u].name));r("}")}if(s.length){for(r("if(o.objects||o.defaults){"),u=0;u<s.length;++u)r("d%s={}",i.safeProp(s[u].name));r("}")}if(c.length){for(r("if(o.defaults){"),u=0;u<c.length;++u){var l,d=c[u],p=i.safeProp(d.name);d.resolvedType instanceof n?r("d%s=o.enums===String?%j:%j",p,d.resolvedType.valuesById[d.typeDefault],d.typeDefault):d.long?r("if(util.Long){")("var n=new util.Long(%i,%i,%j)",d.typeDefault.low,d.typeDefault.high,d.typeDefault.unsigned)("d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n",p)("}else")("d%s=o.longs===String?%j:%i",p,d.typeDefault.toString(),d.typeDefault.toNumber()):d.bytes?(l="["+Array.prototype.slice.call(d.typeDefault).join(",")+"]",r("if(o.bytes===String)d%s=%j",p,String.fromCharCode.apply(String,d.typeDefault))("else{")("d%s=%s",p,l)("if(o.bytes!==Array)d%s=util.newBuffer(d%s)",p,p)("}")):r("d%s=%j",p,d.typeDefault)}r("}")}var f=!1;for(u=0;u<t.length;++u){d=t[u];var h=e.i.indexOf(d);p=i.safeProp(d.name),d.map?(f||(f=!0,r("var ks2")),r("if(m%s&&(ks2=Object.keys(m%s)).length){",p,p)("d%s={}",p)("for(var j=0;j<ks2.length;++j){"),a(r,d,h,p+"[ks2[j]]")("}")):d.repeated?(r("if(m%s&&m%s.length){",p,p)("d%s=[]",p)("for(var j=0;j<m%s.length;++j){",p),a(r,d,h,p+"[j]")("}")):(r("if(m%s!=null&&m.hasOwnProperty(%j)){",p,d.name),a(r,d,h,p),d.partOf&&r("if(o.oneofs)")("d%s=%j",i.safeProp(d.partOf.name),d.name)),r("}")}return r("return d")}},{14:14,33:33}],12:[function(e,t,r){t.exports=function(e){var t=o.codegen(["r","l"],e.name+"$decode")("if(!(r instanceof Reader))")("r=Reader.create(r)")("var c=l===undefined?r.len:r.pos+l,m=new this.ctor"+(e.fieldsArray.filter(function(e){return e.map}).length?",k,value":""))("while(r.pos<c){")("var t=r.uint32()");e.group&&t("if((t&7)===4)")("break"),t("switch(t>>>3){");for(var r=0;r<e.fieldsArray.length;++r){var a=e.i[r].resolve(),s=a.resolvedType instanceof n?"int32":a.type,c="m"+o.safeProp(a.name);t("case %i: {",a.id),a.map?(t("if(%s===util.emptyObject)",c)("%s={}",c)("var c2 = r.uint32()+r.pos"),i.defaults[a.keyType]!==g?t("k=%j",i.defaults[a.keyType]):t("k=null"),i.defaults[s]!==g?t("value=%j",i.defaults[s]):t("value=null"),t("while(r.pos<c2){")("var tag2=r.uint32()")("switch(tag2>>>3){")("case 1: k=r.%s(); break",a.keyType)("case 2:"),i.basic[s]===g?t("value=types[%i].decode(r,r.uint32())",r):t("value=r.%s()",s),t("break")("default:")("r.skipType(tag2&7)")("break")("}")("}"),i.long[a.keyType]!==g?t('%s[typeof k==="object"?util.longToHash(k):k]=value',c):t("%s[k]=value",c)):a.repeated?(t("if(!(%s&&%s.length))",c,c)("%s=[]",c),i.packed[s]!==g&&t("if((t&7)===2){")("var c2=r.uint32()+r.pos")("while(r.pos<c2)")("%s.push(r.%s())",c,s)("}else"),i.basic[s]===g?t(a.resolvedType.group?"%s.push(types[%i].decode(r))":"%s.push(types[%i].decode(r,r.uint32()))",c,r):t("%s.push(r.%s())",c,s)):i.basic[s]===g?t(a.resolvedType.group?"%s=types[%i].decode(r)":"%s=types[%i].decode(r,r.uint32())",c,r):t("%s=r.%s()",c,s),t("break")("}")}for(t("default:")("r.skipType(t&7)")("break")("}")("}"),r=0;r<e.i.length;++r){var u=e.i[r];u.required&&t("if(!m.hasOwnProperty(%j))",u.name)("throw util.ProtocolError(%j,{instance:m})","missing required '"+u.name+"'")}return t("return m")};var n=e(14),i=e(32),o=e(33)},{14:14,32:32,33:33}],13:[function(e,t,r){t.exports=function(e){for(var t,r=o.codegen(["m","w"],e.name+"$encode")("if(!w)")("w=Writer.create()"),s=e.fieldsArray.slice().sort(o.compareFieldsById),c=0;c<s.length;++c){var u=s[c].resolve(),l=e.i.indexOf(u),d=u.resolvedType instanceof n?"int32":u.type,p=i.basic[d];t="m"+o.safeProp(u.name),u.map?(r("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){",t,u.name)("for(var ks=Object.keys(%s),i=0;i<ks.length;++i){",t)("w.uint32(%i).fork().uint32(%i).%s(ks[i])",(u.id<<3|2)>>>0,8|i.mapKey[u.keyType],u.keyType),p===g?r("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()",l,t):r(".uint32(%i).%s(%s[ks[i]]).ldelim()",16|p,d,t),r("}")("}")):u.repeated?(r("if(%s!=null&&%s.length){",t,t),u.packed&&i.packed[d]!==g?r("w.uint32(%i).fork()",(u.id<<3|2)>>>0)("for(var i=0;i<%s.length;++i)",t)("w.%s(%s[i])",d,t)("w.ldelim()"):(r("for(var i=0;i<%s.length;++i)",t),p===g?a(r,u,l,t+"[i]"):r("w.uint32(%i).%s(%s[i])",(u.id<<3|p)>>>0,d,t)),r("}")):(u.optional&&r("if(%s!=null&&Object.hasOwnProperty.call(m,%j))",t,u.name),p===g?a(r,u,l,t):r("w.uint32(%i).%s(%s)",(u.id<<3|p)>>>0,d,t))}return r("return w")};var n=e(14),i=e(32),o=e(33);function a(e,t,r,n){t.resolvedType.group?e("types[%i].encode(%s,w.uint32(%i)).uint32(%i)",r,n,(t.id<<3|3)>>>0,(t.id<<3|4)>>>0):e("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()",r,n,(t.id<<3|2)>>>0)}},{14:14,32:32,33:33}],14:[function(e,t,r){t.exports=a;var n=e(22),i=(((a.prototype=Object.create(n.prototype)).constructor=a).className="Enum",e(21)),o=e(33);function a(e,t,r,i,o,a){if(n.call(this,e,r),t&&"object"!=typeof t)throw TypeError("values must be an object");if(this.valuesById={},this.values=Object.create(this.valuesById),this.comment=i,this.comments=o||{},this.valuesOptions=a,this.reserved=g,t)for(var s=Object.keys(t),c=0;c<s.length;++c)"number"==typeof t[s[c]]&&(this.valuesById[this.values[s[c]]=t[s[c]]]=s[c])}a.fromJSON=function(e,t){return(e=new a(e,t.values,t.options,t.comment,t.comments)).reserved=t.reserved,e},a.prototype.toJSON=function(e){return e=!!e&&!!e.keepComments,o.toObject(["options",this.options,"valuesOptions",this.valuesOptions,"values",this.values,"reserved",this.reserved&&this.reserved.length?this.reserved:g,"comment",e?this.comment:g,"comments",e?this.comments:g])},a.prototype.add=function(e,t,r,n){if(!o.isString(e))throw TypeError("name must be a string");if(!o.isInteger(t))throw TypeError("id must be an integer");if(this.values[e]!==g)throw Error("duplicate name '"+e+"' in "+this);if(this.isReservedId(t))throw Error("id "+t+" is reserved in "+this);if(this.isReservedName(e))throw Error("name '"+e+"' is reserved in "+this);if(this.valuesById[t]!==g){if(!this.options||!this.options.allow_alias)throw Error("duplicate id "+t+" in "+this);this.values[e]=t}else this.valuesById[this.values[e]=t]=e;return n&&(this.valuesOptions===g&&(this.valuesOptions={}),this.valuesOptions[e]=n||null),this.comments[e]=r||null,this},a.prototype.remove=function(e){if(!o.isString(e))throw TypeError("name must be a string");var t=this.values[e];if(null==t)throw Error("name '"+e+"' does not exist in "+this);return delete this.valuesById[t],delete this.values[e],delete this.comments[e],this.valuesOptions&&delete this.valuesOptions[e],this},a.prototype.isReservedId=function(e){return i.isReservedId(this.reserved,e)},a.prototype.isReservedName=function(e){return i.isReservedName(this.reserved,e)}},{21:21,22:22,33:33}],15:[function(e,t,r){t.exports=u;var n,i=e(22),o=(((u.prototype=Object.create(i.prototype)).constructor=u).className="Field",e(14)),a=e(32),s=e(33),c=/^required|optional|repeated$/;function u(e,t,r,n,o,u,l){if(s.isObject(n)?(l=o,u=n,n=o=g):s.isObject(o)&&(l=u,u=o,o=g),i.call(this,e,u),!s.isInteger(t)||t<0)throw TypeError("id must be a non-negative integer");if(!s.isString(r))throw TypeError("type must be a string");if(n!==g&&!c.test(n=n.toString().toLowerCase()))throw TypeError("rule must be a string rule");if(o!==g&&!s.isString(o))throw TypeError("extend must be a string");this.rule=(n="proto3_optional"===n?"optional":n)&&"optional"!==n?n:g,this.type=r,this.id=t,this.extend=o||g,this.required="required"===n,this.optional=!this.required,this.repeated="repeated"===n,this.map=!1,this.message=null,this.partOf=null,this.typeDefault=null,this.defaultValue=null,this.long=!!s.Long&&a.long[r]!==g,this.bytes="bytes"===r,this.resolvedType=null,this.extensionField=null,this.declaringField=null,this.n=null,this.comment=l}u.fromJSON=function(e,t){return new u(e,t.id,t.type,t.rule,t.extend,t.options,t.comment)},Object.defineProperty(u.prototype,"packed",{get:function(){return null===this.n&&(this.n=!1!==this.getOption("packed")),this.n}}),u.prototype.setOption=function(e,t,r){return"packed"===e&&(this.n=null),i.prototype.setOption.call(this,e,t,r)},u.prototype.toJSON=function(e){return e=!!e&&!!e.keepComments,s.toObject(["rule","optional"!==this.rule&&this.rule||g,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",e?this.comment:g])},u.prototype.resolve=function(){var e;return this.resolved?this:((this.typeDefault=a.defaults[this.type])===g?(this.resolvedType=(this.declaringField||this).parent.lookupTypeOrEnum(this.type),this.resolvedType instanceof n?this.typeDefault=null:this.typeDefault=this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]):this.options&&this.options.proto3_optional&&(this.typeDefault=null),this.options&&null!=this.options.default&&(this.typeDefault=this.options.default,this.resolvedType instanceof o&&"string"==typeof this.typeDefault&&(this.typeDefault=this.resolvedType.values[this.typeDefault])),this.options&&(!0!==this.options.packed&&(this.options.packed===g||!this.resolvedType||this.resolvedType instanceof o)||delete this.options.packed,Object.keys(this.options).length||(this.options=g)),this.long?(this.typeDefault=s.Long.fromNumber(this.typeDefault,"u"==(this.type[0]||"")),Object.freeze&&Object.freeze(this.typeDefault)):this.bytes&&"string"==typeof this.typeDefault&&(s.base64.test(this.typeDefault)?s.base64.decode(this.typeDefault,e=s.newBuffer(s.base64.length(this.typeDefault)),0):s.utf8.write(this.typeDefault,e=s.newBuffer(s.utf8.length(this.typeDefault)),0),this.typeDefault=e),this.map?this.defaultValue=s.emptyObject:this.repeated?this.defaultValue=s.emptyArray:this.defaultValue=this.typeDefault,this.parent instanceof n&&(this.parent.ctor.prototype[this.name]=this.defaultValue),i.prototype.resolve.call(this))},u.d=function(e,t,r,n){return"function"==typeof t?t=s.decorateType(t).name:t&&"object"==typeof t&&(t=s.decorateEnum(t).name),function(i,o){s.decorateType(i.constructor).add(new u(o,e,t,r,{default:n}))}},u.r=function(e){n=e}},{14:14,22:22,32:32,33:33}],16:[function(e,t,r){var n=t.exports=e(17);n.build="light",n.load=function(e,t,r){return(t="function"==typeof t?(r=t,new n.Root):t||new n.Root).load(e,r)},n.loadSync=function(e,t){return(t=t||new n.Root).loadSync(e)},n.encoder=e(13),n.decoder=e(12),n.verifier=e(36),n.converter=e(11),n.ReflectionObject=e(22),n.Namespace=e(21),n.Root=e(26),n.Enum=e(14),n.Type=e(31),n.Field=e(15),n.OneOf=e(23),n.MapField=e(18),n.Service=e(30),n.Method=e(20),n.Message=e(19),n.wrappers=e(37),n.types=e(32),n.util=e(33),n.ReflectionObject.r(n.Root),n.Namespace.r(n.Type,n.Service,n.Enum),n.Root.r(n.Type),n.Field.r(n.Type)},{11:11,12:12,13:13,14:14,15:15,17:17,18:18,19:19,20:20,21:21,22:22,23:23,26:26,30:30,31:31,32:32,33:33,36:36,37:37}],17:[function(e,t,r){var n=r;function i(){n.util.r(),n.Writer.r(n.BufferWriter),n.Reader.r(n.BufferReader)}n.build="minimal",n.Writer=e(38),n.BufferWriter=e(39),n.Reader=e(24),n.BufferReader=e(25),n.util=e(35),n.rpc=e(28),n.roots=e(27),n.configure=i,i()},{24:24,25:25,27:27,28:28,35:35,38:38,39:39}],18:[function(e,t,r){t.exports=a;var n=e(15),i=(((a.prototype=Object.create(n.prototype)).constructor=a).className="MapField",e(32)),o=e(33);function a(e,t,r,i,a,s){if(n.call(this,e,t,i,g,g,a,s),!o.isString(r))throw TypeError("keyType must be a string");this.keyType=r,this.resolvedKeyType=null,this.map=!0}a.fromJSON=function(e,t){return new a(e,t.id,t.keyType,t.type,t.options,t.comment)},a.prototype.toJSON=function(e){return e=!!e&&!!e.keepComments,o.toObject(["keyType",this.keyType,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",e?this.comment:g])},a.prototype.resolve=function(){if(this.resolved)return this;if(i.mapKey[this.keyType]===g)throw Error("invalid key type: "+this.keyType);return n.prototype.resolve.call(this)},a.d=function(e,t,r){return"function"==typeof r?r=o.decorateType(r).name:r&&"object"==typeof r&&(r=o.decorateEnum(r).name),function(n,i){o.decorateType(n.constructor).add(new a(i,e,t,r))}}},{15:15,32:32,33:33}],19:[function(e,t,r){t.exports=i;var n=e(35);function i(e){if(e)for(var t=Object.keys(e),r=0;r<t.length;++r)this[t[r]]=e[t[r]]}i.create=function(e){return this.$type.create(e)},i.encode=function(e,t){return this.$type.encode(e,t)},i.encodeDelimited=function(e,t){return this.$type.encodeDelimited(e,t)},i.decode=function(e){return this.$type.decode(e)},i.decodeDelimited=function(e){return this.$type.decodeDelimited(e)},i.verify=function(e){return this.$type.verify(e)},i.fromObject=function(e){return this.$type.fromObject(e)},i.toObject=function(e,t){return this.$type.toObject(e,t)},i.prototype.toJSON=function(){return this.$type.toObject(this,n.toJSONOptions)}},{35:35}],20:[function(e,t,r){t.exports=o;var n=e(22),i=(((o.prototype=Object.create(n.prototype)).constructor=o).className="Method",e(33));function o(e,t,r,o,a,s,c,u,l){if(i.isObject(a)?(c=a,a=s=g):i.isObject(s)&&(c=s,s=g),t!==g&&!i.isString(t))throw TypeError("type must be a string");if(!i.isString(r))throw TypeError("requestType must be a string");if(!i.isString(o))throw TypeError("responseType must be a string");n.call(this,e,c),this.type=t||"rpc",this.requestType=r,this.requestStream=!!a||g,this.responseType=o,this.responseStream=!!s||g,this.resolvedRequestType=null,this.resolvedResponseType=null,this.comment=u,this.parsedOptions=l}o.fromJSON=function(e,t){return new o(e,t.type,t.requestType,t.responseType,t.requestStream,t.responseStream,t.options,t.comment,t.parsedOptions)},o.prototype.toJSON=function(e){return e=!!e&&!!e.keepComments,i.toObject(["type","rpc"!==this.type&&this.type||g,"requestType",this.requestType,"requestStream",this.requestStream,"responseType",this.responseType,"responseStream",this.responseStream,"options",this.options,"comment",e?this.comment:g,"parsedOptions",this.parsedOptions])},o.prototype.resolve=function(){return this.resolved?this:(this.resolvedRequestType=this.parent.lookupType(this.requestType),this.resolvedResponseType=this.parent.lookupType(this.responseType),n.prototype.resolve.call(this))}},{22:22,33:33}],21:[function(e,t,r){t.exports=d;var n,i,o,a=e(22),s=(((d.prototype=Object.create(a.prototype)).constructor=d).className="Namespace",e(15)),c=e(33),u=e(23);function l(e,t){if(!e||!e.length)return g;for(var r={},n=0;n<e.length;++n)r[e[n].name]=e[n].toJSON(t);return r}function d(e,t){a.call(this,e,t),this.nested=g,this.e=null}function p(e){return e.e=null,e}d.fromJSON=function(e,t){return new d(e,t.options).addJSON(t.nested)},d.arrayToJSON=l,d.isReservedId=function(e,t){if(e)for(var r=0;r<e.length;++r)if("string"!=typeof e[r]&&e[r][0]<=t&&e[r][1]>t)return!0;return!1},d.isReservedName=function(e,t){if(e)for(var r=0;r<e.length;++r)if(e[r]===t)return!0;return!1},Object.defineProperty(d.prototype,"nestedArray",{get:function(){return this.e||(this.e=c.toArray(this.nested))}}),d.prototype.toJSON=function(e){return c.toObject(["options",this.options,"nested",l(this.nestedArray,e)])},d.prototype.addJSON=function(e){if(e)for(var t,r=Object.keys(e),a=0;a<r.length;++a)t=e[r[a]],this.add((t.fields!==g?n:t.values!==g?o:t.methods!==g?i:t.id!==g?s:d).fromJSON(r[a],t));return this},d.prototype.get=function(e){return this.nested&&this.nested[e]||null},d.prototype.getEnum=function(e){if(this.nested&&this.nested[e]instanceof o)return this.nested[e].values;throw Error("no such enum: "+e)},d.prototype.add=function(e){if(!(e instanceof s&&e.extend!==g||e instanceof n||e instanceof u||e instanceof o||e instanceof i||e instanceof d))throw TypeError("object must be a valid nested object");if(this.nested){var t=this.get(e.name);if(t){if(!(t instanceof d&&e instanceof d)||t instanceof n||t instanceof i)throw Error("duplicate name '"+e.name+"' in "+this);for(var r=t.nestedArray,a=0;a<r.length;++a)e.add(r[a]);this.remove(t),this.nested||(this.nested={}),e.setOptions(t.options,!0)}}else this.nested={};return(this.nested[e.name]=e).onAdd(this),p(this)},d.prototype.remove=function(e){if(!(e instanceof a))throw TypeError("object must be a ReflectionObject");if(e.parent!==this)throw Error(e+" is not a member of "+this);return delete this.nested[e.name],Object.keys(this.nested).length||(this.nested=g),e.onRemove(this),p(this)},d.prototype.define=function(e,t){if(c.isString(e))e=e.split(".");else if(!Array.isArray(e))throw TypeError("illegal path");if(e&&e.length&&""===e[0])throw Error("path must be relative");for(var r=this;0<e.length;){var n=e.shift();if(r.nested&&r.nested[n]){if(!((r=r.nested[n])instanceof d))throw Error("path conflicts with non-namespace objects")}else r.add(r=new d(n))}return t&&r.addJSON(t),r},d.prototype.resolveAll=function(){for(var e=this.nestedArray,t=0;t<e.length;)e[t]instanceof d?e[t++].resolveAll():e[t++].resolve();return this.resolve()},d.prototype.lookup=function(e,t,r){if("boolean"==typeof t?(r=t,t=g):t&&!Array.isArray(t)&&(t=[t]),c.isString(e)&&e.length){if("."===e)return this.root;e=e.split(".")}else if(!e.length)return this;if(""===e[0])return this.root.lookup(e.slice(1),t);var n=this.get(e[0]);if(n){if(1===e.length){if(!t||~t.indexOf(n.constructor))return n}else if(n instanceof d&&(n=n.lookup(e.slice(1),t,!0)))return n}else for(var i=0;i<this.nestedArray.length;++i)if(this.e[i]instanceof d&&(n=this.e[i].lookup(e,t,!0)))return n;return null===this.parent||r?null:this.parent.lookup(e,t)},d.prototype.lookupType=function(e){var t=this.lookup(e,[n]);if(t)return t;throw Error("no such type: "+e)},d.prototype.lookupEnum=function(e){var t=this.lookup(e,[o]);if(t)return t;throw Error("no such Enum '"+e+"' in "+this)},d.prototype.lookupTypeOrEnum=function(e){var t=this.lookup(e,[n,o]);if(t)return t;throw Error("no such Type or Enum '"+e+"' in "+this)},d.prototype.lookupService=function(e){var t=this.lookup(e,[i]);if(t)return t;throw Error("no such Service '"+e+"' in "+this)},d.r=function(e,t,r){n=e,i=t,o=r}},{15:15,22:22,23:23,33:33}],22:[function(e,t,r){(t.exports=o).className="ReflectionObject";var n,i=e(33);function o(e,t){if(!i.isString(e))throw TypeError("name must be a string");if(t&&!i.isObject(t))throw TypeError("options must be an object");this.options=t,this.parsedOptions=null,this.name=e,this.parent=null,this.resolved=!1,this.comment=null,this.filename=null}Object.defineProperties(o.prototype,{root:{get:function(){for(var e=this;null!==e.parent;)e=e.parent;return e}},fullName:{get:function(){for(var e=[this.name],t=this.parent;t;)e.unshift(t.name),t=t.parent;return e.join(".")}}}),o.prototype.toJSON=function(){throw Error()},o.prototype.onAdd=function(e){this.parent&&this.parent!==e&&this.parent.remove(this),this.parent=e,this.resolved=!1,(e=e.root)instanceof n&&e.u(this)},o.prototype.onRemove=function(e){(e=e.root)instanceof n&&e.o(this),this.parent=null,this.resolved=!1},o.prototype.resolve=function(){return this.resolved||this.root instanceof n&&(this.resolved=!0),this},o.prototype.getOption=function(e){return this.options?this.options[e]:g},o.prototype.setOption=function(e,t,r){return r&&this.options&&this.options[e]!==g||((this.options||(this.options={}))[e]=t),this},o.prototype.setParsedOption=function(e,t,r){this.parsedOptions||(this.parsedOptions=[]);var n,o,a=this.parsedOptions;return r?(n=a.find(function(t){return Object.prototype.hasOwnProperty.call(t,e)}))?(o=n[e],i.setProperty(o,r,t)):((n={})[e]=i.setProperty({},r,t),a.push(n)):((o={})[e]=t,a.push(o)),this},o.prototype.setOptions=function(e,t){if(e)for(var r=Object.keys(e),n=0;n<r.length;++n)this.setOption(r[n],e[r[n]],t);return this},o.prototype.toString=function(){var e=this.constructor.className,t=this.fullName;return t.length?e+" "+t:e},o.r=function(e){n=e}},{33:33}],23:[function(e,t,r){t.exports=a;var n=e(22),i=(((a.prototype=Object.create(n.prototype)).constructor=a).className="OneOf",e(15)),o=e(33);function a(e,t,r,i){if(Array.isArray(t)||(r=t,t=g),n.call(this,e,r),t!==g&&!Array.isArray(t))throw TypeError("fieldNames must be an Array");this.oneof=t||[],this.fieldsArray=[],this.comment=i}function s(e){if(e.parent)for(var t=0;t<e.fieldsArray.length;++t)e.fieldsArray[t].parent||e.parent.add(e.fieldsArray[t])}a.fromJSON=function(e,t){return new a(e,t.oneof,t.options,t.comment)},a.prototype.toJSON=function(e){return e=!!e&&!!e.keepComments,o.toObject(["options",this.options,"oneof",this.oneof,"comment",e?this.comment:g])},a.prototype.add=function(e){if(e instanceof i)return e.parent&&e.parent!==this.parent&&e.parent.remove(e),this.oneof.push(e.name),this.fieldsArray.push(e),s(e.partOf=this),this;throw TypeError("field must be a Field")},a.prototype.remove=function(e){if(!(e instanceof i))throw TypeError("field must be a Field");var t=this.fieldsArray.indexOf(e);if(t<0)throw Error(e+" is not a member of "+this);return this.fieldsArray.splice(t,1),-1<(t=this.oneof.indexOf(e.name))&&this.oneof.splice(t,1),e.partOf=null,this},a.prototype.onAdd=function(e){n.prototype.onAdd.call(this,e);for(var t=0;t<this.oneof.length;++t){var r=e.get(this.oneof[t]);r&&!r.partOf&&(r.partOf=this).fieldsArray.push(r)}s(this)},a.prototype.onRemove=function(e){for(var t,r=0;r<this.fieldsArray.length;++r)(t=this.fieldsArray[r]).parent&&t.parent.remove(t);n.prototype.onRemove.call(this,e)},a.d=function(){for(var e=Array(arguments.length),t=0;t<arguments.length;)e[t]=arguments[t++];return function(t,r){o.decorateType(t.constructor).add(new a(r,e)),Object.defineProperty(t,r,{get:o.oneOfGetter(e),set:o.oneOfSetter(e)})}}},{15:15,22:22,33:33}],24:[function(e,t,r){t.exports=c;var n,i=e(35),o=i.LongBits,a=i.utf8;function s(e,t){return RangeError("index out of range: "+e.pos+" + "+(t||1)+" > "+e.len)}function c(e){this.buf=e,this.pos=0,this.len=e.length}function u(){return i.Buffer?function(e){return(c.create=function(e){return i.Buffer.isBuffer(e)?new n(e):d(e)})(e)}:d}var l,d="undefined"!=typeof Uint8Array?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new c(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new c(e);throw Error("illegal buffer")};function p(){var e=new o(0,0),t=0;if(!(4<this.len-this.pos)){for(;t<3;++t){if(this.pos>=this.len)throw s(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,4<this.len-this.pos){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw s(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}function f(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}function h(){if(this.pos+8>this.len)throw s(this,8);return new o(f(this.buf,this.pos+=4),f(this.buf,this.pos+=4))}c.create=u(),c.prototype.h=i.Array.prototype.subarray||i.Array.prototype.slice,c.prototype.uint32=(l=4294967295,function(){if(l=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128||(l=(l|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128||(l=(l|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128||(l=(l|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128||(l=(l|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128||!((this.pos+=5)>this.len))))))return l;throw this.pos=this.len,s(this,10)}),c.prototype.int32=function(){return 0|this.uint32()},c.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(1&e)},c.prototype.bool=function(){return 0!==this.uint32()},c.prototype.fixed32=function(){if(this.pos+4>this.len)throw s(this,4);return f(this.buf,this.pos+=4)},c.prototype.sfixed32=function(){if(this.pos+4>this.len)throw s(this,4);return 0|f(this.buf,this.pos+=4)},c.prototype.float=function(){if(this.pos+4>this.len)throw s(this,4);var e=i.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e},c.prototype.double=function(){if(this.pos+8>this.len)throw s(this,4);var e=i.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e},c.prototype.bytes=function(){var e=this.uint32(),t=this.pos,r=this.pos+e;if(r>this.len)throw s(this,e);return this.pos+=e,Array.isArray(this.buf)?this.buf.slice(t,r):t===r?(e=i.Buffer)?e.alloc(0):new this.buf.constructor(0):this.h.call(this.buf,t,r)},c.prototype.string=function(){var e=this.bytes();return a.read(e,0,e.length)},c.prototype.skip=function(e){if("number"==typeof e){if(this.pos+e>this.len)throw s(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw s(this)}while(128&this.buf[this.pos++]);return this},c.prototype.skipType=function(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+e+" at offset "+this.pos)}return this},c.r=function(e){n=e,c.create=u(),n.r();var t=i.Long?"toLong":"toNumber";i.merge(c.prototype,{int64:function(){return p.call(this)[t](!1)},uint64:function(){return p.call(this)[t](!0)},sint64:function(){return p.call(this).zzDecode()[t](!1)},fixed64:function(){return h.call(this)[t](!0)},sfixed64:function(){return h.call(this)[t](!1)}})}},{35:35}],25:[function(e,t,r){t.exports=o;var n=e(24),i=((o.prototype=Object.create(n.prototype)).constructor=o,e(35));function o(e){n.call(this,e)}o.r=function(){i.Buffer&&(o.prototype.h=i.Buffer.prototype.slice)},o.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))},o.r()},{24:24,35:35}],26:[function(e,t,r){t.exports=d;var n,i,o,a=e(21),s=(((d.prototype=Object.create(a.prototype)).constructor=d).className="Root",e(15)),c=e(14),u=e(23),l=e(33);function d(e){a.call(this,"",e),this.deferred=[],this.files=[]}function p(){}d.fromJSON=function(e,t){return t=t||new d,e.options&&t.setOptions(e.options),t.addJSON(e.nested)},d.prototype.resolvePath=l.path.resolve,d.prototype.fetch=l.fetch,d.prototype.load=function e(t,r,n){"function"==typeof r&&(n=r,r=g);var a=this;if(!n)return l.asPromise(e,a,t,r);var s=n===p;function c(e,t){if(n){if(s)throw e;var r=n;n=null,r(e,t)}}function u(e){var t=e.lastIndexOf("google/protobuf/");return-1<t&&(e=e.substring(t))in o?e:null}function d(e,t){try{if(l.isString(t)&&"{"==(t[0]||"")&&(t=JSON.parse(t)),l.isString(t)){i.filename=e;var n,o=i(t,a,r),d=0;if(o.imports)for(;d<o.imports.length;++d)(n=u(o.imports[d])||a.resolvePath(e,o.imports[d]))&&f(n);if(o.weakImports)for(d=0;d<o.weakImports.length;++d)(n=u(o.weakImports[d])||a.resolvePath(e,o.weakImports[d]))&&f(n,!0)}else a.setOptions(t.options).addJSON(t.nested)}catch(e){c(e)}s||h||c(null,a)}function f(e,t){if(e=u(e)||e,!~a.files.indexOf(e))if(a.files.push(e),e in o)s?d(e,o[e]):(++h,setTimeout(function(){--h,d(e,o[e])}));else if(s){var r;try{r=l.fs.readFileSync(e).toString("utf8")}catch(r){return void(t||c(r))}d(e,r)}else++h,a.fetch(e,function(r,i){--h,n&&(r?t?h||c(null,a):c(r):d(e,i))})}var h=0;l.isString(t)&&(t=[t]);for(var m,v=0;v<t.length;++v)(m=a.resolvePath("",t[v]))&&f(m);return s?a:(h||c(null,a),g)},d.prototype.loadSync=function(e,t){if(l.isNode)return this.load(e,t,p);throw Error("not supported")},d.prototype.resolveAll=function(){if(this.deferred.length)throw Error("unresolvable extensions: "+this.deferred.map(function(e){return"'extend "+e.extend+"' in "+e.parent.fullName}).join(", "));return a.prototype.resolveAll.call(this)};var f=/^[A-Z]/;function h(e,t){var r,n=t.parent.lookup(t.extend);if(n)return r=new s(t.fullName,t.id,t.type,t.rule,g,t.options),n.get(r.name)||((r.declaringField=t).extensionField=r,n.add(r)),1}d.prototype.u=function(e){if(e instanceof s)e.extend===g||e.extensionField||h(0,e)||this.deferred.push(e);else if(e instanceof c)f.test(e.name)&&(e.parent[e.name]=e.values);else if(!(e instanceof u)){if(e instanceof n)for(var t=0;t<this.deferred.length;)h(0,this.deferred[t])?this.deferred.splice(t,1):++t;for(var r=0;r<e.nestedArray.length;++r)this.u(e.e[r]);f.test(e.name)&&(e.parent[e.name]=e)}},d.prototype.o=function(e){var t;if(e instanceof s)e.extend!==g&&(e.extensionField?(e.extensionField.parent.remove(e.extensionField),e.extensionField=null):-1<(t=this.deferred.indexOf(e))&&this.deferred.splice(t,1));else if(e instanceof c)f.test(e.name)&&delete e.parent[e.name];else if(e instanceof a){for(var r=0;r<e.nestedArray.length;++r)this.o(e.e[r]);f.test(e.name)&&delete e.parent[e.name]}},d.r=function(e,t,r){n=e,i=t,o=r}},{14:14,15:15,21:21,23:23,33:33}],27:[function(e,t,r){t.exports={}},{}],28:[function(e,t,r){r.Service=e(29)},{29:29}],29:[function(e,t,r){t.exports=i;var n=e(35);function i(e,t,r){if("function"!=typeof e)throw TypeError("rpcImpl must be a function");n.EventEmitter.call(this),this.rpcImpl=e,this.requestDelimited=!!t,this.responseDelimited=!!r}((i.prototype=Object.create(n.EventEmitter.prototype)).constructor=i).prototype.rpcCall=function e(t,r,i,o,a){if(!o)throw TypeError("request must be specified");var s=this;if(!a)return n.asPromise(e,s,t,r,i,o);if(!s.rpcImpl)return setTimeout(function(){a(Error("already ended"))},0),g;try{return s.rpcImpl(t,r[s.requestDelimited?"encodeDelimited":"encode"](o).finish(),function(e,r){if(e)return s.emit("error",e,t),a(e);if(null===r)return s.end(!0),g;if(!(r instanceof i))try{r=i[s.responseDelimited?"decodeDelimited":"decode"](r)}catch(e){return s.emit("error",e,t),a(e)}return s.emit("data",r,t),a(null,r)})}catch(e){return s.emit("error",e,t),setTimeout(function(){a(e)},0),g}},i.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}},{35:35}],30:[function(e,t,r){t.exports=s;var n=e(21),i=(((s.prototype=Object.create(n.prototype)).constructor=s).className="Service",e(20)),o=e(33),a=e(28);function s(e,t){n.call(this,e,t),this.methods={},this.f=null}function c(e){return e.f=null,e}s.fromJSON=function(e,t){var r=new s(e,t.options);if(t.methods)for(var n=Object.keys(t.methods),o=0;o<n.length;++o)r.add(i.fromJSON(n[o],t.methods[n[o]]));return t.nested&&r.addJSON(t.nested),r.comment=t.comment,r},s.prototype.toJSON=function(e){var t=n.prototype.toJSON.call(this,e),r=!!e&&!!e.keepComments;return o.toObject(["options",t&&t.options||g,"methods",n.arrayToJSON(this.methodsArray,e)||{},"nested",t&&t.nested||g,"comment",r?this.comment:g])},Object.defineProperty(s.prototype,"methodsArray",{get:function(){return this.f||(this.f=o.toArray(this.methods))}}),s.prototype.get=function(e){return this.methods[e]||n.prototype.get.call(this,e)},s.prototype.resolveAll=function(){for(var e=this.methodsArray,t=0;t<e.length;++t)e[t].resolve();return n.prototype.resolve.call(this)},s.prototype.add=function(e){if(this.get(e.name))throw Error("duplicate name '"+e.name+"' in "+this);return e instanceof i?c((this.methods[e.name]=e).parent=this):n.prototype.add.call(this,e)},s.prototype.remove=function(e){if(e instanceof i){if(this.methods[e.name]!==e)throw Error(e+" is not a member of "+this);return delete this.methods[e.name],e.parent=null,c(this)}return n.prototype.remove.call(this,e)},s.prototype.create=function(e,t,r){for(var n,i=new a.Service(e,t,r),s=0;s<this.methodsArray.length;++s){var c=o.lcFirst((n=this.f[s]).resolve().name).replace(/[^$\w_]/g,"");i[c]=o.codegen(["r","c"],o.isReserved(c)?c+"_":c)("return this.rpcCall(m,q,s,r,c)")({m:n,q:n.resolvedRequestType.ctor,s:n.resolvedResponseType.ctor})}return i}},{20:20,21:21,28:28,33:33}],31:[function(e,t,r){t.exports=b;var n=e(21),i=(((b.prototype=Object.create(n.prototype)).constructor=b).className="Type",e(14)),o=e(23),a=e(15),s=e(18),c=e(30),u=e(19),l=e(24),d=e(38),p=e(33),f=e(13),h=e(12),m=e(36),v=e(11),y=e(37);function b(e,t){n.call(this,e,t),this.fields={},this.oneofs=g,this.extensions=g,this.reserved=g,this.group=g,this.c=null,this.i=null,this.a=null,this.l=null}function S(e){return e.c=e.i=e.a=null,delete e.encode,delete e.decode,delete e.verify,e}Object.defineProperties(b.prototype,{fieldsById:{get:function(){if(!this.c){this.c={};for(var e=Object.keys(this.fields),t=0;t<e.length;++t){var r=this.fields[e[t]],n=r.id;if(this.c[n])throw Error("duplicate id "+n+" in "+this);this.c[n]=r}}return this.c}},fieldsArray:{get:function(){return this.i||(this.i=p.toArray(this.fields))}},oneofsArray:{get:function(){return this.a||(this.a=p.toArray(this.oneofs))}},ctor:{get:function(){return this.l||(this.ctor=b.generateConstructor(this)())},set:function(e){for(var t=e.prototype,r=(t instanceof u||((e.prototype=new u).constructor=e,p.merge(e.prototype,t)),e.$type=e.prototype.$type=this,p.merge(e,u,!0),this.l=e,0);r<this.fieldsArray.length;++r)this.i[r].resolve();var n={};for(r=0;r<this.oneofsArray.length;++r)n[this.a[r].resolve().name]={get:p.oneOfGetter(this.a[r].oneof),set:p.oneOfSetter(this.a[r].oneof)};r&&Object.defineProperties(e.prototype,n)}}}),b.generateConstructor=function(e){for(var t,r=p.codegen(["p"],e.name),n=0;n<e.fieldsArray.length;++n)(t=e.i[n]).map?r("this%s={}",p.safeProp(t.name)):t.repeated&&r("this%s=[]",p.safeProp(t.name));return r("if(p)for(var ks=Object.keys(p),i=0;i<ks.length;++i)if(p[ks[i]]!=null)")("this[ks[i]]=p[ks[i]]")},b.fromJSON=function(e,t){for(var r=new b(e,t.options),u=(r.extensions=t.extensions,r.reserved=t.reserved,Object.keys(t.fields)),l=0;l<u.length;++l)r.add((void 0!==t.fields[u[l]].keyType?s:a).fromJSON(u[l],t.fields[u[l]]));if(t.oneofs)for(u=Object.keys(t.oneofs),l=0;l<u.length;++l)r.add(o.fromJSON(u[l],t.oneofs[u[l]]));if(t.nested)for(u=Object.keys(t.nested),l=0;l<u.length;++l){var d=t.nested[u[l]];r.add((d.id!==g?a:d.fields!==g?b:d.values!==g?i:d.methods!==g?c:n).fromJSON(u[l],d))}return t.extensions&&t.extensions.length&&(r.extensions=t.extensions),t.reserved&&t.reserved.length&&(r.reserved=t.reserved),t.group&&(r.group=!0),t.comment&&(r.comment=t.comment),r},b.prototype.toJSON=function(e){var t=n.prototype.toJSON.call(this,e),r=!!e&&!!e.keepComments;return p.toObject(["options",t&&t.options||g,"oneofs",n.arrayToJSON(this.oneofsArray,e),"fields",n.arrayToJSON(this.fieldsArray.filter(function(e){return!e.declaringField}),e)||{},"extensions",this.extensions&&this.extensions.length?this.extensions:g,"reserved",this.reserved&&this.reserved.length?this.reserved:g,"group",this.group||g,"nested",t&&t.nested||g,"comment",r?this.comment:g])},b.prototype.resolveAll=function(){for(var e=this.fieldsArray,t=0;t<e.length;)e[t++].resolve();var r=this.oneofsArray;for(t=0;t<r.length;)r[t++].resolve();return n.prototype.resolveAll.call(this)},b.prototype.get=function(e){return this.fields[e]||this.oneofs&&this.oneofs[e]||this.nested&&this.nested[e]||null},b.prototype.add=function(e){if(this.get(e.name))throw Error("duplicate name '"+e.name+"' in "+this);if(e instanceof a&&e.extend===g){if((this.c||this.fieldsById)[e.id])throw Error("duplicate id "+e.id+" in "+this);if(this.isReservedId(e.id))throw Error("id "+e.id+" is reserved in "+this);if(this.isReservedName(e.name))throw Error("name '"+e.name+"' is reserved in "+this);return e.parent&&e.parent.remove(e),(this.fields[e.name]=e).message=this,e.onAdd(this),S(this)}return e instanceof o?(this.oneofs||(this.oneofs={}),(this.oneofs[e.name]=e).onAdd(this),S(this)):n.prototype.add.call(this,e)},b.prototype.remove=function(e){if(e instanceof a&&e.extend===g){if(this.fields&&this.fields[e.name]===e)return delete this.fields[e.name],e.parent=null,e.onRemove(this),S(this);throw Error(e+" is not a member of "+this)}if(e instanceof o){if(this.oneofs&&this.oneofs[e.name]===e)return delete this.oneofs[e.name],e.parent=null,e.onRemove(this),S(this);throw Error(e+" is not a member of "+this)}return n.prototype.remove.call(this,e)},b.prototype.isReservedId=function(e){return n.isReservedId(this.reserved,e)},b.prototype.isReservedName=function(e){return n.isReservedName(this.reserved,e)},b.prototype.create=function(e){return new this.ctor(e)},b.prototype.setup=function(){for(var e=this.fullName,t=[],r=0;r<this.fieldsArray.length;++r)t.push(this.i[r].resolve().resolvedType);var n;return this.encode=f(this)({Writer:d,types:t,util:p}),this.decode=h(this)({Reader:l,types:t,util:p}),this.verify=m(this)({types:t,util:p}),this.fromObject=v.fromObject(this)({types:t,util:p}),this.toObject=v.toObject(this)({types:t,util:p}),(e=y[e])&&((n=Object.create(this)).fromObject=this.fromObject,this.fromObject=e.fromObject.bind(n),n.toObject=this.toObject,this.toObject=e.toObject.bind(n)),this},b.prototype.encode=function(e,t){return this.setup().encode(e,t)},b.prototype.encodeDelimited=function(e,t){return this.encode(e,t&&t.len?t.fork():t).ldelim()},b.prototype.decode=function(e,t){return this.setup().decode(e,t)},b.prototype.decodeDelimited=function(e){return e instanceof l||(e=l.create(e)),this.decode(e,e.uint32())},b.prototype.verify=function(e){return this.setup().verify(e)},b.prototype.fromObject=function(e){return this.setup().fromObject(e)},b.prototype.toObject=function(e,t){return this.setup().toObject(e,t)},b.d=function(e){return function(t){p.decorateType(t,e)}}},{11:11,12:12,13:13,14:14,15:15,18:18,19:19,21:21,23:23,24:24,30:30,33:33,36:36,37:37,38:38}],32:[function(e,t,r){e=e(33);var n=["double","float","int32","uint32","sint32","fixed32","sfixed32","int64","uint64","sint64","fixed64","sfixed64","bool","string","bytes"];function i(e,t){var r=0,i={};for(t|=0;r<e.length;)i[n[r+t]]=e[r++];return i}r.basic=i([1,5,0,0,0,5,5,0,0,0,1,1,0,2,2]),r.defaults=i([0,0,0,0,0,0,0,0,0,0,0,0,!1,"",e.emptyArray,null]),r.long=i([0,0,0,1,1],7),r.mapKey=i([0,0,0,5,5,0,0,0,1,1,0,2],2),r.packed=i([1,5,0,0,0,5,5,0,0,0,1,1,0])},{33:33}],33:[function(e,t,r){var n,i,o=t.exports=e(35),a=e(27),s=(o.codegen=e(3),o.fetch=e(5),o.path=e(8),o.fs=o.inquire("fs"),o.toArray=function(e){if(e){for(var t=Object.keys(e),r=Array(t.length),n=0;n<t.length;)r[n]=e[t[n++]];return r}return[]},o.toObject=function(e){for(var t={},r=0;r<e.length;){var n=e[r++],i=e[r++];i!==g&&(t[n]=i)}return t},/\\/g),c=/"/g,u=(o.isReserved=function(e){return/^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(e)},o.safeProp=function(e){return!/^[$\w_]+$/.test(e)||o.isReserved(e)?'["'+e.replace(s,"\\\\").replace(c,'\\"')+'"]':"."+e},o.ucFirst=function(e){return(e[0]||"").toUpperCase()+e.substring(1)},/_([a-z])/g),l=(o.camelCase=function(e){return e.substring(0,1)+e.substring(1).replace(u,function(e,t){return t.toUpperCase()})},o.compareFieldsById=function(e,t){return e.id-t.id},o.decorateType=function(t,r){return t.$type?(r&&t.$type.name!==r&&(o.decorateRoot.remove(t.$type),t.$type.name=r,o.decorateRoot.add(t.$type)),t.$type):(r=new(n=n||e(31))(r||t.name),o.decorateRoot.add(r),r.ctor=t,Object.defineProperty(t,"$type",{value:r,enumerable:!1}),Object.defineProperty(t.prototype,"$type",{value:r,enumerable:!1}),r)},0);o.decorateEnum=function(t){var r;return t.$type||(r=new(i=i||e(14))("Enum"+l++,t),o.decorateRoot.add(r),Object.defineProperty(t,"$type",{value:r,enumerable:!1}),r)},o.setProperty=function(e,t,r){if("object"!=typeof e)throw TypeError("dst must be an object");if(t)return function e(t,r,n){var i=r.shift();return"__proto__"!==i&&"prototype"!==i&&(0<r.length?t[i]=e(t[i]||{},r,n):((r=t[i])&&(n=[].concat(r).concat(n)),t[i]=n)),t}(e,t=t.split("."),r);throw TypeError("path must be specified")},Object.defineProperty(o,"decorateRoot",{get:function(){return a.decorated||(a.decorated=new(e(26)))}})},{14:14,26:26,27:27,3:3,31:31,35:35,5:5,8:8}],34:[function(e,t,r){t.exports=i;var n=e(35);function i(e,t){this.lo=e>>>0,this.hi=t>>>0}var o=i.zero=new i(0,0),a=(o.toNumber=function(){return 0},o.zzEncode=o.zzDecode=function(){return this},o.length=function(){return 1},i.zeroHash="\0\0\0\0\0\0\0\0",i.fromNumber=function(e){var t,r;return 0===e?o:(r=(e=(t=e<0)?-e:e)>>>0,e=(e-r)/4294967296>>>0,t&&(e=~e>>>0,r=~r>>>0,4294967295<++r&&(r=0,4294967295<++e&&(e=0))),new i(r,e))},i.from=function(e){if("number"==typeof e)return i.fromNumber(e);if(n.isString(e)){if(!n.Long)return i.fromNumber(parseInt(e,10));e=n.Long.fromString(e)}return e.low||e.high?new i(e.low>>>0,e.high>>>0):o},i.prototype.toNumber=function(e){var t;return!e&&this.hi>>>31?(e=1+~this.lo>>>0,t=~this.hi>>>0,-(e+4294967296*(t=e?t:t+1>>>0))):this.lo+4294967296*this.hi},i.prototype.toLong=function(e){return n.Long?new n.Long(0|this.lo,0|this.hi,!!e):{low:0|this.lo,high:0|this.hi,unsigned:!!e}},String.prototype.charCodeAt);i.fromHash=function(e){return"\0\0\0\0\0\0\0\0"===e?o:new i((a.call(e,0)|a.call(e,1)<<8|a.call(e,2)<<16|a.call(e,3)<<24)>>>0,(a.call(e,4)|a.call(e,5)<<8|a.call(e,6)<<16|a.call(e,7)<<24)>>>0)},i.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},i.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this},i.prototype.zzDecode=function(){var e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this},i.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return 0==r?0==t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:r<128?9:10}},{35:35}],35:[function(e,t,r){var n=r;function i(e,t,r){for(var n=Object.keys(t),i=0;i<n.length;++i)e[n[i]]!==g&&r||(e[n[i]]=t[n[i]]);return e}function o(e){function t(e,r){if(!(this instanceof t))return new t(e,r);Object.defineProperty(this,"message",{get:function(){return e}}),Error.captureStackTrace?Error.captureStackTrace(this,t):Object.defineProperty(this,"stack",{value:Error().stack||""}),r&&i(this,r)}return t.prototype=Object.create(Error.prototype,{constructor:{value:t,writable:!0,enumerable:!1,configurable:!0},name:{get:function(){return e},set:g,enumerable:!1,configurable:!0},toString:{value:function(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),t}n.asPromise=e(1),n.base64=e(2),n.EventEmitter=e(4),n.float=e(6),n.inquire=e(7),n.utf8=e(10),n.pool=e(9),n.LongBits=e(34),n.isNode=!!(void 0!==commonjsGlobal&&commonjsGlobal&&commonjsGlobal.process&&commonjsGlobal.process.versions&&commonjsGlobal.process.versions.node),n.global=n.isNode&&commonjsGlobal||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||this,n.emptyArray=Object.freeze?Object.freeze([]):[],n.emptyObject=Object.freeze?Object.freeze({}):{},n.isInteger=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e},n.isString=function(e){return"string"==typeof e||e instanceof String},n.isObject=function(e){return e&&"object"==typeof e},n.isset=n.isSet=function(e,t){var r=e[t];return null!=r&&e.hasOwnProperty(t)&&("object"!=typeof r||0<(Array.isArray(r)?r:Object.keys(r)).length)},n.Buffer=function(){try{var e=n.inquire("buffer").Buffer;return e.prototype.utf8Write?e:null}catch(e){return null}}(),n.v=null,n.b=null,n.newBuffer=function(e){return"number"==typeof e?n.Buffer?n.b(e):new n.Array(e):n.Buffer?n.v(e):"undefined"==typeof Uint8Array?e:new Uint8Array(e)},n.Array="undefined"!=typeof Uint8Array?Uint8Array:Array,n.Long=n.global.dcodeIO&&n.global.dcodeIO.Long||n.global.Long||n.inquire("long"),n.key2Re=/^true|false|0|1$/,n.key32Re=/^-?(?:0|[1-9][0-9]*)$/,n.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,n.longToHash=function(e){return e?n.LongBits.from(e).toHash():n.LongBits.zeroHash},n.longFromHash=function(e,t){return e=n.LongBits.fromHash(e),n.Long?n.Long.fromBits(e.lo,e.hi,t):e.toNumber(!!t)},n.merge=i,n.lcFirst=function(e){return(e[0]||"").toLowerCase()+e.substring(1)},n.newError=o,n.ProtocolError=o("ProtocolError"),n.oneOfGetter=function(e){for(var t={},r=0;r<e.length;++r)t[e[r]]=1;return function(){for(var e=Object.keys(this),r=e.length-1;-1<r;--r)if(1===t[e[r]]&&this[e[r]]!==g&&null!==this[e[r]])return e[r]}},n.oneOfSetter=function(e){return function(t){for(var r=0;r<e.length;++r)e[r]!==t&&delete this[e[r]]}},n.toJSONOptions={longs:String,enums:String,bytes:String,json:!0},n.r=function(){var e=n.Buffer;e?(n.v=e.from!==Uint8Array.from&&e.from||function(t,r){return new e(t,r)},n.b=e.allocUnsafe||function(t){return new e(t)}):n.v=n.b=null}},{1:1,10:10,2:2,34:34,4:4,6:6,7:7,9:9}],36:[function(e,t,r){t.exports=function(e){var t=i.codegen(["m"],e.name+"$verify")('if(typeof m!=="object"||m===null)')("return%j","object expected"),r={};e.oneofsArray.length&&t("var p={}");for(var n=0;n<e.fieldsArray.length;++n){var s,c=e.i[n].resolve(),u="m"+i.safeProp(c.name);c.optional&&t("if(%s!=null&&m.hasOwnProperty(%j)){",u,c.name),c.map?(t("if(!util.isObject(%s))",u)("return%j",o(c,"object"))("var k=Object.keys(%s)",u)("for(var i=0;i<k.length;++i){"),function(e,t,r){switch(t.keyType){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":e("if(!util.key32Re.test(%s))",r)("return%j",o(t,"integer key"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":e("if(!util.key64Re.test(%s))",r)("return%j",o(t,"integer|Long key"));break;case"bool":e("if(!util.key2Re.test(%s))",r)("return%j",o(t,"boolean key"))}}(t,c,"k[i]"),a(t,c,n,u+"[k[i]]")("}")):c.repeated?(t("if(!Array.isArray(%s))",u)("return%j",o(c,"array"))("for(var i=0;i<%s.length;++i){",u),a(t,c,n,u+"[i]")("}")):(c.partOf&&(s=i.safeProp(c.partOf.name),1===r[c.partOf.name]&&t("if(p%s===1)",s)("return%j",c.partOf.name+": multiple values"),r[c.partOf.name]=1,t("p%s=1",s)),a(t,c,n,u)),c.optional&&t("}")}return t("return null")};var n=e(14),i=e(33);function o(e,t){return e.name+": "+t+(e.repeated&&"array"!==t?"[]":e.map&&"object"!==t?"{k:"+e.keyType+"}":"")+" expected"}function a(e,t,r,i){if(t.resolvedType)if(t.resolvedType instanceof n){e("switch(%s){",i)("default:")("return%j",o(t,"enum value"));for(var a=Object.keys(t.resolvedType.values),s=0;s<a.length;++s)e("case %i:",t.resolvedType.values[a[s]]);e("break")("}")}else e("{")("var e=types[%i].verify(%s);",r,i)("if(e)")("return%j+e",t.name+".")("}");else switch(t.type){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":e("if(!util.isInteger(%s))",i)("return%j",o(t,"integer"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":e("if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))",i,i,i,i)("return%j",o(t,"integer|Long"));break;case"float":case"double":e('if(typeof %s!=="number")',i)("return%j",o(t,"number"));break;case"bool":e('if(typeof %s!=="boolean")',i)("return%j",o(t,"boolean"));break;case"string":e("if(!util.isString(%s))",i)("return%j",o(t,"string"));break;case"bytes":e('if(!(%s&&typeof %s.length==="number"||util.isString(%s)))',i,i,i)("return%j",o(t,"buffer"))}return e}},{14:14,33:33}],37:[function(e,t,r){var n=e(19);r[".google.protobuf.Any"]={fromObject:function(e){if(e&&e["@type"]){var t,r=e["@type"].substring(1+e["@type"].lastIndexOf("/"));if(r=this.lookup(r))return~(t="."==(e["@type"][0]||"")?e["@type"].slice(1):e["@type"]).indexOf("/")||(t="/"+t),this.create({type_url:t,value:r.encode(r.fromObject(e)).finish()})}return this.fromObject(e)},toObject:function(e,t){var r,i,o="",a="";return t&&t.json&&e.type_url&&e.value&&(a=e.type_url.substring(1+e.type_url.lastIndexOf("/")),o=e.type_url.substring(0,1+e.type_url.lastIndexOf("/")),(r=this.lookup(a))&&(e=r.decode(e.value))),!(e instanceof this.ctor)&&e instanceof n?(r=e.$type.toObject(e,t),i="."===e.$type.fullName[0]?e.$type.fullName.slice(1):e.$type.fullName,r["@type"]=a=(o=""===o?"type.googleapis.com/":o)+i,r):this.toObject(e,t)}}},{19:19}],38:[function(e,t,r){t.exports=d;var n,i=e(35),o=i.LongBits,a=i.base64,s=i.utf8;function c(e,t,r){this.fn=e,this.len=t,this.next=g,this.val=r}function u(){}function l(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}function d(){this.len=0,this.head=new c(u,0,0),this.tail=this.head,this.states=null}function p(){return i.Buffer?function(){return(d.create=function(){return new n})()}:function(){return new d}}function f(e,t,r){t[r]=255&e}function h(e,t){this.len=e,this.next=g,this.val=t}function m(e,t,r){for(;e.hi;)t[r++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;127<e.lo;)t[r++]=127&e.lo|128,e.lo=e.lo>>>7;t[r++]=e.lo}function v(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}d.create=p(),d.alloc=function(e){return new i.Array(e)},i.Array!==Array&&(d.alloc=i.pool(d.alloc,i.Array.prototype.subarray)),d.prototype.p=function(e,t,r){return this.tail=this.tail.next=new c(e,t,r),this.len+=t,this},(h.prototype=Object.create(c.prototype)).fn=function(e,t,r){for(;127<e;)t[r++]=127&e|128,e>>>=7;t[r]=e},d.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new h((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this},d.prototype.int32=function(e){return e<0?this.p(m,10,o.fromNumber(e)):this.uint32(e)},d.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)},d.prototype.int64=d.prototype.uint64=function(e){return e=o.from(e),this.p(m,e.length(),e)},d.prototype.sint64=function(e){return e=o.from(e).zzEncode(),this.p(m,e.length(),e)},d.prototype.bool=function(e){return this.p(f,1,e?1:0)},d.prototype.sfixed32=d.prototype.fixed32=function(e){return this.p(v,4,e>>>0)},d.prototype.sfixed64=d.prototype.fixed64=function(e){return e=o.from(e),this.p(v,4,e.lo).p(v,4,e.hi)},d.prototype.float=function(e){return this.p(i.float.writeFloatLE,4,e)},d.prototype.double=function(e){return this.p(i.float.writeDoubleLE,8,e)};var y=i.Array.prototype.set?function(e,t,r){t.set(e,r)}:function(e,t,r){for(var n=0;n<e.length;++n)t[r+n]=e[n]};d.prototype.bytes=function(e){var t,r=e.length>>>0;return r?(i.isString(e)&&(t=d.alloc(r=a.length(e)),a.decode(e,t,0),e=t),this.uint32(r).p(y,r,e)):this.p(f,1,0)},d.prototype.string=function(e){var t=s.length(e);return t?this.uint32(t).p(s.write,t,e):this.p(f,1,0)},d.prototype.fork=function(){return this.states=new l(this),this.head=this.tail=new c(u,0,0),this.len=0,this},d.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new c(u,0,0),this.len=0),this},d.prototype.ldelim=function(){var e=this.head,t=this.tail,r=this.len;return this.reset().uint32(r),r&&(this.tail.next=e.next,this.tail=t,this.len+=r),this},d.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),r=0;e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t},d.r=function(e){n=e,d.create=p(),n.r()}},{35:35}],39:[function(e,t,r){t.exports=o;var n=e(38),i=((o.prototype=Object.create(n.prototype)).constructor=o,e(35));function o(){n.call(this)}function a(e,t,r){e.length<40?i.utf8.write(e,t,r):t.utf8Write?t.utf8Write(e,r):t.write(e,r)}o.r=function(){o.alloc=i.b,o.writeBytesBuffer=i.Buffer&&i.Buffer.prototype instanceof Uint8Array&&"set"===i.Buffer.prototype.set.name?function(e,t,r){t.set(e,r)}:function(e,t,r){if(e.copy)e.copy(t,r,0,e.length);else for(var n=0;n<e.length;)t[r++]=e[n++]}},o.prototype.bytes=function(e){var t=(e=i.isString(e)?i.v(e,"base64"):e).length>>>0;return this.uint32(t),t&&this.p(o.writeBytesBuffer,t,e),this},o.prototype.string=function(e){var t=i.Buffer.byteLength(e);return this.uint32(t),t&&this.p(a,t,e),this},o.r()},{35:35,38:38}]},e={},i=function t(n){var i=e[n];return i||r[n][0].call(i=e[n]={exports:{}},t,i,i.exports),i.exports}(16),i.util.global.protobuf=i,module&&module.exports&&(module.exports=i)}()})(protobuf);var protobufExports=protobuf.exports,fakeIdToCallback={},lastFakeId=0,addTimer=function(e,t){return"interval"===(arguments.length>2&&void 0!==arguments[2]?arguments[2]:"timeout")?window.setInterval(e,t):window.setTimeout(e,t)},removeTimer=function(e){return"interval"===(arguments.length>1&&void 0!==arguments[1]?arguments[1]:"timeout")?window.clearInterval(e):window.clearTimeout(e)};function commonjsRequire(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}!function(e){var t,r;if(!/MSIE 10/i.test(navigator.userAgent))try{t=new Blob(["\nconst fakeIdToId = {};\nonmessage = (event) => {\n const { fakeId, name, time } = event.data;\n switch (name) {\n case 'setInterval':\n fakeIdToId[fakeId] = setInterval(() => {\n postMessage({ fakeId });\n }, time);\n break;\n case 'clearInterval':\n if (fakeIdToId[fakeId] !== undefined) {\n clearInterval(fakeIdToId[fakeId]);\n delete fakeIdToId[fakeId];\n }\n break;\n case 'setTimeout':\n fakeIdToId[fakeId] = setTimeout(() => {\n postMessage({ fakeId });\n if (fakeIdToId[fakeId] !== undefined) {\n delete fakeIdToId[fakeId];\n }\n }, time);\n break;\n case 'clearTimeout':\n if (fakeIdToId[fakeId] !== undefined) {\n clearTimeout(fakeIdToId[fakeId]);\n delete fakeIdToId[fakeId];\n }\n break;\n }\n}\n"]),e=window.URL.createObjectURL(t)}catch(e){}if("undefined"!=typeof Worker)try{r=new Worker(e),addTimer=function(e,t,n){var i=lastFakeId++;return fakeIdToCallback[i]={callback:e,time:t,isTimeout:"timeout"===n},r.postMessage({name:"interval"===n?"setInterval":"setTimeout",fakeId:i,time:t}),i},removeTimer=function(e,t){fakeIdToCallback[e]&&(delete fakeIdToCallback[e],r.postMessage({name:"timeout"===t?"clearInterval":"clearTimeout",fakeId:e}))},r.onmessage=function(e){var t,r,n=e.data.fakeId;fakeIdToCallback[n]&&(r=(t=fakeIdToCallback[n]).callback,t.isTimeout&&t.isTimeout&&delete fakeIdToCallback[n]),r&&r()},r.onerror=function(e){console.error(e)}}catch(e){console.error("Initialisation failed")}}("timerWorker.js");var base64={exports:{}};base64.exports=function e(t,r,n){function i(a,s){if(!r[a]){if(!t[a]){var c="function"==typeof commonjsRequire&&commonjsRequire;if(!s&&c)return c(a,!0);if(o)return o(a,!0);var u=new Error("Cannot find module '"+a+"'");throw u.code="MODULE_NOT_FOUND",u}var l=r[a]={exports:{}};t[a][0].call(l.exports,function(e){return i(t[a][1][e]||e)},l,l.exports,e,t,r,n)}return r[a].exports}for(var o="function"==typeof commonjsRequire&&commonjsRequire,a=0;a<n.length;a++)i(n[a]);return i}({"/":[function(e,t,r){function n(e){var t=e.length;if(0<t%4)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function i(e){return a[63&e>>18]+a[63&e>>12]+a[63&e>>6]+a[63&e]}function o(e,t,r){for(var n,o=[],a=t;a<r;a+=3)n=(16711680&e[a]<<16)+(65280&e[a+1]<<8)+(255&e[a+2]),o.push(i(n));return o.join("")}r.byteLength=function(e){var t=n(e),r=t[0],i=t[1];return 3*(r+i)/4-i},r.toByteArray=function(e){var t,r,i=n(e),o=i[0],a=i[1],u=new c(function(e,t,r){return 3*(t+r)/4-r}(0,o,a)),l=0,d=0<a?o-4:o;for(r=0;r<d;r+=4)t=s[e.charCodeAt(r)]<<18|s[e.charCodeAt(r+1)]<<12|s[e.charCodeAt(r+2)]<<6|s[e.charCodeAt(r+3)],u[l++]=255&t>>16,u[l++]=255&t>>8,u[l++]=255&t;return 2===a&&(t=s[e.charCodeAt(r)]<<2|s[e.charCodeAt(r+1)]>>4,u[l++]=255&t),1===a&&(t=s[e.charCodeAt(r)]<<10|s[e.charCodeAt(r+1)]<<4|s[e.charCodeAt(r+2)]>>2,u[l++]=255&t>>8,u[l++]=255&t),u},r.fromByteArray=function(e){for(var t,r=e.length,n=r%3,i=[],s=16383,c=0,u=r-n;c<u;c+=s)i.push(o(e,c,c+s>u?u:c+s));return 1===n?(t=e[r-1],i.push(a[t>>2]+a[63&t<<4]+"==")):2===n&&(t=(e[r-2]<<8)+e[r-1],i.push(a[t>>10]+a[63&t>>4]+a[63&t<<2]+"=")),i.join("")};for(var a=[],s=[],c="undefined"==typeof Uint8Array?Array:Uint8Array,u="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",l=0;l<64;++l)a[l]=u[l],s[u.charCodeAt(l)]=l;s[45]=62,s[95]=63},{}]},{},[])("/");var base64Exports=base64.exports;function _createForOfIteratorHelper$d(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$1$1(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$1$1(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$1$1(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_arrayLikeToArray$1$1(e,t):void 0}}function _arrayLikeToArray$1$1(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}var updateProtobuf=function(e){protobufExports.util.Long=e,protobufExports.util.LongBits.prototype.toLong=function(t){return 0===this.hi?this.lo:new e(this.lo,this.hi,t)},protobufExports.configure()},encoder$1=new TextEncoder,decoder=new TextDecoder,toBase64=function(e){return base64Exports.fromByteArray(encoder$1.encode(e))},fromBase64=function(e){return decoder.decode(base64Exports.toByteArray(e))},type=function(e){return Object.prototype.toString.call(e).match(/\[object (.*?)\]/)[1].toLowerCase()},isNumber=function(e){return"number"===type(e)},isString=function(e){return"string"===type(e)},isObject=function(e){return"object"===type(e)},uniqBy=function(){var e,t=arguments.length>1?arguments[1]:void 0,r=[],n={},i=_createForOfIteratorHelper$d(arguments.length>0&&void 0!==arguments[0]?arguments[0]:[]);try{for(i.s();!(e=i.n()).done;){var o=e.value;n[o[t]]||(r.push(o),n[o[t]]=1)}}catch(e){i.e(e)}finally{i.f()}return r},createUuid=function(e){var t="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)});return t.substring(0,e||t.length)},ensureDigits=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:2;if(2===t)return e<10?"0".concat(e):"".concat(e);if(3===t){if(e<10)return"00".concat(e);if(e<100)return"0".concat(e)}return"".concat(e)},formatToBeijingTime=function(e){if(!(e instanceof Date))return"[not a Date]";var t=e.getTime()+288e5,r=new Date(t),n="";try{n="".concat(r.getUTCFullYear(),"-").concat(ensureDigits(r.getUTCMonth()+1),"-").concat(ensureDigits(r.getUTCDate())," ").concat(ensureDigits(r.getUTCHours()),":").concat(ensureDigits(r.getUTCMinutes()),":").concat(ensureDigits(r.getUTCSeconds()),".").concat(ensureDigits(r.getUTCMilliseconds(),3))}catch(e){}return n},tryJsonStringify=function(e){if(void 0===e)return"[undefined]";try{if(e instanceof Set||e instanceof Map)return JSON.stringify(Array.from(e));if(e instanceof Error){var t={name:e.name,message:e.message,stack:e.stack};return e.log&&(t.log=e.log),e.code&&(t.code=e.code),JSON.stringify(t)}return JSON.stringify(e)}catch(e){return"[tryJsonStringify failed]"}},Debouncer=_createClass(function e(){_classCallCheck(this,e),Object.defineProperty(this,"timer",{enumerable:!0,configurable:!0,writable:!0,value:void 0})},[{key:"debounce",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:500;clearTimeout(this.timer),this.timer=setTimeout(function(){e&&e(),t.timer=null},r)}}]),getPlainMediaTrackInfo=function(e){var t={};return e?(t.kind=e.kind,t.label=e.label,t.id=e.id,t.contentHint=e.contentHint,t.enabled=e.enabled,t.muted=e.muted,t.readyState=e.readyState,t.settings=e.getSettings(),t.constraints=e.getConstraints(),t):t},getPlainMediaStreamInfo=function(e){if(!e)return{};var t={id:e.id,active:e.active},r=e.getTracks().map(function(e){return getPlainMediaTrackInfo(e)});return t.trackInfos=r,t},isPrivateIP=function(e){var t=e.split(".").reduce(function(e,t,r){return e+Number(t)*Math.pow(256,3-r)},0);return t>=167772160&&t<=184549375||t>=2886729728&&t<=2887778303||t>=3232235520&&t<=3232301055},getProtobufRoot=function(e){return protobufExports.Root.fromJSON(e)},diffTime=0,setDiffTime=function(e){diffTime=e},getTime=function(){return Date.now()+diffTime},taskQueue$1=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1,t=[],r=0,n=!1,i=function(){var n=_asyncToGenerator(_regeneratorRuntime.mark(function n(){var o,a;return _regeneratorRuntime.wrap(function(n){for(;;)switch(n.prev=n.next){case 0:if(!(r<e&&t.length)){n.next=6;break}if(r++,!(o=t.shift())){n.next=5;break}return n.prev=1,n.next=2,o();case 2:n.next=4;break;case 3:n.prev=3,a=n.catch(1),console.log(a);case 4:r--,i();case 5:n.next=0;break;case 6:case"end":return n.stop()}},n,null,[[1,3]])}));return function(){return n.apply(this,arguments)}}();return{add:function(e){t.push(e),n&&i()},start:function(){n=!0,i()}}},awaitTime$1=function(e){return new Promise(function(t){addTimer(t,1e3*e)})},uaParser={exports:{}};!function(e,t){!function(r,n){var i="function",o="undefined",a="object",s="string",c="major",u="model",l="name",d="type",p="vendor",f="version",h="architecture",g="console",m="mobile",v="tablet",y="smarttv",b="wearable",S="embedded",_="Amazon",E="Apple",T="ASUS",R="BlackBerry",C="Browser",k="Chrome",P="Firefox",w="Google",O="Huawei",I="LG",A="Microsoft",M="Motorola",N="Opera",D="Samsung",x="Sharp",L="Sony",j="Xiaomi",$="Zebra",U="Facebook",F="Chromium OS",V="macOS",G=" Browser",B=function(e){for(var t={},r=0;r<e.length;r++)t[e[r].toUpperCase()]=e[r];return t},H=function(e,t){return typeof e===s&&-1!==q(t).indexOf(q(e))},q=function(e){return e.toLowerCase()},K=function(e,t){if(typeof e===s)return e=e.replace(/^\s\s*/,""),typeof t===o?e:e.substring(0,500)},W=function(e,t){for(var r,o,s,c,u,l,d=0;d<t.length&&!u;){var p=t[d],f=t[d+1];for(r=o=0;r<p.length&&!u&&p[r];)if(u=p[r++].exec(e))for(s=0;s<f.length;s++)l=u[++o],typeof(c=f[s])===a&&c.length>0?2===c.length?typeof c[1]==i?this[c[0]]=c[1].call(this,l):this[c[0]]=c[1]:3===c.length?typeof c[1]!==i||c[1].exec&&c[1].test?this[c[0]]=l?l.replace(c[1],c[2]):n:this[c[0]]=l?c[1].call(this,l,c[2]):n:4===c.length&&(this[c[0]]=l?c[3].call(this,l.replace(c[1],c[2])):n):this[c]=l||n;d+=2}},Y=function(e,t){for(var r in t)if(typeof t[r]===a&&t[r].length>0){for(var i=0;i<t[r].length;i++)if(H(t[r][i],e))return"?"===r?n:r}else if(H(t[r],e))return"?"===r?n:r;return t.hasOwnProperty("*")?t["*"]:e},J={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"},z={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[f,[l,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[f,[l,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[l,f],[/opios[\/ ]+([\w\.]+)/i],[f,[l,N+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[f,[l,N+" GX"]],[/\bopr\/([\w\.]+)/i],[f,[l,N]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[f,[l,"Baidu"]],[/\b(?:mxbrowser|mxios|myie2)\/?([-\w\.]*)\b/i],[f,[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,f],[/quark(?:pc)?\/([-\w\.]+)/i],[f,[l,"Quark"]],[/\bddg\/([\w\.]+)/i],[f,[l,"DuckDuckGo"]],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[f,[l,"UC"+C]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[f,[l,"WeChat"]],[/konqueror\/([\w\.]+)/i],[f,[l,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[f,[l,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[f,[l,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[f,[l,"Smart Lenovo "+C]],[/(avast|avg)\/([\w\.]+)/i],[[l,/(.+)/,"$1 Secure "+C],f],[/\bfocus\/([\w\.]+)/i],[f,[l,P+" Focus"]],[/\bopt\/([\w\.]+)/i],[f,[l,N+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[f,[l,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[f,[l,"Dolphin"]],[/coast\/([\w\.]+)/i],[f,[l,N+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[f,[l,"MIUI"+G]],[/fxios\/([\w\.-]+)/i],[f,[l,P]],[/\bqihoobrowser\/?([\w\.]*)/i],[f,[l,"360"]],[/\b(qq)\/([\w\.]+)/i],[[l,/(.+)/,"$1Browser"],f],[/(oculus|sailfish|huawei|vivo|pico)browser\/([\w\.]+)/i],[[l,/(.+)/,"$1"+G],f],[/samsungbrowser\/([\w\.]+)/i],[f,[l,D+" Internet"]],[/metasr[\/ ]?([\d\.]+)/i],[f,[l,"Sogou Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[l,"Sogou Mobile"],f],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345(?=browser|chrome|explorer))\w*[\/ ]?v?([\w\.]+)/i],[l,f],[/(lbbrowser|rekonq)/i,/\[(linkedin)app\]/i],[l],[/ome\/([\w\.]+) \w* ?(iron) saf/i,/ome\/([\w\.]+).+qihu (360)[es]e/i],[f,l],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[l,U],f],[/(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,f],[/\bgsa\/([\w\.]+) .*safari\//i],[f,[l,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[f,[l,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[f,[l,k+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[l,k+" WebView"],f],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[f,[l,"Android "+C]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[l,f],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[f,[l,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[f,l],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[l,[f,Y,{"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,f],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[l,"Netscape"],f],[/(wolvic|librewolf)\/([\w\.]+)/i],[l,f],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[f,[l,P+" 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,[f,/_/g,"."]],[/(cobalt)\/([\w\.]+)/i],[l,[f,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[h,"amd64"]],[/(ia32(?=;))/i],[[h,q]],[/((?:i[346]|x)86)[;\)]/i],[[h,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[h,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[h,"armhf"]],[/windows (ce|mobile); ppc;/i],[[h,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[h,/ower/,"",q]],[/(sun4\w)[;\)]/i],[[h,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[h,q]]],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],[u,[p,D],[d,v]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]((?!sm-[lr])[-\w]+)/i,/sec-(sgh\w+)/i],[u,[p,D],[d,m]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[u,[p,E],[d,m]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[u,[p,E],[d,v]],[/(macintosh);/i],[u,[p,E]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[u,[p,x],[d,m]],[/(?:honor)([-\w ]+)[;\)]/i],[u,[p,"Honor"],[d,m]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[u,[p,O],[d,v]],[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[u,[p,O],[d,m]],[/\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],[[u,/_/g," "],[p,j],[d,m]],[/oid[^\)]+; (2\d{4}(283|rpbf)[cgl])( bui|\))/i,/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[u,/_/g," "],[p,j],[d,v]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[u,[p,"OPPO"],[d,m]],[/\b(opd2\d{3}a?) bui/i],[u,[p,"OPPO"],[d,v]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[u,[p,"Vivo"],[d,m]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[u,[p,"Realme"],[d,m]],[/\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],[u,[p,M],[d,m]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[u,[p,M],[d,v]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[u,[p,I],[d,v]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[u,[p,I],[d,m]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[u,[p,"Lenovo"],[d,v]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[u,/_/g," "],[p,"Nokia"],[d,m]],[/(pixel c)\b/i],[u,[p,w],[d,v]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[u,[p,w],[d,m]],[/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],[u,[p,L],[d,m]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[u,"Xperia Tablet"],[p,L],[d,v]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[u,[p,"OnePlus"],[d,m]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[u,[p,_],[d,v]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[u,/(.+)/g,"Fire Phone $1"],[p,_],[d,m]],[/(playbook);[-\w\),; ]+(rim)/i],[u,p,[d,v]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[u,[p,R],[d,m]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[u,[p,T],[d,v]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[u,[p,T],[d,m]],[/(nexus 9)/i],[u,[p,"HTC"],[d,v]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[p,[u,/_/g," "],[d,m]],[/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],[u,[p,"TCL"],[d,v]],[/(itel) ((\w+))/i],[[p,q],u,[d,Y,{tablet:["p10001l","w7001"],"*":"mobile"}]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[u,[p,"Acer"],[d,v]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[u,[p,"Meizu"],[d,m]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[u,[p,"Ulefone"],[d,m]],[/; (energy ?\w+)(?: bui|\))/i,/; energizer ([\w ]+)(?: bui|\))/i],[u,[p,"Energizer"],[d,m]],[/; cat (b35);/i,/; (b15q?|s22 flip|s48c|s62 pro)(?: bui|\))/i],[u,[p,"Cat"],[d,m]],[/((?:new )?andromax[\w- ]+)(?: bui|\))/i],[u,[p,"Smartfren"],[d,m]],[/droid.+; (a(?:015|06[35]|142p?))/i],[u,[p,"Nothing"],[d,m]],[/(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],[p,u,[d,m]],[/(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],[p,u,[d,v]],[/(surface duo)/i],[u,[p,A],[d,v]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[u,[p,"Fairphone"],[d,m]],[/(u304aa)/i],[u,[p,"AT&T"],[d,m]],[/\bsie-(\w*)/i],[u,[p,"Siemens"],[d,m]],[/\b(rct\w+) b/i],[u,[p,"RCA"],[d,v]],[/\b(venue[\d ]{2,7}) b/i],[u,[p,"Dell"],[d,v]],[/\b(q(?:mv|ta)\w+) b/i],[u,[p,"Verizon"],[d,v]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[u,[p,"Barnes & Noble"],[d,v]],[/\b(tm\d{3}\w+) b/i],[u,[p,"NuVision"],[d,v]],[/\b(k88) b/i],[u,[p,"ZTE"],[d,v]],[/\b(nx\d{3}j) b/i],[u,[p,"ZTE"],[d,m]],[/\b(gen\d{3}) b.+49h/i],[u,[p,"Swiss"],[d,m]],[/\b(zur\d{3}) b/i],[u,[p,"Swiss"],[d,v]],[/\b((zeki)?tb.*\b) b/i],[u,[p,"Zeki"],[d,v]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[p,"Dragon Touch"],u,[d,v]],[/\b(ns-?\w{0,9}) b/i],[u,[p,"Insignia"],[d,v]],[/\b((nxa|next)-?\w{0,9}) b/i],[u,[p,"NextBook"],[d,v]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[p,"Voice"],u,[d,m]],[/\b(lvtel\-)?(v1[12]) b/i],[[p,"LvTel"],u,[d,m]],[/\b(ph-1) /i],[u,[p,"Essential"],[d,m]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[u,[p,"Envizen"],[d,v]],[/\b(trio[-\w\. ]+) b/i],[u,[p,"MachSpeed"],[d,v]],[/\btu_(1491) b/i],[u,[p,"Rotor"],[d,v]],[/(shield[\w ]+) b/i],[u,[p,"Nvidia"],[d,v]],[/(sprint) (\w+)/i],[p,u,[d,m]],[/(kin\.[onetw]{3})/i],[[u,/\./g," "],[p,A],[d,m]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[u,[p,$],[d,v]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[u,[p,$],[d,m]],[/smart-tv.+(samsung)/i],[p,[d,y]],[/hbbtv.+maple;(\d+)/i],[[u,/^/,"SmartTV"],[p,D],[d,y]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[p,I],[d,y]],[/(apple) ?tv/i],[p,[u,E+" TV"],[d,y]],[/crkey/i],[[u,k+"cast"],[p,w],[d,y]],[/droid.+aft(\w+)( bui|\))/i],[u,[p,_],[d,y]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[u,[p,x],[d,y]],[/(bravia[\w ]+)( bui|\))/i],[u,[p,L],[d,y]],[/(mitv-\w{5}) bui/i],[u,[p,j],[d,y]],[/Hbbtv.*(technisat) (.*);/i],[p,u,[d,y]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[p,K],[u,K],[d,y]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[d,y]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[p,u,[d,g]],[/droid.+; (shield) bui/i],[u,[p,"Nvidia"],[d,g]],[/(playstation [345portablevi]+)/i],[u,[p,L],[d,g]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[u,[p,A],[d,g]],[/\b(sm-[lr]\d\d[05][fnuw]?s?)\b/i],[u,[p,D],[d,b]],[/((pebble))app/i],[p,u,[d,b]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[u,[p,E],[d,b]],[/droid.+; (glass) \d/i],[u,[p,w],[d,b]],[/droid.+; (wt63?0{2,3})\)/i],[u,[p,$],[d,b]],[/droid.+; (glass) \d/i],[u,[p,w],[d,b]],[/(pico) (4|neo3(?: link|pro)?)/i],[p,u,[d,b]],[/; (quest( \d| pro)?)/i],[u,[p,U],[d,b]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[p,[d,S]],[/(aeobc)\b/i],[u,[p,_],[d,S]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i],[u,[d,m]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[u,[d,v]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[d,v]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[d,m]],[/(android[-\w\. ]{0,9});.+buil/i],[u,[p,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[f,[l,"EdgeHTML"]],[/(arkweb)\/([\w\.]+)/i],[l,f],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[f,[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,f],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[f,l]],os:[[/microsoft (windows) (vista|xp)/i],[l,f],[/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i],[l,[f,Y,J]],[/windows nt 6\.2; (arm)/i,/windows[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i,/(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[f,Y,J],[l,"Windows"]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[f,/_/g,"."],[l,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[l,V],[f,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[f,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,f],[/\(bb(10);/i],[f,[l,R]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[f,[l,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[f,[l,P+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[f,[l,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[f,[l,"watchOS"]],[/crkey\/([\d\.]+)/i],[f,[l,k+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[l,F],f],[/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,f],[/(sunos) ?([\w\.\d]*)/i],[[l,"Solaris"],f],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[l,f]]},Q=function(e,t){if(typeof e===a&&(t=e,e=n),!(this instanceof Q))return new Q(e,t).getResult();var g=typeof r!==o&&r.navigator?r.navigator:n,y=e||(g&&g.userAgent?g.userAgent:""),b=g&&g.userAgentData?g.userAgentData:n,S=t?function(e,t){var r={};for(var n in e)t[n]&&t[n].length%2==0?r[n]=t[n].concat(e[n]):r[n]=e[n];return r}(z,t):z,_=g&&g.userAgent==y;return this.getBrowser=function(){var e,t={};return t[l]=n,t[f]=n,W.call(t,y,S.browser),t[c]=typeof(e=t[f])===s?e.replace(/[^\d\.]/g,"").split(".")[0]:n,_&&g&&g.brave&&typeof g.brave.isBrave==i&&(t[l]="Brave"),t},this.getCPU=function(){var e={};return e[h]=n,W.call(e,y,S.cpu),e},this.getDevice=function(){var e={};return e[p]=n,e[u]=n,e[d]=n,W.call(e,y,S.device),_&&!e[d]&&b&&b.mobile&&(e[d]=m),_&&"Macintosh"==e[u]&&g&&typeof g.standalone!==o&&g.maxTouchPoints&&g.maxTouchPoints>2&&(e[u]="iPad",e[d]=v),e},this.getEngine=function(){var e={};return e[l]=n,e[f]=n,W.call(e,y,S.engine),e},this.getOS=function(){var e={};return e[l]=n,e[f]=n,W.call(e,y,S.os),_&&!e[l]&&b&&b.platform&&"Unknown"!=b.platform&&(e[l]=b.platform.replace(/chrome os/i,F).replace(/macos/i,V)),e},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return y},this.setUA=function(e){return y=typeof e===s&&e.length>500?K(e,500):e,this},this.setUA(y),this};Q.VERSION="1.0.40",Q.BROWSER=B([l,f,c]),Q.CPU=B([h]),Q.DEVICE=B([u,p,d,g,m,y,v,b,S]),Q.ENGINE=Q.OS=B([l,f]),e.exports&&(t=e.exports=Q),t.UAParser=Q;var Z=typeof r!==o&&(r.jQuery||r.Zepto);if(Z&&!Z.ua){var X=new Q;Z.ua=X.getResult(),Z.ua.get=function(){return X.getUA()},Z.ua.set=function(e){X.setUA(e);var t=X.getResult();for(var r in t)Z.ua[r]=t[r]}}}("object"==typeof window?window:commonjsGlobal)}(uaParser,uaParser.exports);var uaParserExports=uaParser.exports,BrowserType,OSType,_device$vendor,_a;!function(e){e._2345_EXPLORER="2345Explorer",e._360="360 Browser",e.ALIPAY="Alipay",e.AMAYA="Amaya",e.ANDROID="Android Browser",e.ARORA="Arora",e.AVANT="Avant",e.AVAST="Avast Secure Browser",e.AVG="AVG Secure Browser",e.BAIDU="Baidu Browser",e.BASILISK="Basilisk",e.BLAZER="Blazer",e.BOLT="Bolt",e.BOWSER="Bowser",e.BRAVE="Brave",e.CAMINO="Camino",e.CHIMERA="Chimera",e.CHROME="Chrome",e.CHROME_HEADLESS="Chrome Headless",e.CHROME_MOBILE="Mobile Chrome",e.CHROME_WEBVIEW="Chrome WebView",e.CHROMIUM="Chromium",e.COBALT="Cobalt",e.COC_COC="Coc Coc",e.COMODO_DRAGON="Comodo Dragon",e.CONKEROR="Conkeror",e.DILLO="Dillo",e.DOLPHIN="Dolphin",e.DORIS="Doris",e.DUCKDUCKGO="DuckDuckGo",e.EDGE="Edge",e.EPIPHANY="Epiphany",e.FACEBOOK="Facebook",e.FALKON="Falkon",e.FIREBIRD="Firebird",e.FIREFOX="Firefox",e.FIREFOX_FOCUS="Firefox Focus",e.FIREFOX_MOBILE="Mobile Firefox",e.FIREFOX_REALITY="Firefox Reality",e.FENNEC="Fennec",e.FLOCK="Flock",e.FLOW="Flow",e.GO="Go Browser",e.GOOGLE_SEARCH="GSA",e.HEYTAP="HeyTap",e.HUAWEI="Huawei Browser",e.ICAB="iCab",e.ICE="ICE Browser",e.ICEAPE="IceApe",e.ICECAT="IceCat",e.ICEDRAGON="IceDragon",e.ICEWEASEL="IceWeasel",e.IE="IE",e.INSTAGRAM="Instagram",e.IRIDIUM="Iridium",e.IRON="Iron",e.JASMINE="Jasmine",e.KONQUEROR="Konqueror",e.KAKAO="KakaoTalk",e.KHTML="KHTML",e.K_MELEON="K-Meleon",e.KLAR="Klar",e.KLARNA="Klarna",e.KINDLE="Kindle",e.LENOVO="Smart Lenovo Browser",e.LIEBAO="LBBROWSER",e.LINE="Line",e.LINKEDIN="LinkedIn",e.LINKS="Links",e.LUNASCAPE="Lunascape",e.LYNX="Lynx",e.MAEMO="Maemo Browser",e.MAXTHON="Maxthon",e.MIDORI="Midori",e.MINIMO="Minimo",e.MIUI="MIUI Browser",e.MOZILLA="Mozilla",e.MOSAIC="Mosaic",e.NAVER="Naver",e.NETFRONT="NetFront",e.NETSCAPE="Netscape",e.NETSURF="Netsurf",e.NOKIA="Nokia Browser",e.OBIGO="Obigo",e.OCULUS="Oculus Browser",e.OMNIWEB="OmniWeb",e.OPERA="Opera",e.OPERA_COAST="Opera Coast",e.OPERA_MINI="Opera Mini",e.OPERA_MOBI="Opera Mobi",e.OPERA_TABLET="Opera Tablet",e.OPERA_TOUCH="Opera Touch",e.OVI="OviBrowser",e.PALEMOON="PaleMoon",e.PHANTOMJS="PhantomJS",e.PHOENIX="Phoenix",e.POLARIS="Polaris",e.PUFFIN="Puffin",e.QQ="QQBrowser",e.QQ_LITE="QQBrowserLite",e.QUARK="Quark",e.QUPZILLA="QupZilla",e.REKONQ="rekonq",e.ROCKMELT="Rockmelt",e.SAFARI="Safari",e.SAFARI_MOBILE="Mobile Safari",e.SAILFISH="Sailfish Browser",e.SAMSUNG="Samsung Internet",e.SEAMONKEY="SeaMonkey",e.SILK="Silk",e.SKYFIRE="Skyfire",e.SLEIPNIR="Sleipnir",e.SLIMBROWSER="SlimBrowser",e.SNAPCHAT="Snapchat",e.SOGOU_EXPLORER="Sogou Explorer",e.SOGOU_MOBILE="Sogou Mobile",e.SWIFTFOX="Swiftfox",e.TESLA="Tesla",e.TIKTOK="TikTok",e.TIZEN="Tizen Browser",e.UC="UCBrowser",e.UP="UP.Browser",e.VIERA="Viera",e.VIVALDI="Vivaldi",e.VIVO="Vivo Browser",e.W3M="w3m",e.WATERFOX="Waterfox",e.WEBKIT="WebKit",e.WECHAT="WeChat",e.WEIBO="Weibo",e.WHALE="Whale",e.YANDEX="Yandex",e.ELECTRON="Electron"}(BrowserType||(BrowserType={})),function(e){e.AIX="AIX",e.AMIGA_OS="Amiga OS",e.ANDROID="Android",e.ANDROID_X86="Android-x86",e.ARCH="Arch",e.BADA="Bada",e.BEOS="BeOS",e.BLACKBERRY="BlackBerry",e.CENTOS="CentOS",e.CHROME_OS="Chrome OS",e.CHROMECAST="Chromecast",e.CONTIKI="Contiki",e.DEBIAN="Debian",e.DEEPIN="Deepin",e.DRAGONFLY="DragonFly",e.ELEMENTARY_OS="elementary OS",e.FEDORA="Fedora",e.FIREFOX_OS="Firefox OS",e.FREEBSD="FreeBSD",e.FUCHSIA="Fuchsia",e.GENTOO="Gentoo",e.GHOSTBSD="GhostBSD",e.GNU="GNU",e.HAIKU="Haiku",e.HARMONYOS="HarmonyOS",e.HP_UX="HP-UX",e.HURD="Hurd",e.IOS="iOS",e.JOLI="Joli",e.KAIOS="KaiOS",e.LINPUS="Linpus",e.LINSPIRE="Linspire",e.LINUX="Linux",e.MACOS="macOS",e.MAEMO="Maemo",e.MAGEIA="Mageia",e.MANDRIVA="Mandriva",e.MANJARO="Manjaro",e.MEEGO="MeeGo",e.MINIX="Minix",e.MINT="Mint",e.MORPH_OS="Morph OS",e.NETBSD="NetBSD",e.NETRANGE="NetRange",e.NETTV="NetTV",e.NINTENDO="Nintendo",e.OPENBSD="OpenBSD",e.OPENVMS="OpenVMS",e.OS2="OS/2",e.PALM="Palm",e.PC_BSD="PC-BSD",e.PCLINUXOS="PCLinuxOS",e.PLAN9="Plan9",e.PLAYSTATION="PlayStation",e.QNX="QNX",e.RASPBIAN="Raspbian",e.REDHAT="RedHat",e.RIM_TABLET_OS="RIM Tablet OS",e.RISC_OS="RISC OS",e.SABAYON="Sabayon",e.SAILFISH="Sailfish",e.SERENITYOS="SerenityOS",e.SERIES40="Series40",e.SLACKWARE="Slackware",e.SOLARIS="Solaris",e.SUSE="SUSE",e.SYMBIAN="Symbian",e.TIZEN="Tizen",e.UBUNTU="Ubuntu",e.UNIX="Unix",e.VECTORLINUX="VectorLinux",e.VIERA="Viera",e.WATCHOS="watchOS",e.WEBOS="WebOS",e.WINDOWS="Windows",e.WINDOWS_MOBILE="Windows Mobile",e.WINDOWS_PHONE="Windows Phone",e.XBOX="Xbox",e.ZENWALK="Zenwalk"}(OSType||(OSType={}));var parser$2=new uaParserExports.UAParser(navigator.userAgent),_parser$getResult=parser$2.getResult(),os=_parser$getResult.os,cpu=_parser$getResult.cpu,browser=_parser$getResult.browser,device=_parser$getResult.device,TerminalType$1,SdkType$1;"HarmonyOS"===os.name&&(os.name="Android"),function(e){e[e.Windows=1]="Windows",e[e.Android=2]="Android",e[e.Mac=3]="Mac",e[e.iOS=4]="iOS",e[e.Linux=5]="Linux",e[e.Others=6]="Others"}(TerminalType$1||(TerminalType$1={})),function(e){e[e.Native=1]="Native",e[e.Web=2]="Web",e[e.MiniProgram=3]="MiniProgram"}(SdkType$1||(SdkType$1={}));var clientDeviceId="";try{clientDeviceId=localStorage.getItem(DEVICEID)}catch(e){}if(!clientDeviceId){clientDeviceId=createUuid();try{localStorage.setItem(DEVICEID,clientDeviceId)}catch(e){}}var deviceId=clientDeviceId;window._dingrtc_js_load_tab_id=window._dingrtc_js_load_tab_id||createUuid(8);var browserTabId=window._dingrtc_js_load_tab_id,getTerminalType=function(){var e=TerminalType$1.Others;return os.name===OSType.WINDOWS?e=TerminalType$1.Windows:os.name===OSType.MACOS?e=TerminalType$1.Mac:os.name.includes(OSType.ANDROID)?e=TerminalType$1.Android:os.name===OSType.IOS?e=TerminalType$1.iOS:os.name===OSType.LINUX&&(e=TerminalType$1.Linux),e},Environment=_createClass(function e(){_classCallCheck(this,e)});function ownKeys$2$1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function _objectSpread$2$1(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$2$1(Object(r),!0).forEach(function(t){_defineProperty$1(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$2$1(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}_a=Environment,Object.defineProperty(Environment,"browserType",{enumerable:!0,configurable:!0,writable:!0,value:browser.name}),Object.defineProperty(Environment,"browserVersion",{enumerable:!0,configurable:!0,writable:!0,value:browser.version}),Object.defineProperty(Environment,"system",{enumerable:!0,configurable:!0,writable:!0,value:os.name}),Object.defineProperty(Environment,"terminalType",{enumerable:!0,configurable:!0,writable:!0,value:getTerminalType()}),Object.defineProperty(Environment,"sdkType",{enumerable:!0,configurable:!0,writable:!0,value:SdkType$1.Web}),Object.defineProperty(Environment,"systemVersion",{enumerable:!0,configurable:!0,writable:!0,value:os.version}),Object.defineProperty(Environment,"deviceId",{enumerable:!0,configurable:!0,writable:!0,value:deviceId}),Object.defineProperty(Environment,"browserTabId",{enumerable:!0,configurable:!0,writable:!0,value:browserTabId}),Object.defineProperty(Environment,"networkType",{enumerable:!0,configurable:!0,writable:!0,value:"unknown"}),Object.defineProperty(Environment,"manu",{enumerable:!0,configurable:!0,writable:!0,value:null===(_device$vendor=device.vendor)||void 0===_device$vendor?void 0:_device$vendor.toLocaleLowerCase()}),Object.defineProperty(Environment,"model",{enumerable:!0,configurable:!0,writable:!0,value:device.model}),Object.defineProperty(Environment,"cpu",{enumerable:!0,configurable:!0,writable:!0,value:cpu.architecture}),Object.defineProperty(Environment,"isAndroid",{enumerable:!0,configurable:!0,writable:!0,value:function(){return _a.system.includes(OSType.ANDROID)}}),Object.defineProperty(Environment,"isIOS",{enumerable:!0,configurable:!0,writable:!0,value:function(){return _a.system===OSType.IOS}}),Object.defineProperty(Environment,"isWeixin",{enumerable:!0,configurable:!0,writable:!0,value:function(){return _a.browserType===BrowserType.WECHAT}}),Object.defineProperty(Environment,"isChrome",{enumerable:!0,configurable:!0,writable:!0,value:function(){return _a.browserType.includes(BrowserType.CHROME)}}),Object.defineProperty(Environment,"isSafari",{enumerable:!0,configurable:!0,writable:!0,value:function(){return _a.browserType.includes(BrowserType.SAFARI)}}),Object.defineProperty(Environment,"isFirefox",{enumerable:!0,configurable:!0,writable:!0,value:function(){return _a.browserType.includes(BrowserType.FIREFOX)}}),Object.defineProperty(Environment,"isOpera",{enumerable:!0,configurable:!0,writable:!0,value:function(){return _a.browserType.includes(BrowserType.OPERA)}}),Object.defineProperty(Environment,"isQQBrowser",{enumerable:!0,configurable:!0,writable:!0,value:function(){return _a.browserType===BrowserType.QQ}}),Object.defineProperty(Environment,"isElectron",{enumerable:!0,configurable:!0,writable:!0,value:function(){return _a.browserType===BrowserType.ELECTRON}});var iFetch=function(e,t,r){var n=_objectSpread$2$1(_objectSpread$2$1({},arguments.length>3&&void 0!==arguments[3]?arguments[3]:{}),{},{"Content-Type":"application/json",Accept:"application/json"});return new Promise(function(i,o){var a;fetch(t,{method:e,body:r,headers:n}).then(function(e){return a=e,e.ok?e.json():e.text()}).then(function(e){var t;null!==(t=a)&&void 0!==t&&t.ok?e.code?o(e):i(e):o(a)}).catch(function(e){o(e)})})},post$1=function(e,t,r){return iFetch("POST",e,t,r)},logService=function(e){var t=e.userId;delete e.userId;var r="/v1/users/".concat(t,"/log-service");return post$1("".concat(getGslb()).concat(r),JSON.stringify(e))},EventEmitter=_createClass(function e(){_classCallCheck(this,e),Object.defineProperty(this,"eventMap",{enumerable:!0,configurable:!0,writable:!0,value:{}})},[{key:"listenerCount",value:function(e){return this.eventMap[e].length||0}},{key:"emit",value:function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];var i=this.eventMap[e];return!(!i||0===i.length||(i.forEach(function(t){try{t.fn.apply(t,r)}catch(t){console.error(e,"event callback execute error:",t)}}),this.eventMap[e]=i.filter(function(e){return!e.once}),0))}},{key:"on",value:function(e,t){return this.eventMap[e]||(this.eventMap[e]=[]),this.eventMap[e].some(function(e){return e.fn===t&&!e.once})||this.eventMap[e].push({fn:t,once:!1}),this}},{key:"once",value:function(e,t){return this.eventMap[e]||(this.eventMap[e]=[]),this.eventMap[e].some(function(e){return e.fn===t&&e.once})||this.eventMap[e].push({fn:t,once:!0}),this}},{key:"off",value:function(e,t){if(t){var r=this.eventMap[e];if(r&&r.length>0){var n=r.findIndex(function(e){return e.fn===t});n>-1&&r.splice(n,1)}}else this.eventMap[e]=[]}},{key:"removeAllListeners",value:function(e){e?this.eventMap[e]=[]:this.eventMap={}}}]),EventBus=new EventEmitter;function _callSuper$1$1(e,t,r){return t=_getPrototypeOf(t),_possibleConstructorReturn(e,_isNativeReflectConstruct$1$1()?Reflect.construct(t,[],_getPrototypeOf(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$1$1(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$1$1=function(){return!!e})()}var STSTokenManager=function(e){function t(e,r,n){var i;return _classCallCheck(this,t),i=_callSuper$1$1(this,t),Object.defineProperty(i,"credential",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"updating",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"requesting",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"commonInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"securityToken",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"delayTimerId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"checkTokenTimerId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"startTime",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),i.commonInfo=r,i.securityToken=e,i.updating=!0,i.delayTimerId=0,i.checkTokenTimerId=0,i.requesting=!1,i.updateCredential(n),i}return _inherits(t,EventEmitter),_createClass(t,[{key:"stopUpdateToken",value:function(){this.updating=!1,this.stopDelayTimer(),this.stopCheckTokenTimer()}},{key:"requestStsToken",value:function(){var e=this;if(!this.requesting&&this.updating){this.requesting=!0;var t=this.commonInfo,r=t.usrid,n=t.roomName,i=t.apid;logService({userId:r,channelId:n,appId:i,securityToken:this.securityToken.securityToken}).then(function(t){if(t&&t.logService)return e.updateCredential(t.logService.credentials),e.emit("update",t.logService),e.securityToken=t.securityToken,e.requesting=!1,!0;e.updating&&e.delayRequest()}).catch(function(){e.updating&&e.delayRequest()})}}},{key:"delayRequest",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:3e4;this.delayTimerId||(this.delayTimerId=window.setTimeout(function(){e.requestStsToken()},t))}},{key:"stopDelayTimer",value:function(){this.delayTimerId&&(clearTimeout(this.delayTimerId),this.delayTimerId=null)}},{key:"updateSecurityToken",value:function(e){this.stopDelayTimer(),this.securityToken=e,this.delayRequest()}},{key:"updateCredential",value:function(e){this.credential=e,this.startTime=Date.now(),this.checkToken()}},{key:"checkToken",value:function(){var e=this;if(this.updating)if(this.credential.durationSeconds){var t=Math.round((Date.now()-this.startTime)/1e3);this.credential.durationSeconds-t<=0?this.requestStsToken():this.checkTokenTimerId||(this.checkTokenTimerId=window.setTimeout(function(){e.stopCheckTokenTimer(),e.checkToken()},3e5))}else this.requestStsToken()}},{key:"stopCheckTokenTimer",value:function(){this.checkTokenTimerId&&(clearTimeout(this.checkTokenTimerId),this.checkTokenTimerId=null)}}])}();function _arrayLikeToArray$e(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _arrayWithoutHoles$1(e){if(Array.isArray(e))return _arrayLikeToArray$e(e)}function _iterableToArray$1(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}function _unsupportedIterableToArray$e(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$e(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_arrayLikeToArray$e(e,t):void 0}}function _nonIterableSpread$1(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _toConsumableArray$1(e){return _arrayWithoutHoles$1(e)||_iterableToArray$1(e)||_unsupportedIterableToArray$e(e)||_nonIterableSpread$1()}var pakoDeflate={exports:{}};!function(e){function t(e){for(var t=e.length;--t>=0;)e[t]=0}var r=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]),n=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]),i=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),o=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),a=new Array(576);t(a);var s=new Array(60);t(s);var c=new Array(512);t(c);var u=new Array(256);t(u);var l=new Array(29);t(l);var d,p,f,h=new Array(30);function g(e,t,r,n,i){this.static_tree=e,this.extra_bits=t,this.extra_base=r,this.elems=n,this.max_length=i,this.has_stree=e&&e.length}function m(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}t(h);var v=function(e){return e<256?c[e]:c[256+(e>>>7)]},y=function(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255},b=function(e,t,r){e.bi_valid>16-r?(e.bi_buf|=t<<e.bi_valid&65535,y(e,e.bi_buf),e.bi_buf=t>>16-e.bi_valid,e.bi_valid+=r-16):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=r)},S=function(e,t,r){b(e,r[2*t],r[2*t+1])},_=function(e,t){var r=0;do{r|=1&e,e>>>=1,r<<=1}while(--t>0);return r>>>1},E=function(e,t,r){var n,i,o=new Array(16),a=0;for(n=1;n<=15;n++)a=a+r[n-1]<<1,o[n]=a;for(i=0;i<=t;i++){var s=e[2*i+1];0!==s&&(e[2*i]=_(o[s]++,s))}},T=function(e){var t;for(t=0;t<286;t++)e.dyn_ltree[2*t]=0;for(t=0;t<30;t++)e.dyn_dtree[2*t]=0;for(t=0;t<19;t++)e.bl_tree[2*t]=0;e.dyn_ltree[512]=1,e.opt_len=e.static_len=0,e.sym_next=e.matches=0},R=function(e){e.bi_valid>8?y(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0},C=function(e,t,r,n){var i=2*t,o=2*r;return e[i]<e[o]||e[i]===e[o]&&n[t]<=n[r]},k=function(e,t,r){for(var n=e.heap[r],i=r<<1;i<=e.heap_len&&(i<e.heap_len&&C(t,e.heap[i+1],e.heap[i],e.depth)&&i++,!C(t,n,e.heap[i],e.depth));)e.heap[r]=e.heap[i],r=i,i<<=1;e.heap[r]=n},P=function(e,t,i){var o,a,s,c,d=0;if(0!==e.sym_next)do{o=255&e.pending_buf[e.sym_buf+d++],o+=(255&e.pending_buf[e.sym_buf+d++])<<8,a=e.pending_buf[e.sym_buf+d++],0===o?S(e,a,t):(s=u[a],S(e,s+256+1,t),0!==(c=r[s])&&(a-=l[s],b(e,a,c)),o--,s=v(o),S(e,s,i),0!==(c=n[s])&&(o-=h[s],b(e,o,c)))}while(d<e.sym_next);S(e,256,t)},w=function(e,t){var r,n,i,o=t.dyn_tree,a=t.stat_desc.static_tree,s=t.stat_desc.has_stree,c=t.stat_desc.elems,u=-1;for(e.heap_len=0,e.heap_max=573,r=0;r<c;r++)0!==o[2*r]?(e.heap[++e.heap_len]=u=r,e.depth[r]=0):o[2*r+1]=0;for(;e.heap_len<2;)o[2*(i=e.heap[++e.heap_len]=u<2?++u:0)]=1,e.depth[i]=0,e.opt_len--,s&&(e.static_len-=a[2*i+1]);for(t.max_code=u,r=e.heap_len>>1;r>=1;r--)k(e,o,r);i=c;do{r=e.heap[1],e.heap[1]=e.heap[e.heap_len--],k(e,o,1),n=e.heap[1],e.heap[--e.heap_max]=r,e.heap[--e.heap_max]=n,o[2*i]=o[2*r]+o[2*n],e.depth[i]=(e.depth[r]>=e.depth[n]?e.depth[r]:e.depth[n])+1,o[2*r+1]=o[2*n+1]=i,e.heap[1]=i++,k(e,o,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],function(e,t){var r,n,i,o,a,s,c=t.dyn_tree,u=t.max_code,l=t.stat_desc.static_tree,d=t.stat_desc.has_stree,p=t.stat_desc.extra_bits,f=t.stat_desc.extra_base,h=t.stat_desc.max_length,g=0;for(o=0;o<=15;o++)e.bl_count[o]=0;for(c[2*e.heap[e.heap_max]+1]=0,r=e.heap_max+1;r<573;r++)(o=c[2*c[2*(n=e.heap[r])+1]+1]+1)>h&&(o=h,g++),c[2*n+1]=o,n>u||(e.bl_count[o]++,a=0,n>=f&&(a=p[n-f]),s=c[2*n],e.opt_len+=s*(o+a),d&&(e.static_len+=s*(l[2*n+1]+a)));if(0!==g){do{for(o=h-1;0===e.bl_count[o];)o--;e.bl_count[o]--,e.bl_count[o+1]+=2,e.bl_count[h]--,g-=2}while(g>0);for(o=h;0!==o;o--)for(n=e.bl_count[o];0!==n;)(i=e.heap[--r])>u||(c[2*i+1]!==o&&(e.opt_len+=(o-c[2*i+1])*c[2*i],c[2*i+1]=o),n--)}}(e,t),E(o,u,e.bl_count)},O=function(e,t,r){var n,i,o=-1,a=t[1],s=0,c=7,u=4;for(0===a&&(c=138,u=3),t[2*(r+1)+1]=65535,n=0;n<=r;n++)i=a,a=t[2*(n+1)+1],++s<c&&i===a||(s<u?e.bl_tree[2*i]+=s:0!==i?(i!==o&&e.bl_tree[2*i]++,e.bl_tree[32]++):s<=10?e.bl_tree[34]++:e.bl_tree[36]++,s=0,o=i,0===a?(c=138,u=3):i===a?(c=6,u=3):(c=7,u=4))},I=function(e,t,r){var n,i,o=-1,a=t[1],s=0,c=7,u=4;for(0===a&&(c=138,u=3),n=0;n<=r;n++)if(i=a,a=t[2*(n+1)+1],!(++s<c&&i===a)){if(s<u)do{S(e,i,e.bl_tree)}while(0!=--s);else 0!==i?(i!==o&&(S(e,i,e.bl_tree),s--),S(e,16,e.bl_tree),b(e,s-3,2)):s<=10?(S(e,17,e.bl_tree),b(e,s-3,3)):(S(e,18,e.bl_tree),b(e,s-11,7));s=0,o=i,0===a?(c=138,u=3):i===a?(c=6,u=3):(c=7,u=4)}},A=!1,M=function(e,t,r,n){b(e,0+(n?1:0),3),R(e),y(e,r),y(e,~r),r&&e.pending_buf.set(e.window.subarray(t,t+r),e.pending),e.pending+=r},N=function(e){A||(function(){var e,t,o,m,v,y=new Array(16);for(o=0,m=0;m<28;m++)for(l[m]=o,e=0;e<1<<r[m];e++)u[o++]=m;for(u[o-1]=m,v=0,m=0;m<16;m++)for(h[m]=v,e=0;e<1<<n[m];e++)c[v++]=m;for(v>>=7;m<30;m++)for(h[m]=v<<7,e=0;e<1<<n[m]-7;e++)c[256+v++]=m;for(t=0;t<=15;t++)y[t]=0;for(e=0;e<=143;)a[2*e+1]=8,e++,y[8]++;for(;e<=255;)a[2*e+1]=9,e++,y[9]++;for(;e<=279;)a[2*e+1]=7,e++,y[7]++;for(;e<=287;)a[2*e+1]=8,e++,y[8]++;for(E(a,287,y),e=0;e<30;e++)s[2*e+1]=5,s[2*e]=_(e,5);d=new g(a,r,257,286,15),p=new g(s,n,0,30,15),f=new g(new Array(0),i,0,19,7)}(),A=!0),e.l_desc=new m(e.dyn_ltree,d),e.d_desc=new m(e.dyn_dtree,p),e.bl_desc=new m(e.bl_tree,f),e.bi_buf=0,e.bi_valid=0,T(e)},D=M,x=function(e,t,r,n){var i,c,u=0;e.level>0?(2===e.strm.data_type&&(e.strm.data_type=function(e){var t,r=4093624447;for(t=0;t<=31;t++,r>>>=1)if(1&r&&0!==e.dyn_ltree[2*t])return 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t<256;t++)if(0!==e.dyn_ltree[2*t])return 1;return 0}(e)),w(e,e.l_desc),w(e,e.d_desc),u=function(e){var t;for(O(e,e.dyn_ltree,e.l_desc.max_code),O(e,e.dyn_dtree,e.d_desc.max_code),w(e,e.bl_desc),t=18;t>=3&&0===e.bl_tree[2*o[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t}(e),i=e.opt_len+3+7>>>3,(c=e.static_len+3+7>>>3)<=i&&(i=c)):i=c=r+5,r+4<=i&&-1!==t?M(e,t,r,n):4===e.strategy||c===i?(b(e,2+(n?1:0),3),P(e,a,s)):(b(e,4+(n?1:0),3),function(e,t,r,n){var i;for(b(e,t-257,5),b(e,r-1,5),b(e,n-4,4),i=0;i<n;i++)b(e,e.bl_tree[2*o[i]+1],3);I(e,e.dyn_ltree,t-1),I(e,e.dyn_dtree,r-1)}(e,e.l_desc.max_code+1,e.d_desc.max_code+1,u+1),P(e,e.dyn_ltree,e.dyn_dtree)),T(e),n&&R(e)},L=function(e,t,r){return e.pending_buf[e.sym_buf+e.sym_next++]=t,e.pending_buf[e.sym_buf+e.sym_next++]=t>>8,e.pending_buf[e.sym_buf+e.sym_next++]=r,0===t?e.dyn_ltree[2*r]++:(e.matches++,t--,e.dyn_ltree[2*(u[r]+256+1)]++,e.dyn_dtree[2*v(t)]++),e.sym_next===e.sym_end},j=function(e){b(e,2,3),S(e,256,a),function(e){16===e.bi_valid?(y(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}(e)},$=function(e,t,r,n){for(var i=65535&e,o=e>>>16&65535,a=0;0!==r;){r-=a=r>2e3?2e3:r;do{o=o+(i=i+t[n++]|0)|0}while(--a);i%=65521,o%=65521}return i|o<<16},U=new Uint32Array(function(){for(var e,t=[],r=0;r<256;r++){e=r;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[r]=e}return t}()),F=function(e,t,r,n){var i=U,o=n+r;e^=-1;for(var a=n;a<o;a++)e=e>>>8^i[255&(e^t[a])];return-1^e},V={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"},G={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},B=N,H=D,q=x,K=L,W=j,Y=G.Z_NO_FLUSH,J=G.Z_PARTIAL_FLUSH,z=G.Z_FULL_FLUSH,Q=G.Z_FINISH,Z=G.Z_BLOCK,X=G.Z_OK,ee=G.Z_STREAM_END,te=G.Z_STREAM_ERROR,re=G.Z_DATA_ERROR,ne=G.Z_BUF_ERROR,ie=G.Z_DEFAULT_COMPRESSION,oe=G.Z_FILTERED,ae=G.Z_HUFFMAN_ONLY,se=G.Z_RLE,ce=G.Z_FIXED,ue=G.Z_UNKNOWN,le=G.Z_DEFLATED,de=258,pe=262,fe=42,he=113,ge=666,me=function(e,t){return e.msg=V[t],t},ve=function(e){return 2*e-(e>4?9:0)},ye=function(e){for(var t=e.length;--t>=0;)e[t]=0},be=function(e){var t,r,n,i=e.w_size;n=t=e.hash_size;do{r=e.head[--n],e.head[n]=r>=i?r-i:0}while(--t);n=t=i;do{r=e.prev[--n],e.prev[n]=r>=i?r-i:0}while(--t)},Se=function(e,t,r){return(t<<e.hash_shift^r)&e.hash_mask},_e=function(e){var t=e.state,r=t.pending;r>e.avail_out&&(r=e.avail_out),0!==r&&(e.output.set(t.pending_buf.subarray(t.pending_out,t.pending_out+r),e.next_out),e.next_out+=r,t.pending_out+=r,e.total_out+=r,e.avail_out-=r,t.pending-=r,0===t.pending&&(t.pending_out=0))},Ee=function(e,t){q(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,_e(e.strm)},Te=function(e,t){e.pending_buf[e.pending++]=t},Re=function(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t},Ce=function(e,t,r,n){var i=e.avail_in;return i>n&&(i=n),0===i?0:(e.avail_in-=i,t.set(e.input.subarray(e.next_in,e.next_in+i),r),1===e.state.wrap?e.adler=$(e.adler,t,i,r):2===e.state.wrap&&(e.adler=F(e.adler,t,i,r)),e.next_in+=i,e.total_in+=i,i)},ke=function(e,t){var r,n,i=e.max_chain_length,o=e.strstart,a=e.prev_length,s=e.nice_match,c=e.strstart>e.w_size-pe?e.strstart-(e.w_size-pe):0,u=e.window,l=e.w_mask,d=e.prev,p=e.strstart+de,f=u[o+a-1],h=u[o+a];e.prev_length>=e.good_match&&(i>>=2),s>e.lookahead&&(s=e.lookahead);do{if(u[(r=t)+a]===h&&u[r+a-1]===f&&u[r]===u[o]&&u[++r]===u[o+1]){o+=2,r++;do{}while(u[++o]===u[++r]&&u[++o]===u[++r]&&u[++o]===u[++r]&&u[++o]===u[++r]&&u[++o]===u[++r]&&u[++o]===u[++r]&&u[++o]===u[++r]&&u[++o]===u[++r]&&o<p);if(n=de-(p-o),o=p-de,n>a){if(e.match_start=t,a=n,n>=s)break;f=u[o+a-1],h=u[o+a]}}}while((t=d[t&l])>c&&0!=--i);return a<=e.lookahead?a:e.lookahead},Pe=function(e){var t,r,n,i=e.w_size;do{if(r=e.window_size-e.lookahead-e.strstart,e.strstart>=i+(i-pe)&&(e.window.set(e.window.subarray(i,i+i-r),0),e.match_start-=i,e.strstart-=i,e.block_start-=i,e.insert>e.strstart&&(e.insert=e.strstart),be(e),r+=i),0===e.strm.avail_in)break;if(t=Ce(e.strm,e.window,e.strstart+e.lookahead,r),e.lookahead+=t,e.lookahead+e.insert>=3)for(n=e.strstart-e.insert,e.ins_h=e.window[n],e.ins_h=Se(e,e.ins_h,e.window[n+1]);e.insert&&(e.ins_h=Se(e,e.ins_h,e.window[n+3-1]),e.prev[n&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=n,n++,e.insert--,!(e.lookahead+e.insert<3)););}while(e.lookahead<pe&&0!==e.strm.avail_in)},we=function(e,t){var r,n,i,o=e.pending_buf_size-5>e.w_size?e.w_size:e.pending_buf_size-5,a=0,s=e.strm.avail_in;do{if(r=65535,i=e.bi_valid+42>>3,e.strm.avail_out<i)break;if(i=e.strm.avail_out-i,r>(n=e.strstart-e.block_start)+e.strm.avail_in&&(r=n+e.strm.avail_in),r>i&&(r=i),r<o&&(0===r&&t!==Q||t===Y||r!==n+e.strm.avail_in))break;a=t===Q&&r===n+e.strm.avail_in?1:0,H(e,0,0,a),e.pending_buf[e.pending-4]=r,e.pending_buf[e.pending-3]=r>>8,e.pending_buf[e.pending-2]=~r,e.pending_buf[e.pending-1]=~r>>8,_e(e.strm),n&&(n>r&&(n=r),e.strm.output.set(e.window.subarray(e.block_start,e.block_start+n),e.strm.next_out),e.strm.next_out+=n,e.strm.avail_out-=n,e.strm.total_out+=n,e.block_start+=n,r-=n),r&&(Ce(e.strm,e.strm.output,e.strm.next_out,r),e.strm.next_out+=r,e.strm.avail_out-=r,e.strm.total_out+=r)}while(0===a);return(s-=e.strm.avail_in)&&(s>=e.w_size?(e.matches=2,e.window.set(e.strm.input.subarray(e.strm.next_in-e.w_size,e.strm.next_in),0),e.strstart=e.w_size,e.insert=e.strstart):(e.window_size-e.strstart<=s&&(e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,e.insert>e.strstart&&(e.insert=e.strstart)),e.window.set(e.strm.input.subarray(e.strm.next_in-s,e.strm.next_in),e.strstart),e.strstart+=s,e.insert+=s>e.w_size-e.insert?e.w_size-e.insert:s),e.block_start=e.strstart),e.high_water<e.strstart&&(e.high_water=e.strstart),a?4:t!==Y&&t!==Q&&0===e.strm.avail_in&&e.strstart===e.block_start?2:(i=e.window_size-e.strstart,e.strm.avail_in>i&&e.block_start>=e.w_size&&(e.block_start-=e.w_size,e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,i+=e.w_size,e.insert>e.strstart&&(e.insert=e.strstart)),i>e.strm.avail_in&&(i=e.strm.avail_in),i&&(Ce(e.strm,e.window,e.strstart,i),e.strstart+=i,e.insert+=i>e.w_size-e.insert?e.w_size-e.insert:i),e.high_water<e.strstart&&(e.high_water=e.strstart),i=e.bi_valid+42>>3,o=(i=e.pending_buf_size-i>65535?65535:e.pending_buf_size-i)>e.w_size?e.w_size:i,((n=e.strstart-e.block_start)>=o||(n||t===Q)&&t!==Y&&0===e.strm.avail_in&&n<=i)&&(r=n>i?i:n,a=t===Q&&0===e.strm.avail_in&&r===n?1:0,H(e,e.block_start,r,a),e.block_start+=r,_e(e.strm)),a?3:1)},Oe=function(e,t){for(var r,n;;){if(e.lookahead<pe){if(Pe(e),e.lookahead<pe&&t===Y)return 1;if(0===e.lookahead)break}if(r=0,e.lookahead>=3&&(e.ins_h=Se(e,e.ins_h,e.window[e.strstart+3-1]),r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==r&&e.strstart-r<=e.w_size-pe&&(e.match_length=ke(e,r)),e.match_length>=3)if(n=K(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){e.match_length--;do{e.strstart++,e.ins_h=Se(e,e.ins_h,e.window[e.strstart+3-1]),r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart}while(0!=--e.match_length);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=Se(e,e.ins_h,e.window[e.strstart+1]);else n=K(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(n&&(Ee(e,!1),0===e.strm.avail_out))return 1}return e.insert=e.strstart<2?e.strstart:2,t===Q?(Ee(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(Ee(e,!1),0===e.strm.avail_out)?1:2},Ie=function(e,t){for(var r,n,i;;){if(e.lookahead<pe){if(Pe(e),e.lookahead<pe&&t===Y)return 1;if(0===e.lookahead)break}if(r=0,e.lookahead>=3&&(e.ins_h=Se(e,e.ins_h,e.window[e.strstart+3-1]),r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=2,0!==r&&e.prev_length<e.max_lazy_match&&e.strstart-r<=e.w_size-pe&&(e.match_length=ke(e,r),e.match_length<=5&&(e.strategy===oe||3===e.match_length&&e.strstart-e.match_start>4096)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){i=e.strstart+e.lookahead-3,n=K(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=i&&(e.ins_h=Se(e,e.ins_h,e.window[e.strstart+3-1]),r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart)}while(0!=--e.prev_length);if(e.match_available=0,e.match_length=2,e.strstart++,n&&(Ee(e,!1),0===e.strm.avail_out))return 1}else if(e.match_available){if((n=K(e,0,e.window[e.strstart-1]))&&Ee(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return 1}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(n=K(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<2?e.strstart:2,t===Q?(Ee(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(Ee(e,!1),0===e.strm.avail_out)?1:2};function Ae(e,t,r,n,i){this.good_length=e,this.max_lazy=t,this.nice_length=r,this.max_chain=n,this.func=i}var Me=[new Ae(0,0,0,0,we),new Ae(4,4,8,4,Oe),new Ae(4,5,16,8,Oe),new Ae(4,6,32,32,Oe),new Ae(4,4,16,16,Ie),new Ae(8,16,32,32,Ie),new Ae(8,16,128,128,Ie),new Ae(8,32,128,256,Ie),new Ae(32,128,258,1024,Ie),new Ae(32,258,258,4096,Ie)];function Ne(){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=le,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(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),ye(this.dyn_ltree),ye(this.dyn_dtree),ye(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),ye(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),ye(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}var De=function(e){if(!e)return 1;var t=e.state;return!t||t.strm!==e||t.status!==fe&&57!==t.status&&69!==t.status&&73!==t.status&&91!==t.status&&103!==t.status&&t.status!==he&&t.status!==ge?1:0},xe=function(e){if(De(e))return me(e,te);e.total_in=e.total_out=0,e.data_type=ue;var t=e.state;return t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=2===t.wrap?57:t.wrap?fe:he,e.adler=2===t.wrap?0:1,t.last_flush=-2,B(t),X},Le=function(e){var t,r=xe(e);return r===X&&((t=e.state).window_size=2*t.w_size,ye(t.head),t.max_lazy_match=Me[t.level].max_lazy,t.good_match=Me[t.level].good_length,t.nice_match=Me[t.level].nice_length,t.max_chain_length=Me[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=2,t.match_available=0,t.ins_h=0),r},je=function(e,t,r,n,i,o){if(!e)return te;var a=1;if(t===ie&&(t=6),n<0?(a=0,n=-n):n>15&&(a=2,n-=16),i<1||i>9||r!==le||n<8||n>15||t<0||t>9||o<0||o>ce||8===n&&1!==a)return me(e,te);8===n&&(n=9);var s=new Ne;return e.state=s,s.strm=e,s.status=fe,s.wrap=a,s.gzhead=null,s.w_bits=n,s.w_size=1<<s.w_bits,s.w_mask=s.w_size-1,s.hash_bits=i+7,s.hash_size=1<<s.hash_bits,s.hash_mask=s.hash_size-1,s.hash_shift=~~((s.hash_bits+3-1)/3),s.window=new Uint8Array(2*s.w_size),s.head=new Uint16Array(s.hash_size),s.prev=new Uint16Array(s.w_size),s.lit_bufsize=1<<i+6,s.pending_buf_size=4*s.lit_bufsize,s.pending_buf=new Uint8Array(s.pending_buf_size),s.sym_buf=s.lit_bufsize,s.sym_end=3*(s.lit_bufsize-1),s.level=t,s.strategy=o,s.method=r,Le(e)},$e=je,Ue=function(e,t){return De(e)||2!==e.state.wrap?te:(e.state.gzhead=t,X)},Fe=function(e,t){if(De(e)||t>Z||t<0)return e?me(e,te):te;var r=e.state;if(!e.output||0!==e.avail_in&&!e.input||r.status===ge&&t!==Q)return me(e,0===e.avail_out?ne:te);var n=r.last_flush;if(r.last_flush=t,0!==r.pending){if(_e(e),0===e.avail_out)return r.last_flush=-1,X}else if(0===e.avail_in&&ve(t)<=ve(n)&&t!==Q)return me(e,ne);if(r.status===ge&&0!==e.avail_in)return me(e,ne);if(r.status===fe&&0===r.wrap&&(r.status=he),r.status===fe){var i=le+(r.w_bits-8<<4)<<8;if(i|=(r.strategy>=ae||r.level<2?0:r.level<6?1:6===r.level?2:3)<<6,0!==r.strstart&&(i|=32),Re(r,i+=31-i%31),0!==r.strstart&&(Re(r,e.adler>>>16),Re(r,65535&e.adler)),e.adler=1,r.status=he,_e(e),0!==r.pending)return r.last_flush=-1,X}if(57===r.status)if(e.adler=0,Te(r,31),Te(r,139),Te(r,8),r.gzhead)Te(r,(r.gzhead.text?1:0)+(r.gzhead.hcrc?2:0)+(r.gzhead.extra?4:0)+(r.gzhead.name?8:0)+(r.gzhead.comment?16:0)),Te(r,255&r.gzhead.time),Te(r,r.gzhead.time>>8&255),Te(r,r.gzhead.time>>16&255),Te(r,r.gzhead.time>>24&255),Te(r,9===r.level?2:r.strategy>=ae||r.level<2?4:0),Te(r,255&r.gzhead.os),r.gzhead.extra&&r.gzhead.extra.length&&(Te(r,255&r.gzhead.extra.length),Te(r,r.gzhead.extra.length>>8&255)),r.gzhead.hcrc&&(e.adler=F(e.adler,r.pending_buf,r.pending,0)),r.gzindex=0,r.status=69;else if(Te(r,0),Te(r,0),Te(r,0),Te(r,0),Te(r,0),Te(r,9===r.level?2:r.strategy>=ae||r.level<2?4:0),Te(r,3),r.status=he,_e(e),0!==r.pending)return r.last_flush=-1,X;if(69===r.status){if(r.gzhead.extra){for(var o=r.pending,a=(65535&r.gzhead.extra.length)-r.gzindex;r.pending+a>r.pending_buf_size;){var s=r.pending_buf_size-r.pending;if(r.pending_buf.set(r.gzhead.extra.subarray(r.gzindex,r.gzindex+s),r.pending),r.pending=r.pending_buf_size,r.gzhead.hcrc&&r.pending>o&&(e.adler=F(e.adler,r.pending_buf,r.pending-o,o)),r.gzindex+=s,_e(e),0!==r.pending)return r.last_flush=-1,X;o=0,a-=s}var c=new Uint8Array(r.gzhead.extra);r.pending_buf.set(c.subarray(r.gzindex,r.gzindex+a),r.pending),r.pending+=a,r.gzhead.hcrc&&r.pending>o&&(e.adler=F(e.adler,r.pending_buf,r.pending-o,o)),r.gzindex=0}r.status=73}if(73===r.status){if(r.gzhead.name){var u,l=r.pending;do{if(r.pending===r.pending_buf_size){if(r.gzhead.hcrc&&r.pending>l&&(e.adler=F(e.adler,r.pending_buf,r.pending-l,l)),_e(e),0!==r.pending)return r.last_flush=-1,X;l=0}u=r.gzindex<r.gzhead.name.length?255&r.gzhead.name.charCodeAt(r.gzindex++):0,Te(r,u)}while(0!==u);r.gzhead.hcrc&&r.pending>l&&(e.adler=F(e.adler,r.pending_buf,r.pending-l,l)),r.gzindex=0}r.status=91}if(91===r.status){if(r.gzhead.comment){var d,p=r.pending;do{if(r.pending===r.pending_buf_size){if(r.gzhead.hcrc&&r.pending>p&&(e.adler=F(e.adler,r.pending_buf,r.pending-p,p)),_e(e),0!==r.pending)return r.last_flush=-1,X;p=0}d=r.gzindex<r.gzhead.comment.length?255&r.gzhead.comment.charCodeAt(r.gzindex++):0,Te(r,d)}while(0!==d);r.gzhead.hcrc&&r.pending>p&&(e.adler=F(e.adler,r.pending_buf,r.pending-p,p))}r.status=103}if(103===r.status){if(r.gzhead.hcrc){if(r.pending+2>r.pending_buf_size&&(_e(e),0!==r.pending))return r.last_flush=-1,X;Te(r,255&e.adler),Te(r,e.adler>>8&255),e.adler=0}if(r.status=he,_e(e),0!==r.pending)return r.last_flush=-1,X}if(0!==e.avail_in||0!==r.lookahead||t!==Y&&r.status!==ge){var f=0===r.level?we(r,t):r.strategy===ae?function(e,t){for(var r;;){if(0===e.lookahead&&(Pe(e),0===e.lookahead)){if(t===Y)return 1;break}if(e.match_length=0,r=K(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,r&&(Ee(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===Q?(Ee(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(Ee(e,!1),0===e.strm.avail_out)?1:2}(r,t):r.strategy===se?function(e,t){for(var r,n,i,o,a=e.window;;){if(e.lookahead<=de){if(Pe(e),e.lookahead<=de&&t===Y)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=3&&e.strstart>0&&(n=a[i=e.strstart-1])===a[++i]&&n===a[++i]&&n===a[++i]){o=e.strstart+de;do{}while(n===a[++i]&&n===a[++i]&&n===a[++i]&&n===a[++i]&&n===a[++i]&&n===a[++i]&&n===a[++i]&&n===a[++i]&&i<o);e.match_length=de-(o-i),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=3?(r=K(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(r=K(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),r&&(Ee(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===Q?(Ee(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(Ee(e,!1),0===e.strm.avail_out)?1:2}(r,t):Me[r.level].func(r,t);if(3!==f&&4!==f||(r.status=ge),1===f||3===f)return 0===e.avail_out&&(r.last_flush=-1),X;if(2===f&&(t===J?W(r):t!==Z&&(H(r,0,0,!1),t===z&&(ye(r.head),0===r.lookahead&&(r.strstart=0,r.block_start=0,r.insert=0))),_e(e),0===e.avail_out))return r.last_flush=-1,X}return t!==Q?X:r.wrap<=0?ee:(2===r.wrap?(Te(r,255&e.adler),Te(r,e.adler>>8&255),Te(r,e.adler>>16&255),Te(r,e.adler>>24&255),Te(r,255&e.total_in),Te(r,e.total_in>>8&255),Te(r,e.total_in>>16&255),Te(r,e.total_in>>24&255)):(Re(r,e.adler>>>16),Re(r,65535&e.adler)),_e(e),r.wrap>0&&(r.wrap=-r.wrap),0!==r.pending?X:ee)},Ve=function(e){if(De(e))return te;var t=e.state.status;return e.state=null,t===he?me(e,re):X},Ge=function(e,t){var r=t.length;if(De(e))return te;var n=e.state,i=n.wrap;if(2===i||1===i&&n.status!==fe||n.lookahead)return te;if(1===i&&(e.adler=$(e.adler,t,r,0)),n.wrap=0,r>=n.w_size){0===i&&(ye(n.head),n.strstart=0,n.block_start=0,n.insert=0);var o=new Uint8Array(n.w_size);o.set(t.subarray(r-n.w_size,r),0),t=o,r=n.w_size}var a=e.avail_in,s=e.next_in,c=e.input;for(e.avail_in=r,e.next_in=0,e.input=t,Pe(n);n.lookahead>=3;){var u=n.strstart,l=n.lookahead-2;do{n.ins_h=Se(n,n.ins_h,n.window[u+3-1]),n.prev[u&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=u,u++}while(--l);n.strstart=u,n.lookahead=2,Pe(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,e.next_in=s,e.input=c,e.avail_in=a,n.wrap=i,X};function Be(e){return Be="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Be(e)}var He=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)};try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){}for(var qe=new Uint8Array(256),Ke=0;Ke<256;Ke++)qe[Ke]=Ke>=252?6:Ke>=248?5:Ke>=240?4:Ke>=224?3:Ke>=192?2:1;qe[254]=qe[254]=1;var We=function(e){if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(e);var t,r,n,i,o,a=e.length,s=0;for(i=0;i<a;i++)55296==(64512&(r=e.charCodeAt(i)))&&i+1<a&&56320==(64512&(n=e.charCodeAt(i+1)))&&(r=65536+(r-55296<<10)+(n-56320),i++),s+=r<128?1:r<2048?2:r<65536?3:4;for(t=new Uint8Array(s),o=0,i=0;o<s;i++)55296==(64512&(r=e.charCodeAt(i)))&&i+1<a&&56320==(64512&(n=e.charCodeAt(i+1)))&&(r=65536+(r-55296<<10)+(n-56320),i++),r<128?t[o++]=r:r<2048?(t[o++]=192|r>>>6,t[o++]=128|63&r):r<65536?(t[o++]=224|r>>>12,t[o++]=128|r>>>6&63,t[o++]=128|63&r):(t[o++]=240|r>>>18,t[o++]=128|r>>>12&63,t[o++]=128|r>>>6&63,t[o++]=128|63&r);return t},Ye=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},Je=Object.prototype.toString,ze=G.Z_NO_FLUSH,Qe=G.Z_SYNC_FLUSH,Ze=G.Z_FULL_FLUSH,Xe=G.Z_FINISH,et=G.Z_OK,tt=G.Z_STREAM_END,rt=G.Z_DEFAULT_COMPRESSION,nt=G.Z_DEFAULT_STRATEGY,it=G.Z_DEFLATED;function ot(e){this.options=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var r=t.shift();if(r){if("object"!==Be(r))throw new TypeError(r+"must be non-object");for(var n in r)He(r,n)&&(e[n]=r[n])}}return e}({level:rt,method:it,chunkSize:16384,windowBits:15,memLevel:8,strategy:nt},e||{});var t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Ye,this.strm.avail_out=0;var r=$e(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(r!==et)throw new Error(V[r]);if(t.header&&Ue(this.strm,t.header),t.dictionary){var n;if(n="string"==typeof t.dictionary?We(t.dictionary):"[object ArrayBuffer]"===Je.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,(r=Ge(this.strm,n))!==et)throw new Error(V[r]);this._dict_set=!0}}function at(e,t){var r=new ot(t);if(r.push(e,!0),r.err)throw r.msg||V[r.err];return r.result}ot.prototype.push=function(e,t){var r,n,i=this.strm,o=this.options.chunkSize;if(this.ended)return!1;for(n=t===~~t?t:!0===t?Xe:ze,"string"==typeof e?i.input=We(e):"[object ArrayBuffer]"===Je.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;;)if(0===i.avail_out&&(i.output=new Uint8Array(o),i.next_out=0,i.avail_out=o),(n===Qe||n===Ze)&&i.avail_out<=6)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else{if((r=Fe(i,n))===tt)return i.next_out>0&&this.onData(i.output.subarray(0,i.next_out)),r=Ve(this.strm),this.onEnd(r),this.ended=!0,r===et;if(0!==i.avail_out){if(n>0&&i.next_out>0)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else if(0===i.avail_in)break}else this.onData(i.output)}return!0},ot.prototype.onData=function(e){this.chunks.push(e)},ot.prototype.onEnd=function(e){e===et&&(this.result=function(e){for(var t=0,r=0,n=e.length;r<n;r++)t+=e[r].length;for(var i=new Uint8Array(t),o=0,a=0,s=e.length;o<s;o++){var c=e[o];i.set(c,a),a+=c.length}return i}(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var st=ot,ct=at,ut=function(e,t){return(t=t||{}).raw=!0,at(e,t)},lt=function(e,t){return(t=t||{}).gzip=!0,at(e,t)},dt=G,pt={Deflate:st,deflate:ct,deflateRaw:ut,gzip:lt,constants:dt};e.Deflate=st,e.constants=dt,e.default=pt,e.deflate=ct,e.deflateRaw=ut,e.gzip=lt,Object.defineProperty(e,"__esModule",{value:!0})}(pakoDeflate.exports);var pakoDeflateExports=pakoDeflate.exports,pako=getDefaultExportFromCjs(pakoDeflateExports),SLS_PROTO={nested:{sls:{nested:{Log:{fields:{Time:{rule:"required",type:"uint32",id:1},Contents:{rule:"repeated",type:"Content",id:2}},nested:{Content:{fields:{Key:{rule:"required",type:"string",id:1},Value:{rule:"required",type:"string",id:2}}}}},LogTag:{fields:{Key:{rule:"required",type:"string",id:1},Value:{rule:"required",type:"string",id:2}}},LogGroup:{fields:{Logs:{rule:"repeated",type:"Log",id:1},Reserved:{type:"string",id:2},Topic:{type:"string",id:3},Source:{type:"string",id:4},LogTags:{rule:"repeated",type:"LogTag",id:6}}},LogGroupList:{fields:{logGroupList:{rule:"repeated",type:"LogGroup",id:1}}}}}}},md5$1={exports:{}},core={exports:{}},_nodeResolve_empty={},_nodeResolve_empty$1=Object.freeze({__proto__:null,default:_nodeResolve_empty}),require$$0=getAugmentedNamespace(_nodeResolve_empty$1),hasRequiredCore,CryptoJS;function requireCore(){return hasRequiredCore||(hasRequiredCore=1,core.exports=(e=e||function(e){var t;if("undefined"!=typeof window&&window.crypto&&(t=window.crypto),"undefined"!=typeof self&&self.crypto&&(t=self.crypto),"undefined"!=typeof globalThis&&globalThis.crypto&&(t=globalThis.crypto),!t&&"undefined"!=typeof window&&window.msCrypto&&(t=window.msCrypto),!t&&void 0!==commonjsGlobal&&commonjsGlobal.crypto&&(t=commonjsGlobal.crypto),!t&&"function"==typeof commonjsRequire)try{t=require$$0}catch(e){}var r=function(){if(t){if("function"==typeof t.getRandomValues)try{return t.getRandomValues(new Uint32Array(1))[0]}catch(e){}if("function"==typeof t.randomBytes)try{return t.randomBytes(4).readInt32LE()}catch(e){}}throw new Error("Native crypto module could not be used to get secure random number.")},n=Object.create||function(){function e(){}return function(t){var r;return e.prototype=t,r=new e,e.prototype=null,r}}(),i={},o=i.lib={},a=o.Base={extend:function(e){var t=n(this);return e&&t.mixIn(e),t.hasOwnProperty("init")&&this.init!==t.init||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},s=o.WordArray=a.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||u).stringify(this)},concat:function(e){var t=this.words,r=e.words,n=this.sigBytes,i=e.sigBytes;if(this.clamp(),n%4)for(var o=0;o<i;o++){var a=r[o>>>2]>>>24-o%4*8&255;t[n+o>>>2]|=a<<24-(n+o)%4*8}else for(var s=0;s<i;s+=4)t[n+s>>>2]=r[s>>>2];return this.sigBytes+=i,this},clamp:function(){var t=this.words,r=this.sigBytes;t[r>>>2]&=4294967295<<32-r%4*8,t.length=e.ceil(r/4)},clone:function(){var e=a.clone.call(this);return e.words=this.words.slice(0),e},random:function(e){for(var t=[],n=0;n<e;n+=4)t.push(r());return new s.init(t,e)}}),c=i.enc={},u=c.Hex={stringify:function(e){for(var t=e.words,r=e.sigBytes,n=[],i=0;i<r;i++){var o=t[i>>>2]>>>24-i%4*8&255;n.push((o>>>4).toString(16)),n.push((15&o).toString(16))}return n.join("")},parse:function(e){for(var t=e.length,r=[],n=0;n<t;n+=2)r[n>>>3]|=parseInt(e.substr(n,2),16)<<24-n%8*4;return new s.init(r,t/2)}},l=c.Latin1={stringify:function(e){for(var t=e.words,r=e.sigBytes,n=[],i=0;i<r;i++){var o=t[i>>>2]>>>24-i%4*8&255;n.push(String.fromCharCode(o))}return n.join("")},parse:function(e){for(var t=e.length,r=[],n=0;n<t;n++)r[n>>>2]|=(255&e.charCodeAt(n))<<24-n%4*8;return new s.init(r,t)}},d=c.Utf8={stringify:function(e){try{return decodeURIComponent(escape(l.stringify(e)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(e){return l.parse(unescape(encodeURIComponent(e)))}},p=o.BufferedBlockAlgorithm=a.extend({reset:function(){this._data=new s.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=d.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var r,n=this._data,i=n.words,o=n.sigBytes,a=this.blockSize,c=o/(4*a),u=(c=t?e.ceil(c):e.max((0|c)-this._minBufferSize,0))*a,l=e.min(4*u,o);if(u){for(var d=0;d<u;d+=a)this._doProcessBlock(i,d);r=i.splice(0,u),n.sigBytes-=l}return new s.init(r,l)},clone:function(){var e=a.clone.call(this);return e._data=this._data.clone(),e},_minBufferSize:0});o.Hasher=p.extend({cfg:a.extend(),init:function(e){this.cfg=this.cfg.extend(e),this.reset()},reset:function(){p.reset.call(this),this._doReset()},update:function(e){return this._append(e),this._process(),this},finalize:function(e){return e&&this._append(e),this._doFinalize()},blockSize:16,_createHelper:function(e){return function(t,r){return new e.init(r).finalize(t)}},_createHmacHelper:function(e){return function(t,r){return new f.HMAC.init(e,r).finalize(t)}}});var f=i.algo={};return i}(Math),e)),core.exports;var e}md5$1.exports=(CryptoJS=requireCore(),function(e){var t=CryptoJS,r=t.lib,n=r.WordArray,i=r.Hasher,o=t.algo,a=[];!function(){for(var t=0;t<64;t++)a[t]=4294967296*e.abs(e.sin(t+1))|0}();var s=o.MD5=i.extend({_doReset:function(){this._hash=new n.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(e,t){for(var r=0;r<16;r++){var n=t+r,i=e[n];e[n]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8)}var o=this._hash.words,s=e[t+0],p=e[t+1],f=e[t+2],h=e[t+3],g=e[t+4],m=e[t+5],v=e[t+6],y=e[t+7],b=e[t+8],S=e[t+9],_=e[t+10],E=e[t+11],T=e[t+12],R=e[t+13],C=e[t+14],k=e[t+15],P=o[0],w=o[1],O=o[2],I=o[3];P=c(P,w,O,I,s,7,a[0]),I=c(I,P,w,O,p,12,a[1]),O=c(O,I,P,w,f,17,a[2]),w=c(w,O,I,P,h,22,a[3]),P=c(P,w,O,I,g,7,a[4]),I=c(I,P,w,O,m,12,a[5]),O=c(O,I,P,w,v,17,a[6]),w=c(w,O,I,P,y,22,a[7]),P=c(P,w,O,I,b,7,a[8]),I=c(I,P,w,O,S,12,a[9]),O=c(O,I,P,w,_,17,a[10]),w=c(w,O,I,P,E,22,a[11]),P=c(P,w,O,I,T,7,a[12]),I=c(I,P,w,O,R,12,a[13]),O=c(O,I,P,w,C,17,a[14]),P=u(P,w=c(w,O,I,P,k,22,a[15]),O,I,p,5,a[16]),I=u(I,P,w,O,v,9,a[17]),O=u(O,I,P,w,E,14,a[18]),w=u(w,O,I,P,s,20,a[19]),P=u(P,w,O,I,m,5,a[20]),I=u(I,P,w,O,_,9,a[21]),O=u(O,I,P,w,k,14,a[22]),w=u(w,O,I,P,g,20,a[23]),P=u(P,w,O,I,S,5,a[24]),I=u(I,P,w,O,C,9,a[25]),O=u(O,I,P,w,h,14,a[26]),w=u(w,O,I,P,b,20,a[27]),P=u(P,w,O,I,R,5,a[28]),I=u(I,P,w,O,f,9,a[29]),O=u(O,I,P,w,y,14,a[30]),P=l(P,w=u(w,O,I,P,T,20,a[31]),O,I,m,4,a[32]),I=l(I,P,w,O,b,11,a[33]),O=l(O,I,P,w,E,16,a[34]),w=l(w,O,I,P,C,23,a[35]),P=l(P,w,O,I,p,4,a[36]),I=l(I,P,w,O,g,11,a[37]),O=l(O,I,P,w,y,16,a[38]),w=l(w,O,I,P,_,23,a[39]),P=l(P,w,O,I,R,4,a[40]),I=l(I,P,w,O,s,11,a[41]),O=l(O,I,P,w,h,16,a[42]),w=l(w,O,I,P,v,23,a[43]),P=l(P,w,O,I,S,4,a[44]),I=l(I,P,w,O,T,11,a[45]),O=l(O,I,P,w,k,16,a[46]),P=d(P,w=l(w,O,I,P,f,23,a[47]),O,I,s,6,a[48]),I=d(I,P,w,O,y,10,a[49]),O=d(O,I,P,w,C,15,a[50]),w=d(w,O,I,P,m,21,a[51]),P=d(P,w,O,I,T,6,a[52]),I=d(I,P,w,O,h,10,a[53]),O=d(O,I,P,w,_,15,a[54]),w=d(w,O,I,P,p,21,a[55]),P=d(P,w,O,I,b,6,a[56]),I=d(I,P,w,O,k,10,a[57]),O=d(O,I,P,w,v,15,a[58]),w=d(w,O,I,P,R,21,a[59]),P=d(P,w,O,I,g,6,a[60]),I=d(I,P,w,O,E,10,a[61]),O=d(O,I,P,w,f,15,a[62]),w=d(w,O,I,P,S,21,a[63]),o[0]=o[0]+P|0,o[1]=o[1]+w|0,o[2]=o[2]+O|0,o[3]=o[3]+I|0},_doFinalize:function(){var t=this._data,r=t.words,n=8*this._nDataBytes,i=8*t.sigBytes;r[i>>>5]|=128<<24-i%32;var o=e.floor(n/4294967296),a=n;r[15+(i+64>>>9<<4)]=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8),r[14+(i+64>>>9<<4)]=16711935&(a<<8|a>>>24)|4278255360&(a<<24|a>>>8),t.sigBytes=4*(r.length+1),this._process();for(var s=this._hash,c=s.words,u=0;u<4;u++){var l=c[u];c[u]=16711935&(l<<8|l>>>24)|4278255360&(l<<24|l>>>8)}return s},clone:function(){var e=i.clone.call(this);return e._hash=this._hash.clone(),e}});function c(e,t,r,n,i,o,a){var s=e+(t&r|~t&n)+i+a;return(s<<o|s>>>32-o)+t}function u(e,t,r,n,i,o,a){var s=e+(t&n|r&~n)+i+a;return(s<<o|s>>>32-o)+t}function l(e,t,r,n,i,o,a){var s=e+(t^r^n)+i+a;return(s<<o|s>>>32-o)+t}function d(e,t,r,n,i,o,a){var s=e+(r^(t|~n))+i+a;return(s<<o|s>>>32-o)+t}t.MD5=i._createHelper(s),t.HmacMD5=i._createHmacHelper(s)}(Math),CryptoJS.MD5);var md5Exports=md5$1.exports,md5=getDefaultExportFromCjs(md5Exports),libTypedarrays={exports:{}};libTypedarrays.exports=function(e){return function(){if("function"==typeof ArrayBuffer){var t=e.lib.WordArray,r=t.init,n=t.init=function(e){if(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),(e instanceof Int8Array||"undefined"!=typeof Uint8ClampedArray&&e instanceof Uint8ClampedArray||e instanceof Int16Array||e instanceof Uint16Array||e instanceof Int32Array||e instanceof Uint32Array||e instanceof Float32Array||e instanceof Float64Array)&&(e=new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),e instanceof Uint8Array){for(var t=e.byteLength,n=[],i=0;i<t;i++)n[i>>>2]|=e[i]<<24-i%4*8;r.call(this,n,t)}else r.apply(this,arguments)};n.prototype=t}}(),e.lib.WordArray}(requireCore());var libTypedarraysExports=libTypedarrays.exports,WordArray=getDefaultExportFromCjs(libTypedarraysExports),builder=getProtobufRoot(SLS_PROTO),LogContentProto=builder.lookupType("sls.Log.Content"),LogGroupProto=builder.lookupType("sls.LogGroup"),encoder=new TextEncoder,getCanonicalizedHeaders=function(e){for(var t=Object.keys(e),r=[],n=0;n<t.length;n++){var i=t[n];(i.startsWith("x-log-")||i.startsWith("x-acs-"))&&r.push(i)}r.sort();for(var o="",a=0;a<r.length;a++){var s=r[a];o+="".concat(s,":").concat(String(e[s]).trim(),"\n")}return o},getCanonicalizedResource=function(e,t){for(var r="".concat(e),n=Object.keys(t),i=new Array(n.length),o=0;o<n.length;o++){var a=n[o];i[o]="".concat(a,"=").concat(t[a]||"")}i.sort();var s=i.join("&");return s&&(r+="?".concat(s)),r},sign=function(){var e=_asyncToGenerator(_regeneratorRuntime.mark(function e(t,r,n,i){var o,a,s,c,u,l,d,p,f,h,g;return _regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return o=n["Content-MD5"]||"",a=n["Content-Type"]||"",s=n.Date,c=getCanonicalizedHeaders(n),u=getCanonicalizedResource(t,r),l=encoder.encode(["POST",o,a,s,"".concat(c).concat(u)].join("\n")),e.next=1,window.crypto.subtle.importKey("raw",encoder.encode(i.credentials.accessKeySecret),{name:"HMAC",hash:"SHA-1"},!1,["sign"]);case 1:return d=e.sent,h=Uint8Array,e.next=2,window.crypto.subtle.sign("HMAC",d,l);case 2:return g=e.sent,p=new h(g),f=window.btoa(String.fromCharCode.apply(String,_toConsumableArray$1(p))),e.abrupt("return","LOG ".concat(i.credentials.accessKeyId,":").concat(f));case 3:case"end":return e.stop()}},e)}));return function(t,r,n,i){return e.apply(this,arguments)}}(),postLog=function(){var e=_asyncToGenerator(_regeneratorRuntime.mark(function e(t,r,n,i){var o,a,s,c,u,l,d,p,f,h,g;return _regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return o=t.logstore,a=t.project,s=t.endpoint,c=t.credentials,u="/logstores/".concat(o,"/shards/lb"),l=a?a+".":"",d=(r?"?".concat(new URLSearchParams(r)):"").replace(/\?$/,""),p=window.location.href.indexOf("file://")>-1?"http://":"//",f="".concat(p).concat(l).concat(s.replace(/https?:\/\//,"")).concat(u).concat(d),h=new Date(getTime()).toUTCString(),g={"Content-Type":"application/x-protobuf","x-log-compresstype":"deflate","x-log-bodyrawsize":i,Date:h,Host:"".concat(l).concat(s),"x-log-apiversion":"0.6.0","x-log-signaturemethod":"hmac-sha1",Authorization:"","x-acs-security-token":c.securityToken},n&&(g["Content-MD5"]=md5(WordArray.create(n)).toString().toUpperCase(),g["Content-Length"]=n.length),e.next=1,sign(u,r,g,t);case 1:return g.Authorization=e.sent,g["x-log-date"]=h,e.abrupt("return",{url:f,param:{method:"POST",body:n,headers:g}});case 2:case"end":return e.stop()}},e)}));return function(t,r,n,i){return e.apply(this,arguments)}}(),getUploadParam=function(){var e=_asyncToGenerator(_regeneratorRuntime.mark(function e(t,r){var n,i,o,a,s,c,u;return _regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(i=parseInt(String(getTime()).substr(0,10)),o={Logs:[],Topic:"Event Track"},t.forEach(function(e){o.Logs.push({Time:i,Contents:Object.keys(e).map(function(t){var r={Key:t,Value:String(e[t])},n=LogContentProto.verify(r);if(n)throw n;return r})})}),!(n=LogGroupProto.verify(o))){e.next=1;break}throw new Error(n);case 1:return a=LogGroupProto.create(o),s=LogGroupProto.encode(a).finish(),c=pako.deflate(s),u=s.byteLength,e.next=2,postLog(r,{},c,u);case 2:return e.abrupt("return",e.sent);case 3:case"end":return e.stop()}},e)}));return function(t,r){return e.apply(this,arguments)}}(),_excute=function(e,t,r){return new Promise(function(n,i){fetch(e,t).then(n).catch(function(n){++r<=3?setTimeout(function(){_excute(e,t,r)},500*(r+1)):i(n)})})},post=function(){var e=_asyncToGenerator(_regeneratorRuntime.mark(function e(t,r){var n,i,o;return _regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(t.length){e.next=1;break}return e.abrupt("return");case 1:return e.next=2,getUploadParam(t,r);case 2:return n=e.sent,i=n.url,o=n.param,e.abrupt("return",_excute(i,o,0));case 3:case"end":return e.stop()}},e)}));return function(t,r){return e.apply(this,arguments)}}(),UPLOADTIMER=5e3,UPLOADITEMMAX=10,SlsClient=_createClass(function e(t,r){var n=this;_classCallCheck(this,e),Object.defineProperty(this,"logService",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"statsCache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tokenManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"eventTriggedTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cycleStatsTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cycleStatsInterval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"eventTriggedInterval",{enumerable:!0,configurable:!0,writable:!0,value:void 0});var i=t.securityToken,o=t.logService,a=t.cycleStatsConfig;this.logService=o,this.cache=[],this.statsCache=[],this.cycleStatsInterval=a.uploadIntervalMs||UPLOAD_LOG_INTERVAL,this.eventTriggedInterval=UPLOADTIMER,this.tokenManager=new STSTokenManager(i,r,this.logService.credentials),this.tokenManager.on("update",function(e){n.logService=e}),this.upload(!1,"eventTrigged"),this.cycleStatsTimer=addTimer(function(){n.upload(!0,"cycleStats")},this.cycleStatsInterval,"interval"),this.eventTriggedTimer=addTimer(function(){n.upload(!1,"eventTrigged")},this.eventTriggedInterval,"interval")},[{key:"securityToken",get:function(){var e;return null===(e=this.tokenManager)||void 0===e||null===(e=e.securityToken)||void 0===e?void 0:e.securityToken}},{key:"stopUpdateToken",value:function(){this.tokenManager.stopUpdateToken()}},{key:"send",value:function(e){var t=e.cycleStats;delete e.serverDiffTime,t?(delete e.cycleStats,this.sendStats(e)):this.cache.push(e)}},{key:"sendStats",value:function(e){this.statsCache.push(e)}},{key:"flush",value:function(){this.upload(!0,"eventTrigged"),this.upload(!0,"cycleStats")}},{key:"upload",value:function(){var e;return e="eventTrigged"===(arguments.length>1&&void 0!==arguments[1]?arguments[1]:"eventTrigged")?arguments.length>0&&void 0!==arguments[0]&&arguments[0]?this.cache.splice(0):this.cache.splice(0,UPLOADITEMMAX):this.statsCache.splice(0),post(e,this.logService)}},{key:"clear",value:function(){this.eventTriggedTimer&&(removeTimer(this.eventTriggedTimer,"interval"),this.eventTriggedTimer=null),this.cycleStatsTimer&&(removeTimer(this.cycleStatsTimer,"interval"),this.cycleStatsTimer=null)}}]),Logging=_createClass(function e(){_classCallCheck(this,e),Object.defineProperty(this,"commonInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"buffer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"slsClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.buffer=[],this.slsClient=null,this.commonInfo={udid:Environment.deviceId,tabId:Environment.browserTabId}},[{key:"updateCommonInfo",value:function(e){this.commonInfo=Object.assign({},this.commonInfo,e)}},{key:"start",value:function(e){this.slsClient=new SlsClient(e,this.commonInfo),this.flushLogBuffer()}},{key:"stop",value:function(){var e,t;this.flushLogBuffer(),null===(e=this.slsClient)||void 0===e||e.stopUpdateToken(),null===(t=this.slsClient)||void 0===t||t.clear()}},{key:"send",value:function(e){var t=new Date(getTime());e.date=t.getTime(),e.timeStr="".concat(t.toLocaleString(),":").concat(t.getMilliseconds()),e.acs=Environment.networkType||"unknown",this.commonInfo.apid?(this.realSend(e),this.buffer.length&&this.flushLogBuffer()):this.buffer.push(e)}},{key:"flushLogBuffer",value:function(){var e=this;this.buffer.length&&this.slsClient&&this.buffer.splice(0).forEach(function(t){e.realSend(t)}),this.slsClient&&this.slsClient.flush()}},{key:"realSend",value:function(e){var t=Object.assign({},this.commonInfo,e);this.slsClient&&this.slsClient.send(t)}}]);function ownKeys$1$1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function _objectSpread$1$1(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$1$1(Object(r),!0).forEach(function(t){_defineProperty$1(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$1$1(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}var WebTrackingClient=_createClass(function e(t){_classCallCheck(this,e),Object.defineProperty(this,"commonInfo",{enumerable:!0,configurable:!0,writable:!0,value:{}}),this.commonInfo=Object.assign({},this.commonInfo,t)},[{key:"updateCommonInfo",value:function(e){this.commonInfo=Object.assign({},this.commonInfo,e)}},{key:"gslbAccess",value:function(e,t){this.send({event:"gslbAccess",success:e,message:t})}},{key:"send",value:function(e){var t=new Date(getTime());e.date=t.getTime(),e.timeStr="".concat(t.toLocaleString(),":").concat(t.getMilliseconds());var r=_objectSpread$1$1(_objectSpread$1$1({},this.commonInfo),{},{tm:e.date},e);(new Image).src="".concat(BaseWebTrackingURL,"&").concat(new URLSearchParams(r))}}]);function ownKeys$b(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function _objectSpread$b(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$b(Object(r),!0).forEach(function(t){_defineProperty$1(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$b(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}var SLSSender=_createClass(function e(){_classCallCheck(this,e),Object.defineProperty(this,"logging",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"statsConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"started",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.logging=new Logging},[{key:"start",value:function(e){var t=e.cycleStatsConfig;this.logging.start(e),this.statsConfig=t,this.started=!0}},{key:"stop",value:function(){this.logging.stop(),this.started=!1}},{key:"securityToken",get:function(){var e;return null===(e=this.logging)||void 0===e||null===(e=e.slsClient)||void 0===e?void 0:e.securityToken}},{key:"updateSecurityToken",value:function(e){var t;return null===(t=this.logging)||void 0===t?void 0:t.slsClient.tokenManager.updateSecurityToken(e)}},{key:"sendMetric",value:function(e){return this.logging.send(_objectSpread$b(_objectSpread$b({},e),{},{cycleStats:!0}))}},{key:"sendEvent",value:function(e){return this.logging.send(_objectSpread$b({},e))}},{key:"exception",value:function(e){this.logging.send(_objectSpread$b(_objectSpread$b({},TraceEvent$1.EXCEPTION),{},{code:e.code,message:e.message,name:e.name}))}}]),MAX_LOG_COUNT=5e3,ONE_FLUSH_LIMIT=500,ONE_FLUSH_CHAR_COUNT_LIMIT=5e5,LOG_LEVEL_NUM={debug:1,info:10,warn:20,error:30,none:99},Logger=function(){function e(){var t,r=this,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";_classCallCheck(this,e),Object.defineProperty(this,"logBuffer",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"metricBuffer",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"envInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"isFlushing",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"logSendFunction",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"afterPrinter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"loggerPrefix",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"flushLog",{enumerable:!0,configurable:!0,writable:!0,value:(t=_asyncToGenerator(_regeneratorRuntime.mark(function e(){var t,n,i,o,a;return _regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(!r.logBuffer.length||r.isFlushing){e.next=2;break}if(r.isFlushing=!0,t=r.logBuffer.length,r.logBuffer.length>ONE_FLUSH_LIMIT&&(t=ONE_FLUSH_LIMIT),r.logSendFunction){e.next=1;break}return r.isFlushing=!1,e.abrupt("return",Promise.reject("no log sender"));case 1:for(n=r.logBuffer.slice(0,t),i=n.map(function(e){return JSON.stringify(e)}),o=i.length?i.reduce(function(e,t){return e+t.length},0):0;o>ONE_FLUSH_CHAR_COUNT_LIMIT&&n.length>=2;)n=n.slice(0,n.length/2),i=n.map(function(e){return JSON.stringify(e)}),o=i.length?i.reduce(function(e,t){return e+t.length},0):0;return o>ONE_FLUSH_CHAR_COUNT_LIMIT&&(console.error("error: truncated logs for flushing log size is too large",n),i=["error: truncated logs for flushing log size is too large"]),a=r.logSendFunction,e.abrupt("return",a(i).then(function(e){e&&e.success&&r.logBuffer.splice(0,t)}).catch(function(e){console.warn("caught flushLogs error",e)}).finally(function(){r.isFlushing=!1}));case 2:return e.abrupt("return",Promise.resolve());case 3:case"end":return e.stop()}},e)})),function(){return t.apply(this,arguments)})}),this.loggerPrefix=n}return _createClass(e,[{key:"getLogger",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",n=function(){var e=_asyncToGenerator(_regeneratorRuntime.mark(function e(){return _regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return");case 1:case"end":return e.stop()}},e)}));return function(){return e.apply(this,arguments)}}(),i={debug:n,info:n,warn:n,error:n};return["debug","info","warn","error"].forEach(function(n){return i[n]=t.log(n,"".concat(e,":"),r)}),i}},{key:"pushToMetricBuffer",value:function(e){this.metricBuffer.length>=MAX_LOG_COUNT?console.error("drop metric for log buffer is full: ",e):this.metricBuffer.push(e)}},{key:"pushToLogBuffer",value:function(e){this.logBuffer.length>=MAX_LOG_COUNT?console.error("drop log for log buffer is full: ",e):this.logBuffer.push(e)}},{key:"log",value:function(t){for(var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.loggerPrefix,i=arguments.length,o=new Array(i>2?i-2:0),a=2;a<i;a++)o[a-2]=arguments[a];var s=[formatToBeijingTime(new Date(getTime())),t.toLocaleUpperCase(),n].concat(o),c=this.stringifyArgs(s);"none"!==t&&LOG_LEVEL_NUM[t]>=e.levelThreshold&&Function.apply.call(console[t],console,[c]),null===(r=this.afterPrinter)||void 0===r||r.call(this,c),this.logSendFunction&&this.pushToLogBuffer(c)}},{key:"stringifyArgs",value:function(e){var t=_toConsumableArray$1(e).map(function(e){var t=e;return"string"!=typeof e&&(t=tryJsonStringify(e)),t}).join(" ");return"".concat(t)}},{key:"debug",value:function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return this.log.apply(this,["debug",void 0,""].concat(t))}},{key:"info",value:function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return this.log.apply(this,["info",void 0,""].concat(t))}},{key:"warn",value:function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return this.log.apply(this,["warn",void 0,""].concat(t))}},{key:"error",value:function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return this.log.apply(this,["error",void 0,""].concat(t))}},{key:"injectLogSender",value:function(e){this.logSendFunction=e}},{key:"injectLogPrint",value:function(e){this.afterPrinter=e}}],[{key:"setLogLevel",value:function(t){e.levelThreshold=LOG_LEVEL_NUM[t]}}])}();Object.defineProperty(Logger,"levelThreshold",{enumerable:!0,configurable:!0,writable:!0,value:LOG_LEVEL_NUM.warn});var getAndIncLogSeq=function(){return Reporter._dingrtc_log_seq++},Reporter=_createClass(function e(){var t=this,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";_classCallCheck(this,e),Object.defineProperty(this,"trace",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metric",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"log",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sender",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webtracking",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"commonInfo",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"getLoggerWithPrefix",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var r={debug:function(){for(var r,n=arguments.length,i=new Array(n),o=0;o<n;o++)i[o]=arguments[o];return(r=t.log).debug.apply(r,[e].concat(i))},info:function(){for(var r,n=arguments.length,i=new Array(n),o=0;o<n;o++)i[o]=arguments[o];return(r=t.log).info.apply(r,[e].concat(i))},warn:function(){for(var r,n=arguments.length,i=new Array(n),o=0;o<n;o++)i[o]=arguments[o];return(r=t.log).warn.apply(r,[e].concat(i))},error:function(){for(var r,n=arguments.length,i=new Array(n),o=0;o<n;o++)i[o]=arguments[o];return(r=t.log).error.apply(r,[e].concat(i))}};return r}}),this.commonInfo={bt:Environment.browserType,bv:Environment.browserVersion,osn:Environment.system,osv:Environment.systemVersion,udid:Environment.deviceId,tabId:Environment.browserTabId},this.sender=new SLSSender,this.webtracking=new WebTrackingClient(this.commonInfo),this.trace=new Trace(this.webtracking,this.sender),this.metric=new Metric(this.sender),this.log=new Logger,this.setId(r),this.log.injectLogPrint(function(e){t.trace.simpleLogger(e)})},[{key:"setId",value:function(e){this.id=e,this.log.loggerPrefix="clientId ".concat(this.id)}},{key:"securityToken",get:function(){return this.sender.securityToken}},{key:"statsConfig",get:function(){return this.sender.statsConfig}},{key:"updateCommonInfo",value:function(e){this.commonInfo=Object.assign({},this.commonInfo,e),this.webtracking.updateCommonInfo(this.commonInfo),this.sender.logging.updateCommonInfo(this.commonInfo),e.serverDiffTime&&setDiffTime(e.serverDiffTime)}},{key:"updateSecurityToken",value:function(e){this.sender.updateSecurityToken(e)}},{key:"start",value:function(e){this.sender.start(e)}},{key:"stop",value:function(){this.sender.stop()}}]);Object.defineProperty(Reporter,"_dingrtc_log_seq",{enumerable:!0,configurable:!0,writable:!0,value:0});var clientIdToReportMap=new Map,defaultReport,registerReporter=function(e){var t;return defaultReport?defaultReport&&!defaultReport.id?(defaultReport.setId(e),t=defaultReport):t=new Reporter(e):t=defaultReport=new Reporter(e),clientIdToReportMap.set(e,t),t},getReporter=function(e){return defaultReport||(defaultReport=new Reporter),defaultReport},setLogLevel=function(e){Logger.setLogLevel(e)},_ErrorCodeAndMsgMap,DeviceErrorDescription={MESSAGE_DEVICENOTFOUND:"Requested device not found",MESSAGE_DEVICENOTALLOWED:"Permission denied",MESSAGE_MACCHROMEDEVICENOTREADABLE:"Permission denied by system",MESSAGE_MACSAFARIDEVICENOTALLOWED:"The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.",MESSAGE_MOBILEDEVICE_NOTALLOWED:"video device not allowed",MESSAGE_AUDIODEVICENOTREADABLE:"Could not start audio source",MESSAGE_VIDEODEVICENOTREADABLE:"Could not start video source",NAME_ABORTEERROR:"AbortError",NAME_INVALIDSTATEERROR:"InvalidStateError",NAME_DEVICENOTALLOWED:"NotAllowedError",NAME_DEVICENOTFOUND:"NotFoundError",NAME_DEVICENOTREADABLE:"NotReadableError",NAME_DEVICEOVERCONSTRAINED:"OverconstrainedError",NAME_INVALID_ACCESS:"InvalidAccessError",NAME_TYPEERROR:"TypeError"},GSLBErrorCode,ErrorCode;!function(e){e.CLIENT_ERROR_INVALID_AUTHORIZATION="invalid authorization",e.CLIENT_ERROR_NOT_FOUND_APP="app not found",e.CLIENT_ERROR_INVALID_APP_STATUS="invalid app status",e.CLIENT_ERROR_MISSING_CHANNEL_NAME="channel missing",e.CLIENT_ERROR_INVALID_TOKEN_TIMESTAMP="invalid token timestamp",e.CLIENT_ERROR_INVALID_APP_ID="invalid appId",e.CLIENT_ERROR_MISSING_REQUEST="request missing",e.CLIENT_ERROR_MISSING_DEVICE_ID="deviceId missing",e.CLIENT_ERROR_MISSING_UA="ua missing",e.CLIENT_ERROR_MISSING_CLIENT_IP="clientIp missing",e.CLIENT_ERROR_INVALID_USER_ID="invalid userId",e.CLIENT_ERROR_MISSING_SERVIC="service missing",e.CLIENT_ERROR_MISSING_TASK_ID="taskId missing",e.CLIENT_ERROR_MISSING_APP_ID="appId missing",e.CLIENT_ERROR_MISSING_USER_ID="userId missing",e.CLIENT_ERROR_MISSING_USER="user missing",e.CLIENT_ERROR_MISSING_CHANNEL_ID="channel missing",e.CLIENT_ERROR_MISSING_PARTICIPANT_ID="participantId missing",e.CLIENT_ERROR_INVALID_REQUEST="invalid request",e.CLIENT_ERROR_NOT_FOUND_GSLB_CHANNEL="gslb channel not found",e.SERVER_ERROR_GSLB_NOT_FOUND_CHANNEL_ID_ERROR="gslb not found channelId error",e.SERVER_ERROR_INTERNAL_ERROR="internal error",e.SERVER_ERROR_MEDIA_ENGINE_ACCESS_ERROR="media-engine access error",e.SERVER_ERROR_MEDIA_ENGINE_SCHEDULE_AND_CREATE_ERROR="media-engine scheduleAndCreate error",e.SERVER_ERROR_SECURITY_TOKEN_NOT_FOUND_ERROR="security token not found error",e.SERVER_ERROR_GSLB_ACCESS_ERROR="gslb access error",e.SERVER_ERROR_GSLB_DISPATCH_ERROR="gslb dispatch error",e.SERVER_ERROR_GSLB_MAPI_ERROR="gslb mapi error"}(GSLBErrorCode||(GSLBErrorCode={})),function(e){e[e.NetworkError=40001]="NetworkError",e[e.JoinTimeout=16908804]="JoinTimeout",e[e.JoinChannelFailed=16974338]="JoinChannelFailed",e[e.CLIENT_ERROR_INVALID_AUTHORIZATION=33620485]="CLIENT_ERROR_INVALID_AUTHORIZATION",e[e.CLIENT_ERROR_NOT_FOUND_APP=33620481]="CLIENT_ERROR_NOT_FOUND_APP",e[e.CLIENT_ERROR_INVALID_APP_STATUS=33620486]="CLIENT_ERROR_INVALID_APP_STATUS",e[e.JoinBadParam=16974081]="JoinBadParam",e[e.CLIENT_ERROR_MISSING_CHANNEL_NAME=16974081]="CLIENT_ERROR_MISSING_CHANNEL_NAME",e[e.CLIENT_ERROR_INVALID_TOKEN_TIMESTAMP=33620483]="CLIENT_ERROR_INVALID_TOKEN_TIMESTAMP",e[e.CLIENT_ERROR_INVALID_APP_ID=33620482]="CLIENT_ERROR_INVALID_APP_ID",e[e.CLIENT_ERROR_MISSING_REQUEST=16974081]="CLIENT_ERROR_MISSING_REQUEST",e[e.CLIENT_ERROR_MISSING_CLIENT_IP=16974081]="CLIENT_ERROR_MISSING_CLIENT_IP",e[e.CLIENT_ERROR_INVALID_USER_ID=33622278]="CLIENT_ERROR_INVALID_USER_ID",e[e.CLIENT_ERROR_MISSING_SERVIC=16974081]="CLIENT_ERROR_MISSING_SERVIC",e[e.CLIENT_ERROR_MISSING_TASK_ID=16974081]="CLIENT_ERROR_MISSING_TASK_ID",e[e.CLIENT_ERROR_MISSING_APP_ID=16974081]="CLIENT_ERROR_MISSING_APP_ID",e[e.CLIENT_ERROR_MISSING_USER_ID=16974081]="CLIENT_ERROR_MISSING_USER_ID",e[e.CLIENT_ERROR_MISSING_USER=16974081]="CLIENT_ERROR_MISSING_USER",e[e.CLIENT_ERROR_MISSING_CHANNEL_ID=16974081]="CLIENT_ERROR_MISSING_CHANNEL_ID",e[e.CLIENT_ERROR_MISSING_PARTICIPANT_ID=16974081]="CLIENT_ERROR_MISSING_PARTICIPANT_ID",e[e.CLIENT_ERROR_INVALID_REQUEST=16974082]="CLIENT_ERROR_INVALID_REQUEST",e[e.CLIENT_ERROR_NOT_FOUND_GSLB_CHANNEL=33620484]="CLIENT_ERROR_NOT_FOUND_GSLB_CHANNEL",e[e.ServerResponseInvalid=16974354]="ServerResponseInvalid",e[e.SERVER_ERROR_GSLB_NOT_FOUND_CHANNEL_ID_ERROR=33620496]="SERVER_ERROR_GSLB_NOT_FOUND_CHANNEL_ID_ERROR",e[e.SERVER_ERROR_INTERNAL_ERROR=33620497]="SERVER_ERROR_INTERNAL_ERROR",e[e.SERVER_ERROR_MEDIA_ENGINE_ACCESS_ERROR=33620498]="SERVER_ERROR_MEDIA_ENGINE_ACCESS_ERROR",e[e.SERVER_ERROR_MEDIA_ENGINE_SCHEDULE_AND_CREATE_ERROR=33620499]="SERVER_ERROR_MEDIA_ENGINE_SCHEDULE_AND_CREATE_ERROR",e[e.SERVER_ERROR_SECURITY_TOKEN_NOT_FOUND_ERROR=33620500]="SERVER_ERROR_SECURITY_TOKEN_NOT_FOUND_ERROR",e[e.SERVER_ERROR_GSLB_ACCESS_ERROR=33622281]="SERVER_ERROR_GSLB_ACCESS_ERROR",e[e.SERVER_ERROR_GSLB_DISPATCH_ERROR=33620501]="SERVER_ERROR_GSLB_DISPATCH_ERROR",e[e.SERVER_ERROR_GSLB_MAPI_ERROR=33620502]="SERVER_ERROR_GSLB_MAPI_ERROR",e[e.MicOpenFail=17040388]="MicOpenFail",e[e.SpeakerOpenFail=17040389]="SpeakerOpenFail",e[e.MicInterrupt=17040390]="MicInterrupt",e[e.SpeakerSetNotSupported=17040416]="SpeakerSetNotSupported",e[e.SpeakerInterrupt=17040391]="SpeakerInterrupt",e[e.MicAuthFail=17040392]="MicAuthFail",e[e.MicNotAvailable=17040393]="MicNotAvailable",e[e.SpeakerNotAvailable=17040400]="SpeakerNotAvailable",e[e.SpecifiedAudioDeviceNotFound=17040401]="SpecifiedAudioDeviceNotFound",e[e.AudioMixingUnknownError=17040896]="AudioMixingUnknownError",e[e.LoadAudioFailed=17040897]="LoadAudioFailed",e[e.AudioMixingStateInvalid=17040898]="AudioMixingStateInvalid",e[e.AudioContextNotSupported=17040899]="AudioContextNotSupported",e[e.NotArrayBuffer=17040900]="NotArrayBuffer",e[e.AudioMixingMissingParam=17040901]="AudioMixingMissingParam",e[e.AudioMixingStartFailed=17040902]="AudioMixingStartFailed",e[e.AudioMixingResumeFailed=17040903]="AudioMixingResumeFailed",e[e.AudioPlayTimeError=17040912]="AudioPlayTimeError",e[e.AutoPlayFailed=17040928]="AutoPlayFailed",e[e.CameraOpenFail=17039620]="CameraOpenFail",e[e.CameraInterrupt=17039622]="CameraInterrupt",e[e.SpecifiedCameraDeviceNotFound=17039623]="SpecifiedCameraDeviceNotFound",e[e.CameraNotAvailable=17039673]="CameraNotAvailable",e[e.CameraAuthFail=17039680]="CameraAuthFail",e[e.ScreenShareOpenFail=17039624]="ScreenShareOpenFail",e[e.VideoDisplayOpenFail=17039873]="VideoDisplayOpenFail",e[e.VideoDisplayInterrupt=17039874]="VideoDisplayInterrupt",e[e.DeviceUnknownError=17040537]="DeviceUnknownError",e[e.OverConstrainedError=17040536]="OverConstrainedError",e[e.ScreenShareUnknownError=17040640]="ScreenShareUnknownError",e[e.ScreenShareNotAllowed=17040641]="ScreenShareNotAllowed",e[e.ScreenShareEnded=17040642]="ScreenShareEnded",e[e.ScreenShareNotAuthed=17040643]="ScreenShareNotAuthed",e[e.ScreenShareInvalidAccess=17040644]="ScreenShareInvalidAccess",e[e.ScreenShareAbortError=17040645]="ScreenShareAbortError",e[e.ScreenShareStateError=17040646]="ScreenShareStateError",e[e.ScreenShareTypeError=17040647]="ScreenShareTypeError",e[e.IceConnectionConnectFail=17105409]="IceConnectionConnectFail",e[e.IceConnectionReconnectFail=17105410]="IceConnectionReconnectFail",e[e.IceConnectionAnswerFail=17105426]="IceConnectionAnswerFail",e[e.IceConnectionNoCandidate=17105427]="IceConnectionNoCandidate",e[e.IceConnectionDisconnected=17105428]="IceConnectionDisconnected",e[e.IceConnectionSetLocalDescFail=17105429]="IceConnectionSetLocalDescFail",e[e.ConnectionHeartbeatTimeout=17105411]="ConnectionHeartbeatTimeout",e[e.ConnectionConnectFail=17105665]="ConnectionConnectFail",e[e.APICallTimeOut=17105681]="APICallTimeOut",e[e.PublishNoStream=16974596]="PublishNoStream",e[e.PublishInvaild=16974597]="PublishInvaild",e[e.PublishNotJoinChannel=16843782]="PublishNotJoinChannel",e[e.PublishAudioStreamFailed=16843856]="PublishAudioStreamFailed",e[e.PublishVideoStreamFailed=16843857]="PublishVideoStreamFailed",e[e.PublishScreenShareFailed=16843859]="PublishScreenShareFailed",e[e.PublishScreenShareConfigError=16843860]="PublishScreenShareConfigError",e[e.SubscribeStreamNotExisted=16974851]="SubscribeStreamNotExisted",e[e.SubscribeInvaild=16974852]="SubscribeInvaild",e[e.SubscribeNotJoinChannel=16844112]="SubscribeNotJoinChannel",e[e.SubscribeAudioStreamFailed=16844113]="SubscribeAudioStreamFailed",e[e.SubscribeVideoStreamFailed=16844114]="SubscribeVideoStreamFailed",e[e.SubscribeScreenShareFailed=16844116]="SubscribeScreenShareFailed",e[e.LogAlreadyInit=16974085]="LogAlreadyInit",e[e.LogRootPathError=16974086]="LogRootPathError",e[e.QuotaLimitExceed=16974096]="QuotaLimitExceed",e[e.BrowserNotSupported=16974101]="BrowserNotSupported",e[e.InvaildState=16974340]="InvaildState",e[e.InvaildArgument=16974083]="InvaildArgument",e[e.SessionRemoved=33620229]="SessionRemoved",e[e.AudioBufferFull=17236225]="AudioBufferFull",e[e.VideoBufferFull=17236226]="VideoBufferFull",e[e.AudioStreamError=17301761]="AudioStreamError",e[e.AudioFileOpenFail=17301762]="AudioFileOpenFail",e[e.AudioFormatNotSupported=17301763]="AudioFormatNotSupported",e[e.UpdateRoleChannel=16908801]="UpdateRoleChannel",e[e.Inner=-1]="Inner"}(ErrorCode||(ErrorCode={}));var ErrorCodeAndMsgMap=(_ErrorCodeAndMsgMap={},_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_ErrorCodeAndMsgMap,ErrorCode.NetworkError,"Network error, please check your network connectivity or dns, proxy, firewall etc."),ErrorCode.SERVER_ERROR_GSLB_ACCESS_ERROR,"GSLB access error"),ErrorCode.CLIENT_ERROR_NOT_FOUND_APP,"AppId is not exist"),ErrorCode.CLIENT_ERROR_INVALID_APP_ID,"AppId is invalid"),ErrorCode.CLIENT_ERROR_NOT_FOUND_GSLB_CHANNEL,"channel is not exist"),ErrorCode.CLIENT_ERROR_INVALID_TOKEN_TIMESTAMP,"channel is invalid"),ErrorCode.CLIENT_ERROR_INVALID_AUTHORIZATION,"token is invalid"),ErrorCode.JoinTimeout,"join timeout"),ErrorCode.JoinBadParam,"join with invalid parameter"),ErrorCode.JoinChannelFailed,"join channel failed"),_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_ErrorCodeAndMsgMap,ErrorCode.CLIENT_ERROR_INVALID_APP_STATUS,"invalid app status"),ErrorCode.CLIENT_ERROR_INVALID_USER_ID,"invalid userId"),ErrorCode.CLIENT_ERROR_INVALID_REQUEST,"invalid request"),ErrorCode.SERVER_ERROR_GSLB_NOT_FOUND_CHANNEL_ID_ERROR,"gslb not found channelId error"),ErrorCode.SERVER_ERROR_INTERNAL_ERROR,"internal error"),ErrorCode.SERVER_ERROR_MEDIA_ENGINE_ACCESS_ERROR,"media-engine access error"),ErrorCode.SERVER_ERROR_MEDIA_ENGINE_SCHEDULE_AND_CREATE_ERROR,"media-engine scheduleAndCreate error"),ErrorCode.SERVER_ERROR_SECURITY_TOKEN_NOT_FOUND_ERROR,"security token not found error"),ErrorCode.SERVER_ERROR_GSLB_DISPATCH_ERROR,"gslb dispatch error"),ErrorCode.SERVER_ERROR_GSLB_MAPI_ERROR,"gslb mapi error"),_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_ErrorCodeAndMsgMap,ErrorCode.ScreenShareUnknownError,"unknown screenShare error"),ErrorCode.ScreenShareNotAllowed,"screenShare not allowned"),ErrorCode.ScreenShareEnded,"screenShare ended"),ErrorCode.ScreenShareNotAuthed,"screenShare no permission"),ErrorCode.ScreenShareInvalidAccess,"screenShare invalid access"),ErrorCode.ScreenShareAbortError,"screenShare abort access"),ErrorCode.ScreenShareStateError,"screenShare state error"),ErrorCode.ScreenShareTypeError,"screenShare type error"),ErrorCode.AutoPlayFailed,"auto play failed"),ErrorCode.OverConstrainedError,"Overconstrained error"),_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_ErrorCodeAndMsgMap,ErrorCode.DeviceUnknownError,"unknown device error"),ErrorCode.MicOpenFail,"failed to open audio record device or audio device occupied"),ErrorCode.MicInterrupt,"audio recording error or audio device occupied"),ErrorCode.SpeakerInterrupt,"audio playing error or audio device occupied"),ErrorCode.SpeakerOpenFail,"failed to open playback device"),ErrorCode.SpeakerSetNotSupported,"not support set output device"),ErrorCode.MicAuthFail,"no audio recording permission or audio device occupied"),ErrorCode.MicNotAvailable,"no audio record device found"),ErrorCode.SpeakerNotAvailable,"no audio play device found"),ErrorCode.SpecifiedAudioDeviceNotFound,"specified audio device not found"),_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_ErrorCodeAndMsgMap,ErrorCode.CameraOpenFail,"failed to open camera due to no permission or camera device occupied"),ErrorCode.CameraInterrupt,"camera capturing happens error"),ErrorCode.SpecifiedCameraDeviceNotFound,"specified camera device not found"),ErrorCode.VideoDisplayOpenFail,"failed to open render device"),ErrorCode.VideoDisplayInterrupt,"render happens error"),ErrorCode.ScreenShareOpenFail,"failed to start shareScreen"),ErrorCode.CameraNotAvailable,"no camera device found"),ErrorCode.CameraAuthFail,"no camera permission"),ErrorCode.IceConnectionConnectFail,"ICE connection failed"),ErrorCode.IceConnectionAnswerFail,"failed to answer ICE connection"),_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_ErrorCodeAndMsgMap,ErrorCode.IceConnectionDisconnected,"ICE connection disconnected"),ErrorCode.IceConnectionNoCandidate,"ICE connection has no candidates"),ErrorCode.IceConnectionSetLocalDescFail,"failed to set local SDP"),ErrorCode.ConnectionHeartbeatTimeout,"signal heartbeat timeout"),ErrorCode.ConnectionConnectFail,"signal connection failed"),ErrorCode.APICallTimeOut,"api call is timeout"),ErrorCode.IceConnectionReconnectFail,"failed to reconnect ICE connection"),ErrorCode.PublishVideoStreamFailed,"failed to publish video"),ErrorCode.PublishNoStream,"publish stream is not exist\t"),ErrorCode.PublishInvaild,"already unpublish or not publish for now"),_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_ErrorCodeAndMsgMap,ErrorCode.PublishNotJoinChannel,"can not publish before join channel"),ErrorCode.PublishAudioStreamFailed,"failed to publish audio"),ErrorCode.PublishScreenShareFailed,"failed to publish ScreenShare"),ErrorCode.PublishScreenShareConfigError,"failed to publish ScreenShare due to config error"),ErrorCode.SubscribeStreamNotExisted,"subscribe stream is not exist"),ErrorCode.SubscribeInvaild,"already unsubscribe or not subscribe for now"),ErrorCode.SubscribeNotJoinChannel,"can not subscribe before join channel"),ErrorCode.SubscribeAudioStreamFailed,"failed to subscribe audio"),ErrorCode.SubscribeScreenShareFailed,"failed to subscribe ScreenShare"),ErrorCode.SubscribeVideoStreamFailed,"failed to subscribe video"),_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_ErrorCodeAndMsgMap,ErrorCode.AudioMixingUnknownError,"audio mixing unknown error"),ErrorCode.LoadAudioFailed,"load audio source failed"),ErrorCode.AudioMixingStateInvalid,"invalid audio mixing state"),ErrorCode.AudioContextNotSupported,"audio context is not supported"),ErrorCode.NotArrayBuffer,"source type is not array buffer"),ErrorCode.AudioMixingMissingParam,"audio mixing is missing param"),ErrorCode.AudioMixingStartFailed,"audio mixing start failed"),ErrorCode.AudioMixingResumeFailed,"audio mixing resume failed"),ErrorCode.AudioPlayTimeError,"time out of range"),ErrorCode.QuotaLimitExceed,"task exceed limit"),_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_ErrorCodeAndMsgMap,ErrorCode.InvaildState,"the operation is rejected in current state"),ErrorCode.InvaildArgument,"invalid argument"),ErrorCode.AudioBufferFull,"external audio input buffer is full"),ErrorCode.VideoBufferFull,"external video input buffer is full"),ErrorCode.AudioStreamError,"auido stream has error"),ErrorCode.AudioFileOpenFail,"failed to open audio file"),ErrorCode.AudioFormatNotSupported,"no support the audio format"),ErrorCode.UpdateRoleChannel,"failed to update role"),ErrorCode.BrowserNotSupported,"failed to update role"),ErrorCode.Inner,"sdk internel error occured"),_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_ErrorCodeAndMsgMap,ErrorCode.LogAlreadyInit,"log already init"),ErrorCode.LogRootPathError,"log root path error"),ErrorCode.SessionRemoved,"session has been removed"),ErrorCode.ServerResponseInvalid,"Server response invalid")),converToRtcErrorFromGslbCode=function(e,t){return new DingRTCError(e?ErrorCode[e]:ErrorCode.NetworkError,ErrorCodeAndMsgMap[e]||GSLBErrorCode[e]||t)},NAME_TYPEERROR=DeviceErrorDescription.NAME_TYPEERROR,NAME_ABORTEERROR=DeviceErrorDescription.NAME_ABORTEERROR,NAME_INVALID_ACCESS=DeviceErrorDescription.NAME_INVALID_ACCESS,NAME_DEVICENOTFOUND=DeviceErrorDescription.NAME_DEVICENOTFOUND,NAME_DEVICENOTALLOWED=DeviceErrorDescription.NAME_DEVICENOTALLOWED,NAME_INVALIDSTATEERROR=DeviceErrorDescription.NAME_INVALIDSTATEERROR,MESSAGE_DEVICENOTFOUND=DeviceErrorDescription.MESSAGE_DEVICENOTFOUND,NAME_DEVICENOTREADABLE=DeviceErrorDescription.NAME_DEVICENOTREADABLE,MESSAGE_DEVICENOTALLOWED=DeviceErrorDescription.MESSAGE_DEVICENOTALLOWED,NAME_DEVICEOVERCONSTRAINED=DeviceErrorDescription.NAME_DEVICEOVERCONSTRAINED,MESSAGE_VIDEODEVICENOTREADABLE=DeviceErrorDescription.MESSAGE_VIDEODEVICENOTREADABLE,MESSAGE_AUDIODEVICENOTREADABLE=DeviceErrorDescription.MESSAGE_AUDIODEVICENOTREADABLE,MESSAGE_MOBILEDEVICE_NOTALLOWED=DeviceErrorDescription.MESSAGE_MOBILEDEVICE_NOTALLOWED,MESSAGE_MACSAFARIDEVICENOTALLOWED=DeviceErrorDescription.MESSAGE_MACSAFARIDEVICENOTALLOWED,MESSAGE_MACCHROMEDEVICENOTREADABLE=DeviceErrorDescription.MESSAGE_MACCHROMEDEVICENOTREADABLE,parseAudioDeviceError=function(e){if(e){var t=e.message,r=e.name;if(t===MESSAGE_DEVICENOTFOUND||r===NAME_DEVICENOTFOUND)return new DingRTCError(ErrorCode.MicNotAvailable);if([MESSAGE_DEVICENOTALLOWED,MESSAGE_MACSAFARIDEVICENOTALLOWED].includes(t))return new DingRTCError(ErrorCode.MicAuthFail);if([MESSAGE_MACCHROMEDEVICENOTREADABLE,MESSAGE_AUDIODEVICENOTREADABLE].includes(t)||r===NAME_DEVICENOTREADABLE)return new DingRTCError(ErrorCode.MicOpenFail);if(e instanceof TypeError)return new DingRTCError(ErrorCode.InvaildArgument,t)}return new DingRTCError(ErrorCode.DeviceUnknownError,e.message)},parseVideoDeviceError=function(e){if(e){var t=e.message,r=e.name;if(t===MESSAGE_DEVICENOTFOUND||r===NAME_DEVICENOTFOUND)return new DingRTCError(ErrorCode.CameraNotAvailable);if(t==MESSAGE_DEVICENOTALLOWED||t==MESSAGE_MOBILEDEVICE_NOTALLOWED||t==MESSAGE_MACSAFARIDEVICENOTALLOWED)return new DingRTCError(ErrorCode.CameraAuthFail);if(t==MESSAGE_MACCHROMEDEVICENOTREADABLE||t==MESSAGE_VIDEODEVICENOTREADABLE||r==NAME_DEVICENOTREADABLE)return new DingRTCError(ErrorCode.CameraOpenFail);if(r==NAME_DEVICEOVERCONSTRAINED)return new DingRTCError(ErrorCode.OverConstrainedError);if(e instanceof TypeError)return new DingRTCError(ErrorCode.InvaildArgument,t)}return new DingRTCError(ErrorCode.DeviceUnknownError,e.message)},parseScreenShareError=function(e){if(e){var t=e.name,r=e.message;if("ended"==e.type)return new DingRTCError(ErrorCode.ScreenShareEnded);if(NAME_DEVICENOTALLOWED===t)return new DingRTCError(r==MESSAGE_DEVICENOTALLOWED?ErrorCode.ScreenShareNotAllowed:ErrorCode.ScreenShareNotAuthed,r);if(NAME_INVALID_ACCESS===t)return new DingRTCError(ErrorCode.ScreenShareInvalidAccess,r);if(NAME_ABORTEERROR===t)return new DingRTCError(ErrorCode.ScreenShareAbortError,r);if(NAME_INVALIDSTATEERROR===t)return new DingRTCError(ErrorCode.ScreenShareStateError,r);if(NAME_TYPEERROR===t)return new DingRTCError(ErrorCode.ScreenShareTypeError,r);if(e instanceof TypeError)return new DingRTCError(ErrorCode.InvaildArgument,r)}return new DingRTCError(ErrorCode.ScreenShareUnknownError,"name: ".concat(e.name," message: ").concat(e.message))};function _callSuper$n(e,t,r){return t=_getPrototypeOf(t),_possibleConstructorReturn(e,_isNativeReflectConstruct$n()?Reflect.construct(t,r||[],_getPrototypeOf(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$n(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$n=function(){return!!e})()}var DingRTCError=function(e){function t(e,r){var n;return _classCallCheck(this,t),n=_callSuper$n(this,t,[r=r||ErrorCodeAndMsgMap[e]]),Object.defineProperty(n,"code",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(n,"reason",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),n.code=e,n.reason=r,getReporter().trace.exception(n),n}return _inherits(t,_wrapNativeSuper(Error)),_createClass(t)}(),AudioCodec,VideoCodec,AudioSourceInfo,TaskType,NetworkQualityType,SdkType,TerminalType,DropType,PubSubStates,PeerConnectionState,SubPubFailReason,ClientUserStats,VideoProfileType;function _defineProperty(e,t,r){return(t=toPropertyKey$1(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function _arrayLikeToArray$d(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _arrayWithoutHoles(e){if(Array.isArray(e))return _arrayLikeToArray$d(e)}function _iterableToArray(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}function _unsupportedIterableToArray$d(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$d(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_arrayLikeToArray$d(e,t):void 0}}function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _toConsumableArray(e){return _arrayWithoutHoles(e)||_iterableToArray(e)||_unsupportedIterableToArray$d(e)||_nonIterableSpread()}function _superPropBase(e,t){for(;!{}.hasOwnProperty.call(e,t)&&null!==(e=_getPrototypeOf$1(e)););return e}function _get(){return _get="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(e,t,r){var n=_superPropBase(e,t);if(n){var i=Object.getOwnPropertyDescriptor(n,t);return i.get?i.get.call(arguments.length<3?e:r):i.value}},_get.apply(null,arguments)}!function(e){e.PCMU="pcmu",e.PCMA="pcma",e.OPUS="opus",e.G722="g722",e.ISAC="iSAC",e.ILBC="iLBC",e.AAC="aac",e.AC3="ac3",e.NELLYMOSER="nellymoser"}(AudioCodec||(AudioCodec={})),function(e){e.VP8="vp8",e.VP9="vp9",e.H264="h264",e.H265="h265",e.AV1="av1",e.AV1X="av1x"}(VideoCodec||(VideoCodec={})),exports.AudioSourceInfo=void 0,AudioSourceInfo=exports.AudioSourceInfo||(exports.AudioSourceInfo={}),AudioSourceInfo.MIC="mic",AudioSourceInfo.SCREENCAST="screen-cast",AudioSourceInfo.MIXED="mixed",exports.VideoSourceInfo=void 0,function(e){e.CAMERA="camera",e.SCREENCAST="screen-cast",e.MIXED="mixed"}(exports.VideoSourceInfo||(exports.VideoSourceInfo={})),function(e){e.PUBLISH="publish",e.SUBSCRIBE="subscribe"}(TaskType||(TaskType={})),function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.GREAT=1]="GREAT",e[e.GOOD=2]="GOOD",e[e.NORMAL=3]="NORMAL",e[e.POOR=4]="POOR",e[e.BAD=5]="BAD",e[e.DISCONNECTED=6]="DISCONNECTED"}(NetworkQualityType||(NetworkQualityType={})),function(e){e[e.Native=1]="Native",e[e.Web=2]="Web",e[e.MiniProgram=3]="MiniProgram"}(SdkType||(SdkType={})),function(e){e[e.Windows=1]="Windows",e[e.Android=2]="Android",e[e.Mac=3]="Mac",e[e.iOS=4]="iOS",e[e.Linux=5]="Linux",e[e.Others=6]="Others"}(TerminalType||(TerminalType={})),function(e){e[e.UserKickOut=2011]="UserKickOut",e[e.UserReplaced=2012]="UserReplaced"}(DropType||(DropType={})),function(e){e[e.Idle=0]="Idle",e[e.Processing=1]="Processing",e[e.End=2]="End"}(PubSubStates||(PubSubStates={})),function(e){e[e.New=0]="New",e[e.Idle=1]="Idle",e[e.Processing=2]="Processing",e[e.Ended=3]="Ended"}(PeerConnectionState||(PeerConnectionState={})),function(e){e.QuotaLimit="task exceed limit",e.PCNotExisted="connection does NOT exist",e.RoomClosed="room_already_closed:30107",e.RoomNotExisted="room does not exist",e.RoomBusy="RoomBusy",e.RoomNotJoined="participant has not joined",e.FailOver="Session has been aborted"}(SubPubFailReason||(SubPubFailReason={})),function(e){e[e.MIC_OPEN=0]="MIC_OPEN",e[e.MIC_INTERRUPTED=1]="MIC_INTERRUPTED",e[e.CAMERA_OPEN=2]="CAMERA_OPEN",e[e.BACKGROUND_MODE=3]="BACKGROUND_MODE",e[e.DOWNLINK=4]="DOWNLINK",e[e.UPLINK=5]="UPLINK"}(ClientUserStats||(ClientUserStats={})),function(e){e[e.None=0]="None",e[e.LD=2]="LD",e[e.SD=4]="SD",e[e.HD=8]="HD",e[e.FHD=16]="FHD",e[e.QHD=32]="QHD",e[e.UHD=64]="UHD"}(VideoProfileType||(VideoProfileType={}));var version="3.9.23",pkg={version:version},VideoDimensions={VD_120x120:[120,120],VD_160x120:[160,120],VD_180x180:[180,180],VD_240x180:[240,180],VD_320x180:[320,180],VD_240x240:[240,240],VD_320x240:[320,240],VD_424x240:[424,240],VD_360x360:[360,360],VD_480x360:[480,360],VD_640x360:[640,360],VD_480x480:[480,480],VD_640x480:[640,480],VD_840x480:[840,480],VD_960x540:[960,540],VD_960x720:[960,720],VD_1280x720:[1280,720],VD_1920x1080:[1920,1080],VD_2560x1440:[2560,1440]};exports.AudioSourceState=void 0,function(e){e.Playing="playing",e.Paused="paused",e.Stopped="stopped"}(exports.AudioSourceState||(exports.AudioSourceState={}));var SDK_VERSION=pkg.version,DEFAULT_GSLB_DOMAIN="https://gslb.dingrtc.com",IGNOGRED_VERSION=-999,SIGNAL_CALL_TIMEOUT=1e3,NETWORK_QUALITY_TIMEOUT=2e3,METRIC_STATS_INTERVAL=2e3,DEFAULT_CREATE_PC_TIMEOUT=4e3,MEDIA_ELEMENT_LABEL_ATTR="rtc-label",STUCK_JUDGE_RECV_BYTES=3e4;JSON.stringify({needPersonalityAudioStream:!0,outPeerConnectionNotReuse:!0}),Environment.browserType,Environment.browserVersion,Environment.system,Environment.systemVersion;var USER_STATS_SYNC="onertc_state_sync",TRACK_EVENT_NAME="onertc_internal_track_event",RTC_SDK_EL_DATA_ATTR_NAME="rtc_sdk_el_data",RTC_SDK_PLAYER_CONTAINER_LABEL_ATTR_NAME="rtc_sdk_player_container_label",CONST_DEVELOPER_TODO_LOG_TAG="_DEV_TODO_",logger$a=getReporter().getLoggerWithPrefix("rtc-support"),Support=function(){return _createClass$1(function e(){_classCallCheck$1(this,e),Object.defineProperty(this,"system",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"browser",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"browserVersion",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.system=Environment.system,this.browser=Environment.browserType,this.browserVersion=Environment.browserVersion},[{key:"getSupportedCodec",value:(e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){var t,r,n;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t={audio:[],video:[]},e.prev=1,(r=new RTCPeerConnection).addTransceiver("video",{direction:"recvonly"}),r.addTransceiver("audio",{direction:"recvonly"}),e.next=2,r.createOffer();case 2:if(n=e.sent.sdp){e.next=3;break}return e.abrupt("return",t);case 3:return r.close(),r=null,n.match(/ VP8/i)&&t.video.push("VP8"),n.match(/ VP9/i)&&t.video.push("VP9"),n.match(/ AV1/i)&&t.video.push("AV1"),n.match(/ H264/i)&&t.video.push("H264"),n.match(/ H265/i)&&t.video.push("H265"),n.match(/ opus/i)&&t.audio.push("OPUS"),n.match(/ PCMU/i)&&t.audio.push("PCMU"),n.match(/ PCMA/i)&&t.audio.push("PCMA"),n.match(/ G722/i)&&t.audio.push("G722"),e.abrupt("return",t);case 4:throw e.prev=4,e.catch(1),logger$a.error("get supportedCodecs failed"),new DingRTCError(ErrorCode.IceConnectionSetLocalDescFail,"get supportedCodecs failed");case 5:case"end":return e.stop()}},e,null,[[1,4]])})),function(){return e.apply(this,arguments)})},{key:"checkSupported",value:function(){var e=!1;try{var t=window.RTCPeerConnection,r=navigator.mediaDevices&&navigator.mediaDevices.getUserMedia,n=window.WebSocket;e=!!(t&&r&&n)}catch(e){return logger$a.error("checkSystemRequirements error",e),!1}var i=!1;i=Environment.isChrome()||Environment.isFirefox()?parseInt(Environment.browserVersion,10)>=69:Environment.isOpera()?parseInt(Environment.browserVersion,10)>=45:Environment.isSafari()?parseInt(Environment.browserVersion,10)>=11:(Environment.isWeixin()||Environment.isQQBrowser(),!0);var o=e&&i;return logger$a.info("checkSystemRequirements, api:",e,"browser",i),o}},{key:"isSupportScreenShare",value:function(){return!this.system.includes(OSType.ANDROID)&&this.system!==OSType.IOS&&(!(this.browser===BrowserType.SAFARI&&parseInt(this.browserVersion)<13)&&(!(this.browser===BrowserType.FIREFOX&&parseInt(this.browserVersion)<66)&&!!(navigator&&navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)))}}]);var e}(),support=new Support,isSupportSimulcast=function(){var e,t=(null===(e=window.RTCRtpSender)||void 0===e?void 0:e.prototype)||{},r=t.setParameters,n=t.getParameters;return!(!r||!n)&&(!Environment.isFirefox()&&(Environment.isSafari()?parseInt(Environment.browserVersion)>=14:Environment.isChrome()?parseInt(Environment.browserVersion)>=81:!Environment.isAndroid()))};function _callSuper$m(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$m()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$m(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$m=function(){return!!e})()}var logger$9=getReporter().getLoggerWithPrefix("[rtc-config]"),ClientConfig=function(e){function t(){var e;return _classCallCheck$1(this,t),e=_callSuper$m(this,t),Object.defineProperty(e,"gslb",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(e,"simulcast",{enumerable:!0,configurable:!0,writable:!0,value:isSupportSimulcast()}),Object.defineProperty(e,"audioSFU",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(e,"republish",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(e,"disableTransportCC",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(e,"preferH264CbProfile",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(e,"downlinkForbidHighProfile",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(e,"highStartBitrate",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(e,"_holdVideoLastFrame",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(e,"_consoleLogLevel",{enumerable:!0,configurable:!0,writable:!0,value:"warn"}),Object.defineProperty(e,"connectPcTimeoutMs",{enumerable:!0,configurable:!0,writable:!0,value:DEFAULT_CREATE_PC_TIMEOUT}),e.setClientConfig({gslb:[DEFAULT_GSLB_DOMAIN]}),e}return _inherits$1(t,e),_createClass$1(t,[{key:"setClientConfig",value:function(e){logger$9.info("setClientConfig",e);var t=e||{},r=t.gslb,n=t.simulcast,i=t.audioSFU,o=t.republish,a=t.disableTransportCC,s=t.highStartBitrate;"string"==typeof r&&(this.gslb=[r],setGslb(r)),Array.isArray(r)&&isString(r[0])&&(this.gslb=r,setGslb(r[0])),null!=n&&isSupportSimulcast()&&(this.simulcast=Boolean(n)),null!=i&&(this.audioSFU=Boolean(i)),null!=a&&(this.disableTransportCC=Boolean(a)),null!=o&&(this.republish=Boolean(o)),null!=s&&(this.highStartBitrate=!!s),null!=e&&e._consoleLogLevel&&(this._consoleLogLevel=null==e?void 0:e._consoleLogLevel),"boolean"==typeof(null==e?void 0:e.preferH264CbProfile)&&(this.preferH264CbProfile=e.preferH264CbProfile),(null==e?void 0:e.connectPcTimeoutMs)>=0&&e.connectPcTimeoutMs<=Number.MAX_SAFE_INTEGER?this.connectPcTimeoutMs=e.connectPcTimeoutMs:void 0!==(null==e?void 0:e.connectPcTimeoutMs)&&null!==(null==e?void 0:e.connectPcTimeoutMs)&&console.error("connectPcTimeoutMs should be a non-negative number")}}])}(EventEmitter),clientConfig=new ClientConfig,sortResolutions=function(e,t){return e.width!==t.width?e.width-t.width:e.height-t.height},getStreamSupportedResoArr=function(e){var t;if(!e)return[];var r=e.media.video;if(!r)return[];var n=[],i=r.optional,o=r.parameters;return null!=o&&o.resolution&&n.push(o.resolution),null!=i&&null!==(t=i.parameters)&&void 0!==t&&null!==(t=t.resolution)&&void 0!==t&&t.length&&n.push.apply(n,_toConsumableArray(i.parameters.resolution)),n.sort(sortResolutions),n},parseSubscribeError=function(e,t){var r,n=e.media,i=n.audio,o=n.video;if(t===SubPubFailReason.QuotaLimit)return r=new DingRTCError(ErrorCode.QuotaLimitExceed);if(i)r=new DingRTCError(ErrorCode.SubscribeAudioStreamFailed,t);else if(o){var a=o.source;a===exports.VideoSourceInfo.CAMERA?r=new DingRTCError(ErrorCode.SubscribeVideoStreamFailed,t):a===exports.VideoSourceInfo.SCREENCAST&&(r=new DingRTCError(ErrorCode.SubscribeScreenShareFailed,t))}return r},parsePublishError=function(e,t){var r,n=e.trackMediaType;if(t===SubPubFailReason.QuotaLimit)return r=new DingRTCError(ErrorCode.QuotaLimitExceed);if("audio"===n)r=new DingRTCError(ErrorCode.PublishAudioStreamFailed,t);else{var i=e.source;i===exports.VideoSourceInfo.CAMERA?r=new DingRTCError(ErrorCode.PublishVideoStreamFailed,t):i===exports.VideoSourceInfo.SCREENCAST&&(r=new DingRTCError(ErrorCode.PublishScreenShareFailed,t))}return r},updateRemoteTrack=function(e,t,r,n){var i=n,o=e.getVideoTracks(),a=e.getAudioTracks();return"audio"===t&&a.length?clientConfig.audioSFU?n?n.replaceStream(e):i=new RemoteAudioTrack(null,r,e):n?n.replaceTrack(a[0]):i=new RemoteAudioTrack(a[0],r):"video"===t&&o.length&&(n?n.replaceTrack(o[0]):i=new RemoteVideoTrack(o[0],r)),i},isScreenCast=function(e){return"object"===_typeof$3(e.video)&&e.video.source===exports.VideoSourceInfo.SCREENCAST};function ownKeys$a(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function _objectSpread$a(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$a(Object(r),!0).forEach(function(t){_defineProperty(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$a(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function _createForOfIteratorHelper$c(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$c(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$c(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$c(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_arrayLikeToArray$c(e,t):void 0}}function _arrayLikeToArray$c(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _callSuper$l(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$l()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$l(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$l=function(){return!!e})()}var logger$8=getReporter().getLoggerWithPrefix("[rtc-device]"),DeviceManager=function(e){function t(){var e,r;return _classCallCheck$1(this,t),e=_callSuper$l(this,t),Object.defineProperty(e,"deviceList",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(e,"checking",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(e,"checkDeviceUpdate",{enumerable:!0,configurable:!0,writable:!0,value:(r=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function r(){var n;return _regeneratorRuntime$1.wrap(function(r){for(;;)switch(r.prev=r.next){case 0:if(!e.checking){r.next=1;break}return r.abrupt("return");case 1:return e.checking=!0,r.next=2,t.getDevices();case 2:n=r.sent,e.compareDevices(n,"audiooutput"),e.compareDevices(n,"videoinput"),e.compareDevices(n,"audioinput"),e.deviceList=n,e.checking=!1;case 3:case"end":return r.stop()}},r)})),function(){return r.apply(this,arguments)})}),Object.defineProperty(e,"compareDevices",{enumerable:!0,configurable:!0,writable:!0,value:function(t,r){var n,i=t.filter(function(e){return e.kind===r}),o=e.deviceList.filter(function(e){return e.kind===r}),a=i.map(function(e){return e.deviceId}),s=o.map(function(e){return e.deviceId}),c=i.filter(function(e){var t=e.deviceId;return!s.includes(t)}),u=o.filter(function(e){var t=e.deviceId;return!a.includes(t)}),l={audioinput:"microphone-changed",audiooutput:"playback-device-changed",videoinput:"camera-changed"},d=_createForOfIteratorHelper$c(c);try{for(d.s();!(n=d.n()).done;){var p=n.value;e.emit(l[r],{device:p,state:"active"})}}catch(e){d.e(e)}finally{d.f()}var f,h=_createForOfIteratorHelper$c(u);try{for(h.s();!(f=h.n()).done;){var g=f.value;e.emit(l[r],{device:g,state:"inactive"})}}catch(e){h.e(e)}finally{h.f()}}}),t._instance?_possibleConstructorReturn$1(e,t._instance):(e.deviceList=[],support.checkSupported()?(t.getDevices({audio:!0,video:!0},!0).then(function(t){e.deviceList=t,e.addEventListeners()}),e):_possibleConstructorReturn$1(e))}return _inherits$1(t,e),_createClass$1(t,[{key:"addEventListeners",value:function(){"ondevicechange"in navigator.mediaDevices?navigator.mediaDevices.addEventListener("devicechange",this.checkDeviceUpdate):addTimer(this.checkDeviceUpdate,1e3,"interval")}}],[{key:"getInstance",value:function(){return t._instance}},{key:"getMedias",value:(r=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(r,n){var i,o,a,s,c,u,l,d,p,f,h;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(t.accGetMedia++,i=t.accGetMedia,!isScreenCast(r)){e.next=6;break}if(logger$8.info("getDisplayMedia with",i,r,n),!Environment.isElectron()){e.next=3;break}if(n.video){e.next=1;break}throw new DingRTCError(ErrorCode.ScreenShareOpenFail,"only video screen cast is supported, but got no video parameters");case 1:return e.next=2,navigator.mediaDevices.getUserMedia({audio:!1,video:{mandatory:{chromeMediaSource:"screen",minWidth:(null===(a=n.video)||void 0===a?void 0:a.width)||1280,maxWidth:(null===(s=n.video)||void 0===s?void 0:s.width)||1280,minHeight:(null===(c=n.video)||void 0===c?void 0:c.height)||720,maxHeight:(null===(u=n.video)||void 0===u?void 0:u.height)||720,minFrameRate:(null===(l=n.video)||void 0===l?void 0:l.frameRate)||5,maxFrameRate:(null===(d=n.video)||void 0===d?void 0:d.frameRate)||5}}});case 2:o=e.sent,e.next=5;break;case 3:return e.next=4,null===(p=navigator.mediaDevices)||void 0===p?void 0:p.getDisplayMedia(n);case 4:o=e.sent;case 5:return logger$8.info("succ getDisplayMedia with",i),e.abrupt("return",o);case 6:return logger$8.info("getUserMedia with",i,r,n),e.next=7,null===(f=navigator.mediaDevices)||void 0===f?void 0:f.getUserMedia(n);case 7:return h=e.sent,logger$8.info("succ getUserMedia with",i),r.audio&&(this.audioPermitted=!0),r.video&&(this.videoPermitted=!0),e.abrupt("return",h);case 8:case"end":return e.stop()}},e,this)})),function(e,t){return r.apply(this,arguments)})},{key:"getDevices",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{audio:!0,video:!0},r=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return new Promise(function(n,i){var o;if(null!==(o=navigator.mediaDevices)&&void 0!==o&&o.enumerateDevices){var a=!1;t.audio&&t.video?a=e.audioPermitted&&e.videoPermitted:t.audio?a=e.audioPermitted:t.video&&(a=e.videoPermitted),navigator.mediaDevices.enumerateDevices().then(function(o){var s=o.filter(function(e){return e.deviceId}),c=s.filter(function(e){return"videoinput"===e.kind}),u=s.filter(function(e){return"audioinput"===e.kind}),l=s.filter(function(e){return"audiooutput"===e.kind}),d=[];t.audio&&(d=d.concat(u,l)),t.video&&(d=d.concat(c)),0!==d.length||a||r?d.length?(t.audio&&(e.audioPermitted=!0),t.video&&(e.videoPermitted=!0),n(d)):n(d):(logger$8.info("getUserMedia with",t),navigator.mediaDevices.getUserMedia(t).then(function(r){t.audio&&(e.audioPermitted=!0),t.video&&(e.videoPermitted=!0),r.getTracks().forEach(function(e){e.stop()}),navigator.mediaDevices.enumerateDevices().then(function(e){n(e)},i)},i)),n(s)})}else i(new DingRTCError(ErrorCode.BrowserNotSupported,"enumerateDevices is not supported"))})}}]);var r}(EventEmitter);Object.defineProperty(DeviceManager,"videoPermitted",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(DeviceManager,"audioPermitted",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(DeviceManager,"_instance",{enumerable:!0,configurable:!0,writable:!0,value:new DeviceManager}),Object.defineProperty(DeviceManager,"accGetMedia",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(DeviceManager,"getPlaybackDevices",{enumerable:!0,configurable:!0,writable:!0,value:function(){return DeviceManager.getDevices({audio:!0}).then(function(e){return e.filter(function(e){return"audiooutput"===e.kind})}).catch(function(e){throw parseAudioDeviceError(e)})}}),Object.defineProperty(DeviceManager,"getCameras",{enumerable:!0,configurable:!0,writable:!0,value:function(){return DeviceManager.getDevices({video:!0}).then(function(e){return logger$8.info("getCameras",e),e.filter(function(e){return"videoinput"===e.kind}).map(function(e,t){var r={deviceId:e.deviceId,kind:e.kind,groupId:e.groupId,label:e.label||"camera ".concat(t)};return _objectSpread$a(_objectSpread$a({},r),{},{toJSON:function(){return r}})})}).catch(function(e){throw logger$8.error("getCameras error",e),parseVideoDeviceError(e)})}}),Object.defineProperty(DeviceManager,"getMicrophones",{enumerable:!0,configurable:!0,writable:!0,value:function(){return DeviceManager.getDevices({audio:!0}).then(function(e){return logger$8.info("getMicrophones",e),e.filter(function(e){return"audioinput"===e.kind})}).catch(function(e){throw logger$8.error("getMicrophones error",e),parseAudioDeviceError(e)})}});var parseVideoDimension=function(e){return{width:VideoDimensions[e][0],height:VideoDimensions[e][1]}},addAudioTrackAttribute=function(e){var t,r=Object.create({}),n={};null!==(t=navigator)&&void 0!==t&&null!==(t=t.mediaDevices)&&void 0!==t&&t.getSupportedConstraints&&(n=navigator.mediaDevices.getSupportedConstraints(),console.log(n));var i=e.AEC,o=e.AGC,a=e.ANS;return e.deviceId&&(Environment.isSafari()?r.deviceId=e.deviceId:r.deviceId={exact:e.deviceId}),n.autoGainControl&&(r.autoGainControl={ideal:null==o||o}),n.echoCancellation&&(r.echoCancellation={ideal:null==i||i}),n.noiseSuppression&&(r.noiseSuppression={ideal:null==a||a}),r},createMediaStream=function(e){if(!isObject(e)||!e.audio&&!e.video)return Promise.reject(new TypeError("Invalid constrains"));var t=e.audio,r=e.video;if(!isScreenCast(e)&&"object"===_typeof$3(t)&&t.source===exports.AudioSourceInfo.SCREENCAST)return Promise.reject(new TypeError("Cannot share screen without video."));if(isScreenCast(e)&&"object"===_typeof$3(t)&&t.source!==exports.AudioSourceInfo.SCREENCAST)return Promise.reject(new TypeError("Cannot capture video from screen cast while capture audio from other source."));if(!t&&!r)return Promise.reject(new TypeError("At least one of audio and video must be requested."));var n={};if("object"===_typeof$3(t)&&t.source===exports.AudioSourceInfo.MIC||"object"===_typeof$3(t)&&t.source===exports.AudioSourceInfo.SCREENCAST?n.audio=addAudioTrackAttribute(t):n.audio=e.audio,"object"===_typeof$3(r)){var i,o=r.frameRate,a=r.deviceId,s=r.source,c=r.facingMode,u=r.displaySurface,l=r.dimension;n.video={},isNumber(o)&&(n.video.frameRate=Math.min(r.frameRate,30)),l&&(i=parseVideoDimension(l)),i&&i.width&&i.height&&(s===exports.VideoSourceInfo.SCREENCAST||Environment.isFirefox()?(n.video.width=i.width,n.video.height=i.height):(n.video.width={ideal:i.width,max:i.width},n.video.height={ideal:i.height,max:i.height})),isString(a)&&a&&(n.video.deviceId={exact:a}),s===exports.VideoSourceInfo.SCREENCAST&&(Environment.isFirefox()&&(n.video.mediaSource="screen"),u&&["browser","window","monitor"].includes(u)&&(n.video.displaySurface=u)),c&&["user","environment"].includes(c)&&(n.video.facingMode=c)}else n.video=r;return DeviceManager.getMedias(e,n)},isVideoStreamPlayable=function(e){if(!e)return!1;var t=e.getVideoTracks()[0];return t&&t.enabled&&!t.muted},getDeltaDurationInSeconds=function(e,t){var r=(e.timestamp-((null==t?void 0:t.timestamp)||e.timestamp))/1e3;return r<=0&&(r=1),r},transNativeAndWebNetworkRank=function(e,t){return null!=e?[2,4,6,0][e]:null!==t?[3,0,0,0,1,1,2][t]:void 0},getDelta=function(e,t){isNaN(e)&&(e=0),isNaN(t)&&(t=0);var r=e-t;return r<0&&(r=e),r},multiTryExecute=function(e){var t=e.fn,r=e.times,n=e.interval,i=void 0===n?0:n,o=e.resolve,a=e.reject,s=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){var n,s,c;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:s=0;case 1:if(!(s<r)){e.next=7;break}return e.prev=2,e.next=3,t();case 3:return n=e.sent,null==o||o(n),e.abrupt("continue",7);case 4:if(e.prev=4,c=e.catch(2),s!==r-1){e.next=5;break}return null==a||a(c),e.abrupt("return",c);case 5:return e.next=6,asyncDelayMs(i);case 6:s++,e.next=1;break;case 7:return e.abrupt("return",n);case 8:case"end":return e.stop()}},e,null,[[2,4]])}));return function(){return e.apply(this,arguments)}}();return s()},asyncDelayMs=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(!(t>0)){e.next=1;break}return e.next=1,new Promise(function(e){setTimeout(e,t)});case 1:case"end":return e.stop()}},e)}));return function(t){return e.apply(this,arguments)}}(),taskQueue=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1,t=[],r=0,n=!1,i=function(){for(;r<e&&t.length;){r++;var n=t.shift();n&&n().finally(function(){r--,i()})}};return{add:function(e){t.push(e),n&&i()},start:function(){n=!0,i()}}},awaitTime=function(e){return new Promise(function(t){addTimer(t,1e3*e)})},candidateToPlainObj=function(e){return e?{address:e.address,candidate:e.candidate,component:e.component,foundation:e.foundation,port:e.port,priority:e.priority,protocol:e.protocol,relatedAddress:e.relatedAddress,relatedPort:e.relatedPort,relayProtocol:e.relayProtocol,sdpMLineIndex:e.sdpMLineIndex,sdpMid:e.sdpMid,tcpType:e.tcpType,type:e.type,usernameFragment:e.usernameFragment}:e},logger$7=getReporter().getLoggerWithPrefix("[rtc-mediaElPool]"),MEDIA_ELEMENT_INTERSECTING_ATTR="rtc-intersecting",MEDIA_ELEMENT_INTERSECTING_ATTR_VALUES={visible:"visible",invisible:"invisible"},MEDIA_ELEMENT_EVENT_NAMES=["abort","canplay","canplaythrough","durationchange","emptied","ended","error","loadeddata","loadedmetadata","loadstart","pause","play","playing","ratechange","seeked","seeking","stalled","suspend","volumechange","waiting"],MEDIA_PLAYBACK_CHECK_PERIOD_MS=4e3,getLabel=function(e){return"".concat(null==e?void 0:e.getAttribute(MEDIA_ELEMENT_LABEL_ATTR),"-").concat(null==e?void 0:e.rtcPurpose)},isVideoTagIntersectingVisible=function(e){return e&&e.getAttribute(MEDIA_ELEMENT_INTERSECTING_ATTR)===MEDIA_ELEMENT_INTERSECTING_ATTR_VALUES.visible},MediaElementPool=function(){return _createClass$1(function e(t,r){var n=this;_classCallCheck$1(this,e),Object.defineProperty(this,"mediaElementCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"mediaElementPool",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"mediaElementsInUse",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"allElements",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"hasActivated",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"mediaKind",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"mediaPlaybackCheckInterval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"debouncer",{enumerable:!0,configurable:!0,writable:!0,value:new Debouncer}),Object.defineProperty(this,"currentTimeOfLastCheckMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"observer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_activatedListener",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"destroy",{enumerable:!0,configurable:!0,writable:!0,value:function(){n.mediaElementPool.forEach(function(e){return n._resetMediaElement(e)}),n.mediaElementPool=[],n.allElements.clear(),n.mediaElementsInUse.forEach(function(e){return n._resetMediaElement(e)}),n.mediaElementsInUse=[],document.removeEventListener("click",n._onUserInteraction),document.removeEventListener("touchstart",n._onUserInteraction),document.removeEventListener("visibilitychange",n._tryReloadOnPauseAndErrorWhenVisibleTriggerByVisible),n.mediaPlaybackCheckInterval&&(removeTimer(n.mediaPlaybackCheckInterval,"interval"),n.mediaPlaybackCheckInterval=null),[].concat(_toConsumableArray(n.mediaElementPool),_toConsumableArray(n.mediaElementsInUse)).forEach(function(e){var t;return null===(t=n.observer)||void 0===t?void 0:t.unobserve(e)})}}),Object.defineProperty(this,"_tryReloadOnPauseAndErrorWhenVisible",{enumerable:!0,configurable:!0,writable:!0,value:function(e){n.mediaElementsInUse.forEach(function(t){if(t.srcObject){var r=t.srcObject;if(t.error&&(logger$7.debug("".concat(e,": tag=").concat(t.tagName," ").concat(getLabel(t)," has error, error=").concat(t.error,", doc.visibilityState=").concat(document.visibilityState,", mediaStream="),getPlainMediaStreamInfo(r)),"visible"===document.visibilityState&&isVideoStreamPlayable(r)&&t.load()),t.paused){var i=!1;if(n.hasActivated&&"video"===n.mediaKind?isVideoTagIntersectingVisible(t)&&"visible"===document.visibilityState&&"visible"===getComputedStyle(t).visibility&&(i=!0):i=!0,i){var o="".concat(e,": ").concat(getLabel(t)," paused, doc.visibilityState=").concat(document.visibilityState,", intersecting=").concat(t.getAttribute(MEDIA_ELEMENT_INTERSECTING_ATTR),", mediaStream="),a=getPlainMediaStreamInfo(r);logger$7.error(o,a),isVideoStreamPlayable(r)&&t.load(),t.paused&&t.play().catch(function(e){console.error("inPoll",e)})}}}}),n.debouncer.debounce(n._tryReloadOnCurrentTimeFreeze.bind(n,e),1e3)}}),Object.defineProperty(this,"_tryReloadOnCurrentTimeFreeze",{enumerable:!0,configurable:!0,writable:!0,value:function(e){n.mediaElementsInUse.forEach(function(t){if(t.srcObject){var r=t.srcObject,i="video"===n.mediaKind?r.getVideoTracks()[0]:void 0;if(!t.paused&&n.currentTimeOfLastCheckMap.get(t)===t.currentTime&&"video"===n.mediaKind&&!0!==(null==i?void 0:i.muted))return logger$7.error("".concat(e,": tag=").concat(t.tagName," label=").concat(getLabel(t),", currentTime Stop, doc.visibilityState=").concat(document.visibilityState,", curTime=").concat(t.currentTime,", mediaStream="),getPlainMediaStreamInfo(r)),void("visible"===document.visibilityState&&isVideoStreamPlayable(r)&&t.load());n.currentTimeOfLastCheckMap.set(t,t.currentTime)}})}}),Object.defineProperty(this,"_tryReloadOnPauseAndErrorWhenVisibleTriggerByVisible",{enumerable:!0,configurable:!0,writable:!0,value:function(){n._tryReloadOnPauseAndErrorWhenVisible("visibilityChange")}}),Object.defineProperty(this,"_elementDefaultErrorHandler",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t=e.target,r="error event on ".concat(n.mediaKind," playback, mediaStream="),i=getPlainMediaStreamInfo(null==t?void 0:t.srcObject),o=null==t?void 0:t.error;logger$7.error(r,i,o&&{code:null==o?void 0:o.code,message:null==o?void 0:o.message})}}),Object.defineProperty(this,"_elementDefaultPauseHandler",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t=e.target,r="pause event on ".concat(n.mediaKind," playback, mediaStream="),i=getPlainMediaStreamInfo(null==t?void 0:t.srcObject),o=null==t?void 0:t.error;logger$7.debug(r,i,o&&{code:null==o?void 0:o.code,message:null==o?void 0:o.message})}}),Object.defineProperty(this,"_elementDefaultPlayHandler",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t=e.target,r="play event on ".concat(n.mediaKind," playback, mediaStream="),i=getPlainMediaStreamInfo(null==t?void 0:t.srcObject);logger$7.debug(r,i)}}),Object.defineProperty(this,"_onUserInteraction",{enumerable:!0,configurable:!0,writable:!0,value:function(){var e=[].concat(_toConsumableArray(n.mediaElementPool),_toConsumableArray(n.mediaElementsInUse));if(!n.hasActivated){n.hasActivated=!0;var t="".concat(n.mediaKind," good! media elements activated by click");if(logger$7.debug(t),e.forEach(function(e){e.load()}),logger$7.info("load all for activate"),n._activatedListener)try{n._activatedListener()}catch(e){logger$7.error("error occurred when exec activatedListener",tryJsonStringify(e))}else logger$7.debug("ignore activatedListener for there is no one")}n._tryReloadOnPauseAndErrorWhenVisible("userInteract")}}),logger$7.debug("build ".concat(t," pool size"),r),this.mediaElementCount=r,this.mediaElementsInUse=[],this.mediaElementPool=[],this.mediaKind=t,window.IntersectionObserver&&(this.observer=new IntersectionObserver(function(e){e.forEach(function(e){var t,r;e.isIntersecting?null===(t=e.target)||void 0===t||t.setAttribute(MEDIA_ELEMENT_INTERSECTING_ATTR,MEDIA_ELEMENT_INTERSECTING_ATTR_VALUES.visible):null===(r=e.target)||void 0===r||r.setAttribute(MEDIA_ELEMENT_INTERSECTING_ATTR,MEDIA_ELEMENT_INTERSECTING_ATTR_VALUES.invisible)})}));for(var i=1;i<=r;i++){var o=this._createElement("".concat(t,"-").concat(i));this.mediaElementPool.push(o),this.allElements.add(o)}document.addEventListener("click",this._onUserInteraction,!0),document.addEventListener("touchstart",this._onUserInteraction,!0),document.addEventListener("visibilitychange",this._tryReloadOnPauseAndErrorWhenVisibleTriggerByVisible,!0),this.mediaPlaybackCheckInterval=addTimer(function(){n.hasActivated&&n._tryReloadOnPauseAndErrorWhenVisible("intervalCheck")},MEDIA_PLAYBACK_CHECK_PERIOD_MS,"interval")},[{key:"addAtttribute",value:function(e){if(e.autoplay=!0,e.setAttribute(MEDIA_ELEMENT_LABEL_ATTR,"toReused"),e instanceof HTMLVideoElement)e.muted=!0,e.playsInline=!0,e.controls=!1,e.setAttribute("webkit-playsinline","true"),e.setAttribute("x5-video-player-type","h5"),e.setAttribute("x5-playsinline","true");else{var t,r=e;r.volume=1,null===(t=r.setSinkId)||void 0===t||t.call(r,"")}}},{key:"popElement",value:function(e){var t;return(t=this.mediaElementPool.shift())?logger$7.info("".concat(this.mediaKind," pop label=").concat(getLabel(t)," for ").concat(e)):(t=this._createElement("".concat(this.mediaKind,"-").concat(++this.mediaElementCount)),logger$7.info("".concat(this.mediaKind," create new videoEl for no more video element in pool"))),this.mediaElementsInUse.push(t),this._resetMediaElement(t),t.addEventListener("error",this._elementDefaultErrorHandler),t.addEventListener("pause",this._elementDefaultPauseHandler),t.addEventListener("play",this._elementDefaultPlayHandler),t.rtcPurpose=e||"",t}},{key:"pushElement",value:function(e){if(this.allElements.has(e)){var t=this.mediaElementsInUse;this.mediaElementsInUse=this.mediaElementsInUse.filter(function(t){return t!==e}),t.length!==this.mediaElementsInUse.length&&(logger$7.debug("".concat(this.mediaKind," pushed"),getLabel(e)),this.mediaElementPool.push(e),this._resetMediaElement(e))}}},{key:"isMediaElementActivated",value:function(){return this.hasActivated}},{key:"setActivateListener",value:function(e){this._activatedListener=e}},{key:"_createElement",value:function(e){var t,r=document.createElement(this.mediaKind);return null===(t=this.observer)||void 0===t||t.observe(r),this.addAtttribute(r),r.setAttribute(MEDIA_ELEMENT_LABEL_ATTR,e),r}},{key:"_resetMediaElement",value:function(e){MEDIA_ELEMENT_EVENT_NAMES.forEach(function(t){e["on".concat(t)]=null}),e.removeEventListener("error",this._elementDefaultErrorHandler),e.removeEventListener("pause",this._elementDefaultPauseHandler),e.removeEventListener("play",this._elementDefaultPlayHandler),e.style.cssText="",e.className="",this.addAtttribute(e),e.srcObject=null}}])}(),audioElementMgr,videoElementMgr,getAudioElementPool=function(){return audioElementMgr||initMediaElementPool(),audioElementMgr},getVideoElementPool=function(){return videoElementMgr||initMediaElementPool(),videoElementMgr};window.getAudioElementPool=getAudioElementPool,window.getVideoElementPool=getVideoElementPool;var INIT_AUDIO_TAG_COUNT=2,INIT_VIDEO_TAG_COUNT=Environment.isIOS()||Environment.isAndroid()?9:25,initMediaElementPool=function(){audioElementMgr||(audioElementMgr=new MediaElementPool("audio",INIT_AUDIO_TAG_COUNT)),videoElementMgr||(videoElementMgr=new MediaElementPool("video",INIT_VIDEO_TAG_COUNT))},logger$6=getReporter().getLoggerWithPrefix("[rtc-actx]"),audioContext=null,getAudioContext=function(){if(audioContext||(audioContext=new AudioContext),"running"!==audioContext.state){var e=setTimeout(function(){var e="timeout for resume audioContext, probably page still has no user gesture like click or touch";console.error(e),logger$6.error(e)},2e3);audioContext.resume().finally(function(){clearTimeout(e)})}return audioContext},mergeAudioTracks=function(e){var t=e.getAudioTracks(),r=getAudioContext().createMediaStreamDestination();return t.forEach(function(e){getAudioContext().createMediaStreamSource(new MediaStream([e])).connect(r)}),r.stream.getAudioTracks()[0]},setVideoElementStyle=function(e,t){if(e.style.width="100%",e.style.height="100%",t){var r=t.mirror,n=t.fit;!0===r&&(e.style.transform="scaleX(-1)"),n&&(e.style.objectFit=n)}},getAudioVolumeLevel=function(e,t){t.connect(e),e.fftSize=2048,e.smoothingTimeConstant=.4;var r=new Float32Array(e.fftSize);if(e.getFloatTimeDomainData)e.getFloatTimeDomainData(r);else{var n=new Uint8Array(e.fftSize);e.getByteTimeDomainData(n);for(var i=0;i<r.length;++i)r[i]=n[i]/128-1}for(var o=0,a=0;a<r.length;a++)o+=r[a]*r[a];return Math.max(10*Math.log10(o/r.length)+100,0)/100},getCurrentFrame=function(e){var t=document.createElement("canvas"),r=t.getContext("2d"),n=e.videoHeight,i=e.videoWidth;return t.width=i,t.height=n,r.drawImage(e,0,0,i,n),t.toDataURL("image/png")},audioElementPool=getAudioElementPool(),videoElementPool=getVideoElementPool(),logger$5=getReporter().getLoggerWithPrefix("[rtc-playerMgr]"),PlayController=_createClass$1(function e(t,r,n,i){var o=this;_classCallCheck$1(this,e),Object.defineProperty(this,"mediaEl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"playerConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"mediaWrapperEl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"track",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"snapshotMediaStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"canvas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"snapshotInterval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"checkSwitchSnapshotInterval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lastCheckResult",{enumerable:!0,configurable:!0,writable:!0,value:{msTrackPlayable:!1,elPlaying:!1}}),Object.defineProperty(this,"isPlayerPlaying",{enumerable:!0,configurable:!0,writable:!0,value:function(){return o.mediaEl&&o.mediaEl.currentTime>0&&!o.mediaEl.paused&&!o.mediaEl.ended&&o.mediaEl.readyState>=2}}),Object.defineProperty(this,"snapshot",{enumerable:!0,configurable:!0,writable:!0,value:function(){var e,t,r=o.track.getMediaStreamTrack(),n="live"===(null==r?void 0:r.readyState)&&(null==r?void 0:r.enabled)&&!(null!=r&&r.muted);if(clientConfig._holdVideoLastFrame&&(n&&(null===(e=o.mediaEl)||void 0===e||null===(e=e.srcObject)||void 0===e||null===(t=e.getVideoTracks)||void 0===t||null===(t=t.call(e))||void 0===t?void 0:t[0])===r)){var i=o.canvas.getContext("2d");i.clearRect(0,0,o.canvas.width,o.canvas.height);var a=o.mediaEl.videoHeight,s=o.mediaEl.videoWidth;o.canvas.width===s&&o.canvas.height===a||(o.canvas.width=s,o.canvas.height=a),i.drawImage(o.mediaEl,0,0,s,a)}}}),Object.defineProperty(this,"checkSwitchSnapshot",{enumerable:!0,configurable:!0,writable:!0,value:function(){var e,t,r,n,i,a,s=o.track.getMediaStreamTrack(),c="live"===(null==s?void 0:s.readyState)&&(null==s?void 0:s.enabled)&&!(null!=s&&s.muted);c===o.lastCheckResult.msTrackPlayable&&o.isPlayerPlaying()===o.lastCheckResult.elPlaying||logger$5.info("rtcTrackId=".concat(o.track.getTrackId()," play change trackPlayable=").concat(c," isPlaying=").concat(o.isPlayerPlaying()),{msTrackReadyState:null==s?void 0:s.readyState,msTrackEnabled:null==s?void 0:s.enabled,msTrackMuted:null==s?void 0:s.muted,elCurrentTime:null===(e=o.mediaEl)||void 0===e?void 0:e.currentTime,elPaused:null===(t=o.mediaEl)||void 0===t?void 0:t.paused,elEnded:null===(r=o.mediaEl)||void 0===r?void 0:r.ended,elReadyState:null===(n=o.mediaEl)||void 0===n?void 0:n.readyState});(o.lastCheckResult={msTrackPlayable:c,elPlaying:o.isPlayerPlaying()},clientConfig._holdVideoLastFrame)&&(c&&(null===(i=o.mediaEl)||void 0===i||null===(i=i.srcObject)||void 0===i||null===(a=i.getVideoTracks)||void 0===a||null===(a=a.call(i))||void 0===a?void 0:a[0])!==s?o.switchOriginVideo():c||o.mediaEl.srcObject===o.snapshotMediaStream||o.switchSnapshot())}}),Object.defineProperty(this,"startCheckPlayState",{enumerable:!0,configurable:!0,writable:!0,value:function(){"video"===o.track.trackMediaType&&(logger$5.info("startCheckPlayState trackid=",o.track.getTrackId()),o.snapshotInterval=setInterval(o.snapshot,300),o.checkSwitchSnapshotInterval=setInterval(o.checkSwitchSnapshot,150))}}),Object.defineProperty(this,"stopCheckPlayState",{enumerable:!0,configurable:!0,writable:!0,value:function(){var e,t;logger$5.info("stopCheckPlayState trackid=",null===(e=o.track)||void 0===e||null===(t=e.getTrackId)||void 0===t?void 0:t.call(e)),clearInterval(o.snapshotInterval),clearInterval(o.checkSwitchSnapshotInterval)}}),Object.defineProperty(this,"playVideo",{enumerable:!0,configurable:!0,writable:!0,value:function(){var e;logger$5.info("playVideo",o.track.getTrackId(),null===(e=o.mediaWrapperEl)||void 0===e?void 0:e.getAttribute(RTC_SDK_PLAYER_CONTAINER_LABEL_ATTR_NAME)),o.mediaWrapperEl.appendChild(o.mediaEl),o.mediaEl.pause();var t=o.track.sfuStream||new MediaStream([o.track.getMediaStreamTrack()]);o.mediaEl.srcObject=t,o.mediaEl.play().catch(function(e){var t,r;"AbortError"!==e.name&&logger$5.error("play video error trackid=",null===(t=o.track)||void 0===t||null===(r=t.getTrackId)||void 0===r?void 0:r.call(t),tryJsonStringify(e))}),o.stopCheckPlayState(),o.startCheckPlayState()}}),Object.defineProperty(this,"playAudio",{enumerable:!0,configurable:!0,writable:!0,value:function(){var e=o.track.sfuStream||new MediaStream([o.track.getMediaStreamTrack()]);o.mediaEl.srcObject=e,o.mediaEl.play().catch(function(e){var t,r;"AbortError"!==e.name&&logger$5.error("play audio error trackid=",null===(t=o.track)||void 0===t||null===(r=t.getTrackId)||void 0===r?void 0:r.call(t),tryJsonStringify(e))}),o.stopCheckPlayState(),o.startCheckPlayState()}}),Object.defineProperty(this,"stopPlay",{enumerable:!0,configurable:!0,writable:!0,value:function(){var e,t;if(logger$5.info("stopPlay",o.track.getTrackId(),null===(e=o.mediaWrapperEl)||void 0===e?void 0:e.getAttribute(RTC_SDK_PLAYER_CONTAINER_LABEL_ATTR_NAME)),o.stopCheckPlayState(),o.mediaEl&&o.track){var r,n;if(o.mediaEl.pause(),null!==(t=o.mediaWrapperEl)&&void 0!==t&&t.contains(o.mediaEl))null===(r=o.mediaWrapperEl)||void 0===r||null===(n=r.removeChild)||void 0===n||n.call(r,o.mediaEl);o.mediaEl.srcObject=null,o.canvas=null,"audio"===o.track.trackMediaType?audioElementPool.pushElement(o.mediaEl):videoElementPool.pushElement(o.mediaEl)}}}),Object.defineProperty(this,"switchSnapshot",{enumerable:!0,configurable:!0,writable:!0,value:function(){logger$5.info("switchSnapshot trackid",o.track.getTrackId()),o.mediaEl.srcObject=o.snapshotMediaStream,o.mediaEl.play().catch(function(e){logger$5.info("snapshot play error, trackid",o.track.getTrackId(),tryJsonStringify(e))})}}),Object.defineProperty(this,"switchOriginVideo",{enumerable:!0,configurable:!0,writable:!0,value:function(){setTimeout(function(){var e,t,r=o.track.getMediaStreamTrack();if("live"===(null==r?void 0:r.readyState)&&(null==r?void 0:r.enabled)&&!(null!=r&&r.muted)&&(null===(e=o.mediaEl)||void 0===e||null===(e=e.srcObject)||void 0===e||null===(t=e.getVideoTracks)||void 0===t||null===(t=t.call(e))||void 0===t?void 0:t[0])!==r){logger$5.info("switchOriginVideo trackid",o.track.getTrackId());var n=o.track.sfuStream||new MediaStream([o.track.getMediaStreamTrack()]);o.mediaEl.srcObject=n,o.mediaEl.play().catch(function(e){logger$5.info("switchOriginVideo play error, trackid",o.track.getTrackId(),tryJsonStringify(e))})}},1e3)}}),this.mediaWrapperEl=i,this.mediaWrapperEl&&!this.mediaWrapperEl.getAttribute(RTC_SDK_PLAYER_CONTAINER_LABEL_ATTR_NAME)&&this.mediaWrapperEl.setAttribute(RTC_SDK_PLAYER_CONTAINER_LABEL_ATTR_NAME,"container_".concat(e.containerRtcLabelAcc++)),this.track=t,this.playerConfig=r,this.mediaEl=n,this.mediaEl.setAttribute(RTC_SDK_EL_DATA_ATTR_NAME,this.track.getTrackId()),this.canvas=document.createElement("canvas"),this.canvas.setAttribute(RTC_SDK_EL_DATA_ATTR_NAME,this.track.getTrackId()),this.snapshotMediaStream=this.canvas.captureStream(4)});Object.defineProperty(PlayController,"containerRtcLabelAcc",{enumerable:!0,configurable:!0,writable:!0,value:0});var PlayerManager=function(){return _createClass$1(function e(){_classCallCheck$1(this,e),Object.defineProperty(this,"playControllerArr",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.playControllerArr=[]},[{key:"getElement",value:function(e){return this.playControllerArr.filter(function(t){var r;return(null===(r=t.track)||void 0===r?void 0:r.getTrackId())===e.getTrackId()}).map(function(e){return e.mediaEl})}},{key:"getPlayCtrls",value:function(e){return this.playControllerArr.filter(function(t){var r;return(null===(r=t.track)||void 0===r?void 0:r.getTrackId())===e.getTrackId()})}},{key:"play",value:function(e,t,r){var n,i=this;logger$5.info("call play",e.getTrackId(),t instanceof HTMLElement?t.tagName:t,r);var o=e.getTrackId(),a=e.sfuStream||new MediaStream([e.getMediaStreamTrack()]);if("video"===e.trackMediaType){var s,c=this.findDom(t);if(!c)throw new DingRTCError(ErrorCode.InvaildArgument,"wrapper dom not found");var u=r||{},l=u.mirror,d=u.fit;if((n=this.playControllerArr.find(function(e){return e.mediaWrapperEl===c}))&&(null===(s=n.track)||void 0===s?void 0:s.getTrackId())!==(null==e?void 0:e.getTrackId()))return this.stopPlay(n.track,t),void this.play(e,t,r);if(n)n.mediaEl.pause(),!e.sourceMirror!=!l?n.mediaEl.style.transform="scaleX(-1)":n.mediaEl.style.transform="",d&&(n.mediaEl.style.objectFit=d),n.mediaEl.srcObject=a,n.mediaEl.play().catch(function(e){var t,r;"AbortError"!==e.name&&logger$5.error("play video error trackid=",null===(t=n.track)||void 0===t||null===(r=t.getTrackId)||void 0===r?void 0:r.call(t),tryJsonStringify(e))});else{var p,f=null===(p=this.getPlayCtrls(e))||void 0===p?void 0:p.length;if(f>3){var h,g=["DingRTC WARN: possible memory leak. More than 3 HTMLElement containers are playing the same track.","Please call track.stop to stop playing HTMLElements that will unmount in DOM.","TrackId:",e.getTrackId()];(h=console).warn.apply(h,g),logger$5.info.apply(logger$5,g.concat([f]))}n=new PlayController(e,r,getVideoElementPool().popElement(),c),setVideoElementStyle(n.mediaEl,{mirror:!e.sourceMirror!=!l,fit:d}),n.playVideo(),this.playControllerArr.push(n)}}else(n=this.playControllerArr.find(function(t){var r;return(null===(r=t.track)||void 0===r?void 0:r.getTrackId())===e.getTrackId()}))?(n.mediaEl.pause(),n.mediaEl.srcObject=a,logger$5.info("element loaded",e.getTrackId()),n.mediaEl.load()):((n=new PlayController(e,null,getAudioElementPool().popElement(),null)).playAudio(),this.playControllerArr.push(n));n.mediaEl.paused&&n.mediaEl.play().catch(function(e){"NotAllowedError"===e.name?(logger$5.error("autoplay failed",tryJsonStringify(e)),EventBus.emit("autoplay-failed",i)):"AbortError"!==e.name&&logger$5.warn("".concat(o," play error"),tryJsonStringify(e))})}},{key:"isPlaying",value:function(e){return this.playControllerArr.filter(function(t){var r;return(null===(r=t.track)||void 0===r?void 0:r.getTrackId())===(null==e?void 0:e.getTrackId())}).some(function(e){return e.isPlayerPlaying()})}},{key:"stopPlay",value:function(e,t){var r;logger$5.info("call stop play",e.getTrackId());var n=this.findDom(t),i=this.playControllerArr.filter(function(r){var i;return(null===(i=r.track)||void 0===i?void 0:i.getTrackId())===(null==e?void 0:e.getTrackId())&&(!t||r.mediaWrapperEl===n)});if(i.length){i.forEach(function(e){e.stopPlay()});var o=this.playControllerArr.filter(function(e){return!i.includes(e)});(r=this.playControllerArr).splice.apply(r,[0,this.playControllerArr.length].concat(_toConsumableArray(o)))}}},{key:"findDom",value:function(e){if(!e)return null;var t="string"==typeof e?document.querySelector(e):e;return document.contains(t)?t:null}}])}(),playerMgr$2=new PlayerManager,getPlayerManager=function(){return playerMgr$2};function _callSuper$k(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$k()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$k(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$k=function(){return!!e})()}function _superPropGet$4(e,t,r,n){var i=_get(_getPrototypeOf$1(e.prototype),t,r);return 2&n&&"function"==typeof i?function(e){return i.apply(r,e)}:i}window.playerMgr=playerMgr$2;var reporter=getReporter(),trace=reporter.trace,logger$4=reporter.getLoggerWithPrefix("[rtc-track]"),simpleLogger$2=logger$4,playerManager=getPlayerManager(),Track=function(e){function t(e,r){var n;return _classCallCheck$1(this,t),n=_callSuper$k(this,t),Object.defineProperty(n,"trackMediaType",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"source",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"logger",{enumerable:!0,configurable:!0,writable:!0,value:trace}),Object.defineProperty(n,"sourceNode",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"analyser",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"trackSettings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"sfuStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"mediaStreamTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"trackId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"sourceMirror",{enumerable:!0,configurable:!0,writable:!0,value:!1}),e?(n.trackMediaType=e.kind,n.trackSettings=e.getSettings()):r&&(n.trackMediaType="audio"),"audio"===n.trackMediaType&&(n.analyser=getAudioContext().createAnalyser()),n.trackId="".concat(n.trackMediaType,"_").concat(createUuid(6)),n.setMediaStreamTrack(e,r),n}return _inherits$1(t,e),_createClass$1(t,[{key:"isPlaying",get:function(){return playerManager.isPlaying(this)}},{key:"emit",value:function(e){for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];return logger$4.info("track emit event",e,null==n?void 0:n[0]),_superPropGet$4(t,"emit",this,3)([e].concat(n))}},{key:"getTrackId",value:function(){return this.trackId}},{key:"setMediaStreamTrack",value:function(e,t){var r=this,n=this.mediaStreamTrack;if(n&&(n.onended=null),e||t){var i;if(n&&e&&(e.enabled=n.enabled),"audio"===this.trackMediaType)if(this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),e)this.sourceNode=null===(i=getAudioContext())||void 0===i?void 0:i.createMediaStreamSource(new MediaStream([e]));else if(t){var o,a=mergeAudioTracks(t);this.sourceNode=null===(o=getAudioContext())||void 0===o?void 0:o.createMediaStreamSource(new MediaStream([a]))}e?(this.mediaStreamTrack=e,this.mediaStreamTrack.onended=function(){r.source===exports.VideoSourceInfo.SCREENCAST?r.logger.sendEvent("SCREEN_DEVICE_STOP"):r.source===exports.AudioSourceInfo.MIC?new DingRTCError(ErrorCode.MicInterrupt):r.source===exports.VideoSourceInfo.CAMERA&&new DingRTCError(ErrorCode.CameraInterrupt)}):t&&(this.sfuStream=t)}}},{key:"replaceTrack",value:function(e,t){simpleLogger$2.info("replaceTrack",e,t),t&&this.isPlaying&&this.stopPlay(),this.replaceTrackInner(e,null,!0)}},{key:"replaceTrackInner",value:function(e,t,r){this.setMediaStreamTrack(e,t),this.emit(TRACK_EVENT_NAME,"replace",this),this.innnerPlay({updated:!0})}},{key:"setSource",value:function(e){e===exports.VideoSourceInfo.CAMERA?this.logger.sendEvent("VIDEO_DEVICE_START"):e===exports.VideoSourceInfo.SCREENCAST?this.logger.sendEvent("SCREEN_DEVICE_START"):e===exports.AudioSourceInfo.MIC&&this.logger.sendEvent("AUDIO_DEVICE_START"),this.source=e}},{key:"stop",value:function(e){console.error("The API stop is deprecated. Use stopPlay to stop playing or use close to destroy mediaStream track"),simpleLogger$2.info("stop play track ".concat(this.getTrackId()),e instanceof HTMLElement?e.tagName:e),playerManager.stopPlay(this,e)}},{key:"stopPlay",value:function(e){simpleLogger$2.info("stop play track ".concat(this.getTrackId()),e instanceof HTMLElement?e.tagName:e),playerManager.stopPlay(this,e)}},{key:"innnerPlay",value:function(e){var t=this,r=e.mediaWrapperElement,n=e.config;e.updated?playerManager.getPlayCtrls(this).forEach(function(e){e.mediaWrapperEl?playerManager.findDom(e.mediaWrapperEl)?playerManager.play(t,e.mediaWrapperEl,e.playerConfig):playerManager.stopPlay(t,e.mediaWrapperEl):playerManager.play(t,e.mediaWrapperEl,e.playerConfig)}):playerManager.play(this,r,n);if("audio"===this.trackMediaType){var i=getAudioContext();"running"!==i.state&&simpleLogger$2.error("audioContext not running",i.state)}}},{key:"getMediaStreamTrack",value:function(){return this.mediaStreamTrack}}])}(EventEmitter);function _arrayWithHoles(e){if(Array.isArray(e))return e}function _iterableToArrayLimit(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,i,o,a,s=[],c=!0,u=!1;try{if(o=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;c=!1}else for(;!(c=(n=o.call(r)).done)&&(s.push(n.value),s.length!==t);c=!0);}catch(e){u=!0,i=e}finally{try{if(!c&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(u)throw i}}return s}}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _slicedToArray(e,t){return _arrayWithHoles(e)||_iterableToArrayLimit(e,t)||_unsupportedIterableToArray$d(e,t)||_nonIterableRest()}var is2K=function(e){return e.width>1920&&e.height>1080},simulcastEnabledFinally=function(e){var t;if(!e)return clientConfig.simulcast;var r=null===(t=e.getMediaStreamTrack())||void 0===t?void 0:t.getSettings(),n=(null==r?void 0:r.width)||e.trackSettings.width,i=(null==r?void 0:r.height)||e.trackSettings.height;return clientConfig.simulcast&&e.source===exports.VideoSourceInfo.CAMERA&&!is2K({width:n,height:i})},ResolutionProfile;function ownKeys$9(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function _objectSpread$9(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$9(Object(r),!0).forEach(function(t){_defineProperty(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$9(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}!function(e){e[e.LLD=0]="LLD",e[e.LD=1]="LD",e[e.SD=2]="SD",e[e.HD=3]="HD",e[e.FHD=4]="FHD",e[e.QHD=5]="QHD"}(ResolutionProfile||(ResolutionProfile={}));var ResolutionProfileMap=_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},ResolutionProfile.LLD,"lld"),ResolutionProfile.LD,"ld"),ResolutionProfile.SD,"sd"),ResolutionProfile.HD,"hd"),ResolutionProfile.FHD,"fhd"),ResolutionProfile.QHD,"qhd"),ResolutionRange={high:[2764800,4915200],QHD:[2764800,4915200],FHD:[1228800,2764800],HD:[307200,1228800],SD:[76800,307200],LD:[0,76800],low:[0,76800]},getResolutionLevel=function(e,t){var r={high:VideoProfileType.QHD,low:VideoProfileType.LD,QHD:VideoProfileType.QHD,FHD:VideoProfileType.FHD,HD:VideoProfileType.HD,SD:VideoProfileType.SD,LD:VideoProfileType.LD},n=r[e]||VideoProfileType.None,i=ResolutionRange[e],o=t[t.length-1].width*t[t.length-1].height;if(o<i[0]){var a=Object.entries(ResolutionRange).find(function(e){var t=_slicedToArray(e,2);t[0];var r=t[1];return o>r[0]&&o<=r[1]});n=r[_slicedToArray(a,1)[0]]}return n},calcResolutionInfo=function(e,t){return{resolution:getResolution(e,t),resolutionLevel:getResolutionLevel(e,t)}},getResoLevelNameByResoLevelNum=function(e){return{0:"LLD",1:"LD",2:"LD",4:"SD",8:"HD",16:"FHD",32:"QHD"}[e]},getResolution=function(e,t){var r=ResolutionRange[e],n=t.length,i=t[t.length-1];if(("FHD"===e||"high"===e)&&is2K(i))return i;if(t[0].width*t[0].height>ResolutionRange.FHD[1])return t[0];for(var o=0;n>o;o++){var a=t[o].width*t[o].height;if(a>=r[0]&&r[1]>=a)return t[o]}for(var s=n-1;s>=0;s--){var c=t[s].width*t[s].height;if(r[1]>c)return t[s]}return t[0]},DefaultVideoMaxPixelCount=[49152,76800,307200,1228800,2764800,4915200],DefaultMaxBitrateKbps=[200,350,1e3,1800,2828,5600],DefaultResolution_16_9=[[256,144],[320,180],[640,360],[1280,720],[1920,1080],[2560,1440]],DefaultResolution_4_3=[[256,192],[320,240],[640,480],[1280,960],[1920,1440],[2560,1920]],computeResoLevelName=function(e,t){var r=ResolutionProfile.FHD,n=e*t;return n<=DefaultVideoMaxPixelCount[ResolutionProfile.LLD]?r=ResolutionProfile.LLD:n<=DefaultVideoMaxPixelCount[ResolutionProfile.LD]?r=ResolutionProfile.LD:n<=DefaultVideoMaxPixelCount[ResolutionProfile.SD]?r=ResolutionProfile.SD:n<=DefaultVideoMaxPixelCount[ResolutionProfile.HD]?r=ResolutionProfile.HD:n<=DefaultVideoMaxPixelCount[ResolutionProfile.FHD]?r=ResolutionProfile.FHD:n<=DefaultVideoMaxPixelCount[ResolutionProfile.QHD]&&(r=ResolutionProfile.QHD),r},getTargetResolution=function(e,t,r,n){var i=0,o=0;if(n<=r)return[i=e,o=t];if(t>e){var a=[e,t];t=a[0],e=a[1]}if(16*t==9*e)i=DefaultResolution_16_9[r][0],o=DefaultResolution_16_9[r][1];else if(4*t==3*e)i=DefaultResolution_4_3[r][0],o=DefaultResolution_4_3[r][1];else{var s=Math.sqrt(1*DefaultResolution_16_9[r][0]*DefaultResolution_16_9[r][1]/e/t);s=1*(i=(i=Math.round(e*s))+15&-16)/e,o=Math.round(t*s)}return[i,o]},getVideoMaxbitrate=function(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(!n){var i=1;30!==r&&(i=Math.sqrt(r/30));var o=DefaultMaxBitrateKbps[computeResoLevelName(e,t)];n=Math.round(Math.max(i*o,50))}return n},getDownByScales=function(e,t){var r=computeResoLevelName(e,t),n=function(n){var i=_slicedToArray(getTargetResolution(e,t,n,r),2);i[0];var o=1/(i[1]/t);return Math.max(o,1)};return{ld:n(ResolutionProfile.LD),sd:n(ResolutionProfile.SD),fhd:n(r)}},getSimulcastSenderEncodings=function(e){var t=e.width,r=e.height,n=e.frameRate,i=e.maxBitrate,o=e.resolutionLevel,a=computeResoLevelName(t,r),s=[],c=a>=ResolutionProfile.HD?3:2,u=function(e){var o=_slicedToArray(getTargetResolution(t,r,e,a),2),s=o[0],c=o[1],u=DefaultMaxBitrateKbps[e]/DefaultMaxBitrateKbps[a],l=1/(c/r);return{targetWidth:s,rid:ResolutionProfileMap[e],targetHeight:c,minBitrate:50,maxFramerate:n,maxBitrate:Math.round(Math.max(30,i*u)),scaleResolutionDownBy:l}};a>ResolutionProfile.LLD&&s.push(_objectSpread$9({activeForBitrateMap:!1,activeForRealuse:Math.pow(2,ResolutionProfile.LLD)===o},u(ResolutionProfile.LLD))),a>ResolutionProfile.LD&&s.push(_objectSpread$9({activeForBitrateMap:c>1,activeForRealuse:Math.pow(2,ResolutionProfile.LD)===o},u(ResolutionProfile.LD))),a>ResolutionProfile.SD&&s.push(_objectSpread$9({activeForBitrateMap:c>2,activeForRealuse:Math.pow(2,ResolutionProfile.SD)===o},u(ResolutionProfile.SD))),a===ResolutionProfile.FHD?(s.push(_objectSpread$9({activeForBitrateMap:!1,activeForRealuse:!1},u(ResolutionProfile.HD))),s.push(_objectSpread$9({activeForBitrateMap:!0,activeForRealuse:clientConfig.republish?Math.pow(2,4)===o||o===Math.pow(2,3):Math.pow(2,4)===o},u(ResolutionProfile.FHD)))):s.push(_objectSpread$9({activeForBitrateMap:!0,activeForRealuse:Math.pow(2,a)===o},u(a)));for(var l=0,d=0;d<s.length;++d)0!=d&&(s[d].minBitrate=l),l=Math.round(Math.max((s[d].maxBitrate+s[d].minBitrate)/2,s[d].maxBitrate-400));return s.shift(),s},getHighestResoLevelNum=function(e,t){var r=computeResoLevelName(e,t);return Math.pow(2,r)},getSenderEncodingArrAndResoLevel=function(e){var t,r=e.getMaxBitrate(),n=null===(t=e.getMediaStreamTrack())||void 0===t?void 0:t.getSettings(),i=(null==n?void 0:n.width)||e.trackSettings.width,o=(null==n?void 0:n.height)||e.trackSettings.height,a=(null==n?void 0:n.frameRate)||e.trackSettings.frameRate,s=!simulcastEnabledFinally(e),c={resolutionLevel:getHighestResoLevelNum(i,o),encodings:[]};return s?c.encodings=[{maxFramerate:a,maxBitrate:r,scaleResolutionDownBy:1,activeForBitrateMap:!0,activeForRealuse:!0,rid:"",minBitrate:Math.round((r+30)/2),targetWidth:i,targetHeight:o}]:clientConfig.republish?c.encodings=getSimulcastSenderEncodings({width:1920,height:1080,frameRate:30,maxBitrate:getVideoMaxbitrate(1920,1080,30),resolutionLevel:c.resolutionLevel}):c.encodings=getSimulcastSenderEncodings({width:i,height:o,frameRate:a,maxBitrate:r,resolutionLevel:c.resolutionLevel}),c};function ownKeys$8(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function _objectSpread$8(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$8(Object(r),!0).forEach(function(t){_defineProperty(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$8(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function _callSuper$j(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$j()?Reflect.construct(t,r||[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$j(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$j=function(){return!!e})()}function _superPropGet$3(e,t,r,n){var i=_get(_getPrototypeOf$1(e.prototype),t,r);return 2&n&&"function"==typeof i?function(e){return i.apply(r,e)}:i}var playerMgr$1=getPlayerManager(),logger$3=getReporter().getLoggerWithPrefix("[rtc-localtrack]"),LocalTrack=function(e){function t(e){var r;if(_classCallCheck$1(this,t),r=_callSuper$j(this,t,[e]),Object.defineProperty(r,"muted",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"maxBitrate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"enabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"isClosed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),e){var n=e.muted;r.muted=n}return r.enabled=!0,r}return _inherits$1(t,e),_createClass$1(t,[{key:"setMediaStreamTrack",value:function(e){var r=this;_superPropGet$3(t,"setMediaStreamTrack",this,3)([e]),e&&(this.trackSettings=e.getSettings(),e.onended=function(){r.stopPlay(),r.close&&setTimeout(function(){return r.close()},200),r.emit("track-ended")})}},{key:"play",value:function(e,t){logger$3.info("play track ".concat(this.getTrackId()),(null==e?void 0:e.tagName)||e,t),this.innnerPlay({mediaWrapperElement:e,config:t})}},{key:"setEnabled",value:function(e){var t,r=this;return logger$3.info("setEnabled",e),this.isClosed?Promise.reject(new DingRTCError(ErrorCode.InvaildState)):(this.enabled=e,e?this.updateNewTrack().then(function(e){return r.emit(TRACK_EVENT_NAME,"unmute"),e}):(null===(t=this.mediaStreamTrack)||void 0===t||t.stop(),this.setMediaStreamTrack(null),this.source===exports.VideoSourceInfo.CAMERA?this.logger.sendEvent("VIDEO_DEVICE_STOP"):this.source===exports.VideoSourceInfo.SCREENCAST&&this.logger.sendEvent("SCREEN_DEVICE_STOP"),this.emit(TRACK_EVENT_NAME,"mute"),Promise.resolve()))}},{key:"close",value:function(){var e;logger$3.info("".concat(this.source," track:").concat(this.getTrackId()," close")),this.isClosed||(this.isClosed=!0,this.isPlaying&&this.stopPlay(),this.emit(TRACK_EVENT_NAME,"stop",this),null===(e=this.mediaStreamTrack)||void 0===e||e.stop(),this.setMediaStreamTrack(null),this.sourceNode=null,this.analyser=null,this.source===exports.VideoSourceInfo.CAMERA?this.logger.sendEvent("VIDEO_DEVICE_STOP"):this.source===exports.VideoSourceInfo.SCREENCAST&&this.logger.sendEvent("SCREEN_DEVICE_STOP"))}},{key:"setMuted",value:function(e){return logger$3.info("setMuted",e),this.isClosed?Promise.reject(new DingRTCError(ErrorCode.InvaildState)):(this.muted=e,this.mediaStreamTrack.enabled=!e,this.emit(TRACK_EVENT_NAME,e?"mute":"unmute"),Promise.resolve())}},{key:"getAudioTrack",value:function(){var e=this;return logger$3.debug("gengrate new audioTrack"),new Promise(function(t,r){var n;createMediaStream({audio:_objectSpread$8({source:e.source},e.config)}).then(function(e){n=e.getAudioTracks()[0]}).catch(function(e){try{var t=getAudioContext().createOscillator(),i=getAudioContext().createMediaStreamDestination();t.connect(i),n=i.stream.getAudioTracks()[0]}catch(t){logger$3.error("gengrate new audioTrack error",parseAudioDeviceError(e)),r(parseAudioDeviceError(e))}}).finally(function(){n&&t(n)})})}},{key:"getVideoTrack",value:function(){var e=this;return logger$3.info("gengrate new videoTrack",this.config),new Promise(function(t,r){var n,i=_objectSpread$8({source:e.source},e.config);e.config.facingMode&&e.config.deviceId&&(logger$3.info("ignore deviceId param to create videoTrack because facingMode is",e.config.facingMode),delete i.deviceId),createMediaStream({video:i,audio:!1}).then(function(e){n=e.getVideoTracks()[0],t(n)}).catch(function(e){logger$3.error("gengrate new videoTrack error",parseVideoDeviceError(e)),r(parseVideoDeviceError(e))})})}},{key:"updateNewTrack",value:function(){var e=this,t=this.getMediaStreamTrack();return t.onended=null,logger$3.info("stop oldTrack first"),t.stop(),"audio"===this.trackMediaType?this.getAudioTrack().then(function(t){return e.replaceTrackInner(t,null,!0),e.emit(TRACK_EVENT_NAME,"localMixedAudioReplaceTrack",e)}):"video"===this.trackMediaType?this.getVideoTrack().then(function(t){return e.replaceTrackInner(t,null,!0)}):void 0}},{key:"setDevice",value:(r=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n,i;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(logger$3.info("setDevice",t),!this.isClosed){e.next=1;break}return e.abrupt("return");case 1:if(!(this instanceof CameraVideoTrack)||"user"!==t&&"environment"!==t){e.next=2;break}this.config.facingMode=t,e.next=4;break;case 2:if((this.config.deviceId||(null===(r=this.mediaStreamTrack)||void 0===r||null===(r=r.getSettings())||void 0===r?void 0:r.deviceId)||(null===(n=this.mediaStreamTrack)||void 0===n||null===(i=n.getConstraints)||void 0===i||null===(i=i.call(n))||void 0===i?void 0:i.deviceId))!==t){e.next=3;break}return e.abrupt("return");case 3:this.config.deviceId=t;case 4:return e.abrupt("return",this.updateNewTrack());case 5:case"end":return e.stop()}},e,this)})),function(e){return r.apply(this,arguments)})},{key:"getTrackLabel",value:function(){if(logger$3.info("getTrackLabel"),!this.isClosed)return this.mediaStreamTrack.label}},{key:"getMaxBitrate",value:function(){if(!this.isClosed)return this.maxBitrate}}]);var r}(Track),LocalVideoTrack=function(e){function t(e,r){var n;if(_classCallCheck$1(this,t),(n=_callSuper$j(this,t,[e])).config=r,e){var i=e.getSettings(),o=i.width,a=i.height;n.maxBitrate=getVideoMaxbitrate(o,a,r.frameRate,r.maxBitrate)}return n}return _inherits$1(t,e),_createClass$1(t,[{key:"optimizationMode",get:function(){return this.config.optimizationMode}},{key:"setEncoderConfiguration",value:(r=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n,i,o,a,s,c,u,l,d,p,f,h,g;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(logger$3.info("videoTrack ".concat(this.getTrackId()," setEncoderConfiguration"),t),r=t.dimension,n=t.frameRate,i=t.maxBitrate,o=t.optimizationMode,a=t.mirror,!n||!Number.isNaN(n)){e.next=1;break}return e.abrupt("return",Promise.reject(new DingRTCError(ErrorCode.InvaildArgument,"invalid frameRate")));case 1:if(!r||VideoDimensions[r]){e.next=2;break}return e.abrupt("return",Promise.reject(new DingRTCError(ErrorCode.InvaildArgument,"invalid dimension")));case 2:if(!a!=!this.config.mirror&&(this.emit(TRACK_EVENT_NAME,"mirror",a),this.config.mirror=a),o&&o!==this.optimizationMode&&(this.config.optimizationMode=o,this.emit(TRACK_EVENT_NAME,"optimizationMode")),s=!1,r&&this.config.dimension!==r&&(this.config.dimension=r,s=!0),n&&this.config.frameRate!==Math.min(30,n)&&(this.config.frameRate=Math.min(30,n),s=!0),i&&this.maxBitrate!==i&&(s=!0),s){e.next=3;break}return e.abrupt("return",Promise.resolve());case 3:return c=_objectSpread$8({frameRate:this.config.frameRate},parseVideoDimension(this.config.dimension)),u=this.getMediaStreamTrack(),e.prev=4,e.next=5,null==u?void 0:u.applyConstraints(c);case 5:d=null===(l=this.getMediaStreamTrack())||void 0===l?void 0:l.getSettings(),p=d.width,f=d.height,this.maxBitrate=getVideoMaxbitrate(p,f,this.config.frameRate,i),logger$3.info("after applyConstraints",c,this.maxBitrate,getPlainMediaTrackInfo(u)),this.emit(TRACK_EVENT_NAME,"republish",this),e.next=7;break;case 6:throw e.prev=6,g=e.catch(4),h=parseVideoDeviceError(g),logger$3.error("videoTrack ".concat(this.getTrackId()," setEncoderConfiguration error"),h),h;case 7:case"end":return e.stop()}},e,this,[[4,6]])})),function(e){return r.apply(this,arguments)})},{key:"getCurrentFrameData",value:function(){return logger$3.info("getCurrentFrameData"),this.isClosed||!this.isPlaying?null:getCurrentFrame(playerMgr$1.getElement(this)[0])}},{key:"play",value:function(e,r){return logger$3.info("play track ".concat(this.getTrackId()),(null==e?void 0:e.tagName)||e,r),_superPropGet$3(t,"play",this,3)([e,r])}}]);var r}(LocalTrack),LocalAudioTrack=function(e){function t(e){return _classCallCheck$1(this,t),_callSuper$j(this,t,[e])}return _inherits$1(t,e),_createClass$1(t,[{key:"setVolume",value:function(e){logger$3.info("setVolume",e),this.isClosed||playerMgr$1.getElement(this)[0]&&(playerMgr$1.getElement(this)[0].volume=e)}},{key:"getVolume",value:function(){if(logger$3.info("getVolume"),!this.isClosed)return playerMgr$1.getElement(this)[0]?playerMgr$1.getElement(this)[0].volume:void 0}},{key:"getVolumeLevel",value:function(){return this.isClosed?0:getAudioVolumeLevel(this.analyser,this.sourceNode)}},{key:"play",value:function(){return logger$3.info("local audio play"),_superPropGet$3(t,"play",this,3)([])}},{key:"replaceTrack",value:function(e,t){logger$3.info("replaceTrack",e,t),t&&this.isPlaying&&this.stopPlay(),this.replaceTrackInner(e,null,!0),this.emit(TRACK_EVENT_NAME,"localMixedAudioReplaceTrack",this)}}])}(LocalTrack),CameraVideoTrack=function(e){function t(e,r){var n;return _classCallCheck$1(this,t),(n=_callSuper$j(this,t,[e,r])).setSource(exports.VideoSourceInfo.CAMERA),n}return _inherits$1(t,e),_createClass$1(t)}(LocalVideoTrack),MicrophoneAudioTrack=function(e){function t(e,r){var n;return _classCallCheck$1(this,t),(n=_callSuper$j(this,t,[e])).config=r,n.setSource(exports.AudioSourceInfo.MIC),n.analyser=getAudioContext().createAnalyser(),n}return _inherits$1(t,e),_createClass$1(t,[{key:"setVolume",value:function(e){logger$3.info("setVolume",e),this.isClosed||playerMgr$1.getElement(this)[0]&&(playerMgr$1.getElement(this)[0].volume=e)}},{key:"getVolume",value:function(){if(logger$3.info("getVolume"),!this.isClosed)return playerMgr$1.getElement(this)[0]?playerMgr$1.getElement(this)[0].volume:void 0}}])}(LocalAudioTrack),createMicrophoneAudioTrack=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n,i,o,a,s,c,u,l,d,p;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return logger$3.info("createMicrophoneAudioTrack",t),r={AEC:!0,AGC:!0,ANS:!0},i=(n=t||r).AEC,o=void 0===i||i,a=n.AGC,s=void 0===a||a,c=n.ANS,u=void 0===c||c,e.prev=1,e.next=2,createMediaStream({video:!1,audio:{deviceId:null==t?void 0:t.deviceId,source:exports.AudioSourceInfo.MIC,AEC:o,AGC:s,ANS:u}});case 2:return l=e.sent,d=l.getAudioTracks()[0],logger$3.info("MicrophoneAudioTrack created",getPlainMediaTrackInfo(d)),e.abrupt("return",new MicrophoneAudioTrack(d,Object.assign({},t,{AEC:o,AGC:s,ANS:u})));case 3:throw e.prev=3,p=e.catch(1),parseAudioDeviceError(p);case 4:case"end":return e.stop()}},e,null,[[1,3]])}));return function(t){return e.apply(this,arguments)}}(),createCameraVideoTrack=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n,i,o,a,s,c,u,l,d;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return logger$3.info("createCameraVideoTrack",t),r=t.deviceId,n=t.facingMode,i=t.dimension,o=void 0===i?"VD_640x480":i,a=t.optimizationMode,s=void 0===a?"balanced":a,c=Math.min(30,t.frameRate||15),e.prev=1,e.next=2,createMediaStream({video:{deviceId:r,source:exports.VideoSourceInfo.CAMERA,frameRate:c,dimension:o,facingMode:n},audio:!1});case 2:return u=e.sent,l=u.getVideoTracks()[0],logger$3.info("CameraVideoTrack created",getPlainMediaTrackInfo(l)),l.addEventListener("ended",function(){return logger$3.info("cam track ended",l.id)}),l.addEventListener("unmute",function(){return logger$3.info("cam track unmute",l.id)}),l.addEventListener("mute",function(){return logger$3.info("cam track mute",l.id)}),e.abrupt("return",new CameraVideoTrack(l,Object.assign({},t,{frameRate:c,dimension:o,optimizationMode:s})));case 3:throw e.prev=3,d=e.catch(1),parseVideoDeviceError(d);case 4:case"end":return e.stop()}},e,null,[[1,3]])}));return function(t){return e.apply(this,arguments)}}(),createScreenVideoTrack=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return logger$3.info("createScreenVideoTrack config",t),e.abrupt("return",_createScreenTracks(t,"noAudio"));case 1:case"end":return e.stop()}},e)}));return function(t){return e.apply(this,arguments)}}(),_createScreenTracks=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t,r){var n,i,o,a,s,c,u,l,d,p,f,h,g,m;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return logger$3.info("_createScreenVideoTrack",t,r),n=t.displaySurface,i=void 0===n?"monitor":n,o=t.dimension,a=void 0===o?"VD_1920x1080":o,s=t.optimizationMode,c=void 0===s?"detail":s,u=Math.min(t.frameRate||5,30),e.prev=1,e.next=2,createMediaStream({video:{source:exports.VideoSourceInfo.SCREENCAST,displaySurface:i,frameRate:u,dimension:a},audio:"withAudio"===r});case 2:return l=e.sent,p=l.getVideoTracks()[0],logger$3.info("ScreenVideoTrack created",getPlainMediaTrackInfo(p)),p.addEventListener("ended",function(){return logger$3.info("screen video track ended",p.id)}),p.addEventListener("unmute",function(){return logger$3.info("screen video track unmute",p.id)}),p.addEventListener("mute",function(){return logger$3.info("screen video track mute",p.id)}),(f=new LocalVideoTrack(p,Object.assign({},t,{frameRate:u,dimension:a,optimizationMode:c}))).setSource(exports.VideoSourceInfo.SCREENCAST),(g=null===(d=l.getAudioTracks())||void 0===d?void 0:d[0])&&((h=new LocalAudioTrack(g)).setSource(exports.AudioSourceInfo.SCREENCAST),logger$3.info("ScreenAudioTrack created",getPlainMediaTrackInfo(g)),g.addEventListener("ended",function(){return logger$3.info("screen audio track ended",g.id)}),g.addEventListener("unmute",function(){return logger$3.info("screen audio track unmute",g.id)}),g.addEventListener("mute",function(){return logger$3.info("screen audio track mute",g.id)})),e.abrupt("return",h?[f,h]:[f]);case 3:throw e.prev=3,m=e.catch(1),parseScreenShareError(m);case 4:case"end":return e.stop()}},e,null,[[1,3]])}));return function(t,r){return e.apply(this,arguments)}}(),createScreenVideoAndAudioTrack=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return logger$3.info("createScreenVideoAndAudioTrack",t),e.abrupt("return",_createScreenTracks(t,"withAudio"));case 1:case"end":return e.stop()}},e)}));return function(t){return e.apply(this,arguments)}}(),createMicrophoneAndCameraTracks=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t,r){var n,i,o,a,s,c,u,l,d,p,f,h,g,m,v,y,b,S,_,E,T;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return logger$3.info("createMicrophoneAndCameraTracks",t,r),n=Math.min(t.frameRate||15,30),i=t.deviceId,o=t.facingMode,a=t.dimension,s=void 0===a?"VD_640x480":a,c=t.optimizationMode,u=void 0===c?"balanced":c,l={AEC:!0,AGC:!0,ANS:!0},p=(d=r||l).AEC,f=void 0===p||p,h=d.AGC,g=void 0===h||h,m=d.ANS,v=void 0===m||m,e.prev=1,e.next=2,createMediaStream({video:{deviceId:i,source:exports.VideoSourceInfo.CAMERA,frameRate:n,dimension:s,facingMode:o},audio:{deviceId:null==r?void 0:r.deviceId,source:exports.AudioSourceInfo.MIC,AEC:f,AGC:g,ANS:v}});case 2:return y=e.sent,b=y.getVideoTracks()[0],S=y.getAudioTracks()[0],logger$3.info("CameraVideoTrack and MicrophoneTrack created",getPlainMediaStreamInfo(y)),b.addEventListener("ended",function(){return logger$3.info("cam track ended",b.id)}),b.addEventListener("unmute",function(){return logger$3.info("cam track unmute",b.id)}),b.addEventListener("mute",function(){return logger$3.info("cam track mute",b.id)}),S.addEventListener("ended",function(){return logger$3.info("mic track ended",S.id)}),S.addEventListener("unmute",function(){return logger$3.info("mic track unmute",S.id)}),S.addEventListener("mute",function(){return logger$3.info("mic track mute",S.id)}),_=new CameraVideoTrack(b,Object.assign({},t,{frameRate:n,dimension:s,optimizationMode:u})),E=new MicrophoneAudioTrack(S,Object.assign({},Object.assign({},r,{AEC:f,AGC:g,ANS:v}))),e.abrupt("return",[_,E]);case 3:throw e.prev=3,T=e.catch(1),parseVideoDeviceError(T);case 4:case"end":return e.stop()}},e,null,[[1,3]])}));return function(t,r){return e.apply(this,arguments)}}(),createCustomVideoTrack=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n,i,o,a,s,c,u,l,d=arguments;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(r=d.length>1&&void 0!==d[1]?d[1]:exports.VideoSourceInfo.CAMERA,logger$3.info("createCustomVideoTrack",t,r,getPlainMediaTrackInfo(t.mediaStreamTrack)),i=(n=t||{}).mediaStreamTrack,o=n.dimension,a=void 0===o?"VD_640x480":o,s=n.optimizationMode,c=void 0===s?"balanced":s,u=Math.min(t.frameRate||15,30),i instanceof MediaStreamTrack&&"video"===i.kind){e.next=1;break}throw new DingRTCError(ErrorCode.InvaildArgument,"missing video mediaStreamTrack");case 1:return logger$3.info("createCustomVideoTrack for",getPlainMediaTrackInfo(i)),i.addEventListener("ended",function(){return logger$3.info("custom video track ended",i.id)}),i.addEventListener("unmute",function(){return logger$3.info("custom video track unmute",i.id)}),i.addEventListener("mute",function(){return logger$3.info("custom video track mute",i.id)}),(l=new LocalVideoTrack(i,Object.assign({},t,{frameRate:u,dimension:a,optimizationMode:c}))).setSource(r),e.abrupt("return",l);case 2:case"end":return e.stop()}},e)}));return function(t){return e.apply(this,arguments)}}(),createCustomAudioTrack=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n,i,o=arguments;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(r=o.length>1&&void 0!==o[1]?o[1]:"mic",logger$3.info("createCustomAudioTrack",t,r,getPlainMediaTrackInfo(t.mediaStreamTrack)),(n=(t||{}).mediaStreamTrack)instanceof MediaStreamTrack&&"audio"===n.kind){e.next=1;break}throw new DingRTCError(ErrorCode.InvaildArgument,"missing audio mediaStreamTrack");case 1:return logger$3.info("createCustomAudioTrack succeed"),n.addEventListener("ended",function(){return logger$3.info("custom audio track ended",n.id)}),n.addEventListener("unmute",function(){return logger$3.info("custom audio track unmute",n.id)}),n.addEventListener("mute",function(){return logger$3.info("custom audio track mute",n.id)}),(i=new LocalAudioTrack(n)).setSource(r),e.abrupt("return",i);case 2:case"end":return e.stop()}},e)}));return function(t){return e.apply(this,arguments)}}();function _superPropGet$2(e,t,r,n){var i=_get(_getPrototypeOf$1(e.prototype),t,r);return 2&n&&"function"==typeof i?function(e){return i.apply(r,e)}:i}function _callSuper$i(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$i()?Reflect.construct(t,r||[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$i(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$i=function(){return!!e})()}var simpleLogger$1=getReporter().getLoggerWithPrefix("[rtc-remotetrack]"),playerMgr=getPlayerManager(),RemoteTrack=function(e){function t(e,r,n){var i;return _classCallCheck$1(this,t),i=_callSuper$i(this,t,[e,n]),Object.defineProperty(i,"userId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"subscription",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),i.userId=r,i}return _inherits$1(t,e),_createClass$1(t,[{key:"getUserId",value:function(){return simpleLogger$1.info("getUserId"),this.userId}},{key:"onFirstFrame",value:function(){this.emit("first-frame-decoded")}},{key:"attachSubscription",value:function(e){this.subscription&&this.subscription.off("audio-first-frame",this.onFirstFrame),this.subscription=e,null==e||e.on("audio-first-frame",this.onFirstFrame)}}])}(Track),RemoteAudioTrack=function(e){function t(e,r,n){var i;return _classCallCheck$1(this,t),i=_callSuper$i(this,t,[e,r,n]),Object.defineProperty(i,"deviceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),i.deviceId="",i}return _inherits$1(t,e),_createClass$1(t,[{key:"getMediaStreamTrack",value:function(){return clientConfig.audioSFU?mergeAudioTracks(this.sfuStream):_superPropGet$2(t,"getMediaStreamTrack",this,3)([])}},{key:"replaceStream",value:function(e,t){simpleLogger$1.info("replaceRemote Audio",e,t),t&&this.isPlaying&&this.stopPlay(),this.replaceTrackInner(null,e)}},{key:"setVolume",value:function(e){simpleLogger$1.info("setVolume",e),playerMgr.getElement(this)[0]&&(playerMgr.getElement(this)[0].volume=e)}},{key:"getVolume",value:function(){if(simpleLogger$1.info("getVolume"),playerMgr.getElement(this)[0])return playerMgr.getElement(this)[0].volume}},{key:"setSpeaker",value:function(e){var t=this;return simpleLogger$1.info("setSpeaker",e),new Promise(function(r,n){var i,o=playerMgr.getElement(t)[0];o||n(new DingRTCError(ErrorCode.InvaildState,"please playout audio first")),o.setSinkId||n(new DingRTCError(ErrorCode.SpeakerSetNotSupported)),null===(i=o.setSinkId)||void 0===i||i.call(o,e).then(function(){t.deviceId=e,r()}).catch(function(e){n(parseAudioDeviceError(e))})})}},{key:"getVolumeLevel",value:function(){return getAudioVolumeLevel(this.analyser,this.sourceNode)}},{key:"play",value:function(){return simpleLogger$1.info("remote audio play"),_superPropGet$2(t,"innnerPlay",this,3)([{}])}}])}(RemoteTrack),RemoteVideoTrack=function(e){function t(e,r){return _classCallCheck$1(this,t),_callSuper$i(this,t,[e,r])}return _inherits$1(t,e),_createClass$1(t,[{key:"play",value:function(e,r){return simpleLogger$1.info("remote video play",this.getTrackId()),_superPropGet$2(t,"innnerPlay",this,3)([{mediaWrapperElement:e,config:r}])}},{key:"setSourceMirror",value:function(e){e!==this.sourceMirror&&(simpleLogger$1.info("remote video track set Mirror",e),this.sourceMirror=e,this.isPlaying&&_superPropGet$2(t,"innnerPlay",this,3)([{updated:!0}]))}},{key:"getCurrentFrameData",value:function(){return simpleLogger$1.info("getCurrentFrameData"),this.isPlaying?getCurrentFrame(playerMgr.getElement(this)[0]):null}}])}(RemoteTrack),signal_msg;!function(e){var t,r,n,i,o,a,s,c;(t=e.DataType||(e.DataType={}))[t.DATA_TYPE_STREAM=0]="DATA_TYPE_STREAM",t[t.DATA_TYPE_PARTICIPANTS=1]="DATA_TYPE_PARTICIPANTS",t[t.DATA_TYPE_CONFERENCE=2]="DATA_TYPE_CONFERENCE",t[t.DATA_TYPE_GROUP_LIST=3]="DATA_TYPE_GROUP_LIST",t[t.DATA_TYPE_GROUP=4]="DATA_TYPE_GROUP",(r=e.OptType||(e.OptType={}))[r.OPT_TYPE_ADD=0]="OPT_TYPE_ADD",r[r.OPT_TYPE_REMOVE=1]="OPT_TYPE_REMOVE",r[r.OPT_TYPE_UPDATE=2]="OPT_TYPE_UPDATE",(n=e.SyncResponseCode||(e.SyncResponseCode={}))[n.SYNC_OK=0]="SYNC_OK",n[n.SYNC_PART_SUC=10]="SYNC_PART_SUC",n[n.SYNC_DATA_SIZE_LIMITED=11]="SYNC_DATA_SIZE_LIMITED",n[n.SYNC_NOT_SUPPORT_TYPE=12]="SYNC_NOT_SUPPORT_TYPE",n[n.SYNC_NOT_FOUND=13]="SYNC_NOT_FOUND",n[n.SYNC_CHANNEL_NOT_EXIST=14]="SYNC_CHANNEL_NOT_EXIST",n[n.SYNC_INTERNAL_ERROR=15]="SYNC_INTERNAL_ERROR",(i=e.GroupUpdate||(e.GroupUpdate={}))[i.GROUP_UPDATE_AUDIO_STREAM_LOST=0]="GROUP_UPDATE_AUDIO_STREAM_LOST",i[i.GROUP_UPDATE_AUDIO_STREAM_RECOVER=1]="GROUP_UPDATE_AUDIO_STREAM_RECOVER",i[i.GROUP_UPDATE_ADD_PARTICIPANTS=2]="GROUP_UPDATE_ADD_PARTICIPANTS",i[i.GROUP_UPDATE_REMOVE_PARTICIPANTS=3]="GROUP_UPDATE_REMOVE_PARTICIPANTS",i[i.GROUP_UPDATE_SET_PROPERTIES=4]="GROUP_UPDATE_SET_PROPERTIES",i[i.GROUP_UPDATE_REMOVE_PROPERTIES=5]="GROUP_UPDATE_REMOVE_PROPERTIES",(o=e.GroupListUpdate||(e.GroupListUpdate={}))[o.GROUP_LIST_UPDATE_ADD_ID=0]="GROUP_LIST_UPDATE_ADD_ID",o[o.GROUP_LIST_UPDATE_REMOVE_ID=1]="GROUP_LIST_UPDATE_REMOVE_ID",(a=e.LEAVE_GROUP_REASON_CODE||(e.LEAVE_GROUP_REASON_CODE={}))[a.NORMAL_LEAVE=0]="NORMAL_LEAVE",(s=e.DismissGroupReasonCode||(e.DismissGroupReasonCode={}))[s.NORMAL_DISMISS=0]="NORMAL_DISMISS",(c=e.Result||(e.Result={}))[c.Ok=0]="Ok",c[c.Error=1]="Error"}(signal_msg||(signal_msg={}));var options={syntax:"proto3"},nested={signal_msg:{nested:{AudioSsrcSpec:{fields:{ssrc:{type:"uint32",id:1},rtxSsrc:{type:"uint32",id:2}}},VideoSsrcSpec:{fields:{ssrc:{type:"uint32",id:1},rtxSsrc:{type:"uint32",id:2},fecSsrc:{type:"uint32",id:3}}},MultiPcAdaptRequestInfo:{fields:{audioSsrcSpec:{rule:"repeated",type:"AudioSsrcSpec",id:1},videoSsrcSpec:{rule:"repeated",type:"VideoSsrcSpec",id:2}}},AudioStreamFormat:{fields:{codec:{type:"string",id:1},sampleRate:{type:"int64",id:2},channelNum:{type:"int64",id:3}}},AudioFormatPreference:{fields:{preferred:{type:"AudioStreamFormat",id:1},optional:{rule:"repeated",type:"AudioStreamFormat",id:2}}},AudioStreamOptional:{fields:{format:{rule:"repeated",type:"AudioStreamFormat",id:1}}},VideoStreamFormat:{fields:{codec:{type:"string",id:1},profile:{type:"string",id:2}}},VideoFormatPreference:{fields:{preferred:{type:"VideoStreamFormat",id:1},optional:{rule:"repeated",type:"VideoStreamFormat",id:2}}},FormatPreference:{fields:{audio:{type:"AudioFormatPreference",id:1},video:{type:"VideoFormatPreference",id:2}}},Resolution:{fields:{width:{type:"uint32",id:1},height:{type:"uint32",id:2}}},VideoSsrcParameters:{fields:{ssrc:{type:"uint32",id:1},framerate:{type:"int32",id:2},resolution:{type:"Resolution",id:3},maxBitrate:{type:"int32",id:4},minBitrate:{type:"int32",id:5},active:{type:"bool",id:6},bitrate:{type:"int64",id:7},tlayer:{type:"int64",id:8},multiSlice:{type:"int64",id:9},keyFrameInterval:{type:"int64",id:10},constantPpsid:{type:"int64",id:11},rid:{type:"string",id:12}}},VideoParameters:{oneofs:{_resolutionLevel:{oneof:["resolutionLevel"]}},fields:{ssrc:{type:"uint32",id:1},resolution:{type:"Resolution",id:2},framerate:{type:"int32",id:3},bitrate:{type:"string",id:4},multiSlice:{type:"int32",id:5},keyFrameInterval:{type:"int64",id:6},constantPpsid:{type:"int64",id:7},resolutionLevel:{type:"uint32",id:8,options:{proto3_optional:!0}}}},GroupVersion:{fields:{id:{type:"string",id:1},ver:{type:"int64",id:2}}},StreamInfo:{fields:{type:{type:"string",id:1},owner:{type:"string",id:2},attributesJsonStr:{type:"string",id:3},label:{type:"string",id:4},createTime:{type:"int64",id:7}}},StreamVideoParameters:{fields:{resolution:{type:"Resolution",id:1},framerate:{type:"int64",id:2},bitrate:{type:"int64",id:3},keyFrameInterval:{type:"int64",id:4},multiSlice:{type:"int64",id:5},constantPpsid:{type:"int64",id:6}}},VideoStreamPara:{fields:{specs:{rule:"repeated",type:"string",id:1},resolution:{rule:"repeated",type:"Resolution",id:2},framerate:{rule:"repeated",type:"int32",id:3},bitrate:{rule:"repeated",type:"string",id:4},keyFrameInterval:{rule:"repeated",type:"int32",id:5}}},VideoStreamOptional:{fields:{format:{rule:"repeated",type:"VideoStreamFormat",id:1},parameters:{type:"VideoStreamPara",id:2}}},StreamAudioDesc:{fields:{trackId:{type:"string",id:1},msid:{type:"string",id:2},status:{type:"string",id:3},format:{type:"AudioStreamFormat",id:4},source:{type:"string",id:5},ssrc:{rule:"repeated",type:"uint32",id:6},ssrcGroup:{rule:"repeated",type:"AudioSsrcSpec",id:7},optional:{type:"AudioStreamOptional",id:8}}},StreamVideoDesc:{fields:{trackId:{type:"string",id:1},msid:{type:"string",id:2},status:{type:"string",id:3},source:{type:"string",id:4},format:{type:"VideoStreamFormat",id:5},ssrc:{rule:"repeated",type:"uint32",id:6},ssrcGroup:{rule:"repeated",type:"VideoSsrcSpec",id:7},parameters:{type:"StreamVideoParameters",id:8},optional:{type:"VideoStreamOptional",id:9},highestResolutionLevel:{type:"int32",id:10}}},StreamMediaDesc:{fields:{audio:{type:"StreamAudioDesc",id:1},video:{type:"StreamVideoDesc",id:2}}},Stream:{fields:{id:{type:"string",id:1},type:{type:"string",id:2},media:{type:"StreamMediaDesc",id:3},info:{type:"StreamInfo",id:4},version:{type:"int64",id:5}}},OriginMsg:{fields:{type:{type:"string",id:1},id:{type:"string",id:2}}},ErrorMsg:{fields:{id:{type:"string",id:1},code:{type:"int32",id:2},msg:{type:"string",id:3},origin:{type:"OriginMsg",id:4}}},ErrorMsgs:{fields:{globalStatus:{type:"string",id:1},detailStatus:{rule:"repeated",type:"ErrorMsg",id:2}}},DataType:{values:{DATA_TYPE_STREAM:0,DATA_TYPE_PARTICIPANTS:1,DATA_TYPE_CONFERENCE:2,DATA_TYPE_GROUP_LIST:3,DATA_TYPE_GROUP:4}},OptType:{values:{OPT_TYPE_ADD:0,OPT_TYPE_REMOVE:1,OPT_TYPE_UPDATE:2}},SyncResponseCode:{values:{SYNC_OK:0,SYNC_PART_SUC:10,SYNC_DATA_SIZE_LIMITED:11,SYNC_NOT_SUPPORT_TYPE:12,SYNC_NOT_FOUND:13,SYNC_CHANNEL_NOT_EXIST:14,SYNC_INTERNAL_ERROR:15}},GroupParticipant:{fields:{uid:{type:"string",id:1},pid:{type:"string",id:2},userData:{type:"string",id:3}}},GroupAudioInfo:{fields:{label:{type:"string",id:1},audio:{type:"Stream",id:2}}},GroupInfo:{fields:{id:{type:"string",id:1},ver:{type:"int64",id:2},participants:{rule:"repeated",type:"GroupParticipant",id:3},audioInfo:{type:"GroupAudioInfo",id:4},properties:{rule:"repeated",type:"GroupProperty",id:5}}},GroupProperty:{fields:{key:{type:"string",id:1},value:{type:"string",id:2}}},SyncFullData:{oneofs:{_ver:{oneof:["ver"]},_totalPages:{oneof:["totalPages"]},_pagingSeq:{oneof:["pagingSeq"]}},fields:{ver:{type:"int64",id:1,options:{proto3_optional:!0}},totalPages:{type:"int32",id:2,options:{proto3_optional:!0}},pagingSeq:{type:"int64",id:3,options:{proto3_optional:!0}},groupData:{type:"GroupPagingData",id:10},groupListData:{type:"GroupListPagingData",id:11}}},GroupPagingData:{fields:{pagingSeq:{type:"int64",id:1},curPage:{type:"int32",id:2},groupInfos:{rule:"repeated",type:"GroupInfo",id:3}}},GroupListPagingData:{fields:{pagingSeq:{type:"int64",id:1},curPage:{type:"int32",id:2},groupIds:{rule:"repeated",type:"string",id:3}}},SyncChangeLog:{fields:{groupListChangeLogs:{rule:"repeated",type:"GroupListChangeLog",id:1},groupChangeLogs:{rule:"repeated",type:"GroupChangeLog",id:2}}},SyncDataRequest:{oneofs:{_id:{oneof:["id"]}},fields:{type:{type:"DataType",id:1},id:{type:"string",id:2,options:{proto3_optional:!0}},ver:{type:"int64",id:3},forceFullSync:{type:"bool",id:4},supportPagingSync:{type:"bool",id:5}}},SyncDataResponse:{fields:{code:{type:"SyncResponseCode",id:1},errMsg:{type:"string",id:2},fullSync:{type:"SyncFullData",id:3},changeLogs:{rule:"repeated",type:"SyncChangeLog",id:4}}},SyncIds:{fields:{id:{type:"string",id:1},ver:{type:"int64",id:2}}},SyncDataByIdsRequest:{fields:{type:{type:"DataType",id:1},ids:{rule:"repeated",type:"SyncIds",id:2},forceFullSync:{type:"bool",id:3},supportPagingSync:{type:"bool",id:4}}},SyncDataByIdsResponse:{fields:{code:{type:"SyncResponseCode",id:1},errMsg:{type:"string",id:2},notFoundIds:{rule:"repeated",type:"string",id:3},fullSync:{type:"SyncFullData",id:4},changeLogs:{rule:"repeated",type:"SyncChangeLog",id:5}}},GroupUpdate:{values:{GROUP_UPDATE_AUDIO_STREAM_LOST:0,GROUP_UPDATE_AUDIO_STREAM_RECOVER:1,GROUP_UPDATE_ADD_PARTICIPANTS:2,GROUP_UPDATE_REMOVE_PARTICIPANTS:3,GROUP_UPDATE_SET_PROPERTIES:4,GROUP_UPDATE_REMOVE_PROPERTIES:5}},GroupUpdateOpt:{fields:{updateAction:{type:"GroupUpdate",id:1},participants:{rule:"repeated",type:"GroupParticipant",id:2},properties:{rule:"repeated",type:"GroupProperty",id:3}}},GroupChangeLog:{oneofs:{_groupInfo:{oneof:["groupInfo"]},_updateOpt:{oneof:["updateOpt"]},_msgId:{oneof:["msgId"]}},fields:{ver:{type:"int64",id:1},type:{type:"OptType",id:2},id:{type:"string",id:3},groupInfo:{type:"GroupInfo",id:4,options:{proto3_optional:!0}},updateOpt:{type:"GroupUpdateOpt",id:5,options:{proto3_optional:!0}},msgId:{type:"string",id:6,options:{proto3_optional:!0}}}},GroupListUpdate:{values:{GROUP_LIST_UPDATE_ADD_ID:0,GROUP_LIST_UPDATE_REMOVE_ID:1}},GroupListUpdateOpt:{fields:{updateAction:{type:"GroupListUpdate",id:1},id:{type:"string",id:2}}},GroupListChangeLog:{oneofs:{_msgId:{oneof:["msgId"]}},fields:{ver:{type:"int64",id:1},type:{type:"OptType",id:2},updateOpt:{type:"GroupListUpdateOpt",id:3},msgId:{type:"string",id:4,options:{proto3_optional:!0}}}},JoinGroupRequest:{fields:{groupId:{type:"string",id:1},userData:{type:"string",id:2},autoJoinGroupAudio:{type:"bool",id:3},autoLeaveChannelAudio:{type:"bool",id:4}}},JoinGroupResponse:{oneofs:{_joinGroupAudioSuccess:{oneof:["joinGroupAudioSuccess"]}},fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2},group:{type:"GroupInfo",id:3},joinGroupAudioSuccess:{type:"bool",id:4,options:{proto3_optional:!0}}}},LEAVE_GROUP_REASON_CODE:{values:{NORMAL_LEAVE:0}},LeaveGroupRequest:{fields:{groupId:{type:"string",id:1},reasonCode:{type:"LEAVE_GROUP_REASON_CODE",id:2},autoJoinChannelAudio:{type:"bool",id:3}}},LeaveGroupResponse:{oneofs:{_joinChannelAudioSuccess:{oneof:["joinChannelAudioSuccess"]}},fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2},joinChannelAudioSuccess:{type:"bool",id:3,options:{proto3_optional:!0}}}},DismissGroupReasonCode:{values:{NORMAL_DISMISS:0}},DismissGroupRequest:{fields:{groupId:{type:"string",id:1},reasonCode:{type:"DismissGroupReasonCode",id:2}}},DismissGroupResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}},ObserveAllGroupsRequest:{fields:{}},ObserveAllGroupsResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}},UnobserveAllGroupsRequest:{fields:{}},UnobserveAllGroupsResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}},SetGroupPropertiesRequest:{fields:{groupId:{type:"string",id:1},properties:{rule:"repeated",type:"GroupProperty",id:2}}},SetGroupPropertiesResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}},RemoveGroupPropertiesRequest:{fields:{groupId:{type:"string",id:1},keys:{rule:"repeated",type:"string",id:2}}},RemoveGroupPropertiesResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}},SetParticipantPropertiesRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},propertiesJsonStr:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},RemoveParticipantPropertiesRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},propertiesJsonStr:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},Result:{values:{Ok:0,Error:1}},Response:{oneofs:{data:{oneof:["reason","createPeerConnectionResponse","errorMsg","queryStreamsVerResponse","queryStreamsResponse","publishResponse","subscribeResponse","joinGroupResponse","leaveGroupResponse","dismissGroupResponse","observeAllGroupsResponse","unobserveAllGroupsResponse","syncDataResponse","syncDataByIdsResponse","setGroupPropertiesResponse","removeGroupPropertiesResponse"]}},fields:{result:{type:"Result",id:1},tid:{type:"string",id:2},traceId:{type:"string",id:3},code:{type:"int32",id:4},reason:{type:"string",id:11},createPeerConnectionResponse:{type:"CreatePeerConnectionResponse",id:15},errorMsg:{type:"ErrorMsgs",id:16},queryStreamsVerResponse:{type:"QueryStreamsVerResponse",id:17},queryStreamsResponse:{type:"QueryStreamsResponse",id:18},publishResponse:{type:"PublishResponse",id:21},subscribeResponse:{type:"SubscribeResponse",id:22},joinGroupResponse:{type:"JoinGroupResponse",id:24},leaveGroupResponse:{type:"LeaveGroupResponse",id:25},dismissGroupResponse:{type:"DismissGroupResponse",id:26},observeAllGroupsResponse:{type:"ObserveAllGroupsResponse",id:27},unobserveAllGroupsResponse:{type:"UnobserveAllGroupsResponse",id:28},syncDataResponse:{type:"SyncDataResponse",id:29},syncDataByIdsResponse:{type:"SyncDataByIdsResponse",id:30},setGroupPropertiesResponse:{type:"SetGroupPropertiesResponse",id:31},removeGroupPropertiesResponse:{type:"RemoveGroupPropertiesResponse",id:32}}},NotificationItem:{oneofs:{notification:{oneof:["streamNotification","serverFailoverNotification","progressNotification","groupNotification","groupListNotification"]}},fields:{event:{type:"string",id:1},streamNotification:{type:"StreamNotification",id:11},serverFailoverNotification:{type:"ServerFailoverNotification",id:13},progressNotification:{type:"ProgressNotification",id:14},groupNotification:{type:"GroupChangeLog",id:17},groupListNotification:{type:"GroupListChangeLog",id:18}}},BatchNotification:{fields:{notificationItem:{rule:"repeated",type:"NotificationItem",id:1},tid:{type:"string",id:2},traceId:{type:"string",id:3}}},MediaMessage:{fields:{payload:{type:"string",id:1}}},AudioStreamTrackDesc:{fields:{streamId:{type:"string",id:1},trackId:{type:"string",id:2},msid:{type:"string",id:3},source:{type:"string",id:4},uplinkSsrcGroup:{rule:"repeated",type:"AudioSsrcSpec",id:5},format:{type:"AudioStreamFormat",id:6},autoMix:{rule:"repeated",type:"string",id:7},attributesJsonString:{type:"string",id:8}}},VideoStreamTrackDesc:{fields:{streamId:{type:"string",id:1},trackId:{type:"string",id:2},msid:{type:"string",id:3},source:{type:"string",id:4},logicSsrc:{rule:"repeated",type:"uint32",id:5},uplinkSsrcGroup:{rule:"repeated",type:"VideoSsrcSpec",id:6},ssrcParameters:{rule:"repeated",type:"VideoSsrcParameters",id:7},streamParameters:{type:"VideoParameters",id:8},attributesJsonString:{type:"string",id:9},forwardOnly:{type:"bool",id:10},mid:{type:"string",id:11},highestResolutionLevel:{type:"int32",id:12}}},MediaStreamTrackDesc:{fields:{audio:{rule:"repeated",type:"AudioStreamTrackDesc",id:1},video:{rule:"repeated",type:"VideoStreamTrackDesc",id:2}}},StreamVersion:{fields:{streamId:{type:"string",id:1},streamVer:{type:"int64",id:2}}},StreamData:{fields:{id:{type:"string",id:1},stream:{type:"Stream",id:2}}},AudioPubOptions:{fields:{source:{type:"string",id:1},format:{type:"AudioStreamFormat",id:2},autoMix:{rule:"repeated",type:"string",id:3}}},VideoPubOptions:{fields:{source:{type:"string",id:1},format:{type:"VideoStreamFormat",id:2},parameters:{type:"VideoParameters",id:3},forwardOnly:{type:"bool",id:4}}},MediaPubOptionsSpecify:{fields:{audio:{type:"AudioPubOptions",id:1},video:{type:"VideoPubOptions",id:2}}},BatchPublishRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},type:{type:"string",id:4},simulcast:{type:"bool",id:5},simulcastVersion:{type:"string",id:6},supportTemporalLayer:{type:"bool",id:7},clientType:{type:"string",id:8},clientVersion:{type:"string",id:9},media:{type:"MediaStreamTrackDesc",id:10},event:{type:"string",id:11},tid:{type:"string",id:12},traceId:{type:"string",id:13}}},BatchUnpublishRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},audio:{rule:"repeated",type:"string",id:4},video:{rule:"repeated",type:"string",id:5},tid:{type:"string",id:6},traceId:{type:"string",id:7}}},QueryStreamsVerRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},streamIds:{rule:"repeated",type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},QueryStreamsVerResponse:{fields:{streamVersions:{rule:"repeated",type:"StreamVersion",id:1},totalVer:{type:"int32",id:2},msg:{type:"string",id:3}}},StreamControlRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},streamId:{type:"string",id:3},operation:{type:"string",id:4},data:{type:"string",id:5},tid:{type:"string",id:6},traceId:{type:"string",id:7},highestResolutionLevel:{type:"int32",id:8}}},QueryStreamsRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},streamIds:{rule:"repeated",type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},QueryStreamsResponse:{fields:{totalVer:{type:"int64",id:1},msg:{type:"string",id:2},streams:{rule:"repeated",type:"StreamData",id:3}}},SetStreamPropertiesRequest:{fields:{roomId:{type:"string",id:1},streamId:{type:"string",id:2},propertiesJsonStr:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},PublishRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},type:{type:"string",id:3},event:{type:"string",id:4},media:{type:"MediaPubOptionsSpecify",id:5},attributesJsonStr:{type:"string",id:6},tid:{type:"string",id:7},traceId:{type:"string",id:8}}},PublishResponse:{fields:{id:{type:"string",id:1}}},UnpublishRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},streamId:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},NetworkHealth:{fields:{receiving:{type:"bool",id:1},lossRate:{type:"int32",id:2},timestamp:{type:"int64",id:3},cutoff:{type:"bool",id:4},tid:{type:"string",id:5}}},StreamMsg:{oneofs:{value:{oneof:["networkHealth","streamStatus","stream","activeStream","propertiesJsonStr","highestResolutionLevel"]}},fields:{field:{type:"string",id:1},streamVer:{type:"int64",id:2},expiredMs:{type:"int64",id:3},extraValue:{rule:"repeated",type:"string",id:4},tid:{type:"string",id:5},networkHealth:{type:"NetworkHealth",id:10},streamStatus:{type:"string",id:11},stream:{type:"Stream",id:12},activeStream:{type:"string",id:13},propertiesJsonStr:{type:"string",id:14},highestResolutionLevel:{type:"int32",id:15}}},StreamNotification:{oneofs:{data:{oneof:["stream","msg"]}},fields:{streamId:{type:"string",id:1},status:{type:"string",id:2},totalVer:{type:"int64",id:3},msgId:{type:"string",id:4},ts:{type:"int64",id:5},tid:{type:"string",id:6},traceId:{type:"string",id:7},stream:{type:"Stream",id:10},msg:{type:"StreamMsg",id:11}}},Candidate:{fields:{candidate:{type:"string",id:1},sdpMlineIndex:{type:"int32",id:2},sdpMid:{type:"string",id:3}}},SessionSignaling:{fields:{type:{type:"string",id:1},sdp:{type:"string",id:2},candidate:{type:"Candidate",id:3},optionsJsonStr:{type:"string",id:4}}},SignalingData:{fields:{type:{type:"string",id:1},sdp:{type:"string",id:2}}},CreatePeerConnectionRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},tid:{type:"string",id:4},event:{type:"string",id:5},direction:{type:"string",id:6},sdpOffer:{type:"string",id:7},type:{type:"string",id:8},isOca:{type:"bool",id:9},isFailover:{type:"bool",id:10},multiPcAdaptInfo:{type:"MultiPcAdaptRequestInfo",id:11},pcFormatPreference:{type:"FormatPreference",id:12},optionsJsonStr:{type:"string",id:13},traceId:{type:"string",id:14},sfuSsrcGroup:{rule:"repeated",type:"AudioSsrcSpec",id:15}}},CreatePeerConnectionResponse:{fields:{connectionId:{type:"string",id:1},sdpAnswer:{type:"string",id:2}}},ClosePeerConnectionRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},direction:{type:"string",id:4},tid:{type:"string",id:5},traceId:{type:"string",id:6}}},SoacRequest:{fields:{id:{type:"string",id:1},signaling:{type:"SessionSignaling",id:2},tid:{type:"string",id:3},traceId:{type:"string",id:4}}},NotifyAction:{fields:{actionName:{type:"string",id:1},connectionId:{type:"string",id:2},traceId:{type:"string",id:3}}},ServerFailoverNotification:{fields:{actions:{rule:"repeated",type:"NotifyAction",id:1},msgId:{type:"string",id:2},tid:{type:"string",id:3},traceId:{type:"string",id:4}}},ProgressNotification:{fields:{id:{type:"string",id:1},status:{type:"string",id:2},data:{type:"SignalingData",id:3},msgId:{type:"string",id:4},tid:{type:"string",id:5},traceId:{type:"string",id:6}}},AudioBatchSubOptions:{fields:{subscriptionId:{type:"string",id:1},from:{type:"string",id:2},trackId:{type:"string",id:3},ssrcGroup:{rule:"repeated",type:"AudioSsrcSpec",id:4},format:{type:"AudioStreamFormat",id:5}}},VideoBatchSubOptions:{fields:{subscriptionId:{type:"string",id:1},from:{type:"string",id:2},trackId:{type:"string",id:3},ssrcGroup:{rule:"repeated",type:"VideoSsrcSpec",id:4},parameters:{type:"VideoParameters",id:5},format:{type:"VideoStreamFormat",id:6},subSsrcGroup:{type:"VideoSsrcSpec",id:7}}},MediaBatchSubOptions:{fields:{audio:{rule:"repeated",type:"AudioBatchSubOptions",id:1},video:{rule:"repeated",type:"VideoBatchSubOptions",id:2}}},Audio:{fields:{from:{type:"string",id:1}}},Video:{fields:{from:{type:"string",id:1},params:{type:"VideoParameters",id:2}}},MediaUpdateDesc:{fields:{audio:{type:"Audio",id:1},video:{type:"Video",id:2}}},AudioSubOptions:{fields:{from:{type:"string",id:1},format:{type:"AudioStreamFormat",id:2}}},VideoSubOptions:{fields:{from:{type:"string",id:1},format:{type:"VideoStreamFormat",id:2},parameters:{type:"VideoParameters",id:3}}},MediaSubOptionsSpecify:{fields:{audio:{type:"AudioSubOptions",id:1},video:{type:"VideoSubOptions",id:2}}},SubscribeRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},tid:{type:"string",id:3},event:{type:"string",id:4},media:{type:"MediaSubOptionsSpecify",id:5},type:{type:"string",id:6},propertiesJsonStr:{type:"string",id:7},traceId:{type:"string",id:8}}},SubscribeResponse:{fields:{id:{type:"string",id:1}}},UnsubscribeRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},subscriptionId:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},BatchSubscribeRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},supportTemporalLayer:{type:"bool",id:4},clientType:{type:"string",id:5},clientVersion:{type:"string",id:6},media:{type:"MediaBatchSubOptions",id:7},tid:{type:"string",id:8},type:{type:"string",id:9},event:{type:"string",id:10},propertiesJsonStr:{type:"string",id:11},traceId:{type:"string",id:12}}},BatchUnsubscribeRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},audio:{rule:"repeated",type:"string",id:4},video:{rule:"repeated",type:"string",id:5},tid:{type:"string",id:6},traceId:{type:"string",id:7}}},SubscriptionControlRequest:{oneofs:{data:{oneof:["updateDesc","track"]}},fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},subscriptionId:{type:"string",id:3},operation:{type:"string",id:4},updateDesc:{type:"MediaUpdateDesc",id:6},track:{type:"string",id:7},tid:{type:"string",id:8},traceId:{type:"string",id:9}}}}}},SIGNAL_PROTO={options:options,nested:nested},root=getProtobufRoot(SIGNAL_PROTO),Response=root.lookupType("signal_msg.Response"),BatchNotification=root.lookupType("signal_msg.BatchNotification"),MediaMessage=root.lookupType("signal_msg.MediaMessage"),StreamNotification=root.lookupType("signal_msg.StreamNotification");root.lookupType("signal_msg.ProgressNotification");var ServerFailoverNotification=root.lookupType("signal_msg.ServerFailoverNotification"),PublishRequest=root.lookupType("signal_msg.PublishRequest"),SoacRequest=root.lookupType("signal_msg.SoacRequest"),UnpublishRequest=root.lookupType("signal_msg.UnpublishRequest"),StreamControlRequest=root.lookupType("signal_msg.StreamControlRequest"),SubscribeRequest=root.lookupType("signal_msg.SubscribeRequest"),SetStreamPropertiesRequest=root.lookupType("signal_msg.SetStreamPropertiesRequest"),UnsubscribeRequest=root.lookupType("signal_msg.UnsubscribeRequest"),SubscriptionControlRequest=root.lookupType("signal_msg.SubscriptionControlRequest"),CreatePeerConnectionRequest=root.lookupType("signal_msg.CreatePeerConnectionRequest"),ClosePeerConnectionRequest=root.lookupType("signal_msg.ClosePeerConnectionRequest"),BatchPublishRequest=root.lookupType("signal_msg.BatchPublishRequest"),BatchUnpublishRequest=root.lookupType("signal_msg.BatchUnpublishRequest"),BatchSubscribeRequest=root.lookupType("signal_msg.BatchSubscribeRequest"),BatchUnsubscribeRequest=root.lookupType("signal_msg.BatchUnsubscribeRequest"),JoinGroupRequest=root.lookupType("signal_msg.JoinGroupRequest"),SetGroupPropertiesRequest=root.lookupType("signal_msg.SetGroupPropertiesRequest"),DismissGroupRequest=root.lookupType("signal_msg.DismissGroupRequest"),LeaveGroupRequest=root.lookupType("signal_msg.LeaveGroupRequest"),SyncDataRequest=root.lookupType("signal_msg.SyncDataRequest"),SyncDataByIdsRequest=root.lookupType("signal_msg.SyncDataByIdsRequest"),GroupChangeLog=root.lookupType("signal_msg.GroupChangeLog"),GroupListChangeLog=root.lookupType("signal_msg.GroupListChangeLog"),SetParticipantPropertiesRequest=root.lookupType("signal_msg.SetParticipantPropertiesRequest"),QueryStreamsVerRequest=root.lookupType("signal_msg.QueryStreamsVerRequest"),QueryStreamsRequest=root.lookupType("signal_msg.QueryStreamsRequest");function _callSuper$h(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$h()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$h(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$h=function(){return!!e})()}var RtcSignaling=function(e){function t(e){var r;return _classCallCheck$1(this,t),r=_callSuper$h(this,t),Object.defineProperty(r,"loggedIn",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"channel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"rpcId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.channel=e,r.rpcId=0,r.reporter=e.reporter,r.logger=r.reporter.getLoggerWithPrefix("[rtc-signal]"),r.handleBatchNotifyEvent=r.handleBatchNotifyEvent.bind(r),r.handleNotifyEvent=r.handleNotifyEvent.bind(r),r.handleConnectionStateChangeEvent=r.handleConnectionStateChangeEvent.bind(r),r.handleSyncEvent=r.handleSyncEvent.bind(r),r.handleUserEvent=r.handleUserEvent.bind(r),r.channel.on("connection-state-change",r.handleConnectionStateChangeEvent),r.channel.on("sync",r.handleSyncEvent),r.channel.on("batch-notify",r.handleBatchNotifyEvent),r.channel.on("notify",r.handleNotifyEvent),r.channel.on("user",r.handleUserEvent),r}return _inherits$1(t,e),_createClass$1(t,[{key:"join",value:function(e,t){return this.channel.join(e,t).then(function(e){return{joinResponse:e.joinResponse,iceConfig:e.iceConfig}})}},{key:"leave",value:function(){return this.channel.leave()}},{key:"handleUserEvent",value:function(e,t){this.emit("user",e,t)}},{key:"handleSyncEvent",value:function(e){this.emit("sync",e)}},{key:"handleConnectionStateChangeEvent",value:function(e,t,r){this.emit("connection-state-change",e,t,r)}},{key:"handleNotifyEvent",value:function(e,t){"stream"===e?this.emit("stream",StreamNotification.decode(t)):"serverFailover"===e?this.emit("serverFailover",ServerFailoverNotification.decode(t)):"media-message"===e?this.emit("media-message",MediaMessage.decode(t)):"group"===e?this.emit("group",GroupChangeLog.decode(t)):"group-list"===e&&this.emit("group-list",GroupListChangeLog.decode(t))}},{key:"handleBatchNotifyEvent",value:function(e){var t=this;BatchNotification.decode(e).notificationItem.forEach(function(e){"stream"===e.event?t.emit("stream",e.streamNotification):"serverFailover"===e.event?t.emit("serverFailover",e.serverFailoverNotification):"group"===e.event?t.emit("group",e.groupNotification):"group-list"===e.event&&t.emit("group-list",e.groupListNotification)})}},{key:"createPeerConnection",value:function(e){var t=CreatePeerConnectionRequest.encode(e).finish();return this.rpc("create-peer-connection",t,e).then(function(e){return e.createPeerConnectionResponse})}},{key:"closePeerConnection",value:function(e){var t=ClosePeerConnectionRequest.encode(e).finish();return this.rpc("close-peer-connection",t,e)}},{key:"batchSubscribe",value:function(e){var t=BatchSubscribeRequest.encode(e).finish();return this.rpc("batch-subscribe",t,e).then(function(e){return e.errorMsg})}},{key:"setGroupProperties",value:function(e){var t=SetGroupPropertiesRequest.encode(e).finish();return this.rpc("set-group-properties",t,e).then(function(e){return e.setGroupPropertiesResponse})}},{key:"batchUnSubscribe",value:function(e){var t=BatchUnsubscribeRequest.encode(e).finish();return this.rpc("batch-unsubscribe",t,e)}},{key:"batchPublish",value:function(e){var t=BatchPublishRequest.encode(e).finish();return this.rpc("batch-publish",t,e).then(function(e){return e.errorMsg})}},{key:"batchUnPublish",value:function(e){var t=BatchUnpublishRequest.encode(e).finish();return this.rpc("batch-unpublish",t,e)}},{key:"publish",value:function(e){var t=PublishRequest.encode(e).finish();return this.rpc("publish",t,e).then(function(e){return e.publishResponse})}},{key:"setParticipantProperties",value:function(e){var t=SetParticipantPropertiesRequest.encode(e).finish();return this.rpc("set-participant-properties",t,e)}},{key:"soac",value:function(e){var t=SoacRequest.encode(e).finish();return this.rpc("soac",t,e)}},{key:"unpublish",value:function(e){var t=UnpublishRequest.encode(e).finish();return this.rpc("unpublish",t,e)}},{key:"streamControl",value:function(e){var t=StreamControlRequest.encode(e).finish();return this.rpc("stream-control",t,e)}},{key:"setStreamProperties",value:function(e){var t=SetStreamPropertiesRequest.encode(e).finish();return this.rpc("set-stream-properties",t,e)}},{key:"subscribe",value:function(e){var t=SubscribeRequest.encode(e).finish();return this.rpc("subscribe",t,e).then(function(e){return e.subscribeResponse})}},{key:"unsubscribe",value:function(e){var t=UnsubscribeRequest.encode(e).finish();return this.rpc("unsubscribe",t,e)}},{key:"subscriptionControl",value:function(e){var t=SubscriptionControlRequest.encode(e).finish();return this.rpc("subscription-control",t,e)}},{key:"getStreamsVer",value:function(e){var t=QueryStreamsVerRequest.encode(e).finish();return this.rpc("query-streams-ver",t,e).then(function(e){return e.queryStreamsVerResponse})}},{key:"getStreams",value:function(e){var t=QueryStreamsRequest.encode(e).finish();return this.rpc("query-streams",t,e).then(function(e){return e.queryStreamsResponse})}},{key:"joinGroup",value:function(e){var t=JoinGroupRequest.encode(e).finish();return this.rpc("join-group",t,e).then(function(e){return e.joinGroupResponse})}},{key:"leaveGroup",value:function(e){var t=LeaveGroupRequest.encode(e).finish();return this.rpc("leave-group",t,e).then(function(e){return e.leaveGroupResponse})}},{key:"dismissGroup",value:function(e){var t=DismissGroupRequest.encode(e).finish();return this.rpc("dismiss-group",t,e).then(function(e){return e.dismissGroupResponse})}},{key:"syncData",value:function(e){var t=SyncDataRequest.encode(e).finish();return this.rpc("sync-data",t,e).then(function(e){return e.syncDataResponse})}},{key:"syncDataByIds",value:function(e){var t=SyncDataByIdsRequest.encode(e).finish();return this.rpc("sync-data-by-ids",t,e).then(function(e){return e.syncDataByIdsResponse})}},{key:"observeAllGroups",value:function(){return this.rpc("observe-all-groups",null).then(function(e){return e.observeAllGroupsResponse})}},{key:"unobserveAllGroups",value:function(){return this.rpc("unobserve-all-groups",null).then(function(e){return e.unobserveAllGroupsResponse})}},{key:"rpc",value:function(e,t){var r=this,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0;return new Promise(function(i,o){var a=r.rpcId++;r.logger.info("rtc rpcId ".concat(a,":").concat(e," param"),n),r.channel.signaling.rpc(e,t,n).then(function(t){var n=Response.decode(t);n.code===signal_msg.Result.Ok?(r.logger.info("rtc rpcId ".concat(a,":").concat(e," result====>"),n),i(n)):(r.logger.error("rtc rpcId ".concat(a,":").concat(e," error====>"),n),o(n))}).catch(function(t){r.logger.error("rtc rpcId ".concat(a,":").concat(e," error====>"),t),o(t)})})}}])}(EventEmitter);function _callSuper$g(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$g()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$g(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$g=function(){return!!e})()}var Monitor=function(e){function t(){var e;_classCallCheck$1(this,t),e=_callSuper$g(this,t),Object.defineProperty(e,"interval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(e,"timer",{enumerable:!0,configurable:!0,writable:!0,value:void 0});var r=getReporter().statsConfig;return e.interval=(null==r?void 0:r.statsIntervalMs)||METRIC_STATS_INTERVAL,e.start(),e}return _inherits$1(t,e),_createClass$1(t,[{key:"start",value:function(){var e=this;this.stop(),this.makeReport&&this.makeReport(),this.timer=addTimer(function(){e.makeReport()},this.interval,"interval")}},{key:"stop",value:function(){this.timer&&(removeTimer(this.timer,"interval"),this.timer=null)}}])}(EventEmitter);function ownKeys$7(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function _objectSpread$7(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$7(Object(r),!0).forEach(function(t){_defineProperty(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$7(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function _createForOfIteratorHelper$b(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$b(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$b(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$b(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_arrayLikeToArray$b(e,t):void 0}}function _arrayLikeToArray$b(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _callSuper$f(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$f()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$f(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$f=function(){return!!e})()}var initAudioSendInfo={timestamp:0,audioLevel:0,bytesSent:0,packetsSent:0,packetsLost:0,roundTripTime:0},initVideoSendInfo={totalFramesSent:0,totalBytesSent:0,totalPacketsLost:0,totalPacketsSent:0,totalFramesEncoded:0,timestamp:0,totalQpSum:0,maxSendFrameHeight:0,maxSendFrameWidth:0,captureFrameHeight:0,captureFrameWidth:0,captureFramesPerSecond:0,sendFramesPerSecond:0,availableOutgoingBitrate:0,targetBitrate:0,roundTripTime:0,encodeFramesPerSecond:0,totalEncodedTime:0,trackStats:new Map},PublishMonitor=function(e){function t(e){var r;_classCallCheck$1(this,t),r=_callSuper$f(this,t),Object.defineProperty(r,"videoSendReport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"audioSendReport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"bweReport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"lastVideoSendInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"lastAudioSendInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"track",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"source",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"pc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"tranceiver",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"connection",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.connection=e.connection,r.pc=e.connection.pc;var n=e.tracks.filter(function(e){return"video"===e.trackMediaType})[0];return r.source=null==n?void 0:n.source,r.track=e.tracks[0],r.tranceiver=e.transceiver,r.lastVideoSendInfo=Object.assign({},initVideoSendInfo),r.videoSendReport={attr_bitrate:0,attr_capture_frames:0,attr_enc_average_elapsed_ms:0,attr_encode_qp_sim:"",attr_encoded_framerate_sim:"",attr_resolution_sim:"",attr_stream_options:"",attr_duration_ms:0},r.lastAudioSendInfo=Object.assign({},initAudioSendInfo),r.audioSendReport={attr_duration_ms:0,attr_bitrate:0},r.bweReport={attr_rtt:0,attr_lossrate:0,attr_reported_bitrate:0,attr_duration_ms:0},r}return _inherits$1(t,e),_createClass$1(t,[{key:"extractVideoMetrics",value:function(e){var t=this,r=Object.assign({source:this.source,trackStats:[]},initVideoSendInfo,this.connection.peerConnectionStats);if(r.timestamp=Date.now(),this.track){var n=this.track.getMediaStreamTrack().getSettings(),i=n.width,o=n.height,a=n.frameRate;r.captureFramesPerSecond=a===1/0?0:a||0,r.captureFrameWidth=i||0,r.captureFrameHeight=o||0}var s=new Map,c=getDeltaDurationInSeconds(r,this.lastVideoSendInfo);return e.forEach(function(e){if(/outboundrtp|outbound-rtp/i.test(e.type)){var n=s.get(e.ssrc)||{},i=t.lastVideoSendInfo.trackStats.get(e.ssrc)||{};if(n.sendFrameWidth=e.frameWidth||0,n.sendFrameHeight=e.frameHeight||0,n.framesSent=e.framesSent||0,n.framesEncoded=e.framesEncoded||0,n.targetBitrate=e.targetBitrate||0,n.qpSum=e.qpSum||0,n.bytesSent=e.bytesSent||0,n.packetsSent=e.packetsSent||0,n.packetsSentForLost=n.packetsSent||0,n.sentTimestamp=e.timestamp||0,n.totalEncodeTime=e.totalEncodeTime||0,n.keyFramesEncoded=e.keyFramesEncoded||0,n.firCount=e.firCount||0,n.pliCount=e.pliCount||0,n.retransmittedBytesSent=e.retransmittedBytesSent||0,n.retransmittedPacketsSent=e.retransmittedPacketsSent||0,n.qualityLimitationReason=e.qualityLimitationReason||"",n.web_powerEfficientEncoder=e.powerEfficientEncoder||"",n.web_encoderImplementation=e.encoderImplementation||"",n.web_qualityLimitationResolutionChanges=e.qualityLimitationResolutionChanges>=0?e.qualityLimitationResolutionChanges:-1,n.web_codecId=e.codecId||"",n.sendFramesPerSecond=e.framesPerSecond||0,n.sendFrameWidth>r.maxSendFrameWidth){if(r.maxSendFrameWidth=n.sendFrameWidth,!n.sendFramesPerSecond&&i){var o=getDelta(n.framesSent||n.framesEncoded,i.framesSent||i.framesEncoded);n.sendFramesPerSecond=Math.round(o/c)}if(n.framesEncoded){var a=getDelta(n.framesEncoded,null==i?void 0:i.framesEncoded);r.encodeFramesPerSecond=Math.round(a/c)}r.sendFramesPerSecond=n.sendFramesPerSecond}s.set(e.ssrc,n),r.targetBitrate=n.targetBitrate,r.totalBytesSent+=n.bytesSent,r.totalPacketsSent+=n.packetsSent,r.totalEncodedTime+=n.totalEncodeTime,r.totalFramesEncoded+=n.framesEncoded,r.totalFramesSent+=n.framesSent,r.totalQpSum+=n.qpSum,r.maxSendFrameHeight=Math.max(n.sendFrameHeight,r.maxSendFrameHeight),s.set(e.ssrc,n)}else if(/track/i.test(e.type)&&!1===e.remoteSource){if(Environment.isSafari()){var u=s.get(e.ssrc)||{};u.sendFrameHeight>0||(u.sendFrameWidth=e.frameWidth||0,u.sendFrameHeight=e.frameHeight||0),u.framesSent=e.framesSent||0,u.totalEncodeTime=e.totalEncodeTime||0,s.set(e.ssrc,u),r.totalFramesEncoded+=u.framesEncoded,r.totalEncodedTime+=u.totalEncodeTime,r.totalFramesSent+=u.framesSent,s.set(e.ssrc,u)}}else if(/remote-inbound-rtp/i.test(e.type)){var l=s.get(e.ssrc)||{},d=t.lastVideoSendInfo.trackStats.get(e.ssrc)||{};l.packetsLost=e.packetsLost||0,l.lostTimestamp=e.timestamp,r.totalPacketsLost+=l.packetsLost,l.packetsLost===(d.packetsLost||0)&&(l.packetsSentForLost=d.packetsSentForLost||0,l.lostTimestamp=d.lostTimestamp||0),s.set(e.ssrc,l)}}),r.trackStats=s,r}},{key:"getLayersMetricInfo",value:function(e){var t,r=[],n=_createForOfIteratorHelper$b(e.trackStats.entries());try{for(n.s();!(t=n.n()).done;){var i=_slicedToArray(t.value,2),o=i[0],a=i[1],s=this.lastVideoSendInfo.trackStats.get(o)||{},c=getDelta(a.framesSent,s.framesSent),u=getDelta(a.framesEncoded,s.framesEncoded),l=getDelta(a.keyFramesEncoded,s.keyFramesEncoded),d=getDelta(a.retransmittedBytesSent,s.retransmittedBytesSent),p=getDelta(a.retransmittedPacketsSent,s.retransmittedPacketsSent),f=getDelta(a.firCount,s.firCount),h=getDelta(a.pliCount,s.pliCount),g=getDelta(a.packetsSent,s.packetsSent),m=getDelta(a.packetsSentForLost,s.packetsSentForLost),v=getDelta(a.lostTimestamp,s.lostTimestamp),y=getDelta(a.sentTimestamp,s.sentTimestamp),b=getDelta(a.packetsLost,s.packetsLost),S=getDelta(a.totalEncodeTime,s.totalEncodeTime),_=getDelta(a.qpSum,s.qpSum),E=a.qualityLimitationReason,T=a.sendFrameWidth,R=_objectSpread$7(_objectSpread$7({sendFrameHeight:a.sendFrameHeight,sendFrameWidth:T,qualityLimitationReason:E,web_powerEfficientEncoder:a.web_powerEfficientEncoder,web_encoderImplementation:a.web_encoderImplementation,web_qualityLimitationResolutionChanges:a.web_qualityLimitationResolutionChanges,web_codecId:a.web_codecId},a),{},{deltaQbSum:_,deltaPacketsSent:g,deltaPacketsLost:b,deltaFramesSent:c,deltaTimestampForLost:v,deltaFramesEncoded:u,deltaKeyFramesEncoded:l,deltaFirCount:f,deltaEncodedTime:S,deltaPliCount:h,deltaTimestampForSent:y,deltaPacketsSentForLost:m,deltaRetransmittedBytesSent:d,deltaRetransmittedPacketsSent:p});r.push(R)}}catch(e){n.e(e)}finally{n.f()}return{tracksStatInfo:r,totalBytesSent:e.totalBytesSent,totalFramesEncoded:e.totalFramesEncoded||e.totalFramesSent,totalPacketsSent:e.totalPacketsSent,totalEncodedTime:e.totalEncodedTime,totalQpSum:e.totalQpSum,totalPacketsLost:e.totalPacketsLost}}},{key:"makeVideoReport",value:function(e,t){var r={attr_capture_frames:Math.round(e.captureFramesPerSecond),attr_stream_options:"audio:false/video:".concat(this.source,"/resolution:").concat(e.captureFrameWidth,"*").concat(e.captureFrameHeight,"/")};if(this.lastVideoSendInfo.timestamp){var n,i=this.getLayersMetricInfo(e),o=i.tracksStatInfo,a=i.totalBytesSent,s=i.totalFramesEncoded,c=i.totalEncodedTime;o.length>1&&(r.attr_stream_options+="sim:".concat(o.length,"/"));for(var u={attr_encoded_framerate_sim:[],attr_enc_key_frames_sim:[],attr_fir_count_sim:[],attr_pli_count_sim:[],attr_quality_limitation_reason_sim:[],web_powerEfficientEncoder_sim:[],web_encoderImplementation_sim:[],web_qualityLimitationResolutionChanges_sim:[],web_codecId_sim:[],attr_retx_bytes_sim:[],attr_retx_packets_sim:[],attr_resolution_sim:[],attr_encode_qp_sim:[]},l=[],d=0,p=getDelta(e.timestamp,this.lastVideoSendInfo.timestamp),f=!0,h=0;h<o.length;h++){var g=o[h];u.attr_enc_key_frames_sim.push(g.deltaKeyFramesEncoded),u.attr_fir_count_sim.push(g.deltaFirCount),u.attr_pli_count_sim.push(g.deltaPliCount),u.attr_quality_limitation_reason_sim.push(g.qualityLimitationReason),u.web_powerEfficientEncoder_sim.push(g.web_powerEfficientEncoder),u.web_encoderImplementation_sim.push(g.web_encoderImplementation),u.web_qualityLimitationResolutionChanges_sim.push(g.web_qualityLimitationResolutionChanges),u.web_codecId_sim.push(g.web_codecId),u.attr_retx_bytes_sim.push(g.deltaRetransmittedBytesSent),u.attr_retx_packets_sim.push(g.deltaRetransmittedPacketsSent),u.attr_resolution_sim.push({count:g.deltaFramesSent||g.deltaFramesEncoded,index:h,resolution:"".concat(g.sendFrameWidth,"*").concat(g.sendFrameHeight)});var m=g.deltaFramesEncoded||g.deltaFramesSent;f&&(f=0===m),u.attr_encoded_framerate_sim.push(_defineProperty({},h,Math.round(1e3*m/p))),u.attr_encode_qp_sim.push(_defineProperty({},h,Math.round((g.deltaQbSum||0)/(m||Number.EPSILON))));var v=g.deltaTimestampForLost,y=g.deltaTimestampForSent,b=g.deltaPacketsLost,S=g.deltaPacketsSentForLost;if(b&&S&&v&&y){var _=b/v/(S/y);l.push(Math.max(Math.min(_,1),0))}}for(var E=0,T=Object.entries(u);E<T.length;E++){var R=_slicedToArray(T[E],2),C=R[0],k=R[1];r[C]=k.length?JSON.stringify(k):""}var P=0,w=getDelta(s,this.lastVideoSendInfo.totalFramesEncoded),O=getDelta(c,this.lastVideoSendInfo.totalEncodedTime);w&&O&&(P=Math.round(1e3*O/w));var I=getDelta(a,this.lastVideoSendInfo.totalBytesSent);r.attr_duration_ms=p,r.attr_bitrate=p>0?Math.min(Math.round(8*I*1e3/p),2e7):0,r.attr_enc_average_elapsed_ms=P,this.videoSendReport=r,f&&(r.attr_resolution_sim="null",r.attr_encoded_framerate_sim="null");var A={web_dtlsState:(null===(n=_toConsumableArray(t.values()).find(function(e){return"transport"===e.type}))||void 0===n?void 0:n.dtlsState)||""};this.emit("video-send-stream",Object.assign(A,this.videoSendReport)),l.length&&(d=Math.min(Math.round(l.reduce(function(e,t){return t+e},0)/l.length*255),255)),this.bweReport={attr_duration_ms:p,attr_rtt:Math.round(e.roundTripTime||0),attr_reported_bitrate:Math.max(0,Math.min(e.availableOutgoingBitrate||0,2e7)),attr_lossrate:d},this.emit("bwe",Object.assign({},this.bweReport))}this.lastVideoSendInfo=e}},{key:"extractAudioMetrics",value:function(e){var t=this,r=Object.assign({},initAudioSendInfo,this.connection.peerConnectionStats);return e.forEach(function(e){if(/outboundrtp|outbound-rtp/i.test(e.type)?(r.timestamp=e.timestamp,r.bytesSent=e.bytesSent||0,r.packetsSent=e.packetsSent):/remote-inbound-rtp|remoteinboundrt/i.test(e.type)?void 0!==e.packetsLost&&(r.packetsLost=e.packetsLost):/media-source/i.test(e.type)&&e.audioLevel&&(r.audioLevel=e.audioLevel),t.track){var n=t.track.getMediaStreamTrack().getSettings(),i=n.channelCount,o=n.sampleRate;r.channels=i,r.sampleRate=o}}),r}},{key:"makeAudioReport",value:function(e){this.lastAudioSendInfo.timestamp>0&&e.timestamp&&(this.audioSendReport={attr_duration_ms:Math.round(getDelta(e.timestamp,this.lastAudioSendInfo.timestamp)),attr_bitrate:Math.round(8*getDelta(e.bytesSent,this.lastAudioSendInfo.bytesSent)*1e3/getDelta(e.timestamp,this.lastAudioSendInfo.timestamp))},this.emit("audio-send-stream",Object.assign({},this.audioSendReport))),this.lastAudioSendInfo=e}},{key:"makeReport",value:function(){var e=this;this.getStats().then(function(t){null!=t&&t.audioMetrics&&e.makeAudioReport(t.audioMetrics),null!=t&&t.videoMetrics&&e.makeVideoReport(t.videoMetrics,t.originStats)})}},{key:"getStats",value:function(){var e,t,r=this,n=this.tranceiver,i=this.pc;if(!i||null==n||null===(e=n.sender)||void 0===e||!e.track)return Promise.resolve({});if(null==i||!i.getStats)throw new DingRTCError(ErrorCode.BrowserNotSupported,"getStats is not supported");return null===(t=this.pc.getStats(n.sender.track))||void 0===t?void 0:t.then(function(e){return{videoMetrics:r.source?r.extractVideoMetrics(e):void 0,audioMetrics:r.source?void 0:r.extractAudioMetrics(e),originStats:e}})}}])}(Monitor);function _createForOfIteratorHelper$a(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$a(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$a(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$a(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_arrayLikeToArray$a(e,t):void 0}}function _arrayLikeToArray$a(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _callSuper$e(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$e()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$e(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$e=function(){return!!e})()}function _superPropGet$1(e,t,r,n){var i=_get(_getPrototypeOf$1(e.prototype),t,r);return"function"==typeof i?function(e){return i.apply(r,e)}:i}var initAudioReceiveInfo={timestamp:0,packetsLost:0,packetsReceived:0,bytesReceived:0,audioLevel:0,decodingNormal:0,roundTripTime:0},initVideoReciveInfo={packetsLost:0,packetsReceived:0,framesDropped:0,frameHeight:0,frameWidth:0,framesDecoded:0,framesReceived:0,timestamp:0,framesPerSecond:0,bytesReceived:0,roundTripTime:0},SubscribeMonitor=function(e){function t(e){var r,n;_classCallCheck$1(this,t),n=_callSuper$e(this,t),Object.defineProperty(n,"videoReceiveReport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"audioReceiveReport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"lastVideoReceiveInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"lastAudioReceiveInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"source",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"firstReportFlag",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"firstReportTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"pc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"tranceiver",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"tranceivers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"connection",{enumerable:!0,configurable:!0,writable:!0,value:void 0});var i=e.connection,o=e.transceiver,a=e.uid,s=e.stream,c=e.transceivers;return n.connection=i,n.pc=i.pc,n.tranceiver=o,n.tranceivers=c,n.firstReportTimer=addTimer(function(){n.getStats().then(function(e){n.makeFirstReport(e)})},400,"interval"),n.source="mcu"!==a&&(null===(r=s.media)||void 0===r||null===(r=r.video)||void 0===r?void 0:r.source),n.videoReceiveReport={attr_duration_ms:0,attr_bitrate:0,attr_current_delay:0,attr_stream_options:"",attr_resolution:"",attr_dec_frames:0,attr_decode_qp:0,attr_fraction_lost:0,attr_network_framerate:0,attr_render_delay:0,attr_dec_key_frames:-1},n.lastVideoReceiveInfo=Object.assign({},initVideoReciveInfo),n.firstReportFlag={audioFirstPacket:!1,videoFirstPacket:!1,audioFirstFrame:!1},n.lastAudioReceiveInfo=Object.assign({},initAudioReceiveInfo),n.audioReceiveReport={attr_duration_ms:0,attr_delay_estimate:0,attr_bitrate:0},n}return _inherits$1(t,e),_createClass$1(t,[{key:"extractAudioMetrics",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=Object.assign({},initAudioReceiveInfo,this.connection.peerConnectionStats);return n.timestamp=Date.now(),e.forEach(function(e){e.isRemote||(/inboundrtp|inbound-rtp/i.test(e.type)?(n.bytesReceived=e.bytesReceived||0,n.packetsReceived=e.packetsReceived||0,r||(n.packetsLost===(t.lastAudioReceiveInfo.packetsLost||0)?n.packetsReceivedForLost=t.lastAudioReceiveInfo.packetsReceived||0:n.packetsReceivedForLost=n.packetsReceived||0),n.packetsLost=e.packetsLost||0,n.audioLevel=e.audioLevel||0,n.decodingNormal=Number(e.googDecodingNormal||0)):/track/i.test(e.type)&&(n.audioLevel=e.audioLevel))}),n}},{key:"extractMultipleAudioMetrics",value:function(e){var t=this,r=e.map(function(e){return t.extractAudioMetrics(e,!0)}),n=Object.assign({},initAudioReceiveInfo,this.connection.peerConnectionStats);n.timestamp=Date.now();var i,o=_createForOfIteratorHelper$a(r);try{for(o.s();!(i=o.n()).done;){var a=i.value;n.bytesReceived+=a.bytesReceived||0,n.packetsLost+=a.packetsLost||0,n.packetsReceived+=a.packetsReceived||0,n.audioLevel=Math.max(n.audioLevel,a.audioLevel||0),n.decodingNormal=Math.max(n.decodingNormal,a.decodingNormal||0)}}catch(e){o.e(e)}finally{o.f()}return n.packetsLost===(this.lastAudioReceiveInfo.packetsLost||0)?n.packetsReceivedForLost=this.lastAudioReceiveInfo.packetsReceived||0:n.packetsReceivedForLost=n.packetsReceived||0,n}},{key:"extractVideoMetrics",value:function(e){var t=this,r=Object.assign({source:this.source},initVideoReciveInfo,this.connection.peerConnectionStats);return r.timestamp=Date.now(),e.forEach(function(e){if(!e.isRemote)if(/inboundrtp|inbound-rtp/i.test(e.type))r.framesDecoded=e.framesDecoded,r.packetsReceived=e.packetsReceived||0,r.framesReceived=e.framesReceived,r.keyFramesDecoded=e.keyFramesDecoded||0,r.packetsLost=e.packetsLost||0,r.packetsLost===(t.lastVideoReceiveInfo.packetsLost||0)?r.packetsReceivedForLost=t.lastVideoReceiveInfo.packetsReceived||0:r.packetsReceivedForLost=r.packetsReceived||0,r.bytesReceived=e.bytesReceived||0,r.firCount=e.firCount||0,r.pliCount=e.pliCount||0,r.freezeCount=e.freezeCount||0,r.retransmittedBytesReceived=e.retransmittedBytesReceived||0,r.retransmittedPacketsReceived=e.retransmittedPacketsReceived||0,void 0!==e.frameHeight&&(r.frameWidth=e.frameWidth||0,r.frameHeight=e.frameHeight||0);else if(/track/i.test(e.type))r.frameWidth=e.frameWidth||0,r.frameHeight=e.frameHeight||0;else if(/codec/i.test(e.type)){var n;null!==(n=e.mimeType)&&void 0!==n&&n.includes("video")&&(r.sdpFmtpLine=e.sdpFmtpLine)}}),r}},{key:"makeAudioReport",value:function(e){if(this.lastAudioReceiveInfo.timestamp>0&&e.timestamp){var t=Math.round(getDelta(e.timestamp,this.lastAudioReceiveInfo.timestamp)),r=getDelta(e.packetsLost,this.lastAudioReceiveInfo.packetsLost),n=getDelta(e.packetsReceivedForLost,this.lastAudioReceiveInfo.packetsReceivedForLost),i=getDelta(e.bytesReceived,this.lastAudioReceiveInfo.bytesReceived),o=0;try{o=Math.max(r/n,0)}catch(e){o=0}isNaN(o)&&(o=0),this.audioReceiveReport={attr_delay_estimate:0,attr_duration_ms:t,attr_bitrate:Math.round(8*i/(t/1e3))},this.emit("audio-net-eq",{attr_speech_expand_rate:0,attr_duration_ms:this.audioReceiveReport.attr_duration_ms,attr_packet_lossrate:Math.round(Math.min(16384*o,16384))}),this.emit("audio-recv-stream",Object.assign({},this.audioReceiveReport))}this.lastAudioReceiveInfo=e}},{key:"makeVideoReport",value:function(e){var t=this.lastVideoReceiveInfo,r=t.firCount,n=t.pliCount,i=t.timestamp,o=t.freezeCount,a=t.packetsLost,s=t.framesDecoded,c=t.framesDropped,u=t.bytesReceived,l=t.packetsReceivedForLost,d=t.retransmittedBytesReceived,p=t.retransmittedPacketsReceived;if(i>0&&e.timestamp){var f=getDelta(e.timestamp,i);if(e.bytesReceived-u>=0){var h=getDelta(e.packetsLost,a),g=getDelta(e.packetsReceivedForLost,l),m=0;try{m=Math.round(h/g*255)}catch(e){m=0}isNaN(m)&&(m=0);var v=getDelta(e.framesDecoded,s);this.videoReceiveReport={attr_network_framerate:Math.round(1e3*v/f),attr_dec_frames:v,attr_dec_key_frames:e.keyFramesDecoded,attr_decode_qp:0,attr_render_delay:0,attr_current_delay:0,attr_dropped_count:getDelta(e.framesDropped,c),attr_fir_count:getDelta(e.firCount,r),attr_freeze_count:getDelta(e.freezeCount,o),attr_pli_count:getDelta(e.pliCount,n),attr_retx_bytes:getDelta(e.retransmittedBytesReceived,d),attr_retx_packets:getDelta(e.retransmittedPacketsReceived,p),attr_bitrate:Math.round(8*getDelta(e.bytesReceived,u)*1e3/f),attr_stream_options:"audio:false/video:".concat(this.source,"/resolution:").concat(e.frameWidth,"*").concat(e.frameHeight,"/"),attr_fraction_lost:Math.max(0,Math.min(m,255)),attr_resolution:JSON.stringify([{count:v,resolution:"".concat(e.frameWidth,"*").concat(e.frameHeight)}]),attr_duration_ms:Math.round(f)},this.emit("video-recv-stream",Object.assign({},this.videoReceiveReport))}}this.lastVideoReceiveInfo=e}},{key:"makeReport",value:function(){var e=this;this.getStats().then(function(t){t.audioMetrics&&e.makeAudioReport(t.audioMetrics),t.videoMetrics&&e.makeVideoReport(t.videoMetrics)})}},{key:"makeFirstReport",value:function(e){var t=this.firstReportFlag,r=t.audioFirstFrame,n=t.audioFirstPacket,i=t.videoFirstPacket,o=e.audioMetrics,a=e.videoMetrics;if(o&&a){if((r||-1===(null==o?void 0:o.decodingNormal))&&n&&i)return void(this.firstReportTimer&&(removeTimer(this.firstReportTimer,"interval"),this.firstReportTimer=null))}else if(o){if((r||-1===(null==o?void 0:o.decodingNormal))&&n)return void(this.firstReportTimer&&(removeTimer(this.firstReportTimer,"interval"),this.firstReportTimer=null))}else if(a&&i)return void(this.firstReportTimer&&(removeTimer(this.firstReportTimer,"interval"),this.firstReportTimer=null));null!=o&&o.packetsReceived&&!n&&(this.emit("audio-first-packet"),this.firstReportFlag.audioFirstPacket=!0),Number(null==o?void 0:o.decodingNormal)>0&&!r&&(this.emit("audio-first-frame"),this.firstReportFlag.audioFirstPacket=!0),null!=a&&a.packetsReceived&&!i&&(this.emit("video-first-packet"),this.firstReportFlag.videoFirstPacket=!0)}},{key:"getStats",value:function(){var e,t=this,r=this.tranceiver,n=this.tranceivers,i=this.pc;if(!(i&&(null!=n&&n.length||null!=r&&r.receiver.track)))return Promise.resolve({});if(null==i||!i.getStats)throw new DingRTCError(ErrorCode.BrowserNotSupported,"getStats is not supported");if(n&&n.length){var o=n.map(function(e){return e.receiver.track}).filter(function(e){return!!e});return Promise.all(o.map(function(e){return i.getStats(e)})).then(function(e){return{audioMetrics:t.extractMultipleAudioMetrics(e)}})}return null!=r&&null!==(e=r.receiver)&&void 0!==e&&e.track?i.getStats(r.receiver.track).then(function(e){return{videoMetrics:t.source?t.extractVideoMetrics(e):void 0,audioMetrics:t.source?void 0:t.extractAudioMetrics(e)}}):void 0}},{key:"stop",value:function(){_superPropGet$1(t,"stop",this)([]),this.firstReportTimer&&(removeTimer(this.firstReportTimer,"interval"),this.firstReportTimer=null)}}])}(Monitor),lib={},parser$1={},grammar$3={exports:{}},grammar$2=grammar$3.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(grammar$2).forEach(function(e){grammar$2[e].forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})});var grammarExports=grammar$3.exports;!function(e){var t=function(e){return String(Number(e))===e?Number(e):e},r=function(e,r,n){var i=e.name&&e.names;e.push&&!r[e.push]?r[e.push]=[]:i&&!r[e.name]&&(r[e.name]={});var o=e.push?{}:i?r[e.name]:r;!function(e,r,n,i){if(i&&!n)r[i]=t(e[1]);else for(var o=0;o<n.length;o+=1)null!=e[o+1]&&(r[n[o]]=t(e[o+1]))}(n.match(e.reg),o,e.names,e.name),e.push&&r[e.push].push(o)},n=grammarExports,i=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},o=[],a=t;return e.split(/(\r\n|\r|\n)/).filter(i).forEach(function(e){var t=e[0],i=e.slice(2);"m"===t&&(o.push({rtp:[],fmtp:[]}),a=o[o.length-1]);for(var s=0;s<(n[t]||[]).length;s+=1){var c=n[t][s];if(c.reg.test(i))return r(c,a,i)}}),t.media=o,t};var o=function(e,r){var n=r.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&r.length>1&&(e[n[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var r=[],n=e.split(" ").map(t),i=0;i<n.length;i+=3)r.push({component:n[i],ip:n[i+1],port:n[i+2]});return r},e.parseImageAttributes=function(e){return e.split(" ").map(function(e){return e.substring(1,e.length-1).split(",").reduce(o,{})})},e.parseSimulcastStreamList=function(e){return e.split(";").map(function(e){return e.split(",").map(function(e){var r,n=!1;return"~"!==e[0]?r=t(e):(r=t(e.substring(1,e.length)),n=!0),{scid:r,paused:n}})})}}(parser$1);var grammar$1=grammarExports,formatRegExp=/%[sdv%]/g,format=function(e){var t=1,r=arguments,n=r.length;return e.replace(formatRegExp,function(e){if(t>=n)return e;var i=r[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(i);case"%d":return Number(i);case"%v":return""}})},makeLine=function(e,t,r){var n=[e+"="+(t.format instanceof Function?t.format(t.push?r:r[t.name]):t.format)];if(t.names)for(var i=0;i<t.names.length;i+=1){var o=t.names[i];t.name?n.push(r[t.name][o]):n.push(r[t.names[i]])}else n.push(r[t.name]);return format.apply(null,n)},defaultOuterOrder=["v","o","s","i","u","e","p","c","b","t","r","z","a"],defaultInnerOrder=["i","c","b","a"],writer$1=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach(function(e){null==e.payloads&&(e.payloads="")});var r=t.outerOrder||defaultOuterOrder,n=t.innerOrder||defaultInnerOrder,i=[];return r.forEach(function(t){grammar$1[t].forEach(function(r){r.name in e&&null!=e[r.name]?i.push(makeLine(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach(function(e){i.push(makeLine(t,r,e))})})}),e.media.forEach(function(e){i.push(makeLine("m",grammar$1.m[0],e)),n.forEach(function(t){grammar$1[t].forEach(function(r){r.name in e&&null!=e[r.name]?i.push(makeLine(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach(function(e){i.push(makeLine(t,r,e))})})})}),i.join("\r\n")+"\r\n"},parser=parser$1,writer=writer$1,grammar=grammarExports;function _createForOfIteratorHelper$9(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$9(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$9(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$9(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_arrayLikeToArray$9(e,t):void 0}}function _arrayLikeToArray$9(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function ownKeys$6(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function _objectSpread$6(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$6(Object(r),!0).forEach(function(t){_defineProperty(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$6(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function _callSuper$d(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$d()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$d(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$d=function(){return!!e})()}lib.grammar=grammar,lib.write=writer,lib.parse=parser.parse,lib.parseParams=parser.parseParams,lib.parseFmtpConfig=parser.parseFmtpConfig,lib.parsePayloads=parser.parsePayloads,lib.parseRemoteCandidates=parser.parseRemoteCandidates,lib.parseImageAttributes=parser.parseImageAttributes,lib.parseSimulcastStreamList=parser.parseSimulcastStreamList;var logger$2=getReporter().getLoggerWithPrefix("[rtc-subs]"),Subscription=function(e){function t(e){var r;_classCallCheck$1(this,t),r=_callSuper$d(this,t),Object.defineProperty(r,"stream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"resolutionInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"ssrc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"startTime",{enumerable:!0,configurable:!0,writable:!0,value:Date.now()}),Object.defineProperty(r,"uid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"subIdAcc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"state",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"monitor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"userConfigResolution",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"connection",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"rtcSignaling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"_stream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"stucked",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"metricsMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"audioStatsMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"videoStatsMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"transceiver",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"transceivers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"targetMediaType",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"logTrackEnded",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t;r.state===PubSubStates.Processing&&r.logger.info("sub track ended",null==e||null===(t=e.target)||void 0===t?void 0:t.id,r.subIdAcc)}}),Object.defineProperty(r,"logTrackUnmute",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t;r.state===PubSubStates.Processing&&r.logger.info("sub track unmute",null==e||null===(t=e.target)||void 0===t?void 0:t.id,r.subIdAcc)}}),Object.defineProperty(r,"logTrackMute",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t;r.state===PubSubStates.Processing&&r.logger.info("sub track mute",null==e||null===(t=e.target)||void 0===t?void 0:t.id,r.subIdAcc)}}),Object.defineProperty(r,"updateTransceiverListeners",{enumerable:!0,configurable:!0,writable:!0,value:function(){var e,t;null!==(e=r.transceiver)&&void 0!==e&&null!==(e=e.receiver)&&void 0!==e&&e.transport?(r.transceiver.receiver.transport.onerror=r._onDtlsError,r.transceiver.receiver.transport.onstatechange=r._onDtlsStateChange,null!==(t=r.transceiver)&&void 0!==t&&null!==(t=t.receiver)&&void 0!==t&&t.transport.iceTransport&&(r.transceiver.receiver.transport.iceTransport.onselectedcandidatepairchange=r._onSelectedCandidatePairChange.bind(r,r.transceiver.receiver))):r.logger.info("browser version low, no dtls transport to watch")}}),Object.defineProperty(r,"_onDtlsError",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t;r.logger.error("".concat(r.id," ").concat(r.uid," ").concat(r.subIdAcc," dtls_error"),null==e||null===(t=e.error)||void 0===t?void 0:t.errorDetail)}}),Object.defineProperty(r,"_onDtlsStateChange",{enumerable:!0,configurable:!0,writable:!0,value:function(){r.logger.info("".concat(r.id," ").concat(r.uid," ").concat(r.subIdAcc," dtls_state_change"),r.transceiver.receiver.transport.state)}}),Object.defineProperty(r,"_onSelectedCandidatePairChange",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t,n=null==e||null===(t=e.transport)||void 0===t||null===(t=t.iceTransport)||void 0===t?void 0:t.getSelectedCandidatePair();r.logger.info("".concat(r.id," ").concat(r.uid," ").concat(r.subIdAcc," selected_candidate_pair_change"),n)}}),r.subIdAcc="subIdAcc-".concat(t.subIdAcc++);var n=e.connection,i=e.stream,o=e.uid,a=e.resolutionInfo,s=e.userConfigResolution,c=e.targetMediaType;return r.connection=n,r.targetMediaType=c,r.resolutionInfo=a,r.userConfigResolution=s,r.rtcSignaling=n.rtcSignaling,r.stream=i,r.uid=o,r.reporter=n.reporter,r.logger=r.reporter.getLoggerWithPrefix("[rtc-subs]"),r.connection.once("ended",function(){r.clear()}),r.videoStatsMap=new Map,r.audioStatsMap=new Map,r.metricsMap=new Map,r.state=PubSubStates.Processing,r.handleStreamAdd=r.handleStreamAdd.bind(r),r.connection.on("track",r.handleStreamAdd),r}return _inherits$1(t,e),_createClass$1(t,[{key:"handleStreamAdd",value:function(e,t){var r,n=this;if(clientConfig.audioSFU&&"audio"===e.kind){var i,o=null===(i=this.transceivers)||void 0===i?void 0:i.map(function(e){var t;return null===(t=e.receiver)||void 0===t||null===(t=t.track)||void 0===t?void 0:t.id});null!=o&&o.includes(e.id)&&(e.removeEventListener("ended",this.logTrackEnded),e.removeEventListener("unmute",this.logTrackUnmute),e.removeEventListener("mute",this.logTrackMute),e.addEventListener("ended",this.logTrackEnded),e.addEventListener("unmute",this.logTrackUnmute),e.addEventListener("mute",this.logTrackMute)),this._stream=this._stream||new MediaStream([]),this._stream.addTrack(e)}else if(e.id===(null===(r=this.transceiver)||void 0===r||null===(r=r.receiver)||void 0===r||null===(r=r.track)||void 0===r?void 0:r.id)){e.removeEventListener("ended",this.logTrackEnded),e.removeEventListener("unmute",this.logTrackUnmute),e.removeEventListener("mute",this.logTrackMute),e.addEventListener("ended",this.logTrackEnded),e.addEventListener("unmute",this.logTrackUnmute),e.addEventListener("mute",this.logTrackMute),this._stream=new MediaStream([e]);var a=document.createElement("video");a.onloadeddata=function(){a.srcObject=null,n.handleVideoFirstFrame()},a.srcObject=this._stream}}},{key:"mediaStream",get:function(){return this._stream||this.connection.mcuAudioStream}},{key:"stop",value:function(){var e=this;if(this.state===PubSubStates.Processing)return this.clear(),this.rtcSignaling.unsubscribe({subscriptionId:this.id}).catch(function(t){e.logger.warn("negative ack for unsubscribing, ".concat(t))})}},{key:"mute",value:function(e){return this.rtcSignaling.subscriptionControl({subscriptionId:this.id,operation:"pause",track:e})}},{key:"unmute",value:function(e){return this.rtcSignaling.subscriptionControl({subscriptionId:this.id,operation:"play",track:e})}},{key:"applyOptions",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=this.stream.id;return this.resolutionInfo=getResoParamToSend(this.stream,e),t||(this.userConfigResolution=e),this.rtcSignaling.subscriptionControl({subscriptionId:this.id,operation:"update",updateDesc:{video:{from:r,params:this.resolutionInfo}}})}},{key:"reset",value:function(){this.connection.off("track",this.handleStreamAdd),this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.metricsMap.clear(),this.audioStatsMap.clear(),this.videoStatsMap.clear()}},{key:"clear",value:function(){this.state!==PubSubStates.End&&(this.reset(),this.state=PubSubStates.End,this.emit("ended"))}},{key:"addTransceiver",value:function(e){this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.metricsMap.clear(),this.audioStatsMap.clear(),this.videoStatsMap.clear(),this.transceiver=e,this.monitor=new SubscribeMonitor(this),this.onMonitor()}},{key:"addTransceivers",value:function(e){this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.transceivers=e,this.monitor=new SubscribeMonitor(this),this.onMonitor()}},{key:"handleVideoFirstFrame",value:function(){this.reporter.trace.videoFirstFrame({sessionId:this.id,remoteStreamId:this.stream.id,attr_elapse_time:Date.now()-this.startTime,remoteUserId:this.uid}),this.logger.info("video-first-frame sessionId=".concat(this.id))}},{key:"handleMetrics",value:function(e,t){var r=e.audioMetrics,n=e.videoMetrics;if(r){var i,o=(null===(i=this.metricsMap.get(t))||void 0===i?void 0:i.audioMetrics)||{},a=getDeltaDurationInSeconds(r,o),s=getDelta(r.bytesReceived,o.bytesReceived),c={codec:this.connection.peerConnectionStats.audioCodec||r.codec,receiveBytes:r.bytesReceived,receivePackets:r.packetsReceived,receivePacketsLost:r.packetsLost,rtt:r.roundTripTime,audioLevel:Math.max(r.audioLevel,0),timestamp:r.timestamp,receiveBitrate:8*s/a};this.audioStatsMap.set(t,c)}else if(n){var u,l,d=(null===(u=this.metricsMap.get(t))||void 0===u?void 0:u.videoMetrics)||{},p=getDeltaDurationInSeconds(n,d),f=getDelta(n.bytesReceived,d.bytesReceived),h={codec:this.connection.peerConnectionStats.videoCodec||n.codec,receiveResolution:{width:n.frameWidth,height:n.frameHeight},receiveBitrate:8*f/p,decodeFrameRate:Math.round(getDelta(null==n?void 0:n.framesDecoded,d.framesDecoded)/p),receiveFrameRate:Math.round(getDelta(null==n?void 0:n.framesReceived,d.framesReceived)/p),keyFramesDecoded:null==n?void 0:n.keyFramesDecoded,receiveFramesDropped:getDelta(null==n?void 0:n.framesDropped,d.framesDropped),receiveBytes:n.bytesReceived,receivePackets:n.packetsReceived,receivePacketsLost:n.packetsLost,rtt:n.roundTripTime,timestamp:n.timestamp},g=this.connection.subSdpFmtpLines.some(function(e){return e.includes("64")}),m=(null===(l=this.stream.media)||void 0===l||null===(l=l.video)||void 0===l?void 0:l.source)===exports.VideoSourceInfo.CAMERA&&f>STUCK_JUDGE_RECV_BYTES&&0===h.decodeFrameRate;"network"===t&&(this.stucked&&m?g&&h.receiveFramesDropped>0&&!clientConfig.downlinkForbidHighProfile&&this.connection.handleHighProfileFallback():this.stucked=m),this.videoStatsMap.set(t,h)}this.metricsMap.set(t,e)}},{key:"getMetrics",value:function(e){var t,r=this;return null===(t=this.connection)||void 0===t?void 0:t.getStats().then(function(){var t;null===(t=r.monitor)||void 0===t||t.getStats().then(function(t){return r.handleMetrics(t,e)})})}},{key:"onMonitor",value:function(){var e=this;"mcu"===this.uid?(this.monitor.on("audio-net-eq",function(t){e.reporter.metric.audioNetEQ(_objectSpread$6({sessionId:e.id,remoteStreamId:e.stream.id,remoteUserId:e.uid},t))}),this.monitor.on("audio-recv-stream",function(t){e.reporter.metric.audioRecvStream(_objectSpread$6({sessionId:e.id,remoteStreamId:e.stream.id,remoteUserId:e.uid},t))}),this.monitor.on("audio-first-packet",function(){e.reporter.trace.audioFirstPacket({sessionId:e.id,remoteStreamId:e.stream.id,remoteUserId:e.uid})}),this.monitor.on("audio-first-frame",function(){e.emit("audio-first-frame")})):(this.monitor.on("video-first-packet",function(){e.reporter.trace.videoFirstPacket({sessionId:e.id,remoteStreamId:e.stream.id,remoteUserId:e.uid}),e.logger.info("video-first-packet sessionId=".concat(e.id))}),this.monitor.on("video-recv-stream",function(t){e.reporter.metric.videoRecvStream(_objectSpread$6({sessionId:e.id,remoteStreamId:e.stream.id,remoteUserId:e.uid},t))}))}}])}(EventEmitter);Object.defineProperty(Subscription,"subIdAcc",{enumerable:!0,configurable:!0,writable:!0,value:0});var getResoParamToSend=function(e,t){if(!t)return null;var r=t.resolutionLevel,n=e.media.video.highestResolutionLevel;if(n&&n<r){var i=getResoLevelNameByResoLevelNum(n);return calcResolutionInfo(i,getStreamSupportedResoArr(e))}return t},prepareForBatchSubscribe=function(e){var t,r={audio:[],video:[]},n=_createForOfIteratorHelper$9(e);try{for(n.s();!(t=n.n()).done;){var i=t.value,o=i.stream,a=i.error,s=i.resolutionInfo,c=i.targetMediaType;if(a)logger$2.error("skip subscribe",o,a);else{var u=getSingleMediaOption(o,s,c),l=u.audio,d=u.video;if("audio"===c&&l){var p=_objectSpread$6(_objectSpread$6({},l),{},{trackId:o.media.audio.trackId,ssrcGroup:[{ssrc:generateSubSsrc()}]});clientConfig.audioSFU&&(p.ssrcGroup=new Array(6).fill(0).map(function(){return{ssrc:generateSubSsrc()}})),r.audio.push(p)}else if("video"===c&&d){var f,h;r.video.push(_objectSpread$6(_objectSpread$6({},d),{},{trackId:null===(f=o.media)||void 0===f||null===(f=f.video)||void 0===f?void 0:f.trackId,ssrcGroup:null===(h=o.media)||void 0===h||null===(h=h.video)||void 0===h?void 0:h.ssrcGroup,subSsrcGroup:{ssrc:generateSubSsrc(),rtxSsrc:generateSubSsrc()}}))}}}}catch(e){n.e(e)}finally{n.f()}return r},getSingleMediaOption=function(e,t,r){var n=e.id,i=e.media,o=i.audio,a=i.video,s={};if(o&&"audio"===r)s.audio={from:n};else if(a&&"video"===r){var c;s.video={from:n,format:null===(c=i.video)||void 0===c?void 0:c.format,parameters:getResoParamToSend(e,t)}}return s},batchSubscribeStart=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t,r){var n,i,o,a;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return n=[],i={},t.forEach(function(e,t){var o=e.stream,a=e.error,s=e.uid,c=e.resolutionInfo,u=e.targetMediaType;if(n[t]={stream:o,error:a,uid:s,resolutionInfo:c},!a){var l=new Subscription({connection:r,uid:s,userConfigResolution:c,resolutionInfo:c&&getResoParamToSend(o,c),stream:o,targetMediaType:u});i[o.id]=l}}),a=new Promise(function(e,a){o=function(){var o=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function o(){var s;return _regeneratorRuntime$1.wrap(function(o){for(;;)switch(o.prev=o.next){case 0:if((s=prepareForBatchSubscribe(t)).audio.length||s.video.length){o.next=1;break}return logger$2.info("batchSubscribe no valid media to sub"),o.abrupt("return",e(n));case 1:return o.next=2,adjustDownlinkSDPWhenSubscribe(r,s,i);case 2:r.rtcSignaling.batchSubscribe({connectionId:r.id,propertiesJsonStr:JSON.stringify({opusExtendInbandFec:!0,type:clientConfig.audioSFU?"selective":"mixed"}),supportTemporalLayer:!1,media:s}).then(function(){var r=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function r(o){var a,s,c,u,l,d;return _regeneratorRuntime$1.wrap(function(r){for(;;)switch(r.prev=r.next){case 0:if(a=o.detailStatus,"ok"===(s=o.globalStatus)){r.next=1;break}return n.forEach(function(e){e.error=e.error||parseSubscribeError(e.stream,s)}),r.abrupt("return",e(n));case 1:c=_createForOfIteratorHelper$9(a),r.prev=2,l=_regeneratorRuntime$1.mark(function e(){var r,o,a,s,c,l;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:r=u.value,o=r.id,a=r.msg,s=r.origin,c=i[s.id],l=t.findIndex(function(e){return e.stream.id===s.id}),"ok"===a&&c?(c.id=o,n[l].id=o,n[l].subscription=c):"ok"!==a&&(n[l].error=parseSubscribeError(c.stream,a));case 1:case"end":return e.stop()}},e)}),c.s();case 3:if((u=c.n()).done){r.next=5;break}return r.delegateYield(l(),"t0",4);case 4:r.next=3;break;case 5:r.next=7;break;case 6:r.prev=6,d=r.catch(2),c.e(d);case 7:return r.prev=7,c.f(),r.finish(7);case 8:e(n);case 9:case"end":return r.stop()}},r,null,[[2,6,7,8]])}));return function(e){return r.apply(this,arguments)}}()).catch(a);case 3:case"end":return o.stop()}},o)}));return function(){return o.apply(this,arguments)}}()}),r.addTask(o),e.abrupt("return",a);case 1:case"end":return e.stop()}},e)}));return function(t,r){return e.apply(this,arguments)}}(),batchSubscribeStop=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t,r){var n,i;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return i=new Promise(function(e,i){n=function(){var n=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function n(){var o,a;return _regeneratorRuntime$1.wrap(function(n){for(;;)switch(n.prev=n.next){case 0:return o=t.filter(function(e){var t;return!(null===(t=e.stream)||void 0===t||null===(t=t.media)||void 0===t||!t.audio)}).map(function(e){return e.id}),a=t.filter(function(e){var t;return!(null===(t=e.stream)||void 0===t||null===(t=t.media)||void 0===t||!t.video)}).map(function(e){return e.id}),n.next=1,adjustDownlinkSDPWhenUnsubscribe(r,t);case 1:r.rtcSignaling.batchUnSubscribe({connectionId:r.id,audio:o,video:a}).then(function(){t.forEach(function(e){e.clear()}),e(void 0)}).catch(i);case 2:case"end":return n.stop()}},n)}));return function(){return n.apply(this,arguments)}}()}),r.addTask(n),e.abrupt("return",i);case 1:case"end":return e.stop()}},e)}));return function(t,r){return e.apply(this,arguments)}}();function ownKeys$5(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function _objectSpread$5(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$5(Object(r),!0).forEach(function(t){_defineProperty(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$5(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function _createForOfIteratorHelper$8(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$8(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$8(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$8(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_arrayLikeToArray$8(e,t):void 0}}function _arrayLikeToArray$8(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}var logger$1=getReporter().getLoggerWithPrefix("[rtc-sdp]"),optionzationMap={motion:"maintain-framerate",detail:"maintain-resolution",balanced:"balanced"},ssrcPrefix=0,ssrcMask=0,ssrcSeed=0,inUseSsrcSet=new Set,parseSubSsrcInfo=function(e,t){var r=Math.log2(e+1);t>2147483647>>r||(ssrcMask=e,ssrcPrefix=(t<<r|2147483648)>>>0)},generateSubSsrc=function(){if(0==ssrcPrefix||0==ssrcMask)return 0;var e=Math.min(ssrcMask+1,1e4);do{var t=ssrcPrefix+(ssrcMask&ssrcSeed++);if(0!=t&&!inUseSsrcSet.has(t))return t}while(--e>0);return 0},useSubSsrcGroup=function(e){e.ssrc&&inUseSsrcSet.add(e.ssrc),e.rtxSsrc&&inUseSsrcSet.add(e.rtxSsrc)},addRidsToMline=function(e,t){var r,n;if((null===(r=e.rids)||void 0===r?void 0:r.length)>1)return Environment.isFirefox()&&(t=addRidExtForFirefox(t)),t.rids=null===(n=e.rids)||void 0===n?void 0:n.map(function(e){return{direction:"recv",id:e.id}}),t.simulcast={dir1:"recv",list1:e.simulcast.list1},t},adjustUplinkSDPWhenApplyOptions=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n,i,o,a,s,c;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return r=t.connection,n=t.transceiver,i=r.remoteSDP,o=r.pc,e.next=1,o.createOffer();case 1:return a=e.sent,e.next=2,o.setLocalDescription(a);case 2:return r.localSDP=lib.parse(a.sdp),s=r.localSDP.media.find(function(e){return e.mid==n.mid}),c=i.media.find(function(e){return e.mid==n.mid}),addRidsToMline(s,c),e.next=3,o.setRemoteDescription({type:"answer",sdp:lib.write(i)});case 3:r.remoteSDP=i;case 4:case"end":return e.stop()}},e)}));return function(t){return e.apply(this,arguments)}}(),addTransceiversAndSetSdpToPC=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t,r){var n,i,o,a,s,c,u,l,d,p,f;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return n=t.pc,i=t.idToTransceiverMap,o=t.remoteSDP,a=new MediaStream(r.map(function(e){return e.getMediaStreamTrack()})),s=r.map(function(e){var r={direction:"sendonly"};if(e instanceof LocalVideoTrack){var n=getSenderEncodingArrAndResoLevel(e).encodings;r.sendEncodings=n.filter(function(e){return e.activeForBitrateMap}).map(function(e){return{rid:e.rid||void 0,maxBitrate:1e3*e.maxBitrate,maxFramerate:e.maxFramerate,active:e.activeForRealuse,scaleResolutionDownBy:e.scaleResolutionDownBy}})}var o=t.pc.addTransceiver(e.getMediaStreamTrack()||e.trackMediaType,r);if(e instanceof LocalVideoTrack&&o.sender.setParameters){var a=e.optimizationMode,s=o.sender.getParameters();s.degradationPreference=optionzationMap[a]||"balanced";var c=parseFloat(new URLSearchParams(location.search).get("times"))||0;c&&(logger$1.info("adjustUplinkSDPWhenPublish maxBitrate times",c),s.encodings.forEach(function(e){if(e.maxBitrate){var t=e.maxBitrate;e.maxBitrate=e.maxBitrate*c,logger$1.info("adjustUplinkSDPWhenPublish update maxBitrate",t,e.maxBitrate,e)}})),logger$1.info("adjustUplinkSDPWhenPublish setParameters",s),o.sender.setParameters(s)}return i.set(e.getTrackId(),o),o}),e.next=1,n.createOffer();case 1:return c=e.sent,u=lib.parse(c.sdp),e.next=2,n.setLocalDescription(c);case 2:t.localSDP=u,o.groups[0].mids=t.localSDP.groups[0].mids,l=_createForOfIteratorHelper$8(s),e.prev=3,p=_regeneratorRuntime$1.mark(function e(){var t,r,n,i,a,s,c;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:t=d.value,r=o.media.find(function(e){return e.type===t.sender.track.kind}),Environment.isFirefox()&&"video"===r.type&&(delete r.rids,delete r.simulcast),n=_objectSpread$5(_objectSpread$5({},r),{},{ext:_toConsumableArray(r.ext),mid:t.mid}),i=u.media.find(function(e){return e.mid==t.mid}),a=new URLSearchParams(location.search).get("startkbs")||2e3,s=new URLSearchParams(location.search).get("minkbs"),c=new URLSearchParams(location.search).get("maxkbs"),logger$1.info("startkbs, minkbs, maxkbs",a,s,c),n.fmtp.map(function(e){if(/profile-level-id/i.test(e.config)){var t=e.config.split(";").filter(function(e){return!/x-google-start-bitrate/i.test(e)});a&&clientConfig.highStartBitrate?t.push("x-google-start-bitrate=".concat(a)):t.push("x-google-start-bitrate=500"),s&&t.push("x-google-min-bitrate=".concat(s)),c&&t.push("x-google-max-bitrate=".concat(c)),e.config=t.join(";")}}),addRidsToMline(i,n),o.media.push(n);case 1:case"end":return e.stop()}},e)}),l.s();case 4:if((d=l.n()).done){e.next=6;break}return e.delegateYield(p(),"t0",5);case 5:e.next=4;break;case 6:e.next=8;break;case 7:e.prev=7,f=e.catch(3),l.e(f);case 8:return e.prev=8,l.f(),e.finish(8);case 9:return window.remoteSDP=o,e.next=10,n.setRemoteDescription({type:"answer",sdp:lib.write(o)});case 10:return t.remoteSDP=o,e.abrupt("return",{localSDP:t.localSDP,stream:a});case 11:case"end":return e.stop()}},e,null,[[3,7,8,9]])}));return function(t,r){return e.apply(this,arguments)}}(),adjustUplinkSDPWhenUnpublish=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t,r){var n,i,o,a;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return n=t.pc,i=t.remoteSDP,r.map(function(e){return e.transceiver}).forEach(function(e){if(e){n.removeTrack(e.sender);var t=i.media.find(function(t){return t.mid==(null==e?void 0:e.mid)});e.direction="inactive",t.direction="inactive"}}),e.next=1,n.createOffer();case 1:return o=e.sent,a=lib.parse(o.sdp),e.next=2,n.setLocalDescription(o);case 2:return t.localSDP=a,i.groups[0].mids=a.groups[0].mids,t.remoteSDP=i,e.next=3,n.setRemoteDescription({type:"answer",sdp:lib.write(i)});case 3:case"end":return e.stop()}},e)}));return function(t,r){return e.apply(this,arguments)}}(),addSSRC=function(e,t,r){var n=e.ssrc,i=e.rtxSsrc;useSubSsrcGroup(e),t.ssrcGroups=[],i&&t.ssrcGroups.push({semantics:"FID",ssrcs:"".concat(n," ").concat(i)}),t.ssrcs=[],[n,i].filter(function(e){return void 0!==e}).forEach(function(e){t.ssrcs.push({attribute:"msid",value:"".concat(r," v").concat(n),id:e},{attribute:"cname",value:createUuid(),id:e})})},addRidExtForFirefox=function(e){var t;return null!=e&&null!==(t=e.ext)&&void 0!==t&&t.some(function(e){return e.uri.includes("rtp-stream-id")})||e.ext.push({value:8,uri:"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id"},{value:9,uri:"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"}),e},adjustDownlinkSDPWhenSubscribe=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t,r,n){var i,o,a,s,c,u,l,d,p,f,h,g,m,v,y,b,S,_,E,T,R,C,k,P,w,O,I,A,M,N,D,x,L,j,$,U,F,V,G,B;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(s=t.pc,c=t.idToTransceiverMap,u=t.remoteSDP,l=t.idToTransceiversMap,d=u.media.find(function(e){return"video"===e.type}),p=u.media.find(function(e){return"audio"===e.type}),f=null===(i=d.ssrcs)||void 0===i?void 0:i.find(function(e){return"msid"===e.attribute}).value.split(" ")[0],null!==(o=r.audio)&&void 0!==o&&o[0])if(g=null===(h=r.audio)||void 0===h?void 0:h[0],m=g.from,clientConfig.audioSFU){if(l.get(m)){v=_createForOfIteratorHelper$8(l.get(m));try{for(v.s();!(y=v.n()).done;)y.value.direction="recvonly"}catch(e){v.e(e)}finally{v.f()}b=u.media.filter(function(e){return"audio"===e.type}),S=_createForOfIteratorHelper$8(b);try{for(S.s();!(_=S.n()).done;)_.value.direction="sendonly"}catch(e){S.e(e)}finally{S.f()}}else t.mcuAudioTranceivers=new Array(6).fill(0).map(function(e){return t.pc.addTransceiver("audio",{direction:"recvonly"})}),l.set(m,t.mcuAudioTranceivers);n[m].addTransceivers(l.get(m))}else c.get(m)||c.set(m,t.mcuAudioTranceiver),c.get(m).direction="recvonly",p.direction="sendonly",n[m].addTransceiver(c.get(m));E=_createForOfIteratorHelper$8(r.video),e.prev=1,R=_regeneratorRuntime$1.mark(function e(){var t,r,i,o;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(t=T.value,r=t.from,i=c.get(r)){e.next=1;break}c.set(r,s.addTransceiver("video",{direction:"recvonly"})),e.next=5;break;case 1:if("inactive"===i.direction){e.next=4;break}return i.direction="inactive",e.next=2,s.createOffer();case 2:return o=e.sent,e.next=3,s.setLocalDescription(o);case 3:return u.media.find(function(e){return e.mid==i.mid}).direction="inactive",e.next=4,s.setRemoteDescription({type:"answer",sdp:lib.write(u)});case 4:c.get(r).direction="recvonly";case 5:n[r].addTransceiver(c.get(r));case 6:case"end":return e.stop()}},e)}),E.s();case 2:if((T=E.n()).done){e.next=4;break}return e.delegateYield(R(),"t0",3);case 3:e.next=2;break;case 4:e.next=6;break;case 5:e.prev=5,G=e.catch(1),E.e(G);case 6:return e.prev=6,E.f(),e.finish(6);case 7:return e.next=8,s.createOffer();case 8:return C=e.sent,k=lib.parse(C.sdp),u.groups[0].mids=k.groups[0].mids,e.next=9,s.setLocalDescription(C);case 9:t.localSDP=k,clientConfig.audioSFU&&r.audio[0]&&(P=r.audio[0],w=P.ssrcGroup,O=P.from,l.get(O).forEach(function(e,t){var r,n=null===(r=w[t])||void 0===r?void 0:r.ssrc,i=u.media.find(function(t){var r=t.mid,n=t.type;return r==e.mid&&"audio"===n});i||(i=_objectSpread$5(_objectSpread$5({},p),{},{mid:e.mid}),u.media.push(i)),i.ssrcs=getSsrcInfo(n,f),i.direction="sendonly"})),I=_createForOfIteratorHelper$8(r.video),e.prev=10,M=_regeneratorRuntime$1.mark(function e(){var t,r,i,o,a;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:t=A.value,r=t.from,i=t.subSsrcGroup,o=c.get(r),a=u.media.find(function(e){var t=e.mid,r=e.type;return t==o.mid&&"video"===r}),a||((a=_objectSpread$5({},d)).mid=o.mid,u.media.push(a)),a.direction="sendonly",n[r].ssrc=null==i?void 0:i.ssrc,addSSRC(i,a,f);case 1:case"end":return e.stop()}},e)}),I.s();case 11:if((A=I.n()).done){e.next=13;break}return e.delegateYield(M(),"t1",12);case 12:e.next=11;break;case 13:e.next=15;break;case 14:e.prev=14,B=e.catch(10),I.e(B);case 15:return e.prev=15,I.f(),e.finish(15);case 16:return logger$1.info("sub remoteSDP before remove high profile",lib.write(u)),removeHighProfileH264(u),t.remoteSDP=u,N=lib.write(u),logger$1.info("sub remoteSDP after remove high profile",N),e.next=17,s.setRemoteDescription({type:"answer",sdp:N});case 17:null!==(a=r.audio)&&void 0!==a&&a[0]&&(x=null===(D=r.audio)||void 0===D?void 0:D[0],L=x.from,clientConfig.audioSFU||n[L].addTransceiver(c.get(L))),j=_createForOfIteratorHelper$8(r.video);try{for(j.s();!($=j.n()).done;)F=$.value,V=F.from,null===(U=n[V])||void 0===U||U.updateTransceiverListeners()}catch(e){j.e(e)}finally{j.f()}case 18:case"end":return e.stop()}},e,null,[[1,5,6,7],[10,14,15,16]])}));return function(t,r,n){return e.apply(this,arguments)}}(),keepH264CbProfileOnly=function(e){removeSpecificH264ProfileCodec(e,function(e){return!/profile-level-id=42e01f/i.test(e)&&/profile-level-id/i.test(e)})},removeHighProfileH264=function(e){removeSpecificH264ProfileCodec(e,function(e){return/profile-level-id=64/i.test(e)&&/profile-level-id/i.test(e)})},removeSpecificH264ProfileCodec=function(e,t){e.media.forEach(function(e){if("video"===e.type){var r=e.rtp.filter(function(e){return"H264"===e.codec}).filter(function(r){return e.fmtp.find(function(e){return e.payload===r.payload&&t((null==e?void 0:e.config)||"")})}),n=new Map;e.fmtp.forEach(function(e){/apt=\d+/i.test(e.config)&&n.set(e.payload,e.config.split("=")[1])}),logger$1.info("rtxPayloadMap",Array.from(n.entries())),e.rtp=e.rtp.filter(function(e){return!r.find(function(t){return t.payload===e.payload||"".concat(t.payload)===n.get(e.payload)})}),e.fmtp=e.fmtp.filter(function(e){return!r.find(function(t){return t.payload===e.payload||"".concat(t.payload)===n.get(e.payload)})}),e.payloads=e.payloads.split(" ").map(function(e){return e.trim()}).filter(function(e){return!r.find(function(t){return"".concat(t.payload)===e||"".concat(t.payload)===n.get(parseInt(e))})}).join(" "),e.rtcpFb=e.rtcpFb.filter(function(e){return!r.find(function(t){return parseInt("".concat(t.payload))===parseInt("".concat(e.payload))||"".concat(t.payload)===n.get(parseInt("".concat(e.payload)))})})}})},adjustDownlinkSDPWhenUnsubscribe=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t,r){var n,i,o,a,s,c,u,l,d,p,f,h;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:n=t.pc,i=t.remoteSDP,o=[],a=_createForOfIteratorHelper$8(r);try{for(a.s();!(s=a.n()).done;)c=s.value,u=c.transceiver,l=c.transceivers,u?o.push(u):l&&o.push.apply(o,_toConsumableArray(l))}catch(e){a.e(e)}finally{a.f()}return o.forEach(function(e){e.direction="inactive"}),e.next=1,n.createOffer();case 1:return d=e.sent,e.next=2,n.setLocalDescription(d);case 2:t.localSDP=lib.parse(d.sdp),p=_regeneratorRuntime$1.mark(function e(){var t;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:t=h[f],i.media.find(function(e){return e.mid==t.mid}).direction="inactive";case 1:case"end":return e.stop()}},e)}),f=0,h=o;case 3:if(!(f<h.length)){e.next=5;break}return e.delegateYield(p(),"t0",4);case 4:f++,e.next=3;break;case 5:return t.remoteSDP=i,e.next=6,n.setRemoteDescription({type:"answer",sdp:lib.write(i)});case 6:case"end":return e.stop()}},e)}));return function(t,r){return e.apply(this,arguments)}}(),adjustRemoteSDPWhenFailover=function(e,t){var r=t.media.find(function(e){return"audio"===e.type}),n=t.media.find(function(e){return"video"===e.type});return e.media.forEach(function(t,i){var o=t.mid,a=t.ssrcGroups,s=void 0===a?[]:a,c=t.ssrcs,u=void 0===c?[]:c,l=t.rids,d=void 0===l?[]:l;"audio"===t.type?e.media[i]=_objectSpread$5(_objectSpread$5({},r),{},{mid:o,ssrcs:u}):"video"===t.type&&(e.media[i]=_objectSpread$5(_objectSpread$5({},n),{},{mid:o,ssrcGroups:s,ssrcs:u}),d.length&&(e.media[i].rids=d,e.media[i].simulcast={dir1:"recv",list1:d.map(function(e){return"~".concat(e.id)}).join(";")}))}),e},adjustLocalSDPWhenFailover=function(e,t){var r=t.media;return e.media.forEach(function(e){var t=e.mid,n=e.ssrcGroups,i=void 0===n?[]:n,o=e.ssrcs,a=void 0===o?[]:o,s=e.type,c=r.findIndex(function(e){return e.mid==t&&e.type===s});c>-1&&(r[c]=_objectSpread$5(_objectSpread$5({},r[c]),{},{ssrcGroups:i,ssrcs:a}))}),t},getSsrcInfo=function(e,t){return[{attribute:"msid",value:"".concat(t," v").concat(e),id:e},{attribute:"cname",value:createUuid(),id:e}]},changeRemoteSdpForCreatePc=function(e,t,r){var n=t.direction,i=t.remoteSDP;logger$1.info("origin answer for createpc",t.id,e);var o=lib.parse(e);o.media.forEach(function(e){e.candidates.forEach(function(e){e.generation=0,e["network-cost"]=isPrivateIP(e.ip)?10:1e3})}),r&&(o=adjustRemoteSDPWhenFailover(i,o));var a=o.media.find(function(e){return"video"===e.type});if("uplink"===n&&Environment.isFirefox()&&clientConfig.simulcast&&(a.ext=a.ext.filter(function(e){return!e.uri.includes("rtp-stream-id")})),!a.ssrcs&&"downlink"===n){var s=generateSubSsrc(),c=o.msidSemantic.token;a.ssrcs=getSsrcInfo(s,c)}clientConfig.preferH264CbProfile&&keepH264CbProfileOnly(o),t.remoteSDP=o;var u=lib.write(o);return logger$1.info("final answer for createpc",t.id,u),u},removeTransportCC=function(e){e.media.forEach(function(e){e.ext=e.ext.filter(function(e){return!e.uri.includes("transport-wide-cc")}),e.rtcpFb=e.rtcpFb.filter(function(e){return"transport-cc"!==e.type})})},changeLocalSdpForCreatePc=function(e,t){var r=t.direction,n=lib.parse(e);if(removeHighProfileH264(n),clientConfig.preferH264CbProfile&&keepH264CbProfileOnly(n),clientConfig.disableTransportCC&&"uplink"===r&&removeTransportCC(n),"downlink"===r&&!clientConfig.downlinkForbidHighProfile){var i=[];n.media.find(function(e){return"video"===e.type}).fmtp.forEach(function(e){var t=e.config;t.includes("profile-level-id")&&i.push(t)}),t.subSdpFmtpLines=i}if(Environment.isFirefox()&&(n=removeProfileOfUnsetPacketzationMode(n)),"uplink"===r&&Environment.isFirefox()&&clientConfig.simulcast){var o=n.media.find(function(e){return"video"===e.type});addRidExtForFirefox(o)}return t.localSDP=n,n},adjustOfferWhenFailover=function(e){var t=e.localSDP,r=e.remoteSDP,n=e.sessionManager,i=e.mcuAudioTranceiver,o=e.pc,a=e.idToTransceiverMap,s=e.idToTransceiversMap,c=e.direction,u=t.media.slice(2),l=_toConsumableArray(n.sessions.values());if("downlink"===c){var d=r.media.slice(2),p=l.filter(function(e){return e instanceof Subscription}),f=p.find(function(e){var t;return"admin"===(null===(t=e.stream)||void 0===t||null===(t=t.info)||void 0===t?void 0:t.owner)});f&&!clientConfig.audioSFU&&(a.set(f.id,i),f.addTransceiver(i));var h=[];u.forEach(function(e){var t={direction:e.direction},r=d.find(function(t){return t.type===e.type&&e.mid==t.mid}),n=p.find(function(e){return(null==e?void 0:e.ssrc)===(null==r?void 0:r.ssrcs[0].id)}),i=o.addTransceiver(e.type,t);"recvonly"===e.direction&&("video"===e.type&&n?(a.set(n.stream.id,i),n.addTransceiver(i)):"audio"===e.type&&h.push(i))}),h.length&&f&&(e.mcuAudioTranceivers=h,s.set(f.id,h),f.addTransceivers(h))}else{var g=l.filter(function(e){return e instanceof Publication});u.forEach(function(e){var t={direction:e.direction},r=g.find(function(t){return t.mid==e.mid});if("sendonly"===e.direction&&r){var n=r.tracks[0],i=(null==n?void 0:n.getMediaStreamTrack())||(null==n?void 0:n.trackMediaType);if(n instanceof LocalVideoTrack){var s=getSenderEncodingArrAndResoLevel(n).encodings;t.sendEncodings=s.filter(function(e){return e.activeForBitrateMap}).map(function(e){return{rid:e.rid||void 0,maxBitrate:1e3*e.maxBitrate,maxFramerate:e.maxFramerate,active:e.activeForRealuse,scaleResolutionDownBy:e.scaleResolutionDownBy}})}var c=o.addTransceiver(i,t);a.set(n.getTrackId(),c),r.addTransceiver(c)}else o.addTransceiver(e.type,t)})}},removePayloadTypes=function(e,t){if(e){var r,n=e.fmtp,i=e.payloads,o=e.rtp,a=e.rtcpFb,s=[],c={},u=_createForOfIteratorHelper$8(n);try{for(u.s();!(r=u.n()).done;){var l=r.value,d=l.config,p=l.payload,f=d.split(";");c[p]={};var h,g=_createForOfIteratorHelper$8(f);try{for(g.s();!(h=g.n()).done;){var m=_slicedToArray(h.value.split("="),2),v=m[0],y=m[1];c[p][v]=y}}catch(e){g.e(e)}finally{g.f()}}}catch(e){u.e(e)}finally{u.f()}for(var b in c){var S=c[b];(t(S)||s.includes(+S.apt))&&s.push(parseInt(b))}if(s.length){for(var _=n.length-1;_>=0;_--){var E=n[_].payload;s.includes(E)&&n.splice(_,1)}for(var T=o.length-1;T>=0;T--)s.includes(o[T].payload)&&o.splice(T,1);for(var R=a.length-1;R>=0;R--)s.includes(parseInt("".concat(a[R].payload)))&&a.splice(R,1);e.payloads=i.split(" ").map(Number).filter(function(e){return!s.includes(e)}).join(" ")}}},removeProfileOfUnsetPacketzationMode=function(e){var t=e.media.find(function(e){return"video"===e.type});return removePayloadTypes(t,function(e){return e["profile-level-id"]&&!e["packetization-mode"]}),e};function ownKeys$4(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function _objectSpread$4(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$4(Object(r),!0).forEach(function(t){_defineProperty(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$4(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function _createForOfIteratorHelper$7(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$7(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$7(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$7(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_arrayLikeToArray$7(e,t):void 0}}function _arrayLikeToArray$7(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _callSuper$c(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$c()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$c(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$c=function(){return!!e})()}var logger=getReporter().getLoggerWithPrefix("[publication]"),Publication=function(e){function t(e){var r;_classCallCheck$1(this,t),r=_callSuper$c(this,t),Object.defineProperty(r,"uid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"connection",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"tracks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"rtcSignaling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"transceiver",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"metricsMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"audioStatsMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"videoStatsMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"state",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"mid",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(r,"encodings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"rtcStreamMuted",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"feedbackIndex",{enumerable:!0,configurable:!0,writable:!0,value:-1}),Object.defineProperty(r,"monitor",{enumerable:!0,configurable:!0,writable:!0,value:void 0});var n=e.connection,i=e.uid,o=e.tracks,a=void 0===o?[]:o;return r.tracks=a,r.connection=n,r.rtcSignaling=n.rtcSignaling,r.uid=i,r.reporter=n.reporter,r.logger=r.reporter.getLoggerWithPrefix("[rtp-publication]"),r.state=PubSubStates.Idle,r.videoStatsMap=new Map,r.audioStatsMap=new Map,r.metricsMap=new Map,r.handleTracEvent=r.handleTracEvent.bind(r),r.applyOptions=r.applyOptions.bind(r),a.forEach(function(e){e.on(TRACK_EVENT_NAME,r.handleTracEvent)}),a[0]instanceof LocalVideoTrack&&(r.encodings=getSenderEncodingArrAndResoLevel(a[0]).encodings),r.state=PubSubStates.Processing,r.connection.once("ended",function(){r.clear()}),r}return _inherits$1(t,e),_createClass$1(t,[{key:"stop",value:function(){var e=this;return this.state!==PubSubStates.Processing?Promise.resolve():batchPublishStop([this],{connection:this.connection}).catch(function(t){e.clear(),e.logger.warn("negative ack for unpublish, ".concat(tryJsonStringify(t)))})}},{key:"mute",value:(n=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){var t,r,n;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(this.tracks.length&&this.state===PubSubStates.Processing&&"muted"!==this.rtcStreamMuted){e.next=1;break}return this.logger.info("ignore mute for tracks=".concat(this.tracks.length," state=").concat(this.state," curRtcStreamMuted=").concat(this.rtcStreamMuted)),e.abrupt("return");case 1:return t=this.tracks[0].trackMediaType,this.reporter.trace.localControl(t,!0,this.id),this.rtcStreamMuted="muted",e.prev=2,e.next=3,this.rtcSignaling.streamControl({streamId:this.id,operation:"pause",data:t});case 3:return r=e.sent,e.abrupt("return",r);case 4:e.prev=4,n=e.catch(2),this.logger.error("mute error",this.id,n),this.rtcStreamMuted="unmuted";case 5:case"end":return e.stop()}},e,this,[[2,4]])})),function(){return n.apply(this,arguments)})},{key:"unmute",value:(r=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){var t,r,n;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(this.tracks.length&&this.state===PubSubStates.Processing&&"unmuted"!==this.rtcStreamMuted){e.next=1;break}return this.logger.info("ignore unmute for tracks=".concat(this.tracks.length," state=").concat(this.state," curRtcStreamMuted=").concat(this.rtcStreamMuted)),e.abrupt("return");case 1:return t=this.tracks[0].trackMediaType,this.reporter.trace.localControl(t,!1,this.id),this.rtcStreamMuted="unmuted",e.prev=2,e.next=3,this.rtcSignaling.streamControl({streamId:this.id,operation:"play",data:t});case 3:return r=e.sent,e.abrupt("return",r);case 4:e.prev=4,n=e.catch(2),this.logger.error("unmute error",this.id,n),this.rtcStreamMuted="muted";case 5:case"end":return e.stop()}},e,this,[[2,4]])})),function(){return r.apply(this,arguments)})},{key:"initInner",value:function(e){this.id=e;var t=this.tracks[0],r=this.connection.idToTransceiverMap.get(t.getTrackId());this.addTransceiver(r),"video"===t.trackMediaType&&t.config.mirror&&this.handleMirror(t.config.mirror)}},{key:"handleMirror",value:function(e){return this.rtcSignaling.setStreamProperties({streamId:this.id,propertiesJsonStr:JSON.stringify({mirror:!!e})})}},{key:"handleRepublish",value:function(e){var t=this,r=this.connection,n=this.transceiver,i=e.getMediaStreamTrack().getSettings(),o=i.width,a=i.height,s=getHighestResoLevelNum(o,a);this.rtcSignaling.streamControl({streamId:this.id,operation:"updateResolution",highestResolutionLevel:s});var c=getDownByScales(o,a);r.addTask(_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){var r;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t.logger.info("scales",c),(r=n.sender.getParameters()).encodings.forEach(function(e){e.scaleResolutionDownBy=c[e.rid]}),t.logger.info("handleRepublish setParameters",r),e.abrupt("return",n.sender.setParameters(r).then(function(){console.log(n.sender.getParameters().encodings)}));case 1:case"end":return e.stop()}},e)})))}},{key:"handleTracEvent",value:function(e,t){var r,n=this,i={replace:function(){return n.replaceTrack(t.getMediaStreamTrack())},mute:function(){return n.mute()},unmute:function(){return n.unmute()},republish:function(){clientConfig.republish?n.handleRepublish(t):n.stop().then(function(){n.connection.sessionManager.serviceManager.client.publish([t])})},stop:function(){return n.stop()},optimizationMode:function(){return n.updateOptionzationMode()},mirror:function(){return n.handleMirror(t)}};return null===(r=i[e])||void 0===r?void 0:r.call(i)}},{key:"clear",value:function(){var e=this;this.state!==PubSubStates.End&&(this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.tracks.forEach(function(t){t.off(TRACK_EVENT_NAME,e.handleTracEvent)}),this.tracks=[],this.metricsMap.clear(),this.audioStatsMap.clear(),this.videoStatsMap.clear(),this.state=PubSubStates.End,this.emit("ended"))}},{key:"applyOptions",value:function(e){var t=this,r=e[0],n=r.index,i=r.bitrate;if(this.logger.debug("applyOptions",e),!(n<this.feedbackIndex||this.state!==PubSubStates.Processing)){this.feedbackIndex=n;var o=this.transceiver;this.connection.addTask(function(){return new Promise(function(r){var n,a=0===i,s=!1,c=o.sender.getParameters(),u=e.map(function(e){return e.rid}),l=_createForOfIteratorHelper$7(c.encodings);try{for(l.s();!(n=l.n()).done;){var d,p=n.value,f=_createForOfIteratorHelper$7(e);try{for(f.s();!(d=f.n()).done;){d.value.rid!==p.rid&&p.rid||p.active||a||(p.active=!0,s=!0)}}catch(e){f.e(e)}finally{f.f()}!p.active||u.includes(p.rid)&&!a||(p.active=!1,s=!0)}}catch(e){l.e(e)}finally{l.f()}return t.logger.info("encodings",c.encodings),s&&t.logger.info("applyOptions setParameters",c),o.sender.setParameters(c).then(function(){return adjustUplinkSDPWhenApplyOptions(t).then(r)})})})}}},{key:"updateOptionzationMode",value:function(){var e,t=this,r=this.tracks,n=this.transceiver,i=this.connection;if(r[0]instanceof LocalVideoTrack&&null!=n&&null!==(e=n.sender)&&void 0!==e&&e.setParameters){var o=r[0].optimizationMode;i.addTask(function(){var e=n.sender.getParameters();return e.degradationPreference=optionzationMap[o]||"balanced",t.logger.info("updateOptionzationMode setParameters",e),n.sender.setParameters(e),adjustUplinkSDPWhenApplyOptions(t)})}}},{key:"addTransceiver",value:function(e){this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.metricsMap.clear(),this.audioStatsMap.clear(),this.videoStatsMap.clear(),this.transceiver=e,this.mid||(this.mid=null==e?void 0:e.mid),this.state=PubSubStates.Processing,this.feedbackIndex=-1,this.monitor=new PublishMonitor(this),this.onMonitor()}},{key:"replaceTrack",value:function(e){var t;if(this.transceiver){null===(t=this.transceiver.sender.track)||void 0===t||t.stop();try{this.transceiver.sender.replaceTrack(e)}catch(e){this.logger.error(CONST_DEVELOPER_TODO_LOG_TAG,"sender replaceTrack error",e)}}}},{key:"handleMetrics",value:function(e,t){var r=e.audioMetrics,n=e.videoMetrics;if(r){var i,o=(null===(i=this.metricsMap.get(t))||void 0===i?void 0:i.audioMetrics)||{},a=getDeltaDurationInSeconds(r,o),s=getDelta(r.bytesSent,o.bytesSent),c={codec:this.connection.peerConnectionStats.audioCodec||r.codec,sendBytes:r.bytesSent,audioLevel:Math.max(r.audioLevel,0),sendPackets:r.packetsSent,sendPacketsLost:r.packetsLost,sampleRate:r.sampleRate,channelCount:r.channels,rtt:this.connection.peerConnectionStats.roundTripTime||r.roundTripTime,timestamp:r.timestamp,sendBitrate:8*s/a};this.audioStatsMap.set(t,c)}else if(n){var u,l,d=((null===(u=this.transceiver)||void 0===u||null===(u=u.sender)||void 0===u?void 0:u.getParameters())||{}).encodings,p=void 0===d?[]:d,f=(null===(l=this.metricsMap.get(t))||void 0===l?void 0:l.videoMetrics)||{},h=getDeltaDurationInSeconds(n,f),g=getDelta(n.totalBytesSent,f.totalBytesSent),m={codec:this.connection.peerConnectionStats.videoCodec||n.codec,sendFrameRate:Math.round(n.sendFramesPerSecond),captureFrameRate:n.captureFramesPerSecond,encodeFrameRate:n.encodeFramesPerSecond,qpSum:n.totalQpSum||0,targetBitrate:n.targetBitrate,encodeLayers:p.length,sendLayers:p.filter(function(e){return e.active}).length,outgingBitrate:n.availableOutgoingBitrate,sendResolution:{width:n.maxSendFrameWidth,height:n.maxSendFrameHeight},captureResolution:{width:n.captureFrameWidth,height:n.captureFrameHeight},sendBytes:n.totalBytesSent,sendPackets:n.totalPacketsSent,sendPacketsLost:n.totalPacketsLost,timestamp:n.timestamp,rtt:this.connection.peerConnectionStats.roundTripTime||n.roundTripTime,sendBitrate:8*g/h};this.videoStatsMap.set(t,m)}this.metricsMap.set(t,e)}},{key:"getMetrics",value:function(e){var t,r=this;return null===(t=this.connection)||void 0===t?void 0:t.getStats().then(function(){var t;return null===(t=r.monitor)||void 0===t?void 0:t.getStats().then(function(t){return r.handleMetrics(t,e)})})}},{key:"onMonitor",value:function(){var e=this;this.monitor.on("audio-send-stream",function(t){e.reporter.metric.audioSendStream(_objectSpread$4({sessionId:e.id},t))}),this.monitor.on("video-send-stream",function(t){e.reporter.metric.videoSendStream(_objectSpread$4({sessionId:e.id},t))}),this.monitor.on("bwe",function(t){e.reporter.metric.bwe(_objectSpread$4({sessionId:e.id},t))})}}]);var r,n}(EventEmitter),updatePcAndBuildPubMediaSigInfo=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t,r){var n,i,o,a,s,c=arguments;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return n=c.length>2&&void 0!==c[2]?c[2]:["common"],i={},e.next=1,addTransceiversAndSetSdpToPC(r,t);case 1:return o=e.sent,a=o.localSDP,s=o.stream,t.forEach(function(e){var t=e.getTrackId(),o=a.media.find(function(e){return e.mid==r.idToTransceiverMap.get(t).mid});if("audio"===e.trackMediaType)i.audio=[{source:"mic",autoMix:n,trackId:t,msid:s.id,uplinkSsrcGroup:[{ssrc:Number(o.ssrcs[0].id)}]}];else if(e instanceof LocalVideoTrack){var c;i.video=i.video||[];var u=o.ssrcGroups,l=void 0===u?[]:u,d=getSenderEncodingArrAndResoLevel(e),p=d.encodings,f=d.resolutionLevel;p.length>1&&(l=p.map(function(){return{semantics:"FID",ssrcs:"".concat(generateSubSsrc()," ").concat(generateSubSsrc())}}));var h=l.filter(function(e){return"FID"===e.semantics}).map(function(e){return{ssrc:Number(e.ssrcs.split(" ")[0]),rtxSsrc:Number(e.ssrcs.split(" ")[1])}}),g=p[p.length-1],m={trackId:e.getTrackId(),forwardOnly:e.source===exports.VideoSourceInfo.SCREENCAST,msid:s.id,mid:"".concat(o.mid),highestResolutionLevel:f,uplinkSsrcGroup:h,source:e.source||exports.VideoSourceInfo.CAMERA,streamParameters:{ssrc:null==h||null===(c=h[0])||void 0===c?void 0:c.ssrc,bitrate:"".concat(g.maxBitrate),resolution:{width:g.targetWidth,height:g.targetHeight},framerate:g.maxFramerate},ssrcParameters:h.map(function(e,t){var r;return{ssrc:e.ssrc,active:p[t].activeForBitrateMap,tlayer:1,bitrate:p[t].maxBitrate,rid:(null===(r=p[t])||void 0===r?void 0:r.rid)||void 0,maxBitrate:p[t].maxBitrate,minBitrate:p[t].minBitrate,framerate:p[t].maxFramerate,resolution:{width:p[t].targetWidth,height:p[t].targetHeight}}})};i.video.push(m)}}),e.abrupt("return",i);case 2:case"end":return e.stop()}},e)}));return function(t,r){return e.apply(this,arguments)}}(),execBatchPublish=function(e){var t=e.tracks,r=e.connection,n=e.labels,i=e.existedPublications,o=void 0===i?[]:i,a=e.mixedLocalAudioTrack,s={videoPubResultArr:[]},c=[];t.forEach(function(t){var r;if("audio"!==t.trackMediaType||t.source!==exports.AudioSourceInfo.MIC&&t.source!==exports.AudioSourceInfo.SCREENCAST)s.videoPubResultArr.push({publication:new Publication(_objectSpread$4(_objectSpread$4({},e),{},{tracks:[t]})),track:t});else{var n=o.find(function(e){var t,r,n;return"audio"===(null===(t=e.tracks)||void 0===t?void 0:t[0].trackMediaType)&&((null===(r=e.tracks)||void 0===r?void 0:r[0].source)===exports.AudioSourceInfo.MIC||(null===(n=e.tracks)||void 0===n?void 0:n[0].source)===exports.AudioSourceInfo.SCREENCAST)}),i=c.find(function(e){var t,r,n;return"audio"===(null===(t=e.tracks)||void 0===t?void 0:t[0].trackMediaType)&&((null===(r=e.tracks)||void 0===r?void 0:r[0].source)===exports.AudioSourceInfo.MIC||(null===(n=e.tracks)||void 0===n?void 0:n[0].source)===exports.AudioSourceInfo.SCREENCAST)});n?(n.tracks.push(t),r=n):i?(i.tracks.push(t),r=i):r=new Publication(_objectSpread$4(_objectSpread$4({},e),{},{tracks:[a]})),s.audioPubResult={publication:r,track:t}}});var u=t.filter(function(e){return"audio"===e.trackMediaType&&(e.source===exports.AudioSourceInfo.MIC||e.source===exports.AudioSourceInfo.SCREENCAST)});u.forEach(function(e){(null==e?void 0:e.source)===exports.AudioSourceInfo.MIC?a.setMicAudioTrack(e):a.setScreenAudioTrack(e)});var l=[],d=t.filter(function(e){return!("audio"===e.trackMediaType&&(e.source===exports.AudioSourceInfo.MIC||e.source===exports.AudioSourceInfo.SCREENCAST))});if(l.push.apply(l,_toConsumableArray(d)),u.length&&(null==a||a.updateMixedAudioTrackToPub(),a.isPublished()||l.push(a)),l.length){var p,f=new Promise(function(e,t){p=function(){var i=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function i(){var o,c;return _regeneratorRuntime$1.wrap(function(i){for(;;)switch(i.prev=i.next){case 0:return i.next=1,updatePcAndBuildPubMediaSigInfo(l,r,n);case 1:return o=i.sent,c={connectionId:r.id,media:o,simulcast:simulcastEnabledFinally(l.find(function(e){return e.source===exports.VideoSourceInfo.CAMERA})),simulcastVersion:"1.0",clientType:"web",supportTemporalLayer:!1,type:"webrtc"},i.abrupt("return",r.rtcSignaling.batchPublish(c).then(function(){var t=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function t(r){var n,i,o,c,l,d;return _regeneratorRuntime$1.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(n=r.detailStatus,"ok"===(i=r.globalStatus)){t.next=1;break}return s.videoPubResultArr.forEach(function(e){e.error=parsePublishError(e.track,i)}),s.audioPubResult&&(s.audioPubResult.error=parsePublishError(s.audioPubResult.track,i)),t.abrupt("return",e(s));case 1:o=_createForOfIteratorHelper$7(n),t.prev=2,l=_regeneratorRuntime$1.mark(function e(){var t,r,n,i,o,l,d;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:t=c.value,r=t.id,n=t.origin,i=t.msg,a.getTrackId()===n.id?s.audioPubResult&&(o=s.audioPubResult.publication,"ok"===i&&o?(o.initInner(r),a.setPublication(o),u.forEach(function(e){(null==e?void 0:e.source)===exports.AudioSourceInfo.MIC&&e.muted&&e.emit(TRACK_EVENT_NAME,"mute")})):"ok"!==i&&(s.audioPubResult.error=parsePublishError(s.audioPubResult.track,i))):(l=s.videoPubResultArr.find(function(e){return e.track.getTrackId()===n.id}),d=(l||{}).publication,"ok"===i&&d?d.initInner(r):"ok"!==i&&(l.error=parsePublishError(l.track,i)));case 1:case"end":return e.stop()}},e)}),o.s();case 3:if((c=o.n()).done){t.next=5;break}return t.delegateYield(l(),"t0",4);case 4:t.next=3;break;case 5:t.next=7;break;case 6:t.prev=6,d=t.catch(2),o.e(d);case 7:return t.prev=7,o.f(),t.finish(7);case 8:e(s);case 9:case"end":return t.stop()}},t,null,[[2,6,7,8]])}));return function(e){return t.apply(this,arguments)}}()).catch(function(e){logger.info("batchPublishStart error",e),t(e)}));case 2:case"end":return i.stop()}},i)}));return function(){return i.apply(this,arguments)}}()});return r.addTask(p),f}return Promise.resolve({videoPubResultArr:[],audioPubResult:void 0})},batchPublishStop=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t,r){var n,i;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return i=new Promise(function(e,i){n=function(){var n=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function n(){var o,a;return _regeneratorRuntime$1.wrap(function(n){for(;;)switch(n.prev=n.next){case 0:return o=t.filter(function(e){var t;return"audio"===(null===(t=e.tracks)||void 0===t||null===(t=t[0])||void 0===t?void 0:t.trackMediaType)}).map(function(e){return e.id}),a=t.filter(function(e){var t;return"video"===(null===(t=e.tracks)||void 0===t||null===(t=t[0])||void 0===t?void 0:t.trackMediaType)}).map(function(e){return e.id}),n.next=1,adjustUplinkSDPWhenUnpublish(r.connection,t);case 1:r.connection.rtcSignaling.batchUnPublish({connectionId:r.connection.id,audio:o,video:a}).then(function(){t.forEach(function(e){e.clear()}),e(void 0)}).catch(i);case 2:case"end":return n.stop()}},n)}));return function(){return n.apply(this,arguments)}}()}),r.connection.addTask(n),e.abrupt("return",i);case 1:case"end":return e.stop()}},e)}));return function(t,r){return e.apply(this,arguments)}}();function _callSuper$b(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$b()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$b(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$b=function(){return!!e})()}var initPeerConnectionMetrics={audioCodec:"",videoCodec:"",roundTripTime:-1,availableOutgoingBitrate:-1},PeerConnectionMonitor=function(e){function t(e){var r;return _classCallCheck$1(this,t),r=_callSuper$b(this,t),Object.defineProperty(r,"connectionMetrics",{enumerable:!0,configurable:!0,writable:!0,value:Object.assign({},initPeerConnectionMetrics)}),Object.defineProperty(r,"pc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.pc=e.pc,r}return _inherits$1(t,e),_createClass$1(t,[{key:"extractMetrics",value:function(e){var t=Object.assign({},this.connectionMetrics),r="";return e.forEach(function(e){var n;if(!e.isRemote)if(/local-candidate/i.test(e.type)&&e.id===r)Environment.networkType=(null!==(n=e.networkType)&&void 0!==n?n:Environment.networkType).replace("vpn","unknown");else if(/candidate-pair/i.test(e.type)&&"succeeded"===e.state)r=e.localCandidateId,Environment.isFirefox()||(t.roundTripTime=1e3*(e.currentRoundTripTime||e.totalRoundTripTime/e.responsesReceived)),void 0!==e.availableOutgoingBitrate&&(t.availableOutgoingBitrate=e.availableOutgoingBitrate);else if(/codec/i.test(e.type)){var i,o;null!==(i=e.mimeType)&&void 0!==i&&i.includes("audio")?t.audioCodec=e.mimeType.replace("audio/",""):null!==(o=e.mimeType)&&void 0!==o&&o.includes("video")&&(t.videoCodec=e.mimeType.replace("video/",""),t.sdpFmtpLine=e.sdpFmtpLine)}}),this.connectionMetrics=Object.assign({},t),this.connectionMetrics}},{key:"makeReport",value:function(){var e=this;this.getStats().then(function(t){e.emit("metrics",t)})}},{key:"getStats",value:function(){var e=this;if(!this.pc)return Promise.resolve({});if(!this.pc.getStats)throw new DingRTCError(ErrorCode.BrowserNotSupported,"getStats is not supported");return this.pc.getStats(null).then(function(t){return e.extractMetrics(t)})}}])}(Monitor);function _createForOfIteratorHelper$6(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$6(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$6(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$6(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_arrayLikeToArray$6(e,t):void 0}}function _arrayLikeToArray$6(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _callSuper$a(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$a()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$a(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$a=function(){return!!e})()}var PeerConnection=function(e){function t(e){var r,n,i;_classCallCheck$1(this,t),r=_callSuper$a(this,t),Object.defineProperty(r,"pc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"rtcSignaling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"state",{enumerable:!0,configurable:!0,writable:!0,value:PeerConnectionState.New}),Object.defineProperty(r,"processingExchangeSdp",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"monitor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"peerConnectionTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"createPeerConnectionPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"peerConnectionStats",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"createPeerConnectionTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"mcuAudioStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"idToTransceiverMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"mcuAudioTranceiver",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"idToTransceiversMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"mcuAudioTranceivers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"localSDP",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"remoteSDP",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"subSdpFmtpLines",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"sessionManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"prevId",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(r,"offerSDP",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"clientFailoverTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"audioSfuSsrcs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"enquenTask",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"direction",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"startSinglePC",{enumerable:!0,configurable:!0,writable:!0,value:(n=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){var t,n=arguments;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t=n.length>0&&void 0!==n[0]&&n[0],"uplink"===r.direction?(r.pc.addTransceiver("audio",{direction:"sendonly"}),r.pc.addTransceiver("video",{direction:"sendonly"})):(r.mcuAudioStream=null,r.mcuAudioTranceiver=r.pc.addTransceiver("audio",{direction:"recvonly"}),r.pc.addTransceiver("video",{direction:"recvonly"})),t&&adjustOfferWhenFailover(r),e.next=1,r.exchangeSdpForCreatePc(t);case 1:r.state=PeerConnectionState.Idle,r.enquenTask.start();case 2:case"end":return e.stop()}},e)})),function(){return n.apply(this,arguments)})}),Object.defineProperty(r,"onIceGatheringStateChange",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t=e.target.iceGatheringState;r.logger.info("connectionId:".concat(r.id," ice gathering state: ").concat(t))}}),Object.defineProperty(r,"exchangeSdpForCreatePc",{enumerable:!0,configurable:!0,writable:!0,value:(i=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){var t,n,i,o,a,s,c,u,l,d=arguments;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t=d.length>0&&void 0!==d[0]&&d[0],r.processingExchangeSdp=!0,e.prev=1,e.next=2,r.pc.createOffer();case 2:return n=e.sent,r.logger.info("connectionId:".concat(r.id," origin offer"),n),t&&(n.sdp=lib.write(adjustLocalSDPWhenFailover(r.localSDP,lib.parse(n.sdp)))),i=changeLocalSdpForCreatePc(n.sdp,r),r.offerSDP=i,n={type:"offer",sdp:lib.write(i)},e.next=3,r.pc.setLocalDescription(n);case 3:return r.logger.info("connectionId:".concat(r.id," set local sdp success")),o={direction:"downlink"!==r.direction?"in":"out",sdpOffer:n.sdp,connectionId:r.id,isFailover:t,optionsJsonStr:JSON.stringify({supportCVO:1})},t&&((a=lib.parse(n.sdp)).media=a.media.slice(0,2),a.groups=[{mids:"0 1",type:"BUNDLE"}],o.sdpOffer=lib.write(a)),s=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){var t,n,i,a;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(e.prev=0,"connected"===(null===(t=r.sessionManager)||void 0===t||null===(t=t.serviceManager)||void 0===t||null===(t=t.client)||void 0===t?void 0:t.connectionState)){e.next=1;break}throw new Error("signaling disconnected");case 1:if(o.isFailover||!r.prevId){e.next=3;break}return e.next=2,r.stopSinglePC(!0);case 2:r.id="".concat(r.direction,"_").concat(createUuid()),o.connectionId=r.id;case 3:return r.prevId=r.id,e.next=4,r.rtcSignaling.createPeerConnection(o);case 4:return n=e.sent,i=n.sdpAnswer,r.logger.info("connectionId:".concat(r.id," receive answer success")),e.abrupt("return",i);case 5:throw e.prev=5,a=e.catch(0),r.logger.error("connectionId:".concat(r.id," signal createpc failed: ").concat(a)),a;case 6:case"end":return e.stop()}},e,null,[[0,5]])}));return function(){return e.apply(this,arguments)}}(),e.next=4,multiTryExecute({fn:s,times:3,interval:2e3});case 4:return c=e.sent,u=changeRemoteSdpForCreatePc(c,r,t),e.next=5,r.pc.setRemoteDescription({sdp:u,type:"answer"});case 5:e.next=7;break;case 6:return e.prev=6,l=e.catch(1),r.logger.error("connectionId:".concat(r.id," Failed to exchangeSDP. Message: ").concat(l.message)),r.fireEndedEvent(),e.abrupt("return",Promise.reject(l));case 7:return e.prev=7,r.processingExchangeSdp=!1,e.finish(7);case 8:case"end":return e.stop()}},e,null,[[1,6,7,8]])})),function(){return i.apply(this,arguments)})}),r.pc=null;var o=e.direction,a=e.sessionManager;return r.rtcSignaling=a.serviceManager.rtcSignaling,r.sessionManager=a,r.reporter=a.reporter,r.logger=r.reporter.getLoggerWithPrefix("[rtc-peerconn]"),r.enquenTask=taskQueue(),r.subSdpFmtpLines=[],r.direction=o,r.idToTransceiverMap=new Map,r.idToTransceiversMap=new Map,r.createPeerConnection(),r.id="".concat(r.direction,"_").concat(createUuid()),r}return _inherits$1(t,e),_createClass$1(t,[{key:"stopSinglePC",value:function(){return arguments.length>0&&void 0!==arguments[0]&&arguments[0]||this.emit("ended"),this.rtcSignaling.closePeerConnection({connectionId:this.id,direction:"downlink"===this.direction?"out":"in"})}},{key:"closePeerConnection",value:function(){this.pc&&(this.logger.info("connectionId:".concat(this.id," clear RTC PeerConnection.")),this.detachEvents(),"closed"!==this.pc.signalingState&&this.pc.close(),this.pc=null)}},{key:"onTrack",value:function(e){var t=e.track,r=e.streams;"audio"===t.kind?clientConfig.audioSFU?this.emit("track",t,r[0]):this.mcuAudioStream=new MediaStream([t]):this.emit("track",t)}},{key:"fireEndedEvent",value:function(){this.state!==PeerConnectionState.Ended&&(this.state=PeerConnectionState.Ended,this.emit("ended"))}},{key:"onIceConnectionStateChange",value:function(){var e=this.pc.iceConnectionState;this.logger.info("connectionId:".concat(this.id," ICE connection state changed to ").concat(e))}},{key:"onIceCandidate",value:function(e){var t=candidateToPlainObj(null==e?void 0:e.candidate);this.logger.info("connectionId:".concat(this.id," onIceCandidate"),t)}},{key:"clearPcForReoffer",value:(r=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){var t;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(this.state!==PeerConnectionState.New){e.next=1;break}return e.abrupt("return",Promise.reject());case 1:return this.logger.info("connectionId:".concat(this.id,": start client reoffer")),e.prev=2,e.next=3,this.stopSinglePC(!0);case 3:this.removeAllListeners(),e.next=5;break;case 4:e.prev=4,t=e.catch(2),this.logger.info("connectionId:".concat(this.id," client reoffer close failed ").concat(tryJsonStringify(t)));case 5:this.closePeerConnection();case 6:case"end":return e.stop()}},e,this,[[2,4]])})),function(){return r.apply(this,arguments)})},{key:"addTask",value:function(e){this.enquenTask.add(e)}},{key:"onConnectionStateChange",value:function(){var e=this,t=this.pc.connectionState;this.reporter.trace.connectionsEvent(this.id,t),this.logger.info("connectionId:".concat(this.id," connection state changed to ").concat(t)),"failed"===t||"closed"===t?(this.clientFailoverTimer&&removeTimer(this.clientFailoverTimer),this.clientFailoverTimer=addTimer(function(){e.state!==PeerConnectionState.New&&(e.logger.info("connectionId:".concat(e.id,": emit reoffer")),e.emit("reoffer"))},SIGNAL_CALL_TIMEOUT)):"connected"===t&&(this.clientFailoverTimer&&(removeTimer(this.clientFailoverTimer),this.clientFailoverTimer=null),this.createPeerConnectionTimer&&(removeTimer(this.createPeerConnectionTimer),this.createPeerConnectionTimer=null))}},{key:"getPeerConnectionConfig",value:function(){var e=this.sessionManager.serviceManager.iceConfig,t=e.username,r=e.password,n=e.port,i=e.iceServerList,o={bundlePolicy:"max-bundle",iceTransportPolicy:"all",sdpSemantics:"unified-plan"};if(i.length){var a,s=[],c=_createForOfIteratorHelper$6(i);try{for(c.s();!(a=c.n()).done;){var u=a.value;s.push("turn:".concat(u,":").concat(n,"?transport=udp"),"turn:".concat(u,":").concat(n,"?transport=tcp"))}}catch(e){c.e(e)}finally{c.f()}Environment.isFirefox()&&s.splice(4,2),o.iceServers=[{urls:s,username:t,credential:r}]}return this.logger.info("PeerConnectionConfig",o),o}},{key:"createPeerConnection",value:function(){var e=this;this.pc?this.logger.warn("connectionId:".concat(this.id," A PeerConnection was created. Cannot create again for the same PeerConnectionChannel.")):(this.pc=new RTCPeerConnection(this.getPeerConnectionConfig()),this.attachEvents(),this.createPeerConnectionTimer=addTimer(function(){var t;"connected"===(null===(t=e.pc)||void 0===t?void 0:t.connectionState)||e.processingExchangeSdp||(e.logger.info("connectionId:".concat(e.id,": emit reoffer")),e.emit("reoffer"))},clientConfig.connectPcTimeoutMs))}},{key:"attachEvents",value:function(){var e=this;this.pc&&(this.pc.ontrack=function(t){e.onTrack(t)},this.pc.oniceconnectionstatechange=function(){e.onIceConnectionStateChange()},this.pc.onicecandidate=function(t){e.onIceCandidate(t)},this.pc.onconnectionstatechange=function(){e.onConnectionStateChange()},this.pc.onicegatheringstatechange=function(t){e.onIceGatheringStateChange(t)},this.monitor=new PeerConnectionMonitor(this),this.monitor.on("metrics",function(t){e.peerConnectionStats=t}))}},{key:"getStats",value:function(){var e,t,r=this;return this.monitor?null===(e=this.monitor)||void 0===e||null===(t=e.getStats)||void 0===t?void 0:t.call(e).then(function(e){r.peerConnectionStats=e}):Promise.resolve()}},{key:"detachEvents",value:function(){this.createPeerConnectionTimer&&removeTimer(this.createPeerConnectionTimer),this.clientFailoverTimer&&removeTimer(this.clientFailoverTimer),this.pc&&(this.pc.ontrack=null,this.pc.oniceconnectionstatechange=null,this.pc.onconnectionstatechange=null,this.pc.onicegatheringstatechange=null,this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null)}},{key:"reoffer",value:function(){return this.state===PeerConnectionState.New?Promise.reject():(this.logger.info("connectionId:".concat(this.id," start reoffer")),this.closePeerConnection(),this.idToTransceiverMap=new Map,this.idToTransceiversMap=new Map,this.createPeerConnection(),this.state=PeerConnectionState.New,this.startSinglePC(!0))}},{key:"handleHighProfileFallback",value:function(){clientConfig.downlinkForbidHighProfile=!0,this.logger.info("connectionId:".concat(this.id," start reoffer for disable highProfile")),this.emit("reoffer")}},{key:"handleVideoSubStucked",value:function(e){this.logger.info("connectionId".concat(this.id,": start reoffer for sub:").concat(e.id," video stucked")),this.idToTransceiverMap.delete(e.stream.id),this.sessionManager.handleStuckResubscribe([e])}}]);var r}(EventEmitter);function _callSuper$9(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$9()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$9(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$9=function(){return!!e})()}var MixedLocalAudioTrack=function(e){function t(e){var r;return _classCallCheck$1(this,t),r=_callSuper$9(this,t),Object.defineProperty(r,"_micAudioTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"_screenAudioTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"mixedAudioTrackResult",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(r,"publication",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"serviceManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"_trackId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"trackMediaType",{enumerable:!0,configurable:!0,writable:!0,value:"audio"}),Object.defineProperty(r,"audioContext",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"selfMicMutedProperty",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"isPublished",{enumerable:!0,configurable:!0,writable:!0,value:function(){return!!r.publication}}),Object.defineProperty(r,"setPublication",{enumerable:!0,configurable:!0,writable:!0,value:function(e){r.logger.info("setPublication",null==e?void 0:e.id),r.publication=e}}),Object.defineProperty(r,"getPublication",{enumerable:!0,configurable:!0,writable:!0,value:function(){return r.publication}}),Object.defineProperty(r,"micTrackEventHandler",{enumerable:!0,configurable:!0,writable:!0,value:r._audioTrackInnerEventHandler.bind(r,exports.AudioSourceInfo.MIC)}),Object.defineProperty(r,"screenAudioTrackEventHandler",{enumerable:!0,configurable:!0,writable:!0,value:r._audioTrackInnerEventHandler.bind(r,exports.AudioSourceInfo.SCREENCAST)}),Object.defineProperty(r,"updateMixedAudioTrackToPub",{enumerable:!0,configurable:!0,writable:!0,value:function(){var e,t,n,i,o,a,s;r.logger.info("updateMixTrack",null===(e=r._micAudioTrack)||void 0===e?void 0:e.getTrackId(),null===(t=r._screenAudioTrack)||void 0===t?void 0:t.getTrackId()),null===(n=r.mixedAudioTrackResult)||void 0===n||null===(n=n.mixedTrack)||void 0===n||n.stop(),r.mixedAudioTrackResult=r.mixAudioTracks(null===(i=r._micAudioTrack)||void 0===i?void 0:i.getMediaStreamTrack(),null===(o=r._screenAudioTrack)||void 0===o?void 0:o.getMediaStreamTrack()),null===(a=r.publication)||void 0===a||a.replaceTrack(null===(s=r.mixedAudioTrackResult)||void 0===s?void 0:s.mixedTrack)}}),Object.defineProperty(r,"clear",{enumerable:!0,configurable:!0,writable:!0,value:function(){var e;r.logger.info("clear"),null===(e=r.mixedAudioTrackResult)||void 0===e||null===(e=e.mixedTrack)||void 0===e||e.stop(),r._micAudioTrack=null,r._screenAudioTrack=null,r.publication=void 0}}),Object.defineProperty(r,"getMediaStreamTrack",{enumerable:!0,configurable:!0,writable:!0,value:function(){var e;return(null===(e=r.mixedAudioTrackResult)||void 0===e?void 0:e.mixedTrack)||null}}),r.logger=e.reporter.getLoggerWithPrefix("[rtc-mixedAudioTrack]"),r.serviceManager=e,r._trackId="audio_".concat(createUuid(6)),r}return _inherits$1(t,e),_createClass$1(t,[{key:"getTrackId",value:function(){return this._trackId}},{key:"getScreenAudioTrack",value:function(){return this._screenAudioTrack}},{key:"setScreenAudioTrack",value:function(e){var t,r,n;(this.logger.info("setScreenAudioTrack",null==e?void 0:e.getTrackId()),null===(t=this._screenAudioTrack)||void 0===t||t.off(TRACK_EVENT_NAME,this.screenAudioTrackEventHandler),this._screenAudioTrack=e,null===(r=this._screenAudioTrack)||void 0===r||r.on(TRACK_EVENT_NAME,this.screenAudioTrackEventHandler),e)?e.muted||(this.notifyScreenAudioEnabled(!0),null===(n=this.publication)||void 0===n||n.unmute()):this.notifyScreenAudioEnabled(!1)}},{key:"getMicAudioTrack",value:function(){return this._micAudioTrack}},{key:"setMicAudioTrack",value:function(e){var t,r;this.logger.info("setMicAudioTrack",null==e?void 0:e.getTrackId()),null===(t=this._micAudioTrack)||void 0===t||t.off(TRACK_EVENT_NAME,this.micTrackEventHandler),this._micAudioTrack=e,null===(r=this._micAudioTrack)||void 0===r||r.on(TRACK_EVENT_NAME,this.micTrackEventHandler),this._micAudioTrack&&(this._micAudioTrack.muted&&!this.selfMicMutedProperty?(this.setSelfMicMutedProperty(!0),this.notifyMicDeviceMuted(!0)):!this._micAudioTrack.muted&&this.selfMicMutedProperty&&(this.setSelfMicMutedProperty(!1),this.notifyMicDeviceMuted(!1)))}},{key:"_audioTrackInnerEventHandler",value:function(e,t){if("localMixedAudioReplaceTrack"===t)this.updateMixedAudioTrackToPub();else if("stop"===t){var r,n,i;if(e===exports.AudioSourceInfo.MIC?this.setMicAudioTrack(null):this.setScreenAudioTrack(null),this.updateMixedAudioTrackToPub(),null===(r=this.mixedAudioTrackResult)||void 0===r||!r.mixedTrack)if(this.logger.warn("mixedAudioTrackResult is null, stop pub audio, pubid=",null===(n=this.publication)||void 0===n?void 0:n.id),this.publication)null===(i=this.publication)||void 0===i||i.stop(),this.publication=null}else if("mute"===t){e===exports.AudioSourceInfo.SCREENCAST?this.notifyScreenAudioEnabled(!1):this.selfMicMutedProperty||(this.setSelfMicMutedProperty(!0),this.notifyMicDeviceMuted(!0));var o=e===exports.AudioSourceInfo.MIC?this._screenAudioTrack:this._micAudioTrack;o&&!o.muted&&o.enabled||this.publication.mute()}else"unmute"===t?(e===exports.AudioSourceInfo.SCREENCAST?this.notifyScreenAudioEnabled(!0):this.selfMicMutedProperty&&(this.setSelfMicMutedProperty(!1),this.notifyMicDeviceMuted(!1)),this.publication.unmute()):this.logger.info("unhandled action",t)}},{key:"setSelfMicMutedProperty",value:function(e){this.selfMicMutedProperty=e}},{key:"notifyMicDeviceMuted",value:function(e){return this.serviceManager.rtcUserManager.notifyParticipantProperties(JSON.stringify({mute_audio_record:e?1:0}))}},{key:"notifyScreenAudioEnabled",value:function(e){return this.serviceManager.rtcUserManager.notifyParticipantProperties(JSON.stringify({enable_sys_audio:e?1:0}))}},{key:"mixAudioTracks",value:function(e,t){var r;if(!e&&!t)return null;var n=getAudioContext();this.audioContext=n;var i=n.createMediaStreamDestination();return e&&n.createMediaStreamSource(new MediaStream([e])).connect(i),t&&n.createMediaStreamSource(new MediaStream([t])).connect(i),{mixedTrack:null===(r=i.stream.getAudioTracks())||void 0===r?void 0:r[0],isOriginTrack:!1}}}])}(EventEmitter);function ownKeys$3(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function _objectSpread$3(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$3(Object(r),!0).forEach(function(t){_defineProperty(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$3(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function _createForOfIteratorHelper$5(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$5(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$5(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$5(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_arrayLikeToArray$5(e,t):void 0}}function _arrayLikeToArray$5(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _callSuper$8(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$8()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$8(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$8=function(){return!!e})()}var media_reconnect_duration_ms=45e3,media_reconnect_single_round_min_duration_ms=2e3,SessionManager=function(e){function t(e,r){var n,i,o,a;return _classCallCheck$1(this,t),n=_callSuper$8(this,t),Object.defineProperty(n,"client",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(n,"sessions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"networkQualityInterval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"lastChannelNetworkQuality",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"uplink",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"downlink",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"streamIdToSessionId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"serviceManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"mixedLocalAudioTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"republishPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"resubscribePromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"handleRepublish",{enumerable:!0,configurable:!0,writable:!0,value:(i=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:n.republishPromise=n._handleRepub(),n.republishPromise.finally(function(){n.republishPromise=null});case 1:case"end":return e.stop()}},e)})),function(){return i.apply(this,arguments)})}),Object.defineProperty(n,"handleResubscribe",{enumerable:!0,configurable:!0,writable:!0,value:(o=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){var t,r=arguments;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:t=r.length>0&&void 0!==r[0]&&r[0],n.resubscribePromise=n._handleResubscribe(t),n.resubscribePromise.finally(function(){n.resubscribePromise=null});case 1:case"end":return e.stop()}},e)})),function(){return o.apply(this,arguments)})}),Object.defineProperty(n,"_handleResubscribe",{enumerable:!0,configurable:!0,writable:!0,value:(a=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){var t,r,i,o,a,s,c,u,l,d,p,f,h,g,m,v,y,b,S,_,E,T,R,C,k,P,w,O,I,A,M,N,D,x,L,j,$,U,F,V,G=arguments;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:r=G.length>0&&void 0!==G[0]&&G[0],n.logger.info("handle resub fromServer=",r),i=r?"server":"client",o=[],a=_createForOfIteratorHelper$5(n.sessions.values());try{for(a.s();!(s=a.n()).done;)(c=s.value)instanceof Subscription&&c.state===PubSubStates.Processing&&(u=null,c.stream.media.video?(l=n.serviceManager.rtcUserManager.users.get(c.uid),u="camera"===c.stream.media.video.source?null==l?void 0:l.videoTrack:null==l?void 0:l.auxiliaryTrack):c.stream.media.audio?u=n.serviceManager.remoteAudioTrack:n.logger.error("unknown media type for resub",c.stream),o.push({stream:c.stream,uid:c.uid,targetMediaType:c.targetMediaType,resolutionInfo:c.userConfigResolution,session:c,track:u}))}catch(e){a.e(e)}finally{a.f()}if(d=o.map(function(e){return e.uid}).join(),o.length){n.logger.info("resubscribe start ".concat(d)),n.client.emit("media-reconnect-start",n.client.userId),p=_createForOfIteratorHelper$5(o);try{for(p.s();!(f=p.n()).done;)m=f.value,n.logger.info("emitted sub-media-reconnect-started",null===(h=m.track)||void 0===h?void 0:h.getTrackId()),n.client.emit("sub-media-reconnect-started",null===(g=m.track)||void 0===g?void 0:g.getTrackId())}catch(e){p.e(e)}finally{p.f()}}v=null===(t=n.downlink)||void 0===t?void 0:t.id,y=Date.now(),b=y+media_reconnect_duration_ms,S=!1,_=n.serviceManager.rtcUserManager.currentSelfPid,E=0;case 1:if(!(E<23&&Date.now()<=b)){e.next=10;break}if(!((T=Date.now())<y+E*media_reconnect_single_round_min_duration_ms)){e.next=2;break}return e.next=2,asyncDelayMs(y+E*media_reconnect_single_round_min_duration_ms-T);case 2:if(n.logger.debug("resub round=".concat(E,", channelconnect=").concat(n.serviceManager.internalChannel.connectionState)),"connected"===n.serviceManager.internalChannel.connectionState){e.next=3;break}return e.abrupt("continue",9);case 3:return e.prev=3,n.reporter.trace.connectionsEvent(v,"".concat(i,"ReofferStart")),e.next=4,null===(R=n.downlink)||void 0===R?void 0:R.clearPcForReoffer();case 4:if(n.downlink=null,!o.length){e.next=7;break}return e.next=5,n.batchSubscribe(o);case 5:if(C=e.sent,n.serviceManager.rtcUserManager.currentSelfPid===_){e.next=6;break}return n.logger.error("abort resubscribe for selfCurrentPid changed from to",_,n.serviceManager.rtcUserManager.currentSelfPid),e.abrupt("return");case 6:k=_createForOfIteratorHelper$5(C);try{for(k.s();!(P=k.n()).done;)w=P.value,O=w.subscription,I=w.error,O&&!I&&n.handleResubSuccess(O)}catch(e){k.e(e)}finally{k.f()}n.reporter.trace.connectionsEvent(v,"".concat(i,"ReofferSuccess")),n.logger.debug("resub round=".concat(E," resubscribe ").concat(d," success")),n.client.emit("media-reconnect-end",d),A=_createForOfIteratorHelper$5(o);try{for(A.s();!(M=A.n()).done;)x=M.value,n.logger.info("emitted sub-media-reconnect-succeeded",null===(N=x.track)||void 0===N?void 0:N.getTrackId()),n.client.emit("sub-media-reconnect-succeeded",null===(D=x.track)||void 0===D?void 0:D.getTrackId())}catch(e){A.e(e)}finally{A.f()}case 7:return S=!0,e.abrupt("continue",10);case 8:if(e.prev=8,V=e.catch(3),n.logger.debug("resub round=".concat(E," resubscribe failed for"),V),n.serviceManager.rtcUserManager.currentSelfPid===_){e.next=9;break}return n.logger.error("abort resubscribe for selfCurrentPid changed from to",_,n.serviceManager.rtcUserManager.currentSelfPid),e.abrupt("return");case 9:E++,e.next=1;break;case 10:if(!S){if(n.reporter.trace.connectionsEvent(v,"".concat(i,"ReofferFailed")),n.downlink.clearPcForReoffer(),n.downlink=null,o.length){n.client.emit("media-reconnect-end",d),L=_createForOfIteratorHelper$5(o);try{for(L.s();!(j=L.n()).done;)F=j.value,n.logger.info("emitted sub-media-reconnect-failed",null===($=F.track)||void 0===$?void 0:$.getTrackId()),n.client.emit("sub-media-reconnect-failed",null===(U=F.track)||void 0===U?void 0:U.getTrackId())}catch(e){L.e(e)}finally{L.f()}}o.forEach(function(e){if(n.removeSession(e.session.id),"audio"===e.session.targetMediaType){var t,r;null===(t=n.serviceManager.remoteAudioTrack)||void 0===t||t.stopPlay(),null===(r=n.serviceManager.remoteAudioTrack)||void 0===r||null===(r=r.getMediaStreamTrack())||void 0===r||r.stop(),n.serviceManager.remoteAudioTrack=null}else{var i,o,a,s,c=n.serviceManager.rtcUserManager.users.get(e.session.uid);"camera"===e.session.stream.media.video.source?(null===(i=c.videoTrack)||void 0===i||i.stopPlay(),null===(o=c.videoTrack)||void 0===o||null===(o=o.getMediaStreamTrack())||void 0===o||o.stop(),c.videoTrack=null):(null===(a=c.auxiliaryTrack)||void 0===a||a.stopPlay(),null===(s=c.auxiliaryTrack)||void 0===s||null===(s=s.getMediaStreamTrack())||void 0===s||s.stop(),c.auxiliaryTrack=null)}})}case 11:case"end":return e.stop()}},e,null,[[3,8]])})),function(){return a.apply(this,arguments)})}),n.serviceManager=r,n.client=e,n.reporter=r.reporter,n.logger=n.reporter.getLoggerWithPrefix("[rtc-sessionMgr]"),n.streamIdToSessionId=new Map,n.sessions=new Map,n.mixedLocalAudioTrack=new MixedLocalAudioTrack(r),n.handleMediaMessage=n.handleMediaMessage.bind(n),n.handleServerFailover=n.handleServerFailover.bind(n),n}return _inherits$1(t,e),_createClass$1(t,[{key:"getOrCreatePeerConnection",value:(h=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r=this;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if("uplink"!==t){e.next=3;break}if(this.uplink){e.next=2;break}return this.uplink=new PeerConnection({direction:t,sessionManager:this}),e.next=1,this.uplink.startSinglePC();case 1:this.uplink.on("reoffer",this.handleRepublish),this.uplink.on("ended",function(){r.uplink=null});case 2:return e.abrupt("return",this.uplink);case 3:if(this.downlink){e.next=5;break}return this.downlink=new PeerConnection({direction:t,sessionManager:this}),e.next=4,this.downlink.startSinglePC();case 4:this.downlink.on("reoffer",this.handleResubscribe),this.downlink.on("ended",function(){r.downlink=null});case 5:return e.abrupt("return",this.downlink);case 6:case"end":return e.stop()}},e,this)})),function(e){return h.apply(this,arguments)})},{key:"_handleRepub",value:(f=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){var t,r,n,i,o,a,s,c,u,l,d,p,f,h,g,m,v,y,b,S,_,E,T;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(this.logger.info("handle repub"),r=_toConsumableArray(this.client.localTracks),this.mixedLocalAudioTrack.clear(),r.length){this.client.emit("media-reconnect-start",this.client.userId),n=_createForOfIteratorHelper$5(r);try{for(n.s();!(i=n.n()).done;)o=i.value,this.logger.info("emitted pub-media-reconnect-started",o.getTrackId()),this.client.emit("pub-media-reconnect-started",o.getTrackId())}catch(e){n.e(e)}finally{n.f()}}a=null===(t=this.uplink)||void 0===t?void 0:t.id,s=Date.now(),c=s+media_reconnect_duration_ms,u=!1,l=0,l=0;case 1:if(!(l<23&&Date.now()<=c||"disconnected"!==this.serviceManager.internalChannel.connectionState)){e.next=9;break}if(!((d=Date.now())<s+l*media_reconnect_single_round_min_duration_ms)){e.next=2;break}return e.next=2,asyncDelayMs(s+l*media_reconnect_single_round_min_duration_ms-d);case 2:if(this.logger.debug("repub round=".concat(l,", channelconnect=").concat(this.serviceManager.internalChannel.connectionState)),"connected"===this.serviceManager.internalChannel.connectionState){e.next=3;break}return e.abrupt("continue",8);case 3:return e.prev=3,this.reporter.trace.connectionsEvent(a,"clientReofferStart"),this.logger.info("repub round=".concat(l,", clearPcForReoffer start ").concat(r.map(function(e){return e.trackMediaType}).join())),e.next=4,null===(p=this.uplink)||void 0===p?void 0:p.clearPcForReoffer();case 4:if(this.uplink=null,this.logger.info("repub round=".concat(l,", batchPublish start ").concat(r.map(function(e){return e.trackMediaType}).join())),!r.length){e.next=6;break}return e.next=5,this.batchPublish(r);case 5:this.logger.info("".concat(this.client.userId," batchPublish finished for repub")),this.logger.info("emitted media-reconnect-end",this.client.userId),this.client.emit("media-reconnect-end",this.client.userId),f=_createForOfIteratorHelper$5(r);try{for(f.s();!(h=f.n()).done;)g=h.value,this.logger.info("emitted pub-media-reconnect-succeeded",g.getTrackId()),this.client.emit("pub-media-reconnect-succeeded",g.getTrackId())}catch(e){f.e(e)}finally{f.f()}case 6:return this.reporter.trace.connectionsEvent(a,"clientReofferSuccess"),u=!0,e.abrupt("continue",9);case 7:e.prev=7,E=e.catch(3),this.logger.error("".concat(this.client.userId," republish failed for"),E);case 8:l++,e.next=1;break;case 9:if(this.logger.info("break from repub loop roundNum, connectionstate",l,this.serviceManager.internalChannel.connectionState),u){e.next=14;break}if(this.reporter.trace.connectionsEvent(a,"clientReofferFailed"),"connected"!==this.serviceManager.internalChannel.connectionState){e.next=13;break}return e.prev=10,this.logger.info("unpub all tracks after repub failed"),e.next=11,this.serviceManager.unpublish(r);case 11:e.next=13;break;case 12:e.prev=12,T=e.catch(10),this.logger.info("err for unpub after repub failed",T);case 13:if(null===(m=this.uplink)||void 0===m||m.clearPcForReoffer(),this.uplink=null,r.length){this.client.emit("media-reconnect-end",this.client.userId),v=_createForOfIteratorHelper$5(r);try{for(v.s();!(y=v.n()).done;)b=y.value,(S=this.streamIdToSessionId.get(b.getTrackId()))&&(this.logger.info("clear old publication for repub failed",S),null===(_=this.sessions.get(S))||void 0===_||_.clear(),this.sessions.delete(S)),this.logger.info("emitted pub-media-reconnect-failed",b.getTrackId()),this.client.emit("pub-media-reconnect-failed",b.getTrackId())}catch(e){v.e(e)}finally{v.f()}}case 14:case"end":return e.stop()}},e,this,[[3,7],[10,12]])})),function(){return f.apply(this,arguments)})},{key:"handleStuckResubscribe",value:(p=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n,i,o,a,s,c,u,l,d,p,f;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if("connected"===this.serviceManager.internalChannel.connectionState){e.next=1;break}return this.logger.info("ignore for inner not connected"),e.abrupt("return");case 1:r=[],n=_createForOfIteratorHelper$5(t);try{for(n.s();!(i=n.n()).done;)(o=i.value)instanceof Subscription&&o.state===PubSubStates.Processing&&(r.push({stream:o.stream,uid:o.uid,targetMediaType:o.targetMediaType,resolutionInfo:o.userConfigResolution,session:o,profileFallback:!0}),this.removeSession(o.id))}catch(e){n.e(e)}finally{n.f()}return a=r.map(function(e){return e.uid}).join(),this.client.emit("media-reconnect-start",a),this.logger.info("resubscribe ".concat(a," start")),e.prev=2,e.next=3,this.batchUnscribe(r);case 3:return e.next=4,this.batchSubscribe(r);case 4:s=e.sent,c=_createForOfIteratorHelper$5(s);try{for(c.s();!(u=c.n()).done;)l=u.value,d=l.subscription,p=l.error,d&&!p&&this.handleResubSuccess(d)}catch(e){c.e(e)}finally{c.f()}this.client.emit("media-reconnect-end",a),e.next=6;break;case 5:e.prev=5,f=e.catch(2),this.logger.debug("".concat(this.client.userId," resubscribe failed for"),f),this.client.emit("media-reconnect-end",a),this.serviceManager.rtcSignaling.emit("connection-state-change","disconnected",this.client.connectionState,"network_error");case 6:case"end":return e.stop()}},e,this,[[2,5]])})),function(e){return p.apply(this,arguments)})},{key:"getSessionByStreamId",value:function(e){return e?this.sessions.get(this.streamIdToSessionId.get(e)):null}},{key:"handleResubSuccess",value:function(e){var t,r=e.uid,n=e.mediaStream,i=(null===(t=e.stream.media.video)||void 0===t?void 0:t.source)===exports.VideoSourceInfo.SCREENCAST,o=n.getAudioTracks()[0],a=n.getVideoTracks()[0],s=o?"audio":i?"screen":"camera";if(this.logger.debug("".concat(r," resubscribe ").concat(s," success")),o&&this.serviceManager.remoteAudioTrack){var c,u;if(clientConfig.audioSFU)null===(c=(u=this.serviceManager.remoteAudioTrack).replaceStream)||void 0===c||c.call(u,n);else this.serviceManager.remoteAudioTrack.replaceTrack(o)}else{var l=this.serviceManager.rtcUserManager.remoteUsers.find(function(e){return e.userId===r});a&&null!=l&&l.auxiliaryTrack&&i?l.auxiliaryTrack.replaceTrack(a):a&&null!=l&&l.videoTrack&&!i&&l.videoTrack.replaceTrack(a)}}},{key:"handleServerFailover",value:function(e){var t=this;this.logger.debug("serverFailover",e);var r,n=e.actions,i=_createForOfIteratorHelper$5(void 0===n?[]:n);try{var o=function(){var e,n,i=r.value,o=i.actionName,a=i.connectionId;if("reoffer"!==o)return 1;if(a===(null===(e=t.uplink)||void 0===e?void 0:e.id)){var s=t.uplink,c=t.client,u=c.userId,l=c.localTracks;t.client.emit("media-reconnect-start",u),t.reporter.trace.connectionsEvent(a,"serverReofferStart"),s.reoffer().then(function(){t.logger.info("".concat(u," republish ").concat(l.map(function(e){return e.trackMediaType}).join()," success")),t.reporter.trace.connectionsEvent(a,"serverReofferSuccess"),t.client.emit("media-reconnect-end",u)}).catch(function(e){t.logger.debug("".concat(t.client.userId," republish failed for"),e),t.reporter.trace.connectionsEvent(a,"serverReofferFailed"),t.serviceManager.rtcSignaling.emit("connection-state-change","disconnected",t.client.connectionState,"network_error")})}else a===(null===(n=t.downlink)||void 0===n?void 0:n.id)&&t.handleResubscribe(!0)};for(i.s();!(r=i.n()).done;)o()}catch(e){i.e(e)}finally{i.f()}}},{key:"addSession",value:function(e,t){this.sessions.set(t.id,t),this.streamIdToSessionId.set(e,t.id)}},{key:"getNetworkQuality",value:function(e,t){return e>50||t>600?NetworkQualityType.BAD:e>30||t>450?NetworkQualityType.POOR:e>20||t>300?NetworkQualityType.NORMAL:e>10||t>200?NetworkQualityType.GOOD:e>=0||t>=0?NetworkQualityType.GREAT:NetworkQualityType.UNKNOWN}},{key:"checkChannelNetworkQuality",value:(d=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){var t,r=this;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(0!==(t=_toConsumableArray(this.sessions.values())).length){e.next=1;break}return this.emit("network-quality",NetworkQualityType.UNKNOWN,NetworkQualityType.UNKNOWN),e.abrupt("return");case 1:if(0!==t.filter(function(e){var t,r=e.connection;return"connected"===(null==r||null===(t=r.pc)||void 0===t?void 0:t.connectionState)}).length){e.next=2;break}return this.emit("network-quality",NetworkQualityType.DISCONNECTED,NetworkQualityType.DISCONNECTED),e.abrupt("return");case 2:Promise.all([this.getLocalVideoStats(),this.getLocalAudioStats(),this.getRemoteAudioStats(),this.getRemoteVideoStats()]).then(function(e){var t=_slicedToArray(e,4),n=t[0],i=t[1],o=t[2],a=t[3],s=0,c=0,u=0,l=0,d=0,p=0;if(n){var f=n.camera,h=n.auxiliary;f&&(c+=f.sendPacketsLost,s+=f.sendPackets,d=Math.max(d,f.rtt||0)),h&&(c+=h.sendPacketsLost,s+=h.sendPackets,d=Math.max(d,h.rtt||0))}for(var g in i&&(c+=i.sendPacketsLost||0,s+=i.sendPackets||0,d=Math.max(d,i.rtt||0)),o&&(u+=o.receivePacketsLost||0,l+=o.receivePackets||0,p=Math.max(p,o.rtt||0)),a){var m=a[g],v=m.camera,y=m.auxiliary;v&&(u+=v.receivePacketsLost,l+=v.receivePackets,p=Math.max(p,v.rtt||0)),y&&(u+=y.receivePacketsLost,l+=y.receivePackets,p=Math.max(p,y.rtt||0))}var b=-1,S=-1,_={timestamp:Date.now(),totalUplinkPacketsLost:c,totalUplinkPacketsSent:s,totalDownlinkPacketsLost:u,totalDownlinkPacketsRecv:l};if(s){var E,T,R=c-((null===(E=r.lastChannelNetworkQuality)||void 0===E?void 0:E.totalUplinkPacketsLost)||0);if(R<0&&(R=c),_.totalUplinkPacketsSentForLost=(null===(T=r.lastChannelNetworkQuality)||void 0===T?void 0:T.totalUplinkPacketsSentForLost)||0,0!==R){var C;_.totalUplinkPacketsSentForLost=s;var k=s-((null===(C=r.lastChannelNetworkQuality)||void 0===C?void 0:C.totalUplinkPacketsSentForLost)||0);k<0&&(k=s),b=R/k}}if(l){var P,w,O,I,A=u-((null===(P=r.lastChannelNetworkQuality)||void 0===P?void 0:P.totalDownlinkPacketsLost)||0);A<0&&(A=u),_.totalDownlinkPacketsRecvForLost=(null===(w=r.lastChannelNetworkQuality)||void 0===w?void 0:w.totalDownlinkPacketsRecvForLost)||0,null===(O=r.lastChannelNetworkQuality)||void 0===O||O.totalDownlinkPacketsRecvForLost,A&&(u!==((null===(I=r.lastChannelNetworkQuality)||void 0===I?void 0:I.totalDownlinkPacketsLost)||0)&&(_.totalDownlinkPacketsRecvForLost=l),S=A/l)}r.emit("network-quality",r.getNetworkQuality(Math.min(100*b,100),d),r.getNetworkQuality(Math.min(100*S,100),p)),r.lastChannelNetworkQuality=_});case 3:case"end":return e.stop()}},e,this)})),function(){return d.apply(this,arguments)})},{key:"removeSession",value:function(e,t){t&&(e=this.streamIdToSessionId.get(t),this.streamIdToSessionId.delete(t));var r=this.sessions.get(e);r&&(r.clear(),this.sessions.delete(e),this.mixedLocalAudioTrack.getPublication()===r&&this.mixedLocalAudioTrack.clear())}},{key:"batchPublish",value:(l=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t,r){var n,i,o,a,s,c,u,l,d,p=this;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return n=Date.now(),e.next=1,this.getOrCreatePeerConnection("uplink");case 1:return i=e.sent,o=_toConsumableArray(this.sessions.values()).filter(function(e){return e instanceof Publication}),e.next=2,execBatchPublish({uid:this.client.userId,tracks:t,connection:i,labels:r,existedPublications:o,mixedLocalAudioTrack:this.mixedLocalAudioTrack});case 2:a=e.sent,s=_toConsumableArray(a.videoPubResultArr),a.audioPubResult&&s.push(a.audioPubResult),c=_createForOfIteratorHelper$5(s),e.prev=3,l=_regeneratorRuntime$1.mark(function e(){var t,r,i,o,a,s;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:t=u.value,r=t.error,i=t.publication,o=t.track,r?p.reporter.trace.publish(!1,o,"",Date.now()-n):((a=p.streamIdToSessionId.get(o.getTrackId()))&&(p.logger.info("clear old publication before set new one",a),null===(s=p.sessions.get(a))||void 0===s||s.clear(),p.sessions.delete(a)),p.addSession(o.getTrackId(),i),p.reporter.trace.publish(!0,o,i.id,Date.now()-n),p.reporter.trace.publish(!1,o,i.id,Date.now()-n),i.on("ended",function(){p.removeSession(i.id)}));case 1:case"end":return e.stop()}},e)}),c.s();case 4:if((u=c.n()).done){e.next=6;break}return e.delegateYield(l(),"t0",5);case 5:e.next=4;break;case 6:e.next=8;break;case 7:e.prev=7,d=e.catch(3),c.e(d);case 8:return e.prev=8,c.f(),e.finish(8);case 9:case"end":return e.stop()}},e,this,[[3,7,8,9]])})),function(e,t){return l.apply(this,arguments)})},{key:"batchUnPublish",value:(u=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n=this;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(t.length){e.next=1;break}return this.logger.info("batchUnPublish sessions is empty"),e.abrupt("return",Promise.resolve());case 1:return e.next=2,this.getOrCreatePeerConnection("uplink");case 2:return r=e.sent,e.abrupt("return",batchPublishStop(t,{connection:r}).then(function(){var e,r=_createForOfIteratorHelper$5(t);try{for(r.s();!(e=r.n()).done;){var i,o,a=e.value;n.streamIdToSessionId.delete(null===(i=a.tracks)||void 0===i||null===(i=i[0])||void 0===i||null===(o=i.getTrackId)||void 0===o?void 0:o.call(i)),n.removeSession(a.id)}}catch(e){r.e(e)}finally{r.f()}}));case 3:case"end":return e.stop()}},e,this)})),function(e){return u.apply(this,arguments)})},{key:"batchSubscribe",value:function(e){var t,r=this,n=Date.now(),i=0,o=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var n;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=1,r.getOrCreatePeerConnection("downlink");case 1:return n=e.sent,e.abrupt("return",batchSubscribeStart(t,n).then(function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(n){var a,s,c,u;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:for(a=new Map,s=[],c=0;c<n.length;c++)"RoomBusy"===(null===(u=n[c].error)||void 0===u?void 0:u.message)&&(s.push(t[c]),a.set(s.length-1,c));if(!(s.length&&i<=3)){e.next=3;break}return i++,e.next=1,awaitTime(1);case 1:if("connected"!==r.client.connectionState){e.next=3;break}return e.next=2,o(s);case 2:e.sent.forEach(function(e,t){var r=a.get(t);n[r]=e});case 3:return e.abrupt("return",n);case 4:case"end":return e.stop()}},e)}));return function(t){return e.apply(this,arguments)}}()));case 2:case"end":return e.stop()}},e)}));return function(t){return e.apply(this,arguments)}}(),a=_createForOfIteratorHelper$5(e);try{for(a.s();!(t=a.n()).done;){var s=t.value,c=s.stream,u=s.uid,l=s.resolutionInfo;(null==c?void 0:c.id)&&this.reporter.trace.subscribe({subPhase:"init",capabilities:null==c?void 0:c.media,remoteStreamId:null==c?void 0:c.id,remoteUserId:u,elapse:0,sessionId:"",resolutionInfo:l})}}catch(e){a.e(e)}finally{a.f()}return o(e).then(function(e){var t,i=_createForOfIteratorHelper$5(e);try{var o=function(){var e=t.value,i=e.error,o=e.subscription,a=e.id,s=e.stream,c=e.uid,u=e.resolutionInfo;if(o){r.reporter.trace.subscribe({subPhase:"success",capabilities:s.media,remoteStreamId:s.id,remoteUserId:c,elapse:Date.now()-n,sessionId:a,resolutionInfo:u});var l,d=r.streamIdToSessionId.get(s.id);if(d)r.logger.info("clear old subscription before set new one",d),null===(l=r.sessions.get(d))||void 0===l||l.clear(),r.sessions.delete(d);r.addSession(s.id,o),o.on("ended",function(){r.logger.info("remove subscription for ended",a),r.removeSession(a)})}i&&(r.logger.error("batchSubscribe error",s,i),(null==s?void 0:s.id)&&r.reporter.trace.subscribe({subPhase:"failed",capabilities:(null==s?void 0:s.media)||{},remoteStreamId:null==s?void 0:s.id,remoteUserId:c,elapse:Date.now()-n,sessionId:"",resolutionInfo:u}))};for(i.s();!(t=i.n()).done;)o()}catch(e){i.e(e)}finally{i.f()}return r.logger.info("batchSubscribe result",null==e?void 0:e.map(function(e){var t,r;return{error:null==e?void 0:e.error,uid:null==e?void 0:e.uid,streamId:null==e||null===(t=e.stream)||void 0===t?void 0:t.id,sessionId:null==e||null===(r=e.subscription)||void 0===r?void 0:r.id}})),e})}},{key:"batchUnscribe",value:(c=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n,i,o,a=this;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return r=new Array(t.length),n=[],i={},t.forEach(function(e,t){var o=e.error,s=e.stream,c=e.session;r[t]={},o?(r[t].error=o,a.logger.error("batchUnscribe error",o,s)):(i[null==s?void 0:s.id]=t,n.push(c))}),e.next=1,this.getOrCreatePeerConnection("downlink");case 1:return o=e.sent,e.abrupt("return",batchSubscribeStop(n,o).then(function(){for(var e=0,t=n;e<t.length;e++){var i=t[e];a.removeSession(i.id)}return r}));case 2:case"end":return e.stop()}},e,this)})),function(e){return c.apply(this,arguments)})},{key:"clear",value:function(){var e,t,r=this;this.sessions.forEach(function(e){r.removeSession(e.id)}),this.mixedLocalAudioTrack.clear(),null===(e=this.uplink)||void 0===e||e.closePeerConnection(),this.uplink=null,null===(t=this.downlink)||void 0===t||t.closePeerConnection(),this.downlink=null,this.streamIdToSessionId.clear(),this.networkQualityInterval&&(removeTimer(this.networkQualityInterval,"interval"),this.networkQualityInterval=null),this.serviceManager.rtcSignaling.off("media-message",this.handleMediaMessage),this.serviceManager.rtcSignaling.off("serverFailover",this.handleServerFailover)}},{key:"start",value:(s=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return this.startNetworkQualityTimer(),e.next=1,this.getOrCreatePeerConnection("uplink");case 1:return this.uplink=e.sent,e.next=2,this.getOrCreatePeerConnection("downlink");case 2:this.downlink=e.sent,this.serviceManager.rtcSignaling.on("media-message",this.handleMediaMessage),this.serviceManager.rtcSignaling.on("serverFailover",this.handleServerFailover);case 3:case"end":return e.stop()}},e,this)})),function(){return s.apply(this,arguments)})},{key:"startNetworkQualityTimer",value:function(){var e=this;this.networkQualityInterval=addTimer(function(){navigator&&void 0!==navigator.onLine&&!navigator.onLine?e.emit("network-quality",NetworkQualityType.DISCONNECTED,NetworkQualityType.DISCONNECTED):"connected"!==e.client.connectionState?e.emit("network-quality",NetworkQualityType.BAD,NetworkQualityType.BAD):"connected"===e.client.connectionState?e.checkChannelNetworkQuality():e.emit("network-quality",NetworkQualityType.UNKNOWN,NetworkQualityType.UNKNOWN)},NETWORK_QUALITY_TIMEOUT,"interval")}},{key:"getLocalAudioStats",value:(a=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){var t,r,n,i=arguments;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return r=i.length>0&&void 0!==i[0]?i[0]:"network",n=_toConsumableArray(this.sessions.values()).filter(function(e){var t,r;return e instanceof Publication&&"connected"===(null===(t=e.connection)||void 0===t||null===(t=t.pc)||void 0===t?void 0:t.connectionState)&&"audio"===(null===(r=e.tracks)||void 0===r||null===(r=r[0])||void 0===r?void 0:r.trackMediaType)}),e.next=1,Promise.all(n.map(function(e){return e.getMetrics(r)}));case 1:return e.abrupt("return",(null===(t=n[0])||void 0===t?void 0:t.audioStatsMap.get(r))||{});case 2:case"end":return e.stop()}},e,this)})),function(){return a.apply(this,arguments)})},{key:"getLocalVideoStats",value:(o=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){var t,r,n,i,o,a,s,c,u,l,d,p,f,h,g,m=arguments;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return n=m.length>0&&void 0!==m[0]?m[0]:"network",i=_toConsumableArray(this.sessions.values()).filter(function(e){var t;return e instanceof Publication&&"connected"===(null===(t=e.connection)||void 0===t||null===(t=t.pc)||void 0===t?void 0:t.connectionState)&&"video"===e.tracks[0].trackMediaType}),e.next=1,Promise.all(i.map(function(e){return e.getMetrics(n)}));case 1:o=function(e){var t;return(null==e||null===(t=e.fmtp)||void 0===t?void 0:t.filter(function(e){var t;return null==e||null===(t=e.config)||void 0===t?void 0:t.includes("profile-level-id")}).map(function(e){var t,r=(null==e||null===(t=e.config)||void 0===t?void 0:t.split(";"))||[],n=r.findIndex(function(e){return e.includes("profile-level-id")});return r[n].split("=")[1]}))||[]},a=null===(t=this.uplink)||void 0===t||null===(t=t.offerSDP)||void 0===t||null===(t=t.media)||void 0===t?void 0:t.find(function(e){return"video"===e.type}),s=null===(r=this.downlink)||void 0===r||null===(r=r.offerSDP)||void 0===r||null===(r=r.media)||void 0===r?void 0:r.find(function(e){return"video"===e.type}),c={uplinkProfile:_toConsumableArray(new Set(o(a))),downlinkProfile:_toConsumableArray(new Set(o(s)))},u=_createForOfIteratorHelper$5(i),e.prev=2,u.s();case 3:if((l=u.n()).done){e.next=6;break}if(d=l.value,p=d.videoStatsMap.get(n)){e.next=4;break}return e.abrupt("continue",5);case 4:f=d.tracks,h=f[0].source===exports.VideoSourceInfo.SCREENCAST,c[h?"auxiliary":"camera"]=p;case 5:e.next=3;break;case 6:e.next=8;break;case 7:e.prev=7,g=e.catch(2),u.e(g);case 8:return e.prev=8,u.f(),e.finish(8);case 9:return e.abrupt("return",c);case 10:case"end":return e.stop()}},e,this,[[2,7,8,9]])})),function(){return o.apply(this,arguments)})},{key:"getRemoteVideoStats",value:(i=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){var t,r,n,i,o,a,s,c,u,l,d,p,f,h=arguments;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t=h.length>0&&void 0!==h[0]?h[0]:"network",r=_toConsumableArray(this.sessions.values()).filter(function(e){var t;return e instanceof Subscription&&"connected"===(null===(t=e.connection)||void 0===t||null===(t=t.pc)||void 0===t?void 0:t.connectionState)&&e.stream.media.video}),e.next=1,Promise.all(r.map(function(e){return e.getMetrics(t)}));case 1:n={},i=_createForOfIteratorHelper$5(r),e.prev=2,i.s();case 3:if((o=i.n()).done){e.next=6;break}if(s=o.value,c=s.videoStatsMap,u=s.uid,l=s.stream,d=c.get(t)){e.next=4;break}return e.abrupt("continue",5);case 4:p=(null===(a=l.media.video)||void 0===a?void 0:a.source)===exports.VideoSourceInfo.SCREENCAST?"auxiliary":"camera",n[u]=_objectSpread$3(_objectSpread$3({},n[u]||{}),{},_defineProperty({},p,d));case 5:e.next=3;break;case 6:e.next=8;break;case 7:e.prev=7,f=e.catch(2),i.e(f);case 8:return e.prev=8,i.f(),e.finish(8);case 9:return e.abrupt("return",n);case 10:case"end":return e.stop()}},e,this,[[2,7,8,9]])})),function(){return i.apply(this,arguments)})},{key:"getRemoteAudioStats",value:(n=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){var t,r,n,i=arguments;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return r=i.length>0&&void 0!==i[0]?i[0]:"network",n=_toConsumableArray(this.sessions.values()).filter(function(e){var t;return e instanceof Subscription&&"connected"===(null===(t=e.connection)||void 0===t||null===(t=t.pc)||void 0===t?void 0:t.connectionState)&&e.stream.media.audio}),e.next=1,Promise.all(n.map(function(e){return e.getMetrics(r)}));case 1:return e.abrupt("return",(null===(t=n[0])||void 0===t?void 0:t.audioStatsMap.get(r))||{});case 2:case"end":return e.stop()}},e,this)})),function(){return n.apply(this,arguments)})},{key:"handleMediaMessage",value:(r=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n,i,o,a,s;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(this.logger.debug("remote feedback: ",t.payload),r=JSON.parse(t.payload),Array.isArray(r)&&0!==r.length){e.next=1;break}return e.abrupt("return");case 1:n=_toConsumableArray(this.sessions.values()).filter(function(e){return e instanceof Publication&&e.state===PubSubStates.Processing&&e.tracks[0].source===exports.VideoSourceInfo.CAMERA}),i=_createForOfIteratorHelper$5(n),e.prev=2,a=_regeneratorRuntime$1.mark(function e(){var t,n;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:t=o.value,(n=r.filter(function(e){return e.mid==t.transceiver.mid})).length&&t.applyOptions(n);case 1:case"end":return e.stop()}},e)}),i.s();case 3:if((o=i.n()).done){e.next=5;break}return e.delegateYield(a(),"t0",4);case 4:e.next=3;break;case 5:e.next=7;break;case 6:e.prev=6,s=e.catch(2),i.e(s);case 7:return e.prev=7,i.f(),e.finish(7);case 8:case"end":return e.stop()}},e,this,[[2,6,7,8]])})),function(e){return r.apply(this,arguments)})}]);var r,n,i,o,a,s,c,u,l,d,p,f,h}(EventEmitter);function _createForOfIteratorHelper$4(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$4(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$4(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$4(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_arrayLikeToArray$4(e,t):void 0}}function _arrayLikeToArray$4(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _callSuper$7(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$7()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$7(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$7=function(){return!!e})()}var PropertyNameMap={name:"name"},GroupManager=function(e){function t(e){var r;return _classCallCheck$1(this,t),r=_callSuper$7(this,t),Object.defineProperty(r,"serviceManager",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(r,"groupIds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"groups",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"default",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"listVer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.serviceManager=e,r.logger=r.serviceManager.reporter.getLoggerWithPrefix("[rtc-groupMgr]"),r.groups=new Map,r.listVer=0,r.groupIds=new Set,r.handleGroupListEvents=r.handleGroupListEvents.bind(r),r.handleGroupEvents=r.handleGroupEvents.bind(r),r.handleSyncEvent=r.handleSyncEvent.bind(r),r}return _inherits$1(t,e),_createClass$1(t,[{key:"joinedIds",get:function(){var e=this.serviceManager.rtcUserManager.currentSelfPid,t=new Set;return this.groups.forEach(function(r){var n=r.participants,i=r.id;n.some(function(t){return t.pid===e})&&t.add(i)}),t}},{key:"parseGroup",value:function(e){var t,r=this,n=e.id,i=e.properties,o=e.participants;return{id:n,name:(null==i||null===(t=i.find(function(e){return"name"===e.key}))||void 0===t?void 0:t.value)||"",joined:o.some(function(e){return e.pid===r.serviceManager.rtcUserManager.currentSelfPid}),users:o.map(function(e){return{userId:e.uid,userData:e.userData}})}}},{key:"groupList",get:function(){var e=this,t=[];return this.groups.forEach(function(r){t.push(e.parseGroup(r))}),t}},{key:"init",value:function(e,t){this.listVer=t,this.groupIds=new Set(e),this.batchSyncGroup(e),this.observerAllGroup(),this.serviceManager.rtcSignaling.on("group-list",this.handleGroupListEvents),this.serviceManager.rtcSignaling.on("group",this.handleGroupEvents),this.serviceManager.rtcSignaling.on("sync",this.handleSyncEvent)}},{key:"clear",value:function(){this.listVer=0,this.serviceManager.rtcSignaling.off("group",this.handleGroupEvents),this.serviceManager.rtcSignaling.off("group-list",this.handleGroupListEvents),this.serviceManager.rtcSignaling.off("sync",this.handleSyncEvent),this.groupIds.clear(),this.groups.clear()}},{key:"join",value:function(e){var t=e.publishAudioToGroup,r=void 0===t||t,n=e.groupId,i=e.userData;if(this.joinedIds.has(n))throw new DingRTCError(ErrorCode.InvaildArgument,"you were in group already");return this.serviceManager.rtcSignaling.joinGroup({groupId:n,userData:i,autoJoinGroupAudio:!!r,autoLeaveChannelAudio:!0})}},{key:"leave",value:function(e){var t=e.groupId,r=e.publishAudioToChannel,n=void 0===r||r;if(!this.joinedIds.has(t))throw new DingRTCError(ErrorCode.InvaildArgument,"you are not in the group");return this.serviceManager.rtcSignaling.leaveGroup({groupId:t,reasonCode:signal_msg.LEAVE_GROUP_REASON_CODE.NORMAL_LEAVE,autoJoinChannelAudio:n})}},{key:"dismiss",value:function(e){if(!this.groupIds.has(e))throw new DingRTCError(ErrorCode.InvaildArgument,"group not existed");return this.serviceManager.rtcSignaling.dismissGroup({groupId:e})}},{key:"addUser",value:function(e,t){var r,n=null===(r=this.groups.get(t))||void 0===r?void 0:r.participants;n&&!n.find(function(t){return t.pid===e.pid})&&n.push(e)}},{key:"removeUser",value:function(e,t){var r,n=null===(r=this.groups.get(t))||void 0===r?void 0:r.participants;if(n){var i=n.findIndex(function(t){return t.pid===e.pid});i>-1&&n.splice(i,1)}}},{key:"observerAllGroup",value:function(){return this.serviceManager.rtcSignaling.observeAllGroups()}},{key:"unobserverAllGroup",value:function(){return this.serviceManager.rtcSignaling.unobserveAllGroups()}},{key:"setProperties",value:function(e,t){return this.serviceManager.rtcSignaling.setGroupProperties({groupId:e,properties:[t]})}},{key:"handleGroupListEvents",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=e.ver,n=e.type,i=e.updateOpt;if(this.logger.info("on groupList event:",e),r!==this.listVer+1&&!t||n!==signal_msg.OptType.OPT_TYPE_UPDATE)r>this.listVer+1&&this.syncGroupList();else{var o=i.updateAction,a=i.id;o===signal_msg.GroupListUpdate.GROUP_LIST_UPDATE_ADD_ID?this.groupIds.add(a):o===signal_msg.GroupListUpdate.GROUP_LIST_UPDATE_REMOVE_ID&&this.groupIds.delete(a),this.listVer=r}}},{key:"handleGroupEvents",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this.logger.info("on group event:",e);var n,i=e.id,o=e.ver,a=e.groupInfo,s=e.type,c=e.updateOpt,u=this.groups.get(i);if(s!==signal_msg.OptType.OPT_TYPE_ADD||u){if(s===signal_msg.OptType.OPT_TYPE_REMOVE&&u)this.groups.delete(i),this.emit("group","remove",this.parseGroup(u),u.audioInfo);else if(s===signal_msg.OptType.OPT_TYPE_UPDATE){var l=c.updateAction,d=c.participants;if(u&&(u.ver+1===o||r)){if(l===signal_msg.GroupUpdate.GROUP_UPDATE_ADD_PARTICIPANTS){var p,f=u.participants.map(function(e){return e.pid}),h=_createForOfIteratorHelper$4(d);try{for(h.s();!(p=h.n()).done;){var g=p.value;f.includes(g.pid)||(u.participants.push(g),this.emit("group","user-join",i,{userId:g.uid,userData:g.userData}))}}catch(e){h.e(e)}finally{h.f()}}else if(l===signal_msg.GroupUpdate.GROUP_UPDATE_REMOVE_PARTICIPANTS){var m=d.map(function(e){return e.pid}),v=_toConsumableArray(u.participants);u.participants=u.participants.filter(function(e){return!m.includes(e.pid)}),v.forEach(function(e){m.includes(e.pid)&&t.emit("group","user-leave",i,{userId:e.uid,userData:e.userData})})}else if(l===signal_msg.GroupUpdate.GROUP_UPDATE_AUDIO_STREAM_LOST)this.logger.info("group ".concat(i," audioStream lost"));else if(l===signal_msg.GroupUpdate.GROUP_UPDATE_AUDIO_STREAM_RECOVER)this.logger.debug("group ".concat(i," audioStream recover"));else if(l===signal_msg.GroupUpdate.GROUP_UPDATE_SET_PROPERTIES)c.properties.forEach(function(e){var r=!0;u.properties||(u.properties=[]),u.properties.forEach(function(t){t.key===e.key&&(t.value=e.value,r=!1)}),r&&u.properties.push(e),t.emit("group","info-updated",i,{key:"set-".concat(PropertyNameMap[e.key]),value:e.value})});else if(l===signal_msg.GroupUpdate.GROUP_UPDATE_REMOVE_PROPERTIES){var y,b=c.properties.map(function(e){return e.key});u.properties=null===(y=u.properties)||void 0===y?void 0:y.filter(function(e){var t=e.key;return!b.includes(t)}),c.properties.forEach(function(e){t.emit("group","info-updated",i,{key:"remove-".concat(PropertyNameMap[e.key])})})}u.ver=o}else u&&o>u.ver+1&&this.syncGroup(u.id)}}else null==a||null===(n=a.audioInfo)||void 0===n||null===(n=n.audio)||void 0===n||null===(n=n.media)||void 0===n||delete n.video,null==a.ver&&(a.ver=o),this.groups.set(i,a),this.emit("group","add",this.parseGroup(a))}},{key:"syncGroup",value:function(e){var t=this,r=this.groups.get(e);return this.serviceManager.rtcSignaling.syncData({type:signal_msg.DataType.DATA_TYPE_GROUP,id:e,ver:null==r?void 0:r.ver}).then(function(n){var i=n.fullSync.groupData.groupInfos,o=(void 0===i?[]:i)[0];if(o){var a=o.participants,s=o.properties,c=void 0===s?[]:s,u=(null==r?void 0:r.participants)||[],l=new Map(((null==r?void 0:r.properties)||[]).map(function(e){return[e.key,e.value]})),d=u.map(function(e){return e.pid}),p=a.map(function(e){return e.pid}),f=c.filter(function(e){return e.value!==l[e.key]}),h=c.filter(function(e){return!l.has(e.key)}),g=a.filter(function(e){return!d.includes(e.pid)}),m=u.filter(function(e){return!p.includes(e.pid)});g.length&&t.handleGroupEvents({id:e,type:signal_msg.OptType.OPT_TYPE_REMOVE,ver:o.ver,updateOpt:{updateAction:signal_msg.GroupUpdate.GROUP_UPDATE_ADD_PARTICIPANTS,participants:g}},!0),m.length&&t.handleGroupEvents({id:e,ver:o.ver,type:signal_msg.OptType.OPT_TYPE_REMOVE,updateOpt:{updateAction:signal_msg.GroupUpdate.GROUP_UPDATE_REMOVE_PARTICIPANTS,participants:m}},!0),f.length&&t.handleGroupEvents({id:e,ver:o.ver,type:signal_msg.OptType.OPT_TYPE_UPDATE,updateOpt:{updateAction:signal_msg.GroupUpdate.GROUP_UPDATE_SET_PROPERTIES,properties:f}},!0),h.length&&t.handleGroupEvents({id:e,ver:o.ver,type:signal_msg.OptType.OPT_TYPE_UPDATE,updateOpt:{updateAction:signal_msg.GroupUpdate.GROUP_UPDATE_REMOVE_PROPERTIES,properties:h}},!0)}else t.handleGroupEvents({id:e,type:signal_msg.OptType.OPT_TYPE_REMOVE})})}},{key:"batchSyncGroup",value:function(e){var t=this;if(e.length)return this.serviceManager.rtcSignaling.syncDataByIds({type:signal_msg.DataType.DATA_TYPE_GROUP,ids:e.map(function(e){return{id:e}})}).then(function(e){e.fullSync.groupData.groupInfos.forEach(function(e){t.groupIds.add(e.id),t.groups.set(e.id,e)})})}},{key:"syncGroupList",value:function(){var e=this;this.serviceManager.rtcSignaling.syncData({type:signal_msg.DataType.DATA_TYPE_GROUP_LIST,forceFullSync:!0,ver:this.listVer}).then(function(t){var r=t.fullSync,n=r.ver,i=r.groupListData.groupIds,o=void 0===i?[]:i,a=o.filter(function(t){return!e.groupIds.has(t)}),s=_toConsumableArray(e.groupIds).filter(function(e){return!o.includes(e)});a.length&&a.forEach(function(t){e.handleGroupListEvents({ver:n,updateOpt:{updateAction:signal_msg.GroupListUpdate.GROUP_LIST_UPDATE_ADD_ID,id:t}},!0)}),s.length&&s.forEach(function(t){e.handleGroupListEvents({ver:n,updateOpt:{updateAction:signal_msg.GroupListUpdate.GROUP_LIST_UPDATE_REMOVE_ID,id:t}},!0)})})}},{key:"handleSyncEvent",value:function(e){var t=this,r=e.groupListVer,n=e.groupVer,i=void 0===n?[]:n;this.listVer<r&&(this.syncGroupList(),this.listVer=r),i.forEach(function(e){var r=e.id,n=e.ver,i=t.groups.get(r);(null==i?void 0:i.ver)<n&&(t.syncGroup(r),i.ver=n)})}}])}(EventEmitter);function _callSuper$6(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$6()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$6(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$6=function(){return!!e})()}var User=function(e){function t(e,r){var n;_classCallCheck$1(this,t),n=_callSuper$6(this,t),Object.defineProperty(n,"serviceManager",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(n,"userId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"userName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"streamMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"videoTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"auxiliaryTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"audioTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"joinedTime",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"properties",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"toJSON",{enumerable:!0,configurable:!0,writable:!0,value:function(){return{userId:n.userId,userName:n.userName,hasAuxiliary:n.hasAuxiliary,hasVideo:n.hasVideo,hasAudio:n.hasAudio,joinedTime:n.joinedTime,properties:n.properties,audioMuted:n.audioMuted,auxiliaryMuted:n.auxiliaryMuted,videoMuted:n.videoMuted}}});var i=e.user;return n.userId=i,n.videoTrack=null,n.audioTrack=null,n.auxiliaryTrack=null,n.serviceManager=r,n.joinedTime=Date.now(),n.update(e),n}return _inherits$1(t,e),_createClass$1(t,[{key:"relatedStreams",get:function(){var e=this;return _toConsumableArray(this.serviceManager.streamManager.streams.values()).filter(function(t){var r;return(null==t||null===(r=t.info)||void 0===r?void 0:r.owner)===e.id})}},{key:"hasAuxiliary",get:function(){return this.relatedStreams.some(function(e){var t;return(null===(t=e.media)||void 0===t||null===(t=t.video)||void 0===t?void 0:t.source)===exports.VideoSourceInfo.SCREENCAST})}},{key:"hasVideo",get:function(){return this.relatedStreams.some(function(e){var t,r=e.media;return(null==r||null===(t=r.video)||void 0===t?void 0:t.source)===exports.VideoSourceInfo.CAMERA})}},{key:"hasAudio",get:function(){return this.relatedStreams.some(function(e){var t,r=e.media;return(null==r||null===(t=r.audio)||void 0===t?void 0:t.source)===exports.AudioSourceInfo.MIC})}},{key:"audioMuted",get:function(){return this.relatedStreams.some(function(e){var t,r,n=e.media;return"active"!==(null==n||null===(t=n.audio)||void 0===t?void 0:t.status)&&(null==n||null===(r=n.audio)||void 0===r?void 0:r.source)===exports.AudioSourceInfo.MIC})}},{key:"auxiliaryMuted",get:function(){return this.relatedStreams.some(function(e){var t,r,n=e.media;return"active"!==(null==n||null===(t=n.video)||void 0===t?void 0:t.status)&&(null==n||null===(r=n.video)||void 0===r?void 0:r.source)===exports.VideoSourceInfo.SCREENCAST})}},{key:"videoMuted",get:function(){return this.relatedStreams.some(function(e){var t,r,n=e.media;return"active"!==(null==n||null===(t=n.video)||void 0===t?void 0:t.status)&&(null==n||null===(r=n.video)||void 0===r?void 0:r.source)===exports.VideoSourceInfo.CAMERA})}},{key:"updateNetworkOfUser",value:function(e){var t;if(this.properties.SdkType!==SdkType$1.Web&&e){var r=e.split("");r[ClientUserStats.UPLINK]=transNativeAndWebNetworkRank(r[ClientUserStats.UPLINK]),r[ClientUserStats.DOWNLINK]=transNativeAndWebNetworkRank(r[ClientUserStats.DOWNLINK]),e=r.join("")}e!==(null===(t=this.properties)||void 0===t?void 0:t[USER_STATS_SYNC])&&(this.properties[USER_STATS_SYNC]=e)}},{key:"update",value:function(e){var t=e.id,r=e.propertiesJsonStr,n=e.ver,i=JSON.parse(r||"{}");this.id=t,this.userName=i.__nick,this.version=n;var o=this.properties||{};this.properties=i,this.updateNetworkOfUser(i[USER_STATS_SYNC]),!i.hasOwnProperty("mute_audio_record")||void 0!==o.mute_audio_record&&i.mute_audio_record===o.mute_audio_record||this.serviceManager.client.emit("user-mic-audio-muted",this.userId,!!i.mute_audio_record),!i.hasOwnProperty("enable_sys_audio")||void 0!==o.enable_sys_audio&&i.enable_sys_audio===o.enable_sys_audio||this.serviceManager.client.emit("user-screencast-audio-mixed",this.userId,!!i.enable_sys_audio)}},{key:"updateSubbedVideoTrack",value:function(e,t){var r=t?this.auxiliaryTrack:this.videoTrack,n=JSON.parse(e.stream.info.attributesJsonStr),i=updateRemoteTrack(e.mediaStream,"video",this.userId,r);return t?this.auxiliaryTrack=i:this.videoTrack=i,n.mirror&&i.setSourceMirror(n.mirror),i}}])}(EventEmitter);function _createForOfIteratorHelper$3(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$3(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$3(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$3(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_arrayLikeToArray$3(e,t):void 0}}function _arrayLikeToArray$3(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _callSuper$5(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$5()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$5(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$5=function(){return!!e})()}var RtcUserManager=function(e){function t(e,r){var n;return _classCallCheck$1(this,t),n=_callSuper$5(this,t),Object.defineProperty(n,"serviceManager",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(n,"users",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"currentUid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"currentSelfPid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"streamManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),n.users=new Map,n.serviceManager=e,n.reporter=e.reporter,n.logger=n.reporter.getLoggerWithPrefix("[rtc-userMgr]"),n.handleEvent=n.handleEvent.bind(n),n.streamManager=r,n}return _inherits$1(t,e),_createClass$1(t,[{key:"remoteUsers",get:function(){var e=this;return uniqBy(_toConsumableArray(this.users.values()).sort(function(e,t){return e.joinedTime-t.joinedTime}),"userId").filter(function(t){return t.userId&&t.id!==e.currentSelfPid})}},{key:"init",value:function(e,t){var r,n=_createForOfIteratorHelper$3(e);try{for(n.s();!(r=n.n()).done;){var i=r.value,o=new User(i,this.serviceManager);this.users.set(i.user,o),t===i.user&&(this.currentUid=i.user)}}catch(e){n.e(e)}finally{n.f()}this.currentSelfPid=t,this.serviceManager.internalChannel.on("user",this.handleEvent)}},{key:"clear",value:function(){this.currentSelfPid="",this.currentUid="",this.users.clear(),this.serviceManager.internalChannel.off("user",this.handleEvent)}},{key:"handleEvent",value:function(e,t,r){var n=this;if(this.logger.info("userEvent ".concat(e," ").concat(JSON.stringify(t))),"join"===e){var i=new User(t,this.serviceManager);this.users.set(t.user,i),this.emit("user","join",i)}else if("leave"===e){var o=this.users.get(t.user);this.users.delete(t.user),this.emit("user","leave",o)}else if("update"===e){var a=this.users.get(t.user);null==a||a.update(t)}else if("participant-replace"===e){var s=new Set(null==r?void 0:r.map(function(e){return e.id}));_toConsumableArray(this.streamManager.streams.values()).filter(function(e){var t;return s.has(null==e||null===(t=e.info)||void 0===t?void 0:t.owner)}).map(function(e){return e.id}).forEach(function(e){return n.streamManager.remove(e,!0)});var c=this.users.get(t.user);this.users.delete(t.user),this.emit("user","leave",c);var u=new User(t,this.serviceManager);this.users.set(t.user,u),this.emit("user","join",u)}}},{key:"setParticipantProperties",value:function(e){return this.serviceManager.rtcSignaling.setParticipantProperties({participantId:this.currentSelfPid,roomId:this.serviceManager.roomId,propertiesJsonStr:JSON.stringify(_defineProperty({},USER_STATS_SYNC,e))})}},{key:"notifyParticipantProperties",value:function(e){return this.serviceManager.rtcSignaling.setParticipantProperties({participantId:this.currentSelfPid,roomId:this.serviceManager.roomId,propertiesJsonStr:e})}}])}(EventEmitter);function _createForOfIteratorHelper$2(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$2(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$2(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$2(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_arrayLikeToArray$2(e,t):void 0}}function _arrayLikeToArray$2(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function ownKeys$2(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function _objectSpread$2(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$2(Object(r),!0).forEach(function(t){_defineProperty(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$2(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function _callSuper$4(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$4()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$4(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$4=function(){return!!e})()}var debounce=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:50,r=null;return function(){for(var n=this,i=arguments.length,o=new Array(i),a=0;a<i;a++)o[a]=arguments[a];r&&clearTimeout(r),r=setTimeout(function(){e.apply(n,o)},t)}},StreamManager=function(e){function t(e){var r;_classCallCheck$1(this,t),r=_callSuper$4(this,t),Object.defineProperty(r,"streams",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"totalVer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"rtcSignaling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"debounceSyncRpc",{enumerable:!0,configurable:!0,writable:!0,value:debounce(r.doSyncRpc,1e3)}),r.streams=new Map;var n=e.rtcSignaling,i=e.reporter;return r.rtcSignaling=n,r.reporter=i,r.logger=r.reporter.getLoggerWithPrefix("[rtc-streamMgr]"),r.handleEvent=r.handleEvent.bind(r),r.handleSyncEvent=r.handleSyncEvent.bind(r),r.debounceSyncRpc=r.debounceSyncRpc.bind(r),r}return _inherits$1(t,e),_createClass$1(t,[{key:"clear",value:function(){this.streams.clear(),this.totalVer=0,this.rtcSignaling.off("stream",this.handleEvent),this.rtcSignaling.off("sync",this.handleSyncEvent)}},{key:"init",value:function(e,t){var r,n=e.find(function(e){return"admin"===e.info.owner&&"mixed"===e.type});null==n||null===(r=n.media)||void 0===r||delete r.video,this.streams=new Map(e.map(function(e){return[e.id,e]})),this.totalVer=t,this.rtcSignaling.on("stream",this.handleEvent),this.rtcSignaling.on("sync",this.handleSyncEvent)}},{key:"add",value:function(e){var t,r=e.id,n=e.info.owner,i=e.media,o=i.video,a=i.audio;if(!this.streams.get(r)){var s=null===(t=e.media)||void 0===t||null===(t=t.video)||void 0===t?void 0:t.source,c=_toConsumableArray(this.streams.values()).find(function(e){var t;return e.info.owner===n&&(null===(t=e.media)||void 0===t||null===(t=t.video)||void 0===t?void 0:t.source)===s});c&&s&&this.remove(c.id),this.reporter.trace.streamsEvent(r,"add"),this.streams.set(e.id,e);var u=(null==o?void 0:o.source)===VideoSourceInfo.SCREENCAST;if((null==o?void 0:o.source)===VideoSourceInfo.CAMERA||u){this.emit("stream","add",{id:r,owner:n,mediaType:"video",auxiliary:u});var l="active"===o.status?"unmute":"mute";this.emit("stream","update",{owner:n,id:r,auxiliary:u,updateStatus:"".concat(l,"-video")})}if((null==a?void 0:a.source)===exports.AudioSourceInfo.MIC||(null==a?void 0:a.source)===exports.AudioSourceInfo.MIXED){this.emit("stream","add",{id:r,owner:n,mediaType:"audio"});var d="active"===a.status?"unmute":"mute";this.emit("stream","update",{owner:n,id:r,auxiliary:!1,updateStatus:"".concat(d,"-audio")})}}}},{key:"remove",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=this.streams.get(e);if(r&&(this.streams.delete(e),t)){this.reporter.trace.streamsEvent(e,"remove");var n=r.media,i=n.video,o=n.audio,a=r.info.owner,s=(null==i?void 0:i.source)===VideoSourceInfo.SCREENCAST;((null==i?void 0:i.source)===VideoSourceInfo.CAMERA||s)&&this.emit("stream","remove",{id:e,owner:a,mediaType:"video",auxiliary:s}),(null==o?void 0:o.source)!==exports.AudioSourceInfo.MIC&&(null==o?void 0:o.source)!==exports.AudioSourceInfo.MIXED||this.emit("stream","remove",{id:e,owner:a,mediaType:"audio"})}}},{key:"getStreamByTrackId",value:function(e){return _toConsumableArray(this.streams.values()).find(function(t){var r,n;return(null===(r=t.media.audio)||void 0===r?void 0:r.trackId)===e||(null===(n=t.media.video)||void 0===n?void 0:n.trackId)===e})}},{key:"handleEvent",value:function(e,t){var r=this,n=e.streamId,i=e.status,o=e.stream,a=e.msg,s=e.totalVer,c={add:[],remove:[],update:["audio.status","video.status","properties","highestResolutionLevel"]}[i];c.length&&!c.includes(a.field)||this.logger.info("streamEvent",e);var u=this.totalVer;if(s===u+1||s==IGNOGRED_VERSION||t)if("add"===i){if(!o||!o.media||!o.info)return;this.add(o)}else if("remove"===i)this.remove(n,!0);else if("update"===i){var l=a.field,d=a.streamStatus,p=a.activeStream,f=a.extraValue,h=a.streamVer,g=a.propertiesJsonStr,m=a.highestResolutionLevel,v=this.streams.get(n);if(v){h!==IGNOGRED_VERSION&&(v.version=h);var y=v.media,b=y.audio,S=y.video,_=v.info.owner;if("audio.status"===l||"video.status"===l){var E,T;"audio.status"===l?(T="audio",b.status=d):"video.status"===l&&(T="video",S.status=d),this.reporter.trace.streamsEvent(n,"".concat(T," ").concat(d));var R="active"===d?"unmute":"mute",C=(null===(E=v.media)||void 0===E||null===(E=E.video)||void 0===E?void 0:E.source)===VideoSourceInfo.SCREENCAST;this.emit("stream","update",{owner:_,id:n,updateStatus:"".concat(R,"-").concat(T),auxiliary:C})}else if("activeInput"===l){var k=[p].concat(f||[]).map(function(e){var t;return null===(t=r.streams.get(e))||void 0===t||null===(t=t.info)||void 0===t?void 0:t.owner}).filter(function(e){return!!e});this.reporter.trace.streamsEvent(JSON.stringify(k),l),this.emit("stream","volumeActive",{owners:k})}else if("properties"==l){var P,w={};try{w=JSON.parse(g)}catch(e){}v.info.attributesJsonStr=JSON.stringify(_objectSpread$2(_objectSpread$2({},JSON.parse(v.info.attributesJsonStr)),w));var O=(null===(P=v.media)||void 0===P||null===(P=P.video)||void 0===P?void 0:P.source)===VideoSourceInfo.SCREENCAST;this.emit("stream","update",{owner:_,id:n,properties:w,auxiliary:O})}else"highestResolutionLevel"===l&&(v.media.video.highestResolutionLevel=m,this.emit("stream","update",{owner:_,id:n,highestResolutionLevel:m}))}}t||s<=this.totalVer&&s!==IGNOGRED_VERSION||(s===u+1&&(this.totalVer=s),s>u+1&&!t&&(this.logger.info("debounceSyncRpc by stream event"),this.debounceSyncRpc()))}},{key:"doSyncRpc",value:(r=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){var t,r,n,i,o,a,s,c,u,l,d,p,f,h,g=this;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t=[],r=[],e.next=1,this.rtcSignaling.getStreamsVer({});case 1:n=e.sent,i=n.streamVersions,o=n.totalVer,a=_toConsumableArray(this.streams.keys()).filter(function(e){return!e.includes("vad")}),s=_createForOfIteratorHelper$2(i),e.prev=2,s.s();case 3:if((c=s.n()).done){e.next=6;break}if(u=c.value,l=u.streamId,d=u.streamVer,!l.includes("vad")){e.next=4;break}return e.abrupt("continue",5);case 4:(p=this.streams.get(l))?p&&p.version!==d&&t.push(l):(r.push(l),t.push(l));case 5:e.next=3;break;case 6:e.next=8;break;case 7:e.prev=7,h=e.catch(2),s.e(h);case 8:return e.prev=8,s.f(),e.finish(8);case 9:if(f=i.map(function(e){return e.streamId}),a.filter(function(e){return!f.includes(e)}).forEach(function(e){g.handleEvent({status:"remove",streamId:e,stream:g.streams.get(e),totalVer:o},!0)}),this.reporter.trace.syncEvent("stream",a,f),this.totalVer=o,0!==t.length){e.next=10;break}return e.abrupt("return");case 10:this.rtcSignaling.getStreams({streamIds:t}).then(function(e){var n,i=e.totalVer,o=e.streams,a=new Map,s=_createForOfIteratorHelper$2(g.streams.values());try{for(s.s();!(n=s.n()).done;){var c=n.value;a.set(c.id,c)}}catch(e){s.e(e)}finally{s.f()}var u,l=_createForOfIteratorHelper$2(o);try{for(l.s();!(u=l.n()).done;){var d,p,f,h,m,v,y,b,S,_,E,T,R=u.value,C=g.streams.get(R.id);if(C)["active","inactive"].includes(null===(d=R.stream.media)||void 0===d||null===(d=d.video)||void 0===d?void 0:d.status)&&(null===(p=R.stream.media)||void 0===p||null===(p=p.video)||void 0===p?void 0:p.status)!==(null===(f=C.media)||void 0===f||null===(f=f.video)||void 0===f?void 0:f.status)&&g.handleEvent({streamId:C.id,status:"update",stream:R.stream,msg:{field:"video.status",streamStatus:null===(S=R.stream.media)||void 0===S||null===(S=S.video)||void 0===S?void 0:S.status,streamVer:R.stream.version},totalVer:i},!0),["active","inactive"].includes(null===(h=R.stream.media)||void 0===h||null===(h=h.audio)||void 0===h?void 0:h.status)&&(null===(m=R.stream.media)||void 0===m||null===(m=m.audio)||void 0===m?void 0:m.status)!==(null===(v=C.media)||void 0===v||null===(v=v.audio)||void 0===v?void 0:v.status)&&g.handleEvent({streamId:C.id,status:"update",stream:R.stream,msg:{field:"audio.status",streamStatus:null===(_=R.stream.media)||void 0===_||null===(_=_.audio)||void 0===_?void 0:_.status,activeStream:null,extraValue:null,streamVer:R.stream.version,propertiesJsonStr:"",highestResolutionLevel:void 0},totalVer:i},!0),null!==(y=R.stream.info)&&void 0!==y&&y.attributesJsonStr&&g.handleEvent({streamId:C.id,status:"update",stream:R.stream,msg:{field:"properties",streamVer:R.stream.version,propertiesJsonStr:(null===(E=R.stream.info)||void 0===E?void 0:E.attributesJsonStr)||"{}"},totalVer:i},!0),null!==(b=R.stream.media)&&void 0!==b&&null!==(b=b.video)&&void 0!==b&&b.highestResolutionLevel&&g.handleEvent({streamId:C.id,status:"update",stream:R.stream,msg:{field:"highestResolutionLevel",streamVer:R.stream.version,highestResolutionLevel:null===(T=R.stream.media)||void 0===T||null===(T=T.video)||void 0===T?void 0:T.highestResolutionLevel},totalVer:i},!0);else a.set(R.id,R.stream)}}catch(e){l.e(e)}finally{l.f()}for(var k=t.map(function(e){return a.get(e)}).filter(function(e){return!!e}).sort(function(e,t){return e.version-t.version}),P=0;P<k.length;P++){var w=k[P];r.includes(w.id)&&g.handleEvent({status:"add",streamId:w.id,stream:w,totalVer:i},!0)}a.clear(),g.totalVer=i});case 11:case"end":return e.stop()}},e,this,[[2,7,8,9]])})),function(){return r.apply(this,arguments)})},{key:"handleSyncEvent",value:function(e){var t=e.streamsVer;this.totalVer<t&&(this.logger.info("debounceSyncRpc by sync event"),this.debounceSyncRpc())}}]);var r}(EventEmitter),wasm=null;try{wasm=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function Long(e,t,r){this.low=0|e,this.high=0|t,this.unsigned=!!r}function isLong(e){return!0===(e&&e.__isLong__)}function ctz32(e){var t=Math.clz32(e&-e);return e?31-t:t}Long.prototype.__isLong__,Object.defineProperty(Long.prototype,"__isLong__",{value:!0}),Long.isLong=isLong;var INT_CACHE={},UINT_CACHE={};function fromInt(e,t){var r,n,i;return t?(i=0<=(e>>>=0)&&e<256)&&(n=UINT_CACHE[e])?n:(r=fromBits(e,0,!0),i&&(UINT_CACHE[e]=r),r):(i=-128<=(e|=0)&&e<128)&&(n=INT_CACHE[e])?n:(r=fromBits(e,e<0?-1:0,!1),i&&(INT_CACHE[e]=r),r)}function fromNumber(e,t){if(isNaN(e))return t?UZERO:ZERO;if(t){if(e<0)return UZERO;if(e>=TWO_PWR_64_DBL)return MAX_UNSIGNED_VALUE}else{if(e<=-TWO_PWR_63_DBL)return MIN_VALUE;if(e+1>=TWO_PWR_63_DBL)return MAX_VALUE}return e<0?fromNumber(-e,t).neg():fromBits(e%TWO_PWR_32_DBL|0,e/TWO_PWR_32_DBL|0,t)}function fromBits(e,t,r){return new Long(e,t,r)}Long.fromInt=fromInt,Long.fromNumber=fromNumber,Long.fromBits=fromBits;var pow_dbl=Math.pow;function fromString(e,t,r){if(0===e.length)throw Error("empty string");if("number"==typeof t?(r=t,t=!1):t=!!t,"NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return t?UZERO:ZERO;if((r=r||10)<2||36<r)throw RangeError("radix");var n;if((n=e.indexOf("-"))>0)throw Error("interior hyphen");if(0===n)return fromString(e.substring(1),t,r).neg();for(var i=fromNumber(pow_dbl(r,8)),o=ZERO,a=0;a<e.length;a+=8){var s=Math.min(8,e.length-a),c=parseInt(e.substring(a,a+s),r);if(s<8){var u=fromNumber(pow_dbl(r,s));o=o.mul(u).add(fromNumber(c))}else o=(o=o.mul(i)).add(fromNumber(c))}return o.unsigned=t,o}function fromValue(e,t){return"number"==typeof e?fromNumber(e,t):"string"==typeof e?fromString(e,t):fromBits(e.low,e.high,"boolean"==typeof t?t:e.unsigned)}Long.fromString=fromString,Long.fromValue=fromValue;var TWO_PWR_16_DBL=65536,TWO_PWR_24_DBL=1<<24,TWO_PWR_32_DBL=TWO_PWR_16_DBL*TWO_PWR_16_DBL,TWO_PWR_64_DBL=TWO_PWR_32_DBL*TWO_PWR_32_DBL,TWO_PWR_63_DBL=TWO_PWR_64_DBL/2,TWO_PWR_24=fromInt(TWO_PWR_24_DBL),ZERO=fromInt(0);Long.ZERO=ZERO;var UZERO=fromInt(0,!0);Long.UZERO=UZERO;var ONE=fromInt(1);Long.ONE=ONE;var UONE=fromInt(1,!0);Long.UONE=UONE;var NEG_ONE=fromInt(-1);Long.NEG_ONE=NEG_ONE;var MAX_VALUE=fromBits(-1,2147483647,!1);Long.MAX_VALUE=MAX_VALUE;var MAX_UNSIGNED_VALUE=fromBits(-1,-1,!0);Long.MAX_UNSIGNED_VALUE=MAX_UNSIGNED_VALUE;var MIN_VALUE=fromBits(0,-2147483648,!1);Long.MIN_VALUE=MIN_VALUE;var LongPrototype=Long.prototype;function I(e,t,r,n,i,o,a){try{var s=e[o](a),c=s.value}catch(e){return void r(e)}s.done?t(c):Promise.resolve(c).then(n,i)}function C(e){return function(){var t=this,r=arguments;return new Promise(function(n,i){var o=e.apply(t,r);function a(e){I(o,n,i,a,s,"next",e)}function s(e){I(o,n,i,a,s,"throw",e)}a(void 0)})}}function O(e){return O="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},O(e)}function P(e){var t=function(e,t){if("object"!=O(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t);if("object"!=O(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e,"string");return"symbol"==O(t)?t:t+""}function R(e,t,r){return(t=P(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function _(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function N(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,P(n.key),n)}}function k(e,t,r){return t&&N(e.prototype,t),r&&N(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function M(e,t){if(t&&("object"==O(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}function w(e){return w=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},w(e)}function D(e,t){return D=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},D(e,t)}function j(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&D(e,t)}function A(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}LongPrototype.toInt=function(){return this.unsigned?this.low>>>0:this.low},LongPrototype.toNumber=function(){return this.unsigned?(this.high>>>0)*TWO_PWR_32_DBL+(this.low>>>0):this.high*TWO_PWR_32_DBL+(this.low>>>0)},LongPrototype.toString=function(e){if((e=e||10)<2||36<e)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(MIN_VALUE)){var t=fromNumber(e),r=this.div(t),n=r.mul(t).sub(this);return r.toString(e)+n.toInt().toString(e)}return"-"+this.neg().toString(e)}for(var i=fromNumber(pow_dbl(e,6),this.unsigned),o=this,a="";;){var s=o.div(i),c=(o.sub(s.mul(i)).toInt()>>>0).toString(e);if((o=s).isZero())return c+a;for(;c.length<6;)c="0"+c;a=""+c+a}},LongPrototype.getHighBits=function(){return this.high},LongPrototype.getHighBitsUnsigned=function(){return this.high>>>0},LongPrototype.getLowBits=function(){return this.low},LongPrototype.getLowBitsUnsigned=function(){return this.low>>>0},LongPrototype.getNumBitsAbs=function(){if(this.isNegative())return this.eq(MIN_VALUE)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&!(e&1<<t);t--);return 0!=this.high?t+33:t+1},LongPrototype.isSafeInteger=function(){var e=this.high>>21;return!e||!this.unsigned&&(-1===e&&!(0===this.low&&-2097152===this.high))},LongPrototype.isZero=function(){return 0===this.high&&0===this.low},LongPrototype.eqz=LongPrototype.isZero,LongPrototype.isNegative=function(){return!this.unsigned&&this.high<0},LongPrototype.isPositive=function(){return this.unsigned||this.high>=0},LongPrototype.isOdd=function(){return!(1&~this.low)},LongPrototype.isEven=function(){return!(1&this.low)},LongPrototype.equals=function(e){return isLong(e)||(e=fromValue(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&(this.high===e.high&&this.low===e.low)},LongPrototype.eq=LongPrototype.equals,LongPrototype.notEquals=function(e){return!this.eq(e)},LongPrototype.neq=LongPrototype.notEquals,LongPrototype.ne=LongPrototype.notEquals,LongPrototype.lessThan=function(e){return this.comp(e)<0},LongPrototype.lt=LongPrototype.lessThan,LongPrototype.lessThanOrEqual=function(e){return this.comp(e)<=0},LongPrototype.lte=LongPrototype.lessThanOrEqual,LongPrototype.le=LongPrototype.lessThanOrEqual,LongPrototype.greaterThan=function(e){return this.comp(e)>0},LongPrototype.gt=LongPrototype.greaterThan,LongPrototype.greaterThanOrEqual=function(e){return this.comp(e)>=0},LongPrototype.gte=LongPrototype.greaterThanOrEqual,LongPrototype.ge=LongPrototype.greaterThanOrEqual,LongPrototype.compare=function(e){if(isLong(e)||(e=fromValue(e)),this.eq(e))return 0;var t=this.isNegative(),r=e.isNegative();return t&&!r?-1:!t&&r?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1},LongPrototype.comp=LongPrototype.compare,LongPrototype.negate=function(){return!this.unsigned&&this.eq(MIN_VALUE)?MIN_VALUE:this.not().add(ONE)},LongPrototype.neg=LongPrototype.negate,LongPrototype.add=function(e){isLong(e)||(e=fromValue(e));var t=this.high>>>16,r=65535&this.high,n=this.low>>>16,i=65535&this.low,o=e.high>>>16,a=65535&e.high,s=e.low>>>16,c=0,u=0,l=0,d=0;return l+=(d+=i+(65535&e.low))>>>16,u+=(l+=n+s)>>>16,c+=(u+=r+a)>>>16,c+=t+o,fromBits((l&=65535)<<16|(d&=65535),(c&=65535)<<16|(u&=65535),this.unsigned)},LongPrototype.subtract=function(e){return isLong(e)||(e=fromValue(e)),this.add(e.neg())},LongPrototype.sub=LongPrototype.subtract,LongPrototype.multiply=function(e){if(this.isZero())return this;if(isLong(e)||(e=fromValue(e)),wasm)return fromBits(wasm.mul(this.low,this.high,e.low,e.high),wasm.get_high(),this.unsigned);if(e.isZero())return this.unsigned?UZERO:ZERO;if(this.eq(MIN_VALUE))return e.isOdd()?MIN_VALUE:ZERO;if(e.eq(MIN_VALUE))return this.isOdd()?MIN_VALUE:ZERO;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(TWO_PWR_24)&&e.lt(TWO_PWR_24))return fromNumber(this.toNumber()*e.toNumber(),this.unsigned);var t=this.high>>>16,r=65535&this.high,n=this.low>>>16,i=65535&this.low,o=e.high>>>16,a=65535&e.high,s=e.low>>>16,c=65535&e.low,u=0,l=0,d=0,p=0;return d+=(p+=i*c)>>>16,l+=(d+=n*c)>>>16,d&=65535,l+=(d+=i*s)>>>16,u+=(l+=r*c)>>>16,l&=65535,u+=(l+=n*s)>>>16,l&=65535,u+=(l+=i*a)>>>16,u+=t*c+r*s+n*a+i*o,fromBits((d&=65535)<<16|(p&=65535),(u&=65535)<<16|(l&=65535),this.unsigned)},LongPrototype.mul=LongPrototype.multiply,LongPrototype.divide=function(e){if(isLong(e)||(e=fromValue(e)),e.isZero())throw Error("division by zero");var t,r,n;if(wasm)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?fromBits((this.unsigned?wasm.div_u:wasm.div_s)(this.low,this.high,e.low,e.high),wasm.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?UZERO:ZERO;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return UZERO;if(e.gt(this.shru(1)))return UONE;n=UZERO}else{if(this.eq(MIN_VALUE))return e.eq(ONE)||e.eq(NEG_ONE)?MIN_VALUE:e.eq(MIN_VALUE)?ONE:(t=this.shr(1).div(e).shl(1)).eq(ZERO)?e.isNegative()?ONE:NEG_ONE:(r=this.sub(e.mul(t)),n=t.add(r.div(e)));if(e.eq(MIN_VALUE))return this.unsigned?UZERO:ZERO;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();n=ZERO}for(r=this;r.gte(e);){t=Math.max(1,Math.floor(r.toNumber()/e.toNumber()));for(var i=Math.ceil(Math.log(t)/Math.LN2),o=i<=48?1:pow_dbl(2,i-48),a=fromNumber(t),s=a.mul(e);s.isNegative()||s.gt(r);)s=(a=fromNumber(t-=o,this.unsigned)).mul(e);a.isZero()&&(a=ONE),n=n.add(a),r=r.sub(s)}return n},LongPrototype.div=LongPrototype.divide,LongPrototype.modulo=function(e){return isLong(e)||(e=fromValue(e)),wasm?fromBits((this.unsigned?wasm.rem_u:wasm.rem_s)(this.low,this.high,e.low,e.high),wasm.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},LongPrototype.mod=LongPrototype.modulo,LongPrototype.rem=LongPrototype.modulo,LongPrototype.not=function(){return fromBits(~this.low,~this.high,this.unsigned)},LongPrototype.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32},LongPrototype.clz=LongPrototype.countLeadingZeros,LongPrototype.countTrailingZeros=function(){return this.low?ctz32(this.low):ctz32(this.high)+32},LongPrototype.ctz=LongPrototype.countTrailingZeros,LongPrototype.and=function(e){return isLong(e)||(e=fromValue(e)),fromBits(this.low&e.low,this.high&e.high,this.unsigned)},LongPrototype.or=function(e){return isLong(e)||(e=fromValue(e)),fromBits(this.low|e.low,this.high|e.high,this.unsigned)},LongPrototype.xor=function(e){return isLong(e)||(e=fromValue(e)),fromBits(this.low^e.low,this.high^e.high,this.unsigned)},LongPrototype.shiftLeft=function(e){return isLong(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?fromBits(this.low<<e,this.high<<e|this.low>>>32-e,this.unsigned):fromBits(0,this.low<<e-32,this.unsigned)},LongPrototype.shl=LongPrototype.shiftLeft,LongPrototype.shiftRight=function(e){return isLong(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?fromBits(this.low>>>e|this.high<<32-e,this.high>>e,this.unsigned):fromBits(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},LongPrototype.shr=LongPrototype.shiftRight,LongPrototype.shiftRightUnsigned=function(e){return isLong(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?fromBits(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):fromBits(32===e?this.high:this.high>>>e-32,0,this.unsigned)},LongPrototype.shru=LongPrototype.shiftRightUnsigned,LongPrototype.shr_u=LongPrototype.shiftRightUnsigned,LongPrototype.rotateLeft=function(e){var t;return isLong(e)&&(e=e.toInt()),0==(e&=63)?this:32===e?fromBits(this.high,this.low,this.unsigned):e<32?(t=32-e,fromBits(this.low<<e|this.high>>>t,this.high<<e|this.low>>>t,this.unsigned)):(t=32-(e-=32),fromBits(this.high<<e|this.low>>>t,this.low<<e|this.high>>>t,this.unsigned))},LongPrototype.rotl=LongPrototype.rotateLeft,LongPrototype.rotateRight=function(e){var t;return isLong(e)&&(e=e.toInt()),0==(e&=63)?this:32===e?fromBits(this.high,this.low,this.unsigned):e<32?(t=32-e,fromBits(this.high<<t|this.low>>>e,this.low<<t|this.high>>>e,this.unsigned)):(t=32-(e-=32),fromBits(this.low<<t|this.high>>>e,this.high<<t|this.low>>>e,this.unsigned))},LongPrototype.rotr=LongPrototype.rotateRight,LongPrototype.toSigned=function(){return this.unsigned?fromBits(this.low,this.high,!1):this},LongPrototype.toUnsigned=function(){return this.unsigned?this:fromBits(this.low,this.high,!0)},LongPrototype.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},LongPrototype.toBytesLE=function(){var e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]},LongPrototype.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,255&e,t>>>24,t>>>16&255,t>>>8&255,255&t]},Long.fromBytes=function(e,t,r){return r?Long.fromBytesLE(e,t):Long.fromBytesBE(e,t)},Long.fromBytesLE=function(e,t){return new Long(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},Long.fromBytesBE=function(e,t){return new Long(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)},"function"==typeof BigInt&&(Long.fromBigInt=function(e,t){return fromBits(Number(BigInt.asIntN(32,e)),Number(BigInt.asIntN(32,e>>BigInt(32))),t)},Long.fromValue=function(e,t){return"bigint"==typeof e?Long.fromBigInt(e,t):fromValue(e,t)},LongPrototype.toBigInt=function(){var e=BigInt(this.low>>>0);return BigInt(this.unsigned?this.high>>>0:this.high)<<BigInt(32)|e});var L,U={exports:{}},x={exports:{}};(L=x).exports=function(e,t){this.v=e,this.k=t},L.exports.__esModule=!0,L.exports.default=L.exports;var Y=x.exports,q={exports:{}},V={exports:{}};!function(e){function t(r,n,i,o){var a=Object.defineProperty;try{a({},"",{})}catch(r){a=0}e.exports=t=function(e,r,n,i){function o(r,n){t(e,r,function(e){return this._invoke(r,n,e)})}r?a?a(e,r,{value:n,enumerable:!i,configurable:!i,writable:!i}):e[r]=n:(o("next",0),o("throw",1),o("return",2))},e.exports.__esModule=!0,e.exports.default=e.exports,t(r,n,i,o)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}(V);var G=V.exports;!function(e){var t=G;function r(){
12
12
  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */
13
- var n,i,o="function"==typeof Symbol?Symbol:{},a=o.iterator||"@@iterator",s=o.toStringTag||"@@toStringTag";function c(e,r,o,a){var s=r&&r.prototype instanceof l?r:l,c=Object.create(s.prototype);return t(c,"_invoke",function(e,t,r){var o,a,s,c=0,l=r||[],d=!1,p={p:0,n:0,v:n,a:f,f:f.bind(n,4),d:function(e,t){return o=e,a=0,s=n,p.n=t,u}};function f(e,t){for(a=e,s=t,i=0;!d&&c&&!r&&i<l.length;i++){var r,o=l[i],f=p.p,h=o[2];e>3?(r=h===t)&&(s=o[(a=o[4])?5:(a=3,3)],o[4]=o[5]=n):o[0]<=f&&((r=e<2&&f<o[1])?(a=0,p.v=t,p.n=o[1]):f<h&&(r=e<3||o[0]>t||t>h)&&(o[4]=e,o[5]=t,p.n=h,a=0))}if(r||e>1)return u;throw d=!0,t}return function(r,l,h){if(c>1)throw TypeError("Generator is already running");for(d&&1===l&&f(l,h),a=l,s=h;(i=a<2?n:s)||!d;){o||(a?a<3?(a>1&&(p.n=-1),f(a,s)):p.n=s:p.v=s);try{if(c=2,o){if(a||(r="next"),i=o[r]){if(!(i=i.call(o,s)))throw TypeError("iterator result is not an object");if(!i.done)return i;s=i.value,a<2&&(a=0)}else 1===a&&(i=o.return)&&i.call(o),a<2&&(s=TypeError("The iterator does not provide a '"+r+"' method"),a=1);o=n}else if((i=(d=p.n<0)?s:e.call(t,p))!==u)break}catch(e){o=n,a=1,s=e}finally{c=1}}return{value:i,done:d}}}(e,o,a),!0),c}var u={};function l(){}function d(){}function p(){}i=Object.getPrototypeOf;var f=[][a]?i(i([][a]())):(t(i={},a,function(){return this}),i),h=p.prototype=l.prototype=Object.create(f);function g(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,p):(e.__proto__=p,t(e,s,"GeneratorFunction")),e.prototype=Object.create(h),e}return d.prototype=p,t(h,"constructor",p),t(p,"constructor",d),d.displayName="GeneratorFunction",t(p,s,"GeneratorFunction"),t(h),t(h,s,"Generator"),t(h,a,function(){return this}),t(h,"toString",function(){return"[object Generator]"}),(e.exports=r=function(){return{w:c,m:g}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}(q);var J=q.exports,B={exports:{}},F={exports:{}},K={exports:{}};!function(e){var t=Y,r=G;e.exports=function e(n,i){function o(e,r,a,s){try{var c=n[e](r),u=c.value;return u instanceof t?i.resolve(u.v).then(function(e){o("next",e,a,s)},function(e){o("throw",e,a,s)}):i.resolve(u).then(function(e){c.value=e,a(c)},function(e){return o("throw",e,a,s)})}catch(e){s(e)}}var a;this.next||(r(e.prototype),r(e.prototype,"function"==typeof Symbol&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),r(this,"_invoke",function(e,t,r){function n(){return new i(function(t,n){o(e,r,t,n)})}return a=a?a.then(n,n):n()},!0)},e.exports.__esModule=!0,e.exports.default=e.exports}(K);var H=K.exports;!function(e){var t=J,r=H;e.exports=function(e,n,i,o,a){return new r(t().w(e,n,i,o),a||Promise)},e.exports.__esModule=!0,e.exports.default=e.exports}(F);var W=F.exports;!function(e){var t=W;e.exports=function(e,r,n,i,o){var a=t(e,r,n,i,o);return a.next().then(function(e){return e.done?e.value:a.next()})},e.exports.__esModule=!0,e.exports.default=e.exports}(B);var Q=B.exports,Z={exports:{}};!function(e){e.exports=function(e){var t=Object(e),r=[];for(var n in t)r.unshift(n);return function e(){for(;r.length;)if((n=r.pop())in t)return e.value=n,e.done=!1,e;return e.done=!0,e}},e.exports.__esModule=!0,e.exports.default=e.exports}(Z);var z=Z.exports,$={exports:{}},X={exports:{}};!function(e){function t(r){return e.exports=t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e.exports.__esModule=!0,e.exports.default=e.exports,t(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}(X);var ee=X.exports;!function(e){var t=ee.default;e.exports=function(e){if(null!=e){var r=e["function"==typeof Symbol&&Symbol.iterator||"@@iterator"],n=0;if(r)return r.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length))return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}}}throw new TypeError(t(e)+" is not iterable")},e.exports.__esModule=!0,e.exports.default=e.exports}($);var te=$.exports;!function(e){var t=Y,r=J,n=Q,i=W,o=H,a=z,s=te;function c(){var u=r(),l=u.m(c),d=(Object.getPrototypeOf?Object.getPrototypeOf(l):l.__proto__).constructor;function p(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===d||"GeneratorFunction"===(t.displayName||t.name))}var f={throw:1,return:2,break:3,continue:3};function h(e){var t,r;return function(n){t||(t={stop:function(){return r(n.a,2)},catch:function(){return n.v},abrupt:function(e,t){return r(n.a,f[e],t)},delegateYield:function(e,i,o){return t.resultName=i,r(n.d,s(e),o)},finish:function(e){return r(n.f,e)}},r=function(e,r,i){n.p=t.prev,n.n=t.next;try{return e(r,i)}finally{t.next=n.n}}),t.resultName&&(t[t.resultName]=n.v,t.resultName=void 0),t.sent=n.v,t.next=n.n;try{return e.call(this,t)}finally{n.p=t.prev,n.n=t.next}}}return(e.exports=c=function(){return{wrap:function(e,t,r,n){return u.w(h(e),t,r,n&&n.reverse())},isGeneratorFunction:p,mark:u.m,awrap:function(e,r){return new t(e,r)},AsyncIterator:o,async:function(e,t,r,o,a){return(p(t)?i:n)(h(e),t,r,o,a)},keys:a,values:s}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=c,e.exports.__esModule=!0,e.exports.default=e.exports}(U);var ne=(0,U.exports)(),ie=ne;try{regeneratorRuntime=ne}catch(e){"object"==typeof globalThis?globalThis.regeneratorRuntime=ne:Function("r","regeneratorRuntime = r")(ne)}var re,oe,se,ae,de,ce,pe=A(ie);!function(e){var t;(t=e.Result||(e.Result={}))[t.Ok=0]="Ok",t[t.Error=1]="Error"}(re||(re={})),function(e){var t;(t=e.Type||(e.Type={}))[t.kUnknown=0]="kUnknown",t[t.kConnectReq=1]="kConnectReq",t[t.kConnectResp=2]="kConnectResp",t[t.kDisconnect=3]="kDisconnect",t[t.kChannelCreated=4]="kChannelCreated",t[t.kChannelClosed=5]="kChannelClosed",t[t.kPing=6]="kPing",t[t.kPong=7]="kPong",t[t.kData=64]="kData"}(oe||(oe={})),function(e){var t;(t=e.MessageType||(e.MessageType={}))[t.TYPE_UNKNOWN=0]="TYPE_UNKNOWN",t[t.TYPE_NODE_JOIN=1]="TYPE_NODE_JOIN",t[t.TYPE_NODE_JOIN_CONFIRM=2]="TYPE_NODE_JOIN_CONFIRM",t[t.TYPE_NODE_LEFT=3]="TYPE_NODE_LEFT",t[t.TYPE_ATTACH_USER_CONFIRM=4]="TYPE_ATTACH_USER_CONFIRM",t[t.TYPE_DETACH_USER_CONFIRM=5]="TYPE_DETACH_USER_CONFIRM",t[t.TYPE_NODE_MAP_UPDATE=6]="TYPE_NODE_MAP_UPDATE",t[t.TYPE_CREATE_SESSION=7]="TYPE_CREATE_SESSION",t[t.TYPE_CREATE_SESSION_CONFIRM=8]="TYPE_CREATE_SESSION_CONFIRM",t[t.TYPE_SESSION_CREATED=9]="TYPE_SESSION_CREATED",t[t.TYPE_JOIN_SESSION=10]="TYPE_JOIN_SESSION",t[t.TYPE_JOIN_SESSION_CONFIRM=11]="TYPE_JOIN_SESSION_CONFIRM",t[t.TYPE_LEAVE_SESSION=12]="TYPE_LEAVE_SESSION",t[t.TYPE_LEAVE_SESSION_CONFIRM=13]="TYPE_LEAVE_SESSION_CONFIRM",t[t.TYPE_CLOSE_SESSION=14]="TYPE_CLOSE_SESSION",t[t.TYPE_CLOSE_SESSION_CONFIRM=15]="TYPE_CLOSE_SESSION_CONFIRM",t[t.TYPE_SESSION_CLOSED=16]="TYPE_SESSION_CLOSED",t[t.TYPE_SESSION_CMD_DATA=17]="TYPE_SESSION_CMD_DATA",t[t.TYPE_SESSION_CMD_DATA_CONFIRM=18]="TYPE_SESSION_CMD_DATA_CONFIRM",t[t.TYPE_SESSION_CMD_DATA_NOTIFICATION=19]="TYPE_SESSION_CMD_DATA_NOTIFICATION",t[t.TYPE_SESSION_DATA=20]="TYPE_SESSION_DATA",t[t.TYPE_NODE_MAP_SNAPSHOT=21]="TYPE_NODE_MAP_SNAPSHOT",t[t.TYPE_CLOSE_SWITCHER=22]="TYPE_CLOSE_SWITCHER",t[t.TYPE_KICK_USER=23]="TYPE_KICK_USER",t[t.TYPE_JOIN_GROUP=24]="TYPE_JOIN_GROUP",t[t.TYPE_JOIN_GROUP_CONFIRM=25]="TYPE_JOIN_GROUP_CONFIRM",t[t.TYPE_LEAVE_GROUP=26]="TYPE_LEAVE_GROUP",t[t.TYPE_LEAVE_GROUP_CONFIRM=27]="TYPE_LEAVE_GROUP_CONFIRM",t[t.TYPE_GROUP_CREATED=28]="TYPE_GROUP_CREATED",t[t.TYPE_GROUP_DESTROYED=29]="TYPE_GROUP_DESTROYED",t[t.TYPE_GROUP_STATUS=30]="TYPE_GROUP_STATUS",t[t.TYPE_SWITCHER_UPDATE=31]="TYPE_SWITCHER_UPDATE",t[t.TYPE_SERVICE_STATUS=32]="TYPE_SERVICE_STATUS",t[t.TYPE_SESSION_SYNC_REQUEST=33]="TYPE_SESSION_SYNC_REQUEST"}(se||(se={})),function(e){var t;(t=e.RpcType||(e.RpcType={}))[t.Req=0]="Req",t[t.Resp=1]="Resp"}(ae||(ae={})),function(e){var t,r,n;(t=e.MessageType||(e.MessageType={}))[t.AuthType=0]="AuthType",t[t.AuthResponseType=1]="AuthResponseType",t[t.ChannelBindType=2]="ChannelBindType",t[t.ChannelBindResponseType=3]="ChannelBindResponseType",t[t.KeepaliveType=4]="KeepaliveType",t[t.KeepaliveResponseType=5]="KeepaliveResponseType",t[t.ChannelDataType=6]="ChannelDataType",t[t.ReAuthType=7]="ReAuthType",t[t.ReAuthResponseType=8]="ReAuthResponseType",t[t.RefreshTicketType=9]="RefreshTicketType",t[t.RefreshTicketResponseType=10]="RefreshTicketResponseType",t[t.ServerRequestType=11]="ServerRequestType",t[t.ChannelUnBindType=12]="ChannelUnBindType",t[t.ChannelUnBindResponseType=13]="ChannelUnBindResponseType",t[t.RpcProxyRequestType=14]="RpcProxyRequestType",t[t.RpcProxyResponseType=15]="RpcProxyResponseType",function(e){e[e.Ok=0]="Ok",e[e.Error=1]="Error",e[e.ErrorLogin=2]="ErrorLogin",e[e.ErrorDSInternal=3]="ErrorDSInternal"}(e.ErrorCode||(e.ErrorCode={})),(r=e.AuthErrorMsg||(e.AuthErrorMsg={}))[r.SignatureInvalid=0]="SignatureInvalid",r[r.Expired=1]="Expired",r[r.Unavailable=2]="Unavailable",function(e){e[e.MessageChannel=0]="MessageChannel",e[e.PortalChannel=1]="PortalChannel",e[e.DataSwitcherChannel=2]="DataSwitcherChannel"}(e.ChannelType||(e.ChannelType={})),(n=e.ServerEvent||(e.ServerEvent={}))[n.RejoinRequest=0]="RejoinRequest",n[n.ReauthRequest=1]="ReauthRequest"}(de||(de={}));var le="https://gslb.dingrtc.com",ue=1e4,ye=2e3,he=function(e,t,r){return{protocol:"1.0",configJsonStr:JSON.stringify({needPersonalityAudioStream:!0,outPeerConnectionNotReuse:!0,enable_sys_audio:0,mute_audio_record:r}),userAgent:{sdk:{version:e,type:"JavaScript",scene:t},runtime:{name:Environment.browserType,version:Environment.browserVersion},os:{name:Environment.system,version:Environment.systemVersion}}}},fe="TopServer",ve={confirmTypes:[se.MessageType.TYPE_ATTACH_USER_CONFIRM,se.MessageType.TYPE_JOIN_SESSION_CONFIRM,se.MessageType.TYPE_LEAVE_SESSION_CONFIRM,se.MessageType.TYPE_CLOSE_SESSION_CONFIRM,se.MessageType.TYPE_SESSION_CMD_DATA_CONFIRM,se.MessageType.TYPE_JOIN_GROUP_CONFIRM,se.MessageType.TYPE_LEAVE_GROUP_CONFIRM],rpcTypeKeyMap:R(R(R(R(R(R(R({},se.MessageType.TYPE_JOIN_SESSION,"joinSession"),se.MessageType.TYPE_LEAVE_SESSION,"leaveSession"),se.MessageType.TYPE_CLOSE_SESSION,"closeSession"),se.MessageType.TYPE_SESSION_DATA,"sessionData"),se.MessageType.TYPE_SESSION_CMD_DATA,"sessionCmdData"),se.MessageType.TYPE_JOIN_GROUP,"joinGroup"),se.MessageType.TYPE_LEAVE_GROUP,"leaveGroup"),sendDataTypes:[se.MessageType.TYPE_SESSION_DATA,se.MessageType.TYPE_SESSION_CMD_DATA],msgTypeKeyMap:(ce={},R(R(R(R(R(R(R(R(R(R(ce,se.MessageType.TYPE_JOIN_SESSION_CONFIRM,"joinSessionConfirm"),se.MessageType.TYPE_CLOSE_SESSION_CONFIRM,"closeSessionConfirm"),se.MessageType.TYPE_SESSION_CLOSED,"sessionClosed"),se.MessageType.TYPE_SESSION_CREATED,"sessionCreated"),se.MessageType.TYPE_LEAVE_SESSION_CONFIRM,"leaveSessionConfirm"),se.MessageType.TYPE_SESSION_CMD_DATA_CONFIRM,"sessionCmdDataConfirm"),se.MessageType.TYPE_SESSION_CMD_DATA_NOTIFICATION,"sessionCmdDataNoti"),se.MessageType.TYPE_SESSION_DATA,"sessionData"),se.MessageType.TYPE_ATTACH_USER_CONFIRM,"attachUserConfirm"),se.MessageType.TYPE_DETACH_USER_CONFIRM,"detachUserConfirm"),R(R(R(R(R(R(R(R(R(ce,se.MessageType.TYPE_NODE_MAP_SNAPSHOT,"nodeMapSnapshot"),se.MessageType.TYPE_NODE_MAP_UPDATE,"nodeMapUpdate"),se.MessageType.TYPE_GROUP_CREATED,"groupCreated"),se.MessageType.TYPE_GROUP_DESTROYED,"groupDestroyed"),se.MessageType.TYPE_JOIN_GROUP,"groupStatus"),se.MessageType.TYPE_JOIN_GROUP_CONFIRM,"joinGroupConfirm"),se.MessageType.TYPE_LEAVE_GROUP_CONFIRM,"leaveGroupConfirm"),se.MessageType.TYPE_SERVICE_STATUS,"serviceStatus"),se.MessageType.TYPE_SWITCHER_UPDATE,"switcherUpdate"))},me=getProtobufRoot({options:{syntax:"proto3"},nested:{signal_msg:{nested:{AudioSsrcSpec:{fields:{ssrc:{type:"uint32",id:1},rtxSsrc:{type:"uint32",id:2}}},VideoSsrcSpec:{fields:{ssrc:{type:"uint32",id:1},rtxSsrc:{type:"uint32",id:2},fecSsrc:{type:"uint32",id:3}}},MultiPcAdaptRequestInfo:{fields:{audioSsrcSpec:{rule:"repeated",type:"AudioSsrcSpec",id:1},videoSsrcSpec:{rule:"repeated",type:"VideoSsrcSpec",id:2}}},AudioStreamFormat:{fields:{codec:{type:"string",id:1},sampleRate:{type:"int64",id:2},channelNum:{type:"int64",id:3}}},AudioFormatPreference:{fields:{preferred:{type:"AudioStreamFormat",id:1},optional:{rule:"repeated",type:"AudioStreamFormat",id:2}}},AudioStreamOptional:{fields:{format:{rule:"repeated",type:"AudioStreamFormat",id:1}}},VideoStreamFormat:{fields:{codec:{type:"string",id:1},profile:{type:"string",id:2}}},VideoFormatPreference:{fields:{preferred:{type:"VideoStreamFormat",id:1},optional:{rule:"repeated",type:"VideoStreamFormat",id:2}}},FormatPreference:{fields:{audio:{type:"AudioFormatPreference",id:1},video:{type:"VideoFormatPreference",id:2}}},Resolution:{fields:{width:{type:"uint32",id:1},height:{type:"uint32",id:2}}},VideoSsrcParameters:{fields:{ssrc:{type:"uint32",id:1},framerate:{type:"int32",id:2},resolution:{type:"Resolution",id:3},maxBitrate:{type:"int32",id:4},minBitrate:{type:"int32",id:5},active:{type:"bool",id:6},bitrate:{type:"int64",id:7},tlayer:{type:"int64",id:8},multiSlice:{type:"int64",id:9},keyFrameInterval:{type:"int64",id:10},constantPpsid:{type:"int64",id:11}}},VideoParameters:{oneofs:{_resolutionLevel:{oneof:["resolutionLevel"]}},fields:{ssrc:{type:"uint32",id:1},resolution:{type:"Resolution",id:2},framerate:{type:"int32",id:3},bitrate:{type:"string",id:4},multiSlice:{type:"int32",id:5},keyFrameInterval:{type:"int64",id:6},constantPpsid:{type:"int64",id:7},resolutionLevel:{type:"uint32",id:8,options:{proto3_optional:!0}}}},GroupVersion:{fields:{id:{type:"string",id:1},ver:{type:"int64",id:2}}},StreamInfo:{fields:{type:{type:"string",id:1},owner:{type:"string",id:2},attributesJsonStr:{type:"string",id:3},label:{type:"string",id:4},createTime:{type:"int64",id:7}}},StreamVideoParameters:{fields:{resolution:{type:"Resolution",id:1},framerate:{type:"int64",id:2},bitrate:{type:"int64",id:3},keyFrameInterval:{type:"int64",id:4},multiSlice:{type:"int64",id:5},constantPpsid:{type:"int64",id:6}}},VideoStreamPara:{fields:{specs:{rule:"repeated",type:"string",id:1},resolution:{rule:"repeated",type:"Resolution",id:2},framerate:{rule:"repeated",type:"int32",id:3},bitrate:{rule:"repeated",type:"string",id:4},keyFrameInterval:{rule:"repeated",type:"int32",id:5}}},VideoStreamOptional:{fields:{format:{rule:"repeated",type:"VideoStreamFormat",id:1},parameters:{type:"VideoStreamPara",id:2}}},StreamAudioDesc:{fields:{trackId:{type:"string",id:1},msid:{type:"string",id:2},status:{type:"string",id:3},format:{type:"AudioStreamFormat",id:4},source:{type:"string",id:5},ssrc:{rule:"repeated",type:"uint32",id:6},ssrcGroup:{rule:"repeated",type:"AudioSsrcSpec",id:7},optional:{type:"AudioStreamOptional",id:8}}},StreamVideoDesc:{fields:{trackId:{type:"string",id:1},msid:{type:"string",id:2},status:{type:"string",id:3},source:{type:"string",id:4},format:{type:"VideoStreamFormat",id:5},ssrc:{rule:"repeated",type:"uint32",id:6},ssrcGroup:{rule:"repeated",type:"VideoSsrcSpec",id:7},parameters:{type:"StreamVideoParameters",id:8},optional:{type:"VideoStreamOptional",id:9},highestResolutionLevel:{type:"int32",id:10}}},StreamMediaDesc:{fields:{audio:{type:"StreamAudioDesc",id:1},video:{type:"StreamVideoDesc",id:2}}},Stream:{fields:{id:{type:"string",id:1},type:{type:"string",id:2},media:{type:"StreamMediaDesc",id:3},info:{type:"StreamInfo",id:4},version:{type:"int64",id:5}}},OriginMsg:{fields:{type:{type:"string",id:1},id:{type:"string",id:2}}},ErrorMsg:{fields:{id:{type:"string",id:1},code:{type:"int32",id:2},msg:{type:"string",id:3},origin:{type:"OriginMsg",id:4}}},ErrorMsgs:{fields:{globalStatus:{type:"string",id:1},detailStatus:{rule:"repeated",type:"ErrorMsg",id:2}}},Permission:{fields:{audio:{type:"bool",id:1},video:{type:"bool",id:2}}},PermissionInfo:{fields:{subscribe:{type:"Permission",id:1},publish:{type:"Permission",id:2},vip:{type:"bool",id:3}}},ParticipantInfo:{fields:{id:{type:"string",id:1},user:{type:"string",id:2},role:{type:"string",id:3},ver:{type:"int64",id:4},propertiesJsonStr:{type:"string",id:5}}},RoomInfo:{fields:{id:{type:"string",id:1},views:{rule:"repeated",type:"string",id:2},participants:{rule:"repeated",type:"ParticipantInfo",id:3},participantsVer:{type:"int64",id:4},streams:{rule:"repeated",type:"Stream",id:5},streamsVer:{type:"uint64",id:6},conferenceVer:{type:"uint64",id:7},ts:{type:"int64",id:8},audioSelectEnableV1:{type:"bool",id:9},simulcastEnableV1:{type:"bool",id:10},mediaOutVideoParameters:{rule:"repeated",type:"VideoStreamFormat",id:11},propertiesJsonStr:{type:"string",id:12},ssrcClientSequence:{type:"uint32",id:13},ssrcMask:{type:"uint32",id:14},timeLeft:{type:"int64",id:15},groupList:{rule:"repeated",type:"string",id:16},groupListVer:{type:"int64",id:17}}},ParticipantVer:{fields:{id:{type:"string",id:1},ver:{type:"int64",id:2}}},ParticipantDetail:{fields:{id:{type:"string",id:1},user:{type:"string",id:2},role:{type:"string",id:3},ver:{type:"int64",id:4},propertiesJsonStr:{type:"string",id:5},permission:{type:"PermissionInfo",id:6}}},QueryParticipantsData:{fields:{id:{type:"string",id:1},data:{type:"ParticipantDetail",id:2}}},SetPropertiesData:{fields:{id:{type:"string",id:1},ver:{type:"int64",id:2},propertiesJsonStr:{type:"string",id:3}}},Os:{fields:{name:{type:"string",id:1},version:{type:"string",id:2}}},Runtime:{fields:{name:{type:"string",id:1},version:{type:"string",id:2}}},Sdk:{fields:{version:{type:"string",id:1},type:{type:"string",id:2}}},UserAgent:{fields:{os:{type:"Os",id:1},runtime:{type:"Runtime",id:2},sdk:{type:"Sdk",id:3}}},JoinRequest:{fields:{protocol:{type:"string",id:1},token:{type:"string",id:2},userAgent:{type:"UserAgent",id:3},configJsonStr:{type:"string",id:4},tid:{type:"string",id:5},traceId:{type:"string",id:6}}},JoinResponse:{fields:{user:{type:"string",id:1},role:{type:"string",id:2},permission:{type:"PermissionInfo",id:3},room:{type:"RoomInfo",id:4},id:{type:"string",id:5}}},RejoinRequest:{fields:{token:{type:"string",id:1},tid:{type:"string",id:2},traceId:{type:"string",id:3}}},RejoinResponse:{fields:{participantsVer:{type:"int64",id:1},streamsVer:{type:"uint64",id:2}}},LeaveRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},tid:{type:"string",id:3},traceId:{type:"string",id:4}}},QueryParticipantsVerRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},pids:{rule:"repeated",type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},QueryParticipantsVerResponse:{fields:{participants:{rule:"repeated",type:"ParticipantVer",id:1},totalVer:{type:"int64",id:2},msg:{type:"string",id:3}}},QueryParticipantsRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},pids:{rule:"repeated",type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},QueryParticipantsResponse:{fields:{totalVer:{type:"int64",id:1},msg:{type:"string",id:2},participants:{rule:"repeated",type:"QueryParticipantsData",id:3}}},GetParticipantsAndStreamsRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},pids:{rule:"repeated",type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},GetParticipantsAndStreamsResponse:{fields:{ts:{type:"int64",id:1},msg:{type:"string",id:2},participants:{rule:"repeated",type:"ParticipantDetail",id:3},streams:{rule:"repeated",type:"Stream",id:4}}},SetParticipantPropertiesRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},propertiesJsonStr:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},RemoveParticipantPropertiesRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},propertiesJsonStr:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},ParticipantNotification:{oneofs:{data:{oneof:["info","participantId","propertiesData"]}},fields:{action:{type:"string",id:1},totalVer:{type:"int64",id:2},msgId:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5},info:{type:"ParticipantInfo",id:10},participantId:{type:"string",id:11},propertiesData:{type:"SetPropertiesData",id:12}}},SyncNotification:{fields:{streamsVer:{type:"int64",id:1},participantsVer:{type:"int64",id:2},conferenceVer:{type:"int64",id:3},msgId:{type:"string",id:4},tid:{type:"string",id:5},traceId:{type:"string",id:6},groupListVer:{type:"int64",id:7},groupVer:{rule:"repeated",type:"GroupVersion",id:8}}},Result:{values:{Ok:0,Error:1}},Response:{oneofs:{data:{oneof:["reason","joinResponse","queryParticipantsResponse","queryParticipantsVerResponse","rejoinResponse"]}},fields:{result:{type:"Result",id:1},tid:{type:"string",id:2},traceId:{type:"string",id:3},code:{type:"int32",id:4},reason:{type:"string",id:11},joinResponse:{type:"JoinResponse",id:12},queryParticipantsResponse:{type:"QueryParticipantsResponse",id:13},queryParticipantsVerResponse:{type:"QueryParticipantsVerResponse",id:14},rejoinResponse:{type:"RejoinResponse",id:23}}},ConferenceNotification:{fields:{action:{type:"string",id:1},ver:{type:"int64",id:2},id:{type:"string",id:3},msgId:{type:"string",id:4},tid:{type:"string",id:5},traceId:{type:"string",id:6},propertiesJsonStr:{type:"string",id:7}}},DropNotification:{fields:{tid:{type:"string",id:1},traceId:{type:"string",id:2},code:{type:"int32",id:3},reason:{type:"string",id:4}}},NotificationItem:{oneofs:{notification:{oneof:["participantNotification","syncNotification","conferenceNotification"]}},fields:{event:{type:"string",id:1},participantNotification:{type:"ParticipantNotification",id:12},syncNotification:{type:"SyncNotification",id:15},conferenceNotification:{type:"ConferenceNotification",id:16}}},BatchNotification:{fields:{notificationItem:{rule:"repeated",type:"NotificationItem",id:1},tid:{type:"string",id:2},traceId:{type:"string",id:3}}}}},ddmsg:{options:{optimize_for:"LITE_RUNTIME"},nested:{Type:{values:{kUnknown:0,kConnectReq:1,kConnectResp:2,kDisconnect:3,kChannelCreated:4,kChannelClosed:5,kPing:6,kPong:7,kData:64}},Message:{oneofs:{messageOneof:{oneof:["connectReq","connectResp","diconnect","channelsCreated","channelsClosed","data"]}},fields:{msgType:{type:"Type",id:1},connectReq:{type:"ConnectReq",id:2},connectResp:{type:"ConnectResp",id:3},diconnect:{type:"Disconnect",id:4},channelsCreated:{type:"ChannelsCreated",id:5},channelsClosed:{type:"ChannelsClosed",id:6},data:{type:"Data",id:64}}},ServerAddress:{fields:{name:{type:"string",id:1},ip:{type:"string",id:2},port:{type:"uint32",id:3}}},Channel:{fields:{channelId:{type:"uint32",id:1},customizedChannelType:{type:"uint32",id:2},ownerEndpointId:{type:"uint32",id:3}}},ConnectReq:{fields:{parentAddr:{type:"ServerAddress",id:1},topAddr:{type:"ServerAddress",id:2},nodeId:{type:"fixed64",id:3},requestId:{type:"int32",id:4},subdsType:{type:"int32",id:5},reqData:{type:"bytes",id:10}}},ConnectResp:{fields:{result:{type:"int32",id:1},requestId:{type:"int32",id:2},nodeId:{type:"fixed64",id:3},parentNodeId:{type:"fixed64",id:4},topNodeId:{type:"fixed64",id:5},channels:{rule:"repeated",type:"Channel",id:6},respData:{type:"bytes",id:10}}},Disconnect:{fields:{reason:{type:"int32",id:1}}},ChannelsCreated:{fields:{channels:{rule:"repeated",type:"Channel",id:1}}},ChannelsClosed:{fields:{reason:{type:"int32",id:1},channels:{rule:"repeated",type:"Channel",id:2}}},Data:{fields:{priority:{type:"uint32",id:1},uniform:{type:"bool",id:2},echo:{type:"bool",id:3},compressed:{type:"bool",id:4},from:{type:"fixed64",id:5},to:{type:"fixed64",id:6},excludes:{rule:"repeated",type:"fixed64",id:7},data:{type:"bytes",id:10}}}}},dsmsg:{options:{optimize_for:"LITE_RUNTIME"},nested:{MessageType:{values:{TYPE_UNKNOWN:0,TYPE_NODE_JOIN:1,TYPE_NODE_JOIN_CONFIRM:2,TYPE_NODE_LEFT:3,TYPE_ATTACH_USER_CONFIRM:4,TYPE_DETACH_USER_CONFIRM:5,TYPE_NODE_MAP_UPDATE:6,TYPE_CREATE_SESSION:7,TYPE_CREATE_SESSION_CONFIRM:8,TYPE_SESSION_CREATED:9,TYPE_JOIN_SESSION:10,TYPE_JOIN_SESSION_CONFIRM:11,TYPE_LEAVE_SESSION:12,TYPE_LEAVE_SESSION_CONFIRM:13,TYPE_CLOSE_SESSION:14,TYPE_CLOSE_SESSION_CONFIRM:15,TYPE_SESSION_CLOSED:16,TYPE_SESSION_CMD_DATA:17,TYPE_SESSION_CMD_DATA_CONFIRM:18,TYPE_SESSION_CMD_DATA_NOTIFICATION:19,TYPE_SESSION_DATA:20,TYPE_NODE_MAP_SNAPSHOT:21,TYPE_CLOSE_SWITCHER:22,TYPE_KICK_USER:23,TYPE_JOIN_GROUP:24,TYPE_JOIN_GROUP_CONFIRM:25,TYPE_LEAVE_GROUP:26,TYPE_LEAVE_GROUP_CONFIRM:27,TYPE_GROUP_CREATED:28,TYPE_GROUP_DESTROYED:29,TYPE_GROUP_STATUS:30,TYPE_SWITCHER_UPDATE:31,TYPE_SERVICE_STATUS:32,TYPE_SESSION_SYNC_REQUEST:33}},Message:{oneofs:{messageOneof:{oneof:["nodeJoin","nodeJoinConfirm","nodeLeft","attachUserConfirm","detachUserConfirm","nodeMapUpdate","createSession","createSessionConfirm","sessionCreated","joinSession","joinSessionConfirm","leaveSession","leaveSessionConfirm","closeSession","closeSessionConfirm","sessionClosed","sessionCmdData","sessionCmdDataConfirm","sessionCmdDataNoti","sessionData","nodeMapSnapshot","closeSwitcher","kickUser","joinGroup","joinGroupConfirm","leaveGroup","leaveGroupConfirm","groupCreated","groupDestroyed","groupStatus","switcherUpdate","serviceStatus","sessionSyncReq"]}},fields:{version:{type:"int32",id:1},type:{type:"MessageType",id:2},nodeJoin:{type:"NodeJoin",id:3},nodeJoinConfirm:{type:"NodeJoinConfirm",id:4},nodeLeft:{type:"NodeLeft",id:5},attachUserConfirm:{type:"AttachUserConfirm",id:6},detachUserConfirm:{type:"DetachUserConfirm",id:7},nodeMapUpdate:{type:"NodeMapUpdate",id:8},createSession:{type:"CreateSession",id:9},createSessionConfirm:{type:"CreateSessionConfirm",id:10},sessionCreated:{type:"SessionCreated",id:11},joinSession:{type:"JoinSession",id:12},joinSessionConfirm:{type:"JoinSessionConfirm",id:13},leaveSession:{type:"LeaveSession",id:14},leaveSessionConfirm:{type:"LeaveSessionConfirm",id:15},closeSession:{type:"CloseSession",id:16},closeSessionConfirm:{type:"CloseSessionConfirm",id:17},sessionClosed:{type:"SessionClosed",id:18},sessionCmdData:{type:"SessionCmdData",id:19},sessionCmdDataConfirm:{type:"SessionCmdDataConfirm",id:20},sessionCmdDataNoti:{type:"SessionCmdDataNotification",id:21},sessionData:{type:"SessionData",id:22},nodeMapSnapshot:{type:"NodeMapSnapshot",id:23},closeSwitcher:{type:"CloseSwitcher",id:24},kickUser:{type:"KickUser",id:25},joinGroup:{type:"JoinGroup",id:26},joinGroupConfirm:{type:"JoinGroupConfirm",id:27},leaveGroup:{type:"LeaveGroup",id:28},leaveGroupConfirm:{type:"LeaveGroupConfirm",id:29},groupCreated:{type:"GroupCreated",id:30},groupDestroyed:{type:"GroupDestroyed",id:31},groupStatus:{type:"GroupStatus",id:32},switcherUpdate:{type:"SwitcherUpdate",id:33},serviceStatus:{type:"ServiceStatus",id:34},sessionSyncReq:{type:"SessionSyncRequrst",id:35}}},NodeJoin:{fields:{nodeName:{type:"string",id:1},remainingTime:{type:"int32",id:2}}},NodeJoinConfirm:{fields:{nodeName:{type:"string",id:1},channels:{rule:"repeated",type:"Channel",id:2},endpointId:{type:"int32",id:3},sessionCreateds:{rule:"repeated",type:"SessionCreated",id:4},config:{type:"Config",id:5}}},Config:{fields:{nodeInfoBundleSize:{type:"int32",id:1}}},NodeLeft:{fields:{nodeId:{type:"uint64",id:1}}},AttachUserConfirm:{fields:{pid:{type:"string",id:1},nodeId:{type:"uint64",id:2},serverNodeId:{type:"uint64",id:3},topServerNodeId:{type:"uint64",id:4},endpointId:{type:"int32",id:5},result:{type:"uint32",id:6},channels:{rule:"repeated",type:"Channel",id:7},sessionCreateds:{rule:"repeated",type:"SessionCreated",id:8},reason:{type:"uint32",id:9}}},DetachUser:{fields:{pid:{type:"string",id:1},nodeId:{type:"uint64",id:2},reason:{type:"uint32",id:3}}},DetachUserConfirm:{fields:{pid:{type:"string",id:1},nodeId:{type:"uint64",id:2},result:{type:"uint32",id:3}}},NodeMapUpdate:{fields:{items:{rule:"repeated",type:"NodeMapUpdateItem",id:1}}},NodeMapUpdateItem:{fields:{pid:{type:"string",id:1},nodeId:{type:"uint64",id:2},action:{type:"uint32",id:3},uid:{type:"string",id:4},userName:{type:"string",id:5}}},NodeMapSnapshot:{fields:{start:{type:"bool",id:1},end:{type:"bool",id:2},items:{rule:"repeated",type:"NodeMapUpdateItem",id:3}}},NodeMapSnapshotItem:{fields:{pid:{type:"string",id:1},nodeId:{type:"uint64",id:2}}},CreateSession:{fields:{sessionType:{type:"int32",id:1},sessionKey:{type:"string",id:2},customSessionData:{type:"string",id:3}}},CreateSessionConfirm:{fields:{sessionType:{type:"int32",id:1},sessionKey:{type:"string",id:2},endpointId:{type:"int32",id:3},result:{type:"uint32",id:4}}},SessionCreated:{fields:{sessionType:{type:"int32",id:1},sessionKey:{type:"string",id:2},endpointId:{type:"int32",id:3},channels:{rule:"repeated",type:"Channel",id:4},customSessionData:{type:"string",id:5},groupCreated:{rule:"repeated",type:"GroupCreated",id:6}}},JoinSession:{fields:{sessionType:{type:"int32",id:1},sessionKey:{type:"string",id:2},pid:{type:"string",id:3},nodeId:{type:"uint64",id:4},customSessionData:{type:"string",id:5}}},JoinSessionConfirm:{fields:{sessionType:{type:"int32",id:1},sessionKey:{type:"string",id:2},endpointId:{type:"int32",id:3},pid:{type:"string",id:4},nodeId:{type:"uint64",id:5},result:{type:"uint32",id:6},channels:{rule:"repeated",type:"Channel",id:7},customSessionData:{type:"string",id:8}}},LeaveSession:{fields:{sessionType:{type:"int32",id:1},sessionKey:{type:"string",id:2},nodeId:{type:"uint64",id:3}}},LeaveSessionConfirm:{fields:{sessionType:{type:"int32",id:1},sessionKey:{type:"string",id:2},nodeId:{type:"uint64",id:3},result:{type:"uint32",id:4}}},CloseSession:{fields:{sessionType:{type:"int32",id:1},sessionKey:{type:"string",id:2},nodeId:{type:"uint64",id:3}}},CloseSessionConfirm:{fields:{sessionType:{type:"int32",id:1},sessionKey:{type:"string",id:2},result:{type:"uint32",id:3}}},SessionClosed:{fields:{sessionType:{type:"int32",id:1},sessionKey:{type:"string",id:2}}},Channel:{fields:{id:{type:"int32",id:1},type:{type:"uint32",id:2}}},SessionCmdData:{fields:{cmdType:{type:"uint32",id:1},cmd:{type:"string",id:2},requestId:{type:"uint32",id:3},data:{type:"bytes",id:4},broadcast:{type:"bool",id:5},echo:{type:"bool",id:6},toNodeId:{type:"uint64",id:7},fromPid:{type:"string",id:8}}},SessionCmdDataConfirm:{fields:{cmdType:{type:"uint32",id:1},cmd:{type:"string",id:2},requestId:{type:"uint32",id:3},result:{type:"uint32",id:4},fromPid:{type:"string",id:5}}},SessionCmdDataNotification:{fields:{cmdType:{type:"uint32",id:1},cmd:{type:"string",id:2},requestId:{type:"uint32",id:3},data:{type:"bytes",id:4},fromPid:{type:"string",id:5}}},SessionData:{fields:{data:{type:"bytes",id:1}}},CloseSwitcher:{fields:{reason:{type:"uint32",id:1}}},KickUser:{fields:{pid:{type:"string",id:1},nodeId:{type:"uint64",id:2},reason:{type:"uint32",id:3}}},JoinGroup:{fields:{nodeId:{type:"uint64",id:1},groupId:{type:"string",id:2},requestId:{type:"uint32",id:3}}},JoinGroupConfirm:{fields:{nodeId:{type:"uint64",id:1},groupId:{type:"string",id:2},result:{type:"uint32",id:3},channel:{type:"Channel",id:4},requestId:{type:"uint32",id:5}}},LeaveGroup:{fields:{nodeId:{type:"uint64",id:1},groupId:{type:"string",id:2},requestId:{type:"uint32",id:3}}},LeaveGroupConfirm:{fields:{nodeId:{type:"uint64",id:1},groupId:{type:"string",id:2},result:{type:"uint32",id:3},requestId:{type:"uint32",id:4}}},GroupCreated:{fields:{groupId:{type:"string",id:1},channel:{type:"Channel",id:2},status:{type:"int32",id:3}}},GroupDestroyed:{fields:{groupId:{type:"string",id:1}}},GroupStatus:{fields:{groupId:{type:"string",id:1},status:{type:"int32",id:2}}},SwitcherUpdate:{fields:{channelUpdates:{rule:"repeated",type:"ChannelUpdate",id:1}}},ChannelUpdate:{fields:{endpointId:{type:"int32",id:1},groupId:{type:"string",id:2},channel:{type:"Channel",id:3}}},ServiceStatus:{fields:{status:{type:"int32",id:1},data:{type:"string",id:2}}},SessionSyncRequrst:{fields:{nodeId:{type:"uint64",id:1}}}}},rpc:{nested:{RpcType:{values:{Req:0,Resp:1}},RpcMessage:{fields:{Version:{type:"uint32",id:1},MagicNumber:{type:"uint32",id:2},Type:{type:"RpcType",id:3},RpcId:{type:"uint32",id:4},NeedAck:{type:"bool",id:5},Method:{type:"string",id:6},Data:{type:"bytes",id:7}}}}},rtmpproxy:{nested:{CreateRtmpProxyPushRequest:{fields:{appId:{type:"string",id:1},roomId:{type:"string",id:2},streamId:{type:"string",id:3},timestamp:{type:"string",id:4},nonce:{type:"string",id:5},signature:{type:"string",id:6},localInfo:{type:"string",id:7},sdp:{type:"string",id:8},user:{type:"string",id:9},pid:{type:"string",id:10}}},CreateRtmpProxyPushResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}},CreateRtmpProxyPullRequest:{fields:{appId:{type:"string",id:1},roomId:{type:"string",id:2},streamId:{type:"string",id:3},timestamp:{type:"string",id:4},nonce:{type:"string",id:5},signature:{type:"string",id:6},localInfo:{type:"string",id:7},sdp:{type:"string",id:8},user:{type:"string",id:9},pid:{type:"string",id:10}}},CreateRtmpProxyPullResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}}}},transport:{nested:{MessageType:{values:{AuthType:0,AuthResponseType:1,ChannelBindType:2,ChannelBindResponseType:3,KeepaliveType:4,KeepaliveResponseType:5,ChannelDataType:6,ReAuthType:7,ReAuthResponseType:8,RefreshTicketType:9,RefreshTicketResponseType:10,ServerRequestType:11,ChannelUnBindType:12,ChannelUnBindResponseType:13,RpcProxyRequestType:14,RpcProxyResponseType:15}},ErrorCode:{values:{Ok:0,Error:1,ErrorLogin:2,ErrorDSInternal:3}},AuthErrorMsg:{values:{SignatureInvalid:0,Expired:1,Unavailable:2}},PingConfig:{fields:{pingInterval:{type:"uint32",id:1},pingTimeout:{type:"uint32",id:2}}},TransportOptions:{oneofs:{_supportPingConfig:{oneof:["supportPingConfig"]}},fields:{supportReliable:{type:"bool",id:1},reliableId:{type:"string",id:2},supportPingConfig:{type:"bool",id:3,options:{proto3_optional:!0}}}},Auth:{fields:{token:{type:"string",id:1},duplicate:{type:"bool",id:2},options:{type:"TransportOptions",id:3}}},AuthResponse:{fields:{code:{type:"ErrorCode",id:1},reason:{type:"string",id:2},ticket:{type:"string",id:3},errorMsg:{type:"AuthErrorMsg",id:4},pingConfig:{type:"PingConfig",id:5}}},ReAuth:{fields:{id:{type:"string",id:1},ticket:{type:"string",id:2},options:{type:"TransportOptions",id:3}}},ReAuthResponse:{fields:{code:{type:"ErrorCode",id:1},reason:{type:"string",id:2},ticket:{type:"string",id:3},errorMsg:{type:"AuthErrorMsg",id:4},pingConfig:{type:"PingConfig",id:5}}},RefreshTicket:{fields:{}},RefreshTicketResponse:{fields:{code:{type:"ErrorCode",id:1},reason:{type:"string",id:2},ticket:{type:"string",id:3}}},ChannelType:{values:{MessageChannel:0,PortalChannel:1,DataSwitcherChannel:2}},ChannelBind:{fields:{type:{type:"ChannelType",id:1},chanId:{type:"uint64",id:2},address:{type:"string",id:3}}},ChannelBindResponse:{fields:{code:{type:"ErrorCode",id:1},reason:{type:"string",id:2},chanId:{type:"uint64",id:3}}},ChannelUnBind:{fields:{type:{type:"ChannelType",id:1},chanId:{type:"uint64",id:2}}},ChannelUnBindResponse:{fields:{code:{type:"ErrorCode",id:1},reason:{type:"string",id:2},chanId:{type:"uint64",id:3}}},Keepalive:{fields:{sequence:{type:"uint32",id:1},pingMs:{type:"uint64",id:2}}},KeepaliveResponse:{fields:{sequence:{type:"uint32",id:1},pongMs:{type:"uint64",id:2}}},ChannelData:{fields:{chanId:{type:"uint64",id:1},data:{type:"bytes",id:2}}},ServerEvent:{values:{RejoinRequest:0,ReauthRequest:1}},Notification:{fields:{event:{type:"ServerEvent",id:1}}},RpcProxyRequest:{fields:{rpcId:{type:"string",id:1},targetServer:{type:"string",id:2},targetServerSubProcessIndex:{type:"uint64",id:3},rpcMethod:{type:"string",id:4},rpcRequestBody:{type:"bytes",id:5}}},RpcProxyResponse:{fields:{rpcId:{type:"string",id:1},rpcResponseCode:{type:"uint32",id:2},rpcResponseBody:{type:"bytes",id:3}}},Message:{oneofs:{data:{oneof:["auth","authResponse","channelBind","channelBindResponse","keepalive","keepaliveResponse","channelData","reauth","reauthResponse","refreshTicket","refreshTicketResponse","notification","channelUnBind","channelUnBindResponse","rpcProxyRequest","rpcProxyResponse"]}},fields:{Type:{type:"MessageType",id:1},Version:{type:"uint32",id:2},SequenceId:{type:"uint32",id:3},auth:{type:"Auth",id:11},authResponse:{type:"AuthResponse",id:12},channelBind:{type:"ChannelBind",id:13},channelBindResponse:{type:"ChannelBindResponse",id:14},keepalive:{type:"Keepalive",id:15},keepaliveResponse:{type:"KeepaliveResponse",id:16},channelData:{type:"ChannelData",id:17},reauth:{type:"ReAuth",id:18},reauthResponse:{type:"ReAuthResponse",id:19},refreshTicket:{type:"RefreshTicket",id:20},refreshTicketResponse:{type:"RefreshTicketResponse",id:21},notification:{type:"Notification",id:22},channelUnBind:{type:"ChannelUnBind",id:23},channelUnBindResponse:{type:"ChannelUnBindResponse",id:24},rpcProxyRequest:{type:"RpcProxyRequest",id:25},rpcProxyResponse:{type:"RpcProxyResponse",id:26}}}}}}}),be=me.lookupType("signal_msg.Response"),Se=me.lookupType("signal_msg.BatchNotification"),Te=me.lookupType("signal_msg.ParticipantNotification"),Ee=me.lookupType("signal_msg.ConferenceNotification"),Ie=me.lookupType("signal_msg.DropNotification"),Ce=me.lookupType("signal_msg.SyncNotification"),Oe=me.lookupType("signal_msg.RejoinRequest"),Pe=me.lookupType("rtmpproxy.CreateRtmpProxyPushRequest");me.lookupType("rtmpproxy.CreateRtmpProxyPullRequest");var Re=me.lookupType("signal_msg.QueryParticipantsVerRequest"),_e=me.lookupType("signal_msg.QueryParticipantsRequest"),Ne=me.lookupType("signal_msg.JoinRequest"),ke=me.lookupType("transport.Message"),Me=me.lookupType("rpc.RpcMessage"),we=me.lookupType("ddmsg.Message"),De=me.lookupType("dsmsg.Message");function je(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(je=function(){return!!e})()}me.lookupType("ddmsg.Data");var Ae=function(){function e(){var t,r,n;return _(this,e),r=this,n=w(n=e),t=M(r,je()?Reflect.construct(n,[],w(r).constructor):n.apply(r,undefined)),Object.defineProperty(t,"timer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(t,"seconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(t,"gapTime",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(t,"sequence",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(t,"maxTime",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),t.timer=null,t.gapTime=15e3,t.maxTime=6e4,t.seconds=0,t.sequence=0,t}return j(e,EventEmitter),k(e,[{key:"start",value:function(e){var t=this,r=e||{},n=r.pingInterval,i=r.pingTimeout;n&&i&&(this.stop(),this.gapTime=1e3*n,this.maxTime=1e3*i),this.timer||(this.ping(),this.timer=addTimer(function(){if(t.seconds++,1e3*t.seconds%t.gapTime==0&&t.ping(),1e3*t.seconds>t.maxTime)throw t.stop(),t.emit("retry"),new DingRTCError(ErrorCode.ConnectionHeartbeatTimeout)},1e3,"interval"))}},{key:"ping",value:function(){var e={sequence:++this.sequence,pingMs:Date.now()};this.emit("ping",{keepalive:e})}},{key:"pong",value:function(e){this.sequence=e.sequence,this.seconds=0}},{key:"stop",value:function(){this.timer&&(removeTimer(this.timer,"interval"),this.timer=null,this.sequence=0,this.seconds=0)}}])}();function Le(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(Le=function(){return!!e})()}var Ue,xe,Ye,qe,Ve,Ge,Je,Be=function(){function e(t,r){var n,i,o;return _(this,e),i=this,o=w(o=e),n=M(i,Le()?Reflect.construct(o,[],w(i).constructor):o.apply(i,undefined)),Object.defineProperty(n,"socket",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(n,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(n,"rpcId",{enumerable:!0,configurable:!0,writable:!0,value:20}),Object.defineProperty(n,"requestMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"proxyReqMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"domain",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),n.socket=t,n.reporter=r,n.logger=n.reporter.getLoggerWithPrefix("[chn-basictrans]"),n.requestMap=new Map,n.proxyReqMap=new Map,n}return j(e,EventEmitter),k(e,[{key:"connect",value:function(e,t){var r=this,n=JSON.parse(fromBase64(e)),i=n.secure,o=n.relayServerHosts,a=void 0===o?[]:o;return a[0]&&(this.domain=a[0]),new Promise(function(n,o){var s=(i?"wss":"ws")+"://"+(a[0]||r.domain);r.socket.removeAllListeners(),r.socket.init(s,e,t),r.socket.on("reauth",function(){r.emit("reauth")}),r.socket.on("rejoin",function(){r.emit("rejoin")}),r.socket.on("connection-state-change",function(e,t,i){r.emit("connection-state-change",e,t,i),"disconnected"===e?o(i):"connected"===e&&n()})})}},{key:"disconnect",value:function(){var e;if(this.requestMap.clear(),null!==(e=this.socket)&&void 0!==e&&e.instance&&"disconnected"!==this.socket.state)return this.socket.close(!0)}},{key:"sendChnData",value:function(e,t){var r=this,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,i=arguments.length>3&&void 0!==arguments[3]&&arguments[3],o={MagicNumber:5,Version:1,Type:0,NeedAck:!0,RpcId:this.rpcId++,Method:e,Data:t},a=Me.encode(o).finish();return i&&this.logger.debug("rpcId ".concat(o.RpcId,":").concat(e," param====> ").concat(JSON.stringify(n||""))),new Promise(function(t,s){r.socket.send(de.MessageType.ChannelDataType,{channelData:{data:a,chanId:1}},o.RpcId,e);var c=o.RpcId;r.requestMap.set(c,{resolve:t,reject:s,payload:{methond:e,internal:i,rpcId:c,param:n||""}}),addTimer(function(){var t=r.requestMap.get(c);null!=t&&t.reject&&(t.reject(new DingRTCError(ErrorCode.APICallTimeOut,"".concat(e," timeout"))),r.requestMap.delete(c))},ue)})}},{key:"proxyRtmpReq",value:function(e,t,r,n){var i=this;this.logger.info("rpcRequestBody===",n);var o=Pe.encode(n).finish();return new Promise(function(n,a){var s=e||createUuid(10);i.socket.send(de.MessageType.RpcProxyRequestType,{rpcProxyRequest:{rpcId:s,targetServer:t,targetServerSubProcessIndex:0,rpcMethod:r,rpcRequestBody:o}}),i.proxyReqMap.set(e,{resolve:n,reject:a}),addTimer(function(){var t=i.proxyReqMap.get(e);null!=t&&t.reject&&(t.reject(new DingRTCError(ErrorCode.APICallTimeOut,"proxyRtmpReq timeout ".concat(r," ").concat(e))),i.proxyReqMap.delete(e))},ue)})}},{key:"onProxyRtmpResponseMsg",value:function(e){var t=this.proxyReqMap.get(e.rpcProxyResponse.rpcId);e.rpcProxyResponse.rpcResponseCode?null==t||t.reject(e.rpcProxyResponse.rpcResponseCode):null==t||t.resolve(e.rpcProxyResponse.rpcResponseBody)}},{key:"handleNotification",value:function(e,t){var r=this;if("batch-notify"===e){var n=Se.decode(t).notificationItem,i=["participant","conference","sync"];n.forEach(function(e){"participant"===e.event?r.emit("participant",e.participantNotification):"conference"===e.event?r.emit("conference",e.conferenceNotification):"sync"===e.event&&r.emit("sync",e.syncNotification)}),n.filter(function(e){return!i.includes(e.event)}).length&&this.emit("batch-notify",t)}else"participant"===e?this.emit("participant",Te.decode(t)):"conference"===e?this.emit("conference",Ee.decode(t)):"drop"===e?this.emit("drop",Ie.decode(t)):"sync"===e?this.emit("sync",Ce.decode(t)):this.emit("notify",e,t)}},{key:"onMessage",value:function(e){var t=Me.decode(new Uint8Array(e.channelData.data));if(t.Type===ae.RpcType.Resp){var r=this.requestMap.get(t.RpcId);if(!r)return;var n=r.resolve,i=r.reject,o=r.payload;if(o.internal){var a=be.decode(t.Data);a.result===re.Result.Ok?(this.logger.debug("rpcId ".concat(o.rpcId,": ").concat(o.methond," result====> ").concat(JSON.stringify(a))),n(a)):(this.logger.error("rpcId ".concat(o.rpcId,": ").concat(o.methond," error====> ").concat(JSON.stringify(a))),i(a))}else n(t.Data);this.requestMap.delete(t.RpcId)}else t.Type===ae.RpcType.Req&&this.handleNotification(t.Method,t.Data)}}])}();!function(e){e[e.UserKickOut=2011]="UserKickOut",e[e.UserReplaced=2012]="UserReplaced"}(Ue||(Ue={})),function(e){e[e.Unknown=0]="Unknown",e[e.SubtopDS=1]="SubtopDS",e[e.Linkserver=2]="Linkserver",e[e.Vmixer=3]="Vmixer",e[e.Minutes=4]="Minutes"}(xe||(xe={})),function(e){e[e.UnknownId=0]="UnknownId",e[e.ControlNodeId=1]="ControlNodeId",e[e.TerminalNodeId=2]="TerminalNodeId",e[e.ChannelId=3]="ChannelId"}(Ye||(Ye={})),function(e){e[e.NORMAL_ATTACH=0]="NORMAL_ATTACH",e[e.FORCE_REATTACH=1]="FORCE_REATTACH",e[e.RESYNC=2]="RESYNC"}(qe||(qe={})),function(e){e[e.NODE_JOIN=0]="NODE_JOIN",e[e.NODE_LEAVE=1]="NODE_LEAVE"}(Ve||(Ve={})),function(e){e[e.High=0]="High",e[e.Normal=1]="Normal",e[e.Low=2]="Low"}(Ge||(Ge={})),function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.DEFAULT=1]="DEFAULT",e[e.NODE_MAP=2]="NODE_MAP"}(Je||(Je={}));var Fe=function(e){return"number"==typeof e?Long.fromNumber(e,!0):new Long(e.low,e.high,e.unsigned)},Ke=function(){function e(){_(this,e)}return k(e,null,[{key:"isValidId",value:function(t){var r=Fe(t);if(r.and(e.ChannelMaskLong.not()).eq(Long.ZERO))return!0;var n=r.and(e.NodeTypeMaskLong).eq(e.NodeTypeMaskLong),i=r.and(e.TerminalMaskLong).eq(Long.ZERO);if(!n&&i||n&&!i)return!1;var o=r.and(e.UseCtrlL1MaskLong).eq(e.UseCtrlL1MaskLong),a=r.and(e.CtrlLayer1MaskLong).eq(Long.ZERO);return!(o&&a||!o&&!a)}},{key:"getIdType",value:function(t){var r=Fe(t);return r.and(e.ChannelMaskLong).eq(r)?Ye.ChannelId:e.isValidId(t)?r.and(e.NodeTypeMaskLong).eq(e.NodeTypeMaskLong)?Ye.ControlNodeId:Ye.TerminalNodeId:Ye.UnknownId}},{key:"replaceClusterId",value:function(t,r){return t.and(e.ClusterIdMaskLong.not()).or(Long.fromNumber(r).shiftLeft(42))}},{key:"getTopNodeId",value:function(t){return(4095&t)<<42|e.NodeTypeMask}},{key:"extractParentNodeId",value:function(t,r){var n=Fe(t);if(!this.isValidId(n)||this.isTopControlNode(n))return Long.ZERO;var i=n.and(e.EndpointMaskLong),o=n.and(e.NodeTypeMaskLong).equals(e.NodeTypeMaskLong),a=n.and(e.UseCtrlL1MaskLong).equals(e.UseCtrlL1MaskLong);if(o&&a||!o&&!a){var s=e.replaceClusterId(e.NodeTypeMaskLong.or(e.CtrlLayer0MaskLong.or(e.SubDsMaskLong).and(n)),r).or(i);return o&&a?s.and(e.SubDsMaskLong.not()).or(Long.fromNumber((15&xe.SubtopDS)<<54)):s}return o&&!a?e.replaceClusterId(Long.fromNumber(e.NodeTypeMask),r).or(i).and(e.SubDsMaskLong.not()):!o&&a?e.replaceClusterId(e.NodeTypeMaskLong.or(e.UseCtrlL1MaskLong).or(e.CtrlLayer0MaskLong).or(e.CtrlLayer1MaskLong.or(e.CtrlLayer1MaskLong).or(e.SubDsMaskLong)).and(n),r).or(i):0}},{key:"extractNodeIdWithoutClusterId",value:function(t){var r=e.EndpointMaskLong.or(e.ClusterIdMaskLong).or(e.ReservedMaskLong).or(e.SubDsMask);return Fe(t).and(r.not())}},{key:"isTopControlNode",value:function(t){var r=Fe(t);return r.and(e.NodeTypeMaskLong).equals(e.NodeTypeMaskLong)&&r.and(e.UseCtrlL1MaskLong).or(e.CtrlLayer0MaskLong).or(e.CtrlLayer1MaskLong).or(e.TerminalMaskLong)}},{key:"isDirectChild",value:function(t,r){if(0==(r&e.NodeTypeMask))return!1;var n=t&(e.CtrlLayer0Mask|e.CtrlLayer1Mask|e.TerminalMask),i=r&(e.CtrlLayer0Mask|e.CtrlLayer1Mask|e.TerminalMask);return n!=r&&0!=t&&(i==(n&(e.CtrlLayer0Mask|e.CtrlLayer1Mask))||i==(n&e.CtrlLayer0Mask)&&0==(n&~(e.CtrlLayer0Mask|e.CtrlLayer1Mask))||0==i&&0==(t&~e.CtrlLayer0Mask))}},{key:"isChild",value:function(t,r){if(0==(r&e.NodeTypeMask))return!1;var n=t&(e.CtrlLayer0Mask|e.CtrlLayer1Mask|e.TerminalMask),i=r&(e.CtrlLayer0Mask|e.CtrlLayer1Mask|e.TerminalMask);return n!==i&&0!==n&&(0===i||r==(n&(e.CtrlLayer0Mask|e.CtrlLayer1Mask))||i==(n&e.CtrlLayer0Mask))}},{key:"isMe",value:function(t,r){if(!this.isValidId(t)||!this.isValidId(r))return!1;var n=e.EndpointMaskLong.or(e.ClusterIdMask).or(e.ReservedMaskLong);return Fe(t).and(n.not()).eq(Fe(r).and(n.not()))}},{key:"extractEndpointId",value:function(t){return Fe(t).and(e.EndpointMaskLong).toNumber()}},{key:"composeId",value:function(t,r){return Fe(t).and(e.EndpointMaskLong.not()).or(Fe(r))}},{key:"extractNodeId",value:function(t){return Fe(t).and(e.EndpointMaskLong.not())}}])}();function He(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function We(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?He(Object(r),!0).forEach(function(t){R(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):He(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function Qe(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(Qe=function(){return!!e})()}Object.defineProperty(Ke,"ReservedMask",{enumerable:!0,configurable:!0,writable:!0,value:63<<58}),Object.defineProperty(Ke,"SubDsMask",{enumerable:!0,configurable:!0,writable:!0,value:15<<54}),Object.defineProperty(Ke,"ClusterIdMask",{enumerable:!0,configurable:!0,writable:!0,value:4193280}),Object.defineProperty(Ke,"NodeTypeMask",{enumerable:!0,configurable:!0,writable:!0,value:512}),Object.defineProperty(Ke,"UseCtrlL1Mask",{enumerable:!0,configurable:!0,writable:!0,value:256}),Object.defineProperty(Ke,"CtrlLayer0Mask",{enumerable:!0,configurable:!0,writable:!0,value:1023<<30}),Object.defineProperty(Ke,"CtrlLayer1Mask",{enumerable:!0,configurable:!0,writable:!0,value:1023<<20}),Object.defineProperty(Ke,"TerminalMask",{enumerable:!0,configurable:!0,writable:!0,value:1048320}),Object.defineProperty(Ke,"EndpointMask",{enumerable:!0,configurable:!0,writable:!0,value:255}),Object.defineProperty(Ke,"ChannelMask",{enumerable:!0,configurable:!0,writable:!0,value:255}),Object.defineProperty(Ke,"ReservedMaskLong",{enumerable:!0,configurable:!0,writable:!0,value:Long.fromNumber(63).shiftLeft(58)}),Object.defineProperty(Ke,"SubDsMaskLong",{enumerable:!0,configurable:!0,writable:!0,value:Long.fromNumber(15).shiftLeft(54)}),Object.defineProperty(Ke,"ClusterIdMaskLong",{enumerable:!0,configurable:!0,writable:!0,value:Long.fromNumber(4095).shiftLeft(42)}),Object.defineProperty(Ke,"NodeTypeMaskLong",{enumerable:!0,configurable:!0,writable:!0,value:Long.fromNumber(1).shiftLeft(41)}),Object.defineProperty(Ke,"UseCtrlL1MaskLong",{enumerable:!0,configurable:!0,writable:!0,value:Long.fromNumber(1).shiftLeft(40)}),Object.defineProperty(Ke,"CtrlLayer0MaskLong",{enumerable:!0,configurable:!0,writable:!0,value:Long.fromNumber(1023).shiftLeft(30)}),Object.defineProperty(Ke,"CtrlLayer1MaskLong",{enumerable:!0,configurable:!0,writable:!0,value:Long.fromNumber(63).shiftLeft(20)}),Object.defineProperty(Ke,"TerminalMaskLong",{enumerable:!0,configurable:!0,writable:!0,value:Long.fromNumber(4095).shiftLeft(8)}),Object.defineProperty(Ke,"EndpointMaskLong",{enumerable:!0,configurable:!0,writable:!0,value:Long.fromNumber(255)}),Object.defineProperty(Ke,"ChannelMaskLong",{enumerable:!0,configurable:!0,writable:!0,value:Long.fromNumber(255)});var Ze=function(){function e(t,r){var n,i,o;return _(this,e),i=this,o=w(o=e),n=M(i,Qe()?Reflect.construct(o,[],w(i).constructor):o.apply(i,undefined)),Object.defineProperty(n,"socket",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(n,"requestMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"attachUserConfirm",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),n.socket=t,n.logger=r.getLoggerWithPrefix("[chn-switchtrans]"),n.requestMap=new Map,n}return j(e,EventEmitter),k(e,[{key:"channelBind",value:function(e){var t=this,r={chanId:2,type:de.ChannelType.DataSwitcherChannel,address:location.hostname},n="".concat(e,"#").concat(se.MessageType.TYPE_ATTACH_USER_CONFIRM);return this.commitRPC(function(){return t.socket.send(de.MessageType.ChannelBindType,{channelBind:r}).catch(function(e){var r;throw null===(r=t.requestMap.get(n))||void 0===r||r.reject(e),t.requestMap.delete(n),e})},n)}},{key:"commitRPC",value:function(e,t){var r=this;return t?new Promise(function(n,i){e(),r.requestMap.set(t,{resolve:n,reject:i}),addTimer(function(){var e=r.requestMap.get(t);null!=e&&e.reject&&(e.reject(new DingRTCError(ErrorCode.APICallTimeOut,"".concat(t," timeout"))),r.requestMap.delete(t))},8e3)}):Promise.resolve(e())}},{key:"send",value:function(e,t){var r,n=this,i=e[ve.rpcTypeKeyMap[e.type]],o=i.sessionType,a=i.sessionKey,s=i.requestId,c=i.groupId,u=i.nodeId;s?r="".concat(Ke.extractEndpointId(t.from),"#").concat(s):a?r="".concat(o,"#").concat(a,"#").concat(e.type+1):c&&(r="".concat(u.toString(),"#").concat(c,"#").concat(e.type+1));var l={msgType:oe.Type.kData,data:We(We({},t),{},{data:De.encode(e).finish()})},d={Type:de.MessageType.ChannelDataType,Version:1,channelData:{chanId:2,data:we.encode(l).finish()}};return this.commitRPC(function(){return n.socket.instance.send(ke.encode(d).finish())},r)}},{key:"onMessage",value:function(e){var t=we.decode(e),r=t.msgType,n=t.data,i=n.to,o=n.from,a=n.data;if(r===oe.Type.kData){var s;try{s=De.decode(a)}catch(e){return void this.logger.warn("handleMessage, dsmsg parse failed")}var c=Ke.getIdType(i)===Ye.ChannelId,u=Ke.extractEndpointId(c?o:i),l=s.type,d=ve.msgTypeKeyMap[l],p=s[d];if(p)if(ve.confirmTypes.includes(l)){this.logger.debug("".concat(d,": ").concat(JSON.stringify(p)));var f,h=p.result,g=p.requestId,m=p.sessionKey,v=p.sessionType,y=p.serverNodeId,b=p.pid,S=p.groupId,_=p.nodeId;g?f="".concat(u,"#").concat(g):y?f="".concat(b,"#").concat(l):m?f="".concat(v,"#").concat(m,"#").concat(l):S&&(f="".concat(_.toString(),"#").concat(S,"#").concat(l));var E=this.requestMap.get(f);if(!E)return;0===h?(this.logger.info("".concat(d," rpcId:").concat(f," result===> ").concat(JSON.stringify(p))),E.resolve(p)):(this.logger.warn("".concat(d," rpcId:").concat(f," error===> ").concat(JSON.stringify(p))),E.reject(p)),this.requestMap.delete(f)}else l===se.MessageType.TYPE_SESSION_CMD_DATA_NOTIFICATION?this.emit("sessionCmdData",u,c,p):l===se.MessageType.TYPE_SESSION_DATA?this.emit("sessionData",o,u,c?i:0,p):l===se.MessageType.TYPE_DETACH_USER_CONFIRM?this.emit("detachUserConfirm",p):l===se.MessageType.TYPE_NODE_MAP_UPDATE?this.emit("nodeMapUpdated",u,p):l===se.MessageType.TYPE_NODE_MAP_SNAPSHOT?this.emit("nodeMapSnapshot",u,p):l===se.MessageType.TYPE_SESSION_CREATED?this.emit("sessionCreated",p):l===se.MessageType.TYPE_SESSION_CLOSED?this.emit("sessionClosed",p):l===se.MessageType.TYPE_GROUP_CREATED?this.emit("groupCreated",u,p):l===se.MessageType.TYPE_GROUP_DESTROYED?this.emit("groupDestroyed",u,p):l===se.MessageType.TYPE_SERVICE_STATUS?this.emit("serviceStatus",u,p):l===se.MessageType.TYPE_SWITCHER_UPDATE&&this.emit("switchUpdate",p);else this.logger.warn("msgType: ".concat(d," has no payload"))}}}])}();function ze(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function $e(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return($e=function(){return!!e})()}var Xe=function(){function e(t){var r,n,i;return _(this,e),n=this,i=w(i=e),r=M(n,$e()?Reflect.construct(i,[],w(n).constructor):i.apply(n,undefined)),Object.defineProperty(r,"instance",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"heartBeat",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"requestMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"ticket",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"token",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"refreshTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"sequenceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"rejoin",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"basicTransport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"switchTransport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"destroyed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"retryCount",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"socketReconnectionTimeoutTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"signalReconnectionTimeoutTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"connectionTimeoutTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"state",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"instantlyReconnect",{enumerable:!0,configurable:!0,writable:!0,value:function(){r.logger.info("instantlyReconnect for browser offline event"),window.removeEventListener("offline",r.instantlyReconnect),"reconnecting"!==r.state&&r.setTimerToReconnectSocket(!0)}}),r.logger=t.getLoggerWithPrefix("[chn-socket]"),r.state="disconnected",r.requestMap=new Map,r.heartBeat=new Ae,r.refreshTimer=null,r.sequenceId=1,r.retryCount=0,r.switchTransport=new Ze(r,t),r.basicTransport=new Be(r,t),r}return j(e,EventEmitter),k(e,[{key:"onHeartBeat",value:function(){var e=this;this.heartBeat.on("retry",function(){e.destroyed||e.reconnect("keepalive")}),this.heartBeat.on("ping",function(t){e.send(de.MessageType.KeepaliveType,t)})}},{key:"setTimerToReconnectSocket",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.signalReconnectionTimeoutTimer&&(removeTimer(this.signalReconnectionTimeoutTimer),this.signalReconnectionTimeoutTimer=null),this.signalReconnectionTimeoutTimer=addTimer(function(){e.reconnect(t?"reconnect for noWaitTime":"reconnect req Timeout")},t?0:15e3)}},{key:"reconnect",value:function(e){this.close(),this.logger.debug("retry connect start, for ".concat(e)),this.clearConnectionTimer(!0),"connected"!==this.state&&"connecting"!==this.state||this.updateState("reconnecting"),this.init(this.url,this.token,!1,6e3)}},{key:"init",value:function(e,t){var r,n=this,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:-1;o>0&&(r=addTimer(function(){n.logger.info("finish connect init due to timeout"),n.instance.onclose=null,n.instance.onerror=null,n.instance.onopen=null,n.instance.onmessage=null,n.instance.close(),n.onClose(new CloseEvent("socket connect timeout, positive finished"))},o)),this.url=e,this.token=t,this.rejoin=i,"reconnecting"!==this.state&&(this.updateState("connecting"),this.connectionTimeoutTimer=addTimer(function(){n.updateState("disconnected","network_error"),n.close(!0)},32e3)),this.instance=new WebSocket(e),this.instance.binaryType="arraybuffer",this.instance.onopen=function(){removeTimer(r),n.onOpen()},this.instance.onmessage=function(e){n.onMessage(e)},this.instance.onerror=function(e){n.onError(e)},this.instance.onclose=function(e){removeTimer(r),n.onClose(e)}}},{key:"clear",value:function(){this.heartBeat.stop(),this.clearConnectionTimer(),this.requestMap.clear(),this.heartBeat.removeAllListeners()}},{key:"close",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.destroyed=e,this.clear(),this.instance&&(this.instance.onerror=null,this.instance.onmessage=null,this.instance.onclose=null,this.instance.onopen=null,this.instance.close(),this.instance=null)}},{key:"getTransportData",value:function(e,t){var r=function(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ze(Object(r),!0).forEach(function(t){R(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ze(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}({Type:e,Version:1,SequenceId:this.sequenceId++},t);return ke.encode(r).finish()}},{key:"send",value:function(e,t,r,n){var i,o,a=this;if(1!==(null===(i=this.instance)||void 0===i?void 0:i.readyState))return Promise.reject("socket state error: ".concat((null===(o=this.instance)||void 0===o?void 0:o.readyState)||0));var s=this.getTransportData(e,t);if(de.MessageType.KeepaliveType!==e&&this.setTimerToReconnectSocket(),![de.MessageType.KeepaliveType,de.MessageType.ChannelDataType].includes(e))return new Promise(function(t,i){a.instance.send(s);var o=null!=r?r:e,c=n||e;a.requestMap.set(o,{resolve:t,reject:i}),addTimer(function(){var e=a.requestMap.get(o);null!=e&&e.reject&&(e.reject(new DingRTCError(ErrorCode.APICallTimeOut,"".concat(c," timeout"))),a.requestMap.delete(o))},ue)});this.instance.send(s)}},{key:"clearConnectionTimer",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.signalReconnectionTimeoutTimer&&(removeTimer(this.signalReconnectionTimeoutTimer),this.signalReconnectionTimeoutTimer=null),this.socketReconnectionTimeoutTimer&&e&&(removeTimer(this.socketReconnectionTimeoutTimer),this.socketReconnectionTimeoutTimer=null),null!=this.connectionTimeoutTimer&&(removeTimer(this.connectionTimeoutTimer),this.connectionTimeoutTimer=null)}},{key:"channelBind",value:function(){this.logger.info("channelBind started");var e={chanId:1,type:de.ChannelType.PortalChannel,address:location.hostname};return this.send(de.MessageType.ChannelBindType,{channelBind:e})}},{key:"auth",value:function(e){var t=this;return this.logger.info("auth started rejoin=",this.rejoin),this.send(de.MessageType.AuthType,{auth:{token:e,duplicate:this.rejoin,options:{supportReliable:!1,supportPingConfig:!0}}}).then(function(e){if(t.logger.info("auth res",e),t.refresh(e.ticket),e.pingConfig)return e.pingConfig})}},{key:"refresh",value:function(e){var t=this;this.ticket=e;var r=JSON.parse(fromBase64(e)).notAfter,n=Date.now();if(r<=n-1e4)this.logger.warn("Reconnection ticket expires too soon.");else{var i=r-n-6e4;i<0&&(i=r-n-1e4),removeTimer(this.refreshTimer),this.refreshTimer=addTimer(function(){t.refreshTicket().then(function(e){t.refresh(e.ticket)})},i)}}},{key:"refreshTicket",value:function(){return this.send(de.MessageType.RefreshTicketType,{refreshTicket:{}})}},{key:"reauth",value:function(e){var t=this;return this.send(de.MessageType.ReAuthType,{reauth:{ticket:e,options:{supportReliable:!1,supportPingConfig:!0}}}).then(function(e){t.emit("reauth"),e.pingConfig&&t.heartBeat.start(e.pingConfig)}).catch(function(e){t.logger.error("reauth error"+JSON.stringify(e)),(null==e?void 0:e.errorMsg)!==de.AuthErrorMsg.Unavailable?t.onRejoin():(t.updateState("disconnected","timeout"),t.close(!0))})}},{key:"onRejoin",value:function(){this.rejoin||(this.emit("rejoin"),this.logger.warn("rejoin started")),this.close(!0)}},{key:"onMessage",value:function(e){this.setTimerToReconnectSocket();var t=ke.decode(new Uint8Array(e.data));if(t.Type===de.MessageType.ChannelDataType)1===t.channelData.chanId?this.basicTransport.onMessage(t):2===t.channelData.chanId&&this.switchTransport.onMessage(t.channelData.data);else if(t.Type===de.MessageType.RpcProxyResponseType)this.logger.debug("onmsg",t.Type,t),this.basicTransport.onProxyRtmpResponseMsg(t);else if(t.Type===de.MessageType.KeepaliveResponseType)this.heartBeat.pong(t.keepaliveResponse);else if(t.Type===de.MessageType.ServerRequestType){var r=t.notification.event;this.logger.warn("server request ".concat(1===r?"reauth":"rejoin")),r===de.ServerEvent.ReauthRequest?this.reauth(this.ticket):r===de.ServerEvent.RejoinRequest&&this.onRejoin()}else{var n,i,o=new Map([[de.MessageType.AuthResponseType,t.authResponse],[de.MessageType.ChannelBindResponseType,t.channelBindResponse],[de.MessageType.ReAuthResponseType,t.reauthResponse],[de.MessageType.RefreshTicketResponseType,t.refreshTicketResponse]]).get(t.Type);o.code===de.ErrorCode.Ok?null===(n=this.requestMap.get(t.Type-1))||void 0===n||n.resolve(o):null===(i=this.requestMap.get(t.Type-1))||void 0===i||i.reject(o),this.requestMap.delete(t.Type-1)}}},{key:"onError",value:function(e){this.logger.error("onError: ".concat(JSON.stringify(e)))}},{key:"onOpen",value:(t=C(pe.mark(function e(){var t,r,n,i=this;return pe.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(this.clearConnectionTimer(!0),this.retryCount=0,window.addEventListener("offline",this.instantlyReconnect),"reconnecting"!==this.state){e.next=1;break}this.reauth(this.ticket).then(function(){i.rejoin=!1,i.updateState("connected"),i.onHeartBeat()}),e.next=5;break;case 1:return e.prev=1,e.next=2,this.auth(this.token);case 2:return t=e.sent,e.next=3,this.channelBind();case 3:r=e.sent,this.logger.info("channelBind res",r),this.rejoin=!1,this.updateState("connected"),this.onHeartBeat(),this.heartBeat.start(t),e.next=5;break;case 4:e.prev=4,n=e.catch(1),this.logger.debug("auth or channelBind failed",n),this.updateState("disconnected","server_error"),this.close(!0);case 5:case"end":return e.stop()}},e,this,[[1,4]])})),function(){return t.apply(this,arguments)})},{key:"updateState",value:function(e,t){e!==this.state&&(this.emit("connection-state-change",e,this.state,t),this.state=e)}},{key:"onClose",value:function(e){var t=this;this.logger.warn("socket closed:"+JSON.stringify(e)),this.rejoin?this.updateState("disconnected","server_error"):this.destroyed||("reconnecting"===this.state?(this.retryCount++,this.retryCount>18?(this.updateState("disconnected","network_error"),this.retryCount=0):this.socketReconnectionTimeoutTimer=addTimer(function(){t.reconnect("retry count"+t.retryCount)},ye)):"connecting"==this.state?this.socketReconnectionTimeoutTimer=addTimer(function(){t.reconnect("localNetwork")},ye):"disconnected"!==this.state&&(this.socketReconnectionTimeoutTimer=addTimer(function(){t.reconnect("server closed, retry count"+t.retryCount)},ye))),this.clear()}}]);var t}();function et(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function tt(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?et(Object(r),!0).forEach(function(t){R(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):et(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}var nt=getReporter().getLoggerWithPrefix("[ch-gslb]");function it(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(it=function(){return!!e})()}var rt=function(){function e(t,r){var n,i,o;return _(this,e),i=this,o=w(o=e),n=M(i,it()?Reflect.construct(o,[],w(i).constructor):o.apply(i,undefined)),Object.defineProperty(n,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(n,"transport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),n.transport=t.basicTransport,n.reporter=r,n.logger=n.reporter.getLoggerWithPrefix("[chn-signaling]"),n.forwardNotification(),n}return j(e,EventEmitter),k(e,[{key:"forwardNotification",value:function(){var e=this;["participant","batch-notify","conference","drop","notify","rejoin","connection-state-change","sync","reauth"].forEach(function(t){e.transport.on(t,function(){for(var r=arguments.length,n=new Array(r),i=0;i<r;i++)n[i]=arguments[i];e.emit.apply(e,[t].concat(n))})})}},{key:"relogin",value:function(e){var t=this,r=e.token,n=Oe.encode(e).finish();return this.transport.connect(r,!0).then(function(){return t.transport.sendChnData("rejoin-login",n,e,!0).then(function(e){return e.rejoinResponse})})}},{key:"login",value:function(e){var t=this,r=e.token,n=Ne.encode(e).finish();return this.transport.connect(r,!1).then(function(){return t.transport.sendChnData("login",n,e,!0).then(function(e){return e.joinResponse})})}},{key:"diconnect",value:function(){return this.transport.disconnect()}},{key:"logout",value:function(){var e=this;return this.transport.sendChnData("logout",void 0,null,!0).catch(function(t){e.logger.debug("logout api called failed ".concat(JSON.stringify(t)))}),this.diconnect()}},{key:"getUsersVer",value:function(e){var t=Re.encode(e).finish();return this.transport.sendChnData("query-participants-ver",t,e,!0).then(function(e){return e.queryParticipantsVerResponse})}},{key:"getUsers",value:function(e){var t=_e.encode(e).finish();return this.transport.sendChnData("query-participants",t,e,!0).then(function(e){return e.queryParticipantsResponse})}},{key:"rpc",value:function(e,t,r){return this.transport.sendChnData(e,t,r)}}])}();function ot(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function st(e,t){if(e){if("string"==typeof e)return ot(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?ot(e,t):void 0}}function at(e){return function(e){if(Array.isArray(e))return ot(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||st(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function dt(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function ct(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?dt(Object(r),!0).forEach(function(t){R(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):dt(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function pt(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return lt(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?lt(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function lt(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function ut(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(ut=function(){return!!e})()}var yt,ht,ft,gt,vt,mt,bt,St=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:50,r=null;return function(){for(var n=this,i=arguments.length,o=new Array(i),a=0;a<i;a++)o[a]=arguments[a];r&&clearTimeout(r),r=setTimeout(function(){e.apply(n,o)},t)}},Tt=function(){function e(t){var r,n,i;return _(this,e),n=this,i=w(i=e),r=M(n,ut()?Reflect.construct(i,[],w(n).constructor):i.apply(n,undefined)),Object.defineProperty(r,"channel",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(r,"participants",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"currentPid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"totalVer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"onConnectionStateChange",{enumerable:!0,configurable:!0,writable:!0,value:function(e,t){r.logger.info("chn connection-state-change",e,t),"connected"===e&&"reconnecting"===t&&r.debounceSyncRpc(!1)}}),Object.defineProperty(r,"debounceSyncRpc",{enumerable:!0,configurable:!0,writable:!0,value:St(r.doSyncRpc,1e3)}),r.participants=new Map,r.channel=t,r.reporter=t.reporter,r.logger=r.reporter.getLoggerWithPrefix("[chn-usermgr]"),r.handleEvent=r.handleEvent.bind(r),r.handleSyncEvent=r.handleSyncEvent.bind(r),r.debounceSyncRpc=r.debounceSyncRpc.bind(r),r}return j(e,EventEmitter),k(e,[{key:"currentUids",get:function(){return at(this.participants.values()).map(function(e){return e.user})}},{key:"init",value:function(e,t,r){var n,i=pt(e);try{for(i.s();!(n=i.n()).done;){var o=n.value;this.participants.set(o.id,o)}}catch(e){i.e(e)}finally{i.f()}this.totalVer=t,this.currentPid=r,this.channel.signaling.on("participant",this.handleEvent),this.channel.signaling.on("sync",this.handleSyncEvent),this.channel.signaling.on("reauth",this.debounceSyncRpc),this.channel.on("connection-state-change",this.onConnectionStateChange)}},{key:"clear",value:function(){this.participants.clear(),this.currentPid="",this.totalVer=0,this.channel.signaling.off("participant",this.handleEvent),this.channel.signaling.off("sync",this.handleSyncEvent),this.channel.signaling.off("reauth",this.debounceSyncRpc),this.channel.off("connection-state-change",this.onConnectionStateChange)}},{key:"handleEvent",value:function(e,t){var r=this;this.logger.info("channelUserEvent",e);var n=e.action,i=e.info,o=e.participantId,a=e.totalVer,s=e.propertiesData,c=this.totalVer,u=this.participants.get(o||(null==s?void 0:s.id));if(a==c+1||-999==a||t)if("join"===n&&i){var l=at(this.participants.values()).filter(function(e){return e.user===i.user});this.participants.set(i.id,i),0===l.length?this.emit("user","join",i):(this.logger.info("delete same uid participants, for new join",i,l),l.map(function(e){return r.participants.delete(e.id)}),this.emit("user","participant-replace",i,l))}else"leave"===n?u?(this.participants.delete(o),this.currentUids.includes(u.user)?this.logger.info("user ".concat(u.user," has another pid in channel")):this.emit("user","leave",u)):this.logger.info("Received leave message for unknown participant."):"setProperties"===n&&(u.propertiesJsonStr=JSON.stringify(ct(ct({},JSON.parse(u.propertiesJsonStr||"{}")),JSON.parse(s.propertiesJsonStr||"{}"))),this.emit("user","update",u));t||a<=this.totalVer&&-999!==a||(a===c+1&&(this.totalVer=a),a>c+1&&!t&&(this.logger.info("debounceSyncRpc by user event"),this.debounceSyncRpc()))}},{key:"handleSyncEvent",value:function(e){var t=e.participantsVer;this.totalVer<t&&(this.logger.info("debounceSyncRpc by sync event"),this.debounceSyncRpc())}},{key:"doSyncRpc",value:(t=C(pe.mark(function e(){var t,r,n,i,o,a,s,c,u,l,d,p,f,h,g,m,v,y,b,S,_,E,T,R,C,k,P,w,O,I=arguments;return pe.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t=!(I.length>0&&void 0!==I[0])||I[0],this.logger.info("request sync user checkUserVer=",t),r=[],n=[],e.prev=1,e.next=2,this.channel.signaling.getUsersVer({});case 2:a=e.sent,i=a.participants,o=a.totalVer,e.next=4;break;case 3:return e.prev=3,O=e.catch(1),this.logger.error("sync error",O),e.abrupt("return");case 4:s=at(this.participants.keys()),c=i.map(function(e){return e.id}),u=pt(i);try{for(u.s();!(l=u.n()).done;)p=l.value,f=p.id,h=p.ver,this.participants.has(f)?((null===(d=this.participants.get(f))||void 0===d?void 0:d.ver)!==h&&t||!t)&&r.push(f):n.push(f)}catch(e){u.e(e)}finally{u.f()}if(this.reporter.trace.syncEvent("user",s,c),g=s.filter(function(e){return!c.includes(e)}),m=at(new Set(r.concat(g,n))),this.totalVer=o,0!==m.length){e.next=5;break}return this.logger.info("no diff user, return"),e.abrupt("return");case 5:return e.next=6,this.channel.signaling.getUsers({pids:m});case 6:v=e.sent,y=v.participants,b=v.totalVer,S=new Map,_=pt(this.participants.values());try{for(_.s();!(E=_.n()).done;)T=E.value,S.set(T.id,T)}catch(e){_.e(e)}finally{_.f()}R=pt(y);try{for(R.s();!(C=R.n()).done;)k=C.value,this.participants.has(k.id)?(this.participants.set(k.id,k.data),this.handleEvent({action:"setProperties",participantId:k.id,info:this.participants.get(k.id),totalVer:b,propertiesData:k.data},!0)):S.set(k.id,k.data)}catch(e){R.e(e)}finally{R.f()}for(P=0;P<at(S.values()).length;P++)w=S[P],n.includes(w.id)?this.handleEvent({action:"join",participantId:w.id,info:w,totalVer:b},!0):g.includes(w.id)&&this.handleEvent({action:"leave",participantId:w.id,info:w,totalVer:b},!0);this.totalVer=b;case 7:case"end":return e.stop()}},e,this,[[1,3]])})),function(){return t.apply(this,arguments)})}]);var t}();function Et(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,i,o,a,s=[],c=!0,u=!1;try{if(o=(r=r.call(e)).next,0===t);else for(;!(c=(n=o.call(r)).done)&&(s.push(n.value),s.length!==t);c=!0);}catch(e){u=!0,i=e}finally{try{if(!c&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(u)throw i}}return s}}(e,t)||st(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}!function(e){e[e.UNKNOWN=-1]="UNKNOWN",e[e.WHITEBOARD=0]="WHITEBOARD",e[e.RTCSERVICE=1]="RTCSERVICE",e[e.RTCSUBTITLE=2]="RTCSUBTITLE",e[e.CUSTOMIZE=101]="CUSTOMIZE"}(yt||(yt={})),function(e){e[e.NODE_JOIN=0]="NODE_JOIN",e[e.NODE_LEAVE=1]="NODE_LEAVE"}(ht||(ht={})),function(e){e[e.RTMS=0]="RTMS",e[e.SDK=1]="SDK",e[e.APP=2]="APP"}(ft||(ft={})),function(e){e[e.OPEN=0]="OPEN",e[e.CLOSE=1]="CLOSE",e[e.ERROR=2]="ERROR"}(gt||(gt={})),function(e){e.IDLE="idle",e.READY="ready"}(vt||(vt={})),function(e){e.UNINITED="uninited",e.READY="ready",e.LEFT="left",e.CLOSED="closed"}(mt||(mt={})),function(e){e.UNINITED="uninited",e.BINDING="binding",e.READY="ready",e.CLOSED="closed"}(bt||(bt={}));var It=k(function e(t){_(this,e),Object.defineProperty(this,"log",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pending",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"nodesInfo",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"pid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pidToNodeInfo",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"getNodeInfoKey",{enumerable:!0,configurable:!0,writable:!0,value:function(e){return"number"==typeof e?"number"+e:"low".concat(e.low,"high").concat(e.high,"unsigned").concat(e.unsigned)}}),this.log=t},[{key:"handleNodeMapUpdate",value:function(e){var t=this;return e.items.filter(function(e){return e.action===ht.NODE_JOIN&&t.addNode(e)||e.action===ht.NODE_LEAVE&&t.removeNode(e)})}},{key:"handleNodeMapSnapshot",value:function(e){var t=this,r=e.start,n=e.end,i=e.items;if(r&&this.pending.clear(),i.forEach(function(e){return t.pending.set(e.pid,e)}),n){this.log.info("Snapshot,size:".concat(this.pidToNodeInfo.size," to:").concat(this.pending.size));var o=[];return this.pidToNodeInfo.forEach(function(e,r){var n;o.push({pid:r,uid:e.uid,userName:e.userName,nodeId:(null===(n=t.pending.get(r))||void 0===n?void 0:n.nodeId)||e.nodeId,action:t.pending.has(r)?ht.NODE_JOIN:ht.NODE_LEAVE}),t.pending.delete(r)}),this.pending.forEach(function(e,t){o.push({pid:t,nodeId:e.nodeId,uid:e.uid,userName:e.userName,action:ht.NODE_JOIN})}),this.pending.clear(),this.handleNodeMapUpdate({items:o})}}},{key:"getNodeInfo",value:function(e){var t=this.getNodeInfoKey(e);return this.nodesInfo.get(t)}},{key:"addNode",value:function(e){var t=e.pid,r=e.nodeId,n=this.getNodeInfoKey(r);return this.nodesInfo.has(n)?(this.log.debug("updateNode,pid:".concat(t,", nodeId:").concat(r)),this.nodesInfo.set(n,e),this.pidToNodeInfo.set(n,e),!1):(this.log.debug("addNode,pid:".concat(t,", nodeId:").concat(r)),this.nodesInfo.set(n,e),this.pidToNodeInfo.set(t,e),t!==this.pid)}},{key:"removeNode",value:function(e){var t=e.pid,r=e.nodeId,n=this.getNodeInfoKey(r);return!!this.nodesInfo.has(n)&&(this.log.debug("removeNode, pid:".concat(t,", nodeId:").concat(r)),this.nodesInfo.delete(n),this.pidToNodeInfo.delete(t),t!==this.pid)}},{key:"getPid",value:function(e){var t,r=this.getNodeInfoKey(e);return null===(t=this.nodesInfo.get(r))||void 0===t?void 0:t.pid}},{key:"clear",value:function(){this.pending.clear(),this.nodesInfo.clear(),this.pidToNodeInfo.clear()}}]),Ct=k(function e(t,r,n,i){_(this,e),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"nodeId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"channel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"state",{enumerable:!0,configurable:!0,writable:!0,value:vt.IDLE}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"session",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.id=r.groupId,this.session=n,this.logger=i.getLoggerWithPrefix("[chn-dsgroup]"),this.nodeId=t,this.channel=r.channel},[{key:"join",value:function(){var e=this;return this.logger.info("join dsgroup ".concat(this.session.id,"#group:").concat(this.id," state:").concat(null==this?void 0:this.state)),new Promise(function(t,r){e.session.switcher.enquenTask.add(function(){if((null==e?void 0:e.state)!==vt.READY){var n={type:se.MessageType.TYPE_JOIN_GROUP,joinGroup:{groupId:e.id,nodeId:Ke.extractNodeId(e.nodeId)}};return e.session.switcher.send(n,{to:Ke.extractParentNodeId(e.nodeId,0),priority:Ge.Low,uniform:!1,endpointId:e.session.endpointId}).then(function(){e.state=vt.READY,t()}).catch(r)}r(new DingRTCError(ErrorCode.InvaildState,"group is already ready"))})})}},{key:"leave",value:function(){var e=this;return this.logger.info("leave dsgroup ".concat(this.session.id,"#group:").concat(this.id," state:").concat(null==this?void 0:this.state)),new Promise(function(t,r){(null==e?void 0:e.state)!==vt.READY&&r(new DingRTCError(ErrorCode.InvaildState,"group is not ready")),e.session.switcher.enquenTask.add(function(){var n={type:se.MessageType.TYPE_LEAVE_GROUP,leaveGroup:{groupId:e.id,nodeId:Ke.extractNodeId(e.nodeId)}};return e.session.switcher.send(n,{to:Ke.extractParentNodeId(e.nodeId,0),priority:Ge.Low,uniform:!1,endpointId:e.session.endpointId}).then(function(){e.state=vt.IDLE,t()}).catch(r)})})}}]);function Ot(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(Ot=function(){return!!e})()}var Pt=function(){function e(t,r,n,i){var o,a,s;return _(this,e),a=this,s=w(s=e),o=M(a,Ot()?Reflect.construct(s,[],w(a).constructor):s.apply(a,undefined)),Object.defineProperty(o,"type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(o,"syncing",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(o,"pendingMessages",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(o,"joinPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(o,"groups",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(o,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(o,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(o,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(o,"switcher",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(o,"state",{enumerable:!0,configurable:!0,writable:!0,value:mt.UNINITED}),Object.defineProperty(o,"endpointId",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(o,"nodeMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(o,"broadcastChannel",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(o,"userData",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),o.type=t,o.id=r,o.switcher=n,o.reporter=i,o.logger=i.getLoggerWithPrefix("[chn-dssession]"),o.nodeMap=new It(o.logger),o.join=o.join.bind(o),o.leave=o.leave.bind(o),o.close=o.close.bind(o),o}return j(e,EventEmitter),k(e,[{key:"available",get:function(){var e;return"connected"===(null===(e=this.switcher)||void 0===e||null===(e=e.channel)||void 0===e?void 0:e.connectionState)&&this.state===mt.READY}},{key:"recover",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.logger.info("".concat(this.type,"#").concat(this.id," recover rejoin:").concat(e,",state:").concat(this.state)),e?this.state==mt.READY&&(this.syncing=!0,this.join()):this.syncing=!0}},{key:"retransmit",value:function(){for(this.logger.info("retransmit ".concat(this.type,"#").concat(this.id," pengingMsgLen:").concat(this.pendingMessages.length));this.pendingMessages.length;){var e=this.pendingMessages.shift(),t=e.message,r=e.resolve,n=e.reject;this.sendInner(t).then(r).catch(n)}}},{key:"join",value:function(e){var t,r=this;return this.logger.info("dssession join ".concat(this.type,"#").concat(this.id," state=").concat(this.state)),null!==(t=this.switcher)&&void 0!==t&&null!==(t=t.channel)&&void 0!==t&&t.enableDS?new Promise(function(t,n){r.switcher.enquenTask.add(function(){if(r.state!==mt.READY||r.syncing){r.joinPromise={resolve:t,reject:n};var i={type:se.MessageType.TYPE_JOIN_SESSION,joinSession:{sessionType:r.type,sessionKey:r.id,customSessionData:e||r.userData,nodeId:r.switcher.nodeId,pid:r.switcher.pid}};return r.switcher.send(i).then(function(e){var t,n;r.logger.info("dssession join ",e);var i=e.customSessionData,o=e.endpointId,a=e.channels;r.endpointId=o,r.broadcastChannel=null===(t=a.find(function(e){return e.type===Je.DEFAULT}))||void 0===t?void 0:t.id,r.userData=i,r.state=mt.READY,null===(n=r.joinPromise)||void 0===n||n.resolve(e)}).catch(function(e){var t;r.logger.info("dssession join error",e),null===(t=r.joinPromise)||void 0===t||t.reject(e),r.joinPromise=null})}n(new DingRTCError(ErrorCode.InvaildState,"session is already ready"))})}):Promise.reject(new DingRTCError(ErrorCode.InvaildState,"dataSwitcher not enabled"))}},{key:"leave",value:function(){var e,t=this;return null!==(e=this.switcher)&&void 0!==e&&null!==(e=e.channel)&&void 0!==e&&e.enableDS?(this.logger.info("dssession leave ".concat(this.type,"#").concat(this.id," state:").concat(this.state)),new Promise(function(e,r){t.state!==mt.READY&&r(new DingRTCError(ErrorCode.InvaildState,"session is not ready")),t.switcher.enquenTask.add(function(){var n={type:se.MessageType.TYPE_LEAVE_SESSION,leaveSession:{sessionType:t.type,sessionKey:t.id,nodeId:t.switcher.nodeId}};return t.switcher.send(n).then(function(){t.state=mt.LEFT,e()}).catch(r)})})):Promise.reject(new DingRTCError(ErrorCode.InvaildState,"dataSwitcher not enabled"))}},{key:"close",value:function(){var e,t=this;return null!==(e=this.switcher)&&void 0!==e&&null!==(e=e.channel)&&void 0!==e&&e.enableDS?(this.logger.info("dssession close ".concat(this.type,"#").concat(this.id," state:").concat(this.state)),new Promise(function(e,r){t.switcher.enquenTask.add(function(){t.state===mt.CLOSED&&r(new DingRTCError(ErrorCode.InvaildState,"session is already closed"));var n={type:se.MessageType.TYPE_CLOSE_SESSION,closeSession:{sessionType:t.type,sessionKey:t.id,nodeId:t.switcher.nodeId}};return t.switcher.send(n).then(function(){t.state=mt.CLOSED,e()}).catch(r)})})):Promise.reject(new DingRTCError(ErrorCode.InvaildState,"dataSwitcher not enabled"))}},{key:"sendMessage",value:function(e){var t=this;return new Promise(function(r,n){if(t.state===mt.READY)return t.syncing||!t.available?(t.pendingMessages.length>1e3&&t.pendingMessages.shift().reject(new DingRTCError(ErrorCode.InvaildState,"pending size is full")),void t.pendingMessages.push({message:e,resolve:r,reject:n})):t.sendInner(e).then(r).catch(n);n(new DingRTCError(ErrorCode.InvaildState,"session is not ready"))})}},{key:"sendInner",value:function(e){var t,r,n,i,o=e.targetPid,a=e.echo,s=e.uniform,c=void 0!==s&&s,u=e.message,l=e.cmd,d=e.cmdType,p=e.requestId,f=e.groupId,h=l&&void 0!==d;t=o===fe?Ke.getTopNodeId(0):null===(r=this.nodeMap.pidToNodeInfo.get(o))||void 0===r?void 0:r.nodeId;var g,m="string"==typeof u?(new TextEncoder).encode(u):u;h?(n=Ke.composeId(this.switcher.serverNodeId,this.endpointId),i={type:se.MessageType.TYPE_SESSION_CMD_DATA,sessionCmdData:{cmd:l,echo:a,cmdType:d,toNodeId:t,requestId:p,data:m,broadcast:!o,fromPid:this.switcher.pid}}):(n=o?Ke.composeId(t,this.endpointId):this.broadcastChannel,f&&!o&&(n=null===(g=this.groups.get(f))||void 0===g||null===(g=g.channel)||void 0===g?void 0:g.id),i={type:se.MessageType.TYPE_SESSION_DATA,sessionData:{data:m}});return this.switcher.send(i,{to:n,echo:a,uniform:c,broadcast:!o,endpointId:this.endpointId,priority:h?Ge.Normal:Ge.Low})}},{key:"handleNodeMapSnapshot",value:function(e){var t,r=this,n=this.nodeMap.handleNodeMapSnapshot(e);e.end&&(n.length&&(n.forEach(function(e){var t=r.switcher.nodeMap.getNodeInfo(e.nodeId);t&&(e.uid=t.uid,e.userName=t.userName)}),this.logger.info("handleNodeMapSnapshot ".concat(this.type,"#").concat(this.id," updated=").concat(JSON.stringify(n))),this.emit("user-update",n)),this.retransmit(),null===(t=this.joinPromise)||void 0===t||t.resolve(),this.joinPromise=null,this.syncing&&(this.syncing=!1,this.logger.info("rejoin success ".concat(this.type,"#").concat(this.id))))}},{key:"handleNodeMapUpdate",value:function(e){var t=this,r=this.nodeMap.handleNodeMapUpdate(e);r.length&&(r.forEach(function(e){var r=t.switcher.nodeMap.getNodeInfo(e.nodeId);r&&(e.uid=r.uid,e.userName=r.userName)}),this.logger.info("handleNodeMapUpdate ".concat(this.type,"#").concat(this.id," nodeUpdated:").concat(JSON.stringify(r))),this.emit("user-update",r))}},{key:"handleSessionCreated",value:function(e,t,r){this.endpointId=e,this.broadcastChannel=t,this.userData=r}},{key:"handleSessionClosed",value:function(){this.state=mt.CLOSED,this.emit("leave","closed")}},{key:"handleSessionCmdData",value:function(e,t){var r=t.fromPid,n=t.cmd,i=t.cmdType,o=t.requestId,a=t.data,s=this.type!==yt.CUSTOMIZE?(new TextDecoder).decode(a):a,c=this.type!==yt.CUSTOMIZE?"STRING":"BINARY";this.emit("message",{cmd:n,cmdType:i,requestId:o,broadcast:e,messageType:c,pid:r,message:s})}},{key:"handleSessionData",value:function(e,t,r){var n,i,o=r.data,a=this.nodeMap.getPid(Ke.extractNodeId(e)),s=this.type!==yt.CUSTOMIZE?(new TextDecoder).decode(o):o,c=this.type!==yt.CUSTOMIZE?"STRING":"BINARY";t&&(n=null===(i=at(this.groups.values()).filter(function(e){var r;return(null==e||null===(r=e.channel)||void 0===r?void 0:r.id)===t})[0])||void 0===i?void 0:i.id);var u={pid:a,message:s,broadcast:!!t,messageType:c};n&&(u.groupId=n),this.emit("message",u)}},{key:"getGroup",value:function(e){var t=this.groups.get(e);return t||(t=new Ct(Ke.composeId(this.switcher.nodeId,this.endpointId),{groupId:e},this,this.reporter),this.groups.set(e,t)),t}},{key:"joinGroup",value:function(e){return this.getGroup(e).join()}},{key:"leaveGroup",value:function(e){return this.groups.has(e)?this.getGroup(e).leave():Promise.reject(new DingRTCError(ErrorCode.InvaildArgument,"group not found"))}},{key:"handleGroupCreated",value:function(e){var t=e.groupId;this.logger.info("groupcreated ".concat(this.type,"#").concat(this.id,"#").concat(t," msg:").concat(JSON.stringify(e)));var r=this.groups.get(t);r?r.channel=e.channel:(r=new Ct(Ke.composeId(this.switcher.nodeId,this.endpointId),e,this,this.reporter),this.groups.set(t,r),this.emit("group-add",r))}},{key:"handleGroupDestroyed",value:function(e){var t=e.groupId;this.logger.info("GroupDestroyed ".concat(this.type,"#").concat(this.id,"#").concat(t," msg:").concat(JSON.stringify(e)));var r=this.groups.get(t);r&&(this.groups.delete(t),this.emit("group-remove",r))}},{key:"handleServiceStatus",value:function(e){var t=e.status;this.logger.info("ServiceStatus ".concat(this.type,"#").concat(this.id," msg:").concat(JSON.stringify(e))),this.emit("service-status",t)}},{key:"handleChannelUpdate",value:function(e){var t=this;this.logger.info("ChannelUpdated ".concat(this.type,"#").concat(this.id," msg:").concat(JSON.stringify(e))),e.forEach(function(e){var r;e.groupId?t.getGroup(e.groupId).channel=e.channel:(null==e||null===(r=e.channel)||void 0===r?void 0:r.type)===Je.DEFAULT&&(t.broadcastChannel=e.channel.id)})}}])}();function Rt(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(Rt=function(){return!!e})()}updateProtobuf(Long);var _t=function(){function e(t){var r,n,i;return _(this,e),n=this,i=w(i=e),r=M(n,Rt()?Reflect.construct(i,[],w(n).constructor):i.apply(n,undefined)),Object.defineProperty(r,"endpointId",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(r,"nodeMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"broadcastChannel",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(r,"switcherTransport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"sessionEndPointMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(r,"log",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"pid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"nodeId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"channel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"state",{enumerable:!0,configurable:!0,writable:!0,value:bt.UNINITED}),Object.defineProperty(r,"serverNodeId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"enquenTask",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"sessionMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),r.enquenTask=taskQueue$1(),r.channel=t,r.log=t.reporter.getLoggerWithPrefix("[chn-ds]"),r.reporter=t.reporter,r.nodeMap=new It(r.log),r.handleDetachUserConfirm=r.handleDetachUserConfirm.bind(r),r.handleNodeMapSnapshot=r.handleNodeMapSnapshot.bind(r),r.handleNodeMapUpdate=r.handleNodeMapUpdate.bind(r),r.handleSessionClosed=r.handleSessionClosed.bind(r),r.handleSessionCreated=r.handleSessionCreated.bind(r),r.handleSessionData=r.handleSessionData.bind(r),r.handleSessionCmdData=r.handleSessionCmdData.bind(r),r.handleGroupCreated=r.handleGroupCreated.bind(r),r.handleGroupDestroyed=r.handleGroupDestroyed.bind(r),r.handleServiceStatus=r.handleServiceStatus.bind(r),r.handleSwitchUpdate=r.handleSwitchUpdate.bind(r),r}return j(e,EventEmitter),k(e,[{key:"init",value:function(e){var t=this,r=this.state;if(this.log.debug("init switcher channelBind start:".concat(r),e),r!==bt.BINDING)return this.switcherTransport=this.channel.socket.switchTransport,this.pid=e,this.state=bt.BINDING,this.switcherTransport.channelBind(e).then(function(r){t.nodeMap.pid=e,t.addEventListeners(),t.handleAttachUserConfirm(r),t.enquenTask.start()}).catch(function(){var r=C(pe.mark(function r(n){return pe.wrap(function(r){for(;;)switch(r.prev=r.next){case 0:return t.log.warn("pid:".concat(e," switcher channelBind failed:").concat(tryJsonStringify(n))),r.next=1,awaitTime$1(1);case 1:"connected"===t.channel.connectionState&&t.state!==bt.CLOSED&&(t.state=bt.UNINITED,t.init(e));case 2:case"end":return r.stop()}},r)}));return function(e){return r.apply(this,arguments)}}())}},{key:"addEventListeners",value:function(){this.switcherTransport.on("detachUserConfirm",this.handleDetachUserConfirm),this.switcherTransport.on("nodeMapSnapshot",this.handleNodeMapSnapshot),this.switcherTransport.on("nodeMapUpdated",this.handleNodeMapUpdate),this.switcherTransport.on("sessionClosed",this.handleSessionClosed),this.switcherTransport.on("sessionCreated",this.handleSessionCreated),this.switcherTransport.on("sessionData",this.handleSessionData),this.switcherTransport.on("sessionCmdData",this.handleSessionCmdData),this.switcherTransport.on("groupCreated",this.handleGroupCreated),this.switcherTransport.on("groupDestroyed",this.handleGroupDestroyed),this.switcherTransport.on("serviceStatus",this.handleServiceStatus),this.switcherTransport.on("switchUpdate",this.handleSwitchUpdate)}},{key:"removeEventListeners",value:function(){this.switcherTransport&&(this.switcherTransport.off("detachUserConfirm",this.handleDetachUserConfirm),this.switcherTransport.off("nodeMapSnapshot",this.handleNodeMapSnapshot),this.switcherTransport.off("nodeMapUpdated",this.handleNodeMapUpdate),this.switcherTransport.off("sessionClosed",this.handleSessionClosed),this.switcherTransport.off("sessionCreated",this.handleSessionCreated),this.switcherTransport.off("sessionData",this.handleSessionData),this.switcherTransport.off("sessionCmdData",this.handleSessionCmdData),this.switcherTransport.off("groupCreated",this.handleGroupCreated),this.switcherTransport.off("groupDestroyed",this.handleGroupDestroyed),this.switcherTransport.off("serviceStatus",this.handleServiceStatus),this.switcherTransport.off("switchUpdate",this.handleSwitchUpdate))}},{key:"clear",value:function(){this.switcherTransport.attachUserConfirm=null,this.sessionMap.clear(),this.nodeMap.clear(),this.enquenTask=taskQueue$1(),this.sessionEndPointMap.clear(),this.state=bt.UNINITED,this.removeEventListeners()}},{key:"getSession",value:function(e,t){var r;if(t.length>128)throw new DingRTCError(ErrorCode.InvaildArgument,"invalid id");var n=null===(r=this.sessionMap.get(e))||void 0===r?void 0:r.get(t);return n||(this.log.info("new local DSSession:".concat(e,"#").concat(t)),n=new Pt(e,t,this,this.reporter),this.sessionMap.get(e)?this.sessionMap.get(e).set(t,n):this.sessionMap.set(e,new Map([[t,n]]))),n}},{key:"fetchSession",value:function(e,t){var r=this.sessionEndPointMap.get(e);if(r)return r;this.log.warn("".concat(t," fetchSession:").concat(e," not existed"))}},{key:"send",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.state===bt.CLOSED)return Promise.reject(new DingRTCError(ErrorCode.InvaildState,"switcher is closed"));var r=t.echo,n=void 0!==r&&r,i=t.priority,o=void 0===i?Ge.High:i,a=t.endpointId,s=t.broadcast,c=void 0!==s&&s,u=t.uniform,l=void 0===u||u,d=t.to,p=o===Ge.High,f=Ke.composeId(this.nodeId,p?this.endpointId:a);p&&(d=c?this.broadcastChannel:Ke.composeId(this.serverNodeId,this.endpointId));var h={to:d,from:f,compressed:!1,priority:o,uniform:p||l,echo:n};return this.switcherTransport.send(e,h)}},{key:"handleNodeMapUpdate",value:function(e,t){var r;e===this.endpointId?this.nodeMap.handleNodeMapUpdate(t):null===(r=this.fetchSession(e,"NodeMapUpdate"))||void 0===r||r.handleNodeMapUpdate(t)}},{key:"handleAttachUserConfirm",value:function(e){var t,r=this,n=e.nodeId,i=e.serverNodeId,o=e.endpointId,a=e.channels,s=e.sessionCreateds,c=e.reason;this.broadcastChannel=null===(t=a.find(function(e){return e.type===Je.DEFAULT}))||void 0===t?void 0:t.id,this.nodeId=n,this.endpointId=o,this.serverNodeId=i;var u=[qe.NORMAL_ATTACH,qe.FORCE_REATTACH].includes(c);this.sessionMap.forEach(function(e,t){e.forEach(function(e,n){s.some(function(e){return e.sessionType===t&&e.sessionKey===n})?e.recover(u):r.handleSessionClosed({sessionKey:n,sessionType:t})})}),s.forEach(function(e){r.handleSessionCreated(e)}),this.state=bt.READY}},{key:"handleNodeMapSnapshot",value:function(e,t){var r;this.endpointId==e?this.nodeMap.handleNodeMapSnapshot(t):null===(r=this.fetchSession(e,"NodeMapSnapshot"))||void 0===r||r.handleNodeMapSnapshot(t)}},{key:"handleSessionCreated",value:function(e){var t,r,n=e.sessionKey,i=e.sessionType,o=e.endpointId,a=e.customSessionData,s=null===(t=e.channels.find(function(e){return e.type===Je.DEFAULT}))||void 0===t?void 0:t.id,c=null===(r=this.sessionMap.get(i))||void 0===r?void 0:r.get(n),u=!c,l=u||c&&!c.available;this.log.info("onSessionCreated: ".concat(i,"#").concat(n," is ").concat(u?"new":"existed")),u&&(this.log.info("Created ".concat(i,"#").concat(n)),c=new Pt(i,n,this,this.reporter),this.sessionMap.get(i)?this.sessionMap.get(i).set(n,c):this.sessionMap.set(i,new Map([[n,c]]))),this.sessionEndPointMap.set(o,c),c.handleSessionCreated(o,s,a),l&&this.emit("sessionCreate",{type:i,id:n})}},{key:"handleSessionClosed",value:function(e){var t,r=e.sessionKey,n=e.sessionType,i=null===(t=this.sessionMap.get(n))||void 0===t?void 0:t.get(r);this.log.info("handleSessionClosed: ".concat(n,"#").concat(r," is ").concat(i?"closed":"not existed")),i&&i.state!==mt.UNINITED&&(i.handleSessionClosed(),this.log.info("Closed ".concat(n,"#").concat(r," is closed")),this.sessionMap.get(n).delete(r),this.sessionEndPointMap.delete(i.endpointId),this.emit("sessionClose",{type:n,id:r}))}},{key:"handleDetachUserConfirm",value:function(e){var t=e.pid,r=e.result;this.log.warn("DetachUser pid:".concat(this.pid," result:").concat(r," state:").concat(this.state)),t==this.pid&&0===r&&this.state!==bt.CLOSED&&(this.state=bt.CLOSED)}},{key:"handleSessionCmdData",value:function(e,t,r){var n;null===(n=this.fetchSession(e,"CmdData"))||void 0===n||n.handleSessionCmdData(t,r)}},{key:"handleSessionData",value:function(e,t,r,n){var i;null===(i=this.fetchSession(t,"SessionData"))||void 0===i||i.handleSessionData(e,r,n)}},{key:"handleGroupCreated",value:function(e,t){var r;null===(r=this.fetchSession(e,"GroupCreated"))||void 0===r||r.handleGroupCreated(t)}},{key:"handleGroupDestroyed",value:function(e,t){var r;null===(r=this.fetchSession(e,"GroupDestroyed"))||void 0===r||r.handleGroupDestroyed(t)}},{key:"handleServiceStatus",value:function(e,t){var r;null===(r=this.fetchSession(e,"ServiceStatus"))||void 0===r||r.handleServiceStatus(t)}},{key:"handleSwitchUpdate",value:function(e){var t=this,r=e.channelUpdates,n={};(void 0===r?[]:r).forEach(function(e){var r;e.endpointId===t.endpointId?(null===(r=e.channel)||void 0===r?void 0:r.type)===Je.DEFAULT&&(t.log.info("SwitchUpdate broadcastChannel:".concat(e.channel.id)),t.broadcastChannel=e.channel.id):n[e.endpointId]=(n[e.endpointId]||[]).concat(e)}),Object.entries(n).forEach(function(e){var r,n=Et(e,2),i=n[0],o=n[1];null===(r=t.fetchSession(+i,"ChannelUpdate"))||void 0===r||r.handleChannelUpdate(o)})}}])}();function Nt(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function kt(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Nt(Object(r),!0).forEach(function(t){R(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Nt(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function Mt(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(Mt=function(){return!!e})()}var wt=function(){function e(t){var r,n,i;_(this,e),n=this,i=w(i=e),r=M(n,Mt()?Reflect.construct(i,[],w(n).constructor):i.apply(n,undefined)),Object.defineProperty(r,"dataSwitcher",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"signaling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"joinInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"sdkVersion",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"scene",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"socket",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"enableDS",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(r,"id",{enumerable:!0,configurable:!0,writable:!0,value:createUuid(6)}),Object.defineProperty(r,"userManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"connectionState",{enumerable:!0,configurable:!0,writable:!0,value:"disconnected"}),Object.defineProperty(r,"securityToken",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"staticConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"checkJoinParam",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",r=!t;return r||("userName"===e?r=(new TextEncoder).encode(t).length>64:"token"!==e&&(r=t.length>64||/[^a-zA-Z0-9_-]/g.test(t))),r?"Join with invalid ".concat(e):""}});var o=t.reporter,a=t.sdkVersion,s=t.scene;return r.sdkVersion=a,r.scene=s,r.reporter=o,r.logger=r.reporter.getLoggerWithPrefix("[ch-channel]"),r.userManager=new Tt(r),r.dataSwitcher=new _t(r),r.handleRejoin=r.handleRejoin.bind(r),r.handleConferenceEvent=r.handleConferenceEvent.bind(r),r.handleDropEvent=r.handleDropEvent.bind(r),r.handleConnectionChangeEvent=r.handleConnectionChangeEvent.bind(r),r.handleUserEvent=r.handleUserEvent.bind(r),r.handleSyncEvent=r.handleSyncEvent.bind(r),r.handleNotifyEvent=r.handleNotifyEvent.bind(r),r.handleReauthEvent=r.handleReauthEvent.bind(r),r.handleBatchNotifyEvent=r.handleBatchNotifyEvent.bind(r),r}return j(e,EventEmitter),k(e,[{key:"gslb",get:function(){return getGslb()}},{key:"addEventListeners",value:function(){this.signaling.on("rejoin",this.handleRejoin),this.signaling.on("conference",this.handleConferenceEvent),this.signaling.on("drop",this.handleDropEvent),this.signaling.on("sync",this.handleSyncEvent),this.signaling.on("connection-state-change",this.handleConnectionChangeEvent),this.userManager.on("user",this.handleUserEvent),this.signaling.on("batch-notify",this.handleBatchNotifyEvent),this.signaling.on("notify",this.handleNotifyEvent),this.signaling.on("reauth",this.handleReauthEvent)}},{key:"removeEventListeners",value:function(){this.signaling.off("rejoin",this.handleRejoin),this.signaling.off("conference",this.handleConferenceEvent),this.signaling.off("drop",this.handleDropEvent),this.signaling.off("sync",this.handleSyncEvent),this.signaling.off("connection-state-change",this.handleConnectionChangeEvent),this.userManager.off("user",this.handleUserEvent),this.signaling.off("batch-notify",this.handleBatchNotifyEvent),this.signaling.off("notify",this.handleNotifyEvent),this.signaling.off("reauth",this.handleReauthEvent)}},{key:"handleLeave",value:function(e){this.reporter.trace.wtLeave(e),this.userManager.clear(),this.dataSwitcher.clear(),this.joinInfo=null,this.removeEventListeners();var t=this.connectionState;this.connectionState="disconnected",this.signaling.diconnect(),this.reporter.stop(),this.emit("connection-state-change","disconnected",t,e)}},{key:"modifyToken",value:function(e,t){var r=JSON.parse(window.atob(t));return r.properties=kt(kt({},r.properties),{},{__nick:e,SdkType:Environment.sdkType,TerminalType:Environment.terminalType}),toBase64(JSON.stringify(r))}},{key:"beforeJoin",value:function(e,t){var r=this;this.reporter.trace.wtGslb("accessGslbStart");var n=e.channel,i=e.uid,o=e.token,a=e.userName;this.handleConnectionChangeEvent("connecting",this.connectionState);var s={timestamp:Date.now(),deviceId:deviceId,userId:i,sdkVersion:this.sdkVersion,channelId:n,accessToken:o};return t&&(s=kt(kt({},s),{},{attributes:kt({},t)})),function(e){var t=e.userId,r=e.accessToken,n=e.sdkVersion,i=getGslb()||le,o="/v1/users/".concat(t,"/access");delete e.userId,delete e.accessToken,delete e.sdkVersion;var a=tt(tt({},e),{},{deviceSpecs:{platform:"Web",sdkv:n,osv:Environment.systemVersion,manu:Environment.manu,model:Environment.model}});return Environment.cpu&&(a.deviceSpecs.cpuUarch=Environment.cpu),new Promise(function(e,t){var n=setTimeout(function(){t(new DingRTCError(ErrorCode.NetworkError,"accessGslb timeout"))},6e3);post$1("".concat(i).concat(o),JSON.stringify(a),{Authorization:r}).then(function(t){e(t),clearTimeout(n)}).catch(function(e){t(e),clearTimeout(n)})}).catch(function(e){return nt.info("".concat(i," access error:").concat(tryJsonStringify(e))),Promise.reject(e)})}(s).then(function(e){var t,n=e.logService,i=e.securityToken,o=e.access,s=o.staticConfig,c=o.iceConfig,u=o.rtcToken,l=o.rtmpConfig,d=s.statsConfig,p=void 0===d?{uploadIntervalMs:UPLOAD_LOG_INTERVAL,statsIntervalMs:METRIC_STATS_INTERVAL$1}:d;r.staticConfig=s,r.reporter.trace.wtGslb("accessGslbSuccess",tryJsonStringify(e));var f=Date.now();return r.reporter.updateCommonInfo({serverDiffTime:(1e3*(null!==(t=null==i?void 0:i.updateTime)&&void 0!==t?t:0)||f)-f}),r.reporter.trace.wtGslb("accessGslbSuccess",tryJsonStringify(e)),n?r.reporter.start({securityToken:i,logService:n,cycleStatsConfig:p}):r.logger.warn("logService is empty"),{rtcToken:r.modifyToken(a,u),iceConfig:c,securityToken:i,rtmpConfig:l}}).catch(function(e){var t=e.code,n=e.cause;return r.logger.info("accessGslbFailed",e),r.reporter.trace.wtGslb("accessGslbFailed",tryJsonStringify(e)),r.connectionState="disconnected",Promise.reject(converToRtcErrorFromGslbCode(t,n))})}},{key:"beforeRejoin",value:function(e,t){var r=this;this.reporter.trace.wtGslb("linkerServerStart");var n=e.channel,i=e.uid,o=e.appId,a=e.userName;return function(e){var t=e.userId;delete e.userId;var r="/v1/users/".concat(t,"/link-server"),n=getGslb()||le;return post$1("".concat(n).concat(r),JSON.stringify(e)).catch(function(e){return nt.info("".concat(n," link-server error:").concat(tryJsonStringify(e))),Promise.reject(e)})}({timestamp:Date.now(),deviceId:deviceId,userId:i,channelId:n,appId:o,securityToken:this.reporter.securityToken,participantId:t}).then(function(e){var t=e.securityToken,n=e.access.rtcToken;return r.reporter.updateSecurityToken(t),r.reporter.trace.wtGslb("linkerServerSuccess",tryJsonStringify(e)),r.modifyToken(a,n)}).catch(function(e){var t=e.code,n=e.cause;throw r.reporter.trace.wtGslb("linkerServerFailed",tryJsonStringify(e)),converToRtcErrorFromGslbCode(t,n)})}},{key:"join",value:(r=C(pe.mark(function e(t,r,n){var i,o,a,s,c,u,l,d,p,f,h,g,m,v,y,b=this;return pe.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:this.logger.info("channel join, joinInfo, gslb",t,r),o=(i=t||{}).channel,a=i.uid,s=i.userName,c=i.appId,u=i.token,l=[this.checkJoinParam("appId",c),this.checkJoinParam("token",u),this.checkJoinParam("channel",o),this.checkJoinParam("uid",a),this.checkJoinParam("userName",s)],d=0;case 1:if(!(d<l.length)){e.next=3;break}if(!l[d]){e.next=2;break}return e.abrupt("return",Promise.reject(new DingRTCError(ErrorCode.JoinChannelFailed,l[d])));case 2:d++,e.next=1;break;case 3:if(r&&setGslb(r),"disconnected"===this.connectionState){e.next=4;break}return e.abrupt("return",Promise.reject(new DingRTCError(ErrorCode.InvaildState,"channel is not disconnected")));case 4:return this.reporter.updateCommonInfo({apid:c,usrid:a,usrn:s,clientId:this.id,roomName:o,udid:Environment.deviceId,sdkvrs:this.sdkVersion}),this.reporter.trace.wtJoin(!0),p=Date.now(),e.next=5,this.beforeJoin(t,n);case 5:return f=e.sent,h=f.rtcToken,g=f.iceConfig,m=f.securityToken,v=f.rtmpConfig,this.securityToken=m,y=Date.now(),this.reporter.trace.join(!0),this.socket&&this.socket.removeAllListeners(),this.socket=new Xe(this.reporter),this.joinInfo=t,this.signaling=new rt(this.socket,this.reporter),this.addEventListeners(),e.abrupt("return",this.signaling.login(kt({token:h},he(this.sdkVersion,this.scene,t.initMicMuted?1:0))).then(function(e){var t=e.room,r=t.participants,n=t.participantsVer,i=e.id;return b.dataSwitcher.init(i),b.userManager.init(r,n,i),b.reporter.trace.join(!1,Date.now()-y,!0),b.reporter.trace.wtJoin(!1,Date.now()-p,!0),{joinResponse:e,iceConfig:g,securityToken:m,rtmpConfig:v}}).catch(function(e){throw b.reporter.trace.wtJoin(!0,Date.now()-p,!1,tryJsonStringify(e)),e}));case 6:case"end":return e.stop()}},e,this)})),function(e,t,n){return r.apply(this,arguments)})},{key:"handleConferenceEvent",value:function(e){this.logger.info("roomEvent ".concat(JSON.stringify(e))),"destroy"===(null==e?void 0:e.action)&&this.handleLeave("channel_banned")}},{key:"handleConnectionChangeEvent",value:function(e,t,r){e!==this.connectionState&&("disconnected"===e?this.handleLeave(r):(this.connectionState=e,this.emit("connection-state-change",e,t)))}},{key:"handleDropEvent",value:function(e){this.logger.info("dropEvent ".concat((null==e?void 0:e.reason)||(null==e?void 0:e.code)));var t=(null==e?void 0:e.code)===Ue.UserReplaced?"uid_replaced":"uid_banned";this.handleLeave(t)}},{key:"handleRejoin",value:function(){var e=this,t=Date.now();this.reporter.trace.wtReJoin(!0),this.beforeRejoin(this.joinInfo,this.userManager.currentPid).then(function(r){var n=Date.now();return e.reporter.trace.rejoin(!0),e.rejoin(r).then(function(){e.dataSwitcher.init(e.userManager.currentPid),e.reporter.trace.rejoin(!1,Date.now()-n),e.reporter.trace.wtReJoin(!1,Date.now()-t,!0)},function(t){throw e.reporter.trace.rejoin(!1,Date.now()-n,!1,tryJsonStringify(t)),t})}).catch(function(r){e.reporter.trace.wtReJoin(!1,Date.now()-t,!1,tryJsonStringify(r)),e.handleLeave("server_error")})}},{key:"handleUserEvent",value:function(e,t){this.emit("user",e,t)}},{key:"handleNotifyEvent",value:function(e,t){this.emit("notify",e,t)}},{key:"handleBatchNotifyEvent",value:function(e){this.emit("batch-notify",e)}},{key:"handleSyncEvent",value:function(e){this.emit("sync",e)}},{key:"handleReauthEvent",value:function(){this.dataSwitcher.init(this.userManager.currentPid)}},{key:"rejoin",value:(t=C(pe.mark(function e(t){var r=this;return pe.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",this.signaling.relogin({token:t}).then(function(e){r.signaling.emit("sync",e)}));case 1:case"end":return e.stop()}},e,this)})),function(e){return t.apply(this,arguments)})},{key:"leave",value:function(){this.signaling.logout(),this.handleLeave("leave")}}]);var t,r}();function _createForOfIteratorHelper$1(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$1(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$1(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$1(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_arrayLikeToArray$1(e,t):void 0}}function _arrayLikeToArray$1(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function ownKeys$1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function _objectSpread$1(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$1(Object(r),!0).forEach(function(t){_defineProperty(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$1(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function _callSuper$3(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$3()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$3(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$3=function(){return!!e})()}var ServiceManager=function(e){function t(e,r){var n;return _classCallCheck$1(this,t),n=_callSuper$3(this,t),Object.defineProperty(n,"rtcSignaling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"sessionManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"groupManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"rtcUserManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"streamManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"remoteAudioTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"internalChannel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"roomId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"defaultVideoStreamType",{enumerable:!0,configurable:!0,writable:!0,value:"high"}),Object.defineProperty(n,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"subscribedAudioStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"micMixedGroups",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"iceConfig",{enumerable:!0,configurable:!0,writable:!0,value:{level:0,iceServerList:[]}}),Object.defineProperty(n,"processingSubParamsMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(n,"joinInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"getSubTraceId",{enumerable:!0,configurable:!0,writable:!0,value:function(){return++t.subAcc}}),Object.defineProperty(n,"handleSubscribeParam",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t,r=e.mediaType,i=e.uid,o=e.auxiliary,a=n.getStream(e),s=n.rtcUserManager.users.get(i),c=n.groups.some(function(e){return e.joined}),u="mcu"===i?n.remoteAudioTrack:o?null==s?void 0:s.auxiliaryTrack:null==s?void 0:s.videoTrack,l=[],d=_toConsumableArray(n.processingSubParamsMap.values());n.logger.info("queueingSubParams",d,e),d.forEach(function(e){return l.push.apply(l,_toConsumableArray(e))});var p=l.find(function(e){return e.uid===i&&e.mediaType===r&&!!e.auxiliary==!!o});return"mcu"===i&&"video"===r||i&&"mcu"!==i&&"audio"===r?t=new DingRTCError(ErrorCode.InvaildArgument,"only support subscribe mcu audio"):"mcu"===i&&c?t=new DingRTCError(ErrorCode.SubscribeInvaild,"cannot subscribe mcu while in group"):u||p?t=new DingRTCError(ErrorCode.SubscribeInvaild,"duplicated subscription"):a||(n.logger.warn("".concat(i," videoTrack not existed")),t=new DingRTCError(ErrorCode.SubscribeStreamNotExisted)),{uid:i,user:s,error:t,stream:a,targetMediaType:r,resolutionInfo:"video"!==r||t?null:calcResolutionInfo(n.defaultVideoStreamType,getStreamSupportedResoArr(a))}}}),Object.defineProperty(n,"checkUnsubParam",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t,r=e.mediaType,i=e.uid,o=e.auxiliary,a=n.getStream(e),s=n.rtcUserManager.users.get(i),c="mcu"===i?n.remoteAudioTrack:o?null==s?void 0:s.auxiliaryTrack:null==s?void 0:s.videoTrack;"mcu"===i&&"video"===r||i&&"mcu"!==i&&"audio"===r?(n.logger.warn("only support unsubscribe mcu audio"),t=new DingRTCError(ErrorCode.InvaildArgument,"only support unsubscribe mcu audio")):a&&c||(n.logger.warn("".concat(i," videoTrack not existing")),t=new DingRTCError(ErrorCode.SubscribeStreamNotExisted));var u=n.sessionManager.getSessionByStreamId(null==a?void 0:a.id);return u||(n.logger.warn("no sub session"),t=new DingRTCError(ErrorCode.SubscribeStreamNotExisted)),{uid:i,user:s,error:t,stream:a,session:u,subMediaType:r,resolutionInfo:"video"!==r||t?null:calcResolutionInfo(n.defaultVideoStreamType,getStreamSupportedResoArr(a))}}}),Object.defineProperty(n,"handleJoinResponse",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t=e.room,r=e.id,i=t.participants,o=t.streams,a=t.streamsVer,s=t.groupList,c=t.groupListVer;n.streamManager.init(o,a),n.groupManager.init(s,c),n.rtcUserManager.init(i,r),n.streamManager.on("stream",n.handleStreamEvent),n.rtcUserManager.on("user",n.handleUserEvent),n.groupManager.on("group",n.handleGroupEvent)}}),n.reporter=r,n.logger=n.reporter.getLoggerWithPrefix("[rtc-svcMgr]"),n.internalChannel=new wt({reporter:r,sdkVersion:SDK_VERSION}),n.rtcSignaling=new RtcSignaling(n.internalChannel),n.client=e,n.micMixedGroups=new Set,n.groupManager=new GroupManager(n),n.streamManager=new StreamManager(n),n.rtcUserManager=new RtcUserManager(n,n.streamManager),n.sessionManager=new SessionManager(e,n),n.subscribedAudioStream="",n.handleStreamEvent=n.handleStreamEvent.bind(n),n.handleUserEvent=n.handleUserEvent.bind(n),n.handleGroupEvent=n.handleGroupEvent.bind(n),n}return _inherits$1(t,e),_createClass$1(t,[{key:"publishedLocalTracks",get:function(){var e=_toConsumableArray(this.sessionManager.sessions.values()).filter(function(e){return e.state===PubSubStates.Processing&&e instanceof Publication}),t=new Set;return e.map(function(e){if(e.tracks){var r,n;if((null===(r=e.tracks)||void 0===r?void 0:r[0])instanceof MixedLocalAudioTrack){var i=e.tracks[0].getMicAudioTrack();i&&t.add(i);var o=e.tracks[0].getScreenAudioTrack();return void(o&&t.add(o))}(null===(n=e.tracks)||void 0===n?void 0:n[0])&&t.add(e.tracks[0])}}),_toConsumableArray(t.values())}},{key:"groups",get:function(){var e=this;return this.groupManager.groupList.map(function(t){return _objectSpread$1(_objectSpread$1({},t),{},{audioPublished:e.micMixedGroups.has(t.id)})})}},{key:"handleStreamEvent",value:function(e,t){var r=t.id,n=t.owner,i=t.mediaType,o=t.auxiliary,a=t.owners,s=t.updateStatus,c=t.properties,u=t.highestResolutionLevel,l=this.internalChannel.userManager.participants,d=l.get(n),p=this.rtcUserManager.users.get(null==d?void 0:d.user),f=n===this.rtcUserManager.currentSelfPid;if("add"===e&&!f&&p)this.client.emit("user-published",p,i,o);else if("remove"===e&&p&&!f)this.sessionManager.removeSession(void 0,r),"video"===i&&(o&&p.auxiliaryTrack&&(p.auxiliaryTrack.stopPlay(),p.auxiliaryTrack=null),!o&&p.videoTrack&&(p.videoTrack.stopPlay(),p.videoTrack=null)),this.client.emit("user-unpublished",p,i,o);else if("update"===e){if(s)this.client.emit("user-info-updated",(null==p?void 0:p.userId)||this.rtcUserManager.currentUid,s,o);else if(null!=(null==c?void 0:c.mirror)){var h=o?p.auxiliaryTrack:p.videoTrack;null==h||h.setSourceMirror(c.mirror)}else if(null!=u){var g=this.sessionManager.getSessionByStreamId(r);if(!g)return;g.stream.media.video.highestResolutionLevel=u;var m=g.userConfigResolution,v=g.resolutionInfo;if(u>=m.resolutionLevel&&m.resolutionLevel>v.resolutionLevel)g.applyOptions(m,!0);else if(u<m.resolutionLevel){var y=calcResolutionInfo(getResoLevelNameByResoLevelNum(u),getStreamSupportedResoArr(g.stream));g.applyOptions(y,!0)}}}else if("volumeActive"===e){var b=a.map(function(e){return l.get(e)}).map(function(e){return null==e?void 0:e.user}).filter(function(e){return!!e});this.client.emit("volume-indicator",b)}}},{key:"handleGroupEvent",value:function(e,t,r){var n=this;if("add"===e)this.client.emit("group-add",t);else if("remove"===e){var i;if(this.micMixedGroups.delete(t.id),this.logger.info("unsub group for group removed",t),r&&(null===(i=r.audio)||void 0===i?void 0:i.id)===this.subscribedAudioStream){var o=r.audio;this.sessionManager.batchUnscribe([{stream:o,session:this.sessionManager.getSessionByStreamId(o.id),targetMediaType:"audio"}]).then(function(){o.id===n.subscribedAudioStream&&(n.updateSubscribedAudioStream(!1,""),n.remoteAudioTrack.stopPlay(),n.remoteAudioTrack=null)})}this.client.emit("group-remove",t)}else if("user-join"===e)this.client.emit("group-user-join",t,r);else if("user-leave"===e)this.client.emit("group-user-leave",t,r);else if("info-updated"===e){var a=r.key,s=r.value;this.client.emit("group-info-updated",t,a,s)}}},{key:"handleUserEvent",value:function(e,t){"join"===e?(this.client.emit("user-joined",t),t.hasVideo&&this.client.emit("user-published",t,"video"),t.hasAudio&&this.client.emit("user-published",t,"audio"),t.hasAuxiliary&&this.client.emit("user-published",t,"video",!0)):"leave"===e?this.client.emit("user-left",t):this.logger.warn("unhandled inner rtc user emitted event",e,t)}},{key:"getStream",value:function(e){var t,r=e.groupId,n=e.uid,i=e.auxiliary;if(r){var o,a=this.groupManager.groups.get(r);return null==a||null===(o=a.audioInfo)||void 0===o?void 0:o.audio}var s="mcu"===n?_toConsumableArray(this.streamManager.streams.values()):null===(t=this.rtcUserManager.users.get(n))||void 0===t?void 0:t.relatedStreams;return"mcu"===n?s.find(function(e){var t=e.info.owner,r=e.type;return"admin"===t&&"mixed"===r}):s.find(function(e){var t=e.media.video;return(null==t?void 0:t.source)===(i?VideoSourceInfo.SCREENCAST:VideoSourceInfo.CAMERA)})}},{key:"join",value:(c=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n,i,o,a,s;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return this.logger.info("join",clientConfig.gslb[0]),this.sessionManager.mixedLocalAudioTrack.setSelfMicMutedProperty(t.initMicMuted),e.next=1,this.rtcSignaling.join(t,clientConfig.gslb[0]);case 1:return n=e.sent,i=n.joinResponse,o=n.iceConfig,null!=(null==(a=this.internalChannel.staticConfig)||null===(r=a.websdkConfig)||void 0===r?void 0:r.simulcast)&&(clientConfig.simulcast=null==a||null===(s=a.websdkConfig)||void 0===s?void 0:s.simulcast),this.roomId=i.room.id,parseSubSsrcInfo(i.room.ssrcMask,i.room.ssrcClientSequence),this.reporter.updateCommonInfo({roomId:this.roomId,participantId:i.id}),o&&o.uis&&this.setIceConfig(o.uis),this.sessionManager.start(),this.handleJoinResponse(i),e.abrupt("return",i);case 2:case"end":return e.stop()}},e,this)})),function(e){return c.apply(this,arguments)})},{key:"setIceConfig",value:function(e){var t=e.iceServerList,r=void 0===t?[]:t;e.level&&(e.iceServerList=r.filter(function(e){return/([0-9]{1,3}\.){3}[0-9]{1,3}/i.test(e)}),this.iceConfig=e)}},{key:"clear",value:function(){var e;this.rtcUserManager.clear(),this.streamManager.clear(),this.sessionManager.clear(),this.micMixedGroups.clear(),this.groupManager.clear(),this.subscribedAudioStream="",null===(e=this.remoteAudioTrack)||void 0===e||e.stopPlay(),this.remoteAudioTrack=null,this.iceConfig=null,this.roomId="",this.streamManager.off("stream",this.handleStreamEvent),this.rtcUserManager.off("user",this.handleUserEvent),this.groupManager.off("group",this.handleGroupEvent)}},{key:"leave",value:function(){if("disconnected"!==this.internalChannel.connectionState)return this.reporter.trace.leave(),this.rtcSignaling.leave()}},{key:"publish",value:(s=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n,i,o;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return r=this.micMixedGroups,n=this.groupManager,i=this.groups,o=[],i.some(function(e){return e.joined})?o.push.apply(o,_toConsumableArray(_toConsumableArray(r).map(function(e){var t;return null===(t=n.groups.get(e))||void 0===t||null===(t=t.audioInfo)||void 0===t?void 0:t.label}).filter(function(e){return!!e}))):o.push("common"),e.abrupt("return",this.sessionManager.batchPublish(t,o));case 1:case"end":return e.stop()}},e,this)})),function(e){return s.apply(this,arguments)})},{key:"unpublish",value:(a=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n,i,o,a,s,c,u=this;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.sessionManager.republishPromise){e.next=5;break}return this.logger.info("wait for repub before unpublish"),e.prev=1,e.next=2,this.sessionManager.republishPromise;case 2:e.next=4;break;case 3:e.prev=3,e.catch(1);case 4:this.logger.info("go unpublish after repub");case 5:return r=t.filter(function(e){return"audio"===e.trackMediaType}),n=t.filter(function(e){return"audio"!==e.trackMediaType}),i=!1,r.length>0&&(o=(this.sessionManager.mixedLocalAudioTrack.getMicAudioTrack()?1:0)+(this.sessionManager.mixedLocalAudioTrack.getScreenAudioTrack()?1:0),r.length>=o?(this.sessionManager.mixedLocalAudioTrack.setMicAudioTrack(null),this.sessionManager.mixedLocalAudioTrack.setScreenAudioTrack(null),n.push(this.sessionManager.mixedLocalAudioTrack),i=!0):(r[0].source===exports.AudioSourceInfo.MIC?this.sessionManager.mixedLocalAudioTrack.setMicAudioTrack(null):this.sessionManager.mixedLocalAudioTrack.setScreenAudioTrack(null),this.sessionManager.mixedLocalAudioTrack.updateMixedAudioTrackToPub())),a=new Set(n.map(function(e){return e.getTrackId()})),(s=_toConsumableArray(this.sessionManager.sessions.values()).filter(function(e){var t,r;return e instanceof Publication&&a.has(null===(t=e.tracks)||void 0===t||null===(t=t[0])||void 0===t?void 0:t.getTrackId())&&"video"===(null===(r=e.tracks)||void 0===r||null===(r=r[0])||void 0===r?void 0:r.trackMediaType)})).forEach(function(e){u.reporter.trace.unpublish(e.id)}),c=_toConsumableArray(s),i&&(c.push(this.sessionManager.mixedLocalAudioTrack.getPublication()),this.sessionManager.mixedLocalAudioTrack.setPublication(null)),e.abrupt("return",this.sessionManager.batchUnPublish(c));case 6:case"end":return e.stop()}},e,this,[[1,3]])})),function(e){return a.apply(this,arguments)})},{key:"updateSubbedRemoteTrack",value:function(e,t){var r=this;if(null==t||!t.mediaStream)return null;var n=this.rtcUserManager.users.get(e.uid);if("audio"===e.mediaType){var i=this.remoteAudioTrack;return this.remoteAudioTrack=updateRemoteTrack(t.mediaStream,"audio","mcu",this.remoteAudioTrack),this.updateSubscribedAudioStream(!0,""),i||t.once("audio-first-frame",function(){r.remoteAudioTrack.emit("first-frame-decoded")}),this.remoteAudioTrack}return n.updateSubbedVideoTrack(t,e.auxiliary)}},{key:"batchSubscribe",value:(o=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n,i,o,a,s=this;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return r=t.map(this.handleSubscribeParam),n=this.getSubTraceId(),this.processingSubParamsMap.set(n,t),e.prev=1,e.next=2,this.sessionManager.batchSubscribe(r);case 2:return i=e.sent,o=[],t.forEach(function(e,t){var r=e.auxiliary,n=e.uid,a=i[t],c=a.error,u=a.subscription;o.push({uid:n,auxiliary:r,error:c,track:s.updateSubbedRemoteTrack(e,u)})}),e.abrupt("return",o);case 3:throw e.prev=3,a=e.catch(1),this.logger.error("batch sub error",a),a;case 4:return e.prev=4,this.processingSubParamsMap.delete(n),e.finish(4);case 5:case"end":return e.stop()}},e,this,[[1,3,4,5]])})),function(e){return o.apply(this,arguments)})},{key:"batchUnsubscribe",value:(i=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n,i,o,a,s,c,u,l,d,p=this;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.sessionManager.resubscribePromise){e.next=5;break}return this.logger.info("wait for resuball before unsubscribe"),e.prev=1,e.next=2,this.sessionManager.resubscribePromise;case 2:e.next=4;break;case 3:e.prev=3,e.catch(1);case 4:this.logger.info("go unsubscribe after resuball");case 5:r=[],n=_createForOfIteratorHelper$1(t);try{for(n.s();!(i=n.n()).done;)o=i.value,a=this.checkUnsubParam(o),s=a.session,c=a.stream,u=a.user,l=a.uid,d=a.error,s&&c&&!d&&(this.reporter.trace.unsubscribe({sessionId:s.id,remoteStreamId:c.id,remoteUserId:l}),r.push(_objectSpread$1({stream:c,user:u,session:s},o)))}catch(e){n.e(e)}finally{n.f()}if(r.length){e.next=6;break}return e.abrupt("return",Promise.resolve());case 6:return e.abrupt("return",this.sessionManager.batchUnscribe(r).then(function(e){for(var t=0,n=r;t<n.length;t++){var i,o=n[t],a=o.mediaType,s=o.user,c=o.auxiliary;if("audio"===a)p.updateSubscribedAudioStream(!1,""),null===(i=p.remoteAudioTrack)||void 0===i||i.stopPlay(),p.remoteAudioTrack=null;else if(c){var u;null===(u=s.auxiliaryTrack)||void 0===u||u.stop(),s.auxiliaryTrack=null}else{var l;null===(l=s.videoTrack)||void 0===l||l.stop(),s.videoTrack=null}}return e}));case 7:case"end":return e.stop()}},e,this,[[1,3]])})),function(e){return i.apply(this,arguments)})},{key:"updateSubscribedAudioStream",value:function(e,t){this.subscribedAudioStream=t,this.emit("suscribedAudio",e,t)}},{key:"subscribeGroup",value:function(e){var t=this,r=this.getStream({groupId:e});if(!r)throw new DingRTCError(ErrorCode.InvaildArgument,"cannot find audio info of the group");if(this.subscribedAudioStream)throw new DingRTCError(ErrorCode.InvaildState,"you were subscribed group or channel already");return this.sessionManager.batchSubscribe([{stream:r,uid:e,targetMediaType:"audio"}]).then(function(n){return t.updateSubscribedAudioStream(!0,r.id),t.remoteAudioTrack=updateRemoteTrack(n[0].subscription.mediaStream,"audio",e,t.remoteAudioTrack),t.remoteAudioTrack})}},{key:"unsubscribeGroup",value:function(e){var t=this,r=this.getStream({groupId:e});return r?this.subscribedAudioStream!==r.id?Promise.reject(new DingRTCError(ErrorCode.InvaildState,"you were not subscribed the group")):this.sessionManager.batchUnscribe([{stream:r,session:this.sessionManager.getSessionByStreamId(r.id),targetMediaType:"audio"}]).then(function(){r.id===t.subscribedAudioStream&&(t.updateSubscribedAudioStream(!1,""),t.remoteAudioTrack.stopPlay(),t.remoteAudioTrack=null)}):Promise.reject(new DingRTCError(ErrorCode.InvaildArgument,"cannot find audio info of the group"))}},{key:"setRemoteStreamType",value:function(e,t,r){this.logger.info("setRemoteStreamType",e,t,r);var n=this.getStream({uid:e,mediaType:"video",auxiliary:r}),i=this.sessionManager.getSessionByStreamId(n.id),o=calcResolutionInfo(t,getStreamSupportedResoArr(n));return i.applyOptions(o,!1)}},{key:"joinGroup",value:function(e){var t=this,r=e.groupId,n=e.publishAudioToGroup;return this.groupManager.join(e).then(function(e){t.logger.info("joinGroup response",e);var i=e.joinGroupAudioSuccess;n&&i&&t.micMixedGroups.add(r)})}},{key:"leaveGroup",value:function(e){var t=this,r=e.groupId;return this.groupManager.leave(e).then(function(){t.micMixedGroups.delete(r)})}},{key:"dismissGroup",value:function(e){var t=this;return this.groupManager.dismiss(e).then(function(){t.micMixedGroups.delete(e)})}},{key:"mixGroupAudio",value:function(e,t,r){return this.rtcSignaling.streamControl({operation:r,streamId:e,data:t})}},{key:"setGroupProperties",value:function(e,t){return this.groupManager.setProperties(e,t)}},{key:"publishToGroup",value:(n=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n,i,o=arguments;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(r=!(o.length>1&&void 0!==o[1])||o[1],n=[],null!=t&&n.push(this.groupManager.groups.get(t).audioInfo.label),this.sessionManager.mixedLocalAudioTrack.isPublished()){e.next=1;break}throw this.logger.error("publishToGroup: no published audio track found"),new DingRTCError(ErrorCode.InvaildState,"no published audio track found");case 1:if(i=this.streamManager.getStreamByTrackId(this.sessionManager.mixedLocalAudioTrack.getTrackId()),null==t){e.next=4;break}return e.next=2,this.mixGroupAudio(i.id,n[0],"mix");case 2:if(this.micMixedGroups.add(t),!r){e.next=3;break}return e.next=3,this.mixGroupAudio(i.id,"common","unmix");case 3:e.next=5;break;case 4:return e.next=5,this.mixGroupAudio(i.id,"common","mix");case 5:case"end":return e.stop()}},e,this)})),function(e){return n.apply(this,arguments)})},{key:"unpublishFromGroup",value:(r=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n,i,o=arguments;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(r=o.length>1&&void 0!==o[1]&&o[1],n=this.groupManager.groups.get(t).audioInfo.label,this.sessionManager.mixedLocalAudioTrack.isPublished()){e.next=1;break}throw this.logger.error("unpublishFromGroup: no published audio track found"),new DingRTCError(ErrorCode.InvaildState,"no published audio track found");case 1:return i=this.streamManager.getStreamByTrackId(this.sessionManager.mixedLocalAudioTrack.getTrackId()),e.next=2,this.mixGroupAudio(i.id,n,"unmix");case 2:if(this.micMixedGroups.delete(t),!r){e.next=3;break}return e.next=3,this.mixGroupAudio(i.id,"common","mix");case 3:case"end":return e.stop()}},e,this)})),function(e){return r.apply(this,arguments)})}]);var r,n,i,o,a,s,c}(EventEmitter);function _callSuper$2(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$2()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$2(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$2=function(){return!!e})()}Object.defineProperty(ServiceManager,"subAcc",{enumerable:!0,configurable:!0,writable:!0,value:0});var initAudioDeviceBufferInfo={timestamp:-1,maxPlayLevel:-1,maxRecLevel:-1},DeviceMonitor=function(e){function t(e){var r,n;return _classCallCheck$1(this,t),r=_callSuper$2(this,t),Object.defineProperty(r,"audioDeviceBufferReport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"audioDeviceBufferInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"makeReport",{enumerable:!0,configurable:!0,writable:!0,value:(n=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){var t,n,i,o,a;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=1,r.client.getLocalAudioStats();case 1:return t=e.sent,n=t.audioLevel,e.next=2,r.client.getRemoteAudioStats();case 2:i=e.sent,o=i.audioLevel,a={timestamp:Date.now(),maxRecLevel:Math.min(1,n||0),maxPlayLevel:Math.min(1,Math.max(0,o||0))},r.audioDeviceBufferInfo.timestamp>0&&(r.audioDeviceBufferReport={attr_duration_ms:getDelta(a.timestamp,r.audioDeviceBufferInfo.timestamp),attr_play_level:Math.round(32767*a.maxPlayLevel),attr_rec_level:Math.round(32767*a.maxRecLevel)},r.emit("audio-device-buffer",Object.assign({},r.audioDeviceBufferReport))),r.audioDeviceBufferInfo=a;case 3:case"end":return e.stop()}},e)})),function(){return n.apply(this,arguments)})}),r.audioDeviceBufferReport={attr_duration_ms:0,attr_rec_level:0,attr_play_level:0},r.audioDeviceBufferInfo=Object.assign({},initAudioDeviceBufferInfo),r.client=e,r}return _inherits$1(t,e),_createClass$1(t)}(Monitor);function ownKeys(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function _objectSpread(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys(Object(r),!0).forEach(function(t){_defineProperty(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function _createForOfIteratorHelper(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_arrayLikeToArray(e,t):void 0}}function _arrayLikeToArray(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _callSuper$1(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$1()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$1(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$1=function(){return!!e})()}function _superPropGet(e,t,r,n){var i=_get(_getPrototypeOf$1(e.prototype),t,r);return 2&n&&"function"==typeof i?function(e){return i.apply(r,e)}:i}var DingRTCClient=function(e){function t(e){var r;return _classCallCheck$1(this,t),r=_callSuper$1(this,t),Object.defineProperty(r,"channelName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"id",{enumerable:!0,configurable:!0,writable:!0,value:createUuid(6)}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:registerReporter(r.id)}),Object.defineProperty(r,"logger",{enumerable:!0,configurable:!0,writable:!0,value:r.reporter.getLoggerWithPrefix("[rtc-client]")}),Object.defineProperty(r,"serviceManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"monitor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"syncStatTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"clientStatSync",{enumerable:!0,configurable:!0,writable:!0,value:[0,0,0,0,0,0]}),Object.defineProperty(r,"currentClientState",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(r,"deviceChecker",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.serviceManager=new ServiceManager(r,r.reporter),r.handleVisibilitychange=r.handleVisibilitychange.bind(r),r.handleNetworkQuality=r.handleNetworkQuality.bind(r),r.handleConnectionChangeEvent=r.handleConnectionChangeEvent.bind(r),r.handlePageUnload=r.handlePageUnload.bind(r),r.init(),r.deviceChecker=null==e?void 0:e.deviceChecker,r}return _inherits$1(t,e),_createClass$1(t,[{key:"remoteUsers",get:function(){return this.serviceManager.rtcUserManager.remoteUsers}},{key:"groups",get:function(){return this.serviceManager.groups}},{key:"userId",get:function(){var e;return(null===(e=this.serviceManager.internalChannel)||void 0===e||null===(e=e.joinInfo)||void 0===e?void 0:e.uid)||""}},{key:"localTracks",get:function(){return this.serviceManager.publishedLocalTracks}},{key:"connectionState",get:function(){var e;return(null===(e=this.serviceManager.internalChannel)||void 0===e?void 0:e.connectionState)||"disconnected"}},{key:"init",value:function(){this.syncStatTimer&&(removeTimer(this.syncStatTimer,"interval"),this.syncStatTimer=null),this.currentClientState="",this.channelName="",this.serviceManager.clear(),this.removeEventListeners(),this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.clientStatSync=[0,0,0,0,0,0]}},{key:"emit",value:function(e){for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];var o;"network-quality"!==e&&"volume-indicator"!==e&&(o=this.logger).info.apply(o,["client emit event",e].concat(n));return _superPropGet(t,"emit",this,3)([e].concat(n))}},{key:"startPlugin",value:(l=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t,r){var n;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(this.logger.info("startPlugin",t,r),"DeviceChecker"===t){e.next=1;break}return this.logger.error("not supported plugin",t),e.abrupt("return",Promise.reject("not supported plugin"));case 1:if(this.deviceChecker){e.next=2;break}return this.logger.error("deviceChecker should be created in DingRTC.createClient before start"),e.abrupt("return",Promise.reject("plugin not created"));case 2:return e.prev=2,e.abrupt("return",this.deviceChecker.start(r));case 3:return e.prev=3,n=e.catch(2),this.logger.error("startPlugin error",t,r,n),e.abrupt("return",Promise.reject(n));case 4:case"end":return e.stop()}},e,this,[[2,3]])})),function(e,t){return l.apply(this,arguments)})},{key:"join",value:(u=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n,i=this;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return this.logger.info("join",t),e.prev=1,this.addEventListeners(),void 0===t.initMicMuted&&(t.initMicMuted=!0),e.next=2,this.serviceManager.join(t).then(function(e){var r;return i.channelName=t.channel,i.monitor=new DeviceMonitor(i),i.monitor.on("audio-device-buffer",function(e){i.reporter.metric.audioDeviceBuffer(e)}),i.syncStatTimer=addTimer(function(){i.sendClientStatToRemote()},NETWORK_QUALITY_TIMEOUT,"interval"),{remoteUsers:i.remoteUsers,timeLeft:null===(r=e.room)||void 0===r?void 0:r.timeLeft}}).catch(function(e){throw i.init(),e});case 2:return r=e.sent,e.abrupt("return",r);case 3:return e.prev=3,n=e.catch(1),this.logger.error("join error",t,n),e.abrupt("return",Promise.reject(n));case 4:case"end":return e.stop()}},e,this,[[1,3]])})),function(e){return u.apply(this,arguments)})},{key:"setRemoteDefaultVideoStreamType",value:function(e){this.logger.info("setRemoteDefaultVideoStreamType",e),this.serviceManager.defaultVideoStreamType=e}},{key:"leave",value:function(){this.logger.info("leave"),this.serviceManager.leave(),this.init()}},{key:"publish",value:(c=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n,i,o,a,s,c,u,l,d,p,f=this;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if((r=this.logger).info.apply(r,["publish"].concat(_toConsumableArray((Array.isArray(t)?t:[t]).map(function(e){return{mediaType:null==e?void 0:e.trackMediaType,trackId:null==e?void 0:e.getTrackId(),source:null==e?void 0:e.source}})))),e.prev=1,"connected"===this.connectionState){e.next=2;break}return e.abrupt("return",Promise.reject(new DingRTCError(ErrorCode.PublishNotJoinChannel)));case 2:n=(Array.isArray(t)?t:[t]).filter(function(e){return e instanceof LocalTrack&&!f.localTracks.includes(e)}),i=n.concat(this.localTracks),o=_defineProperty(_defineProperty(_defineProperty(_defineProperty({},"video"+exports.VideoSourceInfo.CAMERA,0),"video"+exports.VideoSourceInfo.SCREENCAST,0),"audio"+exports.AudioSourceInfo.MIC,0),"audio"+exports.AudioSourceInfo.SCREENCAST,0),a=_createForOfIteratorHelper(i),e.prev=3,a.s();case 4:if((s=a.n()).done){e.next=6;break}if(c=s.value,o[c.trackMediaType+c.source]++,!(o[c.trackMediaType+c.source]>=2)){e.next=5;break}throw new DingRTCError(ErrorCode.QuotaLimitExceed,"".concat(c.trackMediaType,"-").concat(c.source," published already"));case 5:e.next=4;break;case 6:e.next=8;break;case 7:e.prev=7,d=e.catch(3),a.e(d);case 8:return e.prev=8,a.f(),e.finish(8);case 9:if(n.length){e.next=10;break}throw new DingRTCError(ErrorCode.PublishNoStream);case 10:return e.next=11,this.serviceManager.publish(n);case 11:return u=e.sent,e.abrupt("return",u);case 12:return e.prev=12,p=e.catch(1),(l=this.logger).error.apply(l,["publish error"].concat(_toConsumableArray((Array.isArray(t)?t:[t]).map(function(e){return{mediaType:null==e?void 0:e.trackMediaType,trackId:null==e?void 0:e.getTrackId(),source:null==e?void 0:e.source}})),[p])),e.abrupt("return",Promise.reject(p));case 13:case"end":return e.stop()}},e,this,[[1,12],[3,7,8,9]])})),function(e){return c.apply(this,arguments)})},{key:"unpublish",value:(s=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n,i,o,a;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if((r=this.logger).info.apply(r,["unpublish param"].concat(_toConsumableArray((Array.isArray(t)?t:[t]).map(function(e){return{mediaType:null==e?void 0:e.trackMediaType,trackId:null==e?void 0:e.getTrackId(),source:null==e?void 0:e.source}})))),e.prev=1,n=Array.isArray(t)?t:[t],t||(n=this.localTracks),this.logger.info("unpublish tracks",n.map(function(e){return e.trackMediaType})),"connected"===this.connectionState){e.next=2;break}return e.abrupt("return",Promise.reject(new DingRTCError(ErrorCode.ConnectionConnectFail)));case 2:return e.next=3,this.serviceManager.unpublish(n);case 3:return i=e.sent,e.abrupt("return",i);case 4:return e.prev=4,a=e.catch(1),(o=this.logger).error.apply(o,["unpub error"].concat(_toConsumableArray((Array.isArray(t)?t:[t]).map(function(e){return{mediaType:null==e?void 0:e.trackMediaType,trackId:null==e?void 0:e.getTrackId(),source:null==e?void 0:e.source}})),[a])),e.abrupt("return",Promise.reject(a));case 5:case"end":return e.stop()}},e,this,[[1,4]])})),function(e){return s.apply(this,arguments)})},{key:"subscribe",value:(a=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t,r,n){var i,o;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(e.prev=0,this.logger.info("subscribe",t,r,n),"connected"===this.connectionState){e.next=1;break}throw new DingRTCError(ErrorCode.SubscribeNotJoinChannel);case 1:return e.next=2,this.serviceManager.batchSubscribe([{uid:t,mediaType:r,auxiliary:n}]).then(function(e){var t=e[0],r=t.error,n=t.track;if(r)throw r;return n});case 2:return i=e.sent,e.abrupt("return",i);case 3:return e.prev=3,o=e.catch(0),this.logger.error("subscribe error",t,r,n,o),e.abrupt("return",Promise.reject(o));case 4:case"end":return e.stop()}},e,this,[[0,3]])})),function(e,t,r){return a.apply(this,arguments)})},{key:"batchSubscribe",value:(o=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(e.prev=0,this.logger.info("batchSubscribe",t),Array.isArray(t)&&t.length){e.next=1;break}return e.abrupt("return");case 1:if("connected"===this.connectionState){e.next=2;break}throw new DingRTCError(ErrorCode.SubscribeNotJoinChannel);case 2:return e.next=3,this.serviceManager.batchSubscribe(t.map(function(e){return _objectSpread(_objectSpread({},e),{},{action:"subscribe"})}));case 3:return r=e.sent,e.abrupt("return",r);case 4:return e.prev=4,n=e.catch(0),this.logger.error("batchSubscribe error",n),e.abrupt("return",Promise.reject(n));case 5:case"end":return e.stop()}},e,this,[[0,4]])})),function(e){return o.apply(this,arguments)})},{key:"unsubscribe",value:(i=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t,r,n){var i,o;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(this.logger.info("unsubscribe",t,r,n),e.prev=1,"connected"===this.connectionState){e.next=2;break}return e.abrupt("return",Promise.reject(new DingRTCError(ErrorCode.ConnectionConnectFail)));case 2:return e.next=3,this.serviceManager.batchUnsubscribe([{uid:t,auxiliary:n,mediaType:r}]).then(function(e){var t,r=null==e||null===(t=e[0])||void 0===t?void 0:t.error;if(r)throw r});case 3:return i=e.sent,e.abrupt("return",i);case 4:return e.prev=4,o=e.catch(1),this.logger.error("unsubscribe error",t,r,o),e.abrupt("return",Promise.reject(o));case 5:case"end":return e.stop()}},e,this,[[1,4]])})),function(e,t,r){return i.apply(this,arguments)})},{key:"batchUnsubscribe",value:(n=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(this.logger.info("batchUnsubscribe",t),e.prev=1,Array.isArray(t)&&t.length){e.next=2;break}return e.abrupt("return");case 2:if("connected"===this.connectionState){e.next=3;break}return e.abrupt("return",Promise.reject(new DingRTCError(ErrorCode.SubscribeNotJoinChannel)));case 3:return e.next=4,this.serviceManager.batchUnsubscribe(t.map(function(e){return _objectSpread(_objectSpread({},e),{},{action:"unsubscribe"})}));case 4:return r=e.sent,e.abrupt("return",r);case 5:return e.prev=5,n=e.catch(1),this.logger.error("batchUnsubscribe error",t,n),e.abrupt("return",Promise.reject(n));case 6:case"end":return e.stop()}},e,this,[[1,5]])})),function(e){return n.apply(this,arguments)})},{key:"getLocalAudioStats",value:function(){return this.serviceManager.sessionManager.getLocalAudioStats("user")}},{key:"getLocalVideoStats",value:function(){return this.serviceManager.sessionManager.getLocalVideoStats("user")}},{key:"setRemoteVideoStreamType",value:(r=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t,r,n){var i,o,a,s=this;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(e.prev=0,this.logger.info("setRemoteVideoStreamType",t,r,n),"connected"===this.connectionState){e.next=1;break}return e.abrupt("return",Promise.reject(new DingRTCError(ErrorCode.ConnectionConnectFail)));case 1:if(null!=(i=this.remoteUsers.find(function(e){return e.userId===t}))&&i.relatedStreams){e.next=2;break}return this.logger.info("".concat(t," videoTrack not existed")),e.abrupt("return",Promise.reject("viedoTrack doesnt exiested"));case 2:return e.next=3,this.serviceManager.setRemoteStreamType(t,r,n).then(function(){s.emit("stream-type-changed",t,r,n)});case 3:return o=e.sent,e.abrupt("return",o);case 4:return e.prev=4,a=e.catch(0),this.logger.error("setRemoteVideoStreamType error",t,r,n,a),e.abrupt("return",Promise.reject(a));case 5:case"end":return e.stop()}},e,this,[[0,4]])})),function(e,t,n){return r.apply(this,arguments)})},{key:"getRemoteVideoStats",value:function(){return this.serviceManager.sessionManager.getRemoteVideoStats("user")}},{key:"getRemoteAudioStats",value:function(){return this.serviceManager.sessionManager.getRemoteAudioStats("user")}},{key:"getRemoteNetworkQuality",value:function(){var e={};return this.remoteUsers.forEach(function(t){var r,n,i=t.properties,o=t.userId;e[o]={downlinkNetworkQuality:Number((null==i||null===(r=i[USER_STATS_SYNC])||void 0===r?void 0:r[ClientUserStats.DOWNLINK])||0),uplinkNetworkQuality:Number((null==i||null===(n=i[USER_STATS_SYNC])||void 0===n?void 0:n[ClientUserStats.UPLINK])||0)}}),e}},{key:"handleConnectionChangeEvent",value:function(e,t,r){this.logger.info("connectionStateChange from ".concat(t," to ").concat(e," ").concat(r||"")),"disconnected"===e&&this.init(),this.emit("connection-state-change",e,t,r)}},{key:"sendClientStatToRemote",value:function(){var e=this,t=this.clientStatSync.join("");if(t!==this.currentClientState){var r=transNativeAndWebNetworkRank(null,t[ClientUserStats.UPLINK]),n=transNativeAndWebNetworkRank(null,this.currentClientState[ClientUserStats.UPLINK]),i=transNativeAndWebNetworkRank(null,t[ClientUserStats.DOWNLINK]),o=transNativeAndWebNetworkRank(null,this.currentClientState[ClientUserStats.DOWNLINK]);r===n&&i===o||this.serviceManager.rtcUserManager.setParticipantProperties(t).catch(function(t){e.logger.info("setParticipantProperties error ".concat(tryJsonStringify(t)))}),this.currentClientState=t}}},{key:"handleVisibilitychange",value:function(){var e="visible"!==document.visibilityState,t=e?TraceEvent$1.APP_BACKGROUND:TraceEvent$1.APP_FOREGROUND;(Environment.isAndroid()||Environment.isIOS())&&(this.reporter.sender.sendEvent(t),this.clientStatSync[ClientUserStats.BACKGROUND_MODE]=Number(e))}},{key:"handleNetworkQuality",value:function(e,t){this.clientStatSync[ClientUserStats.UPLINK]=e,this.clientStatSync[ClientUserStats.DOWNLINK]=t,this.emit("network-quality",e,t)}},{key:"handlePageUnload",value:function(e){"connected"===this.connectionState&&(this.logger.info("leave for ".concat(e.type)),this.leave())}},{key:"addEventListeners",value:function(){window.addEventListener(Environment.isSafari()?"beforeunload":"pagehide",this.handlePageUnload),document.addEventListener("visibilitychange",this.handleVisibilitychange),this.serviceManager.sessionManager.on("network-quality",this.handleNetworkQuality),this.serviceManager.rtcSignaling.on("connection-state-change",this.handleConnectionChangeEvent)}},{key:"removeEventListeners",value:function(){window.removeEventListener(Environment.isSafari()?"beforeunload":"pagehide",this.handlePageUnload),document.removeEventListener("visibilitychange",this.handleVisibilitychange),this.serviceManager.sessionManager.off("network-quality",this.handleNetworkQuality),this.serviceManager.rtcSignaling.off("connection-state-change",this.handleConnectionChangeEvent)}},{key:"joinGroup",value:function(e){this.logger.info("joinGroup",e);try{if("connected"!==this.connectionState)return Promise.reject(new DingRTCError(ErrorCode.ConnectionConnectFail));var t=e.userData,r=e.groupId,n=new TextEncoder;if(!r||n.encode(r).length>64)throw new DingRTCError(ErrorCode.InvaildArgument,"join group with invalid groupId");if(t){var i=new TextEncoder;if("string"!=typeof t||i.encode(t).length>64)throw new DingRTCError(ErrorCode.InvaildArgument,"join group with invalid userData")}return this.serviceManager.joinGroup(e)}catch(t){return this.logger.error("joinGroup error",e,t),Promise.reject(t)}}},{key:"leaveGroup",value:function(e){this.logger.info("leaveGroup",e);try{return"connected"!==this.connectionState?Promise.reject(new DingRTCError(ErrorCode.ConnectionConnectFail)):this.serviceManager.leaveGroup({groupId:e,publishAudioToChannel:!1})}catch(t){return this.logger.error("leaveGroup error",e,t),Promise.reject(t)}}},{key:"setGroupName",value:function(e,t){this.logger.info("setGroupName",e,t);try{if("connected"!==this.connectionState)return Promise.reject(new DingRTCError(ErrorCode.ConnectionConnectFail));var r=new TextEncoder;if(!t||r.encode(t).length>64)throw new DingRTCError(ErrorCode.InvaildArgument,"update group with invalid name");return this.serviceManager.setGroupProperties(e,{key:"name",value:t})}catch(r){return this.logger.error("setGroupName error",e,t,r),Promise.reject(r)}}},{key:"subscribeGroup",value:function(e){this.logger.info("subscribeGroup",e);try{return"connected"!==this.connectionState?Promise.reject(new DingRTCError(ErrorCode.ConnectionConnectFail)):this.serviceManager.subscribeGroup(e)}catch(t){return this.logger.error("subscribeGroup error",e,t),Promise.reject(t)}}},{key:"unsubscribeGroup",value:function(e){this.logger.info("unsubscribeGroup",e);try{return"connected"!==this.connectionState?Promise.reject(new DingRTCError(ErrorCode.ConnectionConnectFail)):this.serviceManager.unsubscribeGroup(e)}catch(t){return this.logger.error("unsubscribeGroup error",e,t),Promise.reject(t)}}},{key:"mixAudioToGroup",value:function(e,t,r){this.logger.info("mixAudioToGroup",{mediaType:null==e?void 0:e.trackMediaType,trackId:null==e?void 0:e.getTrackId(),source:null==e?void 0:e.source},t,r);try{if("connected"!==this.connectionState)throw new DingRTCError(ErrorCode.ConnectionConnectFail);if(t){if(this.logger.info("mix audio to group ".concat(r)),null==r&&this.serviceManager.micMixedGroups.size)throw new DingRTCError(ErrorCode.InvaildState,"cannot mix audio to channel while mixing to others group");return this.serviceManager.publishToGroup(r,!0)}if(this.logger.info("unmix audio from group ".concat(r)),!this.serviceManager.micMixedGroups.has(r))throw new DingRTCError(ErrorCode.InvaildState,"cannot unmix audio from the unmixed group");return this.serviceManager.unpublishFromGroup(r)}catch(n){return this.logger.error("mixAudioToGroup error",{mediaType:null==e?void 0:e.trackMediaType,trackId:null==e?void 0:e.getTrackId(),source:null==e?void 0:e.source},t,r,n),Promise.reject(n)}}},{key:"dismissGroup",value:function(e){this.logger.info("dismissGroup",e);try{return"connected"!==this.connectionState?Promise.reject(new DingRTCError(ErrorCode.ConnectionConnectFail)):this.serviceManager.dismissGroup(e)}catch(t){return this.logger.error("dismissGroup error",e,t),Promise.reject(t)}}},{key:"register",value:function(e){this.logger.info("register",e),e.attach(this.serviceManager.internalChannel,this.serviceManager)}},{key:"ungister",value:function(e){this.logger.info("ungister",e),e.detach(this.serviceManager.internalChannel)}}]);var r,n,i,o,a,s,c,u,l}(EventEmitter),FALLBACK_SUB_VIDEO_PROFILE={height:360,width:640},initListenBrowserEvent=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:window.addEventListener("offline",function(){t.info("browser offline event")}),window.addEventListener("online",function(){t.info("browser online event")}),r=function(){"visible"===document.visibilityState?t.info("page changed to visible"):t.info("page changed to invisible")},document.addEventListener("visibilitychange",r),window.addEventListener("blur",function(){t.info("page blurred")}),window.addEventListener("focus",function(){t.info("page focused")});case 1:case"end":return e.stop()}},e)}));return function(t){return e.apply(this,arguments)}}();function _callSuper(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct=function(){return!!e})()}initMediaElementPool();var simpleLogger=getReporter().getLoggerWithPrefix("[rtc-index]");simpleLogger.info("sdk version",SDK_VERSION),simpleLogger.info("userAgent",navigator.userAgent),simpleLogger.info("href: ".concat(location.href,", in_iframe=").concat(window!==window.parent)),initListenBrowserEvent(simpleLogger);var DingRTC=function(e){function t(){var e;if(_classCallCheck$1(this,t),e=_callSuper(this,t),Object.defineProperty(e,"VERSION",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e.VERSION=SDK_VERSION,!support.checkSupported())return _possibleConstructorReturn$1(e);var r=DeviceManager.getInstance();return r.on("camera-changed",function(t){e.emit("camera-changed",t)}),r.on("microphone-changed",function(t){e.emit("microphone-changed",t)}),r.on("playback-device-changed",function(t){e.emit("playback-device-changed",t)}),EventBus.on("autoplay-failed",function(t){e.emit("autoplay-failed",t)}),e}return _inherits$1(t,e),_createClass$1(t,[{key:"createClient",value:function(e){simpleLogger.info("createClient",null==e?void 0:e.map(function(e){return null==e?void 0:e.pluginName}));var t=null==e?void 0:e.find(function(e){return"DeviceChecker"===(null==e?void 0:e.pluginName)}),r=null==t?void 0:t.createPlugin();return null==r||r.injectLogger(getReporter().getLoggerWithPrefix("[rtc-devcheck]")),new DingRTCClient({deviceChecker:r})}},{key:"checkSystemRequirements",value:function(){return simpleLogger.info("checkSystemRequirements"),support.checkSupported()}},{key:"getSupportedCodec",value:function(){return simpleLogger.info("getSupportedCodec"),support.getSupportedCodec()}},{key:"createCameraVideoTrack",value:function(e){return simpleLogger.info("createCameraVideoTrack",e),createCameraVideoTrack(e)}},{key:"createMicrophoneAudioTrack",value:function(e){return simpleLogger.info("createMicrophoneAudioTrack",e),createMicrophoneAudioTrack(e)}},{key:"createCustomVideoTrack",value:function(e,t){return simpleLogger.info("createCustomVideoTrack",e,t),createCustomVideoTrack(e,t)}},{key:"createCustomAudioTrack",value:function(e,t){return simpleLogger.info("createCustomAudioTrack",e,t),createCustomAudioTrack(e,t)}},{key:"createScreenVideoTrack",value:function(e){return simpleLogger.info("createScreenVideoTrack",e),createScreenVideoTrack(e)}},{key:"createScreenVideoAndAudioTrack",value:function(e){return simpleLogger.info("createScreenVideoAndAudioTrack",e),createScreenVideoAndAudioTrack(e)}},{key:"createMicrophoneAndCameraTracks",value:(n=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t,r){return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return simpleLogger.info("createMicrophoneAndCameraTracks",{videoConfig:t,audioConfig:r}),e.abrupt("return",createMicrophoneAndCameraTracks(t,r));case 1:case"end":return e.stop()}},e)})),function(e,t){return n.apply(this,arguments)})},{key:"getCameras",value:function(){return simpleLogger.info("getCameras"),DeviceManager.getCameras()}},{key:"getDevices",value:(r=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){var t,r;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return simpleLogger.info("start getDevices"),e.prev=1,e.next=2,DeviceManager.getDevices();case 2:return t=e.sent,simpleLogger.info("getDevices suc",t),e.abrupt("return",t);case 3:return e.prev=3,r=e.catch(1),simpleLogger.info("error getDevices ",r),e.abrupt("return",r);case 4:case"end":return e.stop()}},e,null,[[1,3]])})),function(){return r.apply(this,arguments)})},{key:"getPlaybackDevices",value:function(){return simpleLogger.info("getPlaybackDevices"),DeviceManager.getPlaybackDevices()}},{key:"getMicrophones",value:function(){return simpleLogger.info("getMicrophones"),DeviceManager.getMicrophones()}},{key:"setLogLevel",value:function(e){console.warn("[dingrtc]: setLogLevel is deprecated"),setLogLevel(clientConfig._consoleLogLevel),simpleLogger.info(" setLogLevel - ignored and hint deprecated",e)}},{key:"setClientConfig",value:function(e){simpleLogger.info("setClientConfig",e),clientConfig.setClientConfig(e)}}]);var r,n}(EventEmitter),index=new DingRTC;exports.ErrorCodeAndMsgMap=ErrorCodeAndMsgMap,exports.FALLBACK_SUB_VIDEO_PROFILE=FALLBACK_SUB_VIDEO_PROFILE,exports.default=index,Object.defineProperty(exports,"__esModule",{value:!0})});
13
+ var n,i,o="function"==typeof Symbol?Symbol:{},a=o.iterator||"@@iterator",s=o.toStringTag||"@@toStringTag";function c(e,r,o,a){var s=r&&r.prototype instanceof l?r:l,c=Object.create(s.prototype);return t(c,"_invoke",function(e,t,r){var o,a,s,c=0,l=r||[],d=!1,p={p:0,n:0,v:n,a:f,f:f.bind(n,4),d:function(e,t){return o=e,a=0,s=n,p.n=t,u}};function f(e,t){for(a=e,s=t,i=0;!d&&c&&!r&&i<l.length;i++){var r,o=l[i],f=p.p,h=o[2];e>3?(r=h===t)&&(s=o[(a=o[4])?5:(a=3,3)],o[4]=o[5]=n):o[0]<=f&&((r=e<2&&f<o[1])?(a=0,p.v=t,p.n=o[1]):f<h&&(r=e<3||o[0]>t||t>h)&&(o[4]=e,o[5]=t,p.n=h,a=0))}if(r||e>1)return u;throw d=!0,t}return function(r,l,h){if(c>1)throw TypeError("Generator is already running");for(d&&1===l&&f(l,h),a=l,s=h;(i=a<2?n:s)||!d;){o||(a?a<3?(a>1&&(p.n=-1),f(a,s)):p.n=s:p.v=s);try{if(c=2,o){if(a||(r="next"),i=o[r]){if(!(i=i.call(o,s)))throw TypeError("iterator result is not an object");if(!i.done)return i;s=i.value,a<2&&(a=0)}else 1===a&&(i=o.return)&&i.call(o),a<2&&(s=TypeError("The iterator does not provide a '"+r+"' method"),a=1);o=n}else if((i=(d=p.n<0)?s:e.call(t,p))!==u)break}catch(e){o=n,a=1,s=e}finally{c=1}}return{value:i,done:d}}}(e,o,a),!0),c}var u={};function l(){}function d(){}function p(){}i=Object.getPrototypeOf;var f=[][a]?i(i([][a]())):(t(i={},a,function(){return this}),i),h=p.prototype=l.prototype=Object.create(f);function g(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,p):(e.__proto__=p,t(e,s,"GeneratorFunction")),e.prototype=Object.create(h),e}return d.prototype=p,t(h,"constructor",p),t(p,"constructor",d),d.displayName="GeneratorFunction",t(p,s,"GeneratorFunction"),t(h),t(h,s,"Generator"),t(h,a,function(){return this}),t(h,"toString",function(){return"[object Generator]"}),(e.exports=r=function(){return{w:c,m:g}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}(q);var J=q.exports,B={exports:{}},F={exports:{}},K={exports:{}};!function(e){var t=Y,r=G;e.exports=function e(n,i){function o(e,r,a,s){try{var c=n[e](r),u=c.value;return u instanceof t?i.resolve(u.v).then(function(e){o("next",e,a,s)},function(e){o("throw",e,a,s)}):i.resolve(u).then(function(e){c.value=e,a(c)},function(e){return o("throw",e,a,s)})}catch(e){s(e)}}var a;this.next||(r(e.prototype),r(e.prototype,"function"==typeof Symbol&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),r(this,"_invoke",function(e,t,r){function n(){return new i(function(t,n){o(e,r,t,n)})}return a=a?a.then(n,n):n()},!0)},e.exports.__esModule=!0,e.exports.default=e.exports}(K);var H=K.exports;!function(e){var t=J,r=H;e.exports=function(e,n,i,o,a){return new r(t().w(e,n,i,o),a||Promise)},e.exports.__esModule=!0,e.exports.default=e.exports}(F);var W=F.exports;!function(e){var t=W;e.exports=function(e,r,n,i,o){var a=t(e,r,n,i,o);return a.next().then(function(e){return e.done?e.value:a.next()})},e.exports.__esModule=!0,e.exports.default=e.exports}(B);var Q=B.exports,Z={exports:{}};!function(e){e.exports=function(e){var t=Object(e),r=[];for(var n in t)r.unshift(n);return function e(){for(;r.length;)if((n=r.pop())in t)return e.value=n,e.done=!1,e;return e.done=!0,e}},e.exports.__esModule=!0,e.exports.default=e.exports}(Z);var z=Z.exports,$={exports:{}},X={exports:{}};!function(e){function t(r){return e.exports=t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e.exports.__esModule=!0,e.exports.default=e.exports,t(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}(X);var ee=X.exports;!function(e){var t=ee.default;e.exports=function(e){if(null!=e){var r=e["function"==typeof Symbol&&Symbol.iterator||"@@iterator"],n=0;if(r)return r.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length))return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}}}throw new TypeError(t(e)+" is not iterable")},e.exports.__esModule=!0,e.exports.default=e.exports}($);var te=$.exports;!function(e){var t=Y,r=J,n=Q,i=W,o=H,a=z,s=te;function c(){var u=r(),l=u.m(c),d=(Object.getPrototypeOf?Object.getPrototypeOf(l):l.__proto__).constructor;function p(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===d||"GeneratorFunction"===(t.displayName||t.name))}var f={throw:1,return:2,break:3,continue:3};function h(e){var t,r;return function(n){t||(t={stop:function(){return r(n.a,2)},catch:function(){return n.v},abrupt:function(e,t){return r(n.a,f[e],t)},delegateYield:function(e,i,o){return t.resultName=i,r(n.d,s(e),o)},finish:function(e){return r(n.f,e)}},r=function(e,r,i){n.p=t.prev,n.n=t.next;try{return e(r,i)}finally{t.next=n.n}}),t.resultName&&(t[t.resultName]=n.v,t.resultName=void 0),t.sent=n.v,t.next=n.n;try{return e.call(this,t)}finally{n.p=t.prev,n.n=t.next}}}return(e.exports=c=function(){return{wrap:function(e,t,r,n){return u.w(h(e),t,r,n&&n.reverse())},isGeneratorFunction:p,mark:u.m,awrap:function(e,r){return new t(e,r)},AsyncIterator:o,async:function(e,t,r,o,a){return(p(t)?i:n)(h(e),t,r,o,a)},keys:a,values:s}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=c,e.exports.__esModule=!0,e.exports.default=e.exports}(U);var ne=(0,U.exports)(),ie=ne;try{regeneratorRuntime=ne}catch(e){"object"==typeof globalThis?globalThis.regeneratorRuntime=ne:Function("r","regeneratorRuntime = r")(ne)}var re,oe,se,ae,de,ce,pe=A(ie);!function(e){var t;(t=e.Result||(e.Result={}))[t.Ok=0]="Ok",t[t.Error=1]="Error"}(re||(re={})),function(e){var t;(t=e.Type||(e.Type={}))[t.kUnknown=0]="kUnknown",t[t.kConnectReq=1]="kConnectReq",t[t.kConnectResp=2]="kConnectResp",t[t.kDisconnect=3]="kDisconnect",t[t.kChannelCreated=4]="kChannelCreated",t[t.kChannelClosed=5]="kChannelClosed",t[t.kPing=6]="kPing",t[t.kPong=7]="kPong",t[t.kData=64]="kData"}(oe||(oe={})),function(e){var t;(t=e.MessageType||(e.MessageType={}))[t.TYPE_UNKNOWN=0]="TYPE_UNKNOWN",t[t.TYPE_NODE_JOIN=1]="TYPE_NODE_JOIN",t[t.TYPE_NODE_JOIN_CONFIRM=2]="TYPE_NODE_JOIN_CONFIRM",t[t.TYPE_NODE_LEFT=3]="TYPE_NODE_LEFT",t[t.TYPE_ATTACH_USER_CONFIRM=4]="TYPE_ATTACH_USER_CONFIRM",t[t.TYPE_DETACH_USER_CONFIRM=5]="TYPE_DETACH_USER_CONFIRM",t[t.TYPE_NODE_MAP_UPDATE=6]="TYPE_NODE_MAP_UPDATE",t[t.TYPE_CREATE_SESSION=7]="TYPE_CREATE_SESSION",t[t.TYPE_CREATE_SESSION_CONFIRM=8]="TYPE_CREATE_SESSION_CONFIRM",t[t.TYPE_SESSION_CREATED=9]="TYPE_SESSION_CREATED",t[t.TYPE_JOIN_SESSION=10]="TYPE_JOIN_SESSION",t[t.TYPE_JOIN_SESSION_CONFIRM=11]="TYPE_JOIN_SESSION_CONFIRM",t[t.TYPE_LEAVE_SESSION=12]="TYPE_LEAVE_SESSION",t[t.TYPE_LEAVE_SESSION_CONFIRM=13]="TYPE_LEAVE_SESSION_CONFIRM",t[t.TYPE_CLOSE_SESSION=14]="TYPE_CLOSE_SESSION",t[t.TYPE_CLOSE_SESSION_CONFIRM=15]="TYPE_CLOSE_SESSION_CONFIRM",t[t.TYPE_SESSION_CLOSED=16]="TYPE_SESSION_CLOSED",t[t.TYPE_SESSION_CMD_DATA=17]="TYPE_SESSION_CMD_DATA",t[t.TYPE_SESSION_CMD_DATA_CONFIRM=18]="TYPE_SESSION_CMD_DATA_CONFIRM",t[t.TYPE_SESSION_CMD_DATA_NOTIFICATION=19]="TYPE_SESSION_CMD_DATA_NOTIFICATION",t[t.TYPE_SESSION_DATA=20]="TYPE_SESSION_DATA",t[t.TYPE_NODE_MAP_SNAPSHOT=21]="TYPE_NODE_MAP_SNAPSHOT",t[t.TYPE_CLOSE_SWITCHER=22]="TYPE_CLOSE_SWITCHER",t[t.TYPE_KICK_USER=23]="TYPE_KICK_USER",t[t.TYPE_JOIN_GROUP=24]="TYPE_JOIN_GROUP",t[t.TYPE_JOIN_GROUP_CONFIRM=25]="TYPE_JOIN_GROUP_CONFIRM",t[t.TYPE_LEAVE_GROUP=26]="TYPE_LEAVE_GROUP",t[t.TYPE_LEAVE_GROUP_CONFIRM=27]="TYPE_LEAVE_GROUP_CONFIRM",t[t.TYPE_GROUP_CREATED=28]="TYPE_GROUP_CREATED",t[t.TYPE_GROUP_DESTROYED=29]="TYPE_GROUP_DESTROYED",t[t.TYPE_GROUP_STATUS=30]="TYPE_GROUP_STATUS",t[t.TYPE_SWITCHER_UPDATE=31]="TYPE_SWITCHER_UPDATE",t[t.TYPE_SERVICE_STATUS=32]="TYPE_SERVICE_STATUS",t[t.TYPE_SESSION_SYNC_REQUEST=33]="TYPE_SESSION_SYNC_REQUEST"}(se||(se={})),function(e){var t;(t=e.RpcType||(e.RpcType={}))[t.Req=0]="Req",t[t.Resp=1]="Resp"}(ae||(ae={})),function(e){var t,r,n;(t=e.MessageType||(e.MessageType={}))[t.AuthType=0]="AuthType",t[t.AuthResponseType=1]="AuthResponseType",t[t.ChannelBindType=2]="ChannelBindType",t[t.ChannelBindResponseType=3]="ChannelBindResponseType",t[t.KeepaliveType=4]="KeepaliveType",t[t.KeepaliveResponseType=5]="KeepaliveResponseType",t[t.ChannelDataType=6]="ChannelDataType",t[t.ReAuthType=7]="ReAuthType",t[t.ReAuthResponseType=8]="ReAuthResponseType",t[t.RefreshTicketType=9]="RefreshTicketType",t[t.RefreshTicketResponseType=10]="RefreshTicketResponseType",t[t.ServerRequestType=11]="ServerRequestType",t[t.ChannelUnBindType=12]="ChannelUnBindType",t[t.ChannelUnBindResponseType=13]="ChannelUnBindResponseType",t[t.RpcProxyRequestType=14]="RpcProxyRequestType",t[t.RpcProxyResponseType=15]="RpcProxyResponseType",function(e){e[e.Ok=0]="Ok",e[e.Error=1]="Error",e[e.ErrorLogin=2]="ErrorLogin",e[e.ErrorDSInternal=3]="ErrorDSInternal"}(e.ErrorCode||(e.ErrorCode={})),(r=e.AuthErrorMsg||(e.AuthErrorMsg={}))[r.SignatureInvalid=0]="SignatureInvalid",r[r.Expired=1]="Expired",r[r.Unavailable=2]="Unavailable",function(e){e[e.MessageChannel=0]="MessageChannel",e[e.PortalChannel=1]="PortalChannel",e[e.DataSwitcherChannel=2]="DataSwitcherChannel"}(e.ChannelType||(e.ChannelType={})),(n=e.ServerEvent||(e.ServerEvent={}))[n.RejoinRequest=0]="RejoinRequest",n[n.ReauthRequest=1]="ReauthRequest"}(de||(de={}));var le="https://gslb.dingrtc.com",ue=1e4,ye=2e3,he=function(e,t,r){return{protocol:"1.0",configJsonStr:JSON.stringify({needPersonalityAudioStream:!0,outPeerConnectionNotReuse:!0,enable_sys_audio:0,mute_audio_record:r}),userAgent:{sdk:{version:e,type:"JavaScript",scene:t},runtime:{name:Environment.browserType,version:Environment.browserVersion},os:{name:Environment.system,version:Environment.systemVersion}}}},fe="TopServer",ve={confirmTypes:[se.MessageType.TYPE_ATTACH_USER_CONFIRM,se.MessageType.TYPE_JOIN_SESSION_CONFIRM,se.MessageType.TYPE_LEAVE_SESSION_CONFIRM,se.MessageType.TYPE_CLOSE_SESSION_CONFIRM,se.MessageType.TYPE_SESSION_CMD_DATA_CONFIRM,se.MessageType.TYPE_JOIN_GROUP_CONFIRM,se.MessageType.TYPE_LEAVE_GROUP_CONFIRM],rpcTypeKeyMap:R(R(R(R(R(R(R({},se.MessageType.TYPE_JOIN_SESSION,"joinSession"),se.MessageType.TYPE_LEAVE_SESSION,"leaveSession"),se.MessageType.TYPE_CLOSE_SESSION,"closeSession"),se.MessageType.TYPE_SESSION_DATA,"sessionData"),se.MessageType.TYPE_SESSION_CMD_DATA,"sessionCmdData"),se.MessageType.TYPE_JOIN_GROUP,"joinGroup"),se.MessageType.TYPE_LEAVE_GROUP,"leaveGroup"),sendDataTypes:[se.MessageType.TYPE_SESSION_DATA,se.MessageType.TYPE_SESSION_CMD_DATA],msgTypeKeyMap:(ce={},R(R(R(R(R(R(R(R(R(R(ce,se.MessageType.TYPE_JOIN_SESSION_CONFIRM,"joinSessionConfirm"),se.MessageType.TYPE_CLOSE_SESSION_CONFIRM,"closeSessionConfirm"),se.MessageType.TYPE_SESSION_CLOSED,"sessionClosed"),se.MessageType.TYPE_SESSION_CREATED,"sessionCreated"),se.MessageType.TYPE_LEAVE_SESSION_CONFIRM,"leaveSessionConfirm"),se.MessageType.TYPE_SESSION_CMD_DATA_CONFIRM,"sessionCmdDataConfirm"),se.MessageType.TYPE_SESSION_CMD_DATA_NOTIFICATION,"sessionCmdDataNoti"),se.MessageType.TYPE_SESSION_DATA,"sessionData"),se.MessageType.TYPE_ATTACH_USER_CONFIRM,"attachUserConfirm"),se.MessageType.TYPE_DETACH_USER_CONFIRM,"detachUserConfirm"),R(R(R(R(R(R(R(R(R(ce,se.MessageType.TYPE_NODE_MAP_SNAPSHOT,"nodeMapSnapshot"),se.MessageType.TYPE_NODE_MAP_UPDATE,"nodeMapUpdate"),se.MessageType.TYPE_GROUP_CREATED,"groupCreated"),se.MessageType.TYPE_GROUP_DESTROYED,"groupDestroyed"),se.MessageType.TYPE_JOIN_GROUP,"groupStatus"),se.MessageType.TYPE_JOIN_GROUP_CONFIRM,"joinGroupConfirm"),se.MessageType.TYPE_LEAVE_GROUP_CONFIRM,"leaveGroupConfirm"),se.MessageType.TYPE_SERVICE_STATUS,"serviceStatus"),se.MessageType.TYPE_SWITCHER_UPDATE,"switcherUpdate"))},me=getProtobufRoot({options:{syntax:"proto3"},nested:{signal_msg:{nested:{AudioSsrcSpec:{fields:{ssrc:{type:"uint32",id:1},rtxSsrc:{type:"uint32",id:2}}},VideoSsrcSpec:{fields:{ssrc:{type:"uint32",id:1},rtxSsrc:{type:"uint32",id:2},fecSsrc:{type:"uint32",id:3}}},MultiPcAdaptRequestInfo:{fields:{audioSsrcSpec:{rule:"repeated",type:"AudioSsrcSpec",id:1},videoSsrcSpec:{rule:"repeated",type:"VideoSsrcSpec",id:2}}},AudioStreamFormat:{fields:{codec:{type:"string",id:1},sampleRate:{type:"int64",id:2},channelNum:{type:"int64",id:3}}},AudioFormatPreference:{fields:{preferred:{type:"AudioStreamFormat",id:1},optional:{rule:"repeated",type:"AudioStreamFormat",id:2}}},AudioStreamOptional:{fields:{format:{rule:"repeated",type:"AudioStreamFormat",id:1}}},VideoStreamFormat:{fields:{codec:{type:"string",id:1},profile:{type:"string",id:2}}},VideoFormatPreference:{fields:{preferred:{type:"VideoStreamFormat",id:1},optional:{rule:"repeated",type:"VideoStreamFormat",id:2}}},FormatPreference:{fields:{audio:{type:"AudioFormatPreference",id:1},video:{type:"VideoFormatPreference",id:2}}},Resolution:{fields:{width:{type:"uint32",id:1},height:{type:"uint32",id:2}}},VideoSsrcParameters:{fields:{ssrc:{type:"uint32",id:1},framerate:{type:"int32",id:2},resolution:{type:"Resolution",id:3},maxBitrate:{type:"int32",id:4},minBitrate:{type:"int32",id:5},active:{type:"bool",id:6},bitrate:{type:"int64",id:7},tlayer:{type:"int64",id:8},multiSlice:{type:"int64",id:9},keyFrameInterval:{type:"int64",id:10},constantPpsid:{type:"int64",id:11}}},VideoParameters:{oneofs:{_resolutionLevel:{oneof:["resolutionLevel"]}},fields:{ssrc:{type:"uint32",id:1},resolution:{type:"Resolution",id:2},framerate:{type:"int32",id:3},bitrate:{type:"string",id:4},multiSlice:{type:"int32",id:5},keyFrameInterval:{type:"int64",id:6},constantPpsid:{type:"int64",id:7},resolutionLevel:{type:"uint32",id:8,options:{proto3_optional:!0}}}},GroupVersion:{fields:{id:{type:"string",id:1},ver:{type:"int64",id:2}}},StreamInfo:{fields:{type:{type:"string",id:1},owner:{type:"string",id:2},attributesJsonStr:{type:"string",id:3},label:{type:"string",id:4},createTime:{type:"int64",id:7}}},StreamVideoParameters:{fields:{resolution:{type:"Resolution",id:1},framerate:{type:"int64",id:2},bitrate:{type:"int64",id:3},keyFrameInterval:{type:"int64",id:4},multiSlice:{type:"int64",id:5},constantPpsid:{type:"int64",id:6}}},VideoStreamPara:{fields:{specs:{rule:"repeated",type:"string",id:1},resolution:{rule:"repeated",type:"Resolution",id:2},framerate:{rule:"repeated",type:"int32",id:3},bitrate:{rule:"repeated",type:"string",id:4},keyFrameInterval:{rule:"repeated",type:"int32",id:5}}},VideoStreamOptional:{fields:{format:{rule:"repeated",type:"VideoStreamFormat",id:1},parameters:{type:"VideoStreamPara",id:2}}},StreamAudioDesc:{fields:{trackId:{type:"string",id:1},msid:{type:"string",id:2},status:{type:"string",id:3},format:{type:"AudioStreamFormat",id:4},source:{type:"string",id:5},ssrc:{rule:"repeated",type:"uint32",id:6},ssrcGroup:{rule:"repeated",type:"AudioSsrcSpec",id:7},optional:{type:"AudioStreamOptional",id:8}}},StreamVideoDesc:{fields:{trackId:{type:"string",id:1},msid:{type:"string",id:2},status:{type:"string",id:3},source:{type:"string",id:4},format:{type:"VideoStreamFormat",id:5},ssrc:{rule:"repeated",type:"uint32",id:6},ssrcGroup:{rule:"repeated",type:"VideoSsrcSpec",id:7},parameters:{type:"StreamVideoParameters",id:8},optional:{type:"VideoStreamOptional",id:9},highestResolutionLevel:{type:"int32",id:10}}},StreamMediaDesc:{fields:{audio:{type:"StreamAudioDesc",id:1},video:{type:"StreamVideoDesc",id:2}}},Stream:{fields:{id:{type:"string",id:1},type:{type:"string",id:2},media:{type:"StreamMediaDesc",id:3},info:{type:"StreamInfo",id:4},version:{type:"int64",id:5}}},OriginMsg:{fields:{type:{type:"string",id:1},id:{type:"string",id:2}}},ErrorMsg:{fields:{id:{type:"string",id:1},code:{type:"int32",id:2},msg:{type:"string",id:3},origin:{type:"OriginMsg",id:4}}},ErrorMsgs:{fields:{globalStatus:{type:"string",id:1},detailStatus:{rule:"repeated",type:"ErrorMsg",id:2}}},Permission:{fields:{audio:{type:"bool",id:1},video:{type:"bool",id:2}}},PermissionInfo:{fields:{subscribe:{type:"Permission",id:1},publish:{type:"Permission",id:2},vip:{type:"bool",id:3}}},ParticipantInfo:{fields:{id:{type:"string",id:1},user:{type:"string",id:2},role:{type:"string",id:3},ver:{type:"int64",id:4},propertiesJsonStr:{type:"string",id:5}}},RoomInfo:{fields:{id:{type:"string",id:1},views:{rule:"repeated",type:"string",id:2},participants:{rule:"repeated",type:"ParticipantInfo",id:3},participantsVer:{type:"int64",id:4},streams:{rule:"repeated",type:"Stream",id:5},streamsVer:{type:"uint64",id:6},conferenceVer:{type:"uint64",id:7},ts:{type:"int64",id:8},audioSelectEnableV1:{type:"bool",id:9},simulcastEnableV1:{type:"bool",id:10},mediaOutVideoParameters:{rule:"repeated",type:"VideoStreamFormat",id:11},propertiesJsonStr:{type:"string",id:12},ssrcClientSequence:{type:"uint32",id:13},ssrcMask:{type:"uint32",id:14},timeLeft:{type:"int64",id:15},groupList:{rule:"repeated",type:"string",id:16},groupListVer:{type:"int64",id:17}}},ParticipantVer:{fields:{id:{type:"string",id:1},ver:{type:"int64",id:2}}},ParticipantDetail:{fields:{id:{type:"string",id:1},user:{type:"string",id:2},role:{type:"string",id:3},ver:{type:"int64",id:4},propertiesJsonStr:{type:"string",id:5},permission:{type:"PermissionInfo",id:6}}},QueryParticipantsData:{fields:{id:{type:"string",id:1},data:{type:"ParticipantDetail",id:2}}},SetPropertiesData:{fields:{id:{type:"string",id:1},ver:{type:"int64",id:2},propertiesJsonStr:{type:"string",id:3}}},Os:{fields:{name:{type:"string",id:1},version:{type:"string",id:2}}},Runtime:{fields:{name:{type:"string",id:1},version:{type:"string",id:2}}},Sdk:{fields:{version:{type:"string",id:1},type:{type:"string",id:2}}},UserAgent:{fields:{os:{type:"Os",id:1},runtime:{type:"Runtime",id:2},sdk:{type:"Sdk",id:3}}},JoinRequest:{fields:{protocol:{type:"string",id:1},token:{type:"string",id:2},userAgent:{type:"UserAgent",id:3},configJsonStr:{type:"string",id:4},tid:{type:"string",id:5},traceId:{type:"string",id:6}}},JoinResponse:{fields:{user:{type:"string",id:1},role:{type:"string",id:2},permission:{type:"PermissionInfo",id:3},room:{type:"RoomInfo",id:4},id:{type:"string",id:5}}},RejoinRequest:{fields:{token:{type:"string",id:1},tid:{type:"string",id:2},traceId:{type:"string",id:3}}},RejoinResponse:{fields:{participantsVer:{type:"int64",id:1},streamsVer:{type:"uint64",id:2}}},LeaveRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},tid:{type:"string",id:3},traceId:{type:"string",id:4}}},QueryParticipantsVerRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},pids:{rule:"repeated",type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},QueryParticipantsVerResponse:{fields:{participants:{rule:"repeated",type:"ParticipantVer",id:1},totalVer:{type:"int64",id:2},msg:{type:"string",id:3}}},QueryParticipantsRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},pids:{rule:"repeated",type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},QueryParticipantsResponse:{fields:{totalVer:{type:"int64",id:1},msg:{type:"string",id:2},participants:{rule:"repeated",type:"QueryParticipantsData",id:3}}},GetParticipantsAndStreamsRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},pids:{rule:"repeated",type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},GetParticipantsAndStreamsResponse:{fields:{ts:{type:"int64",id:1},msg:{type:"string",id:2},participants:{rule:"repeated",type:"ParticipantDetail",id:3},streams:{rule:"repeated",type:"Stream",id:4}}},SetParticipantPropertiesRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},propertiesJsonStr:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},RemoveParticipantPropertiesRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},propertiesJsonStr:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},ParticipantNotification:{oneofs:{data:{oneof:["info","participantId","propertiesData"]}},fields:{action:{type:"string",id:1},totalVer:{type:"int64",id:2},msgId:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5},info:{type:"ParticipantInfo",id:10},participantId:{type:"string",id:11},propertiesData:{type:"SetPropertiesData",id:12}}},SyncNotification:{fields:{streamsVer:{type:"int64",id:1},participantsVer:{type:"int64",id:2},conferenceVer:{type:"int64",id:3},msgId:{type:"string",id:4},tid:{type:"string",id:5},traceId:{type:"string",id:6},groupListVer:{type:"int64",id:7},groupVer:{rule:"repeated",type:"GroupVersion",id:8}}},Result:{values:{Ok:0,Error:1}},Response:{oneofs:{data:{oneof:["reason","joinResponse","queryParticipantsResponse","queryParticipantsVerResponse","rejoinResponse"]}},fields:{result:{type:"Result",id:1},tid:{type:"string",id:2},traceId:{type:"string",id:3},code:{type:"int32",id:4},reason:{type:"string",id:11},joinResponse:{type:"JoinResponse",id:12},queryParticipantsResponse:{type:"QueryParticipantsResponse",id:13},queryParticipantsVerResponse:{type:"QueryParticipantsVerResponse",id:14},rejoinResponse:{type:"RejoinResponse",id:23}}},ConferenceNotification:{fields:{action:{type:"string",id:1},ver:{type:"int64",id:2},id:{type:"string",id:3},msgId:{type:"string",id:4},tid:{type:"string",id:5},traceId:{type:"string",id:6},propertiesJsonStr:{type:"string",id:7}}},DropNotification:{fields:{tid:{type:"string",id:1},traceId:{type:"string",id:2},code:{type:"int32",id:3},reason:{type:"string",id:4}}},NotificationItem:{oneofs:{notification:{oneof:["participantNotification","syncNotification","conferenceNotification"]}},fields:{event:{type:"string",id:1},participantNotification:{type:"ParticipantNotification",id:12},syncNotification:{type:"SyncNotification",id:15},conferenceNotification:{type:"ConferenceNotification",id:16}}},BatchNotification:{fields:{notificationItem:{rule:"repeated",type:"NotificationItem",id:1},tid:{type:"string",id:2},traceId:{type:"string",id:3}}}}},ddmsg:{options:{optimize_for:"LITE_RUNTIME"},nested:{Type:{values:{kUnknown:0,kConnectReq:1,kConnectResp:2,kDisconnect:3,kChannelCreated:4,kChannelClosed:5,kPing:6,kPong:7,kData:64}},Message:{oneofs:{messageOneof:{oneof:["connectReq","connectResp","diconnect","channelsCreated","channelsClosed","data"]}},fields:{msgType:{type:"Type",id:1},connectReq:{type:"ConnectReq",id:2},connectResp:{type:"ConnectResp",id:3},diconnect:{type:"Disconnect",id:4},channelsCreated:{type:"ChannelsCreated",id:5},channelsClosed:{type:"ChannelsClosed",id:6},data:{type:"Data",id:64}}},ServerAddress:{fields:{name:{type:"string",id:1},ip:{type:"string",id:2},port:{type:"uint32",id:3}}},Channel:{fields:{channelId:{type:"uint32",id:1},customizedChannelType:{type:"uint32",id:2},ownerEndpointId:{type:"uint32",id:3}}},ConnectReq:{fields:{parentAddr:{type:"ServerAddress",id:1},topAddr:{type:"ServerAddress",id:2},nodeId:{type:"fixed64",id:3},requestId:{type:"int32",id:4},subdsType:{type:"int32",id:5},reqData:{type:"bytes",id:10}}},ConnectResp:{fields:{result:{type:"int32",id:1},requestId:{type:"int32",id:2},nodeId:{type:"fixed64",id:3},parentNodeId:{type:"fixed64",id:4},topNodeId:{type:"fixed64",id:5},channels:{rule:"repeated",type:"Channel",id:6},respData:{type:"bytes",id:10}}},Disconnect:{fields:{reason:{type:"int32",id:1}}},ChannelsCreated:{fields:{channels:{rule:"repeated",type:"Channel",id:1}}},ChannelsClosed:{fields:{reason:{type:"int32",id:1},channels:{rule:"repeated",type:"Channel",id:2}}},Data:{fields:{priority:{type:"uint32",id:1},uniform:{type:"bool",id:2},echo:{type:"bool",id:3},compressed:{type:"bool",id:4},from:{type:"fixed64",id:5},to:{type:"fixed64",id:6},excludes:{rule:"repeated",type:"fixed64",id:7},data:{type:"bytes",id:10}}}}},dsmsg:{options:{optimize_for:"LITE_RUNTIME"},nested:{MessageType:{values:{TYPE_UNKNOWN:0,TYPE_NODE_JOIN:1,TYPE_NODE_JOIN_CONFIRM:2,TYPE_NODE_LEFT:3,TYPE_ATTACH_USER_CONFIRM:4,TYPE_DETACH_USER_CONFIRM:5,TYPE_NODE_MAP_UPDATE:6,TYPE_CREATE_SESSION:7,TYPE_CREATE_SESSION_CONFIRM:8,TYPE_SESSION_CREATED:9,TYPE_JOIN_SESSION:10,TYPE_JOIN_SESSION_CONFIRM:11,TYPE_LEAVE_SESSION:12,TYPE_LEAVE_SESSION_CONFIRM:13,TYPE_CLOSE_SESSION:14,TYPE_CLOSE_SESSION_CONFIRM:15,TYPE_SESSION_CLOSED:16,TYPE_SESSION_CMD_DATA:17,TYPE_SESSION_CMD_DATA_CONFIRM:18,TYPE_SESSION_CMD_DATA_NOTIFICATION:19,TYPE_SESSION_DATA:20,TYPE_NODE_MAP_SNAPSHOT:21,TYPE_CLOSE_SWITCHER:22,TYPE_KICK_USER:23,TYPE_JOIN_GROUP:24,TYPE_JOIN_GROUP_CONFIRM:25,TYPE_LEAVE_GROUP:26,TYPE_LEAVE_GROUP_CONFIRM:27,TYPE_GROUP_CREATED:28,TYPE_GROUP_DESTROYED:29,TYPE_GROUP_STATUS:30,TYPE_SWITCHER_UPDATE:31,TYPE_SERVICE_STATUS:32,TYPE_SESSION_SYNC_REQUEST:33}},Message:{oneofs:{messageOneof:{oneof:["nodeJoin","nodeJoinConfirm","nodeLeft","attachUserConfirm","detachUserConfirm","nodeMapUpdate","createSession","createSessionConfirm","sessionCreated","joinSession","joinSessionConfirm","leaveSession","leaveSessionConfirm","closeSession","closeSessionConfirm","sessionClosed","sessionCmdData","sessionCmdDataConfirm","sessionCmdDataNoti","sessionData","nodeMapSnapshot","closeSwitcher","kickUser","joinGroup","joinGroupConfirm","leaveGroup","leaveGroupConfirm","groupCreated","groupDestroyed","groupStatus","switcherUpdate","serviceStatus","sessionSyncReq"]}},fields:{version:{type:"int32",id:1},type:{type:"MessageType",id:2},nodeJoin:{type:"NodeJoin",id:3},nodeJoinConfirm:{type:"NodeJoinConfirm",id:4},nodeLeft:{type:"NodeLeft",id:5},attachUserConfirm:{type:"AttachUserConfirm",id:6},detachUserConfirm:{type:"DetachUserConfirm",id:7},nodeMapUpdate:{type:"NodeMapUpdate",id:8},createSession:{type:"CreateSession",id:9},createSessionConfirm:{type:"CreateSessionConfirm",id:10},sessionCreated:{type:"SessionCreated",id:11},joinSession:{type:"JoinSession",id:12},joinSessionConfirm:{type:"JoinSessionConfirm",id:13},leaveSession:{type:"LeaveSession",id:14},leaveSessionConfirm:{type:"LeaveSessionConfirm",id:15},closeSession:{type:"CloseSession",id:16},closeSessionConfirm:{type:"CloseSessionConfirm",id:17},sessionClosed:{type:"SessionClosed",id:18},sessionCmdData:{type:"SessionCmdData",id:19},sessionCmdDataConfirm:{type:"SessionCmdDataConfirm",id:20},sessionCmdDataNoti:{type:"SessionCmdDataNotification",id:21},sessionData:{type:"SessionData",id:22},nodeMapSnapshot:{type:"NodeMapSnapshot",id:23},closeSwitcher:{type:"CloseSwitcher",id:24},kickUser:{type:"KickUser",id:25},joinGroup:{type:"JoinGroup",id:26},joinGroupConfirm:{type:"JoinGroupConfirm",id:27},leaveGroup:{type:"LeaveGroup",id:28},leaveGroupConfirm:{type:"LeaveGroupConfirm",id:29},groupCreated:{type:"GroupCreated",id:30},groupDestroyed:{type:"GroupDestroyed",id:31},groupStatus:{type:"GroupStatus",id:32},switcherUpdate:{type:"SwitcherUpdate",id:33},serviceStatus:{type:"ServiceStatus",id:34},sessionSyncReq:{type:"SessionSyncRequrst",id:35}}},NodeJoin:{fields:{nodeName:{type:"string",id:1},remainingTime:{type:"int32",id:2}}},NodeJoinConfirm:{fields:{nodeName:{type:"string",id:1},channels:{rule:"repeated",type:"Channel",id:2},endpointId:{type:"int32",id:3},sessionCreateds:{rule:"repeated",type:"SessionCreated",id:4},config:{type:"Config",id:5}}},Config:{fields:{nodeInfoBundleSize:{type:"int32",id:1}}},NodeLeft:{fields:{nodeId:{type:"uint64",id:1}}},AttachUserConfirm:{fields:{pid:{type:"string",id:1},nodeId:{type:"uint64",id:2},serverNodeId:{type:"uint64",id:3},topServerNodeId:{type:"uint64",id:4},endpointId:{type:"int32",id:5},result:{type:"uint32",id:6},channels:{rule:"repeated",type:"Channel",id:7},sessionCreateds:{rule:"repeated",type:"SessionCreated",id:8},reason:{type:"uint32",id:9}}},DetachUser:{fields:{pid:{type:"string",id:1},nodeId:{type:"uint64",id:2},reason:{type:"uint32",id:3}}},DetachUserConfirm:{fields:{pid:{type:"string",id:1},nodeId:{type:"uint64",id:2},result:{type:"uint32",id:3}}},NodeMapUpdate:{fields:{items:{rule:"repeated",type:"NodeMapUpdateItem",id:1}}},NodeMapUpdateItem:{fields:{pid:{type:"string",id:1},nodeId:{type:"uint64",id:2},action:{type:"uint32",id:3},uid:{type:"string",id:4},userName:{type:"string",id:5}}},NodeMapSnapshot:{fields:{start:{type:"bool",id:1},end:{type:"bool",id:2},items:{rule:"repeated",type:"NodeMapUpdateItem",id:3}}},NodeMapSnapshotItem:{fields:{pid:{type:"string",id:1},nodeId:{type:"uint64",id:2}}},CreateSession:{fields:{sessionType:{type:"int32",id:1},sessionKey:{type:"string",id:2},customSessionData:{type:"string",id:3}}},CreateSessionConfirm:{fields:{sessionType:{type:"int32",id:1},sessionKey:{type:"string",id:2},endpointId:{type:"int32",id:3},result:{type:"uint32",id:4}}},SessionCreated:{fields:{sessionType:{type:"int32",id:1},sessionKey:{type:"string",id:2},endpointId:{type:"int32",id:3},channels:{rule:"repeated",type:"Channel",id:4},customSessionData:{type:"string",id:5},groupCreated:{rule:"repeated",type:"GroupCreated",id:6}}},JoinSession:{fields:{sessionType:{type:"int32",id:1},sessionKey:{type:"string",id:2},pid:{type:"string",id:3},nodeId:{type:"uint64",id:4},customSessionData:{type:"string",id:5}}},JoinSessionConfirm:{fields:{sessionType:{type:"int32",id:1},sessionKey:{type:"string",id:2},endpointId:{type:"int32",id:3},pid:{type:"string",id:4},nodeId:{type:"uint64",id:5},result:{type:"uint32",id:6},channels:{rule:"repeated",type:"Channel",id:7},customSessionData:{type:"string",id:8}}},LeaveSession:{fields:{sessionType:{type:"int32",id:1},sessionKey:{type:"string",id:2},nodeId:{type:"uint64",id:3}}},LeaveSessionConfirm:{fields:{sessionType:{type:"int32",id:1},sessionKey:{type:"string",id:2},nodeId:{type:"uint64",id:3},result:{type:"uint32",id:4}}},CloseSession:{fields:{sessionType:{type:"int32",id:1},sessionKey:{type:"string",id:2},nodeId:{type:"uint64",id:3}}},CloseSessionConfirm:{fields:{sessionType:{type:"int32",id:1},sessionKey:{type:"string",id:2},result:{type:"uint32",id:3}}},SessionClosed:{fields:{sessionType:{type:"int32",id:1},sessionKey:{type:"string",id:2}}},Channel:{fields:{id:{type:"int32",id:1},type:{type:"uint32",id:2}}},SessionCmdData:{fields:{cmdType:{type:"uint32",id:1},cmd:{type:"string",id:2},requestId:{type:"uint32",id:3},data:{type:"bytes",id:4},broadcast:{type:"bool",id:5},echo:{type:"bool",id:6},toNodeId:{type:"uint64",id:7},fromPid:{type:"string",id:8}}},SessionCmdDataConfirm:{fields:{cmdType:{type:"uint32",id:1},cmd:{type:"string",id:2},requestId:{type:"uint32",id:3},result:{type:"uint32",id:4},fromPid:{type:"string",id:5}}},SessionCmdDataNotification:{fields:{cmdType:{type:"uint32",id:1},cmd:{type:"string",id:2},requestId:{type:"uint32",id:3},data:{type:"bytes",id:4},fromPid:{type:"string",id:5}}},SessionData:{fields:{data:{type:"bytes",id:1}}},CloseSwitcher:{fields:{reason:{type:"uint32",id:1}}},KickUser:{fields:{pid:{type:"string",id:1},nodeId:{type:"uint64",id:2},reason:{type:"uint32",id:3}}},JoinGroup:{fields:{nodeId:{type:"uint64",id:1},groupId:{type:"string",id:2},requestId:{type:"uint32",id:3}}},JoinGroupConfirm:{fields:{nodeId:{type:"uint64",id:1},groupId:{type:"string",id:2},result:{type:"uint32",id:3},channel:{type:"Channel",id:4},requestId:{type:"uint32",id:5}}},LeaveGroup:{fields:{nodeId:{type:"uint64",id:1},groupId:{type:"string",id:2},requestId:{type:"uint32",id:3}}},LeaveGroupConfirm:{fields:{nodeId:{type:"uint64",id:1},groupId:{type:"string",id:2},result:{type:"uint32",id:3},requestId:{type:"uint32",id:4}}},GroupCreated:{fields:{groupId:{type:"string",id:1},channel:{type:"Channel",id:2},status:{type:"int32",id:3}}},GroupDestroyed:{fields:{groupId:{type:"string",id:1}}},GroupStatus:{fields:{groupId:{type:"string",id:1},status:{type:"int32",id:2}}},SwitcherUpdate:{fields:{channelUpdates:{rule:"repeated",type:"ChannelUpdate",id:1}}},ChannelUpdate:{fields:{endpointId:{type:"int32",id:1},groupId:{type:"string",id:2},channel:{type:"Channel",id:3}}},ServiceStatus:{fields:{status:{type:"int32",id:1},data:{type:"string",id:2}}},SessionSyncRequrst:{fields:{nodeId:{type:"uint64",id:1}}}}},rpc:{nested:{RpcType:{values:{Req:0,Resp:1}},RpcMessage:{fields:{Version:{type:"uint32",id:1},MagicNumber:{type:"uint32",id:2},Type:{type:"RpcType",id:3},RpcId:{type:"uint32",id:4},NeedAck:{type:"bool",id:5},Method:{type:"string",id:6},Data:{type:"bytes",id:7}}}}},rtmpproxy:{nested:{CreateRtmpProxyPushRequest:{fields:{appId:{type:"string",id:1},roomId:{type:"string",id:2},streamId:{type:"string",id:3},timestamp:{type:"string",id:4},nonce:{type:"string",id:5},signature:{type:"string",id:6},localInfo:{type:"string",id:7},sdp:{type:"string",id:8},user:{type:"string",id:9},pid:{type:"string",id:10}}},CreateRtmpProxyPushResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}},CreateRtmpProxyPullRequest:{fields:{appId:{type:"string",id:1},roomId:{type:"string",id:2},streamId:{type:"string",id:3},timestamp:{type:"string",id:4},nonce:{type:"string",id:5},signature:{type:"string",id:6},localInfo:{type:"string",id:7},sdp:{type:"string",id:8},user:{type:"string",id:9},pid:{type:"string",id:10}}},CreateRtmpProxyPullResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}}}},transport:{nested:{MessageType:{values:{AuthType:0,AuthResponseType:1,ChannelBindType:2,ChannelBindResponseType:3,KeepaliveType:4,KeepaliveResponseType:5,ChannelDataType:6,ReAuthType:7,ReAuthResponseType:8,RefreshTicketType:9,RefreshTicketResponseType:10,ServerRequestType:11,ChannelUnBindType:12,ChannelUnBindResponseType:13,RpcProxyRequestType:14,RpcProxyResponseType:15}},ErrorCode:{values:{Ok:0,Error:1,ErrorLogin:2,ErrorDSInternal:3}},AuthErrorMsg:{values:{SignatureInvalid:0,Expired:1,Unavailable:2}},PingConfig:{fields:{pingInterval:{type:"uint32",id:1},pingTimeout:{type:"uint32",id:2}}},TransportOptions:{oneofs:{_supportPingConfig:{oneof:["supportPingConfig"]}},fields:{supportReliable:{type:"bool",id:1},reliableId:{type:"string",id:2},supportPingConfig:{type:"bool",id:3,options:{proto3_optional:!0}}}},Auth:{fields:{token:{type:"string",id:1},duplicate:{type:"bool",id:2},options:{type:"TransportOptions",id:3}}},AuthResponse:{fields:{code:{type:"ErrorCode",id:1},reason:{type:"string",id:2},ticket:{type:"string",id:3},errorMsg:{type:"AuthErrorMsg",id:4},pingConfig:{type:"PingConfig",id:5}}},ReAuth:{fields:{id:{type:"string",id:1},ticket:{type:"string",id:2},options:{type:"TransportOptions",id:3}}},ReAuthResponse:{fields:{code:{type:"ErrorCode",id:1},reason:{type:"string",id:2},ticket:{type:"string",id:3},errorMsg:{type:"AuthErrorMsg",id:4},pingConfig:{type:"PingConfig",id:5}}},RefreshTicket:{fields:{}},RefreshTicketResponse:{fields:{code:{type:"ErrorCode",id:1},reason:{type:"string",id:2},ticket:{type:"string",id:3}}},ChannelType:{values:{MessageChannel:0,PortalChannel:1,DataSwitcherChannel:2}},ChannelBind:{fields:{type:{type:"ChannelType",id:1},chanId:{type:"uint64",id:2},address:{type:"string",id:3}}},ChannelBindResponse:{fields:{code:{type:"ErrorCode",id:1},reason:{type:"string",id:2},chanId:{type:"uint64",id:3}}},ChannelUnBind:{fields:{type:{type:"ChannelType",id:1},chanId:{type:"uint64",id:2}}},ChannelUnBindResponse:{fields:{code:{type:"ErrorCode",id:1},reason:{type:"string",id:2},chanId:{type:"uint64",id:3}}},Keepalive:{fields:{sequence:{type:"uint32",id:1},pingMs:{type:"uint64",id:2}}},KeepaliveResponse:{fields:{sequence:{type:"uint32",id:1},pongMs:{type:"uint64",id:2}}},ChannelData:{fields:{chanId:{type:"uint64",id:1},data:{type:"bytes",id:2}}},ServerEvent:{values:{RejoinRequest:0,ReauthRequest:1}},Notification:{fields:{event:{type:"ServerEvent",id:1}}},RpcProxyRequest:{fields:{rpcId:{type:"string",id:1},targetServer:{type:"string",id:2},targetServerSubProcessIndex:{type:"uint64",id:3},rpcMethod:{type:"string",id:4},rpcRequestBody:{type:"bytes",id:5}}},RpcProxyResponse:{fields:{rpcId:{type:"string",id:1},rpcResponseCode:{type:"uint32",id:2},rpcResponseBody:{type:"bytes",id:3}}},Message:{oneofs:{data:{oneof:["auth","authResponse","channelBind","channelBindResponse","keepalive","keepaliveResponse","channelData","reauth","reauthResponse","refreshTicket","refreshTicketResponse","notification","channelUnBind","channelUnBindResponse","rpcProxyRequest","rpcProxyResponse"]}},fields:{Type:{type:"MessageType",id:1},Version:{type:"uint32",id:2},SequenceId:{type:"uint32",id:3},auth:{type:"Auth",id:11},authResponse:{type:"AuthResponse",id:12},channelBind:{type:"ChannelBind",id:13},channelBindResponse:{type:"ChannelBindResponse",id:14},keepalive:{type:"Keepalive",id:15},keepaliveResponse:{type:"KeepaliveResponse",id:16},channelData:{type:"ChannelData",id:17},reauth:{type:"ReAuth",id:18},reauthResponse:{type:"ReAuthResponse",id:19},refreshTicket:{type:"RefreshTicket",id:20},refreshTicketResponse:{type:"RefreshTicketResponse",id:21},notification:{type:"Notification",id:22},channelUnBind:{type:"ChannelUnBind",id:23},channelUnBindResponse:{type:"ChannelUnBindResponse",id:24},rpcProxyRequest:{type:"RpcProxyRequest",id:25},rpcProxyResponse:{type:"RpcProxyResponse",id:26}}}}}}}),be=me.lookupType("signal_msg.Response"),Se=me.lookupType("signal_msg.BatchNotification"),Te=me.lookupType("signal_msg.ParticipantNotification"),Ee=me.lookupType("signal_msg.ConferenceNotification"),Ie=me.lookupType("signal_msg.DropNotification"),Ce=me.lookupType("signal_msg.SyncNotification"),Oe=me.lookupType("signal_msg.RejoinRequest"),Pe=me.lookupType("rtmpproxy.CreateRtmpProxyPushRequest");me.lookupType("rtmpproxy.CreateRtmpProxyPullRequest");var Re=me.lookupType("signal_msg.QueryParticipantsVerRequest"),_e=me.lookupType("signal_msg.QueryParticipantsRequest"),Ne=me.lookupType("signal_msg.JoinRequest"),ke=me.lookupType("transport.Message"),Me=me.lookupType("rpc.RpcMessage"),we=me.lookupType("ddmsg.Message"),De=me.lookupType("dsmsg.Message");function je(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(je=function(){return!!e})()}me.lookupType("ddmsg.Data");var Ae=function(){function e(){var t,r,n;return _(this,e),r=this,n=w(n=e),t=M(r,je()?Reflect.construct(n,[],w(r).constructor):n.apply(r,undefined)),Object.defineProperty(t,"timer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(t,"seconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(t,"gapTime",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(t,"sequence",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(t,"maxTime",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),t.timer=null,t.gapTime=15e3,t.maxTime=6e4,t.seconds=0,t.sequence=0,t}return j(e,EventEmitter),k(e,[{key:"start",value:function(e){var t=this,r=e||{},n=r.pingInterval,i=r.pingTimeout;n&&i&&(this.stop(),this.gapTime=1e3*n,this.maxTime=1e3*i),this.timer||(this.ping(),this.timer=addTimer(function(){if(t.seconds++,1e3*t.seconds%t.gapTime==0&&t.ping(),1e3*t.seconds>t.maxTime)throw t.stop(),t.emit("retry"),new DingRTCError(ErrorCode.ConnectionHeartbeatTimeout)},1e3,"interval"))}},{key:"ping",value:function(){var e={sequence:++this.sequence,pingMs:Date.now()};this.emit("ping",{keepalive:e})}},{key:"pong",value:function(e){this.sequence=e.sequence,this.seconds=0}},{key:"stop",value:function(){this.timer&&(removeTimer(this.timer,"interval"),this.timer=null,this.sequence=0,this.seconds=0)}}])}();function Le(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(Le=function(){return!!e})()}var Ue,xe,Ye,qe,Ve,Ge,Je,Be=function(){function e(t,r){var n,i,o;return _(this,e),i=this,o=w(o=e),n=M(i,Le()?Reflect.construct(o,[],w(i).constructor):o.apply(i,undefined)),Object.defineProperty(n,"socket",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(n,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(n,"rpcId",{enumerable:!0,configurable:!0,writable:!0,value:20}),Object.defineProperty(n,"requestMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"proxyReqMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"domain",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),n.socket=t,n.reporter=r,n.logger=n.reporter.getLoggerWithPrefix("[chn-basictrans]"),n.requestMap=new Map,n.proxyReqMap=new Map,n}return j(e,EventEmitter),k(e,[{key:"connect",value:function(e,t){var r=this,n=JSON.parse(fromBase64(e)),i=n.secure,o=n.relayServerHosts,a=void 0===o?[]:o;return a[0]&&(this.domain=a[0]),new Promise(function(n,o){var s=(i?"wss":"ws")+"://"+(a[0]||r.domain);r.socket.removeAllListeners(),r.socket.init(s,e,t),r.socket.on("reauth",function(){r.emit("reauth")}),r.socket.on("rejoin",function(){r.emit("rejoin")}),r.socket.on("connection-state-change",function(e,t,i){r.emit("connection-state-change",e,t,i),"disconnected"===e?o(i):"connected"===e&&n()})})}},{key:"disconnect",value:function(){var e;if(this.requestMap.clear(),null!==(e=this.socket)&&void 0!==e&&e.instance&&"disconnected"!==this.socket.state)return this.socket.close(!0)}},{key:"sendChnData",value:function(e,t){var r=this,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,i=arguments.length>3&&void 0!==arguments[3]&&arguments[3],o={MagicNumber:5,Version:1,Type:0,NeedAck:!0,RpcId:this.rpcId++,Method:e,Data:t},a=Me.encode(o).finish();return i&&this.logger.debug("rpcId ".concat(o.RpcId,":").concat(e," param====> ").concat(JSON.stringify(n||""))),new Promise(function(t,s){r.socket.send(de.MessageType.ChannelDataType,{channelData:{data:a,chanId:1}},o.RpcId,e);var c=o.RpcId;r.requestMap.set(c,{resolve:t,reject:s,payload:{methond:e,internal:i,rpcId:c,param:n||""}}),addTimer(function(){var t=r.requestMap.get(c);null!=t&&t.reject&&(t.reject(new DingRTCError(ErrorCode.APICallTimeOut,"".concat(e," timeout"))),r.requestMap.delete(c))},ue)})}},{key:"proxyRtmpReq",value:function(e,t,r,n){var i=this;this.logger.info("rpcRequestBody===",n);var o=Pe.encode(n).finish();return new Promise(function(n,a){var s=e||createUuid(10);i.socket.send(de.MessageType.RpcProxyRequestType,{rpcProxyRequest:{rpcId:s,targetServer:t,targetServerSubProcessIndex:0,rpcMethod:r,rpcRequestBody:o}}),i.proxyReqMap.set(e,{resolve:n,reject:a}),addTimer(function(){var t=i.proxyReqMap.get(e);null!=t&&t.reject&&(t.reject(new DingRTCError(ErrorCode.APICallTimeOut,"proxyRtmpReq timeout ".concat(r," ").concat(e))),i.proxyReqMap.delete(e))},ue)})}},{key:"onProxyRtmpResponseMsg",value:function(e){var t=this.proxyReqMap.get(e.rpcProxyResponse.rpcId);e.rpcProxyResponse.rpcResponseCode?null==t||t.reject(e.rpcProxyResponse.rpcResponseCode):null==t||t.resolve(e.rpcProxyResponse.rpcResponseBody)}},{key:"handleNotification",value:function(e,t){var r=this;if("batch-notify"===e){var n=Se.decode(t).notificationItem,i=["participant","conference","sync"];n.forEach(function(e){"participant"===e.event?r.emit("participant",e.participantNotification):"conference"===e.event?r.emit("conference",e.conferenceNotification):"sync"===e.event&&r.emit("sync",e.syncNotification)}),n.filter(function(e){return!i.includes(e.event)}).length&&this.emit("batch-notify",t)}else"participant"===e?this.emit("participant",Te.decode(t)):"conference"===e?this.emit("conference",Ee.decode(t)):"drop"===e?this.emit("drop",Ie.decode(t)):"sync"===e?this.emit("sync",Ce.decode(t)):this.emit("notify",e,t)}},{key:"onMessage",value:function(e){var t=Me.decode(new Uint8Array(e.channelData.data));if(t.Type===ae.RpcType.Resp){var r=this.requestMap.get(t.RpcId);if(!r)return;var n=r.resolve,i=r.reject,o=r.payload;if(o.internal){var a=be.decode(t.Data);a.result===re.Result.Ok?(this.logger.debug("rpcId ".concat(o.rpcId,": ").concat(o.methond," result====> ").concat(JSON.stringify(a))),n(a)):(this.logger.error("rpcId ".concat(o.rpcId,": ").concat(o.methond," error====> ").concat(JSON.stringify(a))),i(a))}else n(t.Data);this.requestMap.delete(t.RpcId)}else t.Type===ae.RpcType.Req&&this.handleNotification(t.Method,t.Data)}}])}();!function(e){e[e.UserKickOut=2011]="UserKickOut",e[e.UserReplaced=2012]="UserReplaced"}(Ue||(Ue={})),function(e){e[e.Unknown=0]="Unknown",e[e.SubtopDS=1]="SubtopDS",e[e.Linkserver=2]="Linkserver",e[e.Vmixer=3]="Vmixer",e[e.Minutes=4]="Minutes"}(xe||(xe={})),function(e){e[e.UnknownId=0]="UnknownId",e[e.ControlNodeId=1]="ControlNodeId",e[e.TerminalNodeId=2]="TerminalNodeId",e[e.ChannelId=3]="ChannelId"}(Ye||(Ye={})),function(e){e[e.NORMAL_ATTACH=0]="NORMAL_ATTACH",e[e.FORCE_REATTACH=1]="FORCE_REATTACH",e[e.RESYNC=2]="RESYNC"}(qe||(qe={})),function(e){e[e.NODE_JOIN=0]="NODE_JOIN",e[e.NODE_LEAVE=1]="NODE_LEAVE"}(Ve||(Ve={})),function(e){e[e.High=0]="High",e[e.Normal=1]="Normal",e[e.Low=2]="Low"}(Ge||(Ge={})),function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.DEFAULT=1]="DEFAULT",e[e.NODE_MAP=2]="NODE_MAP"}(Je||(Je={}));var Fe=function(e){return"number"==typeof e?Long.fromNumber(e,!0):new Long(e.low,e.high,e.unsigned)},Ke=function(){function e(){_(this,e)}return k(e,null,[{key:"isValidId",value:function(t){var r=Fe(t);if(r.and(e.ChannelMaskLong.not()).eq(Long.ZERO))return!0;var n=r.and(e.NodeTypeMaskLong).eq(e.NodeTypeMaskLong),i=r.and(e.TerminalMaskLong).eq(Long.ZERO);if(!n&&i||n&&!i)return!1;var o=r.and(e.UseCtrlL1MaskLong).eq(e.UseCtrlL1MaskLong),a=r.and(e.CtrlLayer1MaskLong).eq(Long.ZERO);return!(o&&a||!o&&!a)}},{key:"getIdType",value:function(t){var r=Fe(t);return r.and(e.ChannelMaskLong).eq(r)?Ye.ChannelId:e.isValidId(t)?r.and(e.NodeTypeMaskLong).eq(e.NodeTypeMaskLong)?Ye.ControlNodeId:Ye.TerminalNodeId:Ye.UnknownId}},{key:"replaceClusterId",value:function(t,r){return t.and(e.ClusterIdMaskLong.not()).or(Long.fromNumber(r).shiftLeft(42))}},{key:"getTopNodeId",value:function(t){return(4095&t)<<42|e.NodeTypeMask}},{key:"extractParentNodeId",value:function(t,r){var n=Fe(t);if(!this.isValidId(n)||this.isTopControlNode(n))return Long.ZERO;var i=n.and(e.EndpointMaskLong),o=n.and(e.NodeTypeMaskLong).equals(e.NodeTypeMaskLong),a=n.and(e.UseCtrlL1MaskLong).equals(e.UseCtrlL1MaskLong);if(o&&a||!o&&!a){var s=e.replaceClusterId(e.NodeTypeMaskLong.or(e.CtrlLayer0MaskLong.or(e.SubDsMaskLong).and(n)),r).or(i);return o&&a?s.and(e.SubDsMaskLong.not()).or(Long.fromNumber((15&xe.SubtopDS)<<54)):s}return o&&!a?e.replaceClusterId(Long.fromNumber(e.NodeTypeMask),r).or(i).and(e.SubDsMaskLong.not()):!o&&a?e.replaceClusterId(e.NodeTypeMaskLong.or(e.UseCtrlL1MaskLong).or(e.CtrlLayer0MaskLong).or(e.CtrlLayer1MaskLong.or(e.CtrlLayer1MaskLong).or(e.SubDsMaskLong)).and(n),r).or(i):0}},{key:"extractNodeIdWithoutClusterId",value:function(t){var r=e.EndpointMaskLong.or(e.ClusterIdMaskLong).or(e.ReservedMaskLong).or(e.SubDsMask);return Fe(t).and(r.not())}},{key:"isTopControlNode",value:function(t){var r=Fe(t);return r.and(e.NodeTypeMaskLong).equals(e.NodeTypeMaskLong)&&r.and(e.UseCtrlL1MaskLong).or(e.CtrlLayer0MaskLong).or(e.CtrlLayer1MaskLong).or(e.TerminalMaskLong)}},{key:"isDirectChild",value:function(t,r){if(0==(r&e.NodeTypeMask))return!1;var n=t&(e.CtrlLayer0Mask|e.CtrlLayer1Mask|e.TerminalMask),i=r&(e.CtrlLayer0Mask|e.CtrlLayer1Mask|e.TerminalMask);return n!=r&&0!=t&&(i==(n&(e.CtrlLayer0Mask|e.CtrlLayer1Mask))||i==(n&e.CtrlLayer0Mask)&&0==(n&~(e.CtrlLayer0Mask|e.CtrlLayer1Mask))||0==i&&0==(t&~e.CtrlLayer0Mask))}},{key:"isChild",value:function(t,r){if(0==(r&e.NodeTypeMask))return!1;var n=t&(e.CtrlLayer0Mask|e.CtrlLayer1Mask|e.TerminalMask),i=r&(e.CtrlLayer0Mask|e.CtrlLayer1Mask|e.TerminalMask);return n!==i&&0!==n&&(0===i||r==(n&(e.CtrlLayer0Mask|e.CtrlLayer1Mask))||i==(n&e.CtrlLayer0Mask))}},{key:"isMe",value:function(t,r){if(!this.isValidId(t)||!this.isValidId(r))return!1;var n=e.EndpointMaskLong.or(e.ClusterIdMask).or(e.ReservedMaskLong);return Fe(t).and(n.not()).eq(Fe(r).and(n.not()))}},{key:"extractEndpointId",value:function(t){return Fe(t).and(e.EndpointMaskLong).toNumber()}},{key:"composeId",value:function(t,r){return Fe(t).and(e.EndpointMaskLong.not()).or(Fe(r))}},{key:"extractNodeId",value:function(t){return Fe(t).and(e.EndpointMaskLong.not())}}])}();function He(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function We(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?He(Object(r),!0).forEach(function(t){R(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):He(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function Qe(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(Qe=function(){return!!e})()}Object.defineProperty(Ke,"ReservedMask",{enumerable:!0,configurable:!0,writable:!0,value:63<<58}),Object.defineProperty(Ke,"SubDsMask",{enumerable:!0,configurable:!0,writable:!0,value:15<<54}),Object.defineProperty(Ke,"ClusterIdMask",{enumerable:!0,configurable:!0,writable:!0,value:4193280}),Object.defineProperty(Ke,"NodeTypeMask",{enumerable:!0,configurable:!0,writable:!0,value:512}),Object.defineProperty(Ke,"UseCtrlL1Mask",{enumerable:!0,configurable:!0,writable:!0,value:256}),Object.defineProperty(Ke,"CtrlLayer0Mask",{enumerable:!0,configurable:!0,writable:!0,value:1023<<30}),Object.defineProperty(Ke,"CtrlLayer1Mask",{enumerable:!0,configurable:!0,writable:!0,value:1023<<20}),Object.defineProperty(Ke,"TerminalMask",{enumerable:!0,configurable:!0,writable:!0,value:1048320}),Object.defineProperty(Ke,"EndpointMask",{enumerable:!0,configurable:!0,writable:!0,value:255}),Object.defineProperty(Ke,"ChannelMask",{enumerable:!0,configurable:!0,writable:!0,value:255}),Object.defineProperty(Ke,"ReservedMaskLong",{enumerable:!0,configurable:!0,writable:!0,value:Long.fromNumber(63).shiftLeft(58)}),Object.defineProperty(Ke,"SubDsMaskLong",{enumerable:!0,configurable:!0,writable:!0,value:Long.fromNumber(15).shiftLeft(54)}),Object.defineProperty(Ke,"ClusterIdMaskLong",{enumerable:!0,configurable:!0,writable:!0,value:Long.fromNumber(4095).shiftLeft(42)}),Object.defineProperty(Ke,"NodeTypeMaskLong",{enumerable:!0,configurable:!0,writable:!0,value:Long.fromNumber(1).shiftLeft(41)}),Object.defineProperty(Ke,"UseCtrlL1MaskLong",{enumerable:!0,configurable:!0,writable:!0,value:Long.fromNumber(1).shiftLeft(40)}),Object.defineProperty(Ke,"CtrlLayer0MaskLong",{enumerable:!0,configurable:!0,writable:!0,value:Long.fromNumber(1023).shiftLeft(30)}),Object.defineProperty(Ke,"CtrlLayer1MaskLong",{enumerable:!0,configurable:!0,writable:!0,value:Long.fromNumber(63).shiftLeft(20)}),Object.defineProperty(Ke,"TerminalMaskLong",{enumerable:!0,configurable:!0,writable:!0,value:Long.fromNumber(4095).shiftLeft(8)}),Object.defineProperty(Ke,"EndpointMaskLong",{enumerable:!0,configurable:!0,writable:!0,value:Long.fromNumber(255)}),Object.defineProperty(Ke,"ChannelMaskLong",{enumerable:!0,configurable:!0,writable:!0,value:Long.fromNumber(255)});var Ze=function(){function e(t,r){var n,i,o;return _(this,e),i=this,o=w(o=e),n=M(i,Qe()?Reflect.construct(o,[],w(i).constructor):o.apply(i,undefined)),Object.defineProperty(n,"socket",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(n,"requestMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"attachUserConfirm",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),n.socket=t,n.logger=r.getLoggerWithPrefix("[chn-switchtrans]"),n.requestMap=new Map,n}return j(e,EventEmitter),k(e,[{key:"channelBind",value:function(e){var t=this,r={chanId:2,type:de.ChannelType.DataSwitcherChannel,address:location.hostname},n="".concat(e,"#").concat(se.MessageType.TYPE_ATTACH_USER_CONFIRM);return this.commitRPC(function(){return t.socket.send(de.MessageType.ChannelBindType,{channelBind:r}).catch(function(e){var r;throw null===(r=t.requestMap.get(n))||void 0===r||r.reject(e),t.requestMap.delete(n),e})},n)}},{key:"commitRPC",value:function(e,t){var r=this;return t?new Promise(function(n,i){e(),r.requestMap.set(t,{resolve:n,reject:i}),addTimer(function(){var e=r.requestMap.get(t);null!=e&&e.reject&&(e.reject(new DingRTCError(ErrorCode.APICallTimeOut,"".concat(t," timeout"))),r.requestMap.delete(t))},8e3)}):Promise.resolve(e())}},{key:"send",value:function(e,t){var r,n=this,i=e[ve.rpcTypeKeyMap[e.type]],o=i.sessionType,a=i.sessionKey,s=i.requestId,c=i.groupId,u=i.nodeId;s?r="".concat(Ke.extractEndpointId(t.from),"#").concat(s):a?r="".concat(o,"#").concat(a,"#").concat(e.type+1):c&&(r="".concat(u.toString(),"#").concat(c,"#").concat(e.type+1));var l={msgType:oe.Type.kData,data:We(We({},t),{},{data:De.encode(e).finish()})},d={Type:de.MessageType.ChannelDataType,Version:1,channelData:{chanId:2,data:we.encode(l).finish()}};return this.commitRPC(function(){return n.socket.instance.send(ke.encode(d).finish())},r)}},{key:"onMessage",value:function(e){var t=we.decode(e),r=t.msgType,n=t.data,i=n.to,o=n.from,a=n.data;if(r===oe.Type.kData){var s;try{s=De.decode(a)}catch(e){return void this.logger.warn("handleMessage, dsmsg parse failed")}var c=Ke.getIdType(i)===Ye.ChannelId,u=Ke.extractEndpointId(c?o:i),l=s.type,d=ve.msgTypeKeyMap[l],p=s[d];if(p)if(ve.confirmTypes.includes(l)){this.logger.debug("".concat(d,": ").concat(JSON.stringify(p)));var f,h=p.result,g=p.requestId,m=p.sessionKey,v=p.sessionType,y=p.serverNodeId,b=p.pid,S=p.groupId,_=p.nodeId;g?f="".concat(u,"#").concat(g):y?f="".concat(b,"#").concat(l):m?f="".concat(v,"#").concat(m,"#").concat(l):S&&(f="".concat(_.toString(),"#").concat(S,"#").concat(l));var E=this.requestMap.get(f);if(!E)return;0===h?(this.logger.info("".concat(d," rpcId:").concat(f," result===> ").concat(JSON.stringify(p))),E.resolve(p)):(this.logger.warn("".concat(d," rpcId:").concat(f," error===> ").concat(JSON.stringify(p))),E.reject(p)),this.requestMap.delete(f)}else l===se.MessageType.TYPE_SESSION_CMD_DATA_NOTIFICATION?this.emit("sessionCmdData",u,c,p):l===se.MessageType.TYPE_SESSION_DATA?this.emit("sessionData",o,u,c?i:0,p):l===se.MessageType.TYPE_DETACH_USER_CONFIRM?this.emit("detachUserConfirm",p):l===se.MessageType.TYPE_NODE_MAP_UPDATE?this.emit("nodeMapUpdated",u,p):l===se.MessageType.TYPE_NODE_MAP_SNAPSHOT?this.emit("nodeMapSnapshot",u,p):l===se.MessageType.TYPE_SESSION_CREATED?this.emit("sessionCreated",p):l===se.MessageType.TYPE_SESSION_CLOSED?this.emit("sessionClosed",p):l===se.MessageType.TYPE_GROUP_CREATED?this.emit("groupCreated",u,p):l===se.MessageType.TYPE_GROUP_DESTROYED?this.emit("groupDestroyed",u,p):l===se.MessageType.TYPE_SERVICE_STATUS?this.emit("serviceStatus",u,p):l===se.MessageType.TYPE_SWITCHER_UPDATE&&this.emit("switchUpdate",p);else this.logger.warn("msgType: ".concat(d," has no payload"))}}}])}();function ze(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function $e(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return($e=function(){return!!e})()}var Xe=function(){function e(t){var r,n,i;return _(this,e),n=this,i=w(i=e),r=M(n,$e()?Reflect.construct(i,[],w(n).constructor):i.apply(n,undefined)),Object.defineProperty(r,"instance",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"heartBeat",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"requestMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"ticket",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"token",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"refreshTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"sequenceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"rejoin",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"basicTransport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"switchTransport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"destroyed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"retryCount",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"socketReconnectionTimeoutTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"signalReconnectionTimeoutTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"connectionTimeoutTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"state",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"instantlyReconnect",{enumerable:!0,configurable:!0,writable:!0,value:function(){r.logger.info("instantlyReconnect for browser offline event"),window.removeEventListener("offline",r.instantlyReconnect),"reconnecting"!==r.state&&r.setTimerToReconnectSocket(!0)}}),r.logger=t.getLoggerWithPrefix("[chn-socket]"),r.state="disconnected",r.requestMap=new Map,r.heartBeat=new Ae,r.refreshTimer=null,r.sequenceId=1,r.retryCount=0,r.switchTransport=new Ze(r,t),r.basicTransport=new Be(r,t),r}return j(e,EventEmitter),k(e,[{key:"onHeartBeat",value:function(){var e=this;this.heartBeat.on("retry",function(){e.destroyed||e.reconnect("keepalive")}),this.heartBeat.on("ping",function(t){e.send(de.MessageType.KeepaliveType,t)})}},{key:"setTimerToReconnectSocket",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.signalReconnectionTimeoutTimer&&(removeTimer(this.signalReconnectionTimeoutTimer),this.signalReconnectionTimeoutTimer=null),this.signalReconnectionTimeoutTimer=addTimer(function(){e.reconnect(t?"reconnect for noWaitTime":"reconnect req Timeout")},t?0:15e3)}},{key:"reconnect",value:function(e){this.close(),this.logger.debug("retry connect start, for ".concat(e)),this.clearConnectionTimer(!0),"connected"!==this.state&&"connecting"!==this.state||this.updateState("reconnecting"),this.init(this.url,this.token,!1,6e3)}},{key:"init",value:function(e,t){var r,n=this,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:-1;o>0&&(r=addTimer(function(){n.logger.info("finish connect init due to timeout"),n.instance.onclose=null,n.instance.onerror=null,n.instance.onopen=null,n.instance.onmessage=null,n.instance.close(),n.onClose(new CloseEvent("socket connect timeout, positive finished"))},o)),this.url=e,this.token=t,this.rejoin=i,"reconnecting"!==this.state&&(this.updateState("connecting"),this.connectionTimeoutTimer=addTimer(function(){n.updateState("disconnected","network_error"),n.close(!0)},32e3)),this.instance=new WebSocket(e),this.instance.binaryType="arraybuffer",this.instance.onopen=function(){removeTimer(r),n.onOpen()},this.instance.onmessage=function(e){n.onMessage(e)},this.instance.onerror=function(e){n.onError(e)},this.instance.onclose=function(e){removeTimer(r),n.onClose(e)}}},{key:"clear",value:function(){this.heartBeat.stop(),this.clearConnectionTimer(),this.requestMap.clear(),this.heartBeat.removeAllListeners()}},{key:"close",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.destroyed=e,this.clear(),this.instance&&(this.instance.onerror=null,this.instance.onmessage=null,this.instance.onclose=null,this.instance.onopen=null,this.instance.close(),this.instance=null)}},{key:"getTransportData",value:function(e,t){var r=function(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ze(Object(r),!0).forEach(function(t){R(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ze(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}({Type:e,Version:1,SequenceId:this.sequenceId++},t);return ke.encode(r).finish()}},{key:"send",value:function(e,t,r,n){var i,o,a=this;if(1!==(null===(i=this.instance)||void 0===i?void 0:i.readyState))return Promise.reject("socket state error: ".concat((null===(o=this.instance)||void 0===o?void 0:o.readyState)||0));var s=this.getTransportData(e,t);if(de.MessageType.KeepaliveType!==e&&this.setTimerToReconnectSocket(),![de.MessageType.KeepaliveType,de.MessageType.ChannelDataType].includes(e))return new Promise(function(t,i){a.instance.send(s);var o=null!=r?r:e,c=n||e;a.requestMap.set(o,{resolve:t,reject:i}),addTimer(function(){var e=a.requestMap.get(o);null!=e&&e.reject&&(e.reject(new DingRTCError(ErrorCode.APICallTimeOut,"".concat(c," timeout"))),a.requestMap.delete(o))},ue)});this.instance.send(s)}},{key:"clearConnectionTimer",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.signalReconnectionTimeoutTimer&&(removeTimer(this.signalReconnectionTimeoutTimer),this.signalReconnectionTimeoutTimer=null),this.socketReconnectionTimeoutTimer&&e&&(removeTimer(this.socketReconnectionTimeoutTimer),this.socketReconnectionTimeoutTimer=null),null!=this.connectionTimeoutTimer&&(removeTimer(this.connectionTimeoutTimer),this.connectionTimeoutTimer=null)}},{key:"channelBind",value:function(){this.logger.info("channelBind started");var e={chanId:1,type:de.ChannelType.PortalChannel,address:location.hostname};return this.send(de.MessageType.ChannelBindType,{channelBind:e})}},{key:"auth",value:function(e){var t=this;return this.logger.info("auth started rejoin=",this.rejoin),this.send(de.MessageType.AuthType,{auth:{token:e,duplicate:this.rejoin,options:{supportReliable:!1,supportPingConfig:!0}}}).then(function(e){if(t.logger.info("auth res",e),t.refresh(e.ticket),e.pingConfig)return e.pingConfig})}},{key:"refresh",value:function(e){var t=this;this.ticket=e;var r=JSON.parse(fromBase64(e)).notAfter,n=Date.now();if(r<=n-1e4)this.logger.warn("Reconnection ticket expires too soon.");else{var i=r-n-6e4;i<0&&(i=r-n-1e4),removeTimer(this.refreshTimer),this.refreshTimer=addTimer(function(){t.refreshTicket().then(function(e){t.refresh(e.ticket)})},i)}}},{key:"refreshTicket",value:function(){return this.send(de.MessageType.RefreshTicketType,{refreshTicket:{}})}},{key:"reauth",value:function(e){var t=this;return this.send(de.MessageType.ReAuthType,{reauth:{ticket:e,options:{supportReliable:!1,supportPingConfig:!0}}}).then(function(e){t.emit("reauth"),e.pingConfig&&t.heartBeat.start(e.pingConfig)}).catch(function(e){t.logger.error("reauth error"+JSON.stringify(e)),(null==e?void 0:e.errorMsg)!==de.AuthErrorMsg.Unavailable?t.onRejoin():(t.updateState("disconnected","timeout"),t.close(!0))})}},{key:"onRejoin",value:function(){this.rejoin||(this.emit("rejoin"),this.logger.warn("rejoin started")),this.close(!0)}},{key:"onMessage",value:function(e){this.setTimerToReconnectSocket();var t=ke.decode(new Uint8Array(e.data));if(t.Type===de.MessageType.ChannelDataType)1===t.channelData.chanId?this.basicTransport.onMessage(t):2===t.channelData.chanId&&this.switchTransport.onMessage(t.channelData.data);else if(t.Type===de.MessageType.RpcProxyResponseType)this.logger.debug("onmsg",t.Type,t),this.basicTransport.onProxyRtmpResponseMsg(t);else if(t.Type===de.MessageType.KeepaliveResponseType)this.heartBeat.pong(t.keepaliveResponse);else if(t.Type===de.MessageType.ServerRequestType){var r=t.notification.event;this.logger.warn("server request ".concat(1===r?"reauth":"rejoin")),r===de.ServerEvent.ReauthRequest?this.reauth(this.ticket):r===de.ServerEvent.RejoinRequest&&this.onRejoin()}else{var n,i,o=new Map([[de.MessageType.AuthResponseType,t.authResponse],[de.MessageType.ChannelBindResponseType,t.channelBindResponse],[de.MessageType.ReAuthResponseType,t.reauthResponse],[de.MessageType.RefreshTicketResponseType,t.refreshTicketResponse]]).get(t.Type);o.code===de.ErrorCode.Ok?null===(n=this.requestMap.get(t.Type-1))||void 0===n||n.resolve(o):null===(i=this.requestMap.get(t.Type-1))||void 0===i||i.reject(o),this.requestMap.delete(t.Type-1)}}},{key:"onError",value:function(e){this.logger.error("onError: ".concat(JSON.stringify(e)))}},{key:"onOpen",value:(t=C(pe.mark(function e(){var t,r,n,i=this;return pe.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(this.clearConnectionTimer(!0),this.retryCount=0,window.addEventListener("offline",this.instantlyReconnect),"reconnecting"!==this.state){e.next=1;break}this.reauth(this.ticket).then(function(){i.rejoin=!1,i.updateState("connected"),i.onHeartBeat()}),e.next=5;break;case 1:return e.prev=1,e.next=2,this.auth(this.token);case 2:return t=e.sent,e.next=3,this.channelBind();case 3:r=e.sent,this.logger.info("channelBind res",r),this.rejoin=!1,this.updateState("connected"),this.onHeartBeat(),this.heartBeat.start(t),e.next=5;break;case 4:e.prev=4,n=e.catch(1),this.logger.debug("auth or channelBind failed",n),this.updateState("disconnected","server_error"),this.close(!0);case 5:case"end":return e.stop()}},e,this,[[1,4]])})),function(){return t.apply(this,arguments)})},{key:"updateState",value:function(e,t){e!==this.state&&(this.emit("connection-state-change",e,this.state,t),this.state=e)}},{key:"onClose",value:function(e){var t=this;this.logger.warn("socket closed:"+JSON.stringify(e)),this.rejoin?this.updateState("disconnected","server_error"):this.destroyed||("reconnecting"===this.state?(this.retryCount++,this.retryCount>18?(this.updateState("disconnected","network_error"),this.retryCount=0):this.socketReconnectionTimeoutTimer=addTimer(function(){t.reconnect("retry count"+t.retryCount)},ye)):"connecting"==this.state?this.socketReconnectionTimeoutTimer=addTimer(function(){t.reconnect("localNetwork")},ye):"disconnected"!==this.state&&(this.socketReconnectionTimeoutTimer=addTimer(function(){t.reconnect("server closed, retry count"+t.retryCount)},ye))),this.clear()}}]);var t}();function et(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function tt(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?et(Object(r),!0).forEach(function(t){R(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):et(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}var nt=getReporter().getLoggerWithPrefix("[ch-gslb]");function it(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(it=function(){return!!e})()}var rt=function(){function e(t,r){var n,i,o;return _(this,e),i=this,o=w(o=e),n=M(i,it()?Reflect.construct(o,[],w(i).constructor):o.apply(i,undefined)),Object.defineProperty(n,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(n,"transport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),n.transport=t.basicTransport,n.reporter=r,n.logger=n.reporter.getLoggerWithPrefix("[chn-signaling]"),n.forwardNotification(),n}return j(e,EventEmitter),k(e,[{key:"forwardNotification",value:function(){var e=this;["participant","batch-notify","conference","drop","notify","rejoin","connection-state-change","sync","reauth"].forEach(function(t){e.transport.on(t,function(){for(var r=arguments.length,n=new Array(r),i=0;i<r;i++)n[i]=arguments[i];e.emit.apply(e,[t].concat(n))})})}},{key:"relogin",value:function(e){var t=this,r=e.token,n=Oe.encode(e).finish();return this.transport.connect(r,!0).then(function(){return t.transport.sendChnData("rejoin-login",n,e,!0).then(function(e){return e.rejoinResponse})})}},{key:"login",value:function(e){var t=this,r=e.token,n=Ne.encode(e).finish();return this.transport.connect(r,!1).then(function(){return t.transport.sendChnData("login",n,e,!0).then(function(e){return e.joinResponse})})}},{key:"diconnect",value:function(){return this.transport.disconnect()}},{key:"logout",value:function(){var e=this;return this.transport.sendChnData("logout",void 0,null,!0).catch(function(t){e.logger.debug("logout api called failed ".concat(JSON.stringify(t)))}),this.diconnect()}},{key:"getUsersVer",value:function(e){var t=Re.encode(e).finish();return this.transport.sendChnData("query-participants-ver",t,e,!0).then(function(e){return e.queryParticipantsVerResponse})}},{key:"getUsers",value:function(e){var t=_e.encode(e).finish();return this.transport.sendChnData("query-participants",t,e,!0).then(function(e){return e.queryParticipantsResponse})}},{key:"rpc",value:function(e,t,r){return this.transport.sendChnData(e,t,r)}}])}();function ot(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function st(e,t){if(e){if("string"==typeof e)return ot(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?ot(e,t):void 0}}function at(e){return function(e){if(Array.isArray(e))return ot(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||st(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function dt(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function ct(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?dt(Object(r),!0).forEach(function(t){R(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):dt(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function pt(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return lt(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?lt(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function lt(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function ut(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(ut=function(){return!!e})()}var yt,ht,ft,gt,vt,mt,bt,St=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:50,r=null;return function(){for(var n=this,i=arguments.length,o=new Array(i),a=0;a<i;a++)o[a]=arguments[a];r&&clearTimeout(r),r=setTimeout(function(){e.apply(n,o)},t)}},Tt=function(){function e(t){var r,n,i;return _(this,e),n=this,i=w(i=e),r=M(n,ut()?Reflect.construct(i,[],w(n).constructor):i.apply(n,undefined)),Object.defineProperty(r,"channel",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(r,"participants",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"currentPid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"totalVer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"onConnectionStateChange",{enumerable:!0,configurable:!0,writable:!0,value:function(e,t){r.logger.info("chn connection-state-change",e,t),"connected"===e&&"reconnecting"===t&&r.debounceSyncRpc(!1)}}),Object.defineProperty(r,"debounceSyncRpc",{enumerable:!0,configurable:!0,writable:!0,value:St(r.doSyncRpc,1e3)}),r.participants=new Map,r.channel=t,r.reporter=t.reporter,r.logger=r.reporter.getLoggerWithPrefix("[chn-usermgr]"),r.handleEvent=r.handleEvent.bind(r),r.handleSyncEvent=r.handleSyncEvent.bind(r),r.debounceSyncRpc=r.debounceSyncRpc.bind(r),r}return j(e,EventEmitter),k(e,[{key:"currentUids",get:function(){return at(this.participants.values()).map(function(e){return e.user})}},{key:"init",value:function(e,t,r){var n,i=pt(e);try{for(i.s();!(n=i.n()).done;){var o=n.value;this.participants.set(o.id,o)}}catch(e){i.e(e)}finally{i.f()}this.totalVer=t,this.currentPid=r,this.channel.signaling.on("participant",this.handleEvent),this.channel.signaling.on("sync",this.handleSyncEvent),this.channel.signaling.on("reauth",this.debounceSyncRpc),this.channel.on("connection-state-change",this.onConnectionStateChange)}},{key:"clear",value:function(){this.participants.clear(),this.currentPid="",this.totalVer=0,this.channel.signaling.off("participant",this.handleEvent),this.channel.signaling.off("sync",this.handleSyncEvent),this.channel.signaling.off("reauth",this.debounceSyncRpc),this.channel.off("connection-state-change",this.onConnectionStateChange)}},{key:"handleEvent",value:function(e,t){var r=this;this.logger.info("channelUserEvent",e);var n=e.action,i=e.info,o=e.participantId,a=e.totalVer,s=e.propertiesData,c=this.totalVer,u=this.participants.get(o||(null==s?void 0:s.id));if(a==c+1||-999==a||t)if("join"===n&&i){var l=at(this.participants.values()).filter(function(e){return e.user===i.user});this.participants.set(i.id,i),0===l.length?this.emit("user","join",i):(this.logger.info("delete same uid participants, for new join",i,l),l.map(function(e){return r.participants.delete(e.id)}),this.emit("user","participant-replace",i,l))}else"leave"===n?u?(this.participants.delete(o),this.currentUids.includes(u.user)?this.logger.info("user ".concat(u.user," has another pid in channel")):this.emit("user","leave",u)):this.logger.info("Received leave message for unknown participant."):"setProperties"===n&&(u.propertiesJsonStr=JSON.stringify(ct(ct({},JSON.parse(u.propertiesJsonStr||"{}")),JSON.parse(s.propertiesJsonStr||"{}"))),this.emit("user","update",u));t||a<=this.totalVer&&-999!==a||(a===c+1&&(this.totalVer=a),a>c+1&&!t&&(this.logger.info("debounceSyncRpc by user event"),this.debounceSyncRpc()))}},{key:"handleSyncEvent",value:function(e){var t=e.participantsVer;this.totalVer<t&&(this.logger.info("debounceSyncRpc by sync event"),this.debounceSyncRpc())}},{key:"doSyncRpc",value:(t=C(pe.mark(function e(){var t,r,n,i,o,a,s,c,u,l,d,p,f,h,g,m,v,y,b,S,_,E,T,R,C,k,P,w,O,I,A=arguments;return pe.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t=!(A.length>0&&void 0!==A[0])||A[0],this.logger.info("request sync user checkUserVer=",t),r=[],n=[],e.prev=1,e.next=2,this.channel.signaling.getUsersVer({});case 2:a=e.sent,i=a.participants,o=a.totalVer,e.next=4;break;case 3:return e.prev=3,I=e.catch(1),this.logger.error("sync error",I),e.abrupt("return");case 4:s=at(this.participants.keys()),c=i.map(function(e){return e.id}),u=pt(i);try{for(u.s();!(l=u.n()).done;)p=l.value,f=p.id,h=p.ver,this.participants.has(f)?((null===(d=this.participants.get(f))||void 0===d?void 0:d.ver)!==h&&t||!t)&&r.push(f):n.push(f)}catch(e){u.e(e)}finally{u.f()}if(this.reporter.trace.syncEvent("user",s,c),g=s.filter(function(e){return!c.includes(e)}),m=at(new Set(r.concat(g,n))),this.totalVer=o,0!==m.length){e.next=5;break}return this.logger.info("no diff user, return"),e.abrupt("return");case 5:return e.next=6,this.channel.signaling.getUsers({pids:m});case 6:v=e.sent,y=v.participants,b=v.totalVer,S=new Map,_=pt(this.participants.values());try{for(_.s();!(E=_.n()).done;)T=E.value,S.set(T.id,T)}catch(e){_.e(e)}finally{_.f()}R=pt(y);try{for(R.s();!(C=R.n()).done;)k=C.value,this.participants.has(k.id)?(this.participants.set(k.id,k.data),this.handleEvent({action:"setProperties",participantId:k.id,info:this.participants.get(k.id),totalVer:b,propertiesData:k.data},!0)):S.set(k.id,k.data)}catch(e){R.e(e)}finally{R.f()}for(P=at(S.values()),w=0;w<P.length;w++)O=P[w],n.includes(O.id)?this.handleEvent({action:"join",participantId:O.id,info:O,totalVer:b},!0):g.includes(O.id)&&this.handleEvent({action:"leave",participantId:O.id,info:O,totalVer:b},!0);this.totalVer=b;case 7:case"end":return e.stop()}},e,this,[[1,3]])})),function(){return t.apply(this,arguments)})}]);var t}();function Et(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,i,o,a,s=[],c=!0,u=!1;try{if(o=(r=r.call(e)).next,0===t);else for(;!(c=(n=o.call(r)).done)&&(s.push(n.value),s.length!==t);c=!0);}catch(e){u=!0,i=e}finally{try{if(!c&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(u)throw i}}return s}}(e,t)||st(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}!function(e){e[e.UNKNOWN=-1]="UNKNOWN",e[e.WHITEBOARD=0]="WHITEBOARD",e[e.RTCSERVICE=1]="RTCSERVICE",e[e.RTCSUBTITLE=2]="RTCSUBTITLE",e[e.CUSTOMIZE=101]="CUSTOMIZE"}(yt||(yt={})),function(e){e[e.NODE_JOIN=0]="NODE_JOIN",e[e.NODE_LEAVE=1]="NODE_LEAVE"}(ht||(ht={})),function(e){e[e.RTMS=0]="RTMS",e[e.SDK=1]="SDK",e[e.APP=2]="APP"}(ft||(ft={})),function(e){e[e.OPEN=0]="OPEN",e[e.CLOSE=1]="CLOSE",e[e.ERROR=2]="ERROR"}(gt||(gt={})),function(e){e.IDLE="idle",e.READY="ready"}(vt||(vt={})),function(e){e.UNINITED="uninited",e.READY="ready",e.LEFT="left",e.CLOSED="closed"}(mt||(mt={})),function(e){e.UNINITED="uninited",e.BINDING="binding",e.READY="ready",e.CLOSED="closed"}(bt||(bt={}));var It=k(function e(t){_(this,e),Object.defineProperty(this,"log",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pending",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"nodesInfo",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"pid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pidToNodeInfo",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"getNodeInfoKey",{enumerable:!0,configurable:!0,writable:!0,value:function(e){return"number"==typeof e?"number"+e:"low".concat(e.low,"high").concat(e.high,"unsigned").concat(e.unsigned)}}),this.log=t},[{key:"handleNodeMapUpdate",value:function(e){var t=this;return e.items.filter(function(e){return e.action===ht.NODE_JOIN&&t.addNode(e)||e.action===ht.NODE_LEAVE&&t.removeNode(e)})}},{key:"handleNodeMapSnapshot",value:function(e){var t=this,r=e.start,n=e.end,i=e.items;if(r&&this.pending.clear(),i.forEach(function(e){return t.pending.set(e.pid,e)}),n){this.log.info("Snapshot,size:".concat(this.pidToNodeInfo.size," to:").concat(this.pending.size));var o=[];return this.pidToNodeInfo.forEach(function(e,r){var n;o.push({pid:r,uid:e.uid,userName:e.userName,nodeId:(null===(n=t.pending.get(r))||void 0===n?void 0:n.nodeId)||e.nodeId,action:t.pending.has(r)?ht.NODE_JOIN:ht.NODE_LEAVE}),t.pending.delete(r)}),this.pending.forEach(function(e,t){o.push({pid:t,nodeId:e.nodeId,uid:e.uid,userName:e.userName,action:ht.NODE_JOIN})}),this.pending.clear(),this.handleNodeMapUpdate({items:o})}}},{key:"getNodeInfo",value:function(e){var t=this.getNodeInfoKey(e);return this.nodesInfo.get(t)}},{key:"addNode",value:function(e){var t=e.pid,r=e.nodeId,n=this.getNodeInfoKey(r);return this.nodesInfo.has(n)?(this.log.debug("updateNode,pid:".concat(t,", nodeId:").concat(r)),this.nodesInfo.set(n,e),this.pidToNodeInfo.set(n,e),!1):(this.log.debug("addNode,pid:".concat(t,", nodeId:").concat(r)),this.nodesInfo.set(n,e),this.pidToNodeInfo.set(t,e),t!==this.pid)}},{key:"removeNode",value:function(e){var t=e.pid,r=e.nodeId,n=this.getNodeInfoKey(r);return!!this.nodesInfo.has(n)&&(this.log.debug("removeNode, pid:".concat(t,", nodeId:").concat(r)),this.nodesInfo.delete(n),this.pidToNodeInfo.delete(t),t!==this.pid)}},{key:"getPid",value:function(e){var t,r=this.getNodeInfoKey(e);return null===(t=this.nodesInfo.get(r))||void 0===t?void 0:t.pid}},{key:"clear",value:function(){this.pending.clear(),this.nodesInfo.clear(),this.pidToNodeInfo.clear()}}]),Ct=k(function e(t,r,n,i){_(this,e),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"nodeId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"channel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"state",{enumerable:!0,configurable:!0,writable:!0,value:vt.IDLE}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"session",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.id=r.groupId,this.session=n,this.logger=i.getLoggerWithPrefix("[chn-dsgroup]"),this.nodeId=t,this.channel=r.channel},[{key:"join",value:function(){var e=this;return this.logger.info("join dsgroup ".concat(this.session.id,"#group:").concat(this.id," state:").concat(null==this?void 0:this.state)),new Promise(function(t,r){e.session.switcher.enquenTask.add(function(){if((null==e?void 0:e.state)!==vt.READY){var n={type:se.MessageType.TYPE_JOIN_GROUP,joinGroup:{groupId:e.id,nodeId:Ke.extractNodeId(e.nodeId)}};return e.session.switcher.send(n,{to:Ke.extractParentNodeId(e.nodeId,0),priority:Ge.Low,uniform:!1,endpointId:e.session.endpointId}).then(function(){e.state=vt.READY,t()}).catch(r)}r(new DingRTCError(ErrorCode.InvaildState,"group is already ready"))})})}},{key:"leave",value:function(){var e=this;return this.logger.info("leave dsgroup ".concat(this.session.id,"#group:").concat(this.id," state:").concat(null==this?void 0:this.state)),new Promise(function(t,r){(null==e?void 0:e.state)!==vt.READY&&r(new DingRTCError(ErrorCode.InvaildState,"group is not ready")),e.session.switcher.enquenTask.add(function(){var n={type:se.MessageType.TYPE_LEAVE_GROUP,leaveGroup:{groupId:e.id,nodeId:Ke.extractNodeId(e.nodeId)}};return e.session.switcher.send(n,{to:Ke.extractParentNodeId(e.nodeId,0),priority:Ge.Low,uniform:!1,endpointId:e.session.endpointId}).then(function(){e.state=vt.IDLE,t()}).catch(r)})})}}]);function Ot(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(Ot=function(){return!!e})()}var Pt=function(){function e(t,r,n,i){var o,a,s;return _(this,e),a=this,s=w(s=e),o=M(a,Ot()?Reflect.construct(s,[],w(a).constructor):s.apply(a,undefined)),Object.defineProperty(o,"type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(o,"syncing",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(o,"pendingMessages",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(o,"joinPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(o,"groups",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(o,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(o,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(o,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(o,"switcher",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(o,"state",{enumerable:!0,configurable:!0,writable:!0,value:mt.UNINITED}),Object.defineProperty(o,"endpointId",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(o,"nodeMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(o,"broadcastChannel",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(o,"userData",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),o.type=t,o.id=r,o.switcher=n,o.reporter=i,o.logger=i.getLoggerWithPrefix("[chn-dssession]"),o.nodeMap=new It(o.logger),o.join=o.join.bind(o),o.leave=o.leave.bind(o),o.close=o.close.bind(o),o}return j(e,EventEmitter),k(e,[{key:"available",get:function(){var e;return"connected"===(null===(e=this.switcher)||void 0===e||null===(e=e.channel)||void 0===e?void 0:e.connectionState)&&this.state===mt.READY}},{key:"recover",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.logger.info("".concat(this.type,"#").concat(this.id," recover rejoin:").concat(e,",state:").concat(this.state)),e?this.state==mt.READY&&(this.syncing=!0,this.join()):this.syncing=!0}},{key:"retransmit",value:function(){for(this.logger.info("retransmit ".concat(this.type,"#").concat(this.id," pengingMsgLen:").concat(this.pendingMessages.length));this.pendingMessages.length;){var e=this.pendingMessages.shift(),t=e.message,r=e.resolve,n=e.reject;this.sendInner(t).then(r).catch(n)}}},{key:"join",value:function(e){var t,r=this;return this.logger.info("dssession join ".concat(this.type,"#").concat(this.id," state=").concat(this.state)),null!==(t=this.switcher)&&void 0!==t&&null!==(t=t.channel)&&void 0!==t&&t.enableDS?new Promise(function(t,n){r.switcher.enquenTask.add(function(){if(r.state!==mt.READY||r.syncing){r.joinPromise={resolve:t,reject:n};var i={type:se.MessageType.TYPE_JOIN_SESSION,joinSession:{sessionType:r.type,sessionKey:r.id,customSessionData:e||r.userData,nodeId:r.switcher.nodeId,pid:r.switcher.pid}};return r.switcher.send(i).then(function(e){var t,n;r.logger.info("dssession join ",e);var i=e.customSessionData,o=e.endpointId,a=e.channels;r.endpointId=o,r.broadcastChannel=null===(t=a.find(function(e){return e.type===Je.DEFAULT}))||void 0===t?void 0:t.id,r.userData=i,r.state=mt.READY,null===(n=r.joinPromise)||void 0===n||n.resolve(e)}).catch(function(e){var t;r.logger.info("dssession join error",e),null===(t=r.joinPromise)||void 0===t||t.reject(e),r.joinPromise=null})}n(new DingRTCError(ErrorCode.InvaildState,"session is already ready"))})}):Promise.reject(new DingRTCError(ErrorCode.InvaildState,"dataSwitcher not enabled"))}},{key:"leave",value:function(){var e,t=this;return null!==(e=this.switcher)&&void 0!==e&&null!==(e=e.channel)&&void 0!==e&&e.enableDS?(this.logger.info("dssession leave ".concat(this.type,"#").concat(this.id," state:").concat(this.state)),new Promise(function(e,r){t.state!==mt.READY&&r(new DingRTCError(ErrorCode.InvaildState,"session is not ready")),t.switcher.enquenTask.add(function(){var n={type:se.MessageType.TYPE_LEAVE_SESSION,leaveSession:{sessionType:t.type,sessionKey:t.id,nodeId:t.switcher.nodeId}};return t.switcher.send(n).then(function(){t.state=mt.LEFT,e()}).catch(r)})})):Promise.reject(new DingRTCError(ErrorCode.InvaildState,"dataSwitcher not enabled"))}},{key:"close",value:function(){var e,t=this;return null!==(e=this.switcher)&&void 0!==e&&null!==(e=e.channel)&&void 0!==e&&e.enableDS?(this.logger.info("dssession close ".concat(this.type,"#").concat(this.id," state:").concat(this.state)),new Promise(function(e,r){t.switcher.enquenTask.add(function(){t.state===mt.CLOSED&&r(new DingRTCError(ErrorCode.InvaildState,"session is already closed"));var n={type:se.MessageType.TYPE_CLOSE_SESSION,closeSession:{sessionType:t.type,sessionKey:t.id,nodeId:t.switcher.nodeId}};return t.switcher.send(n).then(function(){t.state=mt.CLOSED,e()}).catch(r)})})):Promise.reject(new DingRTCError(ErrorCode.InvaildState,"dataSwitcher not enabled"))}},{key:"sendMessage",value:function(e){var t=this;return new Promise(function(r,n){if(t.state===mt.READY)return t.syncing||!t.available?(t.pendingMessages.length>1e3&&t.pendingMessages.shift().reject(new DingRTCError(ErrorCode.InvaildState,"pending size is full")),void t.pendingMessages.push({message:e,resolve:r,reject:n})):t.sendInner(e).then(r).catch(n);n(new DingRTCError(ErrorCode.InvaildState,"session is not ready"))})}},{key:"sendInner",value:function(e){var t,r,n,i,o=e.targetPid,a=e.echo,s=e.uniform,c=void 0!==s&&s,u=e.message,l=e.cmd,d=e.cmdType,p=e.requestId,f=e.groupId,h=l&&void 0!==d;t=o===fe?Ke.getTopNodeId(0):null===(r=this.nodeMap.pidToNodeInfo.get(o))||void 0===r?void 0:r.nodeId;var g,m="string"==typeof u?(new TextEncoder).encode(u):u;h?(n=Ke.composeId(this.switcher.serverNodeId,this.endpointId),i={type:se.MessageType.TYPE_SESSION_CMD_DATA,sessionCmdData:{cmd:l,echo:a,cmdType:d,toNodeId:t,requestId:p,data:m,broadcast:!o,fromPid:this.switcher.pid}}):(n=o?Ke.composeId(t,this.endpointId):this.broadcastChannel,f&&!o&&(n=null===(g=this.groups.get(f))||void 0===g||null===(g=g.channel)||void 0===g?void 0:g.id),i={type:se.MessageType.TYPE_SESSION_DATA,sessionData:{data:m}});return this.switcher.send(i,{to:n,echo:a,uniform:c,broadcast:!o,endpointId:this.endpointId,priority:h?Ge.Normal:Ge.Low})}},{key:"handleNodeMapSnapshot",value:function(e){var t,r=this,n=this.nodeMap.handleNodeMapSnapshot(e);e.end&&(n.length&&(n.forEach(function(e){var t=r.switcher.nodeMap.getNodeInfo(e.nodeId);t&&(e.uid=t.uid,e.userName=t.userName)}),this.logger.info("handleNodeMapSnapshot ".concat(this.type,"#").concat(this.id," updated=").concat(JSON.stringify(n))),this.emit("user-update",n)),this.retransmit(),null===(t=this.joinPromise)||void 0===t||t.resolve(),this.joinPromise=null,this.syncing&&(this.syncing=!1,this.logger.info("rejoin success ".concat(this.type,"#").concat(this.id))))}},{key:"handleNodeMapUpdate",value:function(e){var t=this,r=this.nodeMap.handleNodeMapUpdate(e);r.length&&(r.forEach(function(e){var r=t.switcher.nodeMap.getNodeInfo(e.nodeId);r&&(e.uid=r.uid,e.userName=r.userName)}),this.logger.info("handleNodeMapUpdate ".concat(this.type,"#").concat(this.id," nodeUpdated:").concat(JSON.stringify(r))),this.emit("user-update",r))}},{key:"handleSessionCreated",value:function(e,t,r){this.endpointId=e,this.broadcastChannel=t,this.userData=r}},{key:"handleSessionClosed",value:function(){this.state=mt.CLOSED,this.emit("leave","closed")}},{key:"handleSessionCmdData",value:function(e,t){var r=t.fromPid,n=t.cmd,i=t.cmdType,o=t.requestId,a=t.data,s=this.type!==yt.CUSTOMIZE?(new TextDecoder).decode(a):a,c=this.type!==yt.CUSTOMIZE?"STRING":"BINARY";this.emit("message",{cmd:n,cmdType:i,requestId:o,broadcast:e,messageType:c,pid:r,message:s})}},{key:"handleSessionData",value:function(e,t,r){var n,i,o=r.data,a=this.nodeMap.getPid(Ke.extractNodeId(e)),s=this.type!==yt.CUSTOMIZE?(new TextDecoder).decode(o):o,c=this.type!==yt.CUSTOMIZE?"STRING":"BINARY";t&&(n=null===(i=at(this.groups.values()).filter(function(e){var r;return(null==e||null===(r=e.channel)||void 0===r?void 0:r.id)===t})[0])||void 0===i?void 0:i.id);var u={pid:a,message:s,broadcast:!!t,messageType:c};n&&(u.groupId=n),this.emit("message",u)}},{key:"getGroup",value:function(e){var t=this.groups.get(e);return t||(t=new Ct(Ke.composeId(this.switcher.nodeId,this.endpointId),{groupId:e},this,this.reporter),this.groups.set(e,t)),t}},{key:"joinGroup",value:function(e){return this.getGroup(e).join()}},{key:"leaveGroup",value:function(e){return this.groups.has(e)?this.getGroup(e).leave():Promise.reject(new DingRTCError(ErrorCode.InvaildArgument,"group not found"))}},{key:"handleGroupCreated",value:function(e){var t=e.groupId;this.logger.info("groupcreated ".concat(this.type,"#").concat(this.id,"#").concat(t," msg:").concat(JSON.stringify(e)));var r=this.groups.get(t);r?r.channel=e.channel:(r=new Ct(Ke.composeId(this.switcher.nodeId,this.endpointId),e,this,this.reporter),this.groups.set(t,r),this.emit("group-add",r))}},{key:"handleGroupDestroyed",value:function(e){var t=e.groupId;this.logger.info("GroupDestroyed ".concat(this.type,"#").concat(this.id,"#").concat(t," msg:").concat(JSON.stringify(e)));var r=this.groups.get(t);r&&(this.groups.delete(t),this.emit("group-remove",r))}},{key:"handleServiceStatus",value:function(e){var t=e.status;this.logger.info("ServiceStatus ".concat(this.type,"#").concat(this.id," msg:").concat(JSON.stringify(e))),this.emit("service-status",t)}},{key:"handleChannelUpdate",value:function(e){var t=this;this.logger.info("ChannelUpdated ".concat(this.type,"#").concat(this.id," msg:").concat(JSON.stringify(e))),e.forEach(function(e){var r;e.groupId?t.getGroup(e.groupId).channel=e.channel:(null==e||null===(r=e.channel)||void 0===r?void 0:r.type)===Je.DEFAULT&&(t.broadcastChannel=e.channel.id)})}}])}();function Rt(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(Rt=function(){return!!e})()}updateProtobuf(Long);var _t=function(){function e(t){var r,n,i;return _(this,e),n=this,i=w(i=e),r=M(n,Rt()?Reflect.construct(i,[],w(n).constructor):i.apply(n,undefined)),Object.defineProperty(r,"endpointId",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(r,"nodeMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"broadcastChannel",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(r,"switcherTransport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"sessionEndPointMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(r,"log",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"pid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"nodeId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"channel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"state",{enumerable:!0,configurable:!0,writable:!0,value:bt.UNINITED}),Object.defineProperty(r,"serverNodeId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"enquenTask",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"sessionMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),r.enquenTask=taskQueue$1(),r.channel=t,r.log=t.reporter.getLoggerWithPrefix("[chn-ds]"),r.reporter=t.reporter,r.nodeMap=new It(r.log),r.handleDetachUserConfirm=r.handleDetachUserConfirm.bind(r),r.handleNodeMapSnapshot=r.handleNodeMapSnapshot.bind(r),r.handleNodeMapUpdate=r.handleNodeMapUpdate.bind(r),r.handleSessionClosed=r.handleSessionClosed.bind(r),r.handleSessionCreated=r.handleSessionCreated.bind(r),r.handleSessionData=r.handleSessionData.bind(r),r.handleSessionCmdData=r.handleSessionCmdData.bind(r),r.handleGroupCreated=r.handleGroupCreated.bind(r),r.handleGroupDestroyed=r.handleGroupDestroyed.bind(r),r.handleServiceStatus=r.handleServiceStatus.bind(r),r.handleSwitchUpdate=r.handleSwitchUpdate.bind(r),r}return j(e,EventEmitter),k(e,[{key:"init",value:function(e){var t=this,r=this.state;if(this.log.debug("init switcher channelBind start:".concat(r),e),r!==bt.BINDING)return this.switcherTransport=this.channel.socket.switchTransport,this.pid=e,this.state=bt.BINDING,this.switcherTransport.channelBind(e).then(function(r){t.nodeMap.pid=e,t.addEventListeners(),t.handleAttachUserConfirm(r),t.enquenTask.start()}).catch(function(){var r=C(pe.mark(function r(n){return pe.wrap(function(r){for(;;)switch(r.prev=r.next){case 0:return t.log.warn("pid:".concat(e," switcher channelBind failed:").concat(tryJsonStringify(n))),r.next=1,awaitTime$1(1);case 1:"connected"===t.channel.connectionState&&t.state!==bt.CLOSED&&(t.state=bt.UNINITED,t.init(e));case 2:case"end":return r.stop()}},r)}));return function(e){return r.apply(this,arguments)}}())}},{key:"addEventListeners",value:function(){this.switcherTransport.on("detachUserConfirm",this.handleDetachUserConfirm),this.switcherTransport.on("nodeMapSnapshot",this.handleNodeMapSnapshot),this.switcherTransport.on("nodeMapUpdated",this.handleNodeMapUpdate),this.switcherTransport.on("sessionClosed",this.handleSessionClosed),this.switcherTransport.on("sessionCreated",this.handleSessionCreated),this.switcherTransport.on("sessionData",this.handleSessionData),this.switcherTransport.on("sessionCmdData",this.handleSessionCmdData),this.switcherTransport.on("groupCreated",this.handleGroupCreated),this.switcherTransport.on("groupDestroyed",this.handleGroupDestroyed),this.switcherTransport.on("serviceStatus",this.handleServiceStatus),this.switcherTransport.on("switchUpdate",this.handleSwitchUpdate)}},{key:"removeEventListeners",value:function(){this.switcherTransport&&(this.switcherTransport.off("detachUserConfirm",this.handleDetachUserConfirm),this.switcherTransport.off("nodeMapSnapshot",this.handleNodeMapSnapshot),this.switcherTransport.off("nodeMapUpdated",this.handleNodeMapUpdate),this.switcherTransport.off("sessionClosed",this.handleSessionClosed),this.switcherTransport.off("sessionCreated",this.handleSessionCreated),this.switcherTransport.off("sessionData",this.handleSessionData),this.switcherTransport.off("sessionCmdData",this.handleSessionCmdData),this.switcherTransport.off("groupCreated",this.handleGroupCreated),this.switcherTransport.off("groupDestroyed",this.handleGroupDestroyed),this.switcherTransport.off("serviceStatus",this.handleServiceStatus),this.switcherTransport.off("switchUpdate",this.handleSwitchUpdate))}},{key:"clear",value:function(){this.switcherTransport.attachUserConfirm=null,this.sessionMap.clear(),this.nodeMap.clear(),this.enquenTask=taskQueue$1(),this.sessionEndPointMap.clear(),this.state=bt.UNINITED,this.removeEventListeners()}},{key:"getSession",value:function(e,t){var r;if(t.length>128)throw new DingRTCError(ErrorCode.InvaildArgument,"invalid id");var n=null===(r=this.sessionMap.get(e))||void 0===r?void 0:r.get(t);return n||(this.log.info("new local DSSession:".concat(e,"#").concat(t)),n=new Pt(e,t,this,this.reporter),this.sessionMap.get(e)?this.sessionMap.get(e).set(t,n):this.sessionMap.set(e,new Map([[t,n]]))),n}},{key:"fetchSession",value:function(e,t){var r=this.sessionEndPointMap.get(e);if(r)return r;this.log.warn("".concat(t," fetchSession:").concat(e," not existed"))}},{key:"send",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.state===bt.CLOSED)return Promise.reject(new DingRTCError(ErrorCode.InvaildState,"switcher is closed"));var r=t.echo,n=void 0!==r&&r,i=t.priority,o=void 0===i?Ge.High:i,a=t.endpointId,s=t.broadcast,c=void 0!==s&&s,u=t.uniform,l=void 0===u||u,d=t.to,p=o===Ge.High,f=Ke.composeId(this.nodeId,p?this.endpointId:a);p&&(d=c?this.broadcastChannel:Ke.composeId(this.serverNodeId,this.endpointId));var h={to:d,from:f,compressed:!1,priority:o,uniform:p||l,echo:n};return this.switcherTransport.send(e,h)}},{key:"handleNodeMapUpdate",value:function(e,t){var r;e===this.endpointId?this.nodeMap.handleNodeMapUpdate(t):null===(r=this.fetchSession(e,"NodeMapUpdate"))||void 0===r||r.handleNodeMapUpdate(t)}},{key:"handleAttachUserConfirm",value:function(e){var t,r=this,n=e.nodeId,i=e.serverNodeId,o=e.endpointId,a=e.channels,s=e.sessionCreateds,c=e.reason;this.broadcastChannel=null===(t=a.find(function(e){return e.type===Je.DEFAULT}))||void 0===t?void 0:t.id,this.nodeId=n,this.endpointId=o,this.serverNodeId=i;var u=[qe.NORMAL_ATTACH,qe.FORCE_REATTACH].includes(c);this.sessionMap.forEach(function(e,t){e.forEach(function(e,n){s.some(function(e){return e.sessionType===t&&e.sessionKey===n})?e.recover(u):r.handleSessionClosed({sessionKey:n,sessionType:t})})}),s.forEach(function(e){r.handleSessionCreated(e)}),this.state=bt.READY}},{key:"handleNodeMapSnapshot",value:function(e,t){var r;this.endpointId==e?this.nodeMap.handleNodeMapSnapshot(t):null===(r=this.fetchSession(e,"NodeMapSnapshot"))||void 0===r||r.handleNodeMapSnapshot(t)}},{key:"handleSessionCreated",value:function(e){var t,r,n=e.sessionKey,i=e.sessionType,o=e.endpointId,a=e.customSessionData,s=null===(t=e.channels.find(function(e){return e.type===Je.DEFAULT}))||void 0===t?void 0:t.id,c=null===(r=this.sessionMap.get(i))||void 0===r?void 0:r.get(n),u=!c,l=u||c&&!c.available;this.log.info("onSessionCreated: ".concat(i,"#").concat(n," is ").concat(u?"new":"existed")),u&&(this.log.info("Created ".concat(i,"#").concat(n)),c=new Pt(i,n,this,this.reporter),this.sessionMap.get(i)?this.sessionMap.get(i).set(n,c):this.sessionMap.set(i,new Map([[n,c]]))),this.sessionEndPointMap.set(o,c),c.handleSessionCreated(o,s,a),l&&this.emit("sessionCreate",{type:i,id:n})}},{key:"handleSessionClosed",value:function(e){var t,r=e.sessionKey,n=e.sessionType,i=null===(t=this.sessionMap.get(n))||void 0===t?void 0:t.get(r);this.log.info("handleSessionClosed: ".concat(n,"#").concat(r," is ").concat(i?"closed":"not existed")),i&&i.state!==mt.UNINITED&&(i.handleSessionClosed(),this.log.info("Closed ".concat(n,"#").concat(r," is closed")),this.sessionMap.get(n).delete(r),this.sessionEndPointMap.delete(i.endpointId),this.emit("sessionClose",{type:n,id:r}))}},{key:"handleDetachUserConfirm",value:function(e){var t=e.pid,r=e.result;this.log.warn("DetachUser pid:".concat(this.pid," result:").concat(r," state:").concat(this.state)),t==this.pid&&0===r&&this.state!==bt.CLOSED&&(this.state=bt.CLOSED)}},{key:"handleSessionCmdData",value:function(e,t,r){var n;null===(n=this.fetchSession(e,"CmdData"))||void 0===n||n.handleSessionCmdData(t,r)}},{key:"handleSessionData",value:function(e,t,r,n){var i;null===(i=this.fetchSession(t,"SessionData"))||void 0===i||i.handleSessionData(e,r,n)}},{key:"handleGroupCreated",value:function(e,t){var r;null===(r=this.fetchSession(e,"GroupCreated"))||void 0===r||r.handleGroupCreated(t)}},{key:"handleGroupDestroyed",value:function(e,t){var r;null===(r=this.fetchSession(e,"GroupDestroyed"))||void 0===r||r.handleGroupDestroyed(t)}},{key:"handleServiceStatus",value:function(e,t){var r;null===(r=this.fetchSession(e,"ServiceStatus"))||void 0===r||r.handleServiceStatus(t)}},{key:"handleSwitchUpdate",value:function(e){var t=this,r=e.channelUpdates,n={};(void 0===r?[]:r).forEach(function(e){var r;e.endpointId===t.endpointId?(null===(r=e.channel)||void 0===r?void 0:r.type)===Je.DEFAULT&&(t.log.info("SwitchUpdate broadcastChannel:".concat(e.channel.id)),t.broadcastChannel=e.channel.id):n[e.endpointId]=(n[e.endpointId]||[]).concat(e)}),Object.entries(n).forEach(function(e){var r,n=Et(e,2),i=n[0],o=n[1];null===(r=t.fetchSession(+i,"ChannelUpdate"))||void 0===r||r.handleChannelUpdate(o)})}}])}();function Nt(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function kt(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Nt(Object(r),!0).forEach(function(t){R(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Nt(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function Mt(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(Mt=function(){return!!e})()}var wt=function(){function e(t){var r,n,i;_(this,e),n=this,i=w(i=e),r=M(n,Mt()?Reflect.construct(i,[],w(n).constructor):i.apply(n,undefined)),Object.defineProperty(r,"dataSwitcher",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"signaling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"joinInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"sdkVersion",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"scene",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"socket",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"enableDS",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(r,"id",{enumerable:!0,configurable:!0,writable:!0,value:createUuid(6)}),Object.defineProperty(r,"userManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"connectionState",{enumerable:!0,configurable:!0,writable:!0,value:"disconnected"}),Object.defineProperty(r,"securityToken",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"staticConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"checkJoinParam",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",r=!t;return r||("userName"===e?r=(new TextEncoder).encode(t).length>64:"token"!==e&&(r=t.length>64||/[^a-zA-Z0-9_-]/g.test(t))),r?"Join with invalid ".concat(e):""}});var o=t.reporter,a=t.sdkVersion,s=t.scene;return r.sdkVersion=a,r.scene=s,r.reporter=o,r.logger=r.reporter.getLoggerWithPrefix("[ch-channel]"),r.userManager=new Tt(r),r.dataSwitcher=new _t(r),r.handleRejoin=r.handleRejoin.bind(r),r.handleConferenceEvent=r.handleConferenceEvent.bind(r),r.handleDropEvent=r.handleDropEvent.bind(r),r.handleConnectionChangeEvent=r.handleConnectionChangeEvent.bind(r),r.handleUserEvent=r.handleUserEvent.bind(r),r.handleSyncEvent=r.handleSyncEvent.bind(r),r.handleNotifyEvent=r.handleNotifyEvent.bind(r),r.handleReauthEvent=r.handleReauthEvent.bind(r),r.handleBatchNotifyEvent=r.handleBatchNotifyEvent.bind(r),r}return j(e,EventEmitter),k(e,[{key:"gslb",get:function(){return getGslb()}},{key:"addEventListeners",value:function(){this.signaling.on("rejoin",this.handleRejoin),this.signaling.on("conference",this.handleConferenceEvent),this.signaling.on("drop",this.handleDropEvent),this.signaling.on("sync",this.handleSyncEvent),this.signaling.on("connection-state-change",this.handleConnectionChangeEvent),this.userManager.on("user",this.handleUserEvent),this.signaling.on("batch-notify",this.handleBatchNotifyEvent),this.signaling.on("notify",this.handleNotifyEvent),this.signaling.on("reauth",this.handleReauthEvent)}},{key:"removeEventListeners",value:function(){this.signaling.off("rejoin",this.handleRejoin),this.signaling.off("conference",this.handleConferenceEvent),this.signaling.off("drop",this.handleDropEvent),this.signaling.off("sync",this.handleSyncEvent),this.signaling.off("connection-state-change",this.handleConnectionChangeEvent),this.userManager.off("user",this.handleUserEvent),this.signaling.off("batch-notify",this.handleBatchNotifyEvent),this.signaling.off("notify",this.handleNotifyEvent),this.signaling.off("reauth",this.handleReauthEvent)}},{key:"handleLeave",value:function(e){this.reporter.trace.wtLeave(e),this.userManager.clear(),this.dataSwitcher.clear(),this.joinInfo=null,this.removeEventListeners();var t=this.connectionState;this.connectionState="disconnected",this.signaling.diconnect(),this.reporter.stop(),this.emit("connection-state-change","disconnected",t,e)}},{key:"modifyToken",value:function(e,t){var r=JSON.parse(window.atob(t));return r.properties=kt(kt({},r.properties),{},{__nick:e,SdkType:Environment.sdkType,TerminalType:Environment.terminalType}),toBase64(JSON.stringify(r))}},{key:"beforeJoin",value:function(e,t){var r=this;this.reporter.trace.wtGslb("accessGslbStart");var n=e.channel,i=e.uid,o=e.token,a=e.userName;this.handleConnectionChangeEvent("connecting",this.connectionState);var s={timestamp:Date.now(),deviceId:deviceId,userId:i,sdkVersion:this.sdkVersion,channelId:n,accessToken:o};return t&&(s=kt(kt({},s),{},{attributes:kt({},t)})),function(e){var t=e.userId,r=e.accessToken,n=e.sdkVersion,i=getGslb()||le,o="/v1/users/".concat(t,"/access");delete e.userId,delete e.accessToken,delete e.sdkVersion;var a=tt(tt({},e),{},{deviceSpecs:{platform:"Web",sdkv:n,osv:Environment.systemVersion,manu:Environment.manu,model:Environment.model}});return Environment.cpu&&(a.deviceSpecs.cpuUarch=Environment.cpu),new Promise(function(e,t){var n=setTimeout(function(){t(new DingRTCError(ErrorCode.NetworkError,"accessGslb timeout"))},6e3);post$1("".concat(i).concat(o),JSON.stringify(a),{Authorization:r}).then(function(t){e(t),clearTimeout(n)}).catch(function(e){t(e),clearTimeout(n)})}).catch(function(e){return nt.info("".concat(i," access error:").concat(tryJsonStringify(e))),Promise.reject(e)})}(s).then(function(e){var t,n=e.logService,i=e.securityToken,o=e.access,s=o.staticConfig,c=o.iceConfig,u=o.rtcToken,l=o.rtmpConfig,d=s.statsConfig,p=void 0===d?{uploadIntervalMs:UPLOAD_LOG_INTERVAL,statsIntervalMs:METRIC_STATS_INTERVAL$1}:d;r.staticConfig=s,r.reporter.trace.wtGslb("accessGslbSuccess",tryJsonStringify(e));var f=Date.now();return r.reporter.updateCommonInfo({serverDiffTime:(1e3*(null!==(t=null==i?void 0:i.updateTime)&&void 0!==t?t:0)||f)-f}),r.reporter.trace.wtGslb("accessGslbSuccess",tryJsonStringify(e)),n?r.reporter.start({securityToken:i,logService:n,cycleStatsConfig:p}):r.logger.warn("logService is empty"),{rtcToken:r.modifyToken(a,u),iceConfig:c,securityToken:i,rtmpConfig:l}}).catch(function(e){var t=e.code,n=e.cause;return r.logger.info("accessGslbFailed",e),r.reporter.trace.wtGslb("accessGslbFailed",tryJsonStringify(e)),r.connectionState="disconnected",Promise.reject(converToRtcErrorFromGslbCode(t,n))})}},{key:"beforeRejoin",value:function(e,t){var r=this;this.reporter.trace.wtGslb("linkerServerStart");var n=e.channel,i=e.uid,o=e.appId,a=e.userName;return function(e){var t=e.userId;delete e.userId;var r="/v1/users/".concat(t,"/link-server"),n=getGslb()||le;return post$1("".concat(n).concat(r),JSON.stringify(e)).catch(function(e){return nt.info("".concat(n," link-server error:").concat(tryJsonStringify(e))),Promise.reject(e)})}({timestamp:Date.now(),deviceId:deviceId,userId:i,channelId:n,appId:o,securityToken:this.reporter.securityToken,participantId:t}).then(function(e){var t=e.securityToken,n=e.access.rtcToken;return r.reporter.updateSecurityToken(t),r.reporter.trace.wtGslb("linkerServerSuccess",tryJsonStringify(e)),r.modifyToken(a,n)}).catch(function(e){var t=e.code,n=e.cause;throw r.reporter.trace.wtGslb("linkerServerFailed",tryJsonStringify(e)),converToRtcErrorFromGslbCode(t,n)})}},{key:"join",value:(r=C(pe.mark(function e(t,r,n){var i,o,a,s,c,u,l,d,p,f,h,g,m,v,y,b=this;return pe.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:this.logger.info("channel join, joinInfo, gslb",t,r),o=(i=t||{}).channel,a=i.uid,s=i.userName,c=i.appId,u=i.token,l=[this.checkJoinParam("appId",c),this.checkJoinParam("token",u),this.checkJoinParam("channel",o),this.checkJoinParam("uid",a),this.checkJoinParam("userName",s)],d=0;case 1:if(!(d<l.length)){e.next=3;break}if(!l[d]){e.next=2;break}return e.abrupt("return",Promise.reject(new DingRTCError(ErrorCode.JoinChannelFailed,l[d])));case 2:d++,e.next=1;break;case 3:if(r&&setGslb(r),"disconnected"===this.connectionState){e.next=4;break}return e.abrupt("return",Promise.reject(new DingRTCError(ErrorCode.InvaildState,"channel is not disconnected")));case 4:return this.reporter.updateCommonInfo({apid:c,usrid:a,usrn:s,clientId:this.id,roomName:o,udid:Environment.deviceId,sdkvrs:this.sdkVersion}),this.reporter.trace.wtJoin(!0),p=Date.now(),e.next=5,this.beforeJoin(t,n);case 5:return f=e.sent,h=f.rtcToken,g=f.iceConfig,m=f.securityToken,v=f.rtmpConfig,this.securityToken=m,y=Date.now(),this.reporter.trace.join(!0),this.socket&&this.socket.removeAllListeners(),this.socket=new Xe(this.reporter),this.joinInfo=t,this.signaling=new rt(this.socket,this.reporter),this.addEventListeners(),e.abrupt("return",this.signaling.login(kt({token:h},he(this.sdkVersion,this.scene,t.initMicMuted?1:0))).then(function(e){var t=e.room,r=t.participants,n=t.participantsVer,i=e.id;return b.dataSwitcher.init(i),b.userManager.init(r,n,i),b.reporter.trace.join(!1,Date.now()-y,!0),b.reporter.trace.wtJoin(!1,Date.now()-p,!0),{joinResponse:e,iceConfig:g,securityToken:m,rtmpConfig:v}}).catch(function(e){throw b.reporter.trace.wtJoin(!0,Date.now()-p,!1,tryJsonStringify(e)),e}));case 6:case"end":return e.stop()}},e,this)})),function(e,t,n){return r.apply(this,arguments)})},{key:"handleConferenceEvent",value:function(e){this.logger.info("roomEvent ".concat(JSON.stringify(e))),"destroy"===(null==e?void 0:e.action)&&this.handleLeave("channel_banned")}},{key:"handleConnectionChangeEvent",value:function(e,t,r){e!==this.connectionState&&("disconnected"===e?this.handleLeave(r):(this.connectionState=e,this.emit("connection-state-change",e,t)))}},{key:"handleDropEvent",value:function(e){this.logger.info("dropEvent ".concat((null==e?void 0:e.reason)||(null==e?void 0:e.code)));var t=(null==e?void 0:e.code)===Ue.UserReplaced?"uid_replaced":"uid_banned";this.handleLeave(t)}},{key:"handleRejoin",value:function(){var e=this,t=Date.now();this.reporter.trace.wtReJoin(!0),this.beforeRejoin(this.joinInfo,this.userManager.currentPid).then(function(r){var n=Date.now();return e.reporter.trace.rejoin(!0),e.rejoin(r).then(function(){e.dataSwitcher.init(e.userManager.currentPid),e.reporter.trace.rejoin(!1,Date.now()-n),e.reporter.trace.wtReJoin(!1,Date.now()-t,!0)},function(t){throw e.reporter.trace.rejoin(!1,Date.now()-n,!1,tryJsonStringify(t)),t})}).catch(function(r){e.reporter.trace.wtReJoin(!1,Date.now()-t,!1,tryJsonStringify(r)),e.handleLeave("server_error")})}},{key:"handleUserEvent",value:function(e,t){this.emit("user",e,t)}},{key:"handleNotifyEvent",value:function(e,t){this.emit("notify",e,t)}},{key:"handleBatchNotifyEvent",value:function(e){this.emit("batch-notify",e)}},{key:"handleSyncEvent",value:function(e){this.emit("sync",e)}},{key:"handleReauthEvent",value:function(){this.dataSwitcher.init(this.userManager.currentPid)}},{key:"rejoin",value:(t=C(pe.mark(function e(t){var r=this;return pe.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",this.signaling.relogin({token:t}).then(function(e){r.signaling.emit("sync",e)}));case 1:case"end":return e.stop()}},e,this)})),function(e){return t.apply(this,arguments)})},{key:"leave",value:function(){this.signaling.logout(),this.handleLeave("leave")}}]);var t,r}();function _createForOfIteratorHelper$1(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray$1(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray$1(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$1(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_arrayLikeToArray$1(e,t):void 0}}function _arrayLikeToArray$1(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function ownKeys$1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function _objectSpread$1(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$1(Object(r),!0).forEach(function(t){_defineProperty(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$1(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function _callSuper$3(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$3()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$3(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$3=function(){return!!e})()}var ServiceManager=function(e){function t(e,r){var n;return _classCallCheck$1(this,t),n=_callSuper$3(this,t),Object.defineProperty(n,"rtcSignaling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"sessionManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"groupManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"rtcUserManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"streamManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"remoteAudioTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"internalChannel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"roomId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"defaultVideoStreamType",{enumerable:!0,configurable:!0,writable:!0,value:"high"}),Object.defineProperty(n,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"subscribedAudioStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"micMixedGroups",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"iceConfig",{enumerable:!0,configurable:!0,writable:!0,value:{level:0,iceServerList:[]}}),Object.defineProperty(n,"processingSubParamsMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(n,"joinInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"getSubTraceId",{enumerable:!0,configurable:!0,writable:!0,value:function(){return++t.subAcc}}),Object.defineProperty(n,"handleSubscribeParam",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t,r=e.mediaType,i=e.uid,o=e.auxiliary,a=n.getStream(e),s=n.rtcUserManager.users.get(i),c=n.groups.some(function(e){return e.joined}),u="mcu"===i?n.remoteAudioTrack:o?null==s?void 0:s.auxiliaryTrack:null==s?void 0:s.videoTrack,l=[],d=_toConsumableArray(n.processingSubParamsMap.values());n.logger.info("queueingSubParams",d,e),d.forEach(function(e){return l.push.apply(l,_toConsumableArray(e))});var p=l.find(function(e){return e.uid===i&&e.mediaType===r&&!!e.auxiliary==!!o});return"mcu"===i&&"video"===r||i&&"mcu"!==i&&"audio"===r?t=new DingRTCError(ErrorCode.InvaildArgument,"only support subscribe mcu audio"):"mcu"===i&&c?t=new DingRTCError(ErrorCode.SubscribeInvaild,"cannot subscribe mcu while in group"):u||p?t=new DingRTCError(ErrorCode.SubscribeInvaild,"duplicated subscription"):a||(n.logger.warn("".concat(i," videoTrack not existed")),t=new DingRTCError(ErrorCode.SubscribeStreamNotExisted)),{uid:i,user:s,error:t,stream:a,targetMediaType:r,resolutionInfo:"video"!==r||t?null:calcResolutionInfo(n.defaultVideoStreamType,getStreamSupportedResoArr(a))}}}),Object.defineProperty(n,"checkUnsubParam",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t,r=e.mediaType,i=e.uid,o=e.auxiliary,a=n.getStream(e),s=n.rtcUserManager.users.get(i),c="mcu"===i?n.remoteAudioTrack:o?null==s?void 0:s.auxiliaryTrack:null==s?void 0:s.videoTrack;"mcu"===i&&"video"===r||i&&"mcu"!==i&&"audio"===r?(n.logger.warn("only support unsubscribe mcu audio"),t=new DingRTCError(ErrorCode.InvaildArgument,"only support unsubscribe mcu audio")):a&&c||(n.logger.warn("".concat(i," videoTrack not existing")),t=new DingRTCError(ErrorCode.SubscribeStreamNotExisted));var u=n.sessionManager.getSessionByStreamId(null==a?void 0:a.id);return u||(n.logger.warn("no sub session"),t=new DingRTCError(ErrorCode.SubscribeStreamNotExisted)),{uid:i,user:s,error:t,stream:a,session:u,subMediaType:r,resolutionInfo:"video"!==r||t?null:calcResolutionInfo(n.defaultVideoStreamType,getStreamSupportedResoArr(a))}}}),Object.defineProperty(n,"handleJoinResponse",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t=e.room,r=e.id,i=t.participants,o=t.streams,a=t.streamsVer,s=t.groupList,c=t.groupListVer;n.streamManager.init(o,a),n.groupManager.init(s,c),n.rtcUserManager.init(i,r),n.streamManager.on("stream",n.handleStreamEvent),n.rtcUserManager.on("user",n.handleUserEvent),n.groupManager.on("group",n.handleGroupEvent)}}),n.reporter=r,n.logger=n.reporter.getLoggerWithPrefix("[rtc-svcMgr]"),n.internalChannel=new wt({reporter:r,sdkVersion:SDK_VERSION}),n.rtcSignaling=new RtcSignaling(n.internalChannel),n.client=e,n.micMixedGroups=new Set,n.groupManager=new GroupManager(n),n.streamManager=new StreamManager(n),n.rtcUserManager=new RtcUserManager(n,n.streamManager),n.sessionManager=new SessionManager(e,n),n.subscribedAudioStream="",n.handleStreamEvent=n.handleStreamEvent.bind(n),n.handleUserEvent=n.handleUserEvent.bind(n),n.handleGroupEvent=n.handleGroupEvent.bind(n),n}return _inherits$1(t,e),_createClass$1(t,[{key:"publishedLocalTracks",get:function(){var e=_toConsumableArray(this.sessionManager.sessions.values()).filter(function(e){return e.state===PubSubStates.Processing&&e instanceof Publication}),t=new Set;return e.map(function(e){if(e.tracks){var r,n;if((null===(r=e.tracks)||void 0===r?void 0:r[0])instanceof MixedLocalAudioTrack){var i=e.tracks[0].getMicAudioTrack();i&&t.add(i);var o=e.tracks[0].getScreenAudioTrack();return void(o&&t.add(o))}(null===(n=e.tracks)||void 0===n?void 0:n[0])&&t.add(e.tracks[0])}}),_toConsumableArray(t.values())}},{key:"groups",get:function(){var e=this;return this.groupManager.groupList.map(function(t){return _objectSpread$1(_objectSpread$1({},t),{},{audioPublished:e.micMixedGroups.has(t.id)})})}},{key:"handleStreamEvent",value:function(e,t){var r=t.id,n=t.owner,i=t.mediaType,o=t.auxiliary,a=t.owners,s=t.updateStatus,c=t.properties,u=t.highestResolutionLevel,l=this.internalChannel.userManager.participants,d=l.get(n),p=this.rtcUserManager.users.get(null==d?void 0:d.user),f=n===this.rtcUserManager.currentSelfPid;if("add"===e&&!f&&p)this.client.emit("user-published",p,i,o);else if("remove"===e&&p&&!f)this.sessionManager.removeSession(void 0,r),"video"===i&&(o&&p.auxiliaryTrack&&(p.auxiliaryTrack.stopPlay(),p.auxiliaryTrack=null),!o&&p.videoTrack&&(p.videoTrack.stopPlay(),p.videoTrack=null)),this.client.emit("user-unpublished",p,i,o);else if("update"===e){if(s)this.client.emit("user-info-updated",(null==p?void 0:p.userId)||this.rtcUserManager.currentUid,s,o);else if(null!=(null==c?void 0:c.mirror)){var h=o?p.auxiliaryTrack:p.videoTrack;null==h||h.setSourceMirror(c.mirror)}else if(null!=u){var g=this.sessionManager.getSessionByStreamId(r);if(!g)return;g.stream.media.video.highestResolutionLevel=u;var m=g.userConfigResolution,v=g.resolutionInfo;if(u>=m.resolutionLevel&&m.resolutionLevel>v.resolutionLevel)g.applyOptions(m,!0);else if(u<m.resolutionLevel){var y=calcResolutionInfo(getResoLevelNameByResoLevelNum(u),getStreamSupportedResoArr(g.stream));g.applyOptions(y,!0)}}}else if("volumeActive"===e){var b=a.map(function(e){return l.get(e)}).map(function(e){return null==e?void 0:e.user}).filter(function(e){return!!e});this.client.emit("volume-indicator",b)}}},{key:"handleGroupEvent",value:function(e,t,r){var n=this;if("add"===e)this.client.emit("group-add",t);else if("remove"===e){var i;if(this.micMixedGroups.delete(t.id),this.logger.info("unsub group for group removed",t),r&&(null===(i=r.audio)||void 0===i?void 0:i.id)===this.subscribedAudioStream){var o=r.audio;this.sessionManager.batchUnscribe([{stream:o,session:this.sessionManager.getSessionByStreamId(o.id),targetMediaType:"audio"}]).then(function(){o.id===n.subscribedAudioStream&&(n.updateSubscribedAudioStream(!1,""),n.remoteAudioTrack.stopPlay(),n.remoteAudioTrack=null)})}this.client.emit("group-remove",t)}else if("user-join"===e)this.client.emit("group-user-join",t,r);else if("user-leave"===e)this.client.emit("group-user-leave",t,r);else if("info-updated"===e){var a=r.key,s=r.value;this.client.emit("group-info-updated",t,a,s)}}},{key:"handleUserEvent",value:function(e,t){"join"===e?(this.client.emit("user-joined",t),t.hasVideo&&this.client.emit("user-published",t,"video"),t.hasAudio&&this.client.emit("user-published",t,"audio"),t.hasAuxiliary&&this.client.emit("user-published",t,"video",!0)):"leave"===e?this.client.emit("user-left",t):this.logger.warn("unhandled inner rtc user emitted event",e,t)}},{key:"getStream",value:function(e){var t,r=e.groupId,n=e.uid,i=e.auxiliary;if(r){var o,a=this.groupManager.groups.get(r);return null==a||null===(o=a.audioInfo)||void 0===o?void 0:o.audio}var s="mcu"===n?_toConsumableArray(this.streamManager.streams.values()):null===(t=this.rtcUserManager.users.get(n))||void 0===t?void 0:t.relatedStreams;return"mcu"===n?s.find(function(e){var t=e.info.owner,r=e.type;return"admin"===t&&"mixed"===r}):s.find(function(e){var t=e.media.video;return(null==t?void 0:t.source)===(i?VideoSourceInfo.SCREENCAST:VideoSourceInfo.CAMERA)})}},{key:"join",value:(c=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n,i,o,a,s;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return this.logger.info("join",clientConfig.gslb[0]),this.sessionManager.mixedLocalAudioTrack.setSelfMicMutedProperty(t.initMicMuted),e.next=1,this.rtcSignaling.join(t,clientConfig.gslb[0]);case 1:return n=e.sent,i=n.joinResponse,o=n.iceConfig,null!=(null==(a=this.internalChannel.staticConfig)||null===(r=a.websdkConfig)||void 0===r?void 0:r.simulcast)&&(clientConfig.simulcast=null==a||null===(s=a.websdkConfig)||void 0===s?void 0:s.simulcast),this.roomId=i.room.id,parseSubSsrcInfo(i.room.ssrcMask,i.room.ssrcClientSequence),this.reporter.updateCommonInfo({roomId:this.roomId,participantId:i.id}),o&&o.uis&&this.setIceConfig(o.uis),this.sessionManager.start(),this.handleJoinResponse(i),e.abrupt("return",i);case 2:case"end":return e.stop()}},e,this)})),function(e){return c.apply(this,arguments)})},{key:"setIceConfig",value:function(e){var t=e.iceServerList,r=void 0===t?[]:t;e.level&&(e.iceServerList=r.filter(function(e){return/([0-9]{1,3}\.){3}[0-9]{1,3}/i.test(e)}),this.iceConfig=e)}},{key:"clear",value:function(){var e;this.rtcUserManager.clear(),this.streamManager.clear(),this.sessionManager.clear(),this.micMixedGroups.clear(),this.groupManager.clear(),this.subscribedAudioStream="",null===(e=this.remoteAudioTrack)||void 0===e||e.stopPlay(),this.remoteAudioTrack=null,this.iceConfig=null,this.roomId="",this.streamManager.off("stream",this.handleStreamEvent),this.rtcUserManager.off("user",this.handleUserEvent),this.groupManager.off("group",this.handleGroupEvent)}},{key:"leave",value:function(){if("disconnected"!==this.internalChannel.connectionState)return this.reporter.trace.leave(),this.rtcSignaling.leave()}},{key:"publish",value:(s=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n,i,o;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return r=this.micMixedGroups,n=this.groupManager,i=this.groups,o=[],i.some(function(e){return e.joined})?o.push.apply(o,_toConsumableArray(_toConsumableArray(r).map(function(e){var t;return null===(t=n.groups.get(e))||void 0===t||null===(t=t.audioInfo)||void 0===t?void 0:t.label}).filter(function(e){return!!e}))):o.push("common"),e.abrupt("return",this.sessionManager.batchPublish(t,o));case 1:case"end":return e.stop()}},e,this)})),function(e){return s.apply(this,arguments)})},{key:"unpublish",value:(a=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n,i,o,a,s,c,u=this;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.sessionManager.republishPromise){e.next=5;break}return this.logger.info("wait for repub before unpublish"),e.prev=1,e.next=2,this.sessionManager.republishPromise;case 2:e.next=4;break;case 3:e.prev=3,e.catch(1);case 4:this.logger.info("go unpublish after repub");case 5:return r=t.filter(function(e){return"audio"===e.trackMediaType}),n=t.filter(function(e){return"audio"!==e.trackMediaType}),i=!1,r.length>0&&(o=(this.sessionManager.mixedLocalAudioTrack.getMicAudioTrack()?1:0)+(this.sessionManager.mixedLocalAudioTrack.getScreenAudioTrack()?1:0),r.length>=o?(this.sessionManager.mixedLocalAudioTrack.setMicAudioTrack(null),this.sessionManager.mixedLocalAudioTrack.setScreenAudioTrack(null),n.push(this.sessionManager.mixedLocalAudioTrack),i=!0):(r[0].source===exports.AudioSourceInfo.MIC?this.sessionManager.mixedLocalAudioTrack.setMicAudioTrack(null):this.sessionManager.mixedLocalAudioTrack.setScreenAudioTrack(null),this.sessionManager.mixedLocalAudioTrack.updateMixedAudioTrackToPub())),a=new Set(n.map(function(e){return e.getTrackId()})),(s=_toConsumableArray(this.sessionManager.sessions.values()).filter(function(e){var t,r;return e instanceof Publication&&a.has(null===(t=e.tracks)||void 0===t||null===(t=t[0])||void 0===t?void 0:t.getTrackId())&&"video"===(null===(r=e.tracks)||void 0===r||null===(r=r[0])||void 0===r?void 0:r.trackMediaType)})).forEach(function(e){u.reporter.trace.unpublish(e.id)}),c=_toConsumableArray(s),i&&(c.push(this.sessionManager.mixedLocalAudioTrack.getPublication()),this.sessionManager.mixedLocalAudioTrack.setPublication(null)),e.abrupt("return",this.sessionManager.batchUnPublish(c));case 6:case"end":return e.stop()}},e,this,[[1,3]])})),function(e){return a.apply(this,arguments)})},{key:"updateSubbedRemoteTrack",value:function(e,t){var r=this;if(null==t||!t.mediaStream)return null;var n=this.rtcUserManager.users.get(e.uid);if("audio"===e.mediaType){var i=this.remoteAudioTrack;return this.remoteAudioTrack=updateRemoteTrack(t.mediaStream,"audio","mcu",this.remoteAudioTrack),this.updateSubscribedAudioStream(!0,""),i||t.once("audio-first-frame",function(){r.remoteAudioTrack.emit("first-frame-decoded")}),this.remoteAudioTrack}return n.updateSubbedVideoTrack(t,e.auxiliary)}},{key:"batchSubscribe",value:(o=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n,i,o,a,s=this;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return r=t.map(this.handleSubscribeParam),n=this.getSubTraceId(),this.processingSubParamsMap.set(n,t),e.prev=1,e.next=2,this.sessionManager.batchSubscribe(r);case 2:return i=e.sent,o=[],t.forEach(function(e,t){var r=e.auxiliary,n=e.uid,a=i[t],c=a.error,u=a.subscription;o.push({uid:n,auxiliary:r,error:c,track:s.updateSubbedRemoteTrack(e,u)})}),e.abrupt("return",o);case 3:throw e.prev=3,a=e.catch(1),this.logger.error("batch sub error",a),a;case 4:return e.prev=4,this.processingSubParamsMap.delete(n),e.finish(4);case 5:case"end":return e.stop()}},e,this,[[1,3,4,5]])})),function(e){return o.apply(this,arguments)})},{key:"batchUnsubscribe",value:(i=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n,i,o,a,s,c,u,l,d,p=this;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.sessionManager.resubscribePromise){e.next=5;break}return this.logger.info("wait for resuball before unsubscribe"),e.prev=1,e.next=2,this.sessionManager.resubscribePromise;case 2:e.next=4;break;case 3:e.prev=3,e.catch(1);case 4:this.logger.info("go unsubscribe after resuball");case 5:r=[],n=_createForOfIteratorHelper$1(t);try{for(n.s();!(i=n.n()).done;)o=i.value,a=this.checkUnsubParam(o),s=a.session,c=a.stream,u=a.user,l=a.uid,d=a.error,s&&c&&!d&&(this.reporter.trace.unsubscribe({sessionId:s.id,remoteStreamId:c.id,remoteUserId:l}),r.push(_objectSpread$1({stream:c,user:u,session:s},o)))}catch(e){n.e(e)}finally{n.f()}if(r.length){e.next=6;break}return e.abrupt("return",Promise.resolve());case 6:return e.abrupt("return",this.sessionManager.batchUnscribe(r).then(function(e){for(var t=0,n=r;t<n.length;t++){var i,o=n[t],a=o.mediaType,s=o.user,c=o.auxiliary;if("audio"===a)p.updateSubscribedAudioStream(!1,""),null===(i=p.remoteAudioTrack)||void 0===i||i.stopPlay(),p.remoteAudioTrack=null;else if(c){var u;null===(u=s.auxiliaryTrack)||void 0===u||u.stop(),s.auxiliaryTrack=null}else{var l;null===(l=s.videoTrack)||void 0===l||l.stop(),s.videoTrack=null}}return e}));case 7:case"end":return e.stop()}},e,this,[[1,3]])})),function(e){return i.apply(this,arguments)})},{key:"updateSubscribedAudioStream",value:function(e,t){this.subscribedAudioStream=t,this.emit("suscribedAudio",e,t)}},{key:"subscribeGroup",value:function(e){var t=this,r=this.getStream({groupId:e});if(!r)throw new DingRTCError(ErrorCode.InvaildArgument,"cannot find audio info of the group");if(this.subscribedAudioStream)throw new DingRTCError(ErrorCode.InvaildState,"you were subscribed group or channel already");return this.sessionManager.batchSubscribe([{stream:r,uid:e,targetMediaType:"audio"}]).then(function(n){return t.updateSubscribedAudioStream(!0,r.id),t.remoteAudioTrack=updateRemoteTrack(n[0].subscription.mediaStream,"audio",e,t.remoteAudioTrack),t.remoteAudioTrack})}},{key:"unsubscribeGroup",value:function(e){var t=this,r=this.getStream({groupId:e});return r?this.subscribedAudioStream!==r.id?Promise.reject(new DingRTCError(ErrorCode.InvaildState,"you were not subscribed the group")):this.sessionManager.batchUnscribe([{stream:r,session:this.sessionManager.getSessionByStreamId(r.id),targetMediaType:"audio"}]).then(function(){r.id===t.subscribedAudioStream&&(t.updateSubscribedAudioStream(!1,""),t.remoteAudioTrack.stopPlay(),t.remoteAudioTrack=null)}):Promise.reject(new DingRTCError(ErrorCode.InvaildArgument,"cannot find audio info of the group"))}},{key:"setRemoteStreamType",value:function(e,t,r){this.logger.info("setRemoteStreamType",e,t,r);var n=this.getStream({uid:e,mediaType:"video",auxiliary:r}),i=this.sessionManager.getSessionByStreamId(n.id),o=calcResolutionInfo(t,getStreamSupportedResoArr(n));return i.applyOptions(o,!1)}},{key:"joinGroup",value:function(e){var t=this,r=e.groupId,n=e.publishAudioToGroup;return this.groupManager.join(e).then(function(e){t.logger.info("joinGroup response",e);var i=e.joinGroupAudioSuccess;n&&i&&t.micMixedGroups.add(r)})}},{key:"leaveGroup",value:function(e){var t=this,r=e.groupId;return this.groupManager.leave(e).then(function(){t.micMixedGroups.delete(r)})}},{key:"dismissGroup",value:function(e){var t=this;return this.groupManager.dismiss(e).then(function(){t.micMixedGroups.delete(e)})}},{key:"mixGroupAudio",value:function(e,t,r){return this.rtcSignaling.streamControl({operation:r,streamId:e,data:t})}},{key:"setGroupProperties",value:function(e,t){return this.groupManager.setProperties(e,t)}},{key:"publishToGroup",value:(n=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n,i,o=arguments;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(r=!(o.length>1&&void 0!==o[1])||o[1],n=[],null!=t&&n.push(this.groupManager.groups.get(t).audioInfo.label),this.sessionManager.mixedLocalAudioTrack.isPublished()){e.next=1;break}throw this.logger.error("publishToGroup: no published audio track found"),new DingRTCError(ErrorCode.InvaildState,"no published audio track found");case 1:if(i=this.streamManager.getStreamByTrackId(this.sessionManager.mixedLocalAudioTrack.getTrackId()),null==t){e.next=4;break}return e.next=2,this.mixGroupAudio(i.id,n[0],"mix");case 2:if(this.micMixedGroups.add(t),!r){e.next=3;break}return e.next=3,this.mixGroupAudio(i.id,"common","unmix");case 3:e.next=5;break;case 4:return e.next=5,this.mixGroupAudio(i.id,"common","mix");case 5:case"end":return e.stop()}},e,this)})),function(e){return n.apply(this,arguments)})},{key:"unpublishFromGroup",value:(r=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n,i,o=arguments;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(r=o.length>1&&void 0!==o[1]&&o[1],n=this.groupManager.groups.get(t).audioInfo.label,this.sessionManager.mixedLocalAudioTrack.isPublished()){e.next=1;break}throw this.logger.error("unpublishFromGroup: no published audio track found"),new DingRTCError(ErrorCode.InvaildState,"no published audio track found");case 1:return i=this.streamManager.getStreamByTrackId(this.sessionManager.mixedLocalAudioTrack.getTrackId()),e.next=2,this.mixGroupAudio(i.id,n,"unmix");case 2:if(this.micMixedGroups.delete(t),!r){e.next=3;break}return e.next=3,this.mixGroupAudio(i.id,"common","mix");case 3:case"end":return e.stop()}},e,this)})),function(e){return r.apply(this,arguments)})}]);var r,n,i,o,a,s,c}(EventEmitter);function _callSuper$2(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$2()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$2(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$2=function(){return!!e})()}Object.defineProperty(ServiceManager,"subAcc",{enumerable:!0,configurable:!0,writable:!0,value:0});var initAudioDeviceBufferInfo={timestamp:-1,maxPlayLevel:-1,maxRecLevel:-1},DeviceMonitor=function(e){function t(e){var r,n;return _classCallCheck$1(this,t),r=_callSuper$2(this,t),Object.defineProperty(r,"audioDeviceBufferReport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"audioDeviceBufferInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"makeReport",{enumerable:!0,configurable:!0,writable:!0,value:(n=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){var t,n,i,o,a;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=1,r.client.getLocalAudioStats();case 1:return t=e.sent,n=t.audioLevel,e.next=2,r.client.getRemoteAudioStats();case 2:i=e.sent,o=i.audioLevel,a={timestamp:Date.now(),maxRecLevel:Math.min(1,n||0),maxPlayLevel:Math.min(1,Math.max(0,o||0))},r.audioDeviceBufferInfo.timestamp>0&&(r.audioDeviceBufferReport={attr_duration_ms:getDelta(a.timestamp,r.audioDeviceBufferInfo.timestamp),attr_play_level:Math.round(32767*a.maxPlayLevel),attr_rec_level:Math.round(32767*a.maxRecLevel)},r.emit("audio-device-buffer",Object.assign({},r.audioDeviceBufferReport))),r.audioDeviceBufferInfo=a;case 3:case"end":return e.stop()}},e)})),function(){return n.apply(this,arguments)})}),r.audioDeviceBufferReport={attr_duration_ms:0,attr_rec_level:0,attr_play_level:0},r.audioDeviceBufferInfo=Object.assign({},initAudioDeviceBufferInfo),r.client=e,r}return _inherits$1(t,e),_createClass$1(t)}(Monitor);function ownKeys(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function _objectSpread(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys(Object(r),!0).forEach(function(t){_defineProperty(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function _createForOfIteratorHelper(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _unsupportedIterableToArray(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_arrayLikeToArray(e,t):void 0}}function _arrayLikeToArray(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _callSuper$1(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct$1()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct$1(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct$1=function(){return!!e})()}function _superPropGet(e,t,r,n){var i=_get(_getPrototypeOf$1(e.prototype),t,r);return 2&n&&"function"==typeof i?function(e){return i.apply(r,e)}:i}var DingRTCClient=function(e){function t(e){var r;return _classCallCheck$1(this,t),r=_callSuper$1(this,t),Object.defineProperty(r,"channelName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"id",{enumerable:!0,configurable:!0,writable:!0,value:createUuid(6)}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:registerReporter(r.id)}),Object.defineProperty(r,"logger",{enumerable:!0,configurable:!0,writable:!0,value:r.reporter.getLoggerWithPrefix("[rtc-client]")}),Object.defineProperty(r,"serviceManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"monitor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"syncStatTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"clientStatSync",{enumerable:!0,configurable:!0,writable:!0,value:[0,0,0,0,0,0]}),Object.defineProperty(r,"currentClientState",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(r,"deviceChecker",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.serviceManager=new ServiceManager(r,r.reporter),r.handleVisibilitychange=r.handleVisibilitychange.bind(r),r.handleNetworkQuality=r.handleNetworkQuality.bind(r),r.handleConnectionChangeEvent=r.handleConnectionChangeEvent.bind(r),r.handlePageUnload=r.handlePageUnload.bind(r),r.init(),r.deviceChecker=null==e?void 0:e.deviceChecker,r}return _inherits$1(t,e),_createClass$1(t,[{key:"remoteUsers",get:function(){return this.serviceManager.rtcUserManager.remoteUsers}},{key:"groups",get:function(){return this.serviceManager.groups}},{key:"userId",get:function(){var e;return(null===(e=this.serviceManager.internalChannel)||void 0===e||null===(e=e.joinInfo)||void 0===e?void 0:e.uid)||""}},{key:"localTracks",get:function(){return this.serviceManager.publishedLocalTracks}},{key:"connectionState",get:function(){var e;return(null===(e=this.serviceManager.internalChannel)||void 0===e?void 0:e.connectionState)||"disconnected"}},{key:"init",value:function(){this.syncStatTimer&&(removeTimer(this.syncStatTimer,"interval"),this.syncStatTimer=null),this.currentClientState="",this.channelName="",this.serviceManager.clear(),this.removeEventListeners(),this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.clientStatSync=[0,0,0,0,0,0]}},{key:"emit",value:function(e){for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];var o;"network-quality"!==e&&"volume-indicator"!==e&&(o=this.logger).info.apply(o,["client emit event",e].concat(n));return _superPropGet(t,"emit",this,3)([e].concat(n))}},{key:"startPlugin",value:(l=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t,r){var n;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(this.logger.info("startPlugin",t,r),"DeviceChecker"===t){e.next=1;break}return this.logger.error("not supported plugin",t),e.abrupt("return",Promise.reject("not supported plugin"));case 1:if(this.deviceChecker){e.next=2;break}return this.logger.error("deviceChecker should be created in DingRTC.createClient before start"),e.abrupt("return",Promise.reject("plugin not created"));case 2:return e.prev=2,e.abrupt("return",this.deviceChecker.start(r));case 3:return e.prev=3,n=e.catch(2),this.logger.error("startPlugin error",t,r,n),e.abrupt("return",Promise.reject(n));case 4:case"end":return e.stop()}},e,this,[[2,3]])})),function(e,t){return l.apply(this,arguments)})},{key:"join",value:(u=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n,i=this;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return this.logger.info("join",t),e.prev=1,this.addEventListeners(),void 0===t.initMicMuted&&(t.initMicMuted=!0),e.next=2,this.serviceManager.join(t).then(function(e){var r;return i.channelName=t.channel,i.monitor=new DeviceMonitor(i),i.monitor.on("audio-device-buffer",function(e){i.reporter.metric.audioDeviceBuffer(e)}),i.syncStatTimer=addTimer(function(){i.sendClientStatToRemote()},NETWORK_QUALITY_TIMEOUT,"interval"),{remoteUsers:i.remoteUsers,timeLeft:null===(r=e.room)||void 0===r?void 0:r.timeLeft}}).catch(function(e){throw i.init(),e});case 2:return r=e.sent,e.abrupt("return",r);case 3:return e.prev=3,n=e.catch(1),this.logger.error("join error",t,n),e.abrupt("return",Promise.reject(n));case 4:case"end":return e.stop()}},e,this,[[1,3]])})),function(e){return u.apply(this,arguments)})},{key:"setRemoteDefaultVideoStreamType",value:function(e){this.logger.info("setRemoteDefaultVideoStreamType",e),this.serviceManager.defaultVideoStreamType=e}},{key:"leave",value:function(){this.logger.info("leave"),this.serviceManager.leave(),this.init()}},{key:"publish",value:(c=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n,i,o,a,s,c,u,l,d,p,f=this;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if((r=this.logger).info.apply(r,["publish"].concat(_toConsumableArray((Array.isArray(t)?t:[t]).map(function(e){return{mediaType:null==e?void 0:e.trackMediaType,trackId:null==e?void 0:e.getTrackId(),source:null==e?void 0:e.source}})))),e.prev=1,"connected"===this.connectionState){e.next=2;break}return e.abrupt("return",Promise.reject(new DingRTCError(ErrorCode.PublishNotJoinChannel)));case 2:n=(Array.isArray(t)?t:[t]).filter(function(e){return e instanceof LocalTrack&&!f.localTracks.includes(e)}),i=n.concat(this.localTracks),o=_defineProperty(_defineProperty(_defineProperty(_defineProperty({},"video"+exports.VideoSourceInfo.CAMERA,0),"video"+exports.VideoSourceInfo.SCREENCAST,0),"audio"+exports.AudioSourceInfo.MIC,0),"audio"+exports.AudioSourceInfo.SCREENCAST,0),a=_createForOfIteratorHelper(i),e.prev=3,a.s();case 4:if((s=a.n()).done){e.next=6;break}if(c=s.value,o[c.trackMediaType+c.source]++,!(o[c.trackMediaType+c.source]>=2)){e.next=5;break}throw new DingRTCError(ErrorCode.QuotaLimitExceed,"".concat(c.trackMediaType,"-").concat(c.source," published already"));case 5:e.next=4;break;case 6:e.next=8;break;case 7:e.prev=7,d=e.catch(3),a.e(d);case 8:return e.prev=8,a.f(),e.finish(8);case 9:if(n.length){e.next=10;break}throw new DingRTCError(ErrorCode.PublishNoStream);case 10:return e.next=11,this.serviceManager.publish(n);case 11:return u=e.sent,e.abrupt("return",u);case 12:return e.prev=12,p=e.catch(1),(l=this.logger).error.apply(l,["publish error"].concat(_toConsumableArray((Array.isArray(t)?t:[t]).map(function(e){return{mediaType:null==e?void 0:e.trackMediaType,trackId:null==e?void 0:e.getTrackId(),source:null==e?void 0:e.source}})),[p])),e.abrupt("return",Promise.reject(p));case 13:case"end":return e.stop()}},e,this,[[1,12],[3,7,8,9]])})),function(e){return c.apply(this,arguments)})},{key:"unpublish",value:(s=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n,i,o,a;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if((r=this.logger).info.apply(r,["unpublish param"].concat(_toConsumableArray((Array.isArray(t)?t:[t]).map(function(e){return{mediaType:null==e?void 0:e.trackMediaType,trackId:null==e?void 0:e.getTrackId(),source:null==e?void 0:e.source}})))),e.prev=1,n=Array.isArray(t)?t:[t],t||(n=this.localTracks),this.logger.info("unpublish tracks",n.map(function(e){return e.trackMediaType})),"connected"===this.connectionState){e.next=2;break}return e.abrupt("return",Promise.reject(new DingRTCError(ErrorCode.ConnectionConnectFail)));case 2:return e.next=3,this.serviceManager.unpublish(n);case 3:return i=e.sent,e.abrupt("return",i);case 4:return e.prev=4,a=e.catch(1),(o=this.logger).error.apply(o,["unpub error"].concat(_toConsumableArray((Array.isArray(t)?t:[t]).map(function(e){return{mediaType:null==e?void 0:e.trackMediaType,trackId:null==e?void 0:e.getTrackId(),source:null==e?void 0:e.source}})),[a])),e.abrupt("return",Promise.reject(a));case 5:case"end":return e.stop()}},e,this,[[1,4]])})),function(e){return s.apply(this,arguments)})},{key:"subscribe",value:(a=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t,r,n){var i,o;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(e.prev=0,this.logger.info("subscribe",t,r,n),"connected"===this.connectionState){e.next=1;break}throw new DingRTCError(ErrorCode.SubscribeNotJoinChannel);case 1:return e.next=2,this.serviceManager.batchSubscribe([{uid:t,mediaType:r,auxiliary:n}]).then(function(e){var t=e[0],r=t.error,n=t.track;if(r)throw r;return n});case 2:return i=e.sent,e.abrupt("return",i);case 3:return e.prev=3,o=e.catch(0),this.logger.error("subscribe error",t,r,n,o),e.abrupt("return",Promise.reject(o));case 4:case"end":return e.stop()}},e,this,[[0,3]])})),function(e,t,r){return a.apply(this,arguments)})},{key:"batchSubscribe",value:(o=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(e.prev=0,this.logger.info("batchSubscribe",t),Array.isArray(t)&&t.length){e.next=1;break}return e.abrupt("return");case 1:if("connected"===this.connectionState){e.next=2;break}throw new DingRTCError(ErrorCode.SubscribeNotJoinChannel);case 2:return e.next=3,this.serviceManager.batchSubscribe(t.map(function(e){return _objectSpread(_objectSpread({},e),{},{action:"subscribe"})}));case 3:return r=e.sent,e.abrupt("return",r);case 4:return e.prev=4,n=e.catch(0),this.logger.error("batchSubscribe error",n),e.abrupt("return",Promise.reject(n));case 5:case"end":return e.stop()}},e,this,[[0,4]])})),function(e){return o.apply(this,arguments)})},{key:"unsubscribe",value:(i=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t,r,n){var i,o;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(this.logger.info("unsubscribe",t,r,n),e.prev=1,"connected"===this.connectionState){e.next=2;break}return e.abrupt("return",Promise.reject(new DingRTCError(ErrorCode.ConnectionConnectFail)));case 2:return e.next=3,this.serviceManager.batchUnsubscribe([{uid:t,auxiliary:n,mediaType:r}]).then(function(e){var t,r=null==e||null===(t=e[0])||void 0===t?void 0:t.error;if(r)throw r});case 3:return i=e.sent,e.abrupt("return",i);case 4:return e.prev=4,o=e.catch(1),this.logger.error("unsubscribe error",t,r,o),e.abrupt("return",Promise.reject(o));case 5:case"end":return e.stop()}},e,this,[[1,4]])})),function(e,t,r){return i.apply(this,arguments)})},{key:"batchUnsubscribe",value:(n=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r,n;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(this.logger.info("batchUnsubscribe",t),e.prev=1,Array.isArray(t)&&t.length){e.next=2;break}return e.abrupt("return");case 2:if("connected"===this.connectionState){e.next=3;break}return e.abrupt("return",Promise.reject(new DingRTCError(ErrorCode.SubscribeNotJoinChannel)));case 3:return e.next=4,this.serviceManager.batchUnsubscribe(t.map(function(e){return _objectSpread(_objectSpread({},e),{},{action:"unsubscribe"})}));case 4:return r=e.sent,e.abrupt("return",r);case 5:return e.prev=5,n=e.catch(1),this.logger.error("batchUnsubscribe error",t,n),e.abrupt("return",Promise.reject(n));case 6:case"end":return e.stop()}},e,this,[[1,5]])})),function(e){return n.apply(this,arguments)})},{key:"getLocalAudioStats",value:function(){return this.serviceManager.sessionManager.getLocalAudioStats("user")}},{key:"getLocalVideoStats",value:function(){return this.serviceManager.sessionManager.getLocalVideoStats("user")}},{key:"setRemoteVideoStreamType",value:(r=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t,r,n){var i,o,a,s=this;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(e.prev=0,this.logger.info("setRemoteVideoStreamType",t,r,n),"connected"===this.connectionState){e.next=1;break}return e.abrupt("return",Promise.reject(new DingRTCError(ErrorCode.ConnectionConnectFail)));case 1:if(null!=(i=this.remoteUsers.find(function(e){return e.userId===t}))&&i.relatedStreams){e.next=2;break}return this.logger.info("".concat(t," videoTrack not existed")),e.abrupt("return",Promise.reject("viedoTrack doesnt exiested"));case 2:return e.next=3,this.serviceManager.setRemoteStreamType(t,r,n).then(function(){s.emit("stream-type-changed",t,r,n)});case 3:return o=e.sent,e.abrupt("return",o);case 4:return e.prev=4,a=e.catch(0),this.logger.error("setRemoteVideoStreamType error",t,r,n,a),e.abrupt("return",Promise.reject(a));case 5:case"end":return e.stop()}},e,this,[[0,4]])})),function(e,t,n){return r.apply(this,arguments)})},{key:"getRemoteVideoStats",value:function(){return this.serviceManager.sessionManager.getRemoteVideoStats("user")}},{key:"getRemoteAudioStats",value:function(){return this.serviceManager.sessionManager.getRemoteAudioStats("user")}},{key:"getRemoteNetworkQuality",value:function(){var e={};return this.remoteUsers.forEach(function(t){var r,n,i=t.properties,o=t.userId;e[o]={downlinkNetworkQuality:Number((null==i||null===(r=i[USER_STATS_SYNC])||void 0===r?void 0:r[ClientUserStats.DOWNLINK])||0),uplinkNetworkQuality:Number((null==i||null===(n=i[USER_STATS_SYNC])||void 0===n?void 0:n[ClientUserStats.UPLINK])||0)}}),e}},{key:"handleConnectionChangeEvent",value:function(e,t,r){this.logger.info("connectionStateChange from ".concat(t," to ").concat(e," ").concat(r||"")),"disconnected"===e&&this.init(),this.emit("connection-state-change",e,t,r)}},{key:"sendClientStatToRemote",value:function(){var e=this,t=this.clientStatSync.join("");if(t!==this.currentClientState){var r=transNativeAndWebNetworkRank(null,t[ClientUserStats.UPLINK]),n=transNativeAndWebNetworkRank(null,this.currentClientState[ClientUserStats.UPLINK]),i=transNativeAndWebNetworkRank(null,t[ClientUserStats.DOWNLINK]),o=transNativeAndWebNetworkRank(null,this.currentClientState[ClientUserStats.DOWNLINK]);r===n&&i===o||this.serviceManager.rtcUserManager.setParticipantProperties(t).catch(function(t){e.logger.info("setParticipantProperties error ".concat(tryJsonStringify(t)))}),this.currentClientState=t}}},{key:"handleVisibilitychange",value:function(){var e="visible"!==document.visibilityState,t=e?TraceEvent$1.APP_BACKGROUND:TraceEvent$1.APP_FOREGROUND;(Environment.isAndroid()||Environment.isIOS())&&(this.reporter.sender.sendEvent(t),this.clientStatSync[ClientUserStats.BACKGROUND_MODE]=Number(e))}},{key:"handleNetworkQuality",value:function(e,t){this.clientStatSync[ClientUserStats.UPLINK]=e,this.clientStatSync[ClientUserStats.DOWNLINK]=t,this.emit("network-quality",e,t)}},{key:"handlePageUnload",value:function(e){"connected"===this.connectionState&&(this.logger.info("leave for ".concat(e.type)),this.leave())}},{key:"addEventListeners",value:function(){window.addEventListener(Environment.isSafari()?"beforeunload":"pagehide",this.handlePageUnload),document.addEventListener("visibilitychange",this.handleVisibilitychange),this.serviceManager.sessionManager.on("network-quality",this.handleNetworkQuality),this.serviceManager.rtcSignaling.on("connection-state-change",this.handleConnectionChangeEvent)}},{key:"removeEventListeners",value:function(){window.removeEventListener(Environment.isSafari()?"beforeunload":"pagehide",this.handlePageUnload),document.removeEventListener("visibilitychange",this.handleVisibilitychange),this.serviceManager.sessionManager.off("network-quality",this.handleNetworkQuality),this.serviceManager.rtcSignaling.off("connection-state-change",this.handleConnectionChangeEvent)}},{key:"joinGroup",value:function(e){this.logger.info("joinGroup",e);try{if("connected"!==this.connectionState)return Promise.reject(new DingRTCError(ErrorCode.ConnectionConnectFail));var t=e.userData,r=e.groupId,n=new TextEncoder;if(!r||n.encode(r).length>64)throw new DingRTCError(ErrorCode.InvaildArgument,"join group with invalid groupId");if(t){var i=new TextEncoder;if("string"!=typeof t||i.encode(t).length>64)throw new DingRTCError(ErrorCode.InvaildArgument,"join group with invalid userData")}return this.serviceManager.joinGroup(e)}catch(t){return this.logger.error("joinGroup error",e,t),Promise.reject(t)}}},{key:"leaveGroup",value:function(e){this.logger.info("leaveGroup",e);try{return"connected"!==this.connectionState?Promise.reject(new DingRTCError(ErrorCode.ConnectionConnectFail)):this.serviceManager.leaveGroup({groupId:e,publishAudioToChannel:!1})}catch(t){return this.logger.error("leaveGroup error",e,t),Promise.reject(t)}}},{key:"setGroupName",value:function(e,t){this.logger.info("setGroupName",e,t);try{if("connected"!==this.connectionState)return Promise.reject(new DingRTCError(ErrorCode.ConnectionConnectFail));var r=new TextEncoder;if(!t||r.encode(t).length>64)throw new DingRTCError(ErrorCode.InvaildArgument,"update group with invalid name");return this.serviceManager.setGroupProperties(e,{key:"name",value:t})}catch(r){return this.logger.error("setGroupName error",e,t,r),Promise.reject(r)}}},{key:"subscribeGroup",value:function(e){this.logger.info("subscribeGroup",e);try{return"connected"!==this.connectionState?Promise.reject(new DingRTCError(ErrorCode.ConnectionConnectFail)):this.serviceManager.subscribeGroup(e)}catch(t){return this.logger.error("subscribeGroup error",e,t),Promise.reject(t)}}},{key:"unsubscribeGroup",value:function(e){this.logger.info("unsubscribeGroup",e);try{return"connected"!==this.connectionState?Promise.reject(new DingRTCError(ErrorCode.ConnectionConnectFail)):this.serviceManager.unsubscribeGroup(e)}catch(t){return this.logger.error("unsubscribeGroup error",e,t),Promise.reject(t)}}},{key:"mixAudioToGroup",value:function(e,t,r){this.logger.info("mixAudioToGroup",{mediaType:null==e?void 0:e.trackMediaType,trackId:null==e?void 0:e.getTrackId(),source:null==e?void 0:e.source},t,r);try{if("connected"!==this.connectionState)throw new DingRTCError(ErrorCode.ConnectionConnectFail);if(t){if(this.logger.info("mix audio to group ".concat(r)),null==r&&this.serviceManager.micMixedGroups.size)throw new DingRTCError(ErrorCode.InvaildState,"cannot mix audio to channel while mixing to others group");return this.serviceManager.publishToGroup(r,!0)}if(this.logger.info("unmix audio from group ".concat(r)),!this.serviceManager.micMixedGroups.has(r))throw new DingRTCError(ErrorCode.InvaildState,"cannot unmix audio from the unmixed group");return this.serviceManager.unpublishFromGroup(r)}catch(n){return this.logger.error("mixAudioToGroup error",{mediaType:null==e?void 0:e.trackMediaType,trackId:null==e?void 0:e.getTrackId(),source:null==e?void 0:e.source},t,r,n),Promise.reject(n)}}},{key:"dismissGroup",value:function(e){this.logger.info("dismissGroup",e);try{return"connected"!==this.connectionState?Promise.reject(new DingRTCError(ErrorCode.ConnectionConnectFail)):this.serviceManager.dismissGroup(e)}catch(t){return this.logger.error("dismissGroup error",e,t),Promise.reject(t)}}},{key:"register",value:function(e){this.logger.info("register",e),e.attach(this.serviceManager.internalChannel,this.serviceManager)}},{key:"ungister",value:function(e){this.logger.info("ungister",e),e.detach(this.serviceManager.internalChannel)}}]);var r,n,i,o,a,s,c,u,l}(EventEmitter),FALLBACK_SUB_VIDEO_PROFILE={height:360,width:640},initListenBrowserEvent=function(){var e=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t){var r;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:window.addEventListener("offline",function(){t.info("browser offline event")}),window.addEventListener("online",function(){t.info("browser online event")}),r=function(){"visible"===document.visibilityState?t.info("page changed to visible"):t.info("page changed to invisible")},document.addEventListener("visibilitychange",r),window.addEventListener("blur",function(){t.info("page blurred")}),window.addEventListener("focus",function(){t.info("page focused")});case 1:case"end":return e.stop()}},e)}));return function(t){return e.apply(this,arguments)}}();function _callSuper(e,t,r){return t=_getPrototypeOf$1(t),_possibleConstructorReturn$1(e,_isNativeReflectConstruct()?Reflect.construct(t,[],_getPrototypeOf$1(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct=function(){return!!e})()}initMediaElementPool();var simpleLogger=getReporter().getLoggerWithPrefix("[rtc-index]");simpleLogger.info("sdk version",SDK_VERSION),simpleLogger.info("userAgent",navigator.userAgent),simpleLogger.info("href: ".concat(location.href,", in_iframe=").concat(window!==window.parent)),initListenBrowserEvent(simpleLogger);var DingRTC=function(e){function t(){var e;if(_classCallCheck$1(this,t),e=_callSuper(this,t),Object.defineProperty(e,"VERSION",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e.VERSION=SDK_VERSION,!support.checkSupported())return _possibleConstructorReturn$1(e);var r=DeviceManager.getInstance();return r.on("camera-changed",function(t){e.emit("camera-changed",t)}),r.on("microphone-changed",function(t){e.emit("microphone-changed",t)}),r.on("playback-device-changed",function(t){e.emit("playback-device-changed",t)}),EventBus.on("autoplay-failed",function(t){e.emit("autoplay-failed",t)}),e}return _inherits$1(t,e),_createClass$1(t,[{key:"createClient",value:function(e){simpleLogger.info("createClient",null==e?void 0:e.map(function(e){return null==e?void 0:e.pluginName}));var t=null==e?void 0:e.find(function(e){return"DeviceChecker"===(null==e?void 0:e.pluginName)}),r=null==t?void 0:t.createPlugin();return null==r||r.injectLogger(getReporter().getLoggerWithPrefix("[rtc-devcheck]")),new DingRTCClient({deviceChecker:r})}},{key:"checkSystemRequirements",value:function(){return simpleLogger.info("checkSystemRequirements"),support.checkSupported()}},{key:"getSupportedCodec",value:function(){return simpleLogger.info("getSupportedCodec"),support.getSupportedCodec()}},{key:"createCameraVideoTrack",value:function(e){return simpleLogger.info("createCameraVideoTrack",e),createCameraVideoTrack(e)}},{key:"createMicrophoneAudioTrack",value:function(e){return simpleLogger.info("createMicrophoneAudioTrack",e),createMicrophoneAudioTrack(e)}},{key:"createCustomVideoTrack",value:function(e,t){return simpleLogger.info("createCustomVideoTrack",e,t),createCustomVideoTrack(e,t)}},{key:"createCustomAudioTrack",value:function(e,t){return simpleLogger.info("createCustomAudioTrack",e,t),createCustomAudioTrack(e,t)}},{key:"createScreenVideoTrack",value:function(e){return simpleLogger.info("createScreenVideoTrack",e),createScreenVideoTrack(e)}},{key:"createScreenVideoAndAudioTrack",value:function(e){return simpleLogger.info("createScreenVideoAndAudioTrack",e),createScreenVideoAndAudioTrack(e)}},{key:"createMicrophoneAndCameraTracks",value:(n=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(t,r){return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return simpleLogger.info("createMicrophoneAndCameraTracks",{videoConfig:t,audioConfig:r}),e.abrupt("return",createMicrophoneAndCameraTracks(t,r));case 1:case"end":return e.stop()}},e)})),function(e,t){return n.apply(this,arguments)})},{key:"getCameras",value:function(){return simpleLogger.info("getCameras"),DeviceManager.getCameras()}},{key:"getDevices",value:(r=_asyncToGenerator$1(_regeneratorRuntime$1.mark(function e(){var t,r;return _regeneratorRuntime$1.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return simpleLogger.info("start getDevices"),e.prev=1,e.next=2,DeviceManager.getDevices();case 2:return t=e.sent,simpleLogger.info("getDevices suc",t),e.abrupt("return",t);case 3:return e.prev=3,r=e.catch(1),simpleLogger.info("error getDevices ",r),e.abrupt("return",r);case 4:case"end":return e.stop()}},e,null,[[1,3]])})),function(){return r.apply(this,arguments)})},{key:"getPlaybackDevices",value:function(){return simpleLogger.info("getPlaybackDevices"),DeviceManager.getPlaybackDevices()}},{key:"getMicrophones",value:function(){return simpleLogger.info("getMicrophones"),DeviceManager.getMicrophones()}},{key:"setLogLevel",value:function(e){console.warn("[dingrtc]: setLogLevel is deprecated"),setLogLevel(clientConfig._consoleLogLevel),simpleLogger.info(" setLogLevel - ignored and hint deprecated",e)}},{key:"setClientConfig",value:function(e){simpleLogger.info("setClientConfig",e),clientConfig.setClientConfig(e)}}]);var r,n}(EventEmitter),index=new DingRTC;exports.ErrorCodeAndMsgMap=ErrorCodeAndMsgMap,exports.FALLBACK_SUB_VIDEO_PROFILE=FALLBACK_SUB_VIDEO_PROFILE,exports.default=index,Object.defineProperty(exports,"__esModule",{value:!0})});