!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("AgoraSDK",[],t):"object"==typeof exports?exports.AgoraSDK=t():e.AgoraSDK=t()}(window,(function(){return function(e){var t={};function i(n){if(t[n])return t[n].exports;var r=t[n]={i:n,l:!1,exports:{}};return e[n].call(r.exports,r,r.exports,i),r.l=!0,r.exports}return i.m=e,i.c=t,i.d=function(e,t,n){i.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},i.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},i.t=function(e,t){if(1&t&&(e=i(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(i.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)i.d(n,r,function(t){return e[t]}.bind(null,r));return n},i.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return i.d(t,"a",t),t},i.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},i.p="",i(i.s=30)}([function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const s=r(i(27)),a=i(6),o=r(i(1)),l=i(2),u=i(3),h=()=>{};class c extends s.default{constructor(e,t){super(),this._state=y.RELAY_STATE_IDLE,this._onStatus=e=>{o.default.debug(`[${this.clientId}] ChannelMediaStatus: ${JSON.stringify(e)}`),e&&e.command&&("onAudioPacketReceived"===e.command&&this.emit("event",v.PACKET_RECEIVED_AUDIO_FROM_SRC),"onVideoPacketReceived"===e.command&&this.emit("event",v.PACKET_RECEIVED_VIDEO_FROM_SRC),"onSrcTokenPrivilegeDidExpire"===e.command&&(this._state=y.RELAY_STATE_FAILURE,this.emit("state",y.RELAY_STATE_FAILURE,E.SRC_TOKEN_EXPIRED)),"onDestTokenPrivilegeDidExpire"===e.command&&(this._state=y.RELAY_STATE_FAILURE,this.emit("state",y.RELAY_STATE_FAILURE,E.DEST_TOKEN_EXPIRED,e.channelName?{came:e.channelName}:null)))},this._onClose=()=>n(this,void 0,void 0,(function*(){if(o.default.debug(`[${this.clientId}] ChannelMediaSocket onClose`),this.emit("event",v.NETWORK_DISCONNECTED),this.state=y.RELAY_STATE_IDLE,this._prevChannelMediaConfig)try{yield this.startChannelMediaRelay(this._prevChannelMediaConfig)}catch(e){if(e instanceof p&&(e.message===f.WS_ABORT||e.message===f.AP_REQUEST_ABORT))return;this.emit("state",y.RELAY_STATE_FAILURE,E.SERVER_CONNECTION_LOST)}})),this.token=e.appId,this.appId=e.appId,this.cname=e.cname,this.uid=e.uid,this.sid=e.sid,this.clientId=t}set state(e){const t=this._state;this._state=e,t!==e&&this.emit("state",e)}get state(){return this._state}startChannelMediaRelay(e){return n(this,void 0,void 0,(function*(){if(this.state!==y.RELAY_STATE_IDLE)throw new p(f.BAD_STATE);this.state=y.RELAY_STATE_CONNECTING,yield this._connect(),o.default.debug(`[${this.clientId}] startChannelMediaRelay: connect success`),yield this._sendStartRelayMessage(e),this._prevChannelMediaConfig=e}))}updateChannelMediaRelay(e){return n(this,void 0,void 0,(function*(){if(this.state!==y.RELAY_STATE_RUNNING)throw new p(f.BAD_STATE);yield this._sendUpdateMessage(e),this._prevChannelMediaConfig=e}))}stopChannelMediaRelay(){return n(this,void 0,void 0,(function*(){yield this._sendStopRelayMessage(),o.default.debug(`[${this.clientId}] stopChannelMediaRelay: send stop message success`),this.state=y.RELAY_STATE_IDLE,this.dispose()}))}dispose(){o.default.debug(`[${this.clientId}] disposeChannelMediaRelay`),this.state=y.RELAY_STATE_IDLE,this.emit("dispose"),this._signal&&this._signal.dispose(),this._prevChannelMediaConfig=null,this.removeEvent()}_requestOneAP(e){return new Promise(((t,i)=>{const n={command:"convergeAllocateEdge",sid:this.sid,appId:this.appId,token:"",ts:+new Date,version:a.VERSION,cname:this.cname,uid:this.uid+"",seq:1,requestId:1},r={service_name:"tele_channel",json_body:JSON.stringify(n)},s="https://"+e;wx.request({url:s,data:r,header:{"content-type":"application/json","X-Packet-Service-Type":0,"X-Packet-URI":61},method:"POST",success:e=>{let n=null,r=null;try{n=e.data}catch(e){i(new p(f.AP_JSON_PARSE_ERROR,e))}0!==n.code&&i(new p(f.AP_REQUEST_ERROR,n));try{r=JSON.parse(n.json_body)}catch(e){i(new p(f.AP_JSON_PARSE_ERROR,e))}200!==r.code&&i(new p(f.AP_REQUEST_ERROR,r)),r.servers?t(r.servers):i(new p(f.AP_JSON_PARSE_ERROR,r))},fail:e=>i(e)})}))}_requestAP(){const e=["uap-ap-web-1.agora.io","uap-ap-web-2.agoraio.cn","uap-ap-web-3.agora.io","uap-ap-web-4.agoraio.cn"];return new Promise(((t,i)=>{setTimeout((()=>{i(new p(f.AP_REQUEST_TIMEOUT))}),3e3),this.on("dispose",(()=>{i(new p(f.AP_REQUEST_ABORT))})),e.forEach((e=>{e+="/api/v1",this._requestOneAP(e).then((i=>{o.default.debug(`[${this.clientId}] startChannelMediaRelay request AP ${e} success: ${JSON.stringify(i)}`);const n=i[0];let r=(e=n.address).split("."),s=r.length;const a=`wss://miniapp.agoraio.cn/${r[s-4]}-${r[s-3]}-${r[s-2]}-${r[s-1]}-${n.ws}/`;t(a)})).catch((t=>{o.default.debug(`[${this.clientId}] startChannelMediaRelay request AP ${e} failed: ${JSON.stringify(t)}`)}))}))}))}_connectWebsocket(e){return this._signal=new d(this.appId,this.cname,this.uid,this.sid),this._signal.connect(e)}_connect(){return n(this,void 0,void 0,(function*(){const e=yield this._requestAP();yield this._connectWebsocket(e),this._signal.on("close",this._onClose.bind(this)),this._signal.on("status",this._onStatus.bind(this)),this.emit("event",v.NETWORK_CONNECTED)}))}_sendStartRelayMessage(e){return n(this,void 0,void 0,(function*(){this._checkSignal();const t=this._genMessage(T.StopPacketTransfer);yield Promise.all([this._signal.request(t),this._signal.waitStatus("Normal Quit")]),o.default.debug(`[${this.clientId}] startChannelMediaRelay: StopPacketTransfer success`);const i=this._genMessage(T.SetSdkProfile,e);yield this._signal.request(i),o.default.debug(`[${this.clientId}] startChannelMediaRelay: SetSdkProfile success`);const n=this._genMessage(T.SetSourceChannel,e);yield Promise.all([this._signal.request(n),this._signal.waitStatus("SetSourceChannelStatus")]),this.emit("event",v.PACKET_JOINED_SRC_CHANNEL),o.default.debug(`[${this.clientId}] startChannelMediaRelay: SetSourceChannel success`);const r=this._genMessage(T.SetSourceUserId,e);yield this._signal.request(r),o.default.debug(`[${this.clientId}] startChannelMediaRelay: SetSourceUserId success`);const s=this._genMessage(T.SetDestChannel,e);yield Promise.all([this._signal.request(s),this._signal.waitStatus("SetDestChannelStatus")]),this.emit("event",v.PACKET_JOINED_DEST_CHANNEL),o.default.debug(`[${this.clientId}] startChannelMediaRelay: SetDestChannel success`);const a=this._genMessage(T.StartPacketTransfer,e);yield this._signal.request(a),this.emit("event",v.PACKET_SENT_TO_DEST_CHANNEL),this.state=y.RELAY_STATE_RUNNING,o.default.debug(`[${this.clientId}] startChannelMediaRelay: StartPacketTransfer success`)}))}_sendReconnectMessage(e){return n(this,void 0,void 0,(function*(){this._checkSignal();const t=this._genMessage(T.Reconnect,e);yield this._signal.request(t)}))}_sendUpdateMessage(e){return n(this,void 0,void 0,(function*(){this._checkSignal();const t=this._genMessage(T.UpdateDestChannel,e);yield this._signal.request(t),this.emit("event",v.PACKET_UPDATE_DEST_CHANNEL),o.default.debug(`[${this.clientId}] sendUpdateMessage: UpdateDestChannel success`)}))}_sendStopRelayMessage(){return n(this,void 0,void 0,(function*(){this._checkSignal();const e=this._genMessage(T.StopPacketTransfer);yield this._signal.request(e),o.default.debug(`[${this.clientId}] sendStopRelayMessage: StopPacketTransfer success`)}))}_genMessage(e,t){const i=[],n=[],r=[],s={appId:this.appId,cname:this.cname,uid:this.uid+"",sdkVersion:a.VERSION,sid:this.sid,ts:+new Date,requestId:0,seq:0,allocate:!0,clientRequest:{}};let o=null,l=null;switch(e){case T.SetSdkProfile:return s.clientRequest={command:"SetSdkProfile",type:"multi_channel"},s;case T.SetSourceChannel:return l=t.getSrcChannelMediaInfo(),s.clientRequest={command:"SetSourceChannel",uid:l.uid+"",channelName:l.channelName,token:l.token||this.appId},s;case T.SetSourceUserId:return l=t.getSrcChannelMediaInfo(),s.clientRequest={command:"SetSourceUserId",uid:this.uid+""},s;case T.SetDestChannel:return o=t.getDestChannelMediaInfos(),o.forEach((e=>{i.push(e.channelName),n.push(e.uid+""),r.push(e.token||this.appId)})),s.clientRequest={command:"SetDestChannel",channelName:i,uid:n,token:r},s;case T.StartPacketTransfer:return s.clientRequest={command:"StartPacketTransfer"},s;case T.Reconnect:return s.clientRequest={command:"Reconnect"},s;case T.StopPacketTransfer:return s.clientRequest={command:"StopPacketTransfer"},s;case T.UpdateDestChannel:return o=t.getDestChannelMediaInfos(),o.forEach((e=>{i.push(e.channelName),n.push(e.uid+""),r.push(e.token||this.appId)})),s.clientRequest={command:"UpdateDestChannel",channelName:i,uid:n,token:r},s}}_checkSignal(){if(!this._signal||!this._signal.isConnect())throw new p(f.WS_DISCONNECTED)}}t.default=c,t.ChannelMediaRelayConfiguration=class{constructor(){this.destChannelMediaInfos=new Map}setSrcChannelInfo(e){l.checkValidObject(e,"srcInfo");const{uid:t,channelName:i,token:n}=e;if(n&&!l.isValidToken(n))throw new Error("Invalid token in SrcChannelInfo");if(!l.isValidChannelName(i))throw new Error("Invalid channelName in SrcChannelInfo");if(!u.is32Uint(t))throw new Error("Invalid uid in SrcChannelInfo");o.default.debug("[setSrcChannelInfo]: srcInfo: ",e),this.srcChannelMediaInfo=e}setDestChannelInfo(e,t){if(!l.isValidChannelName(e))throw new Error("Invalid channelName in DestChannelInfo");l.checkValidObject(t,"destInfo");const{uid:i,token:n}=t,r=t.channelName;if(n&&!l.isValidToken(n))throw new Error("Invalid token in DestChannelInfo");if(!l.isValidChannelName(r))throw new Error("Invalid channelName in DestChannelInfo");if(!u.is32Uint(i))throw new Error("Invalid uid in DestChannelInfo");o.default.debug("[setDestChannelInfo]: destInfo: ",t,"channelName: ",e),this.destChannelMediaInfos.set(e,t)}removeDestChannelInfo(e){if(!l.isValidChannelName(e))throw new Error("Invalid channelName when invoke removeDestChannelInfo");o.default.debug("[removeDestChannelInfo]: channelName: ",e),this.destChannelMediaInfos.delete(e)}getSrcChannelMediaInfo(){return this.srcChannelMediaInfo}getDestChannelMediaInfos(){return this.destChannelMediaInfos}};class d extends s.default{constructor(e,t,i,n){super(),this._onOpen=()=>{o.default.debug("[ChannelMediaRelay] onOpen"),this.emit("open")},this._onClose=e=>{o.default.debug("[ChannelMediaRelay] onClose"),this.emit("close"),this.dispose()},this._onMessage=e=>{o.default.blind("ChannelMediaRelay receive message",e);const t=JSON.parse(e.data);if(!t||"serverResponse"!==t.command||!t.requestId)return t&&"serverStatus"===t.command&&t.serverStatus&&t.serverStatus.command?(this.emit("status",t.serverStatus),void this.emit(t.serverStatus.command,t.serverStatus)):void 0;this.emit("req_"+t.requestId,t)},this._requestId=1,this.appId=e,this.cname=t,this.uid=i,this.sid=n}isConnect(){return this._ws&&1===this._ws.readyState}sendMessage(e){if(!this._ws||1!==this._ws.readyState)throw new p(f.WS_DISCONNECTED);const t=this._requestId++;return e.requestId=t,e.seq=t,this._ws.send({data:JSON.stringify(e)}),t}waitStatus(e){return new Promise(((t,i)=>{const n=setTimeout((()=>{i(new p(f.WAIT_STATUS_TIMEOUT,e))}),5e3);this.once(e,(r=>{clearTimeout(n),r.state&&0!==r.state?i(new p(f.WAIT_STATUS_ERROR,e)):t()})),this.once("dispose",(()=>{clearTimeout(n),i(new p(f.WS_ABORT))}))}))}request(e){return new Promise(((t,i)=>{const n=this.sendMessage(e),r=setTimeout((()=>{this.removeAllListeners("req_"+n),i(new p(f.REQUEST_TIMEOUT))}),3e3);this.once("req_"+n,(e=>{clearTimeout(r),e&&200===e.code?t(e):i(new p(f.REQUEST_FAILED,e))})),this.once("dispose",(()=>{clearTimeout(r),i(new p(f.WS_ABORT))}))}))}connect(e){return new Promise(((t,i)=>{this._ws=wx.connectSocket({url:e}),this._ws.onOpen(((i,n)=>{o.default.debug("[ChannelMediaRelay] ws.onOpen"),this._onOpen(),this._prvUrl=e,this._ws.onMessage(this._onMessage),this._ws.onClose(this._onClose),this._startHeartBeatCheck(),t()})),this._ws.onClose((e=>{o.default.debug("[ChannelMediaRelay] ws.onClose",e),this.dispose(),i(new p(f.CONNECT_FAILED,"websocket error code: "+e.code))})),setTimeout((()=>{this._ws&&1!==this._ws.readyState&&(this._ws.onMessage(h),this._ws.onClose(h),this._ws.close(),this._ws=null,i(new p(f.CONNECT_TIMEOUT)))}),5e3),this.once("dispose",(()=>{i(new p(f.WS_ABORT))}))}))}dispose(){o.default.debug("[ChannelMediaRelay] dispose"),this._clearHeartBeatCheck(),this.emit("dispose"),this.removeEvent(),this._ws&&(this._ws.onOpen(h),this._ws.onClose(h),this._ws.onMessage(h),this._ws.close(h)),this._ws=null}_sendPing(e){if(!this._ws||1!==this._ws.readyState)throw new p(f.WS_DISCONNECTED);const t=this._requestId++;return e.requestId=t,this._ws.send({data:JSON.stringify(e)}),t}_startHeartBeatCheck(){this._heartBeatTimer=setInterval((()=>{this._sendPing({command:"ping",appId:this.appId,cname:this.cname,uid:this.uid+"",sid:this.sid,ts:+new Date,requestId:0})}),3e3)}_clearHeartBeatCheck(){clearInterval(this._heartBeatTimer)}}class p{constructor(e="",t,i){this.code=i,this.data=t,this.message=e}}var f,T,v,y,E;t.ChannelMediaError=p,function(e){e.CONNECT_FAILED="connect failed",e.CONNECT_TIMEOUT="connect timeout",e.WS_DISCONNECTED="websocket disconnected",e.REQUEST_TIMEOUT="request timeout",e.REQUEST_FAILED="request failed",e.WAIT_STATUS_TIMEOUT="wait status timeout",e.WAIT_STATUS_ERROR="wait status error",e.BAD_STATE="bad state",e.WS_ABORT="ws abort",e.AP_REQUEST_TIMEOUT="AP request timeout",e.AP_JSON_PARSE_ERROR="AP json parse error",e.AP_REQUEST_ERROR="AP request error",e.AP_REQUEST_ABORT="AP request abort"}(f=t.CHANNEL_MEDIA_ERROR||(t.CHANNEL_MEDIA_ERROR={})),function(e){e[e.SetSdkProfile=0]="SetSdkProfile",e[e.SetSourceChannel=1]="SetSourceChannel",e[e.SetSourceUserId=2]="SetSourceUserId",e[e.SetDestChannel=3]="SetDestChannel",e[e.StartPacketTransfer=4]="StartPacketTransfer",e[e.StopPacketTransfer=5]="StopPacketTransfer",e[e.UpdateDestChannel=6]="UpdateDestChannel",e[e.Reconnect=7]="Reconnect",e[e.SetVideoProfile=8]="SetVideoProfile"}(T||(T={})),function(e){e[e.NETWORK_DISCONNECTED=0]="NETWORK_DISCONNECTED",e[e.NETWORK_CONNECTED=1]="NETWORK_CONNECTED",e[e.PACKET_JOINED_SRC_CHANNEL=2]="PACKET_JOINED_SRC_CHANNEL",e[e.PACKET_JOINED_DEST_CHANNEL=3]="PACKET_JOINED_DEST_CHANNEL",e[e.PACKET_SENT_TO_DEST_CHANNEL=4]="PACKET_SENT_TO_DEST_CHANNEL",e[e.PACKET_RECEIVED_VIDEO_FROM_SRC=5]="PACKET_RECEIVED_VIDEO_FROM_SRC",e[e.PACKET_RECEIVED_AUDIO_FROM_SRC=6]="PACKET_RECEIVED_AUDIO_FROM_SRC",e[e.PACKET_UPDATE_DEST_CHANNEL=7]="PACKET_UPDATE_DEST_CHANNEL",e[e.PACKET_UPDATE_DEST_CHANNEL_REFUSED=8]="PACKET_UPDATE_DEST_CHANNEL_REFUSED",e[e.PACKET_UPDATE_DEST_CHANNEL_NOT_CHANGE=9]="PACKET_UPDATE_DEST_CHANNEL_NOT_CHANGE"}(v=t.CHANNEL_MEDIA_RELAY_EVENT||(t.CHANNEL_MEDIA_RELAY_EVENT={})),function(e){e[e.RELAY_STATE_IDLE=0]="RELAY_STATE_IDLE",e[e.RELAY_STATE_CONNECTING=1]="RELAY_STATE_CONNECTING",e[e.RELAY_STATE_RUNNING=2]="RELAY_STATE_RUNNING",e[e.RELAY_STATE_FAILURE=3]="RELAY_STATE_FAILURE"}(y=t.CHANNEL_MEDIA_RELAY_STATE||(t.CHANNEL_MEDIA_RELAY_STATE={})),function(e){e[e.RELAY_OK=0]="RELAY_OK",e[e.SERVER_ERROR_RESPONSE=1]="SERVER_ERROR_RESPONSE",e[e.SERVER_NO_RESPONSE=2]="SERVER_NO_RESPONSE",e[e.NO_RESOURCE_AVAILABLE=3]="NO_RESOURCE_AVAILABLE",e[e.FAILED_JOIN_SRC=4]="FAILED_JOIN_SRC",e[e.FAILED_JOIN_DEST=5]="FAILED_JOIN_DEST",e[e.FAILED_PACKET_RECEIVED_FROM_SRC=6]="FAILED_PACKET_RECEIVED_FROM_SRC",e[e.FAILED_PACKET_SENT_TO_DEST=7]="FAILED_PACKET_SENT_TO_DEST",e[e.SERVER_CONNECTION_LOST=8]="SERVER_CONNECTION_LOST",e[e.INTERNAL_ERROR=9]="INTERNAL_ERROR",e[e.SRC_TOKEN_EXPIRED=10]="SRC_TOKEN_EXPIRED",e[e.DEST_TOKEN_EXPIRED=11]="DEST_TOKEN_EXPIRED",e[e.RELAY_ALREADY_START=12]="RELAY_ALREADY_START",e[e.RELAY_NOT_START=13]="RELAY_NOT_START",e[e.OPERATION_ABORT=14]="OPERATION_ABORT"}(E=t.CHANNEL_MEDIA_RELAY_ERROR||(t.CHANNEL_MEDIA_RELAY_ERROR={}))},function(e,t,i){"use strict";i.r(t),i.d(t,"Log",(function(){return u}));var n=i(9),r=i.n(n),s=i(4),a=i.n(s),o=i(5),l=i.n(o),u=function(){function e(){a()(this,e),this.level=3,this.onLog=null}return l()(e,[{key:"setLogLevel",value:function(e){if("number"!=typeof e||!(e<=4&&e>=-1))throw Error("Invaild level");this.level=e}},{key:"log",value:function(){var e,t=Array.prototype.slice.call(arguments);this.onLog&&this.onLog(JSON.stringify(t)),(e=console).log.apply(e,r()(t))}},{key:"error",value:function(){var e,t=Array.prototype.slice.call(arguments);this.onLog&&this.onLog(JSON.stringify(t)),(e=console).error.apply(e,r()(t))}},{key:"blind",value:function(){var e=Array.prototype.slice.call(arguments);this.level<=-1&&this.log.apply(this,["".concat(new Date," [BLIND]: ")].concat(r()(e)))}},{key:"debug",value:function(){var e=Array.prototype.slice.call(arguments);this.level<=0&&this.log.apply(this,["".concat(new Date," [DEBUG]: ")].concat(r()(e)))}},{key:"info",value:function(e){this.level<=1&&this.log("".concat(new Date," [INFO]: ").concat(e))}},{key:"warn",value:function(e){this.level<=2&&this.log("".concat(new Date," [WARN]: ").concat(e))}},{key:"error",value:function(e){this.level<=3&&this.error("".concat(new Date," [ERROR]: ").concat(e))}}]),e}(),h=new u;t.default=h},function(e,t,i){"use strict";i.r(t),i.d(t,"checkValidObject",(function(){return a})),i.d(t,"checkValidString",(function(){return o})),i.d(t,"checkValidNumber",(function(){return l})),i.d(t,"checkValidFloatNumber",(function(){return u})),i.d(t,"checkValidBoolean",(function(){return h})),i.d(t,"checkValidEnum",(function(){return s})),i.d(t,"isValidString",(function(){return c})),i.d(t,"isValidNumber",(function(){return d})),i.d(t,"isValidBoolean",(function(){return f})),i.d(t,"isASCII",(function(){return y})),i.d(t,"isInteger",(function(){return E})),i.d(t,"isNumber",(function(){return S})),i.d(t,"isString",(function(){return g})),i.d(t,"isArray",(function(){return w})),i.d(t,"isEmpty",(function(){return m})),i.d(t,"isValidToken",(function(){return T})),i.d(t,"isValidChannelName",(function(){return v}));var n=i(16),r=i.n(n),s=function(e,t,i){for(var n=0;n=t&&e.length<=i},d=function(e,t,i){return E(e)&&e>=t&&e<=i},p=function(e,t,i){return S(e)&&e>=t&&e<=i},f=function(e){return"boolean"==typeof e},T=function(e){return c(e,1,2047)},v=function(e){return g(e)&&/^[a-zA-Z0-9 \!\#\$\%\&\(\)\+\-\:\;\<\=\.\>\?\@\[\]\^\_\{\}\|\~\,]{1,64}$/.test(e)},y=function(e){if("string"==typeof e){for(var t=0;t255)return!1}return!0}},E=function(e){return"number"==typeof e&&e%1==0},S=function(e){return"number"==typeof e},g=function(e){return"string"==typeof e},w=function(e){return e instanceof Array},m=function(e){return null==e}},function(e,t,i){"use strict";i.r(t),i.d(t,"generateSessionId",(function(){return a})),i.d(t,"shouldUseHttps",(function(){return o})),i.d(t,"random",(function(){return s})),i.d(t,"isWeiXin",(function(){return l})),i.d(t,"is32Uint",(function(){return u}));var n=i(15),r=i.n(n),s=function(e){isNaN(e)&&(e=1e3);var t=+new Date,i=(t=(9301*t+49297)%233280)/233280;return Math.ceil(i*e)},a=function(){return r()().replace(/-/g,"").toUpperCase()},o=function(){return"https:"==document.location.protocol},l=function(){try{return wx,!0}catch(e){return!1}},u=function(e){return!!(0<=e&&e<=4294967295)}},function(e,t){e.exports=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}},function(e,t){function i(e,t){for(var i=0;i0&&(this.send_pending.forEach((function(t){var i;this.socket.send(t.buf),this.callbacks.push((i=t.cb,function(t){e.setRecvBuffer(t),i()}))})),this.send_pending=[])},__onClose:function(e){this.__reset(this.url)},__onMessage:function(e){this.callbacks.length&&this.callbacks.shift()(e.data)},__onError:function(e){console.log("Thrift WebSocket Error: "+e.toString()),this.socket.close()},setRecvBuffer:function(e){this.recv_buf=e,this.recv_buf_sz=this.recv_buf.length,this.wpos=this.recv_buf.length,this.rpos=0},isOpen:function(){return this.socket&&this.socket.readyState==this.socket.OPEN},open:function(){this.socket&&this.socket.readyState!=this.socket.CLOSED||(this.socket=new WebSocket(this.url),this.socket.onopen=this.__onOpen.bind(this),this.socket.onmessage=this.__onMessage.bind(this),this.socket.onerror=this.__onError.bind(this),this.socket.onclose=this.__onClose.bind(this))},close:function(){this.socket.close()},read:function(e){var t=this.wpos-this.rpos;if(0===t)return"";var i=e;te+1;){var r=this.tstack.pop(),s=this.tstack.pop();n?n=!1:i=","+i,isNaN(s)||(s='"'+s+'"'),i=s+":"+r+i}i="{"+i,this.tstack[e].push(i),this.tstack[e]="["+this.tstack[e].join(",")+"]"}},writeListBegin:function(e,t){this.tpos.push(this.tstack.length),this.tstack.push([Thrift.Protocol.Type[e],t])},writeListEnd:function(){for(var e=this.tpos.pop();this.tstack.length>e+1;){var t=this.tstack[e+1];this.tstack.splice(e+1,1),this.tstack[e].push(t)}this.tstack[e]="["+this.tstack[e].join(",")+"]"},writeSetBegin:function(e,t){this.tpos.push(this.tstack.length),this.tstack.push([Thrift.Protocol.Type[e],t])},writeSetEnd:function(){for(var e=this.tpos.pop();this.tstack.length>e+1;){var t=this.tstack[e+1];this.tstack.splice(e+1,1),this.tstack[e].push(t)}this.tstack[e]="["+this.tstack[e].join(",")+"]"},writeBool:function(e){this.tstack.push(e?1:0)},writeByte:function(e){this.tstack.push(e)},writeI16:function(e){this.tstack.push(e)},writeI32:function(e){this.tstack.push(e)},writeI64:function(e){this.tstack.push(e)},writeDouble:function(e){this.tstack.push(e)},writeString:function(e){if(null===e)this.tstack.push(null);else{for(var t="",i=0;ie;)this.rstack.pop()},readMapBegin:function(){var e=this.rstack.pop(),t=e.shift();t instanceof Array&&(this.rstack.push(e),t=(e=t).shift());var i={};return i.ktype=Thrift.Protocol.RType[t],i.vtype=Thrift.Protocol.RType[e.shift()],i.size=e.shift(),this.rpos.push(this.rstack.length),this.rstack.push(e.shift()),i},readMapEnd:function(){this.readFieldEnd()},readListBegin:function(){var e=this.rstack[this.rstack.length-1],t={};return t.etype=Thrift.Protocol.RType[e.shift()],t.size=e.shift(),this.rpos.push(this.rstack.length),this.rstack.push(e.shift()),t},readListEnd:function(){this.readFieldEnd()},readSetBegin:function(e,t){return this.readListBegin(e,t)},readSetEnd:function(){return this.readListEnd()},readBool:function(){var e=this.readI32();return null!==e&&"1"==e.value?e.value=!0:e.value=!1,e},readByte:function(){return this.readI32()},readI16:function(){return this.readI32()},readI32:function(e){void 0===e&&(e=this.rstack[this.rstack.length-1]);var t={};if(e instanceof Array)0===e.length?t.value=void 0:t.value=e.shift();else if(e instanceof Object){for(var i in e)if(null!==i){this.rstack.push(e[i]),delete e[i],t.value=i;break}}else t.value=e,this.rstack.pop();return t},readI64:function(){return this.readI32()},readDouble:function(){return this.readI32()},readString:function(){return this.readI32()},readBinary:function(){var e=this.readI32();return e.value=atob(e.value),e},skip:function(e){var t,i;switch(e){case Thrift.Type.STOP:return null;case Thrift.Type.BOOL:return this.readBool();case Thrift.Type.BYTE:return this.readByte();case Thrift.Type.I16:return this.readI16();case Thrift.Type.I32:return this.readI32();case Thrift.Type.I64:return this.readI64();case Thrift.Type.DOUBLE:return this.readDouble();case Thrift.Type.STRING:return this.readString();case Thrift.Type.STRUCT:for(this.readStructBegin();(t=this.readFieldBegin()).ftype!=Thrift.Type.STOP;)this.skip(t.ftype),this.readFieldEnd();return this.readStructEnd(),null;case Thrift.Type.MAP:for(t=this.readMapBegin(),i=0;i0&&this.rstack.length>this.rpos[this.rpos.length-1]+1&&this.rstack.pop(),this.skip(t.ktype),this.skip(t.vtype);return this.readMapEnd(),null;case Thrift.Type.SET:for(t=this.readSetBegin(),i=0;ie.length)&&(t=e.length);for(var i=0,n=new Array(t);i>>((3&t)<<3)&255;return r}}},function(e,t){for(var i=[],n=0;n<256;++n)i[n]=(n+256).toString(16).substr(1);e.exports=function(e,t){var n=t||0,r=i;return[r[e[n++]],r[e[n++]],r[e[n++]],r[e[n++]],"-",r[e[n++]],r[e[n++]],"-",r[e[n++]],r[e[n++]],"-",r[e[n++]],r[e[n++]],"-",r[e[n++]],r[e[n++]],r[e[n++]],r[e[n++]],r[e[n++]],r[e[n++]]].join("")}},function(e,t,i){var n=function(e){"use strict";var t=Object.prototype,i=t.hasOwnProperty,n="function"==typeof Symbol?Symbol:{},r=n.iterator||"@@iterator",s=n.asyncIterator||"@@asyncIterator",a=n.toStringTag||"@@toStringTag";function o(e,t,i,n){var r=t&&t.prototype instanceof h?t:h,s=Object.create(r.prototype),a=new m(n||[]);return s._invoke=function(e,t,i){var n="suspendedStart";return function(r,s){if("executing"===n)throw new Error("Generator is already running");if("completed"===n){if("throw"===r)throw s;return{value:void 0,done:!0}}for(i.method=r,i.arg=s;;){var a=i.delegate;if(a){var o=S(a,i);if(o){if(o===u)continue;return o}}if("next"===i.method)i.sent=i._sent=i.arg;else if("throw"===i.method){if("suspendedStart"===n)throw n="completed",i.arg;i.dispatchException(i.arg)}else"return"===i.method&&i.abrupt("return",i.arg);n="executing";var h=l(e,t,i);if("normal"===h.type){if(n=i.done?"completed":"suspendedYield",h.arg===u)continue;return{value:h.arg,done:i.done}}"throw"===h.type&&(n="completed",i.method="throw",i.arg=h.arg)}}}(e,i,a),s}function l(e,t,i){try{return{type:"normal",arg:e.call(t,i)}}catch(e){return{type:"throw",arg:e}}}e.wrap=o;var u={};function h(){}function c(){}function d(){}var p={};p[r]=function(){return this};var f=Object.getPrototypeOf,T=f&&f(f(_([])));T&&T!==t&&i.call(T,r)&&(p=T);var v=d.prototype=h.prototype=Object.create(p);function y(e){["next","throw","return"].forEach((function(t){e[t]=function(e){return this._invoke(t,e)}}))}function E(e,t){var n;this._invoke=function(r,s){function a(){return new t((function(n,a){!function n(r,s,a,o){var u=l(e[r],e,s);if("throw"!==u.type){var h=u.arg,c=h.value;return c&&"object"==typeof c&&i.call(c,"__await")?t.resolve(c.__await).then((function(e){n("next",e,a,o)}),(function(e){n("throw",e,a,o)})):t.resolve(c).then((function(e){h.value=e,a(h)}),(function(e){return n("throw",e,a,o)}))}o(u.arg)}(r,s,n,a)}))}return n=n?n.then(a,a):a()}}function S(e,t){var i=e.iterator[t.method];if(void 0===i){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=void 0,S(e,t),"throw"===t.method))return u;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method")}return u}var n=l(i,e.iterator,t.arg);if("throw"===n.type)return t.method="throw",t.arg=n.arg,t.delegate=null,u;var r=n.arg;return r?r.done?(t[e.resultName]=r.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,u):r:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,u)}function g(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function w(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function m(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(g,this),this.reset(!0)}function _(e){if(e){var t=e[r];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var n=-1,s=function t(){for(;++n=0;--r){var s=this.tryEntries[r],a=s.completion;if("root"===s.tryLoc)return n("end");if(s.tryLoc<=this.prev){var o=i.call(s,"catchLoc"),l=i.call(s,"finallyLoc");if(o&&l){if(this.prev=0;--n){var r=this.tryEntries[n];if(r.tryLoc<=this.prev&&i.call(r,"finallyLoc")&&this.prev=0;--t){var i=this.tryEntries[t];if(i.finallyLoc===e)return this.complete(i.completion,i.afterLoc),w(i),u}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var i=this.tryEntries[t];if(i.tryLoc===e){var n=i.completion;if("throw"===n.type){var r=n.arg;w(i)}return r}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,i){return this.delegate={iterator:_(e),resultName:t,nextLoc:i},"next"===this.method&&(this.arg=void 0),u}},e}(e.exports);try{regeneratorRuntime=n}catch(e){Function("r","regeneratorRuntime = r")(n)}},function(e,t,i){var n=i(11);e.exports=function(e){if(Array.isArray(e))return n(e)}},function(e,t){e.exports=function(e){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e))return Array.from(e)}},function(e,t,i){var n=i(11);e.exports=function(e,t){if(e){if("string"==typeof e)return n(e,t);var i=Object.prototype.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?n(e,t):void 0}}},function(e,t){e.exports=function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}},function(e,t,i){(function(e){var n=void 0!==e&&e||"undefined"!=typeof self&&self||window,r=Function.prototype.apply;function s(e,t){this._id=e,this._clearFn=t}t.setTimeout=function(){return new s(r.call(setTimeout,n,arguments),clearTimeout)},t.setInterval=function(){return new s(r.call(setInterval,n,arguments),clearInterval)},t.clearTimeout=t.clearInterval=function(e){e&&e.close()},s.prototype.unref=s.prototype.ref=function(){},s.prototype.close=function(){this._clearFn.call(n,this._id)},t.enroll=function(e,t){clearTimeout(e._idleTimeoutId),e._idleTimeout=t},t.unenroll=function(e){clearTimeout(e._idleTimeoutId),e._idleTimeout=-1},t._unrefActive=t.active=function(e){clearTimeout(e._idleTimeoutId);var t=e._idleTimeout;t>=0&&(e._idleTimeoutId=setTimeout((function(){e._onTimeout&&e._onTimeout()}),t))},i(25),t.setImmediate="undefined"!=typeof self&&self.setImmediate||void 0!==e&&e.setImmediate||this&&this.setImmediate,t.clearImmediate="undefined"!=typeof self&&self.clearImmediate||void 0!==e&&e.clearImmediate||this&&this.clearImmediate}).call(this,i(12))},function(e,t,i){(function(e,t){!function(e,i){"use strict";if(!e.setImmediate){var n,r,s,a,o,l=1,u={},h=!1,c=e.document,d=Object.getPrototypeOf&&Object.getPrototypeOf(e);d=d&&d.setTimeout?d:e,"[object process]"==={}.toString.call(e.process)?n=function(e){t.nextTick((function(){f(e)}))}:function(){if(e.postMessage&&!e.importScripts){var t=!0,i=e.onmessage;return e.onmessage=function(){t=!1},e.postMessage("","*"),e.onmessage=i,t}}()?(a="setImmediate$"+Math.random()+"$",o=function(t){t.source===e&&"string"==typeof t.data&&0===t.data.indexOf(a)&&f(+t.data.slice(a.length))},e.addEventListener?e.addEventListener("message",o,!1):e.attachEvent("onmessage",o),n=function(t){e.postMessage(a+t,"*")}):e.MessageChannel?((s=new MessageChannel).port1.onmessage=function(e){f(e.data)},n=function(e){s.port2.postMessage(e)}):c&&"onreadystatechange"in c.createElement("script")?(r=c.documentElement,n=function(e){var t=c.createElement("script");t.onreadystatechange=function(){f(e),t.onreadystatechange=null,r.removeChild(t),t=null},r.appendChild(t)}):n=function(e){setTimeout(f,0,e)},d.setImmediate=function(e){"function"!=typeof e&&(e=new Function(""+e));for(var t=new Array(arguments.length-1),i=0;i1)for(var i=1;i>>0,1)},emit:function(t,i){(e[t]||[]).slice().map((function(e){e(i)})),(e["*"]||[]).slice().map((function(e){e(t,i)}))}}},T=(i(24),["https://miniapp-1.agoraio.cn/appcenter/1-1-1/getWorkerManager/","https://miniapp-2.agoraio.cn/appcenter/1-1-1/getWorkerManager/","https://miniapp-3.agoraio.cn/appcenter/1-1-1/getWorkerManager/","https://miniapp-4.agoraio.cn/appcenter/1-1-1/getWorkerManager/"]),v=function(){function e(t,i){r()(this,e),this.serverlist=[],this.option=t,this.index=0,this.isInit=!0,this.state="disconnected",this.hasInvokeClose=!1,this.emitter=i,this.on=this.emitter.on,this.off=this.emitter.off,this.emit=this.emitter.emit}return a()(e,[{key:"connect",value:function(){var e=this;"disconnected"!==this.state&&this.close(),function(e){var t=e.reportManager,i={command:"convergeAllocateEdge",sid:e.sid,appId:e.appId,token:e.appId,uid:e.uid+"",cname:e.channel,ts:Math.floor(Date.now()/1e3),version:l.VERSION,seq:0,requestId:1};return new Promise((function(n,r){var s=0,a=function(i,n){try{t.report("chooseServer",{header:{sid:e.sid,cname:e.channel,uid:e.uid,success:!1},body:{csurl:n,ec:JSON.stringify(i)}})}catch(e){}4==++s&&r(i)};T.map((function(r,s){var o;o=T[s],wx.request({url:o,data:i,header:{"content-type":"application/json"},method:"POST",success:function(i){var r=i.data;if(p.default.debug("From choose server",i),200!==r.code)a({code:901,reason:r.error||"choose server fail"},o);else{var s=function(e){return e.map((function(e){var t=(e=e.address).split("."),i=t.length;return"wss://miniapp.agoraio.cn/".concat(t[i-4],"-").concat(t[i-3],"-").concat(t[i-2],"-").concat(t[i-1],"/api")}))}(r.servers);t.report("chooseServer",{header:{sid:e.sid,cname:e.channel,uid:e.uid,success:!0},body:{csurl:o,gatewaylist:s}}),n({serverlist:s,url:o})}},fail:function(e){a({code:901,reason:e.errMsg||"choose server fail"},o)}})}))}))}(this.option).then((function(t){var i=t.serverlist,n=t.url;p.default.debug("Get server list from "+n),e.index=0,e.serverlist=i,e.option&&e.option.servers&&(e.serverlist=e.option.servers),p.default.debug("Connect server with list: ",e.serverlist),e.connectWorker(e.serverlist[e.index])})).catch((function(t){e.emit&&e.emit("socketError",t)}))}},{key:"connectWorker",value:function(){var e=this;this.state="connecting";var t=this.serverlist[this.index];p.default.debug("Connect server: ",t);var i=this.option,n=i.sid,r=i.channel,s=i.uid,a=i.reportManager;this.ws=wx.connectSocket({url:t,complete:function(e){return p.default.debug("wxSocket: complete: ",e)},fail:function(e){p.default.debug("wxSocket: fail: ",e),a&&a.report("connectWebSocket",{header:{sid:n,cname:r,uid:s,success:!1},body:{wsurl:t,ec:JSON.stringify(e)}})},success:function(e){p.default.debug("wxSocket success: ",e),a&&a.report("connectWebSocket",{header:{sid:n,cname:r,uid:s,success:!0},body:{wsurl:t}})}}),this.ws.onOpen(this._onopen.bind(this)),this.ws.onMessage(this._onmessage.bind(this)),this.establishWSTimeoutTimer=setTimeout((function(){"connected"!==e.state&&e.connectNextWorker()}),5e3)}},{key:"connectNextWorker",value:function(){"disconnected"!==this.state&&this.close(),p.default.debug(this.index,this.serverlist.length),this.index>=this.serverlist.length-1?this.emit&&this.emit("socketError",{code:905,reason:"connect websocket failed",wsurl:JSON.stringify(this.serverlist)}):(this.index++,this.connectWorker())}},{key:"_onopen",value:function(){p.default.info("websocket onopen"),clearTimeout(this.establishWSTimeoutTimer),this.state="connected",this.isInit=!1,this.hasInvokeClose?p.default.debug("Alread invoke ws.Close, will not throw onopen event"):(this.ws.onClose(this._onclose.bind(this)),this.emit&&this.emit("onopen"))}},{key:"_onclose",value:function(e){p.default.info("websocket onclose:"+JSON.stringify(e)),this.emitter.emit("_wsClose"),clearTimeout(this.establishWSTimeoutTimer),this.state="disconnected",e&&"close"==e.reason||this.hasInvokeClose||(this.isInit?this.connectNextWorker():this.emit&&this.emit("onclose"))}},{key:"_onmessage",value:function(e){this.hasInvokeClose||(p.default.blind("receive message: ",JSON.stringify(e)),this.isConnected()&&this.emit&&this.emit("onmessage",e))}},{key:"isConnected",value:function(){return"connected"===this.state}},{key:"sendMessage",value:function(e){p.default.blind("send message: ",e),this.isConnected()&&this.ws&&this.ws.send({data:e})}},{key:"_checkServerList",value:function(e){return e instanceof Array!=0&&0!=e.length}},{key:"destroy",value:function(e){var t=this;"disconnected"!==this.state&&this.close(),this.on("_wsClose",(function i(){t.off("_wsClose",i),t.serverlist=null,t.ws=null,t.emitter=null,t.on=null,t.off=null,t.emit=null,e&&e()}))}},{key:"close",value:function(){p.default.debug("Close websocket"),clearTimeout(this.establishWSTimeoutTimer),this.hasInvokeClose=!0,this.state="disconnected",this.ws&&this.ws.close({reason:"close"}),this.ws=null}}]),e}(),y=function(){function e(t){r()(this,e),this.appId=t.appId,this.channel=t.channel,this.uid=t.uid+"",this.sid=t.sid,this.seq=1,this.requestId=2}return a()(e,[{key:"setSid",value:function(e){this.sid=e}},{key:"_getWorkerManagerMsg",value:function(){return{appId:this.appId,cname:this.channel,uid:this.uid,sid:this.sid,sdkVersion:l.VERSION,seq:++this.seq,requestId:++this.requestId,ts:Math.floor(Date.now()/1e3)}}},{key:"send",value:function(e){var t=this._getWorkerManagerMsg();return t.clientRequest=e,t}},{key:"updatePushUrl",value:function(){var e=this._getWorkerManagerMsg();return e.clientRequest={action:"update_url",role:"publish",uid:+this.uid},e}},{key:"ping",value:function(){return{command:"ping",requestId:++this.requestId,appId:this.appId,cname:this.channel,uid:this.uid+"",sid:this.sid,ts:Math.floor(Date.now()/1e3)}}},{key:"ping2",value:function(){var e=this._getWorkerManagerMsg();return e.clientRequest={action:"ping"},e}},{key:"setRole",value:function(e){var t=this._getWorkerManagerMsg();return t.clientRequest={action:"set_role",role:e},t}},{key:"rejoin",value:function(e,t,i,n,r,s){var a=this._getWorkerManagerMsg();return a.clientRequest={action:"join",role:s,appId:e,key_vocs:n||e,key_vos:n||e,channel_name:t,uid:i+"",known_speakers:r,clientType:"undefined"==typeof qq?"wechat":"qq"},a}},{key:"join",value:function(e,t,i,n,r){var s=this._getWorkerManagerMsg();return s.clientRequest={action:"join",role:r,appId:e,key_vocs:n||e,key_vos:n||e,channel_name:t,uid:i+"",clientType:"undefined"==typeof qq?"wechat":"qq"},s}},{key:"muteLocal",value:function(e,t){var i=this._getWorkerManagerMsg();return i.clientRequest={action:"mute_local",uid:+e,target:t,mute:!0},i}},{key:"unmuteLocal",value:function(e,t){var i=this._getWorkerManagerMsg();return i.clientRequest={action:"mute_local",uid:+e,target:t,mute:!1},i}},{key:"mute",value:function(e,t){var i=this._getWorkerManagerMsg();return i.clientRequest={action:"mute",uid:+e,target:t},i}},{key:"unmute",value:function(e,t){var i=this._getWorkerManagerMsg();return i.clientRequest={action:"unmute",uid:+e,target:t},i}},{key:"publish",value:function(e){var t=this._getWorkerManagerMsg();return t.clientRequest={action:"publish",uid:+e},t}},{key:"unpublish",value:function(e){var t=this._getWorkerManagerMsg();return t.clientRequest={action:"unpublish",uid:+e},t}},{key:"subscribe",value:function(e){var t=this._getWorkerManagerMsg();return t.clientRequest={action:"subscribe",uid:+e},t}},{key:"unsubscribe",value:function(e){var t=this._getWorkerManagerMsg();return t.clientRequest={action:"unsubscribe",uid:[+e]},t}},{key:"leave",value:function(e){var t=this._getWorkerManagerMsg();return t.clientRequest={action:"leave",uid:+e},t}}]),e}(),E=i(0),S=i.n(E),g=function(){function e(t,i){r()(this,e),this.appId=t.appId,this.channel=t.channel,this.uid=t.uid,this.sid=t.sid,this.role=t.role,this.channelKey=t.channelKey,this.clientId="client",this.option=t,this.timers=new Set,this.reportManager=t.reportManager,this.clientEmitter=i,this.emitter=new f,this.on=this.emitter.on,this.off=this.emitter.off,this.emit=this.emitter.emit,this.join=this.join.bind(this),this.msgManager=new y(t)}var t,i,n;return a()(e,[{key:"connect",value:function(){var e=this;return new Promise((function(t,i){e.ws=new v(e.option,e.emitter),e.ws.connect(),e.on("onmessage",e._onMessage.bind(e)),e.on("socketError",i),e.on("onopen",(function i(){e.off&&e.off("onopen",i),e._ping(),t()})),e.on("onclose",(function(){return e.clientEmitter.emit("error",{code:904,reason:"websocket disconnected"})}))}))}},{key:"_onMessage",value:function(e){if(e&&e.data){var t=JSON.parse(e.data);if(t&&"pong"!==t.command){p.default.debug("worker message: ",t);try{this.reportManager.report("serverEvent",{header:{sid:this.sid,cname:this.channel,uid:this.uid,success:!0},body:{action:"serverEvent",details:t,req_ts:+new Date}})}catch(e){}}if(t.requestId&&this.emit(t.requestId,t),"serverStatus"===t.command){if(t.code&&200!==t.code){if(503===t.code)return;this.clientEmitter.emit("error",{code:t.code,reason:t.reason||"server error"})}if(t.serverStatus){p.default.info("Receive message from server: ".concat(JSON.stringify(t.serverStatus)));var i=t.serverStatus.action;if("audio-mute"==i)return t.serverStatus.mute?this.clientEmitter.emit("mute-audio",{uid:t.serverStatus.uid}):this.clientEmitter.emit("unmute-audio",{uid:t.serverStatus.uid});if("video-mute"==i)return t.serverStatus.mute?this.clientEmitter.emit("mute-video",{uid:t.serverStatus.uid}):this.clientEmitter.emit("unmute-video",{uid:t.serverStatus.uid});this.clientEmitter.emit(i,t.serverStatus)}}}}},{key:"_sendMessage",value:function(e){var t=this;if(this.ws)return new Promise((function(i,n){if(!t.isWSConnected())return n({code:904,reason:"websocket disconnected",wsurl:t.getWSUrl()});"ping"!==e.command&&p.default.debug("send to woker: ",e);var r,s=e?e.requestId:null,a=function e(a){if(t.ws)return t.off(s,e),clearTimeout(r),t.timers.delete(r),200==a.code?i(a.serverResponse):n({code:a.code,reason:a.msg||a.reason,serverResponse:a.serverResponse,wsurl:t.getWSUrl()})};if(!s)return n({code:902,reason:"no requestid"});t.ws.sendMessage(JSON.stringify(e)),t.on(s,a),r=setTimeout((function(){return a({code:903,reason:"time out"})}),1e4),t.timers.add(r)}))}},{key:"_ping",value:function(){var e=this;this.pingTimer=setInterval((function(){e.ws.sendMessage(JSON.stringify(e.msgManager.ping()))}),3e3)}},{key:"setRole",value:function(e){return this._sendMessage(this.msgManager.setRole(e))}},{key:"rejoin",value:function(e){return this._sendMessage(this.msgManager.rejoin(this.appId,this.channel,this.uid,this.channelKey,e,this.role))}},{key:"join",value:function(){return this._sendMessage(this.msgManager.join(this.appId,this.channel,this.uid,this.channelKey,this.role))}},{key:"send",value:function(e){return this._sendMessage(this.msgManager.send(e))}},{key:"updatePushUrl",value:function(){return this._sendMessage(this.msgManager.updatePushUrl())}},{key:"publish",value:function(){return this._sendMessage(this.msgManager.publish(this.uid))}},{key:"unpublish",value:function(){return this._sendMessage(this.msgManager.unpublish(this.uid))}},{key:"subscribe",value:function(e){return this._sendMessage(this.msgManager.subscribe(e))}},{key:"unsubscribe",value:function(e){return this._sendMessage(this.msgManager.unsubscribe(e))}},{key:"mute",value:function(e,t){return this._sendMessage(this.msgManager.mute(e,t))}},{key:"unmute",value:function(e,t){return this._sendMessage(this.msgManager.unmute(e,t))}},{key:"muteLocal",value:function(e){return this._sendMessage(this.msgManager.muteLocal(this.uid,e))}},{key:"unmuteLocal",value:function(e){return this._sendMessage(this.msgManager.unmuteLocal(this.uid,e))}},{key:"leave",value:function(){return this._sendMessage(this.msgManager.leave(this.uid))}},{key:"isWSConnected",value:function(){return!!this.ws&&this.ws.isConnected()}},{key:"getWSUrl",value:function(){return this.ws.serverlist[this.ws.index]}},{key:"destroy",value:function(e){var t=this;clearInterval(this.pingTimer),this.timers.forEach((function(e){clearInterval(e)})),this.timers=null,this.ws&&this.ws.destroy((function(){t.ws=null,t.emitter=null,t.on=null,t.off=null,t.emit=null,e&&e()}))}},{key:"startChannelMediaRelay",value:(n=d()(h.a.mark((function e(t){var i,n,r,s,a,o=this;return h.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.channelMediaRelayController){e.next=2;break}throw new E.ChannelMediaError("RELAY_ALREADY_START","",E.CHANNEL_MEDIA_RELAY_ERROR.RELAY_ALREADY_START);case 2:return i=function(e){o.clientEmitter.emit({type:"channel-media-relay-event",code:e})},n=function(e,t,i){e===E.CHANNEL_MEDIA_RELAY_STATE.RELAY_STATE_FAILURE&&t===E.CHANNEL_MEDIA_RELAY_ERROR.SERVER_CONNECTION_LOST&&(o.channelMediaRelayController.dispose(),o.channelMediaRelayController=null),o.clientEmitter.emit({type:"channel-media-relay-state",state:e,code:t,data:i})},r={token:this.appId,appId:this.appId,cname:this.channel,uid:this.uid,sid:this.sid,clientId:this.clientId},this.channelMediaRelayController=new S.a(r,this.clientId),this.channelMediaRelayController.on("event",i),this.channelMediaRelayController.on("state",n),e.prev=8,e.next=11,this.channelMediaRelayController.startChannelMediaRelay(t);case 11:e.next=23;break;case 13:throw e.prev=13,e.t0=e.catch(8),p.default.debug("[".concat(this.clientId,"] startChannelMediaRelay exception: ").concat(JSON.stringify(e.t0))),s=E.CHANNEL_MEDIA_RELAY_STATE.RELAY_STATE_FAILURE,"",a=e.t0 instanceof E.ChannelMediaError?"SetSourceChannelStatus"===e.t0.data||e.t0.data&&e.t0.data.serverResponse&&"SetSourceChannel"===e.t0.data.serverResponse.command?"FAILED_JOIN_SRC":"SetDestChannelStatus"===e.t0.data||e.t0.data&&e.t0.data.serverResponse&&"SetDestChannel"===e.t0.data.serverResponse.command?"FAILED_JOIN_DEST":e.t0.data&&e.t0.data.serverResponse&&"StartPacketTransfer"===e.t0.data.serverResponse.command?"FAILED_PACKET_SENT_TO_DEST":e.t0.message===E.CHANNEL_MEDIA_ERROR.REQUEST_TIMEOUT||e.t0.message===E.CHANNEL_MEDIA_ERROR.WAIT_STATUS_TIMEOUT?"SERVER_NO_RESPONSE":e.t0.message===E.CHANNEL_MEDIA_ERROR.REQUEST_FAILED||e.t0.message===E.CHANNEL_MEDIA_ERROR.WAIT_STATUS_ERROR?"SERVER_ERROR_RESPONSE":e.t0.message===E.CHANNEL_MEDIA_ERROR.AP_REQUEST_TIMEOUT?"NO_RESOURCE_AVAILABLE":e.t0.message===E.CHANNEL_MEDIA_ERROR.WS_ABORT||e.t0.message===E.CHANNEL_MEDIA_ERROR.AP_REQUEST_ABORT?"OPERATION_ABORT":"INTERNAL_ERROR":"INTERNAL_ERROR",this.clientEmitter.emit({type:"channel-media-relay-state",state:s,code:E.CHANNEL_MEDIA_RELAY_ERROR[a]}),this.channelMediaRelayController&&(this.channelMediaRelayController.dispose(),this.channelMediaConfig=null,this.channelMediaRelayController=null),this.clientEmitter.emit({type:"channel-media-relay-state",state:E.CHANNEL_MEDIA_RELAY_STATE.RELAY_STATE_IDLE}),new E.ChannelMediaError(a,null,E.CHANNEL_MEDIA_RELAY_ERROR[a]);case 23:this.clientEmitter.emit({type:"channel-media-relay-state",state:E.CHANNEL_MEDIA_RELAY_STATE.RELAY_STATE_RUNNING,code:E.CHANNEL_MEDIA_RELAY_ERROR.RELAY_OK}),this.channelMediaConfig=t;case 25:case"end":return e.stop()}}),e,this,[[8,13]])}))),function(e){return n.apply(this,arguments)})},{key:"updateChannelMediaRelay",value:(i=d()(h.a.mark((function e(t){var i,n;return h.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.channelMediaRelayController){e.next=2;break}throw new E.ChannelMediaError("RELAY_NOT_START",null,E.CHANNEL_MEDIA_RELAY_ERROR.RELAY_NOT_START);case 2:return e.prev=2,e.next=5,this.channelMediaRelayController.updateChannelMediaRelay(t);case 5:e.next=18;break;case 7:throw e.prev=7,e.t0=e.catch(2),p.default.debug("[".concat(this.clientId,"] updateChannelMediaRelay exception: ").concat(JSON.stringify(e.t0))),i=E.CHANNEL_MEDIA_RELAY_STATE.RELAY_STATE_FAILURE,"",n=e.t0 instanceof E.ChannelMediaError?e.t0.message===E.CHANNEL_MEDIA_ERROR.REQUEST_TIMEOUT||e.t0.message===E.CHANNEL_MEDIA_ERROR.WAIT_STATUS_TIMEOUT?"SERVER_NO_RESPONSE":e.t0.message===E.CHANNEL_MEDIA_ERROR.REQUEST_FAILED||e.t0.message===E.CHANNEL_MEDIA_ERROR.WAIT_STATUS_ERROR?"SERVER_ERROR_RESPONSE":e.t0.message===E.CHANNEL_MEDIA_ERROR.WS_ABORT||e.t0.message===E.CHANNEL_MEDIA_ERROR.AP_REQUEST_ABORT?"OPERATION_ABORT":"INTERNAL_ERROR":"INTERNAL_ERROR",this.clientEmitter.emit({type:"channel-media-relay-event",code:E.CHANNEL_MEDIA_RELAY_EVENT.PACKET_UPDATE_DEST_CHANNEL_REFUSED}),this.clientEmitter.emit({type:"channel-media-relay-state",state:i,code:E.CHANNEL_MEDIA_RELAY_ERROR[n]}),this.channelMediaRelayController&&(this.channelMediaRelayController.dispose(),this.channelMediaConfig=null,this.channelMediaRelayController=null),this.clientEmitter.emit({type:"channel-media-relay-state",state:E.CHANNEL_MEDIA_RELAY_STATE.RELAY_STATE_IDLE}),new E.ChannelMediaError(n,null,E.CHANNEL_MEDIA_RELAY_ERROR[n]);case 18:this.channelMediaConfig=t;case 19:case"end":return e.stop()}}),e,this,[[2,7]])}))),function(e){return i.apply(this,arguments)})},{key:"stopChannelMediaRelay",value:(t=d()(h.a.mark((function e(){var t,i;return h.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.channelMediaRelayController){e.next=2;break}throw new E.ChannelMediaError("RELAY_NOT_START",null,E.CHANNEL_MEDIA_RELAY_ERROR.RELAY_NOT_START);case 2:return e.prev=2,e.next=5,this.channelMediaRelayController.stopChannelMediaRelay();case 5:e.next=17;break;case 7:throw e.prev=7,e.t0=e.catch(2),p.default.debug("[".concat(this.clientId,"] stopChannelMediaRelay exception: ").concat(JSON.stringify(e.t0))),t=E.CHANNEL_MEDIA_RELAY_STATE.RELAY_STATE_FAILURE,"",i=e.t0 instanceof E.ChannelMediaError?e.t0.message===E.CHANNEL_MEDIA_ERROR.REQUEST_TIMEOUT||e.t0.message===E.CHANNEL_MEDIA_ERROR.WAIT_STATUS_TIMEOUT?"SERVER_NO_RESPONSE":e.t0.message===E.CHANNEL_MEDIA_ERROR.REQUEST_FAILED||e.t0.message===E.CHANNEL_MEDIA_ERROR.WAIT_STATUS_ERROR?"SERVER_ERROR_RESPONSE":"INTERNAL_ERROR":"INTERNAL_ERROR",this.clientEmitter.emit({type:"channel-media-relay-state",state:t,code:E.CHANNEL_MEDIA_RELAY_ERROR[i]}),this.channelMediaRelayController&&(this.channelMediaRelayController.dispose(),this.channelMediaConfig=null,this.channelMediaRelayController=null),this.emit({type:"channel-media-relay-state",state:E.CHANNEL_MEDIA_RELAY_STATE.RELAY_STATE_IDLE}),new E.ChannelMediaError(i,null,E.CHANNEL_MEDIA_RELAY_ERROR[i]);case 17:this.channelMediaConfig=null,this.channelMediaRelayController=null;case 19:case"end":return e.stop()}}),e,this,[[2,7]])}))),function(){return t.apply(this,arguments)})}]),e}(),w=i(28).ReportServiceClient,m=i(8).default,_=i(14).VosdkHeader,R=i(13),k=function(){function e(){r()(this,e),this.transport=new m.TXHRTransport("https://uni-webcollector.agora.io/report"),this.protocol=new m.TJSONProtocol(this.transport),this.client=new w(this.protocol),this.seqId=0,this._cache=[],this.isReporting=!1,this.retryCount=0}return a()(e,[{key:"generateHeader",value:function(e){if(e&&e.sid)return new _({sid:e.sid,cname:e.cname||"",lts:e.lts,elapse:e.lts-this.startTime,uid:e.uid,success:e.success})}},{key:"report",value:function(e,t){var i=null;if(t.header&&(t.header.lts=+new Date,"sessionStart"===e&&(this.startTime=t.header.lts),i=this.generateHeader(t.header)),t.body&&i){var n=t.body;switch(e){case"sessionStart":(r=new R({miniappSession:!0})).uri=8e3,r.miniappSession.header=i,r.miniappSession.appid=n.appId,r.miniappSession.uname=n.uname,r.miniappSession.ver=l.SDK_VERSION,r.miniappSession.dk=n.dk,r.miniappSession.details=JSON.stringify({seq:this.seqId++});break;case"chooseServer":(r=new R({miniappJoinChooseServer:!0})).uri=8001,r.miniappJoinChooseServer.header=i,r.miniappJoinChooseServer.csurl=n.csurl,r.miniappJoinChooseServer.ec=n.ec,r.miniappJoinChooseServer.gatewaylist=n.gatewaylist,r.miniappJoinChooseServer.details=JSON.stringify({seq:this.seqId++});break;case"connectWebSocket":(r=new R({miniappConnectWebSocket:!0})).uri=8002,r.miniappConnectWebSocket.header=i,r.miniappConnectWebSocket.ec=n.ec,r.miniappConnectWebSocket.wsurl=n.wsurl,r.miniappConnectWebSocket.details=JSON.stringify({seq:this.seqId++});break;case"join":(r=new R({miniappJoin:!0})).uri=8003,r.miniappJoin.header=i,r.miniappJoin.ec=n.ec,r.miniappJoin.isrejoin=n.isrejoin,r.miniappJoin.details=JSON.stringify({seq:this.seqId++,appId:n.appId,wsurl:n.wsurl});break;case"publish":(r=new R({miniappPublish:!0})).uri=8004,r.miniappPublish.header=i,r.miniappPublish.ec=n.ec,r.miniappPublish.pushurl=n.pushurl,r.miniappPublish.details=JSON.stringify({seq:this.seqId++});break;case"unpublish":(r=new R({miniappUnpublish:!0})).uri=8005,r.miniappUnpublish.header=i,r.miniappUnpublish.ec=n.ec,r.miniappUnpublish.details=JSON.stringify({seq:this.seqId++});break;case"subscribe":(r=new R({miniappSubscribe:!0})).uri=8006,r.miniappSubscribe.header=i,r.miniappSubscribe.ec=n.ec,r.miniappSubscribe.pullurl=n.pullurl,r.miniappSubscribe.peerid=n.peerid,r.miniappSubscribe.details=JSON.stringify({seq:this.seqId++});break;case"unsubscribe":(r=new R({miniappUnsubscribe:!0})).uri=8007,r.miniappUnsubscribe.header=i,r.miniappUnsubscribe.ec=n.ec,r.miniappUnsubscribe.peerid=n.peerid,r.miniappUnsubscribe.details=JSON.stringify({seq:this.seqId++});break;case"leave":(r=new R({miniappLeave:!0})).uri=8008,r.miniappLeave.header=i,r.miniappLeave.ec=n.ec,r.miniappLeave.details=JSON.stringify({seq:this.seqId++});break;case"pusherState":(r=new R({miniappPusherState:!0})).uri=8010,r.miniappPusherState.header=i,r.miniappPusherState.url=n.url,r.miniappPusherState.code=n.code,r.miniappPusherState.status=n.status,r.miniappPusherState.error=n.error,r.miniappPusherState.details=JSON.stringify({seq:this.seqId++});break;case"playerState":(r=new R({miniappPlayerState:!0})).uri=8011,r.miniappPlayerState.header=i,r.miniappPlayerState.url=n.url,r.miniappPlayerState.code=n.code,r.miniappPlayerState.status=n.status,r.miniappPlayerState.error=n.error,r.miniappPlayerState.details=JSON.stringify({seq:this.seqId++});break;case"serverEvent":(r=new R({miniappServerEvent:!0})).uri=8009,r.miniappServerEvent.header=i,r.miniappServerEvent.action=n.action,r.miniappServerEvent.details=JSON.stringify(n.details),r.miniappServerEvent.req_ts=n.req_ts}}if(this._cache.push(r),!this.isReporting&&this._cache.length>0){var r=this._cache.shift();this._report(r)}}},{key:"_report",value:function(e){var t=this;this.isReporting=!0,this.client.Report(e,(function(i){if(i){p.default.debug("Report failed: ",i,e);var n=t.retryCount++<2?200:1e4;setTimeout((function(){t._report(e)}),n)}else{p.default.debug("Report succcess: ",e);var r=t._cache.shift();r?t._report(r):t.isReporting=!1}}))}}]),e}(),b=i(2),I=function(){function e(t){var i=this;r()(this,e),this.emitter=new f,this.on=this.emitter.on,this.off=this.emitter.off,this.sid=Object(o.generateSessionId)(),this.pushUrl=null,this.playUrls=new Map,this.servers=t&&t.servers,this.reportManager=new k,this.role="broadcaster",this.emitter.on("stream-removed",(function(e){i.playUrls&&i.playUrls.delete(e.uid)}))}return a()(e,[{key:"init",value:function(e,t,i){if(!e||"string"!=typeof e||"null"===e.toLowerCase())throw Error("Invalid appId");this.appId=e.trim(),this.reportManager.report("sessionStart",{header:{sid:this.sid,lts:+new Date,success:!0},body:{appId:e}}),t&&t()}},{key:"setRole",value:function(e,t,i){if("broadcaster"===!e&&"audience"===!e)throw Error("Invalid role");this.role=e,this.worker&&this.worker.setRole(e).then((function(e){setTimeout((function(){if(!e)return t&&t();t&&t({updateURL:e["update-url"]})}),1)})).catch((function(){i&&i()}))}},{key:"rejoin",value:function(e,t,i,n,r,s){var a=this;if(!this.worker){if(e){if("string"!=typeof e||"null"===e.toLowerCase())throw Error("Invalid channelKey")}else e=this.appId;if(!t||"string"!=typeof t||"null"===t.toLowerCase()||t.length>128)throw Error("Invalid channel");if(this.uid=i||Object(o.random)(1e7),this.uid=Number.parseInt(this.uid),!Object(o.is32Uint)(this.uid))throw new Error("Invalid uid type");this.channel=t,this.worker=new g({appId:this.appId,channel:this.channel,uid:this.uid,sid:this.sid,role:this.role,servers:this.servers,channelKey:e,reportManager:this.reportManager},this.emitter),this.worker.connect().then((function(){return a.worker.rejoin(n)})).then((function(){try{a.reportManager.report("join",{header:{sid:a.sid,cname:a.channel,uid:a.uid,success:!0},body:{isrejoin:!0,appId:a.appId,wsurl:a.worker&&a.worker.getWSUrl()}})}catch(e){}setTimeout((function(){r&&r(this.uid)}),1)})).catch((function(e){try{a.reportManager.report("join",{header:{sid:a.sid,cname:a.channel,uid:a.uid,success:!1},body:{ec:JSON.stringify(e),appId:a.appId,wsurl:a.worker&&a.worker.getWSUrl()}})}catch(e){}a.destroy(),s&&s(e)}))}}},{key:"join",value:function(e,t,i,n,r){var s=this;if(!this.worker){if(e){if("string"!=typeof e||"null"===e.toLowerCase())throw Error("Invalid channelKey")}else e=this.appId;if(!t||"string"!=typeof t||"null"===t.toLowerCase()||t.length>128)throw Error("Invalid channel");if(this.uid=i||Object(o.random)(1e7),this.uid=Number.parseInt(this.uid),!Object(o.is32Uint)(this.uid))throw new Error("Invalid uid type");this.channel=t,this.worker=new g({appId:this.appId,channel:this.channel,uid:this.uid,sid:this.sid,role:this.role,servers:this.servers,channelKey:e,reportManager:this.reportManager},this.emitter),this.worker.connect().then((function(){return s.worker.join()})).then((function(){try{s.reportManager.report("join",{header:{sid:s.sid,cname:s.channel,uid:s.uid,success:!0},body:{isrejoin:!1,appId:s.appId,wsurl:s.worker&&s.worker.getWSUrl()}})}catch(e){}setTimeout((function(){n&&n(this.uid)}),1)})).catch((function(e){try{s.reportManager.report("join",{header:{sid:s.sid,cname:s.channel,uid:s.uid,success:!1},body:{ec:JSON.stringify(e),appId:s.appId,wsurl:e.wsurl||s.worker&&s.worker.getWSUrl()}})}catch(e){}s.destroy(),r&&r(e)}))}}},{key:"publish",value:function(e,t){var i=this;this._checkWorker(),this.worker.publish().then((function(t){i.pushUrl=t.url;try{i.reportManager.report("publish",{header:{sid:i.sid,cname:i.channel,uid:i.uid,success:!0},body:{pushurl:t.url}})}catch(e){}setTimeout((function(){e&&e(t.url)}),1)})).catch((function(e){i.reportManager.report("publish",{header:{sid:i.sid,cname:i.channel,uid:i.uid,success:!1},body:{ec:JSON.stringify(e)}}),t&&t(e)}))}},{key:"unpublish",value:function(e,t){var i=this;this._checkWorker(),this.worker.unpublish().then((function(t){i.pushUrl=null;try{i.reportManager.report("unpublish",{header:{sid:i.sid,cname:i.channel,uid:i.uid,success:!0},body:{}})}catch(e){}setTimeout((function(){e&&e()}),1)})).catch((function(e){i.reportManager.report("unpublish",{header:{sid:i.sid,cname:i.channel,uid:i.uid,success:!1},body:{ec:JSON.stringify(e)}}),t&&t(e)}))}},{key:"subscribe",value:function(e,t,i){var n=this;this._checkUid(e),this._checkWorker(),this.worker.subscribe(e).then((function(i){n.playUrls.set(e,i.url);try{n.reportManager.report("subscribe",{header:{sid:n.sid,cname:n.channel,uid:n.uid,success:!0},body:{pullurl:i.url}})}catch(e){}setTimeout((function(){t&&t(i.url,i.rotation)}),1)})).catch((function(e){n.reportManager.report("subscribe",{header:{sid:n.sid,cname:n.channel,uid:n.uid,success:!1},body:{ec:JSON.stringify(e)}}),i&&i(e)}))}},{key:"unsubscribe",value:function(e,t,i){var n=this;this._checkUid(e),this._checkWorker(),this.worker.unsubscribe(e).then((function(i){n.playUrls.delete(e);try{n.reportManager.report("unsubscribe",{header:{sid:n.sid,cname:n.channel,uid:n.uid,success:!1},body:{}})}catch(e){}setTimeout((function(){t&&t()}),1)})).catch((function(e){n.reportManager.report("unsubscribe",{header:{sid:n.sid,cname:n.channel,uid:n.uid,success:!1},body:{ec:JSON.stringify(e)}}),i&&i(e)}))}},{key:"mute",value:function(e,t,i,n){if(this._checkUid(e),this._checkWorker(),"video"!==t&&"audio"!==t&&"all"!==t)throw new Error('target should be "video", "audio" or "all"');this.worker.mute(e,t).then((function(e){setTimeout((function(){i&&i()}),1)})).catch((function(e){n&&n(e)}))}},{key:"unmute",value:function(e,t,i,n){if(this._checkUid(e),this._checkWorker(),"video"!==t&&"audio"!==t&&"all"!==t)throw new Error('target should be "video", "audio" or "all"');this.worker.unmute(e,t).then((function(e){setTimeout((function(){i&&i()}),1)})).catch((function(e){n&&n(e)}))}},{key:"muteLocal",value:function(e,t,i){if(this._checkWorker(),"video"!==e&&"audio"!==e&&"all"!==e)throw new Error('target should be "video", "audio" or "all"');this.worker.muteLocal(e).then((function(e){setTimeout((function(){t&&t()}),1)})).catch((function(e){i&&i(e)}))}},{key:"unmuteLocal",value:function(e,t,i){if(this._checkWorker(),"video"!==e&&"audio"!==e&&"all"!==e)throw new Error('target should be "video", "audio" or "all"');this.worker.unmuteLocal(e).then((function(e){setTimeout((function(){t&&t()}),1)})).catch((function(e){i&&i(e)}))}},{key:"leave",value:function(e,t){var i=this;this.worker&&this.worker.isWSConnected()&&this.worker.leave().then((function(t){try{i.reportManager.report("leave",{header:{sid:i.sid,cname:i.channel,uid:i.uid,success:!0},body:{}})}catch(e){}i.destroy((function(){setTimeout((function(){e&&e()}),1)}))})).catch((function(e){t&&t(e)}))}},{key:"_checkUid",value:function(e){if(!e||"number"!=typeof e||!Object(o.is32Uint)(e))throw new Error("Invalid uid type")}},{key:"_checkWorker",value:function(){if(!this.worker||!this.worker.isWSConnected())throw new Error("Disconnected from server")}},{key:"isConnected",value:function(){return!(!this.worker||!this.worker.isWSConnected())}},{key:"updatePusherStateChange",value:function(e){if(this.pushUrl){var t=e.detail.code;if(1008==t||t<0){var i=1008==t;this.reportManager&&this.reportManager.report("pusherState",{header:{sid:this.sid,cname:this.channel,uid:this.uid,success:i},body:{url:this.pushUrl,code:t}})}}}},{key:"updatePlayerStateChange",value:function(e,t){var i=this.playUrls.get(e);if(i){var n=t.detail.code;if(2004==n||n<0||n>3e3){var r=2004==n;this.reportManager&&this.reportManager.report("playerState",{header:{sid:this.sid,cname:this.channel,uid:e,success:r},body:{url:i,code:n}})}}}},{key:"updatePusherNetStatus",value:function(e){}},{key:"updatePlayerNetStatus",value:function(e,t){}},{key:"updatePusherError",value:function(e){}},{key:"updatePlayerError",value:function(e,t){}},{key:"send",value:function(e,t,i){this._checkWorker(),this.worker.send(e).then((function(e){t&&t(e)})).catch((function(e){i&&i(e)}))}},{key:"updatePushUrl",value:function(e,t){this._checkWorker(),this.worker.updatePushUrl().then((function(t){setTimeout((function(){e&&e(t)}),1)})).catch((function(e){t&&t(e)}))}},{key:"destroy",value:function(e,t){var i=this;this.worker?(this.worker.destroy((function(){i.pushUrl=null,i.playUrls=null,e&&e()})),this.worker=null):(this.pushUrl=null,this.playUrls=null,e&&e())}},{key:"startChannelMediaRelay",value:function(e,t){if(!(e instanceof E.ChannelMediaRelayConfiguration))throw"Configration should be instance of [ChannelMediaRelayConfiguration]";var i=e.getSrcChannelMediaInfo(),n=e.getDestChannelMediaInfos();if(Object(b.isEmpty)(i))throw"srcChannelMediaInfo should not be empty";if(Object(b.isEmpty)(n)||0===n.length)throw"destChannelMediaInfos should not be empty";if(p.default.debug("[startChannelMediaRelay]: srcInfo: ",i," destInfo: ",n),!Object(o.is32Uint)(i.uid))throw"Invalid uid in srcChannelMediaInfo";if(!Object(b.isValidChannelName)(i.channelName))throw"Invalid channelName in srcChannelMediaInfo";if(i.token&&!Object(b.isValidToken)(i.token))throw"Invalid token in srcChannelMediaInfo";if(n.forEach((function(e){if(!Object(o.is32Uint)(e.uid))throw"Invalid uid in destChannelMediaInfo";if(!Object(b.isValidChannelName)(e.channelName))throw"Invalid channelName in destChannelMediaInfo";if(e.token&&!Object(b.isValidToken)(e.token))throw"Invalid token in destChannelMediaInfo"})),!this.worker)throw"startChannelMediaRelay should be used after join";this.worker.startChannelMediaRelay(e).then((function(){t&&t()})).catch((function(e){t&&t(e)}))}},{key:"updateChannelMediaRelay",value:function(e,t){if(!(e instanceof E.ChannelMediaRelayConfiguration))throw"Configration should be instance of [ChannelMediaRelayConfiguration]";var i=e.getSrcChannelMediaInfo(),n=e.getDestChannelMediaInfos();if(Object(b.isEmpty)(i))throw"srcChannelMediaInfo should not be empty";if(Object(b.isEmpty)(n)||0===n.length)throw"destChannelMediaInfos should not be empty";if(p.default.debug("[updateChannelMediaRelay]: srcInfo: ",i," destInfo: ",n),!Object(o.is32Uint)(i.uid))throw"Invalid uid in srcChannelMediaInfo";if(!Object(b.isValidChannelName)(i.channelName))throw"Invalid channelName in srcChannelMediaInfo";if(i.token&&!Object(b.isValidToken)(i.token))throw"Invalid token in srcChannelMediaInfo";if(n.forEach((function(e){if(!Object(o.is32Uint)(e.uid))throw"Invalid uid in destChannelMediaInfo";if(!Object(b.isValidChannelName)(e.channelName))throw"Invalid channelName in destChannelMediaInfo";if(e.token&&!Object(b.isValidToken)(e.token))throw"Invalid token in destChannelMediaInfo"})),!this.worker)throw"updateChannelMediaRelay should be used after join";this.worker.updateChannelMediaRelay(e).then((function(){t&&t()})).catch((function(e){t&&t(e)}))}},{key:"stopChannelMediaRelay",value:function(e){p.default.debug("[stopChannelMediaRelay]"),this.worker.stopChannelMediaRelay().then((function(){e&&e()})).catch((function(t){e&&e(t)}))}}]),e}()}])}));