/** * AgoraWebSDK_N-v4.22.1-0-g1c8e27e9 Copyright AgoraInc. */ import{getParameter as e,getUTF8StringByteLength as t,getMultiUnilbsFormDataByteLength as s,AgoraRTCErrorCode as E,IS_GLOBAL_VERSION as n,VERSION as _,retryable as o,EventEmitter as i,PromiseMutex as r,NETWORK_STATE as c,networkIndicator as a,NETWORK_INDICATOR_EVENTS as R,createDefer as I,AgoraRTCError as A,getRetryWaitTime as N,wait as h,emitAsPromise as S,emitAsInvokerNoResponse as C,generateSessionID as T,DEFAULT_RETRY_CONFIG as O}from"@agora-js/shared";import{AgoraRTCError as L,AgoraRTCErrorCode as d,logger as l}from"@agora-js/report";import u from"axios";import"formdata-polyfill";function D(e,t,s){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var s=e[Symbol.toPrimitive];if(void 0!==s){var E=s.call(e,t||"default");if("object"!=typeof E)return E;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}function w(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var E=Object.getOwnPropertySymbols(e);t&&(E=E.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),s.push.apply(s,E)}return s}let g=0,V=0;let P=function(e){return e[e.ACCESS_POINT=101]="ACCESS_POINT",e[e.UNILBS=201]="UNILBS",e[e.STRING_UID_ALLOCATOR=901]="STRING_UID_ALLOCATOR",e}({}),U=function(e){return e[e.IIIEGAL_APPID=1]="IIIEGAL_APPID",e[e.IIIEGAL_UID=2]="IIIEGAL_UID",e[e.INTERNAL_ERROR=3]="INTERNAL_ERROR",e}({}),f=function(e){return e[e.INVALID_VENDOR_KEY=5]="INVALID_VENDOR_KEY",e[e.INVALID_CHANNEL_NAME=7]="INVALID_CHANNEL_NAME",e[e.INTERNAL_ERROR=8]="INTERNAL_ERROR",e[e.NO_AUTHORIZED=9]="NO_AUTHORIZED",e[e.DYNAMIC_KEY_TIMEOUT=10]="DYNAMIC_KEY_TIMEOUT",e[e.NO_ACTIVE_STATUS=11]="NO_ACTIVE_STATUS",e[e.DYNAMIC_KEY_EXPIRED=13]="DYNAMIC_KEY_EXPIRED",e[e.STATIC_USE_DYNAMIC_KEY=14]="STATIC_USE_DYNAMIC_KEY",e[e.DYNAMIC_USE_STATIC_KEY=15]="DYNAMIC_USE_STATIC_KEY",e[e.USER_OVERLOAD=16]="USER_OVERLOAD",e[e.FORBIDDEN_REGION=18]="FORBIDDEN_REGION",e[e.CANNOT_MEET_AREA_DEMAND=19]="CANNOT_MEET_AREA_DEMAND",e}({}),m=function(e){return e[e.NO_FLAG_SET=100]="NO_FLAG_SET",e[e.FLAG_SET_BUT_EMPTY=101]="FLAG_SET_BUT_EMPTY",e[e.INVALID_FALG_SET=102]="INVALID_FALG_SET",e[e.FLAG_SET_BUT_NO_RE=103]="FLAG_SET_BUT_NO_RE",e[e.INVALID_SERVICE_ID=104]="INVALID_SERVICE_ID",e[e.NO_SERVICE_AVAILABLE=200]="NO_SERVICE_AVAILABLE",e[e.NO_SERVICE_AVAILABLE_P2P=201]="NO_SERVICE_AVAILABLE_P2P",e[e.NO_SERVICE_AVAILABLE_VOICE=202]="NO_SERVICE_AVAILABLE_VOICE",e[e.NO_SERVICE_AVAILABLE_WEBRTC=203]="NO_SERVICE_AVAILABLE_WEBRTC",e[e.NO_SERVICE_AVAILABLE_CDS=204]="NO_SERVICE_AVAILABLE_CDS",e[e.NO_SERVICE_AVAILABLE_CDN=205]="NO_SERVICE_AVAILABLE_CDN",e[e.NO_SERVICE_AVAILABLE_TDS=206]="NO_SERVICE_AVAILABLE_TDS",e[e.NO_SERVICE_AVAILABLE_REPORT=207]="NO_SERVICE_AVAILABLE_REPORT",e[e.NO_SERVICE_AVAILABLE_APP_CENTER=208]="NO_SERVICE_AVAILABLE_APP_CENTER",e[e.NO_SERVICE_AVAILABLE_ENV0=209]="NO_SERVICE_AVAILABLE_ENV0",e[e.NO_SERVICE_AVAILABLE_VOET=210]="NO_SERVICE_AVAILABLE_VOET",e[e.NO_SERVICE_AVAILABLE_STRING_UID=211]="NO_SERVICE_AVAILABLE_STRING_UID",e[e.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS=212]="NO_SERVICE_AVAILABLE_WEBRTC_UNILBS",e[e.NO_SERVICE_AVAILABLE_UNILBS_FLV=213]="NO_SERVICE_AVAILABLE_UNILBS_FLV",e}({}),M=function(e){return e[e.K_TIMESTAMP_EXPIRED=2]="K_TIMESTAMP_EXPIRED",e[e.K_CHANNEL_PERMISSION_INVALID=3]="K_CHANNEL_PERMISSION_INVALID",e[e.K_CERTIFICATE_INVALID=4]="K_CERTIFICATE_INVALID",e[e.K_CHANNEL_NAME_EMPTY=5]="K_CHANNEL_NAME_EMPTY",e[e.K_CHANNEL_NOT_FOUND=6]="K_CHANNEL_NOT_FOUND",e[e.K_TICKET_INVALID=7]="K_TICKET_INVALID",e[e.K_CHANNEL_CONFLICTED=8]="K_CHANNEL_CONFLICTED",e[e.K_SERVICE_NOT_READY=9]="K_SERVICE_NOT_READY",e[e.K_SERVICE_TOO_HEAVY=10]="K_SERVICE_TOO_HEAVY",e[e.K_UID_BANNED=14]="K_UID_BANNED",e[e.K_IP_BANNED=15]="K_IP_BANNED",e[e.K_CHANNEL_BANNED=16]="K_CHANNEL_BANNED",e[e.K_AUTO_REBALANCE=28]="K_AUTO_REBALANCE",e[e.WARN_NO_AVAILABLE_CHANNEL=103]="WARN_NO_AVAILABLE_CHANNEL",e[e.WARN_LOOKUP_CHANNEL_TIMEOUT=104]="WARN_LOOKUP_CHANNEL_TIMEOUT",e[e.WARN_LOOKUP_CHANNEL_REJECTED=105]="WARN_LOOKUP_CHANNEL_REJECTED",e[e.WARN_OPEN_CHANNEL_TIMEOUT=106]="WARN_OPEN_CHANNEL_TIMEOUT",e[e.WARN_OPEN_CHANNEL_REJECTED=107]="WARN_OPEN_CHANNEL_REJECTED",e[e.WARN_REQUEST_DEFERRED=108]="WARN_REQUEST_DEFERRED",e[e.ERR_DYNAMIC_KEY_TIMEOUT=109]="ERR_DYNAMIC_KEY_TIMEOUT",e[e.ERR_NO_AUTHORIZED=110]="ERR_NO_AUTHORIZED",e[e.ERR_VOM_SERVICE_UNAVAILABLE=111]="ERR_VOM_SERVICE_UNAVAILABLE",e[e.ERR_NO_CHANNEL_AVAILABLE_CODE=112]="ERR_NO_CHANNEL_AVAILABLE_CODE",e[e.ERR_MASTER_VOCS_UNAVAILABLE=114]="ERR_MASTER_VOCS_UNAVAILABLE",e[e.ERR_INTERNAL_ERROR=115]="ERR_INTERNAL_ERROR",e[e.ERR_NO_ACTIVE_STATUS=116]="ERR_NO_ACTIVE_STATUS",e[e.ERR_INVALID_UID=117]="ERR_INVALID_UID",e[e.ERR_DYNAMIC_KEY_EXPIRED=118]="ERR_DYNAMIC_KEY_EXPIRED",e[e.ERR_STATIC_USE_DYANMIC_KE=119]="ERR_STATIC_USE_DYANMIC_KE",e[e.ERR_DYNAMIC_USE_STATIC_KE=120]="ERR_DYNAMIC_USE_STATIC_KE",e[e.ERR_NO_VOCS_AVAILABLE=2e3]="ERR_NO_VOCS_AVAILABLE",e[e.ERR_NO_VOS_AVAILABLE=2001]="ERR_NO_VOS_AVAILABLE",e[e.ERR_JOIN_CHANNEL_TIMEOUT=2002]="ERR_JOIN_CHANNEL_TIMEOUT",e[e.ERR_REPEAT_JOIN_CHANNEL=2003]="ERR_REPEAT_JOIN_CHANNEL",e[e.ERR_JOIN_BY_MULTI_IP=2004]="ERR_JOIN_BY_MULTI_IP",e[e.ERR_NOT_JOINED=2011]="ERR_NOT_JOINED",e[e.ERR_REPEAT_JOIN_REQUEST=2012]="ERR_REPEAT_JOIN_REQUEST",e[e.ERR_INVALID_VENDOR_KEY=2013]="ERR_INVALID_VENDOR_KEY",e[e.ERR_INVALID_CHANNEL_NAME=2014]="ERR_INVALID_CHANNEL_NAME",e[e.ERR_INVALID_STRINGUID=2015]="ERR_INVALID_STRINGUID",e[e.ERR_TOO_MANY_USERS=2016]="ERR_TOO_MANY_USERS",e[e.ERR_SET_CLIENT_ROLE_TIMEOUT=2017]="ERR_SET_CLIENT_ROLE_TIMEOUT",e[e.ERR_SET_CLIENT_ROLE_NO_PERMISSION=2018]="ERR_SET_CLIENT_ROLE_NO_PERMISSION",e[e.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE=2019]="ERR_SET_CLIENT_ROLE_ALREADY_IN_USE",e[e.ERR_PUBLISH_REQUEST_INVALID=2020]="ERR_PUBLISH_REQUEST_INVALID",e[e.ERR_SUBSCRIBE_REQUEST_INVALID=2021]="ERR_SUBSCRIBE_REQUEST_INVALID",e[e.ERR_NOT_SUPPORTED_MESSAGE=2022]="ERR_NOT_SUPPORTED_MESSAGE",e[e.ERR_ILLEAGAL_PLUGIN=2023]="ERR_ILLEAGAL_PLUGIN",e[e.ERR_REJOIN_TOKEN_INVALID=2024]="ERR_REJOIN_TOKEN_INVALID",e[e.ERR_REJOIN_USER_NOT_JOINED=2025]="ERR_REJOIN_USER_NOT_JOINED",e[e.ERR_INVALID_OPTIONAL_INFO=2027]="ERR_INVALID_OPTIONAL_INFO",e[e.ILLEGAL_AES_PASSWORD=2028]="ILLEGAL_AES_PASSWORD",e[e.ILLEGAL_CLIENT_ROLE_LEVEL=2029]="ILLEGAL_CLIENT_ROLE_LEVEL",e[e.ERR_TOO_MANY_BROADCASTERS=2031]="ERR_TOO_MANY_BROADCASTERS",e[e.ERR_TOO_MANY_SUBSCRIBERS=2032]="ERR_TOO_MANY_SUBSCRIBERS",e[e.ERR_LICENSE_MISSING=32769]="ERR_LICENSE_MISSING",e[e.ERR_LICENSE_EXPIRED=32771]="ERR_LICENSE_EXPIRED",e[e.ERR_LICENSE_MINUTES_EXCEEDED=32773]="ERR_LICENSE_MINUTES_EXCEEDED",e[e.ERR_LICENSE_PERIOD_INVALID=32774]="ERR_LICENSE_PERIOD_INVALID",e[e.ERR_LICENSE_MULTIPLE_SDK_SERVICE=32778]="ERR_LICENSE_MULTIPLE_SDK_SERVICE",e[e.ERR_LICENSE_ILLEGAL=32783]="ERR_LICENSE_ILLEGAL",e[e.ERR_TEST_RECOVER=9e3]="ERR_TEST_RECOVER",e[e.ERR_TEST_TRYNEXT=9001]="ERR_TEST_TRYNEXT",e[e.ERR_TEST_RETRY=9002]="ERR_TEST_RETRY",e}({});P.ACCESS_POINT,m.NO_FLAG_SET,m.FLAG_SET_BUT_EMPTY,m.INVALID_FALG_SET,m.FLAG_SET_BUT_NO_RE,m.INVALID_SERVICE_ID,m.NO_SERVICE_AVAILABLE,m.NO_SERVICE_AVAILABLE_P2P,m.NO_SERVICE_AVAILABLE_VOICE,m.NO_SERVICE_AVAILABLE_WEBRTC,m.NO_SERVICE_AVAILABLE_CDS,m.NO_SERVICE_AVAILABLE_CDN,m.NO_SERVICE_AVAILABLE_TDS,m.NO_SERVICE_AVAILABLE_REPORT,m.NO_SERVICE_AVAILABLE_APP_CENTER,m.NO_SERVICE_AVAILABLE_ENV0,m.NO_SERVICE_AVAILABLE_VOET,m.NO_SERVICE_AVAILABLE_STRING_UID,m.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS,P.UNILBS,f.INVALID_VENDOR_KEY,f.INVALID_CHANNEL_NAME,f.INTERNAL_ERROR,f.NO_AUTHORIZED,f.DYNAMIC_KEY_TIMEOUT,f.NO_ACTIVE_STATUS,f.DYNAMIC_KEY_EXPIRED,f.STATIC_USE_DYNAMIC_KEY,f.DYNAMIC_USE_STATIC_KEY,f.USER_OVERLOAD,f.FORBIDDEN_REGION,f.CANNOT_MEET_AREA_DEMAND,P.STRING_UID_ALLOCATOR,U.IIIEGAL_APPID,U.IIIEGAL_UID,U.INTERNAL_ERROR,M.K_TIMESTAMP_EXPIRED,M.K_CHANNEL_PERMISSION_INVALID,M.K_CERTIFICATE_INVALID,M.K_CHANNEL_NAME_EMPTY,M.K_CHANNEL_NOT_FOUND,M.K_TICKET_INVALID,M.K_CHANNEL_CONFLICTED,M.K_SERVICE_NOT_READY,M.K_SERVICE_TOO_HEAVY,M.K_UID_BANNED,M.K_IP_BANNED,M.K_AUTO_REBALANCE,M.ERR_INVALID_VENDOR_KEY,M.ERR_INVALID_CHANNEL_NAME,M.WARN_NO_AVAILABLE_CHANNEL,M.WARN_LOOKUP_CHANNEL_TIMEOUT,M.WARN_LOOKUP_CHANNEL_REJECTED,M.WARN_OPEN_CHANNEL_TIMEOUT,M.WARN_OPEN_CHANNEL_REJECTED,M.WARN_REQUEST_DEFERRED,M.ERR_DYNAMIC_KEY_TIMEOUT,M.ERR_NO_AUTHORIZED,M.ERR_VOM_SERVICE_UNAVAILABLE,M.ERR_NO_CHANNEL_AVAILABLE_CODE,M.ERR_MASTER_VOCS_UNAVAILABLE,M.ERR_INTERNAL_ERROR,M.ERR_NO_ACTIVE_STATUS,M.ERR_INVALID_UID,M.ERR_DYNAMIC_KEY_EXPIRED,M.ERR_STATIC_USE_DYANMIC_KE,M.ERR_DYNAMIC_USE_STATIC_KE,M.ERR_NO_VOCS_AVAILABLE,M.ERR_NO_VOS_AVAILABLE,M.ERR_JOIN_CHANNEL_TIMEOUT,M.ERR_JOIN_BY_MULTI_IP,M.ERR_NOT_JOINED,M.ERR_REPEAT_JOIN_REQUEST,M.ERR_REPEAT_JOIN_CHANNEL,M.ERR_INVALID_STRINGUID,M.ERR_TOO_MANY_USERS,M.ERR_SET_CLIENT_ROLE_TIMEOUT,M.ERR_SET_CLIENT_ROLE_NO_PERMISSION,M.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE,M.ERR_PUBLISH_REQUEST_INVALID,M.ERR_SUBSCRIBE_REQUEST_INVALID,M.ERR_NOT_SUPPORTED_MESSAGE,M.ERR_ILLEAGAL_PLUGIN,M.ILLEGAL_CLIENT_ROLE_LEVEL,M.ERR_REJOIN_TOKEN_INVALID,M.ERR_REJOIN_USER_NOT_JOINED,M.ERR_INVALID_OPTIONAL_INFO,M.ERR_TEST_RECOVER,M.ERR_TEST_TRYNEXT,M.ERR_TEST_RETRY,M.ILLEGAL_AES_PASSWORD,M.ERR_TOO_MANY_BROADCASTERS,M.ERR_TOO_MANY_SUBSCRIBERS,M.ERR_LICENSE_ILLEGAL,M.ERR_LICENSE_MISSING,M.ERR_LICENSE_EXPIRED,M.ERR_LICENSE_MINUTES_EXCEEDED,M.ERR_LICENSE_PERIOD_INVALID,M.ERR_LICENSE_MULTIPLE_SDK_SERVICE;let p=function(e){return e.CHINA="CHINA",e.ASIA="ASIA",e.NORTH_AMERICA="NORTH_AMERICA",e.EUROPE="EUROPE",e.JAPAN="JAPAN",e.INDIA="INDIA",e.KOREA="KOREA",e.HKMC="HKMC",e.US="US",e.OCEANIA="OCEANIA",e.SOUTH_AMERICA="SOUTH_AMERICA",e.AFRICA="AFRICA",e.OVERSEA="OVERSEA",e.GLOBAL="GLOBAL",e.EXTENSIONS="EXTENSIONS",e}({});p.AFRICA,p.ASIA,p.CHINA,p.EUROPE,p.GLOBAL,p.INDIA,p.JAPAN,p.NORTH_AMERICA,p.OCEANIA,p.OVERSEA,p.SOUTH_AMERICA;let b=function(e){return e.CHINA="CN",e.ASIA="AS",e.NORTH_AMERICA="NA",e.EUROPE="EU",e.JAPAN="JP",e.INDIA="IN",e.KOREA="KR",e.HKMC="HK",e.US="US",e.OCEANIA="OC",e.SOUTH_AMERICA="SA",e.AFRICA="AF",e.OVERSEA="OVERSEA",e.GLOBAL="GLOBAL",e.EXTENSIONS="GLOBAL",e}({});b.ASIA,b.NORTH_AMERICA,b.EUROPE,b.JAPAN,b.INDIA,b.KOREA,b.HKMC,b.US,b.OVERSEA,b.GLOBAL,b.OCEANIA,b.SOUTH_AMERICA,b.AFRICA,n&&b.CHINA;const v={GLOBAL:{ASIA:[p.CHINA,p.JAPAN,p.INDIA,p.KOREA,p.HKMC],EUROPE:[],NORTH_AMERICA:[p.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}};Object.keys(v[p.GLOBAL]),p.CHINA,p.NORTH_AMERICA,p.EUROPE,p.ASIA,p.JAPAN,p.INDIA,p.OCEANIA,p.SOUTH_AMERICA,p.AFRICA,p.KOREA,p.HKMC,p.US;let y=1;function B(n,i,r,c){const a={command:"convergeAllocateEdge",sid:i.sid,appId:i.appId,token:i.token,ts:Date.now(),version:_,cname:i.cname,uid:i.uid.toString(),requestId:y,seq:y};y+=1;const R={service_name:"tele_channel",json_body:JSON.stringify(a)};return o((async()=>{const _=await function(n,_,o,i){return new Promise(((r,c)=>{_.timeout=_.timeout||e("HTTP_CONNECT_TIMEOUT"),_.responseType=_.responseType||"json",_.data&&!o?(_.data=JSON.stringify(_.data),g+=t(_.data)):o&&(_.data.size?g+=_.data.size:_.data instanceof FormData?g+=s(_.data):g+=t(JSON.stringify(_.data))),_.headers=_.headers||{},_.headers["Content-Type"]=_.headers["Content-Type"]||"application/json",_.method="POST",_.url=n,u.request(_).then((e=>{"string"==typeof e.data?V+=t(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?V+=e.data.byteLength:V+=t(JSON.stringify(e.data)),i&&r({data:e.data,headers:e.headers}),r(e.data)})).catch((e=>{u.isCancel(e)?c(new L(E.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?c(new L(E.NETWORK_TIMEOUT,e.message)):e.response?c(new L(E.NETWORK_RESPONSE_ERROR,e.response.status)):c(new L(E.NETWORK_ERROR,e.message))}))}))}(n,{data:R,cancelToken:r,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":61}});if(0!==_.code){const e=new L(d.UNEXPECTED_RESPONSE,"cross channel ap error, code"+_.code,{retry:!0});throw l.error(e.toString()),e}const o=JSON.parse(_.json_body);if(200!==o.code){const e=new L(d.UNEXPECTED_RESPONSE,"cross channel app center error, code: ".concat(o.code,", reason: ").concat(o.reason));throw l.error(e.toString()),e}if(!o.servers||0===o.servers.length){const e=new L(d.UNEXPECTED_RESPONSE,"cross channel app center empty server");throw l.error(e.toString()),e}return{vid:o.vid,workerToken:o.workerToken,addressList:(e("CHANNEL_MEDIA_RELAY_SERVERS")||o.servers).map((t=>"wss://".concat(t.address.replace(/\./g,"-"),".").concat(e("WORKER_DOMAIN"),":").concat(t.wss)))}}),void 0,(e=>!!(e.code!==d.OPERATION_ABORTED&&e.code!==d.UNEXPECTED_RESPONSE||e.data&&e.data.retry)),c)}async function K(t,s,E){const n=e("UAP_AP").slice(0,e("AJAX_REQUEST_CONCURRENT")).map((e=>t.proxyServer?"https://".concat(t.proxyServer,"/ap/?url=").concat(e+"/api/v1?action=uap"):"https://".concat(e,"/api/v1?action=uap"))).map((e=>B(e,t,s,E)));try{const e=await(_=n,Promise.all(_.map((e=>e.then((e=>{throw e}),(e=>e))))).then((e=>{throw e}),(e=>e)));return n.forEach((e=>e.cancel())),e}catch(e){throw e[0]}var _}let k=function(e){return e.CONNECTED="websocket:connected",e.RECONNECTING="websocket:reconnecting",e.WILL_RECONNECT="websocket:will_reconnect",e.CLOSED="websocket:closed",e.FAILED="websocket:failed",e.ON_MESSAGE="websocket:on_message",e.REQUEST_NEW_URLS="websocket:request_new_urls",e.RECONNECT_WAITTING_FINISH="websocket:reconnect_waitting_finish",e.RECONNECT_CREATE_CONNECTION="websocket:reconnect_create_connection",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="websocket:on_token_privilege_did_expire",e}({}),H=function(e){return e[e.SetSdkProfile=0]="SetSdkProfile",e[e.SetSourceChannel=1]="SetSourceChannel",e[e.SetSourceUserId=2]="SetSourceUserId",e[e.SetDestChannel=3]="SetDestChannel",e[e.StartPacketTransfer=4]="StartPacketTransfer",e[e.StopPacketTransfer=5]="StopPacketTransfer",e[e.UpdateDestChannel=6]="UpdateDestChannel",e[e.Reconnect=7]="Reconnect",e[e.SetVideoProfile=8]="SetVideoProfile",e}({}),Y=function(e){return e.NETWORK_DISCONNECTED="NETWORK_DISCONNECTED",e.NETWORK_CONNECTED="NETWORK_CONNECTED",e.PACKET_JOINED_SRC_CHANNEL="PACKET_JOINED_SRC_CHANNEL",e.PACKET_JOINED_DEST_CHANNEL="PACKET_JOINED_DEST_CHANNEL",e.PACKET_SENT_TO_DEST_CHANNEL="PACKET_SENT_TO_DEST_CHANNEL",e.PACKET_RECEIVED_VIDEO_FROM_SRC="PACKET_RECEIVED_VIDEO_FROM_SRC",e.PACKET_RECEIVED_AUDIO_FROM_SRC="PACKET_RECEIVED_AUDIO_FROM_SRC",e.PACKET_UPDATE_DEST_CHANNEL="PACKET_UPDATE_DEST_CHANNEL",e.PACKET_UPDATE_DEST_CHANNEL_REFUSED="PACKET_UPDATE_DEST_CHANNEL_REFUSED",e.PACKET_UPDATE_DEST_CHANNEL_NOT_CHANGE="PACKET_UPDATE_DEST_CHANNEL_NOT_CHANGE",e}({}),W=function(e){return e.RELAY_STATE_IDLE="RELAY_STATE_IDLE",e.RELAY_STATE_CONNECTING="RELAY_STATE_CONNECTING",e.RELAY_STATE_RUNNING="RELAY_STATE_RUNNING",e.RELAY_STATE_FAILURE="RELAY_STATE_FAILURE",e}({}),G=function(e){return e.RELAY_OK="RELAY_OK",e.SERVER_CONNECTION_LOST="SERVER_CONNECTION_LOST",e.SRC_TOKEN_EXPIRED="SRC_TOKEN_EXPIRED",e.DEST_TOKEN_EXPIRED="DEST_TOKEN_EXPIRED",e}({}),F=function(e){return e.CONNECTED="transmitter:connected",e.RECONNECTING="transmitter:reconnecting",e.WILL_RECONNECT="transmitter:will_reconnect",e.CLOSED="transmitter:closed",e.FAILED="transmitter:failed",e.ON_MESSAGE="transmitter:on_message",e.REQUEST_NEW_URLS="transmitter:request_new_urls",e.RECONNECT_WAITTING_FINISH="transmitter:reconnect_waitting_finish",e.RECONNECT_CREATE_CONNECTION="transmitter:reconnect_create_connection",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="transmitter:on_token_privilege_did_expire",e.TO_CONNECT_DATACHANNEL="transmitter:to_connect_datachannel",e.FAILBACK="transmitter:failback",e.PRE_CONNECT_PC="transmitter:pre_connect_pc",e}({});class J extends i{get url(){return this.websocket&&this.websocket.url||null}get reconnectMode(){return this._reconnectMode}set reconnectMode(e){["tryNext","recover"].includes(e)&&this.resetReconnectCount(e),this._reconnectMode=e}get state(){return this._state}set state(e){e!==this._state&&(this._state=e,"reconnecting"===this._state?this.emit(k.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(k.CONNECTED):"closed"===this._state?this.emit(k.CLOSED):"failed"===this._state&&this.emit(k.FAILED))}resetReconnectCount(e){l.debug("websocket reset reconnect count, reason: "+e),this.reconnectCount=0}constructor(e,t){let s=arguments.length>2&&void 0!==arguments[2]&&arguments[2],E=arguments.length>3&&void 0!==arguments[3]&&arguments[3],n=arguments.length>4&&void 0!==arguments[4]&&arguments[4],_=arguments.length>5?arguments[5]:void 0;super(),this.connectionID=0,this.currentURLIndex=0,this.urls=[],this._reconnectMode="tryNext",this.reconnectReason=void 0,this._initMutex=new r("websocket"),this.name=void 0,this._state="closed",this.reconnectInterrupter=void 0,this.websocket=void 0,this.retryConfig=void 0,this.reconnectCount=0,this.forceCloseTimeout=5e3,this.onlineReconnectListener=void 0,this.useCompress=void 0,this.tryDoubleDomain=!1,this.use443PortOnly=!1,this.wsInflateLength=0,this.wsDeflateLength=0,this.closeEstablishingWs=()=>{},this.store=void 0,this.joinGatewayRecordIndex=void 0,this.store=_,this.name=e,this.retryConfig=function(e){for(var t=1;t{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===c.ONLINE?(this.retryConfig.timeout=I,this.retryConfig.timeoutFactor=A):(this.retryConfig.timeout=o,this.retryConfig.timeoutFactor=i))}))}getConnection(){return this.websocket||void 0}async init(t){let s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const n=await this._initMutex.lock();this.forceCloseTimeout=s,this.urls=t,this.state="connecting";try{const t=I(),s=this.urls[this.currentURLIndex];e("ENABLE_PREALLOC_PC")&&this.emit(F.PRE_CONNECT_PC),this.createWebSocketConnection(s).then(t.resolve).catch(t.reject),this.once(k.CLOSED,(()=>{t.reject(new A(E.WS_DISCONNECT))})),this.once(k.CONNECTED,t.resolve),await t.promise}catch(e){}finally{n()}}close(e,t){if(this.currentURLIndex=0,this.resetReconnectCount("close"),this.reconnectInterrupter&&this.reconnectInterrupter(),this.websocket){this.websocket.onclose=null,this.websocket.onopen=null,this.websocket.onmessage=null;const e=this.websocket;t?setTimeout((()=>e.close()),500):e.close(),this.websocket=void 0}this.state=e?"failed":"closed",this.closeEstablishingWs&&this.closeEstablishingWs()}reconnect(e,t){if(!this.websocket)return void l.warning("[".concat(this.name,"] can not reconnect, no websocket"));void 0!==e&&(this.reconnectMode=e),l.debug("[".concat(this.name,"] reconnect is triggered initiative")),"number"==typeof this.joinGatewayRecordIndex&&this.store&&this.store.recordJoinChannelService({status:"error",errors:[new Error(t)]},this.joinGatewayRecordIndex);const s=this.websocket.onclose;this.websocket.onclose=null,this.websocket.close(),s&&s.bind(this.websocket)({code:9999,reason:t})}sendMessage(e){let t=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new A(E.WS_ABORT,"websocket is not ready");try{t||(e=JSON.stringify(e)),this.websocket.send(e)}catch(e){throw new A(E.WS_ERR,"send websocket message error"+e.toString())}}setWsInflateData(e){this.wsDeflateLength=this.wsDeflateLength+e.originLength,this.wsInflateLength=this.wsInflateLength+e.compressedLength}getWsInflateData(){const e=this.wsInflateLength,t=this.wsDeflateLength;return this.clearWsInflateData(),{wsInflateLength:e,wsDeflateLength:t}}clearWsInflateData(){this.wsInflateLength=0,this.wsDeflateLength=0}async createWebSocketConnection(t){var s;const n=I();this.connectionID+=1,this.joinGatewayRecordIndex=void 0;const _=e=>{var t;null===(t=this.store)||void 0===t||t.signalChannelOpen(),l.debug("[".concat(this.name,"] websocket opened:"),e),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),n.resolve()},o=async e=>{var t;if(l.debug("[".concat(this.name,"] websocket close ").concat(null===(t=this.websocket)||void 0===t?void 0:t.url,", code: ").concat(e.code,", reason: ").concat(e.reason,", current mode: ").concat(this.reconnectMode)),this.reconnectCount>=this.retryConfig.maxRetryCount)n.reject(new A(E.WS_DISCONNECT,"websocket close: ".concat(e.code))),this.close();else{"connected"===this.state&&(this.reconnectReason=e.reason,this.state="reconnecting");const t=C(this,k.WILL_RECONNECT,this.reconnectMode,e.reason)||this.reconnectMode,s=await this.reconnectWithAction(t);if("closed"===this.state)return void l.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!s)return n.reject(new A(E.WS_DISCONNECT,"websocket reconnect failed: ".concat(e.code))),this.close(!0);n.resolve()}},i=e=>{this.emit(k.ON_MESSAGE,e)},r=e=>{l.warn("[".concat(this.connectionID,"] ws open error ").concat(e))};this.websocket&&(this.websocket.onclose=null,this.websocket.close()),e("GATEWAY_WSS_ADDRESS")&&this.name.startsWith("gateway")&&(t=e("GATEWAY_WSS_ADDRESS")),l.debug("[".concat(this.name,"] start connect, url:"),t);const c=null===(s=this.store)||void 0===s?void 0:s.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"});try{var a;const e=await this.chooseBestWebsocketConnection(t);this.websocket=e,_&&_(this.websocket.url),this.websocket.onclose=o,this.websocket.onmessage=i,this.websocket.onerror=r,null===(a=this.store)||void 0===a||a.recordJoinChannelService({endTs:Date.now(),status:"success"},c),this.joinGatewayRecordIndex=c}catch(e){const t="closed"===this.state,s=e instanceof A,_=s&&e.code===E.WS_ABORT,i=s&&e.code===E.WS_ERR,r=s?e.message:e&&(e.reason||e.toString());l.warning("[choose-best-ws] chooseBestWebsocket error: ".concat(r)),this.store&&this.store.recordJoinChannelService({endTs:Date.now(),status:_?"aborted":"error",errors:[e]},c),t||i?(n.reject(t?new A(E.WS_DISCONNECT,"websocket is closed: ".concat(r)):new A(E.WS_ERR,"init websocket failed: ".concat(r))),i&&l.error("[".concat(this.name,"] init websocket failed: ").concat(r))):o&&o(e)}return n.promise}async reconnectWithAction(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(this.reconnectCount>=this.retryConfig.maxRetryCount)return!1;if(0===this.urls.length)return!1;if("closed"===this.state)return!1;l.warning("[choose-best-ws] action: =>",e),this.onlineReconnectListener||a.isOnline||!a.onlineWaiter||(this.onlineReconnectListener=a.onlineWaiter.then((()=>{this.onlineReconnectListener=void 0})));let s=!0;if(this.reconnectInterrupter=()=>s=!1,t){const t=N(this.reconnectCount,this.retryConfig);l.debug("[".concat(this.name,"] wait ").concat(t,"ms to reconnect websocket, mode: ").concat(e)),await Promise.race([h(t),this.onlineReconnectListener||new Promise((()=>{}))])}if("closed"===this._state||!s)return!1;this.reconnectCount+=1;const E=async(e,t)=>{this.emit(k.RECONNECT_CREATE_CONNECTION,t),await this.createWebSocketConnection(e)};try{if("retry"===e)this.emit(k.RECONNECT_WAITTING_FINISH,e),await E(this.urls[this.currentURLIndex],e);else if("tryNext"===e){if(this.currentURLIndex+=1,this.currentURLIndex>=this.urls.length)return this.reconnectWithAction("recover",!1);l.debug("[".concat(this.name,"] websocket url length: ").concat(this.urls.length," current index: ").concat(this.currentURLIndex)),this.emit(k.RECONNECT_WAITTING_FINISH,e),await E(this.urls[this.currentURLIndex],e)}else"recover"===e&&(l.debug("[".concat(this.name,"] request new urls")),this.resetReconnectCount("recover mode"),this.emit(k.RECONNECT_WAITTING_FINISH,e),this.urls=await S(this,k.REQUEST_NEW_URLS),this.currentURLIndex=0,await E(this.urls[this.currentURLIndex],e))}catch(s){var n;l.error("[".concat(this.name,"] reconnect failed ").concat(s&&s.toString()));const E=null==s||null===(n=s.data)||void 0===n?void 0:n.desc;return Array.isArray(E)&&E.includes("dynamic key expired")?(this.emit(k.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):this.reconnectWithAction(e,t)}return!0}}class j extends J{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2],arguments.length>3&&void 0!==arguments[3]&&arguments[3],arguments.length>4&&void 0!==arguments[4]&&arguments[4],arguments.length>5?arguments[5]:void 0)}async chooseBestWebsocketConnection(t,s){return new Promise(((n,_)=>{let o=!1;const i=[];this.closeEstablishingWs=()=>{l.debug("[choose-best-ws] close establishing websockets"),i.forEach((e=>{e.onclose=null,e.onopen=null,e.onmessage=null,e.close()})),_(new A(E.WS_ABORT,"choose best websocket aborted"))};const r=e("GATEWAY_DOMAINS");let c;const a=t.indexOf("?h="),R=r.find((e=>-1!==a?t.includes(e,a):t.includes(e)));l.debug("[choose-best-ws] currentDomain: ",R,", domains: ",r);let I=!this.tryDoubleDomain||!R;if(!I&&R){var N;const e=Date.now();try{r.forEach((e=>{const s=-1===a?t.replace(R,e):t.substr(0,a)+t.substr(a).replace(R,e),E=new WebSocket(s);E.binaryType="arraybuffer",i.push(E),l.debug("[choose-best-ws] ws is connecting:",E.url)}))}catch(e){for(l.debug("[choose-best-ws] ws create failed, fallback to single url"),i.forEach((e=>e.close()));i.length;)i.pop();I=!0}null===(N=this.store)||void 0===N||N.recordJoinChannelService({urls:i.map((e=>e.url)),service:"gateway"},s),i.forEach((t=>{t.onopen=()=>{if(o)return;const s=Date.now()-e;l.debug("[choose-best-ws] ws open cost ".concat(s,"ms")),i.filter((e=>e!==t)).forEach((e=>{l.debug("[choose-best-ws]close backup websocket: ".concat(e.url)),e.close()})),o=!0,n(t)},t.onclose=e=>{if(c=e,o)return;i.find((e=>!(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING)))||(l.debug("[choose-best-ws] all websocket is closed"),o=!0,_(c))},t.onmessage=e=>{l.debug("[choose-best-ws]".concat(t.url," onmessage: ").concat(e.data))}})),h(this.forceCloseTimeout).then((()=>{i.forEach((e=>{e.readyState!==WebSocket.OPEN&&e.close()}))}))}if(I){var S;let e;l.debug("[choose-best-ws] use single url: ",t),null===(S=this.store)||void 0===S||S.recordJoinChannelService({urls:[t],service:"gateway"},s);try{e=new WebSocket(t),i.push(e),e.binaryType="arraybuffer"}catch(e){const t=new A(E.WS_ERR,"init websocket failed! Error: ".concat(e.toString()));return l.error("[".concat(this.name,"]").concat(t)),void _(t)}e.onopen=()=>{n(e)},e.onclose=e=>{_(e)},e.onmessage=t=>{l.debug("[choose-best-ws]".concat(e.url," onmessage: ").concat(t.data))},h(this.forceCloseTimeout).then((()=>{e&&e.readyState!==WebSocket.OPEN&&e.close()}))}})).then((e=>(this.closeEstablishingWs=void 0,e))).catch((e=>{throw this.closeEstablishingWs=void 0,e}))}}class q extends i{constructor(e,t,s){super(),this.ws=void 0,this.requestId=1,this.heartBeatTimer=void 0,this.joinInfo=void 0,this.clientId=void 0,this.onOpen=()=>{this.emit("open"),this.startHeartBeatCheck()},this.onClose=e=>{this.emit("close"),this.dispose()},this.onMessage=e=>{const t=JSON.parse(e.data);if(!t||"serverResponse"!==t.command||!t.requestId)return t&&"serverStatus"===t.command&&t.serverStatus&&t.serverStatus.command?(this.emit("status",t.serverStatus),void this.emit(t.serverStatus.command,t.serverStatus)):void 0;this.emit("req_".concat(t.requestId),t)},this.joinInfo=e,this.clientId=t,this.ws=new j("cross-channel-".concat(this.clientId),s),this.ws.on(k.RECONNECTING,(()=>{this.ws.reconnectMode="retry",this.emit("reconnecting")})),this.ws.on(k.CONNECTED,this.onOpen),this.ws.on(k.ON_MESSAGE,this.onMessage),this.ws.on(k.CLOSED,this.onClose)}isConnect(){return"connected"===this.ws.state}sendMessage(e){const t=this.requestId++;return e.requestId=t,e.seq=t,this.ws.sendMessage(e),t}waitStatus(e){return new Promise(((t,s)=>{const E=window.setTimeout((()=>{s(new L(d.TIMEOUT,"wait status timeout, status: ".concat(e)))}),5e3);this.once(e,(n=>{window.clearTimeout(E),n.state&&0!==n.state?s(new L(d.CROSS_CHANNEL_WAIT_STATUS_ERROR,"wait status error, status: ".concat(e))):t(void 0)})),this.once("dispose",(()=>{window.clearTimeout(E),s(new L(d.WS_ABORT))}))}))}async request(e){if("closed"===this.ws.state)throw new L(d.WS_DISCONNECT);const t=()=>new Promise(((e,t)=>{this.ws.once(k.CLOSED,(()=>t(new L(d.WS_ABORT)))),this.ws.once(k.CONNECTED,e)}));"connected"!==this.ws.state&&await t();const s=this.sendMessage(e),E=new Promise(((e,t)=>{const E=()=>{t(new L(d.WS_ABORT))};this.ws.once(k.RECONNECTING,E),this.ws.once(k.CLOSED,E),this.once("req_".concat(s),e),h(3e3).then((()=>{this.removeAllListeners("req_".concat(s)),this.ws.off(k.RECONNECTING,E),this.ws.off(k.CLOSED,E),t(new L(d.TIMEOUT,"cross channel ws request timeout"))}))})),n=await E;if(!n||200!==n.code)throw new L(d.CROSS_CHANNEL_SERVER_ERROR_RESPONSE,"response: ".concat(JSON.stringify(n)));return n}async connect(e){this.ws.removeAllListeners(k.REQUEST_NEW_URLS),this.ws.on(k.REQUEST_NEW_URLS,(t=>{t(e)})),await this.ws.init(e)}dispose(){this.clearHeartBeatCheck(),this.emit("dispose"),this.removeAllListeners(),this.ws.close()}sendPing(e){const t=this.requestId++;return e.requestId=t,this.ws.sendMessage(e),t}startHeartBeatCheck(){this.heartBeatTimer&&window.clearInterval(this.heartBeatTimer),this.heartBeatTimer=window.setInterval((()=>{this.sendPing({command:"ping",appId:this.joinInfo.appId,cname:this.joinInfo.cname,uid:this.joinInfo.uid.toString(),sid:this.joinInfo.sid,ts:+new Date,requestId:0})}),3e3)}clearHeartBeatCheck(){window.clearInterval(this.heartBeatTimer),this.heartBeatTimer=void 0}}class X extends i{set state(e){e!==this._state&&(e!==W.RELAY_STATE_FAILURE&&(this.errorCode=G.RELAY_OK),this.emit("state",e,this.errorCode),this._state=e)}get state(){return this._state}constructor(e,t,s,E,n){super(),this.joinInfo=void 0,this.sid=void 0,this.clientId=void 0,this.cancelToken=u.CancelToken.source(),this.workerToken=void 0,this.requestId=0,this.signal=void 0,this.prevChannelMediaConfig=void 0,this.httpRetryConfig=void 0,this._resolution=void 0,this._state=W.RELAY_STATE_IDLE,this.errorCode=G.RELAY_OK,this.onStatus=e=>{l.debug("[".concat(this.clientId,"] ChannelMediaStatus: ").concat(JSON.stringify(e))),e&&e.command&&("onAudioPacketReceived"===e.command&&this.emit("event",Y.PACKET_RECEIVED_AUDIO_FROM_SRC),"onVideoPacketReceived"===e.command&&this.emit("event",Y.PACKET_RECEIVED_VIDEO_FROM_SRC),"onSrcTokenPrivilegeDidExpire"===e.command&&(this.errorCode=G.SRC_TOKEN_EXPIRED,this.state=W.RELAY_STATE_FAILURE),"onDestTokenPrivilegeDidExpire"===e.command&&(this.errorCode=G.DEST_TOKEN_EXPIRED,this.state=W.RELAY_STATE_FAILURE))},this.onReconnect=async()=>{l.debug("[".concat(this.clientId,"] ChannelMediaSocket disconnect, reconnecting")),this.emit("event",Y.NETWORK_DISCONNECTED),this.state=W.RELAY_STATE_IDLE,this.prevChannelMediaConfig&&this.sendStartRelayMessage(this.prevChannelMediaConfig).catch((e=>{this.state!==W.RELAY_STATE_IDLE&&(l.error("auto restart channel media relay failed",e.toString()),this.errorCode=G.SERVER_CONNECTION_LOST,this.state=W.RELAY_STATE_FAILURE)}))},this.joinInfo=e,this.clientId=t,this.sid=T(),this.signal=new q(this.joinInfo,this.clientId,s),this.httpRetryConfig=E,this._resolution=n}async startChannelMediaRelay(e){if(this.state!==W.RELAY_STATE_IDLE)throw new L(d.INVALID_OPERATION);this.state=W.RELAY_STATE_CONNECTING,await this.connect(),l.debug("[".concat(this.clientId,"] startChannelMediaRelay: connect success"));try{await this.sendStartRelayMessage(e)}catch(e){if(e.data&&e.data.serverResponse&&"SetSourceChannel"===e.data.serverResponse.command)throw new L(d.CROSS_CHANNEL_FAILED_JOIN_SRC);if(e.data&&e.data.serverResponse&&"SetDestChannelStatus"===e.serverResponse.command)throw new L(d.CROSS_CHANNEL_FAILED_JOIN_DEST);if(e.data&&e.data.serverResponse&&"StartPacketTransfer"===e.serverResponse.command)throw new L(d.CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST);throw e}this.prevChannelMediaConfig=e}async updateChannelMediaRelay(e){if(this.state!==W.RELAY_STATE_RUNNING)throw new L(d.INVALID_OPERATION);await this.sendUpdateMessage(e),this.prevChannelMediaConfig=e}async setVideoProfile(e){if(this._resolution=e,this.state!==W.RELAY_STATE_RUNNING)throw new L(d.INVALID_OPERATION);const t=this.genMessage(H.SetVideoProfile);await this.signal.request(t),l.debug("[".concat(this.clientId,"] startChannelMediaRelay: setVideoProfile success"))}async stopChannelMediaRelay(){await this.sendStopRelayMessage(),l.debug("[".concat(this.clientId,"] stopChannelMediaRelay: send stop message success")),this.state=W.RELAY_STATE_IDLE,this.dispose()}dispose(){l.debug("[".concat(this.clientId,"] disposeChannelMediaRelay")),this.cancelToken.cancel(),this.cancelToken=u.CancelToken.source(),this.state=W.RELAY_STATE_IDLE,this.emit("dispose"),this.signal.dispose(),this.prevChannelMediaConfig=void 0}async connect(){const e=await K(this.joinInfo,this.cancelToken.token,this.httpRetryConfig);this.workerToken=e.workerToken,await this.signal.connect(e.addressList),this.emit("event",Y.NETWORK_CONNECTED),this.signal.on("status",this.onStatus),this.signal.on("reconnecting",this.onReconnect)}async sendStartRelayMessage(e){const t=this.genMessage(H.StopPacketTransfer);await this.signal.request(t),await this.signal.waitStatus("Normal Quit"),l.debug("[".concat(this.clientId,"] startChannelMediaRelay: StopPacketTransfer success"));const s=this.genMessage(H.SetSdkProfile,e);await this.signal.request(s),l.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSdkProfile success"));const E=this.genMessage(H.SetSourceChannel,e);await this.signal.request(E),await this.signal.waitStatus("SetSourceChannelStatus"),this.emit("event",Y.PACKET_JOINED_SRC_CHANNEL),l.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceChannel success"));const n=this.genMessage(H.SetSourceUserId,e);await this.signal.request(n),l.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceUserId success"));const _=this.genMessage(H.SetDestChannel,e);await this.signal.request(_),await this.signal.waitStatus("SetDestChannelStatus"),this.emit("event",Y.PACKET_JOINED_DEST_CHANNEL),l.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetDestChannel success"));const o=this.genMessage(H.StartPacketTransfer,e);await this.signal.request(o),this.emit("event",Y.PACKET_SENT_TO_DEST_CHANNEL),this.state=W.RELAY_STATE_RUNNING,l.debug("[".concat(this.clientId,"] startChannelMediaRelay: StartPacketTransfer success")),this.setVideoProfile(this._resolution)}async sendUpdateMessage(e){const t=this.genMessage(H.UpdateDestChannel,e);await this.signal.request(t),this.emit("event",Y.PACKET_UPDATE_DEST_CHANNEL),l.debug("[".concat(this.clientId,"] sendUpdateMessage: UpdateDestChannel success"))}async sendStopRelayMessage(){const e=this.genMessage(H.StopPacketTransfer);await this.signal.request(e),l.debug("[".concat(this.clientId,"] sendStopRelayMessage: StopPacketTransfer success"))}genMessage(e,t){const s=[],E=[],n=[];this.requestId+=1;const o={appId:this.joinInfo.appId,cname:this.joinInfo.cname,uid:this.joinInfo.uid.toString(),sdkVersion:_,sid:this.sid,ts:Date.now(),requestId:this.requestId,seq:this.requestId,allocate:!0,clientRequest:{}};"4.22.1"===o.sdkVersion&&(o.sdkVersion="0.0.1");let i=null,r=null;switch(e){case H.SetSdkProfile:return o.clientRequest={command:"SetSdkProfile",type:"multi_channel"},o;case H.SetSourceChannel:if(r=t&&t.getSrcChannelMediaInfo(),!r)throw new L(d.UNEXPECTED_ERROR,"can not find source config");return o.clientRequest={command:"SetSourceChannel",uid:"0",channelName:r.channelName,token:r.token||this.joinInfo.appId},o;case H.SetSourceUserId:if(r=t&&t.getSrcChannelMediaInfo(),!r)throw new L(d.UNEXPECTED_ERROR,"can not find source config");return o.clientRequest={command:"SetSourceUserId",uid:r.uid+""},o;case H.SetDestChannel:if(i=t&&t.getDestChannelMediaInfo(),!i)throw new L(d.UNEXPECTED_ERROR,"can not find dest config");return i.forEach((e=>{s.push(e.channelName),E.push(e.uid+""),n.push(e.token||this.joinInfo.appId)})),o.clientRequest={command:"SetDestChannel",channelName:s,uid:E,token:n},o;case H.StartPacketTransfer:return o.clientRequest={command:"StartPacketTransfer"},o;case H.Reconnect:return o.clientRequest={command:"Reconnect"},o;case H.StopPacketTransfer:return o.clientRequest={command:"StopPacketTransfer"},o;case H.UpdateDestChannel:if(i=t&&t.getDestChannelMediaInfo(),!i)throw new L(d.UNEXPECTED_ERROR,"can not find dest config");return i.forEach((e=>{s.push(e.channelName),E.push(e.uid+""),n.push(e.token||this.joinInfo.appId)})),o.clientRequest={command:"UpdateDestChannel",channelName:s,uid:E,token:n},o;case H.SetVideoProfile:o.clientRequest={command:"SetVideoProfile",width:this._resolution.width,height:this._resolution.height}}return o}}const x={name:"ChannelMediaRelay",create:function(e){return new X(e.joinInfo,e.clientId,e.websocketRetryConfig||O,e.httpRetryConfig||O,e.resolution)}};export{x as ChannelMediaRelayService};