agora-rtc-sdk-ng
Advanced tools
Comparing version 4.22.0 to 4.22.1
{ | ||
"name": "agora-rtc-sdk-ng", | ||
"version": "4.22.0", | ||
"version": "4.22.1", | ||
"module": "AgoraRTC_N-production.esm-bundler.mjs", | ||
@@ -5,0 +5,0 @@ "types": "rtc-sdk_en.esm.d.ts", |
{ | ||
"name": "agora-rtc-sdk-ng", | ||
"version": "4.22.0", | ||
"version": "4.22.1", | ||
"description": "Agora WebRTC SDK for JavaScript", | ||
@@ -58,7 +58,7 @@ "main": "AgoraRTC_N-production.js", | ||
"dependencies": { | ||
"@agora-js/shared": "4.22.0", | ||
"@agora-js/report": "4.22.0", | ||
"@agora-js/media": "4.22.0", | ||
"@agora-js/shared": "4.22.1", | ||
"@agora-js/report": "4.22.1", | ||
"@agora-js/media": "4.22.1", | ||
"agora-rte-extension": "^1.2.4", | ||
"axios": "^1.6.8", | ||
"axios": "^1.7.7", | ||
"formdata-polyfill": "^4.0.7", | ||
@@ -65,0 +65,0 @@ "ua-parser-js": "^0.7.34", |
@@ -23,3 +23,3 @@ # AgoraRTC SDK (Version 4.x) | ||
```html | ||
<script src="https://download.agora.io/sdk/release/AgoraRTC_N-4.22.0.js"></script> | ||
<script src="https://download.agora.io/sdk/release/AgoraRTC_N-4.22.1.js"></script> | ||
``` | ||
@@ -26,0 +26,0 @@ |
@@ -23,3 +23,3 @@ # AgoraRTC SDK (Version 4.x) | ||
```html | ||
<script src="https://download.agora.io/sdk/release/AgoraRTC_N-4.22.0.js"></script> | ||
<script src="https://download.agora.io/sdk/release/AgoraRTC_N-4.22.1.js"></script> | ||
``` | ||
@@ -26,0 +26,0 @@ |
@@ -90,2 +90,3 @@ import { RTMConfiguration, TurnServerConfigWithMode, CloudProxyServerMode, EncryptionMode, EventEmitter, RetryConfiguration } from '@agora-js/shared'; | ||
preload?: boolean; | ||
apRequestDetail?: string; | ||
} | ||
@@ -92,0 +93,0 @@ interface JoinInfoWithAPResponse extends JoinInfo { |
/** | ||
* AgoraWebSDK_N-v4.22.0-0-g8569241d-dirty Copyright AgoraInc. | ||
* AgoraWebSDK_N-v4.22.1-0-g1c8e27e9 Copyright AgoraInc. | ||
*/ | ||
import{IS_GLOBAL_VERSION as e,MUTABLE_PARAMS as t,AgoraRTCError as s,getParameter as E,getUTF8StringByteLength as n,getMultiUnilbsFormDataByteLength as o,AgoraRTCErrorCode as _,VERSION as i,retryable as r,EventEmitter as a,PromiseMutex as c,NETWORK_STATE as R,networkIndicator as A,NETWORK_INDICATOR_EVENTS as I,createDefer as N,getRetryWaitTime as S,wait as h,emitAsPromise as C,emitAsInvokerNoResponse as T,generateSessionID as O,DEFAULT_RETRY_CONFIG as L}from"@agora-js/shared";import{AgoraRTCEventReport as d,logger as l}from"@agora-js/report";import u from"axios";import"formdata-polyfill";const D=function(){const e="us".concat("erna","me"),t="pa".concat("sswo","rd"),s=["t","s","t"];s.splice(1,0,"e");const E=s.join(""),n=[];for(let e=0;e<6;e++)n.push("1");const o=n.join(""),_={};return _[e]=E,_[t]=o,Object.assign(_,{turnServerURL:"",tcpport:3433,udpport:3478,forceturn:!1})}();window.DEFAULT_TURN_CONFIG=D,e||(t.WEBCS_DOMAIN=["ap-web-1-oversea.agora.io","ap-web-1-north-america.agora.io"],t.WEBCS_DOMAIN_BACKUP_LIST=["ap-web-2-oversea.agora.io","ap-web-2-north-america.agora.io"],t.PROXY_CS=["proxy-ap-web-oversea.agora.io","proxy-ap-web-america.agora.io"],t.CDS_AP=["cds-ap-web-oversea.agora.io","cds-ap-web-america.agora.io","cds-ap-web-america2.agora.io"],t.ACCOUNT_REGISTER=["sua-ap-web-oversea.agora.io","sua-ap-web-america.agora.io","sua-ap-web-america2.agora.io"],t.UAP_AP=["uap-ap-web-oversea.agora.io","uap-ap-web-america.agora.io","uap-ap-web-america2.agora.io"],t.LOG_UPLOAD_SERVER="logservice-oversea.agora.io",t.EVENT_REPORT_DOMAIN="statscollector-1-oversea.agora.io",t.EVENT_REPORT_BACKUP_DOMAIN="statscollector-2-oversea.agora.io",t.PROXY_SERVER_TYPE3="webrtc-cloud-proxy.agora.io",t.AREAS=["NORTH_AMERICA","OVERSEA"]);function w(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 g(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}d.__CLIENT_LIST__=[];class P extends s{constructor(e){super(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",arguments.length>2?arguments[2]:void 0),this.name="AgoraRTCException"}print(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"error";return super.print(e,l)}throw(){super.throw(l)}}let V=0,U=0;let f=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}({}),m=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}({}),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}({}),b=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}({});f.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,f.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,f.STRING_UID_ALLOCATOR,m.IIIEGAL_APPID,m.IIIEGAL_UID,m.INTERNAL_ERROR,b.K_TIMESTAMP_EXPIRED,b.K_CHANNEL_PERMISSION_INVALID,b.K_CERTIFICATE_INVALID,b.K_CHANNEL_NAME_EMPTY,b.K_CHANNEL_NOT_FOUND,b.K_TICKET_INVALID,b.K_CHANNEL_CONFLICTED,b.K_SERVICE_NOT_READY,b.K_SERVICE_TOO_HEAVY,b.K_UID_BANNED,b.K_IP_BANNED,b.K_AUTO_REBALANCE,b.ERR_INVALID_VENDOR_KEY,b.ERR_INVALID_CHANNEL_NAME,b.WARN_NO_AVAILABLE_CHANNEL,b.WARN_LOOKUP_CHANNEL_TIMEOUT,b.WARN_LOOKUP_CHANNEL_REJECTED,b.WARN_OPEN_CHANNEL_TIMEOUT,b.WARN_OPEN_CHANNEL_REJECTED,b.WARN_REQUEST_DEFERRED,b.ERR_DYNAMIC_KEY_TIMEOUT,b.ERR_NO_AUTHORIZED,b.ERR_VOM_SERVICE_UNAVAILABLE,b.ERR_NO_CHANNEL_AVAILABLE_CODE,b.ERR_MASTER_VOCS_UNAVAILABLE,b.ERR_INTERNAL_ERROR,b.ERR_NO_ACTIVE_STATUS,b.ERR_INVALID_UID,b.ERR_DYNAMIC_KEY_EXPIRED,b.ERR_STATIC_USE_DYANMIC_KE,b.ERR_DYNAMIC_USE_STATIC_KE,b.ERR_NO_VOCS_AVAILABLE,b.ERR_NO_VOS_AVAILABLE,b.ERR_JOIN_CHANNEL_TIMEOUT,b.ERR_JOIN_BY_MULTI_IP,b.ERR_NOT_JOINED,b.ERR_REPEAT_JOIN_REQUEST,b.ERR_REPEAT_JOIN_CHANNEL,b.ERR_INVALID_STRINGUID,b.ERR_TOO_MANY_USERS,b.ERR_SET_CLIENT_ROLE_TIMEOUT,b.ERR_SET_CLIENT_ROLE_NO_PERMISSION,b.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE,b.ERR_PUBLISH_REQUEST_INVALID,b.ERR_SUBSCRIBE_REQUEST_INVALID,b.ERR_NOT_SUPPORTED_MESSAGE,b.ERR_ILLEAGAL_PLUGIN,b.ILLEGAL_CLIENT_ROLE_LEVEL,b.ERR_REJOIN_TOKEN_INVALID,b.ERR_REJOIN_USER_NOT_JOINED,b.ERR_INVALID_OPTIONAL_INFO,b.ERR_TEST_RECOVER,b.ERR_TEST_TRYNEXT,b.ERR_TEST_RETRY,b.ILLEGAL_AES_PASSWORD,b.ERR_TOO_MANY_BROADCASTERS,b.ERR_TOO_MANY_SUBSCRIBERS,b.ERR_LICENSE_ILLEGAL,b.ERR_LICENSE_MISSING,b.ERR_LICENSE_EXPIRED,b.ERR_LICENSE_MINUTES_EXCEEDED,b.ERR_LICENSE_PERIOD_INVALID,b.ERR_LICENSE_MULTIPLE_SDK_SERVICE;let v=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}({});v.AFRICA,v.ASIA,v.CHINA,v.EUROPE,v.GLOBAL,v.INDIA,v.JAPAN,v.NORTH_AMERICA,v.OCEANIA,v.OVERSEA,v.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:[v.CHINA,v.JAPAN,v.INDIA,v.KOREA,v.HKMC],EUROPE:[],NORTH_AMERICA:[v.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}};Object.keys(y[v.GLOBAL]),v.CHINA,v.NORTH_AMERICA,v.EUROPE,v.ASIA,v.JAPAN,v.INDIA,v.OCEANIA,v.SOUTH_AMERICA,v.AFRICA,v.KOREA,v.HKMC,v.US;let K=1;function k(e,t,s,a){const c={command:"convergeAllocateEdge",sid:t.sid,appId:t.appId,token:t.token,ts:Date.now(),version:i,cname:t.cname,uid:t.uid.toString(),requestId:K,seq:K};K+=1;const R={service_name:"tele_channel",json_body:JSON.stringify(c)};return r((async()=>{const t=await function(e,t,s,i){return new Promise(((r,a)=>{t.timeout=t.timeout||E("HTTP_CONNECT_TIMEOUT"),t.responseType=t.responseType||"json",t.data&&!s?(t.data=JSON.stringify(t.data),V+=n(t.data)):s&&(t.data.size?V+=t.data.size:t.data instanceof FormData?V+=o(t.data):V+=n(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,u.request(t).then((e=>{"string"==typeof e.data?U+=n(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?U+=e.data.byteLength:U+=n(JSON.stringify(e.data)),i&&r({data:e.data,headers:e.headers}),r(e.data)})).catch((e=>{u.isCancel(e)?a(new P(_.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?a(new P(_.NETWORK_TIMEOUT,e.message)):e.response?a(new P(_.NETWORK_RESPONSE_ERROR,e.response.status)):a(new P(_.NETWORK_ERROR,e.message))}))}))}(e,{data:R,cancelToken:s,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":61}});if(0!==t.code){const e=new P(_.UNEXPECTED_RESPONSE,"cross channel ap error, code"+t.code,{retry:!0});throw l.error(e.toString()),e}const i=JSON.parse(t.json_body);if(200!==i.code){const e=new P(_.UNEXPECTED_RESPONSE,"cross channel app center error, code: ".concat(i.code,", reason: ").concat(i.reason));throw l.error(e.toString()),e}if(!i.servers||0===i.servers.length){const e=new P(_.UNEXPECTED_RESPONSE,"cross channel app center empty server");throw l.error(e.toString()),e}return{vid:i.vid,workerToken:i.workerToken,addressList:(E("CHANNEL_MEDIA_RELAY_SERVERS")||i.servers).map((e=>"wss://".concat(e.address.replace(/\./g,"-"),".").concat(E("WORKER_DOMAIN"),":").concat(e.wss)))}}),void 0,(e=>!!(e.code!==_.OPERATION_ABORTED&&e.code!==_.UNEXPECTED_RESPONSE||e.data&&e.data.retry)),a)}async function H(e,t,s){const n=E("UAP_AP").slice(0,E("AJAX_REQUEST_CONCURRENT")).map((t=>e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v1?action=uap"):"https://".concat(t,"/api/v1?action=uap"))).map((E=>k(E,e,t,s)));try{const e=await(o=n,Promise.all(o.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 o}let Y=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}({}),W=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}({}),G=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}({}),F=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}({}),J=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}({}),j=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 q extends a{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(Y.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(Y.CONNECTED):"closed"===this._state?this.emit(Y.CLOSED):"failed"===this._state&&this.emit(Y.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],o=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 c("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=o,this.name=e,this.retryConfig=function(e){for(var t=1;t<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?g(Object(s),!0).forEach((function(t){w(e,t,s[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):g(Object(s)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(s,t))}))}return e}({},t),this.useCompress=s,this.tryDoubleDomain=E,this.use443PortOnly=n;const{timeout:_,timeoutFactor:i}=t,r=Math.max(300,Math.floor(3*_/5)),a=Math.max(1.2,Math.floor(8*i)/10);R.ONLINE&&(this.retryConfig.timeout=r,this.retryConfig.timeoutFactor=a),A.on(I.NETWORK_STATE_CHANGE,((e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===R.ONLINE?(this.retryConfig.timeout=r,this.retryConfig.timeoutFactor=a):(this.retryConfig.timeout=_,this.retryConfig.timeoutFactor=i))}))}getConnection(){return this.websocket||void 0}async init(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const n=await this._initMutex.lock();this.forceCloseTimeout=t,this.urls=e,this.state="connecting";try{const e=N(),t=this.urls[this.currentURLIndex];E("ENABLE_PREALLOC_PC")&&this.emit(j.PRE_CONNECT_PC),this.createWebSocketConnection(t).then(e.resolve).catch(e.reject),this.once(Y.CLOSED,(()=>{e.reject(new s(_.WS_DISCONNECT))})),this.once(Y.CONNECTED,e.resolve),await e.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 s(_.WS_ABORT,"websocket is not ready");try{t||(e=JSON.stringify(e)),this.websocket.send(e)}catch(e){throw new 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(e){var t;const n=N();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"),n.resolve()},i=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 s(_.WS_DISCONNECT,"websocket close: ".concat(e.code))),this.close();else{"connected"===this.state&&(this.reconnectReason=e.reason,this.state="reconnecting");const t=T(this,Y.WILL_RECONNECT,this.reconnectMode,e.reason)||this.reconnectMode,E=await this.reconnectWithAction(t);if("closed"===this.state)return void l.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!E)return n.reject(new s(_.WS_DISCONNECT,"websocket reconnect failed: ".concat(e.code))),this.close(!0);n.resolve()}},r=e=>{this.emit(Y.ON_MESSAGE,e)},a=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")&&(e=E("GATEWAY_WSS_ADDRESS")),l.debug("[".concat(this.name,"] start connect, url:"),e);const c=null===(t=this.store)||void 0===t?void 0:t.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"});try{var R;const t=await this.chooseBestWebsocketConnection(e);this.websocket=t,o&&o(this.websocket.url),this.websocket.onclose=i,this.websocket.onmessage=r,this.websocket.onerror=a,null===(R=this.store)||void 0===R||R.recordJoinChannelService({endTs:Date.now(),status:"success"},c),this.joinGatewayRecordIndex=c}catch(e){const t="closed"===this.state,E=e instanceof s,o=E&&e.code===_.WS_ABORT,r=E&&e.code===_.WS_ERR,a=E?e.message:e&&(e.reason||e.toString());l.warning("[choose-best-ws] chooseBestWebsocket error: ".concat(a)),this.store&&this.store.recordJoinChannelService({endTs:Date.now(),status:o?"aborted":"error",errors:[e]},c),t||r?(n.reject(t?new s(_.WS_DISCONNECT,"websocket is closed: ".concat(a)):new s(_.WS_ERR,"init websocket failed: ".concat(a))),r&&l.error("[".concat(this.name,"] init websocket failed: ").concat(a))):i&&i(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=S(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(Y.RECONNECT_CREATE_CONNECTION,t),await this.createWebSocketConnection(e)};try{if("retry"===e)this.emit(Y.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(Y.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(Y.RECONNECT_WAITTING_FINISH,e),this.urls=await C(this,Y.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(Y.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):this.reconnectWithAction(e,t)}return!0}}class x extends q{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,t){return new Promise(((n,o)=>{let i=!1;const r=[];this.closeEstablishingWs=()=>{l.debug("[choose-best-ws] close establishing websockets"),r.forEach((e=>{e.onclose=null,e.onopen=null,e.onmessage=null,e.close()})),o(new s(_.WS_ABORT,"choose best websocket aborted"))};const a=E("GATEWAY_DOMAINS");let c;const R=e.indexOf("?h="),A=a.find((t=>-1!==R?e.includes(t,R):e.includes(t)));l.debug("[choose-best-ws] currentDomain: ",A,", domains: ",a);let I=!this.tryDoubleDomain||!A;if(!I&&A){var N;const s=Date.now();try{a.forEach((t=>{const s=-1===R?e.replace(A,t):e.substr(0,R)+e.substr(R).replace(A,t),E=new WebSocket(s);E.binaryType="arraybuffer",r.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"),r.forEach((e=>e.close()));r.length;)r.pop();I=!0}null===(N=this.store)||void 0===N||N.recordJoinChannelService({urls:r.map((e=>e.url)),service:"gateway"},t),r.forEach((e=>{e.onopen=()=>{if(i)return;const t=Date.now()-s;l.debug("[choose-best-ws] ws open cost ".concat(t,"ms")),r.filter((t=>t!==e)).forEach((e=>{l.debug("[choose-best-ws]close backup websocket: ".concat(e.url)),e.close()})),i=!0,n(e)},e.onclose=e=>{if(c=e,i)return;r.find((e=>!(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING)))||(l.debug("[choose-best-ws] all websocket is closed"),i=!0,o(c))},e.onmessage=t=>{l.debug("[choose-best-ws]".concat(e.url," onmessage: ").concat(t.data))}})),h(this.forceCloseTimeout).then((()=>{r.forEach((e=>{e.readyState!==WebSocket.OPEN&&e.close()}))}))}if(I){var S;let E;l.debug("[choose-best-ws] use single url: ",e),null===(S=this.store)||void 0===S||S.recordJoinChannelService({urls:[e],service:"gateway"},t);try{E=new WebSocket(e),r.push(E),E.binaryType="arraybuffer"}catch(e){const t=new s(_.WS_ERR,"init websocket failed! Error: ".concat(e.toString()));return l.error("[".concat(this.name,"]").concat(t)),void o(t)}E.onopen=()=>{n(E)},E.onclose=e=>{o(e)},E.onmessage=e=>{l.debug("[choose-best-ws]".concat(E.url," onmessage: ").concat(e.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 X extends a{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 x("cross-channel-".concat(this.clientId),s),this.ws.on(Y.RECONNECTING,(()=>{this.ws.reconnectMode="retry",this.emit("reconnecting")})),this.ws.on(Y.CONNECTED,this.onOpen),this.ws.on(Y.ON_MESSAGE,this.onMessage),this.ws.on(Y.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 P(_.TIMEOUT,"wait status timeout, status: ".concat(e)))}),5e3);this.once(e,(n=>{window.clearTimeout(E),n.state&&0!==n.state?s(new P(_.CROSS_CHANNEL_WAIT_STATUS_ERROR,"wait status error, status: ".concat(e))):t(void 0)})),this.once("dispose",(()=>{window.clearTimeout(E),s(new P(_.WS_ABORT))}))}))}async request(e){if("closed"===this.ws.state)throw new P(_.WS_DISCONNECT);const t=()=>new Promise(((e,t)=>{this.ws.once(Y.CLOSED,(()=>t(new P(_.WS_ABORT)))),this.ws.once(Y.CONNECTED,e)}));"connected"!==this.ws.state&&await t();const s=this.sendMessage(e),E=new Promise(((e,t)=>{const E=()=>{t(new P(_.WS_ABORT))};this.ws.once(Y.RECONNECTING,E),this.ws.once(Y.CLOSED,E),this.once("req_".concat(s),e),h(3e3).then((()=>{this.removeAllListeners("req_".concat(s)),this.ws.off(Y.RECONNECTING,E),this.ws.off(Y.CLOSED,E),t(new P(_.TIMEOUT,"cross channel ws request timeout"))}))})),n=await E;if(!n||200!==n.code)throw new P(_.CROSS_CHANNEL_SERVER_ERROR_RESPONSE,"response: ".concat(JSON.stringify(n)));return n}async connect(e){this.ws.removeAllListeners(Y.REQUEST_NEW_URLS),this.ws.on(Y.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 Q extends a{set state(e){e!==this._state&&(e!==F.RELAY_STATE_FAILURE&&(this.errorCode=J.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=F.RELAY_STATE_IDLE,this.errorCode=J.RELAY_OK,this.onStatus=e=>{l.debug("[".concat(this.clientId,"] ChannelMediaStatus: ").concat(JSON.stringify(e))),e&&e.command&&("onAudioPacketReceived"===e.command&&this.emit("event",G.PACKET_RECEIVED_AUDIO_FROM_SRC),"onVideoPacketReceived"===e.command&&this.emit("event",G.PACKET_RECEIVED_VIDEO_FROM_SRC),"onSrcTokenPrivilegeDidExpire"===e.command&&(this.errorCode=J.SRC_TOKEN_EXPIRED,this.state=F.RELAY_STATE_FAILURE),"onDestTokenPrivilegeDidExpire"===e.command&&(this.errorCode=J.DEST_TOKEN_EXPIRED,this.state=F.RELAY_STATE_FAILURE))},this.onReconnect=async()=>{l.debug("[".concat(this.clientId,"] ChannelMediaSocket disconnect, reconnecting")),this.emit("event",G.NETWORK_DISCONNECTED),this.state=F.RELAY_STATE_IDLE,this.prevChannelMediaConfig&&this.sendStartRelayMessage(this.prevChannelMediaConfig).catch((e=>{this.state!==F.RELAY_STATE_IDLE&&(l.error("auto restart channel media relay failed",e.toString()),this.errorCode=J.SERVER_CONNECTION_LOST,this.state=F.RELAY_STATE_FAILURE)}))},this.joinInfo=e,this.clientId=t,this.sid=O(),this.signal=new X(this.joinInfo,this.clientId,s),this.httpRetryConfig=E,this._resolution=n}async startChannelMediaRelay(e){if(this.state!==F.RELAY_STATE_IDLE)throw new P(_.INVALID_OPERATION);this.state=F.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 P(_.CROSS_CHANNEL_FAILED_JOIN_SRC);if(e.data&&e.data.serverResponse&&"SetDestChannelStatus"===e.serverResponse.command)throw new P(_.CROSS_CHANNEL_FAILED_JOIN_DEST);if(e.data&&e.data.serverResponse&&"StartPacketTransfer"===e.serverResponse.command)throw new P(_.CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST);throw e}this.prevChannelMediaConfig=e}async updateChannelMediaRelay(e){if(this.state!==F.RELAY_STATE_RUNNING)throw new P(_.INVALID_OPERATION);await this.sendUpdateMessage(e),this.prevChannelMediaConfig=e}async setVideoProfile(e){if(this._resolution=e,this.state!==F.RELAY_STATE_RUNNING)throw new P(_.INVALID_OPERATION);const t=this.genMessage(W.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=F.RELAY_STATE_IDLE,this.dispose()}dispose(){l.debug("[".concat(this.clientId,"] disposeChannelMediaRelay")),this.cancelToken.cancel(),this.cancelToken=u.CancelToken.source(),this.state=F.RELAY_STATE_IDLE,this.emit("dispose"),this.signal.dispose(),this.prevChannelMediaConfig=void 0}async connect(){const e=await H(this.joinInfo,this.cancelToken.token,this.httpRetryConfig);this.workerToken=e.workerToken,await this.signal.connect(e.addressList),this.emit("event",G.NETWORK_CONNECTED),this.signal.on("status",this.onStatus),this.signal.on("reconnecting",this.onReconnect)}async sendStartRelayMessage(e){const t=this.genMessage(W.StopPacketTransfer);await this.signal.request(t),await this.signal.waitStatus("Normal Quit"),l.debug("[".concat(this.clientId,"] startChannelMediaRelay: StopPacketTransfer success"));const s=this.genMessage(W.SetSdkProfile,e);await this.signal.request(s),l.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSdkProfile success"));const E=this.genMessage(W.SetSourceChannel,e);await this.signal.request(E),await this.signal.waitStatus("SetSourceChannelStatus"),this.emit("event",G.PACKET_JOINED_SRC_CHANNEL),l.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceChannel success"));const n=this.genMessage(W.SetSourceUserId,e);await this.signal.request(n),l.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceUserId success"));const o=this.genMessage(W.SetDestChannel,e);await this.signal.request(o),await this.signal.waitStatus("SetDestChannelStatus"),this.emit("event",G.PACKET_JOINED_DEST_CHANNEL),l.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetDestChannel success"));const _=this.genMessage(W.StartPacketTransfer,e);await this.signal.request(_),this.emit("event",G.PACKET_SENT_TO_DEST_CHANNEL),this.state=F.RELAY_STATE_RUNNING,l.debug("[".concat(this.clientId,"] startChannelMediaRelay: StartPacketTransfer success")),this.setVideoProfile(this._resolution)}async sendUpdateMessage(e){const t=this.genMessage(W.UpdateDestChannel,e);await this.signal.request(t),this.emit("event",G.PACKET_UPDATE_DEST_CHANNEL),l.debug("[".concat(this.clientId,"] sendUpdateMessage: UpdateDestChannel success"))}async sendStopRelayMessage(){const e=this.genMessage(W.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:i,sid:this.sid,ts:Date.now(),requestId:this.requestId,seq:this.requestId,allocate:!0,clientRequest:{}};"4.22.0"===o.sdkVersion&&(o.sdkVersion="0.0.1");let r=null,a=null;switch(e){case W.SetSdkProfile:return o.clientRequest={command:"SetSdkProfile",type:"multi_channel"},o;case W.SetSourceChannel:if(a=t&&t.getSrcChannelMediaInfo(),!a)throw new P(_.UNEXPECTED_ERROR,"can not find source config");return o.clientRequest={command:"SetSourceChannel",uid:"0",channelName:a.channelName,token:a.token||this.joinInfo.appId},o;case W.SetSourceUserId:if(a=t&&t.getSrcChannelMediaInfo(),!a)throw new P(_.UNEXPECTED_ERROR,"can not find source config");return o.clientRequest={command:"SetSourceUserId",uid:a.uid+""},o;case W.SetDestChannel:if(r=t&&t.getDestChannelMediaInfo(),!r)throw new P(_.UNEXPECTED_ERROR,"can not find dest config");return r.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 W.StartPacketTransfer:return o.clientRequest={command:"StartPacketTransfer"},o;case W.Reconnect:return o.clientRequest={command:"Reconnect"},o;case W.StopPacketTransfer:return o.clientRequest={command:"StopPacketTransfer"},o;case W.UpdateDestChannel:if(r=t&&t.getDestChannelMediaInfo(),!r)throw new P(_.UNEXPECTED_ERROR,"can not find dest config");return r.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 W.SetVideoProfile:o.clientRequest={command:"SetVideoProfile",width:this._resolution.width,height:this._resolution.height}}return o}}const Z={name:"ChannelMediaRelay",create:function(e){return new Q(e.joinInfo,e.clientId,e.websocketRetryConfig||L,e.httpRetryConfig||L,e.resolution)}};export{Z as ChannelMediaRelayService}; | ||
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<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?w(Object(s),!0).forEach((function(t){D(e,t,s[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):w(Object(s)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(s,t))}))}return e}({},t),this.useCompress=s,this.tryDoubleDomain=E,this.use443PortOnly=n;const{timeout:o,timeoutFactor:i}=t,I=Math.max(300,Math.floor(3*o/5)),A=Math.max(1.2,Math.floor(8*i)/10);c.ONLINE&&(this.retryConfig.timeout=I,this.retryConfig.timeoutFactor=A),a.on(R.NETWORK_STATE_CHANGE,((e,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}; |
/** | ||
* AgoraWebSDK_N-v4.22.0-0-g8569241d-dirty Copyright AgoraInc. | ||
* AgoraWebSDK_N-v4.22.1-0-g1c8e27e9 Copyright AgoraInc. | ||
*/ | ||
import{AgoraRTCError as e,IS_GLOBAL_VERSION as t,MUTABLE_PARAMS as n,EventEmitter as o,PromiseMutex as E,NETWORK_STATE as i,networkIndicator as s,NETWORK_INDICATOR_EVENTS as r,createDefer as _,getParameter as c,AgoraRTCErrorCode as a,getRetryWaitTime as R,wait as N,emitAsPromise as I,emitAsInvokerNoResponse as A,getUTF8StringByteLength as C,getMultiUnilbsFormDataByteLength as T,retryable as O,getRandomString as h,DEFAULT_RETRY_CONFIG as S}from"@agora-js/shared";import{logger as l,AgoraRTCEventReport as L,report as d}from"@agora-js/report";import{frameData2CryptoBuffer as u}from"@agora-js/media";import D from"axios";import"formdata-polyfill";function w(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 p(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 f(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?p(Object(n),!0).forEach((function(t){w(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):p(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}class g extends e{constructor(e){super(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",arguments.length>2?arguments[2]:void 0),this.name="AgoraRTCException"}print(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"error";return super.print(e,l)}throw(){super.throw(l)}}let m=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}({}),V=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}({}),U=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}({}),b=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}({}),y=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}({});const M=function(){const e="us".concat("erna","me"),t="pa".concat("sswo","rd"),n=["t","s","t"];n.splice(1,0,"e");const o=n.join(""),E=[];for(let e=0;e<6;e++)E.push("1");const i=E.join(""),s={};return s[e]=o,s[t]=i,Object.assign(s,{turnServerURL:"",tcpport:3433,udpport:3478,forceturn:!1})}();window.DEFAULT_TURN_CONFIG=M,t||(n.WEBCS_DOMAIN=["ap-web-1-oversea.agora.io","ap-web-1-north-america.agora.io"],n.WEBCS_DOMAIN_BACKUP_LIST=["ap-web-2-oversea.agora.io","ap-web-2-north-america.agora.io"],n.PROXY_CS=["proxy-ap-web-oversea.agora.io","proxy-ap-web-america.agora.io"],n.CDS_AP=["cds-ap-web-oversea.agora.io","cds-ap-web-america.agora.io","cds-ap-web-america2.agora.io"],n.ACCOUNT_REGISTER=["sua-ap-web-oversea.agora.io","sua-ap-web-america.agora.io","sua-ap-web-america2.agora.io"],n.UAP_AP=["uap-ap-web-oversea.agora.io","uap-ap-web-america.agora.io","uap-ap-web-america2.agora.io"],n.LOG_UPLOAD_SERVER="logservice-oversea.agora.io",n.EVENT_REPORT_DOMAIN="statscollector-1-oversea.agora.io",n.EVENT_REPORT_BACKUP_DOMAIN="statscollector-2-oversea.agora.io",n.PROXY_SERVER_TYPE3="webrtc-cloud-proxy.agora.io",n.AREAS=["NORTH_AMERICA","OVERSEA"]);L.__CLIENT_LIST__=[];let v=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}({});v.AFRICA,v.ASIA,v.CHINA,v.EUROPE,v.GLOBAL,v.INDIA,v.JAPAN,v.NORTH_AMERICA,v.OCEANIA,v.OVERSEA,v.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,t&&k.CHINA;let B=function(e){return e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED",e}({}),W=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}({}),K=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}({}),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_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 H extends o{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(y.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(y.CONNECTED):"closed"===this._state?this.emit(y.CLOSED):"failed"===this._state&&this.emit(y.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],o=arguments.length>3&&void 0!==arguments[3]&&arguments[3],_=arguments.length>4&&void 0!==arguments[4]&&arguments[4],c=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 E("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=c,this.name=e,this.retryConfig=f({},t),this.useCompress=n,this.tryDoubleDomain=o,this.use443PortOnly=_;const{timeout:a,timeoutFactor:R}=t,N=Math.max(300,Math.floor(3*a/5)),I=Math.max(1.2,Math.floor(8*R)/10);i.ONLINE&&(this.retryConfig.timeout=N,this.retryConfig.timeoutFactor=I),s.on(r.NETWORK_STATE_CHANGE,((e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===i.ONLINE?(this.retryConfig.timeout=N,this.retryConfig.timeoutFactor=I):(this.retryConfig.timeout=a,this.retryConfig.timeoutFactor=R))}))}getConnection(){return this.websocket||void 0}async init(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const o=await this._initMutex.lock();this.forceCloseTimeout=n,this.urls=t,this.state="connecting";try{const t=_(),n=this.urls[this.currentURLIndex];c("ENABLE_PREALLOC_PC")&&this.emit(G.PRE_CONNECT_PC),this.createWebSocketConnection(n).then(t.resolve).catch(t.reject),this.once(y.CLOSED,(()=>{t.reject(new e(a.WS_DISCONNECT))})),this.once(y.CONNECTED,t.resolve),await t.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.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(t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new e(a.WS_ABORT,"websocket is not ready");try{n||(t=JSON.stringify(t)),this.websocket.send(t)}catch(t){throw new e(a.WS_ERR,"send websocket message error"+t.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 o=_();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()},i=async t=>{var n;if(l.debug("[".concat(this.name,"] websocket close ").concat(null===(n=this.websocket)||void 0===n?void 0:n.url,", code: ").concat(t.code,", reason: ").concat(t.reason,", current mode: ").concat(this.reconnectMode)),this.reconnectCount>=this.retryConfig.maxRetryCount)o.reject(new e(a.WS_DISCONNECT,"websocket close: ".concat(t.code))),this.close();else{"connected"===this.state&&(this.reconnectReason=t.reason,this.state="reconnecting");const n=A(this,y.WILL_RECONNECT,this.reconnectMode,t.reason)||this.reconnectMode,E=await this.reconnectWithAction(n);if("closed"===this.state)return void l.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!E)return o.reject(new e(a.WS_DISCONNECT,"websocket reconnect failed: ".concat(t.code))),this.close(!0);o.resolve()}},s=e=>{this.emit(y.ON_MESSAGE,e)},r=e=>{l.warn("[".concat(this.connectionID,"] ws open error ").concat(e))};this.websocket&&(this.websocket.onclose=null,this.websocket.close()),c("GATEWAY_WSS_ADDRESS")&&this.name.startsWith("gateway")&&(t=c("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 N;const e=await this.chooseBestWebsocketConnection(t);this.websocket=e,E&&E(this.websocket.url),this.websocket.onclose=i,this.websocket.onmessage=s,this.websocket.onerror=r,null===(N=this.store)||void 0===N||N.recordJoinChannelService({endTs:Date.now(),status:"success"},R),this.joinGatewayRecordIndex=R}catch(t){const n="closed"===this.state,E=t instanceof e,s=E&&t.code===a.WS_ABORT,r=E&&t.code===a.WS_ERR,_=E?t.message:t&&(t.reason||t.toString());l.warning("[choose-best-ws] chooseBestWebsocket error: ".concat(_)),this.store&&this.store.recordJoinChannelService({endTs:Date.now(),status:s?"aborted":"error",errors:[t]},R),n||r?(o.reject(n?new e(a.WS_DISCONNECT,"websocket is closed: ".concat(_)):new e(a.WS_ERR,"init websocket failed: ".concat(_))),r&&l.error("[".concat(this.name,"] init websocket failed: ").concat(_))):i&&i(t)}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||s.isOnline||!s.onlineWaiter||(this.onlineReconnectListener=s.onlineWaiter.then((()=>{this.onlineReconnectListener=void 0})));let n=!0;if(this.reconnectInterrupter=()=>n=!1,t){const t=R(this.reconnectCount,this.retryConfig);l.debug("[".concat(this.name,"] wait ").concat(t,"ms to reconnect websocket, mode: ").concat(e)),await Promise.race([N(t),this.onlineReconnectListener||new Promise((()=>{}))])}if("closed"===this._state||!n)return!1;this.reconnectCount+=1;const o=async(e,t)=>{this.emit(y.RECONNECT_CREATE_CONNECTION,t),await this.createWebSocketConnection(e)};try{if("retry"===e)this.emit(y.RECONNECT_WAITTING_FINISH,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)),this.emit(y.RECONNECT_WAITTING_FINISH,e),await o(this.urls[this.currentURLIndex],e)}else"recover"===e&&(l.debug("[".concat(this.name,"] request new urls")),this.resetReconnectCount("recover mode"),this.emit(y.RECONNECT_WAITTING_FINISH,e),this.urls=await I(this,y.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;return Array.isArray(o)&&o.includes("dynamic key expired")?(this.emit(y.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):this.reconnectWithAction(e,t)}return!0}}class Y extends H{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(((o,E)=>{let i=!1;const s=[];this.closeEstablishingWs=()=>{l.debug("[choose-best-ws] close establishing websockets"),s.forEach((e=>{e.onclose=null,e.onopen=null,e.onmessage=null,e.close()})),E(new e(a.WS_ABORT,"choose best websocket aborted"))};const r=c("GATEWAY_DOMAINS");let _;const R=t.indexOf("?h="),I=r.find((e=>-1!==R?t.includes(e,R):t.includes(e)));l.debug("[choose-best-ws] currentDomain: ",I,", domains: ",r);let A=!this.tryDoubleDomain||!I;if(!A&&I){var C;const e=Date.now();try{r.forEach((e=>{const n=-1===R?t.replace(I,e):t.substr(0,R)+t.substr(R).replace(I,e),o=new WebSocket(n);o.binaryType="arraybuffer",s.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"),s.forEach((e=>e.close()));s.length;)s.pop();A=!0}null===(C=this.store)||void 0===C||C.recordJoinChannelService({urls:s.map((e=>e.url)),service:"gateway"},n),s.forEach((t=>{t.onopen=()=>{if(i)return;const n=Date.now()-e;l.debug("[choose-best-ws] ws open cost ".concat(n,"ms")),s.filter((e=>e!==t)).forEach((e=>{l.debug("[choose-best-ws]close backup websocket: ".concat(e.url)),e.close()})),i=!0,o(t)},t.onclose=e=>{if(_=e,i)return;s.find((e=>!(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING)))||(l.debug("[choose-best-ws] all websocket is closed"),i=!0,E(_))},t.onmessage=e=>{l.debug("[choose-best-ws]".concat(t.url," onmessage: ").concat(e.data))}})),N(this.forceCloseTimeout).then((()=>{s.forEach((e=>{e.readyState!==WebSocket.OPEN&&e.close()}))}))}if(A){var T;let i;l.debug("[choose-best-ws] use single url: ",t),null===(T=this.store)||void 0===T||T.recordJoinChannelService({urls:[t],service:"gateway"},n);try{i=new WebSocket(t),s.push(i),i.binaryType="arraybuffer"}catch(t){const n=new e(a.WS_ERR,"init websocket failed! Error: ".concat(t.toString()));return l.error("[".concat(this.name,"]").concat(n)),void E(n)}i.onopen=()=>{o(i)},i.onclose=e=>{E(e)},i.onmessage=e=>{l.debug("[choose-best-ws]".concat(i.url," onmessage: ").concat(e.data))},N(this.forceCloseTimeout).then((()=>{i&&i.readyState!==WebSocket.OPEN&&i.close()}))}})).then((e=>(this.closeEstablishingWs=void 0,e))).catch((e=>{throw this.closeEstablishingWs=void 0,e}))}}function F(e){let t=te();return function(e,t){let n=e.appId;void 0!==n&&(Ce(t,10),_e(t,n));let o=e.cid;void 0!==o&&(Ce(t,16),Ce(t,o));let E=e.cname;void 0!==E&&(Ce(t,26),_e(t,E));let i=e.deviceId;void 0!==i&&(Ce(t,34),_e(t,i));let s=e.elapse;void 0!==s&&(Ce(t,40),Te(t,s));let r=e.fileSize;void 0!==r&&(Ce(t,48),Te(t,$(r)));let _=e.height;void 0!==_&&(Ce(t,56),Te(t,$(_)));let c=e.jpg;void 0!==c&&(Ce(t,66),Ce(t,c.length),function(e,t){let n=ie(e,t.length);e.bytes.set(t,n)}(t,c));let a=e.networkType;void 0!==a&&(Ce(t,72),Te(t,$(a)));let R=e.osType;void 0!==R&&(Ce(t,80),Te(t,$(R)));let N=e.requestId;void 0!==N&&(Ce(t,90),_e(t,N));let I=e.sdkVersion;void 0!==I&&(Ce(t,98),_e(t,I));let A=e.sequence;void 0!==A&&(Ce(t,104),Te(t,$(A)));let C=e.sid;void 0!==C&&(Ce(t,114),_e(t,C));let T=e.timestamp;void 0!==T&&(Ce(t,120),Te(t,T));let O=e.uid;void 0!==O&&(Ce(t,128),Ce(t,O));let h=e.vid;void 0!==h&&(Ce(t,136),Ce(t,h));let S=e.width;void 0!==S&&(Ce(t,144),Te(t,$(S)));let l=e.service;void 0!==l&&(Ce(t,152),Ce(t,l));let L=e.callbackData;void 0!==L&&(Ce(t,162),_e(t,L));let d=e.jpgEncryption;void 0!==d&&(Ce(t,168),Ce(t,d));let u=e.requestType;void 0!==u&&(Ce(t,176),Ce(t,u));let D=e.scorePorn;void 0!==D&&(Ce(t,185),Ie(t,D));let w=e.scoreSexy;void 0!==w&&(Ce(t,193),Ie(t,w));let p=e.scoreNeutral;void 0!==p&&(Ce(t,201),Ie(t,p));let f=e.scene;void 0!==f&&(Ce(t,208),Ce(t,f));let g=e.ossFilePrefix;void 0!==g&&(Ce(t,218),_e(t,g));let m=e.serviceVendor;if(void 0!==m)for(let e of m){Ce(t,226);let n=te();J(e,n),Ce(t,n.limit),ce(t,n),ne(n)}}(e,t),function(e){let t=e.bytes,n=e.limit;return t.length===n?t:t.subarray(0,n)}(t)}function x(e){return function(e){let t={};e:for(;!Ee(e);){let n=Ae(e);switch(n>>>3){case 0:break e;case 1:t.code=Ae(e);break;case 2:t.msg=re(e,Ae(e));break;case 3:{let n=j(e);t.data=q(e),e.limit=n;break}default:X(e,7&n)}}return t}({bytes:t=e,offset:0,limit:t.length});var t}function q(e){let t={};e:for(;!Ee(e);){let n=Ae(e);switch(n>>>3){case 0:break e;case 1:t.requestId=re(e,Ae(e));break;case 2:t.requestType=Ae(e)>>>0;break;case 3:t.scorePorn=Ne(e);break;case 4:t.scoreSexy=Ne(e);break;case 5:t.scoreNeutral=Ne(e);break;case 6:t.requestScene=Ae(e)>>>0;break;case 7:t.scene=Ae(e)>>>0;break;default:X(e,7&n)}}return t}function J(e,t){let n=e.service;void 0!==n&&(Ce(t,8),Ce(t,n));let o=e.vendor;void 0!==o&&(Ce(t,16),Ce(t,o));let E=e.token;void 0!==E&&(Ce(t,26),_e(t,E));let i=e.callbackUrl;void 0!==i&&(Ce(t,34),_e(t,i))}function j(e){let t=Ae(e),n=e.limit;return e.limit=e.offset+t,n}function X(e,t){switch(t){case 0:for(;128&ae(e););break;case 2:oe(e,Ae(e));break;case 5:oe(e,4);break;case 1:oe(e,8);break;default:throw new Error("Unimplemented type: "+t)}}let Q=new Float32Array(1);new Uint8Array(Q.buffer);let Z=new Float64Array(1),z=new Uint8Array(Z.buffer);function $(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}let ee=[];function te(){const e=ee.pop();return e?(e.offset=e.limit=0,e):{bytes:new Uint8Array(64),offset:0,limit:0}}function ne(e){ee.push(e)}function oe(e,t){if(e.offset+t>e.limit)throw new Error("Skip past limit");e.offset+=t}function Ee(e){return e.offset>=e.limit}function ie(e,t){let n=e.bytes,o=e.offset,E=e.limit,i=o+t;if(i>n.length){let t=new Uint8Array(2*i);t.set(n),e.bytes=t}return e.offset=i,i>E&&(e.limit=i),o}function se(e,t){let n=e.offset;if(n+t>e.limit)throw new Error("Read past limit");return e.offset+=t,n}function re(e,t){let n=se(e,t),o=String.fromCharCode,E=e.bytes,i="�",s="";for(let e=0;e<t;e++){let r,_,c,a,R=E[e+n];0==(128&R)?s+=o(R):192==(224&R)?e+1>=t?s+=i:(r=E[e+n+1],128!=(192&r)?s+=i:(a=(31&R)<<6|63&r,a<128?s+=i:(s+=o(a),e++))):224==(240&R)?e+2>=t?s+=i:(r=E[e+n+1],_=E[e+n+2],32896!=(49344&(r|_<<8))?s+=i:(a=(15&R)<<12|(63&r)<<6|63&_,a<2048||a>=55296&&a<=57343?s+=i:(s+=o(a),e+=2))):240==(248&R)?e+3>=t?s+=i:(r=E[e+n+1],_=E[e+n+2],c=E[e+n+3],8421504!=(12632256&(r|_<<8|c<<16))?s+=i:(a=(7&R)<<18|(63&r)<<12|(63&_)<<6|63&c,a<65536||a>1114111?s+=i:(a-=65536,s+=o(55296+(a>>10),56320+(1023&a)),e+=3))):s+=i}return s}function _e(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}Ce(e,o);let E=ie(e,o),i=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?i[E++]=o:(o<2048?i[E++]=o>>6&31|192:(o<65536?i[E++]=o>>12&15|224:(i[E++]=o>>18&7|240,i[E++]=o>>12&63|128),i[E++]=o>>6&63|128),i[E++]=63&o|128)}}function ce(e,t){let n=ie(e,t.limit),o=e.bytes,E=t.bytes;for(let e=0,i=t.limit;e<i;e++)o[e+n]=E[e]}function ae(e){return e.bytes[se(e,1)]}function Re(e,t){let n=ie(e,1);e.bytes[n]=t}function Ne(e){let t=se(e,8),n=e.bytes;return z[0]=n[t++],z[1]=n[t++],z[2]=n[t++],z[3]=n[t++],z[4]=n[t++],z[5]=n[t++],z[6]=n[t++],z[7]=n[t++],Z[0]}function Ie(e,t){let n=ie(e,8),o=e.bytes;Z[0]=t,o[n++]=z[0],o[n++]=z[1],o[n++]=z[2],o[n++]=z[3],o[n++]=z[4],o[n++]=z[5],o[n++]=z[6],o[n++]=z[7]}function Ae(e){let t,n=0,o=0;do{t=ae(e),n<32&&(o|=(127&t)<<n),n+=7}while(128&t);return o}function Ce(e,t){for(t>>>=0;t>=128;)Re(e,127&t|128),t>>>=7;Re(e,t)}function Te(e,t){let n=t.low>>>0,o=(t.low>>>28|t.high<<4)>>>0,E=t.high>>>24,i=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,s=ie(e,i),r=e.bytes;switch(i){case 10:r[s+9]=E>>>7&1;case 9:r[s+8]=9!==i?128|E:127&E;case 8:r[s+7]=8!==i?o>>>21|128:o>>>21&127;case 7:r[s+6]=7!==i?o>>>14|128:o>>>14&127;case 6:r[s+5]=6!==i?o>>>7|128:o>>>7&127;case 5:r[s+4]=5!==i?128|o:127&o;case 4:r[s+3]=4!==i?n>>>21|128:n>>>21&127;case 3:r[s+2]=3!==i?n>>>14|128:n>>>14&127;case 2:r[s+1]=2!==i?n>>>7|128:n>>>7&127;case 1:r[s]=1!==i?128|n:127&n}}let Oe=0,he=0;m.ACCESS_POINT,U.NO_FLAG_SET,U.FLAG_SET_BUT_EMPTY,U.INVALID_FALG_SET,U.FLAG_SET_BUT_NO_RE,U.INVALID_SERVICE_ID,U.NO_SERVICE_AVAILABLE,U.NO_SERVICE_AVAILABLE_P2P,U.NO_SERVICE_AVAILABLE_VOICE,U.NO_SERVICE_AVAILABLE_WEBRTC,U.NO_SERVICE_AVAILABLE_CDS,U.NO_SERVICE_AVAILABLE_CDN,U.NO_SERVICE_AVAILABLE_TDS,U.NO_SERVICE_AVAILABLE_REPORT,U.NO_SERVICE_AVAILABLE_APP_CENTER,U.NO_SERVICE_AVAILABLE_ENV0,U.NO_SERVICE_AVAILABLE_VOET,U.NO_SERVICE_AVAILABLE_STRING_UID,U.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS,m.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,m.STRING_UID_ALLOCATOR,V.IIIEGAL_APPID,V.IIIEGAL_UID,V.INTERNAL_ERROR,b.K_TIMESTAMP_EXPIRED,b.K_CHANNEL_PERMISSION_INVALID,b.K_CERTIFICATE_INVALID,b.K_CHANNEL_NAME_EMPTY,b.K_CHANNEL_NOT_FOUND,b.K_TICKET_INVALID,b.K_CHANNEL_CONFLICTED,b.K_SERVICE_NOT_READY,b.K_SERVICE_TOO_HEAVY,b.K_UID_BANNED,b.K_IP_BANNED,b.K_AUTO_REBALANCE,b.ERR_INVALID_VENDOR_KEY,b.ERR_INVALID_CHANNEL_NAME,b.WARN_NO_AVAILABLE_CHANNEL,b.WARN_LOOKUP_CHANNEL_TIMEOUT,b.WARN_LOOKUP_CHANNEL_REJECTED,b.WARN_OPEN_CHANNEL_TIMEOUT,b.WARN_OPEN_CHANNEL_REJECTED,b.WARN_REQUEST_DEFERRED,b.ERR_DYNAMIC_KEY_TIMEOUT,b.ERR_NO_AUTHORIZED,b.ERR_VOM_SERVICE_UNAVAILABLE,b.ERR_NO_CHANNEL_AVAILABLE_CODE,b.ERR_MASTER_VOCS_UNAVAILABLE,b.ERR_INTERNAL_ERROR,b.ERR_NO_ACTIVE_STATUS,b.ERR_INVALID_UID,b.ERR_DYNAMIC_KEY_EXPIRED,b.ERR_STATIC_USE_DYANMIC_KE,b.ERR_DYNAMIC_USE_STATIC_KE,b.ERR_NO_VOCS_AVAILABLE,b.ERR_NO_VOS_AVAILABLE,b.ERR_JOIN_CHANNEL_TIMEOUT,b.ERR_JOIN_BY_MULTI_IP,b.ERR_NOT_JOINED,b.ERR_REPEAT_JOIN_REQUEST,b.ERR_REPEAT_JOIN_CHANNEL,b.ERR_INVALID_STRINGUID,b.ERR_TOO_MANY_USERS,b.ERR_SET_CLIENT_ROLE_TIMEOUT,b.ERR_SET_CLIENT_ROLE_NO_PERMISSION,b.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE,b.ERR_PUBLISH_REQUEST_INVALID,b.ERR_SUBSCRIBE_REQUEST_INVALID,b.ERR_NOT_SUPPORTED_MESSAGE,b.ERR_ILLEAGAL_PLUGIN,b.ILLEGAL_CLIENT_ROLE_LEVEL,b.ERR_REJOIN_TOKEN_INVALID,b.ERR_REJOIN_USER_NOT_JOINED,b.ERR_INVALID_OPTIONAL_INFO,b.ERR_TEST_RECOVER,b.ERR_TEST_TRYNEXT,b.ERR_TEST_RETRY,b.ILLEGAL_AES_PASSWORD,b.ERR_TOO_MANY_BROADCASTERS,b.ERR_TOO_MANY_SUBSCRIBERS,b.ERR_LICENSE_ILLEGAL,b.ERR_LICENSE_MISSING,b.ERR_LICENSE_EXPIRED,b.ERR_LICENSE_MINUTES_EXCEEDED,b.ERR_LICENSE_PERIOD_INVALID,b.ERR_LICENSE_MULTIPLE_SDK_SERVICE;const Se={GLOBAL:{ASIA:[v.CHINA,v.JAPAN,v.INDIA,v.KOREA,v.HKMC],EUROPE:[],NORTH_AMERICA:[v.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}};Object.keys(Se[v.GLOBAL]),v.CHINA,v.NORTH_AMERICA,v.EUROPE,v.ASIA,v.JAPAN,v.INDIA,v.OCEANIA,v.SOUTH_AMERICA,v.AFRICA,v.KOREA,v.HKMC,v.US;let le=0;function Le(e,t,n,o){let{appId:E,areaCode:i,cname:s,sid:r,token:_,uid:R}=t;le++;const N="image_moderation_api",I={service_name:N,json_body:JSON.stringify({appId:E,areaCode:i,cname:s,command:"allocateEdge",requestId:le,seq:le,sid:r,token:_,ts:Date.now(),uid:R+""})};let A,h,S=e[0];return O((async()=>{A=Date.now();const e=await function(e,t,n,o){return new Promise(((E,i)=>{t.timeout=t.timeout||c("HTTP_CONNECT_TIMEOUT"),t.responseType=t.responseType||"json",t.data&&!n?(t.data=JSON.stringify(t.data),Oe+=C(t.data)):n&&(t.data.size?Oe+=t.data.size:t.data instanceof FormData?Oe+=T(t.data):Oe+=C(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,D.request(t).then((e=>{"string"==typeof e.data?he+=C(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?he+=e.data.byteLength:he+=C(JSON.stringify(e.data)),o&&E({data:e.data,headers:e.headers}),E(e.data)})).catch((e=>{D.isCancel(e)?i(new g(a.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?i(new g(a.NETWORK_TIMEOUT,e.message)):e.response?i(new g(a.NETWORK_RESPONSE_ERROR,e.response.status)):i(new g(a.NETWORK_ERROR,e.message))}))}))}(S,{data:I,cancelToken:n,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"},params:{action:"wrtc_gateway"}});if(h=Date.now()-A,0!==e.code){const t=new g(a.UNEXPECTED_RESPONSE,"image inspect ap error, code"+e.code,{retry:!0,responseTime:h});throw l.error(t.toString()),t}const t=JSON.parse(e.json_body);if(200!==t.code){const e=new g(a.UNEXPECTED_RESPONSE,"image inspect ap error, code: ".concat(t.code,", reason: ").concat(t.reason),{code:t.code,responseTime:h});throw l.error(e.toString()),e}if(!t.servers||!Array.isArray(t.servers)||0===t.servers.length){const e=new g(a.UNEXPECTED_RESPONSE,"image inspect ap empty server",{code:t.code,responseTime:h});throw l.error(e.toString()),e}const o=c("VIDEO_INSPECT_WORKER_MANAGER_HOST"),E=c("VIDEO_INSPECT_WORKER_MANAGER_PORT");return{addressList:t.servers.map((e=>{let{address:t,wss:n}=e;if(t&&n)return"wss://".concat(t.replace(/\./g,"-"),".").concat(o,":").concat(E||n)})).filter((e=>!!e)),workerToken:t.workerToken,vid:t.vid,responseTime:h}}),((t,n)=>(d.apworkerEvent(r,{success:!0,sc:200,serviceName:N,responseDetail:JSON.stringify(t.addressList),firstSuccess:0===n,responseTime:h,serverIp:e[n%e.length]}),!1)),((t,n)=>(d.apworkerEvent(r,{success:!1,sc:t.data&&t.data.code||200,serviceName:N,responseTime:h,serverIp:e[n%e.length]}),!!(t.code!==a.OPERATION_ABORTED&&t.code!==a.UNEXPECTED_RESPONSE||t.data&&t.data.retry)&&(S=e[(n+1)%e.length],!0))),o)}const de=new Map([["moderation",1],["supervise",2]]);function ue(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}class De extends o{get connectionState(){return this._connectionState}set connectionState(e){if(this._connectionState===e)return;const t=this._connectionState;this._connectionState=e,this.emit(K.CONNECTION_STATE_CHANGE,t,e)}get inspectType(){return this._inspectType}set inspectType(e){this._inspectMode=e.map((e=>de.get(e)||0)).reduce(((e,t)=>e+t)),this._inspectType=e}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){super(),this.name="AgoraRTCVideoContentInspect",this._connectionState=B.CONNECTING,this._innerConnectionState=void 0,this.sequence=0,this.inspectStartTime=void 0,this.workerManagerConnection=void 0,this.workerConnection=void 0,this.workerMessageLengthLimit=void 0,this.inspectIntervalMinimum=void 0,this.qualityRatio=void 0,this._connectInfo=void 0,this._cancelTokenSource=D.CancelToken.source(),this._retryConfig=void 0,this.wmSequence=0,this.inspectInterval=void 0,this.inspectTimer=null,this.ossFilePrefix=void 0,this.extraInfo=void 0,this._inspectType=void 0,this._inspectMode=void 0,this._quality=1,this.qualityTimer=null,this._inspectId=void 0,this._needWorkUrlOnly=!1,this.inspectImage=()=>{if(this.connectionState!==B.CONNECTED)throw new g(a.OPERATION_ABORTED,"content inspect service connection status is ".concat(this.connectionState));this.inspectTimer&&(window.clearInterval(this.inspectTimer),this.inspectTimer=null),this.inspectTimer=window.setInterval((()=>{this.connectionState===B.CONNECTED?this.requestToInspectImage():l.debug("[".concat(this._inspectId,"] Inspect State is not connected , "),this.connectionState)}),this.inspectInterval<this.inspectIntervalMinimum?this.inspectIntervalMinimum:this.inspectInterval),this.requestToInspectImage()},this._inspectId=h(5,"inspect-"),this.workerMessageLengthLimit=c("VIDEO_INSPECT_WORKER_MESSAGE_LENGTH_LIMIT"),this.inspectIntervalMinimum=c("VIDEO_INSPECT_INTERVAL_MINIMUM"),this.qualityRatio=c("VIDEO_INSPECT_QUALITY_RATIO"),this.inspectInterval=e.interval,this.ossFilePrefix=e.ossFilePrefix,this.extraInfo=e.extraInfo,this.inspectType=e.inspectType,this.inspectStartTime=Number(Date.now()),this.workerManagerConnection=new Y("worker-manager-"+this._inspectId,S),this.on(K.STATE_CHANGE,((e,t)=>{this._innerConnectionState=e,l.debug("[".concat(this._inspectId,"] Inspect operation :").concat(W[e]," ").concat(t||""))})),this.handleWorkerManagerEvents(),this.workerConnection=new Y("worker-"+this._inspectId,S),this.handleWorkerEvents()}async init(e,t){this.emit(K.STATE_CHANGE,W.CONNECT_AP),this._connectInfo=e;const n=this._cancelTokenSource.token;return this._retryConfig=t,new Promise(((o,E)=>{this.on(K.CONNECTION_STATE_CHANGE,((e,t)=>{t===B.CONNECTED&&o()})),this.requestAP(e,n,t).then((e=>{this.connectWorkerManager(e)})).catch((e=>{E(e)}))}))}async requestAP(e,t,n){const o=c("WEBCS_DOMAIN").map((e=>"https://".concat(e,"/api/v1"))),E=await Le(o,e,t,n);this.emit(K.STATE_CHANGE,W.AP_CONNECTED);const{addressList:i}=E;return this.wmSequence++,i}async connectWorkerManager(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._needWorkUrlOnly=t,this.emit(K.STATE_CHANGE,W.CONNECT_WORKER_MANAGER),await this.workerManagerConnection.init(e,1e4)}async connectWorker(e){await this.workerConnection.init([e])}handleWorkerManagerEvents(){this.workerManagerConnection.on(y.CONNECTED,(async()=>{this.emit(K.STATE_CHANGE,W.WORKER_MANAGER_CONNECTED,this.workerManagerConnection.url),this.workerManagerConnection.sendMessage({appId:this._connectInfo.appId,cname:this._connectInfo.cname,uid:this._connectInfo.uid+"",sdkVersion:"4.22.0",sid:this._connectInfo.sid,seq:this.wmSequence,ts:Number(Date.now()),requestId:Math.floor(1e12*Math.random()),allocate:!0,clientRequest:{command:"join"}},!0)})),this.workerManagerConnection.on(y.CLOSED,(()=>{this._innerConnectionState<W.GET_WORKER_MANAGER_RESPONSE&&l.debug("[".concat(this._inspectId,"] Inspect worker manager is closed before connecting worker"))})),this.workerManagerConnection.on(y.FAILED,(()=>{this._innerConnectionState<W.GET_WORKER_MANAGER_RESPONSE&&l.debug("[".concat(this._inspectId,"] Connecting inspect worker manager is failed before connecting worker"))})),this.workerManagerConnection.on(y.RECONNECTING,(()=>{this._innerConnectionState<W.GET_WORKER_MANAGER_RESPONSE&&l.debug("[".concat(this._inspectId,"] Inspect worker manager is reconnecting before connecting worker"))})),this.workerManagerConnection.on(y.ON_MESSAGE,(async e=>{this.emit(K.STATE_CHANGE,W.GET_WORKER_MANAGER_RESPONSE);const t=this.workerManagerConnection.url;this.workerManagerConnection.close();const n=JSON.parse(e.data);if(200!==n.code)throw l.error("[".concat(this._inspectId,"] Unexpected code ").concat(n.code," from worker manager")),new g(a.UNEXPECTED_RESPONSE,"response code of worker is unexpected",n);if(!(n.serverResponse&&n.serverResponse.portWss&&t))throw l.error("[".concat(this._inspectId,"] Unexpected content from worker manager : ").concat(JSON.stringify(n))),new g(a.UNEXPECTED_RESPONSE,"response content of worker is unexpected",n);{const e=c("VIDEO_INSPECT_WORKER_PORT")||n.serverResponse.portWss,o=t.replace(/:\d+\/?$/,":".concat(e));this.emit(K.STATE_CHANGE,W.CONNECT_WORKER,o),this._needWorkUrlOnly?this.emit(K.REQUEST_NEW_WORKER_URL,o):await this.connectWorker(o)}})),this.workerManagerConnection.on(y.WILL_RECONNECT,((e,t,n)=>{n(e)})),this.workerManagerConnection.on(y.REQUEST_NEW_URLS,((e,t)=>{this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(e).catch(t)}))}handleWorkerEvents(){this.workerConnection.on(y.CONNECTED,(async()=>{this.emit(K.STATE_CHANGE,W.WORKER_CONNECTED,this.workerConnection.url),this.connectionState=B.CONNECTED})),this.workerConnection.on(y.ON_MESSAGE,(async e=>{if(e.data instanceof ArrayBuffer){const t=x(new Uint8Array(e.data));if(c("SHOW_VIDEO_INSPECT_WORKER_MESSAGE")&&l.debug("[".concat(this._inspectId,"] Response message for worker of inspect content "),JSON.stringify(t)),200===t.code){if(Array.isArray(this.inspectType)&&1===this.inspectType.length&&"supervise"===this.inspectType[0])return void this.emit(K.INSPECT_RESULT,void 0,void 0);if(t.data&&t.data.scorePorn&&t.data.scoreSexy&&t.data.scoreNeutral){const e={porn:t.data.scorePorn,sexy:t.data.scoreSexy,neutral:t.data.scoreNeutral},n=Object.keys(e).reduce(((t,n)=>e[t]>e[n]?t:n),"porn"),o=Object.keys(e).find((e=>e===n));this.emit(K.INSPECT_RESULT,o)}else this.emit(K.INSPECT_RESULT,void 0,new g(a.UNEXPECTED_RESPONSE,t.code+"","There is an unexpected data on message"))}else this.emit(K.INSPECT_RESULT,void 0,new g(a.UNEXPECTED_RESPONSE,t.code+"",t.msg))}else l.error("[".concat(this._inspectId,"] Unexpected message type from worker")),this.emit(K.INSPECT_RESULT,void 0,new g(a.UNEXPECTED_RESPONSE,"invalid worker message type"))})),this.workerConnection.on(y.CLOSED,(()=>{this.connectionState=B.CLOSED})),this.workerConnection.on(y.FAILED,(()=>{this.connectionState=B.CLOSED})),this.workerConnection.on(y.RECONNECTING,(()=>{this.connectionState=this.connectionState===B.CONNECTED?B.RECONNECTING:B.CONNECTING})),this.workerConnection.on(y.WILL_RECONNECT,((e,t,n)=>{"recover"===e&&n(e),n("tryNext")})),this.workerConnection.on(y.REQUEST_NEW_URLS,((e,t)=>{this.workerManagerConnection.close(),this.once(K.REQUEST_NEW_WORKER_URL,(t=>{e([t])})),this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then((e=>{this.connectWorkerManager(e,!0)})).catch((e=>{t(e)}))}))}async requestToInspectImage(){this.sequence++;const e=A(this,K.CLIENT_LOCAL_VIDEO_TRACK),t={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 this.emit(K.INSPECT_RESULT,void 0,new g(a.INVALID_OPERATION,"Only the track being played can be inspected"));const n=await this.generateRequestData(e,t);this.workerConnection.sendMessage(n,!0,!0)}else this.emit(K.INSPECT_RESULT,void 0,new g(a.INVALID_OPERATION,"Only the track being published can be inspected"))}async generateRequestData(e,t){let{appId:n,cname:o,cid:E,vid:i,sid:s,uid:r}=t;const _=Date.now(),a=await e.getCurrentFrameImage("image/jpeg",this.quality),R=await u(a,n,o),N=this.sequence+"-"+E+"-"+r+"-"+_+"-"+h(12,""),I={appId:n,cid:E,cname:o,deviceId:"",elapse:ue(Number(_-this.inspectStartTime)),fileSize:R.byteLength,jpgEncryption:2,height:a.height,width:a.width,jpg:R,networkType:6,osType:7,requestId:N,sdkVersion:"4.22.0",sequence:this.sequence,sid:s,timestamp:ue(_),uid:r,vid:i,service:this._inspectMode,callbackData:this.extraInfo,ossFilePrefix:this.ossFilePrefix};void 0===this.extraInfo&&delete I.callbackData,void 0===this.ossFilePrefix&&delete I.ossFilePrefix;const A=F(I);if(A.byteLength<this.workerMessageLengthLimit){if(c("SHOW_VIDEO_INSPECT_WORKER_MESSAGE")){const e=f({},I);delete e.jpg,l.debug("[".concat(this._inspectId,"] Request message for worker of inspect content "),JSON.stringify(e))}return A}{const t=this.quality*this.qualityRatio;return this.quality=t,await this.generateRequestData(e,{appId:n,cname:o,cid:E,vid:i,sid:s,uid:r})}}close(){this._cancelTokenSource.cancel(),this._cancelTokenSource=D.CancelToken.source(),this.workerManagerConnection&&this.workerManagerConnection.close(),this.workerConnection&&this.workerConnection.close(),this.inspectTimer&&window.clearInterval(this.inspectTimer),this.inspectTimer=null,this.connectionState=B.CLOSED,this.emit(K.STATE_CHANGE,W.CLOSED)}}function we(e){if(!e)throw new g(a.INVALID_PARAMS,"inspectConfig is necessary.");if(!e.inspectType||!Array.isArray(e.inspectType))throw new g(a.INVALID_PARAMS,"inspectConfig.inspectType is necessary and is an instance of Array.");{const t=[...new Set(e.inspectType)];t.forEach((e=>{if(!["supervise","moderation"].includes(e))throw new g(a.INVALID_PARAMS,"".concat(e," is not a valid inspect type."))})),e.inspectType=t}if(e&&e.extraInfo&&e.extraInfo.length>1024)throw new g(a.INVALID_PARAMS,"inspectConfig.extraInfo length cannot exceed 1024 bytes")}const pe={name:"ContentInspect",create:function(e){let{config:t}=e;return we(t),new De(t)}};export{pe as ContentInspectService,we as checkContentInspectConfig}; | ||
import{IS_GLOBAL_VERSION as e,EventEmitter as t,PromiseMutex as n,NETWORK_STATE as E,networkIndicator as o,NETWORK_INDICATOR_EVENTS as s,createDefer as i,getParameter as r,AgoraRTCError as _,AgoraRTCErrorCode as c,getRetryWaitTime as a,wait as N,emitAsPromise as R,emitAsInvokerNoResponse as I,getUTF8StringByteLength as A,getMultiUnilbsFormDataByteLength as C,retryable as T,getRandomString as O,DEFAULT_RETRY_CONFIG as h}from"@agora-js/shared";import{logger as S,AgoraRTCError as L,AgoraRTCErrorCode as l,report as d}from"@agora-js/report";import{frameData2CryptoBuffer as u}from"@agora-js/media";import D from"axios";import"formdata-polyfill";function w(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 E=n.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:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function f(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var E=Object.getOwnPropertySymbols(e);t&&(E=E.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,E)}return n}function p(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?f(Object(n),!0).forEach((function(t){w(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):f(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}let g=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}({}),m=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}({}),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}({}),U=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}({}),y=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}({}),M=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}({});M.AFRICA,M.ASIA,M.CHINA,M.EUROPE,M.GLOBAL,M.INDIA,M.JAPAN,M.NORTH_AMERICA,M.OCEANIA,M.OVERSEA,M.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;let k=function(e){return e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED",e}({}),v=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}({}),W=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}({}),B=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 K extends t{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(y.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(y.CONNECTED):"closed"===this._state?this.emit(y.CLOSED):"failed"===this._state&&this.emit(y.FAILED))}resetReconnectCount(e){S.debug("websocket reset reconnect count, reason: "+e),this.reconnectCount=0}constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=arguments.length>3&&void 0!==arguments[3]&&arguments[3],_=arguments.length>4&&void 0!==arguments[4]&&arguments[4],c=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 n("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=c,this.name=e,this.retryConfig=p({},t),this.useCompress=i,this.tryDoubleDomain=r,this.use443PortOnly=_;const{timeout:a,timeoutFactor:N}=t,R=Math.max(300,Math.floor(3*a/5)),I=Math.max(1.2,Math.floor(8*N)/10);E.ONLINE&&(this.retryConfig.timeout=R,this.retryConfig.timeoutFactor=I),o.on(s.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=I):(this.retryConfig.timeout=a,this.retryConfig.timeoutFactor=N))}))}getConnection(){return this.websocket||void 0}async init(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const n=await this._initMutex.lock();this.forceCloseTimeout=t,this.urls=e,this.state="connecting";try{const e=i(),t=this.urls[this.currentURLIndex];r("ENABLE_PREALLOC_PC")&&this.emit(B.PRE_CONNECT_PC),this.createWebSocketConnection(t).then(e.resolve).catch(e.reject),this.once(y.CLOSED,(()=>{e.reject(new _(c.WS_DISCONNECT))})),this.once(y.CONNECTED,e.resolve),await e.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 S.warning("[".concat(this.name,"] can not reconnect, no websocket"));void 0!==e&&(this.reconnectMode=e),S.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 _(c.WS_ABORT,"websocket is not ready");try{t||(e=JSON.stringify(e)),this.websocket.send(e)}catch(e){throw new _(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 t;const n=i();this.connectionID+=1,this.joinGatewayRecordIndex=void 0;const E=e=>{var t;null===(t=this.store)||void 0===t||t.signalChannelOpen(),S.debug("[".concat(this.name,"] websocket opened:"),e),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),n.resolve()},o=async e=>{var t;if(S.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 _(c.WS_DISCONNECT,"websocket close: ".concat(e.code))),this.close();else{"connected"===this.state&&(this.reconnectReason=e.reason,this.state="reconnecting");const t=I(this,y.WILL_RECONNECT,this.reconnectMode,e.reason)||this.reconnectMode,E=await this.reconnectWithAction(t);if("closed"===this.state)return void S.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!E)return n.reject(new _(c.WS_DISCONNECT,"websocket reconnect failed: ".concat(e.code))),this.close(!0);n.resolve()}},s=e=>{this.emit(y.ON_MESSAGE,e)},a=e=>{S.warn("[".concat(this.connectionID,"] ws open error ").concat(e))};this.websocket&&(this.websocket.onclose=null,this.websocket.close()),r("GATEWAY_WSS_ADDRESS")&&this.name.startsWith("gateway")&&(e=r("GATEWAY_WSS_ADDRESS")),S.debug("[".concat(this.name,"] start connect, url:"),e);const N=null===(t=this.store)||void 0===t?void 0:t.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"});try{var R;const t=await this.chooseBestWebsocketConnection(e);this.websocket=t,E&&E(this.websocket.url),this.websocket.onclose=o,this.websocket.onmessage=s,this.websocket.onerror=a,null===(R=this.store)||void 0===R||R.recordJoinChannelService({endTs:Date.now(),status:"success"},N),this.joinGatewayRecordIndex=N}catch(e){const t="closed"===this.state,E=e instanceof _,s=E&&e.code===c.WS_ABORT,i=E&&e.code===c.WS_ERR,r=E?e.message:e&&(e.reason||e.toString());S.warning("[choose-best-ws] chooseBestWebsocket error: ".concat(r)),this.store&&this.store.recordJoinChannelService({endTs:Date.now(),status:s?"aborted":"error",errors:[e]},N),t||i?(n.reject(t?new _(c.WS_DISCONNECT,"websocket is closed: ".concat(r)):new _(c.WS_ERR,"init websocket failed: ".concat(r))),i&&S.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;S.warning("[choose-best-ws] action: =>",e),this.onlineReconnectListener||o.isOnline||!o.onlineWaiter||(this.onlineReconnectListener=o.onlineWaiter.then((()=>{this.onlineReconnectListener=void 0})));let n=!0;if(this.reconnectInterrupter=()=>n=!1,t){const t=a(this.reconnectCount,this.retryConfig);S.debug("[".concat(this.name,"] wait ").concat(t,"ms to reconnect websocket, mode: ").concat(e)),await Promise.race([N(t),this.onlineReconnectListener||new Promise((()=>{}))])}if("closed"===this._state||!n)return!1;this.reconnectCount+=1;const E=async(e,t)=>{this.emit(y.RECONNECT_CREATE_CONNECTION,t),await this.createWebSocketConnection(e)};try{if("retry"===e)this.emit(y.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);S.debug("[".concat(this.name,"] websocket url length: ").concat(this.urls.length," current index: ").concat(this.currentURLIndex)),this.emit(y.RECONNECT_WAITTING_FINISH,e),await E(this.urls[this.currentURLIndex],e)}else"recover"===e&&(S.debug("[".concat(this.name,"] request new urls")),this.resetReconnectCount("recover mode"),this.emit(y.RECONNECT_WAITTING_FINISH,e),this.urls=await R(this,y.REQUEST_NEW_URLS),this.currentURLIndex=0,await E(this.urls[this.currentURLIndex],e))}catch(n){var s;S.error("[".concat(this.name,"] reconnect failed ").concat(n&&n.toString()));const E=null==n||null===(s=n.data)||void 0===s?void 0:s.desc;return Array.isArray(E)&&E.includes("dynamic key expired")?(this.emit(y.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):this.reconnectWithAction(e,t)}return!0}}class G extends K{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,t){return new Promise(((n,E)=>{let o=!1;const s=[];this.closeEstablishingWs=()=>{S.debug("[choose-best-ws] close establishing websockets"),s.forEach((e=>{e.onclose=null,e.onopen=null,e.onmessage=null,e.close()})),E(new _(c.WS_ABORT,"choose best websocket aborted"))};const i=r("GATEWAY_DOMAINS");let a;const R=e.indexOf("?h="),I=i.find((t=>-1!==R?e.includes(t,R):e.includes(t)));S.debug("[choose-best-ws] currentDomain: ",I,", domains: ",i);let A=!this.tryDoubleDomain||!I;if(!A&&I){var C;const r=Date.now();try{i.forEach((t=>{const n=-1===R?e.replace(I,t):e.substr(0,R)+e.substr(R).replace(I,t),E=new WebSocket(n);E.binaryType="arraybuffer",s.push(E),S.debug("[choose-best-ws] ws is connecting:",E.url)}))}catch(e){for(S.debug("[choose-best-ws] ws create failed, fallback to single url"),s.forEach((e=>e.close()));s.length;)s.pop();A=!0}null===(C=this.store)||void 0===C||C.recordJoinChannelService({urls:s.map((e=>e.url)),service:"gateway"},t),s.forEach((e=>{e.onopen=()=>{if(o)return;const t=Date.now()-r;S.debug("[choose-best-ws] ws open cost ".concat(t,"ms")),s.filter((t=>t!==e)).forEach((e=>{S.debug("[choose-best-ws]close backup websocket: ".concat(e.url)),e.close()})),o=!0,n(e)},e.onclose=e=>{if(a=e,o)return;s.find((e=>!(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING)))||(S.debug("[choose-best-ws] all websocket is closed"),o=!0,E(a))},e.onmessage=t=>{S.debug("[choose-best-ws]".concat(e.url," onmessage: ").concat(t.data))}})),N(this.forceCloseTimeout).then((()=>{s.forEach((e=>{e.readyState!==WebSocket.OPEN&&e.close()}))}))}if(A){var T;let o;S.debug("[choose-best-ws] use single url: ",e),null===(T=this.store)||void 0===T||T.recordJoinChannelService({urls:[e],service:"gateway"},t);try{o=new WebSocket(e),s.push(o),o.binaryType="arraybuffer"}catch(e){const t=new _(c.WS_ERR,"init websocket failed! Error: ".concat(e.toString()));return S.error("[".concat(this.name,"]").concat(t)),void E(t)}o.onopen=()=>{n(o)},o.onclose=e=>{E(e)},o.onmessage=e=>{S.debug("[choose-best-ws]".concat(o.url," onmessage: ").concat(e.data))},N(this.forceCloseTimeout).then((()=>{o&&o.readyState!==WebSocket.OPEN&&o.close()}))}})).then((e=>(this.closeEstablishingWs=void 0,e))).catch((e=>{throw this.closeEstablishingWs=void 0,e}))}}function H(e){let t=$();return function(e,t){let n=e.appId;void 0!==n&&(Ie(t,10),ie(t,n));let E=e.cid;void 0!==E&&(Ie(t,16),Ie(t,E));let o=e.cname;void 0!==o&&(Ie(t,26),ie(t,o));let s=e.deviceId;void 0!==s&&(Ie(t,34),ie(t,s));let i=e.elapse;void 0!==i&&(Ie(t,40),Ae(t,i));let r=e.fileSize;void 0!==r&&(Ie(t,48),Ae(t,Z(r)));let _=e.height;void 0!==_&&(Ie(t,56),Ae(t,Z(_)));let c=e.jpg;void 0!==c&&(Ie(t,66),Ie(t,c.length),function(e,t){let n=Ee(e,t.length);e.bytes.set(t,n)}(t,c));let a=e.networkType;void 0!==a&&(Ie(t,72),Ae(t,Z(a)));let N=e.osType;void 0!==N&&(Ie(t,80),Ae(t,Z(N)));let R=e.requestId;void 0!==R&&(Ie(t,90),ie(t,R));let I=e.sdkVersion;void 0!==I&&(Ie(t,98),ie(t,I));let A=e.sequence;void 0!==A&&(Ie(t,104),Ae(t,Z(A)));let C=e.sid;void 0!==C&&(Ie(t,114),ie(t,C));let T=e.timestamp;void 0!==T&&(Ie(t,120),Ae(t,T));let O=e.uid;void 0!==O&&(Ie(t,128),Ie(t,O));let h=e.vid;void 0!==h&&(Ie(t,136),Ie(t,h));let S=e.width;void 0!==S&&(Ie(t,144),Ae(t,Z(S)));let L=e.service;void 0!==L&&(Ie(t,152),Ie(t,L));let l=e.callbackData;void 0!==l&&(Ie(t,162),ie(t,l));let d=e.jpgEncryption;void 0!==d&&(Ie(t,168),Ie(t,d));let u=e.requestType;void 0!==u&&(Ie(t,176),Ie(t,u));let D=e.scorePorn;void 0!==D&&(Ie(t,185),Ne(t,D));let w=e.scoreSexy;void 0!==w&&(Ie(t,193),Ne(t,w));let f=e.scoreNeutral;void 0!==f&&(Ie(t,201),Ne(t,f));let p=e.scene;void 0!==p&&(Ie(t,208),Ie(t,p));let g=e.ossFilePrefix;void 0!==g&&(Ie(t,218),ie(t,g));let m=e.serviceVendor;if(void 0!==m)for(let e of m){Ie(t,226);let n=$();x(e,n),Ie(t,n.limit),re(t,n),ee(n)}}(e,t),function(e){let t=e.bytes,n=e.limit;return t.length===n?t:t.subarray(0,n)}(t)}function Y(e){return function(e){let t={};e:for(;!ne(e);){let n=Re(e);switch(n>>>3){case 0:break e;case 1:t.code=Re(e);break;case 2:t.msg=se(e,Re(e));break;case 3:{let n=q(e);t.data=F(e),e.limit=n;break}default:J(e,7&n)}}return t}({bytes:t=e,offset:0,limit:t.length});var t}function F(e){let t={};e:for(;!ne(e);){let n=Re(e);switch(n>>>3){case 0:break e;case 1:t.requestId=se(e,Re(e));break;case 2:t.requestType=Re(e)>>>0;break;case 3:t.scorePorn=ae(e);break;case 4:t.scoreSexy=ae(e);break;case 5:t.scoreNeutral=ae(e);break;case 6:t.requestScene=Re(e)>>>0;break;case 7:t.scene=Re(e)>>>0;break;default:J(e,7&n)}}return t}function x(e,t){let n=e.service;void 0!==n&&(Ie(t,8),Ie(t,n));let E=e.vendor;void 0!==E&&(Ie(t,16),Ie(t,E));let o=e.token;void 0!==o&&(Ie(t,26),ie(t,o));let s=e.callbackUrl;void 0!==s&&(Ie(t,34),ie(t,s))}function q(e){let t=Re(e),n=e.limit;return e.limit=e.offset+t,n}function J(e,t){switch(t){case 0:for(;128&_e(e););break;case 2:te(e,Re(e));break;case 5:te(e,4);break;case 1:te(e,8);break;default:throw new Error("Unimplemented type: "+t)}}let j=new Float32Array(1);new Uint8Array(j.buffer);let X=new Float64Array(1),Q=new Uint8Array(X.buffer);function Z(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}let z=[];function $(){const e=z.pop();return e?(e.offset=e.limit=0,e):{bytes:new Uint8Array(64),offset:0,limit:0}}function ee(e){z.push(e)}function te(e,t){if(e.offset+t>e.limit)throw new Error("Skip past limit");e.offset+=t}function ne(e){return e.offset>=e.limit}function Ee(e,t){let n=e.bytes,E=e.offset,o=e.limit,s=E+t;if(s>n.length){let t=new Uint8Array(2*s);t.set(n),e.bytes=t}return e.offset=s,s>o&&(e.limit=s),E}function oe(e,t){let n=e.offset;if(n+t>e.limit)throw new Error("Read past limit");return e.offset+=t,n}function se(e,t){let n=oe(e,t),E=String.fromCharCode,o=e.bytes,s="�",i="";for(let e=0;e<t;e++){let r,_,c,a,N=o[e+n];0==(128&N)?i+=E(N):192==(224&N)?e+1>=t?i+=s:(r=o[e+n+1],128!=(192&r)?i+=s:(a=(31&N)<<6|63&r,a<128?i+=s:(i+=E(a),e++))):224==(240&N)?e+2>=t?i+=s:(r=o[e+n+1],_=o[e+n+2],32896!=(49344&(r|_<<8))?i+=s:(a=(15&N)<<12|(63&r)<<6|63&_,a<2048||a>=55296&&a<=57343?i+=s:(i+=E(a),e+=2))):240==(248&N)?e+3>=t?i+=s:(r=o[e+n+1],_=o[e+n+2],c=o[e+n+3],8421504!=(12632256&(r|_<<8|c<<16))?i+=s:(a=(7&N)<<18|(63&r)<<12|(63&_)<<6|63&c,a<65536||a>1114111?i+=s:(a-=65536,i+=E(55296+(a>>10),56320+(1023&a)),e+=3))):i+=s}return i}function ie(e,t){let n=t.length,E=0;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),E+=o<128?1:o<2048?2:o<65536?3:4}Ie(e,E);let o=Ee(e,E),s=e.bytes;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),E<128?s[o++]=E:(E<2048?s[o++]=E>>6&31|192:(E<65536?s[o++]=E>>12&15|224:(s[o++]=E>>18&7|240,s[o++]=E>>12&63|128),s[o++]=E>>6&63|128),s[o++]=63&E|128)}}function re(e,t){let n=Ee(e,t.limit),E=e.bytes,o=t.bytes;for(let e=0,s=t.limit;e<s;e++)E[e+n]=o[e]}function _e(e){return e.bytes[oe(e,1)]}function ce(e,t){let n=Ee(e,1);e.bytes[n]=t}function ae(e){let t=oe(e,8),n=e.bytes;return Q[0]=n[t++],Q[1]=n[t++],Q[2]=n[t++],Q[3]=n[t++],Q[4]=n[t++],Q[5]=n[t++],Q[6]=n[t++],Q[7]=n[t++],X[0]}function Ne(e,t){let n=Ee(e,8),E=e.bytes;X[0]=t,E[n++]=Q[0],E[n++]=Q[1],E[n++]=Q[2],E[n++]=Q[3],E[n++]=Q[4],E[n++]=Q[5],E[n++]=Q[6],E[n++]=Q[7]}function Re(e){let t,n=0,E=0;do{t=_e(e),n<32&&(E|=(127&t)<<n),n+=7}while(128&t);return E}function Ie(e,t){for(t>>>=0;t>=128;)ce(e,127&t|128),t>>>=7;ce(e,t)}function Ae(e,t){let n=t.low>>>0,E=(t.low>>>28|t.high<<4)>>>0,o=t.high>>>24,s=0===o?0===E?n<16384?n<128?1:2:n<1<<21?3:4:E<16384?E<128?5:6:E<1<<21?7:8:o<128?9:10,i=Ee(e,s),r=e.bytes;switch(s){case 10:r[i+9]=o>>>7&1;case 9:r[i+8]=9!==s?128|o:127&o;case 8:r[i+7]=8!==s?E>>>21|128:E>>>21&127;case 7:r[i+6]=7!==s?E>>>14|128:E>>>14&127;case 6:r[i+5]=6!==s?E>>>7|128:E>>>7&127;case 5:r[i+4]=5!==s?128|E:127&E;case 4:r[i+3]=4!==s?n>>>21|128:n>>>21&127;case 3:r[i+2]=3!==s?n>>>14|128:n>>>14&127;case 2:r[i+1]=2!==s?n>>>7|128:n>>>7&127;case 1:r[i]=1!==s?128|n:127&n}}let Ce=0,Te=0;g.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,g.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,g.STRING_UID_ALLOCATOR,m.IIIEGAL_APPID,m.IIIEGAL_UID,m.INTERNAL_ERROR,U.K_TIMESTAMP_EXPIRED,U.K_CHANNEL_PERMISSION_INVALID,U.K_CERTIFICATE_INVALID,U.K_CHANNEL_NAME_EMPTY,U.K_CHANNEL_NOT_FOUND,U.K_TICKET_INVALID,U.K_CHANNEL_CONFLICTED,U.K_SERVICE_NOT_READY,U.K_SERVICE_TOO_HEAVY,U.K_UID_BANNED,U.K_IP_BANNED,U.K_AUTO_REBALANCE,U.ERR_INVALID_VENDOR_KEY,U.ERR_INVALID_CHANNEL_NAME,U.WARN_NO_AVAILABLE_CHANNEL,U.WARN_LOOKUP_CHANNEL_TIMEOUT,U.WARN_LOOKUP_CHANNEL_REJECTED,U.WARN_OPEN_CHANNEL_TIMEOUT,U.WARN_OPEN_CHANNEL_REJECTED,U.WARN_REQUEST_DEFERRED,U.ERR_DYNAMIC_KEY_TIMEOUT,U.ERR_NO_AUTHORIZED,U.ERR_VOM_SERVICE_UNAVAILABLE,U.ERR_NO_CHANNEL_AVAILABLE_CODE,U.ERR_MASTER_VOCS_UNAVAILABLE,U.ERR_INTERNAL_ERROR,U.ERR_NO_ACTIVE_STATUS,U.ERR_INVALID_UID,U.ERR_DYNAMIC_KEY_EXPIRED,U.ERR_STATIC_USE_DYANMIC_KE,U.ERR_DYNAMIC_USE_STATIC_KE,U.ERR_NO_VOCS_AVAILABLE,U.ERR_NO_VOS_AVAILABLE,U.ERR_JOIN_CHANNEL_TIMEOUT,U.ERR_JOIN_BY_MULTI_IP,U.ERR_NOT_JOINED,U.ERR_REPEAT_JOIN_REQUEST,U.ERR_REPEAT_JOIN_CHANNEL,U.ERR_INVALID_STRINGUID,U.ERR_TOO_MANY_USERS,U.ERR_SET_CLIENT_ROLE_TIMEOUT,U.ERR_SET_CLIENT_ROLE_NO_PERMISSION,U.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE,U.ERR_PUBLISH_REQUEST_INVALID,U.ERR_SUBSCRIBE_REQUEST_INVALID,U.ERR_NOT_SUPPORTED_MESSAGE,U.ERR_ILLEAGAL_PLUGIN,U.ILLEGAL_CLIENT_ROLE_LEVEL,U.ERR_REJOIN_TOKEN_INVALID,U.ERR_REJOIN_USER_NOT_JOINED,U.ERR_INVALID_OPTIONAL_INFO,U.ERR_TEST_RECOVER,U.ERR_TEST_TRYNEXT,U.ERR_TEST_RETRY,U.ILLEGAL_AES_PASSWORD,U.ERR_TOO_MANY_BROADCASTERS,U.ERR_TOO_MANY_SUBSCRIBERS,U.ERR_LICENSE_ILLEGAL,U.ERR_LICENSE_MISSING,U.ERR_LICENSE_EXPIRED,U.ERR_LICENSE_MINUTES_EXCEEDED,U.ERR_LICENSE_PERIOD_INVALID,U.ERR_LICENSE_MULTIPLE_SDK_SERVICE;const Oe={GLOBAL:{ASIA:[M.CHINA,M.JAPAN,M.INDIA,M.KOREA,M.HKMC],EUROPE:[],NORTH_AMERICA:[M.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}};Object.keys(Oe[M.GLOBAL]),M.CHINA,M.NORTH_AMERICA,M.EUROPE,M.ASIA,M.JAPAN,M.INDIA,M.OCEANIA,M.SOUTH_AMERICA,M.AFRICA,M.KOREA,M.HKMC,M.US;let he=0;function Se(e,t,n,E){let{appId:o,areaCode:s,cname:i,sid:_,token:a,uid:N}=t;he++;const R="image_moderation_api",I={service_name:R,json_body:JSON.stringify({appId:o,areaCode:s,cname:i,command:"allocateEdge",requestId:he,seq:he,sid:_,token:a,ts:Date.now(),uid:N+""})};let O,h,u=e[0];return T((async()=>{O=Date.now();const e=await function(e,t,n,E){return new Promise(((o,s)=>{t.timeout=t.timeout||r("HTTP_CONNECT_TIMEOUT"),t.responseType=t.responseType||"json",t.data&&!n?(t.data=JSON.stringify(t.data),Ce+=A(t.data)):n&&(t.data.size?Ce+=t.data.size:t.data instanceof FormData?Ce+=C(t.data):Ce+=A(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,D.request(t).then((e=>{"string"==typeof e.data?Te+=A(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?Te+=e.data.byteLength:Te+=A(JSON.stringify(e.data)),E&&o({data:e.data,headers:e.headers}),o(e.data)})).catch((e=>{D.isCancel(e)?s(new L(c.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?s(new L(c.NETWORK_TIMEOUT,e.message)):e.response?s(new L(c.NETWORK_RESPONSE_ERROR,e.response.status)):s(new L(c.NETWORK_ERROR,e.message))}))}))}(u,{data:I,cancelToken:n,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"},params:{action:"wrtc_gateway"}});if(h=Date.now()-O,0!==e.code){const t=new L(l.UNEXPECTED_RESPONSE,"image inspect ap error, code"+e.code,{retry:!0,responseTime:h});throw S.error(t.toString()),t}const t=JSON.parse(e.json_body);if(200!==t.code){const e=new L(l.UNEXPECTED_RESPONSE,"image inspect ap error, code: ".concat(t.code,", reason: ").concat(t.reason),{code:t.code,responseTime:h});throw S.error(e.toString()),e}if(!t.servers||!Array.isArray(t.servers)||0===t.servers.length){const e=new L(l.UNEXPECTED_RESPONSE,"image inspect ap empty server",{code:t.code,responseTime:h});throw S.error(e.toString()),e}const E=r("VIDEO_INSPECT_WORKER_MANAGER_HOST"),o=r("VIDEO_INSPECT_WORKER_MANAGER_PORT");return{addressList:t.servers.map((e=>{let{address:t,wss:n}=e;if(t&&n)return"wss://".concat(t.replace(/\./g,"-"),".").concat(E,":").concat(o||n)})).filter((e=>!!e)),workerToken:t.workerToken,vid:t.vid,responseTime:h}}),((t,n)=>(d.apworkerEvent(_,{success:!0,sc:200,serviceName:R,responseDetail:JSON.stringify(t.addressList),firstSuccess:0===n,responseTime:h,serverIp:e[n%e.length]}),!1)),((t,n)=>(d.apworkerEvent(_,{success:!1,sc:t.data&&t.data.code||200,serviceName:R,responseTime:h,serverIp:e[n%e.length]}),!!(t.code!==l.OPERATION_ABORTED&&t.code!==l.UNEXPECTED_RESPONSE||t.data&&t.data.retry)&&(u=e[(n+1)%e.length],!0))),E)}const Le=new Map([["moderation",1],["supervise",2]]);function le(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}class de extends t{get connectionState(){return this._connectionState}set connectionState(e){if(this._connectionState===e)return;const t=this._connectionState;this._connectionState=e,this.emit(W.CONNECTION_STATE_CHANGE,t,e)}get inspectType(){return this._inspectType}set inspectType(e){this._inspectMode=e.map((e=>Le.get(e)||0)).reduce(((e,t)=>e+t)),this._inspectType=e}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){super(),this.name="AgoraRTCVideoContentInspect",this._connectionState=k.CONNECTING,this._innerConnectionState=void 0,this.sequence=0,this.inspectStartTime=void 0,this.workerManagerConnection=void 0,this.workerConnection=void 0,this.workerMessageLengthLimit=void 0,this.inspectIntervalMinimum=void 0,this.qualityRatio=void 0,this._connectInfo=void 0,this._cancelTokenSource=D.CancelToken.source(),this._retryConfig=void 0,this.wmSequence=0,this.inspectInterval=void 0,this.inspectTimer=null,this.ossFilePrefix=void 0,this.extraInfo=void 0,this._inspectType=void 0,this._inspectMode=void 0,this._quality=1,this.qualityTimer=null,this._inspectId=void 0,this._needWorkUrlOnly=!1,this.inspectImage=()=>{if(this.connectionState!==k.CONNECTED)throw new L(l.OPERATION_ABORTED,"content inspect service connection status is ".concat(this.connectionState));this.inspectTimer&&(window.clearInterval(this.inspectTimer),this.inspectTimer=null),this.inspectTimer=window.setInterval((()=>{this.connectionState===k.CONNECTED?this.requestToInspectImage():S.debug("[".concat(this._inspectId,"] Inspect State is not connected , "),this.connectionState)}),this.inspectInterval<this.inspectIntervalMinimum?this.inspectIntervalMinimum:this.inspectInterval),this.requestToInspectImage()},this._inspectId=O(5,"inspect-"),this.workerMessageLengthLimit=r("VIDEO_INSPECT_WORKER_MESSAGE_LENGTH_LIMIT"),this.inspectIntervalMinimum=r("VIDEO_INSPECT_INTERVAL_MINIMUM"),this.qualityRatio=r("VIDEO_INSPECT_QUALITY_RATIO"),this.inspectInterval=e.interval,this.ossFilePrefix=e.ossFilePrefix,this.extraInfo=e.extraInfo,this.inspectType=e.inspectType,this.inspectStartTime=Number(Date.now()),this.workerManagerConnection=new G("worker-manager-"+this._inspectId,h),this.on(W.STATE_CHANGE,((e,t)=>{this._innerConnectionState=e,S.debug("[".concat(this._inspectId,"] Inspect operation :").concat(v[e]," ").concat(t||""))})),this.handleWorkerManagerEvents(),this.workerConnection=new G("worker-"+this._inspectId,h),this.handleWorkerEvents()}async init(e,t){this.emit(W.STATE_CHANGE,v.CONNECT_AP),this._connectInfo=e;const n=this._cancelTokenSource.token;return this._retryConfig=t,new Promise(((E,o)=>{this.on(W.CONNECTION_STATE_CHANGE,((e,t)=>{t===k.CONNECTED&&E()})),this.requestAP(e,n,t).then((e=>{this.connectWorkerManager(e)})).catch((e=>{o(e)}))}))}async requestAP(e,t,n){const E=r("WEBCS_DOMAIN").map((e=>"https://".concat(e,"/api/v1"))),o=await Se(E,e,t,n);this.emit(W.STATE_CHANGE,v.AP_CONNECTED);const{addressList:s}=o;return this.wmSequence++,s}async connectWorkerManager(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._needWorkUrlOnly=t,this.emit(W.STATE_CHANGE,v.CONNECT_WORKER_MANAGER),await this.workerManagerConnection.init(e,1e4)}async connectWorker(e){await this.workerConnection.init([e])}handleWorkerManagerEvents(){this.workerManagerConnection.on(y.CONNECTED,(async()=>{this.emit(W.STATE_CHANGE,v.WORKER_MANAGER_CONNECTED,this.workerManagerConnection.url),this.workerManagerConnection.sendMessage({appId:this._connectInfo.appId,cname:this._connectInfo.cname,uid:this._connectInfo.uid+"",sdkVersion:"4.22.1",sid:this._connectInfo.sid,seq:this.wmSequence,ts:Number(Date.now()),requestId:Math.floor(1e12*Math.random()),allocate:!0,clientRequest:{command:"join"}},!0)})),this.workerManagerConnection.on(y.CLOSED,(()=>{this._innerConnectionState<v.GET_WORKER_MANAGER_RESPONSE&&S.debug("[".concat(this._inspectId,"] Inspect worker manager is closed before connecting worker"))})),this.workerManagerConnection.on(y.FAILED,(()=>{this._innerConnectionState<v.GET_WORKER_MANAGER_RESPONSE&&S.debug("[".concat(this._inspectId,"] Connecting inspect worker manager is failed before connecting worker"))})),this.workerManagerConnection.on(y.RECONNECTING,(()=>{this._innerConnectionState<v.GET_WORKER_MANAGER_RESPONSE&&S.debug("[".concat(this._inspectId,"] Inspect worker manager is reconnecting before connecting worker"))})),this.workerManagerConnection.on(y.ON_MESSAGE,(async e=>{this.emit(W.STATE_CHANGE,v.GET_WORKER_MANAGER_RESPONSE);const t=this.workerManagerConnection.url;this.workerManagerConnection.close();const n=JSON.parse(e.data);if(200!==n.code)throw S.error("[".concat(this._inspectId,"] Unexpected code ").concat(n.code," from worker manager")),new L(l.UNEXPECTED_RESPONSE,"response code of worker is unexpected",n);if(!(n.serverResponse&&n.serverResponse.portWss&&t))throw S.error("[".concat(this._inspectId,"] Unexpected content from worker manager : ").concat(JSON.stringify(n))),new L(l.UNEXPECTED_RESPONSE,"response content of worker is unexpected",n);{const e=r("VIDEO_INSPECT_WORKER_PORT")||n.serverResponse.portWss,E=t.replace(/:\d+\/?$/,":".concat(e));this.emit(W.STATE_CHANGE,v.CONNECT_WORKER,E),this._needWorkUrlOnly?this.emit(W.REQUEST_NEW_WORKER_URL,E):await this.connectWorker(E)}})),this.workerManagerConnection.on(y.WILL_RECONNECT,((e,t,n)=>{n(e)})),this.workerManagerConnection.on(y.REQUEST_NEW_URLS,((e,t)=>{this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(e).catch(t)}))}handleWorkerEvents(){this.workerConnection.on(y.CONNECTED,(async()=>{this.emit(W.STATE_CHANGE,v.WORKER_CONNECTED,this.workerConnection.url),this.connectionState=k.CONNECTED})),this.workerConnection.on(y.ON_MESSAGE,(async e=>{if(e.data instanceof ArrayBuffer){const t=Y(new Uint8Array(e.data));if(r("SHOW_VIDEO_INSPECT_WORKER_MESSAGE")&&S.debug("[".concat(this._inspectId,"] Response message for worker of inspect content "),JSON.stringify(t)),200===t.code){if(Array.isArray(this.inspectType)&&1===this.inspectType.length&&"supervise"===this.inspectType[0])return void this.emit(W.INSPECT_RESULT,void 0,void 0);if(t.data&&t.data.scorePorn&&t.data.scoreSexy&&t.data.scoreNeutral){const e={porn:t.data.scorePorn,sexy:t.data.scoreSexy,neutral:t.data.scoreNeutral},n=Object.keys(e).reduce(((t,n)=>e[t]>e[n]?t:n),"porn"),E=Object.keys(e).find((e=>e===n));this.emit(W.INSPECT_RESULT,E)}else this.emit(W.INSPECT_RESULT,void 0,new L(l.UNEXPECTED_RESPONSE,t.code+"","There is an unexpected data on message"))}else this.emit(W.INSPECT_RESULT,void 0,new L(l.UNEXPECTED_RESPONSE,t.code+"",t.msg))}else S.error("[".concat(this._inspectId,"] Unexpected message type from worker")),this.emit(W.INSPECT_RESULT,void 0,new L(l.UNEXPECTED_RESPONSE,"invalid worker message type"))})),this.workerConnection.on(y.CLOSED,(()=>{this.connectionState=k.CLOSED})),this.workerConnection.on(y.FAILED,(()=>{this.connectionState=k.CLOSED})),this.workerConnection.on(y.RECONNECTING,(()=>{this.connectionState=this.connectionState===k.CONNECTED?k.RECONNECTING:k.CONNECTING})),this.workerConnection.on(y.WILL_RECONNECT,((e,t,n)=>{"recover"===e&&n(e),n("tryNext")})),this.workerConnection.on(y.REQUEST_NEW_URLS,((e,t)=>{this.workerManagerConnection.close(),this.once(W.REQUEST_NEW_WORKER_URL,(t=>{e([t])})),this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then((e=>{this.connectWorkerManager(e,!0)})).catch((e=>{t(e)}))}))}async requestToInspectImage(){this.sequence++;const e=I(this,W.CLIENT_LOCAL_VIDEO_TRACK),t={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 this.emit(W.INSPECT_RESULT,void 0,new L(l.INVALID_OPERATION,"Only the track being played can be inspected"));const n=await this.generateRequestData(e,t);this.workerConnection.sendMessage(n,!0,!0)}else this.emit(W.INSPECT_RESULT,void 0,new L(l.INVALID_OPERATION,"Only the track being published can be inspected"))}async generateRequestData(e,t){let{appId:n,cname:E,cid:o,vid:s,sid:i,uid:_}=t;const c=Date.now(),a=await e.getCurrentFrameImage("image/jpeg",this.quality),N=await u(a,n,E),R=this.sequence+"-"+o+"-"+_+"-"+c+"-"+O(12,""),I={appId:n,cid:o,cname:E,deviceId:"",elapse:le(Number(c-this.inspectStartTime)),fileSize:N.byteLength,jpgEncryption:2,height:a.height,width:a.width,jpg:N,networkType:6,osType:7,requestId:R,sdkVersion:"4.22.1",sequence:this.sequence,sid:i,timestamp:le(c),uid:_,vid:s,service:this._inspectMode,callbackData:this.extraInfo,ossFilePrefix:this.ossFilePrefix};void 0===this.extraInfo&&delete I.callbackData,void 0===this.ossFilePrefix&&delete I.ossFilePrefix;const A=H(I);if(A.byteLength<this.workerMessageLengthLimit){if(r("SHOW_VIDEO_INSPECT_WORKER_MESSAGE")){const e=p({},I);delete e.jpg,S.debug("[".concat(this._inspectId,"] Request message for worker of inspect content "),JSON.stringify(e))}return A}{const t=this.quality*this.qualityRatio;return this.quality=t,await this.generateRequestData(e,{appId:n,cname:E,cid:o,vid:s,sid:i,uid:_})}}close(){this._cancelTokenSource.cancel(),this._cancelTokenSource=D.CancelToken.source(),this.workerManagerConnection&&this.workerManagerConnection.close(),this.workerConnection&&this.workerConnection.close(),this.inspectTimer&&window.clearInterval(this.inspectTimer),this.inspectTimer=null,this.connectionState=k.CLOSED,this.emit(W.STATE_CHANGE,v.CLOSED)}}function ue(e){if(!e)throw new L(l.INVALID_PARAMS,"inspectConfig is necessary.");if(!e.inspectType||!Array.isArray(e.inspectType))throw new L(l.INVALID_PARAMS,"inspectConfig.inspectType is necessary and is an instance of Array.");{const t=[...new Set(e.inspectType)];t.forEach((e=>{if(!["supervise","moderation"].includes(e))throw new L(l.INVALID_PARAMS,"".concat(e," is not a valid inspect type."))})),e.inspectType=t}if(e&&e.extraInfo&&e.extraInfo.length>1024)throw new L(l.INVALID_PARAMS,"inspectConfig.extraInfo length cannot exceed 1024 bytes")}const De={name:"ContentInspect",create:function(e){let{config:t}=e;return ue(t),new de(t)}};export{De as ContentInspectService,ue as checkContentInspectConfig}; |
/** | ||
* AgoraWebSDK_N-v4.22.0-0-g8569241d-dirty Copyright AgoraInc. | ||
* AgoraWebSDK_N-v4.22.1-0-g1c8e27e9 Copyright AgoraInc. | ||
*/ | ||
import{RemoteDataChannel as e,LocalDataChannel as t}from"@agora-js/media";import{logger as n}from"@agora-js/report";import{getParameter as r}from"@agora-js/shared";import{inflate as a,deflate as s}from"pako";var i=function(e){return e[e.ONE_BYTE=0]="ONE_BYTE",e[e.TWO_BYTE=1]="TWO_BYTE",e}(i||{});class o{constructor(){this._sequence=0,this._startTime=Date.now(),this.isUseOneByte=!0}get startTime(){const e=Date.now()-this._startTime;return e<Math.pow(2,16)?e:(this._startTime+=Math.pow(2,16),this.startTime)}get sequence(){return this._sequence<Math.pow(2,32)?this._sequence++:(this._sequence-=Math.pow(2,32),this.sequence)}serialize(e){const t={commonPacketHeader:{length:0,reserved:0,extension:0,sequence:this.sequence},commonStreamHeader:this.startTime,extension:void 0,payload:e};if(e.byteLength>128){const n=new Uint8Array(4);n.set([1,0,0,0]);const r={id:0,length:4,data:n.buffer},a={profile:this.isUseOneByte?0:1,length:this.isUseOneByte?5:6,datas:[r]};t.commonPacketHeader.extension=1,t.extension=a,t.payload=this.compress(e),t.commonPacketHeader.length=8+(t.extension.length+2)+t.payload.byteLength}else t.commonPacketHeader.length=8+t.payload.byteLength;r("SHOW_DATASTREAM2_LOG")&&n.debug("send data header: ".concat(JSON.stringify(t.commonPacketHeader)));const a=new ArrayBuffer(t.commonPacketHeader.length),s=new Uint8Array(a),i=new DataView(a);let o=0;if(i.setUint16(o,t.commonPacketHeader.extension<<15|t.commonPacketHeader.reserved<<14|t.commonPacketHeader.length,!0),o+=2,i.setUint32(o,t.commonPacketHeader.sequence,!0),o+=4,i.setUint16(o,t.commonStreamHeader,!0),o+=2,t.extension){const e=this.serializeExtension(t.extension);s.set(new Uint8Array(e),o),o+=e.byteLength}if(s.set(new Uint8Array(t.payload),o),o+=t.payload.byteLength,o!==t.commonPacketHeader.length)throw Error("serialize error!");return a}deserialize(e){if(e.byteLength<4)return new ArrayBuffer(0);const t=new DataView(e);let a=0;const s=t.getUint16(a,!0);a+=2;const i={length:16383&s,reserved:(16384&s)>>14,extension:(32768&s)>>15,sequence:t.getUint16(a+2,!0)<<16|t.getUint16(a,!0)};let o,c;if(a+=4,r("SHOW_DATASTREAM2_LOG")&&n.debug("receive data header: ".concat(JSON.stringify(i))),t.getUint16(a,!0),a+=2,i.extension){c=this.deserializeExtension(e.slice(a)),a+=2+c.length,o=e.slice(a);let t=!1;if(c.datas.length>0){const e=c.datas.find((e=>0===e.id));if(e){t=1==(1&new DataView(e.data).getUint32(0,!0))}}o=t?this.decompress(o):o}else o=e.slice(8);return o}serializeExtension(e){const{profile:t,length:n,datas:r}=e,a=new ArrayBuffer(n+2),s=new Uint8Array(a),i=new DataView(a);let o=0;if(i.setUint8(o++,t),i.setUint8(o++,n),r.forEach((e=>{t?(i.setUint8(o++,e.id),i.setUint8(o++,e.length),s.set(new Uint8Array(e.data),o),o+=e.data.byteLength):(i.setUint8(o++,e.id|e.length<<4),s.set(new Uint8Array(e.data),o),o+=e.data.byteLength)})),o!==n+2)throw Error("serialize extension error, is ".concat(o,"!==").concat(n+2));return a}deserializeExtension(e){const t=new DataView(e);let n=0;const r=t.getUint8(n);n++;const a=t.getUint8(n);n++;const s=r===i.TWO_BYTE,o=[],c=new DataView(e,2);let h=0;for(;h<a;){let e=0,t=0,n=new ArrayBuffer(0);s?(e=c.getUint8(h),h++,t=c.getUint8(h),h++):(e=15&c.getUint8(h),t=c.getUint8(h)>>4,h++),t>0&&(n=c.buffer.slice(h+2,h+2+t),h+=n.byteLength),o.push({id:e,length:t,data:n})}if(h!==a)throw Error("parse error");return{profile:r,length:a,datas:o}}decompress(e){return a(new Uint8Array(e))}compress(e){return s(new Uint8Array(e))}}const c={name:"DataStream",create:(n,r)=>{const a=r?new e(n):new t(n);return a.useDataStream(new o),a}};export{c as DataStreamService}; |
/** | ||
* AgoraWebSDK_N-v4.22.0-0-g8569241d-dirty Copyright AgoraInc. | ||
* AgoraWebSDK_N-v4.22.1-0-g1c8e27e9 Copyright AgoraInc. | ||
*/ | ||
import{AgoraRTCError as e,IS_GLOBAL_VERSION as t,MUTABLE_PARAMS as n,EventEmitter as o,PromiseMutex as E,NETWORK_STATE as i,networkIndicator as _,NETWORK_INDICATOR_EVENTS as s,createDefer as r,getParameter as c,AgoraRTCErrorCode as a,getRetryWaitTime as R,wait as N,emitAsPromise as I,emitAsInvokerNoResponse as A,getUTF8StringByteLength as O,getMultiUnilbsFormDataByteLength as T,retryable as C,checkValidNumber as h,getRandomString as S,DEFAULT_RETRY_CONFIG as L,AgoraAPIName as d,AgoraAPITag as l}from"@agora-js/shared";import{logger as u,AgoraRTCEventReport as D,report as m}from"@agora-js/report";import{frameData2CryptoBuffer as w}from"@agora-js/media";import g from"axios";import"formdata-polyfill";function f(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 V(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 p(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?V(Object(n),!0).forEach((function(t){f(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):V(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}class b extends e{constructor(e){super(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",arguments.length>2?arguments[2]:void 0),this.name="AgoraRTCException"}print(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"error";return super.print(e,u)}throw(){super.throw(u)}}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}({}),M=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}({}),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.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}({}),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}({});const B=function(){const e="us".concat("erna","me"),t="pa".concat("sswo","rd"),n=["t","s","t"];n.splice(1,0,"e");const o=n.join(""),E=[];for(let e=0;e<6;e++)E.push("1");const i=E.join(""),_={};return _[e]=o,_[t]=i,Object.assign(_,{turnServerURL:"",tcpport:3433,udpport:3478,forceturn:!1})}();window.DEFAULT_TURN_CONFIG=B,t||(n.WEBCS_DOMAIN=["ap-web-1-oversea.agora.io","ap-web-1-north-america.agora.io"],n.WEBCS_DOMAIN_BACKUP_LIST=["ap-web-2-oversea.agora.io","ap-web-2-north-america.agora.io"],n.PROXY_CS=["proxy-ap-web-oversea.agora.io","proxy-ap-web-america.agora.io"],n.CDS_AP=["cds-ap-web-oversea.agora.io","cds-ap-web-america.agora.io","cds-ap-web-america2.agora.io"],n.ACCOUNT_REGISTER=["sua-ap-web-oversea.agora.io","sua-ap-web-america.agora.io","sua-ap-web-america2.agora.io"],n.UAP_AP=["uap-ap-web-oversea.agora.io","uap-ap-web-america.agora.io","uap-ap-web-america2.agora.io"],n.LOG_UPLOAD_SERVER="logservice-oversea.agora.io",n.EVENT_REPORT_DOMAIN="statscollector-1-oversea.agora.io",n.EVENT_REPORT_BACKUP_DOMAIN="statscollector-2-oversea.agora.io",n.PROXY_SERVER_TYPE3="webrtc-cloud-proxy.agora.io",n.AREAS=["NORTH_AMERICA","OVERSEA"]);D.__CLIENT_LIST__=[];let G=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}({});G.AFRICA,G.ASIA,G.CHINA,G.EUROPE,G.GLOBAL,G.INDIA,G.JAPAN,G.NORTH_AMERICA,G.OCEANIA,G.OVERSEA,G.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,t&&K.CHINA;let W=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}({}),H=function(e){return e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED",e}({}),Y=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}({}),F=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 x extends o{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){u.debug("websocket reset reconnect count, reason: "+e),this.reconnectCount=0}constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],o=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.connectionID=0,this.currentURLIndex=0,this.urls=[],this._reconnectMode="tryNext",this.reconnectReason=void 0,this._initMutex=new E("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=c,this.name=e,this.retryConfig=p({},t),this.useCompress=n,this.tryDoubleDomain=o,this.use443PortOnly=r;const{timeout:a,timeoutFactor:R}=t,N=Math.max(300,Math.floor(3*a/5)),I=Math.max(1.2,Math.floor(8*R)/10);i.ONLINE&&(this.retryConfig.timeout=N,this.retryConfig.timeoutFactor=I),_.on(s.NETWORK_STATE_CHANGE,((e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===i.ONLINE?(this.retryConfig.timeout=N,this.retryConfig.timeoutFactor=I):(this.retryConfig.timeout=a,this.retryConfig.timeoutFactor=R))}))}getConnection(){return this.websocket||void 0}async init(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const o=await this._initMutex.lock();this.forceCloseTimeout=n,this.urls=t,this.state="connecting";try{const t=r(),n=this.urls[this.currentURLIndex];c("ENABLE_PREALLOC_PC")&&this.emit(W.PRE_CONNECT_PC),this.createWebSocketConnection(n).then(t.resolve).catch(t.reject),this.once(k.CLOSED,(()=>{t.reject(new e(a.WS_DISCONNECT))})),this.once(k.CONNECTED,t.resolve),await t.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.state=e?"failed":"closed",this.closeEstablishingWs&&this.closeEstablishingWs()}reconnect(e,t){if(!this.websocket)return void u.warning("[".concat(this.name,"] can not reconnect, no websocket"));void 0!==e&&(this.reconnectMode=e),u.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(t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new e(a.WS_ABORT,"websocket is not ready");try{n||(t=JSON.stringify(t)),this.websocket.send(t)}catch(t){throw new e(a.WS_ERR,"send websocket message error"+t.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 o=r();this.connectionID+=1,this.joinGatewayRecordIndex=void 0;const E=e=>{var t;null===(t=this.store)||void 0===t||t.signalChannelOpen(),u.debug("[".concat(this.name,"] websocket opened:"),e),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),o.resolve()},i=async t=>{var n;if(u.debug("[".concat(this.name,"] websocket close ").concat(null===(n=this.websocket)||void 0===n?void 0:n.url,", code: ").concat(t.code,", reason: ").concat(t.reason,", current mode: ").concat(this.reconnectMode)),this.reconnectCount>=this.retryConfig.maxRetryCount)o.reject(new e(a.WS_DISCONNECT,"websocket close: ".concat(t.code))),this.close();else{"connected"===this.state&&(this.reconnectReason=t.reason,this.state="reconnecting");const n=A(this,k.WILL_RECONNECT,this.reconnectMode,t.reason)||this.reconnectMode,E=await this.reconnectWithAction(n);if("closed"===this.state)return void u.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!E)return o.reject(new e(a.WS_DISCONNECT,"websocket reconnect failed: ".concat(t.code))),this.close(!0);o.resolve()}},_=e=>{this.emit(k.ON_MESSAGE,e)},s=e=>{u.warn("[".concat(this.connectionID,"] ws open error ").concat(e))};this.websocket&&(this.websocket.onclose=null,this.websocket.close()),c("GATEWAY_WSS_ADDRESS")&&this.name.startsWith("gateway")&&(t=c("GATEWAY_WSS_ADDRESS")),u.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 N;const e=await this.chooseBestWebsocketConnection(t);this.websocket=e,E&&E(this.websocket.url),this.websocket.onclose=i,this.websocket.onmessage=_,this.websocket.onerror=s,null===(N=this.store)||void 0===N||N.recordJoinChannelService({endTs:Date.now(),status:"success"},R),this.joinGatewayRecordIndex=R}catch(t){const n="closed"===this.state,E=t instanceof e,_=E&&t.code===a.WS_ABORT,s=E&&t.code===a.WS_ERR,r=E?t.message:t&&(t.reason||t.toString());u.warning("[choose-best-ws] chooseBestWebsocket error: ".concat(r)),this.store&&this.store.recordJoinChannelService({endTs:Date.now(),status:_?"aborted":"error",errors:[t]},R),n||s?(o.reject(n?new e(a.WS_DISCONNECT,"websocket is closed: ".concat(r)):new e(a.WS_ERR,"init websocket failed: ".concat(r))),s&&u.error("[".concat(this.name,"] init websocket failed: ").concat(r))):i&&i(t)}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;u.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=R(this.reconnectCount,this.retryConfig);u.debug("[".concat(this.name,"] wait ").concat(t,"ms to reconnect websocket, mode: ").concat(e)),await Promise.race([N(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)this.emit(k.RECONNECT_WAITTING_FINISH,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);u.debug("[".concat(this.name,"] websocket url length: ").concat(this.urls.length," current index: ").concat(this.currentURLIndex)),this.emit(k.RECONNECT_WAITTING_FINISH,e),await o(this.urls[this.currentURLIndex],e)}else"recover"===e&&(u.debug("[".concat(this.name,"] request new urls")),this.resetReconnectCount("recover mode"),this.emit(k.RECONNECT_WAITTING_FINISH,e),this.urls=await I(this,k.REQUEST_NEW_URLS),this.currentURLIndex=0,await o(this.urls[this.currentURLIndex],e))}catch(n){var E;u.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;return Array.isArray(o)&&o.includes("dynamic key expired")?(this.emit(k.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):this.reconnectWithAction(e,t)}return!0}}class J extends x{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(((o,E)=>{let i=!1;const _=[];this.closeEstablishingWs=()=>{u.debug("[choose-best-ws] close establishing websockets"),_.forEach((e=>{e.onclose=null,e.onopen=null,e.onmessage=null,e.close()})),E(new e(a.WS_ABORT,"choose best websocket aborted"))};const s=c("GATEWAY_DOMAINS");let r;const R=t.indexOf("?h="),I=s.find((e=>-1!==R?t.includes(e,R):t.includes(e)));u.debug("[choose-best-ws] currentDomain: ",I,", domains: ",s);let A=!this.tryDoubleDomain||!I;if(!A&&I){var O;const e=Date.now();try{s.forEach((e=>{const n=-1===R?t.replace(I,e):t.substr(0,R)+t.substr(R).replace(I,e),o=new WebSocket(n);o.binaryType="arraybuffer",_.push(o),u.debug("[choose-best-ws] ws is connecting:",o.url)}))}catch(e){for(u.debug("[choose-best-ws] ws create failed, fallback to single url"),_.forEach((e=>e.close()));_.length;)_.pop();A=!0}null===(O=this.store)||void 0===O||O.recordJoinChannelService({urls:_.map((e=>e.url)),service:"gateway"},n),_.forEach((t=>{t.onopen=()=>{if(i)return;const n=Date.now()-e;u.debug("[choose-best-ws] ws open cost ".concat(n,"ms")),_.filter((e=>e!==t)).forEach((e=>{u.debug("[choose-best-ws]close backup websocket: ".concat(e.url)),e.close()})),i=!0,o(t)},t.onclose=e=>{if(r=e,i)return;_.find((e=>!(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING)))||(u.debug("[choose-best-ws] all websocket is closed"),i=!0,E(r))},t.onmessage=e=>{u.debug("[choose-best-ws]".concat(t.url," onmessage: ").concat(e.data))}})),N(this.forceCloseTimeout).then((()=>{_.forEach((e=>{e.readyState!==WebSocket.OPEN&&e.close()}))}))}if(A){var T;let i;u.debug("[choose-best-ws] use single url: ",t),null===(T=this.store)||void 0===T||T.recordJoinChannelService({urls:[t],service:"gateway"},n);try{i=new WebSocket(t),_.push(i),i.binaryType="arraybuffer"}catch(t){const n=new e(a.WS_ERR,"init websocket failed! Error: ".concat(t.toString()));return u.error("[".concat(this.name,"]").concat(n)),void E(n)}i.onopen=()=>{o(i)},i.onclose=e=>{E(e)},i.onmessage=e=>{u.debug("[choose-best-ws]".concat(i.url," onmessage: ").concat(e.data))},N(this.forceCloseTimeout).then((()=>{i&&i.readyState!==WebSocket.OPEN&&i.close()}))}})).then((e=>(this.closeEstablishingWs=void 0,e))).catch((e=>{throw this.closeEstablishingWs=void 0,e}))}}function q(e){let t=function(){const e=Z.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&&(re(t,10),Ee(t,n));let o=e.cid;void 0!==o&&(re(t,16),re(t,o));let E=e.cname;void 0!==E&&(re(t,26),Ee(t,E));let i=e.deviceId;void 0!==i&&(re(t,34),Ee(t,i));let _=e.elapse;void 0!==_&&(re(t,40),ae(t,_));let s=e.fileSize;void 0!==s&&(re(t,48),ae(t,Q(s)));let r=e.height;void 0!==r&&(re(t,56),ae(t,Q(r)));let c=e.jpg;void 0!==c&&(re(t,66),re(t,c.length),ne(t,c));let a=e.networkType;void 0!==a&&(re(t,72),ae(t,Q(a)));let R=e.osType;void 0!==R&&(re(t,80),ae(t,Q(R)));let N=e.requestId;void 0!==N&&(re(t,90),Ee(t,N));let I=e.sdkVersion;void 0!==I&&(re(t,98),Ee(t,I));let A=e.sequence;void 0!==A&&(re(t,104),ae(t,Q(A)));let O=e.sid;void 0!==O&&(re(t,114),Ee(t,O));let T=e.timestamp;void 0!==T&&(re(t,120),ae(t,T));let C=e.uid;void 0!==C&&(re(t,128),re(t,C));let h=e.vid;void 0!==h&&(re(t,136),re(t,h));let S=e.width;void 0!==S&&(re(t,144),ae(t,Q(S)));let L=e.service;void 0!==L&&(re(t,152),re(t,L));let d=e.callbackData;void 0!==d&&(re(t,162),re(t,d.length),ne(t,d));let l=e.ticket;void 0!==l&&(re(t,170),Ee(t,l));let u=e.vendorConfigs;void 0!==u&&(re(t,178),Ee(t,u))}(e,t),function(e){let t=e.bytes,n=e.limit;return t.length===n?t:t.subarray(0,n)}(t)}function j(e){return function(e){let t={};e:for(;!$(e);){let n=se(e);switch(n>>>3){case 0:break e;case 1:t.code=se(e);break;case 2:t.msg=oe(e,se(e));break;case 3:t.requestId=oe(e,se(e));break;case 4:t.timestamp=ce(e,!1);break;default:X(e,7&n)}}return t}({bytes:t=e,offset:0,limit:t.length});var t}function X(e,t){switch(t){case 0:for(;128&ie(e););break;case 2:z(e,se(e));break;case 5:z(e,4);break;case 1:z(e,8);break;default:throw new Error("Unimplemented type: "+t)}}function Q(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}let Z=[];function z(e,t){if(e.offset+t>e.limit)throw new Error("Skip past limit");e.offset+=t}function $(e){return e.offset>=e.limit}function ee(e,t){let n=e.bytes,o=e.offset,E=e.limit,i=o+t;if(i>n.length){let t=new Uint8Array(2*i);t.set(n),e.bytes=t}return e.offset=i,i>E&&(e.limit=i),o}function te(e,t){let n=e.offset;if(n+t>e.limit)throw new Error("Read past limit");return e.offset+=t,n}function ne(e,t){let n=ee(e,t.length);e.bytes.set(t,n)}function oe(e,t){let n=te(e,t),o=String.fromCharCode,E=e.bytes,i="�",_="";for(let e=0;e<t;e++){let s,r,c,a,R=E[e+n];0==(128&R)?_+=o(R):192==(224&R)?e+1>=t?_+=i:(s=E[e+n+1],128!=(192&s)?_+=i:(a=(31&R)<<6|63&s,a<128?_+=i:(_+=o(a),e++))):224==(240&R)?e+2>=t?_+=i:(s=E[e+n+1],r=E[e+n+2],32896!=(49344&(s|r<<8))?_+=i:(a=(15&R)<<12|(63&s)<<6|63&r,a<2048||a>=55296&&a<=57343?_+=i:(_+=o(a),e+=2))):240==(248&R)?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&R)<<18|(63&s)<<12|(63&r)<<6|63&c,a<65536||a>1114111?_+=i:(a-=65536,_+=o(55296+(a>>10),56320+(1023&a)),e+=3))):_+=i}return _}function Ee(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}re(e,o);let E=ee(e,o),i=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?i[E++]=o:(o<2048?i[E++]=o>>6&31|192:(o<65536?i[E++]=o>>12&15|224:(i[E++]=o>>18&7|240,i[E++]=o>>12&63|128),i[E++]=o>>6&63|128),i[E++]=63&o|128)}}function ie(e){return e.bytes[te(e,1)]}function _e(e,t){let n=ee(e,1);e.bytes[n]=t}function se(e){let t,n=0,o=0;do{t=ie(e),n<32&&(o|=(127&t)<<n),n+=7}while(128&t);return o}function re(e,t){for(t>>>=0;t>=128;)_e(e,127&t|128),t>>>=7;_e(e,t)}function ce(e,t){let n,o=0,E=0,i=0;return n=ie(e),o=127&n,128&n&&(n=ie(e),o|=(127&n)<<7,128&n&&(n=ie(e),o|=(127&n)<<14,128&n&&(n=ie(e),o|=(127&n)<<21,128&n&&(n=ie(e),E=127&n,128&n&&(n=ie(e),E|=(127&n)<<7,128&n&&(n=ie(e),E|=(127&n)<<14,128&n&&(n=ie(e),E|=(127&n)<<21,128&n&&(n=ie(e),i=127&n,128&n&&(n=ie(e),i|=(127&n)<<7))))))))),{low:o|E<<28,high:E>>>4|i<<24,unsigned:t}}function ae(e,t){let n=t.low>>>0,o=(t.low>>>28|t.high<<4)>>>0,E=t.high>>>24,i=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,_=ee(e,i),s=e.bytes;switch(i){case 10:s[_+9]=E>>>7&1;case 9:s[_+8]=9!==i?128|E:127&E;case 8:s[_+7]=8!==i?o>>>21|128:o>>>21&127;case 7:s[_+6]=7!==i?o>>>14|128:o>>>14&127;case 6:s[_+5]=6!==i?o>>>7|128:o>>>7&127;case 5:s[_+4]=5!==i?128|o:127&o;case 4:s[_+3]=4!==i?n>>>21|128:n>>>21&127;case 3:s[_+2]=3!==i?n>>>14|128:n>>>14&127;case 2:s[_+1]=2!==i?n>>>7|128:n>>>7&127;case 1:s[_]=1!==i?128|n:127&n}}const Re={},Ne={},Ie=4294967296,Ae=Ie*Ie,Oe=Ae/2,Te=de(0,!0),Ce=de(0),he=le(0,-2147483648,!1),Se=le(-1,2147483647,!1),Le=le(-1,-1,!0);function de(e,t){let n,o,E;return t?(E=0<=(e>>>=0)&&e<256)&&(o=Ne[e],o)?o:(n=le(e,0,!0),E&&(Ne[e]=n),n):(E=-128<=(e|=0)&&e<128)&&(o=Re[e],o)?o:(n=le(e,e<0?-1:0,!1),E&&(Re[e]=n),n)}function le(e,t,n){return{low:0|e,high:0|t,unsigned:!!n}}function ue(e,t){if(isNaN(e))return t?Te:Ce;if(t){if(e<0)return Te;if(e>=Ae)return Le}else{if(e<=-Oe)return he;if(e+1>=Oe)return Se}return e<0?t?Te:Ce:le(e%Ie|0,e/Ie|0,t)}let De=0,me=0;U.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,U.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,U.STRING_UID_ALLOCATOR,M.IIIEGAL_APPID,M.IIIEGAL_UID,M.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.K_AUTO_REBALANCE,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 we={GLOBAL:{ASIA:[G.CHINA,G.JAPAN,G.INDIA,G.KOREA,G.HKMC],EUROPE:[],NORTH_AMERICA:[G.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}};Object.keys(we[G.GLOBAL]),G.CHINA,G.NORTH_AMERICA,G.EUROPE,G.ASIA,G.JAPAN,G.INDIA,G.OCEANIA,G.SOUTH_AMERICA,G.AFRICA,G.KOREA,G.HKMC,G.US;let ge=0;function fe(e,t,n,o){let{appId:E,areaCode:i,cname:_,sid:s,token:r,uid:R}=t;ge++;const N="moderation_plugin",I={service_name:N,json_body:JSON.stringify({appId:E,areaCode:i,cname:_,command:"allocateEdge",requestId:ge,seq:ge,sid:s,appToken:r,ts:Date.now(),uid:R+""})};let A,h,S=e[0];return C((async()=>{A=Date.now();const e=await function(e,t,n,o){return new Promise(((E,i)=>{t.timeout=t.timeout||c("HTTP_CONNECT_TIMEOUT"),t.responseType=t.responseType||"json",t.data&&!n?(t.data=JSON.stringify(t.data),De+=O(t.data)):n&&(t.data.size?De+=t.data.size:t.data instanceof FormData?De+=T(t.data):De+=O(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,g.request(t).then((e=>{"string"==typeof e.data?me+=O(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?me+=e.data.byteLength:me+=O(JSON.stringify(e.data)),o&&E({data:e.data,headers:e.headers}),E(e.data)})).catch((e=>{g.isCancel(e)?i(new b(a.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?i(new b(a.NETWORK_TIMEOUT,e.message)):e.response?i(new b(a.NETWORK_RESPONSE_ERROR,e.response.status)):i(new b(a.NETWORK_ERROR,e.message))}))}))}(S,{data:I,cancelToken:n,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"},params:{action:"wrtc_gateway"}});if(h=Date.now()-A,0!==e.code){const t=new b(a.UNEXPECTED_RESPONSE,"moderation plugin ap error, code"+e.code,{retry:!0,responseTime:h});throw u.error(t.toString()),t}const t=JSON.parse(e.json_body);if(200!==t.code){const e=new b(a.UNEXPECTED_RESPONSE,"moderation plugin ap error, code: ".concat(t.code,", reason: ").concat(t.reason),{code:t.code,responseTime:h});throw u.error(e.toString()),e}if(!t.servers||!Array.isArray(t.servers)||0===t.servers.length){const e=new b(a.UNEXPECTED_RESPONSE,"moderation plugin ap empty server",{code:t.code,responseTime:h});throw u.error(e.toString()),e}if(!t.servers.some((e=>!!e.wss))){const e=new b(a.UNEXPECTED_RESPONSE,"moderation plugin ap empty port",{code:t.code,responseTime:h});throw u.error(e.toString()),e}const o=c("IMAGE_MODERATION_WORKER_HOST");return{addressList:t.servers.map((e=>{let{address:t,wss:n}=e;if(t&&n)return"wss://".concat(t.replace(/\./g,"-"),".").concat(o,":").concat(n,"/moderation")})).filter((e=>!!e)),workerToken:t.workerToken,vid:t.vid,ticket:t.appTicket,responseTime:h}}),((t,n)=>(m.apworkerEvent(s,{success:!0,sc:200,serviceName:N,responseDetail:JSON.stringify(t.addressList),firstSuccess:0===n,responseTime:h,serverIp:e[n%e.length]}),!1)),((t,n)=>(m.apworkerEvent(s,{success:!1,sc:t.data&&t.data.code||200,serviceName:N,responseTime:h,serverIp:e[n%e.length]}),!!(t.code!==a.OPERATION_ABORTED&&t.code!==a.UNEXPECTED_RESPONSE||t.data&&t.data.retry)&&(S=e[(n+1)%e.length],!0))),o)}class Ve extends o{get connectionState(){return this._connectionState}set connectionState(e){if(this._connectionState===e)return;const t=this._connectionState;this._connectionState=e,this.emit(Y.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 t;super(),this.name="AgoraRTCImageModeration",this._connectionState=H.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!==H.CONNECTED)throw new b(a.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===H.CONNECTED?this.requestToInspectImage():u.debug("[".concat(this._moderationId,"] Moderation State is not connected , "),this.connectionState)}),this._moderationInterval<this._moderationIntervalMinimum?this._moderationIntervalMinimum:this._moderationInterval),this.requestToInspectImage()},this._moderationId=S(5,"image-moderation-"),this._workerMessageLengthLimit=c("IMAGE_MODERATION_WORKER_MESSAGE_LENGTH_LIMIT"),this._moderationIntervalMinimum=c("IMAGE_MODERATION_INTERVAL_MINIMUM"),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),this._qualityRatio=c("IMAGE_MODERATION_QUALITY_RATIO"),this._moderationStartTime=Number(Date.now()),this._workerConnection=new J("worker-"+this._moderationId,L),this.on(Y.STATE_CHANGE,((e,t)=>{u.debug("[".concat(this._moderationId,"] Moderation operation :").concat(F[e]," ").concat(t||""))})),this.handleWorkerEvents()}async init(e,t){this.emit(Y.STATE_CHANGE,F.CONNECT_AP),this._connectInfo=e;const n=this._cancelTokenSource.token;return this._retryConfig=t,new Promise(((o,E)=>{this.on(Y.CONNECTION_STATE_CHANGE,((e,t)=>{e===H.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),u.debug("[".concat(this._moderationId,"] updateConfig: ").concat(JSON.stringify(e))),this.connectionState===H.CONNECTED&&this.inspectImage()}async requestAP(e,t,n){const o=c("WEBCS_DOMAIN").map((e=>"https://".concat(e,"/api/v1"))),E=await fe(o,e,t,n);this.emit(Y.STATE_CHANGE,F.AP_CONNECTED);const{addressList:i,ticket:_}=E;return this._ticket=_,i}async connectWorker(e){this.emit(Y.STATE_CHANGE,F.CONNECT_WORKER),await this._workerConnection.init(e,1e4)}handleWorkerEvents(){this._workerConnection.on(k.CONNECTED,(async()=>{this.emit(Y.STATE_CHANGE,F.WORKER_CONNECTED,this._workerConnection.url),this.connectionState=H.CONNECTED})),this._workerConnection.on(k.CLOSED,(()=>{this.connectionState=H.CLOSED})),this._workerConnection.on(k.FAILED,(()=>{this.connectionState=H.CLOSED})),this._workerConnection.on(k.RECONNECTING,(()=>{this.connectionState=this.connectionState===H.CONNECTED?H.RECONNECTING:H.CONNECTING})),this._workerConnection.on(k.ON_MESSAGE,(async e=>{if(e.data instanceof ArrayBuffer){const t=j(new Uint8Array(e.data));c("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&u.debug("[".concat(this._moderationId,"] Response message for worker of image moderation "),JSON.stringify(t)),this._uploadNum++,void 0===t.code||0===t.code||(this._uploadFailedNum++,u.error("[".concat(this._moderationId,"] Error response from worke, code is ").concat(t.code,", msg is ").concat(t.msg)),this._uploadTimer||(this._uploadTimer=window.setTimeout((()=>{m.reportApiInvoke(this._connectInfo.sid||null,{name:d.IMAGE_MODERATION_UPLOAD,options:[this._uploadFailedNum,this._uploadNum,t.code],tag:l.TRACER}).onError(new b(a.IMAGE_MODERATION_UPLOAD_FAILED,t.msg)),this._uploadTimer=null}),c("IMAGE_MODERATION_UPLOAD_REPORT_INTERVAL"))))}else u.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=A(this,Y.CLIENT_LOCAL_VIDEO_TRACK),t={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(c("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&u.debug("Only the track being played can be inspected"));this._sequence++;const n=await this.generateRequestData(e,t);this._workerConnection.sendMessage(n,!0,!0)}else c("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&u.debug("Only the track being published can be inspected")}async generateRequestData(e,t){let{appId:n,cname:o,cid:E,vid:i,sid:_,uid:s}=t;const r=Date.now(),a=await e.getCurrentFrameImage("image/jpeg",this.quality),R=await w(a,n,o),N=this._sequence+"-"+E+"-"+s+"-"+r+"-"+S(12,""),I={appId:n,cid:E,cname:o,deviceId:"",elapse:Ve.intToLong(Number(r-this._moderationStartTime)),fileSize:a.buffer.byteLength,height:a.height,width:a.width,jpg:R,networkType:6,osType:7,requestId:N,sdkVersion:"4.22.0",sequence:this._sequence,sid:_,timestamp:ue(r),uid:s,vid:i,service:this._moderationMode,ticket:this._ticket,callbackData:this._extraInfo,vendorConfigs:this._vendor};void 0===this._extraInfo&&delete I.callbackData;const A=q(I);if(A.byteLength<this._workerMessageLengthLimit){if(c("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")){const e=p({},I);delete e.jpg,u.debug("[".concat(this._moderationId,"] Request message for worker of image moderation service: "),JSON.stringify(e))}return A}{const t=this.quality*this._qualityRatio;return this.quality=t,await this.generateRequestData(e,{appId:n,cname:o,cid:E,vid:i,sid:_,uid:s})}}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=H.CLOSED,this.emit(Y.STATE_CHANGE,F.CLOSED)}}function pe(e){if(h(e.interval,"interval",1e3,1/0),e&&e.extraInfo&&e.extraInfo.length>1024)throw new b(a.INVALID_PARAMS,"config.extraInfo length cannot exceed 1024 bytes");if(e&&e.vendor&&e.vendor.length>1024)throw new b(a.INVALID_PARAMS,"config.vendor length cannot exceed 1024 bytes")}const be={name:"ImageModeration",create:function(e){let{config:t}=e;return pe(t),new Ve(t)}};export{be as ImageModerationService,pe as checkImageModerationConfig}; | ||
import{IS_GLOBAL_VERSION as e,EventEmitter as t,PromiseMutex as n,NETWORK_STATE as E,networkIndicator as o,NETWORK_INDICATOR_EVENTS as i,createDefer as _,getParameter as s,AgoraRTCError as r,AgoraRTCErrorCode as c,getRetryWaitTime as a,wait as N,emitAsPromise as R,emitAsInvokerNoResponse as I,getUTF8StringByteLength as A,getMultiUnilbsFormDataByteLength as O,retryable as T,checkValidNumber as C,getRandomString as h,DEFAULT_RETRY_CONFIG as S,AgoraAPIName as L,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{frameData2CryptoBuffer as f}from"@agora-js/media";import w from"axios";import"formdata-polyfill";function g(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 E=n.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:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function V(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var E=Object.getOwnPropertySymbols(e);t&&(E=E.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,E)}return n}function M(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?V(Object(n),!0).forEach((function(t){g(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):V(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}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}({}),b=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}({}),v=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}({}),P=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}({}),y=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}({}),k=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}({});k.AFRICA,k.ASIA,k.CHINA,k.EUROPE,k.GLOBAL,k.INDIA,k.JAPAN,k.NORTH_AMERICA,k.OCEANIA,k.OVERSEA,k.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;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_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}({}),K=function(e){return e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED",e}({}),W=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}({}),H=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 Y extends t{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(y.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(y.CONNECTED):"closed"===this._state?this.emit(y.CLOSED):"failed"===this._state&&this.emit(y.FAILED))}resetReconnectCount(e){l.debug("websocket reset reconnect count, reason: "+e),this.reconnectCount=0}constructor(e,t){let _=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.connectionID=0,this.currentURLIndex=0,this.urls=[],this._reconnectMode="tryNext",this.reconnectReason=void 0,this._initMutex=new n("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=c,this.name=e,this.retryConfig=M({},t),this.useCompress=_,this.tryDoubleDomain=s,this.use443PortOnly=r;const{timeout:a,timeoutFactor:N}=t,R=Math.max(300,Math.floor(3*a/5)),I=Math.max(1.2,Math.floor(8*N)/10);E.ONLINE&&(this.retryConfig.timeout=R,this.retryConfig.timeoutFactor=I),o.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=I):(this.retryConfig.timeout=a,this.retryConfig.timeoutFactor=N))}))}getConnection(){return this.websocket||void 0}async init(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const n=await this._initMutex.lock();this.forceCloseTimeout=t,this.urls=e,this.state="connecting";try{const e=_(),t=this.urls[this.currentURLIndex];s("ENABLE_PREALLOC_PC")&&this.emit(G.PRE_CONNECT_PC),this.createWebSocketConnection(t).then(e.resolve).catch(e.reject),this.once(y.CLOSED,(()=>{e.reject(new r(c.WS_DISCONNECT))})),this.once(y.CONNECTED,e.resolve),await e.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 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 t;const n=_();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"),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 r(c.WS_DISCONNECT,"websocket close: ".concat(e.code))),this.close();else{"connected"===this.state&&(this.reconnectReason=e.reason,this.state="reconnecting");const t=I(this,y.WILL_RECONNECT,this.reconnectMode,e.reason)||this.reconnectMode,E=await this.reconnectWithAction(t);if("closed"===this.state)return void l.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!E)return n.reject(new r(c.WS_DISCONNECT,"websocket reconnect failed: ".concat(e.code))),this.close(!0);n.resolve()}},i=e=>{this.emit(y.ON_MESSAGE,e)},a=e=>{l.warn("[".concat(this.connectionID,"] ws open error ").concat(e))};this.websocket&&(this.websocket.onclose=null,this.websocket.close()),s("GATEWAY_WSS_ADDRESS")&&this.name.startsWith("gateway")&&(e=s("GATEWAY_WSS_ADDRESS")),l.debug("[".concat(this.name,"] start connect, url:"),e);const N=null===(t=this.store)||void 0===t?void 0:t.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"});try{var R;const t=await this.chooseBestWebsocketConnection(e);this.websocket=t,E&&E(this.websocket.url),this.websocket.onclose=o,this.websocket.onmessage=i,this.websocket.onerror=a,null===(R=this.store)||void 0===R||R.recordJoinChannelService({endTs:Date.now(),status:"success"},N),this.joinGatewayRecordIndex=N}catch(e){const t="closed"===this.state,E=e instanceof r,i=E&&e.code===c.WS_ABORT,_=E&&e.code===c.WS_ERR,s=E?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:i?"aborted":"error",errors:[e]},N),t||_?(n.reject(t?new r(c.WS_DISCONNECT,"websocket is closed: ".concat(s)):new r(c.WS_ERR,"init websocket failed: ".concat(s))),_&&l.error("[".concat(this.name,"] init websocket failed: ").concat(s))):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||o.isOnline||!o.onlineWaiter||(this.onlineReconnectListener=o.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([N(t),this.onlineReconnectListener||new Promise((()=>{}))])}if("closed"===this._state||!n)return!1;this.reconnectCount+=1;const E=async(e,t)=>{this.emit(y.RECONNECT_CREATE_CONNECTION,t),await this.createWebSocketConnection(e)};try{if("retry"===e)this.emit(y.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(y.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(y.RECONNECT_WAITTING_FINISH,e),this.urls=await R(this,y.REQUEST_NEW_URLS),this.currentURLIndex=0,await E(this.urls[this.currentURLIndex],e))}catch(n){var i;l.error("[".concat(this.name,"] reconnect failed ").concat(n&&n.toString()));const E=null==n||null===(i=n.data)||void 0===i?void 0:i.desc;return Array.isArray(E)&&E.includes("dynamic key expired")?(this.emit(y.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):this.reconnectWithAction(e,t)}return!0}}class F extends Y{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,t){return new Promise(((n,E)=>{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()})),E(new r(c.WS_ABORT,"choose best websocket aborted"))};const _=s("GATEWAY_DOMAINS");let a;const R=e.indexOf("?h="),I=_.find((t=>-1!==R?e.includes(t,R):e.includes(t)));l.debug("[choose-best-ws] currentDomain: ",I,", domains: ",_);let A=!this.tryDoubleDomain||!I;if(!A&&I){var O;const s=Date.now();try{_.forEach((t=>{const n=-1===R?e.replace(I,t):e.substr(0,R)+e.substr(R).replace(I,t),E=new WebSocket(n);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();A=!0}null===(O=this.store)||void 0===O||O.recordJoinChannelService({urls:i.map((e=>e.url)),service:"gateway"},t),i.forEach((e=>{e.onopen=()=>{if(o)return;const t=Date.now()-s;l.debug("[choose-best-ws] ws open cost ".concat(t,"ms")),i.filter((t=>t!==e)).forEach((e=>{l.debug("[choose-best-ws]close backup websocket: ".concat(e.url)),e.close()})),o=!0,n(e)},e.onclose=e=>{if(a=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,E(a))},e.onmessage=t=>{l.debug("[choose-best-ws]".concat(e.url," onmessage: ").concat(t.data))}})),N(this.forceCloseTimeout).then((()=>{i.forEach((e=>{e.readyState!==WebSocket.OPEN&&e.close()}))}))}if(A){var T;let o;l.debug("[choose-best-ws] use single url: ",e),null===(T=this.store)||void 0===T||T.recordJoinChannelService({urls:[e],service:"gateway"},t);try{o=new WebSocket(e),i.push(o),o.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)}o.onopen=()=>{n(o)},o.onclose=e=>{E(e)},o.onmessage=e=>{l.debug("[choose-best-ws]".concat(o.url," onmessage: ").concat(e.data))},N(this.forceCloseTimeout).then((()=>{o&&o.readyState!==WebSocket.OPEN&&o.close()}))}})).then((e=>(this.closeEstablishingWs=void 0,e))).catch((e=>{throw this.closeEstablishingWs=void 0,e}))}}function J(e){let t=function(){const e=X.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&&(_e(t,10),ne(t,n));let E=e.cid;void 0!==E&&(_e(t,16),_e(t,E));let o=e.cname;void 0!==o&&(_e(t,26),ne(t,o));let i=e.deviceId;void 0!==i&&(_e(t,34),ne(t,i));let _=e.elapse;void 0!==_&&(_e(t,40),re(t,_));let s=e.fileSize;void 0!==s&&(_e(t,48),re(t,j(s)));let r=e.height;void 0!==r&&(_e(t,56),re(t,j(r)));let c=e.jpg;void 0!==c&&(_e(t,66),_e(t,c.length),ee(t,c));let a=e.networkType;void 0!==a&&(_e(t,72),re(t,j(a)));let N=e.osType;void 0!==N&&(_e(t,80),re(t,j(N)));let R=e.requestId;void 0!==R&&(_e(t,90),ne(t,R));let I=e.sdkVersion;void 0!==I&&(_e(t,98),ne(t,I));let A=e.sequence;void 0!==A&&(_e(t,104),re(t,j(A)));let O=e.sid;void 0!==O&&(_e(t,114),ne(t,O));let T=e.timestamp;void 0!==T&&(_e(t,120),re(t,T));let C=e.uid;void 0!==C&&(_e(t,128),_e(t,C));let h=e.vid;void 0!==h&&(_e(t,136),_e(t,h));let S=e.width;void 0!==S&&(_e(t,144),re(t,j(S)));let L=e.service;void 0!==L&&(_e(t,152),_e(t,L));let d=e.callbackData;void 0!==d&&(_e(t,162),_e(t,d.length),ee(t,d));let l=e.ticket;void 0!==l&&(_e(t,170),ne(t,l));let u=e.vendorConfigs;void 0!==u&&(_e(t,178),ne(t,u))}(e,t),function(e){let t=e.bytes,n=e.limit;return t.length===n?t:t.subarray(0,n)}(t)}function x(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=te(e,ie(e));break;case 3:t.requestId=te(e,ie(e));break;case 4:t.timestamp=se(e,!1);break;default:q(e,7&n)}}return t}({bytes:t=e,offset:0,limit:t.length});var t}function q(e,t){switch(t){case 0:for(;128&Ee(e););break;case 2:Q(e,ie(e));break;case 5:Q(e,4);break;case 1:Q(e,8);break;default:throw new Error("Unimplemented type: "+t)}}function j(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}let X=[];function Q(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 z(e,t){let n=e.bytes,E=e.offset,o=e.limit,i=E+t;if(i>n.length){let t=new Uint8Array(2*i);t.set(n),e.bytes=t}return e.offset=i,i>o&&(e.limit=i),E}function $(e,t){let n=e.offset;if(n+t>e.limit)throw new Error("Read past limit");return e.offset+=t,n}function ee(e,t){let n=z(e,t.length);e.bytes.set(t,n)}function te(e,t){let n=$(e,t),E=String.fromCharCode,o=e.bytes,i="�",_="";for(let e=0;e<t;e++){let s,r,c,a,N=o[e+n];0==(128&N)?_+=E(N):192==(224&N)?e+1>=t?_+=i:(s=o[e+n+1],128!=(192&s)?_+=i:(a=(31&N)<<6|63&s,a<128?_+=i:(_+=E(a),e++))):224==(240&N)?e+2>=t?_+=i:(s=o[e+n+1],r=o[e+n+2],32896!=(49344&(s|r<<8))?_+=i:(a=(15&N)<<12|(63&s)<<6|63&r,a<2048||a>=55296&&a<=57343?_+=i:(_+=E(a),e+=2))):240==(248&N)?e+3>=t?_+=i:(s=o[e+n+1],r=o[e+n+2],c=o[e+n+3],8421504!=(12632256&(s|r<<8|c<<16))?_+=i:(a=(7&N)<<18|(63&s)<<12|(63&r)<<6|63&c,a<65536||a>1114111?_+=i:(a-=65536,_+=E(55296+(a>>10),56320+(1023&a)),e+=3))):_+=i}return _}function ne(e,t){let n=t.length,E=0;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),E+=o<128?1:o<2048?2:o<65536?3:4}_e(e,E);let o=z(e,E),i=e.bytes;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),E<128?i[o++]=E:(E<2048?i[o++]=E>>6&31|192:(E<65536?i[o++]=E>>12&15|224:(i[o++]=E>>18&7|240,i[o++]=E>>12&63|128),i[o++]=E>>6&63|128),i[o++]=63&E|128)}}function Ee(e){return e.bytes[$(e,1)]}function oe(e,t){let n=z(e,1);e.bytes[n]=t}function ie(e){let t,n=0,E=0;do{t=Ee(e),n<32&&(E|=(127&t)<<n),n+=7}while(128&t);return E}function _e(e,t){for(t>>>=0;t>=128;)oe(e,127&t|128),t>>>=7;oe(e,t)}function se(e,t){let n,E=0,o=0,i=0;return 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),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),i=127&n,128&n&&(n=Ee(e),i|=(127&n)<<7))))))))),{low:E|o<<28,high:o>>>4|i<<24,unsigned:t}}function re(e,t){let n=t.low>>>0,E=(t.low>>>28|t.high<<4)>>>0,o=t.high>>>24,i=0===o?0===E?n<16384?n<128?1:2:n<1<<21?3:4:E<16384?E<128?5:6:E<1<<21?7:8:o<128?9:10,_=z(e,i),s=e.bytes;switch(i){case 10:s[_+9]=o>>>7&1;case 9:s[_+8]=9!==i?128|o:127&o;case 8:s[_+7]=8!==i?E>>>21|128:E>>>21&127;case 7:s[_+6]=7!==i?E>>>14|128:E>>>14&127;case 6:s[_+5]=6!==i?E>>>7|128:E>>>7&127;case 5:s[_+4]=5!==i?128|E:127&E;case 4:s[_+3]=4!==i?n>>>21|128:n>>>21&127;case 3:s[_+2]=3!==i?n>>>14|128:n>>>14&127;case 2:s[_+1]=2!==i?n>>>7|128:n>>>7&127;case 1:s[_]=1!==i?128|n:127&n}}const ce={},ae={},Ne=4294967296,Re=Ne*Ne,Ie=Re/2,Ae=Se(0,!0),Oe=Se(0),Te=Le(0,-2147483648,!1),Ce=Le(-1,2147483647,!1),he=Le(-1,-1,!0);function Se(e,t){let n,E,o;return t?(o=0<=(e>>>=0)&&e<256)&&(E=ae[e],E)?E:(n=Le(e,0,!0),o&&(ae[e]=n),n):(o=-128<=(e|=0)&&e<128)&&(E=ce[e],E)?E:(n=Le(e,e<0?-1:0,!1),o&&(ce[e]=n),n)}function Le(e,t,n){return{low:0|e,high:0|t,unsigned:!!n}}function de(e,t){if(isNaN(e))return t?Ae:Oe;if(t){if(e<0)return Ae;if(e>=Re)return he}else{if(e<=-Ie)return Te;if(e+1>=Ie)return Ce}return e<0?t?Ae:Oe:Le(e%Ne|0,e/Ne|0,t)}let le=0,ue=0;U.ACCESS_POINT,v.NO_FLAG_SET,v.FLAG_SET_BUT_EMPTY,v.INVALID_FALG_SET,v.FLAG_SET_BUT_NO_RE,v.INVALID_SERVICE_ID,v.NO_SERVICE_AVAILABLE,v.NO_SERVICE_AVAILABLE_P2P,v.NO_SERVICE_AVAILABLE_VOICE,v.NO_SERVICE_AVAILABLE_WEBRTC,v.NO_SERVICE_AVAILABLE_CDS,v.NO_SERVICE_AVAILABLE_CDN,v.NO_SERVICE_AVAILABLE_TDS,v.NO_SERVICE_AVAILABLE_REPORT,v.NO_SERVICE_AVAILABLE_APP_CENTER,v.NO_SERVICE_AVAILABLE_ENV0,v.NO_SERVICE_AVAILABLE_VOET,v.NO_SERVICE_AVAILABLE_STRING_UID,v.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,U.STRING_UID_ALLOCATOR,b.IIIEGAL_APPID,b.IIIEGAL_UID,b.INTERNAL_ERROR,P.K_TIMESTAMP_EXPIRED,P.K_CHANNEL_PERMISSION_INVALID,P.K_CERTIFICATE_INVALID,P.K_CHANNEL_NAME_EMPTY,P.K_CHANNEL_NOT_FOUND,P.K_TICKET_INVALID,P.K_CHANNEL_CONFLICTED,P.K_SERVICE_NOT_READY,P.K_SERVICE_TOO_HEAVY,P.K_UID_BANNED,P.K_IP_BANNED,P.K_AUTO_REBALANCE,P.ERR_INVALID_VENDOR_KEY,P.ERR_INVALID_CHANNEL_NAME,P.WARN_NO_AVAILABLE_CHANNEL,P.WARN_LOOKUP_CHANNEL_TIMEOUT,P.WARN_LOOKUP_CHANNEL_REJECTED,P.WARN_OPEN_CHANNEL_TIMEOUT,P.WARN_OPEN_CHANNEL_REJECTED,P.WARN_REQUEST_DEFERRED,P.ERR_DYNAMIC_KEY_TIMEOUT,P.ERR_NO_AUTHORIZED,P.ERR_VOM_SERVICE_UNAVAILABLE,P.ERR_NO_CHANNEL_AVAILABLE_CODE,P.ERR_MASTER_VOCS_UNAVAILABLE,P.ERR_INTERNAL_ERROR,P.ERR_NO_ACTIVE_STATUS,P.ERR_INVALID_UID,P.ERR_DYNAMIC_KEY_EXPIRED,P.ERR_STATIC_USE_DYANMIC_KE,P.ERR_DYNAMIC_USE_STATIC_KE,P.ERR_NO_VOCS_AVAILABLE,P.ERR_NO_VOS_AVAILABLE,P.ERR_JOIN_CHANNEL_TIMEOUT,P.ERR_JOIN_BY_MULTI_IP,P.ERR_NOT_JOINED,P.ERR_REPEAT_JOIN_REQUEST,P.ERR_REPEAT_JOIN_CHANNEL,P.ERR_INVALID_STRINGUID,P.ERR_TOO_MANY_USERS,P.ERR_SET_CLIENT_ROLE_TIMEOUT,P.ERR_SET_CLIENT_ROLE_NO_PERMISSION,P.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE,P.ERR_PUBLISH_REQUEST_INVALID,P.ERR_SUBSCRIBE_REQUEST_INVALID,P.ERR_NOT_SUPPORTED_MESSAGE,P.ERR_ILLEAGAL_PLUGIN,P.ILLEGAL_CLIENT_ROLE_LEVEL,P.ERR_REJOIN_TOKEN_INVALID,P.ERR_REJOIN_USER_NOT_JOINED,P.ERR_INVALID_OPTIONAL_INFO,P.ERR_TEST_RECOVER,P.ERR_TEST_TRYNEXT,P.ERR_TEST_RETRY,P.ILLEGAL_AES_PASSWORD,P.ERR_TOO_MANY_BROADCASTERS,P.ERR_TOO_MANY_SUBSCRIBERS,P.ERR_LICENSE_ILLEGAL,P.ERR_LICENSE_MISSING,P.ERR_LICENSE_EXPIRED,P.ERR_LICENSE_MINUTES_EXCEEDED,P.ERR_LICENSE_PERIOD_INVALID,P.ERR_LICENSE_MULTIPLE_SDK_SERVICE;const De={GLOBAL:{ASIA:[k.CHINA,k.JAPAN,k.INDIA,k.KOREA,k.HKMC],EUROPE:[],NORTH_AMERICA:[k.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}};Object.keys(De[k.GLOBAL]),k.CHINA,k.NORTH_AMERICA,k.EUROPE,k.ASIA,k.JAPAN,k.INDIA,k.OCEANIA,k.SOUTH_AMERICA,k.AFRICA,k.KOREA,k.HKMC,k.US;let me=0;function fe(e,t,n,E){let{appId:o,areaCode:i,cname:_,sid:r,token:a,uid:N}=t;me++;const R="moderation_plugin",I={service_name:R,json_body:JSON.stringify({appId:o,areaCode:i,cname:_,command:"allocateEdge",requestId:me,seq:me,sid:r,appToken:a,ts:Date.now(),uid:N+""})};let C,h,S=e[0];return T((async()=>{C=Date.now();const e=await function(e,t,n,E){return new Promise(((o,i)=>{t.timeout=t.timeout||s("HTTP_CONNECT_TIMEOUT"),t.responseType=t.responseType||"json",t.data&&!n?(t.data=JSON.stringify(t.data),le+=A(t.data)):n&&(t.data.size?le+=t.data.size:t.data instanceof FormData?le+=O(t.data):le+=A(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,w.request(t).then((e=>{"string"==typeof e.data?ue+=A(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?ue+=e.data.byteLength:ue+=A(JSON.stringify(e.data)),E&&o({data:e.data,headers:e.headers}),o(e.data)})).catch((e=>{w.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))}))}))}(S,{data:I,cancelToken:n,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 t=JSON.parse(e.json_body);if(200!==t.code){const e=new u(D.UNEXPECTED_RESPONSE,"moderation plugin ap error, code: ".concat(t.code,", reason: ").concat(t.reason),{code:t.code,responseTime:h});throw l.error(e.toString()),e}if(!t.servers||!Array.isArray(t.servers)||0===t.servers.length){const e=new u(D.UNEXPECTED_RESPONSE,"moderation plugin ap empty server",{code:t.code,responseTime:h});throw l.error(e.toString()),e}if(!t.servers.some((e=>!!e.wss))){const e=new u(D.UNEXPECTED_RESPONSE,"moderation plugin ap empty port",{code:t.code,responseTime:h});throw l.error(e.toString()),e}const E=s("IMAGE_MODERATION_WORKER_HOST");return{addressList:t.servers.map((e=>{let{address:t,wss:n}=e;if(t&&n)return"wss://".concat(t.replace(/\./g,"-"),".").concat(E,":").concat(n,"/moderation")})).filter((e=>!!e)),workerToken:t.workerToken,vid:t.vid,ticket:t.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)&&(S=e[(n+1)%e.length],!0))),E)}class we extends t{get connectionState(){return this._connectionState}set connectionState(e){if(this._connectionState===e)return;const t=this._connectionState;this._connectionState=e,this.emit(W.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 t;super(),this.name="AgoraRTCImageModeration",this._connectionState=K.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=w.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!==K.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===K.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=s("IMAGE_MODERATION_WORKER_MESSAGE_LENGTH_LIMIT"),this._moderationIntervalMinimum=s("IMAGE_MODERATION_INTERVAL_MINIMUM"),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),this._qualityRatio=s("IMAGE_MODERATION_QUALITY_RATIO"),this._moderationStartTime=Number(Date.now()),this._workerConnection=new F("worker-"+this._moderationId,S),this.on(W.STATE_CHANGE,((e,t)=>{l.debug("[".concat(this._moderationId,"] Moderation operation :").concat(H[e]," ").concat(t||""))})),this.handleWorkerEvents()}async init(e,t){this.emit(W.STATE_CHANGE,H.CONNECT_AP),this._connectInfo=e;const n=this._cancelTokenSource.token;return this._retryConfig=t,new Promise(((E,o)=>{this.on(W.CONNECTION_STATE_CHANGE,((e,t)=>{e===K.CONNECTED&&E()})),this.requestAP(e,n,t).then((e=>{this.connectWorker(e)})).catch((e=>{o(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===K.CONNECTED&&this.inspectImage()}async requestAP(e,t,n){const E=s("WEBCS_DOMAIN").map((e=>"https://".concat(e,"/api/v1"))),o=await fe(E,e,t,n);this.emit(W.STATE_CHANGE,H.AP_CONNECTED);const{addressList:i,ticket:_}=o;return this._ticket=_,i}async connectWorker(e){this.emit(W.STATE_CHANGE,H.CONNECT_WORKER),await this._workerConnection.init(e,1e4)}handleWorkerEvents(){this._workerConnection.on(y.CONNECTED,(async()=>{this.emit(W.STATE_CHANGE,H.WORKER_CONNECTED,this._workerConnection.url),this.connectionState=K.CONNECTED})),this._workerConnection.on(y.CLOSED,(()=>{this.connectionState=K.CLOSED})),this._workerConnection.on(y.FAILED,(()=>{this.connectionState=K.CLOSED})),this._workerConnection.on(y.RECONNECTING,(()=>{this.connectionState=this.connectionState===K.CONNECTED?K.RECONNECTING:K.CONNECTING})),this._workerConnection.on(y.ON_MESSAGE,(async e=>{if(e.data instanceof ArrayBuffer){const t=x(new Uint8Array(e.data));s("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&l.debug("[".concat(this._moderationId,"] Response message for worker of image moderation "),JSON.stringify(t)),this._uploadNum++,void 0===t.code||0===t.code||(this._uploadFailedNum++,l.error("[".concat(this._moderationId,"] Error response from worke, code is ").concat(t.code,", msg is ").concat(t.msg)),this._uploadTimer||(this._uploadTimer=window.setTimeout((()=>{m.reportApiInvoke(this._connectInfo.sid||null,{name:L.IMAGE_MODERATION_UPLOAD,options:[this._uploadFailedNum,this._uploadNum,t.code],tag:d.TRACER}).onError(new u(D.IMAGE_MODERATION_UPLOAD_FAILED,t.msg)),this._uploadTimer=null}),s("IMAGE_MODERATION_UPLOAD_REPORT_INTERVAL"))))}else l.error("[".concat(this._moderationId,"] Unexpected message type from worker"))})),this._workerConnection.on(y.WILL_RECONNECT,((e,t,n)=>{"recover"===e&&n(e),n("tryNext")})),this._workerConnection.on(y.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=I(this,W.CLIENT_LOCAL_VIDEO_TRACK),t={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(s("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&l.debug("Only the track being played can be inspected"));this._sequence++;const n=await this.generateRequestData(e,t);this._workerConnection.sendMessage(n,!0,!0)}else s("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&l.debug("Only the track being published can be inspected")}async generateRequestData(e,t){let{appId:n,cname:E,cid:o,vid:i,sid:_,uid:r}=t;const c=Date.now(),a=await e.getCurrentFrameImage("image/jpeg",this.quality),N=await f(a,n,E),R=this._sequence+"-"+o+"-"+r+"-"+c+"-"+h(12,""),I={appId:n,cid:o,cname:E,deviceId:"",elapse:we.intToLong(Number(c-this._moderationStartTime)),fileSize:a.buffer.byteLength,height:a.height,width:a.width,jpg:N,networkType:6,osType:7,requestId:R,sdkVersion:"4.22.1",sequence:this._sequence,sid:_,timestamp:de(c),uid:r,vid:i,service:this._moderationMode,ticket:this._ticket,callbackData:this._extraInfo,vendorConfigs:this._vendor};void 0===this._extraInfo&&delete I.callbackData;const A=J(I);if(A.byteLength<this._workerMessageLengthLimit){if(s("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")){const e=M({},I);delete e.jpg,l.debug("[".concat(this._moderationId,"] Request message for worker of image moderation service: "),JSON.stringify(e))}return A}{const t=this.quality*this._qualityRatio;return this.quality=t,await this.generateRequestData(e,{appId:n,cname:E,cid:o,vid:i,sid:_,uid:r})}}close(){this._cancelTokenSource.cancel(),this._cancelTokenSource=w.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=K.CLOSED,this.emit(W.STATE_CHANGE,H.CLOSED)}}function ge(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 Ve={name:"ImageModeration",create:function(e){let{config:t}=e;return ge(t),new we(t)}};export{Ve as ImageModerationService,ge as checkImageModerationConfig}; |
@@ -1,3 +0,4 @@ | ||
import { UID, RTMConfiguration, TurnServerConfigWithMode, CloudProxyServerMode, EncryptionMode, AgoraRTCError as AgoraRTCError$1, AgoraRTCErrorCode, EventEmitter, RetryConfiguration } from '@agora-js/shared'; | ||
import { UID, RTMConfiguration, TurnServerConfigWithMode, CloudProxyServerMode, EncryptionMode, EventEmitter, RetryConfiguration } from '@agora-js/shared'; | ||
import { RemoteStreamType } from '@agora-js/media'; | ||
import { AgoraRTCError } from '@agora-js/report'; | ||
@@ -277,2 +278,3 @@ declare enum LiveStreamingServiceMode { | ||
preload?: boolean; | ||
apRequestDetail?: string; | ||
} | ||
@@ -292,12 +294,2 @@ interface JoinInfoWithUID extends JoinInfo { | ||
/** | ||
* @ignore | ||
*/ | ||
declare class AgoraRTCError extends AgoraRTCError$1 { | ||
readonly name: string; | ||
constructor(code: AgoraRTCErrorCode, message?: string, data?: any); | ||
print(level?: "error" | "warning"): AgoraRTCError; | ||
throw(): never; | ||
} | ||
declare class AgoraRTCLiveStreamingClient extends EventEmitter { | ||
@@ -304,0 +296,0 @@ onLiveStreamWarning?: (url: string, err: AgoraRTCError) => void; |
/** | ||
* AgoraWebSDK_N-v4.22.0-0-g8569241d-dirty Copyright AgoraInc. | ||
* AgoraWebSDK_N-v4.22.1-0-g1c8e27e9 Copyright AgoraInc. | ||
*/ | ||
import{AgoraRTCError as e,isValidString as t,AgoraRTCErrorCode as s,isEmpty as n,checkValidNumber as E,checkValidBoolean as r,checkValidEnum as o,checkValidString as i,checkValidArray as _,IS_GLOBAL_VERSION as c,MUTABLE_PARAMS as a,EventEmitter as R,PromiseMutex as A,NETWORK_STATE as I,networkIndicator as N,NETWORK_INDICATOR_EVENTS as S,createDefer as T,getParameter as d,getRetryWaitTime as h,wait as O,emitAsPromise as L,emitAsInvokerNoResponse as u,noop as l,VERSION as C,getUTF8StringByteLength as g,getMultiUnilbsFormDataByteLength as D,retryable as w,DEFAULT_RETRY_CONFIG as U}from"@agora-js/shared";import{logger as m,AgoraRTCEventReport as M,report as V}from"@agora-js/report";import P from"axios";import"formdata-polyfill";function p(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 n=s.call(e,t||"default");if("object"!=typeof n)return n;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 f(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),s.push.apply(s,n)}return s}function v(e){for(var t=1;t<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?f(Object(s),!0).forEach((function(t){p(e,t,s[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):f(Object(s)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(s,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}({}),y=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}({}),k=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}({}),B=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}({}),W=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}({}),G=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}({});class H extends e{constructor(e){super(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",arguments.length>2?arguments[2]:void 0),this.name="AgoraRTCException"}print(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"error";return super.print(e,m)}throw(){super.throw(m)}}function K(e){if(!(n=e,"number"==typeof n&&Math.floor(n)===n&&0<=n&&n<=4294967295||t(e,1,255)))throw new H(s.INVALID_PARAMS,"[String uid] Length of the string: [1,255]. ASCII characters only. [Number uid] The value range is [0,10000]");var n;"string"==typeof e&&m.warn("You input a string as the user ID, to ensure better end-user experience, Agora highly suggests not using a string as the user ID.")}let Y=function(e){return e.TRANSCODE="mix_streaming",e.RAW="raw_streaming",e}({});const F={alpha:1,height:640,width:360,x:0,y:0,zOrder:0,audioChannel:0},x={x:0,y:0,width:160,height:160,zOrder:255,alpha:1};function J(e,t){i(e.url,"".concat(t,".url"),1,1e3,!1),n(e.x)||E(e.x,"".concat(t,".x"),0,1e4),n(e.y)||E(e.y,"".concat(t,".y"),0,1e4),n(e.width)||E(e.width,"".concat(t,".width"),0,1e4),n(e.height)||E(e.height,"".concat(t,".height"),0,1e4),n(e.zOrder)||E(e.zOrder,"".concat(t,".zOrder"),0,255),n(e.alpha)||E(e.alpha,"".concat(t,".alpha"),0,1,!1)}const q={audioBitrate:48,audioChannels:1,audioSampleRate:48e3,backgroundColor:0,height:360,lowLatency:!1,videoBitrate:400,videoCodecProfile:100,videoCodecType:1,videoFrameRate:15,videoGop:30,width:640,images:[],userConfigs:[],userConfigExtraInfo:""};let X=function(e){return e.WARNING="@live_uap-warning",e.ERROR="@line_uap-error",e.PUBLISH_STREAM_STATUS="@live_uap-publish-status",e.WORKER_STATUS="@live_uap-worker-status",e.REQUEST_NEW_ADDRESS="@live_uap-request-address",e}({}),j=function(e){return e.REQUEST_WORKER_MANAGER_LIST="@live_req_worker_manager",e}({}),Q=function(e){return e[e.LIVE_STREAM_RESPONSE_SUCCEED=200]="LIVE_STREAM_RESPONSE_SUCCEED",e[e.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM=454]="LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM",e[e.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR=450]="LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR",e[e.LIVE_STREAM_RESPONSE_BAD_STREAM=451]="LIVE_STREAM_RESPONSE_BAD_STREAM",e[e.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR=400]="LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR",e[e.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST=404]="LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST",e[e.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED=456]="LIVE_STREAM_RESPONSE_NOT_AUTHORIZED",e[e.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE=457]="LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE",e[e.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN=429]="LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN",e[e.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH=452]="LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH",e[e.LIVE_STREAM_RESPONSE_NOT_SUPPORTED=453]="LIVE_STREAM_RESPONSE_NOT_SUPPORTED",e[e.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM=455]="LIVE_STREAM_RESPONSE_MAX_STREAM_NUM",e[e.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR=500]="LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR",e[e.LIVE_STREAM_RESPONSE_WORKER_LOST=501]="LIVE_STREAM_RESPONSE_WORKER_LOST",e[e.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT=502]="LIVE_STREAM_RESPONSE_RESOURCE_LIMIT",e[e.LIVE_STREAM_RESPONSE_WORKER_QUIT=503]="LIVE_STREAM_RESPONSE_WORKER_QUIT",e[e.ERROR_FAIL_SEND_MESSAGE=504]="ERROR_FAIL_SEND_MESSAGE",e[e.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE=30]="PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE",e[e.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT=31]="PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT",e[e.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH=32]="PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH",e[e.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN=33]="PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN",e}({});const z=function(){const e="us".concat("erna","me"),t="pa".concat("sswo","rd"),s=["t","s","t"];s.splice(1,0,"e");const n=s.join(""),E=[];for(let e=0;e<6;e++)E.push("1");const r=E.join(""),o={};return o[e]=n,o[t]=r,Object.assign(o,{turnServerURL:"",tcpport:3433,udpport:3478,forceturn:!1})}();window.DEFAULT_TURN_CONFIG=z,c||(a.WEBCS_DOMAIN=["ap-web-1-oversea.agora.io","ap-web-1-north-america.agora.io"],a.WEBCS_DOMAIN_BACKUP_LIST=["ap-web-2-oversea.agora.io","ap-web-2-north-america.agora.io"],a.PROXY_CS=["proxy-ap-web-oversea.agora.io","proxy-ap-web-america.agora.io"],a.CDS_AP=["cds-ap-web-oversea.agora.io","cds-ap-web-america.agora.io","cds-ap-web-america2.agora.io"],a.ACCOUNT_REGISTER=["sua-ap-web-oversea.agora.io","sua-ap-web-america.agora.io","sua-ap-web-america2.agora.io"],a.UAP_AP=["uap-ap-web-oversea.agora.io","uap-ap-web-america.agora.io","uap-ap-web-america2.agora.io"],a.LOG_UPLOAD_SERVER="logservice-oversea.agora.io",a.EVENT_REPORT_DOMAIN="statscollector-1-oversea.agora.io",a.EVENT_REPORT_BACKUP_DOMAIN="statscollector-2-oversea.agora.io",a.PROXY_SERVER_TYPE3="webrtc-cloud-proxy.agora.io",a.AREAS=["NORTH_AMERICA","OVERSEA"]);M.__CLIENT_LIST__=[];let Z=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}({});Z.AFRICA,Z.ASIA,Z.CHINA,Z.EUROPE,Z.GLOBAL,Z.INDIA,Z.JAPAN,Z.NORTH_AMERICA,Z.OCEANIA,Z.OVERSEA,Z.SOUTH_AMERICA;let $=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}({});$.ASIA,$.NORTH_AMERICA,$.EUROPE,$.JAPAN,$.INDIA,$.KOREA,$.HKMC,$.US,$.OVERSEA,$.GLOBAL,$.OCEANIA,$.SOUTH_AMERICA,$.AFRICA,c&&$.CHINA;let ee=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 te extends R{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(G.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(G.CONNECTED):"closed"===this._state?this.emit(G.CLOSED):"failed"===this._state&&this.emit(G.FAILED))}resetReconnectCount(e){m.debug("websocket reset reconnect count, reason: "+e),this.reconnectCount=0}constructor(e,t){let s=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],E=arguments.length>4&&void 0!==arguments[4]&&arguments[4],r=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 A("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=r,this.name=e,this.retryConfig=v({},t),this.useCompress=s,this.tryDoubleDomain=n,this.use443PortOnly=E;const{timeout:o,timeoutFactor:i}=t,_=Math.max(300,Math.floor(3*o/5)),c=Math.max(1.2,Math.floor(8*i)/10);I.ONLINE&&(this.retryConfig.timeout=_,this.retryConfig.timeoutFactor=c),N.on(S.NETWORK_STATE_CHANGE,((e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===I.ONLINE?(this.retryConfig.timeout=_,this.retryConfig.timeoutFactor=c):(this.retryConfig.timeout=o,this.retryConfig.timeoutFactor=i))}))}getConnection(){return this.websocket||void 0}async init(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const E=await this._initMutex.lock();this.forceCloseTimeout=n,this.urls=t,this.state="connecting";try{const t=T(),n=this.urls[this.currentURLIndex];d("ENABLE_PREALLOC_PC")&&this.emit(ee.PRE_CONNECT_PC),this.createWebSocketConnection(n).then(t.resolve).catch(t.reject),this.once(G.CLOSED,(()=>{t.reject(new e(s.WS_DISCONNECT))})),this.once(G.CONNECTED,t.resolve),await t.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.state=e?"failed":"closed",this.closeEstablishingWs&&this.closeEstablishingWs()}reconnect(e,t){if(!this.websocket)return void m.warning("[".concat(this.name,"] can not reconnect, no websocket"));void 0!==e&&(this.reconnectMode=e),m.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(t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new e(s.WS_ABORT,"websocket is not ready");try{n||(t=JSON.stringify(t)),this.websocket.send(t)}catch(t){throw new e(s.WS_ERR,"send websocket message error"+t.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=T();this.connectionID+=1,this.joinGatewayRecordIndex=void 0;const r=e=>{var t;null===(t=this.store)||void 0===t||t.signalChannelOpen(),m.debug("[".concat(this.name,"] websocket opened:"),e),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),E.resolve()},o=async t=>{var n;if(m.debug("[".concat(this.name,"] websocket close ").concat(null===(n=this.websocket)||void 0===n?void 0:n.url,", code: ").concat(t.code,", reason: ").concat(t.reason,", current mode: ").concat(this.reconnectMode)),this.reconnectCount>=this.retryConfig.maxRetryCount)E.reject(new e(s.WS_DISCONNECT,"websocket close: ".concat(t.code))),this.close();else{"connected"===this.state&&(this.reconnectReason=t.reason,this.state="reconnecting");const n=u(this,G.WILL_RECONNECT,this.reconnectMode,t.reason)||this.reconnectMode,r=await this.reconnectWithAction(n);if("closed"===this.state)return void m.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!r)return E.reject(new e(s.WS_DISCONNECT,"websocket reconnect failed: ".concat(t.code))),this.close(!0);E.resolve()}},i=e=>{this.emit(G.ON_MESSAGE,e)},_=e=>{m.warn("[".concat(this.connectionID,"] ws open error ").concat(e))};this.websocket&&(this.websocket.onclose=null,this.websocket.close()),d("GATEWAY_WSS_ADDRESS")&&this.name.startsWith("gateway")&&(t=d("GATEWAY_WSS_ADDRESS")),m.debug("[".concat(this.name,"] start connect, url:"),t);const c=null===(n=this.store)||void 0===n?void 0:n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"});try{var a;const e=await this.chooseBestWebsocketConnection(t);this.websocket=e,r&&r(this.websocket.url),this.websocket.onclose=o,this.websocket.onmessage=i,this.websocket.onerror=_,null===(a=this.store)||void 0===a||a.recordJoinChannelService({endTs:Date.now(),status:"success"},c),this.joinGatewayRecordIndex=c}catch(t){const n="closed"===this.state,r=t instanceof e,i=r&&t.code===s.WS_ABORT,_=r&&t.code===s.WS_ERR,a=r?t.message:t&&(t.reason||t.toString());m.warning("[choose-best-ws] chooseBestWebsocket error: ".concat(a)),this.store&&this.store.recordJoinChannelService({endTs:Date.now(),status:i?"aborted":"error",errors:[t]},c),n||_?(E.reject(n?new e(s.WS_DISCONNECT,"websocket is closed: ".concat(a)):new e(s.WS_ERR,"init websocket failed: ".concat(a))),_&&m.error("[".concat(this.name,"] init websocket failed: ").concat(a))):o&&o(t)}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;m.warning("[choose-best-ws] action: =>",e),this.onlineReconnectListener||N.isOnline||!N.onlineWaiter||(this.onlineReconnectListener=N.onlineWaiter.then((()=>{this.onlineReconnectListener=void 0})));let s=!0;if(this.reconnectInterrupter=()=>s=!1,t){const t=h(this.reconnectCount,this.retryConfig);m.debug("[".concat(this.name,"] wait ").concat(t,"ms to reconnect websocket, mode: ").concat(e)),await Promise.race([O(t),this.onlineReconnectListener||new Promise((()=>{}))])}if("closed"===this._state||!s)return!1;this.reconnectCount+=1;const n=async(e,t)=>{this.emit(G.RECONNECT_CREATE_CONNECTION,t),await this.createWebSocketConnection(e)};try{if("retry"===e)this.emit(G.RECONNECT_WAITTING_FINISH,e),await n(this.urls[this.currentURLIndex],e);else if("tryNext"===e){if(this.currentURLIndex+=1,this.currentURLIndex>=this.urls.length)return this.reconnectWithAction("recover",!1);m.debug("[".concat(this.name,"] websocket url length: ").concat(this.urls.length," current index: ").concat(this.currentURLIndex)),this.emit(G.RECONNECT_WAITTING_FINISH,e),await n(this.urls[this.currentURLIndex],e)}else"recover"===e&&(m.debug("[".concat(this.name,"] request new urls")),this.resetReconnectCount("recover mode"),this.emit(G.RECONNECT_WAITTING_FINISH,e),this.urls=await L(this,G.REQUEST_NEW_URLS),this.currentURLIndex=0,await n(this.urls[this.currentURLIndex],e))}catch(s){var E;m.error("[".concat(this.name,"] reconnect failed ").concat(s&&s.toString()));const n=null==s||null===(E=s.data)||void 0===E?void 0:E.desc;return Array.isArray(n)&&n.includes("dynamic key expired")?(this.emit(G.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):this.reconnectWithAction(e,t)}return!0}}class se extends te{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,r)=>{let o=!1;const i=[];this.closeEstablishingWs=()=>{m.debug("[choose-best-ws] close establishing websockets"),i.forEach((e=>{e.onclose=null,e.onopen=null,e.onmessage=null,e.close()})),r(new e(s.WS_ABORT,"choose best websocket aborted"))};const _=d("GATEWAY_DOMAINS");let c;const a=t.indexOf("?h="),R=_.find((e=>-1!==a?t.includes(e,a):t.includes(e)));m.debug("[choose-best-ws] currentDomain: ",R,", domains: ",_);let A=!this.tryDoubleDomain||!R;if(!A&&R){var I;const e=Date.now();try{_.forEach((e=>{const s=-1===a?t.replace(R,e):t.substr(0,a)+t.substr(a).replace(R,e),n=new WebSocket(s);n.binaryType="arraybuffer",i.push(n),m.debug("[choose-best-ws] ws is connecting:",n.url)}))}catch(e){for(m.debug("[choose-best-ws] ws create failed, fallback to single url"),i.forEach((e=>e.close()));i.length;)i.pop();A=!0}null===(I=this.store)||void 0===I||I.recordJoinChannelService({urls:i.map((e=>e.url)),service:"gateway"},n),i.forEach((t=>{t.onopen=()=>{if(o)return;const s=Date.now()-e;m.debug("[choose-best-ws] ws open cost ".concat(s,"ms")),i.filter((e=>e!==t)).forEach((e=>{m.debug("[choose-best-ws]close backup websocket: ".concat(e.url)),e.close()})),o=!0,E(t)},t.onclose=e=>{if(c=e,o)return;i.find((e=>!(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING)))||(m.debug("[choose-best-ws] all websocket is closed"),o=!0,r(c))},t.onmessage=e=>{m.debug("[choose-best-ws]".concat(t.url," onmessage: ").concat(e.data))}})),O(this.forceCloseTimeout).then((()=>{i.forEach((e=>{e.readyState!==WebSocket.OPEN&&e.close()}))}))}if(A){var N;let o;m.debug("[choose-best-ws] use single url: ",t),null===(N=this.store)||void 0===N||N.recordJoinChannelService({urls:[t],service:"gateway"},n);try{o=new WebSocket(t),i.push(o),o.binaryType="arraybuffer"}catch(t){const n=new e(s.WS_ERR,"init websocket failed! Error: ".concat(t.toString()));return m.error("[".concat(this.name,"]").concat(n)),void r(n)}o.onopen=()=>{E(o)},o.onclose=e=>{r(e)},o.onmessage=e=>{m.debug("[choose-best-ws]".concat(o.url," onmessage: ").concat(e.data))},O(this.forceCloseTimeout).then((()=>{o&&o.readyState!==WebSocket.OPEN&&o.close()}))}})).then((e=>(this.closeEstablishingWs=void 0,e))).catch((e=>{throw this.closeEstablishingWs=void 0,e}))}}class ne extends R{constructor(e,t,s,n){super(),this.spec=void 0,this.token=void 0,this.websocket=void 0,this.pingpongTimer=void 0,this.reconnectMode="retry",this.serviceMode=void 0,this.reqId=0,this.commandReqId=0,this.handleWebSocketOpen=()=>{this.reconnectMode="retry",this.startPingPong()},this.handleWebSocketMessage=e=>{if(!e.data)return;const t=JSON.parse(e.data);t.requestId?this.emit("@".concat(t.requestId,"-").concat(t.sid),t):(V.workerEvent(this.spec.sid,{actionType:"status",serverCode:t.code,workerType:this.serviceMode===Y.TRANSCODE?1:2}),this.emit(X.PUBLISH_STREAM_STATUS,t))},this.spec=t,this.token=e,this.serviceMode=n,this.websocket=new se("live-streaming",s),this.websocket.on(G.CONNECTED,this.handleWebSocketOpen),this.websocket.on(G.ON_MESSAGE,this.handleWebSocketMessage),this.websocket.on(G.REQUEST_NEW_URLS,((e,t)=>{L(this,X.REQUEST_NEW_ADDRESS).then(e).catch(t)})),this.websocket.on(G.RECONNECTING,(()=>{this.websocket.reconnectMode=this.reconnectMode}))}init(e){return this.websocket.init(e)}async request(e,t,n,E){this.reqId+=1,"request"===e&&(this.commandReqId+=1);const r=this.commandReqId,o=this.reqId;if(!o||!this.websocket)throw new H(s.UNEXPECTED_ERROR);const i=v({command:e,sdkVersion:"4.22.0"===C?"0.0.1":C,seq:o,requestId:o,allocate:n,cname:this.spec.cname,appId:this.spec.appId,sid:this.spec.sid,uid:this.spec.uid.toString(),ts:Math.floor(Date.now()/1e3)},t);if("closed"===this.websocket.state)throw new H(s.WS_DISCONNECT);const _=()=>new Promise(((e,t)=>{this.websocket.once(G.CLOSED,(()=>t(new H(s.WS_ABORT)))),this.websocket.once(G.CONNECTED,e)}));"connected"!==this.websocket.state&&await _(),i.clientRequest&&(i.clientRequest.workerToken=this.token);const c=new Promise(((e,t)=>{const n=()=>{t(new H(s.WS_ABORT))};this.websocket.once(G.RECONNECTING,n),this.websocket.once(G.CLOSED,n),this.once("@".concat(o,"-").concat(this.spec.sid),(t=>{e(t)}))}));E&&V.workerEvent(this.spec.sid,v(v({},E),{},{requestId:r,actionType:"request",payload:JSON.stringify(t.clientRequest),serverCode:0,code:0}));const a=Date.now();this.websocket.sendMessage(i);let R=null;try{R=await c}catch(s){if("closed"===this.websocket.state)throw s;return await _(),await this.request(e,t,n)}return E&&V.workerEvent(this.spec.sid,v(v({},E),{},{requestId:r,actionType:"response",payload:JSON.stringify(R.serverResponse),serverCode:R.code,success:200===R.code,responseTime:Date.now()-a})),200!==R.code&&this.handleResponseError(R),R}tryNextAddress(){this.reconnectMode="tryNext",this.websocket.reconnect("tryNext")}close(){const e="4.22.0"===C?"0.0.1":C;this.reqId+=1,"connected"===this.websocket.state?(this.websocket.sendMessage({command:"request",appId:this.spec.appId,cname:this.spec.cname,uid:this.spec.uid.toString(),sdkVersion:e,sid:this.spec.sid,seq:this.reqId,ts:Math.floor(Date.now()/1e3),requestId:this.reqId,clientRequest:{command:"DestroyWorker"}}),this.websocket.close(!1,!0)):this.websocket.close(!1),this.pingpongTimer&&(window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0)}handleResponseError(e){switch(e.code){case Q.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM:return void m.warning("live stream response already exists stream");case Q.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR:case Q.LIVE_STREAM_RESPONSE_BAD_STREAM:case Q.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR:return new H(s.LIVE_STREAMING_INVALID_ARGUMENT,"",{code:e.code}).throw();case Q.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST:if("UnpublishStream"===e.serverResponse.command)return;throw new H(s.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case Q.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED:return new H(s.LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED,"",{code:e.code}).throw();case Q.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const t=new H(s.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE);return this.emit(X.WARNING,t,e.serverResponse.url)}case Q.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN:{const t=new H(s.LIVE_STREAMING_WARN_FREQUENT_REQUEST);return this.emit(X.WARNING,t,e.serverResponse.url)}case Q.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH:throw new H(s.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case Q.LIVE_STREAM_RESPONSE_NOT_SUPPORTED:return new H(s.LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED,"",{code:e.code}).throw();case Q.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM:{const t=new H(s.LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT);return this.emit(X.WARNING,t,e.serverResponse.url)}case Q.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR:return new H(s.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:e.code}).throw();case Q.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT:throw new H(s.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream resource limit",{retry:!0,changeAddress:!0});case Q.LIVE_STREAM_RESPONSE_WORKER_LOST:case Q.LIVE_STREAM_RESPONSE_WORKER_QUIT:if("UnpublishStream"===e.serverResponse.command)return;throw new H(s.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case Q.ERROR_FAIL_SEND_MESSAGE:if("UnpublishStream"===e.serverResponse.command)return;if("UpdateTranscoding"===e.serverResponse.command||"ControlStream"===e.serverResponse.command)return new H(s.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{code:e.code}).throw();throw new H(s.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case Q.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case Q.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case Q.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case Q.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:return new H(s.LIVE_STREAMING_CDN_ERROR,"",{code:e.code}).throw()}}startPingPong(){this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval((()=>{"connected"===this.websocket.state&&this.request("ping",{}).catch(l)}),6e3)}}let Ee=0,re=0;const oe={[b.ACCESS_POINT]:{[B.NO_FLAG_SET]:{desc:"flag is zero",retry:!1},[B.FLAG_SET_BUT_EMPTY]:{desc:"flag is empty",retry:!1},[B.INVALID_FALG_SET]:{desc:"invalid flag",retry:!1},[B.FLAG_SET_BUT_NO_RE]:{desc:"flag set unilbs but no request",retry:!1},[B.INVALID_SERVICE_ID]:{desc:"invalid service id",retry:!1},[B.NO_SERVICE_AVAILABLE]:{desc:"no service available",retry:!0},[B.NO_SERVICE_AVAILABLE_P2P]:{desc:"no unilbs p2p service available",retry:!0},[B.NO_SERVICE_AVAILABLE_VOICE]:{desc:"no unilbs voice service available",retry:!0},[B.NO_SERVICE_AVAILABLE_WEBRTC]:{desc:"no unilbs webrtc service available",retry:!0},[B.NO_SERVICE_AVAILABLE_CDS]:{desc:"no cds service available",retry:!0},[B.NO_SERVICE_AVAILABLE_CDN]:{desc:"no cdn dispatcher service available",retry:!0},[B.NO_SERVICE_AVAILABLE_TDS]:{desc:"no tds service available",retry:!0},[B.NO_SERVICE_AVAILABLE_REPORT]:{desc:"no unilbs report service available",retry:!0},[B.NO_SERVICE_AVAILABLE_APP_CENTER]:{desc:"no app center service available",retry:!0},[B.NO_SERVICE_AVAILABLE_ENV0]:{desc:"no unilbs sig env0 service available",retry:!0},[B.NO_SERVICE_AVAILABLE_VOET]:{desc:"no unilbs voet service available",retry:!0},[B.NO_SERVICE_AVAILABLE_STRING_UID]:{desc:"no string uid service available",retry:!0},[B.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS]:{desc:"no webrtc unilbs service available",retry:!0}},[b.UNILBS]:{[k.INVALID_VENDOR_KEY]:{desc:"invalid vendor key, can not find appid",retry:!1},[k.INVALID_CHANNEL_NAME]:{desc:"invalid channel name",retry:!1},[k.INTERNAL_ERROR]:{desc:"unilbs internal error",retry:!1},[k.NO_AUTHORIZED]:{desc:"invalid token, authorized failed",retry:!1},[k.DYNAMIC_KEY_TIMEOUT]:{desc:"dynamic key or token timeout",retry:!1},[k.NO_ACTIVE_STATUS]:{desc:"no active status",retry:!1},[k.DYNAMIC_KEY_EXPIRED]:{desc:"dynamic key expired",retry:!1},[k.STATIC_USE_DYNAMIC_KEY]:{desc:"static use dynamic key",retry:!1},[k.DYNAMIC_USE_STATIC_KEY]:{desc:"dynamic use static key",retry:!1},[k.USER_OVERLOAD]:{desc:"amount of users over load",retry:!1},[k.FORBIDDEN_REGION]:{desc:"the request is forbidden in this area",retry:!1},[k.CANNOT_MEET_AREA_DEMAND]:{desc:"unable to allocate services in this area",retry:!1}},[b.STRING_UID_ALLOCATOR]:{[y.IIIEGAL_APPID]:{desc:"invalid appid",retry:!1},[y.IIIEGAL_UID]:{desc:"invalid string uid",retry:!1},[y.INTERNAL_ERROR]:{desc:"string uid allocator internal error",retry:!0}}};function ie(e){const t=oe[Math.floor(e/1e4)];if(!t)return{desc:"unknown error",retry:!1};const s=t[e%1e4];if(!s){if(Math.floor(e/1e4)===b.ACCESS_POINT){const t=e%1e4;if("1"===t.toString()[0])return{desc:e.toString(),retry:!1};if("2"===t.toString()[0])return{desc:e.toString(),retry:!0}}return{desc:"unknown error",retry:!1}}return s}W.K_TIMESTAMP_EXPIRED,W.K_CHANNEL_PERMISSION_INVALID,W.K_CERTIFICATE_INVALID,W.K_CHANNEL_NAME_EMPTY,W.K_CHANNEL_NOT_FOUND,W.K_TICKET_INVALID,W.K_CHANNEL_CONFLICTED,W.K_SERVICE_NOT_READY,W.K_SERVICE_TOO_HEAVY,W.K_UID_BANNED,W.K_IP_BANNED,W.K_AUTO_REBALANCE,W.ERR_INVALID_VENDOR_KEY,W.ERR_INVALID_CHANNEL_NAME,W.WARN_NO_AVAILABLE_CHANNEL,W.WARN_LOOKUP_CHANNEL_TIMEOUT,W.WARN_LOOKUP_CHANNEL_REJECTED,W.WARN_OPEN_CHANNEL_TIMEOUT,W.WARN_OPEN_CHANNEL_REJECTED,W.WARN_REQUEST_DEFERRED,W.ERR_DYNAMIC_KEY_TIMEOUT,W.ERR_NO_AUTHORIZED,W.ERR_VOM_SERVICE_UNAVAILABLE,W.ERR_NO_CHANNEL_AVAILABLE_CODE,W.ERR_MASTER_VOCS_UNAVAILABLE,W.ERR_INTERNAL_ERROR,W.ERR_NO_ACTIVE_STATUS,W.ERR_INVALID_UID,W.ERR_DYNAMIC_KEY_EXPIRED,W.ERR_STATIC_USE_DYANMIC_KE,W.ERR_DYNAMIC_USE_STATIC_KE,W.ERR_NO_VOCS_AVAILABLE,W.ERR_NO_VOS_AVAILABLE,W.ERR_JOIN_CHANNEL_TIMEOUT,W.ERR_JOIN_BY_MULTI_IP,W.ERR_NOT_JOINED,W.ERR_REPEAT_JOIN_REQUEST,W.ERR_REPEAT_JOIN_CHANNEL,W.ERR_INVALID_STRINGUID,W.ERR_TOO_MANY_USERS,W.ERR_SET_CLIENT_ROLE_TIMEOUT,W.ERR_SET_CLIENT_ROLE_NO_PERMISSION,W.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE,W.ERR_PUBLISH_REQUEST_INVALID,W.ERR_SUBSCRIBE_REQUEST_INVALID,W.ERR_NOT_SUPPORTED_MESSAGE,W.ERR_ILLEAGAL_PLUGIN,W.ILLEGAL_CLIENT_ROLE_LEVEL,W.ERR_REJOIN_TOKEN_INVALID,W.ERR_REJOIN_USER_NOT_JOINED,W.ERR_INVALID_OPTIONAL_INFO,W.ERR_TEST_RECOVER,W.ERR_TEST_TRYNEXT,W.ERR_TEST_RETRY,W.ILLEGAL_AES_PASSWORD,W.ERR_TOO_MANY_BROADCASTERS,W.ERR_TOO_MANY_SUBSCRIBERS,W.ERR_LICENSE_ILLEGAL,W.ERR_LICENSE_MISSING,W.ERR_LICENSE_EXPIRED,W.ERR_LICENSE_MINUTES_EXCEEDED,W.ERR_LICENSE_PERIOD_INVALID,W.ERR_LICENSE_MULTIPLE_SDK_SERVICE;const _e={GLOBAL:{ASIA:[Z.CHINA,Z.JAPAN,Z.INDIA,Z.KOREA,Z.HKMC],EUROPE:[],NORTH_AMERICA:[Z.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}};async function ce(e,t,n,E,r){const o=Date.now(),i={sid:n.sid,opid:10,appid:n.appId,string_uid:t};let _=e[0];const c=await w((()=>function(e,t,n,E){return new Promise(((r,o)=>{t.timeout=t.timeout||d("HTTP_CONNECT_TIMEOUT"),t.responseType=t.responseType||"json",t.data&&!n?(t.data=JSON.stringify(t.data),Ee+=g(t.data)):n&&(t.data.size?Ee+=t.data.size:t.data instanceof FormData?Ee+=D(t.data):Ee+=g(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,P.request(t).then((e=>{"string"==typeof e.data?re+=g(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?re+=e.data.byteLength:re+=g(JSON.stringify(e.data)),E&&r({data:e.data,headers:e.headers}),r(e.data)})).catch((e=>{P.isCancel(e)?o(new H(s.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?o(new H(s.NETWORK_TIMEOUT,e.message)):e.response?o(new H(s.NETWORK_RESPONSE_ERROR,e.response.status)):o(new H(s.NETWORK_ERROR,e.message))}))}))}(_+"".concat(-1===_.indexOf("?")?"?":"&","action=stringuid"),{data:i,cancelToken:E,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":72}})),((n,E)=>{if(0===n.code){if(n.uid<=0||n.uid>=Math.pow(2,32))throw m.error("Invalid Uint Uid ".concat(t," => ").concat(n.uid),n),V.reqUserAccount(i.sid,{lts:o,success:!1,serverAddr:_,stringUid:i.string_uid,uid:n.uid,errorCode:s.INVALID_UINT_UID_FROM_STRING_UID,extend:i}),new H(s.INVALID_UINT_UID_FROM_STRING_UID);return V.reqUserAccount(i.sid,{lts:o,success:!0,serverAddr:_,stringUid:i.string_uid,uid:n.uid,errorCode:null,extend:i}),!1}const r=ie(n.code);return r.retry&&(_=e[(E+1)%e.length]),V.reqUserAccount(i.sid,{lts:o,success:!1,serverAddr:_,stringUid:i.string_uid,uid:n.uid,errorCode:r.desc,extend:i}),r.retry}),((t,n)=>t.code!==s.OPERATION_ABORTED&&(V.reqUserAccount(i.sid,{lts:o,success:!1,serverAddr:_,stringUid:i.string_uid,uid:null,errorCode:t.code,extend:i}),_=e[(n+1)%e.length],!0)),r);if(0!==c.code){const e=ie(c.code);throw new H(s.UNEXPECTED_RESPONSE,e.desc)}return c}Object.keys(_e[Z.GLOBAL]),Z.CHINA,Z.NORTH_AMERICA,Z.EUROPE,Z.ASIA,Z.JAPAN,Z.INDIA,Z.OCEANIA,Z.SOUTH_AMERICA,Z.AFRICA,Z.KOREA,Z.HKMC,Z.US;class ae extends R{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:U,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:U;super(),this.onLiveStreamWarning=void 0,this.onLiveStreamError=void 0,this.spec=void 0,this.retryTimeout=1e4,this.connection=void 0,this.httpRetryConfig=void 0,this.wsRetryConfig=void 0,this.streamingTasks=new Map,this.isStartingStreamingTask=!1,this.taskMutex=new A("live-streaming"),this.cancelToken=P.CancelToken.source(),this.transcodingConfig=void 0,this.uapResponse=void 0,this.lastTaskId=1,this.statusError=new Map,this.spec=e,this.httpRetryConfig=s,this.wsRetryConfig=t}async setTranscodingConfig(e){const t=v(v({},q),e);66!==t.videoCodecProfile&&77!==t.videoCodecProfile&&100!==t.videoCodecProfile&&(m.debug("[".concat(this.spec.clientId,"] set transcoding config, fix video codec profile: ").concat(t.videoCodecProfile," -> 100")),t.videoCodecProfile=100),t.transcodingUsers||(t.transcodingUsers=t.userConfigs),t.transcodingUsers&&(t.transcodingUsers=t.transcodingUsers.map((e=>v(v(v({},F),e),{},{zOrder:e.zOrder?e.zOrder+1:1})))),function(e){n(e.width)||E(e.width,"config.width",0,1e4),n(e.height)||E(e.height,"config.height",0,1e4),n(e.videoBitrate)||E(e.videoBitrate,"config.videoBitrate",1,1e6),n(e.videoFrameRate)||E(e.videoFrameRate,"config.videoFrameRate"),n(e.lowLatency)||r(e.lowLatency,"config.lowLatency"),n(e.audioSampleRate)||o(e.audioSampleRate,"config.audioSampleRate",[32e3,44100,48e3]),n(e.audioBitrate)||E(e.audioBitrate,"config.audioBitrate",1,128),n(e.audioChannels)||o(e.audioChannels,"config.audioChannels",[1,2,3,4,5]),n(e.videoGop)||E(e.videoGop,"config.videoGop"),n(e.videoCodecProfile)||o(e.videoCodecProfile,"config.videoCodecProfile",[66,77,100]),n(e.userCount)||E(e.userCount,"config.userCount",0,17),n(e.backgroundColor)||E(e.backgroundColor,"config.backgroundColor",0,16777215),n(e.userConfigExtraInfo)||i(e.userConfigExtraInfo,"config.userConfigExtraInfo",0,4096,!1),e.transcodingUsers&&!n(e.transcodingUsers)&&(_(e.transcodingUsers,"config.transcodingUsers"),e.transcodingUsers.forEach(((e,t)=>{K(e.uid),n(e.x)||E(e.x,"transcodingUser[".concat(t,"].x"),0,1e4),n(e.y)||E(e.y,"transcodingUser[".concat(t,"].y"),0,1e4),n(e.width)||E(e.width,"transcodingUser[".concat(t,"].width"),0,1e4),n(e.height)||E(e.height,"transcodingUser[".concat(t,"].height"),0,1e4),n(e.zOrder)||E(e.zOrder-1,"transcodingUser[".concat(t,"].zOrder"),0,100),n(e.alpha)||E(e.alpha,"transcodingUser[".concat(t,"].alpha"),0,1,!1)}))),n(e.watermark)||J(e.watermark,"watermark"),n(e.backgroundImage)||J(e.backgroundImage,"backgroundImage"),e.images&&!n(e.images)&&(_(e.images,"config.images"),e.images.forEach(((e,t)=>{J(e,"images[".concat(t,"]"))})))}(t);const s=[];t.images&&s.push(...t.images.map((e=>v(v(v({},x),e),{},{zOrder:255})))),t.backgroundImage&&(s.push(v(v(v({},x),t.backgroundImage),{},{zOrder:0})),delete t.backgroundImage),t.watermark&&(s.push(v(v(v({},x),t.watermark),{},{zOrder:255})),delete t.watermark),t.images=s,t.transcodingUsers&&(t.userConfigs=t.transcodingUsers.map((e=>v({},e))),t.userCount=t.transcodingUsers.length,delete t.transcodingUsers);const c=(t.userConfigs||[]).map((e=>"number"==typeof e.uid?Promise.resolve(e.uid):async function(e,t,s,n,E){const r=d("ACCOUNT_REGISTER").slice(0,d("AJAX_REQUEST_CONCURRENT"));let o=[];o=t.proxyServer?r.map((e=>"https://".concat(t.proxyServer,"/ap/?url=").concat(e+"/api/v1"))):r.map((e=>"https://".concat(e,"/api/v1")));const i=null==E?void 0:E.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"stringUID",urls:o});try{const r=await ce(o,e,t,s,n);return null==E||E.recordJoinChannelService({status:"success",endTs:Date.now()},i),r.uid}catch(e){throw null==E||E.recordJoinChannelService({status:"error",endTs:Date.now(),errors:[e]},i),e}}(e.uid,this.spec,this.cancelToken.token,this.httpRetryConfig)));if((await Promise.all(c)).forEach(((e,s)=>{t.userConfigs&&t.userConfigs[s]&&(t.userConfigs[s].uid=e)})),this.transcodingConfig=t,this.connection)try{const e=await this.connection.request("request",{clientRequest:{command:"UpdateTranscoding",transcodingConfig:this.transcodingConfig}},!1,{command:"UpdateTranscoding",workerType:1,requestByUser:!0,tid:Array.from(this.streamingTasks.values()).map((e=>e.taskId)).join("#")});m.debug("[".concat(this.spec.clientId,"] update live transcoding config success, code: ").concat(e.code,", config:"),JSON.stringify(this.transcodingConfig))}catch(e){if(!e.data||!e.data.retry)throw e;e.data.changeAddress&&this.connection.tryNextAddress(),this.streamingTasks.forEach((t=>{m.warning("[".concat(this.spec.clientId,"] live streaming receive error"),e.toString(),"try to republish",t.url),this.startLiveStreamingTask(t.url,t.mode,e).then((()=>{m.debug("[".concat(this.spec.clientId,"] live streaming republish ").concat(t.url," success"))})).catch((e=>{m.error("[".concat(this.spec.clientId,"] live streaming republish failed"),t.url,e.toString()),this.onLiveStreamError&&this.onLiveStreamError(t.url,e)}))}))}}async startLiveStreamingTask(e,t,n){if(!this.transcodingConfig&&t===Y.TRANSCODE)throw new H(s.INVALID_OPERATION,"[LiveStreaming] no transcoding config found, can not start transcoding streaming task");const E={command:"PublishStream",ts:Date.now(),url:e,uid:this.spec.uid.toString(),autoDestroyTime:100,acceptImageTimeout:!0};m.debug("[".concat(this.spec.clientId,"] start live streaming ").concat(e,", mode: ").concat(t));const r=await this.taskMutex.lock();if(!this.connection&&n)return void r();if(this.streamingTasks.get(e)&&!n)return r(),new H(s.LIVE_STREAMING_TASK_CONFLICT).throw();try{this.connection||(this.connection=await this.connect(t))}catch(e){throw r(),e}switch(t){case Y.TRANSCODE:E.transcodingConfig=v({},this.transcodingConfig);case Y.RAW:}this.uapResponse&&this.uapResponse.vid&&(E.vid=this.uapResponse.vid),this.isStartingStreamingTask=!0;const o=this.lastTaskId++;try{const s=new Promise(((t,s)=>{O(this.retryTimeout).then((()=>{if(n)return s(n);const t=this.statusError.get(e);return t?(this.statusError.delete(e),s(t)):void 0}))})),i=await Promise.race([this.connection.request("request",{clientRequest:E},!0,{url:e,command:"PublishStream",workerType:t===Y.TRANSCODE?1:2,requestByUser:!n,tid:o.toString()}),s]);this.isStartingStreamingTask=!1,m.debug("[".concat(this.spec.clientId,"] live streaming started, code: ").concat(i.code)),this.streamingTasks.set(e,{clientRequest:E,mode:t,url:e,taskId:o}),r()}catch(s){if(r(),this.isStartingStreamingTask=!1,!s.data||!s.data.retry||n)throw s;return s.data.changeAddress?(this.connection.tryNextAddress(),await this.startLiveStreamingTask(e,t,s)):await this.startLiveStreamingTask(e,t,s)}}stopLiveStreamingTask(e){return new Promise(((t,n)=>{const E=this.streamingTasks.get(e);if(!E||!this.connection)return new H(s.UNEXPECTED_ERROR,"can not find streaming task to stop").throw();const r=E.mode;E.abortTask=()=>{m.debug("[".concat(this.spec.clientId,"] stop live streaming success(worker exception)")),this.streamingTasks.delete(e),t()},this.connection.request("request",{clientRequest:{command:"UnpublishStream",url:E.url}},!1,{url:e,command:"UnPublishStream",workerType:r===Y.TRANSCODE?1:2,requestByUser:!0,tid:(this.lastTaskId++).toString()}).then((s=>{m.debug("[".concat(this.spec.clientId,"] stop live streaming success, code: ").concat(s.code)),this.streamingTasks.delete(e),0===this.streamingTasks.size&&(this.connection&&this.connection.close(),this.connection=void 0),t()})).catch(n)}))}resetAllTask(){const e=Array.from(this.streamingTasks.values());this.terminate();for(const t of e)this.startLiveStreamingTask(t.url,t.mode).catch((e=>{this.onLiveStreamError&&this.onLiveStreamError(t.url,e)}))}terminate(){this.cancelToken&&this.cancelToken.cancel(),this.streamingTasks=new Map,this.isStartingStreamingTask=!1,this.statusError=new Map,this.cancelToken=P.CancelToken.source(),this.uapResponse=void 0,this.connection&&this.connection.close(),this.connection=void 0}async connect(e){if(this.connection)throw new H(s.UNEXPECTED_ERROR,"live streaming connection has already connected");const t=await L(this,j.REQUEST_WORKER_MANAGER_LIST,e);return this.uapResponse=t,this.connection=new ne(t.workerToken,this.spec,this.wsRetryConfig,e),this.connection.on(X.WARNING,((e,t)=>this.onLiveStreamWarning&&this.onLiveStreamWarning(t,e))),this.connection.on(X.PUBLISH_STREAM_STATUS,(e=>this.handlePublishStreamServer(e))),this.connection.on(X.REQUEST_NEW_ADDRESS,((t,n)=>{if(!this.connection)return n(new H(s.UNEXPECTED_ERROR,"can not get new live streaming address list"));L(this,j.REQUEST_WORKER_MANAGER_LIST,e).then((e=>{this.uapResponse=e,t(e.addressList)})).catch(n)})),await this.connection.init(t.addressList),this.connection}handlePublishStreamServer(e){const t=e.serverStatus&&e.serverStatus.url||"empty_url",n=this.streamingTasks.get(t),E=e.reason;switch(e.code){case Q.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case Q.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case Q.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case Q.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:{const E=new H(s.LIVE_STREAMING_CDN_ERROR,"",{code:e.code});if(n)return m.error(E.toString()),this.onLiveStreamError&&this.onLiveStreamError(t,E);if(!this.isStartingStreamingTask)return;this.statusError.set(t,E)}case Q.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const e=new H(s.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE,E);return this.onLiveStreamWarning&&this.onLiveStreamWarning(t,e)}case Q.LIVE_STREAM_RESPONSE_WORKER_LOST:case Q.LIVE_STREAM_RESPONSE_WORKER_QUIT:{if(!this.connection)return;this.connection.tryNextAddress();const t=Array.from(this.streamingTasks.values());for(const n of t)n.abortTask?n.abortTask():(m.warning("[".concat(this.spec.clientId,"] publish stream status code"),e.code,"try to republish",n.url),this.startLiveStreamingTask(n.url,n.mode,new H(s.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:e.code})).then((()=>{m.debug("[".concat(this.spec.clientId,"] republish live stream success"),n.url)})).catch((e=>{m.error(e.toString()),this.onLiveStreamError&&this.onLiveStreamError(n.url,e)})));return}}}hasUrl(e){return this.streamingTasks.has(e)}}const Re={name:"LiveStreaming",create:function(e){return new ae(e.joinInfo,e.websocketRetryConfig||U,e.httpRetryConfig||U)}};export{Re as LiveStreamingService}; | ||
import{isValidString as e,AgoraRTCErrorCode as t,isEmpty as s,checkValidNumber as n,checkValidBoolean as E,checkValidEnum as r,checkValidString as i,checkValidArray as o,IS_GLOBAL_VERSION as _,EventEmitter as c,PromiseMutex as R,NETWORK_STATE as a,networkIndicator as A,NETWORK_INDICATOR_EVENTS as I,createDefer as N,getParameter as S,AgoraRTCError as T,getRetryWaitTime as d,wait as h,emitAsPromise as O,emitAsInvokerNoResponse as L,noop as C,VERSION as l,getUTF8StringByteLength as u,getMultiUnilbsFormDataByteLength as g,retryable as D,DEFAULT_RETRY_CONFIG as w}from"@agora-js/shared";import{AgoraRTCError as U,logger as M,report as m,AgoraRTCErrorCode as V}from"@agora-js/report";import P from"axios";import"formdata-polyfill";function f(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 n=s.call(e,t||"default");if("object"!=typeof n)return n;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 p(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),s.push.apply(s,n)}return s}function v(e){for(var t=1;t<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?p(Object(s),!0).forEach((function(t){f(e,t,s[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):p(Object(s)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(s,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}({}),y=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}({}),k=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}({}),B=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}({}),W=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}({}),H=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}({});function G(s){if(!(n=s,"number"==typeof n&&Math.floor(n)===n&&0<=n&&n<=4294967295||e(s,1,255)))throw new U(t.INVALID_PARAMS,"[String uid] Length of the string: [1,255]. ASCII characters only. [Number uid] The value range is [0,10000]");var n;"string"==typeof s&&M.warn("You input a string as the user ID, to ensure better end-user experience, Agora highly suggests not using a string as the user ID.")}let K=function(e){return e.TRANSCODE="mix_streaming",e.RAW="raw_streaming",e}({});const Y={alpha:1,height:640,width:360,x:0,y:0,zOrder:0,audioChannel:0},F={x:0,y:0,width:160,height:160,zOrder:255,alpha:1};function x(e,t){i(e.url,"".concat(t,".url"),1,1e3,!1),s(e.x)||n(e.x,"".concat(t,".x"),0,1e4),s(e.y)||n(e.y,"".concat(t,".y"),0,1e4),s(e.width)||n(e.width,"".concat(t,".width"),0,1e4),s(e.height)||n(e.height,"".concat(t,".height"),0,1e4),s(e.zOrder)||n(e.zOrder,"".concat(t,".zOrder"),0,255),s(e.alpha)||n(e.alpha,"".concat(t,".alpha"),0,1,!1)}const J={audioBitrate:48,audioChannels:1,audioSampleRate:48e3,backgroundColor:0,height:360,lowLatency:!1,videoBitrate:400,videoCodecProfile:100,videoCodecType:1,videoFrameRate:15,videoGop:30,width:640,images:[],userConfigs:[],userConfigExtraInfo:""};let q=function(e){return e.WARNING="@live_uap-warning",e.ERROR="@line_uap-error",e.PUBLISH_STREAM_STATUS="@live_uap-publish-status",e.WORKER_STATUS="@live_uap-worker-status",e.REQUEST_NEW_ADDRESS="@live_uap-request-address",e}({}),X=function(e){return e.REQUEST_WORKER_MANAGER_LIST="@live_req_worker_manager",e}({}),Q=function(e){return e[e.LIVE_STREAM_RESPONSE_SUCCEED=200]="LIVE_STREAM_RESPONSE_SUCCEED",e[e.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM=454]="LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM",e[e.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR=450]="LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR",e[e.LIVE_STREAM_RESPONSE_BAD_STREAM=451]="LIVE_STREAM_RESPONSE_BAD_STREAM",e[e.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR=400]="LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR",e[e.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST=404]="LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST",e[e.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED=456]="LIVE_STREAM_RESPONSE_NOT_AUTHORIZED",e[e.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE=457]="LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE",e[e.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN=429]="LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN",e[e.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH=452]="LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH",e[e.LIVE_STREAM_RESPONSE_NOT_SUPPORTED=453]="LIVE_STREAM_RESPONSE_NOT_SUPPORTED",e[e.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM=455]="LIVE_STREAM_RESPONSE_MAX_STREAM_NUM",e[e.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR=500]="LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR",e[e.LIVE_STREAM_RESPONSE_WORKER_LOST=501]="LIVE_STREAM_RESPONSE_WORKER_LOST",e[e.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT=502]="LIVE_STREAM_RESPONSE_RESOURCE_LIMIT",e[e.LIVE_STREAM_RESPONSE_WORKER_QUIT=503]="LIVE_STREAM_RESPONSE_WORKER_QUIT",e[e.ERROR_FAIL_SEND_MESSAGE=504]="ERROR_FAIL_SEND_MESSAGE",e[e.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE=30]="PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE",e[e.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT=31]="PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT",e[e.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH=32]="PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH",e[e.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN=33]="PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN",e}({}),j=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}({});j.AFRICA,j.ASIA,j.CHINA,j.EUROPE,j.GLOBAL,j.INDIA,j.JAPAN,j.NORTH_AMERICA,j.OCEANIA,j.OVERSEA,j.SOUTH_AMERICA;let z=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}({});z.ASIA,z.NORTH_AMERICA,z.EUROPE,z.JAPAN,z.INDIA,z.KOREA,z.HKMC,z.US,z.OVERSEA,z.GLOBAL,z.OCEANIA,z.SOUTH_AMERICA,z.AFRICA,_&&z.CHINA;let Z=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 $ extends c{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(H.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(H.CONNECTED):"closed"===this._state?this.emit(H.CLOSED):"failed"===this._state&&this.emit(H.FAILED))}resetReconnectCount(e){M.debug("websocket reset reconnect count, reason: "+e),this.reconnectCount=0}constructor(e,t){let s=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],E=arguments.length>4&&void 0!==arguments[4]&&arguments[4],r=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=r,this.name=e,this.retryConfig=v({},t),this.useCompress=s,this.tryDoubleDomain=n,this.use443PortOnly=E;const{timeout:i,timeoutFactor:o}=t,_=Math.max(300,Math.floor(3*i/5)),c=Math.max(1.2,Math.floor(8*o)/10);a.ONLINE&&(this.retryConfig.timeout=_,this.retryConfig.timeoutFactor=c),A.on(I.NETWORK_STATE_CHANGE,((e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===a.ONLINE?(this.retryConfig.timeout=_,this.retryConfig.timeoutFactor=c):(this.retryConfig.timeout=i,this.retryConfig.timeoutFactor=o))}))}getConnection(){return this.websocket||void 0}async init(e){let s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const n=await this._initMutex.lock();this.forceCloseTimeout=s,this.urls=e,this.state="connecting";try{const e=N(),s=this.urls[this.currentURLIndex];S("ENABLE_PREALLOC_PC")&&this.emit(Z.PRE_CONNECT_PC),this.createWebSocketConnection(s).then(e.resolve).catch(e.reject),this.once(H.CLOSED,(()=>{e.reject(new T(t.WS_DISCONNECT))})),this.once(H.CONNECTED,e.resolve),await e.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 M.warning("[".concat(this.name,"] can not reconnect, no websocket"));void 0!==e&&(this.reconnectMode=e),M.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 s=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new T(t.WS_ABORT,"websocket is not ready");try{s||(e=JSON.stringify(e)),this.websocket.send(e)}catch(e){throw new T(t.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 s;const n=N();this.connectionID+=1,this.joinGatewayRecordIndex=void 0;const E=e=>{var t;null===(t=this.store)||void 0===t||t.signalChannelOpen(),M.debug("[".concat(this.name,"] websocket opened:"),e),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),n.resolve()},r=async e=>{var s;if(M.debug("[".concat(this.name,"] websocket close ").concat(null===(s=this.websocket)||void 0===s?void 0:s.url,", code: ").concat(e.code,", reason: ").concat(e.reason,", current mode: ").concat(this.reconnectMode)),this.reconnectCount>=this.retryConfig.maxRetryCount)n.reject(new T(t.WS_DISCONNECT,"websocket close: ".concat(e.code))),this.close();else{"connected"===this.state&&(this.reconnectReason=e.reason,this.state="reconnecting");const s=L(this,H.WILL_RECONNECT,this.reconnectMode,e.reason)||this.reconnectMode,E=await this.reconnectWithAction(s);if("closed"===this.state)return void M.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!E)return n.reject(new T(t.WS_DISCONNECT,"websocket reconnect failed: ".concat(e.code))),this.close(!0);n.resolve()}},i=e=>{this.emit(H.ON_MESSAGE,e)},o=e=>{M.warn("[".concat(this.connectionID,"] ws open error ").concat(e))};this.websocket&&(this.websocket.onclose=null,this.websocket.close()),S("GATEWAY_WSS_ADDRESS")&&this.name.startsWith("gateway")&&(e=S("GATEWAY_WSS_ADDRESS")),M.debug("[".concat(this.name,"] start connect, url:"),e);const _=null===(s=this.store)||void 0===s?void 0:s.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"});try{var c;const t=await this.chooseBestWebsocketConnection(e);this.websocket=t,E&&E(this.websocket.url),this.websocket.onclose=r,this.websocket.onmessage=i,this.websocket.onerror=o,null===(c=this.store)||void 0===c||c.recordJoinChannelService({endTs:Date.now(),status:"success"},_),this.joinGatewayRecordIndex=_}catch(e){const s="closed"===this.state,E=e instanceof T,i=E&&e.code===t.WS_ABORT,o=E&&e.code===t.WS_ERR,c=E?e.message:e&&(e.reason||e.toString());M.warning("[choose-best-ws] chooseBestWebsocket error: ".concat(c)),this.store&&this.store.recordJoinChannelService({endTs:Date.now(),status:i?"aborted":"error",errors:[e]},_),s||o?(n.reject(s?new T(t.WS_DISCONNECT,"websocket is closed: ".concat(c)):new T(t.WS_ERR,"init websocket failed: ".concat(c))),o&&M.error("[".concat(this.name,"] init websocket failed: ").concat(c))):r&&r(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;M.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=d(this.reconnectCount,this.retryConfig);M.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 n=async(e,t)=>{this.emit(H.RECONNECT_CREATE_CONNECTION,t),await this.createWebSocketConnection(e)};try{if("retry"===e)this.emit(H.RECONNECT_WAITTING_FINISH,e),await n(this.urls[this.currentURLIndex],e);else if("tryNext"===e){if(this.currentURLIndex+=1,this.currentURLIndex>=this.urls.length)return this.reconnectWithAction("recover",!1);M.debug("[".concat(this.name,"] websocket url length: ").concat(this.urls.length," current index: ").concat(this.currentURLIndex)),this.emit(H.RECONNECT_WAITTING_FINISH,e),await n(this.urls[this.currentURLIndex],e)}else"recover"===e&&(M.debug("[".concat(this.name,"] request new urls")),this.resetReconnectCount("recover mode"),this.emit(H.RECONNECT_WAITTING_FINISH,e),this.urls=await O(this,H.REQUEST_NEW_URLS),this.currentURLIndex=0,await n(this.urls[this.currentURLIndex],e))}catch(s){var E;M.error("[".concat(this.name,"] reconnect failed ").concat(s&&s.toString()));const n=null==s||null===(E=s.data)||void 0===E?void 0:E.desc;return Array.isArray(n)&&n.includes("dynamic key expired")?(this.emit(H.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):this.reconnectWithAction(e,t)}return!0}}class ee extends ${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,s){return new Promise(((n,E)=>{let r=!1;const i=[];this.closeEstablishingWs=()=>{M.debug("[choose-best-ws] close establishing websockets"),i.forEach((e=>{e.onclose=null,e.onopen=null,e.onmessage=null,e.close()})),E(new T(t.WS_ABORT,"choose best websocket aborted"))};const o=S("GATEWAY_DOMAINS");let _;const c=e.indexOf("?h="),R=o.find((t=>-1!==c?e.includes(t,c):e.includes(t)));M.debug("[choose-best-ws] currentDomain: ",R,", domains: ",o);let a=!this.tryDoubleDomain||!R;if(!a&&R){var A;const t=Date.now();try{o.forEach((t=>{const s=-1===c?e.replace(R,t):e.substr(0,c)+e.substr(c).replace(R,t),n=new WebSocket(s);n.binaryType="arraybuffer",i.push(n),M.debug("[choose-best-ws] ws is connecting:",n.url)}))}catch(e){for(M.debug("[choose-best-ws] ws create failed, fallback to single url"),i.forEach((e=>e.close()));i.length;)i.pop();a=!0}null===(A=this.store)||void 0===A||A.recordJoinChannelService({urls:i.map((e=>e.url)),service:"gateway"},s),i.forEach((e=>{e.onopen=()=>{if(r)return;const s=Date.now()-t;M.debug("[choose-best-ws] ws open cost ".concat(s,"ms")),i.filter((t=>t!==e)).forEach((e=>{M.debug("[choose-best-ws]close backup websocket: ".concat(e.url)),e.close()})),r=!0,n(e)},e.onclose=e=>{if(_=e,r)return;i.find((e=>!(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING)))||(M.debug("[choose-best-ws] all websocket is closed"),r=!0,E(_))},e.onmessage=t=>{M.debug("[choose-best-ws]".concat(e.url," onmessage: ").concat(t.data))}})),h(this.forceCloseTimeout).then((()=>{i.forEach((e=>{e.readyState!==WebSocket.OPEN&&e.close()}))}))}if(a){var I;let r;M.debug("[choose-best-ws] use single url: ",e),null===(I=this.store)||void 0===I||I.recordJoinChannelService({urls:[e],service:"gateway"},s);try{r=new WebSocket(e),i.push(r),r.binaryType="arraybuffer"}catch(e){const s=new T(t.WS_ERR,"init websocket failed! Error: ".concat(e.toString()));return M.error("[".concat(this.name,"]").concat(s)),void E(s)}r.onopen=()=>{n(r)},r.onclose=e=>{E(e)},r.onmessage=e=>{M.debug("[choose-best-ws]".concat(r.url," onmessage: ").concat(e.data))},h(this.forceCloseTimeout).then((()=>{r&&r.readyState!==WebSocket.OPEN&&r.close()}))}})).then((e=>(this.closeEstablishingWs=void 0,e))).catch((e=>{throw this.closeEstablishingWs=void 0,e}))}}class te extends c{constructor(e,t,s,n){super(),this.spec=void 0,this.token=void 0,this.websocket=void 0,this.pingpongTimer=void 0,this.reconnectMode="retry",this.serviceMode=void 0,this.reqId=0,this.commandReqId=0,this.handleWebSocketOpen=()=>{this.reconnectMode="retry",this.startPingPong()},this.handleWebSocketMessage=e=>{if(!e.data)return;const t=JSON.parse(e.data);t.requestId?this.emit("@".concat(t.requestId,"-").concat(t.sid),t):(m.workerEvent(this.spec.sid,{actionType:"status",serverCode:t.code,workerType:this.serviceMode===K.TRANSCODE?1:2}),this.emit(q.PUBLISH_STREAM_STATUS,t))},this.spec=t,this.token=e,this.serviceMode=n,this.websocket=new ee("live-streaming",s),this.websocket.on(H.CONNECTED,this.handleWebSocketOpen),this.websocket.on(H.ON_MESSAGE,this.handleWebSocketMessage),this.websocket.on(H.REQUEST_NEW_URLS,((e,t)=>{O(this,q.REQUEST_NEW_ADDRESS).then(e).catch(t)})),this.websocket.on(H.RECONNECTING,(()=>{this.websocket.reconnectMode=this.reconnectMode}))}init(e){return this.websocket.init(e)}async request(e,t,s,n){this.reqId+=1,"request"===e&&(this.commandReqId+=1);const E=this.commandReqId,r=this.reqId;if(!r||!this.websocket)throw new U(V.UNEXPECTED_ERROR);const i=v({command:e,sdkVersion:"4.22.1"===l?"0.0.1":l,seq:r,requestId:r,allocate:s,cname:this.spec.cname,appId:this.spec.appId,sid:this.spec.sid,uid:this.spec.uid.toString(),ts:Math.floor(Date.now()/1e3)},t);if("closed"===this.websocket.state)throw new U(V.WS_DISCONNECT);const o=()=>new Promise(((e,t)=>{this.websocket.once(H.CLOSED,(()=>t(new U(V.WS_ABORT)))),this.websocket.once(H.CONNECTED,e)}));"connected"!==this.websocket.state&&await o(),i.clientRequest&&(i.clientRequest.workerToken=this.token);const _=new Promise(((e,t)=>{const s=()=>{t(new U(V.WS_ABORT))};this.websocket.once(H.RECONNECTING,s),this.websocket.once(H.CLOSED,s),this.once("@".concat(r,"-").concat(this.spec.sid),(t=>{e(t)}))}));n&&m.workerEvent(this.spec.sid,v(v({},n),{},{requestId:E,actionType:"request",payload:JSON.stringify(t.clientRequest),serverCode:0,code:0}));const c=Date.now();this.websocket.sendMessage(i);let R=null;try{R=await _}catch(n){if("closed"===this.websocket.state)throw n;return await o(),await this.request(e,t,s)}return n&&m.workerEvent(this.spec.sid,v(v({},n),{},{requestId:E,actionType:"response",payload:JSON.stringify(R.serverResponse),serverCode:R.code,success:200===R.code,responseTime:Date.now()-c})),200!==R.code&&this.handleResponseError(R),R}tryNextAddress(){this.reconnectMode="tryNext",this.websocket.reconnect("tryNext")}close(){const e="4.22.1"===l?"0.0.1":l;this.reqId+=1,"connected"===this.websocket.state?(this.websocket.sendMessage({command:"request",appId:this.spec.appId,cname:this.spec.cname,uid:this.spec.uid.toString(),sdkVersion:e,sid:this.spec.sid,seq:this.reqId,ts:Math.floor(Date.now()/1e3),requestId:this.reqId,clientRequest:{command:"DestroyWorker"}}),this.websocket.close(!1,!0)):this.websocket.close(!1),this.pingpongTimer&&(window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0)}handleResponseError(e){switch(e.code){case Q.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM:return void M.warning("live stream response already exists stream");case Q.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR:case Q.LIVE_STREAM_RESPONSE_BAD_STREAM:case Q.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR:return new U(V.LIVE_STREAMING_INVALID_ARGUMENT,"",{code:e.code}).throw();case Q.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST:if("UnpublishStream"===e.serverResponse.command)return;throw new U(V.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case Q.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED:return new U(V.LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED,"",{code:e.code}).throw();case Q.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const t=new U(V.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE);return this.emit(q.WARNING,t,e.serverResponse.url)}case Q.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN:{const t=new U(V.LIVE_STREAMING_WARN_FREQUENT_REQUEST);return this.emit(q.WARNING,t,e.serverResponse.url)}case Q.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH:throw new U(V.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case Q.LIVE_STREAM_RESPONSE_NOT_SUPPORTED:return new U(V.LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED,"",{code:e.code}).throw();case Q.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM:{const t=new U(V.LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT);return this.emit(q.WARNING,t,e.serverResponse.url)}case Q.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR:return new U(V.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:e.code}).throw();case Q.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT:throw new U(V.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream resource limit",{retry:!0,changeAddress:!0});case Q.LIVE_STREAM_RESPONSE_WORKER_LOST:case Q.LIVE_STREAM_RESPONSE_WORKER_QUIT:if("UnpublishStream"===e.serverResponse.command)return;throw new U(V.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case Q.ERROR_FAIL_SEND_MESSAGE:if("UnpublishStream"===e.serverResponse.command)return;if("UpdateTranscoding"===e.serverResponse.command||"ControlStream"===e.serverResponse.command)return new U(V.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{code:e.code}).throw();throw new U(V.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case Q.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case Q.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case Q.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case Q.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:return new U(V.LIVE_STREAMING_CDN_ERROR,"",{code:e.code}).throw()}}startPingPong(){this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval((()=>{"connected"===this.websocket.state&&this.request("ping",{}).catch(C)}),6e3)}}let se=0,ne=0;const Ee={[b.ACCESS_POINT]:{[B.NO_FLAG_SET]:{desc:"flag is zero",retry:!1},[B.FLAG_SET_BUT_EMPTY]:{desc:"flag is empty",retry:!1},[B.INVALID_FALG_SET]:{desc:"invalid flag",retry:!1},[B.FLAG_SET_BUT_NO_RE]:{desc:"flag set unilbs but no request",retry:!1},[B.INVALID_SERVICE_ID]:{desc:"invalid service id",retry:!1},[B.NO_SERVICE_AVAILABLE]:{desc:"no service available",retry:!0},[B.NO_SERVICE_AVAILABLE_P2P]:{desc:"no unilbs p2p service available",retry:!0},[B.NO_SERVICE_AVAILABLE_VOICE]:{desc:"no unilbs voice service available",retry:!0},[B.NO_SERVICE_AVAILABLE_WEBRTC]:{desc:"no unilbs webrtc service available",retry:!0},[B.NO_SERVICE_AVAILABLE_CDS]:{desc:"no cds service available",retry:!0},[B.NO_SERVICE_AVAILABLE_CDN]:{desc:"no cdn dispatcher service available",retry:!0},[B.NO_SERVICE_AVAILABLE_TDS]:{desc:"no tds service available",retry:!0},[B.NO_SERVICE_AVAILABLE_REPORT]:{desc:"no unilbs report service available",retry:!0},[B.NO_SERVICE_AVAILABLE_APP_CENTER]:{desc:"no app center service available",retry:!0},[B.NO_SERVICE_AVAILABLE_ENV0]:{desc:"no unilbs sig env0 service available",retry:!0},[B.NO_SERVICE_AVAILABLE_VOET]:{desc:"no unilbs voet service available",retry:!0},[B.NO_SERVICE_AVAILABLE_STRING_UID]:{desc:"no string uid service available",retry:!0},[B.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS]:{desc:"no webrtc unilbs service available",retry:!0}},[b.UNILBS]:{[k.INVALID_VENDOR_KEY]:{desc:"invalid vendor key, can not find appid",retry:!1},[k.INVALID_CHANNEL_NAME]:{desc:"invalid channel name",retry:!1},[k.INTERNAL_ERROR]:{desc:"unilbs internal error",retry:!1},[k.NO_AUTHORIZED]:{desc:"invalid token, authorized failed",retry:!1},[k.DYNAMIC_KEY_TIMEOUT]:{desc:"dynamic key or token timeout",retry:!1},[k.NO_ACTIVE_STATUS]:{desc:"no active status",retry:!1},[k.DYNAMIC_KEY_EXPIRED]:{desc:"dynamic key expired",retry:!1},[k.STATIC_USE_DYNAMIC_KEY]:{desc:"static use dynamic key",retry:!1},[k.DYNAMIC_USE_STATIC_KEY]:{desc:"dynamic use static key",retry:!1},[k.USER_OVERLOAD]:{desc:"amount of users over load",retry:!1},[k.FORBIDDEN_REGION]:{desc:"the request is forbidden in this area",retry:!1},[k.CANNOT_MEET_AREA_DEMAND]:{desc:"unable to allocate services in this area",retry:!1}},[b.STRING_UID_ALLOCATOR]:{[y.IIIEGAL_APPID]:{desc:"invalid appid",retry:!1},[y.IIIEGAL_UID]:{desc:"invalid string uid",retry:!1},[y.INTERNAL_ERROR]:{desc:"string uid allocator internal error",retry:!0}}};function re(e){const t=Ee[Math.floor(e/1e4)];if(!t)return{desc:"unknown error",retry:!1};const s=t[e%1e4];if(!s){if(Math.floor(e/1e4)===b.ACCESS_POINT){const t=e%1e4;if("1"===t.toString()[0])return{desc:e.toString(),retry:!1};if("2"===t.toString()[0])return{desc:e.toString(),retry:!0}}return{desc:"unknown error",retry:!1}}return s}W.K_TIMESTAMP_EXPIRED,W.K_CHANNEL_PERMISSION_INVALID,W.K_CERTIFICATE_INVALID,W.K_CHANNEL_NAME_EMPTY,W.K_CHANNEL_NOT_FOUND,W.K_TICKET_INVALID,W.K_CHANNEL_CONFLICTED,W.K_SERVICE_NOT_READY,W.K_SERVICE_TOO_HEAVY,W.K_UID_BANNED,W.K_IP_BANNED,W.K_AUTO_REBALANCE,W.ERR_INVALID_VENDOR_KEY,W.ERR_INVALID_CHANNEL_NAME,W.WARN_NO_AVAILABLE_CHANNEL,W.WARN_LOOKUP_CHANNEL_TIMEOUT,W.WARN_LOOKUP_CHANNEL_REJECTED,W.WARN_OPEN_CHANNEL_TIMEOUT,W.WARN_OPEN_CHANNEL_REJECTED,W.WARN_REQUEST_DEFERRED,W.ERR_DYNAMIC_KEY_TIMEOUT,W.ERR_NO_AUTHORIZED,W.ERR_VOM_SERVICE_UNAVAILABLE,W.ERR_NO_CHANNEL_AVAILABLE_CODE,W.ERR_MASTER_VOCS_UNAVAILABLE,W.ERR_INTERNAL_ERROR,W.ERR_NO_ACTIVE_STATUS,W.ERR_INVALID_UID,W.ERR_DYNAMIC_KEY_EXPIRED,W.ERR_STATIC_USE_DYANMIC_KE,W.ERR_DYNAMIC_USE_STATIC_KE,W.ERR_NO_VOCS_AVAILABLE,W.ERR_NO_VOS_AVAILABLE,W.ERR_JOIN_CHANNEL_TIMEOUT,W.ERR_JOIN_BY_MULTI_IP,W.ERR_NOT_JOINED,W.ERR_REPEAT_JOIN_REQUEST,W.ERR_REPEAT_JOIN_CHANNEL,W.ERR_INVALID_STRINGUID,W.ERR_TOO_MANY_USERS,W.ERR_SET_CLIENT_ROLE_TIMEOUT,W.ERR_SET_CLIENT_ROLE_NO_PERMISSION,W.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE,W.ERR_PUBLISH_REQUEST_INVALID,W.ERR_SUBSCRIBE_REQUEST_INVALID,W.ERR_NOT_SUPPORTED_MESSAGE,W.ERR_ILLEAGAL_PLUGIN,W.ILLEGAL_CLIENT_ROLE_LEVEL,W.ERR_REJOIN_TOKEN_INVALID,W.ERR_REJOIN_USER_NOT_JOINED,W.ERR_INVALID_OPTIONAL_INFO,W.ERR_TEST_RECOVER,W.ERR_TEST_TRYNEXT,W.ERR_TEST_RETRY,W.ILLEGAL_AES_PASSWORD,W.ERR_TOO_MANY_BROADCASTERS,W.ERR_TOO_MANY_SUBSCRIBERS,W.ERR_LICENSE_ILLEGAL,W.ERR_LICENSE_MISSING,W.ERR_LICENSE_EXPIRED,W.ERR_LICENSE_MINUTES_EXCEEDED,W.ERR_LICENSE_PERIOD_INVALID,W.ERR_LICENSE_MULTIPLE_SDK_SERVICE;const ie={GLOBAL:{ASIA:[j.CHINA,j.JAPAN,j.INDIA,j.KOREA,j.HKMC],EUROPE:[],NORTH_AMERICA:[j.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}};async function oe(e,s,n,E,r){const i=Date.now(),o={sid:n.sid,opid:10,appid:n.appId,string_uid:s};let _=e[0];const c=await D((()=>function(e,s,n,E){return new Promise(((r,i)=>{s.timeout=s.timeout||S("HTTP_CONNECT_TIMEOUT"),s.responseType=s.responseType||"json",s.data&&!n?(s.data=JSON.stringify(s.data),se+=u(s.data)):n&&(s.data.size?se+=s.data.size:s.data instanceof FormData?se+=g(s.data):se+=u(JSON.stringify(s.data))),s.headers=s.headers||{},s.headers["Content-Type"]=s.headers["Content-Type"]||"application/json",s.method="POST",s.url=e,P.request(s).then((e=>{"string"==typeof e.data?ne+=u(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?ne+=e.data.byteLength:ne+=u(JSON.stringify(e.data)),E&&r({data:e.data,headers:e.headers}),r(e.data)})).catch((e=>{P.isCancel(e)?i(new U(t.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?i(new U(t.NETWORK_TIMEOUT,e.message)):e.response?i(new U(t.NETWORK_RESPONSE_ERROR,e.response.status)):i(new U(t.NETWORK_ERROR,e.message))}))}))}(_+"".concat(-1===_.indexOf("?")?"?":"&","action=stringuid"),{data:o,cancelToken:E,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":72}})),((t,n)=>{if(0===t.code){if(t.uid<=0||t.uid>=Math.pow(2,32))throw M.error("Invalid Uint Uid ".concat(s," => ").concat(t.uid),t),m.reqUserAccount(o.sid,{lts:i,success:!1,serverAddr:_,stringUid:o.string_uid,uid:t.uid,errorCode:V.INVALID_UINT_UID_FROM_STRING_UID,extend:o}),new U(V.INVALID_UINT_UID_FROM_STRING_UID);return m.reqUserAccount(o.sid,{lts:i,success:!0,serverAddr:_,stringUid:o.string_uid,uid:t.uid,errorCode:null,extend:o}),!1}const E=re(t.code);return E.retry&&(_=e[(n+1)%e.length]),m.reqUserAccount(o.sid,{lts:i,success:!1,serverAddr:_,stringUid:o.string_uid,uid:t.uid,errorCode:E.desc,extend:o}),E.retry}),((t,s)=>t.code!==V.OPERATION_ABORTED&&(m.reqUserAccount(o.sid,{lts:i,success:!1,serverAddr:_,stringUid:o.string_uid,uid:null,errorCode:t.code,extend:o}),_=e[(s+1)%e.length],!0)),r);if(0!==c.code){const e=re(c.code);throw new U(V.UNEXPECTED_RESPONSE,e.desc)}return c}Object.keys(ie[j.GLOBAL]),j.CHINA,j.NORTH_AMERICA,j.EUROPE,j.ASIA,j.JAPAN,j.INDIA,j.OCEANIA,j.SOUTH_AMERICA,j.AFRICA,j.KOREA,j.HKMC,j.US;class _e extends c{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:w,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:w;super(),this.onLiveStreamWarning=void 0,this.onLiveStreamError=void 0,this.spec=void 0,this.retryTimeout=1e4,this.connection=void 0,this.httpRetryConfig=void 0,this.wsRetryConfig=void 0,this.streamingTasks=new Map,this.isStartingStreamingTask=!1,this.taskMutex=new R("live-streaming"),this.cancelToken=P.CancelToken.source(),this.transcodingConfig=void 0,this.uapResponse=void 0,this.lastTaskId=1,this.statusError=new Map,this.spec=e,this.httpRetryConfig=s,this.wsRetryConfig=t}async setTranscodingConfig(e){const t=v(v({},J),e);66!==t.videoCodecProfile&&77!==t.videoCodecProfile&&100!==t.videoCodecProfile&&(M.debug("[".concat(this.spec.clientId,"] set transcoding config, fix video codec profile: ").concat(t.videoCodecProfile," -> 100")),t.videoCodecProfile=100),t.transcodingUsers||(t.transcodingUsers=t.userConfigs),t.transcodingUsers&&(t.transcodingUsers=t.transcodingUsers.map((e=>v(v(v({},Y),e),{},{zOrder:e.zOrder?e.zOrder+1:1})))),function(e){s(e.width)||n(e.width,"config.width",0,1e4),s(e.height)||n(e.height,"config.height",0,1e4),s(e.videoBitrate)||n(e.videoBitrate,"config.videoBitrate",1,1e6),s(e.videoFrameRate)||n(e.videoFrameRate,"config.videoFrameRate"),s(e.lowLatency)||E(e.lowLatency,"config.lowLatency"),s(e.audioSampleRate)||r(e.audioSampleRate,"config.audioSampleRate",[32e3,44100,48e3]),s(e.audioBitrate)||n(e.audioBitrate,"config.audioBitrate",1,128),s(e.audioChannels)||r(e.audioChannels,"config.audioChannels",[1,2,3,4,5]),s(e.videoGop)||n(e.videoGop,"config.videoGop"),s(e.videoCodecProfile)||r(e.videoCodecProfile,"config.videoCodecProfile",[66,77,100]),s(e.userCount)||n(e.userCount,"config.userCount",0,17),s(e.backgroundColor)||n(e.backgroundColor,"config.backgroundColor",0,16777215),s(e.userConfigExtraInfo)||i(e.userConfigExtraInfo,"config.userConfigExtraInfo",0,4096,!1),e.transcodingUsers&&!s(e.transcodingUsers)&&(o(e.transcodingUsers,"config.transcodingUsers"),e.transcodingUsers.forEach(((e,t)=>{G(e.uid),s(e.x)||n(e.x,"transcodingUser[".concat(t,"].x"),0,1e4),s(e.y)||n(e.y,"transcodingUser[".concat(t,"].y"),0,1e4),s(e.width)||n(e.width,"transcodingUser[".concat(t,"].width"),0,1e4),s(e.height)||n(e.height,"transcodingUser[".concat(t,"].height"),0,1e4),s(e.zOrder)||n(e.zOrder-1,"transcodingUser[".concat(t,"].zOrder"),0,100),s(e.alpha)||n(e.alpha,"transcodingUser[".concat(t,"].alpha"),0,1,!1)}))),s(e.watermark)||x(e.watermark,"watermark"),s(e.backgroundImage)||x(e.backgroundImage,"backgroundImage"),e.images&&!s(e.images)&&(o(e.images,"config.images"),e.images.forEach(((e,t)=>{x(e,"images[".concat(t,"]"))})))}(t);const _=[];t.images&&_.push(...t.images.map((e=>v(v(v({},F),e),{},{zOrder:255})))),t.backgroundImage&&(_.push(v(v(v({},F),t.backgroundImage),{},{zOrder:0})),delete t.backgroundImage),t.watermark&&(_.push(v(v(v({},F),t.watermark),{},{zOrder:255})),delete t.watermark),t.images=_,t.transcodingUsers&&(t.userConfigs=t.transcodingUsers.map((e=>v({},e))),t.userCount=t.transcodingUsers.length,delete t.transcodingUsers);const c=(t.userConfigs||[]).map((e=>"number"==typeof e.uid?Promise.resolve(e.uid):async function(e,t,s,n,E){const r=S("ACCOUNT_REGISTER").slice(0,S("AJAX_REQUEST_CONCURRENT"));let i=[];i=t.proxyServer?r.map((e=>"https://".concat(t.proxyServer,"/ap/?url=").concat(e+"/api/v1"))):r.map((e=>"https://".concat(e,"/api/v1")));const o=null==E?void 0:E.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"stringUID",urls:i});try{const r=await oe(i,e,t,s,n);return null==E||E.recordJoinChannelService({status:"success",endTs:Date.now()},o),r.uid}catch(e){throw null==E||E.recordJoinChannelService({status:"error",endTs:Date.now(),errors:[e]},o),e}}(e.uid,this.spec,this.cancelToken.token,this.httpRetryConfig)));if((await Promise.all(c)).forEach(((e,s)=>{t.userConfigs&&t.userConfigs[s]&&(t.userConfigs[s].uid=e)})),this.transcodingConfig=t,this.connection)try{const e=await this.connection.request("request",{clientRequest:{command:"UpdateTranscoding",transcodingConfig:this.transcodingConfig}},!1,{command:"UpdateTranscoding",workerType:1,requestByUser:!0,tid:Array.from(this.streamingTasks.values()).map((e=>e.taskId)).join("#")});M.debug("[".concat(this.spec.clientId,"] update live transcoding config success, code: ").concat(e.code,", config:"),JSON.stringify(this.transcodingConfig))}catch(e){if(!e.data||!e.data.retry)throw e;e.data.changeAddress&&this.connection.tryNextAddress(),this.streamingTasks.forEach((t=>{M.warning("[".concat(this.spec.clientId,"] live streaming receive error"),e.toString(),"try to republish",t.url),this.startLiveStreamingTask(t.url,t.mode,e).then((()=>{M.debug("[".concat(this.spec.clientId,"] live streaming republish ").concat(t.url," success"))})).catch((e=>{M.error("[".concat(this.spec.clientId,"] live streaming republish failed"),t.url,e.toString()),this.onLiveStreamError&&this.onLiveStreamError(t.url,e)}))}))}}async startLiveStreamingTask(e,t,s){if(!this.transcodingConfig&&t===K.TRANSCODE)throw new U(V.INVALID_OPERATION,"[LiveStreaming] no transcoding config found, can not start transcoding streaming task");const n={command:"PublishStream",ts:Date.now(),url:e,uid:this.spec.uid.toString(),autoDestroyTime:100,acceptImageTimeout:!0};M.debug("[".concat(this.spec.clientId,"] start live streaming ").concat(e,", mode: ").concat(t));const E=await this.taskMutex.lock();if(!this.connection&&s)return void E();if(this.streamingTasks.get(e)&&!s)return E(),new U(V.LIVE_STREAMING_TASK_CONFLICT).throw();try{this.connection||(this.connection=await this.connect(t))}catch(e){throw E(),e}switch(t){case K.TRANSCODE:n.transcodingConfig=v({},this.transcodingConfig);case K.RAW:}this.uapResponse&&this.uapResponse.vid&&(n.vid=this.uapResponse.vid),this.isStartingStreamingTask=!0;const r=this.lastTaskId++;try{const i=new Promise(((t,n)=>{h(this.retryTimeout).then((()=>{if(s)return n(s);const t=this.statusError.get(e);return t?(this.statusError.delete(e),n(t)):void 0}))})),o=await Promise.race([this.connection.request("request",{clientRequest:n},!0,{url:e,command:"PublishStream",workerType:t===K.TRANSCODE?1:2,requestByUser:!s,tid:r.toString()}),i]);this.isStartingStreamingTask=!1,M.debug("[".concat(this.spec.clientId,"] live streaming started, code: ").concat(o.code)),this.streamingTasks.set(e,{clientRequest:n,mode:t,url:e,taskId:r}),E()}catch(n){if(E(),this.isStartingStreamingTask=!1,!n.data||!n.data.retry||s)throw n;return n.data.changeAddress?(this.connection.tryNextAddress(),await this.startLiveStreamingTask(e,t,n)):await this.startLiveStreamingTask(e,t,n)}}stopLiveStreamingTask(e){return new Promise(((t,s)=>{const n=this.streamingTasks.get(e);if(!n||!this.connection)return new U(V.UNEXPECTED_ERROR,"can not find streaming task to stop").throw();const E=n.mode;n.abortTask=()=>{M.debug("[".concat(this.spec.clientId,"] stop live streaming success(worker exception)")),this.streamingTasks.delete(e),t()},this.connection.request("request",{clientRequest:{command:"UnpublishStream",url:n.url}},!1,{url:e,command:"UnPublishStream",workerType:E===K.TRANSCODE?1:2,requestByUser:!0,tid:(this.lastTaskId++).toString()}).then((s=>{M.debug("[".concat(this.spec.clientId,"] stop live streaming success, code: ").concat(s.code)),this.streamingTasks.delete(e),0===this.streamingTasks.size&&(this.connection&&this.connection.close(),this.connection=void 0),t()})).catch(s)}))}resetAllTask(){const e=Array.from(this.streamingTasks.values());this.terminate();for(const t of e)this.startLiveStreamingTask(t.url,t.mode).catch((e=>{this.onLiveStreamError&&this.onLiveStreamError(t.url,e)}))}terminate(){this.cancelToken&&this.cancelToken.cancel(),this.streamingTasks=new Map,this.isStartingStreamingTask=!1,this.statusError=new Map,this.cancelToken=P.CancelToken.source(),this.uapResponse=void 0,this.connection&&this.connection.close(),this.connection=void 0}async connect(e){if(this.connection)throw new U(V.UNEXPECTED_ERROR,"live streaming connection has already connected");const t=await O(this,X.REQUEST_WORKER_MANAGER_LIST,e);return this.uapResponse=t,this.connection=new te(t.workerToken,this.spec,this.wsRetryConfig,e),this.connection.on(q.WARNING,((e,t)=>this.onLiveStreamWarning&&this.onLiveStreamWarning(t,e))),this.connection.on(q.PUBLISH_STREAM_STATUS,(e=>this.handlePublishStreamServer(e))),this.connection.on(q.REQUEST_NEW_ADDRESS,((t,s)=>{if(!this.connection)return s(new U(V.UNEXPECTED_ERROR,"can not get new live streaming address list"));O(this,X.REQUEST_WORKER_MANAGER_LIST,e).then((e=>{this.uapResponse=e,t(e.addressList)})).catch(s)})),await this.connection.init(t.addressList),this.connection}handlePublishStreamServer(e){const t=e.serverStatus&&e.serverStatus.url||"empty_url",s=this.streamingTasks.get(t),n=e.reason;switch(e.code){case Q.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case Q.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case Q.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case Q.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:{const n=new U(V.LIVE_STREAMING_CDN_ERROR,"",{code:e.code});if(s)return M.error(n.toString()),this.onLiveStreamError&&this.onLiveStreamError(t,n);if(!this.isStartingStreamingTask)return;this.statusError.set(t,n)}case Q.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const e=new U(V.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE,n);return this.onLiveStreamWarning&&this.onLiveStreamWarning(t,e)}case Q.LIVE_STREAM_RESPONSE_WORKER_LOST:case Q.LIVE_STREAM_RESPONSE_WORKER_QUIT:{if(!this.connection)return;this.connection.tryNextAddress();const t=Array.from(this.streamingTasks.values());for(const s of t)s.abortTask?s.abortTask():(M.warning("[".concat(this.spec.clientId,"] publish stream status code"),e.code,"try to republish",s.url),this.startLiveStreamingTask(s.url,s.mode,new U(V.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:e.code})).then((()=>{M.debug("[".concat(this.spec.clientId,"] republish live stream success"),s.url)})).catch((e=>{M.error(e.toString()),this.onLiveStreamError&&this.onLiveStreamError(s.url,e)})));return}}}hasUrl(e){return this.streamingTasks.has(e)}}const ce={name:"LiveStreaming",create:function(e){return new _e(e.joinInfo,e.websocketRetryConfig||w,e.httpRetryConfig||w)}};export{ce as LiveStreamingService}; |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
3773823
26719
+ Added@agora-js/media@4.22.1(transitive)
+ Added@agora-js/report@4.22.1(transitive)
+ Added@agora-js/shared@4.22.1(transitive)
- Removed@agora-js/media@4.22.0(transitive)
- Removed@agora-js/report@4.22.0(transitive)
- Removed@agora-js/shared@4.22.0(transitive)
Updated@agora-js/media@4.22.1
Updated@agora-js/report@4.22.1
Updated@agora-js/shared@4.22.1
Updatedaxios@^1.7.7