agora-rtc-sdk-ng
Version:
Agora WebRTC SDK for JavaScript
6 lines (4 loc) • 40.3 kB
JavaScript
/**
* AgoraWebSDK_N-v4.24.3-0-g6cc16b0bb-dirty Copyright AgoraInc.
*/
import{IS_GLOBAL_VERSION as e,getParameter as t,EventEmitter as n,PromiseMutex as o,NETWORK_STATE as E,networkIndicator as _,NETWORK_INDICATOR_EVENTS as i,createDefer as s,AgoraRTCError as r,AgoraRTCErrorCode as c,getRetryWaitTime as a,wait as A,emitAsPromise as R,emitAsInvokerNoResponse as N,getUTF8StringByteLength as I,getMultiUnilbsFormDataByteLength as O,retryable as T,checkValidNumber as C,getRandomString as h,DEFAULT_RETRY_CONFIG as L,AgoraAPIName as S,AgoraAPITag as d}from"@agora-js/shared";import{logger as l,AgoraRTCError as u,AgoraRTCErrorCode as D,report as m}from"@agora-js/report";import{detectSupportPrePc as f,frameData2CryptoBuffer as w}from"@agora-js/media";import"@agora-js/protocol";import g from"axios";import"formdata-polyfill";function V(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 o=n.call(e,t||"default");if("object"!=typeof o)return o;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 M(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,o)}return n}function U(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?M(Object(n),!0).forEach((function(t){V(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):M(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}let b=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}({}),p=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}({}),v=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}({}),P=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}({}),y=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_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}({}),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_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}({}),B=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}({});B.AFRICA,B.ASIA,B.CHINA,B.EUROPE,B.GLOBAL,B.INDIA,B.JAPAN,B.NORTH_AMERICA,B.OCEANIA,B.OVERSEA,B.SOUTH_AMERICA;let K=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}({});K.ASIA,K.NORTH_AMERICA,K.EUROPE,K.JAPAN,K.INDIA,K.KOREA,K.HKMC,K.US,K.OVERSEA,K.GLOBAL,K.OCEANIA,K.SOUTH_AMERICA,K.AFRICA,e&&K.CHINA;let G=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_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}({}),W=function(e){return e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED",e}({}),H=function(e){return e.CONNECTION_STATE_CHANGE="connection-state-change",e.STATE_CHANGE="state-change",e.INSPECT_RESULT="inspect-result",e.CLIENT_LOCAL_VIDEO_TRACK="client-local-video-track",e.REQUEST_NEW_WORKER_URL="request-new-worker-url",e}({}),Y=function(e){return e[e.CONNECT_AP=0]="CONNECT_AP",e[e.AP_CONNECTED=1]="AP_CONNECTED",e[e.CONNECT_WORKER_MANAGER=2]="CONNECT_WORKER_MANAGER",e[e.WORKER_MANAGER_CONNECTED=3]="WORKER_MANAGER_CONNECTED",e[e.GET_WORKER_MANAGER_RESPONSE=4]="GET_WORKER_MANAGER_RESPONSE",e[e.CONNECT_WORKER=5]="CONNECT_WORKER",e[e.WORKER_CONNECTED=6]="WORKER_CONNECTED",e[e.CLOSED=7]="CLOSED",e}({});class F extends n{get url(){return this.websocket&&this.websocket.url||this._websocketUrl}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 n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],s=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=arguments.length>4&&void 0!==arguments[4]&&arguments[4],c=arguments.length>5?arguments[5]:void 0;super(),this._websocketUrl=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.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=c,this.name=e,this.retryConfig=U({},t),this.useCompress=n,this.tryDoubleDomain=s,this.use443PortOnly=r,this._initMutex=new o("websocket",c?c.clientId:void 0);const{timeout:a,timeoutFactor:A}=t,R=Math.max(300,Math.floor(3*a/5)),N=Math.max(1.2,Math.floor(8*A)/10);E.ONLINE&&(this.retryConfig.timeout=R,this.retryConfig.timeoutFactor=N),_.on(i.NETWORK_STATE_CHANGE,((e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===E.ONLINE?(this.retryConfig.timeout=R,this.retryConfig.timeoutFactor=N):(this.retryConfig.timeout=a,this.retryConfig.timeoutFactor=A))}))}getConnection(){return this.websocket||void 0}async init(e){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const o=await this._initMutex.lock();this._reconnectMode="tryNext",this.forceCloseTimeout=n,this.urls=e,this.state="connecting";try{var E;const e=s(),n=this.urls[this.currentURLIndex];null===(E=this.store)||void 0===E||E.beforeConnect(),(f(this.store)||t("ENABLE_JOIN_V4"))&&this.emit(G.PRE_CONNECT_PC),this.createWebSocketConnection(n).then(e.resolve).catch(e.reject),this.once(k.CLOSED,(()=>{e.reject(new r(c.WS_DISCONNECT))})),this.once(k.CONNECTED,e.resolve),await e.promise}catch(e){}finally{o()}}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 r(c.WS_ABORT,"websocket is not ready");try{t||(e=JSON.stringify(e)),this.websocket.send(e)}catch(e){throw new r(c.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(e){var n;const o=s();this.connectionID+=1,this.joinGatewayRecordIndex=void 0;const E=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"),o.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)o.reject(new r(c.WS_DISCONNECT,"websocket close: ".concat(e.code))),this.close();else{"connected"===this.state&&(this.reconnectReason=e.reason,this.state="reconnecting");const t=N(this,k.WILL_RECONNECT,this.reconnectMode,e.reason)||this.reconnectMode,n=await this.reconnectWithAction(t);if("closed"===this.state)return void l.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!n)return o.reject(new r(c.WS_DISCONNECT,"websocket reconnect failed: ".concat(e.code))),this.close(!0);o.resolve()}},i=e=>{this.emit(k.ON_MESSAGE,e)},a=e=>{l.warn("[".concat(this.connectionID,"] ws open error ").concat(e))};this.websocket&&(this.websocket.onclose=null,this.websocket.close()),t("GATEWAY_WSS_ADDRESS")&&this.name.startsWith("gateway")&&(e=t("GATEWAY_WSS_ADDRESS")),l.debug("[".concat(this.name,"] start connect, url:"),e);const A=null===(n=this.store)||void 0===n?void 0:n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"});try{var R;this._websocketUrl=function(e,n){if("string"==typeof e)return e;const{proxy:o,host:E,port:_}=e;if(n){const e=t("JOIN_GATEWAY_FALLBACK_PORT")||443;return 443===e?"wss://".concat(E,"/ws/?p=").concat(Number(_)+150):"wss://".concat(E,":").concat(e,"/ws/?p=").concat(Number(_)+150)}return o?"wss://".concat(o,"/ws/?h=").concat(E,"&p=").concat(_):"wss://".concat(E,":").concat(_)}(e);const n=await this.chooseBestWebsocketConnection(e);this.websocket=n,E&&E(this.websocket.url),this.websocket.onclose=_,this.websocket.onmessage=i,this.websocket.onerror=a,null===(R=this.store)||void 0===R||R.recordJoinChannelService({endTs:Date.now(),status:"success"},A),this.joinGatewayRecordIndex=A}catch(e){const t="closed"===this.state,n=e instanceof r,E=n&&e.code===c.WS_ABORT,i=n&&e.code===c.WS_ERR,s=n?e.message:e&&(e.reason||e.toString());l.warning("[choose-best-ws] chooseBestWebsocket error: ".concat(s)),this.store&&this.store.recordJoinChannelService({endTs:Date.now(),status:E?"aborted":"error",errors:[e]},A),t||i?(o.reject(t?new r(c.WS_DISCONNECT,"websocket is closed: ".concat(s)):new r(c.WS_ERR,"init websocket failed: ".concat(s))),i&&l.error("[".concat(this.name,"] init websocket failed: ").concat(s))):_&&_(e)}return o.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||_.isOnline||!_.onlineWaiter||(this.onlineReconnectListener=_.onlineWaiter.then((()=>{this.onlineReconnectListener=void 0})));let n=!0;if(this.reconnectInterrupter=()=>n=!1,t){const t=a(this.reconnectCount,this.retryConfig);l.debug("[".concat(this.name,"] wait ").concat(t,"ms to reconnect websocket, mode: ").concat(e)),await Promise.race([A(t),this.onlineReconnectListener||new Promise((()=>{}))])}if("closed"===this._state||!n)return!1;this.reconnectCount+=1;const o=async(e,t)=>{this.emit(k.RECONNECT_CREATE_CONNECTION,t),await this.createWebSocketConnection(e)};try{if("retry"===e)await o(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 o(this.urls[this.currentURLIndex],e)}else"recover"===e&&(l.debug("[".concat(this.name,"] request new urls")),this.resetReconnectCount("recover mode"),this.urls=await R(this,k.REQUEST_NEW_URLS),this.currentURLIndex=0,await o(this.urls[this.currentURLIndex],e))}catch(n){var E;l.error("[".concat(this.name,"] reconnect failed ").concat(n&&n.toString()));const o=null==n||null===(E=n.data)||void 0===E?void 0:E.desc;if(Array.isArray(o)){if(o.includes("dynamic key expired"))return this.emit(k.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1;if(o.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(e,n){return new Promise(((o,E)=>{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()})),E(new r(c.WS_ABORT,"choose best websocket aborted"))};const s=t("GATEWAY_DOMAINS");let a;const R=e.indexOf("?h="),N=s.find((t=>-1!==R?e.includes(t,R):e.includes(t)));l.debug("[choose-best-ws] currentDomain: ",N,", domains: ",s);let I=!this.tryDoubleDomain||!N;if(!I&&N){var O;const t=Date.now();try{s.forEach((t=>{const n=-1===R?e.replace(N,t):e.substr(0,R)+e.substr(R).replace(N,t),o=new WebSocket(n);o.binaryType="arraybuffer",i.push(o),l.debug("[choose-best-ws] ws is connecting:",o.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===(O=this.store)||void 0===O||O.recordJoinChannelService({urls:i.map((e=>e.url)),service:"gateway"},n),i.forEach((e=>{e.onopen=()=>{if(_)return;const n=Date.now()-t;l.debug("[choose-best-ws] ws open cost ".concat(n,"ms")),i.filter((t=>t!==e)).forEach((e=>{l.debug("[choose-best-ws]close backup websocket: ".concat(e.url)),e.close()})),_=!0,o(e)},e.onclose=e=>{if(a=e,_)return;i.find((e=>!(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING)))||(l.debug("[choose-best-ws] all websocket is closed"),_=!0,E(a))},e.onmessage=t=>{l.debug("[choose-best-ws]".concat(e.url," onmessage: ").concat(t.data))}})),A(this.forceCloseTimeout).then((()=>{i.forEach((e=>{e.readyState!==WebSocket.OPEN&&e.close()}))}))}if(I){var T;let t;l.debug("[choose-best-ws] use single url: ",e),null===(T=this.store)||void 0===T||T.recordJoinChannelService({urls:[e],service:"gateway"},n);try{t=new WebSocket(e),i.push(t),t.binaryType="arraybuffer"}catch(e){const t=new r(c.WS_ERR,"init websocket failed! Error: ".concat(e.toString()));return l.error("[".concat(this.name,"]").concat(t)),void E(t)}t.onopen=()=>{o(t)},t.onclose=e=>{E(e)},t.onmessage=e=>{l.debug("[choose-best-ws]".concat(t.url," onmessage: ").concat(e.data))},A(this.forceCloseTimeout).then((()=>{t&&t.readyState!==WebSocket.OPEN&&t.close()}))}})).then((e=>(this.closeEstablishingWs=void 0,e))).catch((e=>{throw this.closeEstablishingWs=void 0,e}))}}function x(e){let t=function(){const e=Q.pop();return e?(e.offset=e.limit=0,e):{bytes:new Uint8Array(64),offset:0,limit:0}}();return function(e,t){let n=e.appId;void 0!==n&&(se(t,10),oe(t,n));let o=e.cid;void 0!==o&&(se(t,16),se(t,o));let E=e.cname;void 0!==E&&(se(t,26),oe(t,E));let _=e.deviceId;void 0!==_&&(se(t,34),oe(t,_));let i=e.elapse;void 0!==i&&(se(t,40),ce(t,i));let s=e.fileSize;void 0!==s&&(se(t,48),ce(t,X(s)));let r=e.height;void 0!==r&&(se(t,56),ce(t,X(r)));let c=e.jpg;void 0!==c&&(se(t,66),se(t,c.length),te(t,c));let a=e.networkType;void 0!==a&&(se(t,72),ce(t,X(a)));let A=e.osType;void 0!==A&&(se(t,80),ce(t,X(A)));let R=e.requestId;void 0!==R&&(se(t,90),oe(t,R));let N=e.sdkVersion;void 0!==N&&(se(t,98),oe(t,N));let I=e.sequence;void 0!==I&&(se(t,104),ce(t,X(I)));let O=e.sid;void 0!==O&&(se(t,114),oe(t,O));let T=e.timestamp;void 0!==T&&(se(t,120),ce(t,T));let C=e.uid;void 0!==C&&(se(t,128),se(t,C));let h=e.vid;void 0!==h&&(se(t,136),se(t,h));let L=e.width;void 0!==L&&(se(t,144),ce(t,X(L)));let S=e.service;void 0!==S&&(se(t,152),se(t,S));let d=e.callbackData;void 0!==d&&(se(t,162),se(t,d.length),te(t,d));let l=e.ticket;void 0!==l&&(se(t,170),oe(t,l));let u=e.vendorConfigs;void 0!==u&&(se(t,178),oe(t,u))}(e,t),function(e){let t=e.bytes,n=e.limit;return t.length===n?t:t.subarray(0,n)}(t)}function q(e){return function(e){let t={};e:for(;!z(e);){let n=ie(e);switch(n>>>3){case 0:break e;case 1:t.code=ie(e);break;case 2:t.msg=ne(e,ie(e));break;case 3:t.requestId=ne(e,ie(e));break;case 4:t.timestamp=re(e,!1);break;default:j(e,7&n)}}return t}({bytes:t=e,offset:0,limit:t.length});var t}function j(e,t){switch(t){case 0:for(;128&Ee(e););break;case 2:Z(e,ie(e));break;case 5:Z(e,4);break;case 1:Z(e,8);break;default:throw new Error("Unimplemented type: "+t)}}function X(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}let Q=[];function Z(e,t){if(e.offset+t>e.limit)throw new Error("Skip past limit");e.offset+=t}function z(e){return e.offset>=e.limit}function $(e,t){let n=e.bytes,o=e.offset,E=e.limit,_=o+t;if(_>n.length){let t=new Uint8Array(2*_);t.set(n),e.bytes=t}return e.offset=_,_>E&&(e.limit=_),o}function ee(e,t){let n=e.offset;if(n+t>e.limit)throw new Error("Read past limit");return e.offset+=t,n}function te(e,t){let n=$(e,t.length);e.bytes.set(t,n)}function ne(e,t){let n=ee(e,t),o=String.fromCharCode,E=e.bytes,_="�",i="";for(let e=0;e<t;e++){let s,r,c,a,A=E[e+n];0==(128&A)?i+=o(A):192==(224&A)?e+1>=t?i+=_:(s=E[e+n+1],128!=(192&s)?i+=_:(a=(31&A)<<6|63&s,a<128?i+=_:(i+=o(a),e++))):224==(240&A)?e+2>=t?i+=_:(s=E[e+n+1],r=E[e+n+2],32896!=(49344&(s|r<<8))?i+=_:(a=(15&A)<<12|(63&s)<<6|63&r,a<2048||a>=55296&&a<=57343?i+=_:(i+=o(a),e+=2))):240==(248&A)?e+3>=t?i+=_:(s=E[e+n+1],r=E[e+n+2],c=E[e+n+3],8421504!=(12632256&(s|r<<8|c<<16))?i+=_:(a=(7&A)<<18|(63&s)<<12|(63&r)<<6|63&c,a<65536||a>1114111?i+=_:(a-=65536,i+=o(55296+(a>>10),56320+(1023&a)),e+=3))):i+=_}return i}function oe(e,t){let n=t.length,o=0;for(let e=0;e<n;e++){let E=t.charCodeAt(e);E>=55296&&E<=56319&&e+1<n&&(E=(E<<10)+t.charCodeAt(++e)-56613888),o+=E<128?1:E<2048?2:E<65536?3:4}se(e,o);let E=$(e,o),_=e.bytes;for(let e=0;e<n;e++){let o=t.charCodeAt(e);o>=55296&&o<=56319&&e+1<n&&(o=(o<<10)+t.charCodeAt(++e)-56613888),o<128?_[E++]=o:(o<2048?_[E++]=o>>6&31|192:(o<65536?_[E++]=o>>12&15|224:(_[E++]=o>>18&7|240,_[E++]=o>>12&63|128),_[E++]=o>>6&63|128),_[E++]=63&o|128)}}function Ee(e){return e.bytes[ee(e,1)]}function _e(e,t){let n=$(e,1);e.bytes[n]=t}function ie(e){let t,n=0,o=0;do{t=Ee(e),n<32&&(o|=(127&t)<<n),n+=7}while(128&t);return o}function se(e,t){for(t>>>=0;t>=128;)_e(e,127&t|128),t>>>=7;_e(e,t)}function re(e,t){let n,o=0,E=0,_=0;return n=Ee(e),o=127&n,128&n&&(n=Ee(e),o|=(127&n)<<7,128&n&&(n=Ee(e),o|=(127&n)<<14,128&n&&(n=Ee(e),o|=(127&n)<<21,128&n&&(n=Ee(e),E=127&n,128&n&&(n=Ee(e),E|=(127&n)<<7,128&n&&(n=Ee(e),E|=(127&n)<<14,128&n&&(n=Ee(e),E|=(127&n)<<21,128&n&&(n=Ee(e),_=127&n,128&n&&(n=Ee(e),_|=(127&n)<<7))))))))),{low:o|E<<28,high:E>>>4|_<<24,unsigned:t}}function ce(e,t){let n=t.low>>>0,o=(t.low>>>28|t.high<<4)>>>0,E=t.high>>>24,_=0===E?0===o?n<16384?n<128?1:2:n<1<<21?3:4:o<16384?o<128?5:6:o<1<<21?7:8:E<128?9:10,i=$(e,_),s=e.bytes;switch(_){case 10:s[i+9]=E>>>7&1;case 9:s[i+8]=9!==_?128|E:127&E;case 8:s[i+7]=8!==_?o>>>21|128:o>>>21&127;case 7:s[i+6]=7!==_?o>>>14|128:o>>>14&127;case 6:s[i+5]=6!==_?o>>>7|128:o>>>7&127;case 5:s[i+4]=5!==_?128|o:127&o;case 4:s[i+3]=4!==_?n>>>21|128:n>>>21&127;case 3:s[i+2]=3!==_?n>>>14|128:n>>>14&127;case 2:s[i+1]=2!==_?n>>>7|128:n>>>7&127;case 1:s[i]=1!==_?128|n:127&n}}const ae={},Ae={},Re=4294967296,Ne=Re*Re,Ie=Ne/2,Oe=Se(0,!0),Te=Se(0),Ce=de(0,-2147483648,!1),he=de(-1,2147483647,!1),Le=de(-1,-1,!0);function Se(e,t){let n,o,E;return t?(E=0<=(e>>>=0)&&e<256)&&(o=Ae[e],o)?o:(n=de(e,0,!0),E&&(Ae[e]=n),n):(E=-128<=(e|=0)&&e<128)&&(o=ae[e],o)?o:(n=de(e,e<0?-1:0,!1),E&&(ae[e]=n),n)}function de(e,t,n){return{low:0|e,high:0|t,unsigned:!!n}}function le(e,t){if(isNaN(e))return t?Oe:Te;if(t){if(e<0)return Oe;if(e>=Ne)return Le}else{if(e<=-Ie)return Ce;if(e+1>=Ie)return he}return e<0?t?Oe:Te:de(e%Re|0,e/Re|0,t)}let ue=0,De=0;b.ACCESS_POINT,P.NO_FLAG_SET,P.FLAG_SET_BUT_EMPTY,P.INVALID_FALG_SET,P.FLAG_SET_BUT_NO_RE,P.INVALID_SERVICE_ID,P.NO_SERVICE_AVAILABLE,P.NO_SERVICE_AVAILABLE_P2P,P.NO_SERVICE_AVAILABLE_VOICE,P.NO_SERVICE_AVAILABLE_WEBRTC,P.NO_SERVICE_AVAILABLE_CDS,P.NO_SERVICE_AVAILABLE_CDN,P.NO_SERVICE_AVAILABLE_TDS,P.NO_SERVICE_AVAILABLE_REPORT,P.NO_SERVICE_AVAILABLE_APP_CENTER,P.NO_SERVICE_AVAILABLE_ENV0,P.NO_SERVICE_AVAILABLE_VOET,P.NO_SERVICE_AVAILABLE_STRING_UID,P.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS,b.UNILBS,v.INVALID_VENDOR_KEY,v.INVALID_CHANNEL_NAME,v.INTERNAL_ERROR,v.NO_AUTHORIZED,v.DYNAMIC_KEY_TIMEOUT,v.NO_ACTIVE_STATUS,v.DYNAMIC_KEY_EXPIRED,v.STATIC_USE_DYNAMIC_KEY,v.DYNAMIC_USE_STATIC_KEY,v.USER_OVERLOAD,v.FORBIDDEN_REGION,v.CANNOT_MEET_AREA_DEMAND,v.REQ_DOWNGRADE_FALLBACK,b.STRING_UID_ALLOCATOR,p.IIIEGAL_APPID,p.IIIEGAL_UID,p.INTERNAL_ERROR,y.K_TIMESTAMP_EXPIRED,y.K_CHANNEL_PERMISSION_INVALID,y.K_CERTIFICATE_INVALID,y.K_CHANNEL_NAME_EMPTY,y.K_CHANNEL_NOT_FOUND,y.K_TICKET_INVALID,y.K_CHANNEL_CONFLICTED,y.K_SERVICE_NOT_READY,y.K_SERVICE_TOO_HEAVY,y.K_UID_BANNED,y.K_IP_BANNED,y.DATASTREAM2_NOT_AVAILABLE,y.K_AUTO_REBALANCE,y.K_VOS_FALLBACK,y.ERR_INVALID_VENDOR_KEY,y.ERR_INVALID_CHANNEL_NAME,y.WARN_NO_AVAILABLE_CHANNEL,y.WARN_LOOKUP_CHANNEL_TIMEOUT,y.WARN_LOOKUP_CHANNEL_REJECTED,y.WARN_OPEN_CHANNEL_TIMEOUT,y.WARN_OPEN_CHANNEL_REJECTED,y.WARN_REQUEST_DEFERRED,y.ERR_DYNAMIC_KEY_TIMEOUT,y.ERR_NO_AUTHORIZED,y.ERR_VOM_SERVICE_UNAVAILABLE,y.ERR_NO_CHANNEL_AVAILABLE_CODE,y.ERR_MASTER_VOCS_UNAVAILABLE,y.ERR_INTERNAL_ERROR,y.ERR_NO_ACTIVE_STATUS,y.ERR_INVALID_UID,y.ERR_DYNAMIC_KEY_EXPIRED,y.ERR_STATIC_USE_DYANMIC_KE,y.ERR_DYNAMIC_USE_STATIC_KE,y.ERR_NO_VOCS_AVAILABLE,y.ERR_NO_VOS_AVAILABLE,y.ERR_JOIN_CHANNEL_TIMEOUT,y.ERR_JOIN_BY_MULTI_IP,y.ERR_NOT_JOINED,y.ERR_REPEAT_JOIN_REQUEST,y.ERR_REPEAT_JOIN_CHANNEL,y.ERR_INVALID_STRINGUID,y.ERR_TOO_MANY_USERS,y.ERR_SET_CLIENT_ROLE_TIMEOUT,y.ERR_SET_CLIENT_ROLE_NO_PERMISSION,y.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE,y.ERR_PUBLISH_REQUEST_INVALID,y.ERR_SUBSCRIBE_REQUEST_INVALID,y.ERR_NOT_SUPPORTED_MESSAGE,y.ERR_ILLEAGAL_PLUGIN,y.ILLEGAL_CLIENT_ROLE_LEVEL,y.ERR_REJOIN_TOKEN_INVALID,y.ERR_REJOIN_USER_NOT_JOINED,y.ERR_INVALID_OPTIONAL_INFO,y.ERR_TEST_RECOVER,y.ERR_TEST_TRYNEXT,y.ERR_TEST_RETRY,y.ILLEGAL_AES_PASSWORD,y.ERR_TOO_MANY_BROADCASTERS,y.ERR_TOO_MANY_SUBSCRIBERS,y.ERR_LICENSE_ILLEGAL,y.ERR_LICENSE_MISSING,y.ERR_LICENSE_EXPIRED,y.ERR_LICENSE_MINUTES_EXCEEDED,y.ERR_LICENSE_PERIOD_INVALID,y.ERR_LICENSE_MULTIPLE_SDK_SERVICE;const me={GLOBAL:{ASIA:[B.CHINA,B.JAPAN,B.INDIA,B.KOREA,B.HKMC],EUROPE:[],NORTH_AMERICA:[B.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}};Object.keys(me[B.GLOBAL]),B.CHINA,B.NORTH_AMERICA,B.EUROPE,B.ASIA,B.JAPAN,B.INDIA,B.OCEANIA,B.SOUTH_AMERICA,B.AFRICA,B.KOREA,B.HKMC,B.US;let fe=0;function we(e,n,o,E){let{appId:_,areaCode:i,cname:s,sid:r,token:a,uid:A}=n;fe++;const R="moderation_plugin",N={service_name:R,json_body:JSON.stringify({appId:_,areaCode:i,cname:s,command:"allocateEdge",requestId:fe,seq:fe,sid:r,appToken:a,ts:Date.now(),uid:A+""})};let C,h,L=e[0];return T((async()=>{C=Date.now();const e=await function(e,n,o,E){return new Promise(((_,i)=>{n.timeout=n.timeout||t("HTTP_CONNECT_TIMEOUT"),n.responseType=n.responseType||"json",n.data&&!o?(n.data=JSON.stringify(n.data),ue+=I(n.data)):o&&(n.data.size?ue+=n.data.size:n.data instanceof FormData?ue+=O(n.data):ue+=I(JSON.stringify(n.data))),n.headers=n.headers||{},n.headers["Content-Type"]=n.headers["Content-Type"]||"application/json",n.method="POST",n.url=e,g.request(n).then((e=>{"string"==typeof e.data?De+=I(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?De+=e.data.byteLength:De+=I(JSON.stringify(e.data)),E&&_({data:e.data,headers:e.headers}),_(e.data)})).catch((e=>{g.isCancel(e)?i(new u(c.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?i(new u(c.NETWORK_TIMEOUT,e.message)):e.response?i(new u(c.NETWORK_RESPONSE_ERROR,e.response.status)):i(new u(c.NETWORK_ERROR,e.message))}))}))}(L,{data:N,cancelToken:o,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"},params:{action:"wrtc_gateway"}});if(h=Date.now()-C,0!==e.code){const t=new u(D.UNEXPECTED_RESPONSE,"moderation plugin ap error, code"+e.code,{retry:!0,responseTime:h});throw l.error(t.toString()),t}const n=JSON.parse(e.json_body);if(200!==n.code){const e=new u(D.UNEXPECTED_RESPONSE,"moderation plugin ap error, code: ".concat(n.code,", reason: ").concat(n.reason),{code:n.code,responseTime:h});throw l.error(e.toString()),e}if(!n.servers||!Array.isArray(n.servers)||0===n.servers.length){const e=new u(D.UNEXPECTED_RESPONSE,"moderation plugin ap empty server",{code:n.code,responseTime:h});throw l.error(e.toString()),e}if(!n.servers.some((e=>!!e.wss))){const e=new u(D.UNEXPECTED_RESPONSE,"moderation plugin ap empty port",{code:n.code,responseTime:h});throw l.error(e.toString()),e}const E=t("IMAGE_MODERATION_WORKER_WSS");if(E)return{addressList:[E],workerToken:n.workerToken,vid:n.vid,responseTime:h};const _=t("IMAGE_MODERATION_WORKER_HOST"),i=n.servers.map((e=>{let{address:t,wss:n}=e;if(t&&n)return"wss://".concat(t.replace(/\./g,"-"),".").concat(_,":").concat(n,"/moderation")})).filter((e=>!!e));return{addressList:i,workerToken:n.workerToken,vid:n.vid,ticket:n.appTicket,responseTime:h}}),((t,n)=>(m.apworkerEvent(r,{success:!0,sc:200,serviceName:R,responseDetail:JSON.stringify(t.addressList),firstSuccess:0===n,responseTime:h,serverIp:e[n%e.length]}),!1)),((t,n)=>(m.apworkerEvent(r,{success:!1,sc:t.data&&t.data.code||200,serviceName:R,responseTime:h,serverIp:e[n%e.length]}),!!(t.code!==D.OPERATION_ABORTED&&t.code!==D.UNEXPECTED_RESPONSE||t.data&&t.data.retry)&&(L=e[(n+1)%e.length],!0))),E)}class ge extends n{get connectionState(){return this._connectionState}set connectionState(e){if(this._connectionState===e)return;const t=this._connectionState;this._connectionState=e,this.emit(H.CONNECTION_STATE_CHANGE,e,t)}get quality(){return this._quality}set quality(e){this._quality=e>1?1:e<.1?.1:e,this._qualityTimer&&(window.clearTimeout(this._qualityTimer),this._qualityTimer=null),this._quality>=1||(this._qualityTimer=window.setTimeout((()=>{this.quality=this._quality/this._qualityRatio}),6e4))}constructor(e){var n;super(),this.name="AgoraRTCImageModeration",this._connectionState=W.CONNECTING,this._sequence=0,this._moderationStartTime=void 0,this._workerConnection=void 0,this._workerMessageLengthLimit=void 0,this._qualityRatio=void 0,this._connectInfo=void 0,this._cancelTokenSource=g.CancelToken.source(),this._retryConfig=void 0,this._moderationInterval=void 0,this._moderationTimer=null,this._moderationMode=1,this._quality=1,this._qualityTimer=null,this._ticket=void 0,this._moderationIntervalMinimum=void 0,this._uploadFailedNum=0,this._uploadNum=0,this._uploadTimer=null,this._extraInfo=void 0,this._vendor="",this._encoder=new TextEncoder,this._moderationId=void 0,this.inspectImage=()=>{if(this.connectionState!==W.CONNECTED)throw new u(D.OPERATION_ABORTED,"image moderation service connection status is ".concat(this.connectionState));this._moderationTimer&&(window.clearInterval(this._moderationTimer),this._moderationTimer=null),this._moderationTimer=window.setInterval((()=>{this.connectionState===W.CONNECTED?this.requestToInspectImage():l.debug("[".concat(this._moderationId,"] Moderation State is not connected , "),this.connectionState)}),this._moderationInterval<this._moderationIntervalMinimum?this._moderationIntervalMinimum:this._moderationInterval),this.requestToInspectImage()},this._moderationId=h(5,"image-moderation-"),this._workerMessageLengthLimit=t("IMAGE_MODERATION_WORKER_MESSAGE_LENGTH_LIMIT"),this._moderationIntervalMinimum=t("IMAGE_MODERATION_INTERVAL_MINIMUM"),this._moderationInterval=null!==(n=e.interval)&&void 0!==n?n:1e3,e.extraInfo&&(this._extraInfo=this._encoder.encode(e.extraInfo)),e.vendor&&(this._vendor=e.vendor),this._qualityRatio=t("IMAGE_MODERATION_QUALITY_RATIO"),this._moderationStartTime=Number(Date.now()),this._workerConnection=new J("worker-"+this._moderationId,L),this.on(H.STATE_CHANGE,((e,t)=>{l.debug("[".concat(this._moderationId,"] Moderation operation :").concat(Y[e]," ").concat(t||""))})),this.handleWorkerEvents()}async init(e,t){this.emit(H.STATE_CHANGE,Y.CONNECT_AP),this._connectInfo=e;const n=this._cancelTokenSource.token;return this._retryConfig=t,new Promise(((o,E)=>{this.on(H.CONNECTION_STATE_CHANGE,((e,t)=>{e===W.CONNECTED&&o()})),this.requestAP(e,n,t).then((e=>{this.connectWorker(e)})).catch((e=>{E(e)}))}))}updateConfig(e){var t;this._moderationInterval=null!==(t=e.interval)&&void 0!==t?t:1e3,e.extraInfo&&(this._extraInfo=this._encoder.encode(e.extraInfo)),e.vendor&&(this._vendor=e.vendor),l.debug("[".concat(this._moderationId,"] updateConfig: ").concat(JSON.stringify(e))),this.connectionState===W.CONNECTED&&this.inspectImage()}async requestAP(e,n,o){const E=t("WEBCS_DOMAIN").map((e=>"https://".concat(e,"/api/v1"))),_=await we(E,e,n,o);this.emit(H.STATE_CHANGE,Y.AP_CONNECTED);const{addressList:i,ticket:s}=_;return this._ticket=s,i}async connectWorker(e){this.emit(H.STATE_CHANGE,Y.CONNECT_WORKER),await this._workerConnection.init(e,1e4)}handleWorkerEvents(){this._workerConnection.on(k.CONNECTED,(async()=>{this.emit(H.STATE_CHANGE,Y.WORKER_CONNECTED,this._workerConnection.url),this.connectionState=W.CONNECTED})),this._workerConnection.on(k.CLOSED,(()=>{this.connectionState=W.CLOSED})),this._workerConnection.on(k.FAILED,(()=>{this.connectionState=W.CLOSED})),this._workerConnection.on(k.RECONNECTING,(()=>{this.connectionState=this.connectionState===W.CONNECTED?W.RECONNECTING:W.CONNECTING})),this._workerConnection.on(k.ON_MESSAGE,(async e=>{if(e.data instanceof ArrayBuffer){const n=q(new Uint8Array(e.data));t("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&l.debug("[".concat(this._moderationId,"] Response message for worker of image moderation "),JSON.stringify(n)),this._uploadNum++,void 0===n.code||0===n.code||(this._uploadFailedNum++,l.error("[".concat(this._moderationId,"] Error response from worke, code is ").concat(n.code,", msg is ").concat(n.msg)),this._uploadTimer||(this._uploadTimer=window.setTimeout((()=>{m.reportApiInvoke(this._connectInfo.sid||null,{name:S.IMAGE_MODERATION_UPLOAD,options:[this._uploadFailedNum,this._uploadNum,n.code],tag:d.TRACER}).onError(new u(D.IMAGE_MODERATION_UPLOAD_FAILED,n.msg)),this._uploadTimer=null}),t("IMAGE_MODERATION_UPLOAD_REPORT_INTERVAL"))))}else l.error("[".concat(this._moderationId,"] Unexpected message type from worker"))})),this._workerConnection.on(k.WILL_RECONNECT,((e,t,n)=>{"recover"===e&&n(e),n("tryNext")})),this._workerConnection.on(k.REQUEST_NEW_URLS,((e,t)=>{this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(e).catch(t)}))}static intToLong(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}async requestToInspectImage(){const e=N(this,H.CLIENT_LOCAL_VIDEO_TRACK),n={appId:this._connectInfo.appId,cname:this._connectInfo.cname,cid:this._connectInfo.cid,sid:this._connectInfo.sid,uid:this._connectInfo.uid,vid:this._connectInfo.vid};if(e){if(!e.isPlaying)return void(t("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&l.debug("Only the track being played can be inspected"));this._sequence++;const o=await this.generateRequestData(e,n);this._workerConnection.sendMessage(o,!0,!0)}else t("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&l.debug("Only the track being published can be inspected")}async generateRequestData(e,n){let{appId:o,cname:E,cid:_,vid:i,sid:s,uid:r}=n;const c=Date.now(),a=await e.getCurrentFrameImage("image/jpeg",this.quality),A=await w(a,o,E),R=this._sequence+"-"+_+"-"+r+"-"+c+"-"+h(12,""),N={appId:o,cid:_,cname:E,deviceId:"",elapse:ge.intToLong(Number(c-this._moderationStartTime)),fileSize:a.buffer.byteLength,height:a.height,width:a.width,jpg:A,networkType:6,osType:7,requestId:R,sdkVersion:"4.24.3",sequence:this._sequence,sid:s,timestamp:le(c),uid:r,vid:i,service:this._moderationMode,ticket:this._ticket,callbackData:this._extraInfo,vendorConfigs:this._vendor};void 0===this._extraInfo&&delete N.callbackData;const I=x(N);if(I.byteLength<this._workerMessageLengthLimit){if(t("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")){const e=U({},N);delete e.jpg,l.debug("[".concat(this._moderationId,"] Request message for worker of image moderation service: "),JSON.stringify(e))}return I}{const t=this.quality*this._qualityRatio;return this.quality=t,await this.generateRequestData(e,{appId:o,cname:E,cid:_,vid:i,sid:s,uid:r})}}close(){this._cancelTokenSource.cancel(),this._cancelTokenSource=g.CancelToken.source(),this._workerConnection&&this._workerConnection.close(),this._moderationTimer&&window.clearInterval(this._moderationTimer),this._moderationTimer=null,this._uploadTimer&&window.clearTimeout(this._uploadTimer),this._uploadTimer=null,this.connectionState=W.CLOSED,this.emit(H.STATE_CHANGE,Y.CLOSED)}}function Ve(e){if(C(e.interval,"interval",1e3,1/0),e&&e.extraInfo&&e.extraInfo.length>1024)throw new u(D.INVALID_PARAMS,"config.extraInfo length cannot exceed 1024 bytes");if(e&&e.vendor&&e.vendor.length>1024)throw new u(D.INVALID_PARAMS,"config.vendor length cannot exceed 1024 bytes")}const Me={name:"ImageModeration",create:function(e){let{config:t}=e;return Ve(t),new ge(t)}};export{Me as ImageModerationService,Ve as checkImageModerationConfig};