aliyun-rtc-sdk 6.11.8 → 6.11.9-beta.0

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.
@@ -1,7 +1,7 @@
1
1
  var H0=Object.defineProperty,j0=Object.defineProperties;var W0=Object.getOwnPropertyDescriptors;var Ki=Object.getOwnPropertySymbols,K0=Object.getPrototypeOf,Ba=Object.prototype.hasOwnProperty,Pa=Object.prototype.propertyIsEnumerable,$0=Reflect.get;var ys=(he,me,ve)=>me in he?H0(he,me,{enumerable:!0,configurable:!0,writable:!0,value:ve}):he[me]=ve,Se=(he,me)=>{for(var ve in me||(me={}))Ba.call(me,ve)&&ys(he,ve,me[ve]);if(Ki)for(var ve of Ki(me))Pa.call(me,ve)&&ys(he,ve,me[ve]);return he},Rt=(he,me)=>j0(he,W0(me));var $i=(he,me)=>{var ve={};for(var $e in he)Ba.call(he,$e)&&me.indexOf($e)<0&&(ve[$e]=he[$e]);if(he!=null&&Ki)for(var $e of Ki(he))me.indexOf($e)<0&&Pa.call(he,$e)&&(ve[$e]=he[$e]);return ve};var A=(he,me,ve)=>(ys(he,typeof me!="symbol"?me+"":me,ve),ve);var As=(he,me,ve)=>$0(K0(he),ve,me);var z=(he,me,ve)=>new Promise(($e,kt)=>{var nt=qe=>{try{Qe(ve.next(qe))}catch(lt){kt(lt)}},dt=qe=>{try{Qe(ve.throw(qe))}catch(lt){kt(lt)}},Qe=qe=>qe.done?$e(qe.value):Promise.resolve(qe.value).then(nt,dt);Qe((ve=ve.apply(he,me)).next())}),qi=function(he,me){this[0]=he,this[1]=me},La=(he,me,ve)=>{var $e=(dt,Qe,qe,lt)=>{try{var je=ve[dt](Qe),Zt=(Qe=je.value)instanceof qi,oi=je.done;Promise.resolve(Zt?Qe[0]:Qe).then(ft=>Zt?$e(dt==="return"?dt:"next",Qe[1]?{done:ft.done,value:ft.value}:ft,qe,lt):qe({value:ft,done:oi})).catch(ft=>$e("throw",ft,qe,lt))}catch(ft){lt(ft)}},kt=dt=>nt[dt]=Qe=>new Promise((qe,lt)=>$e(dt,Qe,qe,lt)),nt={};return ve=ve.apply(he,me),nt[Symbol.asyncIterator]=()=>nt,kt("next"),kt("throw"),kt("return"),nt};(function(he,me){typeof exports=="object"&&typeof module!="undefined"?me(exports,require("aliyun-rts-sdk"),require("eventemitter3")):typeof define=="function"&&define.amd?define(["exports","aliyun-rts-sdk","eventemitter3"],me):(he=typeof globalThis!="undefined"?globalThis:he||self,me(he.AliRtcEngine={},he.AliyunRts,he.EventEmitter))})(this,function(he,me,ve){var it,Lt,_t,si,fe,Ia;"use strict";var $e=Object.defineProperty,kt=(s,c,e)=>c in s?$e(s,c,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[c]=e,nt=(s,c,e)=>(kt(s,typeof c!="symbol"?c+"":c,e),e),dt={exports:{}},Qe={exports:{}},qe,lt;function je(){if(lt)return qe;lt=1,Date.now=Date.now||function(){return new Date().getTime()};var s=Date.now(),c=function(){},e=function(){var r=typeof console=="object"?console.warn:c;try{var i={warn:r};i.warn.call(i)}catch(n){return c}return r},t={noop:c,warn:e(),key:"__bl",selfErrKey:"ARMS_SDK_ERROR",selfErrPage:"ARMSSDK",win:typeof window=="object"&&window.document?window:void 0,regionMap:{cn:"https://arms-retcode.aliyuncs.com/r.png?",sg:"https://arms-retcode-sg.aliyuncs.com/r.png?",sg_2:"https://retcode-sg-lazada.arms.aliyuncs.com/r.png?",daily:"http://arms-retcode-daily.alibaba.net/r.png?",daily_2:"https://arms-retcode-daily.alibaba.net/r.png?",daily_3:"http://arms-retcode-daily.aliyun.test/r.png?",us:"https://retcode-us-west-1.arms.aliyuncs.com/r.png?",tw:"https://arms-retcode.orientalgame.com.tw/r.png?",tw_sg:"https://arms-retcode-sg.orientalgame.com.tw/r.png?",hz_finance:"https://arms-retcode-hz-finance.aliyuncs.com/r.png?"},defaultImgUrl:"https://arms-retcode.aliyuncs.com/r.png?",createObject:function(r){if(Object.create)return Object.create(r);var i=function(){};return i.prototype=r,new i},each:function(r,i){var n=0,a=r.length;if(this.T(r,"Array"))for(;n<a&&i.call(r[n],r[n],n)!==!1;n++);else for(n in r)if(i.call(r[n],r[n],n)===!1)break;return r},safetyCall:function(r,i,n){if(typeof r!="function")return n;try{return r.apply(this,i)}catch(a){return n}},T:function(r,i){var n=Object.prototype.toString.call(r).substring(8).replace("]","");return i?n===i:n},duration:function(){var r=Date;try{performance&&this.T(performance.now,"Function")&&(r=performance)}catch(n){r=Date}var i=r.now();return function(){return Math.round(r.now()-i)}},filterByRule:function(){var r=[].slice.call(arguments),i=r.length;if(i<2)return r[0];var n=r[i-1],a=r[0];if(!a)return"";if(!n)return a;var o=this,u=o.T(n),h=r.slice(0,i-1);return u==="Function"?o.safetyCall(n,h,a):u==="Array"?(this.each(n,function(g){h[0]=a=o.filterByRule.apply(o,[].concat(h,g))}),a):u==="Object"?a.replace(n.rule,n.target||""):a.replace(n,"")},ignoreByRule:function(r,i){if(!r||!i)return!1;if((this.isString(i)||i.source||this.T(i)==="Function")&&(i=[i]),!this.isArray(i))return this.warn("[arms] invalid rules of ignore config, (list of) String/RegExp/Funcitons are available"),!1;for(var n,a=[],o=0,u=i.length;o<u;o++)if(n=i[o],this.isString(n))a.push(n.replace(/([.*+?^=!:${}()|\[\]\/\\])/g,"\\$1"));else if(n&&n.source)a.push(n.source);else if(n&&this.T(n)==="Function"&&this.safetyCall(n,[r],!1)===!0)return!0;var h=new RegExp(a.join("|"),"i");return!!(a.length&&h.test&&h.test(r))},J:function(r){if(!r||typeof r!="string")return r;var i=null;try{i=JSON.parse(r)}catch(n){}return i},pick:function(r){return r===1||Math.ceil(Math.random()*r)===1},verifyConfig:function(r){if("sample"in r){var i=r.sample,n=i;i&&/^\d+(\.\d+)?%$/.test(i)&&(n=parseInt(100/parseFloat(i))),0<n&&1>n&&(n=parseInt(1/n)),n>=1&&n<=100?r.sample=n:delete r.sample}return r},on:function(r,i,n,a,o){return r.addEventListener?(o=o||!1,r.addEventListener(i,function u(h){a&&r.removeEventListener(i,u,o),n.call(this,h)},o)):r.attachEvent&&r.attachEvent("on"+i,function u(h){a&&r.detachEvent("on"+i,u),n.call(this,h)}),this},off:function(r,i,n){return n?(r.removeEventListener?r.removeEventListener(i,n):r.detachEvent&&r.detachEvent(i,n),this):this},delay:function(r,i){return i===-1?(r(),null):setTimeout(r,i||0)},ext:function(r){for(var i=1,n=arguments.length;i<n;i++){var a=arguments[i];for(var o in a)Object.prototype.hasOwnProperty.call(a,o)&&(r[o]=a[o])}return r},sub:function(r,i){var n={};return this.each(r,function(a,o){i.indexOf(o)!==-1&&(n[o]=a)}),n},uu:function(){for(var r,i,n=20,a=new Array(n),o=Date.now().toString(36).split("");n-- >0;)i=(r=36*Math.random()|0).toString(36),a[n]=r%3?i:i.toUpperCase();for(var u=0;u<8;u++)a.splice(3*u+2,0,o[u]);return a.join("")},guid:function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(r){var i=16*Math.random()|0;return(r==="x"?i:3&i|8).toString(16)})},seq:function(){return(s++).toString(36)},decode:function(r){try{r=decodeURIComponent(r)}catch(i){}return r},encode:function(r,i){try{r=i?encodeURIComponent(r).replace(/\(/g,"%28").replace(/\)/g,"%29"):encodeURIComponent(r)}catch(n){}return r},serialize:function(r){r=r||{};var i=[];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&r[n]!==void 0&&i.push(n+"="+this.encode(r[n],n==="msg"));return i.join("&")},checkAPI:function(r,i){if(!r||typeof r!="string")return!1;var n=/arms-retcode[\w-]*\.aliyuncs/.test(r);return!n&&i&&(n=/(alicdn\.com)|(mmstat\.com)/.test(r)),!n},checkAutoError:function(r){return!(!r||!r.message)&&!/failed[\w\s]+fetch/i.test(r.message)},cutUrlSearch:function(r){return r&&typeof r=="string"?r.replace(/^(https?:)?\/\//,"").replace(/\?.*$/,""):""},removeUrlSearch:function(r){return r&&typeof r=="string"?r.replace(/\?.*$/,""):""},createFakeToString:function(r){return function(){return r+"() { [native code] }"}},checkSameOrigin:function(r,i){if(!i||!r)return!1;var n="//"+i.split("/")[2];return r===i||r.slice(0,i.length+1)===i+"/"||r===n||r.slice(0,n.length+1)===n+"/"||!/^(\/\/|http:|https:).*/.test(r)},getRandIP:function(){for(var r=[],i=0;i<4;i++){var n=Math.floor(256*Math.random());r[i]=(n>15?"":"0")+n.toString(16)}return r.join("").replace(/^0/,"1")},getSortNum:function(r){return r?(r+=1)>=1e3&&r<=9999?r:r<1e3?r+1e3:r%1e4+1e3:1e3},getRandNum:function(r){return r&&typeof r=="string"?r.length<5?this.getNum(5):r.substring(r.length-5):this.getNum(5)},getNum:function(r){for(var i=[],n=0;n<r;n++){var a=Math.floor(16*Math.random());i[n]=a.toString(16)}return i.join("")},getCurDomain:function(){return location&&location.hostname||""},getSrcType:function(r,i){var n=location&&location.host||"";if(!n)return"";var a=new URL(r).host;if(a===n)return"self";for(var o=0;o<i.length;o+=1)if(a.includes(i[o]))return"cdn";return"others"},parseFetchHeaders:function(r){if(!r)return{};var i={};try{if(typeof r.keys=="function")for(var n=r.keys(),a=n.next();!a.done;){var o=a.value;i[o]=r.get(o),a=n.next()}else i=r}catch(u){i={}}return i},parseXhrHeaders:function(r){if(!r&&typeof r!="string")return{};var i={};try{var n=r.split(`\r
2
2
  `);i=n.reduce(function(a,o){var u=o.split(": ");return a[u[0]]=u[1],a},{})}catch(a){i={}}return i},getQuerys:function(r){if(!r)return"";var i={},n=[],a="",o="";try{var u=[];if(r.indexOf("?")>=0&&(u=r.substring(r.indexOf("?")+1,r.length).split("&")),u.length>0)for(var h in u)a=(n=u[h].split("="))[0],o=n[1],i[a]=o}catch(g){i={}}return i},getURL:function(r){if(!r)return null;var i={},n=r.length,a=r.indexOf("://");if(a<0)return null;i.protocol=r.substring(0,a+1);var o=r.indexOf("#"),u=r.indexOf("?");o<0&&(o=n),u<0&&(u=o),i.search=r.substring(u,o).substring(0,1e3);var h=r.substring(a+3,u),g=h.indexOf("/");return g<0&&(g=h.length),i.domain=h.substring(0,g).split(":")[0],i.path=h.substring(g,h.length).substring(0,1e3),i},getResType:function(r,i){if(["script","img","other"].indexOf(r)>-1)return r;if(["video"].indexOf(r)>-1)return"media";if(["document","iframe"].indexOf(r)>-1)return"doc";var n=i?this.getURL(i):null,a=n&&n.path?n.path.lastIndexOf("."):-1,o=(a>0?n.path.substr(a+1):"").toLowerCase();if(o){if(["eot","woff","woff2","ttf"].indexOf(o)>-1)return"font";if(o==="css")return"css";if(o==="js")return"script"}return["fetch","xmlhttprequest","beacon"].indexOf(r)>-1?"api":"others"},areInOrder:function(){for(var r=1;r<arguments.length;r+=1)if(arguments[r-1]>arguments[r])return!1;return!0},getFetchSnapshot:function(r,i,n){var a,o;try{var u=(r&&typeof r[0]!="string"?r[0].url:r[0])||"",h=(r&&typeof r[0]!="string"?r[0]:r[1])||{},g=h.method.toUpperCase()==="POST"?h.body:this.getQuerys(u);a={originApi:u,method:h.method||"unknown",params:g,response:i||"",reqHeaders:this.parseFetchHeaders(h.headers||null),resHeaders:this.parseFetchHeaders(n)},o=JSON&&JSON.stringify(a)||"{}"}catch(f){o="{}"}return o},getXhrSnapshot:function(r,i,n){if(!r||!i||!n)return{};var a,o;try{var u="";n.responseType===""||n.responseType==="text"?u=n.responseText:n.responseType==="document"&&(u=n.responseXML),a={originApi:r,method:i,params:this.getQuerys(r),response:u,reqHeaders:{},resHeaders:this.parseXhrHeaders(typeof n.getAllResponseHeaders=="function"&&n.getAllResponseHeaders()||"")},o=JSON&&JSON.stringify(a)||"{}"}catch(h){o="{}"}return o},isRobot:function(){var r=["nuhk","googlebot/","googlebot-image","yammybot","openbot","slurp","msnbot","ask jeeves/teoma","ia_archiver","baiduspider","bingbot/","adsbot"];if(!navigator||typeof navigator.userAgent!="string")return!1;try{for(var i=navigator.userAgent.toLowerCase(),n=0;n<r.length;n++){var a=r[n];if(i.lastIndexOf(a)>=0)return!0}}catch(o){this.warn("[arms] useragent parse error")}return!1},isFunction:function(r){return typeof r=="function"},isPlainObject:function(r){return Object.prototype.toString.call(r)==="[object Object]"},isString:function(r){return Object.prototype.toString.call(r)==="[object String]"},isArray:function(r){return Object.prototype.toString.call(r)==="[object Array]"},joinRegExp:function(r){for(var i,n=[],a=0,o=r.length;a<o;a++)i=r[a],this.isString(i)?n.push(i.replace(/([.*+?^=!:${}()|\[\]\/\\])/g,"\\$1")):i&&i.source&&n.push(i.source);return new RegExp(n.join("|"),"i")},reWriteMethod:function(r,i,n){if(r!==null){var a=r[i];r[i]=n(a)}},checkSDKError:function(r,i){return!r&&!i?!1:new RegExp(this.selfErrKey,"i").test(r)?!0:!!this.ignoreByRule(i,[/retcode.alicdn.com\/retcode\/bl.js/,/g.alicdn.com\/retcode\/cloud-sdk\/bl.js/,/laz-g-cdn.alicdn.com\/retcode\/cloud-sdk\/bl.js/,/local.taobao.com:8880\/build\/bl/])},sdkError:function(r){return{msg:r,message:this.selfErrKey}},dealParam:function(r,i,n){var a={};try{a=this.isPlainObject(r)?this.ext({key:r.key||"default",val:r.val||r.value||n},r,{begin:Date.now()}):{key:r||"default",val:i||n,begin:Date.now()}}catch(o){this.warn("[retcode] baseLog error: "+o)}return a}};return qe=t,qe}var Zt={exports:{}},oi={exports:{}},ft,Es;function Na(){if(Es)return ft;Es=1;var s=je();return ft=function(c,e,t){typeof c=="object"&&(c=s.serialize(c));var r=e+c+(t?"&post_res=":"");window&&window.navigator&&typeof window.navigator.sendBeacon=="function"?window.navigator.sendBeacon(r,t||"&post_res="):s.warn("[arms] navigator.sendBeacon not surported")},ft}var ws;function Ma(){if(ws)return oi.exports;ws=1;var s=je(),c=Na(),e="aokcdqn3ly@e629dabd48a9933",t=function(i,n){var a;if(n.t==="error"&&(a=i.requestQueue[0])&&a.t==="error"&&n.msg===a.msg)return n.times=a.times+1,void(i.requestQueue[0]=n);if(n.t==="behavior"){var o=i.requestQueue&&i.requestQueue.length;if(o>0&&i.requestQueue[o-1].t==="behavior"){var u=n.behavior||[];i.requestQueue[o-1].behavior.concat(u)}else i.requestQueue.push(n)}else i.requestQueue.unshift(n);return i.onReady(function(){i.requestTimmer=s.delay(function(){i.clear()},i.requestQueue[0]&&i.requestQueue[0].t==="error"?3e3:-1)}),!0},r=function(i){return this.ver="1.8.36-beta.12",this._conf=s.ext({},r.dftCon),this.sampleCache={},this.requestQueue=[],this.selfQueue=[],this.sdkFlag=!0,this.hash=s.seq(),this.resetPageview(),this.setConfig(i),this.rip=s.getRandIP(),this.record=999,this["EagleEye-TraceID"]=this.getTraceId()["EagleEye-TraceID"],this._common={},this};return r.dftCon={sample:1,pvSample:1,tag:"",imgUrl:"https://arms-retcode.aliyuncs.com/r.png?",region:null,ignore:{ignoreUrls:[],ignoreApis:[],ignoreErrors:[/^Script error\.?$/],ignoreResErrors:[],ignoreResources:[/\/(bl|wl)(.debug)?.js$/]},release:void 0,environment:"prod",beforeReport:null,parseTraceId:null},r.prototype={constructor:r,onReady:function(i){return i()},getPage:function(){var i=this._conf.page;return s.safetyCall(i,[],i+"")},setPage:function(){},setConfig:function(i){i&&typeof i=="object"&&(s.verifyConfig(i),i=this.setImgUrl(i),this._conf=s.ext({},this._conf,i))},setImgUrl:function(i){var n=i.region,a=i.imgUrl;if(n){var o=s.regionMap[n];return i.imgUrl=o||s.defaultImgUrl,i}return a&&(i.imgUrl=a),i},checkImgUrl:function(){return!0},sendRequest:function(){},sendBeacon:function(i,n,a){c(i,n||this.getConfig("imgUrl"),a)},postData:function(){},commonInfo:function(){return{}},setCommonInfo:function(i){i&&typeof i=="object"&&(this._common=s.ext({},this._common,i))},resetPageview:function(){this.pageview=s.uu(),this.sBegin=Date.now()},getUsername:function(){if(this.username)return this.username;var i=this._conf,n=i&&i.setUsername;if(typeof n=="function")try{var a=n();typeof a=="string"&&(a=a.substr(0,40),this.username=a)}catch(o){s.warn("[arms] setUsername fail",o)}return this.username},getTraceId:function(){var i=this.rip,n=Date.now(),a=s.getSortNum(this.record),o=i+n+a+s.getRandNum(this._conf.pid);return this["EagleEye-TraceID"]=o,this.record=a,{"EagleEye-TraceID":o}},getUberTraceId:function(i){var n=this.rip,a=Date.now(),o=s.getSortNum(this.record),u=s.getRandNum(this._conf.pid),h=n+a+o+s.getNum(2)+u,g=h.substring(0,16);return i=i?"1":"0",h[0]==="0"&&(h[0]="1"),h[16]==="0"&&(h[16]="1"),{"uber-trace-id":h+":"+g+":0:"+i,traceId:h}},getB3TraceId:function(i){var n=this.rip,a=Date.now(),o=s.getSortNum(this.record),u=s.getRandNum(this._conf.pid),h=n+a+o+s.getNum(2)+u,g=h.substring(0,16);return i=i?"1":"0",h[0]==="0"&&(h[0]="1"),h[16]==="0"&&(h[16]="1"),{b3:h+"-"+g+"-"+i+"-0","X-B3-TraceId":h,"X-B3-ParentSpanId":"0","X-B3-SpanId":g,"X-B3-Sampled":i}},getPageviewId:function(){return{"EagleEye-SessionID":this.pageview}},getConfig:function(i){return i?this._conf[i]:s.ext({},this._conf)},sampling:function(i){return i===1||(typeof this.sampleCache[i]=="boolean"?this.sampleCache[i]:(this.sampleCache[i]=s.pick(i),this.sampleCache[i]))},clear:function(i){var n;clearTimeout(this.requestTimmer),this.requestTimmer=null;for(var a=this._conf&&typeof this._conf.sendRequest=="function";n=this.requestQueue.pop();)if(n.t==="res")this.postData(n,"res");else if(n.t==="error")this.postData(n,"err");else if(n.t==="api")this.postData(n,"apiSnapshot");else if(n.t==="behavior")this.postData(n,"behavior");else if(n.t==="health"&&!a&&window&&window.navigator&&typeof window.navigator.sendBeacon=="function")this.sendBeacon(n);else if(n.t==="resource"&&!a&&window&&window.navigator&&typeof window.navigator.sendBeacon=="function"){var o=JSON.stringify({resource:n.resource});delete n.resource,this.sendBeacon(n,null,o)}else n.t==="resource"?this.postData(n,"resource"):this.sendRequest(n);return i&&this.clearSelf(),this},clearSelf:function(){var i;for(clearTimeout(this.Timmer),this.Timmer=null;i=this.selfQueue.pop();)this.postData(i,"err");return this},_lg:function(i,n,a,o){var u=this,h=u._conf,g=u.getPage(),f=h.ignore||{},l=f.ignoreErrors,p=f.ignoreResErrors,d=f.ignoreUrls,m=f.ignoreApis;if(u._isRobot||s.ignoreByRule(g,d)||s.ignoreByRule(s.decode(g),d)||i==="error"&&(s.ignoreByRule(n.msg,l)||s.ignoreByRule(s.decode(n.msg),l))||i==="resourceError"&&(s.ignoreByRule(n.src,p)||s.ignoreByRule(s.decode(n.src),p))||i==="api"&&(s.ignoreByRule(n.api,m)||s.ignoreByRule(s.decode(n.api),m))||!u.checkImgUrl(h.imgUrl)||!n||h.disabled||!h.pid||o===0)return u;var x=n.dl;if(delete n.dl,n=s.ext({t:i,times:1,page:g,tag:h.tag||"",release:h.release||"",environment:h.environment,begin:Date.now(),c1:h.c1,c2:h.c2,c3:h.c3},n,u.commonInfo(),u._common,{pid:h.pid,_v:u.ver,pv_id:u.pageview,username:u.getUsername(),sampling:a||1,dl:x,z:s.seq()}),s.T(h.beforeReport)==="Function")try{if(!(n=h.beforeReport(n)))return u}catch(v){return u}return o===1?t(u,n):a&&!u.sampling(a)?u:t(u,n)},_self:function(i,n,a){var o=this,u=o._conf;if(i!=="error"||!o.checkImgUrl(u.imgUrl)||!n||u.disabled||!u.pid||!e||a&&!o.sampling(a))return o;n=s.ext({t:i,times:1,page:s.selfErrPage,tag:u.pid,begin:Date.now()},n,{pid:e,_v:o.ver,sampling:a||1,z:s.seq()});var h=o.selfQueue[0];if(h){h.times++;try{h.err&&n.err&&h.err.msg_raw&&n.err.msg_raw&&h.err.msg_raw.split("&").indexOf(n.err.msg_raw)<0&&h.err.msg_raw.length<1e3&&(h.err.msg_raw+="&"+n.err.msg_raw)}catch(g){}}else o.selfQueue.unshift(n),o.onReady(function(){o.sdkFlag&&(o.sdkFlag=!1,o.Timmer=s.delay(function(){o.clearSelf()},1e4))})},custom:function(i,n){if(!i||typeof i!="object")return this;var a=!1,o={begin:Date.now()};return s.each(i,function(u,h){return!(a=h&&h.length<=20)&&s.warn("[retcode] invalid key: "+h),o["x-"+h]=u,a}),a?this._lg("custom",o,n||1):this}},oi.exports=r,oi.exports}var Cs;function Fa(){if(Cs)return Zt.exports;Cs=1;var s=je(),c=Ma(),e=["api","success","time","code","msg","trace","traceId","begin","pv_id","sid","seq","domain","flag","apiSnapshot","tag","c1","c2","c3"],t=function(i){var n=(i.key||"default").split("::");return n.length>1?s.ext(i,{group:n[0],key:n[1]}):s.ext(i,{group:"default_group",key:n[0]})},r=function(i){c.call(this,i);var n;try{n=typeof performance=="object"?performance.timing.fetchStart:Date.now()}catch(a){n=Date.now()}return this._startTime=n,this};return r.prototype=s.createObject(c.prototype),s.ext(c.dftCon,{startTime:null}),s.ext(r.prototype,{constructor:r,_super:c,sum:function(i,n,a){try{var o=s.dealParam(i,n,1);return this._lg("sum",t(o),a)}catch(u){s.warn("[retcode] can not get parseStatData: "+u)}},avg:function(i,n,a){try{var o=s.dealParam(i,n,0);return this._lg("avg",t(o),a)}catch(u){s.warn("[retcode] can not get parseStatData: "+u)}},percent:function(i,n,a,o){try{return this._lg("percent",t({key:i,subkey:n,val:a||0,begin:Date.now()}),o)}catch(u){s.warn("[retcode] can not get parseStatData: "+u)}},msg:function(i,n){if(i&&!(i.length>180))return this.custom({msg:i},n)},error:function(i,n){if(!i)return s.warn("[retcode] invalid param e: "+i),this;arguments.length===1?(typeof i=="string"&&(i={message:i},n={}),typeof i=="object"&&(n=i=i.error||i)):(typeof i=="string"&&(i={message:i}),typeof n!="object"&&(n={}));var a=i.name||"CustomError",o=i.message||"",u=i.stack||"";n=n||{};var h=typeof location=="object"&&typeof location.href=="string"&&location.href.substring(0,500)||"";if(s.checkSDKError(o,n.filename)){var g=/^Script error\.?$/,f=i.msg||i.message;if(s.ignoreByRule(f,g)||s.ignoreByRule(s.decode(f),g))return this;var l={msg:s.selfErrKey,err:{msg_raw:s.encode(i.msg||i.message)}};return this._self("error",l,1)}for(var p={begin:Date.now(),cate:a,msg:o&&o.substring(0,1e3),stack:u&&u.substring(0,1e3),file:s.removeUrlSearch(n.filename||""),line:n.lineno||"",col:n.colno||"",err:{msg_raw:s.encode(o),stack_raw:s.encode(u)},dl:h},d=["tag","c1","c2","c3"],m=0;m<d.length;m++){var x=d[m];n[x]&&(p[x]=n[x])}var v=(this.getConfig("ignore")||{}).ignoreErrors;return s.ignoreByRule(p.msg,v)||s.ignoreByRule(s.decode(p.msg),v)?this:(this.beforeSend&&this.beforeSend("error",p),this._lg("error",p,1))},behavior:function(i){if(i){var n=typeof i=="object"&&i.behavior?i:{behavior:i};return this.beforeSend&&this.beforeSend("behavior",n),this._lg("behavior",n,1)}},api:function(i,n,a,o,u,h,g,f,l,p,d,m,x,v,b,y){if(!i)return s.warn("[retcode] api is null"),this;if(i=typeof i=="string"?{api:i,success:n,time:a,code:o,msg:u,begin:h,traceId:g,pv_id:f,apiSnapshot:l,domain:p,flag:m,tag:x,c1:v,c2:b,c3:y}:s.sub(i,e),!s.checkAPI(i.api,!0))return this;i.code=i.code||"";var E=i.msg||"";if(E=typeof E=="string"?E.substring(0,1e3):E,i.msg=E,i.success=i.success?1:0,i.time=+i.time,i.begin=i.begin,i.traceId=i.traceId||"",i.pv_id=i.pv_id||"",i.domain=i.domain||"",i.flag=i.flag,i.dl=typeof location=="object"&&typeof location.href=="string"&&location.href.substring(0,500)||"",i.apiSnapshot&&(typeof i.apiSnapshot=="object"&&(i.apiSnapshot=JSON.stringify(i.apiSnapshot)),typeof i.apiSnapshot!="string"&&delete i.apiSnapshot,i.apiSnapshot.length>2e3&&(i.apiSnapshot=i.apiSnapshot.substring(0,2e3))),d&&(i.traceOrigin=d),!i.api||isNaN(i.time))return s.warn("[retcode] invalid time or api"),this;var I=(this.getConfig("ignore")||{}).ignoreApis;return s.ignoreByRule(i.api,I)||s.ignoreByRule(s.decode(i.api),I)?this:i.time<0?this:(this.beforeSend&&this.beforeSend("api",i),this._lg("api",i,i.success&&this.getConfig("sample"),i.flag))},speed:function(i,n,a){var o=this,u=this.getConfig("startTime")||this._startTime;return/^s(\d|1[0])$/.test(i)?(n=typeof n!="number"?Date.now()-u:n>=u?n-u:n,o.speedCache=o.speedCache||{},o.speedCache[i]=n,o.speedCache.begin=u,clearTimeout(o.speedTimmer),o.speedTimmer=setTimeout(function(){a||(o.speedCache.page=o.getPage(!0)),o._lg("speed",o.speedCache),o.speedCache=null},5e3),o):(s.warn("[retcode] invalid point: "+i),o)},performance:function(i){if(i&&typeof i=="object"&&!this.hasSendPerf){var n={},a={},o=this.getConfig("autoSendPerf");if(i.autoSend&&o)return a=s.ext(this.perfData||{},i),this.hasSendPerf=!0,this._lg("perf",a,this.getConfig("sample"));if(i.autoSend&&!o)return delete i.autoSend,this.perfData?(a=s.ext(this.perfData||{},i),this.hasSendPerf=!0,this._lg("perf",a,this.getConfig("sample"))):void(this.perfData=i);for(var u in i)(/^t([1-9]|1[0])$/.test(u)||u==="ctti"||u==="cfpt")&&(n[u]=i[u]);if(i.autoSend===!0||!o&&(o||this.perfData))return i.autoSend!==!0&&o===!1&&this.perfData?(n=s.ext(this.perfData||{},n),this.hasSendPerf=!0,this._lg("perf",n,this.getConfig("sample"))):void 0;this.perfData=s.ext(this.perfData||{},n)}},resource:function(i,n){if(!i||!s.isPlainObject(i))return s.warn("[arms] invalid param data: "+i),this;var a=Object.keys(i),o=["begin","dom","load","res","dl"],u=!1;for(var h in o)if(a.indexOf(o[h])<0){u=!0;break}if(u)return s.warn("[arms] lack param data: "+i),this;var g={begin:i.begin||Date.now(),dom:i.dom||"",load:i.load||"",res:s.isArray(i.res)?JSON.stringify(i.res):JSON.stringify([]),dl:i.dl||""};return this._lg("res",g,n)},event:function(i,n){if(typeof i=="object"&&i&&i.key){var a={},o=["key","success","time","c1","c2","c3"];for(var u in i)o.indexOf(u)>-1&&(a[u]=i[u]);a.success=i.success===!1?0:1,this._lg("event",a,n)}}}),r._super=c,r._root=c,c.Reporter=r,Zt.exports=r,Zt.exports}var Gi={exports:{}},Is;function Oa(){if(Is)return Gi.exports;Is=1;var s=je(),c=typeof window=="object"?window:{},e="catch",t=c.__oFetch_||c.fetch;return t=typeof t=="function"?t:void 0,Gi.exports=function(r,i){var n=-1;typeof r=="object"&&(n=r.z,r=s.serialize(r));var a=i+r;if(t)return t(a,{method:"HEAD",mode:"no-cors"})[e](s.noop);if(c.document&&c.document.createElement){var o="__request_hold_"+n,u=c[o]=new Image;u.onload=u.onerror=function(){c[o]=void 0},u.src=a,u=null}},Gi.exports}var Ji={exports:{}},Rs;function Va(){if(Rs)return Ji.exports;Rs=1;var s=je(),c=typeof window=="object"?window:{},e=c.__oXMLHttpRequest_||c.XMLHttpRequest;return e=typeof e=="function"?e:void 0,Ji.exports=function(t,r){try{var i=new e;i.open("POST",r,!0),i.setRequestHeader("Content-Type","text/plain"),i.send(JSON.stringify(t))}catch(n){s.warn(`[retcode] Failed to log, exception is :
3
3
  `+n)}},Ji.exports}var Xi,ks;function Ua(){if(ks)return Xi;ks=1;var s=je();return Xi=function(c,e){var t=[],r=null,i=e&&e.location&&e.location.href,n=void 0,a=null,o=function(f,l,p){if(f!==null){var d=f[l];f[l]=p(d)}},u=function(f){var l,p,d,m,x,v=[];if(!f||typeof f.tagName!="string")return"";if(v.push(f.tagName.toLowerCase()),typeof f.id=="string"&&v.push("#".concat(f.id)),typeof(l=f.className)=="string")for(p=l.split(/\s+/),x=0;x<p.length;x++)v.push(".".concat(p[x]));var b=["type","name","title","alt","data-arms-attr"];for(x=0;x<b.length;x++)d=b[x],typeof(m=f.getAttribute(d))=="string"&&v.push("[".concat(d,'="').concat(m,'"]'));return v.join("")},h=function(f,l){return function(p){if(p&&p!==a){a=p;var d;try{d=p.target}catch(x){d="<unknown>"}if(d.length!==0){var m={type:"ui.".concat(f),data:{message:function(x){if(!x||x.nodeType!==1)return"";for(var v=x||null,b=[],y=0,E=0,I=3,C="";v&&y++<5&&!((C=u(v))==="html"||y>1&&E+b.length*I+C.length>=80);)b.push(C),E+=C.length,v=v.parentNode;return b.reverse().join(" > ")}(d)},timestamp:Date.now()};f==="click"?r&&r.addBehavior(m):f==="keypress"&&(n||r&&r.addBehavior(m),clearTimeout(n),n=setTimeout(function(){n=void 0},100))}}}},g=function(){if(function(){var d=e&&e.chrome,m=d&&d.app&&d.app.runtime,x="history"in e&&!!e.history.pushState&&!!e.history.replaceState;return!m&&x}()){var f=function(d,m){var x={type:"navigation",data:{from:d,to:m}};r&&r.addBehavior(x),i=m},l=e.onpopstate;e.onpopstate=function(){for(var d=arguments.length,m=new Array(d),x=0;x<d;x++)m[x]=arguments[x];var v=e.location.href;if(f(i,v),l)return l.apply(this,m)};var p=function(d){return function(){for(var m=arguments.length,x=new Array(m),v=0;v<m;v++)x[v]=arguments[v];var b=x.length>2?x[2]:void 0;return b&&f(i,String(b)),d.apply(this,x)}};o(e.history,"pushState",p),o(e.history,"replaceState",p)}};s.ext(c.prototype,{addBehavior:function(f){if(this.getConfig("behavior")&&f&&typeof f=="object"){var l={},p=f.data||{};if(f.type)l=p;else{if(typeof p.name!="string"||typeof p.message!="string")return;l.name=p.name.substr(0,20),l.message=p.message.substr(0,200)}l.message&&(l.message=s.encode(l.message));var d={type:f.type||"custom",data:l||{},timestamp:f.timestamp||Date.now(),page:f.page||e&&e.location&&e.location.pathname};return t.push(d),t=t.slice(-100)}},getBehavior:function(){return t||[]},setBehavior:function(f){return f&&(t=f),t},reportBehavior:function(f){var l=this;l.getConfig("behavior")&&(l.sendBhTimer&&(clearTimeout(l.sendBhTimer),l.sendBhTimer=void 0),l.sendBhTimer=setTimeout(function(){t&&t.length>0&&(l.behavior(t),t=[],l.sendBhTimer=void 0,f&&typeof f=="function"&&f())},0))},initBehavior:function(){if(!this.hasInitBehavior&&!r){try{(function(){if(document&&document.referrer&&document.location){var l=document.referrer,p=document.location.href;if(l!==""){var d={type:"navigation",data:{from:l,to:p}};i=p,r&&r.addBehavior(d)}}})(),e&&e.document&&e.document.addEventListener&&(e.document.addEventListener("click",h("click"),!1),e.document.addEventListener("keypress",h("keypress"),!1)),g();var f=this.getConfig("enableConsole");f&&function(l){if(e&&e.console){var p=["debug","info","warn","log","error","assert"];s.isArray(l)&&(p=l);for(var d=0;d<p.length;d++){var m=p[d];m&&s.isString(m)&&e.console[m]&&typeof e.console[m]=="function"&&o(e.console,m,function(x){var v=m;return function(){for(var b=arguments.length,y=new Array(b),E=0;E<b;E++)y[E]=arguments[E];var I={type:"console",data:{level:v,message:y}};if(r&&r.addBehavior(I),v==="error")for(var C=0;C<y.length;C++){var R=y[C];R&&R.message&&R.stack&&r&&r.errorHandler(new ErrorEvent("error",{error:R,message:R.message}))}x&&Function.prototype.apply.call(x,e.console,y)}})}}}(f)}catch(l){s.warn("[arms] error in initBehavior",l)}r=this,this.hasInitBehavior=!0}return this}})},Xi}var Ds={},Ts;function Zi(){return Ts||(Ts=1,Ds.TIMING_KEYS=["startTime","fetchStart","domainLookupStart","domainLookupEnd","connectStart","connectEnd","requestStart","responseStart","responseEnd","","domInteractive","","domContentLoadedEventEnd","","loadEventStart","","msFirstPaint","secureConnectionStart","redirectStart","redirectEnd"]),Ds}var Yi,Bs;function za(){if(Bs)return Yi;Bs=1;var s=je(),c=Zi(),e=c.TIMING_KEYS;return Yi=function(){var t=s.win||{},r=t.performance;if(!r||typeof r!="object"||typeof r.getEntriesByType!="function")return null;var i={},n=r.timing||{},a=r.getEntriesByType("resource")||[];if(i.begin=n[e[1]]||Date.now(),typeof t.PerformanceNavigationTiming=="function"){var o=r.getEntriesByType("navigation")[0];o&&(n=o)}return s.each({dom:[10,8],load:[14,1]},function(u,h){var g=n[e[u[1]]],f=n[e[u[0]]];if(g>0&&f>0){var l=Math.round(f-g);l>=0&&l<6e5&&(i[h]=l)}}),i.res=JSON.stringify(a),i},Yi}var Qi,Ps;function Ha(){if(Ps)return Qi;Ps=1;var s=je(),c=Zi(),e=c.TIMING_KEYS;return Qi=function(){var t=s.win||{},r=t.performance;if(!r||typeof r!="object")return null;var i={},n=r.timing||{},a=Date.now(),o=1;if(typeof t.PerformanceNavigationTiming=="function"){var u=r.getEntriesByType("navigation")[0];u&&(n=u,o=2)}s.each({dns:[3,2],tcp:[5,4],ssl:[5,17],ttfb:[7,6],trans:[8,7],dom:[10,8],res:[14,12],firstbyte:[7,2],fpt:[8,1],tti:[10,1],ready:[12,1],load:[14,1]},function(p,d){var m=n[e[p[1]]],x=n[e[p[0]]];if(o===2||m>0&&x>0){var v=Math.round(x-m);v>=0&&v<6e5&&(i[d]=v)}});var h=t.navigator.connection,g=r.navigation||{};i.ct=h?h.effectiveType||h.type:"";var f=h&&(h.downlink||h.downlinkMax||h.bandwidth)||null;if((f=f>999?999:f)&&(i.bandwidth=f),i.navtype=g.type===1?"Reload":"Other",o===1&&n[e[16]]>0&&n[e[1]]>0){var l=n[e[16]]-n[e[1]];l>=0&&l<36e5&&(i.fpt=l)}return o===1&&n[e[1]]>0?i.begin=n[e[1]]:o===2&&i.load>0?i.begin=a-i.load:i.begin=a,i},Qi}var Ls,Ns;function ja(){return Ns||(Ns=1,Ls=function(s,c,e){var t=je(),r=za(),i=Ha(),n=null,a=e.documentElement,o=c.innerWidth||a.clientWidth||e.body.clientWidth,u=c.innerHeight||a.clientHeight||e.body.clientHeight,h=c.navigator.connection,g={sr:screen.width+"x"+screen.height,vp:o+"x"+u,ct:h?h.effectiveType||h.type:""},f={},l=function(d,m,x,v,b){if(m===void 0){var y,E;if(!f[d]){y=new RegExp(d+"=([^;]+)");try{E=y.exec(e.cookie)}catch(C){return t.warn("[retcode] can not get cookie:",C),null}E&&(f[d]=E[1])}return f[d]}var I=d+"="+m;I+="; path=/",x&&(I+="; max-age="+x);try{return e.cookie=I,!!e.cookie}catch(C){return t.warn("[retcode] can not set cookie: ",C),!1}},p=function(d){var m=d._conf.uid||l("_nk_")||l("_bl_uid");return!m&&(m=t.uu(),!l("_bl_uid",m,15552e3))?null:m};return t.ext(s.prototype,{activeErrHandler:function(d){return n&&!d?this:(n=this,this)},errorHandler:function(d){if(!d)return this;var m=d.type;if(m==="error"){var x=d.target||d.srcElement;!x||!x.tagName||d.message||d.filename||d.lineno||d.colno?this.error(d.error||{message:d.message},d):this.resourceErrorHandler(d)}else m==="unhandledrejection"&&t.T(d.reason,"Error")&&t.checkAutoError(d.reason)&&this.error(d.reason);try{this.getConfig("behavior")&&this.reportBehavior&&this.reportBehavior()}catch(v){}return this},resourceErrorHandler:function(d){var m=this,x=d.target||d.srcElement;try{var v=m.getSrc(x),b=typeof x.tagName=="string"?x.tagName.toLowerCase():"",y=m.getXPath(x,5),E=t.getURL(v),I={src:v&&v.substring(0,1e3),node_name:b,xpath:y,res_type:t.getResType(b,v),res_name:E.path,domain:E.domain};return m._conf.enableResource&&m.fixResourceStatus&&d.timeStamp&&m.fixResourceStatus({src:v,node_name:b,res_type:t.getResType(b,v),timeStamp:d.timeStamp,domain:E.domain}),m._lg("resourceError",I),m}catch(C){return t.warn("[ARMS] resourceErrorHandler error :",C),m}},getSrc:function(d){var m=d.src||d.href;try{if(!m){var x=(typeof d.tagName=="string"?d.tagName.toLowerCase():"")==="object",v=d.getAttribute("classid")&&d.getAttribute("classid").toLowerCase()==="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"||d.getAttribute("type")==="application/x-shockwave-flash";x&&v&&(m=d.getAttribute("data")||d.getAttribute("codebase")),m||(m=d.outerHTML||d.innerHTML)}}catch(b){m=""}return m},getXPath:function(d,m){var x=d.id?"#"+d.id:"",v=typeof d.className=="string"?"."+d.className.split(" ").join("."):"",b=(typeof d.tagName=="string"?d.tagName.toLowerCase():"")+x+v;return d.parentNode&&d.parentNode.tagName&&m-1!=0?this.getXPath(d.parentNode,m-1)+" > "+b:b},sendPerformance:function(d){var m=this;m.onReady(function(){var x=i();x&&x.load&&x.load>0&&(x.page=m.getPage(!0),d&&(x=t.ext(x,d)),x.autoSend=!0,m.performance(x))})},sendResources:function(d){var m=this;m.onReady(function(){var x=r();x&&x.load&&x.load>0&&(x.load&&x.load<=2e3||x.load&&x.load<=8e3&&Math.random()>.05||(x.page=m.getPage(!0),x.dl=location.href,d&&(x=t.ext(x,d)),m._lg("res",x,m.getConfig("sample"))))})},sendPV:function(){var d=this;d.onReady(function(){var m=function(x){var v=p(x),b=c.devicePixelRatio||1;return{uid:v,dt:e.title,dl:location.href,dr:e.referrer,dpr:b.toFixed(2),de:(e.characterSet||e.defaultCharset||"").toLowerCase(),ul:a.lang,begin:Date.now()}}(d);m&&m.uid&&d._lg("pv",m,d.getConfig("pvSample"))})},commonInfo:function(){return g.uid=p(this),g.sid=function(d){if(d.session)return d.session;var m;try{if(typeof window=="object"&&typeof sessionStorage=="object"&&typeof sessionStorage.getItem=="function")return typeof(m=sessionStorage.getItem("_bl_sid"))=="string"?(d.session=m,m):(m=t.uu(),d.session=m,typeof sessionStorage.setItem=="function"&&sessionStorage.setItem("_bl_sid",m),m)}catch(x){t.warn("[ARMS] getSid error :",x)}return d.session=m=t.uu(),m}(this),g},handleUnload:function(d){var m=Date.now();if(m-this._lastUnload<200)return this;this._lastUnload=m,this.sendHealth(d),this.speedCache&&(this._lg("speed",this.speedCache),this.speedCache=null,clearTimeout(this.speedTimmer)),this._conf&&this._conf.enableResource&&this.resourceComboReport(),this.clear(!0)},bindHashChange:function(d){var m=this;if(!d^m.hashChangeHandler)return m;d?(m.hackHistoryState(),m.hashChangeHandler=function(x){var v=m._conf.parseHash(location.hash);v&&m.setPage(v,x!==!1)},m.stateChangeHandler=function(x){var v=m._conf.parseHash(x.detail);v&&m.setPage(v)},t.on(c,"hashchange",m.hashChangeHandler),t.on(c,"historystatechange",m.stateChangeHandler),m.hashChangeHandler(!1)):(t.off(c,"hashchange",m.hashChangeHandler),t.off(c,"historystatechange",m.stateChangeHandler),m.hashChangeHandler=null,m.stateChangeHandler=null)},initHandler:function(){var d=this;if(d.hasInitHandler)return d;var m=d._conf;return t.on(c,"beforeunload",function(){d.handleUnload(0)}),d.bindHashChange(m.enableSPA),d.activeErrHandler(!1),d.hasInitHandler=!0,d}}),t.on(c,"error",function(d){n&&n.errorHandler(d)},!1,!0).on(c,"unhandledrejection",function(d){n&&n.errorHandler(d)}),s}),Ls}var er,Ms;function Wa(){if(Ms)return er;Ms=1;var s=je(),c=500;return er=function(e,t,r){function i(g,f,l){var p=0,d=g.tagName;if(d!=="SCRIPT"&&d!=="STYLE"&&d!=="META"&&d!=="HEAD"){var m=g.children?g.children.length:0;if(m>0)for(var x=g.children,v=m-1;v>=0;v--)p+=i(x[v],f+1,p>0);if(p<=0&&!l&&!(g.getBoundingClientRect&&g.getBoundingClientRect().top<a))return 0;p+=1+.5*f}return p}function n(g){for(var f=1;f<g.length;f++)if(g[f].score<g[f-1].score)return g.splice(f,1),n(g);return g}var a=t.innerHeight||0,o=[],u=null,h=0;s.ext(e.prototype,{initFmpObserver:function(g){var f=this;if(!f._conf||!f._conf.useFmp)return null;if(!t.MutationObserver)return s.warn("[retcode] first meaningful paint can not be retrieved"),f.sendPerformance(),null;s.on(t,"beforeunload",function(){f.endObserving(0,!0)});var l=t.MutationObserver;return(u=new l(function(){(function(p){var d=Date.now()-p,m=r.querySelector("body");if(m){var x=0;x+=i(m,1,!1),o.push({score:x,t:d})}else o.push({score:0,t:d})})(f._startTime)})).observe(document,{childList:!0,subtree:!0}),h=1,f.onReady(function(){f.endObserving(g)}),u},endObserving:function(g,f){var l=this;if(u&&h)if(l.fmpTimmer&&(clearTimeout(l.fmpTimmer),l.fmpTimmer=null),f||!function(x,v){var b=Date.now()-x;return!(b>v||b-(o&&o.length&&o[o.length-1].t||0)>2*c)}(l._startTime,g)){u.disconnect(),h=0,o=n(o);for(var p=null,d=1;d<o.length;d++)if(o[d].t>=o[d-1].t){var m=o[d].score-o[d-1].score;(!p||p.rate<=m)&&(p={t:o[d].t,rate:m})}p&&p.t>0&&p.t<36e5?l.sendPerformance({fmp:p.t}):l.sendPerformance()}else l.fmpTimmer=s.delay(function(){l.endObserving(g)},c)}})},er}var Fs,Os;function Ka(){return Os||(Os=1,Fs=function(s,c){var e=je(),t=null,r=e.getCurDomain(),i=function(h,g,f,l,p,d,m,x,v,b,y,E,I){var C=e.J(p)||null,R=e.safetyCall(g,[C,l],null);if(!R)return!1;var L=R.code||d,k=!("success"in R)||R.success;h.api(f,k,m,L,R.msg,x,v,b,k?{}:y,r,E,I)},n="fetch",a="__oFetch_",o="__oXMLHttpRequest_",u="XMLHttpRequest";return e.ext(s.prototype,{removeHook:function(h,g){return t&&(g||this===t)?(c[a]&&(c[n]=c[a],delete c[a]),c[o]&&(c[u]=c[o],delete c[o]),t=null,this):this},addHook:function(h){return!h&&t?this:(t||(function(){if(typeof c[n]=="function"){var g=c[n];c[a]=g,c[n]=function(f,l){var p=arguments.length===1?[arguments[0]]:Array.apply(null,arguments),d=t;if(!d||!d.api||l&&(l.method==="HEAD"||l.mode==="no-cors"))return g.apply(c,p);l||(l={});var m=Date.now(),x=d._conf,v=e.duration(),b=(f&&typeof f!="string"?f.url:f)||"",y=b;b=e.cutUrlSearch(b);var E=(x.ignore||{}).ignoreApis,I=x.parseTraceId;if(!e.checkAPI(b,!0)||e.ignoreByRule(b,E))return g.apply(c,p);b=e.filterByRule(b,y,x.ignoreApiPath?x.ignoreApiPath:x.apiHelper);var C=x.enableLinkTrace,R="",L="",k=d.getConfig("pid"),M=null,w=d.getConfig("sample"),N=d.getConfig("linkType"),_=1;if(w&&!d.sampling(w)&&(_=0),C){var V="";try{V=location.origin?location.origin:location.protocol+"//"+location.hostname+(location.port?":"+location.port:"")}catch(K){V=""}var ee=e.checkSameOrigin(y,V);if(d.getConfig("enableApiCors")||ee)if(f&&typeof f!="string")try{if(p[0].headers&&typeof p[0].headers.get=="function"&&typeof p[0].headers.append=="function")switch(N){case"arms":var q=p[0].headers.get("EagleEye-TraceID"),re=p[0].headers.get("EagleEye-SessionID"),$=p[0].headers.get("EagleEye-pAppName");q?R=q:(R=d.getTraceId()["EagleEye-TraceID"],p[0].headers.append("EagleEye-TraceID",R)),re?L=re:(L=d.getPageviewId()["EagleEye-SessionID"],p[0].headers.append("EagleEye-SessionID",L)),$||p[0].headers.append("EagleEye-pAppName",k);break;case"b3":var ie=p[0].headers.get("X-B3-TraceId");if(ie)R=ie;else{var T=d.getB3TraceId(_);p[0].headers.append("X-B3-TraceId",T["X-B3-TraceId"]),p[0].headers.append("X-B3-ParentSpanId",T["X-B3-ParentSpanId"]),p[0].headers.append("X-B3-SpanId",T["X-B3-SpanId"]),p[0].headers.append("X-B3-Sampled",T["X-B3-Sampled"]),p[0].headers.append("X-Request-ID",e.guid()),R=T["X-B3-TraceId"]}L=d.pageview;break;case"tracing":default:var B=p[0].headers.get("uber-trace-id");B?R=B.split(":")[0]:(B=d.getUberTraceId(_),p[0].headers.append("uber-trace-id",B["uber-trace-id"]),R=B.traceId),L=d.pageview}}catch(K){e.warn(`[retcode] fetch failed to set header, exception is :
4
- `+K)}else switch(l.headers=l.headers?l.headers:{},N){case"arms":l.headers["EagleEye-TraceID"]?R=l.headers["EagleEye-TraceID"]:(R=d.getTraceId()["EagleEye-TraceID"],l.headers["EagleEye-TraceID"]=R),l.headers["EagleEye-SessionID"]?L=l.headers["EagleEye-SessionID"]:(L=d.getPageviewId()["EagleEye-SessionID"],l.headers["EagleEye-SessionID"]=L),l.headers["EagleEye-pAppName"]||(l.headers["EagleEye-pAppName"]=k);break;case"b3":if(l.headers["X-B3-TraceId"])R=l.headers["X-B3-TraceId"];else{var H=d.getB3TraceId(_);l.headers["X-B3-TraceId"]=H["X-B3-TraceId"],l.headers["X-B3-ParentSpanId"]=H["X-B3-ParentSpanId"],l.headers["X-B3-SpanId"]=H["X-B3-SpanId"],l.headers["X-B3-Sampled"]=H["X-B3-Sampled"],l.headers["X-Request-ID"]=e.guid(),R=H["X-B3-TraceId"]}L=d.getPageviewId()["EagleEye-SessionID"];break;case"tracing":default:if(l.headers["uber-trace-id"])R=l.headers["uber-trace-id"].split(":")[0];else{var F=d.getUberTraceId(_);l.headers["uber-trace-id"]=F["uber-trace-id"],R=F.traceId}L=d.getPageviewId()["EagleEye-SessionID"]}}return g.apply(c,p).then(function(K){if(!d||!d.api)return K;try{if(!K||typeof K.clone!="function")return K;var Y=K.clone(),ge=Y.headers;if(ge&&typeof ge.get=="function"){var se=ge.get("content-type");if(se&&!/(text)|(json)/.test(se))return K;if(!R){var xe=e.parseFetchHeaders(ge);typeof xe=="object"&&xe["eagleeye-traceid"]&&(R=xe["eagleeye-traceid"],M="response")}}var Re=v();return Y.text().then(function(Ce){if(!R&&e.isFunction(I)){var Me=I(Y,Ce);Me&&e.isString(Me)&&(R=Me)}var ke=e.getFetchSnapshot(p,Ce,ge);Y.ok?i(d,x.parseResponse,b,y,Ce,Y.status||200,Re,m,R,L,ke,M,_):(d.api(b,!1,Re,Y.status||404,Y.statusText,m,R,L,ke,r,M,_),x.enableResource&&t.fixResourceStatus&&t.fixResourceStatus({src:Y.url,res_type:"api"}))}),K}catch(Ce){return e.warn("[ARMS] fetch response error :",Ce),K}}).catch(function(K){if(!d||!d.api)throw K;var Y=v();throw d.api(b,!1,Y,K.name||"Error",K.message,m,R,L,{},r),x.enableResource&&t.fixResourceStatus&&t.fixResourceStatus({src:y,res_type:"api"}),K})},c[n].toString=e.createFakeToString(n)}}(),function(){if(typeof c[u]=="function"){var g,f=c[u];c[o]=f;var l=function(p){var d=new f(p),m=t;if(!m||!m.api||!d.addEventListener)return d;var x,v,b,y,E=d.send,I=d.open,C=d.setRequestHeader,R=m._conf,L=(R.ignore||{}).ignoreApis,k=R.parseTraceId,M=m.getConfig("enableLinkTrace"),w="",N="",_="",V=null,ee=m.getConfig("sample"),q=m.getConfig("linkType"),re=1;return ee&&!m.sampling(ee)&&(re=0),d.open=function($,ie){g=$;var T=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);I.apply(d,T),y=ie||"",b=e.cutUrlSearch(y);var B=!e.checkAPI(b,!0)||e.ignoreByRule(b,L);if(b=b?e.filterByRule(b,y,R.ignoreApiPath?R.ignoreApiPath:R.apiHelper):"",!B&&M){var H="";try{H=location.origin?location.origin:location.protocol+"//"+location.hostname+(location.port?":"+location.port:"")}catch(ge){H=""}var F=e.checkSameOrigin(y,H);if((m.getConfig("enableApiCors")||F)&&C&&typeof C=="function")switch(q){case"arms":w=m.getTraceId()["EagleEye-TraceID"],C.apply(d,["EagleEye-TraceID",w]),N=m.getPageviewId()["EagleEye-SessionID"],C.apply(d,["EagleEye-SessionID",N]),_=m.getConfig("pid"),C.apply(d,["EagleEye-pAppName",_]);break;case"b3":var K=m.getB3TraceId(re);C.apply(d,["X-B3-TraceId",K["X-B3-TraceId"]]),C.apply(d,["X-B3-ParentSpanId",K["X-B3-ParentSpanId"]]),C.apply(d,["X-B3-SpanId",K["X-B3-SpanId"]]),C.apply(d,["X-B3-Sampled",K["X-B3-Sampled"]]),C.apply(d,["X-Request-ID",e.guid()]),w=K["X-B3-TraceId"],N=m.getPageviewId()["EagleEye-SessionID"];break;case"tracing":default:var Y=m.getUberTraceId(re);C.apply(d,["uber-trace-id",Y["uber-trace-id"]]),w=Y.traceId,N=m.getPageviewId()["EagleEye-SessionID"]}}},d.send=function(){x=Date.now(),v=e.duration();var $=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);E.apply(d,$)},e.on(d,"readystatechange",function(){if(b&&d.readyState===4){var $=v(),ie=e.getXhrSnapshot(y,g,d);if(!w){var T=e.parseXhrHeaders(typeof d.getAllResponseHeaders=="function"&&d.getAllResponseHeaders()||"");typeof T=="object"&&T["eagleeye-traceid"]&&(w=T["eagleeye-traceid"],V="response")}if(!w&&e.isFunction(k)){var B=k(d);B&&e.isString(B)&&(w=B)}if(d.status>=200&&d.status<=299){var H=d.status||200;if(typeof d.getResponseHeader=="function"){var F=d.getResponseHeader("Content-Type");if(F&&!/(text)|(json)/.test(F))return}d.responseType&&d.responseType!=="text"?m.api(b,!0,$,H,"",x,w,N,{},r,V,re):i(m,R.parseResponse,b,y,d.responseText,H,$,x,w,N,ie,V,re)}else m.api(b,!1,$,d.status||"FAILED",d.statusText,x,w,N,ie,r,V,re),R.enableResource&&t.fixResourceStatus&&t.fixResourceStatus({src:d.responseURL||y,res_type:"api"})}}),d};l.prototype=f.prototype,e.each(Object.keys(f),function(p){l[p]=f[p]}),c[u]=l,c[u].toString=e.createFakeToString(u)}}()),t=this,this)},initHook:function(){return this.hasInitHook?this:(this.getConfig("disableHook")||this.addHook(),this.hasInitHook=!0,this)}}),s}),Fs}var Vs,Us;function $a(){return Us||(Us=1,Vs=function(s,c){var e=je(),t=c.history||{},r=c.document,i=function(a,o){var u;c.CustomEvent?u=new CustomEvent(a,{detail:o}):((u=r.createEvent("HTMLEvents")).initEvent(a,!1,!0),u.detail=o),c.dispatchEvent(u)},n=function(a){var o=t[a];typeof o=="function"&&(t[a]=function(u,h,g){var f=arguments.length===1?[arguments[0]]:Array.apply(null,arguments),l=location.href,p=o.apply(t,f);if(!g||typeof g!="string"||g===l)return p;try{var d=l.split("#"),m=g.split("#"),x=e.cutUrlSearch(d[0]),v=e.cutUrlSearch(m[0]),b=d[1]&&d[1].replace(/^\/?(.*)/,"$1"),y=m[1]&&m[1].replace(/^\/?(.*)/,"$1");b!==y?i("historystatechange",y):x!==v&&i("historystatechange",v)}catch(E){e.warn("[retcode] error in "+a+": "+E)}return p},t[a].toString=e.createFakeToString(a))};e.ext(s.prototype,{hackHistoryState:function(){return this.hasHackedHistoryState?this:(n("pushState"),n("replaceState"),this.hasHackedHistoryState=!0,this)}})}),Vs}var tr,zs;function qa(){if(zs)return tr;zs=1;var s=je(),c=Zi(),e=c.TIMING_KEYS;return tr=function(t,r){function i(o,u,h){if(o instanceof r.PerformanceResourceTiming&&o.initiatorType){var g=s.getResType(o.initiatorType,o.name),f=u.resourceTypes||[],l=(u.ignore||{}).ignoreResources;if(g&&f.includes(g)&&!s.ignoreByRule(o.name,l)&&!s.ignoreByRule(s.decode(o.name),l)){var p=o[e[0]],d=o[e[1]],m=o[e[2]],x=o[e[3]],v=o[e[4]],b=o[e[5]],y=o[e[6]],E=o[e[7]],I=o[e[8]],C=o[e[18]],R=o[e[19]];if(!h.has(o)&&(!s.areInOrder(p,d,m,x,v,b,y,E,I)||p>E))return;if(C<p&&(C=p),R<p&&(R=d),s.areInOrder(p,C,R,d))return{domain:s.getURL(o.name).domain,res_type:g,src_type:s.getSrcType(o.name,u.cdnHostList),success:1,size:Math.round(o.decodedBodySize),duration:Math.round(o.duration),timeStamp:o.responseEnd,timing:o}}}}var n="_resource-"+Date.now(),a="_resource_error-"+Date.now();s.ext(t.prototype,{initResource:function(){var o=this,u=r.performance,h=r.PerformanceObserver;if(o[a]||(o[a]=new WeakMap),!u||!h||typeof u!="object"||typeof u.getEntriesByType!="function")return null;var g=u.getEntriesByType("resource")||[];return setTimeout(function(){o.setResource(g)},10),new h(function(f){setTimeout(function(){o.setResource(f.getEntries())},10)}).observe({entryTypes:["resource"]}),this.onReady(function(){setTimeout(o.resourceComboReport.bind(o),5e3)}),o},setResource:function(o){var u=this._conf,h=this[a];if(s.isArray(o)&&o.length){this[n]||(this[n]={});for(var g=this[n],f=0,l=o.length;f<l;f+=1){var p=o[f];if(s.checkAPI(p.name,!1)){var d=i(p,u,h);if(d){var m=d.res_type+"-"+d.domain;m in g||(g[m]=[]),g[m].push(d)}}}return this}},fixResourceStatus:function(o){var u=r.performance;if(!u||typeof u.getEntriesByName!="function")return null;var h=this[a];if(!o.src||!s.checkAPI(o.src,!1))return this;var g=o.timeStamp||u.now(),f=u.getEntriesByName(o.src,"resource");return s.each(f,function(l){h.has(l)||g-l.responseEnd<100&&h.set(l,{success:0})}),this},resourceComboReport:function(){var o=this[n]||{},u=this._conf.resourceSlow||2e3,h=this[a];this[n]={};var g=Object.keys(o);if(g.length!==0){var f=[];s.each(g,function(m){var x=o[m],v={domain:"",res_type:"",src_type:"",size:0,duration:0,count:0,err_count:0,err_duration:0,slow_count:0,slow_duration:0,timings:[]};s.each(x,function(b){var y=b.timing||{},E=h.get(b.timing),I=E?E.success:1,C=b.duration>u?1:0;v.domain=b.domain,v.res_type=b.res_type,v.src_type=b.src_type,v.count+=1,v.duration+=b.duration,v.size+=b.size,I||(v.err_count+=1,v.err_duration+=b.duration),C&&(v.slow_count+=1,v.slow_duration+=b.duration);try{var R=JSON.parse(JSON.stringify(y));R.success=I,R.resourceSlow=u,R.isSlow=C,v.timings.push(R)}catch(L){}}),v.count&&(v.size=Math.round(v.size/v.count),v.duration=Math.round(v.duration/v.count)),v.slow_count&&(v.slow_duration=Math.round(v.slow_duration/v.slow_count)),v.err_count&&(v.err_duration=Math.round(v.err_duration/v.err_count)),v.timings.length>20&&(v.timings.sort(function(b,y){return y.duration-b.duration}),v.timings.length=20),v.timings=encodeURIComponent(JSON.stringify(v.timings)),f.push(v)});var l={_combo:1,resource:JSON.stringify(f)},p=r.navigator.connection;l.ct=p?p.effectiveType||p.type:"";var d=p&&(p.downlink||p.downlinkMax||p.bandwidth)||null;(d=d>999?999:d)&&(l.bandwidth=d),this._lg("resource",l,this.getConfig("sample"))}}})},tr}var Hs;function Ga(){if(Hs)return Qe.exports;Hs=1;var s=je(),c=Fa(),e=Oa(),t=Va(),r=s.win,i=r.document,n=/^(error|api|speed|sum|avg|percent|custom|msg|setPage|setConfig|behavior|performance)$/,a=function(o){var u=this;return c.call(u,o),u._initialPage=o.page&&s.safetyCall(o.page,[],o.page+"")||null,u._isRobot=s.isRobot(),u._health={errcount:0,apisucc:0,apifail:0},u.beforeSend=function(h,g){h==="error"?u._health.errcount++:h==="api"&&u._health[g.success?"apisucc":"apifail"]++},o.enableInstanceAutoSend!==!1&&(u.initHandler(),u.initHook(),u.initFmpObserver(1e4),u._conf&&u._conf.behavior&&typeof u.initBehavior=="function"&&u.initBehavior(),u._conf&&u._conf.enableResource&&typeof u.initResource=="function"&&u.initResource()),Object.defineProperty&&r.addEventListener&&Object.defineProperty(u,"pipe",{set:u.sendPipe}),u};return a.prototype=s.createObject(c.prototype),s.ext(c._root.dftCon,{uid:null,setUsername:null,ignoreUrlPath:null,ignoreApiPath:null,urlHelper:[{rule:/\/([a-z\-_]+)?\d{2,20}/g,target:"/$1**"},/\/$/],resourceHelper:[],apiHelper:{rule:/\/([a-z\-_]+)?\d{2,20}/g,target:"/$1**"},ignoreUrlCase:!0,imgUrl:"https://arms-retcode.aliyuncs.com/r.png?",cdnHostList:[],resourceTypes:["css","script","img","font"],resourceSlow:2e3,disableHook:!1,autoSendPv:!0,autoSendPerf:!0,enableSPA:!1,enableLinkTrace:!1,linkType:"arms",enableApiCors:!1,sendResource:!0,behavior:!0,enableConsole:!1,parseHash:function(o){return(o?s.cutUrlSearch(o.replace(/^#\/?/,"")):"")||"[index]"},parseResponse:function(o){if(!o||typeof o!="object")return{};var u=o.code,h=o.msg||o.message||o.subMsg||o.errorMsg||o.ret||o.errorResponse||"";return typeof h=="object"&&(u=u||h.code,h=h.msg||h.message||h.info||h.ret||JSON.stringify(h)),{msg:h,code:u,success:!0}}}),s.ext(a.prototype,{constructor:a,_super:c,onReady:function(o){var u=this;if(u.hasReady)return o();i.readyState==="complete"?(u.hasReady=!0,o()):s.on(r,"load",function(){u.hasReady=!0,o()},!0)},getPage:function(o){var u=this._conf,h=u.page,g=location,f=g.host+g.pathname;return h&&!o?s.safetyCall(h,[],h+""):this._initialPage||s.filterByRule(u.ignoreUrlCase?f.toLowerCase():f,g.href,u.ignoreUrlPath?u.ignoreUrlPath:u.urlHelper)},setPage:function(o,u){var h=this,g=h.prevPage;if(u!==!1){if(!o||o===g)return h;h.prevPage=o,clearTimeout(h.sendPVTimmer),h.handleUnload(1),h.resetPageview(),h.sendPVTimmer=setTimeout(function(){h.sendPV()},10)}else h.prevPage=o;return h._conf.page=o,h},setConfig:function(o,u){if(o&&typeof o=="object"){s.verifyConfig(o),o=this.setImgUrl(o);var h=this._conf;if(this._conf=s.ext({},h,o),!u){var g="disableHook";g in o&&h[g]!==o[g]&&(o[g]?this.removeHook():this.addHook()),(g="enableSPA")in o&&h[g]!==o[g]&&this.bindHashChange(o[g])}}},sendRequest:function(o){e(o,this.getConfig("imgUrl"))},postData:function(o,u){var h={};h[u]=o[u],delete o[u];var g="";typeof o=="object"&&(g=s.serialize(o)),t(h,this.getConfig("imgUrl")+g+"&post_res=")},sendPipe:function(o){var u=this;if(!o||!o.length)return u;try{if(s.T(o[0])==="Array")return s.each(o,function(g){return u.sendPipe(g)});if(s.T(o)!=="Array")return u;var h=o.shift();if(!n.test(h))return u;u[h].apply(u,o)}catch(g){return s.warn("[retcode] error in sendPipe",g),u}},sendHealth:function(){var o=s.ext({},this._health);o.healthy=o.errcount>0?0:1,o.begin=Date.now();var u=o.begin-this.sBegin;o.stay=u,this._lg("health",o,1),this._health={errcount:0,apisucc:0,apifail:0}},createInstance:function(o){o=s.ext({pid:this._conf.pid},o);var u=this.__proto__.constructor(o);return o.page&&u.sendPV(),u}}),Ua()(a,r),ja()(a,r,i),Wa()(a,r,i),Ka()(a,r),$a()(a,r),qa()(a,r),a._super=c,a._root=c._root,c.Browser=a,Qe.exports=a,Qe.exports}var js;function Ja(){if(js)return dt.exports;js=1;function s(a,o){var u=e[r]=new t(a);u.sendPipe(o);var h=u._conf;return h.autoSendPv!==!1&&u.sendPV(),h&&h.useFmp||u.sendPerformance(),h&&h.sendResource&&u.sendResources(),e[i]=!0,u}function c(){if(e[i])return e[r];var a={},o=[];return r in e&&(a=e[r].config||{},o=e[r].pipe||[]),s(a,o)}var e=window,t=e.BrowserLogger=Ga(),r=je().key,i="__hasInitBlSdk";t.singleton=function(a,o){return e[i]?e[r]:s(a,o)},t.createExtraInstance=function(a){a&&typeof a=="object"&&a.enableInstanceAutoSend!==!0&&(a.enableInstanceAutoSend=!1);var o=new t(a),u=o._conf;return u.enableInstanceAutoSend&&(u.autoSendPv!==!1&&o.sendPV(),u&&u.useFmp||o.sendPerformance(),u&&u.sendResource&&o.sendResources()),o};var n=typeof window=="object"&&!!window.navigator;return n&&e[r]&&(t.bl=c()),dt.exports=t,dt.exports}function Xa(){return Ja()}var Za={getArmsLogger:Xa};function Ya(s,c,e){const t=[],r=typeof Object.getOwnPropertyDescriptors=="function"?Object.getOwnPropertyDescriptors(Object.getPrototypeOf(s)):{};for(const n of Object.keys(r))r[n].get&&t.push(n);const i={MediaboxWrapperObjectGetter(n,a){if(typeof a=="string"&&t.indexOf(a)>-1)return xt(n[a],c+1,e);const o={MediaboxWrapperObjectMethod(...u){return xt(n[a](...u),c+1,e)}};return typeof n[a]=="function"?o.MediaboxWrapperObjectMethod:c>10?n[a]:xt(n[a],c+1,e)},MediaboxWrapperObjectSetter(n,a,o){return n[a]=xt(o,c+1,e),!0}};return new Proxy(s,{get:i.MediaboxWrapperObjectGetter,set:i.MediaboxWrapperObjectSetter})}function Qa(s,c,e){const t={MediaboxWrapperFunctionApply(r,i,n){const a=r.apply(i,n);return xt(a,c+1,e)},MediaboxWrapperFunctionGet(r,i){const n=Object.getOwnPropertyDescriptor(r,i);if(n&&!n.writable&&!n.configurable)return r[i];const a={MediaboxWrapperFunctionGet(...o){const u=r[i](...o);return xt(u,c+1,e)}};return typeof r[i]=="function"?a.MediaboxWrapperFunctionGet:xt(r[i],c+1,e)},MediaboxWrapperClassConstructor(r,i){const n=new r(...i);return xt(n,c+1,e)}};return new Proxy(s,{apply:t.MediaboxWrapperFunctionApply,get:t.MediaboxWrapperFunctionGet,construct:t.MediaboxWrapperClassConstructor})}const eo=s=>s!==null&&typeof s=="object",to=s=>Object.prototype.toString.call(s).slice(8,-1),io=s=>Object.isExtensible(s)?to(s)==="Object":!1;function xt(s,c,e){return typeof s=="function"?Qa(s,c+1,e):s instanceof Promise?s.then(t=>xt(t,c+1,e)).catch(t=>(t instanceof Error&&typeof t.stack=="string"&&t.stack.indexOf("MediaboxWrapper")>-1&&e(t),Promise.reject(t))):Array.isArray(s)?s.map(t=>xt(t,c+1,e)):eo(s)&&io(s)?Ya(s,c+1,e):s}const ro="https://arms-retcode-sg.aliyuncs.com/r.png?",so="https://arms-retcode.aliyuncs.com/r.png?",no="https://retcode-us-west-1.arms.aliyuncs.com/r.png?",ao={cn:so,sg:ro,usw:no};class ir{constructor(c){nt(this,"armsLogger"),nt(this,"isReady",!1),nt(this,"isDestroyed",!1),nt(this,"options"),nt(this,"queue",[]),nt(this,"helper",{MediaboxWrapperQueue(n){return new Error(n)},MediaboxWrapperInitiative(n){return new Error(n)}}),this.options=c;const{region:e="cn",env:t="prod"}=c,r=n=>{var a;if(this.isDestroyed)return!1;if(n.c1=(a=this.options.cid)!=null?a:window.location.host,n.c2=ir.version,this.options.customData&&(n.c3=new URLSearchParams(this.options.customData).toString()),n.t==="error"){if(n.file.indexOf("g.alicdn.com/apsara-media-")>-1||n.file.indexOf("g.alicdn.com/thor-server")>-1||n.stack.indexOf("MediaboxWrapper")>-1){let o=n;return this.options.beforeSend&&(o=this.options.beforeSend(n)),this.isReady?o:(o&&this.queue.push(o),!1)}return!1}return n},i=Za.getArmsLogger();this.armsLogger=i.singleton({pid:"e1iftji1w7@7ec1cef2cc88733",tag:c.businessName,release:`${c.businessName}_${c.version}`,imgUrl:ao[e],behavior:!0,sample:1,disableHook:!0,environment:t,beforeReport:r})}static get version(){return"0.10.0"}wrap(c){return this.options.disabled||typeof Proxy>"u"?c:xt(c,0,e=>this.armsLogger.error(e))}updateOptions(c){this.options=Se(Se({},this.options),c)}setReady(){this.isReady=!0,this.queue.length&&this.queue.forEach(c=>{this.armsLogger.error(this.helper.MediaboxWrapperQueue(c.msg),{filename:c.file,lineno:c.line,colno:c.col})})}report(c,e){this.armsLogger.error(this.helper.MediaboxWrapperInitiative(c),e)}destroy(){this.isDestroyed=!0}}for(var Ie=(s=>(s.PullStreamStats="remoteStat",s.RtsSubscribeExceeds="rtsSubscribeExceeds",s.UserJoined="userJoined",s.UserLeft="userLeft",s.Bye="bye",s.MuteAudio="muteAudio",s.UnmuteAudio="unmuteAudio",s.MuteVideo="muteVideo",s.UnmuteVideo="unmuteVideo",s.MuteScreen="muteScreen",s.UnmuteScreen="unmuteScreen",s.Error="error",s))(Ie||{}),et=(s=>(s.Local="local-device-status-change",s.Remote="remote-device-status-change",s))(et||{}),Z=(s=>(s.Audio="sophon_audio",s.VideoLarge="sophon_video_camera_large",s.VideoSmall="sophon_video_camera_small",s.Screen="sophon_video_screen_share",s))(Z||{}),rr=(s=>(s.Audio="rts audio",s.VideoLarge="rts video",s))(rr||{}),Ft=(s=>(s.Add="add",s.Delete="delete",s.Replace="replace",s.Stop="stop",s.UnPublish="unpublish",s))(Ft||{}),Yt=(s=>(s[s.Camera=0]="Camera",s[s.Screen=1]="Screen",s[s.Image=2]="Image",s))(Yt||{}),yi=(s=>(s[s.Microphone=0]="Microphone",s[s.Screen=1]="Screen",s[s.Mixed=2]="Mixed",s))(yi||{}),Be=(s=>(s.InRoom="inRoom",s.Join="join",s.Publish="publish",s.User="user",s.Resume="resume",s))(Be||{}),Ot=(s=>(s[s.MANUAL=0]="MANUAL",s[s.JOINCHANNEL=1]="JOINCHANNEL",s))(Ot||{}),Ge=[],sr=0;sr<256;++sr)Ge.push((sr+256).toString(16).slice(1));function oo(s,c=0){return(Ge[s[c+0]]+Ge[s[c+1]]+Ge[s[c+2]]+Ge[s[c+3]]+"-"+Ge[s[c+4]]+Ge[s[c+5]]+"-"+Ge[s[c+6]]+Ge[s[c+7]]+"-"+Ge[s[c+8]]+Ge[s[c+9]]+"-"+Ge[s[c+10]]+Ge[s[c+11]]+Ge[s[c+12]]+Ge[s[c+13]]+Ge[s[c+14]]+Ge[s[c+15]]).toLowerCase()}var Ai,co=new Uint8Array(16);function uo(){if(!Ai&&(Ai=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Ai))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Ai(co)}var ho=typeof crypto!="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const Ws={randomUUID:ho};function Vt(s,c,e){if(Ws.randomUUID&&!c&&!s)return Ws.randomUUID();s=s||{};var t=s.random||(s.rng||uo)();if(t[6]=t[6]&15|64,t[8]=t[8]&63|128,c){e=e||0;for(var r=0;r<16;++r)c[e+r]=t[r];return c}return oo(t)}var Ei=(s=>(s.prod="rs.rtn.aliyuncs.com",s.pre="prs.rtn.aliyuncs.com",s))(Ei||{});const nr="6.11.8",Ks="web";class At{static getVersionNumber(){let c=nr.split("."),e="";return c.forEach(t=>{t.length===1?e+="0"+t:e+=t}),parseInt(e)}static queryingParam(c){let e=[];if(c)for(let t in c)e.push(t+"="+c[t]);return e.join("&")}static getQueryParams(c){const t=window.location.search.substring(1).split("&");for(let r=0;r<t.length;r++){const i=t[r].split("=");if(decodeURIComponent(i[0])===c)return decodeURIComponent(i[1])}}static createCallid(c=""){const e=Vt();return c&&e&&e.length>c.length?`${c}${e.substring(c.length)}`:e}static checkSubOptionsValid(c){if(c){const{audio:e,video:t,screen:r}=c;if(e===!1&&t===!1&&r===!1)return!1}return!0}static isNetworkAvailable(){return z(this,null,function*(){const c=Ei.prod,{onLine:e}=navigator;if(!e)return!1;try{return yield fetch(`https://${c}/roomserver/v1/ws/version`),!0}catch(t){return!1}})}}var _e=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function $s(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function lo(s){if(s.__esModule)return s;var c=s.default;if(typeof c=="function"){var e=function t(){return this instanceof t?Reflect.construct(c,arguments,this.constructor):c.apply(this,arguments)};e.prototype=c.prototype}else e={};return Object.defineProperty(e,"__esModule",{value:!0}),Object.keys(s).forEach(function(t){var r=Object.getOwnPropertyDescriptor(s,t);Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:function(){return s[t]}})}),e}function ci(s){throw new Error('Could not dynamically require "'+s+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var qs={exports:{}};/*!
4
+ `+K)}else switch(l.headers=l.headers?l.headers:{},N){case"arms":l.headers["EagleEye-TraceID"]?R=l.headers["EagleEye-TraceID"]:(R=d.getTraceId()["EagleEye-TraceID"],l.headers["EagleEye-TraceID"]=R),l.headers["EagleEye-SessionID"]?L=l.headers["EagleEye-SessionID"]:(L=d.getPageviewId()["EagleEye-SessionID"],l.headers["EagleEye-SessionID"]=L),l.headers["EagleEye-pAppName"]||(l.headers["EagleEye-pAppName"]=k);break;case"b3":if(l.headers["X-B3-TraceId"])R=l.headers["X-B3-TraceId"];else{var H=d.getB3TraceId(_);l.headers["X-B3-TraceId"]=H["X-B3-TraceId"],l.headers["X-B3-ParentSpanId"]=H["X-B3-ParentSpanId"],l.headers["X-B3-SpanId"]=H["X-B3-SpanId"],l.headers["X-B3-Sampled"]=H["X-B3-Sampled"],l.headers["X-Request-ID"]=e.guid(),R=H["X-B3-TraceId"]}L=d.getPageviewId()["EagleEye-SessionID"];break;case"tracing":default:if(l.headers["uber-trace-id"])R=l.headers["uber-trace-id"].split(":")[0];else{var F=d.getUberTraceId(_);l.headers["uber-trace-id"]=F["uber-trace-id"],R=F.traceId}L=d.getPageviewId()["EagleEye-SessionID"]}}return g.apply(c,p).then(function(K){if(!d||!d.api)return K;try{if(!K||typeof K.clone!="function")return K;var Y=K.clone(),ge=Y.headers;if(ge&&typeof ge.get=="function"){var se=ge.get("content-type");if(se&&!/(text)|(json)/.test(se))return K;if(!R){var xe=e.parseFetchHeaders(ge);typeof xe=="object"&&xe["eagleeye-traceid"]&&(R=xe["eagleeye-traceid"],M="response")}}var Re=v();return Y.text().then(function(Ce){if(!R&&e.isFunction(I)){var Me=I(Y,Ce);Me&&e.isString(Me)&&(R=Me)}var ke=e.getFetchSnapshot(p,Ce,ge);Y.ok?i(d,x.parseResponse,b,y,Ce,Y.status||200,Re,m,R,L,ke,M,_):(d.api(b,!1,Re,Y.status||404,Y.statusText,m,R,L,ke,r,M,_),x.enableResource&&t.fixResourceStatus&&t.fixResourceStatus({src:Y.url,res_type:"api"}))}),K}catch(Ce){return e.warn("[ARMS] fetch response error :",Ce),K}}).catch(function(K){if(!d||!d.api)throw K;var Y=v();throw d.api(b,!1,Y,K.name||"Error",K.message,m,R,L,{},r),x.enableResource&&t.fixResourceStatus&&t.fixResourceStatus({src:y,res_type:"api"}),K})},c[n].toString=e.createFakeToString(n)}}(),function(){if(typeof c[u]=="function"){var g,f=c[u];c[o]=f;var l=function(p){var d=new f(p),m=t;if(!m||!m.api||!d.addEventListener)return d;var x,v,b,y,E=d.send,I=d.open,C=d.setRequestHeader,R=m._conf,L=(R.ignore||{}).ignoreApis,k=R.parseTraceId,M=m.getConfig("enableLinkTrace"),w="",N="",_="",V=null,ee=m.getConfig("sample"),q=m.getConfig("linkType"),re=1;return ee&&!m.sampling(ee)&&(re=0),d.open=function($,ie){g=$;var T=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);I.apply(d,T),y=ie||"",b=e.cutUrlSearch(y);var B=!e.checkAPI(b,!0)||e.ignoreByRule(b,L);if(b=b?e.filterByRule(b,y,R.ignoreApiPath?R.ignoreApiPath:R.apiHelper):"",!B&&M){var H="";try{H=location.origin?location.origin:location.protocol+"//"+location.hostname+(location.port?":"+location.port:"")}catch(ge){H=""}var F=e.checkSameOrigin(y,H);if((m.getConfig("enableApiCors")||F)&&C&&typeof C=="function")switch(q){case"arms":w=m.getTraceId()["EagleEye-TraceID"],C.apply(d,["EagleEye-TraceID",w]),N=m.getPageviewId()["EagleEye-SessionID"],C.apply(d,["EagleEye-SessionID",N]),_=m.getConfig("pid"),C.apply(d,["EagleEye-pAppName",_]);break;case"b3":var K=m.getB3TraceId(re);C.apply(d,["X-B3-TraceId",K["X-B3-TraceId"]]),C.apply(d,["X-B3-ParentSpanId",K["X-B3-ParentSpanId"]]),C.apply(d,["X-B3-SpanId",K["X-B3-SpanId"]]),C.apply(d,["X-B3-Sampled",K["X-B3-Sampled"]]),C.apply(d,["X-Request-ID",e.guid()]),w=K["X-B3-TraceId"],N=m.getPageviewId()["EagleEye-SessionID"];break;case"tracing":default:var Y=m.getUberTraceId(re);C.apply(d,["uber-trace-id",Y["uber-trace-id"]]),w=Y.traceId,N=m.getPageviewId()["EagleEye-SessionID"]}}},d.send=function(){x=Date.now(),v=e.duration();var $=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);E.apply(d,$)},e.on(d,"readystatechange",function(){if(b&&d.readyState===4){var $=v(),ie=e.getXhrSnapshot(y,g,d);if(!w){var T=e.parseXhrHeaders(typeof d.getAllResponseHeaders=="function"&&d.getAllResponseHeaders()||"");typeof T=="object"&&T["eagleeye-traceid"]&&(w=T["eagleeye-traceid"],V="response")}if(!w&&e.isFunction(k)){var B=k(d);B&&e.isString(B)&&(w=B)}if(d.status>=200&&d.status<=299){var H=d.status||200;if(typeof d.getResponseHeader=="function"){var F=d.getResponseHeader("Content-Type");if(F&&!/(text)|(json)/.test(F))return}d.responseType&&d.responseType!=="text"?m.api(b,!0,$,H,"",x,w,N,{},r,V,re):i(m,R.parseResponse,b,y,d.responseText,H,$,x,w,N,ie,V,re)}else m.api(b,!1,$,d.status||"FAILED",d.statusText,x,w,N,ie,r,V,re),R.enableResource&&t.fixResourceStatus&&t.fixResourceStatus({src:d.responseURL||y,res_type:"api"})}}),d};l.prototype=f.prototype,e.each(Object.keys(f),function(p){l[p]=f[p]}),c[u]=l,c[u].toString=e.createFakeToString(u)}}()),t=this,this)},initHook:function(){return this.hasInitHook?this:(this.getConfig("disableHook")||this.addHook(),this.hasInitHook=!0,this)}}),s}),Fs}var Vs,Us;function $a(){return Us||(Us=1,Vs=function(s,c){var e=je(),t=c.history||{},r=c.document,i=function(a,o){var u;c.CustomEvent?u=new CustomEvent(a,{detail:o}):((u=r.createEvent("HTMLEvents")).initEvent(a,!1,!0),u.detail=o),c.dispatchEvent(u)},n=function(a){var o=t[a];typeof o=="function"&&(t[a]=function(u,h,g){var f=arguments.length===1?[arguments[0]]:Array.apply(null,arguments),l=location.href,p=o.apply(t,f);if(!g||typeof g!="string"||g===l)return p;try{var d=l.split("#"),m=g.split("#"),x=e.cutUrlSearch(d[0]),v=e.cutUrlSearch(m[0]),b=d[1]&&d[1].replace(/^\/?(.*)/,"$1"),y=m[1]&&m[1].replace(/^\/?(.*)/,"$1");b!==y?i("historystatechange",y):x!==v&&i("historystatechange",v)}catch(E){e.warn("[retcode] error in "+a+": "+E)}return p},t[a].toString=e.createFakeToString(a))};e.ext(s.prototype,{hackHistoryState:function(){return this.hasHackedHistoryState?this:(n("pushState"),n("replaceState"),this.hasHackedHistoryState=!0,this)}})}),Vs}var tr,zs;function qa(){if(zs)return tr;zs=1;var s=je(),c=Zi(),e=c.TIMING_KEYS;return tr=function(t,r){function i(o,u,h){if(o instanceof r.PerformanceResourceTiming&&o.initiatorType){var g=s.getResType(o.initiatorType,o.name),f=u.resourceTypes||[],l=(u.ignore||{}).ignoreResources;if(g&&f.includes(g)&&!s.ignoreByRule(o.name,l)&&!s.ignoreByRule(s.decode(o.name),l)){var p=o[e[0]],d=o[e[1]],m=o[e[2]],x=o[e[3]],v=o[e[4]],b=o[e[5]],y=o[e[6]],E=o[e[7]],I=o[e[8]],C=o[e[18]],R=o[e[19]];if(!h.has(o)&&(!s.areInOrder(p,d,m,x,v,b,y,E,I)||p>E))return;if(C<p&&(C=p),R<p&&(R=d),s.areInOrder(p,C,R,d))return{domain:s.getURL(o.name).domain,res_type:g,src_type:s.getSrcType(o.name,u.cdnHostList),success:1,size:Math.round(o.decodedBodySize),duration:Math.round(o.duration),timeStamp:o.responseEnd,timing:o}}}}var n="_resource-"+Date.now(),a="_resource_error-"+Date.now();s.ext(t.prototype,{initResource:function(){var o=this,u=r.performance,h=r.PerformanceObserver;if(o[a]||(o[a]=new WeakMap),!u||!h||typeof u!="object"||typeof u.getEntriesByType!="function")return null;var g=u.getEntriesByType("resource")||[];return setTimeout(function(){o.setResource(g)},10),new h(function(f){setTimeout(function(){o.setResource(f.getEntries())},10)}).observe({entryTypes:["resource"]}),this.onReady(function(){setTimeout(o.resourceComboReport.bind(o),5e3)}),o},setResource:function(o){var u=this._conf,h=this[a];if(s.isArray(o)&&o.length){this[n]||(this[n]={});for(var g=this[n],f=0,l=o.length;f<l;f+=1){var p=o[f];if(s.checkAPI(p.name,!1)){var d=i(p,u,h);if(d){var m=d.res_type+"-"+d.domain;m in g||(g[m]=[]),g[m].push(d)}}}return this}},fixResourceStatus:function(o){var u=r.performance;if(!u||typeof u.getEntriesByName!="function")return null;var h=this[a];if(!o.src||!s.checkAPI(o.src,!1))return this;var g=o.timeStamp||u.now(),f=u.getEntriesByName(o.src,"resource");return s.each(f,function(l){h.has(l)||g-l.responseEnd<100&&h.set(l,{success:0})}),this},resourceComboReport:function(){var o=this[n]||{},u=this._conf.resourceSlow||2e3,h=this[a];this[n]={};var g=Object.keys(o);if(g.length!==0){var f=[];s.each(g,function(m){var x=o[m],v={domain:"",res_type:"",src_type:"",size:0,duration:0,count:0,err_count:0,err_duration:0,slow_count:0,slow_duration:0,timings:[]};s.each(x,function(b){var y=b.timing||{},E=h.get(b.timing),I=E?E.success:1,C=b.duration>u?1:0;v.domain=b.domain,v.res_type=b.res_type,v.src_type=b.src_type,v.count+=1,v.duration+=b.duration,v.size+=b.size,I||(v.err_count+=1,v.err_duration+=b.duration),C&&(v.slow_count+=1,v.slow_duration+=b.duration);try{var R=JSON.parse(JSON.stringify(y));R.success=I,R.resourceSlow=u,R.isSlow=C,v.timings.push(R)}catch(L){}}),v.count&&(v.size=Math.round(v.size/v.count),v.duration=Math.round(v.duration/v.count)),v.slow_count&&(v.slow_duration=Math.round(v.slow_duration/v.slow_count)),v.err_count&&(v.err_duration=Math.round(v.err_duration/v.err_count)),v.timings.length>20&&(v.timings.sort(function(b,y){return y.duration-b.duration}),v.timings.length=20),v.timings=encodeURIComponent(JSON.stringify(v.timings)),f.push(v)});var l={_combo:1,resource:JSON.stringify(f)},p=r.navigator.connection;l.ct=p?p.effectiveType||p.type:"";var d=p&&(p.downlink||p.downlinkMax||p.bandwidth)||null;(d=d>999?999:d)&&(l.bandwidth=d),this._lg("resource",l,this.getConfig("sample"))}}})},tr}var Hs;function Ga(){if(Hs)return Qe.exports;Hs=1;var s=je(),c=Fa(),e=Oa(),t=Va(),r=s.win,i=r.document,n=/^(error|api|speed|sum|avg|percent|custom|msg|setPage|setConfig|behavior|performance)$/,a=function(o){var u=this;return c.call(u,o),u._initialPage=o.page&&s.safetyCall(o.page,[],o.page+"")||null,u._isRobot=s.isRobot(),u._health={errcount:0,apisucc:0,apifail:0},u.beforeSend=function(h,g){h==="error"?u._health.errcount++:h==="api"&&u._health[g.success?"apisucc":"apifail"]++},o.enableInstanceAutoSend!==!1&&(u.initHandler(),u.initHook(),u.initFmpObserver(1e4),u._conf&&u._conf.behavior&&typeof u.initBehavior=="function"&&u.initBehavior(),u._conf&&u._conf.enableResource&&typeof u.initResource=="function"&&u.initResource()),Object.defineProperty&&r.addEventListener&&Object.defineProperty(u,"pipe",{set:u.sendPipe}),u};return a.prototype=s.createObject(c.prototype),s.ext(c._root.dftCon,{uid:null,setUsername:null,ignoreUrlPath:null,ignoreApiPath:null,urlHelper:[{rule:/\/([a-z\-_]+)?\d{2,20}/g,target:"/$1**"},/\/$/],resourceHelper:[],apiHelper:{rule:/\/([a-z\-_]+)?\d{2,20}/g,target:"/$1**"},ignoreUrlCase:!0,imgUrl:"https://arms-retcode.aliyuncs.com/r.png?",cdnHostList:[],resourceTypes:["css","script","img","font"],resourceSlow:2e3,disableHook:!1,autoSendPv:!0,autoSendPerf:!0,enableSPA:!1,enableLinkTrace:!1,linkType:"arms",enableApiCors:!1,sendResource:!0,behavior:!0,enableConsole:!1,parseHash:function(o){return(o?s.cutUrlSearch(o.replace(/^#\/?/,"")):"")||"[index]"},parseResponse:function(o){if(!o||typeof o!="object")return{};var u=o.code,h=o.msg||o.message||o.subMsg||o.errorMsg||o.ret||o.errorResponse||"";return typeof h=="object"&&(u=u||h.code,h=h.msg||h.message||h.info||h.ret||JSON.stringify(h)),{msg:h,code:u,success:!0}}}),s.ext(a.prototype,{constructor:a,_super:c,onReady:function(o){var u=this;if(u.hasReady)return o();i.readyState==="complete"?(u.hasReady=!0,o()):s.on(r,"load",function(){u.hasReady=!0,o()},!0)},getPage:function(o){var u=this._conf,h=u.page,g=location,f=g.host+g.pathname;return h&&!o?s.safetyCall(h,[],h+""):this._initialPage||s.filterByRule(u.ignoreUrlCase?f.toLowerCase():f,g.href,u.ignoreUrlPath?u.ignoreUrlPath:u.urlHelper)},setPage:function(o,u){var h=this,g=h.prevPage;if(u!==!1){if(!o||o===g)return h;h.prevPage=o,clearTimeout(h.sendPVTimmer),h.handleUnload(1),h.resetPageview(),h.sendPVTimmer=setTimeout(function(){h.sendPV()},10)}else h.prevPage=o;return h._conf.page=o,h},setConfig:function(o,u){if(o&&typeof o=="object"){s.verifyConfig(o),o=this.setImgUrl(o);var h=this._conf;if(this._conf=s.ext({},h,o),!u){var g="disableHook";g in o&&h[g]!==o[g]&&(o[g]?this.removeHook():this.addHook()),(g="enableSPA")in o&&h[g]!==o[g]&&this.bindHashChange(o[g])}}},sendRequest:function(o){e(o,this.getConfig("imgUrl"))},postData:function(o,u){var h={};h[u]=o[u],delete o[u];var g="";typeof o=="object"&&(g=s.serialize(o)),t(h,this.getConfig("imgUrl")+g+"&post_res=")},sendPipe:function(o){var u=this;if(!o||!o.length)return u;try{if(s.T(o[0])==="Array")return s.each(o,function(g){return u.sendPipe(g)});if(s.T(o)!=="Array")return u;var h=o.shift();if(!n.test(h))return u;u[h].apply(u,o)}catch(g){return s.warn("[retcode] error in sendPipe",g),u}},sendHealth:function(){var o=s.ext({},this._health);o.healthy=o.errcount>0?0:1,o.begin=Date.now();var u=o.begin-this.sBegin;o.stay=u,this._lg("health",o,1),this._health={errcount:0,apisucc:0,apifail:0}},createInstance:function(o){o=s.ext({pid:this._conf.pid},o);var u=this.__proto__.constructor(o);return o.page&&u.sendPV(),u}}),Ua()(a,r),ja()(a,r,i),Wa()(a,r,i),Ka()(a,r),$a()(a,r),qa()(a,r),a._super=c,a._root=c._root,c.Browser=a,Qe.exports=a,Qe.exports}var js;function Ja(){if(js)return dt.exports;js=1;function s(a,o){var u=e[r]=new t(a);u.sendPipe(o);var h=u._conf;return h.autoSendPv!==!1&&u.sendPV(),h&&h.useFmp||u.sendPerformance(),h&&h.sendResource&&u.sendResources(),e[i]=!0,u}function c(){if(e[i])return e[r];var a={},o=[];return r in e&&(a=e[r].config||{},o=e[r].pipe||[]),s(a,o)}var e=window,t=e.BrowserLogger=Ga(),r=je().key,i="__hasInitBlSdk";t.singleton=function(a,o){return e[i]?e[r]:s(a,o)},t.createExtraInstance=function(a){a&&typeof a=="object"&&a.enableInstanceAutoSend!==!0&&(a.enableInstanceAutoSend=!1);var o=new t(a),u=o._conf;return u.enableInstanceAutoSend&&(u.autoSendPv!==!1&&o.sendPV(),u&&u.useFmp||o.sendPerformance(),u&&u.sendResource&&o.sendResources()),o};var n=typeof window=="object"&&!!window.navigator;return n&&e[r]&&(t.bl=c()),dt.exports=t,dt.exports}function Xa(){return Ja()}var Za={getArmsLogger:Xa};function Ya(s,c,e){const t=[],r=typeof Object.getOwnPropertyDescriptors=="function"?Object.getOwnPropertyDescriptors(Object.getPrototypeOf(s)):{};for(const n of Object.keys(r))r[n].get&&t.push(n);const i={MediaboxWrapperObjectGetter(n,a){if(typeof a=="string"&&t.indexOf(a)>-1)return xt(n[a],c+1,e);const o={MediaboxWrapperObjectMethod(...u){return xt(n[a](...u),c+1,e)}};return typeof n[a]=="function"?o.MediaboxWrapperObjectMethod:c>10?n[a]:xt(n[a],c+1,e)},MediaboxWrapperObjectSetter(n,a,o){return n[a]=xt(o,c+1,e),!0}};return new Proxy(s,{get:i.MediaboxWrapperObjectGetter,set:i.MediaboxWrapperObjectSetter})}function Qa(s,c,e){const t={MediaboxWrapperFunctionApply(r,i,n){const a=r.apply(i,n);return xt(a,c+1,e)},MediaboxWrapperFunctionGet(r,i){const n=Object.getOwnPropertyDescriptor(r,i);if(n&&!n.writable&&!n.configurable)return r[i];const a={MediaboxWrapperFunctionGet(...o){const u=r[i](...o);return xt(u,c+1,e)}};return typeof r[i]=="function"?a.MediaboxWrapperFunctionGet:xt(r[i],c+1,e)},MediaboxWrapperClassConstructor(r,i){const n=new r(...i);return xt(n,c+1,e)}};return new Proxy(s,{apply:t.MediaboxWrapperFunctionApply,get:t.MediaboxWrapperFunctionGet,construct:t.MediaboxWrapperClassConstructor})}const eo=s=>s!==null&&typeof s=="object",to=s=>Object.prototype.toString.call(s).slice(8,-1),io=s=>Object.isExtensible(s)?to(s)==="Object":!1;function xt(s,c,e){return typeof s=="function"?Qa(s,c+1,e):s instanceof Promise?s.then(t=>xt(t,c+1,e)).catch(t=>(t instanceof Error&&typeof t.stack=="string"&&t.stack.indexOf("MediaboxWrapper")>-1&&e(t),Promise.reject(t))):Array.isArray(s)?s.map(t=>xt(t,c+1,e)):eo(s)&&io(s)?Ya(s,c+1,e):s}const ro="https://arms-retcode-sg.aliyuncs.com/r.png?",so="https://arms-retcode.aliyuncs.com/r.png?",no="https://retcode-us-west-1.arms.aliyuncs.com/r.png?",ao={cn:so,sg:ro,usw:no};class ir{constructor(c){nt(this,"armsLogger"),nt(this,"isReady",!1),nt(this,"isDestroyed",!1),nt(this,"options"),nt(this,"queue",[]),nt(this,"helper",{MediaboxWrapperQueue(n){return new Error(n)},MediaboxWrapperInitiative(n){return new Error(n)}}),this.options=c;const{region:e="cn",env:t="prod"}=c,r=n=>{var a;if(this.isDestroyed)return!1;if(n.c1=(a=this.options.cid)!=null?a:window.location.host,n.c2=ir.version,this.options.customData&&(n.c3=new URLSearchParams(this.options.customData).toString()),n.t==="error"){if(n.file.indexOf("g.alicdn.com/apsara-media-")>-1||n.file.indexOf("g.alicdn.com/thor-server")>-1||n.stack.indexOf("MediaboxWrapper")>-1){let o=n;return this.options.beforeSend&&(o=this.options.beforeSend(n)),this.isReady?o:(o&&this.queue.push(o),!1)}return!1}return n},i=Za.getArmsLogger();this.armsLogger=i.singleton({pid:"e1iftji1w7@7ec1cef2cc88733",tag:c.businessName,release:`${c.businessName}_${c.version}`,imgUrl:ao[e],behavior:!0,sample:1,disableHook:!0,environment:t,beforeReport:r})}static get version(){return"0.10.0"}wrap(c){return this.options.disabled||typeof Proxy>"u"?c:xt(c,0,e=>this.armsLogger.error(e))}updateOptions(c){this.options=Se(Se({},this.options),c)}setReady(){this.isReady=!0,this.queue.length&&this.queue.forEach(c=>{this.armsLogger.error(this.helper.MediaboxWrapperQueue(c.msg),{filename:c.file,lineno:c.line,colno:c.col})})}report(c,e){this.armsLogger.error(this.helper.MediaboxWrapperInitiative(c),e)}destroy(){this.isDestroyed=!0}}for(var Ie=(s=>(s.PullStreamStats="remoteStat",s.RtsSubscribeExceeds="rtsSubscribeExceeds",s.UserJoined="userJoined",s.UserLeft="userLeft",s.Bye="bye",s.MuteAudio="muteAudio",s.UnmuteAudio="unmuteAudio",s.MuteVideo="muteVideo",s.UnmuteVideo="unmuteVideo",s.MuteScreen="muteScreen",s.UnmuteScreen="unmuteScreen",s.Error="error",s))(Ie||{}),et=(s=>(s.Local="local-device-status-change",s.Remote="remote-device-status-change",s))(et||{}),Z=(s=>(s.Audio="sophon_audio",s.VideoLarge="sophon_video_camera_large",s.VideoSmall="sophon_video_camera_small",s.Screen="sophon_video_screen_share",s))(Z||{}),rr=(s=>(s.Audio="rts audio",s.VideoLarge="rts video",s))(rr||{}),Ft=(s=>(s.Add="add",s.Delete="delete",s.Replace="replace",s.Stop="stop",s.UnPublish="unpublish",s))(Ft||{}),Yt=(s=>(s[s.Camera=0]="Camera",s[s.Screen=1]="Screen",s[s.Image=2]="Image",s))(Yt||{}),yi=(s=>(s[s.Microphone=0]="Microphone",s[s.Screen=1]="Screen",s[s.Mixed=2]="Mixed",s))(yi||{}),Be=(s=>(s.InRoom="inRoom",s.Join="join",s.Publish="publish",s.User="user",s.Resume="resume",s))(Be||{}),Ot=(s=>(s[s.MANUAL=0]="MANUAL",s[s.JOINCHANNEL=1]="JOINCHANNEL",s))(Ot||{}),Ge=[],sr=0;sr<256;++sr)Ge.push((sr+256).toString(16).slice(1));function oo(s,c=0){return(Ge[s[c+0]]+Ge[s[c+1]]+Ge[s[c+2]]+Ge[s[c+3]]+"-"+Ge[s[c+4]]+Ge[s[c+5]]+"-"+Ge[s[c+6]]+Ge[s[c+7]]+"-"+Ge[s[c+8]]+Ge[s[c+9]]+"-"+Ge[s[c+10]]+Ge[s[c+11]]+Ge[s[c+12]]+Ge[s[c+13]]+Ge[s[c+14]]+Ge[s[c+15]]).toLowerCase()}var Ai,co=new Uint8Array(16);function uo(){if(!Ai&&(Ai=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Ai))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Ai(co)}var ho=typeof crypto!="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const Ws={randomUUID:ho};function Vt(s,c,e){if(Ws.randomUUID&&!c&&!s)return Ws.randomUUID();s=s||{};var t=s.random||(s.rng||uo)();if(t[6]=t[6]&15|64,t[8]=t[8]&63|128,c){e=e||0;for(var r=0;r<16;++r)c[e+r]=t[r];return c}return oo(t)}var Ei=(s=>(s.prod="rs.rtn.aliyuncs.com",s.pre="prs.rtn.aliyuncs.com",s))(Ei||{});const nr="6.11.9-beta.0",Ks="web";class At{static getVersionNumber(){let c=nr.split("."),e="";return c.forEach(t=>{t.length===1?e+="0"+t:e+=t}),parseInt(e)}static queryingParam(c){let e=[];if(c)for(let t in c)e.push(t+"="+c[t]);return e.join("&")}static getQueryParams(c){const t=window.location.search.substring(1).split("&");for(let r=0;r<t.length;r++){const i=t[r].split("=");if(decodeURIComponent(i[0])===c)return decodeURIComponent(i[1])}}static createCallid(c=""){const e=Vt();return c&&e&&e.length>c.length?`${c}${e.substring(c.length)}`:e}static checkSubOptionsValid(c){if(c){const{audio:e,video:t,screen:r}=c;if(e===!1&&t===!1&&r===!1)return!1}return!0}static isNetworkAvailable(){return z(this,null,function*(){const c=Ei.prod,{onLine:e}=navigator;if(!e)return!1;try{return yield fetch(`https://${c}/roomserver/v1/ws/version`),!0}catch(t){return!1}})}}var _e=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function $s(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function lo(s){if(s.__esModule)return s;var c=s.default;if(typeof c=="function"){var e=function t(){return this instanceof t?Reflect.construct(c,arguments,this.constructor):c.apply(this,arguments)};e.prototype=c.prototype}else e={};return Object.defineProperty(e,"__esModule",{value:!0}),Object.keys(s).forEach(function(t){var r=Object.getOwnPropertyDescriptor(s,t);Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:function(){return s[t]}})}),e}function ci(s){throw new Error('Could not dynamically require "'+s+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var qs={exports:{}};/*!
5
5
 
6
6
  JSZip v3.10.1 - A JavaScript class for generating and reading zip files
7
7
  <http://stuartk.com/jszip>
@@ -35,7 +35,7 @@ var H0=Object.defineProperty,j0=Object.defineProperties;var W0=Object.getOwnProp
35
35
  `;const h=(p,d)=>p[0].localeCompare(d[0]),g=p=>p[0].startsWith("x-log-")||p[0].startsWith("x-acs-");try{const p=[...i.entries()].filter(g).sort(h).map(d=>d[0]+":"+d[1]+`
36
36
  `).join("");u+=p}catch(p){}u+=c,r.size>0&&(u+="?");try{u+=[...r.entries()].sort(h).map(p=>p[0]+"="+p[1]).join("&")}catch(p){}const f=ui.HmacSHA1(u,t).toString(ui.enc.Base64),l="LOG "+e+":"+f;return i.set("Authorization",l),i.set("x-log-date",a),l}var _c=(s,c,e)=>new Promise((t,r)=>{var i=o=>{try{a(e.next(o))}catch(u){r(u)}},n=o=>{try{a(e.throw(o))}catch(u){r(u)}},a=o=>o.done?t(o.value):Promise.resolve(o.value).then(i,n);a((e=e.apply(s,c)).next())});function yc(s){return _c(this,null,function*(){const c=new Date;if(s.refreshSTSTokenInterval||(s.refreshSTSTokenInterval=3e5),!s.stsTokenFreshTime||+c-s.stsTokenFreshTime>=s.refreshSTSTokenInterval){s.stsTokenFreshTime=c;try{yield s.refreshSTSToken()}catch(e){typeof console.error=="function"&&console.error(`Some error occured during excuting refreshSTSToken, see:
37
37
  `+e)}}return null})}var Ac=(s,c,e)=>new Promise((t,r)=>{var i=o=>{try{a(e.next(o))}catch(u){r(u)}},n=o=>{try{a(e.throw(o))}catch(u){r(u)}},a=o=>o.done?t(o.value):Promise.resolve(o.value).then(i,n);a((e=e.apply(s,c)).next())});function Xn(s){return{transString:function(c){let e={},t=0,r=!1;for(let i in c){if((i==="time"||i==="__time__")&&typeof c[i]=="number"){t=c[i],r=!0;continue}typeof c[i]=="object"?e[i]=JSON.stringify(c[i]):e[i]=String(c[i])}return e.__time__=r?t:Math.floor(new Date().getTime()/1e3),e},process:function(c,e){return Ac(this,null,function*(){yield yc(s);let t=c.slice(c.indexOf("/logstores")),r=e.length,i=bc(e),n=new Date().toUTCString(),a=new Map,o=new Map([["Content-Type","application/json"],["Content-MD5",i],["x-log-bodyrawsize",r.toString()]]);s.securityToken&&o.set("x-acs-security-token",s.securityToken),Sc("POST",t,s.accessKeyId,s.accessKeySecret,a,o,i,n);let u=Object.fromEntries(o);return{data:e,header:u}})}}}typeof window!="undefined"&&qn(window,"stsPlugin",Xn);const{BrowserUtil:Ec}=me.AliRTS,Qt={EdgeHTML:"EdgeHTML",Blink:"Blink",Trident:"Trident",Gecko:"Gecko",WebKit:"WebKit"},ki=(s,c)=>{const e=c.match(s);return e&&e.length>0&&e[1]||""},wc=[{test:[/\sedg\//i,[/edg([ea]|ios)/i]],describe(s){if(/\sedg\//i.test(s))return{name:Qt.Blink};const e=ki(/edge\/(\d+(\.?_?\d+)+)/i,s);return{name:Qt.EdgeHTML,version:e}}},{test:[/trident/i],describe(s){const c={name:Qt.Trident},e=ki(/trident\/(\d+(\.?_?\d+)+)/i,s);return e&&(c.version=e),c}},{test(s){const c=/gecko/i.test(s),e=/like gecko/i.test(s);return c&&!e},describe(s){const c={name:Qt.Gecko},e=ki(/gecko\/(\d+(\.?_?\d+)+)/i,s);return e&&(c.version=e),c}},{test:[/(apple)?webkit\/537\.36/i],describe(){return{name:Qt.Blink}}},{test:[/(apple)?webkit/i],describe(s){const c={name:Qt.WebKit},e=ki(/webkit\/(\d+(\.?_?\d+)+)/i,s);return e&&(c.version=e),c}}],Yr=(s,c)=>s.find(e=>{if(typeof e.test=="function")return e.test(c);if(Array.isArray(e.test))return e.test.some(t=>typeof t=="string"?c.indexOf(t)>-1:t instanceof RegExp?t.test(c):!1)}),Cc=()=>{try{const s=navigator.userAgent||"",c=Yr(wc,s);if(c){const e=c.describe(s);return`${e.name}/${e.version||Ec.browserVersion}`}}catch(s){}return navigator.userAgent},Ic=[{test:["wow64","win64","x64"],describe(){return"amd64"}},{test:["i686","x86"],describe(){return"x86"}},{test:["aarch64","arm64"],describe(){return"arm64"}},{test:["arm"],describe(){return"arm"}}],Rc=()=>{let s="unknown";try{const c=navigator.userAgent||"",e=Yr(Ic,c);if(!e)return s;s=e.describe(c)}catch(c){}return s},kc=[{test:[/\b((?:s[cgp]h|gt|sm)-\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]([-\w]+)/i,/sec-(sgh\w+)/i],describe(){return"Samsung"}},{test:[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i,/\((ipad);[-\w\),; ]+apple/i,/(macintosh);/i],describe(){return"Apple"}},{test:[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],describe(){return"Huawei"}},{test:[/(?:honor)([-\w ]+)[;\)]/i],describe(){return"Honor"}},{test:[/\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)?)(?: bui|\))/i],describe(){return"Xiaomi"}},{test:[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],describe(){return"Oppo"}},{test:[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],describe(){return"Vivo"}},{test:[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],describe(){return"Realme"}},{test:[/(pixel c)\b/i,/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],describe(){return"Google"}},{test:[/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],describe(){return"ZTE"}},{test:[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],describe(){return"Meizu"}}],Dc=()=>{let s="Unknown";try{const c=navigator.userAgent||"",e=Yr(kc,c);if(!e)return s;s=e.describe(c)}catch(c){}return s},{BrowserUtil:Qr,SystenUtil:Zn}=me.AliRTS;class Yn{constructor(){A(this,"tracker");A(this,"param");A(this,"msgCacheArr",[]);A(this,"index",0);A(this,"stsOpt");A(this,"slsToken");A(this,"ossToken")}createTracker(){if(!this.tracker&&this.slsToken&&this.param){const c=this.slsToken;this.ossToken&&(this.param.ossbn=this.ossToken.bucket_name,this.param.ossep=this.ossToken.region_endpoint);const e=new Jn({host:c.region_endpoint,project:c.project,logstore:c.log_store_stats}),t={accessKeyId:c.access_key_id,accessKeySecret:c.access_key_secret,securityToken:c.security_token,refreshSTSToken:()=>{this.slsToken&&(t.accessKeyId=this.slsToken.access_key_id,t.accessKeySecret=this.slsToken.access_key_secret,t.securityToken=this.slsToken.security_token)}};this.stsOpt=t;const r=Xn(t);e.useStsPlugin(r),this.tracker=e,this.msgCacheArr.forEach((i,n)=>{var a,o;(o=this.tracker)==null||o.send(Se(Rt(Se({},this.param),{stat_log_id:`${((a=this.param)==null?void 0:a.sesid)||"nosession"}-${n}`}),i))}),this.index=this.index+this.msgCacheArr.length,this.msgCacheArr=[]}}start(c){this.initParam(c),this.createTracker()}updateToken(c,e){this.slsToken=c,this.ossToken=e,this.createTracker()}stop(){this.tracker=void 0}sendReport(c){var e,t;if(c.tm=Date.now(),!this.tracker){this.msgCacheArr.push(c);return}(t=this.tracker)==null||t.send(Se(Rt(Se({bt:Qr.browserName||"unknown"},this.param),{stat_log_id:`${((e=this.param)==null?void 0:e.sesid)||"nosession"}-${this.index}`}),c)),this.index++}initParam(c){let e=localStorage.getItem("AliRtcUUID");e||(e=Vt(),localStorage.setItem("AliRtcUUID",e)),this.param||(this.param={apid:c.appId,usrid:c.userId,statsvrs:"0.6.1",evetid:0,sesid:c.sessionId,sessionId:c.sessionId,channelid:c.channelId,usrn:c.userId,osn:Zn.systemName,osv:Zn.systemVersion,deb:Dc(),den:Cc(),udid:e,sdkvrs:nr,acs:"Unknown",cput:Rc(),dm:`${window.location.protocol}//${window.location.host}`,bt:Qr.browserName,bv:Qr.browserVersion,envir:"PRODUCT",args:""})}}const Te=(s,c=1,e=6e4,t=0)=>{let r=s;return r||(r=0),Math.min(e,Math.max(t,Math.round(r*c)))},pt=(s,c,e=2e7,t=0)=>{let r=c;(!c||c<0||c>1e4)&&(r=1e3);let i=s;return i||(i=0),Math.min(e,Math.max(t,Math.round(i/(r/1e3))))},jt=(s,c)=>{if(c===0)return 0;let e=s;return(!e||e<0)&&(e=0),+((e||0)/c*100).toFixed(2)},Qn=s=>s>=0&&s<=1?Te(Math.floor(32767*s),1,32767):0,Ne=(s,c)=>{var t,r,i;let e=((t=s._last)==null?void 0:t[c])||0;return s.ssrc&&((r=s._last)!=null&&r.ssrc)&&s.ssrc!==((i=s._last)==null?void 0:i.ssrc)&&(e=0),((s==null?void 0:s[c])||0)-e},Tc=(s,c)=>{var e,t,r;return(((e=s==null?void 0:s._source)==null?void 0:e[c])||0)-(((r=(t=s==null?void 0:s._last)==null?void 0:t._source)==null?void 0:r[c])||0)},ea=(s,c)=>Te(Ne(s,c),1e3,1e4),Wt=(s,c=2e7)=>Te(s,1,c),Si=class Si{constructor(c){A(this,"engine");A(this,"logClient");A(this,"authInfo");this.logClient=new Yn,this.engine=c}static getLogClient(){return this.staticClient||(this.staticClient=new Yn),this.staticClient}static reportOSSUpload(c,e,t=0){Si.getLogClient().sendReport({errmsg:`${e}/${c}.log`,errtype:t,evetid:70017,sesid:c,sessionId:c,stat_log_id:`${c}-70017`})}start(c){this.authInfo=c,this.logClient.start(c)}updateToken(c,e){this.logClient.updateToken(c,e),Si.getLogClient().updateToken(c,e)}stop(){this.logClient.stop()}reportPublishMonitor(c,e,t,r,i){if(!t||i.length<=0)return;const n=t===Z.Audio,a={ctm:Math.floor(i[0].timestamp||0),src:i[0].ssrc||"",codec:i[0]._codec||""},o=[],u=[],h=[],g=[],f=[],l=[],p=[],d=[],m=[],x=[],v=[],b=[],y=[],E=[],I=[],C=[],R=[],L=[],k=[];try{if(i.forEach(M=>{var H,F,K,Y,ge,se;if(!M||!M.timestamp)return;const w=(H=M._last)!=null&&H.timestamp?M.timestamp-M._last.timestamp:1e3,N=Ne(M,"bytesSent"),_=Ne(M,"headerBytesSent"),V=pt(Te(N+_,8,2e7),w);o.push(V);const ee=pt(Te(N,8,2e7),w);u.push(ee);const q=pt(Te(_,8,2e7),w);h.push(q);const re=Ne(M,"packetsSent"),$=pt(re,w);g.push($);const ie=Ne(M,"packetsLost"),T=pt(ie,w);f.push(T);const B=jt(ie,re);if(l.push(B),n)(F=M._source)!=null&&F.audioLevel&&p.push(Qn(M._source.audioLevel)),d.push(0);else{m.push(ea(M,"totalEncodeTime")),x.push(Wt((K=M._source)==null?void 0:K.framesPerSecond,100)),v.push(Wt((Y=M._source)==null?void 0:Y.framesPerSecond,100)),b.push(Wt(M.framesPerSecond,100)),y.push(Wt((ge=M._source)==null?void 0:ge.height,4400)),E.push(Wt((se=M._source)==null?void 0:se.width,7700)),I.push(Wt(M.frameHeight,4400)),C.push(Wt(M.frameWidth,7700));const xe=Ne(M,"totalPacketSendDelay");R.push(Te(xe,1/(ie||1),2e3));const Re=Ne(M,"qpSum");L.push(Te(Re,1/(M.framesPerSecond||1),51)),k.push(0)}}),a.sbr=o.join(","),a.mbrs=u.join(","),a.pbrs=h.join(","),a.ps=g.join(","),a.pl=f.join(","),a.plr=l.join(","),n){const M=(r==null?void 0:r.getSettings().sampleRate)||0;a.ailevel=p.join(","),a.arpc=d.join(","),a.arsr=M,a.aesr=M,a.publevel=-90,a.rawlevel=-90}else a.em=m.join(","),a.cfps=x.join(","),a.ifps=v.join(","),a.sfps=b.join(","),a.ih=y.join(","),a.iw=E.join(","),a.sh=I.join(","),a.sw=C.join(","),a.sd=R.join(","),a.aqp=L.join(","),a.caf=k.join(","),a.can=k.join(","),a.cav=u.join(","),a.ifimax=k.join(","),a.ifimin=k.join(","),a.efimax=k.join(","),a.efimin=k.join(","),a.sfimax=k.join(","),a.sfimin=k.join(","),a.apsnr=k.join(",")}catch(M){}this.log({evetid:10070,traceid:e,calid:c,args:this.data2String(Se({calid:c,tckid:t,traceid:e},a))})}reportSubscribeMonitor(c,e,t,r,i){if(!r||!i||i.length<=0)return;const n=r===Z.Audio,a={ctm:Math.floor(i[0].timestamp||0),src:i[0].ssrc||"",codec:i[0]._codec||""},o=[],u=[],h=[],g=[],f=[],l=[],p=[],d=[],m=[],x=[],v=[],b=[],y=[],E=[],I=[],C=[],R=[],L=[],k=[],M=[],w=[],N=[],_=[],V=[],ee=[],q=[],re=[],$=[],ie=[],T=[],B=[],H=[],F=[],K=[];try{i.forEach(Y=>{var U,Q;if(!Y||!Y.timestamp)return;const ge=(U=Y._last)!=null&&U.timestamp?Y.timestamp-Y._last.timestamp:1e3,se=Ne(Y,"bytesReceived"),xe=Ne(Y,"headerBytesReceived"),Re=pt(Te(se+xe,8,2e7),ge);o.push(Re);const Ce=pt(Te(se,8,2e7),ge);u.push(Ce);const Me=pt(Te(xe,8,2e7),ge);h.push(Me);const ke=Ne(Y,"packetsReceived"),S=pt(ke,ge);g.push(S);const G=Ne(Y,"packetsLost"),W=pt(G,ge);f.push(W);const P=jt(G,ke);l.push(P);const D=Te(Y.jitterBufferDelay,1e3/Y.jitterBufferEmittedCount,3e4);p.push(D);const O=Ne(Y,"fecPacketsReceived");b.push(jt(O,ke));const X=Ne(Y,"retransmittedPacketsReceived"),J=ke+G-X;if(m.push(jt(ke-X,J)),x.push(jt(G,J)),d.push(jt(X,J)),v.push(J),F.push(0),K.push(""),n){E.push(Qn(Y.audioLevel));const ue=Tc(Y,"synthesizedSamplesEvents");I.push(ue);const te=ea(Y,"synthesizedSamplesDuration");C.push(te);const pe=jt(te,ge);y.push(pe),R.push(0)}else{const ue=(Q=Y._last)!=null&&Q.totalInterFrameDelay?Y.totalInterFrameDelay-Y._last.totalInterFrameDelay:0;L.push(Te(ue,1e3/(Y.framesDecoded||30),500)),k.push(Te(Y.framesPerSecond,1,100)),M.push(Te(Y.framesPerSecond,1,100)),w.push(Te(Y.frameHeight,1,4400)),N.push(Te(Y.frameWidth,1,7700));const te=Ne(Y,"totalProcessingDelay");_.push(Te(te,1e3/(Y.framesDecoded||30),12e4));const pe=Ne(Y,"nackCount");ee.push(pe);const we=Ne(Y,"pliCount");V.push(we);const ye=Ne(Y,"qpSum");q.push(Te(ye,1/(Y.framesPerSecond||1),51)),re.push(Te(Y.framesDropped));const Ze=Ne(Y,"totalFreezesDuration");$.push(Te(Ze,1e3,3e4));const vt=Ne(Y,"jitterBufferEmittedCount"),He=Ne(Y,"jitterBufferDelay");ie.push(Te(He,1e3/(vt||1),3e4));const ut=Ne(Y,"jitterBufferTargetDelay");T.push(Te(ut,1e3/(vt||1),3e4));const Pe=Ne(Y,"jitterBufferMinimumDelay");B.push(Te(Pe,1e3/(vt||1),3e4)),H.push(Te(Y.framesPerSecond,1,100))}}),a.rbr=o.join(","),a.mbrs=u.join(","),a.pbrs=h.join(","),a.pr=g.join(","),a.pl=f.join(","),a.plr=l.join(","),a.jd=p.join(","),a.fecr=b.join(","),a.retransr=d.join(","),a.baser=m.join(","),a.basel=x.join(","),a.recoverr=F.join(","),a.alll=x.join(","),a.totalc=v.join(","),n?(a.er=y.join(","),a.aolevel=E.join(","),a.asrc=R.join(","),a.scnt=I.join(","),a.sdura=C.join(",")):(a.dm=L.join(","),a.dfps=k.join(","),a.rfps=M.join(","),a.rh=w.join(","),a.rw=N.join(","),a.fpt=K.join(","),a.ns=ee.join(","),a.pliss=V.join(","),a.aqp=q.join(","),a.ofimax=F.join(","),a.ofimin=F.join(","),a.dfimax=F.join(","),a.dfimin=F.join(","),a.rfimax=F.join(","),a.rfimin=F.join(","),a.vrstutter=$.join(","),a.cdm=ie.join(","),a.tdm=T.join(","),a.pdm=B.join(","),a.ofps=H.join(","),a.dfbd=re.join(","))}catch(Y){}this.log({evetid:10080,traceid:t,rmtid:e,calid:c,args:this.data2String(Se({calid:c,rmtid:e,tckid:r,traceid:t},a))})}reportNetworkMonitor(c){if(c.length<=0)return;const e=[],t=[],r=[],i=[],n=[],a=[],o=[],u=[],h=[],g=[];c.forEach((l,p)=>{var m;if(!l.timestamp)return;const d=(m=l._last)!=null&&m.timestamp?l.timestamp-l._last.timestamp:1e3;e.push(Te(l.currentRoundTripTime,1e3)),t.push(Te(l.availableOutgoingBitrate,8,2e8)),r.push(pt(Te(l.bytesSent,8,2e7),d,25e6)),i.push(pt(Te(l.bytesReceived,8,2e7),d,25e6)),n.push(0),a.push(0),p%5===0&&(o.push(""),u.push(""),h.push(""),g.push(""))});const f={ctm:Math.floor(c[0].timestamp||0),rtt:e.join(","),bsps:r.join(","),brps:i.join(","),cpu:o.join(","),mem:u.join(","),sysmem:h.join(","),systotalmem:g.join(","),audioonly:this.engine.isAudioOnly()?1:0};this.log({evetid:10071,args:this.data2String(Se({asb:t.join(","),abms:n.join(","),vbms:a.join(",")},f))}),this.log({evetid:10081,args:this.data2String(Se({},f))})}reportJoin(c,e,t=""){var g,f;const{start:r,rs:i=0,re:n=0}=e,a=Date.now()-r,o=n-i;let u=0;i&&(u=i-r);let h=0;n&&(h=n-i),this.log({evetid:10010,args:this.data2String({sesid:((g=this.authInfo)==null?void 0:g.sessionId)||"",joitm:a,rslt:c,gslbtm:0,dnstm:0,avcftm:0,gslbrslt:0,dnsrslt:0,avcfrslt:0,mode:2,jrtc:o,usrn:(f=this.authInfo)==null?void 0:f.userId,mgt:"cdn",cttc:u,iptc:h,ndn:1,gslbloc:1,ccag:0,ucag:0,cpg:0,upg:0,tid:t})})}reportJoinConnection(c){this.log({evetid:20002,args:this.data2String(Se({transretrynum:0,ldnstc:0,tcptc:0,ssltc:0,url:""},c))})}reportLeave(c,e,t){this.log({evetid:10020,args:this.data2String({lvetm:c,rslt:e,tid:t})})}reportPublish(c,e,t,r,i,n,a,o,u,h,g){this.log({evetid:c?10032:10030,calid:t,args:this.data2String({calid:t,url:e,isvl:r?1:0,isvs:i?1:0,isvss:n?1:0,isaudio:a?1:0,rslt:o,tid:"123",pubtm:Date.now()-g,pctid:u,pubtid:h,isvp:0,isarecording:0,isad:0,isdc:0,pubretry:0,pbrttimes:0})})}reportPublishFirstPacket(c,e,t,r,i,n,a,o,u){const h=Date.now();this.log({evetid:c?10033:10031,calid:e,args:this.data2String({calid:e,fpst:h-t,tckid:n,est:t,pctid:a,pubtid:o,totaltm:h-i,jorm:u===Ot.JOINCHANNEL?1:0,cptc:0,sptc:r-t,iptc:0,ipc2fptc:0,dctc:0,patc:0})})}reportUnpublish(c,e,t,r){var i;this.log({evetid:10040,args:this.data2String({calid:c,unpubtm:e,rslt:t,tid:r,sesid:((i=this.authInfo)==null?void 0:i.sessionId)||""})})}reportSubscribe(c,e,t,r,i,n,a,o,u,h){this.log({evetid:10050,calid:c,rmtid:e,args:this.data2String(Se({calid:c,rmtid:e,isvl:t?1:0,isvs:r?1:0,isvss:i?1:0,isaudio:n?1:0,rslt:a,tid:o,subtm:u,isvp:0,isaplaying:0,isad:0,isdc:0,subretry:0,sbrttimes:0},h))})}reportSubscribeFirstPacket(c,e,t,r,i){this.log({evetid:c?10054:10051,calid:e,rmtid:t,args:this.data2String(Se({calid:e,rmtid:t,tckid:r,cptc:0,iptc:0,ipc2fptc:0,dctc:0,patc:0},i))})}reportSubscribeFirstFrame(c,e,t,r,i){this.log({evetid:c?10055:10052,calid:e,rmtid:t,args:this.data2String(Se({calid:e,rmtid:t,tckid:r},i))}),this.log({evetid:c?10058:10057,args:this.data2String(Se({calid:e,rmtid:t,tckid:r},i))})}reportUnsubscribe(c,e,t,r,i){this.log({evetid:10060,calid:c,args:this.data2String({calid:c,rmtid:e,unsubtm:t,rslt:r,tid:i})})}reportMute(c,e,t){this.log({evetid:11030,args:this.data2String({calid:c,rmtid:"",enable:e?1:0,mt:t})})}reportRoleUpdate(c,e){this.log({evetid:11040,args:this.data2String({or:c||"",nr:e,ctm:Date.now(),rslt:0})})}reportRoleUpdateResult(c,e,t,r){this.log({evetid:11041,args:this.data2String({or:c||"",nr:e,ctm:t,rslt:r})})}reportVideoProfile(c){this.log({evetid:20074,args:this.data2String({pf:c,tckid:"sophon_camera_large"})})}reportScreenProfile(c){this.log({evetid:20074,args:this.data2String({pf:c,tckid:"sophon_screenshare"})})}reportError(c){this.log({evetid:10091,args:this.data2String({rslt:c.code||-1})})}reportWarning(c){this.log({evetid:10092,args:this.data2String({rslt:-1,errmsg:c})})}reportRoomServerEvent(c,e,t,r){this.log({evetid:20005,args:this.data2String({calid:"",rmtid:"",rt:c?0:1,dr:c?"s":"r",mt:e,ri:t,cs:1,srt:Date.now(),rspc:r.code||"",mc:JSON.stringify(r)})})}reportTranscodingError(c,e){this.log({evetid:10101,args:this.data2String({rslt:c,taskid:e})})}reportBye(c){var e;this.log({evetid:10093,args:this.data2String({rslt:c,sesid:((e=this.authInfo)==null?void 0:e.sessionId)||""})})}reportAudio(c,e,t){var r;this.log({evetid:80013,args:this.data2String({rslt:c?-1:0,adm:1,adt:0,adr:c?2:0,acms:e,adrpn:t})}),this.log({evetid:80014,args:this.data2String({sesid:((r=this.authInfo)==null?void 0:r.sessionId)||"",rslt:c?-1:0,adm:1,adt:0,adr:c?2:0,acms:e,adrpn:t})})}reportScreen(c,e){var t,r;this.log({evetid:90013,args:this.data2String({rslt:c?-1:0,vcms:e,vde:c.code?c.code:-1,sesid:((t=this.authInfo)==null?void 0:t.sessionId)||""})}),this.log({evetid:90014,args:this.data2String({rslt:c?-1:0,vcms:e,vde:c.code?c.code:-1,sesid:((r=this.authInfo)==null?void 0:r.sessionId)||""})})}reportScreenStop(c){this.log({evetid:90019,args:this.data2String({rslt:c?c.code||-1:0})}),this.log({evetid:90020,args:this.data2String({rslt:c?c.code||-1:0})})}reportSwitchCamera(c){var e;this.log({evetid:90025,args:this.data2String({rslt:0,td:c,sesid:((e=this.authInfo)==null?void 0:e.sessionId)||""})})}reportPublishProfile(c,e){this.log({evetid:10201,args:this.data2String(Se({tckid:c},e))})}reportSDKCreated(c){this.log({evetid:70011,createtm:Date.now()-c,tm:c})}reportJoinInvoked(c){this.log({evetid:70012,jnnonce:c.nonce||"",jntoken:c.token||"",jntm:c.timestamp||""})}reportJoinResult(c){this.log({evetid:70013,rslt:c?c.code||-1:0,dnsrslt:0})}reportSTSResult(c){this.log({evetid:70014,rslt:c,asty:1})}reportLeaveInvoked(){this.log({evetid:70015})}reportSEIMessage(c,e,t,r,i){this.log({evetid:40301,args:this.data2String({tm:Date.now(),sei_pt:c,sei_len:e,sei_rep:t,sei_delay:r,sei_key:i})})}log(c){c&&(c.tm=new Date().getTime(),oe.debug("[ConsoleLogger]","log",c),this.logClient.sendReport(c))}data2String(c){let e="";for(let t in c)e.length&&(e+="&"),e+=t+"="+c[t];return e}};A(Si,"staticClient");let hi=Si;const Bc=1e3*60*60*24*7,Pc=s=>{if(s.length!==8)return new Date;const c=parseInt(s.substring(0,4),10),e=parseInt(s.substring(4,6),10)-1,t=parseInt(s.substring(6,8),10);if(isNaN(c)||isNaN(e)||isNaN(t))return new Date;const r=new Date(c,e,t);return isNaN(r.getTime())?new Date:r};var es=(s=>(s[s.DEBUG=0]="DEBUG",s[s.INFO=1]="INFO",s[s.API=2]="API",s[s.WARNING=3]="WARNING",s[s.ERROR=4]="ERROR",s[s.NONE=5]="NONE",s))(es||{});class Di{constructor(){A(this,"dbPromise");A(this,"stsToken");A(this,"logLevel");A(this,"logToConsole");A(this,"logToServer");A(this,"appId");A(this,"sessionId");A(this,"logCache",[]);A(this,"logMethod",(c,e=console.log)=>(...t)=>{if(this.logLevel>c)return;let r=this.getCurrentTime();this.logToConsole&&e(r,...t);let i=Di.paramArrayToString(t);c>0&&this.addLog(i)});A(this,"d",this.logMethod(0,console.debug));A(this,"i",this.logMethod(1));A(this,"w",this.logMethod(3,console.warn));A(this,"e",this.logMethod(4,(...c)=>{const[e,...t]=c;console.error(e,"<error>",t)}));A(this,"ev",this.logMethod(2));A(this,"a",this.logMethod(2,(...c)=>{const[e,...t]=c;if(t.length>2){const r=`${t[1]}`;r.startsWith("__g__")&&console.group(`${r.substring(5)}_${t[2]}`)}console.log(e,...t)}));A(this,"ar",this.logMethod(2,(...c)=>{const[e,...t]=c;console.log(e,...t),t.length>2&&`${t[1]}`.startsWith("__g__")&&console.groupEnd()}));A(this,"ae",this.logMethod(2,(...c)=>{const[e,...t]=c;console.error(e,"<error>",...t),t.length>2&&`${t[1]}`.startsWith("__g__")&&console.groupEnd()}));this.logLevel=3,this.logToConsole=!0,this.logToServer=!0,this.appId="",this.sessionId="",this.dbPromise=Ro()}static toString(c){let e;if(c instanceof Error)e=c.message;else if(typeof c=="string")e=c;else try{e=JSON.stringify(c)}catch(t){e="undefined"}return e}changeConfig(c){c.logLevel!==void 0&&c.logLevel>=0&&c.logLevel<=5&&(this.logLevel=c.logLevel),c.logToConsole!==void 0&&(this.logToConsole=c.logToConsole),c.logToServer!==void 0&&(this.logToServer=c.logToServer)}updateSTSToken(c){const e=!!this.stsToken;this.stsToken=c,!e&&c&&this.tryUploadHistorySessionLog()}uploadSessionDateLog(c,e,t){return z(this,null,function*(){if(!c||!e||!t||t.length===0||!this.stsToken)return;const r=new po;r.file(`${c}.log`,t.map(f=>f.log||"").join(`
38
- `));const i=yield r.generateAsync({type:"blob"}),n=yield nc(i),a=Zr(new Date,"UTC:ddd, dd mmm yyyy HH:MM:ss 'GMT'"),o={"x-oss-date":a,"content-md5":n,"content-type":"application/zip"};o.date=a,o["x-oss-security-token"]=this.stsToken.security_token;const u=`client/${e}/${this.appId}/${c}.zip`;o.authorization=yield oc(this.stsToken.access_key_id,this.stsToken.access_key_secret,o,`/${this.stsToken.bucket_name}/${u}`);const h=`https://${this.stsToken.bucket_name}.${this.stsToken.region_endpoint}/${u}`,g=yield fetch(h,{method:"PUT",headers:o,body:i});if(g.status===200){hi.reportOSSUpload(c,e);const f=yield this.dbPromise;t.forEach(l=>{sn(f,l.id)})}else hi.reportOSSUpload(c,e,g.status)})}uploadSessionLog(c){c&&this.dbPromise.then(e=>z(this,null,function*(){if(!this.stsToken)return;const t=yield rn(e,c),r={},i=[];t.forEach(n=>{const a=n.date;if(Date.now()-Pc(a).getTime()>Bc)try{sn(e,n.id)}catch(o){}else r[a]||(r[a]=[],i.push(a)),r[a].push(n)}),Promise.all(i.map(n=>this.uploadSessionDateLog(c,n,r[n]))).then(()=>z(this,null,function*(){(yield rn(e,c)).length===0&&To(e,c)}))}))}tryUploadHistorySessionLog(){this.dbPromise.then(c=>z(this,null,function*(){(yield Do(c)).filter(t=>t.sid!==this.sessionId).forEach(t=>{this.uploadSessionLog(t.sid)})}))}uploadCurrent(){const c=this.sessionId;this.sessionId="",this.uploadSessionLog(c)}setSessionID(c,e){!c||!e||(this.appId=c,this.dbPromise.then(t=>{this.sessionId=e,ko(t,e),this.logCache&&(this.logCache.forEach(r=>{tn(t,this.sessionId,r.date,`${r.log}`)}),this.logCache=[])}))}addLog(c){if(!this.logToServer)return;const e=this.getCurrentTime(),t=this.getCurrentDate(),r=`${e} ${c}`;this.sessionId?this.dbPromise.then(i=>{tn(i,this.sessionId,t,r)}):this.logCache.push({date:t,log:r})}getCurrentTime(){return Zr(new Date,"HH:MM:ss.l")}getCurrentDate(){return Zr(new Date,"yyyymmdd")}static paramArrayToString(c){let e="";for(let t=0;t<c.length;t++){e!==""&&(e+=" ");let r=Di.toString(c[t]);e+=r}return e}}class oe{static getLogger(){return this.logger||(this.logger=new Di),this.logger}static setLogLevel(c){this.getLogger().changeConfig({logLevel:c})}static config(c){this.getLogger().changeConfig(c)}static updateToken(c){this.getLogger().updateSTSToken(c)}static setSessionID(c,e){this.getLogger().setSessionID(c,e)}static uploadLog(){this.getLogger().uploadCurrent()}static interface(...c){this.getLogger().a("[API]",...c)}static interfaceResult(c,e,t,...r){t?this.getLogger().ar("[ARE]",c,e,...r):this.getLogger().ae("[ARE]",c,e,...r)}static event(...c){this.getLogger().ev("[EVT]",...c)}static debug(...c){this.getLogger().d("[DBG]",...c)}static info(...c){this.getLogger().i("[INF]",...c)}static warn(...c){this.getLogger().w("[WARN]",...c)}static error(...c){this.getLogger().e("[ERR]",...c)}}A(oe,"logger");const Lc=s=>z(this,null,function*(){const c=new me.AliRTS.SupportUtil;let e={support:!1,detail:{isWebRTCSupported:c.checkMediaDevices()&&c.checkWebRtcSupport(),isH264DecodeSupported:!1,isH264EncodeSupported:!1,isScreenShareSupported:!1,isSendMediaExtensionMsgSupported:!1,isBrowserSupported:c.checkBrowser({errorCode:0,message:""})}};if(e.support=e.detail.isWebRTCSupported&&e.detail.isBrowserSupported,c.checkWebRtcSupport()&&s!=="sendonly"){const t=yield c.checkH264Decode();e.detail.isH264DecodeSupported=t,e.support=e.support&&t}if(c.checkWebRtcSupport()&&s!=="recvonly"){const t=yield c.checkH264Encode();e.detail.isH264EncodeSupported=t,e.support=e.support&&t}return e.detail.isScreenShareSupported=c.checkWebRtcSupport()&&c.checkScreenCapture()&&!me.AliRTS.SystenUtil.isAndroid&&!me.AliRTS.SystenUtil.isIos,e.detail.isSendMediaExtensionMsgSupported=c.checkWebRtcSupport()&&c.checkEncodedTransformSupport(),e});var Ke=(s=>(s[s.AliRtcSdkStreamTypeCapture=0]="AliRtcSdkStreamTypeCapture",s[s.AliRtcSdkStreamTypeScreen=1]="AliRtcSdkStreamTypeScreen",s))(Ke||{}),ta=(s=>(s[s.PRE_PROCESSOR=0]="PRE_PROCESSOR",s[s.POST_PROCESSOR=1]="POST_PROCESSOR",s))(ta||{}),Ti=(s=>(s[s.AUDIO=0]="AUDIO",s[s.VIDEO=1]="VIDEO",s[s.BOTH=2]="BOTH",s))(Ti||{});class ei extends ve{constructor(e,t=Ke.AliRtcSdkStreamTypeCapture,r=1){super();A(this,"name");A(this,"options");A(this,"type",0);A(this,"streamType");A(this,"trackType");A(this,"zIndex",1);A(this,"_isEnable",!0);A(this,"lastInputAudioTrack");A(this,"lastOutputAudioTrack");A(this,"lastInputVideoTrack");A(this,"lastOutputVideoTrack");A(this,"_hasCleared",!0);this.name=e,this.streamType=t,this.trackType=r,this.options=this.initOptions}get initOptions(){return{}}getOptions(){return this.options}init(){return z(this,null,function*(){})}enable(){this._isEnable||(this._isEnable=!0,this.init(),this.emit("enabled"))}disable(){this._isEnable&&(this._isEnable=!1,this.clear(),this.emit("disabled"))}get isEnable(){return this._isEnable}audioUpdated(e){var t,r;return((t=this.lastInputAudioTrack)==null?void 0:t.id)!==((r=e.currentAudioTrack)==null?void 0:r.id)}videoUpdated(e){var t,r;return((t=this.lastInputVideoTrack)==null?void 0:t.id)!==((r=e.currentVideoTrack)==null?void 0:r.id)}execute(e,t){return z(this,null,function*(){const r=this.shouldUpdate(e,t);this.lastInputAudioTrack=e.currentAudioTrack,this.lastInputVideoTrack=e.currentVideoTrack,this._hasCleared||r?(yield this.process(e,t),this._hasCleared=!1):(this.lastOutputAudioTrack&&(this.trackType===2||this.trackType===0)&&this.lastOutputAudioTrack&&e.updateAudioTrack(this.lastOutputAudioTrack),this.lastOutputVideoTrack&&(this.trackType===2||this.trackType===1)&&this.lastOutputVideoTrack&&e.updateVideoTrack(this.lastOutputVideoTrack)),this.lastOutputAudioTrack=e.currentAudioTrack,this.lastOutputVideoTrack=e.currentVideoTrack})}clear(e){this._hasCleared=!0,this.lastInputAudioTrack=void 0,this.lastInputVideoTrack=void 0,this.lastOutputAudioTrack=void 0,this.lastOutputVideoTrack=void 0}}var di=(s=>(s[s.LiveTranscodingSingle=0]="LiveTranscodingSingle",s[s.LiveTranscodingMix=1]="LiveTranscodingMix",s))(di||{}),ts=(s=>(s[s.LiveTranscodingOrigin=0]="LiveTranscodingOrigin",s[s.LiveTranscodingAudio=1]="LiveTranscodingAudio",s[s.LiveTranscodingVideo=2]="LiveTranscodingVideo",s))(ts||{}),ti=(s=>(s[s.LiveTranscodingCamera=0]="LiveTranscodingCamera",s[s.LiveTranscodingShareScreen=1]="LiveTranscodingShareScreen",s))(ti||{});const li={0:"camera",1:"shareScreen"};var is=(s=>(s[s.LiveTranscoding_Profile_1IN_1080P=0]="LiveTranscoding_Profile_1IN_1080P",s[s.LiveTranscoding_Profile_1IN_720P=1]="LiveTranscoding_Profile_1IN_720P",s[s.LiveTranscoding_Profile_1IN_360P=2]="LiveTranscoding_Profile_1IN_360P",s[s.LiveTranscoding_Profile_2IN_1080P=3]="LiveTranscoding_Profile_2IN_1080P",s[s.LiveTranscoding_Profile_2IN_720P=4]="LiveTranscoding_Profile_2IN_720P",s[s.LiveTranscoding_Profile_2IN_360P=5]="LiveTranscoding_Profile_2IN_360P",s[s.LiveTranscoding_Profile_4IN_1080P=6]="LiveTranscoding_Profile_4IN_1080P",s[s.LiveTranscoding_Profile_4IN_720P=7]="LiveTranscoding_Profile_4IN_720P",s[s.LiveTranscoding_Profile_4IN_360P=8]="LiveTranscoding_Profile_4IN_360P",s[s.LiveTranscoding_Profile_9IN_1080P=9]="LiveTranscoding_Profile_9IN_1080P",s[s.LiveTranscoding_Profile_9IN_720P=10]="LiveTranscoding_Profile_9IN_720P",s[s.LiveTranscoding_Profile_9IN_360P=11]="LiveTranscoding_Profile_9IN_360P",s[s.LiveTranscoding_Profile_12IN_1080P=12]="LiveTranscoding_Profile_12IN_1080P",s[s.LiveTranscoding_Profile_12IN_720P=13]="LiveTranscoding_Profile_12IN_720P",s[s.LiveTranscoding_Profile_12IN_360P=14]="LiveTranscoding_Profile_12IN_360P",s[s.LiveTranscoding_Profile_16IN_1080P=15]="LiveTranscoding_Profile_16IN_1080P",s[s.LiveTranscoding_Profile_16IN_720P=16]="LiveTranscoding_Profile_16IN_720P",s[s.LiveTranscoding_Profile_16IN_360P=17]="LiveTranscoding_Profile_16IN_360P",s[s.LiveTranscoding_Profile_Mixed=9999]="LiveTranscoding_Profile_Mixed",s))(is||{});const Nc={0:"1IN_1080P",1:"1IN_720P",2:"1IN_360P",3:"2IN_1080P",4:"2IN_720P",5:"2IN_360P",6:"4IN_1080P",7:"4IN_720P",8:"4IN_360P",9:"9IN_1080P",10:"9IN_720P",11:"9IN_360P",12:"12IN_1080P",13:"12IN_720P",14:"12IN_360P",15:"16IN_1080P",16:"16IN_720P",17:"16IN_360P",9999:"Mixed_Audio"};var Bi=(s=>(s[s.LiveTranscoding_HZ_48000=48e3]="LiveTranscoding_HZ_48000",s[s.LiveTranscoding_HZ_44100=44100]="LiveTranscoding_HZ_44100",s[s.LiveTranscoding_HZ_32000=32e3]="LiveTranscoding_HZ_32000",s[s.LiveTranscoding_HZ_16000=16e3]="LiveTranscoding_HZ_16000",s[s.LiveTranscoding_HZ_8000=8e3]="LiveTranscoding_HZ_8000",s))(Bi||{}),fi=(s=>(s[s.LiveTranscodingNoBody=0]="LiveTranscodingNoBody",s[s.LiveTranscodingBody=1]="LiveTranscodingBody",s))(fi||{}),pi=(s=>(s[s.NOTO_SERIF_CJKSC_REGULAR=0]="NOTO_SERIF_CJKSC_REGULAR",s[s.ALIBABA_PUHUITI_REGULAR=1]="ALIBABA_PUHUITI_REGULAR",s[s.ALIBABA_PUHUITI_BOLD=2]="ALIBABA_PUHUITI_BOLD",s[s.ALIBABA_PUHUITI_Heavy=3]="ALIBABA_PUHUITI_Heavy",s[s.ALIBABA_PUHUITI_LIGHT=4]="ALIBABA_PUHUITI_LIGHT",s[s.ALIBABA_PUHUITI_MEDIUM=5]="ALIBABA_PUHUITI_MEDIUM",s))(pi||{}),rs=(s=>(s[s.LiveTranscodingOrigin=0]="LiveTranscodingOrigin",s[s.LiveTranscodingCrop=1]="LiveTranscodingCrop",s[s.LiveTranscodingFill=2]="LiveTranscodingFill",s))(rs||{}),Pi=(s=>(s[s.LiveTranscodingNormal=0]="LiveTranscodingNormal",s[s.LiveTranscodingVirtualBackground=1]="LiveTranscodingVirtualBackground",s))(Pi||{}),ss=(s=>(s[s.LiveTranscodingState_IDLE=0]="LiveTranscodingState_IDLE",s[s.LiveTranscodingState_CONNNECT=1]="LiveTranscodingState_CONNNECT",s[s.LiveTranscodingState_RUNNING=2]="LiveTranscodingState_RUNNING",s[s.LiveTranscodingState_RECOVERING=3]="LiveTranscodingState_RECOVERING",s[s.LiveTranscodingState_FAILURE=4]="LiveTranscodingState_FAILURE",s[s.LiveTranscodingState_END=5]="LiveTranscodingState_END",s))(ss||{}),Et=(s=>(s[s.LiveTranscodingErrorPublishOk=0]="LiveTranscodingErrorPublishOk",s[s.LiveTranscodingErrorStreamNotFound=17825793]="LiveTranscodingErrorStreamNotFound",s[s.LiveTranscodingErrorStreamAlreadyExist=17825794]="LiveTranscodingErrorStreamAlreadyExist",s[s.LiveTranscodingErrorInvalidParam=17825795]="LiveTranscodingErrorInvalidParam",s[s.LiveTranscodingErrorInternalError=17825796]="LiveTranscodingErrorInternalError",s[s.LiveTranscodingErrorRtmpServerError=17825797]="LiveTranscodingErrorRtmpServerError",s[s.LiveTranscodingErrorRtmpStreamUrlError=17825798]="LiveTranscodingErrorRtmpStreamUrlError",s[s.LiveTranscodingErrorPublishTimeout=17825799]="LiveTranscodingErrorPublishTimeout",s[s.LiveTranscodingErrorNotAuthorized=17825800]="LiveTranscodingErrorNotAuthorized",s))(Et||{}),ns=(s=>(s[s.TrascodingPublishTaskStatusStart=0]="TrascodingPublishTaskStatusStart",s[s.TrascodingPublishTaskStatusUpdate=1]="TrascodingPublishTaskStatusUpdate",s[s.TrascodingPublishTaskStatusStop=2]="TrascodingPublishTaskStatusStop",s))(ns||{}),st=(s=>(s[s.MPU_TASK_TRANSACTION_START=0]="MPU_TASK_TRANSACTION_START",s[s.MPU_TASK_TRANSACTION_UPDATE=1]="MPU_TASK_TRANSACTION_UPDATE",s[s.MPU_TASK_TRANSACTION_STOP=2]="MPU_TASK_TRANSACTION_STOP",s[s.MPU_TASK_TRANSACTION_LIST=3]="MPU_TASK_TRANSACTION_LIST",s[s.MPU_TASK_TRANSACTION_POLLING=4]="MPU_TASK_TRANSACTION_POLLING",s[s.MPU_TASK_TRANSACTION_ACKNOWLEDGE=5]="MPU_TASK_TRANSACTION_ACKNOWLEDGE",s[s.MPU_TASK_TRANSACTION_END=6]="MPU_TASK_TRANSACTION_END",s))(st||{});const Mc={0:"/libra/v1/sdk/start-task",1:"/libra/v1/sdk/update-task",2:"/libra/v1/sdk/stop-task",3:"/libra/v1/sdk/list-task",4:"/libra/v1/sdk/polling",5:"/libra/v1/sdk/acknowledge",6:"/"};class as{constructor(c,e,t,r,i,n,a,o){A(this,"videoWidth");A(this,"videoHeight");A(this,"videoFramerate",20);A(this,"videoBitrate",2e3);A(this,"videoGop",30);A(this,"audioSamplerate",Bi.LiveTranscoding_HZ_44100);A(this,"audioBitrate",500);A(this,"audioChannels",1);this.videoWidth=c,this.videoHeight=e,t&&(this.videoFramerate=t),r&&(this.videoBitrate=r),i&&(this.videoGop=i),n&&(this.audioSamplerate=n),a&&(this.audioBitrate=a),o&&(this.audioChannels=o)}}const os=s=>((s&16711680)>>16)+(s&65280)+((s&255)<<16),mt=(s=0,c)=>{if(c==0)return 0;let e=s/c;return e<0&&(e=0),e>1&&(e=1),e};class Li{constructor(c,e,t){A(this,"mixMode",di.LiveTranscodingSingle);A(this,"singleParam");A(this,"mixParam");c&&(this.mixMode=c),e&&(this.singleParam=e),t&&(this.mixParam=t)}toJson(c,e,t,r,i){const n={appid:e.appId,channelid:e.channelId};if(c===st.MPU_TASK_TRANSACTION_POLLING||c===st.MPU_TASK_TRANSACTION_LIST||c===st.MPU_TASK_TRANSACTION_ACKNOWLEDGE)return c===st.MPU_TASK_TRANSACTION_ACKNOWLEDGE&&(n.messageid=i),n;if(n.taskid=t,c!==st.MPU_TASK_TRANSACTION_STOP){if(n.mixmode=this.mixMode,r&&(n.streamurl=r),this.mixMode===di.LiveTranscodingSingle){const a=this.singleParam;if(a){n.streamtype=a.streamType,a.sourceType===ti.LiveTranscodingShareScreen?n.sourcetype=li[a.sourceType]:n.sourcetype=li[ti.LiveTranscodingCamera];const o=[];a.userId&&o.push(a.userId),n.subspecusers=o}}else if(c===st.MPU_TASK_TRANSACTION_START||c===st.MPU_TASK_TRANSACTION_UPDATE){const a=this.mixParam;if(a){a.taskProfile&&(n.taskprofile=Nc[a.taskProfile]);const o=a.encodeParam||new as(1280,720);let u=o.videoWidth,h=o.videoHeight;const g={};Object.keys(o).forEach(l=>{const p=o[l];p>0&&(g[l.toLowerCase()]=p)}),g.lowbitratehighquality=0,n.encodeparam=g,n.backgrounds=a.backgrounds.map(l=>l.toJson(u,h)),n.watermarks=a.watermarks.map(l=>l.toJson(u,h)),n.clockwidgets=a.clockWidgets.map(l=>l.toJson(u,h));const f=a.users.map(l=>l.userId);n.subspecusers=[...new Set(f)],n.layouts=[{audiomixcount:a.users.length,panes:a.users.map((l,p)=>l.toJson(p,u,h,a.mediaProcessMode))}],n.layoutids=["0"],n.cropmode=a.cropMode,n.backgroundcolor=os(a.backgroundColor),n.taskmode=a.mediaProcessMode}}}return n}}var Ct=(s=>(s.pre="pre",s.prod="prod",s))(Ct||{}),It=(s=>(s.AliRtcSdkCommunication="communication",s.AliRtcSdkInteractiveLive="interactive_live",s.AliRtcSdkInteractiveWithLowLatencyLive="cdn_live",s))(It||{}),Tt=(s=>(s.AliRtcSdkInteractive="interactive",s.AliRtcSdkLive="live",s))(Tt||{}),wt=(s=>(s[s.AliEngineLocalDeviceTypeUnknown=0]="AliEngineLocalDeviceTypeUnknown",s[s.AliEngineLocalDeviceTypeMic=1]="AliEngineLocalDeviceTypeMic",s[s.AliEngineLocalDeviceTypeSpeaker=2]="AliEngineLocalDeviceTypeSpeaker",s[s.AliEngineLocalDeviceTypeAudioDevice=3]="AliEngineLocalDeviceTypeAudioDevice",s[s.AliEngineLocalDeviceTypeCamera=4]="AliEngineLocalDeviceTypeCamera",s[s.AliEngineLocalDeviceTypeDisplay=5]="AliEngineLocalDeviceTypeDisplay",s[s.AliEngineLocalDeviceTypeVideoDevice=6]="AliEngineLocalDeviceTypeVideoDevice",s))(wt||{}),Fe=(s=>(s[s.AliEngineLocalDeviceExceptionTypeUnknown=0]="AliEngineLocalDeviceExceptionTypeUnknown",s[s.AliEngineLocalDeviceExceptionTypeMicOpenFail=1]="AliEngineLocalDeviceExceptionTypeMicOpenFail",s[s.AliEngineLocalDeviceExceptionTypeMicInterrupt=2]="AliEngineLocalDeviceExceptionTypeMicInterrupt",s[s.AliEngineLocalDeviceExceptionTypeMicAuthFail=3]="AliEngineLocalDeviceExceptionTypeMicAuthFail",s[s.AliEngineLocalDeviceExceptionTypeMicNotAvailable=4]="AliEngineLocalDeviceExceptionTypeMicNotAvailable",s[s.AliEngineLocalDeviceExceptionTypeSpeakerOpenFail=5]="AliEngineLocalDeviceExceptionTypeSpeakerOpenFail",s[s.AliEngineLocalDeviceExceptionTypeSpeakerInterrupt=6]="AliEngineLocalDeviceExceptionTypeSpeakerInterrupt",s[s.AliEngineLocalDeviceExceptionTypeSpeakerNotAvailable=7]="AliEngineLocalDeviceExceptionTypeSpeakerNotAvailable",s[s.AliEngineLocalDeviceExceptionTypeAudioDeviceException=8]="AliEngineLocalDeviceExceptionTypeAudioDeviceException",s[s.AliEngineLocalDeviceExceptionTypeCameraOpenFail=9]="AliEngineLocalDeviceExceptionTypeCameraOpenFail",s[s.AliEngineLocalDeviceExceptionTypeCameraInterrupt=10]="AliEngineLocalDeviceExceptionTypeCameraInterrupt",s[s.AliEngineLocalDeviceExceptionTypeCameraAuthFail=11]="AliEngineLocalDeviceExceptionTypeCameraAuthFail",s[s.AliEngineLocalDeviceExceptionTypeDisplayException=12]="AliEngineLocalDeviceExceptionTypeDisplayException",s[s.AliEngineLocalDeviceExceptionTypeVideoDeviceException=13]="AliEngineLocalDeviceExceptionTypeVideoDeviceException",s))(Fe||{}),De=(s=>(s[s.AliRtcConnectionStatusInit=0]="AliRtcConnectionStatusInit",s[s.AliRtcConnectionStatusDisconnected=1]="AliRtcConnectionStatusDisconnected",s[s.AliRtcConnectionStatusConnecting=2]="AliRtcConnectionStatusConnecting",s[s.AliRtcConnectionStatusConnected=3]="AliRtcConnectionStatusConnected",s[s.AliRtcConnectionStatusReconnecting=4]="AliRtcConnectionStatusReconnecting",s[s.AliRtcConnectionStatusFailed=5]="AliRtcConnectionStatusFailed",s))(De||{}),Kt=(s=>(s[s.AliRtcConnectionChangedDummyReason=0]="AliRtcConnectionChangedDummyReason",s[s.AliRtcConnectionMediaPathChanged=1]="AliRtcConnectionMediaPathChanged",s[s.AliRtcConnectionSignalingHeartbeatTimeout=2]="AliRtcConnectionSignalingHeartbeatTimeout",s[s.AliRtcConnectionSignalingHeartbeatAlive=3]="AliRtcConnectionSignalingHeartbeatAlive",s[s.AliRtcConnectionSignalingHttpDnsResolved=4]="AliRtcConnectionSignalingHttpDnsResolved",s[s.AliRtcConnectionSignalingHttpDnsFailure=5]="AliRtcConnectionSignalingHttpDnsFailure",s[s.AliRtcConnectionSignalingGslbFailure=6]="AliRtcConnectionSignalingGslbFailure",s[s.AliRtcConnectionSignalingGslbSuccess=7]="AliRtcConnectionSignalingGslbSuccess",s[s.AliRtcConnectionSignalingJoinRoomFailure=8]="AliRtcConnectionSignalingJoinRoomFailure",s[s.AliRtcConnectionSignalingJoinRoomSuccess=9]="AliRtcConnectionSignalingJoinRoomSuccess",s[s.AliRtcConnectionSignalingLeaveRoom=10]="AliRtcConnectionSignalingLeaveRoom",s[s.AliRtcConnectionSignalingConnecting=11]="AliRtcConnectionSignalingConnecting",s[s.AliRtcConnectionChangedNetworkInterrupted=12]="AliRtcConnectionChangedNetworkInterrupted",s))(Kt||{}),cs=(s=>(s[s.AliRtcUserOfflineQuit=0]="AliRtcUserOfflineQuit",s[s.AliRtcUserOfflineDropped=1]="AliRtcUserOfflineDropped",s[s.AliRtcUserOfflineBecomeAudience=2]="AliRtcUserOfflineBecomeAudience",s))(cs||{}),ii=(s=>(s[s.AliRtcAudioTrackNo=0]="AliRtcAudioTrackNo",s[s.AliRtcAudioTrackMic=1]="AliRtcAudioTrackMic",s[s.AliRtcAudioTrackDual=2]="AliRtcAudioTrackDual",s))(ii||{}),Ae=(s=>(s[s.AliRtcVideoTrackNo=0]="AliRtcVideoTrackNo",s[s.AliRtcVideoTrackCamera=1]="AliRtcVideoTrackCamera",s[s.AliRtcVideoTrackScreen=2]="AliRtcVideoTrackScreen",s[s.AliRtcVideoTrackBoth=3]="AliRtcVideoTrackBoth",s))(Ae||{}),be=(s=>(s[s.AliRtcStatePublishIdle=0]="AliRtcStatePublishIdle",s[s.AliRtcStateNoPublish=1]="AliRtcStateNoPublish",s[s.AliRtcStatePublishing=2]="AliRtcStatePublishing",s[s.AliRtcStatePublished=3]="AliRtcStatePublished",s))(be||{}),Le=(s=>(s[s.AliRtcStateSubscribeIdle=0]="AliRtcStateSubscribeIdle",s[s.AliRtcStateNoSubscribe=1]="AliRtcStateNoSubscribe",s[s.AliRtcStateSubscribing=2]="AliRtcStateSubscribing",s[s.AliRtcStateSubscribed=3]="AliRtcStateSubscribed",s))(Le||{}),Je=(s=>(s[s.AliRtcVideoStreamTypeNone=0]="AliRtcVideoStreamTypeNone",s[s.AliRtcVideoStreamTypeHigh=1]="AliRtcVideoStreamTypeHigh",s[s.AliRtcVideoStreamTypeLow=2]="AliRtcVideoStreamTypeLow",s))(Je||{}),mi=(s=>(s[s.CAMERA_INVALID=-1]="CAMERA_INVALID",s[s.CAMERA_REAR=0]="CAMERA_REAR",s[s.CAMERA_FRONT=1]="CAMERA_FRONT",s))(mi||{});const ia=10,ra=5e3,Vi=class Vi extends ve{constructor(e){super();A(this,"ws");A(this,"socketStatus",0);A(this,"wsUrl","");A(this,"lastConnectStartTime",0);A(this,"maxConnectRetryCount",ia);A(this,"connectRetryCount",0);A(this,"gotErr",!1);A(this,"closedByInvoke",!0);A(this,"isReconnecting",!1);A(this,"networkAvailableChecked",!0);this.maxConnectRetryCount=e!=null?e:ia,this.onOpen=this.onOpen.bind(this),this.onMessage=this.onMessage.bind(this),this.onError=this.onError.bind(this),this.onClose=this.onClose.bind(this)}get connectUrl(){return this.wsUrl}get connectStatus(){return this.socketStatus}start(e){this.wsUrl=e,this.initWebSocket()}send(e){return this.ws&&this.socketStatus===2?(this.ws.send(JSON.stringify(e)),!0):!1}close(){this.closedByInvoke=!0,this.uninitWebscoket()}reconnect(){this.emit("onReconnectStart"),this.isReconnecting=!0,this.initWebSocket()}onOpen(e){this.socketStatus=2,this.connectRetryCount=0,this.networkAvailableChecked=!1,this.closedByInvoke=!1,this.gotErr=!1,this.isReconnecting=!1,this.emit("onOpen",e)}onMessage(e){this.emit("onMessage",e)}onError(e){this.isReconnecting&&this.emit("onReconnectFail",e),this.emit("onError",e),this.isReconnecting=!1,this.gotErr=!0}onClose(e){return z(this,null,function*(){const t=this.socketStatus;if(oe.info(Vi.logName,`onClose, status: ${t}, retryCount: ${this.connectRetryCount}`),t!==0||this.connectRetryCount)if(yield At.isNetworkAvailable()){if(!this.networkAvailableChecked&&!this.closedByInvoke&&!this.gotErr){this.reconnect();return}this.networkAvailableChecked=!0,this.emit("onAuthInvalid")}else{if(this.connectRetryCount||this.emit("onNetworkError"),this.closedByInvoke)return;this.connectRetryCount+=1,this.connectRetryCount>this.maxConnectRetryCount?this.emit("onConnectFail"):Date.now()-this.lastConnectStartTime>=ra?this.reconnect():window.setTimeout(()=>{this.reconnect()},ra)}this.socketStatus=0,this.emit("onClose",e)})}initWebSocket(){this.uninitWebscoket(),this.socketStatus=1,this.lastConnectStartTime=Date.now(),this.ws=new WebSocket(this.wsUrl),this.ws.addEventListener("open",this.onOpen),this.ws.addEventListener("message",this.onMessage),this.ws.addEventListener("error",this.onError),this.ws.addEventListener("close",this.onClose)}uninitWebscoket(){this.ws&&(this.ws.removeEventListener("open",this.onOpen),this.ws.removeEventListener("message",this.onMessage),this.ws.removeEventListener("error",this.onError),this.ws.removeEventListener("close",this.onClose),this.ws.close(),this.ws=void 0,this.socketStatus=0)}};A(Vi,"logName","Socket");let us=Vi;var Oe=(s=>(s.KEEPALIVE="keepalive",s.JOINCHANNEL="joinchannel",s.NOTIFYJOIN="notifyjoin",s.NOTIFYSTATUS="notifystatus",s.STATUSREPORT="statusreport",s.LEAVECHANNEL="leavechannel",s.NOTIFYLEAVE="notifyleave",s.NOTIFYPUBLISH="notifypublish",s.BYE="bye",s.RECONNECT="reconnect",s.PUBLISH="publish",s.REFRESHURL="refreshurl",s.UNSUBSCRIBE="unsubscribe",s.ROLEUPDATE="roleupdate",s))(Oe||{});class Fc{constructor(c,e){A(this,"authInfo");A(this,"userName");A(this,"seqIndex",0);this.authInfo=c,this.userName=e}get roleAuth(){if(this.authInfo.role){const{timestamp:c,nonce:e,token:t,role:r}=this.authInfo;return{timestamp:c,nonce:e,token:t,tokenrole:r}}}refreshAuthInfo(c){this.authInfo=c}getSeqIndex(){return this.seqIndex}createKeepAlivePackage(){return this.createBaseSendPackage("keepalive")}createJoinPackage(){let c=this.createBaseSendPackage("joinchannel");return c.header.displayName=this.userName,c.header.clientversion=At.getVersionNumber().toString(),c.header.platform=Ks,this.roleAuth&&(c.data.auth=this.roleAuth),c}crateLeavePackage(){return this.createBaseSendPackage("leavechannel")}createStatusPackage(c){let e=this.createBaseSendPackage("statusreport");return e.header.displayName=this.userName,e.data.status=c,e}createPublishPackage(){let c=this.createBaseSendPackage("publish");return c.data.users=[{}],this.roleAuth&&(c.data.auth=this.roleAuth),c}createRoleUpdatePackage(){let c=this.createBaseSendPackage("roleupdate");return c.header.displayName=this.userName,c}createReconnectPackage(c){let e=this.createBaseSendPackage("reconnect");return e.header.displayName=this.userName,e.header.clientversion=At.getVersionNumber().toString(),e.header.platform=Ks,e.data=Se(Se({},e.data),c!=null?c:{}),this.roleAuth&&(e.data.auth=this.roleAuth),e}createRefreshUrlPackage(){let c=this.createBaseSendPackage("refreshurl");return c.header.displayName=this.userName,c}createResponsePackage(c,e){return{version:1,code:200,tid:c,msgtype:e}}createBaseSendPackage(c){var t;return++this.seqIndex,{version:1,msgtype:c,tid:Vt(),header:{appid:this.authInfo.appId,channelid:this.authInfo.channelId,sessionid:(t=this.authInfo.sessionId)!=null?t:"",userid:this.authInfo.userId},data:{seq:this.seqIndex}}}}var ce=(s=>(s[s.ERR_JOIN_ALREADY_JOINED=16843521]="ERR_JOIN_ALREADY_JOINED",s[s.ERR_JOIN_BAD_APPID=33620481]="ERR_JOIN_BAD_APPID",s[s.ERR_JOIN_INVALID_APPID=33620482]="ERR_JOIN_INVALID_APPID",s[s.ERR_JOIN_BAD_CHANNEL=33620484]="ERR_JOIN_BAD_CHANNEL",s[s.ERR_JOIN_INVALID_CHANNEL=33620483]="ERR_JOIN_INVALID_CHANNEL",s[s.ERR_JOIN_BAD_TOKEN=33620485]="ERR_JOIN_BAD_TOKEN",s[s.ERR_JOIN_TIMEOUT=16908804]="ERR_JOIN_TIMEOUT",s[s.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD=16974081]="ERR_JOIN_ERR_JOIN_BAD_PARAMBAD",s[s.ERR_JOIN_CHANNEL_FAILED=16974338]="ERR_JOIN_CHANNEL_FAILED",s[s.ERR_LOG_ALREADY_INIT=16974085]="ERR_LOG_ALREADY_INIT",s[s.ERR_LOG_ROOT_PATH_ERROR=16974086]="ERR_LOG_ROOT_PATH_ERROR",s[s.ERR_MIC_OPEN_FAIL=17040388]="ERR_MIC_OPEN_FAIL",s[s.ERR_SPEAKER_OPEN_FAIL=17040389]="ERR_SPEAKER_OPEN_FAIL",s[s.ERR_MIC_INTERRUPT=17040390]="ERR_MIC_INTERRUPT",s[s.ERR_SPEAKER_INTERRUPT=17040391]="ERR_SPEAKER_INTERRUPT",s[s.ERR_MIC_AUTH_FAIL=17040392]="ERR_MIC_AUTH_FAIL",s[s.ERR_MIC_NOT_AVAILABLE=17040393]="ERR_MIC_NOT_AVAILABLE",s[s.ERR_SPEAKER_NO_AVAILABLE=17040400]="ERR_SPEAKER_NO_AVAILABLE",s[s.ERR_CAMERA_OPEN_FAIL=17039620]="ERR_CAMERA_OPEN_FAIL",s[s.ERR_CAMERA_INTERRUPT=17039622]="ERR_CAMERA_INTERRUPT",s[s.ERR_VIDEO_DISPLAY_OPEN_FAIL=17039873]="ERR_VIDEO_DISPLAY_OPEN_FAIL",s[s.ERR_VIDEO_DISPLAY_INTERRUPT=1064992]="ERR_VIDEO_DISPLAY_INTERRUPT",s[s.ERR_ICE_CONNECTION_CONNECT_FAIL=17105409]="ERR_ICE_CONNECTION_CONNECT_FAIL",s[s.ERR_ICE_CONNECTION_RECONNECT_FAI=17105410]="ERR_ICE_CONNECTION_RECONNECT_FAI",s[s.ERR_ICE_CONNECTION_MOBILITY_FAIL=17105411]="ERR_ICE_CONNECTION_MOBILITY_FAIL",s[s.ERR_ICE_CONNECTION_HEARTBEAT_TIMEOUT=16908812]="ERR_ICE_CONNECTION_HEARTBEAT_TIMEOUT",s[s.ERR_LATENCY_LIVE_COMMUNICATION_FAILED=17235971]="ERR_LATENCY_LIVE_COMMUNICATION_FAILED",s[s.ERR_LATENCY_LIVE_MEIDASETTING_FAILED=17235972]="ERR_LATENCY_LIVE_MEIDASETTING_FAILED",s[s.ERR_LATENCY_LIVE_NONE_BROADCASTER=17235973]="ERR_LATENCY_LIVE_NONE_BROADCASTER",s[s.ERR_LATENCY_LIVE_NEED_RESTART=17235974]="ERR_LATENCY_LIVE_NEED_RESTART",s[s.ERR_LATENCY_LIVE_NEED_RESTART_AGAIN_LATER=17235975]="ERR_LATENCY_LIVE_NEED_RESTART_AGAIN_LATER",s[s.ERR_LATENCY_LIVE_SERVICE_UNAVAILABLE=17235976]="ERR_LATENCY_LIVE_SERVICE_UNAVAILABLE",s[s.ERR_LATENCY_LIVE_MEDIACONNECTION_INTERRUPTION=17235977]="ERR_LATENCY_LIVE_MEDIACONNECTION_INTERRUPTION",s[s.ERR_SDK_PUBLISH_INVAILD=16974597]="ERR_SDK_PUBLISH_INVAILD",s[s.ERR_SDK_PUBLISH_NOT_JOIN_CHANNEL=16843782]="ERR_SDK_PUBLISH_NOT_JOIN_CHANNEL",s[s.ERR_SDK_PUBLISH_AUDIO_STRAM_FAILED=16843856]="ERR_SDK_PUBLISH_AUDIO_STRAM_FAILED",s[s.ERR_SDK_PUBLISH_VIDEO_STRAM_FAILED=16843857]="ERR_SDK_PUBLISH_VIDEO_STRAM_FAILED",s[s.ERR_SDK_PUBLISH_DUAL_STRAM_FAILED=16843858]="ERR_SDK_PUBLISH_DUAL_STRAM_FAILED",s[s.ERR_SDK_PUBLISH_SCEEN_SHARE_FAILED=16843859]="ERR_SDK_PUBLISH_SCEEN_SHARE_FAILED",s[s.ERR_SDK_PUBLISH_SCREEN_SHARE_CONFIG_ERROR=16843860]="ERR_SDK_PUBLISH_SCREEN_SHARE_CONFIG_ERROR",s[s.ERR_SDK_SUBSCRIBE_INVAILD=16974852]="ERR_SDK_SUBSCRIBE_INVAILD",s[s.ERR_SDK_SUBSCRIBE_NOT_JOIN_CHANNEL=16844112]="ERR_SDK_SUBSCRIBE_NOT_JOIN_CHANNEL",s[s.ERR_SDK_SUBSCRIBE_AUDIO_STRAM_FAILED=16844113]="ERR_SDK_SUBSCRIBE_AUDIO_STRAM_FAILED",s[s.ERR_SDK_SUBSCRIBE_VIDEO_STRAM_FAILED=16844114]="ERR_SDK_SUBSCRIBE_VIDEO_STRAM_FAILED",s[s.ERR_SDK_SUBSCRIBE_DUAL_STRAM_FAILED=16844115]="ERR_SDK_SUBSCRIBE_DUAL_STRAM_FAILED",s[s.ERR_SDK_SUBSCRIBE_SCREEN_SHARE_FAILED=16844116]="ERR_SDK_SUBSCRIBE_SCREEN_SHARE_FAILED",s[s.ERR_SDK_INVALID_STATE=16974340]="ERR_SDK_INVALID_STATE",s[s.ERR_INVALID_ARGUMENTS=16974083]="ERR_INVALID_ARGUMENTS",s[s.ERR_SESSION_REMOVED=33620229]="ERR_SESSION_REMOVED",s[s.ERR_SDK_UPDATE_ROLE_CHANNEL=16908801]="ERR_SDK_UPDATE_ROLE_CHANNEL",s[s.ERR_INNER=-1]="ERR_INNER",s[s.ERR_SDK_MPU_TASK_PUBLISH_OK=0]="ERR_SDK_MPU_TASK_PUBLISH_OK",s[s.ERR_SDK_MPU_TASK_STREAM_NOT_FOUND=17825793]="ERR_SDK_MPU_TASK_STREAM_NOT_FOUND",s[s.ERR_SDK_MPU_TASK_STREAM_ALREADY_EXIST=17825794]="ERR_SDK_MPU_TASK_STREAM_ALREADY_EXIST",s[s.ERR_SDK_MPU_TASK_INVALID_PARAM=17825795]="ERR_SDK_MPU_TASK_INVALID_PARAM",s[s.ERR_SDK_MPU_TASK_INTERNAL_ERROR=17825796]="ERR_SDK_MPU_TASK_INTERNAL_ERROR",s[s.ERR_SDK_MPU_TASK_RTMP_SERVER_ERROR=17825797]="ERR_SDK_MPU_TASK_RTMP_SERVER_ERROR",s[s.ERR_SDK_MPU_TASK_RTMP_STREAM_URL_ERROR=17825798]="ERR_SDK_MPU_TASK_RTMP_STREAM_URL_ERROR",s[s.ERR_SDK_MPU_TASK_PUBLISH_TIMEOUT=17825799]="ERR_SDK_MPU_TASK_PUBLISH_TIMEOUT",s[s.ERR_SDK_MPU_TASK_NOT_AUTHORIZED=17825800]="ERR_SDK_MPU_TASK_NOT_AUTHORIZED",s[s.ERR_SDK_CHANNEL_RELAY_STATE_ERROR=18874369]="ERR_SDK_CHANNEL_RELAY_STATE_ERROR",s[s.ERR_SDK_CHANNEL_RELAY_SRC_NOT_ALLOW=18874370]="ERR_SDK_CHANNEL_RELAY_SRC_NOT_ALLOW",s[s.ERR_SDK_CHANNEL_RELAY_JOIN_DEST_FAILED=18874371]="ERR_SDK_CHANNEL_RELAY_JOIN_DEST_FAILED",s[s.ERR_SDK_CHANNEL_RELAY_TOKEN_INVALID=18874372]="ERR_SDK_CHANNEL_RELAY_TOKEN_INVALID",s[s.ERR_SDK_CHANNEL_RELAY_ROLE_ERROR=18874373]="ERR_SDK_CHANNEL_RELAY_ROLE_ERROR",s[s.ERR_SDK_CHANNEL_RELAY_INVALID_PARAM=18874374]="ERR_SDK_CHANNEL_RELAY_INVALID_PARAM",s[s.ERR_SDK_CHANNEL_RELAY_TO_SELF_ERROR=18874375]="ERR_SDK_CHANNEL_RELAY_TO_SELF_ERROR",s))(ce||{});class ne extends Error{constructor(e,t,r){super(t);A(this,"_code");A(this,"_extra");this._code=e,this._extra=r}static fromError(e,t=-1,r=""){return new ne(t,e.message||e.reason||r||"error",e.extraInfo)}get code(){return this._code}set code(e){this._code=e}get reason(){return this.message}get extra(){return this._extra}}const Oc=3e4,ct=class ct extends ve{constructor(e,t,r,i,n,a){super();A(this,"authInfo");A(this,"userName");A(this,"channelProfile");A(this,"clientRole");A(this,"slsReporter");A(this,"wsClient");A(this,"packageCreater");A(this,"keepAliveTimer",0);A(this,"packageCache",new Map);A(this,"isFirstConnect",!0);A(this,"aliveChecker",0);A(this,"reconnectData");this.authInfo=e,this.userName=t,this.packageCreater=new Fc(e,t),this.channelProfile=r,this.clientRole=i,this.slsReporter=n,this.wsClient=new us(a),this.wsClient.on("onOpen",this.onOpen.bind(this)),this.wsClient.on("onMessage",this.onMessage.bind(this)),this.wsClient.on("onError",this.onError.bind(this)),this.wsClient.on("onClose",this.onClose.bind(this)),this.wsClient.on("onConnectFail",this.onConnectFail.bind(this)),this.wsClient.on("onAuthInvalid",this.onAuthInvalid.bind(this)),this.wsClient.on("onNetworkError",this.onNetworkError.bind(this)),this.wsClient.on("onReconnectStart",this.onReconnectStart.bind(this)),this.wsClient.on("onReconnectFail",this.onReconnectFail.bind(this))}get retryCount(){return this.wsClient.connectRetryCount}start(e){this.wsClient.start(e)}startKeepAlive(){this.keepAliveTimer===0&&(this.keepAliveTimer=window.setInterval(()=>{let e=this.packageCreater.createKeepAlivePackage();this.sendPackage(e)},5e3)),this.checkAlive()}stopKeepAlive(){this.keepAliveTimer!==0&&(clearInterval(this.keepAliveTimer),this.keepAliveTimer=0),this.aliveChecker&&(window.clearTimeout(this.aliveChecker),this.aliveChecker=0)}sendPkgCache(){this.packageCache.forEach(e=>{this.wsClient.send(e)})}leave(){let e=this.packageCreater.crateLeavePackage();this.sendPackage(e)}reportStatus(e){let t=this.packageCreater.createStatusPackage(e);this.sendPackage(t)}publish(e){let t=this.packageCreater.createPublishPackage();t.data.users=[],e.subscribe.signal=this.wsClient.connectUrl;const{tracks:r,resume:i}=e;r.forEach(n=>{const{codec:a,ssrc:o}=n;n.userdata=JSON.stringify({codec:a}),n.ssrc=`${o}`,i&&(n.attr={reason:"reconnect"})}),t.data.users.push(e),this.sendPackage(t)}roleUpdate(e){let t=this.packageCreater.createRoleUpdatePackage();t.data.clientrole=e,this.sendPackage(t)}refreshUrl(e){const t=this.packageCreater.createRefreshUrlPackage();t.data=Se(Rt(Se({},t.data),{sessionid:t.header.sessionid}),e),this.sendPackage(t)}refreshAuthInfo(e){this.authInfo=e,this.packageCreater.refreshAuthInfo(e)}close(){oe.info(`[${ct.logName}] close`),this.stopKeepAlive(),this.wsClient.off("onOpen",this.onOpen.bind(this)),this.wsClient.off("onMessage",this.onMessage.bind(this)),this.wsClient.off("onError",this.onError.bind(this)),this.wsClient.off("onClose",this.onClose.bind(this)),this.wsClient.off("onConnectFail",this.onConnectFail.bind(this)),this.wsClient.off("onAuthInvalid",this.onAuthInvalid.bind(this)),this.wsClient.off("onReconnectStart"),this.wsClient.off("onReconnectFail"),this.wsClient.close()}sendPackage(e){[Oe.KEEPALIVE,Oe.RECONNECT,Oe.JOINCHANNEL].includes(e.msgtype)||this.packageCache.set(e.tid,e),this.wsClient.send(e),e.msgtype!==Oe.KEEPALIVE&&this.slsReporter.reportRoomServerEvent(!0,e.msgtype,e.tid,e)}updateReconnectData(e){this.reconnectData=e}onOpen(){if(oe.info(`[${ct.logName}] onOpen`),this.isFirstConnect){let e=this.packageCreater.createJoinPackage();e.data.configure={channelprofile:this.channelProfile},(this.channelProfile===It.AliRtcSdkInteractiveLive||this.channelProfile===It.AliRtcSdkInteractiveWithLowLatencyLive)&&(e.data.configure.clientrole=this.clientRole),this.sendPackage(e)}else{this.stopKeepAlive();const e=this.packageCreater.createReconnectPackage(this.reconnectData);this.sendPackage(e)}}onMessage(e){try{let t=JSON.parse(e.data);this.packageCache.delete(t.tid),this.onRecvMessage(t),t!=null&&t.msgtype&&(t==null?void 0:t.msgtype)!==Oe.KEEPALIVE&&this.slsReporter.reportRoomServerEvent(!1,t.msgtype,t.tid,t)}catch(t){oe.warn(`[${ct.logName}] onMessage err`,t,e)}}onError(e){oe.warn(`[${ct.logName}] onError`,e),this.isFirstConnect&&this.onConnectFail()}onConnectFail(){oe.warn(`[${ct.logName}] onConnectFail`);const e=new ne(ce.ERR_INNER,"Signaling connect failed.");this.isFirstConnect?this.emit("onJoinChannelResult",e):this.emit("onConnectFail",e)}onAuthInvalid(){oe.warn(`[${ct.logName}] onAuthInvalid`),this.isFirstConnect&&this.emit("onAuthInvalid")}onNetworkError(){oe.warn(`[${ct.logName}] onNetworkError`);const e=new ne(ce.ERR_INNER,"Network error, signaling connect failed.");this.emit("onNetworkError",e)}onClose(e){oe.info(`[${ct.logName}] onClose`,e),this.stopKeepAlive()}onKeepAliveRsp(){this.emit("onKeepAliveRsp"),this.checkAlive()}onReconnectStart(){this.emit("onReconnectStart")}onReconnectFail(){this.emit("onReconnectFail",new ne(ce.ERR_INNER,"signaling reconnect failed."))}checkAlive(){window.clearTimeout(this.aliveChecker),this.aliveChecker=window.setTimeout(()=>{oe.info(`[${ct.logName}] not alive, reconnect`),this.stopKeepAlive(),this.emit("onReconnectStart"),this.wsClient.reconnect()},Oc)}onRecvMessage(e){switch(e.msgtype!==Oe.KEEPALIVE&&oe.info(`[${ct.logName}] recv msg: ${e.msgtype}`),e.msgtype){case Oe.JOINCHANNEL:this.onJoinResult(e);break;case Oe.KEEPALIVE:this.onKeepAliveRsp();break;case Oe.PUBLISH:this.onPublishResult(e);break;case Oe.NOTIFYJOIN:this.onNotifyJoin(e);break;case Oe.NOTIFYSTATUS:this.onNotifyStatus(e);break;case Oe.LEAVECHANNEL:this.onLeaveResult(e);break;case Oe.NOTIFYLEAVE:this.onNotifyLeave(e);break;case Oe.NOTIFYPUBLISH:this.onNotifyPublish(e);break;case Oe.STATUSREPORT:this.onStatusReport(e);break;case Oe.BYE:this.onBye(e);break;case Oe.ROLEUPDATE:this.onRoleUpdateResult(e);break;case Oe.REFRESHURL:this.onRefreshUrlResult(e);break;case Oe.RECONNECT:this.onReconnectResult(e);break}}onJoinResult(e){this.isFirstConnect=!1,this.emit("onJoinChannelResult",e)}onLeaveResult(e){this.emit("onLeaveResult",e.code,e.tid)}onPublishResult(e){this.emit("onPublishResult",e.code,e.tid,e.description)}onRoleUpdateResult(e){this.emit("onRoleUpdateResult",e.code,e.tid,e.description)}onRefreshUrlResult(e){this.emit("onRefreshUrlResult",e)}onReconnectResult(e){if(e.code===200)this.sendPkgCache(),this.startKeepAlive(),this.emit("onReconnectSuccess",e.data.users);else{const t=new ne(ce.ERR_INNER,`reconnect failed, code: ${e.code};description: ${e.description}`);e.code===403&&(t.code=403),this.emit("onReconnectFail",t),this.close()}}onNotifyJoin(e){let t=this.packageCreater.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e&&e.data&&e.data.users&&this.emit("onNotifyJoin",e.data.users)}onNotifyStatus(e){let t=this.packageCreater.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e.data&&e.data.status&&e.data.status.length&&this.emit("onNotifyStatus",e.data.status)}onNotifyLeave(e){let t=this.packageCreater.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e.data&&e.data.users&&e.data.users.length&&this.emit("onNotifyLeave",e.data.users)}onNotifyPublish(e){let t=this.packageCreater.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e.data&&e.data.users&&e.data.users.length&&this.emit("onNotifyPublish",e.data.users)}onStatusReport(e){this.emit("onStatusReport",e.code,e.tid,e.description)}onBye(e){this.stopKeepAlive(),this.emit("onBye",e.reason,e.description)}};A(ct,"logName","RSMessageCenter");let hs=ct;const j=(s,c)=>(e,t,r)=>{const i=r.value;return r.value=function(...n){var g;const a=`[${((g=e.constructor)==null?void 0:g.logName)||""}]`,o=Date.now();let u=[];if(s)try{u=s(n)}catch(f){}oe.interface(a,t,...u);const h=i.apply(this,n);return Promise.resolve(h).then(f=>f).catch(f=>f).then(f=>{var m;let l="";const p=f instanceof Error,d=p&&((m=e.constructor)==null?void 0:m.logError);if(!(!c&&!p)){if(d)l=f;else if(p)l=f.message||"";else if(c)if(f===void 0)l="";else try{l=c(f)}catch(x){}else return;oe.interfaceResult(a,t,!(p&&d),`${Date.now()-o}ms`,l)}}),h},r},ae=s=>s;var Vc=Object.defineProperty,Uc=Object.getOwnPropertyDescriptor,ds=(s,c,e,t)=>{for(var r=t>1?void 0:t?Uc(c,e):c,i=s.length-1,n;i>=0;i--)(n=s[i])&&(r=(t?n(c,e,r):n(r))||r);return t&&r&&Vc(c,e,r),r};const Ni=(it=class extends ve{constructor(e,t,r,i=Ct.prod){super();A(this,"messageCenter");A(this,"authInfo");A(this,"userName");A(this,"channelProfile");A(this,"clientRole");A(this,"slsReporter");A(this,"reconnectData");A(this,"roomServerUri","");this.channelProfile=e,this.clientRole=t,this.slsReporter=r,this.reconnectData={role:{channelprofile:e,clientrole:t}};const n=i===Ct.pre?Ei.pre:Ei.prod;this.roomServerUri=`wss://${n}/roomserver/v1/ws`}updateReconnectData(e){var t;this.reconnectData=e,(t=this.messageCenter)==null||t.updateReconnectData(this.reconnectData)}reset(){oe.info("[roomsig] reset"),this.messageCenter&&(this.messageCenter.close(),this.messageCenter=void 0),this.authInfo=void 0}join(e,t,r){return z(this,null,function*(){return new Promise((i,n)=>{const a={};this.authInfo=e,this.userName=t,this.messageCenter=new hs(e,t,this.channelProfile,this.clientRole,this.slsReporter,r),this.initMessageCenter(),this.messageCenter.once("onJoinChannelResult",u=>{var h,g,f;if(oe.info(`[${it.logName}]`,"join result: ",u),a.taskretrynum=((h=this.messageCenter)==null?void 0:h.retryCount)||0,u.code==200){(g=this.messageCenter)==null||g.sendPkgCache(),(f=this.messageCenter)==null||f.startKeepAlive();let l=u.data;l.tid=u.tid,l.users=u.data.users,l.timestamp=u.timestamp,a.est&&(a.joinconnecttc=Date.now()-a.est),this.slsReporter.reportJoinConnection(a),i(l)}else this.reset(),n(this.handleSignalError(u.code,u.reason,ce.ERR_JOIN_CHANNEL_FAILED))}),this.messageCenter.once("onAuthInvalid",()=>{this.reset(),n(new ne(ce.ERR_JOIN_BAD_TOKEN,"join failed because authentication failed"))}),oe.info(`[${it.logName}]`,"start ws connecting roomserver and auto join when connected");const o={appid:this.authInfo.appId,callid:this.authInfo.sessionId,channelid:this.authInfo.channelId,userid:this.authInfo.userId,nonce:this.authInfo.nonce||"",timestamp:this.authInfo.timestamp,token:this.authInfo.token,authtype:"app",tid:Vt()};e.role&&(o.tokenrole=e.role),a.est=Date.now(),this.messageCenter.start(this.roomServerUri+"?"+At.queryingParam(o))})})}leave(){return oe.info("[roomsig] leave .."),new Promise((e,t)=>{this.messageCenter?(this.messageCenter.on("onLeaveResult",(r,i)=>{oe.info(`[${it.logName}]`,"recv leave response "+r),r===200?(this.updateReconnectData(),this.reset(),e({tid:i})):t(this.handleSignalError(r,"leave error"))}),oe.info(`[${it.logName}]`,"send leave request"),this.messageCenter.leave()):(oe.info(`[${it.logName}]`,"no message center, ok to leave"),e({tid:""}))})}publish(e){return new Promise((t,r)=>{var i;this.messageCenter?(this.messageCenter.once("onPublishResult",(n,a,o)=>{oe.info(`[${it.logName}]`,"recv pubish response "+n),n===200?(this.updateReconnectData(Rt(Se({},this.reconnectData),{publish:{users:[e]}})),t({tid:a})):r(this.handleSignalError(n,`publish error, ${o}`))}),this.authInfo&&(e.sessionid=(i=this.authInfo.sessionId)!=null?i:""),e.callid||(e.callid=Vt()),oe.info(`[${it.logName}]`,"assign callid "+e.callid+" and send publish request"),this.messageCenter.publish(e)):r(this.handleSignalError(-1,"publish error, no message center"))})}roleUpdate(e){return new Promise((t,r)=>{if(!this.messageCenter){r(this.handleSignalError(-1,"role update error, no message center"));return}this.messageCenter.on("onRoleUpdateResult",(i,n,a)=>{var o,u;oe.info(`[${it.logName}]`,"recv role update response "+i),i===200?((u=(o=this.reconnectData)==null?void 0:o.role)!=null&&u.clientrole&&(this.reconnectData.role.clientrole=e,this.updateReconnectData(this.reconnectData)),t({tid:n})):r(this.handleSignalError(i,`role update error, ${a}`))}),this.messageCenter.roleUpdate(e)})}setChannelProfile(e){this.channelProfile=e}refreshUrl(e){return oe.info(`[${it.logName}]`,"refreshUrl .."),new Promise((t,r)=>{if(!this.messageCenter){r(this.handleSignalError(-1,"refresh url error, no message center"));return}this.messageCenter.on("onRefreshUrlResult",i=>{const{code:n,description:a,data:o={}}=i||{};oe.info("recv refresh url response "+n),n===200?t(o):r(this.handleSignalError(n,`refresh url error, ${a}`))}),oe.info("send refresh url request"),this.messageCenter.refreshUrl(e)})}reportStatus(e){return oe.info(`[${it.logName}]`,"reportStatus "+e),new Promise((t,r)=>{this.messageCenter?(this.messageCenter.once("onStatusReport",(i,n)=>{i===200?t():r(new ne(i,n))}),this.messageCenter.reportStatus(e)):r(new ne(-1,"No messageCenter"))})}handleSignalError(e,t,r=ce.ERR_INNER){const i=`signal error: code - ${e}; description - ${t}`;return new ne(r,i)}refreshAuthInfo(e){return z(this,null,function*(){var t;this.authInfo&&(this.authInfo=e,(t=this.messageCenter)==null||t.refreshAuthInfo(this.authInfo))})}initMessageCenter(){var e,t,r,i,n,a,o,u,h,g,f,l;(e=this.messageCenter)==null||e.on("onKeepAliveRsp",()=>{this.emit("onKeepAliveRsp")}),(t=this.messageCenter)==null||t.on("onNotifyJoin",p=>{this.emit("onNotifyJoin",p)}),(r=this.messageCenter)==null||r.on("onNotifyStatus",p=>{this.emit("onNotifyStatus",p)}),(i=this.messageCenter)==null||i.on("onNotifyLeave",p=>{this.emit("onNotifyLeave",p)}),(n=this.messageCenter)==null||n.on("onNotifyPublish",p=>{this.emit("onNotifyPublish",p)}),(a=this.messageCenter)==null||a.on("onBye",(p,d)=>{this.emit("onBye",p,d)}),(o=this.messageCenter)==null||o.on("onReconnectStart",()=>{this.emit("onReconnectStart")}),(u=this.messageCenter)==null||u.on("onReconnectSuccess",p=>{this.emit("onReconnectSuccess",p)}),(h=this.messageCenter)==null||h.on("onReconnectFail",p=>{this.emit("onReconnectFail",p)}),(g=this.messageCenter)==null||g.on("onConnectFail",p=>{this.emit("onConnectFail",p),this.reset()}),(f=this.messageCenter)==null||f.on("onNetworkError",p=>{this.emit("onNetworkError",p)}),(l=this.messageCenter)==null||l.on("onAuthInvalid",()=>{this.emit("onAuthInvalid")})}},A(it,"logName","RoomServerSignaling"),it);ds([j()],Ni.prototype,"join",1),ds([j()],Ni.prototype,"publish",1),ds([j()],Ni.prototype,"roleUpdate",1);let zc=Ni;const Hc="https://pgw.rtn.aliyuncs.com",jc="https://gw.rtn.aliyuncs.com",sa=10*60*1e3,Wc=12,_i=class _i extends ve{constructor(e,t){super();A(this,"env");A(this,"authInfo");A(this,"timer");A(this,"slsReporter");A(this,"expiration",0);A(this,"skipTime",0);A(this,"requestToken",()=>z(this,null,function*(){if(this.skipTime=0,!this.authInfo)return;const{appId:e,channelId:t,userId:r,nonce:i="",token:n,timestamp:a,sessionId:o,role:u}=this.authInfo;let h=jc;this.env===Ct.pre&&(h=Hc);const g=`${h}/gslb/v1/stsupdate?appid=${e}&channelid=${t}&userid=${r}&nonce=${i}&token=${n}&timestamp=${a}&session=${o}${u?`&tokenrole=${u}`:""}&slstoken=true&osstoken=true&tokensid=false`;fetch(g).then(f=>f.json()).then(f=>{var l,p;if(f.code===0){const d=(l=f.data)==null?void 0:l.oss,m=(p=f.data)==null?void 0:p.sls;return this.expiration=d.expiration||m.expiration,this.emit("onTokenUpdate",d,m),oe.event(`[${_i.logName}]`,"getToken",d,m),f}this.slsReporter.reportSTSResult(200)}).catch(f=>{this.slsReporter.reportSTSResult(-1),oe.error(`[${_i.logName}]`,"getToken",f.message)})}));this.slsReporter=e,this.env=t}refreshAuthInfo(e){this.authInfo=e}startSTSUpdate(e){this.authInfo=e,this.requestToken(),this.timer&&clearInterval(this.timer),this.timer=window.setInterval(()=>{if(this.expiration&&Math.floor((Date.now()+sa*1.5)/1e3)<this.expiration&&this.skipTime<Wc){this.skipTime+=1;return}this.requestToken()},sa)}clear(){this.timer&&clearInterval(this.timer)}};A(_i,"logName","StsManager");let ls=_i;class Kc extends ve{constructor(e,t,r,i=Ct.prod){super();A(this,"signaling");A(this,"authInfo");A(this,"userName");A(this,"channelProfile");A(this,"clientRole");A(this,"env",Ct.prod);A(this,"maxConnectRetryCount");A(this,"stsManager");A(this,"slsReporter");this.channelProfile=e,this.clientRole=t,this.env=i,this.slsReporter=r,this.stsManager=new ls(r,i)}reset(){var e;oe.info("[signalingmanager] reset"),(e=this.signaling)==null||e.reset(),this.stsManager.clear(),this.signaling=void 0,this.authInfo=void 0}join(e,t=e.userId,r,i){return this.maxConnectRetryCount=r,this.userName=t,new Promise((n,a)=>{this.signaling?a(new ne(ce.ERR_JOIN_ALREADY_JOINED,"already joined")):(oe.info("[signalingmanager] create signaling"),this.signaling=new zc(this.channelProfile,this.clientRole,this.slsReporter,this.env),this.initSignaling(),i&&(i.rs=Date.now()),this.signaling.join(e,t,r).then(o=>{this.authInfo=e,i&&(i.re=Date.now()),n(o)}).catch(o=>{this.reset(),a(o)}),this.stsManager.startSTSUpdate(e))})}retryJoin(){const e=this.authInfo;this.reset(),e&&this.join(e,this.userName,this.maxConnectRetryCount)}leave(){return new Promise((e,t)=>{this.signaling?this.signaling.leave().then(r=>{this.reset(),e(r)}).catch(r=>{t(r)}):e({tid:""})})}publish(e){return new Promise((t,r)=>{var i;this.signaling&&this.authInfo?(e.userid=this.authInfo.userId,e.displayname=(i=this.userName)!=null?i:this.authInfo.userId,this.signaling.publish(e).then(n=>{t(n)}).catch(n=>{r(n)})):r(new ne(ce.ERR_SDK_PUBLISH_NOT_JOIN_CHANNEL,"no signaling"))})}reportStatus(e){return new Promise((t,r)=>{this.signaling?this.signaling.reportStatus(e).then(()=>{t()}).catch(i=>{r(i)}):r(new ne(-1,"no signaling"))})}setClientRole(e){return z(this,null,function*(){const t=this.clientRole;if(!this.signaling){this.clientRole=e;return}const r=Date.now();try{const i=yield this.signaling.roleUpdate(e);return this.slsReporter.reportRoleUpdateResult(t,e,Date.now()-r,0),i}catch(i){this.slsReporter.reportRoleUpdateResult(t,e,Date.now()-r,i.code||-1)}})}setChannelProfile(e){this.signaling?this.signaling.setChannelProfile(e):this.channelProfile=e}refreshUrl(e){return this.signaling?this.signaling.refreshUrl(e):Promise.reject(new ne(ce.ERR_SDK_INVALID_STATE,"should join first"))}refreshAuthInfo(e){return z(this,null,function*(){var t;try{this.authInfo&&(this.authInfo=Se(Se({},this.authInfo),e),(t=this.signaling)==null||t.refreshAuthInfo(this.authInfo),this.stsManager.refreshAuthInfo(this.authInfo))}catch(r){throw r}})}initSignaling(){var e,t,r,i,n,a,o,u,h,g,f,l,p;(e=this.signaling)==null||e.on("onKeepAliveRsp",this.onKeepAliveRsp.bind(this)),(t=this.signaling)==null||t.on("onNotifyJoin",this.onNotifyJoin.bind(this)),(r=this.signaling)==null||r.on("onNotifyStatus",this.onNotifyStatus.bind(this)),(i=this.signaling)==null||i.on("onNotifyLeave",this.onNotifyLeave.bind(this)),(n=this.signaling)==null||n.on("onNotifyPublish",this.onNotifyPublish.bind(this)),(a=this.signaling)==null||a.on("onBye",this.onBye.bind(this)),(o=this.signaling)==null||o.on("onReconnectStart",this.onReconnectStart.bind(this)),(u=this.signaling)==null||u.on("onReconnectSuccess",this.onReconnectSuccess.bind(this)),(h=this.signaling)==null||h.on("onReconnectFail",this.onReconnectFail.bind(this)),(g=this.signaling)==null||g.on("onConnectFail",this.onConnectFail.bind(this)),(f=this.signaling)==null||f.on("onNetworkError",this.onNetworkError.bind(this)),(l=this.signaling)==null||l.on("onAuthInvalid",this.onAuthInvalid.bind(this)),(p=this.signaling)==null||p.on("onError",this.onError.bind(this))}onKeepAliveRsp(){this.emit("onKeepAliveRsp")}onNotifyJoin(e){this.emit("onNotifyJoin",e)}onNotifyStatus(e){this.emit("onNotifyStatus",e)}onNotifyLeave(e){this.emit("onNotifyLeave",e)}onNotifyPublish(e){this.emit("onNotifyPublish",e)}onBye(e,t){this.emit("onBye",e,t)}onConnectFail(e){this.reset(),this.emit("onConnectFail",e)}onNetworkError(e){this.emit("onNetworkError",e)}onAuthInvalid(e){}onReconnectStart(){this.emit("onReconnectStart")}onReconnectSuccess(e){this.emit("onReconnectSuccess",e)}onReconnectFail(e){this.emit("onReconnectFail",e)}onError(e){this.emit("onError",e)}}const Jt=class Jt{static getInstance(){return Jt.instance||(Jt.instance=new AudioContext),Jt.instance.resume(),Jt.instance}};A(Jt,"instance");let ri=Jt;function $c(s,c,e,t,r){let i=t,n=0,a;const o=s.createAnalyser();o.fftSize=256;const u=new Uint8Array(o.frequencyBinCount);c.connect(o),o.connect(e);const h=()=>{a&&window.clearInterval(a)},g=()=>{a=window.setInterval(()=>{o.getByteFrequencyData(u);let f=Math.round(u.reduce((l,p)=>l+p)/u.length);f=Math.min(100,f),n=f,r&&r(f)},i)};return g(),{updateInterval:f=>{h(),i=f,g()},getLevel:()=>n,dispose:()=>{h(),c.disconnect(),o.disconnect()}}}class qc extends ve{constructor(){super();A(this,"audioContext");A(this,"stream");A(this,"sourceNode");A(this,"analyser");this.audioContext=ri.getInstance(),this.stream=new MediaStream}getLevel(){return this.analyser?this.analyser.getLevel():0}start(e,t=1e3){this.sourceNode&&this.stop(),this.stream.addTrack(e),this.sourceNode=this.audioContext.createMediaStreamSource(this.stream);const r=this.audioContext.createMediaStreamDestination();this.analyser=$c(this.audioContext,this.sourceNode,r,t,i=>{this.emit("audioLevel",i)})}stop(){this.analyser&&this.analyser.dispose(),this.analyser=void 0,this.sourceNode=void 0,this.stream.getAudioTracks().forEach(e=>{this.stream.removeTrack(e)})}dispose(){this.stop()}}class na extends ve{constructor(e,t,r,i){super();A(this,"uid");A(this,"name");A(this,"rtsManager");A(this,"callId","");A(this,"audioLevelMonitor");A(this,"audioVolumeIndicationInterval",0);this.uid=e,this.name=t,this.rtsManager=r,this.audioVolumeIndicationInterval=i,this.audioLevelMonitor=new qc}get userId(){return this.uid}get displayname(){return this.name}createCallId(){this.callId||(this.callId=At.createCallid())}setUserInfo(e,t){this.uid=e,this.name=t}refreshUserInfo(e){this.uid=e}getAudioLevel(){return this.audioLevelMonitor.getLevel()}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval=e}clear(){this.audioLevelMonitor.dispose()}}class aa{static getCurrentStatus(c){let e=0;c.micOpen&&(e+=1),c.micInterrupted&&(e+=2),c.cameraOpen&&(e+=4),c.screenShare&&(e+=128),c.audioDisable&&(e+=8),c.videoDisable&&(e+=16),c.screenDisable&&(e+=256);let t=e.toString(16);for(;t.length<16;)t="0"+t;return t}static parseStatus(c){let e=parseInt(c,16);return{micOpen:!!(e&1),micInterrupted:!!(e&2),cameraOpen:!!(e&4),screenShare:!!(e&128),audioDisable:!!(e&8),videoDisable:!!(e&16),screenDisable:!!(e&256),backgroundMode:!!(e&32),accompanyPlaying:!!(e&64)}}}const oa="customVideoProfile",ca="customScreenProfile",gi={width:1280,height:720,frameRate:30,maxBitrate:2e3},vi={width:1920,height:1080,frameRate:30,maxBitrate:2600},Gc={1e4:Fe.AliEngineLocalDeviceExceptionTypeUnknown,2e4:Fe.AliEngineLocalDeviceExceptionTypeUnknown,10001:Fe.AliEngineLocalDeviceExceptionTypeMicNotAvailable,10002:Fe.AliEngineLocalDeviceExceptionTypeMicAuthFail,10003:Fe.AliEngineLocalDeviceExceptionTypeMicOpenFail,10005:Fe.AliEngineLocalDeviceExceptionTypeCameraAuthFail,10004:Fe.AliEngineLocalDeviceExceptionTypeVideoDeviceException,10006:Fe.AliEngineLocalDeviceExceptionTypeCameraOpenFail,10010:Fe.AliEngineLocalDeviceExceptionTypeDisplayException,10011:Fe.AliEngineLocalDeviceExceptionTypeDisplayException,10012:Fe.AliEngineLocalDeviceExceptionTypeDisplayException,10013:Fe.AliEngineLocalDeviceExceptionTypeDisplayException,10014:Fe.AliEngineLocalDeviceExceptionTypeDisplayException,10019:Fe.AliEngineLocalDeviceExceptionTypeDisplayException},Jc=s=>s.getAudioTracks()[0];function ua(s){var c;if(((c=s==null?void 0:s.nodeName)==null?void 0:c.toLowerCase())==="video")return s.setAttribute("playsinline",""),s;if(typeof s=="string"){let e=document.getElementById(s);if(e){if(e.nodeName.toLocaleLowerCase()==="video")return e.setAttribute("playsinline",""),e;throw new ne(ce.ERR_INVALID_ARGUMENTS,"element should be HtmlVideoElement")}else throw new ne(ce.ERR_INVALID_ARGUMENTS,"element not founded")}else throw new ne(ce.ERR_INVALID_ARGUMENTS,"element id should be string")}function fs(s){var e;const c=[];if(Array.isArray(s))s.forEach(t=>{try{c.push(ua(t))}catch(r){}});else if(typeof s=="string"||((e=s==null?void 0:s.nodeName)==null?void 0:e.toLowerCase())==="video")try{c.push(ua(s))}catch(t){}return c}function $t(s){return new Promise(c=>setTimeout(c,s))}const ha=(s,c)=>{const e=()=>(s.muted=!0,Promise.race([$t(500),s._playPromise||Promise.resolve()]).catch(()=>{}).then(()=>{let t;return s.srcObject!==c?(s.load(),s.srcObject=c,t=s.play(),s._playPromise=t):t=Promise.resolve(),t}));return new Promise(t=>{if(me.AliRTS.BrowserUtil.isMicroMessenger){const r=window.top!==window.self,i=window.WeixinJSBridge||window.top.WeixinJSBridge;i?i.invoke("getNetworkType",{},()=>{t(e())}):(r?window.top.document:document).addEventListener("WeixinJSBridgeReady",()=>{i.invoke("getNetworkType",{},()=>{t(e())})}),setTimeout(()=>{t(e())},1e3)}else t(e())})},Bt=s=>{Promise.race([$t(100),s._playPromise||Promise.resolve()]).catch(()=>{}).then(()=>{s.srcObject=null,s._playPromise=void 0})};var Xc=Object.defineProperty,Zc=Object.getOwnPropertyDescriptor,ze=(s,c,e,t)=>{for(var r=t>1?void 0:t?Zc(c,e):c,i=s.length-1,n;i>=0;i--)(n=s[i])&&(r=(t?n(c,e,r):n(r))||r);return t&&r&&Xc(c,e,r),r};const da=30;class Mi extends ve{constructor(){super();A(this,"state");A(this,"time");this.state=be.AliRtcStatePublishIdle,this.time=Date.now()}setState(e){const t=this.state,r=this.time;this.state=e,this.time=Date.now(),this.emit("change",t,e,Math.floor((this.time-r)/1e3))}}const Ve=(Lt=class extends na{constructor(e){const{rtsManager:t,localStreamManager:r,slsReporter:i,signalingManager:n,audioVolumeIndicationInterval:a,parameter:o}=e;super("","",t,a);A(this,"url","");A(this,"joinTime",0);A(this,"_isPublishing",!1);A(this,"publishPromise",Promise.resolve(""));A(this,"previewElements",[]);A(this,"screenPreviewElements",[]);A(this,"streamManager");A(this,"streamTracks");A(this,"publishId",Vt());A(this,"signalingManager");A(this,"traceId","");A(this,"monitorTimerId");A(this,"monitorDataCache",{});A(this,"trackTraceIdMap",{});A(this,"candidateDataCache",[]);A(this,"pcMediaStatsMap",{});A(this,"slsReporter");A(this,"audioPubState");A(this,"videoPubState");A(this,"videoSmallPubState");A(this,"screenPubState");A(this,"parameter",{});A(this,"onTrackEnd",e=>{this.emit(e)});this.streamManager=r,this.signalingManager=n,this.slsReporter=i,this.parameter=o,this.streamManager.on("trackended",u=>{this.onTrackEnd(u)}),this.streamManager.on("publishupdate",()=>{this.publishUpdate()}),this.audioPubState=new Mi,this.audioPubState.on("change",(u,h,g)=>{this.emit("audioPublishStateChanged",u,h,g)}),this.videoPubState=new Mi,this.videoPubState.on("change",(u,h,g)=>{this.emit("videoPublishStateChanged",u,h,g)}),this.videoSmallPubState=new Mi,this.videoSmallPubState.on("change",(u,h,g)=>{this.emit("dualStreamPublishStateChanged",u,h,g)}),this.screenPubState=new Mi,this.screenPubState.on("change",(u,h,g)=>{this.emit("screenPublishStateChanged",u,h,g)}),this.startStreamMonitor()}get joined(){return!!this.uid}get isPublishing(){return this._isPublishing}get publishStreams(){return this.streamManager.publishStreams}get cameraTrack(){return this.streamManager.cameraStreamInfo.originVideoTrack}get screenTrack(){return this.streamManager.screenStreamInfo.originVideoTrack}get audioTrack(){return this.streamManager.cameraStreamInfo.originAudioTrack}get hasCamera(){return!!this.streamManager.cameraStreamInfo.originVideoTrack}get hasMicrophone(){return!!this.streamManager.cameraStreamInfo.originAudioTrack}get hasScreenShare(){return!!this.streamManager.screenStreamInfo.originVideoTrack}get hasCameraTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:r,msid:i})=>r==="video"&&t&&i===Z.VideoLarge))}get hasCameraDualTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:r,msid:i})=>r==="video"&&t&&i===Z.VideoSmall))}get hasScreenTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:r,msid:i})=>r==="video"&&t&&i===Z.Screen))}get hasAudioTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:r,msid:i})=>r==="audio"&&t&&i===Z.Audio))}get cameraDirection(){var e,t;return(t=(e=this.streamManager.cameraStreamInfo)==null?void 0:e.cameraVideoConstraints)==null?void 0:t.facingMode}get audioCaptureDisabled(){return this.streamManager.audioCaptureDisabled}get cameraCaptureDisabled(){return this.streamManager.cameraCaptureDisabled}get publishLocalVideoStreamEnabled(){return this.streamManager.publishLocalVideoStreamEnabled}get publishLocalAudioStreamEnabled(){return this.streamManager.publishLocalAudioStreamEnabled}get publishLocalScreenStreamEnabled(){return this.streamManager.publishLocalScreenStreamEnabled}setPublishLocalAudioStreamEnabled(e){this.streamManager.publishLocalAudioStreamEnabled=e}setPublishLocalVideoStreamEnabled(e){this.streamManager.publishLocalVideoStreamEnabled=e}setPublishLocalScreenStreamEnabled(e){this.streamManager.publishLocalScreenStreamEnabled=e}initInfo(e,t){this.joinTime=Date.now(),this.rtsManager.localJoinTime=this.joinTime,this.setUserInfo(e.userId,e.userId),this.url=t,this.callId=e.sessionId||At.createCallid(),this.updatePubId()}setVideoProfile(e,t){return z(this,null,function*(){yield this.streamManager.setVideoProfile(e,t)})}setVideoContentHint(e){this.streamManager.setVideoContentHint(e)}setScreenContentHint(e){this.streamManager.setScreenContentHint(e)}setAudioProfile(e){return z(this,null,function*(){yield this.streamManager.setAudioProfile(e)})}setScreenProfile(e,t){return z(this,null,function*(){yield this.streamManager.setScreenProfile(e,t)})}setCameraDirection(e){if(e===mi.CAMERA_FRONT)this.streamManager.setCameraVideoConstraints({facingMode:"user"});else if(e===mi.CAMERA_REAR)this.streamManager.setCameraVideoConstraints({facingMode:"environment"});else throw new ne(ce.ERR_CAMERA_OPEN_FAIL,`camera direction set to ${e} failed`)}setCameraDeviceId(e){this.streamManager.setCameraVideoConstraints({deviceId:e})}muteLocalCamera(e){this.streamManager.setCameraMuted(e),this.slsReporter.reportMute(this.callId,!e,"video")}muteLocalMic(e){this.streamManager.setAudioMuted(e),this.slsReporter.reportMute(this.callId,!e,"audio")}muteLocalScreen(e){this.streamManager.setScreenMuted(e),this.slsReporter.reportMute(this.callId,!e,"screen")}setMicrophoneDeviceId(e){this.streamManager.setMicAudioConstraints({deviceId:e})}updatePubId(){this.publishId=Vt()}clearPublishState(){this.streamTracks=void 0}clear(){return z(this,null,function*(){As(Lt.prototype,this,"clear").call(this),this._isPublishing&&(yield this.unPublish()),this.stopPreview(),this.resetPreviewElements(),this.resetSecondayPreviewElements(),this.clearStream(),this.streamManager.cameraCaptureDisabled=!1})}resetElement(e){this.previewElements.includes(e)&&(Bt(e),this.previewElements.splice(this.previewElements.indexOf(e),1)),this.screenPreviewElements.includes(e)&&(Bt(e),this.screenPreviewElements.splice(this.screenPreviewElements.indexOf(e),1))}setPreviewElement(e){const{videoElement:t,screen:r}=e;r?this.screenPreviewElements.includes(t)||this.screenPreviewElements.push(t):this.previewElements.includes(t)||this.previewElements.push(t)}setViewConfig(e,t){if(!e){t===Ae.AliRtcVideoTrackCamera?this.stopPreview({primary:!0,screen:!1}):this.stopPreview({primary:!1,screen:!0});return}if(![Ae.AliRtcVideoTrackCamera,Ae.AliRtcVideoTrackScreen].includes(t))throw new ne(ce.ERR_INVALID_ARGUMENTS,"set view config invalid track",{track:t});e.forEach(r=>{this.setPreviewElement({videoElement:r,screen:t===Ae.AliRtcVideoTrackScreen})})}startCameraCapture(e){return z(this,null,function*(){return this.streamManager.cameraCaptureDisabled=!1,yield this.createLocalStream(e)})}stopCameraCapture(){return z(this,null,function*(){this.streamManager.cameraCaptureDisabled=!0,yield this.stopLocalStream({video:!0})})}stopAudioCapture(){return z(this,null,function*(){this.streamManager.audioCaptureDisabled=!0,yield this.stopLocalStream({audio:!0})})}preview(e){return z(this,null,function*(){const{videoElement:t,screen:r}=e!=null?e:{};try{let i=r?this.streamManager.screenStreamInfo.previewStream:this.streamManager.cameraStreamInfo.previewStream;if(!t)throw new ne(ce.ERR_INVALID_ARGUMENTS,"no video element found",{videoElement:t});if(!i){oe.info(`[${Lt.logName}]`,"preview no stream founded");return}return ha(t,i.mediaStream),this.setPreviewElement(e),i.mediaStream}catch(i){const n=ce.ERR_INNER;throw ne.fromError(i,n,"preview failed")}})}previewAll(e){return z(this,null,function*(){const{primary:t=!0,screen:r=!0}=e!=null?e:{};if(t&&this.previewElements.length)for(let i=0;i<this.previewElements.length;i++){const n=this.previewElements[i];yield this.preview({videoElement:n})}if(r&&this.screenPreviewElements.length)for(let i=0;i<this.screenPreviewElements.length;i++){const n=this.screenPreviewElements[i];yield this.preview({videoElement:n,screen:!0})}})}stopPreview(e){const{videoElement:t,primary:r=!0,screen:i=!0}=e||{};if(!t)r&&(this.previewElements.forEach(n=>{Bt(n)}),this.previewElements=[]),i&&(this.screenPreviewElements.forEach(n=>{Bt(n)}),this.screenPreviewElements=[]);else{const n=this.previewElements.findIndex(a=>a===t);if(n>=0)this.previewElements.splice(n,1),Bt(t);else{const a=this.screenPreviewElements.findIndex(o=>o===t);a>=0&&(this.screenPreviewElements.splice(a,1),Bt(t))}}}resumePublish(){return z(this,null,function*(){this._isPublishing=!1,yield this.startPublish(!0)})}createLocalStream(e){return z(this,null,function*(){try{const t=yield this.streamManager.createLocalStream(e);return t!=null&&t.audioTrack&&this.audioVolumeIndicationInterval>0&&this.audioLevelMonitor.start(t.audioTrack,this.audioVolumeIndicationInterval),e.video?this.previewAll({primary:!0}):e.screen&&this.previewAll({screen:!0}),t}catch(t){const r=Gc[t.errorCode];throw r&&(e.audio?this.emit("localDeviceException",wt.AliEngineLocalDeviceTypeMic,r,""):e.video?this.emit("localDeviceException",wt.AliEngineLocalDeviceTypeCamera,r,""):e.screen?this.emit("localDeviceException",wt.AliEngineLocalDeviceTypeDisplay,r,""):this.emit("localDeviceException",wt.AliEngineLocalDeviceTypeUnknown,r,"")),t}})}stopLocalStream(e){return z(this,null,function*(){e.audio&&this.audioLevelMonitor.stop(),yield this.streamManager.stopLocalStream(e)})}compareAndPublish(e,t,r){return z(this,null,function*(){var n,a;if(!e&&!t)return;if(e&&!t){const o={};return r===Z.Audio?o.audio=!0:r===Z.VideoLarge||r===Z.VideoSmall?(o.video=!0,o.vMsid=r):r===Z.Screen&&(o.screen=!0),yield this.publishDeleteTracks(o)}const i={};if(t!=null&&t.hasVideo&&(i.isScreen=r===Z.Screen,i.vMsid=r),t!=null&&t.hasAudio&&(i.aMsid=r),!e&&t)return yield this.publishAdd(t,i,!1);if(e&&t){const o=e.trackId,u=((n=t.videoTrack)==null?void 0:n.id)||((a=t.audioTrack)==null?void 0:a.id);if(o!==u)return yield this.publishReplace(t,i)}})}reportAudioProfile(){const e=this.streamManager.cameraStreamInfo.audioProfile||"standard",t=me.AliRTS.AudioProfileMap.get(e);this.slsReporter.reportPublishProfile(Z.Audio,{a_profile:e,bits:(t==null?void 0:t.maxBitrate)||0,samplerate:(t==null?void 0:t.sampleRate)||0,channel:(t==null?void 0:t.channelCount)||0})}reportVideoProfile(){const e=this.streamManager.cameraStreamInfo.videoProfile||"",t=me.AliRTS.VideoProfileMap.get(e);t&&this.slsReporter.reportPublishProfile(Z.VideoLarge,{v_profile:e,wdth:(t==null?void 0:t.width)||0,hgt:(t==null?void 0:t.height)||0,fps:(t==null?void 0:t.frameRate)||0,bitrate:(t==null?void 0:t.maxBitrate)||0})}reportScreenProfile(){const e=this.streamManager.screenStreamInfo.videoProfile||"",t=me.AliRTS.VideoProfileMap.get(e);t&&this.slsReporter.reportPublishProfile(Z.Screen,{v_profile:e,wdth:(t==null?void 0:t.width)||0,hgt:(t==null?void 0:t.height)||0,fps:(t==null?void 0:t.frameRate)||0,bitrate:(t==null?void 0:t.maxBitrate)||0})}startPublish(){return z(this,arguments,function*(e=!1,t=Ot.MANUAL){if(!this.joined)return;this.createCallId();const r=yield this.streamManager.publishStreams,{audio:i,video:n,videoSmall:a,screen:o}=r;try{const u=new Date().getTime();i&&this.audioPubState.setState(be.AliRtcStatePublishing),n&&this.videoPubState.setState(be.AliRtcStatePublishing),a&&this.videoSmallPubState.setState(be.AliRtcStatePublishing),o&&this.screenPubState.setState(be.AliRtcStatePublishing),this.publishPromise=this.rtsManager.publish(this.url,this.callId,e,t);const h=yield this.publishPromise;this._isPublishing=!0,this.streamTracks=this.rtsManager.publishingTracks,this.traceId=h,i&&(this.trackTraceIdMap[Z.Audio]=h,this.reportAudioProfile()),a&&(this.trackTraceIdMap[Z.VideoSmall]=h),n&&(this.trackTraceIdMap[Z.VideoLarge]=h,this.reportVideoProfile()),o&&(this.trackTraceIdMap[Z.Screen]=h,this.reportScreenProfile());const g={type:Ft.Add,userid:this.userId,sessionid:"",displayname:this.name,pubid:this.publishId,resume:e,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callId,tracks:this.streamTracks,traceId:h};yield this.syncPublishToRoomServer(g,r,u),i&&this.audioPubState.setState(be.AliRtcStatePublished),n&&this.videoPubState.setState(be.AliRtcStatePublished),a&&this.videoSmallPubState.setState(be.AliRtcStatePublished),o&&this.screenPubState.setState(be.AliRtcStatePublished)}catch(u){throw i&&this.audioPubState.setState(be.AliRtcStateNoPublish),n&&this.videoPubState.setState(be.AliRtcStateNoPublish),a&&this.videoSmallPubState.setState(be.AliRtcStateNoPublish),o&&this.screenPubState.setState(be.AliRtcStateNoPublish),u}})}publishUpdate(){return z(this,null,function*(){var i,n,a,o;if(!this._isPublishing)return;yield this.publishPromise;const e=this.streamManager.publishStreams;let t;const r=new Date().getTime();try{const u=(i=this.streamTracks)==null?void 0:i.find(({ssrc:x,type:v,msid:b})=>v==="audio"&&x&&b===Z.Audio),h=yield this.compareAndPublish(u,e.audio,Z.Audio);h&&(t=h);const g=(n=this.streamTracks)==null?void 0:n.find(({ssrc:x,type:v,msid:b})=>v==="video"&&x&&b===Z.VideoLarge),f=yield this.compareAndPublish(g,e.video,Z.VideoLarge);f&&(t=f);const l=(a=this.streamTracks)==null?void 0:a.find(({ssrc:x,type:v,msid:b})=>v==="video"&&x&&b===Z.VideoSmall),p=yield this.compareAndPublish(l,e.videoSmall,Z.VideoSmall);p&&(t=p);const d=(o=this.streamTracks)==null?void 0:o.find(({ssrc:x,type:v,msid:b})=>v==="video"&&x&&b===Z.Screen),m=yield this.compareAndPublish(d,e.screen,Z.Screen);if(m&&(t=m),!t)return;yield this.syncPublishToRoomServer(t,e,r)}catch(u){const{code:h}=u!=null?u:{},g=this.url;throw h===403&&g&&(yield this.refreshPushStreamUrl(),t=yield this.publishUpdate()),u}return t})}syncPublishToRoomServer(e,t,r){return z(this,null,function*(){if(!e)throw new ne(ce.ERR_INNER,"sync publish to room server failed because no publishInfo");const i=yield this.signalingManager.publish(e);e.signaltid=i.tid})}refreshPushStreamUrl(){return z(this,null,function*(){const e=new ne(ce.ERR_INNER,"refresh push stream url error"),t=this.url;if(!t)throw e;const r=yield this.signalingManager.refreshUrl({pushstreamurl:t});if(!(r!=null&&r.pushstreamurl))throw e;this.url=r==null?void 0:r.pushstreamurl})}publishAdd(e,t,r=!1,i=0){return z(this,null,function*(){this.createCallId();const n=(t==null?void 0:t.aMsid)===Z.Audio,a=(t==null?void 0:t.vMsid)===Z.VideoLarge,o=(t==null?void 0:t.vMsid)===Z.VideoSmall,u=(t==null?void 0:t.vMsid)===Z.Screen;n&&this.audioPubState.setState(be.AliRtcStatePublishing),a&&this.videoPubState.setState(be.AliRtcStatePublishing),o&&this.videoSmallPubState.setState(be.AliRtcStatePublishing),u&&this.screenPubState.setState(be.AliRtcStatePublishing);try{const h=yield this.rtsManager.publishAdd(this.url,e,this.callId,t,!1,0,!0);n&&(this.audioPubState.setState(be.AliRtcStatePublished),this.reportAudioProfile(),this.trackTraceIdMap[Z.Audio]=h),a&&(this.videoPubState.setState(be.AliRtcStatePublished),this.reportVideoProfile(),this.trackTraceIdMap[Z.VideoLarge]=h),o&&(this.videoSmallPubState.setState(be.AliRtcStatePublished),this.trackTraceIdMap[Z.VideoSmall]=h),u&&(this.screenPubState.setState(be.AliRtcStatePublished),this.reportScreenProfile(),this.trackTraceIdMap[Z.Screen]=h),this.streamTracks=this.rtsManager.publishingTracks;const g={type:Ft.Add,userid:this.userId,sessionid:"",displayname:this.name,pubid:this.publishId,resume:r,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callId,tracks:this.streamTracks,traceid:h};return this.reportSelfDeviceStatus(),this.monitorTimerId||this.startStreamMonitor(),g}catch(h){let g=ce.ERR_SDK_PUBLISH_INVAILD;if(n&&(this.audioPubState.setState(be.AliRtcStateNoPublish),g=ce.ERR_SDK_PUBLISH_AUDIO_STRAM_FAILED),a&&(this.videoPubState.setState(be.AliRtcStateNoPublish),g=ce.ERR_SDK_PUBLISH_VIDEO_STRAM_FAILED),o&&(this.videoSmallPubState.setState(be.AliRtcStateNoPublish),g=ce.ERR_SDK_PUBLISH_DUAL_STRAM_FAILED),u&&(this.screenPubState.setState(be.AliRtcStateNoPublish),g=ce.ERR_SDK_PUBLISH_SCEEN_SHARE_FAILED),h.errorCode===15006&&i<3)return this.publishAdd(e,t,r,i+1);throw ne.fromError(h,g,"publish add failed")}})}publishReplace(e,t){return z(this,null,function*(){try{yield this.rtsManager.publishReplace(this.url,e,t),this.streamTracks=this.rtsManager.publishingTracks;const r={type:Ft.Replace,userid:this.userId,sessionid:"",pubid:this.publishId,displayname:this.name,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callId,tracks:this.streamTracks};return this.reportSelfDeviceStatus(),r}catch(r){throw ne.fromError(r,ce.ERR_INNER,`publish replace failed, vMsid: ${t==null?void 0:t.vMsid} aMsid: ${t==null?void 0:t.aMsid}`)}})}publishDeleteTracks(e){return z(this,null,function*(){const t={type:Ft.Delete,userid:this.userId,sessionid:"",displayname:this.displayname,callid:this.callId,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},tracks:[]};try{return yield this.rtsManager.publishDelete(this.url,e),this.streamTracks=this.rtsManager.publishingTracks,e.audio&&this.audioPubState.setState(be.AliRtcStateNoPublish),e.video&&(e.vMsid===Z.VideoSmall?this.videoSmallPubState.setState(be.AliRtcStateNoPublish):this.videoPubState.setState(be.AliRtcStateNoPublish)),e.screen&&this.screenPubState.setState(be.AliRtcStateNoPublish),t.tracks=this.streamTracks,this.reportSelfDeviceStatus(),t}catch(r){throw ne.fromError(r,ce.ERR_INNER,"publish delete tracks failed")}})}publishStop(){return z(this,null,function*(){if(!this._isPublishing)throw new ne(ce.ERR_INNER,"publish stop failed, previous localStream is required for publishing stopping");oe.info(`[${Lt.logName}]`,"publishStop",{url:this.url});const e=new Date().getTime();try{const t=this.hasAudioTrackInMS,r=this.hasCameraTrackInMS,i=this.hasCameraDualTrackInMS,n=this.hasScreenTrackInMS;yield this.rtsManager.publishStop(this.url),t&&this.audioPubState.setState(be.AliRtcStateNoPublish),r&&this.videoPubState.setState(be.AliRtcStateNoPublish),i&&this.videoSmallPubState.setState(be.AliRtcStateNoPublish),n&&this.screenPubState.setState(be.AliRtcStateNoPublish),this.traceId="",Object.keys(this.monitorDataCache).forEach(o=>{this.reportPublishMonitor(o)}),this.streamTracks=[];const a={type:Ft.Stop,userid:this.userId,sessionid:"",displayname:this.displayname,callid:this.callId,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},tracks:[]};return this.syncPublishToRoomServer(a,{},e),a}catch(t){throw ne.fromError(t,ce.ERR_INNER,"publish stop failed")}})}unPublish(){return z(this,null,function*(){const e=new Date().getTime();let t={type:Ft.UnPublish,userid:this.userId,sessionid:"",displayname:this.displayname,callid:this.callId,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},tracks:[]};try{if(this._isPublishing){const r=this.hasAudioTrackInMS,i=this.hasCameraTrackInMS,n=this.hasCameraDualTrackInMS,a=this.hasScreenTrackInMS;yield this.rtsManager.unpublish(),this.streamTracks=[],this.stopStreamMonitor(),r&&this.audioPubState.setState(be.AliRtcStateNoPublish),i&&this.videoPubState.setState(be.AliRtcStateNoPublish),n&&this.videoSmallPubState.setState(be.AliRtcStateNoPublish),a&&this.screenPubState.setState(be.AliRtcStateNoPublish),this._isPublishing=!1,this.traceId="",this.clearStream()}return this.slsReporter.reportUnpublish(this.callId||"",e,0,""),t}catch(r){throw ne.fromError(r,ce.ERR_INNER,"unpublish failed")}})}reportSelfDeviceStatus(){this.emit(et.Local,this.getDeviceStatus())}getDeviceStatus(){var t,r,i,n;let e={micOpen:!1,micInterrupted:!1,cameraOpen:!1,screenShare:!1,audioDisable:!0,videoDisable:!0,screenDisable:!0,backgroundMode:!1,accompanyPlaying:!1};return e.cameraOpen=this.hasCamera,e.micOpen=this.hasMicrophone,e.screenShare=this.hasScreenShare,e.audioDisable=!((t=this.streamManager.cameraStreamInfo.originAudioTrack)!=null&&t.enabled),e.videoDisable=!((r=this.streamManager.cameraStreamInfo.originVideoTrack)!=null&&r.enabled),e.screenDisable=!this.hasScreenShare||!((n=(i=this.streamManager.screenStreamInfo)==null?void 0:i.originVideoTrack)!=null&&n.enabled),aa.getCurrentStatus(e)}resetPreviewElements(){this.previewElements=[]}resetSecondayPreviewElements(){this.screenPreviewElements=[]}getMediaStats(e){return this.pcMediaStatsMap[e]}reportPublishMonitor(e){if(!e)return;let t;try{e===Z.Audio?t=this.rtsManager.getStreamByMsid({url:this.url,aMsid:e}).audioTrack:t=this.rtsManager.getStreamByMsid({url:this.url,vMsid:e}).videoTrack}catch(r){}this.slsReporter.reportPublishMonitor(this.callId,this.trackTraceIdMap[e]||"",e,t,this.monitorDataCache[e]),this.monitorDataCache[e]=[]}reportNetwork(){this.slsReporter.reportNetworkMonitor(this.candidateDataCache),this.candidateDataCache=[]}startStreamMonitor(){this.monitorTimerId||(this.monitorTimerId=window.setInterval(()=>z(this,null,function*(){var e,r;try{const i=yield this.rtsManager.getPCStats();let n;i==null||i.forEach(u=>{u.type==="media-source"||u.type==="media-playout"?u.id&&(this.pcMediaStatsMap[u.id]=u):u.type==="candidate-pair"&&u.state==="succeeded"&&(n=u)});let a;if(((e=this.candidateDataCache)==null?void 0:e.length)>0){const t=this.candidateDataCache[this.candidateDataCache.length-1]||{},{_last:h}=t;a=$i(t,["_last"])}((r=this.candidateDataCache)==null?void 0:r.length)>=da&&this.reportNetwork(),n&&(n._last=a,this.candidateDataCache.push(n));let o=Object.keys(this.monitorDataCache).filter(u=>{var h;return((h=this.monitorDataCache[u])==null?void 0:h.length)>0});(this.streamTracks||[]).forEach(u=>{const h=u.msid;if(!h)return;o.includes(h)&&(o=o.filter(l=>l!==h));let g;h===Z.Audio?g=this.rtsManager.getPublishAudioStats(this.url):g=this.rtsManager.getPublishVideoStats(this.url,h),g.then(l=>{if(!l.timestamp)return;this.monitorDataCache[h]||(this.monitorDataCache[h]=[]);const p=this.getMediaStats(l.mediaSourceId);l._source=p;const d=this.monitorDataCache[h];let m;if((d==null?void 0:d.length)>0){const x=d[d.length-1]||{},{_last:b}=x;m=$i(x,["_last"])}(d==null?void 0:d.length)>=da&&this.reportPublishMonitor(h),l._last=m,l._codec=u.codec||"",this.monitorDataCache[h].push(l)})}),o.forEach(u=>{this.reportPublishMonitor(u)})}catch(i){}}),1e3))}stopStreamMonitor(){this.monitorTimerId&&(clearInterval(this.monitorTimerId),this.monitorTimerId=void 0),Object.keys(this.monitorDataCache).forEach(e=>{this.reportPublishMonitor(e)})}clearStream(){this.streamManager.stop(),this.audioPubState.setState(be.AliRtcStatePublishIdle),this.videoPubState.setState(be.AliRtcStatePublishIdle),this.videoSmallPubState.setState(be.AliRtcStatePublishIdle),this.screenPubState.setState(be.AliRtcStatePublishIdle)}getCurrentCameraDeviceId(){var e;return(e=this.streamManager.cameraStreamInfo.originVideoTrack)==null?void 0:e.getSettings().deviceId}getCurrentMicDeviceId(){var e;return(e=this.streamManager.cameraStreamInfo.originAudioTrack)==null?void 0:e.getSettings().deviceId}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval!==e&&(this.audioVolumeIndicationInterval>0&&e<=0&&this.audioLevelMonitor.stop(),e>0&&this.streamManager.cameraStreamInfo.originAudioTrack&&this.audioLevelMonitor.start(this.streamManager.cameraStreamInfo.originAudioTrack,e),this.audioVolumeIndicationInterval=e)}sendSEI(e,t,r){return z(this,null,function*(){if(!this.url)return;let i=0;return!t||t<1?i=1:i=t-1,this.rtsManager.sendSEI(this.url,e,i,r)})}getStats(){return z(this,null,function*(){const e=[];if(this.hasAudioTrackInMS){const n=yield this.rtsManager.getPublishAudioStats(this.url);n&&e.push({stats:n,track:ii.AliRtcAudioTrackMic})}const t=[];if(this.hasCameraTrackInMS){const n=yield this.rtsManager.getPublishVideoStats(this.url,Z.VideoLarge);n&&t.push({track:Ae.AliRtcVideoTrackCamera,streamType:Je.AliRtcVideoStreamTypeHigh,stats:n})}if(this.hasCameraDualTrackInMS){const n=yield this.rtsManager.getPublishVideoStats(this.url,Z.VideoSmall);n&&t.push({track:Ae.AliRtcVideoTrackCamera,streamType:Je.AliRtcVideoStreamTypeLow,stats:n})}if(this.hasScreenTrackInMS){const n=yield this.rtsManager.getPublishVideoStats(this.url,Z.Screen);n&&t.push({track:Ae.AliRtcVideoTrackScreen,stats:n})}let r;const i=yield this.rtsManager.getPCStats();return i==null||i.forEach(n=>{n.type==="candidate-pair"&&n.state==="succeeded"&&(r=n)}),{audio:e,video:t,candidate:r}})}},A(Lt,"logName","LocalUser"),Lt);ze([j()],Ve.prototype,"clearPublishState",1),ze([j()],Ve.prototype,"clear",1),ze([j()],Ve.prototype,"setViewConfig",1),ze([j()],Ve.prototype,"startCameraCapture",1),ze([j()],Ve.prototype,"stopCameraCapture",1),ze([j()],Ve.prototype,"stopAudioCapture",1),ze([j()],Ve.prototype,"stopPreview",1),ze([j()],Ve.prototype,"resumePublish",1),ze([j()],Ve.prototype,"createLocalStream",1),ze([j()],Ve.prototype,"stopLocalStream",1),ze([j(ae)],Ve.prototype,"startPublish",1),ze([j(([s])=>[s])],Ve.prototype,"syncPublishToRoomServer",1),ze([j()],Ve.prototype,"refreshPushStreamUrl",1),ze([j(([s,c,e])=>[JSON.stringify(e)])],Ve.prototype,"publishAdd",1),ze([j(([s,c])=>[JSON.stringify(c)])],Ve.prototype,"publishReplace",1),ze([j(ae)],Ve.prototype,"publishDeleteTracks",1),ze([j()],Ve.prototype,"publishStop",1),ze([j()],Ve.prototype,"unPublish",1),ze([j(([s,c,e])=>[s.length,c,e])],Ve.prototype,"sendSEI",1);let la=Ve;var qt=(s=>(s.OPUS="opus",s.H264="H264",s.UNKONWN="",s))(qt||{}),Gt=(s=>(s.VideoTrackEnded="videoTrackEnded",s.AudioTrackEnded="audioTrackEnded",s.ScreenTrackEnded="screenTrackEnded",s))(Gt||{});const Yc=s=>{const c=new MediaStream;return c.addTrack(s),c},fa=s=>z(this,null,function*(){return yield me.AliRTS.createStream({custom:!0,mediaStream:s})}),xi=s=>z(this,null,function*(){const c=Yc(s);return yield fa(c)}),Qc=s=>{const{audio:c,video:e,screen:t}=s;if(e&&t)throw new ne(ce.ERR_INNER,"create stream error, cannot create video && screen together");return!(!e&&!c&&!t)},e0=s=>s===Z.Audio||s===rr.Audio,t0=s=>s===Z.VideoLarge||s===rr.VideoLarge,i0=s=>s===Z.VideoSmall,r0=s=>s===Z.Screen;var s0=Object.defineProperty,n0=Object.getOwnPropertyDescriptor,a0=(s,c,e,t)=>{for(var r=t>1?void 0:t?n0(c,e):c,i=s.length-1,n;i>=0;i--)(n=s[i])&&(r=(t?n(c,e,r):n(r))||r);return t&&r&&s0(c,e,r),r};class Fi extends ve{constructor(){super();A(this,"audioInfo",{subscribed:!1,ssrc:"",msid:"",pt:0,red:0,codec:qt.UNKONWN});A(this,"videoLargeInfo",{subscribed:!1,ssrc:"",msid:"",pt:0,red:0,codec:qt.UNKONWN});A(this,"videoSmallInfo",{subscribed:!1,ssrc:"",msid:"",pt:0,red:0,codec:qt.UNKONWN});A(this,"screenInfo",{subscribed:!1,ssrc:"",msid:"",pt:0,red:0,codec:qt.UNKONWN});A(this,"audioVolume",1);A(this,"audioMuted",!1);A(this,"userStatus")}getAudioInfo(){return this.audioInfo}getVideoSmallInfo(){return this.videoSmallInfo}getVideoLargeInfo(){return this.videoLargeInfo}getScreenInfo(){return this.screenInfo}get subscribingInfos(){return[this.audioInfo,this.videoLargeInfo,this.videoSmallInfo,this.screenInfo].filter(e=>e.msid&&e.subscribed)}get hasAudio(){return this.audioInfo.ssrc!==""}get hasVideo(){return this.videoLargeInfo.ssrc!==""||this.videoSmallInfo.ssrc!==""}get hasVideoLarge(){return this.videoLargeInfo.ssrc!==""}get hasVideoSmall(){return this.videoSmallInfo.ssrc!==""}get hasScreen(){return this.screenInfo.ssrc!==""}get isAudioSubscribing(){return!!this.audioInfo.subscribed}get isVideoSubscribing(){return!!this.videoLargeInfo.subscribed||!!this.videoSmallInfo.subscribed}get isVideoLargeSubscribing(){return!!this.videoLargeInfo.subscribed}get isVideoSmallSubscribing(){return!!this.videoSmallInfo.subscribed}get isScreenSubscribing(){return!!this.screenInfo.subscribed}get audioCodec(){return this.audioInfo.codec}get videoCodec(){return this.hasVideoLarge?this.videoLargeInfo.codec:this.hasVideoSmall?this.videoSmallInfo.codec:this.hasScreen?this.screenInfo.codec:qt.UNKONWN}get audioTrackInfo(){return this.hasAudio?ii.AliRtcAudioTrackMic:ii.AliRtcAudioTrackNo}get videoTrackInfo(){return this.hasVideo&&this.hasScreen?Ae.AliRtcVideoTrackBoth:this.hasVideo?Ae.AliRtcVideoTrackCamera:this.hasScreen?Ae.AliRtcVideoTrackScreen:Ae.AliRtcVideoTrackNo}updateTracks(e){let t="",r="",i="",n="";return e?(e.forEach(a=>{var h;let o=qt.UNKONWN;const u=((h=a==null?void 0:a.attr)==null?void 0:h.reason)==="reconnect";if(a.userdata){const{codec:g}=JSON.parse(a.userdata);g&&(o=g)}e0(a.msid)?(t=a.ssrc,this.audioInfo.msid=a.msid,this.audioInfo.codec=o,u&&(this.audioInfo.subscribed=!1)):i0(a.msid)?(i=a.ssrc,this.videoSmallInfo.msid=a.msid,this.videoSmallInfo.codec=o,u&&(this.videoSmallInfo.subscribed=!1)):t0(a.msid)?(r=a.ssrc,this.videoLargeInfo.msid=a.msid,this.videoLargeInfo.codec=o,u&&(this.videoLargeInfo.subscribed=!1)):r0(a.msid)&&(n=a.ssrc,this.screenInfo.msid=a.msid,this.screenInfo.codec=o,u&&(this.screenInfo.subscribed=!1))}),this.updateRemoteTrackSsrc(t,r,i,n)):this.updateRemoteTrackSsrc(t,r,i,n),{}}updateRemoteTrackSsrc(e,t,r,i){this.audioInfo.ssrc=e,this.videoSmallInfo.ssrc=r,this.videoLargeInfo.ssrc=t,this.screenInfo.ssrc=i}updateRemoteTrackSubState(e){return e.video!==void 0&&((e.vMsid===this.videoSmallInfo.msid||!e.vMsid)&&(this.videoSmallInfo.subscribed=e.video),(e.vMsid===this.videoLargeInfo.msid||!e.vMsid)&&(this.videoLargeInfo.subscribed=e.video)),e.screen!==void 0&&(this.screenInfo.subscribed=e.screen),e.audio!==void 0&&(this.audioInfo.subscribed=e.audio),{audioInfo:this.audioInfo,videoLargeInfo:this.videoLargeInfo,videoSmallInfo:this.videoSmallInfo,screenInfo:this.screenInfo}}updateRemoteUserDeviceStatus(e){let t=aa.parseStatus(e);const{audioDisable:r,videoDisable:i,screenDisable:n}=t;return this.userStatus?(this.userStatus.audioDisable!=r&&(this.userStatus.audioDisable=r,this.emit(et.Remote,r?Ie.MuteAudio:Ie.UnmuteAudio)),this.userStatus.videoDisable!=i&&(this.userStatus.videoDisable=i,this.emit(et.Remote,i?Ie.MuteVideo:Ie.UnmuteVideo)),this.userStatus.screenDisable!=n&&(this.userStatus.screenDisable=n,this.emit(et.Remote,n?Ie.MuteScreen:Ie.UnmuteScreen))):(this.userStatus=t,this.emit(et.Remote,r?Ie.MuteAudio:Ie.UnmuteAudio),this.emit(et.Remote,i?Ie.MuteVideo:Ie.UnmuteVideo),this.emit(et.Remote,n?Ie.MuteScreen:Ie.UnmuteScreen)),!1}}A(Fi,"logName","RemoteStreamInfo"),a0([j()],Fi.prototype,"updateRemoteTrackSubState",1);class pa{constructor(c){A(this,"remoteUser");this.remoteUser=c}get userId(){return this.remoteUser.userId}get displayName(){return this.remoteUser.displayname}get isMuteAudioPlaying(){return this.remoteUser.getAudioMuted()}get hasAudio(){return this.remoteUser.hasAudioTrack}get hasCamera(){return this.remoteUser.hasVideoTrack}get hasCameraLarge(){return this.remoteUser.hasVideoLargeTrack}get hasCameraSmall(){return this.remoteUser.hasVideoSmallTrack}get hasScreenShare(){return this.remoteUser.hasScreenTrack}get isAudioSubscribing(){return this.remoteUser.isAudioSubscribing}get isVideoSubscribing(){return this.remoteUser.isVideoSubscribing}get isVideoLargeSubscribing(){return this.remoteUser.isVideoLargeSubscribing}get isVideoSmallSubscribing(){return this.remoteUser.isVideoSmallSubscribing}get isScreenSubscribing(){return this.remoteUser.isScreenSubscribing}}var o0=Object.defineProperty,c0=Object.getOwnPropertyDescriptor,Xe=(s,c,e,t)=>{for(var r=t>1?void 0:t?c0(c,e):c,i=s.length-1,n;i>=0;i--)(n=s[i])&&(r=(t?n(c,e,r):n(r))||r);return t&&r&&o0(c,e,r),r};class bi extends ve{constructor(){super();A(this,"state");A(this,"time");A(this,"_enabled");this.state=Le.AliRtcStateSubscribeIdle,this.time=Date.now(),this._enabled=!0}setState(e){if(this.state===e)return;const t=this.state,r=this.time;this.state=e,this.time=Date.now(),this.emit("change",t,e,Math.floor((this.time-r)/1e3))}get currentState(){return this.state}getEnabled(){return this._enabled}setEnabled(e){this._enabled=e}}const u0=30,Ui=class Ui extends na{constructor(e){var l;const{userId:t,displayName:r,rtsManager:i,usersViewMap:n,slsReporter:a,signalingManager:o,localUser:u,audioVolumeIndicationInterval:h,playoutVolume:g,parameter:f}=e;super(t,r,i,h);A(this,"remoteCallid","");A(this,"remoteUserInfo");A(this,"localUser");A(this,"lastPubId","");A(this,"stream");A(this,"screenStream");A(this,"viewMap");A(this,"audioTrack");A(this,"audioElement");A(this,"subscribed",!1);A(this,"mediaStream");A(this,"secondaryMediaStream");A(this,"prevSubConfig");A(this,"signalingManager");A(this,"slsReporter");A(this,"wantSubAudio",!1);A(this,"wantSubVideo",!1);A(this,"wantSubScreen",!1);A(this,"defaultVideoStreamType",Je.AliRtcVideoStreamTypeHigh);A(this,"audioMuted",!1);A(this,"playoutVolume",1);A(this,"playoutGainNode");A(this,"audioSubState");A(this,"videoSubState");A(this,"videoLargeSubState",new bi);A(this,"videoSmallSubState",new bi);A(this,"screenSubState");A(this,"streamInfo");A(this,"streamUrl","");A(this,"parameter",{});A(this,"monitorTimerId");A(this,"monitorDataCache",{});A(this,"trackTraceIdMap",{});A(this,"handleAudioContextSuspended",e=>{e.target.state==="suspended"&&this.emit("remoteAudioPlayError",this.uid,"AudioContext suspended")});A(this,"handleAudioPaused",()=>{this.emit("remoteAudioPlayError","paused")});this.streamInfo=new Fi,this.remoteUserInfo=new pa(this),this.parameter=f,this.streamInfo.on(et.Remote,p=>{this.emit(et.Remote,p,this.userId)}),this.signalingManager=o,this.viewMap=(l=n[t])!=null?l:{cameraViews:[],screenViews:[]},n[t]=this.viewMap,this.slsReporter=a,this.localUser=u,this.audioSubState=new bi,this.audioSubState.on("change",(p,d,m)=>{this.emit("audioSubscribeStateChanged",this.uid,p,d,m)}),this.videoSubState=new bi,this.videoSubState.on("change",(p,d,m)=>{this.emit("videoSubscribeStateChanged",this.uid,p,d,m)}),this.screenSubState=new bi,this.screenSubState.on("change",(p,d,m)=>{this.emit("screenSubscribeStateChanged",this.uid,p,d,m)}),this.playoutVolume=g}isWantSubAudio(){return this.wantSubAudio}setWantSubAudio(e){this.wantSubAudio=e}isWantSubVideo(){return this.wantSubVideo}setWantSubVideo(e){this.wantSubVideo=e}isWantSubScreen(){return this.wantSubScreen}setWantSubScreen(e){this.wantSubScreen=e}setRemoteDefaultVideoStreamType(e){e!==this.defaultVideoStreamType&&(this.defaultVideoStreamType=e,this.updateSubscribe(Be.User))}setAudioMuted(e){this.audioMuted=e,this.toggleAudio(!e)}setPlayoutVolume(e){if(this.playoutVolume=e,this.audioElement)if(this.parameter.enableAudioContextPlayoutVolume)if(this.playoutGainNode)this.playoutGainNode.gain.value=e;else{const t=this.audioElement.srcObject;if(t){const r=ri.getInstance();r.addEventListener("statechange",this.handleAudioContextSuspended);const i=r.createMediaStreamSource(t);this.audioElement.muted=!0,this.playoutGainNode=r.createGain(),i.connect(this.playoutGainNode),this.playoutGainNode.gain.value=e,this.playoutGainNode.connect(r.destination)}}else this.audioElement.volume=e}getAudioMuted(){return this.audioMuted}get hasAudioTrack(){var e;return!!((e=this.streamInfo)!=null&&e.hasAudio)}get hasVideoTrack(){var e;return!!((e=this.streamInfo)!=null&&e.hasVideo)}get hasVideoLargeTrack(){var e;return!!((e=this.streamInfo)!=null&&e.hasVideoLarge)}get hasVideoSmallTrack(){var e;return!!((e=this.streamInfo)!=null&&e.hasVideoSmall)}get hasScreenTrack(){var e;return!!((e=this.streamInfo)!=null&&e.hasScreen)}get isAudioSubscribing(){var e;return!!((e=this.streamInfo)!=null&&e.isAudioSubscribing)}get isVideoSubscribing(){var e;return!!((e=this.streamInfo)!=null&&e.isVideoSubscribing)}get isVideoLargeSubscribing(){var e;return!!((e=this.streamInfo)!=null&&e.isVideoLargeSubscribing)}get isVideoSmallSubscribing(){var e;return!!((e=this.streamInfo)!=null&&e.isVideoSmallSubscribing)}get isScreenSubscribing(){var e;return!!((e=this.streamInfo)!=null&&e.isScreenSubscribing)}get audioEnabled(){var e,t;return!!((t=(e=this.stream)==null?void 0:e.audioTrack)!=null&&t.enabled)}get videoEnabled(){var e,t;return!!((t=(e=this.stream)==null?void 0:e.videoTrack)!=null&&t.enabled)}get screenEnabled(){var e,t;return!!((t=(e=this.screenStream)==null?void 0:e.videoTrack)!=null&&t.enabled)}get getAudioTrack(){return this.audioTrack}get getCameraStream(){return this.stream}get getScreenStream(){return this.screenStream}setViewConfig(e,t){if(t!==Ae.AliRtcVideoTrackScreen&&t!==Ae.AliRtcVideoTrackCamera)throw new ne(ce.ERR_INVALID_ARGUMENTS,"track is not AliRtcVideoTrackScreen or AliRtcVideoTrackCamera");e?fs(e).forEach(i=>{i.setAttribute("playsinline",""),me.AliRTS.BrowserUtil.isMicroMessenger&&(i.setAttribute("x5-video-player-type","h5-page"),i.setAttribute("x5-playsinline",""),me.AliRTS.SystenUtil.isAndroid||me.AliRTS.SystenUtil.isIos&&i.setAttribute("x-webkit-airplay","allow")),t===Ae.AliRtcVideoTrackScreen?this.viewMap.screenViews.push(i):this.viewMap.cameraViews.push(i),this.play(i,t===Ae.AliRtcVideoTrackScreen)}):(this.stopPlayAll(t===Ae.AliRtcVideoTrackScreen),t===Ae.AliRtcVideoTrackScreen?this.viewMap.screenViews=[]:this.viewMap.cameraViews=[])}clear(e=!0){return z(this,null,function*(){var t;e&&this.doStopSubscribe(this.streamUrl),As(Ui.prototype,this,"clear").call(this),this.clearStream(),this.clearScreenStream(),this.playoutGainNode&&(this.playoutGainNode.disconnect(),this.playoutGainNode=void 0,ri.getInstance().removeEventListener("statechange",this.handleAudioContextSuspended)),(t=this.streamInfo)==null||t.removeAllListeners(et.Remote)})}updateRemoteUserDeviceStatus(e){var t;(t=this.streamInfo)==null||t.updateRemoteUserDeviceStatus(e)}updateRemoteTracks(e,t,r,i){return z(this,null,function*(){var a;return this.remoteCallid=e,this.streamUrl=t!=null?t:"",this.callId=e!=null?e:"",this.streamInfo||(this.streamInfo=new Fi),(a=this.streamInfo)==null?void 0:a.updateTracks(i)})}subscribe(i,n){return z(this,arguments,function*(e,t,r=Date.now()){var l;let a=e;if(!a){const{hasAudio:p,hasVideo:d,hasScreen:m}=(l=this.streamInfo)!=null?l:{};a={audio:this.wantSubAudio&&p,video:this.wantSubVideo&&d,screen:this.wantSubScreen&&m}}const{screen:o,audio:u,video:h,vMsid:g}=a,f=[];(h||u)&&f.push({audio:u,video:h,vMsid:g}),o&&f.push({screen:o}),f.length!==0&&(yield Promise.all(f.map(p=>this.subscribeProxy(p,t||Be.User,r))))})}subscribeProxy(e,t,r){return z(this,null,function*(){var a,o,u,h;let i=new Date().getTime(),n="";try{e.audio&&this.audioSubState.setState(Le.AliRtcStateSubscribing),e.video&&(this.videoSubState.currentState===Le.AliRtcStateSubscribeIdle||this.videoSubState.currentState===Le.AliRtcStateNoSubscribe)&&this.videoSubState.setState(Le.AliRtcStateSubscribing),e.screen&&this.screenSubState.setState(Le.AliRtcStateSubscribing);const g=yield this.rtsManager.subscribe({remoteUser:this,options:e},t,((a=this.localUser)==null?void 0:a.callId)||"",this.callId,r);this.streamInfo.updateRemoteTrackSubState(e),n=g.traceId||"";const{stream:f}=g;if(e.audio){this.trackTraceIdMap[Z.Audio]=n;const p=f.audioTrack;p&&(this.audioTrack=p,(o=f.mediaStream)==null||o.removeTrack(p),this.playAudio(),this.audioVolumeIndicationInterval&&this.audioLevelMonitor.start(p,this.audioVolumeIndicationInterval)),this.audioSubState.setState(Le.AliRtcStateSubscribed),this.audioSubState.getEnabled()||this.toggleAudio(!1)}e.video&&(e.vMsid===Z.VideoSmall?(this.trackTraceIdMap[Z.VideoSmall]=n,this.videoSmallSubState.setState(Le.AliRtcStateSubscribed)):(this.trackTraceIdMap[Z.VideoLarge]=n,this.videoLargeSubState.setState(Le.AliRtcStateSubscribed)),this.videoSubState.setState(Le.AliRtcStateSubscribed),this.videoSubState.getEnabled()||this.toggleVideo(!1),this.updateStream(f,this.isVideoLargeSubscribing&&this.isVideoSmallSubscribing)),e.screen&&(this.trackTraceIdMap[Z.Screen]=n,this.screenSubState.setState(Le.AliRtcStateSubscribed),this.videoSubState.getEnabled()||this.toggleScreen(!1),this.updateScreenStream(f));const l=new Date().getTime()-i;this.slsReporter.reportSubscribe(((u=this.localUser)==null?void 0:u.callId)||"",this.callId,!!e.video&&e.vMsid===Z.VideoLarge,!!e.video&&e.vMsid===Z.VideoSmall,!!e.screen,!!e.audio,0,"",l,{pctid:this.rtsManager.pcTraceId,subtid:n,ajsub:t===Be.Join?1:0,url:this.streamUrl,est:i}),this.startStreamMonitor()}catch(g){const f=new Date().getTime()-i;g&&(g.message=`user(${this.uid}) subscribe error, ${(g==null?void 0:g.message)||""}`);let l=ce.ERR_INNER;e.audio&&(l=ce.ERR_SDK_SUBSCRIBE_AUDIO_STRAM_FAILED),e.video&&(e.vMsid===Z.VideoSmall?l=ce.ERR_SDK_SUBSCRIBE_DUAL_STRAM_FAILED:l=ce.ERR_SDK_SUBSCRIBE_VIDEO_STRAM_FAILED),e.screen&&(l=ce.ERR_SDK_SUBSCRIBE_SCREEN_SHARE_FAILED),this.slsReporter.reportSubscribe(((h=this.localUser)==null?void 0:h.callId)||"",this.callId,!!e.video&&e.vMsid===Z.VideoLarge,!!e.video&&e.vMsid===Z.VideoSmall,!!e.screen,!!e.audio,l,"",f,{pctid:this.rtsManager.pcTraceId,subtid:"",ajsub:t===Be.Join?1:0,url:this.streamUrl,est:i});const p=ne.fromError(g,l);throw this.emit("remoteSubscribeError",p),p}})}subscribeDeleteTracks(e){return z(this,null,function*(){const{audio:t,video:r,screen:i,vMsid:n}=e,a=[];(t||r)&&a.push({audio:t,video:r,vMsid:n}),i&&a.push({screen:i}),a.length!==0&&(yield Promise.all(a.map(o=>this.subscribeDeleteProxy(o))))})}subscribeDeleteProxy(e){return z(this,null,function*(){try{const t=yield this.rtsManager.subscibeDelete({remoteUser:this,options:e}),{stream:r}=t!=null?t:{},i={};e.audio===!0&&(i.audio=!1,this.audioSubState.setState(Le.AliRtcStateNoSubscribe)),e.video===!0&&(i.video=!1,e.vMsid===Z.VideoSmall?(this.videoSmallSubState.setState(Le.AliRtcStateNoSubscribe),(this.videoLargeSubState.currentState===Le.AliRtcStateNoSubscribe||this.videoLargeSubState.currentState===Le.AliRtcStateSubscribeIdle)&&this.videoSubState.setState(Le.AliRtcStateNoSubscribe)):(this.videoLargeSubState.setState(Le.AliRtcStateNoSubscribe),(this.videoSmallSubState.currentState===Le.AliRtcStateNoSubscribe||this.videoSmallSubState.currentState===Le.AliRtcStateSubscribeIdle)&&this.videoSubState.setState(Le.AliRtcStateNoSubscribe))),e.screen===!0&&(i.screen=!1,this.screenSubState.setState(Le.AliRtcStateNoSubscribe));const{callId:n,remoteCallid:a}=this,o={callid:n,remoteCallid:a,remoteStream:r};return e.audio&&(this.audioLevelMonitor.stop(),this.stopPlayAudio(),this.audioTrack=void 0),this.streamInfo.updateRemoteTrackSubState({audio:e.audio===!0?!1:void 0,video:e.video===!0?!1:void 0,screen:e.screen===!0?!1:void 0,vMsid:e.vMsid}),o}catch(t){throw ne.fromError(t,ce.ERR_INNER,"subscribe delete failed")}})}restore(){this.callId="",this.clearStream(),this.clearScreenStream(),this.audioTrack=void 0,this.streamInfo.updateRemoteTrackSubState({audio:!1,video:!1,screen:!1}),this.audioElement&&this.audioElement.removeEventListener("pause",this.handleAudioPaused)}resumeAudio(){return z(this,null,function*(){var t;const e=ri.getInstance();return e.state!=="running"&&e.resume(),(t=this.audioElement)==null?void 0:t.play()})}resumeVideo(e){return z(this,null,function*(){if(!e||e===Ae.AliRtcVideoTrackCamera||e===Ae.AliRtcVideoTrackBoth)return this.playAll();if(!e||e===Ae.AliRtcVideoTrackScreen||e===Ae.AliRtcVideoTrackBoth)return this.playAll(!0)})}resumePlay(){this.playAudio(),this.playAll(),this.playAll(!0)}stopSubscribe(e){return z(this,null,function*(){var r,i;let t=new Date().getTime();try{let n;e?n=yield this.subscribeDeleteTracks(e):n=yield this.doStopSubscribe(this.streamUrl),this.slsReporter.reportUnsubscribe(((r=this.localUser)==null?void 0:r.callId)||(n==null?void 0:n.callid)||"",this.callId,new Date().getTime()-t,0,"")}catch(n){throw this.slsReporter.reportUnsubscribe(((i=this.localUser)==null?void 0:i.callId)||"",this.callId,new Date().getTime()-t,0,""),n}})}doStopSubscribe(e){return z(this,null,function*(){var i,n,a,o;const{callId:t,remoteCallid:r}=this;if((this.isAudioSubscribing||this.isVideoSubscribing||this.isScreenSubscribing)&&e)try{this.stopStreamMonitor(),yield this.rtsManager.subscibeStop(e),this.restore();const u={callid:t,remoteCallid:r,remoteStream:this.stream};return this.callId="",u}catch(u){if(((o=(a=(n=(i=u==null?void 0:u.extraInfo)==null?void 0:i.parsedData)==null?void 0:n.streams)==null?void 0:a[0])==null?void 0:o.res_code)!==404)throw ne.fromError(u,ce.ERR_INNER,"subscribe stop failed")}})}updateStream(e,t=!1){return z(this,null,function*(){this.stream&&this.stream.videoTrack&&e.mediaStream&&t&&(yield new Promise(r=>{let i,n;if(e.mediaStream){n=document.createElement("video");const a=()=>{oe.event(`uid: ${this.userId} new mediaStream canplay`),n&&n.removeEventListener("canplaythrough",a,!1),n=void 0,clearTimeout(i),r(!0)};n.addEventListener("canplaythrough",a,!1),(n._playPromise||Promise.resolve()).then(()=>{n&&e.mediaStream&&(n.srcObject=e.mediaStream)})}else r(!0);i=window.setTimeout(()=>{oe.event(`uid: ${this.userId} new mediaStream timeout`),n=void 0,r(!0)},3e3)}),this.updateSubscribe(Be.User)),this.stream=e,this.playAll(),!this.subscribed&&e&&(this.subscribed=!0),e.hasAudio&&this.isAudioSubscribing&&e.enableAudio(),e.hasVideo&&this.isVideoSubscribing&&e.enableVideo()})}updateScreenStream(e){this.screenStream=e,this.playAll(!0),!this.subscribed&&e&&(this.subscribed=!0),e.hasVideo&&this.isScreenSubscribing&&e.enableVideo()}clearStream(){var e;(e=this.stream)==null||e.stop(),this.stream=void 0}clearScreenStream(){var e;(e=this.screenStream)==null||e.stop(),this.screenStream=void 0}updateSubscribe(e){var n,a,o,u,h,g,f,l;const t=Date.now(),r={},i={};return this.wantSubAudio&&!this.isAudioSubscribing&&((n=this.streamInfo)!=null&&n.hasAudio)?r.audio=!0:(!this.wantSubAudio||!((a=this.streamInfo)!=null&&a.hasAudio))&&this.isAudioSubscribing&&(i.audio=!0),this.wantSubVideo&&((o=this.streamInfo)!=null&&o.hasVideo)?(this.defaultVideoStreamType===Je.AliRtcVideoStreamTypeLow&&!this.isVideoSmallSubscribing&&((u=this.streamInfo)!=null&&u.hasVideoSmall)?(r.video=!0,r.vMsid=Z.VideoSmall):!this.isVideoLargeSubscribing&&((h=this.streamInfo)!=null&&h.hasVideoLarge)&&!(this.defaultVideoStreamType===Je.AliRtcVideoStreamTypeLow&&this.isVideoSmallSubscribing)&&(r.video=!0,r.vMsid=Z.VideoLarge),this.defaultVideoStreamType===Je.AliRtcVideoStreamTypeLow&&this.isVideoLargeSubscribing&&this.isVideoSmallSubscribing&&this.streamInfo.hasVideoSmall?(i.video=!0,i.vMsid=Z.VideoLarge):this.defaultVideoStreamType===Je.AliRtcVideoStreamTypeHigh&&this.isVideoLargeSubscribing&&this.isVideoSmallSubscribing&&(i.video=!0,i.vMsid=Z.VideoSmall)):(!this.wantSubVideo||!((g=this.streamInfo)!=null&&g.hasVideo))&&this.isVideoSubscribing&&(i.video=!0,i.vMsid=this.streamInfo.isVideoSmallSubscribing?Z.VideoSmall:Z.VideoLarge),this.wantSubScreen&&!this.isScreenSubscribing&&((f=this.streamInfo)!=null&&f.hasScreen)?r.screen=!0:(!this.wantSubScreen||!((l=this.streamInfo)!=null&&l.hasScreen))&&this.isScreenSubscribing&&(i.screen=!0),(r.audio||r.video||r.screen)&&(this.createCallId(),this.subscribe(r,e,t)),i.audio&&i.video&&i.screen?this.stopSubscribe():(i.audio||i.video||i.screen)&&this.subscribeDeleteTracks(i),{addOption:r,deleteOption:i}}handleAutoPlayFailed(){this.emit("remoteAudioAutoPlayFail",this.uid);const e=()=>{this.resumeAudio().then(()=>{document.removeEventListener("click",e,!1),document.removeEventListener("touchstart",e,!1)})};document.addEventListener("click",e,!1),document.addEventListener("touchstart",e,!1)}handleVideoPlayFailded(e,t){this.emit("remoteVideoAutoPlayFail",this.uid,t);const r=()=>{var n;const i=(n=t===Ae.AliRtcVideoTrackScreen?this.screenStream:this.stream)==null?void 0:n.mediaStream;e.srcObject===i&&this.play(e,t===Ae.AliRtcVideoTrackScreen),document.removeEventListener("click",r,!1),document.removeEventListener("touchstart",r,!1)};document.addEventListener("click",r,!1),document.addEventListener("touchstart",r,!1)}playAudio(){return z(this,null,function*(){var t,r;if(!this.audioTrack)return;if(this.toggleAudio(!this.audioMuted),this.audioElement||(this.audioElement=document.createElement("audio"),this.audioElement.addEventListener("pause",this.handleAudioPaused),this.setPlayoutVolume(this.playoutVolume)),((r=(t=this.audioElement.srcObject)==null?void 0:t.getAudioTracks())==null?void 0:r[0])!==this.audioTrack){let i=this.audioElement.srcObject;i?i.getAudioTracks().forEach(n=>{i.removeTrack(n)}):(i=new MediaStream,this.audioElement.srcObject=i),i.addTrack(this.audioTrack)}this.audioElement.play().catch(()=>{this.handleAutoPlayFailed()});const e=this.audioElement;this.audioElement.addEventListener("playing",function i(){e.removeEventListener("playing",i),me.AliRTS.SystenUtil.isIos&&parseInt(me.AliRTS.SystenUtil.systemVersion)<=14&&(e.muted||(e.pause(),e.play()))})})}stopPlayAudio(){this.audioElement&&(this.audioElement.pause(),this.audioElement.srcObject=null)}playAll(e=!1){e?(this.viewMap.screenViews||[]).forEach(t=>{this.play(t,e)}):(this.viewMap.cameraViews||[]).forEach(t=>{this.play(t,e)})}play(e,t=!1){const r=t?this.screenStream:this.stream;!e||!r||!r.mediaStream||ha(e,r.mediaStream).catch(i=>{i.code===20||i.name==="AbortError"||this.handleVideoPlayFailded(e,t?Ae.AliRtcVideoTrackScreen:Ae.AliRtcVideoTrackCamera)})}stopPlayAll(e=!1){e?this.viewMap.screenViews.forEach(t=>{Bt(t)}):this.viewMap.cameraViews.forEach(t=>{Bt(t)})}toggleAudio(e=!0){this.audioSubState.setEnabled(e),this.audioTrack&&(this.audioTrack.enabled=e)}toggleVideo(e=!0){this.videoSubState.setEnabled(e),this.stream&&(e?this.stream.enableVideo():this.stream.disableVideo())}toggleScreen(e=!0){this.screenSubState.setEnabled(e),this.screenStream&&(e?this.screenStream.enableVideo():this.screenStream.disableVideo())}getStats(){return z(this,null,function*(){var r,i;const e=[];if(this.isAudioSubscribing){const n=yield this.rtsManager.getSubscribeAudioStats(this.streamUrl);n&&e.push({uid:this.uid,track:ii.AliRtcAudioTrackMic,stats:n})}const t=[];if((r=this.streamInfo)!=null&&r.isVideoLargeSubscribing){const n=yield this.rtsManager.getSubscribeVideoStats(this.streamUrl,Z.VideoLarge);n&&t.push({uid:this.uid,track:Ae.AliRtcVideoTrackCamera,streamType:Je.AliRtcVideoStreamTypeHigh,stats:n})}if((i=this.streamInfo)!=null&&i.isVideoSmallSubscribing){const n=yield this.rtsManager.getSubscribeVideoStats(this.streamUrl,Z.VideoSmall);n&&t.push({uid:this.uid,track:Ae.AliRtcVideoTrackCamera,streamType:Je.AliRtcVideoStreamTypeLow,stats:n})}if(this.isScreenSubscribing){const n=yield this.rtsManager.getSubscribeVideoStats(this.streamUrl,Z.Screen);n&&t.push({uid:this.uid,track:Ae.AliRtcVideoTrackScreen,stats:n})}return{audio:e,video:t}})}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval!==e&&(this.audioVolumeIndicationInterval>0&&e<=0&&this.audioLevelMonitor.stop(),e>0&&this.audioTrack&&this.audioLevelMonitor.start(this.audioTrack,e),this.audioVolumeIndicationInterval=e)}reportSubscribeMonitor(e){var t;e&&(this.slsReporter.reportSubscribeMonitor(((t=this.localUser)==null?void 0:t.callId)||"",this.callId,this.trackTraceIdMap[e]||"",e,this.monitorDataCache[e]),this.monitorDataCache[e]=[])}startStreamMonitor(){this.monitorTimerId||(this.monitorTimerId=window.setInterval(()=>z(this,null,function*(){try{if(this.streamInfo.subscribingInfos.length===0){this.stopStreamMonitor();return}let e=Object.keys(this.monitorDataCache).filter(t=>{var r;return((r=this.monitorDataCache[t])==null?void 0:r.length)>0});this.streamInfo.subscribingInfos.forEach(t=>{const r=t.msid;if(!r)return;e.includes(r)&&(e=e.filter(a=>a!==r));let i;const n=r===Z.Audio;n?i=this.rtsManager.getSubscribeAudioStats(this.streamUrl):i=this.rtsManager.getSubscribeVideoStats(this.streamUrl,r),i.then(a=>{var g;if(!a.timestamp)return;this.monitorDataCache[r]||(this.monitorDataCache[r]=[]);const o=this.monitorDataCache[r];let u;if((o==null?void 0:o.length)>0){const h=o[o.length-1]||{},{_last:l}=h;u=$i(h,["_last"])}(o==null?void 0:o.length)>=u0&&this.reportSubscribeMonitor(r),a._last=u,a._codec=t.codec,n&&(a._source=(g=this.localUser)==null?void 0:g.getMediaStats(a.playoutId)),this.monitorDataCache[r].push(a)})}),e.forEach(t=>{this.reportSubscribeMonitor(t)})}catch(e){}}),1e3))}stopStreamMonitor(){this.monitorTimerId&&(clearInterval(this.monitorTimerId),this.monitorTimerId=void 0),Object.keys(this.monitorDataCache).forEach(e=>{this.reportSubscribeMonitor(e)})}};A(Ui,"logName","RemoteUser");let Ue=Ui;Xe([j()],Ue.prototype,"clear",1),Xe([j()],Ue.prototype,"updateRemoteUserDeviceStatus",1),Xe([j()],Ue.prototype,"updateRemoteTracks",1),Xe([j(ae)],Ue.prototype,"subscribe",1),Xe([j()],Ue.prototype,"subscribeProxy",1),Xe([j(ae)],Ue.prototype,"subscribeDeleteProxy",1),Xe([j()],Ue.prototype,"restore",1),Xe([j(ae)],Ue.prototype,"stopSubscribe",1),Xe([j(ae)],Ue.prototype,"doStopSubscribe",1),Xe([j()],Ue.prototype,"clearStream",1),Xe([j()],Ue.prototype,"clearScreenStream",1),Xe([j()],Ue.prototype,"updateSubscribe",1),Xe([j()],Ue.prototype,"playAudio",1),Xe([j()],Ue.prototype,"stopPlayAudio",1),Xe([j(ae)],Ue.prototype,"playAll",1),Xe([j()],Ue.prototype,"play",1),Xe([j()],Ue.prototype,"stopPlayAll",1);var Pt=(s=>(s[s.AliRtcPluginErrorCodeSuccess=0]="AliRtcPluginErrorCodeSuccess",s[s.AliRtcPluginErrorCodeFailed=-1]="AliRtcPluginErrorCodeFailed",s[s.AliRtcPluginErrorNoFindPlugin=-2]="AliRtcPluginErrorNoFindPlugin",s[s.AliRtcPluginErrorParameterError=-3]="AliRtcPluginErrorParameterError",s[s.AliRtcPluginErrorLoadError=-4]="AliRtcPluginErrorLoadError",s[s.AliRtcPluginErrorCreateError=-5]="AliRtcPluginErrorCreateError",s[s.AliRtcPluginErrorInitError=-6]="AliRtcPluginErrorInitError",s[s.AliRtcPluginErrorInitTokenError=-7]="AliRtcPluginErrorInitTokenError",s))(Pt||{});class h0 extends ve{constructor(){super(...arguments);A(this,"plugins",new Map)}add(e,t){if(this.plugins.has(e.name))throw new ne(Pt.AliRtcPluginErrorCreateError,`Plugin ${e.name} already exists`);this.plugins.set(e.name,e),t&&e.setOptions(t),this.emit("added",e),e.on("enabled",()=>this.emit("added",e)),e.on("disabled",()=>this.emit("removed",e)),e.on("updated",()=>this.emit("updated",e))}remove(e){const t=this.plugins.get(e);if(!t)throw new ne(Pt.AliRtcPluginErrorNoFindPlugin,`Plugin ${e} not founded`);this.plugins.delete(e),t.removeAllListeners(),this.emit("removed",t)}get(e){return this.plugins.get(e)}has(e){return!!this.plugins.get(e)}getAll(){return Array.from(this.plugins.values())}}var d0=Object.defineProperty,l0=Object.getOwnPropertyDescriptor,tt=(s,c,e,t)=>{for(var r=t>1?void 0:t?l0(c,e):c,i=s.length-1,n;i>=0;i--)(n=s[i])&&(r=(t?n(c,e,r):n(r))||r);return t&&r&&d0(c,e,r),r};const Oi=([s])=>{const{remoteUser:c,options:e}=s;return[`user(${c.userId})`,e]},Ye=(_t=class extends ve{constructor(e,t){super();A(this,"rts");A(this,"encodedInsertableStreams",!0);A(this,"audioRedEnabled",!1);A(this,"localStreamManager");A(this,"slsReporter");A(this,"connecting",!1);A(this,"connected",!1);A(this,"_pcTraceId","");A(this,"_localJoinTime",0);A(this,"connectionResolve");A(this,"connectingPromise");A(this,"dcResolve");A(this,"dcConnectingPromise");A(this,"_publishingTracks",[]);this.rts=me.AliRTS.createClient(),this.localStreamManager=e,this.slsReporter=t,this.rts.on("connectStatusChange",r=>{var i,n,a,o;if(oe.event(`[${_t.logName}]`,"rts connectStatusChange to:",r.status),r.status===me.EConnectStatus.CONNECT_STATUS_DISCONNECTED)this.emit("disconnected"),this.setConnected(!1),this.slsReporter.reportWarning("rts disconnected");else if(r.status===me.EConnectStatus.CONNECT_STATUS_RECONNECTING)this.emit("reconnecting"),this.setConnected(!1),this.slsReporter.reportWarning("rts reconnecting");else if(r.status===me.EConnectStatus.CONNECT_STATUS_CONNECTED){this.setConnected(!0);const u=(o=(a=(n=(i=this.rts.commonController)==null?void 0:i.peerCore)==null?void 0:n.getSignal())==null?void 0:a.getDatachannelCore())==null?void 0:o.readyState;oe.event(_t.logName,"dcReadyState:",u),u==="open"&&this.dcResolve&&this.dcResolve(!0),this.emit("connected")}}),this.rts.on("datachannelStatusChange",r=>{oe.event(`[${_t.logName}]`,"rts datachannelStatusChange to:",r.status),r.status===me.EDatachannelStatus.DATACHANNEL_STATUS_OPEN?this.dcResolve&&this.dcResolve(!0):r.status===me.EDatachannelStatus.DATACHANNEL_STATUS_CLOSE&&(this.dcConnectingPromise=new Promise(i=>{this.dcResolve=i}),console.warn("DC DisConnected"))}),this.rts.on("receivedSEI",r=>{this.emit("seimessage",r.url,r.sei.payloadType,r.sei.data)})}get pcTraceId(){return this._pcTraceId}set localJoinTime(e){this._localJoinTime=e}setEncodedInsertableStreams(e){this.encodedInsertableStreams=e}setAudioRedEnabled(e){var t;if(e!==this.audioRedEnabled){try{const i=[...((t=RTCRtpReceiver.getCapabilities("audio"))==null?void 0:t.codecs)||[]];if(i.length>0){if(e){const n=i.findIndex(o=>o.mimeType==="audio/red"),a=i.findIndex(o=>o.mimeType==="audio/opus");if(n>-1&&a>-1&&n>a){const o=i[a];i[a]=i[n],i[n]=o}}this.rts.setSenderCodecPreferences({audio:i}),this.rts.setReceiverCodecPreferences({audio:i})}}catch(r){}this.audioRedEnabled=e}}destroy(){this.rts.unpublish()}startConnect(){this.connecting=!0,this.connectingPromise=new Promise(e=>{this.connectionResolve=e}),this.dcConnectingPromise=new Promise(e=>{this.dcResolve=e})}setConnected(e){var t;this.connected=e,this.connecting=!1,(t=this.connectionResolve)==null||t.call(this,!0),e||(this.dcConnectingPromise=new Promise(r=>{this.dcResolve=r}))}get isConnecting(){return this.connecting}get isConnected(){return this.connected}get publishingTracks(){return this._publishingTracks}getPubMsid(e,t){const{aMsid:r,vMsid:i}=t!=null?t:{},n={};return e.hasAudio&&(n.aMsid=[r!=null?r:Z.Audio]),e.hasScreen&&(n.vMsid=[Z.Screen]),e.hasVideo&&(n.vMsid=[i!=null?i:t!=null&&t.isScreen?Z.Screen:Z.VideoLarge]),n}updatePublishingTracks(e){e&&(this._publishingTracks=e.map(({msid:t,from:r,ssrc:i,codec:n,type:a,trackId:o})=>({msid:t,from:r,type:a,ssrc:`${i}`,codec:n!=null?n:"",trackId:o})))}httpPublish(n,a){return z(this,arguments,function*(e,t,r=!1,i=Ot.MANUAL){const{publishStream:o,videoSmallStream:u,screenStream:h,vMsid:g}=yield this.localStreamManager.createHTTPPublishStream();if(!o)return"";const f=this.getPubMsid(o,{vMsid:g});f.retryTimes=0,this.encodedInsertableStreams&&(f.encodedInsertableStreams=!0);let l=!o.hasVideo,p=g;try{this.startConnect();const d=Date.now(),m=yield this.rts.publish(e,o,f);this.slsReporter.reportPublish(r,e,t,o.hasVideo&&(!g||g===Z.VideoLarge),o.hasVideo&&g===Z.VideoSmall,o.hasVideo&&g===Z.Screen,o.hasAudio,0,m,m,d);const x=Date.now();return this._pcTraceId=m,this.setConnected(!0),this._publishingTracks=this.rts.getPublishTrackInfoList(),u&&(yield this.publishAdd(e,u,t,{vMsid:Z.VideoSmall},r),l=!1,p=Z.VideoSmall),h&&(yield this.publishAdd(e,h,t,{vMsid:Z.Screen},r),l=!1,p=Z.Screen),yield this.waitPublishSender(e,l,p),this.slsReporter.reportPublishFirstPacket(r,t,d,x,this._localJoinTime,l?Z.Audio:f.vMsid,m||"",m||"",i),m}catch(d){throw this.setConnected(!1),d}})}waitPublishSender(e,t=!1,r){return z(this,null,function*(){const i=(n,a)=>{let o=0;const u=()=>(t?this.rts.getPublishAudioStats(e,r):this.rts.getPublishVideoStats(e,r)).then(g=>!(g.bytesSent>0)&&o<n?(o++,new Promise(l=>setTimeout(()=>l(u()),a))):Promise.resolve());return u()};return Promise.race([$t(1e3),i(5,100)]).catch(()=>{})})}getPublishVideoStats(e,t){return z(this,null,function*(){return yield this.rts.getPublishVideoStats(e,t)})}getPublishAudioStats(e,t){return z(this,null,function*(){return yield this.rts.getPublishAudioStats(e,t)})}publishAdd(h,g,f,l){return z(this,arguments,function*(e,t,r,i,n=!1,a=0,o=!1,u=Ot.MANUAL){var m,x,v,b,y,E,I,C;yield this.dcConnectingPromise;const p=Date.now(),d=this.getPubMsid(t,i);try{const R=yield this.rts.publishAdd([Se({url:e,stream:t,updateSourceStream:!1},d)]);if(R){const L=Date.now(),[k]=R;return this.slsReporter.reportPublish(!1,e,r,((m=d.vMsid)==null?void 0:m[0])===Z.VideoLarge,((x=d.vMsid)==null?void 0:x[0])===Z.VideoSmall,((v=d.vMsid)==null?void 0:v[0])===Z.Screen,((b=d.aMsid)==null?void 0:b[0])===Z.Audio,0,this.pcTraceId,k.traceId||"",p),this.updatePublishingTracks(k.trackInfoList),o&&(yield this.waitPublishSender(e,!t.hasVideo,t.hasVideo?i==null?void 0:i.vMsid:i==null?void 0:i.aMsid)),this.slsReporter.reportPublishFirstPacket(n||a>0,r,p,L,this._localJoinTime,(t.hasVideo?i==null?void 0:i.vMsid:i==null?void 0:i.aMsid)||"",this.pcTraceId,k.traceId||"",u),k.traceId||""}}catch(R){if(this.slsReporter.reportPublish(!1,e,r,((y=d.vMsid)==null?void 0:y[0])===Z.VideoLarge,((E=d.vMsid)==null?void 0:E[0])===Z.VideoSmall,((I=d.vMsid)==null?void 0:I[0])===Z.Screen,((C=d.aMsid)==null?void 0:C[0])===Z.Audio,R.errorCode||-1,this.pcTraceId,"",p),R.errorCode===15006&&a<3)return yield this.publishAdd(e,t,r,i,n,a+1);throw R}return""})}publishDelete(e,t){return z(this,null,function*(){var h,g,f,l,p,d,m,x;yield this.dcConnectingPromise;const r=(g=(h=this.publishingTracks)==null?void 0:h.find(({msid:v})=>v===Z.Audio))==null?void 0:g.msid,i=(l=(f=this.publishingTracks)==null?void 0:f.find(({msid:v})=>v===Z.VideoLarge))==null?void 0:l.msid,n=(d=(p=this.publishingTracks)==null?void 0:p.find(({msid:v})=>v===Z.Screen))==null?void 0:d.msid,a=[];t.screen&&n?a.push(n):t.video&&a.push(t.vMsid||i);const o=[];t.audio&&r&&o.push(r),oe.event(_t.logName,"publishDelete",{streamUrl:e,aMsid:o,vMsid:a});const[u]=(yield this.rts.publishDeleteTracks([{url:e,aMsid:o,vMsid:a}]))||[];return oe.event(_t.logName,"publishDelete",{result:u}),u&&this.updatePublishingTracks(u.trackInfoList),((x=(m=u==null?void 0:u.trackInfoList)==null?void 0:m[0])==null?void 0:x.trackId)||""})}publishReplace(e,t,r){return z(this,null,function*(){var u,h;yield this.dcConnectingPromise;const{vMsid:i,aMsid:n}=r!=null?r:{},a=yield this.rts.publishReplaceTracks([{url:e,stream:t,updateSourceStream:!1,vMsid:i,aMsid:n}]),[o]=a;return this.updatePublishingTracks(o.trackInfoList),((h=(u=o==null?void 0:o.trackInfoList)==null?void 0:u[0])==null?void 0:h.trackId)||""})}publishStop(e){return z(this,null,function*(){return yield this.rts.publishStop([{url:e}]),this._publishingTracks=[],""})}unpublish(){return z(this,null,function*(){yield this.rts.unpublish(),this.connecting=!1,this.connected=!1})}getSubConfig(e,t){let r=t!=null?t:{};t||(r={audio:!0,video:!0,screen:!0});const i={};return r.audio&&(i.aMsid=[(e==null?void 0:e.getAudioInfo().msid)||Z.Audio]),r.video?r.vMsid?i.vMsid=[r.vMsid]:e!=null&&e.hasVideoLarge?i.vMsid=[(e==null?void 0:e.getVideoLargeInfo().msid)||Z.VideoLarge]:e!=null&&e.hasVideoSmall?i.vMsid=[(e==null?void 0:e.getVideoSmallInfo().msid)||Z.VideoSmall]:i.vMsid=[Z.VideoLarge]:r.screen&&e!=null&&e.hasScreen&&(i.vMsid=[(e==null?void 0:e.getScreenInfo().msid)||Z.Screen]),i}httpSubscribe(e){return z(this,null,function*(){const{remoteUser:t,options:r}=e;let i=t.streamUrl;r.video||r.screen?r!=null&&r.audio||(i+="@subaudio=no"):i+="@subvideo=no";const n=this.getSubConfig(t.streamInfo,r);n.retryTimes=0,this.encodedInsertableStreams&&(n.encodedInsertableStreams=!0);try{this.startConnect();const a=yield this.rts.subscribe(i,n);return this._pcTraceId=a.traceId,this.setConnected(!0),{traceId:a.traceId,stream:a}}catch(a){throw this.setConnected(!1),a}})}subscribeAdd(e){return z(this,null,function*(){var n,a,o,u;const{remoteUser:t,options:r}=e,i=Rt(Se({url:t.streamUrl,subAudio:!!r.audio,subVideo:!!(r.screen||r.video)},this.getSubConfig(t.streamInfo,r)),{targetStream:r.screen?t.getScreenStream:t.getCameraStream});try{return(yield this.rts.subscribeAdd([i]))[0]}catch(h){if(((u=(o=(a=(n=h==null?void 0:h.extraInfo)==null?void 0:n.parsedData)==null?void 0:a.streams)==null?void 0:o[0])==null?void 0:u.res_code)===508)return this.emit("subscribeexceeds"),null;throw ne.fromError(h)}})}subscibeDelete(e){return z(this,null,function*(){var n,a,o,u;yield this.dcConnectingPromise;const{remoteUser:t,options:r}=e,i=Rt(Se({url:t.streamUrl,subAudio:!!r.audio,subVideo:!!(r.screen||r.video)},this.getSubConfig(t.streamInfo,r)),{targetStream:r.screen?t.getScreenStream:t.getCameraStream});try{return(yield this.rts.subscribeDeleteTracks([i]))[0]}catch(h){if(((u=(o=(a=(n=h==null?void 0:h.extraInfo)==null?void 0:n.parsedData)==null?void 0:a.streams)==null?void 0:o[0])==null?void 0:u.res_code)===404)return;throw h}})}subscibeStop(e){return z(this,null,function*(){var t,r,i,n;try{yield this.rts.subscribeStop([{url:e}])}catch(a){if(((n=(i=(r=(t=a==null?void 0:a.extraInfo)==null?void 0:t.parsedData)==null?void 0:r.streams)==null?void 0:i[0])==null?void 0:n.res_code)===404)return;throw a}})}publish(n,a){return z(this,arguments,function*(e,t,r=!1,i=Ot.MANUAL){let o="";if(this.connecting&&(yield this.connectingPromise),this.connected){yield this.dcConnectingPromise;let u=!1,h;const{audio:g,video:f,videoSmall:l,screen:p}=this.localStreamManager.publishStreams;g&&(o=yield this.publishAdd(e,g,t,{aMsid:Z.Audio},r),u=!0,h=Z.Audio,yield $t(100)),f&&(o=yield this.publishAdd(e,f,t,{vMsid:Z.VideoLarge},r),u=!1,h=Z.VideoLarge,yield $t(100)),l&&(o=yield this.publishAdd(e,l,t,{vMsid:Z.VideoSmall},r),u=!1,h=Z.VideoSmall,yield $t(100)),p&&(o=yield this.publishAdd(e,p,t,{isScreen:!0,vMsid:Z.Screen},r),u=!1,h=Z.Screen),h&&(yield this.waitPublishSender(e,u,h))}else o=yield this.httpPublish(e,t,r,i);return o})}subscribe(e,t,r,i,n){return z(this,null,function*(){const{options:a,remoteUser:o}=e;if(a.video&&a.screen)throw new ne(ce.ERR_INNER,"subscribe error, video and screen cannot be subscribed at the same time");this.connecting&&(yield this.connectingPromise);let u,h=Date.now();this.connected?(yield this.dcConnectingPromise,h=Date.now(),u=yield this.subscribeAdd(e)):u=yield this.httpSubscribe(e);const g=Date.now();let f=Z.VideoLarge,l=a.video||a.screen,p=a.audio;a.video&&a.vMsid?f=a.vMsid:a.screen&&(f=Z.Screen);let d=0,m=0,x=0;return((b,y)=>{let E=0;const I=()=>{let C;return p&&!d&&(C=this.rts.getSubscribeAudioStats(o.streamUrl).then(R=>{if(R.packetsReceived>0)d=Date.now();else if(!l)return E<b?(E++,new Promise(L=>setTimeout(()=>L(I()),y))):!1;return!0})),l&&!x&&(C=this.rts.getSubscribeVideoStats(o.streamUrl,f).then(R=>{if(R.packetsReceived>0&&(m=Date.now()),R.framesDecoded>0)x=Date.now();else return E<b?(E++,new Promise(L=>setTimeout(()=>L(I()),y))):(oe.error(`[${_t.logName}]`,"checkInStatsWithRetry fail"),!1);return!0})),Promise.resolve(C)};return I()})(20,100).then(()=>{m&&this.slsReporter.reportSubscribeFirstPacket(t===Be.Resume,r,i,f,{fprt:m-h,ifsprtc:x?x-h:0,ajsub:t===Be.Join?1:0,pctid:this.pcTraceId,subtid:(u==null?void 0:u.traceId)||"",sstc:g-h}),x&&this.slsReporter.reportSubscribeFirstFrame(t===Be.Resume,r,i,f,{fvfrt:x-h,fp2fftc:x-m,ajsub:t===Be.Join?1:0,tffrtc:t===Be.Join?x-this.localJoinTime:x-n,pctid:this.pcTraceId,subtid:(u==null?void 0:u.traceId)||"",fvfdtc:x-h}),d&&this.slsReporter.reportSubscribeFirstPacket(t===Be.Resume,r,i,Z.Audio,{fprt:d-h,ifsprtc:d-h,ajsub:t===Be.Join?1:0,pctid:this.pcTraceId,subtid:(u==null?void 0:u.traceId)||"",sstc:g-h})}),u})}getSubscribeVideoStats(e,t){return z(this,null,function*(){return yield this.rts.getSubscribeVideoStats(e,t)})}getSubscribeAudioStats(e,t){return z(this,null,function*(){return yield this.rts.getSubscribeAudioStats(e,t)})}getStreamByMsid(e){return this.rts.commonController.streamManager.getStreamByMsid(e)}getPCStats(){return z(this,null,function*(){var e,t;return(t=(e=this.rts.commonController.peerCore)==null?void 0:e.pc)==null?void 0:t.getStats()})}sendSEI(e,t,r,i){return z(this,null,function*(){return this.rts.sendSEI({url:e,vMsid:Z.VideoLarge,data:t,repeatCount:r,payloadType:i})})}},A(_t,"logName","RtsManager"),_t);tt([j()],Ye.prototype,"updatePublishingTracks",1),tt([j(ae,ae)],Ye.prototype,"httpPublish",1),tt([j(ae,ae)],Ye.prototype,"waitPublishSender",1),tt([j(([s,c,e])=>[s,JSON.stringify(e)],ae)],Ye.prototype,"publishAdd",1),tt([j(ae,ae)],Ye.prototype,"publishDelete",1),tt([j(([s,c,e])=>[s,JSON.stringify(e)])],Ye.prototype,"publishReplace",1),tt([j(ae)],Ye.prototype,"publishStop",1),tt([j()],Ye.prototype,"unpublish",1),tt([j(Oi,({traceId:s})=>s)],Ye.prototype,"httpSubscribe",1),tt([j(Oi,({traceId:s})=>s)],Ye.prototype,"subscribeAdd",1),tt([j(Oi)],Ye.prototype,"subscibeDelete",1),tt([j(ae)],Ye.prototype,"subscibeStop",1),tt([j(ae)],Ye.prototype,"publish",1),tt([j(Oi)],Ye.prototype,"subscribe",1),tt([j()],Ye.prototype,"sendSEI",1);let f0=Ye;class ps{constructor(){A(this,"profile");A(this,"profileMap",new Map);A(this,"audioProfile");A(this,"contentHint")}updateProfile(c,e){e&&this.profileMap.set(c,e),this.profile=c}get videoProfile(){return this.profile}updateAudioProfile(c){this.audioProfile=c}setContentHint(c,e){e&&(this.contentHint=e),this.contentHint&&c&&(c.contentHint=this.contentHint)}setVideoProfile(c,e,t=!1){return z(this,null,function*(){if(!this.profile)return;const r=this.profileMap.get(this.profile)||(e==null?void 0:e.VideoProfileMap.get(this.profile));if(r){if(!t&&c&&c.applyConstraints)try{yield c.applyConstraints(r)}catch(i){}e&&(e==null||e.VideoProfileMap.set(this.profile,r),yield e.setVideoProfile(this.profile))}})}}class ms extends ve{constructor(e){super();A(this,"type");A(this,"originVideoTrack");A(this,"videoSource");A(this,"_videoMuted",!1);A(this,"originAudioTrack");A(this,"audioSource");A(this,"_audioMuted",!1);A(this,"_targetVideoTrack");A(this,"_targetDualVideoTrack");A(this,"_targetAudioTrack");A(this,"_publishVideoStream");A(this,"_publishDualVideoStream");A(this,"_publishAudioStream");A(this,"_previewStream");A(this,"plugins",[]);A(this,"_profileManager");A(this,"cameraVideoConstraints");A(this,"micAudioConstraints");A(this,"onVideoTrackEnded",()=>{this.emit("videotrackended")});A(this,"onAudioTrackEnded",()=>{this.emit("audiotrackended")});this.type=e}get profileManager(){return this._profileManager}get audioProfile(){var e;return(e=this.profileManager)==null?void 0:e.audioProfile}updateSource(e,t,r){return z(this,null,function*(){var a,o,u,h,g,f;const{videoTrack:i,audioTrack:n}=e;i&&((a=this.originVideoTrack)==null||a.removeEventListener("ended",this.onVideoTrackEnded)),n&&((o=this.originAudioTrack)==null||o.removeEventListener("ended",this.onAudioTrackEnded)),this.type===Ke.AliRtcSdkStreamTypeScreen?this.stop():(i&&((u=this.originVideoTrack)==null||u.stop()),n&&((h=this.originAudioTrack)==null||h.stop())),i&&(this.originVideoTrack=i,(g=this.originVideoTrack)==null||g.addEventListener("ended",this.onVideoTrackEnded),this.videoSource=t||Yt.Camera,this.updateVideoTrack(i)),n&&(this.originAudioTrack=n,(f=this.originAudioTrack)==null||f.addEventListener("ended",this.onAudioTrackEnded),this.audioSource=r||yi.Microphone,this.updateAudioTrack(n))})}get currentProfile(){var e;return(e=this.profileManager)==null?void 0:e.profile}get currentVideoTrack(){return this._targetVideoTrack}get currentDualVideoTrack(){return this._targetDualVideoTrack}get publishVideoStream(){return this._publishVideoStream}get publishDualVideoStream(){return this._publishDualVideoStream}get currentAudioTrack(){return this._targetAudioTrack}get publishAudioStream(){return this._publishAudioStream}get previewStream(){return this._previewStream}updateVideoTrack(e,t=!1){return z(this,null,function*(){(this._targetVideoTrack!==e||t)&&(this._targetVideoTrack=e)})}updateDualVideoTrack(e,t=!1){return z(this,null,function*(){(this._targetDualVideoTrack!==e||t)&&(this._targetDualVideoTrack=e)})}updateAudioTrack(e,t=!1){return z(this,null,function*(){(this._targetAudioTrack!==e||t)&&(this._targetAudioTrack=e)})}setAudioMuted(e){var t,r;this._audioMuted=e,e?(t=this.publishAudioStream)==null||t.disableAudio():(r=this.publishAudioStream)==null||r.enableAudio()}get isAudioMuted(){return this._audioMuted}setVideoMuted(e){var t,r;this._videoMuted=e,e?(t=this.publishVideoStream)==null||t.disableVideo():(r=this.publishVideoStream)==null||r.enableVideo()}get isVideoMuted(){return this._videoMuted}process(e){return z(this,null,function*(){var t,r,i,n,a,o,u,h,g,f,l,p;this._targetAudioTrack=this.originAudioTrack,this._targetVideoTrack=this.originVideoTrack;for(const d of this.plugins)try{yield d.execute(this,e)}catch(m){console.error(`error in plugin-${d.name}, error: ${m}`)}this._targetVideoTrack?((r=(t=this._publishVideoStream)==null?void 0:t.videoTrack)==null?void 0:r.id)!==this._targetVideoTrack.id&&(this._publishVideoStream=yield xi(this._targetVideoTrack),this.setVideoMuted(this._videoMuted),(i=this.profileManager)==null||i.setVideoProfile(this.originVideoTrack,this._publishVideoStream,!0),(n=this.profileManager)==null||n.setContentHint(this._targetVideoTrack),this.previewStream?(a=this.previewStream)==null||a.mergeStream(this._publishVideoStream):this._previewStream=yield xi(this._targetVideoTrack)):(this._publishVideoStream=void 0,(o=this.previewStream)==null||o.deleteTracks({video:!0})),this._targetDualVideoTrack?((h=(u=this._publishDualVideoStream)==null?void 0:u.videoTrack)==null?void 0:h.id)!==this._targetDualVideoTrack.id&&(this._publishDualVideoStream=yield xi(this._targetDualVideoTrack),this._videoMuted?this._publishDualVideoStream.disableVideo():this._publishDualVideoStream.enableVideo()):this._publishDualVideoStream=void 0,this._targetAudioTrack?((f=(g=this._publishAudioStream)==null?void 0:g.audioTrack)==null?void 0:f.id)!==this._targetAudioTrack.id&&(this._publishAudioStream=yield xi(this._targetAudioTrack),this.setAudioMuted(this._audioMuted),this.previewStream?(l=this.previewStream)==null||l.mergeStream(this._publishAudioStream):this._previewStream=yield xi(this._targetAudioTrack)):(this._publishAudioStream=void 0,(p=this.previewStream)==null||p.deleteTracks({audio:!0}))})}stopVideo(){var e,t;this.originVideoTrack&&((e=this.originVideoTrack)==null||e.removeEventListener("ended",this.onAudioTrackEnded),(t=this.originVideoTrack)==null||t.stop(),this.originVideoTrack=void 0),this.updateVideoTrack(void 0)}stopAudio(){var e,t;this.originAudioTrack&&((e=this.originAudioTrack)==null||e.removeEventListener("ended",this.onAudioTrackEnded),(t=this.originAudioTrack)==null||t.stop(),this.originAudioTrack=void 0),this.updateAudioTrack(void 0)}stop(){this.stopVideo(),this.stopAudio()}updateVideoProfile(e,t){return z(this,null,function*(){this._profileManager||(this._profileManager=new ps),e&&this._profileManager.updateProfile(e,t),yield this._profileManager.setVideoProfile(this.originVideoTrack,this._publishVideoStream,this.type===Ke.AliRtcSdkStreamTypeScreen)})}get videoProfile(){var e;return(e=this.profileManager)==null?void 0:e.videoProfile}setVideoContentHint(e){this._profileManager||(this._profileManager=new ps),this._profileManager.setContentHint(this.currentVideoTrack,e)}updateAudioProfile(e){return z(this,null,function*(){this._profileManager||(this._profileManager=new ps),this._profileManager.updateAudioProfile(e)})}cloneVideoProfile(e){return z(this,null,function*(){var t;yield(t=this.profileManager)==null?void 0:t.setVideoProfile(void 0,e)})}addPlugin(e){const t=this.plugins.findIndex(r=>r.zIndex>e.zIndex);t>-1?this.plugins.splice(t,0,e):this.plugins.push(e)}removePlugin(e){const t=this.plugins.indexOf(e);return t>-1?(e.clear(this),this.plugins.splice(t,1),!0):!1}}var p0=Object.defineProperty,m0=Object.getOwnPropertyDescriptor,bt=(s,c,e,t)=>{for(var r=t>1?void 0:t?m0(c,e):c,i=s.length-1,n;i>=0;i--)(n=s[i])&&(r=(t?n(c,e,r):n(r))||r);return t&&r&&p0(c,e,r),r};const gt=(si=class extends ve{constructor(e,t){super();A(this,"pluginManager");A(this,"slsReporter");A(this,"publishingCameraVideoStream");A(this,"publishingScreenVideoStream");A(this,"cameraStreamInfo",new ms(Ke.AliRtcSdkStreamTypeCapture));A(this,"screenStreamInfo",new ms(Ke.AliRtcSdkStreamTypeScreen));A(this,"streamInfos",[this.cameraStreamInfo,this.screenStreamInfo]);A(this,"_audioCaptureDisabled",!1);A(this,"_cameraCaptureDisabled",!1);A(this,"_publishLocalAudioStreamEnabled",!0);A(this,"_publishLocalVideoStreamEnabled",!0);A(this,"_publishLocalScreenStreamEnabled",!0);this.screenStreamInfo.setVideoContentHint("motion"),this.pluginManager=e,this.slsReporter=t;const r=i=>z(this,null,function*(){if(oe.info(`[${si.logName}]`,"plugin added",i.name),!i.isSupported("6.11.8")){console.warn(`${i.name} is not supported!!!`),i.emit("unsupported");return}try{yield i.init()}catch(n){i.emit("error",ne.fromError(n,Pt.AliRtcPluginErrorInitError))}i.streamType===Ke.AliRtcSdkStreamTypeCapture&&(this.cameraStreamInfo.addPlugin(i),yield this.cameraStreamInfo.process(this.streamInfos)),i.streamType===Ke.AliRtcSdkStreamTypeScreen&&(this.screenStreamInfo.addPlugin(i),yield this.screenStreamInfo.process(this.streamInfos)),this.emit("publishupdate")});this.cameraStreamInfo.updateVideoProfile(oa,gi),this.cameraStreamInfo.on("videotrackended",()=>z(this,null,function*(){yield this.stopLocalStream({video:!0}),this.emit("trackended",Gt.VideoTrackEnded)})),this.cameraStreamInfo.on("audiotrackended",()=>z(this,null,function*(){yield this.stopLocalStream({audio:!0}),this.emit("trackended",Gt.AudioTrackEnded)})),this.screenStreamInfo.updateVideoProfile(ca,vi),this.screenStreamInfo.on("videotrackended",()=>z(this,null,function*(){yield this.stopLocalStream({screen:!0}),this.emit("trackended",Gt.ScreenTrackEnded)})),this.pluginManager.on("added",r),this.pluginManager.on("removed",i=>z(this,null,function*(){this.cameraStreamInfo.removePlugin(i)&&(yield this.cameraStreamInfo.process(this.streamInfos)),this.screenStreamInfo.removePlugin(i)&&(yield this.screenStreamInfo.process(this.streamInfos)),this.emit("publishupdate")})),this.pluginManager.on("updated",()=>z(this,null,function*(){yield this.updateStreams()}))}get hasCamera(){return!!this.cameraStreamInfo.originVideoTrack}get audioCaptureDisabled(){return this._audioCaptureDisabled}set audioCaptureDisabled(e){this._audioCaptureDisabled=e}get cameraCaptureDisabled(){return this._cameraCaptureDisabled}setAudioMuted(e){this.cameraStreamInfo.setAudioMuted(e)}get isAudioMuted(){return this.cameraStreamInfo.isAudioMuted}setCameraMuted(e){this.cameraStreamInfo.setVideoMuted(e)}get isCameraMuted(){return this.cameraStreamInfo.isVideoMuted}setScreenMuted(e){this.screenStreamInfo.setVideoMuted(e)}get isScreenMuted(){return this.screenStreamInfo.isVideoMuted}set cameraCaptureDisabled(e){this._cameraCaptureDisabled=e}get publishLocalAudioStreamEnabled(){return this._publishLocalAudioStreamEnabled}set publishLocalAudioStreamEnabled(e){this._publishLocalAudioStreamEnabled=e}get publishLocalVideoStreamEnabled(){return this._publishLocalVideoStreamEnabled}set publishLocalVideoStreamEnabled(e){this._publishLocalVideoStreamEnabled=e}get publishLocalScreenStreamEnabled(){return this._publishLocalScreenStreamEnabled}set publishLocalScreenStreamEnabled(e){this._publishLocalScreenStreamEnabled=e}updateStreams(){return z(this,null,function*(){yield this.cameraStreamInfo.process(this.streamInfos),yield this.screenStreamInfo.process(this.streamInfos),this.emit("publishupdate")})}setAvailableCameraDeviceId(){return z(this,null,function*(){var e,t,r,i;if((e=this.cameraStreamInfo.cameraVideoConstraints)!=null&&e.deviceId){let n=(t=this.cameraStreamInfo.cameraVideoConstraints)==null?void 0:t.deviceId;const a=yield me.AliRTS.getCameraList();a.find(o=>o.deviceId===n)||(n=(i=(r=a.find(o=>!!o.deviceId))==null?void 0:r.deviceId)!=null?i:""),this.cameraStreamInfo.cameraVideoConstraints.deviceId=n}})}setAvailableMicrophoneDeviceId(){return z(this,null,function*(){var e,t,r,i;if((e=this.cameraStreamInfo.micAudioConstraints)!=null&&e.deviceId){let n=(t=this.cameraStreamInfo.micAudioConstraints)==null?void 0:t.deviceId;const a=yield me.AliRTS.getMicList();a.find(o=>o.deviceId===n)||(n=(i=(r=a.find(o=>!!o.deviceId))==null?void 0:r.deviceId)!=null?i:""),this.cameraStreamInfo.micAudioConstraints.deviceId=n}})}createLocalStream(e){return z(this,null,function*(){var g;const{screen:t,mediaStream:r,videoProfile:i,screenProfile:n}=e;let{video:a,audio:o}=e;const u=Qc(e);let h;if(u){r||(a===!0&&this.cameraStreamInfo.cameraVideoConstraints?(yield this.setAvailableCameraDeviceId(),a=Se({},this.cameraStreamInfo.cameraVideoConstraints)):typeof a=="object"&&(yield this.setAvailableCameraDeviceId(),a=Se(Se({},a),this.cameraStreamInfo.cameraVideoConstraints)),o===void 0&&this.audioCaptureDisabled?o=!1:o&&(o===!0&&this.cameraStreamInfo.micAudioConstraints?(yield this.setAvailableMicrophoneDeviceId(),o=Se({},this.cameraStreamInfo.micAudioConstraints)):typeof o=="object"&&(yield this.setAvailableMicrophoneDeviceId(),o=Se(Se({},o),this.cameraStreamInfo.micAudioConstraints)),this._audioCaptureDisabled=!1));const f=Date.now();try{h=yield me.AliRTS.createStream({audio:o,video:a,screen:t,custom:!!r,mediaStream:r,skipProfile:!0}),o&&!r&&this.slsReporter.reportAudio(null,Date.now()-f,((g=h==null?void 0:h.audioTrack)==null?void 0:g.label)||""),t&&!r&&this.slsReporter.reportScreen(null,Date.now()-f)}catch(l){throw o&&!r&&this.slsReporter.reportAudio(l,Date.now()-f,""),t&&!r&&this.slsReporter.reportScreen(null,Date.now()-f),l}if(t)yield this.screenStreamInfo.updateSource(h,Yt.Screen,yi.Screen),yield this.setScreenProfile(n),this.setScreenContentHint(),this.publishingScreenVideoStream=void 0;else if(yield this.cameraStreamInfo.updateSource(h,Yt.Camera,yi.Microphone),h.hasVideo&&(yield this.setVideoProfile(i),this.setVideoContentHint(),this.publishingCameraVideoStream=void 0),h.hasAudio&&typeof o=="boolean"){const l=this.cameraStreamInfo.audioProfile;l&&(yield h.setAudioProfile(l))}}return me.AliRTS.SystenUtil.isIos&&me.AliRTS.SystenUtil.compareVersion("15.1")&&!me.AliRTS.SystenUtil.compareVersion("15.2")&&(yield $t(1e3)),yield this.updateStreams(),h})}stopLocalStream(e){return z(this,null,function*(){const{screen:t,video:r,audio:i}=e!=null?e:{};let n=!1;r&&this.cameraStreamInfo.originVideoTrack&&(n=!0,this.cameraStreamInfo.stopVideo(),this.publishingCameraVideoStream=void 0),i&&this.cameraStreamInfo.originAudioTrack&&(n=!0,this.cameraStreamInfo.stopAudio()),t&&this.screenStreamInfo.originVideoTrack&&(n=!0,this.screenStreamInfo.stop(),this.publishingScreenVideoStream=void 0,this.slsReporter.reportScreenStop(null)),n&&(yield this.updateStreams())})}get publishStreams(){const{publishLocalVideoStreamEnabled:e,publishLocalAudioStreamEnabled:t,publishLocalScreenStreamEnabled:r}=this;return{video:e?this.cameraStreamInfo.publishVideoStream:void 0,videoSmall:e?this.cameraStreamInfo.publishDualVideoStream:void 0,audio:t?this.cameraStreamInfo.publishAudioStream:void 0,screen:r?this.screenStreamInfo.publishVideoStream:void 0}}createHTTPPublishStream(){return z(this,null,function*(){var o,u,h,g;let e,t=!1,r,i,n;const a=yield this.publishStreams;try{if(!a.audio&&!a.video&&!a.videoSmall&&!a.screen)throw new ne(ce.ERR_SDK_PUBLISH_INVAILD,"no tracks founded");const f=new MediaStream;(o=a.audio)!=null&&o.audioTrack&&f.addTrack(a.audio.audioTrack),(u=a.video)!=null&&u.videoTrack?(f.addTrack(a.video.videoTrack),i=a.videoSmall,n=a.screen):(h=a.screen)!=null&&h.videoTrack&&(r=Z.Screen,f.addTrack((g=a.screen)==null?void 0:g.videoTrack),t=!0),e=yield fa(f),t?(this.screenStreamInfo.cloneVideoProfile(e),this.publishingScreenVideoStream=e):(this.cameraStreamInfo.cloneVideoProfile(e),this.publishingCameraVideoStream=e)}catch(f){}return{publishStream:e,videoSmallStream:i,screenStream:n,vMsid:r}})}stop(){this.cameraStreamInfo.stop(),this.screenStreamInfo.stop()}setVideoProfile(e,t){return z(this,null,function*(){yield this.cameraStreamInfo.updateVideoProfile(e,t),this.publishingCameraVideoStream&&this.cameraStreamInfo.cloneVideoProfile(this.publishingCameraVideoStream)})}setVideoContentHint(e){this.cameraStreamInfo.setVideoContentHint(e)}setAudioProfile(e){return z(this,null,function*(){var t;yield this.cameraStreamInfo.updateAudioProfile(e),yield(t=this.publishingCameraVideoStream)==null?void 0:t.setAudioProfile(e)})}setScreenProfile(e,t){return z(this,null,function*(){yield this.screenStreamInfo.updateVideoProfile(e,t),this.publishingScreenVideoStream&&this.screenStreamInfo.cloneVideoProfile(this.publishingScreenVideoStream)})}setScreenContentHint(e){this.screenStreamInfo.setVideoContentHint(e)}setCameraVideoConstraints(e){var t;this.cameraStreamInfo.cameraVideoConstraints=Se(Se({},(t=this.cameraStreamInfo.cameraVideoConstraints)!=null?t:{}),e)}setMicAudioConstraints(e){var t;this.cameraStreamInfo.micAudioConstraints=Se(Se({},(t=this.cameraStreamInfo.micAudioConstraints)!=null?t:{}),e)}},A(si,"logName","LocalStreamManager"),si);bt([j(([s])=>{const{audio:c,video:e,screen:t,custom:r,skipProfile:i,videoProfile:n,screenProfile:a}=s;return[{audio:c,video:e,screen:t,custom:r,skipProfile:i,videoProfile:n,screenProfile:a}]})],gt.prototype,"createLocalStream",1),bt([j(ae)],gt.prototype,"stopLocalStream",1),bt([j()],gt.prototype,"createHTTPPublishStream",1),bt([j()],gt.prototype,"stop",1),bt([j(ae)],gt.prototype,"setVideoProfile",1),bt([j(ae)],gt.prototype,"setVideoContentHint",1),bt([j(ae)],gt.prototype,"setAudioProfile",1),bt([j(ae)],gt.prototype,"setScreenProfile",1),bt([j(ae)],gt.prototype,"setScreenContentHint",1),bt([j(ae)],gt.prototype,"setCameraVideoConstraints",1),bt([j(ae)],gt.prototype,"setMicAudioConstraints",1);let g0=gt;var v0=Object.defineProperty,x0=Object.getOwnPropertyDescriptor,St=(s,c,e,t)=>{for(var r=t>1?void 0:t?x0(c,e):c,i=s.length-1,n;i>=0;i--)(n=s[i])&&(r=(t?n(c,e,r):n(r))||r);return t&&r&&v0(c,e,r),r};class ot extends ve{constructor(e){super();A(this,"self");A(this,"userMap",{});A(this,"usersViewMap",{});A(this,"rtsManager");A(this,"localStreamManager");A(this,"authInfo");A(this,"signalingManager");A(this,"pluginManager");A(this,"slsReporter");A(this,"statsMonitorId");A(this,"autoSubAudio",!0);A(this,"autoSubVideo",!0);A(this,"autoSubScreen",!0);A(this,"wantSubAudio",!0);A(this,"wantSubVideo",!0);A(this,"wantSubScreen",!0);A(this,"defaultStreamType",Je.AliRtcVideoStreamTypeHigh);A(this,"audioMuted",!1);A(this,"playoutVolume",1);A(this,"audioVolumeIndicationInterval",0);A(this,"indicationTimer",0);A(this,"parameter",{});const{signalingManager:t,slsReporter:r}=e;this.signalingManager=t,this.addSignalingManagerListener(),this.slsReporter=r,this.pluginManager=new h0,this.localStreamManager=new g0(this.pluginManager,this.slsReporter),this.rtsManager=new f0(this.localStreamManager,this.slsReporter),this.self=new la({rtsManager:this.rtsManager,localStreamManager:this.localStreamManager,slsReporter:this.slsReporter,signalingManager:this.signalingManager,pluginManager:this.pluginManager,audioVolumeIndicationInterval:this.audioVolumeIndicationInterval,parameter:this.parameter})}addSignalingManagerListener(){this.signalingManager.on("onNotifyPublish",e=>{oe.event("[Signaling] Notify Publish ",e),e.forEach(t=>{this.onRemotePublishStateChange(t)})}),this.signalingManager.stsManager.on("onTokenUpdate",(e,t)=>{oe.updateToken(e),this.slsReporter.updateToken(t,e)})}isAutoSubAudio(){return this.autoSubAudio}setAutoSubAudio(e){this.autoSubAudio=e}isAutoSubVideo(){return this.autoSubVideo}setAutoSubVideo(e){this.autoSubVideo=e}isAutoSubScreen(){return this.autoSubScreen}setAutoSubScreen(e){this.autoSubScreen=e}isWantSubAudio(){return this.wantSubAudio}setWantSubAudio(e){this.wantSubAudio=e,this.remoteUsers.forEach(t=>{t.setWantSubAudio(e),t.updateSubscribe(Be.User)})}isWantSubVideo(){return this.wantSubVideo}setWantSubVideo(e){this.wantSubVideo=e,this.remoteUsers.forEach(t=>{t.setWantSubVideo(e),t.updateSubscribe(Be.User)})}isWantSubScreen(){return this.wantSubScreen}setWantSubScreen(e){this.wantSubScreen=e,this.remoteUsers.forEach(t=>{t.setWantSubScreen(e),t.updateSubscribe(Be.User)})}setRemoteDefaultVideoStreamType(e){this.defaultStreamType=e,this.remoteUsers.forEach(t=>{t.setRemoteDefaultVideoStreamType(e)})}setRemoteUserVideoStreamType(e,t){var r;(r=this.getRemoteUser(e))==null||r.setRemoteDefaultVideoStreamType(t)}setAudioMuted(e){this.audioMuted=e,this.remoteUsers.forEach(t=>{t.setAudioMuted(e)})}setLocalViewConfig(e,t){var i;if(!e)return(i=this.publisher)==null?void 0:i.setViewConfig(null,t);const r=fs(e);r.length!==0&&r.forEach(n=>{var a,o;(a=this.publisher)==null||a.resetElement(n),Object.values(this.usersViewMap).forEach(({cameraViews:u=[],screenViews:h=[]})=>{u.includes(n)&&u.splice(u.indexOf(n),1),h.includes(n)&&h.splice(h.indexOf(n),1)}),(o=this.publisher)==null||o.setViewConfig(r,t)})}setRemoteViewConfig(e,t,r){var n,a;if(!t)return(n=this.userMap[e])==null?void 0:n.setViewConfig(null,r);const i=fs(t);i.length!==0&&(i.forEach(o=>{var u;(u=this.publisher)==null||u.resetElement(o),Object.values(this.usersViewMap).forEach(({cameraViews:h=[],screenViews:g=[]})=>{h.includes(o)&&h.splice(h.indexOf(o),1),g.includes(o)&&g.splice(g.indexOf(o),1)})}),(a=this.userMap[e])==null||a.setViewConfig(i,r))}get channel(){var e;return(e=this.authInfo)==null?void 0:e.channelId}get userId(){var e;return(e=this.authInfo)==null?void 0:e.userId}get remoteUsers(){return Object.values(this.userMap)}get publisher(){return this.self}get isSubscribing(){var e;return((e=this.remoteUsers)!=null?e:[]).some(t=>{var o;const{isAudioSubscribing:r,isVideoLargeSubscribing:i,isVideoSmallSubscribing:n,isScreenSubscribing:a}=(o=t.streamInfo)!=null?o:{};return r||i||n||a})}onRemotePublishStateChange(e){var f;const{userid:t,callid:r,subscribe:i,pubid:n="",tracks:a}=e,o=(f=i==null?void 0:i.pullstreamurl)!=null?f:"";let u=this.getRemoteUser(t);if(!u)return;const h=u.streamInfo.audioTrackInfo,g=u.streamInfo.videoTrackInfo;u.updateRemoteTracks(r,o,n,a),u.updateSubscribe(Be.Publish),(h!==u.streamInfo.audioTrackInfo||g!==u.streamInfo.videoTrackInfo)&&this.emit("remoteTrackAvailableChange",t,u.streamInfo.audioTrackInfo,u.streamInfo.videoTrackInfo)}init(e,t){var r;this.authInfo=e,this.self||(this.self=new la({rtsManager:this.rtsManager,localStreamManager:this.localStreamManager,slsReporter:this.slsReporter,signalingManager:this.signalingManager,pluginManager:this.pluginManager,audioVolumeIndicationInterval:this.audioVolumeIndicationInterval,parameter:this.parameter})),this.self.enableAudioVolumeIndication(this.audioVolumeIndicationInterval),(r=this.self)==null||r.initInfo(e,t.pushstreamurl),t.users.forEach(i=>{const n=i.userid;if(n){const a=this.addUser(n,i.displayname,Be.InRoom),{callid:o,subscribe:u,tracks:h}=i;a.updateRemoteTracks(o,(u==null?void 0:u.pullstreamurl)||"","",h),this.emit("remoteTrackAvailableChange",n,a.streamInfo.audioTrackInfo,a.streamInfo.videoTrackInfo)}}),this.startStatsMonitor()}clear(){return z(this,null,function*(){var e;this.stopStatsMonitor();for(let t in this.userMap)this.userMap[t]&&(yield this.userMap[t].clear(),delete this.userMap[t]);yield(e=this.self)==null?void 0:e.clear(),this.authInfo=void 0})}startStatsMonitor(){this.statsMonitorId=window.setInterval(()=>z(this,null,function*(){if(this.publisher){const{audio:r,video:i,candidate:n}=yield this.publisher.getStats();r&&r.length>0&&this.emit("rtcLocalAudioStats",r),i&&i.length>0&&this.emit("rtcLocalVideoStats",i),n&&this.emit("rtcStats",n)}const e=[],t=[];for(const r of this.remoteUsers){const{audio:i,video:n}=yield r.getStats();i&&i.forEach(a=>{e.push(a)}),n&&n.forEach(a=>{t.push(a)})}e.length>0&&this.emit("rtcRemoteAudioStats",e),t.length>0&&this.emit("rtcRemoteVideoStats",t)}),2e3)}stopStatsMonitor(){this.statsMonitorId&&clearInterval(this.statsMonitorId)}addUser(e,t,r){return this.userMap[e]||(this.userMap[e]=this.executeAddUser(e,t,r)),this.userMap[e]}executeAddUser(e,t,r){const i=new Ue({userId:e,displayName:t,rtsManager:this.rtsManager,signalingManager:this.signalingManager,usersViewMap:this.usersViewMap,slsReporter:this.slsReporter,localUser:this.self,audioVolumeIndicationInterval:this.audioVolumeIndicationInterval,playoutVolume:this.playoutVolume,parameter:this.parameter});return i.on(et.Remote,this.onRemoteDeviceStatusChange.bind(this)),i.on(Ie.PullStreamStats,this.onRemoteStatReport.bind(this)),i.on(Ie.RtsSubscribeExceeds,this.onSubscribeExceeds.bind(this)),i.on("audioSubscribeStateChanged",(n,a,o,u)=>{this.emit("audioSubscribeStateChanged",n,a,o,u,this.channel||"")}),i.on("videoSubscribeStateChanged",(n,a,o,u)=>{this.emit("videoSubscribeStateChanged",n,a,o,u,this.channel||"")}),i.on("screenSubscribeStateChanged",(n,a,o,u)=>{this.emit("screenSubscribeStateChanged",n,a,o,u,this.channel||"")}),i.on("remoteAudioAutoPlayFail",n=>{this.emit("remoteAudioAutoPlayFail",n)}),i.on("remoteVideoAutoPlayFail",(n,a)=>{this.emit("remoteVideoAutoPlayFail",n,a)}),i.on("remoteAudioPlayError",(n,a)=>{this.emit("remoteAudioPlayError",n,a)}),i.on("remoteVideoPlayError",(n,a)=>{this.emit("remoteVideoPlayError",n,a)}),i.on("remoteSubscribeError",n=>{this.emit("remoteSubscribeError",n)}),i.setWantSubAudio(this.autoSubAudio&&this.wantSubAudio),i.setWantSubVideo(this.autoSubVideo&&this.wantSubVideo),i.setWantSubScreen(this.autoSubScreen&&this.wantSubScreen),i.setRemoteDefaultVideoStreamType(this.defaultStreamType),i.setAudioMuted(this.audioMuted),(this.autoSubAudio||this.autoSubVideo||this.autoSubScreen)&&i.updateSubscribe(r),i}onRemoteDeviceStatusChange(e,t){e===Ie.MuteAudio?this.emit("userAudioMuted",t,!0):e===Ie.UnmuteAudio?this.emit("userAudioMuted",t,!1):e===Ie.MuteVideo?this.emit("userVideoMuted",t,!0):e===Ie.UnmuteVideo?this.emit("userVideoMuted",t,!1):e===Ie.MuteScreen?this.emit("userScreenMuted",t,!0):e===Ie.UnmuteScreen&&this.emit("userScreenMuted",t,!1)}onRemoteStatReport(e,t,r){this.emit(Ie.PullStreamStats,e,t,r)}onSubscribeExceeds(e,t){this.emit(Ie.RtsSubscribeExceeds,e,t)}removeLeftUser(e){return z(this,null,function*(){e.userid&&this.userMap[e.userid]&&(yield this.userMap[e.userid].clear(!1),delete this.userMap[e.userid])})}updateUsers(e){const t=[],r=[],i={};e.forEach(o=>{o.userid&&(this.userMap[o.userid]?(r.push(o),i[o.userid]=this.userMap[o.userid]):(t.push(o),i[o.userid]=this.executeAddUser(o.userid,o.displayname,Be.Resume)))});const n=Object.keys(this.userMap),a=[];return n.forEach(o=>{i[o]||a.push({userid:o,reason:"",leavecode:cs.AliRtcUserOfflineQuit})}),this.userMap=i,{joinList:t,leaveList:a,presentList:r}}getRemoteUser(e){return this.userMap[e]}updateRemoteUserDeviceStatus(e){e&&e.userid&&this.userMap[e.userid]&&this.userMap[e.userid].updateRemoteUserDeviceStatus(e.status)}updateAudioWant(e,t){const r=this.userMap[e];if(!r)throw new ne(ce.ERR_INNER,`no remote user(${e}) founded`);r.setWantSubAudio(t),t?r.updateSubscribe(Be.User):r.stopSubscribe({audio:!0})}updateVideoWant(e,t){const r=this.userMap[e];if(!r)throw new ne(ce.ERR_INNER,`no remote user(${e}) founded`);r.setWantSubVideo(t),t?r.updateSubscribe(Be.User):r.stopSubscribe({video:!0})}updateScreenWant(e,t){const r=this.userMap[e];if(!r)throw new ne(ce.ERR_INNER,`no remote user(${e}) founded`);r.setWantSubScreen(t),t?r.updateSubscribe(Be.User):r.stopSubscribe({screen:!0})}stopIndication(){this.indicationTimer&&window.clearInterval(this.indicationTimer)}startIndication(e){this.stopIndication(),this.indicationTimer=window.setInterval(()=>{var r;const t=this.remoteUsers.map(i=>({userId:i.userId,volume:i.getAudioLevel()||0}));t.unshift({userId:"",volume:((r=this.self)==null?void 0:r.getAudioLevel())||0}),this.emit("audioVolume",t)},e)}enableAudioVolumeIndication(e){var t;this.audioVolumeIndicationInterval!==e&&(this.audioVolumeIndicationInterval>0&&e<=0&&this.stopIndication(),e>0&&this.startIndication(e),this.audioVolumeIndicationInterval=e,this.remoteUsers.forEach(r=>{r.enableAudioVolumeIndication(e)}),(t=this.self)==null||t.enableAudioVolumeIndication(e))}setPlayoutVolume(e){this.playoutVolume=e,this.remoteUsers.forEach(t=>{t.setPlayoutVolume(e)})}refreshAuthInfo(e){var t;this.authInfo&&(this.authInfo=Se(Se({},this.authInfo),e)),e.userId&&((t=this.self)==null||t.refreshUserInfo(e.userId))}setEnableMediaExtensionMsg(e){this.rtsManager.setEncodedInsertableStreams(e)}setAudioRedEnabled(e){this.rtsManager.setAudioRedEnabled(e)}setParameter(e){const t=JSON.parse(e);Object.keys(t).forEach(r=>{this.parameter[r]=t[r]})}getParameter(){return JSON.stringify(this.parameter)}}A(ot,"logName","BizControl"),St([j()],ot.prototype,"init",1),St([j()],ot.prototype,"clear",1),St([j(ae)],ot.prototype,"addUser",1),St([j()],ot.prototype,"removeLeftUser",1),St([j()],ot.prototype,"updateUsers",1),St([j(ae)],ot.prototype,"updateAudioWant",1),St([j(ae)],ot.prototype,"updateVideoWant",1),St([j(ae)],ot.prototype,"updateScreenWant",1),St([j()],ot.prototype,"stopIndication",1),St([j()],ot.prototype,"startIndication",1),St([j()],ot.prototype,"enableAudioVolumeIndication",1);const gs=s=>z(this,null,function*(){const c=new Uint8Array(160).fill(170),e=new TextEncoder().encode(s),t=yield window.crypto.subtle.importKey("raw",c,{name:"HMAC",hash:{name:"SHA-1"}},!1,["sign"]),r=yield window.crypto.subtle.sign("HMAC",t,e);return Array.from(new Uint8Array(r)).map(i=>i.toString(16).padStart(2,"0")).join("")});class b0{constructor(c){A(this,"authInfo");A(this,"slsReporter");this.slsReporter=c}doRequest(c,e){var u;const t=this.authInfo;if(!t)return Promise.reject(Et.LiveTranscodingErrorInvalidParam);const r="https://gw.rtn.aliyuncs.com",i=Mc[c],n={appid:t.appId,userid:t.userId,channelid:t.channelId,timestamp:t.timestamp,token:t.token,nonce:t.nonce?t.nonce:"",requestid:At.createCallid(),tokensid:!1,session:(u=t.sessionId)!=null?u:At.createCallid()},a=Object.keys(n).map(h=>`${h}=${encodeURIComponent(n[h])}`).join("&"),o=`${r}${i}?${a}`;return fetch(o,{method:"POST",headers:{"Content-Type":"application/json; charset=UTF-8"},body:JSON.stringify(e)}).then(h=>h.status!==200?(this.slsReporter.reportTranscodingError(h.status,e.taskid||""),Promise.reject(new ne(ce.ERR_INNER,`transcoding request failed, status: ${h.status}`))):h).catch(h=>Promise.reject(new ne(ce.ERR_INNER,`transcoding request failed, err: ${h.message}`)))}setAuthInfo(c){this.authInfo=c}clear(){this.authInfo=void 0}startPublishLiveStream(c,e){return z(this,null,function*(){if(!this.authInfo)return Promise.reject(Et.LiveTranscodingErrorInvalidParam);const t=yield gs(c.split("?")[0]),r=st.MPU_TASK_TRANSACTION_UPDATE,i=e.toJson(r,this.authInfo,t,c);return this.doRequest(r,i)})}startPublishLiveStreamWithTaskId(c,e){return z(this,null,function*(){if(!this.authInfo)return Promise.reject(Et.LiveTranscodingErrorInvalidParam);const t=st.MPU_TASK_TRANSACTION_UPDATE,r=e.toJson(t,this.authInfo,c);return this.doRequest(t,r)})}updatePublishLiveStream(c,e){return z(this,null,function*(){if(!this.authInfo)return Promise.reject(Et.LiveTranscodingErrorInvalidParam);const t=yield gs(c.split("?")[0]),r=st.MPU_TASK_TRANSACTION_UPDATE,i=e.toJson(r,this.authInfo,t,c);return this.doRequest(r,i)})}updatePublishLiveStreamWithTaskId(c,e){return z(this,null,function*(){if(!this.authInfo)return Promise.reject(Et.LiveTranscodingErrorInvalidParam);const t=st.MPU_TASK_TRANSACTION_UPDATE,r=e.toJson(t,this.authInfo,c);return this.doRequest(t,r)})}stopPublishLiveStream(c){return z(this,null,function*(){if(!this.authInfo)return Promise.reject(Et.LiveTranscodingErrorInvalidParam);const e=yield gs(c.split("?")[0]),t=st.MPU_TASK_TRANSACTION_STOP,r=new Li().toJson(t,this.authInfo,e,c);return this.doRequest(t,r)})}stopPublishLiveStreamWithTaskId(c){if(!this.authInfo)return Promise.reject(Et.LiveTranscodingErrorInvalidParam);const e=st.MPU_TASK_TRANSACTION_STOP,t=new Li().toJson(e,this.authInfo,c);return this.doRequest(e,t)}refreshAuthInfo(c){this.authInfo&&this.setAuthInfo(Se(Se({},this.authInfo),c))}}class ma{constructor(c){A(this,"name","COMMON");this.name=c||this.name}info(...c){}warn(...c){}print(c,...e){const t=c.toLowerCase();t&&console[t](`[${c}][${this.name}]`,...e)}}A(ma,"LEVEL",0);class S0{constructor(){A(this,"logger",new ma("AudioMixer"));A(this,"audioContext",new AudioContext);A(this,"audioDestination",this.audioContext.createMediaStreamDestination());A(this,"audioTrack",Jc(this.audioDestination.stream));A(this,"sourceNodeMap",{})}get sourceNodeList(){return Object.values(this.sourceNodeMap).map(c=>c.sourceNode).filter(c=>!!c)}get gainNodeList(){return Object.values(this.sourceNodeMap).map(c=>c.gainNode).filter(c=>!!c)}get sourceCount(){return this.sourceNodeList.length}resume(){var c;return(c=this.audioContext)==null?void 0:c.resume()}addTrack(c){this.connectTrack(c)}hasTrack(c){return!!this.sourceNodeMap[c]}removeTrack(c){const{sourceNode:e,gainNode:t}=this.sourceNodeMap[c]||{};t==null||t.disconnect(),e==null||e.disconnect(),delete this.sourceNodeMap[c],e?this.logger.info("SourceNode disconnected. Active source node:",this.sourceNodeList.length):this.logger.warn(`SourceNode ${c} does not exit. Active source node: ${this.sourceNodeList.length}`)}getAudioTrack(){return this.audioTrack}setVolume(c,e){const{gainNode:t}=this.sourceNodeMap[e]||{};t?(this.logger.info(`Setting node(${e}) volume to ${this.scale(c)}`),t.gain.value=this.scale(c)):this.logger.warn(`GainNode ${e} does not exit.`)}reset(){this.disconnectSourceNode(),this.sourceNodeMap={}}dispose(){var c;this.reset(),(c=this.audioTrack)==null||c.stop(),this.audioDestination.disconnect(),this.audioContext.close()}connectTrack(c){if(!this.audioContext)return this.logger.warn("AudioContext not initialized");let e=new MediaStream;e.addTrack(c);const t=this.audioContext.createMediaStreamSource(e),r=this.audioContext.createGain();r.gain.value=1,t.connect(r),r.connect(this.audioDestination),this.sourceNodeMap[c.id]={track:c,sourceNode:t,gainNode:r},this.logger.info("New sourceNode connected. Active source node:",this.sourceNodeList.length)}disconnectSourceNode(){this.sourceNodeList.forEach(c=>c.disconnect()),this.gainNodeList.forEach(c=>c.disconnect())}scale(c){return c/100}}const _0=4;class y0 extends ei{constructor(){super("audioMixer",Ke.AliRtcSdkStreamTypeCapture,Ti.AUDIO);A(this,"audioMixer");A(this,"primaryAudioTrackId");A(this,"screenAudioTrackId");A(this,"dirty",!1);this.zIndex=8}get initOptions(){return{audio:1,screen:1}}setOptions(e){Object.entries(e).forEach(([t,r])=>{this.isValidVolume(r)&&(this.options[t]=r)}),this.dirty=!0,this.emit("updated")}isSupported(){return"AudioContext"in window}shouldUpdate(e,t){var n,a;if(e.type!==Ke.AliRtcSdkStreamTypeCapture)return!1;const r=t.find(o=>o.type===Ke.AliRtcSdkStreamTypeCapture),i=t.find(o=>o.type===Ke.AliRtcSdkStreamTypeScreen);return!(this.primaryAudioTrackId===((n=r==null?void 0:r.currentAudioTrack)==null?void 0:n.id)&&this.screenAudioTrackId===((a=i==null?void 0:i.currentAudioTrack)==null?void 0:a.id)&&!this.dirty)}process(e,t){return z(this,null,function*(){var a,o;this.dirty=!1;const r=t.find(u=>u.type===Ke.AliRtcSdkStreamTypeScreen),i=e.currentAudioTrack,n=r==null?void 0:r.currentAudioTrack;if(!n&&this.options.audio===1){this.audioMixer&&(this.audioMixer.dispose(),this.audioMixer=void 0),this.primaryAudioTrackId=i==null?void 0:i.id,e.updateAudioTrack(i);return}this.audioMixer||(this.audioMixer=new S0),yield this.audioMixer.resume(),this.primaryAudioTrackId&&(i==null?void 0:i.id)!==this.primaryAudioTrackId&&((a=this.audioMixer)==null||a.removeTrack(this.primaryAudioTrackId)),i&&!this.audioMixer.hasTrack(i==null?void 0:i.id)&&this.audioMixer.addTrack(i),this.primaryAudioTrackId=i==null?void 0:i.id,this.screenAudioTrackId&&(n==null?void 0:n.id)!==this.screenAudioTrackId&&((o=this.audioMixer)==null||o.removeTrack(this.screenAudioTrackId)),n&&!this.audioMixer.hasTrack(n==null?void 0:n.id)&&this.audioMixer.addTrack(n),this.screenAudioTrackId=n==null?void 0:n.id,this.updateVolume(),e.updateAudioTrack(this.audioMixer.getAudioTrack())})}isValidVolume(e){return e!==void 0&&e>=0&&e<=_0}updateVolume(){this.audioMixer&&(this.primaryAudioTrackId&&this.audioMixer.setVolume(this.options.audio*100,this.primaryAudioTrackId),this.screenAudioTrackId&&this.audioMixer.setVolume(this.options.screen*100,this.screenAudioTrackId))}clear(e){var t;(t=this.audioMixer)==null||t.dispose(),super.clear(e)}}class vs{constructor(c,e){A(this,"originTrack");A(this,"originVideo");A(this,"targetWidth");A(this,"targetHeight");A(this,"targetFrameRate");A(this,"targetCanvas");A(this,"animationFrameId");A(this,"resultTrack");this.targetWidth=e.width,this.targetHeight=e.height,this.targetFrameRate=e.frameRate,this.originTrack=c,this.originVideo=document.createElement("video"),this.originVideo.muted=!0,this.originVideo.autoplay=!0,this.originVideo.controls=!1,this.targetCanvas=document.createElement("canvas"),this.targetCanvas.width=this.targetWidth,this.targetCanvas.height=this.targetHeight}updateOptions(c){this.targetWidth=c.width,this.targetHeight=c.height,this.targetFrameRate=c.frameRate,this.targetCanvas.width=this.targetWidth,this.targetCanvas.height=this.targetHeight,this.resultTrack&&this.resultTrack.applyConstraints({frameRate:this.targetFrameRate})}dispose(){}getVideoTrack(){return this.resultTrack||(this.resultTrack=this.targetCanvas.captureStream().getVideoTracks()[0],this.resultTrack.applyConstraints({frameRate:this.targetFrameRate})),this.resultTrack}cancelAnimation(){this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=void 0)}getPositionAndSize(c,e,t,r){const i=e/c,n=r/t;let a=t,o=r,u=0,h=0;return n>i?(a=Math.round(o/i),u=Math.round((t-a)/2)):n<i&&(o=Math.round(a*i),h=Math.round((r-o)/2)),{x:u,y:h,width:a,height:o}}}class A0 extends vs{constructor(e,t){super(e,t);A(this,"targetCtx");this.targetCtx=this.targetCanvas.getContext("2d"),this.startRender=this.startRender.bind(this),this.stopRender=this.startRender.bind(this),this.initStream(e)}initStream(e){const t=new MediaStream;t.addTrack(e),this.originVideo.srcObject=t,this.originVideo.play(),this.originVideo.addEventListener("canplay",this.startRender),this.originVideo.addEventListener("pause",this.stopRender),this.originVideo.addEventListener("ended",this.stopRender)}startRender(){this.cancelAnimation();const e=()=>{if(!this.targetCtx)return;const t=this.getPositionAndSize(this.originVideo.videoWidth,this.originVideo.videoHeight,this.targetWidth,this.targetHeight);this.targetCtx.drawImage(this.originVideo,0,0,this.originVideo.videoWidth,this.originVideo.videoHeight,t.x,t.y,t.width,t.height),!this.originVideo.paused&&!this.originVideo.ended&&(this.animationFrameId=requestAnimationFrame(e))};e()}stopRender(){this.cancelAnimation()}dispose(){this.stopRender(),this.originVideo.removeEventListener("play",this.startRender),this.originVideo.removeEventListener("pause",this.stopRender),this.originVideo.removeEventListener("ended",this.stopRender),this.originVideo.pause(),this.originVideo.srcObject=null}}const E0=`
38
+ `));const i=yield r.generateAsync({type:"blob"}),n=yield nc(i),a=Zr(new Date,"UTC:ddd, dd mmm yyyy HH:MM:ss 'GMT'"),o={"x-oss-date":a,"content-md5":n,"content-type":"application/zip"};o.date=a,o["x-oss-security-token"]=this.stsToken.security_token;const u=`client/${e}/${this.appId}/${c}.zip`;o.authorization=yield oc(this.stsToken.access_key_id,this.stsToken.access_key_secret,o,`/${this.stsToken.bucket_name}/${u}`);const h=`https://${this.stsToken.bucket_name}.${this.stsToken.region_endpoint}/${u}`,g=yield fetch(h,{method:"PUT",headers:o,body:i});if(g.status===200){hi.reportOSSUpload(c,e);const f=yield this.dbPromise;t.forEach(l=>{sn(f,l.id)})}else hi.reportOSSUpload(c,e,g.status)})}uploadSessionLog(c){c&&this.dbPromise.then(e=>z(this,null,function*(){if(!this.stsToken)return;const t=yield rn(e,c),r={},i=[];t.forEach(n=>{const a=n.date;if(Date.now()-Pc(a).getTime()>Bc)try{sn(e,n.id)}catch(o){}else r[a]||(r[a]=[],i.push(a)),r[a].push(n)}),Promise.all(i.map(n=>this.uploadSessionDateLog(c,n,r[n]))).then(()=>z(this,null,function*(){(yield rn(e,c)).length===0&&To(e,c)}))}))}tryUploadHistorySessionLog(){this.dbPromise.then(c=>z(this,null,function*(){(yield Do(c)).filter(t=>t.sid!==this.sessionId).forEach(t=>{this.uploadSessionLog(t.sid)})}))}uploadCurrent(){const c=this.sessionId;this.sessionId="",this.uploadSessionLog(c)}setSessionID(c,e){!c||!e||(this.appId=c,this.dbPromise.then(t=>{this.sessionId=e,ko(t,e),this.logCache&&(this.logCache.forEach(r=>{tn(t,this.sessionId,r.date,`${r.log}`)}),this.logCache=[])}))}addLog(c){if(!this.logToServer)return;const e=this.getCurrentTime(),t=this.getCurrentDate(),r=`${e} ${c}`;this.sessionId?this.dbPromise.then(i=>{tn(i,this.sessionId,t,r)}):this.logCache.push({date:t,log:r})}getCurrentTime(){return Zr(new Date,"HH:MM:ss.l")}getCurrentDate(){return Zr(new Date,"yyyymmdd")}static paramArrayToString(c){let e="";for(let t=0;t<c.length;t++){e!==""&&(e+=" ");let r=Di.toString(c[t]);e+=r}return e}}class oe{static getLogger(){return this.logger||(this.logger=new Di),this.logger}static setLogLevel(c){this.getLogger().changeConfig({logLevel:c})}static config(c){this.getLogger().changeConfig(c)}static updateToken(c){this.getLogger().updateSTSToken(c)}static setSessionID(c,e){this.getLogger().setSessionID(c,e)}static uploadLog(){this.getLogger().uploadCurrent()}static interface(...c){this.getLogger().a("[API]",...c)}static interfaceResult(c,e,t,...r){t?this.getLogger().ar("[ARE]",c,e,...r):this.getLogger().ae("[ARE]",c,e,...r)}static event(...c){this.getLogger().ev("[EVT]",...c)}static debug(...c){this.getLogger().d("[DBG]",...c)}static info(...c){this.getLogger().i("[INF]",...c)}static warn(...c){this.getLogger().w("[WARN]",...c)}static error(...c){this.getLogger().e("[ERR]",...c)}}A(oe,"logger");const Lc=s=>z(this,null,function*(){const c=new me.AliRTS.SupportUtil;let e={support:!1,detail:{isWebRTCSupported:c.checkMediaDevices()&&c.checkWebRtcSupport(),isH264DecodeSupported:!1,isH264EncodeSupported:!1,isScreenShareSupported:!1,isSendMediaExtensionMsgSupported:!1,isBrowserSupported:c.checkBrowser({errorCode:0,message:""})}};if(e.support=e.detail.isWebRTCSupported&&e.detail.isBrowserSupported,c.checkWebRtcSupport()&&s!=="sendonly"){const t=yield c.checkH264Decode();e.detail.isH264DecodeSupported=t,e.support=e.support&&t}if(c.checkWebRtcSupport()&&s!=="recvonly"){const t=yield c.checkH264Encode();e.detail.isH264EncodeSupported=t,e.support=e.support&&t}return e.detail.isScreenShareSupported=c.checkWebRtcSupport()&&c.checkScreenCapture()&&!me.AliRTS.SystenUtil.isAndroid&&!me.AliRTS.SystenUtil.isIos,e.detail.isSendMediaExtensionMsgSupported=c.checkWebRtcSupport()&&c.checkEncodedTransformSupport(),e});var Ke=(s=>(s[s.AliRtcSdkStreamTypeCapture=0]="AliRtcSdkStreamTypeCapture",s[s.AliRtcSdkStreamTypeScreen=1]="AliRtcSdkStreamTypeScreen",s))(Ke||{}),ta=(s=>(s[s.PRE_PROCESSOR=0]="PRE_PROCESSOR",s[s.POST_PROCESSOR=1]="POST_PROCESSOR",s))(ta||{}),Ti=(s=>(s[s.AUDIO=0]="AUDIO",s[s.VIDEO=1]="VIDEO",s[s.BOTH=2]="BOTH",s))(Ti||{});class ei extends ve{constructor(e,t=Ke.AliRtcSdkStreamTypeCapture,r=1){super();A(this,"name");A(this,"options");A(this,"type",0);A(this,"streamType");A(this,"trackType");A(this,"zIndex",1);A(this,"_isEnable",!0);A(this,"lastInputAudioTrack");A(this,"lastOutputAudioTrack");A(this,"lastInputVideoTrack");A(this,"lastOutputVideoTrack");A(this,"_hasCleared",!0);this.name=e,this.streamType=t,this.trackType=r,this.options=this.initOptions}get initOptions(){return{}}getOptions(){return this.options}init(){return z(this,null,function*(){})}enable(){this._isEnable||(this._isEnable=!0,this.init(),this.emit("enabled"))}disable(){this._isEnable&&(this._isEnable=!1,this.clear(),this.emit("disabled"))}get isEnable(){return this._isEnable}audioUpdated(e){var t,r;return((t=this.lastInputAudioTrack)==null?void 0:t.id)!==((r=e.currentAudioTrack)==null?void 0:r.id)}videoUpdated(e){var t,r;return((t=this.lastInputVideoTrack)==null?void 0:t.id)!==((r=e.currentVideoTrack)==null?void 0:r.id)}execute(e,t){return z(this,null,function*(){const r=this.shouldUpdate(e,t);this.lastInputAudioTrack=e.currentAudioTrack,this.lastInputVideoTrack=e.currentVideoTrack,this._hasCleared||r?(yield this.process(e,t),this._hasCleared=!1):(this.lastOutputAudioTrack&&(this.trackType===2||this.trackType===0)&&this.lastOutputAudioTrack&&e.updateAudioTrack(this.lastOutputAudioTrack),this.lastOutputVideoTrack&&(this.trackType===2||this.trackType===1)&&this.lastOutputVideoTrack&&e.updateVideoTrack(this.lastOutputVideoTrack)),this.lastOutputAudioTrack=e.currentAudioTrack,this.lastOutputVideoTrack=e.currentVideoTrack})}clear(e){this._hasCleared=!0,this.lastInputAudioTrack=void 0,this.lastInputVideoTrack=void 0,this.lastOutputAudioTrack=void 0,this.lastOutputVideoTrack=void 0}}var di=(s=>(s[s.LiveTranscodingSingle=0]="LiveTranscodingSingle",s[s.LiveTranscodingMix=1]="LiveTranscodingMix",s))(di||{}),ts=(s=>(s[s.LiveTranscodingOrigin=0]="LiveTranscodingOrigin",s[s.LiveTranscodingAudio=1]="LiveTranscodingAudio",s[s.LiveTranscodingVideo=2]="LiveTranscodingVideo",s))(ts||{}),ti=(s=>(s[s.LiveTranscodingCamera=0]="LiveTranscodingCamera",s[s.LiveTranscodingShareScreen=1]="LiveTranscodingShareScreen",s))(ti||{});const li={0:"camera",1:"shareScreen"};var is=(s=>(s[s.LiveTranscoding_Profile_1IN_1080P=0]="LiveTranscoding_Profile_1IN_1080P",s[s.LiveTranscoding_Profile_1IN_720P=1]="LiveTranscoding_Profile_1IN_720P",s[s.LiveTranscoding_Profile_1IN_360P=2]="LiveTranscoding_Profile_1IN_360P",s[s.LiveTranscoding_Profile_2IN_1080P=3]="LiveTranscoding_Profile_2IN_1080P",s[s.LiveTranscoding_Profile_2IN_720P=4]="LiveTranscoding_Profile_2IN_720P",s[s.LiveTranscoding_Profile_2IN_360P=5]="LiveTranscoding_Profile_2IN_360P",s[s.LiveTranscoding_Profile_4IN_1080P=6]="LiveTranscoding_Profile_4IN_1080P",s[s.LiveTranscoding_Profile_4IN_720P=7]="LiveTranscoding_Profile_4IN_720P",s[s.LiveTranscoding_Profile_4IN_360P=8]="LiveTranscoding_Profile_4IN_360P",s[s.LiveTranscoding_Profile_9IN_1080P=9]="LiveTranscoding_Profile_9IN_1080P",s[s.LiveTranscoding_Profile_9IN_720P=10]="LiveTranscoding_Profile_9IN_720P",s[s.LiveTranscoding_Profile_9IN_360P=11]="LiveTranscoding_Profile_9IN_360P",s[s.LiveTranscoding_Profile_12IN_1080P=12]="LiveTranscoding_Profile_12IN_1080P",s[s.LiveTranscoding_Profile_12IN_720P=13]="LiveTranscoding_Profile_12IN_720P",s[s.LiveTranscoding_Profile_12IN_360P=14]="LiveTranscoding_Profile_12IN_360P",s[s.LiveTranscoding_Profile_16IN_1080P=15]="LiveTranscoding_Profile_16IN_1080P",s[s.LiveTranscoding_Profile_16IN_720P=16]="LiveTranscoding_Profile_16IN_720P",s[s.LiveTranscoding_Profile_16IN_360P=17]="LiveTranscoding_Profile_16IN_360P",s[s.LiveTranscoding_Profile_Mixed=9999]="LiveTranscoding_Profile_Mixed",s))(is||{});const Nc={0:"1IN_1080P",1:"1IN_720P",2:"1IN_360P",3:"2IN_1080P",4:"2IN_720P",5:"2IN_360P",6:"4IN_1080P",7:"4IN_720P",8:"4IN_360P",9:"9IN_1080P",10:"9IN_720P",11:"9IN_360P",12:"12IN_1080P",13:"12IN_720P",14:"12IN_360P",15:"16IN_1080P",16:"16IN_720P",17:"16IN_360P",9999:"Mixed_Audio"};var Bi=(s=>(s[s.LiveTranscoding_HZ_48000=48e3]="LiveTranscoding_HZ_48000",s[s.LiveTranscoding_HZ_44100=44100]="LiveTranscoding_HZ_44100",s[s.LiveTranscoding_HZ_32000=32e3]="LiveTranscoding_HZ_32000",s[s.LiveTranscoding_HZ_16000=16e3]="LiveTranscoding_HZ_16000",s[s.LiveTranscoding_HZ_8000=8e3]="LiveTranscoding_HZ_8000",s))(Bi||{}),fi=(s=>(s[s.LiveTranscodingNoBody=0]="LiveTranscodingNoBody",s[s.LiveTranscodingBody=1]="LiveTranscodingBody",s))(fi||{}),pi=(s=>(s[s.NOTO_SERIF_CJKSC_REGULAR=0]="NOTO_SERIF_CJKSC_REGULAR",s[s.ALIBABA_PUHUITI_REGULAR=1]="ALIBABA_PUHUITI_REGULAR",s[s.ALIBABA_PUHUITI_BOLD=2]="ALIBABA_PUHUITI_BOLD",s[s.ALIBABA_PUHUITI_Heavy=3]="ALIBABA_PUHUITI_Heavy",s[s.ALIBABA_PUHUITI_LIGHT=4]="ALIBABA_PUHUITI_LIGHT",s[s.ALIBABA_PUHUITI_MEDIUM=5]="ALIBABA_PUHUITI_MEDIUM",s))(pi||{}),rs=(s=>(s[s.LiveTranscodingOrigin=0]="LiveTranscodingOrigin",s[s.LiveTranscodingCrop=1]="LiveTranscodingCrop",s[s.LiveTranscodingFill=2]="LiveTranscodingFill",s))(rs||{}),Pi=(s=>(s[s.LiveTranscodingNormal=0]="LiveTranscodingNormal",s[s.LiveTranscodingVirtualBackground=1]="LiveTranscodingVirtualBackground",s))(Pi||{}),ss=(s=>(s[s.LiveTranscodingState_IDLE=0]="LiveTranscodingState_IDLE",s[s.LiveTranscodingState_CONNNECT=1]="LiveTranscodingState_CONNNECT",s[s.LiveTranscodingState_RUNNING=2]="LiveTranscodingState_RUNNING",s[s.LiveTranscodingState_RECOVERING=3]="LiveTranscodingState_RECOVERING",s[s.LiveTranscodingState_FAILURE=4]="LiveTranscodingState_FAILURE",s[s.LiveTranscodingState_END=5]="LiveTranscodingState_END",s))(ss||{}),Et=(s=>(s[s.LiveTranscodingErrorPublishOk=0]="LiveTranscodingErrorPublishOk",s[s.LiveTranscodingErrorStreamNotFound=17825793]="LiveTranscodingErrorStreamNotFound",s[s.LiveTranscodingErrorStreamAlreadyExist=17825794]="LiveTranscodingErrorStreamAlreadyExist",s[s.LiveTranscodingErrorInvalidParam=17825795]="LiveTranscodingErrorInvalidParam",s[s.LiveTranscodingErrorInternalError=17825796]="LiveTranscodingErrorInternalError",s[s.LiveTranscodingErrorRtmpServerError=17825797]="LiveTranscodingErrorRtmpServerError",s[s.LiveTranscodingErrorRtmpStreamUrlError=17825798]="LiveTranscodingErrorRtmpStreamUrlError",s[s.LiveTranscodingErrorPublishTimeout=17825799]="LiveTranscodingErrorPublishTimeout",s[s.LiveTranscodingErrorNotAuthorized=17825800]="LiveTranscodingErrorNotAuthorized",s))(Et||{}),ns=(s=>(s[s.TrascodingPublishTaskStatusStart=0]="TrascodingPublishTaskStatusStart",s[s.TrascodingPublishTaskStatusUpdate=1]="TrascodingPublishTaskStatusUpdate",s[s.TrascodingPublishTaskStatusStop=2]="TrascodingPublishTaskStatusStop",s))(ns||{}),st=(s=>(s[s.MPU_TASK_TRANSACTION_START=0]="MPU_TASK_TRANSACTION_START",s[s.MPU_TASK_TRANSACTION_UPDATE=1]="MPU_TASK_TRANSACTION_UPDATE",s[s.MPU_TASK_TRANSACTION_STOP=2]="MPU_TASK_TRANSACTION_STOP",s[s.MPU_TASK_TRANSACTION_LIST=3]="MPU_TASK_TRANSACTION_LIST",s[s.MPU_TASK_TRANSACTION_POLLING=4]="MPU_TASK_TRANSACTION_POLLING",s[s.MPU_TASK_TRANSACTION_ACKNOWLEDGE=5]="MPU_TASK_TRANSACTION_ACKNOWLEDGE",s[s.MPU_TASK_TRANSACTION_END=6]="MPU_TASK_TRANSACTION_END",s))(st||{});const Mc={0:"/libra/v1/sdk/start-task",1:"/libra/v1/sdk/update-task",2:"/libra/v1/sdk/stop-task",3:"/libra/v1/sdk/list-task",4:"/libra/v1/sdk/polling",5:"/libra/v1/sdk/acknowledge",6:"/"};class as{constructor(c,e,t,r,i,n,a,o){A(this,"videoWidth");A(this,"videoHeight");A(this,"videoFramerate",20);A(this,"videoBitrate",2e3);A(this,"videoGop",30);A(this,"audioSamplerate",Bi.LiveTranscoding_HZ_44100);A(this,"audioBitrate",500);A(this,"audioChannels",1);this.videoWidth=c,this.videoHeight=e,t&&(this.videoFramerate=t),r&&(this.videoBitrate=r),i&&(this.videoGop=i),n&&(this.audioSamplerate=n),a&&(this.audioBitrate=a),o&&(this.audioChannels=o)}}const os=s=>((s&16711680)>>16)+(s&65280)+((s&255)<<16),mt=(s=0,c)=>{if(c==0)return 0;let e=s/c;return e<0&&(e=0),e>1&&(e=1),e};class Li{constructor(c,e,t){A(this,"mixMode",di.LiveTranscodingSingle);A(this,"singleParam");A(this,"mixParam");c&&(this.mixMode=c),e&&(this.singleParam=e),t&&(this.mixParam=t)}toJson(c,e,t,r,i){const n={appid:e.appId,channelid:e.channelId};if(c===st.MPU_TASK_TRANSACTION_POLLING||c===st.MPU_TASK_TRANSACTION_LIST||c===st.MPU_TASK_TRANSACTION_ACKNOWLEDGE)return c===st.MPU_TASK_TRANSACTION_ACKNOWLEDGE&&(n.messageid=i),n;if(n.taskid=t,c!==st.MPU_TASK_TRANSACTION_STOP){if(n.mixmode=this.mixMode,r&&(n.streamurl=r),this.mixMode===di.LiveTranscodingSingle){const a=this.singleParam;if(a){n.streamtype=a.streamType,a.sourceType===ti.LiveTranscodingShareScreen?n.sourcetype=li[a.sourceType]:n.sourcetype=li[ti.LiveTranscodingCamera];const o=[];a.userId&&o.push(a.userId),n.subspecusers=o}}else if(c===st.MPU_TASK_TRANSACTION_START||c===st.MPU_TASK_TRANSACTION_UPDATE){const a=this.mixParam;if(a){a.taskProfile&&(n.taskprofile=Nc[a.taskProfile]);const o=a.encodeParam||new as(1280,720);let u=o.videoWidth,h=o.videoHeight;const g={};Object.keys(o).forEach(l=>{const p=o[l];p>0&&(g[l.toLowerCase()]=p)}),g.lowbitratehighquality=0,n.encodeparam=g,n.backgrounds=a.backgrounds.map(l=>l.toJson(u,h)),n.watermarks=a.watermarks.map(l=>l.toJson(u,h)),n.clockwidgets=a.clockWidgets.map(l=>l.toJson(u,h));const f=a.users.map(l=>l.userId);n.subspecusers=[...new Set(f)],n.layouts=[{audiomixcount:a.users.length,panes:a.users.map((l,p)=>l.toJson(p,u,h,a.mediaProcessMode))}],n.layoutids=["0"],n.cropmode=a.cropMode,n.backgroundcolor=os(a.backgroundColor),n.taskmode=a.mediaProcessMode}}}return n}}var Ct=(s=>(s.pre="pre",s.prod="prod",s))(Ct||{}),It=(s=>(s.AliRtcSdkCommunication="communication",s.AliRtcSdkInteractiveLive="interactive_live",s.AliRtcSdkInteractiveWithLowLatencyLive="cdn_live",s))(It||{}),Tt=(s=>(s.AliRtcSdkInteractive="interactive",s.AliRtcSdkLive="live",s))(Tt||{}),wt=(s=>(s[s.AliEngineLocalDeviceTypeUnknown=0]="AliEngineLocalDeviceTypeUnknown",s[s.AliEngineLocalDeviceTypeMic=1]="AliEngineLocalDeviceTypeMic",s[s.AliEngineLocalDeviceTypeSpeaker=2]="AliEngineLocalDeviceTypeSpeaker",s[s.AliEngineLocalDeviceTypeAudioDevice=3]="AliEngineLocalDeviceTypeAudioDevice",s[s.AliEngineLocalDeviceTypeCamera=4]="AliEngineLocalDeviceTypeCamera",s[s.AliEngineLocalDeviceTypeDisplay=5]="AliEngineLocalDeviceTypeDisplay",s[s.AliEngineLocalDeviceTypeVideoDevice=6]="AliEngineLocalDeviceTypeVideoDevice",s))(wt||{}),Fe=(s=>(s[s.AliEngineLocalDeviceExceptionTypeUnknown=0]="AliEngineLocalDeviceExceptionTypeUnknown",s[s.AliEngineLocalDeviceExceptionTypeMicOpenFail=1]="AliEngineLocalDeviceExceptionTypeMicOpenFail",s[s.AliEngineLocalDeviceExceptionTypeMicInterrupt=2]="AliEngineLocalDeviceExceptionTypeMicInterrupt",s[s.AliEngineLocalDeviceExceptionTypeMicAuthFail=3]="AliEngineLocalDeviceExceptionTypeMicAuthFail",s[s.AliEngineLocalDeviceExceptionTypeMicNotAvailable=4]="AliEngineLocalDeviceExceptionTypeMicNotAvailable",s[s.AliEngineLocalDeviceExceptionTypeSpeakerOpenFail=5]="AliEngineLocalDeviceExceptionTypeSpeakerOpenFail",s[s.AliEngineLocalDeviceExceptionTypeSpeakerInterrupt=6]="AliEngineLocalDeviceExceptionTypeSpeakerInterrupt",s[s.AliEngineLocalDeviceExceptionTypeSpeakerNotAvailable=7]="AliEngineLocalDeviceExceptionTypeSpeakerNotAvailable",s[s.AliEngineLocalDeviceExceptionTypeAudioDeviceException=8]="AliEngineLocalDeviceExceptionTypeAudioDeviceException",s[s.AliEngineLocalDeviceExceptionTypeCameraOpenFail=9]="AliEngineLocalDeviceExceptionTypeCameraOpenFail",s[s.AliEngineLocalDeviceExceptionTypeCameraInterrupt=10]="AliEngineLocalDeviceExceptionTypeCameraInterrupt",s[s.AliEngineLocalDeviceExceptionTypeCameraAuthFail=11]="AliEngineLocalDeviceExceptionTypeCameraAuthFail",s[s.AliEngineLocalDeviceExceptionTypeDisplayException=12]="AliEngineLocalDeviceExceptionTypeDisplayException",s[s.AliEngineLocalDeviceExceptionTypeVideoDeviceException=13]="AliEngineLocalDeviceExceptionTypeVideoDeviceException",s))(Fe||{}),De=(s=>(s[s.AliRtcConnectionStatusInit=0]="AliRtcConnectionStatusInit",s[s.AliRtcConnectionStatusDisconnected=1]="AliRtcConnectionStatusDisconnected",s[s.AliRtcConnectionStatusConnecting=2]="AliRtcConnectionStatusConnecting",s[s.AliRtcConnectionStatusConnected=3]="AliRtcConnectionStatusConnected",s[s.AliRtcConnectionStatusReconnecting=4]="AliRtcConnectionStatusReconnecting",s[s.AliRtcConnectionStatusFailed=5]="AliRtcConnectionStatusFailed",s))(De||{}),Kt=(s=>(s[s.AliRtcConnectionChangedDummyReason=0]="AliRtcConnectionChangedDummyReason",s[s.AliRtcConnectionMediaPathChanged=1]="AliRtcConnectionMediaPathChanged",s[s.AliRtcConnectionSignalingHeartbeatTimeout=2]="AliRtcConnectionSignalingHeartbeatTimeout",s[s.AliRtcConnectionSignalingHeartbeatAlive=3]="AliRtcConnectionSignalingHeartbeatAlive",s[s.AliRtcConnectionSignalingHttpDnsResolved=4]="AliRtcConnectionSignalingHttpDnsResolved",s[s.AliRtcConnectionSignalingHttpDnsFailure=5]="AliRtcConnectionSignalingHttpDnsFailure",s[s.AliRtcConnectionSignalingGslbFailure=6]="AliRtcConnectionSignalingGslbFailure",s[s.AliRtcConnectionSignalingGslbSuccess=7]="AliRtcConnectionSignalingGslbSuccess",s[s.AliRtcConnectionSignalingJoinRoomFailure=8]="AliRtcConnectionSignalingJoinRoomFailure",s[s.AliRtcConnectionSignalingJoinRoomSuccess=9]="AliRtcConnectionSignalingJoinRoomSuccess",s[s.AliRtcConnectionSignalingLeaveRoom=10]="AliRtcConnectionSignalingLeaveRoom",s[s.AliRtcConnectionSignalingConnecting=11]="AliRtcConnectionSignalingConnecting",s[s.AliRtcConnectionChangedNetworkInterrupted=12]="AliRtcConnectionChangedNetworkInterrupted",s))(Kt||{}),cs=(s=>(s[s.AliRtcUserOfflineQuit=0]="AliRtcUserOfflineQuit",s[s.AliRtcUserOfflineDropped=1]="AliRtcUserOfflineDropped",s[s.AliRtcUserOfflineBecomeAudience=2]="AliRtcUserOfflineBecomeAudience",s))(cs||{}),ii=(s=>(s[s.AliRtcAudioTrackNo=0]="AliRtcAudioTrackNo",s[s.AliRtcAudioTrackMic=1]="AliRtcAudioTrackMic",s[s.AliRtcAudioTrackDual=2]="AliRtcAudioTrackDual",s))(ii||{}),Ae=(s=>(s[s.AliRtcVideoTrackNo=0]="AliRtcVideoTrackNo",s[s.AliRtcVideoTrackCamera=1]="AliRtcVideoTrackCamera",s[s.AliRtcVideoTrackScreen=2]="AliRtcVideoTrackScreen",s[s.AliRtcVideoTrackBoth=3]="AliRtcVideoTrackBoth",s))(Ae||{}),be=(s=>(s[s.AliRtcStatePublishIdle=0]="AliRtcStatePublishIdle",s[s.AliRtcStateNoPublish=1]="AliRtcStateNoPublish",s[s.AliRtcStatePublishing=2]="AliRtcStatePublishing",s[s.AliRtcStatePublished=3]="AliRtcStatePublished",s))(be||{}),Le=(s=>(s[s.AliRtcStateSubscribeIdle=0]="AliRtcStateSubscribeIdle",s[s.AliRtcStateNoSubscribe=1]="AliRtcStateNoSubscribe",s[s.AliRtcStateSubscribing=2]="AliRtcStateSubscribing",s[s.AliRtcStateSubscribed=3]="AliRtcStateSubscribed",s))(Le||{}),Je=(s=>(s[s.AliRtcVideoStreamTypeNone=0]="AliRtcVideoStreamTypeNone",s[s.AliRtcVideoStreamTypeHigh=1]="AliRtcVideoStreamTypeHigh",s[s.AliRtcVideoStreamTypeLow=2]="AliRtcVideoStreamTypeLow",s))(Je||{}),mi=(s=>(s[s.CAMERA_INVALID=-1]="CAMERA_INVALID",s[s.CAMERA_REAR=0]="CAMERA_REAR",s[s.CAMERA_FRONT=1]="CAMERA_FRONT",s))(mi||{});const ia=10,ra=5e3,Vi=class Vi extends ve{constructor(e){super();A(this,"ws");A(this,"socketStatus",0);A(this,"wsUrl","");A(this,"lastConnectStartTime",0);A(this,"maxConnectRetryCount",ia);A(this,"connectRetryCount",0);A(this,"gotErr",!1);A(this,"closedByInvoke",!0);A(this,"isReconnecting",!1);A(this,"networkAvailableChecked",!0);this.maxConnectRetryCount=e!=null?e:ia,this.onOpen=this.onOpen.bind(this),this.onMessage=this.onMessage.bind(this),this.onError=this.onError.bind(this),this.onClose=this.onClose.bind(this)}get connectUrl(){return this.wsUrl}get connectStatus(){return this.socketStatus}start(e){this.wsUrl=e,this.initWebSocket()}send(e){return this.ws&&this.socketStatus===2?(this.ws.send(JSON.stringify(e)),!0):!1}close(){this.closedByInvoke=!0,this.uninitWebscoket()}reconnect(){this.emit("onReconnectStart"),this.isReconnecting=!0,this.initWebSocket()}onOpen(e){this.socketStatus=2,this.connectRetryCount=0,this.networkAvailableChecked=!1,this.closedByInvoke=!1,this.gotErr=!1,this.isReconnecting=!1,this.emit("onOpen",e)}onMessage(e){this.emit("onMessage",e)}onError(e){this.isReconnecting&&this.emit("onReconnectFail",e),this.emit("onError",e),this.isReconnecting=!1,this.gotErr=!0}onClose(e){return z(this,null,function*(){const t=this.socketStatus;if(oe.info(Vi.logName,`onClose, status: ${t}, retryCount: ${this.connectRetryCount}`),t!==0||this.connectRetryCount)if(yield At.isNetworkAvailable()){if(!this.networkAvailableChecked&&!this.closedByInvoke&&!this.gotErr){this.reconnect();return}this.networkAvailableChecked=!0,this.emit("onAuthInvalid")}else{if(this.connectRetryCount||this.emit("onNetworkError"),this.closedByInvoke)return;this.connectRetryCount+=1,this.connectRetryCount>this.maxConnectRetryCount?this.emit("onConnectFail"):Date.now()-this.lastConnectStartTime>=ra?this.reconnect():window.setTimeout(()=>{this.reconnect()},ra)}this.socketStatus=0,this.emit("onClose",e)})}initWebSocket(){this.uninitWebscoket(),this.socketStatus=1,this.lastConnectStartTime=Date.now(),this.ws=new WebSocket(this.wsUrl),this.ws.addEventListener("open",this.onOpen),this.ws.addEventListener("message",this.onMessage),this.ws.addEventListener("error",this.onError),this.ws.addEventListener("close",this.onClose)}uninitWebscoket(){this.ws&&(this.ws.removeEventListener("open",this.onOpen),this.ws.removeEventListener("message",this.onMessage),this.ws.removeEventListener("error",this.onError),this.ws.removeEventListener("close",this.onClose),this.ws.close(),this.ws=void 0,this.socketStatus=0)}};A(Vi,"logName","Socket");let us=Vi;var Oe=(s=>(s.KEEPALIVE="keepalive",s.JOINCHANNEL="joinchannel",s.NOTIFYJOIN="notifyjoin",s.NOTIFYSTATUS="notifystatus",s.STATUSREPORT="statusreport",s.LEAVECHANNEL="leavechannel",s.NOTIFYLEAVE="notifyleave",s.NOTIFYPUBLISH="notifypublish",s.BYE="bye",s.RECONNECT="reconnect",s.PUBLISH="publish",s.REFRESHURL="refreshurl",s.UNSUBSCRIBE="unsubscribe",s.ROLEUPDATE="roleupdate",s))(Oe||{});class Fc{constructor(c,e){A(this,"authInfo");A(this,"userName");A(this,"seqIndex",0);this.authInfo=c,this.userName=e}get roleAuth(){if(this.authInfo.role){const{timestamp:c,nonce:e,token:t,role:r}=this.authInfo;return{timestamp:c,nonce:e,token:t,tokenrole:r}}}refreshAuthInfo(c){this.authInfo=c}getSeqIndex(){return this.seqIndex}createKeepAlivePackage(){return this.createBaseSendPackage("keepalive")}createJoinPackage(){let c=this.createBaseSendPackage("joinchannel");return c.header.displayName=this.userName,c.header.clientversion=At.getVersionNumber().toString(),c.header.platform=Ks,this.roleAuth&&(c.data.auth=this.roleAuth),c}crateLeavePackage(){return this.createBaseSendPackage("leavechannel")}createStatusPackage(c){let e=this.createBaseSendPackage("statusreport");return e.header.displayName=this.userName,e.data.status=c,e}createPublishPackage(){let c=this.createBaseSendPackage("publish");return c.data.users=[{}],this.roleAuth&&(c.data.auth=this.roleAuth),c}createRoleUpdatePackage(){let c=this.createBaseSendPackage("roleupdate");return c.header.displayName=this.userName,c}createReconnectPackage(c){let e=this.createBaseSendPackage("reconnect");return e.header.displayName=this.userName,e.header.clientversion=At.getVersionNumber().toString(),e.header.platform=Ks,e.data=Se(Se({},e.data),c!=null?c:{}),this.roleAuth&&(e.data.auth=this.roleAuth),e}createRefreshUrlPackage(){let c=this.createBaseSendPackage("refreshurl");return c.header.displayName=this.userName,c}createResponsePackage(c,e){return{version:1,code:200,tid:c,msgtype:e}}createBaseSendPackage(c){var t;return++this.seqIndex,{version:1,msgtype:c,tid:Vt(),header:{appid:this.authInfo.appId,channelid:this.authInfo.channelId,sessionid:(t=this.authInfo.sessionId)!=null?t:"",userid:this.authInfo.userId},data:{seq:this.seqIndex}}}}var ce=(s=>(s[s.ERR_JOIN_ALREADY_JOINED=16843521]="ERR_JOIN_ALREADY_JOINED",s[s.ERR_JOIN_BAD_APPID=33620481]="ERR_JOIN_BAD_APPID",s[s.ERR_JOIN_INVALID_APPID=33620482]="ERR_JOIN_INVALID_APPID",s[s.ERR_JOIN_BAD_CHANNEL=33620484]="ERR_JOIN_BAD_CHANNEL",s[s.ERR_JOIN_INVALID_CHANNEL=33620483]="ERR_JOIN_INVALID_CHANNEL",s[s.ERR_JOIN_BAD_TOKEN=33620485]="ERR_JOIN_BAD_TOKEN",s[s.ERR_JOIN_TIMEOUT=16908804]="ERR_JOIN_TIMEOUT",s[s.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD=16974081]="ERR_JOIN_ERR_JOIN_BAD_PARAMBAD",s[s.ERR_JOIN_CHANNEL_FAILED=16974338]="ERR_JOIN_CHANNEL_FAILED",s[s.ERR_LOG_ALREADY_INIT=16974085]="ERR_LOG_ALREADY_INIT",s[s.ERR_LOG_ROOT_PATH_ERROR=16974086]="ERR_LOG_ROOT_PATH_ERROR",s[s.ERR_MIC_OPEN_FAIL=17040388]="ERR_MIC_OPEN_FAIL",s[s.ERR_SPEAKER_OPEN_FAIL=17040389]="ERR_SPEAKER_OPEN_FAIL",s[s.ERR_MIC_INTERRUPT=17040390]="ERR_MIC_INTERRUPT",s[s.ERR_SPEAKER_INTERRUPT=17040391]="ERR_SPEAKER_INTERRUPT",s[s.ERR_MIC_AUTH_FAIL=17040392]="ERR_MIC_AUTH_FAIL",s[s.ERR_MIC_NOT_AVAILABLE=17040393]="ERR_MIC_NOT_AVAILABLE",s[s.ERR_SPEAKER_NO_AVAILABLE=17040400]="ERR_SPEAKER_NO_AVAILABLE",s[s.ERR_CAMERA_OPEN_FAIL=17039620]="ERR_CAMERA_OPEN_FAIL",s[s.ERR_CAMERA_INTERRUPT=17039622]="ERR_CAMERA_INTERRUPT",s[s.ERR_VIDEO_DISPLAY_OPEN_FAIL=17039873]="ERR_VIDEO_DISPLAY_OPEN_FAIL",s[s.ERR_VIDEO_DISPLAY_INTERRUPT=1064992]="ERR_VIDEO_DISPLAY_INTERRUPT",s[s.ERR_ICE_CONNECTION_CONNECT_FAIL=17105409]="ERR_ICE_CONNECTION_CONNECT_FAIL",s[s.ERR_ICE_CONNECTION_RECONNECT_FAI=17105410]="ERR_ICE_CONNECTION_RECONNECT_FAI",s[s.ERR_ICE_CONNECTION_MOBILITY_FAIL=17105411]="ERR_ICE_CONNECTION_MOBILITY_FAIL",s[s.ERR_ICE_CONNECTION_HEARTBEAT_TIMEOUT=16908812]="ERR_ICE_CONNECTION_HEARTBEAT_TIMEOUT",s[s.ERR_LATENCY_LIVE_COMMUNICATION_FAILED=17235971]="ERR_LATENCY_LIVE_COMMUNICATION_FAILED",s[s.ERR_LATENCY_LIVE_MEIDASETTING_FAILED=17235972]="ERR_LATENCY_LIVE_MEIDASETTING_FAILED",s[s.ERR_LATENCY_LIVE_NONE_BROADCASTER=17235973]="ERR_LATENCY_LIVE_NONE_BROADCASTER",s[s.ERR_LATENCY_LIVE_NEED_RESTART=17235974]="ERR_LATENCY_LIVE_NEED_RESTART",s[s.ERR_LATENCY_LIVE_NEED_RESTART_AGAIN_LATER=17235975]="ERR_LATENCY_LIVE_NEED_RESTART_AGAIN_LATER",s[s.ERR_LATENCY_LIVE_SERVICE_UNAVAILABLE=17235976]="ERR_LATENCY_LIVE_SERVICE_UNAVAILABLE",s[s.ERR_LATENCY_LIVE_MEDIACONNECTION_INTERRUPTION=17235977]="ERR_LATENCY_LIVE_MEDIACONNECTION_INTERRUPTION",s[s.ERR_SDK_PUBLISH_INVAILD=16974597]="ERR_SDK_PUBLISH_INVAILD",s[s.ERR_SDK_PUBLISH_NOT_JOIN_CHANNEL=16843782]="ERR_SDK_PUBLISH_NOT_JOIN_CHANNEL",s[s.ERR_SDK_PUBLISH_AUDIO_STRAM_FAILED=16843856]="ERR_SDK_PUBLISH_AUDIO_STRAM_FAILED",s[s.ERR_SDK_PUBLISH_VIDEO_STRAM_FAILED=16843857]="ERR_SDK_PUBLISH_VIDEO_STRAM_FAILED",s[s.ERR_SDK_PUBLISH_DUAL_STRAM_FAILED=16843858]="ERR_SDK_PUBLISH_DUAL_STRAM_FAILED",s[s.ERR_SDK_PUBLISH_SCEEN_SHARE_FAILED=16843859]="ERR_SDK_PUBLISH_SCEEN_SHARE_FAILED",s[s.ERR_SDK_PUBLISH_SCREEN_SHARE_CONFIG_ERROR=16843860]="ERR_SDK_PUBLISH_SCREEN_SHARE_CONFIG_ERROR",s[s.ERR_SDK_SUBSCRIBE_INVAILD=16974852]="ERR_SDK_SUBSCRIBE_INVAILD",s[s.ERR_SDK_SUBSCRIBE_NOT_JOIN_CHANNEL=16844112]="ERR_SDK_SUBSCRIBE_NOT_JOIN_CHANNEL",s[s.ERR_SDK_SUBSCRIBE_AUDIO_STRAM_FAILED=16844113]="ERR_SDK_SUBSCRIBE_AUDIO_STRAM_FAILED",s[s.ERR_SDK_SUBSCRIBE_VIDEO_STRAM_FAILED=16844114]="ERR_SDK_SUBSCRIBE_VIDEO_STRAM_FAILED",s[s.ERR_SDK_SUBSCRIBE_DUAL_STRAM_FAILED=16844115]="ERR_SDK_SUBSCRIBE_DUAL_STRAM_FAILED",s[s.ERR_SDK_SUBSCRIBE_SCREEN_SHARE_FAILED=16844116]="ERR_SDK_SUBSCRIBE_SCREEN_SHARE_FAILED",s[s.ERR_SDK_INVALID_STATE=16974340]="ERR_SDK_INVALID_STATE",s[s.ERR_INVALID_ARGUMENTS=16974083]="ERR_INVALID_ARGUMENTS",s[s.ERR_SESSION_REMOVED=33620229]="ERR_SESSION_REMOVED",s[s.ERR_SDK_UPDATE_ROLE_CHANNEL=16908801]="ERR_SDK_UPDATE_ROLE_CHANNEL",s[s.ERR_INNER=-1]="ERR_INNER",s[s.ERR_SDK_MPU_TASK_PUBLISH_OK=0]="ERR_SDK_MPU_TASK_PUBLISH_OK",s[s.ERR_SDK_MPU_TASK_STREAM_NOT_FOUND=17825793]="ERR_SDK_MPU_TASK_STREAM_NOT_FOUND",s[s.ERR_SDK_MPU_TASK_STREAM_ALREADY_EXIST=17825794]="ERR_SDK_MPU_TASK_STREAM_ALREADY_EXIST",s[s.ERR_SDK_MPU_TASK_INVALID_PARAM=17825795]="ERR_SDK_MPU_TASK_INVALID_PARAM",s[s.ERR_SDK_MPU_TASK_INTERNAL_ERROR=17825796]="ERR_SDK_MPU_TASK_INTERNAL_ERROR",s[s.ERR_SDK_MPU_TASK_RTMP_SERVER_ERROR=17825797]="ERR_SDK_MPU_TASK_RTMP_SERVER_ERROR",s[s.ERR_SDK_MPU_TASK_RTMP_STREAM_URL_ERROR=17825798]="ERR_SDK_MPU_TASK_RTMP_STREAM_URL_ERROR",s[s.ERR_SDK_MPU_TASK_PUBLISH_TIMEOUT=17825799]="ERR_SDK_MPU_TASK_PUBLISH_TIMEOUT",s[s.ERR_SDK_MPU_TASK_NOT_AUTHORIZED=17825800]="ERR_SDK_MPU_TASK_NOT_AUTHORIZED",s[s.ERR_SDK_CHANNEL_RELAY_STATE_ERROR=18874369]="ERR_SDK_CHANNEL_RELAY_STATE_ERROR",s[s.ERR_SDK_CHANNEL_RELAY_SRC_NOT_ALLOW=18874370]="ERR_SDK_CHANNEL_RELAY_SRC_NOT_ALLOW",s[s.ERR_SDK_CHANNEL_RELAY_JOIN_DEST_FAILED=18874371]="ERR_SDK_CHANNEL_RELAY_JOIN_DEST_FAILED",s[s.ERR_SDK_CHANNEL_RELAY_TOKEN_INVALID=18874372]="ERR_SDK_CHANNEL_RELAY_TOKEN_INVALID",s[s.ERR_SDK_CHANNEL_RELAY_ROLE_ERROR=18874373]="ERR_SDK_CHANNEL_RELAY_ROLE_ERROR",s[s.ERR_SDK_CHANNEL_RELAY_INVALID_PARAM=18874374]="ERR_SDK_CHANNEL_RELAY_INVALID_PARAM",s[s.ERR_SDK_CHANNEL_RELAY_TO_SELF_ERROR=18874375]="ERR_SDK_CHANNEL_RELAY_TO_SELF_ERROR",s))(ce||{});class ne extends Error{constructor(e,t,r){super(t);A(this,"_code");A(this,"_extra");this._code=e,this._extra=r}static fromError(e,t=-1,r=""){return new ne(t,e.message||e.reason||r||"error",e.extraInfo)}get code(){return this._code}set code(e){this._code=e}get reason(){return this.message}get extra(){return this._extra}}const Oc=3e4,ct=class ct extends ve{constructor(e,t,r,i,n,a){super();A(this,"authInfo");A(this,"userName");A(this,"channelProfile");A(this,"clientRole");A(this,"slsReporter");A(this,"wsClient");A(this,"packageCreater");A(this,"keepAliveTimer",0);A(this,"packageCache",new Map);A(this,"isFirstConnect",!0);A(this,"aliveChecker",0);A(this,"reconnectData");this.authInfo=e,this.userName=t,this.packageCreater=new Fc(e,t),this.channelProfile=r,this.clientRole=i,this.slsReporter=n,this.wsClient=new us(a),this.wsClient.on("onOpen",this.onOpen.bind(this)),this.wsClient.on("onMessage",this.onMessage.bind(this)),this.wsClient.on("onError",this.onError.bind(this)),this.wsClient.on("onClose",this.onClose.bind(this)),this.wsClient.on("onConnectFail",this.onConnectFail.bind(this)),this.wsClient.on("onAuthInvalid",this.onAuthInvalid.bind(this)),this.wsClient.on("onNetworkError",this.onNetworkError.bind(this)),this.wsClient.on("onReconnectStart",this.onReconnectStart.bind(this)),this.wsClient.on("onReconnectFail",this.onReconnectFail.bind(this))}get retryCount(){return this.wsClient.connectRetryCount}start(e){this.wsClient.start(e)}startKeepAlive(){this.keepAliveTimer===0&&(this.keepAliveTimer=window.setInterval(()=>{let e=this.packageCreater.createKeepAlivePackage();this.sendPackage(e)},5e3)),this.checkAlive()}stopKeepAlive(){this.keepAliveTimer!==0&&(clearInterval(this.keepAliveTimer),this.keepAliveTimer=0),this.aliveChecker&&(window.clearTimeout(this.aliveChecker),this.aliveChecker=0)}sendPkgCache(){this.packageCache.forEach(e=>{this.wsClient.send(e)})}leave(){let e=this.packageCreater.crateLeavePackage();this.sendPackage(e)}reportStatus(e){let t=this.packageCreater.createStatusPackage(e);this.sendPackage(t)}publish(e){let t=this.packageCreater.createPublishPackage();t.data.users=[],e.subscribe.signal=this.wsClient.connectUrl;const{tracks:r,resume:i}=e;r.forEach(n=>{const{codec:a,ssrc:o}=n;n.userdata=JSON.stringify({codec:a}),n.ssrc=`${o}`,i&&(n.attr={reason:"reconnect"})}),t.data.users.push(e),this.sendPackage(t)}roleUpdate(e){let t=this.packageCreater.createRoleUpdatePackage();t.data.clientrole=e,this.sendPackage(t)}refreshUrl(e){const t=this.packageCreater.createRefreshUrlPackage();t.data=Se(Rt(Se({},t.data),{sessionid:t.header.sessionid}),e),this.sendPackage(t)}refreshAuthInfo(e){this.authInfo=e,this.packageCreater.refreshAuthInfo(e)}close(){oe.info(`[${ct.logName}] close`),this.stopKeepAlive(),this.wsClient.off("onOpen",this.onOpen.bind(this)),this.wsClient.off("onMessage",this.onMessage.bind(this)),this.wsClient.off("onError",this.onError.bind(this)),this.wsClient.off("onClose",this.onClose.bind(this)),this.wsClient.off("onConnectFail",this.onConnectFail.bind(this)),this.wsClient.off("onAuthInvalid",this.onAuthInvalid.bind(this)),this.wsClient.off("onReconnectStart"),this.wsClient.off("onReconnectFail"),this.wsClient.close()}sendPackage(e){[Oe.KEEPALIVE,Oe.RECONNECT,Oe.JOINCHANNEL].includes(e.msgtype)||this.packageCache.set(e.tid,e),this.wsClient.send(e),e.msgtype!==Oe.KEEPALIVE&&this.slsReporter.reportRoomServerEvent(!0,e.msgtype,e.tid,e)}updateReconnectData(e){this.reconnectData=e}onOpen(){if(oe.info(`[${ct.logName}] onOpen`),this.isFirstConnect){let e=this.packageCreater.createJoinPackage();e.data.configure={channelprofile:this.channelProfile},(this.channelProfile===It.AliRtcSdkInteractiveLive||this.channelProfile===It.AliRtcSdkInteractiveWithLowLatencyLive)&&(e.data.configure.clientrole=this.clientRole),this.sendPackage(e)}else{this.stopKeepAlive();const e=this.packageCreater.createReconnectPackage(this.reconnectData);this.sendPackage(e)}}onMessage(e){try{let t=JSON.parse(e.data);this.packageCache.delete(t.tid),this.onRecvMessage(t),t!=null&&t.msgtype&&(t==null?void 0:t.msgtype)!==Oe.KEEPALIVE&&this.slsReporter.reportRoomServerEvent(!1,t.msgtype,t.tid,t)}catch(t){oe.warn(`[${ct.logName}] onMessage err`,t,e)}}onError(e){oe.warn(`[${ct.logName}] onError`,e),this.isFirstConnect&&this.onConnectFail()}onConnectFail(){oe.warn(`[${ct.logName}] onConnectFail`);const e=new ne(ce.ERR_INNER,"Signaling connect failed.");this.isFirstConnect?this.emit("onJoinChannelResult",e):this.emit("onConnectFail",e)}onAuthInvalid(){oe.warn(`[${ct.logName}] onAuthInvalid`),this.isFirstConnect&&this.emit("onAuthInvalid")}onNetworkError(){oe.warn(`[${ct.logName}] onNetworkError`);const e=new ne(ce.ERR_INNER,"Network error, signaling connect failed.");this.emit("onNetworkError",e)}onClose(e){oe.info(`[${ct.logName}] onClose`,e),this.stopKeepAlive()}onKeepAliveRsp(){this.emit("onKeepAliveRsp"),this.checkAlive()}onReconnectStart(){this.emit("onReconnectStart")}onReconnectFail(){this.emit("onReconnectFail",new ne(ce.ERR_INNER,"signaling reconnect failed."))}checkAlive(){window.clearTimeout(this.aliveChecker),this.aliveChecker=window.setTimeout(()=>{oe.info(`[${ct.logName}] not alive, reconnect`),this.stopKeepAlive(),this.emit("onReconnectStart"),this.wsClient.reconnect()},Oc)}onRecvMessage(e){switch(e.msgtype!==Oe.KEEPALIVE&&oe.info(`[${ct.logName}] recv msg: ${e.msgtype}`),e.msgtype){case Oe.JOINCHANNEL:this.onJoinResult(e);break;case Oe.KEEPALIVE:this.onKeepAliveRsp();break;case Oe.PUBLISH:this.onPublishResult(e);break;case Oe.NOTIFYJOIN:this.onNotifyJoin(e);break;case Oe.NOTIFYSTATUS:this.onNotifyStatus(e);break;case Oe.LEAVECHANNEL:this.onLeaveResult(e);break;case Oe.NOTIFYLEAVE:this.onNotifyLeave(e);break;case Oe.NOTIFYPUBLISH:this.onNotifyPublish(e);break;case Oe.STATUSREPORT:this.onStatusReport(e);break;case Oe.BYE:this.onBye(e);break;case Oe.ROLEUPDATE:this.onRoleUpdateResult(e);break;case Oe.REFRESHURL:this.onRefreshUrlResult(e);break;case Oe.RECONNECT:this.onReconnectResult(e);break}}onJoinResult(e){this.isFirstConnect=!1,this.emit("onJoinChannelResult",e)}onLeaveResult(e){this.emit("onLeaveResult",e.code,e.tid)}onPublishResult(e){this.emit("onPublishResult",e.code,e.tid,e.description)}onRoleUpdateResult(e){this.emit("onRoleUpdateResult",e.code,e.tid,e.description)}onRefreshUrlResult(e){this.emit("onRefreshUrlResult",e)}onReconnectResult(e){if(e.code===200)this.sendPkgCache(),this.startKeepAlive(),this.emit("onReconnectSuccess",e.data.users);else{const t=new ne(ce.ERR_INNER,`reconnect failed, code: ${e.code};description: ${e.description}`);e.code===403&&(t.code=403),this.emit("onReconnectFail",t),this.close()}}onNotifyJoin(e){let t=this.packageCreater.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e&&e.data&&e.data.users&&this.emit("onNotifyJoin",e.data.users)}onNotifyStatus(e){let t=this.packageCreater.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e.data&&e.data.status&&e.data.status.length&&this.emit("onNotifyStatus",e.data.status)}onNotifyLeave(e){let t=this.packageCreater.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e.data&&e.data.users&&e.data.users.length&&this.emit("onNotifyLeave",e.data.users)}onNotifyPublish(e){let t=this.packageCreater.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e.data&&e.data.users&&e.data.users.length&&this.emit("onNotifyPublish",e.data.users)}onStatusReport(e){this.emit("onStatusReport",e.code,e.tid,e.description)}onBye(e){this.stopKeepAlive(),this.emit("onBye",e.reason,e.description)}};A(ct,"logName","RSMessageCenter");let hs=ct;const j=(s,c)=>(e,t,r)=>{const i=r.value;return r.value=function(...n){var g;const a=`[${((g=e.constructor)==null?void 0:g.logName)||""}]`,o=Date.now();let u=[];if(s)try{u=s(n)}catch(f){}oe.interface(a,t,...u);const h=i.apply(this,n);return Promise.resolve(h).then(f=>f).catch(f=>f).then(f=>{var m;let l="";const p=f instanceof Error,d=p&&((m=e.constructor)==null?void 0:m.logError);if(!(!c&&!p)){if(d)l=f;else if(p)l=f.message||"";else if(c)if(f===void 0)l="";else try{l=c(f)}catch(x){}else return;oe.interfaceResult(a,t,!(p&&d),`${Date.now()-o}ms`,l)}}),h},r},ae=s=>s;var Vc=Object.defineProperty,Uc=Object.getOwnPropertyDescriptor,ds=(s,c,e,t)=>{for(var r=t>1?void 0:t?Uc(c,e):c,i=s.length-1,n;i>=0;i--)(n=s[i])&&(r=(t?n(c,e,r):n(r))||r);return t&&r&&Vc(c,e,r),r};const Ni=(it=class extends ve{constructor(e,t,r,i=Ct.prod){super();A(this,"messageCenter");A(this,"authInfo");A(this,"userName");A(this,"channelProfile");A(this,"clientRole");A(this,"slsReporter");A(this,"reconnectData");A(this,"roomServerUri","");this.channelProfile=e,this.clientRole=t,this.slsReporter=r,this.reconnectData={role:{channelprofile:e,clientrole:t}};const n=i===Ct.pre?Ei.pre:Ei.prod;this.roomServerUri=`wss://${n}/roomserver/v1/ws`}updateReconnectData(e){var t;this.reconnectData=e,(t=this.messageCenter)==null||t.updateReconnectData(this.reconnectData)}reset(){oe.info("[roomsig] reset"),this.messageCenter&&(this.messageCenter.close(),this.messageCenter=void 0),this.authInfo=void 0}join(e,t,r){return z(this,null,function*(){return new Promise((i,n)=>{const a={};this.authInfo=e,this.userName=t,this.messageCenter=new hs(e,t,this.channelProfile,this.clientRole,this.slsReporter,r),this.initMessageCenter(),this.messageCenter.once("onJoinChannelResult",u=>{var h,g,f;if(oe.info(`[${it.logName}]`,"join result: ",u),a.taskretrynum=((h=this.messageCenter)==null?void 0:h.retryCount)||0,u.code==200){(g=this.messageCenter)==null||g.sendPkgCache(),(f=this.messageCenter)==null||f.startKeepAlive();let l=u.data;l.tid=u.tid,l.users=u.data.users,l.timestamp=u.timestamp,a.est&&(a.joinconnecttc=Date.now()-a.est),this.slsReporter.reportJoinConnection(a),i(l)}else this.reset(),n(this.handleSignalError(u.code,u.reason,ce.ERR_JOIN_CHANNEL_FAILED))}),this.messageCenter.once("onAuthInvalid",()=>{this.reset(),n(new ne(ce.ERR_JOIN_BAD_TOKEN,"join failed because authentication failed"))}),oe.info(`[${it.logName}]`,"start ws connecting roomserver and auto join when connected");const o={appid:this.authInfo.appId,callid:this.authInfo.sessionId,channelid:this.authInfo.channelId,userid:this.authInfo.userId,nonce:this.authInfo.nonce||"",timestamp:this.authInfo.timestamp,token:this.authInfo.token,authtype:"app",tid:Vt()};e.role&&(o.tokenrole=e.role),a.est=Date.now(),this.messageCenter.start(this.roomServerUri+"?"+At.queryingParam(o))})})}leave(){return oe.info("[roomsig] leave .."),new Promise((e,t)=>{this.messageCenter?(this.messageCenter.on("onLeaveResult",(r,i)=>{oe.info(`[${it.logName}]`,"recv leave response "+r),r===200?(this.updateReconnectData(),this.reset(),e({tid:i})):t(this.handleSignalError(r,"leave error"))}),oe.info(`[${it.logName}]`,"send leave request"),this.messageCenter.leave()):(oe.info(`[${it.logName}]`,"no message center, ok to leave"),e({tid:""}))})}publish(e){return new Promise((t,r)=>{var i;this.messageCenter?(this.messageCenter.once("onPublishResult",(n,a,o)=>{oe.info(`[${it.logName}]`,"recv pubish response "+n),n===200?(this.updateReconnectData(Rt(Se({},this.reconnectData),{publish:{users:[e]}})),t({tid:a})):r(this.handleSignalError(n,`publish error, ${o}`))}),this.authInfo&&(e.sessionid=(i=this.authInfo.sessionId)!=null?i:""),e.callid||(e.callid=Vt()),oe.info(`[${it.logName}]`,"assign callid "+e.callid+" and send publish request"),this.messageCenter.publish(e)):r(this.handleSignalError(-1,"publish error, no message center"))})}roleUpdate(e){return new Promise((t,r)=>{if(!this.messageCenter){r(this.handleSignalError(-1,"role update error, no message center"));return}this.messageCenter.on("onRoleUpdateResult",(i,n,a)=>{var o,u;oe.info(`[${it.logName}]`,"recv role update response "+i),i===200?((u=(o=this.reconnectData)==null?void 0:o.role)!=null&&u.clientrole&&(this.reconnectData.role.clientrole=e,this.updateReconnectData(this.reconnectData)),t({tid:n})):r(this.handleSignalError(i,`role update error, ${a}`))}),this.messageCenter.roleUpdate(e)})}setChannelProfile(e){this.channelProfile=e}refreshUrl(e){return oe.info(`[${it.logName}]`,"refreshUrl .."),new Promise((t,r)=>{if(!this.messageCenter){r(this.handleSignalError(-1,"refresh url error, no message center"));return}this.messageCenter.on("onRefreshUrlResult",i=>{const{code:n,description:a,data:o={}}=i||{};oe.info("recv refresh url response "+n),n===200?t(o):r(this.handleSignalError(n,`refresh url error, ${a}`))}),oe.info("send refresh url request"),this.messageCenter.refreshUrl(e)})}reportStatus(e){return oe.info(`[${it.logName}]`,"reportStatus "+e),new Promise((t,r)=>{this.messageCenter?(this.messageCenter.once("onStatusReport",(i,n)=>{i===200?t():r(new ne(i,n))}),this.messageCenter.reportStatus(e)):r(new ne(-1,"No messageCenter"))})}handleSignalError(e,t,r=ce.ERR_INNER){const i=`signal error: code - ${e}; description - ${t}`;return new ne(r,i)}refreshAuthInfo(e){return z(this,null,function*(){var t;this.authInfo&&(this.authInfo=e,(t=this.messageCenter)==null||t.refreshAuthInfo(this.authInfo))})}initMessageCenter(){var e,t,r,i,n,a,o,u,h,g,f,l;(e=this.messageCenter)==null||e.on("onKeepAliveRsp",()=>{this.emit("onKeepAliveRsp")}),(t=this.messageCenter)==null||t.on("onNotifyJoin",p=>{this.emit("onNotifyJoin",p)}),(r=this.messageCenter)==null||r.on("onNotifyStatus",p=>{this.emit("onNotifyStatus",p)}),(i=this.messageCenter)==null||i.on("onNotifyLeave",p=>{this.emit("onNotifyLeave",p)}),(n=this.messageCenter)==null||n.on("onNotifyPublish",p=>{this.emit("onNotifyPublish",p)}),(a=this.messageCenter)==null||a.on("onBye",(p,d)=>{this.emit("onBye",p,d)}),(o=this.messageCenter)==null||o.on("onReconnectStart",()=>{this.emit("onReconnectStart")}),(u=this.messageCenter)==null||u.on("onReconnectSuccess",p=>{this.emit("onReconnectSuccess",p)}),(h=this.messageCenter)==null||h.on("onReconnectFail",p=>{this.emit("onReconnectFail",p)}),(g=this.messageCenter)==null||g.on("onConnectFail",p=>{this.emit("onConnectFail",p),this.reset()}),(f=this.messageCenter)==null||f.on("onNetworkError",p=>{this.emit("onNetworkError",p)}),(l=this.messageCenter)==null||l.on("onAuthInvalid",()=>{this.emit("onAuthInvalid")})}},A(it,"logName","RoomServerSignaling"),it);ds([j()],Ni.prototype,"join",1),ds([j()],Ni.prototype,"publish",1),ds([j()],Ni.prototype,"roleUpdate",1);let zc=Ni;const Hc="https://pgw.rtn.aliyuncs.com",jc="https://gw.rtn.aliyuncs.com",sa=10*60*1e3,Wc=12,_i=class _i extends ve{constructor(e,t){super();A(this,"env");A(this,"authInfo");A(this,"timer");A(this,"slsReporter");A(this,"expiration",0);A(this,"skipTime",0);A(this,"requestToken",()=>z(this,null,function*(){if(this.skipTime=0,!this.authInfo)return;const{appId:e,channelId:t,userId:r,nonce:i="",token:n,timestamp:a,sessionId:o,role:u}=this.authInfo;let h=jc;this.env===Ct.pre&&(h=Hc);const g=`${h}/gslb/v1/stsupdate?appid=${e}&channelid=${t}&userid=${r}&nonce=${i}&token=${n}&timestamp=${a}&session=${o}${u?`&tokenrole=${u}`:""}&slstoken=true&osstoken=true&tokensid=false`;fetch(g).then(f=>f.json()).then(f=>{var l,p;if(f.code===0){const d=(l=f.data)==null?void 0:l.oss,m=(p=f.data)==null?void 0:p.sls;return this.expiration=d.expiration||m.expiration,this.emit("onTokenUpdate",d,m),oe.event(`[${_i.logName}]`,"getToken",d,m),f}this.slsReporter.reportSTSResult(200)}).catch(f=>{this.slsReporter.reportSTSResult(-1),oe.error(`[${_i.logName}]`,"getToken",f.message)})}));this.slsReporter=e,this.env=t}refreshAuthInfo(e){this.authInfo=e}startSTSUpdate(e){this.authInfo=e,this.requestToken(),this.timer&&clearInterval(this.timer),this.timer=window.setInterval(()=>{if(this.expiration&&Math.floor((Date.now()+sa*1.5)/1e3)<this.expiration&&this.skipTime<Wc){this.skipTime+=1;return}this.requestToken()},sa)}clear(){this.timer&&clearInterval(this.timer)}};A(_i,"logName","StsManager");let ls=_i;class Kc extends ve{constructor(e,t,r,i=Ct.prod){super();A(this,"signaling");A(this,"authInfo");A(this,"userName");A(this,"channelProfile");A(this,"clientRole");A(this,"env",Ct.prod);A(this,"maxConnectRetryCount");A(this,"stsManager");A(this,"slsReporter");this.channelProfile=e,this.clientRole=t,this.env=i,this.slsReporter=r,this.stsManager=new ls(r,i)}reset(){var e;oe.info("[signalingmanager] reset"),(e=this.signaling)==null||e.reset(),this.stsManager.clear(),this.signaling=void 0,this.authInfo=void 0}join(e,t=e.userId,r,i){return this.maxConnectRetryCount=r,this.userName=t,new Promise((n,a)=>{this.signaling?a(new ne(ce.ERR_JOIN_ALREADY_JOINED,"already joined")):(oe.info("[signalingmanager] create signaling"),this.signaling=new zc(this.channelProfile,this.clientRole,this.slsReporter,this.env),this.initSignaling(),i&&(i.rs=Date.now()),this.signaling.join(e,t,r).then(o=>{this.authInfo=e,i&&(i.re=Date.now()),n(o)}).catch(o=>{this.reset(),a(o)}),this.stsManager.startSTSUpdate(e))})}retryJoin(){const e=this.authInfo;this.reset(),e&&this.join(e,this.userName,this.maxConnectRetryCount)}leave(){return new Promise((e,t)=>{this.signaling?this.signaling.leave().then(r=>{this.reset(),e(r)}).catch(r=>{t(r)}):e({tid:""})})}publish(e){return new Promise((t,r)=>{var i;this.signaling&&this.authInfo?(e.userid=this.authInfo.userId,e.displayname=(i=this.userName)!=null?i:this.authInfo.userId,this.signaling.publish(e).then(n=>{t(n)}).catch(n=>{r(n)})):r(new ne(ce.ERR_SDK_PUBLISH_NOT_JOIN_CHANNEL,"no signaling"))})}reportStatus(e){return new Promise((t,r)=>{this.signaling?this.signaling.reportStatus(e).then(()=>{t()}).catch(i=>{r(i)}):r(new ne(-1,"no signaling"))})}setClientRole(e){return z(this,null,function*(){const t=this.clientRole;if(!this.signaling){this.clientRole=e;return}const r=Date.now();try{const i=yield this.signaling.roleUpdate(e);return this.slsReporter.reportRoleUpdateResult(t,e,Date.now()-r,0),i}catch(i){this.slsReporter.reportRoleUpdateResult(t,e,Date.now()-r,i.code||-1)}})}setChannelProfile(e){this.signaling?this.signaling.setChannelProfile(e):this.channelProfile=e}refreshUrl(e){return this.signaling?this.signaling.refreshUrl(e):Promise.reject(new ne(ce.ERR_SDK_INVALID_STATE,"should join first"))}refreshAuthInfo(e){return z(this,null,function*(){var t;try{this.authInfo&&(this.authInfo=Se(Se({},this.authInfo),e),(t=this.signaling)==null||t.refreshAuthInfo(this.authInfo),this.stsManager.refreshAuthInfo(this.authInfo))}catch(r){throw r}})}initSignaling(){var e,t,r,i,n,a,o,u,h,g,f,l,p;(e=this.signaling)==null||e.on("onKeepAliveRsp",this.onKeepAliveRsp.bind(this)),(t=this.signaling)==null||t.on("onNotifyJoin",this.onNotifyJoin.bind(this)),(r=this.signaling)==null||r.on("onNotifyStatus",this.onNotifyStatus.bind(this)),(i=this.signaling)==null||i.on("onNotifyLeave",this.onNotifyLeave.bind(this)),(n=this.signaling)==null||n.on("onNotifyPublish",this.onNotifyPublish.bind(this)),(a=this.signaling)==null||a.on("onBye",this.onBye.bind(this)),(o=this.signaling)==null||o.on("onReconnectStart",this.onReconnectStart.bind(this)),(u=this.signaling)==null||u.on("onReconnectSuccess",this.onReconnectSuccess.bind(this)),(h=this.signaling)==null||h.on("onReconnectFail",this.onReconnectFail.bind(this)),(g=this.signaling)==null||g.on("onConnectFail",this.onConnectFail.bind(this)),(f=this.signaling)==null||f.on("onNetworkError",this.onNetworkError.bind(this)),(l=this.signaling)==null||l.on("onAuthInvalid",this.onAuthInvalid.bind(this)),(p=this.signaling)==null||p.on("onError",this.onError.bind(this))}onKeepAliveRsp(){this.emit("onKeepAliveRsp")}onNotifyJoin(e){this.emit("onNotifyJoin",e)}onNotifyStatus(e){this.emit("onNotifyStatus",e)}onNotifyLeave(e){this.emit("onNotifyLeave",e)}onNotifyPublish(e){this.emit("onNotifyPublish",e)}onBye(e,t){this.emit("onBye",e,t)}onConnectFail(e){this.reset(),this.emit("onConnectFail",e)}onNetworkError(e){this.emit("onNetworkError",e)}onAuthInvalid(e){}onReconnectStart(){this.emit("onReconnectStart")}onReconnectSuccess(e){this.emit("onReconnectSuccess",e)}onReconnectFail(e){this.emit("onReconnectFail",e)}onError(e){this.emit("onError",e)}}const Jt=class Jt{static getInstance(){return Jt.instance||(Jt.instance=new AudioContext),Jt.instance.resume(),Jt.instance}};A(Jt,"instance");let ri=Jt;function $c(s,c,e,t,r){let i=t,n=0,a;const o=s.createAnalyser();o.fftSize=256;const u=new Uint8Array(o.frequencyBinCount);c.connect(o),o.connect(e);const h=()=>{a&&window.clearInterval(a)},g=()=>{a=window.setInterval(()=>{o.getByteFrequencyData(u);let f=Math.round(u.reduce((l,p)=>l+p)/u.length);f=Math.min(100,f),n=f,r&&r(f)},i)};return g(),{updateInterval:f=>{h(),i=f,g()},getLevel:()=>n,dispose:()=>{h(),c.disconnect(),o.disconnect()}}}class qc extends ve{constructor(){super();A(this,"audioContext");A(this,"stream");A(this,"sourceNode");A(this,"analyser");this.audioContext=ri.getInstance(),this.stream=new MediaStream}getLevel(){return this.analyser?this.analyser.getLevel():0}start(e,t=1e3){this.sourceNode&&this.stop(),this.stream.addTrack(e),this.sourceNode=this.audioContext.createMediaStreamSource(this.stream);const r=this.audioContext.createMediaStreamDestination();this.analyser=$c(this.audioContext,this.sourceNode,r,t,i=>{this.emit("audioLevel",i)})}stop(){this.analyser&&this.analyser.dispose(),this.analyser=void 0,this.sourceNode=void 0,this.stream.getAudioTracks().forEach(e=>{this.stream.removeTrack(e)})}dispose(){this.stop()}}class na extends ve{constructor(e,t,r,i){super();A(this,"uid");A(this,"name");A(this,"rtsManager");A(this,"callId","");A(this,"audioLevelMonitor");A(this,"audioVolumeIndicationInterval",0);this.uid=e,this.name=t,this.rtsManager=r,this.audioVolumeIndicationInterval=i,this.audioLevelMonitor=new qc}get userId(){return this.uid}get displayname(){return this.name}createCallId(){this.callId||(this.callId=At.createCallid())}setUserInfo(e,t){this.uid=e,this.name=t}refreshUserInfo(e){this.uid=e}getAudioLevel(){return this.audioLevelMonitor.getLevel()}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval=e}clear(){this.audioLevelMonitor.dispose()}}class aa{static getCurrentStatus(c){let e=0;c.micOpen&&(e+=1),c.micInterrupted&&(e+=2),c.cameraOpen&&(e+=4),c.screenShare&&(e+=128),c.audioDisable&&(e+=8),c.videoDisable&&(e+=16),c.screenDisable&&(e+=256);let t=e.toString(16);for(;t.length<16;)t="0"+t;return t}static parseStatus(c){let e=parseInt(c,16);return{micOpen:!!(e&1),micInterrupted:!!(e&2),cameraOpen:!!(e&4),screenShare:!!(e&128),audioDisable:!!(e&8),videoDisable:!!(e&16),screenDisable:!!(e&256),backgroundMode:!!(e&32),accompanyPlaying:!!(e&64)}}}const oa="customVideoProfile",ca="customScreenProfile",gi={width:1280,height:720,frameRate:30,maxBitrate:2e3},vi={width:1920,height:1080,frameRate:30,maxBitrate:2600},Gc={1e4:Fe.AliEngineLocalDeviceExceptionTypeUnknown,2e4:Fe.AliEngineLocalDeviceExceptionTypeUnknown,10001:Fe.AliEngineLocalDeviceExceptionTypeMicNotAvailable,10002:Fe.AliEngineLocalDeviceExceptionTypeMicAuthFail,10003:Fe.AliEngineLocalDeviceExceptionTypeMicOpenFail,10005:Fe.AliEngineLocalDeviceExceptionTypeCameraAuthFail,10004:Fe.AliEngineLocalDeviceExceptionTypeVideoDeviceException,10006:Fe.AliEngineLocalDeviceExceptionTypeCameraOpenFail,10010:Fe.AliEngineLocalDeviceExceptionTypeDisplayException,10011:Fe.AliEngineLocalDeviceExceptionTypeDisplayException,10012:Fe.AliEngineLocalDeviceExceptionTypeDisplayException,10013:Fe.AliEngineLocalDeviceExceptionTypeDisplayException,10014:Fe.AliEngineLocalDeviceExceptionTypeDisplayException,10019:Fe.AliEngineLocalDeviceExceptionTypeDisplayException},Jc=s=>s.getAudioTracks()[0];function ua(s){var c;if(((c=s==null?void 0:s.nodeName)==null?void 0:c.toLowerCase())==="video")return s.setAttribute("playsinline",""),s;if(typeof s=="string"){let e=document.getElementById(s);if(e){if(e.nodeName.toLocaleLowerCase()==="video")return e.setAttribute("playsinline",""),e;throw new ne(ce.ERR_INVALID_ARGUMENTS,"element should be HtmlVideoElement")}else throw new ne(ce.ERR_INVALID_ARGUMENTS,"element not founded")}else throw new ne(ce.ERR_INVALID_ARGUMENTS,"element id should be string")}function fs(s){var e;const c=[];if(Array.isArray(s))s.forEach(t=>{try{c.push(ua(t))}catch(r){}});else if(typeof s=="string"||((e=s==null?void 0:s.nodeName)==null?void 0:e.toLowerCase())==="video")try{c.push(ua(s))}catch(t){}return c}function $t(s){return new Promise(c=>setTimeout(c,s))}const ha=(s,c)=>{const e=()=>(s.muted=!0,Promise.race([$t(500),s._playPromise||Promise.resolve()]).catch(()=>{}).then(()=>{let t;return s.srcObject!==c?(s.load(),s.srcObject=c,t=s.play(),s._playPromise=t):t=Promise.resolve(),t}));return new Promise(t=>{if(me.AliRTS.BrowserUtil.isMicroMessenger){const r=window.top!==window.self,i=window.WeixinJSBridge||window.top.WeixinJSBridge;i?i.invoke("getNetworkType",{},()=>{t(e())}):(r?window.top.document:document).addEventListener("WeixinJSBridgeReady",()=>{i.invoke("getNetworkType",{},()=>{t(e())})}),setTimeout(()=>{t(e())},1e3)}else t(e())})},Bt=s=>{Promise.race([$t(100),s._playPromise||Promise.resolve()]).catch(()=>{}).then(()=>{s.srcObject=null,s._playPromise=void 0})};var Xc=Object.defineProperty,Zc=Object.getOwnPropertyDescriptor,ze=(s,c,e,t)=>{for(var r=t>1?void 0:t?Zc(c,e):c,i=s.length-1,n;i>=0;i--)(n=s[i])&&(r=(t?n(c,e,r):n(r))||r);return t&&r&&Xc(c,e,r),r};const da=30;class Mi extends ve{constructor(){super();A(this,"state");A(this,"time");this.state=be.AliRtcStatePublishIdle,this.time=Date.now()}setState(e){const t=this.state,r=this.time;this.state=e,this.time=Date.now(),this.emit("change",t,e,Math.floor((this.time-r)/1e3))}}const Ve=(Lt=class extends na{constructor(e){const{rtsManager:t,localStreamManager:r,slsReporter:i,signalingManager:n,audioVolumeIndicationInterval:a,parameter:o}=e;super("","",t,a);A(this,"url","");A(this,"joinTime",0);A(this,"_isPublishing",!1);A(this,"publishPromise",Promise.resolve(""));A(this,"previewElements",[]);A(this,"screenPreviewElements",[]);A(this,"streamManager");A(this,"streamTracks");A(this,"publishId",Vt());A(this,"signalingManager");A(this,"traceId","");A(this,"monitorTimerId");A(this,"monitorDataCache",{});A(this,"trackTraceIdMap",{});A(this,"candidateDataCache",[]);A(this,"pcMediaStatsMap",{});A(this,"slsReporter");A(this,"audioPubState");A(this,"videoPubState");A(this,"videoSmallPubState");A(this,"screenPubState");A(this,"parameter",{});A(this,"onTrackEnd",e=>{this.emit(e)});this.streamManager=r,this.signalingManager=n,this.slsReporter=i,this.parameter=o,this.streamManager.on("trackended",u=>{this.onTrackEnd(u)}),this.streamManager.on("publishupdate",()=>{this.publishUpdate()}),this.audioPubState=new Mi,this.audioPubState.on("change",(u,h,g)=>{this.emit("audioPublishStateChanged",u,h,g)}),this.videoPubState=new Mi,this.videoPubState.on("change",(u,h,g)=>{this.emit("videoPublishStateChanged",u,h,g)}),this.videoSmallPubState=new Mi,this.videoSmallPubState.on("change",(u,h,g)=>{this.emit("dualStreamPublishStateChanged",u,h,g)}),this.screenPubState=new Mi,this.screenPubState.on("change",(u,h,g)=>{this.emit("screenPublishStateChanged",u,h,g)}),this.startStreamMonitor()}get joined(){return!!this.uid}get isPublishing(){return this._isPublishing}get publishStreams(){return this.streamManager.publishStreams}get cameraTrack(){return this.streamManager.cameraStreamInfo.originVideoTrack}get screenTrack(){return this.streamManager.screenStreamInfo.originVideoTrack}get audioTrack(){return this.streamManager.cameraStreamInfo.originAudioTrack}get hasCamera(){return!!this.streamManager.cameraStreamInfo.originVideoTrack}get hasMicrophone(){return!!this.streamManager.cameraStreamInfo.originAudioTrack}get hasScreenShare(){return!!this.streamManager.screenStreamInfo.originVideoTrack}get hasCameraTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:r,msid:i})=>r==="video"&&t&&i===Z.VideoLarge))}get hasCameraDualTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:r,msid:i})=>r==="video"&&t&&i===Z.VideoSmall))}get hasScreenTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:r,msid:i})=>r==="video"&&t&&i===Z.Screen))}get hasAudioTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:r,msid:i})=>r==="audio"&&t&&i===Z.Audio))}get cameraDirection(){var e,t;return(t=(e=this.streamManager.cameraStreamInfo)==null?void 0:e.cameraVideoConstraints)==null?void 0:t.facingMode}get audioCaptureDisabled(){return this.streamManager.audioCaptureDisabled}get cameraCaptureDisabled(){return this.streamManager.cameraCaptureDisabled}get publishLocalVideoStreamEnabled(){return this.streamManager.publishLocalVideoStreamEnabled}get publishLocalAudioStreamEnabled(){return this.streamManager.publishLocalAudioStreamEnabled}get publishLocalScreenStreamEnabled(){return this.streamManager.publishLocalScreenStreamEnabled}setPublishLocalAudioStreamEnabled(e){this.streamManager.publishLocalAudioStreamEnabled=e}setPublishLocalVideoStreamEnabled(e){this.streamManager.publishLocalVideoStreamEnabled=e}setPublishLocalScreenStreamEnabled(e){this.streamManager.publishLocalScreenStreamEnabled=e}initInfo(e,t){this.joinTime=Date.now(),this.rtsManager.localJoinTime=this.joinTime,this.setUserInfo(e.userId,e.userId),this.url=t,this.callId=e.sessionId||At.createCallid(),this.updatePubId()}setVideoProfile(e,t){return z(this,null,function*(){yield this.streamManager.setVideoProfile(e,t)})}setVideoContentHint(e){this.streamManager.setVideoContentHint(e)}setScreenContentHint(e){this.streamManager.setScreenContentHint(e)}setAudioProfile(e){return z(this,null,function*(){yield this.streamManager.setAudioProfile(e)})}setScreenProfile(e,t){return z(this,null,function*(){yield this.streamManager.setScreenProfile(e,t)})}setCameraDirection(e){if(e===mi.CAMERA_FRONT)this.streamManager.setCameraVideoConstraints({facingMode:"user"});else if(e===mi.CAMERA_REAR)this.streamManager.setCameraVideoConstraints({facingMode:"environment"});else throw new ne(ce.ERR_CAMERA_OPEN_FAIL,`camera direction set to ${e} failed`)}setCameraDeviceId(e){this.streamManager.setCameraVideoConstraints({deviceId:e})}muteLocalCamera(e){this.streamManager.setCameraMuted(e),this.slsReporter.reportMute(this.callId,!e,"video")}muteLocalMic(e){this.streamManager.setAudioMuted(e),this.slsReporter.reportMute(this.callId,!e,"audio")}muteLocalScreen(e){this.streamManager.setScreenMuted(e),this.slsReporter.reportMute(this.callId,!e,"screen")}setMicrophoneDeviceId(e){this.streamManager.setMicAudioConstraints({deviceId:e})}updatePubId(){this.publishId=Vt()}clearPublishState(){this.streamTracks=void 0}clear(){return z(this,null,function*(){As(Lt.prototype,this,"clear").call(this),this._isPublishing&&(yield this.unPublish()),this.stopPreview(),this.resetPreviewElements(),this.resetSecondayPreviewElements(),this.clearStream(),this.streamManager.cameraCaptureDisabled=!1})}resetElement(e){this.previewElements.includes(e)&&(Bt(e),this.previewElements.splice(this.previewElements.indexOf(e),1)),this.screenPreviewElements.includes(e)&&(Bt(e),this.screenPreviewElements.splice(this.screenPreviewElements.indexOf(e),1))}setPreviewElement(e){const{videoElement:t,screen:r}=e;r?this.screenPreviewElements.includes(t)||this.screenPreviewElements.push(t):this.previewElements.includes(t)||this.previewElements.push(t)}setViewConfig(e,t){if(!e){t===Ae.AliRtcVideoTrackCamera?this.stopPreview({primary:!0,screen:!1}):this.stopPreview({primary:!1,screen:!0});return}if(![Ae.AliRtcVideoTrackCamera,Ae.AliRtcVideoTrackScreen].includes(t))throw new ne(ce.ERR_INVALID_ARGUMENTS,"set view config invalid track",{track:t});e.forEach(r=>{this.setPreviewElement({videoElement:r,screen:t===Ae.AliRtcVideoTrackScreen})})}startCameraCapture(e){return z(this,null,function*(){return this.streamManager.cameraCaptureDisabled=!1,yield this.createLocalStream(e)})}stopCameraCapture(){return z(this,null,function*(){this.streamManager.cameraCaptureDisabled=!0,yield this.stopLocalStream({video:!0})})}stopAudioCapture(){return z(this,null,function*(){this.streamManager.audioCaptureDisabled=!0,yield this.stopLocalStream({audio:!0})})}preview(e){return z(this,null,function*(){const{videoElement:t,screen:r}=e!=null?e:{};try{let i=r?this.streamManager.screenStreamInfo.previewStream:this.streamManager.cameraStreamInfo.previewStream;if(!t)throw new ne(ce.ERR_INVALID_ARGUMENTS,"no video element found",{videoElement:t});if(!i){oe.info(`[${Lt.logName}]`,"preview no stream founded");return}return ha(t,i.mediaStream),this.setPreviewElement(e),i.mediaStream}catch(i){const n=ce.ERR_INNER;throw ne.fromError(i,n,"preview failed")}})}previewAll(e){return z(this,null,function*(){const{primary:t=!0,screen:r=!0}=e!=null?e:{};if(t&&this.previewElements.length)for(let i=0;i<this.previewElements.length;i++){const n=this.previewElements[i];yield this.preview({videoElement:n})}if(r&&this.screenPreviewElements.length)for(let i=0;i<this.screenPreviewElements.length;i++){const n=this.screenPreviewElements[i];yield this.preview({videoElement:n,screen:!0})}})}stopPreview(e){const{videoElement:t,primary:r=!0,screen:i=!0}=e||{};if(!t)r&&(this.previewElements.forEach(n=>{Bt(n)}),this.previewElements=[]),i&&(this.screenPreviewElements.forEach(n=>{Bt(n)}),this.screenPreviewElements=[]);else{const n=this.previewElements.findIndex(a=>a===t);if(n>=0)this.previewElements.splice(n,1),Bt(t);else{const a=this.screenPreviewElements.findIndex(o=>o===t);a>=0&&(this.screenPreviewElements.splice(a,1),Bt(t))}}}resumePublish(){return z(this,null,function*(){this._isPublishing=!1,yield this.startPublish(!0)})}createLocalStream(e){return z(this,null,function*(){try{const t=yield this.streamManager.createLocalStream(e);return t!=null&&t.audioTrack&&this.audioVolumeIndicationInterval>0&&this.audioLevelMonitor.start(t.audioTrack,this.audioVolumeIndicationInterval),e.video?this.previewAll({primary:!0}):e.screen&&this.previewAll({screen:!0}),t}catch(t){const r=Gc[t.errorCode];throw r&&(e.audio?this.emit("localDeviceException",wt.AliEngineLocalDeviceTypeMic,r,""):e.video?this.emit("localDeviceException",wt.AliEngineLocalDeviceTypeCamera,r,""):e.screen?this.emit("localDeviceException",wt.AliEngineLocalDeviceTypeDisplay,r,""):this.emit("localDeviceException",wt.AliEngineLocalDeviceTypeUnknown,r,"")),t}})}stopLocalStream(e){return z(this,null,function*(){e.audio&&this.audioLevelMonitor.stop(),yield this.streamManager.stopLocalStream(e)})}compareAndPublish(e,t,r){return z(this,null,function*(){var n,a;if(!e&&!t)return;if(e&&!t){const o={};return r===Z.Audio?o.audio=!0:r===Z.VideoLarge||r===Z.VideoSmall?(o.video=!0,o.vMsid=r):r===Z.Screen&&(o.screen=!0),yield this.publishDeleteTracks(o)}const i={};if(t!=null&&t.hasVideo&&(i.isScreen=r===Z.Screen,i.vMsid=r),t!=null&&t.hasAudio&&(i.aMsid=r),!e&&t)return yield this.publishAdd(t,i,!1);if(e&&t){const o=e.trackId,u=((n=t.videoTrack)==null?void 0:n.id)||((a=t.audioTrack)==null?void 0:a.id);if(o!==u)return yield this.publishReplace(t,i)}})}reportAudioProfile(){const e=this.streamManager.cameraStreamInfo.audioProfile||"standard",t=me.AliRTS.AudioProfileMap.get(e);this.slsReporter.reportPublishProfile(Z.Audio,{a_profile:e,bits:(t==null?void 0:t.maxBitrate)||0,samplerate:(t==null?void 0:t.sampleRate)||0,channel:(t==null?void 0:t.channelCount)||0})}reportVideoProfile(){const e=this.streamManager.cameraStreamInfo.videoProfile||"",t=me.AliRTS.VideoProfileMap.get(e);t&&this.slsReporter.reportPublishProfile(Z.VideoLarge,{v_profile:e,wdth:(t==null?void 0:t.width)||0,hgt:(t==null?void 0:t.height)||0,fps:(t==null?void 0:t.frameRate)||0,bitrate:(t==null?void 0:t.maxBitrate)||0})}reportScreenProfile(){const e=this.streamManager.screenStreamInfo.videoProfile||"",t=me.AliRTS.VideoProfileMap.get(e);t&&this.slsReporter.reportPublishProfile(Z.Screen,{v_profile:e,wdth:(t==null?void 0:t.width)||0,hgt:(t==null?void 0:t.height)||0,fps:(t==null?void 0:t.frameRate)||0,bitrate:(t==null?void 0:t.maxBitrate)||0})}startPublish(){return z(this,arguments,function*(e=!1,t=Ot.MANUAL){if(!this.joined)return;this.createCallId();const r=yield this.streamManager.publishStreams,{audio:i,video:n,videoSmall:a,screen:o}=r;try{const u=new Date().getTime();i&&this.audioPubState.setState(be.AliRtcStatePublishing),n&&this.videoPubState.setState(be.AliRtcStatePublishing),a&&this.videoSmallPubState.setState(be.AliRtcStatePublishing),o&&this.screenPubState.setState(be.AliRtcStatePublishing),this.publishPromise=this.rtsManager.publish(this.url,this.callId,e,t);const h=yield this.publishPromise;this._isPublishing=!0,this.streamTracks=this.rtsManager.publishingTracks,this.traceId=h,i&&(this.trackTraceIdMap[Z.Audio]=h,this.reportAudioProfile()),a&&(this.trackTraceIdMap[Z.VideoSmall]=h),n&&(this.trackTraceIdMap[Z.VideoLarge]=h,this.reportVideoProfile()),o&&(this.trackTraceIdMap[Z.Screen]=h,this.reportScreenProfile());const g={type:Ft.Add,userid:this.userId,sessionid:"",displayname:this.name,pubid:this.publishId,resume:e,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callId,tracks:this.streamTracks,traceId:h};yield this.syncPublishToRoomServer(g,r,u),i&&this.audioPubState.setState(be.AliRtcStatePublished),n&&this.videoPubState.setState(be.AliRtcStatePublished),a&&this.videoSmallPubState.setState(be.AliRtcStatePublished),o&&this.screenPubState.setState(be.AliRtcStatePublished)}catch(u){throw i&&this.audioPubState.setState(be.AliRtcStateNoPublish),n&&this.videoPubState.setState(be.AliRtcStateNoPublish),a&&this.videoSmallPubState.setState(be.AliRtcStateNoPublish),o&&this.screenPubState.setState(be.AliRtcStateNoPublish),u}})}publishUpdate(){return z(this,null,function*(){var i,n,a,o;if(!this._isPublishing)return;yield this.publishPromise;const e=this.streamManager.publishStreams;let t;const r=new Date().getTime();try{const u=(i=this.streamTracks)==null?void 0:i.find(({ssrc:x,type:v,msid:b})=>v==="audio"&&x&&b===Z.Audio),h=yield this.compareAndPublish(u,e.audio,Z.Audio);h&&(t=h);const g=(n=this.streamTracks)==null?void 0:n.find(({ssrc:x,type:v,msid:b})=>v==="video"&&x&&b===Z.VideoLarge),f=yield this.compareAndPublish(g,e.video,Z.VideoLarge);f&&(t=f);const l=(a=this.streamTracks)==null?void 0:a.find(({ssrc:x,type:v,msid:b})=>v==="video"&&x&&b===Z.VideoSmall),p=yield this.compareAndPublish(l,e.videoSmall,Z.VideoSmall);p&&(t=p);const d=(o=this.streamTracks)==null?void 0:o.find(({ssrc:x,type:v,msid:b})=>v==="video"&&x&&b===Z.Screen),m=yield this.compareAndPublish(d,e.screen,Z.Screen);if(m&&(t=m),!t)return;yield this.syncPublishToRoomServer(t,e,r)}catch(u){const{code:h}=u!=null?u:{},g=this.url;throw h===403&&g&&(yield this.refreshPushStreamUrl(),t=yield this.publishUpdate()),u}return t})}syncPublishToRoomServer(e,t,r){return z(this,null,function*(){if(!e)throw new ne(ce.ERR_INNER,"sync publish to room server failed because no publishInfo");const i=yield this.signalingManager.publish(e);e.signaltid=i.tid})}refreshPushStreamUrl(){return z(this,null,function*(){const e=new ne(ce.ERR_INNER,"refresh push stream url error"),t=this.url;if(!t)throw e;const r=yield this.signalingManager.refreshUrl({pushstreamurl:t});if(!(r!=null&&r.pushstreamurl))throw e;this.url=r==null?void 0:r.pushstreamurl})}publishAdd(e,t,r=!1,i=0){return z(this,null,function*(){this.createCallId();const n=(t==null?void 0:t.aMsid)===Z.Audio,a=(t==null?void 0:t.vMsid)===Z.VideoLarge,o=(t==null?void 0:t.vMsid)===Z.VideoSmall,u=(t==null?void 0:t.vMsid)===Z.Screen;n&&this.audioPubState.setState(be.AliRtcStatePublishing),a&&this.videoPubState.setState(be.AliRtcStatePublishing),o&&this.videoSmallPubState.setState(be.AliRtcStatePublishing),u&&this.screenPubState.setState(be.AliRtcStatePublishing);try{const h=yield this.rtsManager.publishAdd(this.url,e,this.callId,t,!1,0,!0);n&&(this.audioPubState.setState(be.AliRtcStatePublished),this.reportAudioProfile(),this.trackTraceIdMap[Z.Audio]=h),a&&(this.videoPubState.setState(be.AliRtcStatePublished),this.reportVideoProfile(),this.trackTraceIdMap[Z.VideoLarge]=h),o&&(this.videoSmallPubState.setState(be.AliRtcStatePublished),this.trackTraceIdMap[Z.VideoSmall]=h),u&&(this.screenPubState.setState(be.AliRtcStatePublished),this.reportScreenProfile(),this.trackTraceIdMap[Z.Screen]=h),this.streamTracks=this.rtsManager.publishingTracks;const g={type:Ft.Add,userid:this.userId,sessionid:"",displayname:this.name,pubid:this.publishId,resume:r,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callId,tracks:this.streamTracks,traceid:h};return this.reportSelfDeviceStatus(),this.monitorTimerId||this.startStreamMonitor(),g}catch(h){let g=ce.ERR_SDK_PUBLISH_INVAILD;if(n&&(this.audioPubState.setState(be.AliRtcStateNoPublish),g=ce.ERR_SDK_PUBLISH_AUDIO_STRAM_FAILED),a&&(this.videoPubState.setState(be.AliRtcStateNoPublish),g=ce.ERR_SDK_PUBLISH_VIDEO_STRAM_FAILED),o&&(this.videoSmallPubState.setState(be.AliRtcStateNoPublish),g=ce.ERR_SDK_PUBLISH_DUAL_STRAM_FAILED),u&&(this.screenPubState.setState(be.AliRtcStateNoPublish),g=ce.ERR_SDK_PUBLISH_SCEEN_SHARE_FAILED),h.errorCode===15006&&i<3)return this.publishAdd(e,t,r,i+1);throw ne.fromError(h,g,"publish add failed")}})}publishReplace(e,t){return z(this,null,function*(){try{yield this.rtsManager.publishReplace(this.url,e,t),this.streamTracks=this.rtsManager.publishingTracks;const r={type:Ft.Replace,userid:this.userId,sessionid:"",pubid:this.publishId,displayname:this.name,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callId,tracks:this.streamTracks};return this.reportSelfDeviceStatus(),r}catch(r){throw ne.fromError(r,ce.ERR_INNER,`publish replace failed, vMsid: ${t==null?void 0:t.vMsid} aMsid: ${t==null?void 0:t.aMsid}`)}})}publishDeleteTracks(e){return z(this,null,function*(){const t={type:Ft.Delete,userid:this.userId,sessionid:"",displayname:this.displayname,callid:this.callId,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},tracks:[]};try{return yield this.rtsManager.publishDelete(this.url,e),this.streamTracks=this.rtsManager.publishingTracks,e.audio&&this.audioPubState.setState(be.AliRtcStateNoPublish),e.video&&(e.vMsid===Z.VideoSmall?this.videoSmallPubState.setState(be.AliRtcStateNoPublish):this.videoPubState.setState(be.AliRtcStateNoPublish)),e.screen&&this.screenPubState.setState(be.AliRtcStateNoPublish),t.tracks=this.streamTracks,this.reportSelfDeviceStatus(),t}catch(r){throw ne.fromError(r,ce.ERR_INNER,"publish delete tracks failed")}})}publishStop(){return z(this,null,function*(){if(!this._isPublishing)throw new ne(ce.ERR_INNER,"publish stop failed, previous localStream is required for publishing stopping");oe.info(`[${Lt.logName}]`,"publishStop",{url:this.url});const e=new Date().getTime();try{const t=this.hasAudioTrackInMS,r=this.hasCameraTrackInMS,i=this.hasCameraDualTrackInMS,n=this.hasScreenTrackInMS;yield this.rtsManager.publishStop(this.url),t&&this.audioPubState.setState(be.AliRtcStateNoPublish),r&&this.videoPubState.setState(be.AliRtcStateNoPublish),i&&this.videoSmallPubState.setState(be.AliRtcStateNoPublish),n&&this.screenPubState.setState(be.AliRtcStateNoPublish),this.traceId="",Object.keys(this.monitorDataCache).forEach(o=>{this.reportPublishMonitor(o)}),this.streamTracks=[];const a={type:Ft.Stop,userid:this.userId,sessionid:"",displayname:this.displayname,callid:this.callId,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},tracks:[]};return this.syncPublishToRoomServer(a,{},e),a}catch(t){throw ne.fromError(t,ce.ERR_INNER,"publish stop failed")}})}unPublish(){return z(this,null,function*(){const e=new Date().getTime();let t={type:Ft.UnPublish,userid:this.userId,sessionid:"",displayname:this.displayname,callid:this.callId,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},tracks:[]};try{if(this._isPublishing){const r=this.hasAudioTrackInMS,i=this.hasCameraTrackInMS,n=this.hasCameraDualTrackInMS,a=this.hasScreenTrackInMS;yield this.rtsManager.unpublish(),this.streamTracks=[],this.stopStreamMonitor(),r&&this.audioPubState.setState(be.AliRtcStateNoPublish),i&&this.videoPubState.setState(be.AliRtcStateNoPublish),n&&this.videoSmallPubState.setState(be.AliRtcStateNoPublish),a&&this.screenPubState.setState(be.AliRtcStateNoPublish),this._isPublishing=!1,this.traceId="",this.clearStream()}return this.slsReporter.reportUnpublish(this.callId||"",e,0,""),t}catch(r){throw ne.fromError(r,ce.ERR_INNER,"unpublish failed")}})}reportSelfDeviceStatus(){this.emit(et.Local,this.getDeviceStatus())}getDeviceStatus(){var t,r,i,n;let e={micOpen:!1,micInterrupted:!1,cameraOpen:!1,screenShare:!1,audioDisable:!0,videoDisable:!0,screenDisable:!0,backgroundMode:!1,accompanyPlaying:!1};return e.cameraOpen=this.hasCamera,e.micOpen=this.hasMicrophone,e.screenShare=this.hasScreenShare,e.audioDisable=!((t=this.streamManager.cameraStreamInfo.originAudioTrack)!=null&&t.enabled),e.videoDisable=!((r=this.streamManager.cameraStreamInfo.originVideoTrack)!=null&&r.enabled),e.screenDisable=!this.hasScreenShare||!((n=(i=this.streamManager.screenStreamInfo)==null?void 0:i.originVideoTrack)!=null&&n.enabled),aa.getCurrentStatus(e)}resetPreviewElements(){this.previewElements=[]}resetSecondayPreviewElements(){this.screenPreviewElements=[]}getMediaStats(e){return this.pcMediaStatsMap[e]}reportPublishMonitor(e){if(!e)return;let t;try{e===Z.Audio?t=this.rtsManager.getStreamByMsid({url:this.url,aMsid:e}).audioTrack:t=this.rtsManager.getStreamByMsid({url:this.url,vMsid:e}).videoTrack}catch(r){}this.slsReporter.reportPublishMonitor(this.callId,this.trackTraceIdMap[e]||"",e,t,this.monitorDataCache[e]),this.monitorDataCache[e]=[]}reportNetwork(){this.slsReporter.reportNetworkMonitor(this.candidateDataCache),this.candidateDataCache=[]}startStreamMonitor(){this.monitorTimerId||(this.monitorTimerId=window.setInterval(()=>z(this,null,function*(){var e,r;try{const i=yield this.rtsManager.getPCStats();let n;i==null||i.forEach(u=>{u.type==="media-source"||u.type==="media-playout"?u.id&&(this.pcMediaStatsMap[u.id]=u):u.type==="candidate-pair"&&u.state==="succeeded"&&(n=u)});let a;if(((e=this.candidateDataCache)==null?void 0:e.length)>0){const t=this.candidateDataCache[this.candidateDataCache.length-1]||{},{_last:h}=t;a=$i(t,["_last"])}((r=this.candidateDataCache)==null?void 0:r.length)>=da&&this.reportNetwork(),n&&(n._last=a,this.candidateDataCache.push(n));let o=Object.keys(this.monitorDataCache).filter(u=>{var h;return((h=this.monitorDataCache[u])==null?void 0:h.length)>0});(this.streamTracks||[]).forEach(u=>{const h=u.msid;if(!h)return;o.includes(h)&&(o=o.filter(l=>l!==h));let g;h===Z.Audio?g=this.rtsManager.getPublishAudioStats(this.url):g=this.rtsManager.getPublishVideoStats(this.url,h),g.then(l=>{if(!l.timestamp)return;this.monitorDataCache[h]||(this.monitorDataCache[h]=[]);const p=this.getMediaStats(l.mediaSourceId);l._source=p;const d=this.monitorDataCache[h];let m;if((d==null?void 0:d.length)>0){const x=d[d.length-1]||{},{_last:b}=x;m=$i(x,["_last"])}(d==null?void 0:d.length)>=da&&this.reportPublishMonitor(h),l._last=m,l._codec=u.codec||"",this.monitorDataCache[h].push(l)})}),o.forEach(u=>{this.reportPublishMonitor(u)})}catch(i){}}),1e3))}stopStreamMonitor(){this.monitorTimerId&&(clearInterval(this.monitorTimerId),this.monitorTimerId=void 0),Object.keys(this.monitorDataCache).forEach(e=>{this.reportPublishMonitor(e)})}clearStream(){this.streamManager.stop(),this.audioPubState.setState(be.AliRtcStatePublishIdle),this.videoPubState.setState(be.AliRtcStatePublishIdle),this.videoSmallPubState.setState(be.AliRtcStatePublishIdle),this.screenPubState.setState(be.AliRtcStatePublishIdle)}getCurrentCameraDeviceId(){var e;return(e=this.streamManager.cameraStreamInfo.originVideoTrack)==null?void 0:e.getSettings().deviceId}getCurrentMicDeviceId(){var e;return(e=this.streamManager.cameraStreamInfo.originAudioTrack)==null?void 0:e.getSettings().deviceId}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval!==e&&(this.audioVolumeIndicationInterval>0&&e<=0&&this.audioLevelMonitor.stop(),e>0&&this.streamManager.cameraStreamInfo.originAudioTrack&&this.audioLevelMonitor.start(this.streamManager.cameraStreamInfo.originAudioTrack,e),this.audioVolumeIndicationInterval=e)}sendSEI(e,t,r){return z(this,null,function*(){if(!this.url)return;let i=0;return!t||t<1?i=1:i=t-1,this.rtsManager.sendSEI(this.url,e,i,r)})}getStats(){return z(this,null,function*(){const e=[];if(this.hasAudioTrackInMS){const n=yield this.rtsManager.getPublishAudioStats(this.url);n&&e.push({stats:n,track:ii.AliRtcAudioTrackMic})}const t=[];if(this.hasCameraTrackInMS){const n=yield this.rtsManager.getPublishVideoStats(this.url,Z.VideoLarge);n&&t.push({track:Ae.AliRtcVideoTrackCamera,streamType:Je.AliRtcVideoStreamTypeHigh,stats:n})}if(this.hasCameraDualTrackInMS){const n=yield this.rtsManager.getPublishVideoStats(this.url,Z.VideoSmall);n&&t.push({track:Ae.AliRtcVideoTrackCamera,streamType:Je.AliRtcVideoStreamTypeLow,stats:n})}if(this.hasScreenTrackInMS){const n=yield this.rtsManager.getPublishVideoStats(this.url,Z.Screen);n&&t.push({track:Ae.AliRtcVideoTrackScreen,stats:n})}let r;const i=yield this.rtsManager.getPCStats();return i==null||i.forEach(n=>{n.type==="candidate-pair"&&n.state==="succeeded"&&(r=n)}),{audio:e,video:t,candidate:r}})}},A(Lt,"logName","LocalUser"),Lt);ze([j()],Ve.prototype,"clearPublishState",1),ze([j()],Ve.prototype,"clear",1),ze([j()],Ve.prototype,"setViewConfig",1),ze([j()],Ve.prototype,"startCameraCapture",1),ze([j()],Ve.prototype,"stopCameraCapture",1),ze([j()],Ve.prototype,"stopAudioCapture",1),ze([j()],Ve.prototype,"stopPreview",1),ze([j()],Ve.prototype,"resumePublish",1),ze([j()],Ve.prototype,"createLocalStream",1),ze([j()],Ve.prototype,"stopLocalStream",1),ze([j(ae)],Ve.prototype,"startPublish",1),ze([j(([s])=>[s])],Ve.prototype,"syncPublishToRoomServer",1),ze([j()],Ve.prototype,"refreshPushStreamUrl",1),ze([j(([s,c,e])=>[JSON.stringify(e)])],Ve.prototype,"publishAdd",1),ze([j(([s,c])=>[JSON.stringify(c)])],Ve.prototype,"publishReplace",1),ze([j(ae)],Ve.prototype,"publishDeleteTracks",1),ze([j()],Ve.prototype,"publishStop",1),ze([j()],Ve.prototype,"unPublish",1),ze([j(([s,c,e])=>[s.length,c,e])],Ve.prototype,"sendSEI",1);let la=Ve;var qt=(s=>(s.OPUS="opus",s.H264="H264",s.UNKONWN="",s))(qt||{}),Gt=(s=>(s.VideoTrackEnded="videoTrackEnded",s.AudioTrackEnded="audioTrackEnded",s.ScreenTrackEnded="screenTrackEnded",s))(Gt||{});const Yc=s=>{const c=new MediaStream;return c.addTrack(s),c},fa=s=>z(this,null,function*(){return yield me.AliRTS.createStream({custom:!0,mediaStream:s})}),xi=s=>z(this,null,function*(){const c=Yc(s);return yield fa(c)}),Qc=s=>{const{audio:c,video:e,screen:t}=s;if(e&&t)throw new ne(ce.ERR_INNER,"create stream error, cannot create video && screen together");return!(!e&&!c&&!t)},e0=s=>s===Z.Audio||s===rr.Audio,t0=s=>s===Z.VideoLarge||s===rr.VideoLarge,i0=s=>s===Z.VideoSmall,r0=s=>s===Z.Screen;var s0=Object.defineProperty,n0=Object.getOwnPropertyDescriptor,a0=(s,c,e,t)=>{for(var r=t>1?void 0:t?n0(c,e):c,i=s.length-1,n;i>=0;i--)(n=s[i])&&(r=(t?n(c,e,r):n(r))||r);return t&&r&&s0(c,e,r),r};class Fi extends ve{constructor(){super();A(this,"audioInfo",{subscribed:!1,ssrc:"",msid:"",pt:0,red:0,codec:qt.UNKONWN});A(this,"videoLargeInfo",{subscribed:!1,ssrc:"",msid:"",pt:0,red:0,codec:qt.UNKONWN});A(this,"videoSmallInfo",{subscribed:!1,ssrc:"",msid:"",pt:0,red:0,codec:qt.UNKONWN});A(this,"screenInfo",{subscribed:!1,ssrc:"",msid:"",pt:0,red:0,codec:qt.UNKONWN});A(this,"audioVolume",1);A(this,"audioMuted",!1);A(this,"userStatus")}getAudioInfo(){return this.audioInfo}getVideoSmallInfo(){return this.videoSmallInfo}getVideoLargeInfo(){return this.videoLargeInfo}getScreenInfo(){return this.screenInfo}get subscribingInfos(){return[this.audioInfo,this.videoLargeInfo,this.videoSmallInfo,this.screenInfo].filter(e=>e.msid&&e.subscribed)}get hasAudio(){return this.audioInfo.ssrc!==""}get hasVideo(){return this.videoLargeInfo.ssrc!==""||this.videoSmallInfo.ssrc!==""}get hasVideoLarge(){return this.videoLargeInfo.ssrc!==""}get hasVideoSmall(){return this.videoSmallInfo.ssrc!==""}get hasScreen(){return this.screenInfo.ssrc!==""}get isAudioSubscribing(){return!!this.audioInfo.subscribed}get isVideoSubscribing(){return!!this.videoLargeInfo.subscribed||!!this.videoSmallInfo.subscribed}get isVideoLargeSubscribing(){return!!this.videoLargeInfo.subscribed}get isVideoSmallSubscribing(){return!!this.videoSmallInfo.subscribed}get isScreenSubscribing(){return!!this.screenInfo.subscribed}get audioCodec(){return this.audioInfo.codec}get videoCodec(){return this.hasVideoLarge?this.videoLargeInfo.codec:this.hasVideoSmall?this.videoSmallInfo.codec:this.hasScreen?this.screenInfo.codec:qt.UNKONWN}get audioTrackInfo(){return this.hasAudio?ii.AliRtcAudioTrackMic:ii.AliRtcAudioTrackNo}get videoTrackInfo(){return this.hasVideo&&this.hasScreen?Ae.AliRtcVideoTrackBoth:this.hasVideo?Ae.AliRtcVideoTrackCamera:this.hasScreen?Ae.AliRtcVideoTrackScreen:Ae.AliRtcVideoTrackNo}updateTracks(e){let t="",r="",i="",n="";return e?(e.forEach(a=>{var h;let o=qt.UNKONWN;const u=((h=a==null?void 0:a.attr)==null?void 0:h.reason)==="reconnect";if(a.userdata){const{codec:g}=JSON.parse(a.userdata);g&&(o=g)}e0(a.msid)?(t=a.ssrc,this.audioInfo.msid=a.msid,this.audioInfo.codec=o,u&&(this.audioInfo.subscribed=!1)):i0(a.msid)?(i=a.ssrc,this.videoSmallInfo.msid=a.msid,this.videoSmallInfo.codec=o,u&&(this.videoSmallInfo.subscribed=!1)):t0(a.msid)?(r=a.ssrc,this.videoLargeInfo.msid=a.msid,this.videoLargeInfo.codec=o,u&&(this.videoLargeInfo.subscribed=!1)):r0(a.msid)&&(n=a.ssrc,this.screenInfo.msid=a.msid,this.screenInfo.codec=o,u&&(this.screenInfo.subscribed=!1))}),this.updateRemoteTrackSsrc(t,r,i,n)):this.updateRemoteTrackSsrc(t,r,i,n),{}}updateRemoteTrackSsrc(e,t,r,i){this.audioInfo.ssrc=e,this.videoSmallInfo.ssrc=r,this.videoLargeInfo.ssrc=t,this.screenInfo.ssrc=i}updateRemoteTrackSubState(e){return e.video!==void 0&&((e.vMsid===this.videoSmallInfo.msid||!e.vMsid)&&(this.videoSmallInfo.subscribed=e.video),(e.vMsid===this.videoLargeInfo.msid||!e.vMsid)&&(this.videoLargeInfo.subscribed=e.video)),e.screen!==void 0&&(this.screenInfo.subscribed=e.screen),e.audio!==void 0&&(this.audioInfo.subscribed=e.audio),{audioInfo:this.audioInfo,videoLargeInfo:this.videoLargeInfo,videoSmallInfo:this.videoSmallInfo,screenInfo:this.screenInfo}}updateRemoteUserDeviceStatus(e){let t=aa.parseStatus(e);const{audioDisable:r,videoDisable:i,screenDisable:n}=t;return this.userStatus?(this.userStatus.audioDisable!=r&&(this.userStatus.audioDisable=r,this.emit(et.Remote,r?Ie.MuteAudio:Ie.UnmuteAudio)),this.userStatus.videoDisable!=i&&(this.userStatus.videoDisable=i,this.emit(et.Remote,i?Ie.MuteVideo:Ie.UnmuteVideo)),this.userStatus.screenDisable!=n&&(this.userStatus.screenDisable=n,this.emit(et.Remote,n?Ie.MuteScreen:Ie.UnmuteScreen))):(this.userStatus=t,this.emit(et.Remote,r?Ie.MuteAudio:Ie.UnmuteAudio),this.emit(et.Remote,i?Ie.MuteVideo:Ie.UnmuteVideo),this.emit(et.Remote,n?Ie.MuteScreen:Ie.UnmuteScreen)),!1}}A(Fi,"logName","RemoteStreamInfo"),a0([j()],Fi.prototype,"updateRemoteTrackSubState",1);class pa{constructor(c){A(this,"remoteUser");this.remoteUser=c}get userId(){return this.remoteUser.userId}get displayName(){return this.remoteUser.displayname}get isMuteAudioPlaying(){return this.remoteUser.getAudioMuted()}get hasAudio(){return this.remoteUser.hasAudioTrack}get hasCamera(){return this.remoteUser.hasVideoTrack}get hasCameraLarge(){return this.remoteUser.hasVideoLargeTrack}get hasCameraSmall(){return this.remoteUser.hasVideoSmallTrack}get hasScreenShare(){return this.remoteUser.hasScreenTrack}get isAudioSubscribing(){return this.remoteUser.isAudioSubscribing}get isVideoSubscribing(){return this.remoteUser.isVideoSubscribing}get isVideoLargeSubscribing(){return this.remoteUser.isVideoLargeSubscribing}get isVideoSmallSubscribing(){return this.remoteUser.isVideoSmallSubscribing}get isScreenSubscribing(){return this.remoteUser.isScreenSubscribing}}var o0=Object.defineProperty,c0=Object.getOwnPropertyDescriptor,Xe=(s,c,e,t)=>{for(var r=t>1?void 0:t?c0(c,e):c,i=s.length-1,n;i>=0;i--)(n=s[i])&&(r=(t?n(c,e,r):n(r))||r);return t&&r&&o0(c,e,r),r};class bi extends ve{constructor(){super();A(this,"state");A(this,"time");A(this,"_enabled");this.state=Le.AliRtcStateSubscribeIdle,this.time=Date.now(),this._enabled=!0}setState(e){if(this.state===e)return;const t=this.state,r=this.time;this.state=e,this.time=Date.now(),this.emit("change",t,e,Math.floor((this.time-r)/1e3))}get currentState(){return this.state}getEnabled(){return this._enabled}setEnabled(e){this._enabled=e}}const u0=30,Ui=class Ui extends na{constructor(e){var l;const{userId:t,displayName:r,rtsManager:i,usersViewMap:n,slsReporter:a,signalingManager:o,localUser:u,audioVolumeIndicationInterval:h,playoutVolume:g,parameter:f}=e;super(t,r,i,h);A(this,"remoteCallid","");A(this,"remoteUserInfo");A(this,"localUser");A(this,"lastPubId","");A(this,"stream");A(this,"screenStream");A(this,"viewMap");A(this,"audioTrack");A(this,"audioElement");A(this,"subscribed",!1);A(this,"mediaStream");A(this,"secondaryMediaStream");A(this,"prevSubConfig");A(this,"signalingManager");A(this,"slsReporter");A(this,"wantSubAudio",!1);A(this,"wantSubVideo",!1);A(this,"wantSubScreen",!1);A(this,"defaultVideoStreamType",Je.AliRtcVideoStreamTypeHigh);A(this,"audioMuted",!1);A(this,"playoutVolume",1);A(this,"playoutGainNode");A(this,"audioSubState");A(this,"videoSubState");A(this,"videoLargeSubState",new bi);A(this,"videoSmallSubState",new bi);A(this,"screenSubState");A(this,"streamInfo");A(this,"streamUrl","");A(this,"parameter",{});A(this,"monitorTimerId");A(this,"monitorDataCache",{});A(this,"trackTraceIdMap",{});A(this,"handleAudioContextSuspended",e=>{e.target.state==="suspended"&&this.emit("remoteAudioPlayError",this.uid,"AudioContext suspended")});A(this,"handleAudioPaused",()=>{this.emit("remoteAudioPlayError","paused")});this.streamInfo=new Fi,this.remoteUserInfo=new pa(this),this.parameter=f,this.streamInfo.on(et.Remote,p=>{this.emit(et.Remote,p,this.userId)}),this.signalingManager=o,this.viewMap=(l=n[t])!=null?l:{cameraViews:[],screenViews:[]},n[t]=this.viewMap,this.slsReporter=a,this.localUser=u,this.audioSubState=new bi,this.audioSubState.on("change",(p,d,m)=>{this.emit("audioSubscribeStateChanged",this.uid,p,d,m)}),this.videoSubState=new bi,this.videoSubState.on("change",(p,d,m)=>{this.emit("videoSubscribeStateChanged",this.uid,p,d,m)}),this.screenSubState=new bi,this.screenSubState.on("change",(p,d,m)=>{this.emit("screenSubscribeStateChanged",this.uid,p,d,m)}),this.playoutVolume=g}isWantSubAudio(){return this.wantSubAudio}setWantSubAudio(e){this.wantSubAudio=e}isWantSubVideo(){return this.wantSubVideo}setWantSubVideo(e){this.wantSubVideo=e}isWantSubScreen(){return this.wantSubScreen}setWantSubScreen(e){this.wantSubScreen=e}setRemoteDefaultVideoStreamType(e){e!==this.defaultVideoStreamType&&(this.defaultVideoStreamType=e,this.updateSubscribe(Be.User))}setAudioMuted(e){this.audioMuted=e,this.toggleAudio(!e)}setPlayoutVolume(e){if(this.playoutVolume=e,this.audioElement)if(this.parameter.enableAudioContextPlayoutVolume)if(this.playoutGainNode)this.playoutGainNode.gain.value=e;else{const t=this.audioElement.srcObject;if(t){const r=ri.getInstance();r.addEventListener("statechange",this.handleAudioContextSuspended);const i=r.createMediaStreamSource(t);this.audioElement.muted=!0,this.playoutGainNode=r.createGain(),i.connect(this.playoutGainNode),this.playoutGainNode.gain.value=e,this.playoutGainNode.connect(r.destination)}}else this.audioElement.volume=e}getAudioMuted(){return this.audioMuted}get hasAudioTrack(){var e;return!!((e=this.streamInfo)!=null&&e.hasAudio)}get hasVideoTrack(){var e;return!!((e=this.streamInfo)!=null&&e.hasVideo)}get hasVideoLargeTrack(){var e;return!!((e=this.streamInfo)!=null&&e.hasVideoLarge)}get hasVideoSmallTrack(){var e;return!!((e=this.streamInfo)!=null&&e.hasVideoSmall)}get hasScreenTrack(){var e;return!!((e=this.streamInfo)!=null&&e.hasScreen)}get isAudioSubscribing(){var e;return!!((e=this.streamInfo)!=null&&e.isAudioSubscribing)}get isVideoSubscribing(){var e;return!!((e=this.streamInfo)!=null&&e.isVideoSubscribing)}get isVideoLargeSubscribing(){var e;return!!((e=this.streamInfo)!=null&&e.isVideoLargeSubscribing)}get isVideoSmallSubscribing(){var e;return!!((e=this.streamInfo)!=null&&e.isVideoSmallSubscribing)}get isScreenSubscribing(){var e;return!!((e=this.streamInfo)!=null&&e.isScreenSubscribing)}get audioEnabled(){var e,t;return!!((t=(e=this.stream)==null?void 0:e.audioTrack)!=null&&t.enabled)}get videoEnabled(){var e,t;return!!((t=(e=this.stream)==null?void 0:e.videoTrack)!=null&&t.enabled)}get screenEnabled(){var e,t;return!!((t=(e=this.screenStream)==null?void 0:e.videoTrack)!=null&&t.enabled)}get getAudioTrack(){return this.audioTrack}get getCameraStream(){return this.stream}get getScreenStream(){return this.screenStream}setViewConfig(e,t){if(t!==Ae.AliRtcVideoTrackScreen&&t!==Ae.AliRtcVideoTrackCamera)throw new ne(ce.ERR_INVALID_ARGUMENTS,"track is not AliRtcVideoTrackScreen or AliRtcVideoTrackCamera");e?fs(e).forEach(i=>{i.setAttribute("playsinline",""),me.AliRTS.BrowserUtil.isMicroMessenger&&(i.setAttribute("x5-video-player-type","h5-page"),i.setAttribute("x5-playsinline",""),me.AliRTS.SystenUtil.isAndroid||me.AliRTS.SystenUtil.isIos&&i.setAttribute("x-webkit-airplay","allow")),t===Ae.AliRtcVideoTrackScreen?this.viewMap.screenViews.push(i):this.viewMap.cameraViews.push(i),this.play(i,t===Ae.AliRtcVideoTrackScreen)}):(this.stopPlayAll(t===Ae.AliRtcVideoTrackScreen),t===Ae.AliRtcVideoTrackScreen?this.viewMap.screenViews=[]:this.viewMap.cameraViews=[])}clear(e=!0){return z(this,null,function*(){var t;e&&this.doStopSubscribe(this.streamUrl),As(Ui.prototype,this,"clear").call(this),this.clearStream(),this.clearScreenStream(),this.playoutGainNode&&(this.playoutGainNode.disconnect(),this.playoutGainNode=void 0,ri.getInstance().removeEventListener("statechange",this.handleAudioContextSuspended)),(t=this.streamInfo)==null||t.removeAllListeners(et.Remote)})}updateRemoteUserDeviceStatus(e){var t;(t=this.streamInfo)==null||t.updateRemoteUserDeviceStatus(e)}updateRemoteTracks(e,t,r,i){return z(this,null,function*(){var a;return this.remoteCallid=e,this.streamUrl=t!=null?t:"",this.callId=e!=null?e:"",this.streamInfo||(this.streamInfo=new Fi),(a=this.streamInfo)==null?void 0:a.updateTracks(i)})}subscribe(i,n){return z(this,arguments,function*(e,t,r=Date.now()){var l;let a=e;if(!a){const{hasAudio:p,hasVideo:d,hasScreen:m}=(l=this.streamInfo)!=null?l:{};a={audio:this.wantSubAudio&&p,video:this.wantSubVideo&&d,screen:this.wantSubScreen&&m}}const{screen:o,audio:u,video:h,vMsid:g}=a,f=[];(h||u)&&f.push({audio:u,video:h,vMsid:g}),o&&f.push({screen:o}),f.length!==0&&(yield Promise.all(f.map(p=>this.subscribeProxy(p,t||Be.User,r))))})}subscribeProxy(e,t,r){return z(this,null,function*(){var a,o,u,h;let i=new Date().getTime(),n="";try{e.audio&&this.audioSubState.setState(Le.AliRtcStateSubscribing),e.video&&(this.videoSubState.currentState===Le.AliRtcStateSubscribeIdle||this.videoSubState.currentState===Le.AliRtcStateNoSubscribe)&&this.videoSubState.setState(Le.AliRtcStateSubscribing),e.screen&&this.screenSubState.setState(Le.AliRtcStateSubscribing);const g=yield this.rtsManager.subscribe({remoteUser:this,options:e},t,((a=this.localUser)==null?void 0:a.callId)||"",this.callId,r);this.streamInfo.updateRemoteTrackSubState(e),n=g.traceId||"";const{stream:f}=g;if(e.audio){this.trackTraceIdMap[Z.Audio]=n;const p=f.audioTrack;p&&(this.audioTrack=p,(o=f.mediaStream)==null||o.removeTrack(p),this.playAudio(),this.audioVolumeIndicationInterval&&this.audioLevelMonitor.start(p,this.audioVolumeIndicationInterval)),this.audioSubState.setState(Le.AliRtcStateSubscribed),this.audioSubState.getEnabled()||this.toggleAudio(!1)}e.video&&(e.vMsid===Z.VideoSmall?(this.trackTraceIdMap[Z.VideoSmall]=n,this.videoSmallSubState.setState(Le.AliRtcStateSubscribed)):(this.trackTraceIdMap[Z.VideoLarge]=n,this.videoLargeSubState.setState(Le.AliRtcStateSubscribed)),this.videoSubState.setState(Le.AliRtcStateSubscribed),this.videoSubState.getEnabled()||this.toggleVideo(!1),this.updateStream(f,this.isVideoLargeSubscribing&&this.isVideoSmallSubscribing)),e.screen&&(this.trackTraceIdMap[Z.Screen]=n,this.screenSubState.setState(Le.AliRtcStateSubscribed),this.videoSubState.getEnabled()||this.toggleScreen(!1),this.updateScreenStream(f));const l=new Date().getTime()-i;this.slsReporter.reportSubscribe(((u=this.localUser)==null?void 0:u.callId)||"",this.callId,!!e.video&&e.vMsid===Z.VideoLarge,!!e.video&&e.vMsid===Z.VideoSmall,!!e.screen,!!e.audio,0,"",l,{pctid:this.rtsManager.pcTraceId,subtid:n,ajsub:t===Be.Join?1:0,url:this.streamUrl,est:i}),this.startStreamMonitor()}catch(g){const f=new Date().getTime()-i;g&&(g.message=`user(${this.uid}) subscribe error, ${(g==null?void 0:g.message)||""}`);let l=ce.ERR_INNER;e.audio&&(l=ce.ERR_SDK_SUBSCRIBE_AUDIO_STRAM_FAILED),e.video&&(e.vMsid===Z.VideoSmall?l=ce.ERR_SDK_SUBSCRIBE_DUAL_STRAM_FAILED:l=ce.ERR_SDK_SUBSCRIBE_VIDEO_STRAM_FAILED),e.screen&&(l=ce.ERR_SDK_SUBSCRIBE_SCREEN_SHARE_FAILED),this.slsReporter.reportSubscribe(((h=this.localUser)==null?void 0:h.callId)||"",this.callId,!!e.video&&e.vMsid===Z.VideoLarge,!!e.video&&e.vMsid===Z.VideoSmall,!!e.screen,!!e.audio,l,"",f,{pctid:this.rtsManager.pcTraceId,subtid:"",ajsub:t===Be.Join?1:0,url:this.streamUrl,est:i});const p=ne.fromError(g,l);throw this.emit("remoteSubscribeError",p),p}})}subscribeDeleteTracks(e){return z(this,null,function*(){const{audio:t,video:r,screen:i,vMsid:n}=e,a=[];(t||r)&&a.push({audio:t,video:r,vMsid:n}),i&&a.push({screen:i}),a.length!==0&&(yield Promise.all(a.map(o=>this.subscribeDeleteProxy(o))))})}subscribeDeleteProxy(e){return z(this,null,function*(){try{const t=yield this.rtsManager.subscibeDelete({remoteUser:this,options:e}),{stream:r}=t!=null?t:{},i={};e.audio===!0&&(i.audio=!1,this.audioSubState.setState(Le.AliRtcStateNoSubscribe)),e.video===!0&&(i.video=!1,e.vMsid===Z.VideoSmall?(this.videoSmallSubState.setState(Le.AliRtcStateNoSubscribe),(this.videoLargeSubState.currentState===Le.AliRtcStateNoSubscribe||this.videoLargeSubState.currentState===Le.AliRtcStateSubscribeIdle)&&this.videoSubState.setState(Le.AliRtcStateNoSubscribe)):(this.videoLargeSubState.setState(Le.AliRtcStateNoSubscribe),(this.videoSmallSubState.currentState===Le.AliRtcStateNoSubscribe||this.videoSmallSubState.currentState===Le.AliRtcStateSubscribeIdle)&&this.videoSubState.setState(Le.AliRtcStateNoSubscribe))),e.screen===!0&&(i.screen=!1,this.screenSubState.setState(Le.AliRtcStateNoSubscribe));const{callId:n,remoteCallid:a}=this,o={callid:n,remoteCallid:a,remoteStream:r};return e.audio&&(this.audioLevelMonitor.stop(),this.stopPlayAudio(),this.audioTrack=void 0),this.streamInfo.updateRemoteTrackSubState({audio:e.audio===!0?!1:void 0,video:e.video===!0?!1:void 0,screen:e.screen===!0?!1:void 0,vMsid:e.vMsid}),o}catch(t){throw ne.fromError(t,ce.ERR_INNER,"subscribe delete failed")}})}restore(){this.callId="",this.clearStream(),this.clearScreenStream(),this.audioTrack=void 0,this.streamInfo.updateRemoteTrackSubState({audio:!1,video:!1,screen:!1}),this.audioElement&&this.audioElement.removeEventListener("pause",this.handleAudioPaused)}resumeAudio(){return z(this,null,function*(){var t;const e=ri.getInstance();return e.state!=="running"&&e.resume(),(t=this.audioElement)==null?void 0:t.play()})}resumeVideo(e){return z(this,null,function*(){if(!e||e===Ae.AliRtcVideoTrackCamera||e===Ae.AliRtcVideoTrackBoth)return this.playAll();if(!e||e===Ae.AliRtcVideoTrackScreen||e===Ae.AliRtcVideoTrackBoth)return this.playAll(!0)})}resumePlay(){this.playAudio(),this.playAll(),this.playAll(!0)}stopSubscribe(e){return z(this,null,function*(){var r,i;let t=new Date().getTime();try{let n;e?n=yield this.subscribeDeleteTracks(e):n=yield this.doStopSubscribe(this.streamUrl),this.slsReporter.reportUnsubscribe(((r=this.localUser)==null?void 0:r.callId)||(n==null?void 0:n.callid)||"",this.callId,new Date().getTime()-t,0,"")}catch(n){throw this.slsReporter.reportUnsubscribe(((i=this.localUser)==null?void 0:i.callId)||"",this.callId,new Date().getTime()-t,0,""),n}})}doStopSubscribe(e){return z(this,null,function*(){var i,n,a,o;const{callId:t,remoteCallid:r}=this;if((this.isAudioSubscribing||this.isVideoSubscribing||this.isScreenSubscribing)&&e)try{this.stopStreamMonitor(),yield this.rtsManager.subscibeStop(e),this.restore();const u={callid:t,remoteCallid:r,remoteStream:this.stream};return this.callId="",u}catch(u){if(((o=(a=(n=(i=u==null?void 0:u.extraInfo)==null?void 0:i.parsedData)==null?void 0:n.streams)==null?void 0:a[0])==null?void 0:o.res_code)!==404)throw ne.fromError(u,ce.ERR_INNER,"subscribe stop failed")}})}updateStream(e,t=!1){return z(this,null,function*(){this.stream&&this.stream.videoTrack&&e.mediaStream&&t&&(yield new Promise(r=>{let i,n;if(e.mediaStream){n=document.createElement("video");const a=()=>{oe.event(`uid: ${this.userId} new mediaStream canplay`),n&&n.removeEventListener("canplaythrough",a,!1),n=void 0,clearTimeout(i),r(!0)};n.addEventListener("canplaythrough",a,!1),(n._playPromise||Promise.resolve()).then(()=>{n&&e.mediaStream&&(n.srcObject=e.mediaStream)})}else r(!0);i=window.setTimeout(()=>{oe.event(`uid: ${this.userId} new mediaStream timeout`),n=void 0,r(!0)},3e3)}),this.updateSubscribe(Be.User)),this.stream=e,this.playAll(),!this.subscribed&&e&&(this.subscribed=!0),e.hasAudio&&this.isAudioSubscribing&&e.enableAudio(),e.hasVideo&&this.isVideoSubscribing&&e.enableVideo()})}updateScreenStream(e){this.screenStream=e,this.playAll(!0),!this.subscribed&&e&&(this.subscribed=!0),e.hasVideo&&this.isScreenSubscribing&&e.enableVideo()}clearStream(){var e;(e=this.stream)==null||e.stop(),this.stream=void 0}clearScreenStream(){var e;(e=this.screenStream)==null||e.stop(),this.screenStream=void 0}updateSubscribe(e){var n,a,o,u,h,g,f,l;const t=Date.now(),r={},i={};return this.wantSubAudio&&!this.isAudioSubscribing&&((n=this.streamInfo)!=null&&n.hasAudio)?r.audio=!0:(!this.wantSubAudio||!((a=this.streamInfo)!=null&&a.hasAudio))&&this.isAudioSubscribing&&(i.audio=!0),this.wantSubVideo&&((o=this.streamInfo)!=null&&o.hasVideo)?(this.defaultVideoStreamType===Je.AliRtcVideoStreamTypeLow&&!this.isVideoSmallSubscribing&&((u=this.streamInfo)!=null&&u.hasVideoSmall)?(r.video=!0,r.vMsid=Z.VideoSmall):!this.isVideoLargeSubscribing&&((h=this.streamInfo)!=null&&h.hasVideoLarge)&&!(this.defaultVideoStreamType===Je.AliRtcVideoStreamTypeLow&&this.isVideoSmallSubscribing)&&(r.video=!0,r.vMsid=Z.VideoLarge),this.defaultVideoStreamType===Je.AliRtcVideoStreamTypeLow&&this.isVideoLargeSubscribing&&this.isVideoSmallSubscribing&&this.streamInfo.hasVideoSmall?(i.video=!0,i.vMsid=Z.VideoLarge):this.defaultVideoStreamType===Je.AliRtcVideoStreamTypeHigh&&this.isVideoLargeSubscribing&&this.isVideoSmallSubscribing&&(i.video=!0,i.vMsid=Z.VideoSmall)):(!this.wantSubVideo||!((g=this.streamInfo)!=null&&g.hasVideo))&&this.isVideoSubscribing&&(i.video=!0,i.vMsid=this.streamInfo.isVideoSmallSubscribing?Z.VideoSmall:Z.VideoLarge),this.wantSubScreen&&!this.isScreenSubscribing&&((f=this.streamInfo)!=null&&f.hasScreen)?r.screen=!0:(!this.wantSubScreen||!((l=this.streamInfo)!=null&&l.hasScreen))&&this.isScreenSubscribing&&(i.screen=!0),(r.audio||r.video||r.screen)&&(this.createCallId(),this.subscribe(r,e,t)),i.audio&&i.video&&i.screen?this.stopSubscribe():(i.audio||i.video||i.screen)&&this.subscribeDeleteTracks(i),{addOption:r,deleteOption:i}}handleAutoPlayFailed(){this.emit("remoteAudioAutoPlayFail",this.uid);const e=()=>{this.resumeAudio().then(()=>{document.removeEventListener("click",e,!1),document.removeEventListener("touchstart",e,!1)})};document.addEventListener("click",e,!1),document.addEventListener("touchstart",e,!1)}handleVideoPlayFailded(e,t){this.emit("remoteVideoAutoPlayFail",this.uid,t);const r=()=>{var n;const i=(n=t===Ae.AliRtcVideoTrackScreen?this.screenStream:this.stream)==null?void 0:n.mediaStream;e.srcObject===i&&this.play(e,t===Ae.AliRtcVideoTrackScreen),document.removeEventListener("click",r,!1),document.removeEventListener("touchstart",r,!1)};document.addEventListener("click",r,!1),document.addEventListener("touchstart",r,!1)}playAudio(){return z(this,null,function*(){var t,r;if(!this.audioTrack)return;if(this.toggleAudio(!this.audioMuted),this.audioElement||(this.audioElement=document.createElement("audio"),this.audioElement.addEventListener("pause",this.handleAudioPaused),this.setPlayoutVolume(this.playoutVolume)),((r=(t=this.audioElement.srcObject)==null?void 0:t.getAudioTracks())==null?void 0:r[0])!==this.audioTrack){let i=this.audioElement.srcObject;i?i.getAudioTracks().forEach(n=>{i.removeTrack(n)}):(i=new MediaStream,this.audioElement.srcObject=i),i.addTrack(this.audioTrack)}this.audioElement.play().catch(()=>{this.handleAutoPlayFailed()});const e=this.audioElement;this.audioElement.addEventListener("playing",function i(){e.removeEventListener("playing",i),me.AliRTS.SystenUtil.isIos&&parseInt(me.AliRTS.SystenUtil.systemVersion)<=14&&(e.muted||(e.pause(),e.play()))})})}stopPlayAudio(){this.audioElement&&(this.audioElement.pause(),this.audioElement.srcObject=null)}playAll(e=!1){e?(this.viewMap.screenViews||[]).forEach(t=>{this.play(t,e)}):(this.viewMap.cameraViews||[]).forEach(t=>{this.play(t,e)})}play(e,t=!1){const r=t?this.screenStream:this.stream;!e||!r||!r.mediaStream||ha(e,r.mediaStream).catch(i=>{i.code===20||i.name==="AbortError"||this.handleVideoPlayFailded(e,t?Ae.AliRtcVideoTrackScreen:Ae.AliRtcVideoTrackCamera)})}stopPlayAll(e=!1){e?this.viewMap.screenViews.forEach(t=>{Bt(t)}):this.viewMap.cameraViews.forEach(t=>{Bt(t)})}toggleAudio(e=!0){this.audioSubState.setEnabled(e),this.audioTrack&&(this.audioTrack.enabled=e)}toggleVideo(e=!0){this.videoSubState.setEnabled(e),this.stream&&(e?this.stream.enableVideo():this.stream.disableVideo())}toggleScreen(e=!0){this.screenSubState.setEnabled(e),this.screenStream&&(e?this.screenStream.enableVideo():this.screenStream.disableVideo())}getStats(){return z(this,null,function*(){var r,i;const e=[];if(this.isAudioSubscribing){const n=yield this.rtsManager.getSubscribeAudioStats(this.streamUrl);n&&e.push({uid:this.uid,track:ii.AliRtcAudioTrackMic,stats:n})}const t=[];if((r=this.streamInfo)!=null&&r.isVideoLargeSubscribing){const n=yield this.rtsManager.getSubscribeVideoStats(this.streamUrl,Z.VideoLarge);n&&t.push({uid:this.uid,track:Ae.AliRtcVideoTrackCamera,streamType:Je.AliRtcVideoStreamTypeHigh,stats:n})}if((i=this.streamInfo)!=null&&i.isVideoSmallSubscribing){const n=yield this.rtsManager.getSubscribeVideoStats(this.streamUrl,Z.VideoSmall);n&&t.push({uid:this.uid,track:Ae.AliRtcVideoTrackCamera,streamType:Je.AliRtcVideoStreamTypeLow,stats:n})}if(this.isScreenSubscribing){const n=yield this.rtsManager.getSubscribeVideoStats(this.streamUrl,Z.Screen);n&&t.push({uid:this.uid,track:Ae.AliRtcVideoTrackScreen,stats:n})}return{audio:e,video:t}})}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval!==e&&(this.audioVolumeIndicationInterval>0&&e<=0&&this.audioLevelMonitor.stop(),e>0&&this.audioTrack&&this.audioLevelMonitor.start(this.audioTrack,e),this.audioVolumeIndicationInterval=e)}reportSubscribeMonitor(e){var t;e&&(this.slsReporter.reportSubscribeMonitor(((t=this.localUser)==null?void 0:t.callId)||"",this.callId,this.trackTraceIdMap[e]||"",e,this.monitorDataCache[e]),this.monitorDataCache[e]=[])}startStreamMonitor(){this.monitorTimerId||(this.monitorTimerId=window.setInterval(()=>z(this,null,function*(){try{if(this.streamInfo.subscribingInfos.length===0){this.stopStreamMonitor();return}let e=Object.keys(this.monitorDataCache).filter(t=>{var r;return((r=this.monitorDataCache[t])==null?void 0:r.length)>0});this.streamInfo.subscribingInfos.forEach(t=>{const r=t.msid;if(!r)return;e.includes(r)&&(e=e.filter(a=>a!==r));let i;const n=r===Z.Audio;n?i=this.rtsManager.getSubscribeAudioStats(this.streamUrl):i=this.rtsManager.getSubscribeVideoStats(this.streamUrl,r),i.then(a=>{var g;if(!a.timestamp)return;this.monitorDataCache[r]||(this.monitorDataCache[r]=[]);const o=this.monitorDataCache[r];let u;if((o==null?void 0:o.length)>0){const h=o[o.length-1]||{},{_last:l}=h;u=$i(h,["_last"])}(o==null?void 0:o.length)>=u0&&this.reportSubscribeMonitor(r),a._last=u,a._codec=t.codec,n&&(a._source=(g=this.localUser)==null?void 0:g.getMediaStats(a.playoutId)),this.monitorDataCache[r].push(a)})}),e.forEach(t=>{this.reportSubscribeMonitor(t)})}catch(e){}}),1e3))}stopStreamMonitor(){this.monitorTimerId&&(clearInterval(this.monitorTimerId),this.monitorTimerId=void 0),Object.keys(this.monitorDataCache).forEach(e=>{this.reportSubscribeMonitor(e)})}};A(Ui,"logName","RemoteUser");let Ue=Ui;Xe([j()],Ue.prototype,"clear",1),Xe([j()],Ue.prototype,"updateRemoteUserDeviceStatus",1),Xe([j()],Ue.prototype,"updateRemoteTracks",1),Xe([j(ae)],Ue.prototype,"subscribe",1),Xe([j()],Ue.prototype,"subscribeProxy",1),Xe([j(ae)],Ue.prototype,"subscribeDeleteProxy",1),Xe([j()],Ue.prototype,"restore",1),Xe([j(ae)],Ue.prototype,"stopSubscribe",1),Xe([j(ae)],Ue.prototype,"doStopSubscribe",1),Xe([j()],Ue.prototype,"clearStream",1),Xe([j()],Ue.prototype,"clearScreenStream",1),Xe([j()],Ue.prototype,"updateSubscribe",1),Xe([j()],Ue.prototype,"playAudio",1),Xe([j()],Ue.prototype,"stopPlayAudio",1),Xe([j(ae)],Ue.prototype,"playAll",1),Xe([j()],Ue.prototype,"play",1),Xe([j()],Ue.prototype,"stopPlayAll",1);var Pt=(s=>(s[s.AliRtcPluginErrorCodeSuccess=0]="AliRtcPluginErrorCodeSuccess",s[s.AliRtcPluginErrorCodeFailed=-1]="AliRtcPluginErrorCodeFailed",s[s.AliRtcPluginErrorNoFindPlugin=-2]="AliRtcPluginErrorNoFindPlugin",s[s.AliRtcPluginErrorParameterError=-3]="AliRtcPluginErrorParameterError",s[s.AliRtcPluginErrorLoadError=-4]="AliRtcPluginErrorLoadError",s[s.AliRtcPluginErrorCreateError=-5]="AliRtcPluginErrorCreateError",s[s.AliRtcPluginErrorInitError=-6]="AliRtcPluginErrorInitError",s[s.AliRtcPluginErrorInitTokenError=-7]="AliRtcPluginErrorInitTokenError",s))(Pt||{});class h0 extends ve{constructor(){super(...arguments);A(this,"plugins",new Map)}add(e,t){if(this.plugins.has(e.name))throw new ne(Pt.AliRtcPluginErrorCreateError,`Plugin ${e.name} already exists`);this.plugins.set(e.name,e),t&&e.setOptions(t),this.emit("added",e),e.on("enabled",()=>this.emit("added",e)),e.on("disabled",()=>this.emit("removed",e)),e.on("updated",()=>this.emit("updated",e))}remove(e){const t=this.plugins.get(e);if(!t)throw new ne(Pt.AliRtcPluginErrorNoFindPlugin,`Plugin ${e} not founded`);this.plugins.delete(e),t.removeAllListeners(),this.emit("removed",t)}get(e){return this.plugins.get(e)}has(e){return!!this.plugins.get(e)}getAll(){return Array.from(this.plugins.values())}}var d0=Object.defineProperty,l0=Object.getOwnPropertyDescriptor,tt=(s,c,e,t)=>{for(var r=t>1?void 0:t?l0(c,e):c,i=s.length-1,n;i>=0;i--)(n=s[i])&&(r=(t?n(c,e,r):n(r))||r);return t&&r&&d0(c,e,r),r};const Oi=([s])=>{const{remoteUser:c,options:e}=s;return[`user(${c.userId})`,e]},Ye=(_t=class extends ve{constructor(e,t){super();A(this,"rts");A(this,"encodedInsertableStreams",!0);A(this,"audioRedEnabled",!1);A(this,"localStreamManager");A(this,"slsReporter");A(this,"connecting",!1);A(this,"connected",!1);A(this,"_pcTraceId","");A(this,"_localJoinTime",0);A(this,"connectionResolve");A(this,"connectingPromise");A(this,"dcResolve");A(this,"dcConnectingPromise");A(this,"_publishingTracks",[]);this.rts=me.AliRTS.createClient(),this.localStreamManager=e,this.slsReporter=t,this.rts.on("connectStatusChange",r=>{var i,n,a,o;if(oe.event(`[${_t.logName}]`,"rts connectStatusChange to:",r.status),r.status===me.EConnectStatus.CONNECT_STATUS_DISCONNECTED)this.emit("disconnected"),this.setConnected(!1),this.slsReporter.reportWarning("rts disconnected");else if(r.status===me.EConnectStatus.CONNECT_STATUS_RECONNECTING)this.emit("reconnecting"),this.setConnected(!1),this.slsReporter.reportWarning("rts reconnecting");else if(r.status===me.EConnectStatus.CONNECT_STATUS_CONNECTED){this.setConnected(!0);const u=(o=(a=(n=(i=this.rts.commonController)==null?void 0:i.peerCore)==null?void 0:n.getSignal())==null?void 0:a.getDatachannelCore())==null?void 0:o.readyState;oe.event(_t.logName,"dcReadyState:",u),u==="open"&&this.dcResolve&&this.dcResolve(!0),this.emit("connected")}}),this.rts.on("datachannelStatusChange",r=>{oe.event(`[${_t.logName}]`,"rts datachannelStatusChange to:",r.status),r.status===me.EDatachannelStatus.DATACHANNEL_STATUS_OPEN?this.dcResolve&&this.dcResolve(!0):r.status===me.EDatachannelStatus.DATACHANNEL_STATUS_CLOSE&&(this.dcConnectingPromise=new Promise(i=>{this.dcResolve=i}),console.warn("DC DisConnected"))}),this.rts.on("receivedSEI",r=>{this.emit("seimessage",r.url,r.sei.payloadType,r.sei.data)})}get pcTraceId(){return this._pcTraceId}set localJoinTime(e){this._localJoinTime=e}setEncodedInsertableStreams(e){this.encodedInsertableStreams=e}setAudioRedEnabled(e){var t;if(e!==this.audioRedEnabled){try{const i=[...((t=RTCRtpReceiver.getCapabilities("audio"))==null?void 0:t.codecs)||[]];if(i.length>0){if(e){const n=i.findIndex(o=>o.mimeType==="audio/red"),a=i.findIndex(o=>o.mimeType==="audio/opus");if(n>-1&&a>-1&&n>a){const o=i[a];i[a]=i[n],i[n]=o}}this.rts.setSenderCodecPreferences({audio:i}),this.rts.setReceiverCodecPreferences({audio:i})}}catch(r){}this.audioRedEnabled=e}}destroy(){this.rts.unpublish()}startConnect(){this.connecting=!0,this.connectingPromise=new Promise(e=>{this.connectionResolve=e}),this.dcConnectingPromise=new Promise(e=>{this.dcResolve=e})}setConnected(e){var t;this.connected=e,this.connecting=!1,(t=this.connectionResolve)==null||t.call(this,!0),e||(this.dcConnectingPromise=new Promise(r=>{this.dcResolve=r}))}get isConnecting(){return this.connecting}get isConnected(){return this.connected}get publishingTracks(){return this._publishingTracks}getPubMsid(e,t){const{aMsid:r,vMsid:i}=t!=null?t:{},n={};return e.hasAudio&&(n.aMsid=[r!=null?r:Z.Audio]),e.hasScreen&&(n.vMsid=[Z.Screen]),e.hasVideo&&(n.vMsid=[i!=null?i:t!=null&&t.isScreen?Z.Screen:Z.VideoLarge]),n}updatePublishingTracks(e){e&&(this._publishingTracks=e.map(({msid:t,from:r,ssrc:i,codec:n,type:a,trackId:o})=>({msid:t,from:r,type:a,ssrc:`${i}`,codec:n!=null?n:"",trackId:o})))}httpPublish(n,a){return z(this,arguments,function*(e,t,r=!1,i=Ot.MANUAL){const{publishStream:o,videoSmallStream:u,screenStream:h,vMsid:g}=yield this.localStreamManager.createHTTPPublishStream();if(!o)return"";const f=this.getPubMsid(o,{vMsid:g});f.retryTimes=0,this.encodedInsertableStreams&&(f.encodedInsertableStreams=!0);let l=!o.hasVideo,p=g;try{this.startConnect();const d=Date.now(),m=yield this.rts.publish(e,o,f);this.slsReporter.reportPublish(r,e,t,o.hasVideo&&(!g||g===Z.VideoLarge),o.hasVideo&&g===Z.VideoSmall,o.hasVideo&&g===Z.Screen,o.hasAudio,0,m,m,d);const x=Date.now();return this._pcTraceId=m,this.setConnected(!0),this._publishingTracks=this.rts.getPublishTrackInfoList(),u&&(yield this.publishAdd(e,u,t,{vMsid:Z.VideoSmall},r),l=!1,p=Z.VideoSmall),h&&(yield this.publishAdd(e,h,t,{vMsid:Z.Screen},r),l=!1,p=Z.Screen),yield this.waitPublishSender(e,l,p),this.slsReporter.reportPublishFirstPacket(r,t,d,x,this._localJoinTime,l?Z.Audio:f.vMsid,m||"",m||"",i),m}catch(d){throw this.setConnected(!1),d}})}waitPublishSender(e,t=!1,r){return z(this,null,function*(){const i=(n,a)=>{let o=0;const u=()=>(t?this.rts.getPublishAudioStats(e,r):this.rts.getPublishVideoStats(e,r)).then(g=>!(g.bytesSent>0)&&o<n?(o++,new Promise(l=>setTimeout(()=>l(u()),a))):Promise.resolve());return u()};return Promise.race([$t(1e3),i(5,100)]).catch(()=>{})})}getPublishVideoStats(e,t){return z(this,null,function*(){return yield this.rts.getPublishVideoStats(e,t)})}getPublishAudioStats(e,t){return z(this,null,function*(){return yield this.rts.getPublishAudioStats(e,t)})}publishAdd(h,g,f,l){return z(this,arguments,function*(e,t,r,i,n=!1,a=0,o=!1,u=Ot.MANUAL){var m,x,v,b,y,E,I,C;yield this.dcConnectingPromise;const p=Date.now(),d=this.getPubMsid(t,i);try{const R=yield this.rts.publishAdd([Se({url:e,stream:t,updateSourceStream:!1},d)]);if(R){const L=Date.now(),[k]=R;return this.slsReporter.reportPublish(!1,e,r,((m=d.vMsid)==null?void 0:m[0])===Z.VideoLarge,((x=d.vMsid)==null?void 0:x[0])===Z.VideoSmall,((v=d.vMsid)==null?void 0:v[0])===Z.Screen,((b=d.aMsid)==null?void 0:b[0])===Z.Audio,0,this.pcTraceId,k.traceId||"",p),this.updatePublishingTracks(k.trackInfoList),o&&(yield this.waitPublishSender(e,!t.hasVideo,t.hasVideo?i==null?void 0:i.vMsid:i==null?void 0:i.aMsid)),this.slsReporter.reportPublishFirstPacket(n||a>0,r,p,L,this._localJoinTime,(t.hasVideo?i==null?void 0:i.vMsid:i==null?void 0:i.aMsid)||"",this.pcTraceId,k.traceId||"",u),k.traceId||""}}catch(R){if(this.slsReporter.reportPublish(!1,e,r,((y=d.vMsid)==null?void 0:y[0])===Z.VideoLarge,((E=d.vMsid)==null?void 0:E[0])===Z.VideoSmall,((I=d.vMsid)==null?void 0:I[0])===Z.Screen,((C=d.aMsid)==null?void 0:C[0])===Z.Audio,R.errorCode||-1,this.pcTraceId,"",p),R.errorCode===15006&&a<3)return yield this.publishAdd(e,t,r,i,n,a+1);throw R}return""})}publishDelete(e,t){return z(this,null,function*(){var h,g,f,l,p,d,m,x;yield this.dcConnectingPromise;const r=(g=(h=this.publishingTracks)==null?void 0:h.find(({msid:v})=>v===Z.Audio))==null?void 0:g.msid,i=(l=(f=this.publishingTracks)==null?void 0:f.find(({msid:v})=>v===Z.VideoLarge))==null?void 0:l.msid,n=(d=(p=this.publishingTracks)==null?void 0:p.find(({msid:v})=>v===Z.Screen))==null?void 0:d.msid,a=[];t.screen&&n?a.push(n):t.video&&a.push(t.vMsid||i);const o=[];t.audio&&r&&o.push(r),oe.event(_t.logName,"publishDelete",{streamUrl:e,aMsid:o,vMsid:a});const[u]=(yield this.rts.publishDeleteTracks([{url:e,aMsid:o,vMsid:a}]))||[];return oe.event(_t.logName,"publishDelete",{result:u}),u&&this.updatePublishingTracks(u.trackInfoList),((x=(m=u==null?void 0:u.trackInfoList)==null?void 0:m[0])==null?void 0:x.trackId)||""})}publishReplace(e,t,r){return z(this,null,function*(){var u,h;yield this.dcConnectingPromise;const{vMsid:i,aMsid:n}=r!=null?r:{},a=yield this.rts.publishReplaceTracks([{url:e,stream:t,updateSourceStream:!1,vMsid:i,aMsid:n}]),[o]=a;return this.updatePublishingTracks(o.trackInfoList),((h=(u=o==null?void 0:o.trackInfoList)==null?void 0:u[0])==null?void 0:h.trackId)||""})}publishStop(e){return z(this,null,function*(){return yield this.rts.publishStop([{url:e}]),this._publishingTracks=[],""})}unpublish(){return z(this,null,function*(){yield this.rts.unpublish(),this.connecting=!1,this.connected=!1})}getSubConfig(e,t){let r=t!=null?t:{};t||(r={audio:!0,video:!0,screen:!0});const i={};return r.audio&&(i.aMsid=[(e==null?void 0:e.getAudioInfo().msid)||Z.Audio]),r.video?r.vMsid?i.vMsid=[r.vMsid]:e!=null&&e.hasVideoLarge?i.vMsid=[(e==null?void 0:e.getVideoLargeInfo().msid)||Z.VideoLarge]:e!=null&&e.hasVideoSmall?i.vMsid=[(e==null?void 0:e.getVideoSmallInfo().msid)||Z.VideoSmall]:i.vMsid=[Z.VideoLarge]:r.screen&&e!=null&&e.hasScreen&&(i.vMsid=[(e==null?void 0:e.getScreenInfo().msid)||Z.Screen]),i}httpSubscribe(e){return z(this,null,function*(){const{remoteUser:t,options:r}=e;let i=t.streamUrl;r.video||r.screen?r!=null&&r.audio||(i+="@subaudio=no"):i+="@subvideo=no";const n=this.getSubConfig(t.streamInfo,r);n.retryTimes=0,this.encodedInsertableStreams&&(n.encodedInsertableStreams=!0);try{this.startConnect();const a=yield this.rts.subscribe(i,n);return this._pcTraceId=a.traceId,this.setConnected(!0),{traceId:a.traceId,stream:a}}catch(a){throw this.setConnected(!1),a}})}subscribeAdd(e){return z(this,null,function*(){var n,a,o,u;const{remoteUser:t,options:r}=e,i=Rt(Se({url:t.streamUrl,subAudio:!!r.audio,subVideo:!!(r.screen||r.video)},this.getSubConfig(t.streamInfo,r)),{targetStream:r.screen?t.getScreenStream:t.getCameraStream});try{return(yield this.rts.subscribeAdd([i]))[0]}catch(h){if(((u=(o=(a=(n=h==null?void 0:h.extraInfo)==null?void 0:n.parsedData)==null?void 0:a.streams)==null?void 0:o[0])==null?void 0:u.res_code)===508)return this.emit("subscribeexceeds"),null;throw ne.fromError(h)}})}subscibeDelete(e){return z(this,null,function*(){var n,a,o,u;yield this.dcConnectingPromise;const{remoteUser:t,options:r}=e,i=Rt(Se({url:t.streamUrl,subAudio:!!r.audio,subVideo:!!(r.screen||r.video)},this.getSubConfig(t.streamInfo,r)),{targetStream:r.screen?t.getScreenStream:t.getCameraStream});try{return(yield this.rts.subscribeDeleteTracks([i]))[0]}catch(h){if(((u=(o=(a=(n=h==null?void 0:h.extraInfo)==null?void 0:n.parsedData)==null?void 0:a.streams)==null?void 0:o[0])==null?void 0:u.res_code)===404)return;throw h}})}subscibeStop(e){return z(this,null,function*(){var t,r,i,n;try{yield this.rts.subscribeStop([{url:e}])}catch(a){if(((n=(i=(r=(t=a==null?void 0:a.extraInfo)==null?void 0:t.parsedData)==null?void 0:r.streams)==null?void 0:i[0])==null?void 0:n.res_code)===404)return;throw a}})}publish(n,a){return z(this,arguments,function*(e,t,r=!1,i=Ot.MANUAL){let o="";if(this.connecting&&(yield this.connectingPromise),this.connected){yield this.dcConnectingPromise;let u=!1,h;const{audio:g,video:f,videoSmall:l,screen:p}=this.localStreamManager.publishStreams;g&&(o=yield this.publishAdd(e,g,t,{aMsid:Z.Audio},r),u=!0,h=Z.Audio,yield $t(100)),f&&(o=yield this.publishAdd(e,f,t,{vMsid:Z.VideoLarge},r),u=!1,h=Z.VideoLarge,yield $t(100)),l&&(o=yield this.publishAdd(e,l,t,{vMsid:Z.VideoSmall},r),u=!1,h=Z.VideoSmall,yield $t(100)),p&&(o=yield this.publishAdd(e,p,t,{isScreen:!0,vMsid:Z.Screen},r),u=!1,h=Z.Screen),h&&(yield this.waitPublishSender(e,u,h))}else o=yield this.httpPublish(e,t,r,i);return o})}subscribe(e,t,r,i,n){return z(this,null,function*(){const{options:a,remoteUser:o}=e;if(a.video&&a.screen)throw new ne(ce.ERR_INNER,"subscribe error, video and screen cannot be subscribed at the same time");this.connecting&&(yield this.connectingPromise);let u,h=Date.now();this.connected?(yield this.dcConnectingPromise,h=Date.now(),u=yield this.subscribeAdd(e)):u=yield this.httpSubscribe(e);const g=Date.now();let f=Z.VideoLarge,l=a.video||a.screen,p=a.audio;a.video&&a.vMsid?f=a.vMsid:a.screen&&(f=Z.Screen);let d=0,m=0,x=0;return((b,y)=>{let E=0;const I=()=>{let C;return p&&!d&&(C=this.rts.getSubscribeAudioStats(o.streamUrl).then(R=>{if(R.packetsReceived>0)d=Date.now();else if(!l)return E<b?(E++,new Promise(L=>setTimeout(()=>L(I()),y))):!1;return!0})),l&&!x&&(C=this.rts.getSubscribeVideoStats(o.streamUrl,f).then(R=>{if(R.packetsReceived>0&&(m=Date.now()),R.framesDecoded>0)x=Date.now();else return E<b?(E++,new Promise(L=>setTimeout(()=>L(I()),y))):(oe.error(`[${_t.logName}]`,"checkInStatsWithRetry fail"),!1);return!0})),Promise.resolve(C)};return I()})(20,100).then(()=>{m&&this.slsReporter.reportSubscribeFirstPacket(t===Be.Resume,r,i,f,{fprt:m-h,ifsprtc:x?x-h:0,ajsub:t===Be.Join?1:0,pctid:this.pcTraceId,subtid:(u==null?void 0:u.traceId)||"",sstc:g-h}),x&&this.slsReporter.reportSubscribeFirstFrame(t===Be.Resume,r,i,f,{fvfrt:x-h,fp2fftc:x-m,ajsub:t===Be.Join?1:0,tffrtc:t===Be.Join?x-this.localJoinTime:x-n,pctid:this.pcTraceId,subtid:(u==null?void 0:u.traceId)||"",fvfdtc:x-h}),d&&this.slsReporter.reportSubscribeFirstPacket(t===Be.Resume,r,i,Z.Audio,{fprt:d-h,ifsprtc:d-h,ajsub:t===Be.Join?1:0,pctid:this.pcTraceId,subtid:(u==null?void 0:u.traceId)||"",sstc:g-h})}),u})}getSubscribeVideoStats(e,t){return z(this,null,function*(){return yield this.rts.getSubscribeVideoStats(e,t)})}getSubscribeAudioStats(e,t){return z(this,null,function*(){return yield this.rts.getSubscribeAudioStats(e,t)})}getStreamByMsid(e){return this.rts.commonController.streamManager.getStreamByMsid(e)}getPCStats(){return z(this,null,function*(){var e,t;return(t=(e=this.rts.commonController.peerCore)==null?void 0:e.pc)==null?void 0:t.getStats()})}sendSEI(e,t,r,i){return z(this,null,function*(){return this.rts.sendSEI({url:e,vMsid:Z.VideoLarge,data:t,repeatCount:r,payloadType:i})})}},A(_t,"logName","RtsManager"),_t);tt([j()],Ye.prototype,"updatePublishingTracks",1),tt([j(ae,ae)],Ye.prototype,"httpPublish",1),tt([j(ae,ae)],Ye.prototype,"waitPublishSender",1),tt([j(([s,c,e])=>[s,JSON.stringify(e)],ae)],Ye.prototype,"publishAdd",1),tt([j(ae,ae)],Ye.prototype,"publishDelete",1),tt([j(([s,c,e])=>[s,JSON.stringify(e)])],Ye.prototype,"publishReplace",1),tt([j(ae)],Ye.prototype,"publishStop",1),tt([j()],Ye.prototype,"unpublish",1),tt([j(Oi,({traceId:s})=>s)],Ye.prototype,"httpSubscribe",1),tt([j(Oi,({traceId:s})=>s)],Ye.prototype,"subscribeAdd",1),tt([j(Oi)],Ye.prototype,"subscibeDelete",1),tt([j(ae)],Ye.prototype,"subscibeStop",1),tt([j(ae)],Ye.prototype,"publish",1),tt([j(Oi)],Ye.prototype,"subscribe",1),tt([j()],Ye.prototype,"sendSEI",1);let f0=Ye;class ps{constructor(){A(this,"profile");A(this,"profileMap",new Map);A(this,"audioProfile");A(this,"contentHint")}updateProfile(c,e){e&&this.profileMap.set(c,e),this.profile=c}get videoProfile(){return this.profile}updateAudioProfile(c){this.audioProfile=c}setContentHint(c,e){e&&(this.contentHint=e),this.contentHint&&c&&(c.contentHint=this.contentHint)}setVideoProfile(c,e,t=!1){return z(this,null,function*(){if(!this.profile)return;const r=this.profileMap.get(this.profile)||(e==null?void 0:e.VideoProfileMap.get(this.profile));if(r){if(!t&&c&&c.applyConstraints)try{yield c.applyConstraints(r)}catch(i){}e&&(e==null||e.VideoProfileMap.set(this.profile,r),yield e.setVideoProfile(this.profile))}})}}class ms extends ve{constructor(e){super();A(this,"type");A(this,"originVideoTrack");A(this,"videoSource");A(this,"_videoMuted",!1);A(this,"originAudioTrack");A(this,"audioSource");A(this,"_audioMuted",!1);A(this,"_targetVideoTrack");A(this,"_targetDualVideoTrack");A(this,"_targetAudioTrack");A(this,"_publishVideoStream");A(this,"_publishDualVideoStream");A(this,"_publishAudioStream");A(this,"_previewStream");A(this,"plugins",[]);A(this,"_profileManager");A(this,"cameraVideoConstraints");A(this,"micAudioConstraints");A(this,"onVideoTrackEnded",()=>{this.emit("videotrackended")});A(this,"onAudioTrackEnded",()=>{this.emit("audiotrackended")});this.type=e}get profileManager(){return this._profileManager}get audioProfile(){var e;return(e=this.profileManager)==null?void 0:e.audioProfile}updateSource(e,t,r){return z(this,null,function*(){var a,o,u,h,g,f;const{videoTrack:i,audioTrack:n}=e;i&&((a=this.originVideoTrack)==null||a.removeEventListener("ended",this.onVideoTrackEnded)),n&&((o=this.originAudioTrack)==null||o.removeEventListener("ended",this.onAudioTrackEnded)),this.type===Ke.AliRtcSdkStreamTypeScreen?this.stop():(i&&((u=this.originVideoTrack)==null||u.stop()),n&&((h=this.originAudioTrack)==null||h.stop())),i&&(this.originVideoTrack=i,(g=this.originVideoTrack)==null||g.addEventListener("ended",this.onVideoTrackEnded),this.videoSource=t||Yt.Camera,this.updateVideoTrack(i)),n&&(this.originAudioTrack=n,(f=this.originAudioTrack)==null||f.addEventListener("ended",this.onAudioTrackEnded),this.audioSource=r||yi.Microphone,this.updateAudioTrack(n))})}get currentProfile(){var e;return(e=this.profileManager)==null?void 0:e.profile}get currentVideoTrack(){return this._targetVideoTrack}get currentDualVideoTrack(){return this._targetDualVideoTrack}get publishVideoStream(){return this._publishVideoStream}get publishDualVideoStream(){return this._publishDualVideoStream}get currentAudioTrack(){return this._targetAudioTrack}get publishAudioStream(){return this._publishAudioStream}get previewStream(){return this._previewStream}updateVideoTrack(e,t=!1){return z(this,null,function*(){(this._targetVideoTrack!==e||t)&&(this._targetVideoTrack=e)})}updateDualVideoTrack(e,t=!1){return z(this,null,function*(){(this._targetDualVideoTrack!==e||t)&&(this._targetDualVideoTrack=e)})}updateAudioTrack(e,t=!1){return z(this,null,function*(){(this._targetAudioTrack!==e||t)&&(this._targetAudioTrack=e)})}setAudioMuted(e){var t,r;this._audioMuted=e,e?(t=this.publishAudioStream)==null||t.disableAudio():(r=this.publishAudioStream)==null||r.enableAudio()}get isAudioMuted(){return this._audioMuted}setVideoMuted(e){var t,r;this._videoMuted=e,e?(t=this.publishVideoStream)==null||t.disableVideo():(r=this.publishVideoStream)==null||r.enableVideo()}get isVideoMuted(){return this._videoMuted}process(e){return z(this,null,function*(){var t,r,i,n,a,o,u,h,g,f,l,p;this._targetAudioTrack=this.originAudioTrack,this._targetVideoTrack=this.originVideoTrack;for(const d of this.plugins)try{yield d.execute(this,e)}catch(m){console.error(`error in plugin-${d.name}, error: ${m}`)}this._targetVideoTrack?((r=(t=this._publishVideoStream)==null?void 0:t.videoTrack)==null?void 0:r.id)!==this._targetVideoTrack.id&&(this._publishVideoStream=yield xi(this._targetVideoTrack),this.setVideoMuted(this._videoMuted),(i=this.profileManager)==null||i.setVideoProfile(this.originVideoTrack,this._publishVideoStream,!0),(n=this.profileManager)==null||n.setContentHint(this._targetVideoTrack),this.previewStream?(a=this.previewStream)==null||a.mergeStream(this._publishVideoStream):this._previewStream=yield xi(this._targetVideoTrack)):(this._publishVideoStream=void 0,(o=this.previewStream)==null||o.deleteTracks({video:!0})),this._targetDualVideoTrack?((h=(u=this._publishDualVideoStream)==null?void 0:u.videoTrack)==null?void 0:h.id)!==this._targetDualVideoTrack.id&&(this._publishDualVideoStream=yield xi(this._targetDualVideoTrack),this._videoMuted?this._publishDualVideoStream.disableVideo():this._publishDualVideoStream.enableVideo()):this._publishDualVideoStream=void 0,this._targetAudioTrack?((f=(g=this._publishAudioStream)==null?void 0:g.audioTrack)==null?void 0:f.id)!==this._targetAudioTrack.id&&(this._publishAudioStream=yield xi(this._targetAudioTrack),this.setAudioMuted(this._audioMuted),this.previewStream?(l=this.previewStream)==null||l.mergeStream(this._publishAudioStream):this._previewStream=yield xi(this._targetAudioTrack)):(this._publishAudioStream=void 0,(p=this.previewStream)==null||p.deleteTracks({audio:!0}))})}stopVideo(){var e,t;this.originVideoTrack&&((e=this.originVideoTrack)==null||e.removeEventListener("ended",this.onAudioTrackEnded),(t=this.originVideoTrack)==null||t.stop(),this.originVideoTrack=void 0),this.updateVideoTrack(void 0)}stopAudio(){var e,t;this.originAudioTrack&&((e=this.originAudioTrack)==null||e.removeEventListener("ended",this.onAudioTrackEnded),(t=this.originAudioTrack)==null||t.stop(),this.originAudioTrack=void 0),this.updateAudioTrack(void 0)}stop(){this.stopVideo(),this.stopAudio()}updateVideoProfile(e,t){return z(this,null,function*(){this._profileManager||(this._profileManager=new ps),e&&this._profileManager.updateProfile(e,t),yield this._profileManager.setVideoProfile(this.originVideoTrack,this._publishVideoStream,this.type===Ke.AliRtcSdkStreamTypeScreen)})}get videoProfile(){var e;return(e=this.profileManager)==null?void 0:e.videoProfile}setVideoContentHint(e){this._profileManager||(this._profileManager=new ps),this._profileManager.setContentHint(this.currentVideoTrack,e)}updateAudioProfile(e){return z(this,null,function*(){this._profileManager||(this._profileManager=new ps),this._profileManager.updateAudioProfile(e)})}cloneVideoProfile(e){return z(this,null,function*(){var t;yield(t=this.profileManager)==null?void 0:t.setVideoProfile(void 0,e)})}addPlugin(e){const t=this.plugins.findIndex(r=>r.zIndex>e.zIndex);t>-1?this.plugins.splice(t,0,e):this.plugins.push(e)}removePlugin(e){const t=this.plugins.indexOf(e);return t>-1?(e.clear(this),this.plugins.splice(t,1),!0):!1}}var p0=Object.defineProperty,m0=Object.getOwnPropertyDescriptor,bt=(s,c,e,t)=>{for(var r=t>1?void 0:t?m0(c,e):c,i=s.length-1,n;i>=0;i--)(n=s[i])&&(r=(t?n(c,e,r):n(r))||r);return t&&r&&p0(c,e,r),r};const gt=(si=class extends ve{constructor(e,t){super();A(this,"pluginManager");A(this,"slsReporter");A(this,"publishingCameraVideoStream");A(this,"publishingScreenVideoStream");A(this,"cameraStreamInfo",new ms(Ke.AliRtcSdkStreamTypeCapture));A(this,"screenStreamInfo",new ms(Ke.AliRtcSdkStreamTypeScreen));A(this,"streamInfos",[this.cameraStreamInfo,this.screenStreamInfo]);A(this,"_audioCaptureDisabled",!1);A(this,"_cameraCaptureDisabled",!1);A(this,"_publishLocalAudioStreamEnabled",!0);A(this,"_publishLocalVideoStreamEnabled",!0);A(this,"_publishLocalScreenStreamEnabled",!0);this.screenStreamInfo.setVideoContentHint("motion"),this.pluginManager=e,this.slsReporter=t;const r=i=>z(this,null,function*(){if(oe.info(`[${si.logName}]`,"plugin added",i.name),!i.isSupported("6.11.9-beta.0")){console.warn(`${i.name} is not supported!!!`),i.emit("unsupported");return}try{yield i.init()}catch(n){i.emit("error",ne.fromError(n,Pt.AliRtcPluginErrorInitError))}i.streamType===Ke.AliRtcSdkStreamTypeCapture&&(this.cameraStreamInfo.addPlugin(i),yield this.cameraStreamInfo.process(this.streamInfos)),i.streamType===Ke.AliRtcSdkStreamTypeScreen&&(this.screenStreamInfo.addPlugin(i),yield this.screenStreamInfo.process(this.streamInfos)),this.emit("publishupdate")});this.cameraStreamInfo.updateVideoProfile(oa,gi),this.cameraStreamInfo.on("videotrackended",()=>z(this,null,function*(){yield this.stopLocalStream({video:!0}),this.emit("trackended",Gt.VideoTrackEnded)})),this.cameraStreamInfo.on("audiotrackended",()=>z(this,null,function*(){yield this.stopLocalStream({audio:!0}),this.emit("trackended",Gt.AudioTrackEnded)})),this.screenStreamInfo.updateVideoProfile(ca,vi),this.screenStreamInfo.on("videotrackended",()=>z(this,null,function*(){yield this.stopLocalStream({screen:!0}),this.emit("trackended",Gt.ScreenTrackEnded)})),this.pluginManager.on("added",r),this.pluginManager.on("removed",i=>z(this,null,function*(){this.cameraStreamInfo.removePlugin(i)&&(yield this.cameraStreamInfo.process(this.streamInfos)),this.screenStreamInfo.removePlugin(i)&&(yield this.screenStreamInfo.process(this.streamInfos)),this.emit("publishupdate")})),this.pluginManager.on("updated",()=>z(this,null,function*(){yield this.updateStreams()}))}get hasCamera(){return!!this.cameraStreamInfo.originVideoTrack}get audioCaptureDisabled(){return this._audioCaptureDisabled}set audioCaptureDisabled(e){this._audioCaptureDisabled=e}get cameraCaptureDisabled(){return this._cameraCaptureDisabled}setAudioMuted(e){this.cameraStreamInfo.setAudioMuted(e)}get isAudioMuted(){return this.cameraStreamInfo.isAudioMuted}setCameraMuted(e){this.cameraStreamInfo.setVideoMuted(e)}get isCameraMuted(){return this.cameraStreamInfo.isVideoMuted}setScreenMuted(e){this.screenStreamInfo.setVideoMuted(e)}get isScreenMuted(){return this.screenStreamInfo.isVideoMuted}set cameraCaptureDisabled(e){this._cameraCaptureDisabled=e}get publishLocalAudioStreamEnabled(){return this._publishLocalAudioStreamEnabled}set publishLocalAudioStreamEnabled(e){this._publishLocalAudioStreamEnabled=e}get publishLocalVideoStreamEnabled(){return this._publishLocalVideoStreamEnabled}set publishLocalVideoStreamEnabled(e){this._publishLocalVideoStreamEnabled=e}get publishLocalScreenStreamEnabled(){return this._publishLocalScreenStreamEnabled}set publishLocalScreenStreamEnabled(e){this._publishLocalScreenStreamEnabled=e}updateStreams(){return z(this,null,function*(){yield this.cameraStreamInfo.process(this.streamInfos),yield this.screenStreamInfo.process(this.streamInfos),this.emit("publishupdate")})}setAvailableCameraDeviceId(){return z(this,null,function*(){var e,t,r,i;if((e=this.cameraStreamInfo.cameraVideoConstraints)!=null&&e.deviceId){let n=(t=this.cameraStreamInfo.cameraVideoConstraints)==null?void 0:t.deviceId;const a=yield me.AliRTS.getCameraList();a.find(o=>o.deviceId===n)||(n=(i=(r=a.find(o=>!!o.deviceId))==null?void 0:r.deviceId)!=null?i:""),this.cameraStreamInfo.cameraVideoConstraints.deviceId=n}})}setAvailableMicrophoneDeviceId(){return z(this,null,function*(){var e,t,r,i;if((e=this.cameraStreamInfo.micAudioConstraints)!=null&&e.deviceId){let n=(t=this.cameraStreamInfo.micAudioConstraints)==null?void 0:t.deviceId;const a=yield me.AliRTS.getMicList();a.find(o=>o.deviceId===n)||(n=(i=(r=a.find(o=>!!o.deviceId))==null?void 0:r.deviceId)!=null?i:""),this.cameraStreamInfo.micAudioConstraints.deviceId=n}})}createLocalStream(e){return z(this,null,function*(){var g;const{screen:t,mediaStream:r,videoProfile:i,screenProfile:n}=e;let{video:a,audio:o}=e;const u=Qc(e);let h;if(u){r||(a===!0&&this.cameraStreamInfo.cameraVideoConstraints?(yield this.setAvailableCameraDeviceId(),a=Se({},this.cameraStreamInfo.cameraVideoConstraints)):typeof a=="object"&&(yield this.setAvailableCameraDeviceId(),a=Se(Se({},a),this.cameraStreamInfo.cameraVideoConstraints)),o===void 0&&this.audioCaptureDisabled?o=!1:o&&(o===!0&&this.cameraStreamInfo.micAudioConstraints?(yield this.setAvailableMicrophoneDeviceId(),o=Se({},this.cameraStreamInfo.micAudioConstraints)):typeof o=="object"&&(yield this.setAvailableMicrophoneDeviceId(),o=Se(Se({},o),this.cameraStreamInfo.micAudioConstraints)),this._audioCaptureDisabled=!1));const f=Date.now();try{h=yield me.AliRTS.createStream({audio:o,video:a,screen:t,custom:!!r,mediaStream:r,skipProfile:!0}),o&&!r&&this.slsReporter.reportAudio(null,Date.now()-f,((g=h==null?void 0:h.audioTrack)==null?void 0:g.label)||""),t&&!r&&this.slsReporter.reportScreen(null,Date.now()-f)}catch(l){throw o&&!r&&this.slsReporter.reportAudio(l,Date.now()-f,""),t&&!r&&this.slsReporter.reportScreen(null,Date.now()-f),l}if(t)yield this.screenStreamInfo.updateSource(h,Yt.Screen,yi.Screen),yield this.setScreenProfile(n),this.setScreenContentHint(),this.publishingScreenVideoStream=void 0;else if(yield this.cameraStreamInfo.updateSource(h,Yt.Camera,yi.Microphone),h.hasVideo&&(yield this.setVideoProfile(i),this.setVideoContentHint(),this.publishingCameraVideoStream=void 0),h.hasAudio&&typeof o=="boolean"){const l=this.cameraStreamInfo.audioProfile;l&&(yield h.setAudioProfile(l))}}return me.AliRTS.SystenUtil.isIos&&me.AliRTS.SystenUtil.compareVersion("15.1")&&!me.AliRTS.SystenUtil.compareVersion("15.2")&&(yield $t(1e3)),yield this.updateStreams(),h})}stopLocalStream(e){return z(this,null,function*(){const{screen:t,video:r,audio:i}=e!=null?e:{};let n=!1;r&&this.cameraStreamInfo.originVideoTrack&&(n=!0,this.cameraStreamInfo.stopVideo(),this.publishingCameraVideoStream=void 0),i&&this.cameraStreamInfo.originAudioTrack&&(n=!0,this.cameraStreamInfo.stopAudio()),t&&this.screenStreamInfo.originVideoTrack&&(n=!0,this.screenStreamInfo.stop(),this.publishingScreenVideoStream=void 0,this.slsReporter.reportScreenStop(null)),n&&(yield this.updateStreams())})}get publishStreams(){const{publishLocalVideoStreamEnabled:e,publishLocalAudioStreamEnabled:t,publishLocalScreenStreamEnabled:r}=this;return{video:e?this.cameraStreamInfo.publishVideoStream:void 0,videoSmall:e?this.cameraStreamInfo.publishDualVideoStream:void 0,audio:t?this.cameraStreamInfo.publishAudioStream:void 0,screen:r?this.screenStreamInfo.publishVideoStream:void 0}}createHTTPPublishStream(){return z(this,null,function*(){var o,u,h,g;let e,t=!1,r,i,n;const a=yield this.publishStreams;try{if(!a.audio&&!a.video&&!a.videoSmall&&!a.screen)throw new ne(ce.ERR_SDK_PUBLISH_INVAILD,"no tracks founded");const f=new MediaStream;(o=a.audio)!=null&&o.audioTrack&&f.addTrack(a.audio.audioTrack),(u=a.video)!=null&&u.videoTrack?(f.addTrack(a.video.videoTrack),i=a.videoSmall,n=a.screen):(h=a.screen)!=null&&h.videoTrack&&(r=Z.Screen,f.addTrack((g=a.screen)==null?void 0:g.videoTrack),t=!0),e=yield fa(f),t?(this.screenStreamInfo.cloneVideoProfile(e),this.publishingScreenVideoStream=e):(this.cameraStreamInfo.cloneVideoProfile(e),this.publishingCameraVideoStream=e)}catch(f){}return{publishStream:e,videoSmallStream:i,screenStream:n,vMsid:r}})}stop(){this.cameraStreamInfo.stop(),this.screenStreamInfo.stop()}setVideoProfile(e,t){return z(this,null,function*(){yield this.cameraStreamInfo.updateVideoProfile(e,t),this.publishingCameraVideoStream&&this.cameraStreamInfo.cloneVideoProfile(this.publishingCameraVideoStream)})}setVideoContentHint(e){this.cameraStreamInfo.setVideoContentHint(e)}setAudioProfile(e){return z(this,null,function*(){var t;yield this.cameraStreamInfo.updateAudioProfile(e),yield(t=this.publishingCameraVideoStream)==null?void 0:t.setAudioProfile(e)})}setScreenProfile(e,t){return z(this,null,function*(){yield this.screenStreamInfo.updateVideoProfile(e,t),this.publishingScreenVideoStream&&this.screenStreamInfo.cloneVideoProfile(this.publishingScreenVideoStream)})}setScreenContentHint(e){this.screenStreamInfo.setVideoContentHint(e)}setCameraVideoConstraints(e){var t;this.cameraStreamInfo.cameraVideoConstraints=Se(Se({},(t=this.cameraStreamInfo.cameraVideoConstraints)!=null?t:{}),e)}setMicAudioConstraints(e){var t;this.cameraStreamInfo.micAudioConstraints=Se(Se({},(t=this.cameraStreamInfo.micAudioConstraints)!=null?t:{}),e)}},A(si,"logName","LocalStreamManager"),si);bt([j(([s])=>{const{audio:c,video:e,screen:t,custom:r,skipProfile:i,videoProfile:n,screenProfile:a}=s;return[{audio:c,video:e,screen:t,custom:r,skipProfile:i,videoProfile:n,screenProfile:a}]})],gt.prototype,"createLocalStream",1),bt([j(ae)],gt.prototype,"stopLocalStream",1),bt([j()],gt.prototype,"createHTTPPublishStream",1),bt([j()],gt.prototype,"stop",1),bt([j(ae)],gt.prototype,"setVideoProfile",1),bt([j(ae)],gt.prototype,"setVideoContentHint",1),bt([j(ae)],gt.prototype,"setAudioProfile",1),bt([j(ae)],gt.prototype,"setScreenProfile",1),bt([j(ae)],gt.prototype,"setScreenContentHint",1),bt([j(ae)],gt.prototype,"setCameraVideoConstraints",1),bt([j(ae)],gt.prototype,"setMicAudioConstraints",1);let g0=gt;var v0=Object.defineProperty,x0=Object.getOwnPropertyDescriptor,St=(s,c,e,t)=>{for(var r=t>1?void 0:t?x0(c,e):c,i=s.length-1,n;i>=0;i--)(n=s[i])&&(r=(t?n(c,e,r):n(r))||r);return t&&r&&v0(c,e,r),r};class ot extends ve{constructor(e){super();A(this,"self");A(this,"userMap",{});A(this,"usersViewMap",{});A(this,"rtsManager");A(this,"localStreamManager");A(this,"authInfo");A(this,"signalingManager");A(this,"pluginManager");A(this,"slsReporter");A(this,"statsMonitorId");A(this,"autoSubAudio",!0);A(this,"autoSubVideo",!0);A(this,"autoSubScreen",!0);A(this,"wantSubAudio",!0);A(this,"wantSubVideo",!0);A(this,"wantSubScreen",!0);A(this,"defaultStreamType",Je.AliRtcVideoStreamTypeHigh);A(this,"audioMuted",!1);A(this,"playoutVolume",1);A(this,"audioVolumeIndicationInterval",0);A(this,"indicationTimer",0);A(this,"parameter",{});const{signalingManager:t,slsReporter:r}=e;this.signalingManager=t,this.addSignalingManagerListener(),this.slsReporter=r,this.pluginManager=new h0,this.localStreamManager=new g0(this.pluginManager,this.slsReporter),this.rtsManager=new f0(this.localStreamManager,this.slsReporter),this.self=new la({rtsManager:this.rtsManager,localStreamManager:this.localStreamManager,slsReporter:this.slsReporter,signalingManager:this.signalingManager,pluginManager:this.pluginManager,audioVolumeIndicationInterval:this.audioVolumeIndicationInterval,parameter:this.parameter})}addSignalingManagerListener(){this.signalingManager.on("onNotifyPublish",e=>{oe.event("[Signaling] Notify Publish ",e),e.forEach(t=>{this.onRemotePublishStateChange(t)})}),this.signalingManager.stsManager.on("onTokenUpdate",(e,t)=>{oe.updateToken(e),this.slsReporter.updateToken(t,e)})}isAutoSubAudio(){return this.autoSubAudio}setAutoSubAudio(e){this.autoSubAudio=e}isAutoSubVideo(){return this.autoSubVideo}setAutoSubVideo(e){this.autoSubVideo=e}isAutoSubScreen(){return this.autoSubScreen}setAutoSubScreen(e){this.autoSubScreen=e}isWantSubAudio(){return this.wantSubAudio}setWantSubAudio(e){this.wantSubAudio=e,this.remoteUsers.forEach(t=>{t.setWantSubAudio(e),t.updateSubscribe(Be.User)})}isWantSubVideo(){return this.wantSubVideo}setWantSubVideo(e){this.wantSubVideo=e,this.remoteUsers.forEach(t=>{t.setWantSubVideo(e),t.updateSubscribe(Be.User)})}isWantSubScreen(){return this.wantSubScreen}setWantSubScreen(e){this.wantSubScreen=e,this.remoteUsers.forEach(t=>{t.setWantSubScreen(e),t.updateSubscribe(Be.User)})}setRemoteDefaultVideoStreamType(e){this.defaultStreamType=e,this.remoteUsers.forEach(t=>{t.setRemoteDefaultVideoStreamType(e)})}setRemoteUserVideoStreamType(e,t){var r;(r=this.getRemoteUser(e))==null||r.setRemoteDefaultVideoStreamType(t)}setAudioMuted(e){this.audioMuted=e,this.remoteUsers.forEach(t=>{t.setAudioMuted(e)})}setLocalViewConfig(e,t){var i;if(!e)return(i=this.publisher)==null?void 0:i.setViewConfig(null,t);const r=fs(e);r.length!==0&&r.forEach(n=>{var a,o;(a=this.publisher)==null||a.resetElement(n),Object.values(this.usersViewMap).forEach(({cameraViews:u=[],screenViews:h=[]})=>{u.includes(n)&&u.splice(u.indexOf(n),1),h.includes(n)&&h.splice(h.indexOf(n),1)}),(o=this.publisher)==null||o.setViewConfig(r,t)})}setRemoteViewConfig(e,t,r){var n,a;if(!t)return(n=this.userMap[e])==null?void 0:n.setViewConfig(null,r);const i=fs(t);i.length!==0&&(i.forEach(o=>{var u;(u=this.publisher)==null||u.resetElement(o),Object.values(this.usersViewMap).forEach(({cameraViews:h=[],screenViews:g=[]})=>{h.includes(o)&&h.splice(h.indexOf(o),1),g.includes(o)&&g.splice(g.indexOf(o),1)})}),(a=this.userMap[e])==null||a.setViewConfig(i,r))}get channel(){var e;return(e=this.authInfo)==null?void 0:e.channelId}get userId(){var e;return(e=this.authInfo)==null?void 0:e.userId}get remoteUsers(){return Object.values(this.userMap)}get publisher(){return this.self}get isSubscribing(){var e;return((e=this.remoteUsers)!=null?e:[]).some(t=>{var o;const{isAudioSubscribing:r,isVideoLargeSubscribing:i,isVideoSmallSubscribing:n,isScreenSubscribing:a}=(o=t.streamInfo)!=null?o:{};return r||i||n||a})}onRemotePublishStateChange(e){var f;const{userid:t,callid:r,subscribe:i,pubid:n="",tracks:a}=e,o=(f=i==null?void 0:i.pullstreamurl)!=null?f:"";let u=this.getRemoteUser(t);if(!u)return;const h=u.streamInfo.audioTrackInfo,g=u.streamInfo.videoTrackInfo;u.updateRemoteTracks(r,o,n,a),u.updateSubscribe(Be.Publish),(h!==u.streamInfo.audioTrackInfo||g!==u.streamInfo.videoTrackInfo)&&this.emit("remoteTrackAvailableChange",t,u.streamInfo.audioTrackInfo,u.streamInfo.videoTrackInfo)}init(e,t){var r;this.authInfo=e,this.self||(this.self=new la({rtsManager:this.rtsManager,localStreamManager:this.localStreamManager,slsReporter:this.slsReporter,signalingManager:this.signalingManager,pluginManager:this.pluginManager,audioVolumeIndicationInterval:this.audioVolumeIndicationInterval,parameter:this.parameter})),this.self.enableAudioVolumeIndication(this.audioVolumeIndicationInterval),(r=this.self)==null||r.initInfo(e,t.pushstreamurl),t.users.forEach(i=>{const n=i.userid;if(n){const a=this.addUser(n,i.displayname,Be.InRoom),{callid:o,subscribe:u,tracks:h}=i;a.updateRemoteTracks(o,(u==null?void 0:u.pullstreamurl)||"","",h),this.emit("remoteTrackAvailableChange",n,a.streamInfo.audioTrackInfo,a.streamInfo.videoTrackInfo)}}),this.startStatsMonitor()}clear(){return z(this,null,function*(){var e;this.stopStatsMonitor();for(let t in this.userMap)this.userMap[t]&&(yield this.userMap[t].clear(),delete this.userMap[t]);yield(e=this.self)==null?void 0:e.clear(),this.authInfo=void 0})}startStatsMonitor(){this.statsMonitorId=window.setInterval(()=>z(this,null,function*(){if(this.publisher){const{audio:r,video:i,candidate:n}=yield this.publisher.getStats();r&&r.length>0&&this.emit("rtcLocalAudioStats",r),i&&i.length>0&&this.emit("rtcLocalVideoStats",i),n&&this.emit("rtcStats",n)}const e=[],t=[];for(const r of this.remoteUsers){const{audio:i,video:n}=yield r.getStats();i&&i.forEach(a=>{e.push(a)}),n&&n.forEach(a=>{t.push(a)})}e.length>0&&this.emit("rtcRemoteAudioStats",e),t.length>0&&this.emit("rtcRemoteVideoStats",t)}),2e3)}stopStatsMonitor(){this.statsMonitorId&&clearInterval(this.statsMonitorId)}addUser(e,t,r){return this.userMap[e]||(this.userMap[e]=this.executeAddUser(e,t,r)),this.userMap[e]}executeAddUser(e,t,r){const i=new Ue({userId:e,displayName:t,rtsManager:this.rtsManager,signalingManager:this.signalingManager,usersViewMap:this.usersViewMap,slsReporter:this.slsReporter,localUser:this.self,audioVolumeIndicationInterval:this.audioVolumeIndicationInterval,playoutVolume:this.playoutVolume,parameter:this.parameter});return i.on(et.Remote,this.onRemoteDeviceStatusChange.bind(this)),i.on(Ie.PullStreamStats,this.onRemoteStatReport.bind(this)),i.on(Ie.RtsSubscribeExceeds,this.onSubscribeExceeds.bind(this)),i.on("audioSubscribeStateChanged",(n,a,o,u)=>{this.emit("audioSubscribeStateChanged",n,a,o,u,this.channel||"")}),i.on("videoSubscribeStateChanged",(n,a,o,u)=>{this.emit("videoSubscribeStateChanged",n,a,o,u,this.channel||"")}),i.on("screenSubscribeStateChanged",(n,a,o,u)=>{this.emit("screenSubscribeStateChanged",n,a,o,u,this.channel||"")}),i.on("remoteAudioAutoPlayFail",n=>{this.emit("remoteAudioAutoPlayFail",n)}),i.on("remoteVideoAutoPlayFail",(n,a)=>{this.emit("remoteVideoAutoPlayFail",n,a)}),i.on("remoteAudioPlayError",(n,a)=>{this.emit("remoteAudioPlayError",n,a)}),i.on("remoteVideoPlayError",(n,a)=>{this.emit("remoteVideoPlayError",n,a)}),i.on("remoteSubscribeError",n=>{this.emit("remoteSubscribeError",n)}),i.setWantSubAudio(this.autoSubAudio&&this.wantSubAudio),i.setWantSubVideo(this.autoSubVideo&&this.wantSubVideo),i.setWantSubScreen(this.autoSubScreen&&this.wantSubScreen),i.setRemoteDefaultVideoStreamType(this.defaultStreamType),i.setAudioMuted(this.audioMuted),(this.autoSubAudio||this.autoSubVideo||this.autoSubScreen)&&i.updateSubscribe(r),i}onRemoteDeviceStatusChange(e,t){e===Ie.MuteAudio?this.emit("userAudioMuted",t,!0):e===Ie.UnmuteAudio?this.emit("userAudioMuted",t,!1):e===Ie.MuteVideo?this.emit("userVideoMuted",t,!0):e===Ie.UnmuteVideo?this.emit("userVideoMuted",t,!1):e===Ie.MuteScreen?this.emit("userScreenMuted",t,!0):e===Ie.UnmuteScreen&&this.emit("userScreenMuted",t,!1)}onRemoteStatReport(e,t,r){this.emit(Ie.PullStreamStats,e,t,r)}onSubscribeExceeds(e,t){this.emit(Ie.RtsSubscribeExceeds,e,t)}removeLeftUser(e){return z(this,null,function*(){e.userid&&this.userMap[e.userid]&&(yield this.userMap[e.userid].clear(!1),delete this.userMap[e.userid])})}updateUsers(e){const t=[],r=[],i={};e.forEach(o=>{o.userid&&(this.userMap[o.userid]?(r.push(o),i[o.userid]=this.userMap[o.userid]):(t.push(o),i[o.userid]=this.executeAddUser(o.userid,o.displayname,Be.Resume)))});const n=Object.keys(this.userMap),a=[];return n.forEach(o=>{i[o]||a.push({userid:o,reason:"",leavecode:cs.AliRtcUserOfflineQuit})}),this.userMap=i,{joinList:t,leaveList:a,presentList:r}}getRemoteUser(e){return this.userMap[e]}updateRemoteUserDeviceStatus(e){e&&e.userid&&this.userMap[e.userid]&&this.userMap[e.userid].updateRemoteUserDeviceStatus(e.status)}updateAudioWant(e,t){const r=this.userMap[e];if(!r)throw new ne(ce.ERR_INNER,`no remote user(${e}) founded`);r.setWantSubAudio(t),t?r.updateSubscribe(Be.User):r.stopSubscribe({audio:!0})}updateVideoWant(e,t){const r=this.userMap[e];if(!r)throw new ne(ce.ERR_INNER,`no remote user(${e}) founded`);r.setWantSubVideo(t),t?r.updateSubscribe(Be.User):r.stopSubscribe({video:!0})}updateScreenWant(e,t){const r=this.userMap[e];if(!r)throw new ne(ce.ERR_INNER,`no remote user(${e}) founded`);r.setWantSubScreen(t),t?r.updateSubscribe(Be.User):r.stopSubscribe({screen:!0})}stopIndication(){this.indicationTimer&&window.clearInterval(this.indicationTimer)}startIndication(e){this.stopIndication(),this.indicationTimer=window.setInterval(()=>{var r;const t=this.remoteUsers.map(i=>({userId:i.userId,volume:i.getAudioLevel()||0}));t.unshift({userId:"",volume:((r=this.self)==null?void 0:r.getAudioLevel())||0}),this.emit("audioVolume",t)},e)}enableAudioVolumeIndication(e){var t;this.audioVolumeIndicationInterval!==e&&(this.audioVolumeIndicationInterval>0&&e<=0&&this.stopIndication(),e>0&&this.startIndication(e),this.audioVolumeIndicationInterval=e,this.remoteUsers.forEach(r=>{r.enableAudioVolumeIndication(e)}),(t=this.self)==null||t.enableAudioVolumeIndication(e))}setPlayoutVolume(e){this.playoutVolume=e,this.remoteUsers.forEach(t=>{t.setPlayoutVolume(e)})}refreshAuthInfo(e){var t;this.authInfo&&(this.authInfo=Se(Se({},this.authInfo),e)),e.userId&&((t=this.self)==null||t.refreshUserInfo(e.userId))}setEnableMediaExtensionMsg(e){this.rtsManager.setEncodedInsertableStreams(e)}setAudioRedEnabled(e){this.rtsManager.setAudioRedEnabled(e)}setParameter(e){const t=JSON.parse(e);Object.keys(t).forEach(r=>{this.parameter[r]=t[r]})}getParameter(){return JSON.stringify(this.parameter)}}A(ot,"logName","BizControl"),St([j()],ot.prototype,"init",1),St([j()],ot.prototype,"clear",1),St([j(ae)],ot.prototype,"addUser",1),St([j()],ot.prototype,"removeLeftUser",1),St([j()],ot.prototype,"updateUsers",1),St([j(ae)],ot.prototype,"updateAudioWant",1),St([j(ae)],ot.prototype,"updateVideoWant",1),St([j(ae)],ot.prototype,"updateScreenWant",1),St([j()],ot.prototype,"stopIndication",1),St([j()],ot.prototype,"startIndication",1),St([j()],ot.prototype,"enableAudioVolumeIndication",1);const gs=s=>z(this,null,function*(){const c=new Uint8Array(160).fill(170),e=new TextEncoder().encode(s),t=yield window.crypto.subtle.importKey("raw",c,{name:"HMAC",hash:{name:"SHA-1"}},!1,["sign"]),r=yield window.crypto.subtle.sign("HMAC",t,e);return Array.from(new Uint8Array(r)).map(i=>i.toString(16).padStart(2,"0")).join("")});class b0{constructor(c){A(this,"authInfo");A(this,"slsReporter");this.slsReporter=c}doRequest(c,e){var u;const t=this.authInfo;if(!t)return Promise.reject(Et.LiveTranscodingErrorInvalidParam);const r="https://gw.rtn.aliyuncs.com",i=Mc[c],n={appid:t.appId,userid:t.userId,channelid:t.channelId,timestamp:t.timestamp,token:t.token,nonce:t.nonce?t.nonce:"",requestid:At.createCallid(),tokensid:!1,session:(u=t.sessionId)!=null?u:At.createCallid()},a=Object.keys(n).map(h=>`${h}=${encodeURIComponent(n[h])}`).join("&"),o=`${r}${i}?${a}`;return fetch(o,{method:"POST",headers:{"Content-Type":"application/json; charset=UTF-8"},body:JSON.stringify(e)}).then(h=>h.status!==200?(this.slsReporter.reportTranscodingError(h.status,e.taskid||""),Promise.reject(new ne(ce.ERR_INNER,`transcoding request failed, status: ${h.status}`))):h).catch(h=>Promise.reject(new ne(ce.ERR_INNER,`transcoding request failed, err: ${h.message}`)))}setAuthInfo(c){this.authInfo=c}clear(){this.authInfo=void 0}startPublishLiveStream(c,e){return z(this,null,function*(){if(!this.authInfo)return Promise.reject(Et.LiveTranscodingErrorInvalidParam);const t=yield gs(c.split("?")[0]),r=st.MPU_TASK_TRANSACTION_UPDATE,i=e.toJson(r,this.authInfo,t,c);return this.doRequest(r,i)})}startPublishLiveStreamWithTaskId(c,e){return z(this,null,function*(){if(!this.authInfo)return Promise.reject(Et.LiveTranscodingErrorInvalidParam);const t=st.MPU_TASK_TRANSACTION_UPDATE,r=e.toJson(t,this.authInfo,c);return this.doRequest(t,r)})}updatePublishLiveStream(c,e){return z(this,null,function*(){if(!this.authInfo)return Promise.reject(Et.LiveTranscodingErrorInvalidParam);const t=yield gs(c.split("?")[0]),r=st.MPU_TASK_TRANSACTION_UPDATE,i=e.toJson(r,this.authInfo,t,c);return this.doRequest(r,i)})}updatePublishLiveStreamWithTaskId(c,e){return z(this,null,function*(){if(!this.authInfo)return Promise.reject(Et.LiveTranscodingErrorInvalidParam);const t=st.MPU_TASK_TRANSACTION_UPDATE,r=e.toJson(t,this.authInfo,c);return this.doRequest(t,r)})}stopPublishLiveStream(c){return z(this,null,function*(){if(!this.authInfo)return Promise.reject(Et.LiveTranscodingErrorInvalidParam);const e=yield gs(c.split("?")[0]),t=st.MPU_TASK_TRANSACTION_STOP,r=new Li().toJson(t,this.authInfo,e,c);return this.doRequest(t,r)})}stopPublishLiveStreamWithTaskId(c){if(!this.authInfo)return Promise.reject(Et.LiveTranscodingErrorInvalidParam);const e=st.MPU_TASK_TRANSACTION_STOP,t=new Li().toJson(e,this.authInfo,c);return this.doRequest(e,t)}refreshAuthInfo(c){this.authInfo&&this.setAuthInfo(Se(Se({},this.authInfo),c))}}class ma{constructor(c){A(this,"name","COMMON");this.name=c||this.name}info(...c){}warn(...c){}print(c,...e){const t=c.toLowerCase();t&&console[t](`[${c}][${this.name}]`,...e)}}A(ma,"LEVEL",0);class S0{constructor(){A(this,"logger",new ma("AudioMixer"));A(this,"audioContext",new AudioContext);A(this,"audioDestination",this.audioContext.createMediaStreamDestination());A(this,"audioTrack",Jc(this.audioDestination.stream));A(this,"sourceNodeMap",{})}get sourceNodeList(){return Object.values(this.sourceNodeMap).map(c=>c.sourceNode).filter(c=>!!c)}get gainNodeList(){return Object.values(this.sourceNodeMap).map(c=>c.gainNode).filter(c=>!!c)}get sourceCount(){return this.sourceNodeList.length}resume(){var c;return(c=this.audioContext)==null?void 0:c.resume()}addTrack(c){this.connectTrack(c)}hasTrack(c){return!!this.sourceNodeMap[c]}removeTrack(c){const{sourceNode:e,gainNode:t}=this.sourceNodeMap[c]||{};t==null||t.disconnect(),e==null||e.disconnect(),delete this.sourceNodeMap[c],e?this.logger.info("SourceNode disconnected. Active source node:",this.sourceNodeList.length):this.logger.warn(`SourceNode ${c} does not exit. Active source node: ${this.sourceNodeList.length}`)}getAudioTrack(){return this.audioTrack}setVolume(c,e){const{gainNode:t}=this.sourceNodeMap[e]||{};t?(this.logger.info(`Setting node(${e}) volume to ${this.scale(c)}`),t.gain.value=this.scale(c)):this.logger.warn(`GainNode ${e} does not exit.`)}reset(){this.disconnectSourceNode(),this.sourceNodeMap={}}dispose(){var c;this.reset(),(c=this.audioTrack)==null||c.stop(),this.audioDestination.disconnect(),this.audioContext.close()}connectTrack(c){if(!this.audioContext)return this.logger.warn("AudioContext not initialized");let e=new MediaStream;e.addTrack(c);const t=this.audioContext.createMediaStreamSource(e),r=this.audioContext.createGain();r.gain.value=1,t.connect(r),r.connect(this.audioDestination),this.sourceNodeMap[c.id]={track:c,sourceNode:t,gainNode:r},this.logger.info("New sourceNode connected. Active source node:",this.sourceNodeList.length)}disconnectSourceNode(){this.sourceNodeList.forEach(c=>c.disconnect()),this.gainNodeList.forEach(c=>c.disconnect())}scale(c){return c/100}}const _0=4;class y0 extends ei{constructor(){super("audioMixer",Ke.AliRtcSdkStreamTypeCapture,Ti.AUDIO);A(this,"audioMixer");A(this,"primaryAudioTrackId");A(this,"screenAudioTrackId");A(this,"dirty",!1);this.zIndex=8}get initOptions(){return{audio:1,screen:1}}setOptions(e){Object.entries(e).forEach(([t,r])=>{this.isValidVolume(r)&&(this.options[t]=r)}),this.dirty=!0,this.emit("updated")}isSupported(){return"AudioContext"in window}shouldUpdate(e,t){var n,a;if(e.type!==Ke.AliRtcSdkStreamTypeCapture)return!1;const r=t.find(o=>o.type===Ke.AliRtcSdkStreamTypeCapture),i=t.find(o=>o.type===Ke.AliRtcSdkStreamTypeScreen);return!(this.primaryAudioTrackId===((n=r==null?void 0:r.currentAudioTrack)==null?void 0:n.id)&&this.screenAudioTrackId===((a=i==null?void 0:i.currentAudioTrack)==null?void 0:a.id)&&!this.dirty)}process(e,t){return z(this,null,function*(){var a,o;this.dirty=!1;const r=t.find(u=>u.type===Ke.AliRtcSdkStreamTypeScreen),i=e.currentAudioTrack,n=r==null?void 0:r.currentAudioTrack;if(!n&&this.options.audio===1){this.audioMixer&&(this.audioMixer.dispose(),this.audioMixer=void 0),this.primaryAudioTrackId=i==null?void 0:i.id,e.updateAudioTrack(i);return}this.audioMixer||(this.audioMixer=new S0),yield this.audioMixer.resume(),this.primaryAudioTrackId&&(i==null?void 0:i.id)!==this.primaryAudioTrackId&&((a=this.audioMixer)==null||a.removeTrack(this.primaryAudioTrackId)),i&&!this.audioMixer.hasTrack(i==null?void 0:i.id)&&this.audioMixer.addTrack(i),this.primaryAudioTrackId=i==null?void 0:i.id,this.screenAudioTrackId&&(n==null?void 0:n.id)!==this.screenAudioTrackId&&((o=this.audioMixer)==null||o.removeTrack(this.screenAudioTrackId)),n&&!this.audioMixer.hasTrack(n==null?void 0:n.id)&&this.audioMixer.addTrack(n),this.screenAudioTrackId=n==null?void 0:n.id,this.updateVolume(),e.updateAudioTrack(this.audioMixer.getAudioTrack())})}isValidVolume(e){return e!==void 0&&e>=0&&e<=_0}updateVolume(){this.audioMixer&&(this.primaryAudioTrackId&&this.audioMixer.setVolume(this.options.audio*100,this.primaryAudioTrackId),this.screenAudioTrackId&&this.audioMixer.setVolume(this.options.screen*100,this.screenAudioTrackId))}clear(e){var t;(t=this.audioMixer)==null||t.dispose(),super.clear(e)}}class vs{constructor(c,e){A(this,"originTrack");A(this,"originVideo");A(this,"targetWidth");A(this,"targetHeight");A(this,"targetFrameRate");A(this,"targetCanvas");A(this,"animationFrameId");A(this,"resultTrack");this.targetWidth=e.width,this.targetHeight=e.height,this.targetFrameRate=e.frameRate,this.originTrack=c,this.originVideo=document.createElement("video"),this.originVideo.muted=!0,this.originVideo.autoplay=!0,this.originVideo.controls=!1,this.targetCanvas=document.createElement("canvas"),this.targetCanvas.width=this.targetWidth,this.targetCanvas.height=this.targetHeight}updateOptions(c){this.targetWidth=c.width,this.targetHeight=c.height,this.targetFrameRate=c.frameRate,this.targetCanvas.width=this.targetWidth,this.targetCanvas.height=this.targetHeight,this.resultTrack&&this.resultTrack.applyConstraints({frameRate:this.targetFrameRate})}dispose(){}getVideoTrack(){return this.resultTrack||(this.resultTrack=this.targetCanvas.captureStream().getVideoTracks()[0],this.resultTrack.applyConstraints({frameRate:this.targetFrameRate})),this.resultTrack}cancelAnimation(){this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=void 0)}getPositionAndSize(c,e,t,r){const i=e/c,n=r/t;let a=t,o=r,u=0,h=0;return n>i?(a=Math.round(o/i),u=Math.round((t-a)/2)):n<i&&(o=Math.round(a*i),h=Math.round((r-o)/2)),{x:u,y:h,width:a,height:o}}}class A0 extends vs{constructor(e,t){super(e,t);A(this,"targetCtx");this.targetCtx=this.targetCanvas.getContext("2d"),this.startRender=this.startRender.bind(this),this.stopRender=this.startRender.bind(this),this.initStream(e)}initStream(e){const t=new MediaStream;t.addTrack(e),this.originVideo.srcObject=t,this.originVideo.play(),this.originVideo.addEventListener("canplay",this.startRender),this.originVideo.addEventListener("pause",this.stopRender),this.originVideo.addEventListener("ended",this.stopRender)}startRender(){this.cancelAnimation();const e=()=>{if(!this.targetCtx)return;const t=this.getPositionAndSize(this.originVideo.videoWidth,this.originVideo.videoHeight,this.targetWidth,this.targetHeight);this.targetCtx.drawImage(this.originVideo,0,0,this.originVideo.videoWidth,this.originVideo.videoHeight,t.x,t.y,t.width,t.height),!this.originVideo.paused&&!this.originVideo.ended&&(this.animationFrameId=requestAnimationFrame(e))};e()}stopRender(){this.cancelAnimation()}dispose(){this.stopRender(),this.originVideo.removeEventListener("play",this.startRender),this.originVideo.removeEventListener("pause",this.stopRender),this.originVideo.removeEventListener("ended",this.stopRender),this.originVideo.pause(),this.originVideo.srcObject=null}}const E0=`
39
39
  attribute vec2 a_position;
40
40
  attribute vec2 a_texCoord;
41
41
 
@@ -3318,7 +3318,7 @@ declare class RtsManager extends default_2<RtsManagerEventListener> {
3318
3318
  getPublishAudioStats(streamUrl: string, msid?: string): Promise<unknown>;
3319
3319
  publishAdd(streamUrl: string, stream: LocalStream, callId: string, extra?: PublishExtraParams, isResume?: boolean, retryTimes?: number, waitSender?: boolean, reason?: PublishReason): Promise<string>;
3320
3320
  publishDelete(streamUrl: string, options: PublishOptions): Promise<string>;
3321
- publishReplace(streamUrl: string, stream: LocalStream, extra?: PublishExtraParams): Promise<string>;
3321
+ publishReplace(streamUrl: string, stream: LocalStream, extra?: PublishExtraParams): Promise<any>;
3322
3322
  publishStop(streamUrl: string): Promise<string>;
3323
3323
  unpublish(): Promise<void>;
3324
3324
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aliyun-rtc-sdk",
3
- "version": "6.11.8",
3
+ "version": "6.11.9-beta.0",
4
4
  "type": "module",
5
5
  "description": "rtc web sdk of aliyun",
6
6
  "main": "dist/aliyun-rtc-sdk.js",
@@ -9,7 +9,7 @@
9
9
  "@aliyun-sls/web-sts-plugin": "^0.3.5",
10
10
  "@aliyun-sls/web-track-browser": "^0.3.5",
11
11
  "aliyun-queen-engine": "^6.3.3",
12
- "aliyun-rts-sdk": "2.8.1-beta.5",
12
+ "aliyun-rts-sdk": "2.9.0",
13
13
  "crypto-js": "^4.1.1",
14
14
  "dateformat": "^5.0.3",
15
15
  "eventemitter3": "^5.0.1",