UNPKG

agora-rtc-sdk-ng

Version:
6 lines (4 loc) 37.8 kB
/** * AgoraWebSDK_N-v4.24.8-0-gf100be755-dirty Copyright AgoraInc. */ import{getParameter as e,getUTF8StringByteLength as t,getMultiUnilbsFormDataByteLength as n,AgoraRTCErrorCode as s,IS_GLOBAL_VERSION as E,VERSION as o,retryable as _,EventEmitter as i,PromiseMutex as c,NETWORK_STATE as r,networkIndicator as a,NETWORK_INDICATOR_EVENTS as R,createDefer as A,AgoraRTCError as I,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"@agora-js/protocol";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,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var s=n.call(e,t||"default");if("object"!=typeof s)return s;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:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function w(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,s)}return n}let g=0,V=0;let U=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}({}),f=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}({}),P=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[e.REQ_DOWNGRADE_FALLBACK=27]="REQ_DOWNGRADE_FALLBACK",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.DATASTREAM2_NOT_AVAILABLE=27]="DATASTREAM2_NOT_AVAILABLE",e[e.K_AUTO_REBALANCE=28]="K_AUTO_REBALANCE",e[e.K_VOS_FALLBACK=30]="K_VOS_FALLBACK",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_TOO_MANY_MESSAGES=2033]="ERR_TOO_MANY_MESSAGES",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}({});U.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,U.UNILBS,P.INVALID_VENDOR_KEY,P.INVALID_CHANNEL_NAME,P.INTERNAL_ERROR,P.NO_AUTHORIZED,P.DYNAMIC_KEY_TIMEOUT,P.NO_ACTIVE_STATUS,P.DYNAMIC_KEY_EXPIRED,P.STATIC_USE_DYNAMIC_KEY,P.DYNAMIC_USE_STATIC_KEY,P.USER_OVERLOAD,P.FORBIDDEN_REGION,P.CANNOT_MEET_AREA_DEMAND,P.REQ_DOWNGRADE_FALLBACK,U.STRING_UID_ALLOCATOR,f.IIIEGAL_APPID,f.IIIEGAL_UID,f.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.DATASTREAM2_NOT_AVAILABLE,m.K_AUTO_REBALANCE,m.K_VOS_FALLBACK,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_TOO_MANY_MESSAGES,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,E&&b.CHINA;const y={GLOBAL:{ASIA:[p.CHINA,p.JAPAN,p.INDIA,p.KOREA,p.HKMC],EUROPE:[],NORTH_AMERICA:[p.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}};Object.keys(y[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 B=1;function K(E,i,c,r){const a={command:"convergeAllocateEdge",sid:i.sid,appId:i.appId,token:i.token,ts:Date.now(),version:o,cname:i.cname,uid:i.uid.toString(),requestId:B,seq:B};B+=1;const R={service_name:"tele_channel",json_body:JSON.stringify(a)};return _((async()=>{const o=await function(E,o,_,i){return new Promise(((c,r)=>{o.timeout=o.timeout||e("HTTP_CONNECT_TIMEOUT"),o.responseType=o.responseType||"json",o.data&&!_?(o.data=JSON.stringify(o.data),g+=t(o.data)):_&&(o.data.size?g+=o.data.size:o.data instanceof FormData?g+=n(o.data):g+=t(JSON.stringify(o.data))),o.headers=o.headers||{},o.headers["Content-Type"]=o.headers["Content-Type"]||"application/json",o.method="POST",o.url=E,u.request(o).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&&c({data:e.data,headers:e.headers}),c(e.data)})).catch((e=>{u.isCancel(e)?r(new L(s.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?r(new L(s.NETWORK_TIMEOUT,e.message)):e.response?r(new L(s.NETWORK_RESPONSE_ERROR,e.response.status)):r(new L(s.NETWORK_ERROR,e.message))}))}))}(E,{data:R,cancelToken:c,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":61}});if(0!==o.code){const e=new L(d.UNEXPECTED_RESPONSE,"cross channel ap error, code"+o.code,{retry:!0});throw l.error(e.toString()),e}const _=JSON.parse(o.json_body);if(200!==_.code){const e=new L(d.UNEXPECTED_RESPONSE,"cross channel app center error, code: ".concat(_.code,", reason: ").concat(_.reason));throw l.error(e.toString()),e}if(!_.servers||0===_.servers.length){const e=new L(d.UNEXPECTED_RESPONSE,"cross channel app center empty server");throw l.error(e.toString()),e}return{vid:_.vid,workerToken:_.workerToken,addressList:(e("CHANNEL_MEDIA_RELAY_SERVERS")||_.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)),r)}async function v(t,n,s){const E=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=>K(e,t,n,s)));try{const e=await(o=E,Promise.all(o.map((e=>e.then((e=>{throw e}),(e=>e))))).then((e=>{throw e}),(e=>e)));return E.forEach((e=>e.cancel())),e}catch(e){throw e[0]}var o}let k=function(e){return e.CONNECTED="websocket:connected",e.RECONNECTING="websocket:reconnecting",e.WILL_RECONNECT="websocket:will_reconnect",e.SHOULD_ENTER_RECONNECTING="websocket:should_enter_reconnecting",e.CLOSED="websocket:closed",e.FAILED="websocket:failed",e.ON_MESSAGE="websocket:on_message",e.REQUEST_NEW_URLS="websocket:request_new_urls",e.RECONNECT_CREATE_CONNECTION="websocket:reconnect_create_connection",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="websocket:on_token_privilege_did_expire",e.ON_FALLBACK="websocket:on_fallback",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}({});class F extends i{get url(){return this.websocket&&this.websocket.url||this._websocketUrl}get reportUrl(){return"connected"===this._state&&this.websocket?this.websocket.url:this._lastAttemptedUrl}get reconnectMode(){return this._reconnectMode}set reconnectMode(e){["tryNext","recover"].includes(e)&&this.resetReconnectCount(e),this._reconnectMode=e}get isFirstJoin(){return this.queryReconnectingWhenConnecting}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 n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],s=arguments.length>3&&void 0!==arguments[3]&&arguments[3],E=arguments.length>4&&void 0!==arguments[4]&&arguments[4],o=arguments.length>5?arguments[5]:void 0;super(),this._websocketUrl=null,this._lastAttemptedUrl=null,this.connectionID=0,this.currentURLIndex=0,this.urls=[],this._reconnectMode="tryNext",this.reconnectReason=void 0,this._initMutex=void 0,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.queryReconnectingWhenConnecting=!1,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=o,this.name=e,this.retryConfig=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?w(Object(n),!0).forEach((function(t){D(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):w(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}({},t),this.useCompress=n,this.tryDoubleDomain=s,this.use443PortOnly=E,this._initMutex=new c("websocket",o?o.clientId:void 0);const _=t.timeout,i=t.timeoutFactor,A=Math.max(300,Math.floor(3*_/5)),I=Math.max(1.2,Math.floor(8*i)/10);r.ONLINE&&(this.retryConfig.timeout=A,this.retryConfig.timeoutFactor=I),a.on(R.NETWORK_STATE_CHANGE,((e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===r.ONLINE?(this.retryConfig.timeout=A,this.retryConfig.timeoutFactor=I):(this.retryConfig.timeout=_,this.retryConfig.timeoutFactor=i))}))}getConnection(){return this.websocket||void 0}disableQueryReconnectingWhenConnecting(){this.queryReconnectingWhenConnecting=!1}async init(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const E=await this._initMutex.lock();this._lastAttemptedUrl=null,this._reconnectMode="tryNext",this.forceCloseTimeout=t,this.queryReconnectingWhenConnecting=!0===n.queryReconnectingWhenConnecting,this.urls=e,this.state="connecting";try{var o;const e=A(),t=this.urls[this.currentURLIndex];null===(o=this.store)||void 0===o||o.beforeConnect(),this.createWebSocketConnection(t).then(e.resolve).catch(e.reject),this.once(k.CLOSED,(()=>{e.reject(new I(s.WS_DISCONNECT))})),this.once(k.CONNECTED,e.resolve),await e.promise}catch(e){}finally{E()}}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._websocketUrl=null}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 n=this.websocket.onclose;this.websocket.onclose=null,this.websocket.close(),n&&n.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 I(s.WS_ABORT,"websocket is not ready");try{t||(e=JSON.stringify(e)),this.websocket.send(e)}catch(e){throw new I(s.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 n;const E=A();this.connectionID+=1,this.joinGatewayRecordIndex=void 0;const o=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"),E.resolve()},_=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)E.reject(new I(s.WS_DISCONNECT,"websocket close: ".concat(e.code))),this.close();else{const t=this.queryReconnectingWhenConnecting;this.disableQueryReconnectingWhenConnecting();const n=t&&("connecting"===this.state||"connected"===this.state)&&!0===C(this,k.SHOULD_ENTER_RECONNECTING,e.reason);("connected"===this.state||n)&&(this.reconnectReason=e.reason,this.state="reconnecting");const o=C(this,k.WILL_RECONNECT,this.reconnectMode,e.reason)||this.reconnectMode,_=await this.reconnectWithAction(o);if("closed"===this.state)return void l.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!_)return E.reject(new I(s.WS_DISCONNECT,"websocket reconnect failed: ".concat(e.code))),this.close(!0);E.resolve()}},i=e=>{this.emit(k.ON_MESSAGE,e)},c=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 r=null===(n=this.store)||void 0===n?void 0:n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"});try{var a;const n=function(t,n){if("string"==typeof t)return t;const s=t.proxy,E=t.host,o=t.port;if(n){const t=e("JOIN_GATEWAY_FALLBACK_PORT")||443;return 443===t?"wss://".concat(E,"/ws/?p=").concat(Number(o)+150):"wss://".concat(E,":").concat(t,"/ws/?p=").concat(Number(o)+150)}return s?"wss://".concat(s,"/ws/?h=").concat(E,"&p=").concat(o):"wss://".concat(E,":").concat(o)}(t);this._websocketUrl=n,this._lastAttemptedUrl=n;const s=await this.chooseBestWebsocketConnection(t);this.websocket=s,o&&o(this.websocket.url),this.websocket.onclose=_,this.websocket.onmessage=i,this.websocket.onerror=c,null===(a=this.store)||void 0===a||a.recordJoinChannelService({endTs:Date.now(),status:"success"},r),this.joinGatewayRecordIndex=r}catch(e){const t="closed"===this.state,n=e instanceof I,o=n&&e.code===s.WS_ABORT,i=n&&e.code===s.WS_ERR,c=n?e.message:e&&(e.reason||e.toString());l.warning("[choose-best-ws] chooseBestWebsocket error: ".concat(c)),this.store&&this.store.recordJoinChannelService({endTs:Date.now(),status:o?"aborted":"error",errors:[e]},r),t||i?(E.reject(t?new I(s.WS_DISCONNECT,"websocket is closed: ".concat(c)):new I(s.WS_ERR,"init websocket failed: ".concat(c))),i&&l.error("[".concat(this.name,"] init websocket failed: ").concat(c))):_&&_(e)}return E.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 n=!0;if(this.reconnectInterrupter=()=>n=!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||!n)return!1;this.reconnectCount+=1;const s=async(e,t)=>{this.emit(k.RECONNECT_CREATE_CONNECTION,t),await this.createWebSocketConnection(e)};try{if("retry"===e)await s(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)),await s(this.urls[this.currentURLIndex],e)}else"recover"===e&&(l.debug("[".concat(this.name,"] request new urls")),this.resetReconnectCount("recover mode"),this.urls=await S(this,k.REQUEST_NEW_URLS),this.currentURLIndex=0,await s(this.urls[this.currentURLIndex],e))}catch(n){var E;l.error("[".concat(this.name,"] reconnect failed ").concat(n&&n.toString()));const s=null==n||null===(E=n.data)||void 0===E?void 0:E.desc;if(Array.isArray(s)){if(s.includes("dynamic key expired"))return this.emit(k.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1;if(s.includes("request downgrade fallback"))return this.emit(k.ON_FALLBACK),!1}return this.reconnectWithAction(e,t)}return!0}}class J extends F{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,n){return new Promise(((E,o)=>{let _=!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()})),o(new I(s.WS_ABORT,"choose best websocket aborted"))};const c=e("GATEWAY_DOMAINS");let r;const a=t.indexOf("?h="),R=c.find((e=>-1!==a?t.includes(e,a):t.includes(e)));l.debug("[choose-best-ws] currentDomain: ",R,", domains: ",c);let A=!this.tryDoubleDomain||!R;if(!A&&R){var N;const e=Date.now();try{c.forEach((e=>{const n=-1===a?t.replace(R,e):t.substr(0,a)+t.substr(a).replace(R,e),s=new WebSocket(n);s.binaryType="arraybuffer",i.push(s),l.debug("[choose-best-ws] ws is connecting:",s.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();A=!0}null===(N=this.store)||void 0===N||N.recordJoinChannelService({urls:i.map((e=>e.url)),service:"gateway"},n),i.forEach((t=>{t.onopen=()=>{if(_)return;const n=Date.now()-e;l.debug("[choose-best-ws] ws open cost ".concat(n,"ms")),i.filter((e=>e!==t)).forEach((e=>{l.debug("[choose-best-ws]close backup websocket: ".concat(e.url)),e.close()})),_=!0,E(t)},t.onclose=e=>{if(r=e,_)return;i.find((e=>!(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING)))||(l.debug("[choose-best-ws] all websocket is closed"),_=!0,o(r))},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(A){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"},n);try{e=new WebSocket(t),i.push(e),e.binaryType="arraybuffer"}catch(e){const t=new I(s.WS_ERR,"init websocket failed! Error: ".concat(e.toString()));return l.error("[".concat(this.name,"]").concat(t)),void o(t)}e.onopen=()=>{E(e)},e.onclose=e=>{o(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,n){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),n),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,n)=>{const s=window.setTimeout((()=>{n(new L(d.TIMEOUT,"wait status timeout, status: ".concat(e)))}),5e3);this.once(e,(E=>{window.clearTimeout(s),E.state&&0!==E.state?n(new L(d.CROSS_CHANNEL_WAIT_STATUS_ERROR,"wait status error, status: ".concat(e))):t(void 0)})),this.once("dispose",(()=>{window.clearTimeout(s),n(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 n=this.sendMessage(e),s=new Promise(((e,t)=>{const s=()=>{t(new L(d.WS_ABORT))};this.ws.once(k.RECONNECTING,s),this.ws.once(k.CLOSED,s),this.once("req_".concat(n),e),h(3e3).then((()=>{this.removeAllListeners("req_".concat(n)),this.ws.off(k.RECONNECTING,s),this.ws.off(k.CLOSED,s),t(new L(d.TIMEOUT,"cross channel ws request timeout"))}))})),E=await s;if(!E||200!==E.code)throw new L(d.CROSS_CHANNEL_SERVER_ERROR_RESPONSE,"response: ".concat(JSON.stringify(E)));return E}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 j 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,n,s,E){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,n),this.httpRetryConfig=s,this._resolution=E}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 v(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.SetSdkProfile,e);await this.signal.request(t),l.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSdkProfile success"));const n=this.genMessage(H.SetSourceChannel,e);await this.signal.request(n),await this.signal.waitStatus("SetSourceChannelStatus"),this.emit("event",Y.PACKET_JOINED_SRC_CHANNEL),l.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceChannel success"));const s=this.genMessage(H.SetSourceUserId,e);await this.signal.request(s),l.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceUserId success"));const E=this.genMessage(H.SetDestChannel,e);await this.signal.request(E),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 n=[],s=[],E=[];this.requestId+=1;const _={appId:this.joinInfo.appId,cname:this.joinInfo.cname,uid:this.joinInfo.uid.toString(),sdkVersion:o,sid:this.sid,ts:Date.now(),requestId:this.requestId,seq:this.requestId,allocate:!0,clientRequest:{}};"4.24.8"===_.sdkVersion&&(_.sdkVersion="0.0.1");let i=null,c=null;switch(e){case H.SetSdkProfile:return _.clientRequest={command:"SetSdkProfile",type:"multi_channel"},_;case H.SetSourceChannel:if(c=t&&t.getSrcChannelMediaInfo(),!c)throw new L(d.UNEXPECTED_ERROR,"can not find source config");return _.clientRequest={command:"SetSourceChannel",uid:"0",channelName:c.channelName,token:c.token||this.joinInfo.appId},_;case H.SetSourceUserId:if(c=t&&t.getSrcChannelMediaInfo(),!c)throw new L(d.UNEXPECTED_ERROR,"can not find source config");return _.clientRequest={command:"SetSourceUserId",uid:c.uid+""},_;case H.SetDestChannel:if(i=t&&t.getDestChannelMediaInfo(),!i)throw new L(d.UNEXPECTED_ERROR,"can not find dest config");return i.forEach((e=>{n.push(e.channelName),s.push(e.uid+""),E.push(e.token||this.joinInfo.appId)})),_.clientRequest={command:"SetDestChannel",channelName:n,uid:s,token:E},_;case H.StartPacketTransfer:return _.clientRequest={command:"StartPacketTransfer"},_;case H.Reconnect:return _.clientRequest={command:"Reconnect"},_;case H.StopPacketTransfer:return _.clientRequest={command:"StopPacketTransfer"},_;case H.UpdateDestChannel:if(i=t&&t.getDestChannelMediaInfo(),!i)throw new L(d.UNEXPECTED_ERROR,"can not find dest config");return i.forEach((e=>{n.push(e.channelName),s.push(e.uid+""),E.push(e.token||this.joinInfo.appId)})),_.clientRequest={command:"UpdateDestChannel",channelName:n,uid:s,token:E},_;case H.SetVideoProfile:_.clientRequest={command:"SetVideoProfile",width:this._resolution.width,height:this._resolution.height}}return _}}const x={name:"ChannelMediaRelay",create:function(e){return new j(e.joinInfo,e.clientId,e.websocketRetryConfig||O,e.httpRetryConfig||O,e.resolution)}};export{x as ChannelMediaRelayService};