nim-web-sdk-ng
Version:
Yunxin IM SDK next generation
16 lines • 325 kB
JavaScript
/**
*
* Version: 10.9.41
*
* Git Hash: 5b4fa64fd28f6f2c4dc5e957f39887f24696a2ae
*
* Created At: 8/14/2025, 7:20:32 AM
*
* Target: CHATROOM_MINIAPP_SDK.js
*
*/
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).Chatroom={})}(this,(function(e){"use strict";function __rest(e,t){var r={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(r[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(o=Object.getOwnPropertySymbols(e);i<o.length;i++)t.indexOf(o[i])<0&&Object.prototype.propertyIsEnumerable.call(e,o[i])&&(r[o[i]]=e[o[i]])}return r}function __awaiter(e,t,r,o){return new(r||(r=Promise))((function(i,n){function fulfilled(e){try{step(o.next(e))}catch(e){n(e)}}function rejected(e){try{step(o.throw(e))}catch(e){n(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof r?e:new r((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))}"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;function createCommonjsModule(e){var t={exports:{}};return e(t,t.exports),t.exports}var t=createCommonjsModule((function(e,t){e.exports=function(){function _regeneratorRuntime(){
/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
_regeneratorRuntime=function(){return e};var e={},t=Object.prototype,r=t.hasOwnProperty,o="function"==typeof Symbol?Symbol:{},i=o.iterator||"@@iterator",n=o.asyncIterator||"@@asyncIterator",s=o.toStringTag||"@@toStringTag";function define(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{define({},"")}catch(e){define=function(e,t,r){return e[t]=r}}function wrap(e,t,r,o){var i=t&&t.prototype instanceof Generator?t:Generator,n=Object.create(i.prototype),s=new Context(o||[]);return n._invoke=function(e,t,r){var o="suspendedStart";return function(i,n){if("executing"===o)throw new Error("Generator is already running");if("completed"===o){if("throw"===i)throw n;return doneResult()}for(r.method=i,r.arg=n;;){var s=r.delegate;if(s){var c=maybeInvokeDelegate(s,r);if(c){if(c===a)continue;return c}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if("suspendedStart"===o)throw o="completed",r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);o="executing";var l=tryCatch(e,t,r);if("normal"===l.type){if(o=r.done?"completed":"suspendedYield",l.arg===a)continue;return{value:l.arg,done:r.done}}"throw"===l.type&&(o="completed",r.method="throw",r.arg=l.arg)}}}(e,r,s),n}function tryCatch(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}e.wrap=wrap;var a={};function Generator(){}function GeneratorFunction(){}function GeneratorFunctionPrototype(){}var c={};define(c,i,(function(){return this}));var l=Object.getPrototypeOf,_=l&&l(l(values([])));_&&_!==t&&r.call(_,i)&&(c=_);var d=GeneratorFunctionPrototype.prototype=Generator.prototype=Object.create(c);function defineIteratorMethods(e){["next","throw","return"].forEach((function(t){define(e,t,(function(e){return this._invoke(t,e)}))}))}function AsyncIterator(e,t){function invoke(o,i,n,s){var a=tryCatch(e[o],e,i);if("throw"!==a.type){var c=a.arg,l=c.value;return l&&"object"==typeof l&&r.call(l,"__await")?t.resolve(l.__await).then((function(e){invoke("next",e,n,s)}),(function(e){invoke("throw",e,n,s)})):t.resolve(l).then((function(e){c.value=e,n(c)}),(function(e){return invoke("throw",e,n,s)}))}s(a.arg)}var o;this._invoke=function(e,r){function callInvokeWithMethodAndArg(){return new t((function(t,o){invoke(e,r,t,o)}))}return o=o?o.then(callInvokeWithMethodAndArg,callInvokeWithMethodAndArg):callInvokeWithMethodAndArg()}}function maybeInvokeDelegate(e,t){var r=e.iterator[t.method];if(void 0===r){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=void 0,maybeInvokeDelegate(e,t),"throw"===t.method))return a;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method")}return a}var o=tryCatch(r,e.iterator,t.arg);if("throw"===o.type)return t.method="throw",t.arg=o.arg,t.delegate=null,a;var i=o.arg;return i?i.done?(t[e.resultName]=i.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,a):i:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,a)}function pushTryEntry(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function resetTryEntry(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function Context(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(pushTryEntry,this),this.reset(!0)}function values(e){if(e){var t=e[i];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,n=function next(){for(;++o<e.length;)if(r.call(e,o))return next.value=e[o],next.done=!1,next;return next.value=void 0,next.done=!0,next};return n.next=n}}return{next:doneResult}}function doneResult(){return{value:void 0,done:!0}}return GeneratorFunction.prototype=GeneratorFunctionPrototype,define(d,"constructor",GeneratorFunctionPrototype),define(GeneratorFunctionPrototype,"constructor",GeneratorFunction),GeneratorFunction.displayName=define(GeneratorFunctionPrototype,s,"GeneratorFunction"),e.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===GeneratorFunction||"GeneratorFunction"===(t.displayName||t.name))},e.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,GeneratorFunctionPrototype):(e.__proto__=GeneratorFunctionPrototype,define(e,s,"GeneratorFunction")),e.prototype=Object.create(d),e},e.awrap=function(e){return{__await:e}},defineIteratorMethods(AsyncIterator.prototype),define(AsyncIterator.prototype,n,(function(){return this})),e.AsyncIterator=AsyncIterator,e.async=function(t,r,o,i,n){void 0===n&&(n=Promise);var s=new AsyncIterator(wrap(t,r,o,i),n);return e.isGeneratorFunction(r)?s:s.next().then((function(e){return e.done?e.value:s.next()}))},defineIteratorMethods(d),define(d,s,"Generator"),define(d,i,(function(){return this})),define(d,"toString",(function(){return"[object Generator]"})),e.keys=function(e){var t=[];for(var r in e)t.push(r);return t.reverse(),function next(){for(;t.length;){var r=t.pop();if(r in e)return next.value=r,next.done=!1,next}return next.done=!0,next}},e.values=values,Context.prototype={constructor:Context,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(resetTryEntry),!e)for(var t in this)"t"===t.charAt(0)&&r.call(this,t)&&!isNaN(+t.slice(1))&&(this[t]=void 0)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var t=this;function handle(r,o){return n.type="throw",n.arg=e,t.next=r,o&&(t.method="next",t.arg=void 0),!!o}for(var o=this.tryEntries.length-1;o>=0;--o){var i=this.tryEntries[o],n=i.completion;if("root"===i.tryLoc)return handle("end");if(i.tryLoc<=this.prev){var s=r.call(i,"catchLoc"),a=r.call(i,"finallyLoc");if(s&&a){if(this.prev<i.catchLoc)return handle(i.catchLoc,!0);if(this.prev<i.finallyLoc)return handle(i.finallyLoc)}else if(s){if(this.prev<i.catchLoc)return handle(i.catchLoc,!0)}else{if(!a)throw new Error("try statement without catch or finally");if(this.prev<i.finallyLoc)return handle(i.finallyLoc)}}}},abrupt:function(e,t){for(var o=this.tryEntries.length-1;o>=0;--o){var i=this.tryEntries[o];if(i.tryLoc<=this.prev&&r.call(i,"finallyLoc")&&this.prev<i.finallyLoc){var n=i;break}}n&&("break"===e||"continue"===e)&&n.tryLoc<=t&&t<=n.finallyLoc&&(n=null);var s=n?n.completion:{};return s.type=e,s.arg=t,n?(this.method="next",this.next=n.finallyLoc,a):this.complete(s)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),a},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),resetTryEntry(r),a}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var o=r.completion;if("throw"===o.type){var i=o.arg;resetTryEntry(r)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,r){return this.delegate={iterator:values(e),resultName:t,nextLoc:r},"next"===this.method&&(this.arg=void 0),a}},e}function _typeof(e){return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof(e)}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,t){for(var r=0;r<t.length;r++){var o=t[r];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}function _createClass(e,t,r){return t&&_defineProperties(e.prototype,t),r&&_defineProperties(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function __awaiter(e,t,r,o){function adopt(e){return e instanceof r?e:new r((function(t){t(e)}))}return new(r||(r=Promise))((function(r,i){function fulfilled(e){try{step(o.next(e))}catch(e){i(e)}}function rejected(e){try{step(o.throw(e))}catch(e){i(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))}var e={isDataReportEnable:!0,maxSize:100,msgListMaxSize:1e3,cacheMaxSize:1e3,maxDelay:3e5,maxInterval:3e4,minInterval:1e4,timeout:5e3,autoStart:!0,loginFailIgnoreInterval:72e5},t=12,r=8e3,o=function emptyFn(){},i=function(){function Reporter(t){_classCallCheck(this,Reporter),this.isUploadEnable=!0,this.serverAllowUpload=!1,this.initConfigLoaded=!1,this.loading=!1,this.isDestroyed=!1,this.reportConfig=e,this.configPath="dispatcher/req",this.dataReportPath="statics/report/common/form",this.traceMsgCache={},this.reqRetryCount=0,this.highPriorityMsgList=[],this.msgList=[],this.lowPriorityMsgList=[],this.cacheMsgList=[],this.lastReportTime=Date.now(),this.timer=null,this.endedAsyncMsgByModule={},this.lastFailLogin={},this.setConfig(t),this.reportConfig.isDataReportEnable&&this.reportConfig.autoStart&&this.initUploadConfig()}return _createClass(Reporter,[{key:"setConfig",value:function setConfig(e){var t=Object.assign({},this.reportConfig.common,e.common);this.reportConfig=Object.assign({},this.reportConfig,e),this.reportConfig.common=t,this.reportConfig.common.sdk_type||(this.reportConfig.common.sdk_type="im")}},{key:"reportImmediately",value:function reportImmediately(e,t){var r=this;this.reportConfig.isDataReportEnable&&this.reportConfig.request(e,Object.assign({dataType:"json",method:"POST",timeout:this.reportConfig.timeout},t)).catch((function(e){var t,o;null===(o=null===(t=r.reportConfig)||void 0===t?void 0:t.logger)||void 0===o||o.warn("Reporter immediately upload failed",e)}))}},{key:"report",value:function report(t,r){var o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(o.priority||(o.priority=this.getEventPriority(t,r)),this.reportConfig.isDataReportEnable&&t){if("login"===t&&!1===r.succeed&&r.process_id){var i=r.extension&&r.extension.find((function(e){return"TCP"===e.operation_type})),n=i&&i.target||"",s=r.process_id+n,a=this.lastFailLogin[s]||0;if(r.start_time-a<e.loginFailIgnoreInterval)return;this.lastFailLogin[s]=r.start_time}var c=Date.now();"HIGH"===o.priority?this.highPriorityMsgList.push({module:t,msg:r,createTime:c}):"NORMAL"===o.priority?this.msgList.push({module:t,msg:r,createTime:c}):"LOW"===o.priority&&this.lowPriorityMsgList.push({module:t,msg:r,createTime:c}),this.highPriorityMsgList.length>this.reportConfig.msgListMaxSize&&this.highPriorityMsgList.shift(),this.msgList.length>this.reportConfig.msgListMaxSize&&this.msgList.shift(),this.lowPriorityMsgList.length>this.reportConfig.msgListMaxSize&&this.lowPriorityMsgList.shift(),this.doReport()}}},{key:"reportTraceStart",value:function reportTraceStart(e,t){if(this.reportConfig.isDataReportEnable&&e&&!this.traceMsgCache[e]){var r=Object.assign(Object.assign({start_time:Date.now()},t),{extension:[]});this.traceMsgCache[e]=r}}},{key:"reportTraceUpdate",value:function reportTraceUpdate(e){}},{key:"reportTraceUpdateV2",value:function reportTraceUpdateV2(e,t,r){var o,i=this;if(this.reportConfig.isDataReportEnable&&this.traceMsgCache[e]){var n=this.traceMsgCache[e].extension,s=n.length,a=(new Date).getTime();0===s?t.duration=a-this.traceMsgCache[e].start_time:n[s-1].end_time?t.duration=a-n[s-1].end_time:t.duration=a-this.traceMsgCache[e].start_time,n.push(Object.assign({end_time:a},t));var c=n.length-1;(null==r?void 0:r.asyncParams)&&((o=this.traceMsgCache[e]).asyncPromiseArray||(o.asyncPromiseArray=[]),this.traceMsgCache[e].asyncPromiseArray.push(r.asyncParams.then((function(t){i.traceMsgCache[e]&&i.traceMsgCache[e].extension[c]&&Object.assign(i.traceMsgCache[e].extension[c],t)}))))}}},{key:"reportTraceEnd",value:function reportTraceEnd(e){var t,r=this,o=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(this.reportConfig.isDataReportEnable&&this.traceMsgCache[e])if("nos"!==e||!1===o){"boolean"==typeof o?this.traceMsgCache[e].succeed=!!o:this.traceMsgCache[e].state=o,this.traceMsgCache[e].duration=Date.now()-this.traceMsgCache[e].start_time,this.traceMsgCache[e].extension.forEach((function(e){delete e.end_time}));var i=this.traceMsgCache[e];if(this.traceMsgCache[e]=null,i.asyncPromiseArray){(t=this.endedAsyncMsgByModule)[e]||(t[e]=[]),this.endedAsyncMsgByModule[e].push(i);var n=function asyncCallback(){r.endedAsyncMsgByModule[e]&&r.endedAsyncMsgByModule[e].includes(i)&&(delete i.asyncPromiseArray,r.report(e,i,{priority:r.getEventPriority(e,i)}))};Promise.all(i.asyncPromiseArray).then(n).catch(n)}else this.report(e,i,{priority:this.getEventPriority(e,i)})}else this.traceMsgCache[e]=null}},{key:"getEventPriority",value:function getEventPriority(e,t){if("exceptions"===e){if(0===t.action)return"HIGH";if(2===t.action)return"HIGH";if(1===t.action&&0!==t.exception_service)return"HIGH"}else{if("msgReceive"===e)return"LOW";if("nim_api_trace"===e)return"LOW"}return"NORMAL"}},{key:"reportTraceCancel",value:function reportTraceCancel(e){this.reportConfig.isDataReportEnable&&(this.endedAsyncMsgByModule[e]=[],this.traceMsgCache[e]=null)}},{key:"pause",value:function pause(){this.reportConfig.isDataReportEnable&&(this.isUploadEnable=!1)}},{key:"restore",value:function restore(){this.reportConfig.isDataReportEnable&&(this.isUploadEnable=!0,this.initConfigLoaded||this.initUploadConfig())}},{key:"destroy",value:function destroy(){var e=this;this.reportConfig.isDataReportEnable&&(Object.keys(this.traceMsgCache).forEach((function(t){e.reportTraceEnd(t,1)})),null!==this.timer&&clearTimeout(this.timer),this.setConfig=o,this.report=o,this.reportTraceStart=o,this.reportTraceUpdate=o,this.reportTraceEnd=o,this.pause=o,this.restore=o,this.destroy=o,this.reqRetryCount=0,this.cacheMsgList=[],this.traceMsgCache={},this.lowPriorityMsgList=[],this.msgList=[],this.highPriorityMsgList=[],this.reportConfig={},this.isDestroyed=!0)}},{key:"initUploadConfig",value:function initUploadConfig(){var e,o;return __awaiter(this,void 0,void 0,_regeneratorRuntime().mark((function _callee(){var i,n,s,a,c,l=this;return _regeneratorRuntime().wrap((function _callee$(_){for(;;)switch(_.prev=_.next){case 0:if(!this.loading){_.next=2;break}return _.abrupt("return");case 2:this.loading=!0,i=this.reportConfig.common||{},n=this.reportConfig.compassDataEndpoint.split(",").map((function(e){return"".concat(e,"/").concat(l.configPath)})),s=_regeneratorRuntime().mark((function _loop(s){return _regeneratorRuntime().wrap((function _loop$(a){for(;;)switch(a.prev=a.next){case 0:if(!l.initConfigLoaded&&!l.isDestroyed){a.next=2;break}return a.abrupt("return","break");case 2:return a.prev=2,a.next=5,l.reportConfig.request(n[s],{method:"GET",dataType:"json",params:{deviceId:i.dev_id,sdkVer:i.sdk_ver,platform:i.platform,hostEnv:i.host_env,appkey:i.app_key},timeout:l.reportConfig.timeout}).then((function(e){var t,r;if(!l.isDestroyed){if(200===e.status&&e.data&&200===e.data.code){l.initConfigLoaded=!0;var o=e.data.data||{};l.reportConfig.maxSize=o.maxSize>1e3?1e3:o.maxSize,l.reportConfig.maxInterval=o.maxInterval>1e4?1e4:o.maxInterval,l.reportConfig.maxInterval=o.maxInterval<10?10:o.maxInterval,l.reportConfig.minInterval=o.minInterval<2?2:o.minInterval,l.reportConfig.maxDelay=o.maxDelay||300,l.reportConfig.maxInterval=1e3*l.reportConfig.maxInterval,l.reportConfig.minInterval=1e3*l.reportConfig.minInterval,l.reportConfig.maxDelay=1e3*l.reportConfig.maxDelay,o.endpoint?l.dataReportEndpoint=o.endpoint:l.dataReportEndpoint=n[s],l.serverAllowUpload=!0,l.loading=!1,l.reportHeartBeat()}else 200===e.status&&(l.initConfigLoaded=!0);null===(r=null===(t=l.reportConfig)||void 0===t?void 0:t.logger)||void 0===r||r.log("Get reporter upload config success")}})).catch((function(e){var o,i;l.isDestroyed||(l.loading=!1,null===(i=null===(o=l.reportConfig)||void 0===o?void 0:o.logger)||void 0===i||i.error("Get reporter upload config failed",e),l.reqRetryCount<t&&(l.reqRetryCount++,setTimeout((function(){l.isDestroyed||l.initUploadConfig()}),r)))}));case 5:a.next=14;break;case 7:if(a.prev=7,a.t0=a.catch(2),!l.isDestroyed){a.next=11;break}return a.abrupt("return",{v:void 0});case 11:l.loading=!1,null===(o=null===(e=l.reportConfig)||void 0===e?void 0:e.logger)||void 0===o||o.error("Exec reporter request failed",a.t0),l.reqRetryCount<t&&(l.reqRetryCount++,setTimeout((function(){l.isDestroyed||l.initUploadConfig()}),r));case 14:case"end":return a.stop()}}),_loop,null,[[2,7]])})),a=0;case 7:if(!(a<n.length)){_.next=17;break}return _.delegateYield(s(a),"t0",9);case 9:if("break"!==(c=_.t0)){_.next=12;break}return _.abrupt("break",17);case 12:if("object"!==_typeof(c)){_.next=14;break}return _.abrupt("return",c.v);case 14:a++,_.next=7;break;case 17:case"end":return _.stop()}}),_callee,this)})))}},{key:"reportHeartBeat",value:function reportHeartBeat(){var e=this;this.isDestroyed||(this.timer=setTimeout((function(){e.reportHeartBeat()}),this.reportConfig.minInterval),this.doReport())}},{key:"doReport",value:function doReport(){if(!this.isDestroyed){var e=this.highPriorityMsgList.length+this.msgList.length+this.lowPriorityMsgList.length+this.cacheMsgList.length>2*this.reportConfig.maxSize?this.reportConfig.minInterval:this.reportConfig.maxInterval;Date.now()-this.lastReportTime>=e&&this.upload()}}},{key:"getUploadMsg",value:function getUploadMsg(){var e=this,t={},r=Date.now();this.highPriorityMsgList=this.highPriorityMsgList.filter((function(t){return r-t.createTime<e.reportConfig.maxDelay})),this.msgList=this.msgList.filter((function(t){return r-t.createTime<e.reportConfig.maxDelay})),this.lowPriorityMsgList=this.lowPriorityMsgList.filter((function(t){return r-t.createTime<e.reportConfig.maxDelay})),this.cacheMsgList=this.cacheMsgList.filter((function(t){return r-t.createTime<e.reportConfig.maxDelay}));var o=this.highPriorityMsgList.slice(0,this.reportConfig.maxSize);if(this.highPriorityMsgList=this.highPriorityMsgList.slice(o.length),o.length<this.reportConfig.maxSize){var i=this.reportConfig.maxSize-o.length;o=o.concat(this.msgList.slice(0,i)),this.msgList=this.msgList.slice(i)}if(o.length<this.reportConfig.maxSize){var n=this.reportConfig.maxSize-o.length;o=o.concat(this.lowPriorityMsgList.slice(0,n)),this.lowPriorityMsgList=this.lowPriorityMsgList.slice(n)}if(o.length<this.reportConfig.maxSize){var s=this.reportConfig.maxSize-o.length;o=o.concat(this.cacheMsgList.slice(0,s)),this.cacheMsgList=this.cacheMsgList.slice(s)}return o.forEach((function(e){t[e.module]?t[e.module].push(e.msg):t[e.module]=[e.msg]})),{uploadMsgArr:o,uploadMsg:t}}},{key:"upload",value:function upload(){var e,t,r=this;if(this.isUploadEnable&&this.serverAllowUpload&&!(this.lastReportTime&&Date.now()-this.lastReportTime<this.reportConfig.minInterval)){var o=this.getUploadMsg(),i=o.uploadMsgArr,n=o.uploadMsg;if(i.length){this.lastReportTime=Date.now();try{var s="".concat(this.dataReportEndpoint,"/").concat(this.dataReportPath);this.reportConfig.request(s,{dataType:"json",method:"POST",data:{common:this.reportConfig.common,event:n},headers:{sdktype:"im"},timeout:this.reportConfig.timeout}).catch((function(e){var t,o;r.cacheMsgList=r.cacheMsgList.concat(i).slice(0,r.reportConfig.cacheMaxSize),null===(o=null===(t=r.reportConfig)||void 0===t?void 0:t.logger)||void 0===o||o.warn("Reporter upload failed",e)}))}catch(r){null===(t=null===(e=this.reportConfig)||void 0===e?void 0:e.logger)||void 0===t||t.warn("Exec reporter request failed",r)}clearTimeout(this.timer),this.reportHeartBeat()}}}}]),Reporter}();return i}()}));function isPlainObject(e){return null!=e&&"object"==typeof e&&Object.getPrototypeOf(e)==Object.prototype}function merge(e,t){var r=isPlainObject(e)||Array.isArray(e),o=isPlainObject(t)||Array.isArray(t);if(r&&o){for(var i in t){var n=merge(e[i],t[i]);void 0!==n&&(e[i]=n)}return e}return t}var r={getNetworkStatus:()=>Promise.resolve({net_type:0,net_connect:!0}),onNetworkStatusChange(e){},offNetworkStatusChange(){}},o={isActive:()=>!0,getStatus:()=>0,setStatus(e){},destroy(){}};var i,n,s,a,c,l,_,d,E,h,u,m,g,p,I,N,T,O,M,f,S,R,C,A,v,y,D,V,L,b,P,k,w,U,x,G,B,H,Y,$,j,K,q,W,z,J,Q,X,Z,ee,te,re,oe,ie,ne,se,ae={setLogger:function(e){throw new Error("setLogger not implemented.")},platform:"",WebSocket:class AdapterSocket{constructor(e,t){throw this.CONNECTING=0,this.OPEN=1,this.CLOSING=2,this.CLOSED=3,this.binaryType="",new Error("Method not implemented.")}close(e,t){throw new Error("Method not implemented.")}send(e){throw new Error("Method not implemented.")}onclose(e){throw new Error("Method not implemented.")}onerror(e){throw new Error("Method not implemented.")}onmessage(e){throw new Error("Method not implemented.")}onopen(e){throw new Error("Method not implemented.")}},localStorage:{},request:function(e,t){throw new Error("request not implemented.")},uploadFile:function(e){throw new Error("uploadFile not implemented.")},getSystemInfo:function(){throw new Error("getSystemInfo not implemented.")},getFileUploadInformation(e){throw new Error("getFileUploadInformation not implemented.")},envPayload:{},net:r,powerMonitor:o,logStorage:class AdapterLogStorageImpl{constructor(e){}open(){return Promise.resolve()}close(){}addLogs(e){return Promise.resolve()}extractLogs(){return Promise.resolve()}afterUpload(){return Promise.resolve()}}};!function(e){e[e.V2NIM_DATA_SYNC_TYPE_LEVEL_FULL=0]="V2NIM_DATA_SYNC_TYPE_LEVEL_FULL",e[e.V2NIM_DATA_SYNC_TYPE_LEVEL_BASIC=1]="V2NIM_DATA_SYNC_TYPE_LEVEL_BASIC"}(i||(i={})),function(e){e[e.V2NIM_DATA_SYNC_TYPE_MAIN=1]="V2NIM_DATA_SYNC_TYPE_MAIN",e[e.V2NIM_DATA_SYNC_TYPE_TEAM_MEMBER=2]="V2NIM_DATA_SYNC_TYPE_TEAM_MEMBER",e[e.V2NIM_DATA_SYNC_TYPE_SUPER_TEAM_MEMBER=3]="V2NIM_DATA_SYNC_TYPE_SUPER_TEAM_MEMBER"}(n||(n={})),function(e){e[e.V2NIM_DATA_SYNC_STATE_WAITING=1]="V2NIM_DATA_SYNC_STATE_WAITING",e[e.V2NIM_DATA_SYNC_STATE_SYNCING=2]="V2NIM_DATA_SYNC_STATE_SYNCING",e[e.V2NIM_DATA_SYNC_STATE_COMPLETED=3]="V2NIM_DATA_SYNC_STATE_COMPLETED"}(s||(s={})),function(e){e[e.V2NIM_CONVERSATION_TYPE_UNKNOWN=0]="V2NIM_CONVERSATION_TYPE_UNKNOWN",e[e.V2NIM_CONVERSATION_TYPE_P2P=1]="V2NIM_CONVERSATION_TYPE_P2P",e[e.V2NIM_CONVERSATION_TYPE_TEAM=2]="V2NIM_CONVERSATION_TYPE_TEAM",e[e.V2NIM_CONVERSATION_TYPE_SUPER_TEAM=3]="V2NIM_CONVERSATION_TYPE_SUPER_TEAM"}(a||(a={})),function(e){e[e.V2NIM_MESSAGE_STATUS_DEFAULT=0]="V2NIM_MESSAGE_STATUS_DEFAULT",e[e.V2NIM_MESSAGE_STATUS_REVOKE=1]="V2NIM_MESSAGE_STATUS_REVOKE",e[e.V2NIM_MESSAGE_STATUS_BACKFILL=2]="V2NIM_MESSAGE_STATUS_BACKFILL"}(c||(c={})),function(e){e[e.V2NIM_FRIEND_MODE_TYPE_ADD=1]="V2NIM_FRIEND_MODE_TYPE_ADD",e[e.V2NIM_FRIEND_MODE_TYPE_APPLY=2]="V2NIM_FRIEND_MODE_TYPE_APPLY"}(l||(l={})),function(e){e[e.V2NIM_FRIEND_ADD_APPLICATION_TYPE_RECEIVED=1]="V2NIM_FRIEND_ADD_APPLICATION_TYPE_RECEIVED",e[e.V2NIM_FRIEND_ADD_APPLICATION_TYPE_REJECTED=2]="V2NIM_FRIEND_ADD_APPLICATION_TYPE_REJECTED"}(_||(_={})),function(e){e[e.V2NIM_FRIEND_ADD_APPLICATION_STATUS_INIT=0]="V2NIM_FRIEND_ADD_APPLICATION_STATUS_INIT",e[e.V2NIM_FRIEND_ADD_APPLICATION_STATUS_AGREED=1]="V2NIM_FRIEND_ADD_APPLICATION_STATUS_AGREED",e[e.V2NIM_FRIEND_ADD_APPLICATION_STATUS_REJECTED=2]="V2NIM_FRIEND_ADD_APPLICATION_STATUS_REJECTED",e[e.V2NIM_FRIEND_ADD_APPLICATION_STATUS_EXPIRED=3]="V2NIM_FRIEND_ADD_APPLICATION_STATUS_EXPIRED",e[e.V2NIM_FRIEND_ADD_APPLICATION_STATUS_DIRECT_ADD=4]="V2NIM_FRIEND_ADD_APPLICATION_STATUS_DIRECT_ADD"}(d||(d={})),function(e){e[e.V2NIM_FRIEND_DELETION_TYPE_BY_SELF=1]="V2NIM_FRIEND_DELETION_TYPE_BY_SELF",e[e.V2NIM_FRIEND_DELETION_TYPE_BY_PEER=2]="V2NIM_FRIEND_DELETION_TYPE_BY_PEER"}(E||(E={})),function(e){e[e.V2NIM_FRIEND_VERIFY_TYPE_ADD=1]="V2NIM_FRIEND_VERIFY_TYPE_ADD",e[e.V2NIM_FRIEND_VERIFY_TYPE_APPLY=2]="V2NIM_FRIEND_VERIFY_TYPE_APPLY",e[e.V2NIM_FRIEND_VERIFY_TYPE_ACCEPT=3]="V2NIM_FRIEND_VERIFY_TYPE_ACCEPT",e[e.V2NIM_FRIEND_VERIFY_TYPE_REJECT=4]="V2NIM_FRIEND_VERIFY_TYPE_REJECT"}(h||(h={})),function(e){e[e.V2NIM_LOGIN_AUTH_TYPE_DEFAULT=0]="V2NIM_LOGIN_AUTH_TYPE_DEFAULT",e[e.V2NIM_LOGIN_AUTH_TYPE_DYNAMIC_TOKEN=1]="V2NIM_LOGIN_AUTH_TYPE_DYNAMIC_TOKEN",e[e.V2NIM_LOGIN_AUTH_TYPE_THIRD_PARTY=2]="V2NIM_LOGIN_AUTH_TYPE_THIRD_PARTY"}(u||(u={})),function(e){e[e.V2NIM_LOGIN_STATUS_LOGOUT=0]="V2NIM_LOGIN_STATUS_LOGOUT",e[e.V2NIM_LOGIN_STATUS_LOGINED=1]="V2NIM_LOGIN_STATUS_LOGINED",e[e.V2NIM_LOGIN_STATUS_LOGINING=2]="V2NIM_LOGIN_STATUS_LOGINING",e[e.V2NIM_LOGIN_STATUS_UNLOGIN=3]="V2NIM_LOGIN_STATUS_UNLOGIN"}(m||(m={})),function(e){e[e.V2NIM_LOGIN_CLIENT_TYPE_UNKNOWN=0]="V2NIM_LOGIN_CLIENT_TYPE_UNKNOWN",e[e.V2NIM_LOGIN_CLIENT_TYPE_ANDROID=1]="V2NIM_LOGIN_CLIENT_TYPE_ANDROID",e[e.V2NIM_LOGIN_CLIENT_TYPE_IOS=2]="V2NIM_LOGIN_CLIENT_TYPE_IOS",e[e.V2NIM_LOGIN_CLIENT_TYPE_PC=4]="V2NIM_LOGIN_CLIENT_TYPE_PC",e[e.V2NIM_LOGIN_CLIENT_TYPE_WP=8]="V2NIM_LOGIN_CLIENT_TYPE_WP",e[e.V2NIM_LOGIN_CLIENT_TYPE_WEB=16]="V2NIM_LOGIN_CLIENT_TYPE_WEB",e[e.V2NIM_LOGIN_CLIENT_TYPE_RESTFUL=32]="V2NIM_LOGIN_CLIENT_TYPE_RESTFUL",e[e.V2NIM_LOGIN_CLIENT_TYPE_MAC_OS=64]="V2NIM_LOGIN_CLIENT_TYPE_MAC_OS",e[e.V2NIM_LOGIN_CLIENT_TYPE_HARMONY_OS=65]="V2NIM_LOGIN_CLIENT_TYPE_HARMONY_OS"}(g||(g={})),function(e){e[e.V2NIM_KICKED_OFFLINE_REASON_CLIENT_EXCLUSIVE=1]="V2NIM_KICKED_OFFLINE_REASON_CLIENT_EXCLUSIVE",e[e.V2NIM_KICKED_OFFLINE_REASON_SERVER=2]="V2NIM_KICKED_OFFLINE_REASON_SERVER",e[e.V2NIM_KICKED_OFFLINE_REASON_CLIENT=3]="V2NIM_KICKED_OFFLINE_REASON_CLIENT",e[e.V2NIM_KICKED_OFFLINE_REASON_CLIENT_QUIETLY=4]="V2NIM_KICKED_OFFLINE_REASON_CLIENT_QUIETLY"}(p||(p={})),function(e){e[e.V2NIM_LOGIN_CLIENT_CHANGE_LIST=1]="V2NIM_LOGIN_CLIENT_CHANGE_LIST",e[e.V2NIM_LOGIN_CLIENT_CHANGE_LOGIN=2]="V2NIM_LOGIN_CLIENT_CHANGE_LOGIN",e[e.V2NIM_LOGIN_CLIENT_CHANGE_LOGOUT=3]="V2NIM_LOGIN_CLIENT_CHANGE_LOGOUT"}(I||(I={})),function(e){e[e.V2NIM_CONNECT_STATUS_DISCONNECTED=0]="V2NIM_CONNECT_STATUS_DISCONNECTED",e[e.V2NIM_CONNECT_STATUS_CONNECTED=1]="V2NIM_CONNECT_STATUS_CONNECTED",e[e.V2NIM_CONNECT_STATUS_CONNECTING=2]="V2NIM_CONNECT_STATUS_CONNECTING",e[e.V2NIM_CONNECT_STATUS_WAITING=3]="V2NIM_CONNECT_STATUS_WAITING"}(N||(N={})),function(e){e[e.NIM_MESSAGE_AI_STREAM_STATUS_STREAMING=-1]="NIM_MESSAGE_AI_STREAM_STATUS_STREAMING",e[e.NIM_MESSAGE_AI_STREAM_STATUS_NONE=0]="NIM_MESSAGE_AI_STREAM_STATUS_NONE",e[e.NIM_MESSAGE_AI_STREAM_STATUS_PLACEHOLDER=1]="NIM_MESSAGE_AI_STREAM_STATUS_PLACEHOLDER",e[e.NIM_MESSAGE_AI_STREAM_STATUS_CANCEL=2]="NIM_MESSAGE_AI_STREAM_STATUS_CANCEL",e[e.NIM_MESSAGE_AI_STREAM_STATUS_UPDATE=3]="NIM_MESSAGE_AI_STREAM_STATUS_UPDATE",e[e.NIM_MESSAGE_AI_STREAM_STATUS_COMPLETE=4]="NIM_MESSAGE_AI_STREAM_STATUS_COMPLETE",e[e.NIM_MESSAGE_AI_STREAM_STATUS_EXCEPTION=5]="NIM_MESSAGE_AI_STREAM_STATUS_EXCEPTION"}(T||(T={})),function(e){e[e.V2NIM_MESSAGE_AI_STREAM_STOP_OP_DEFAULT=0]="V2NIM_MESSAGE_AI_STREAM_STOP_OP_DEFAULT",e[e.V2NIM_MESSAGE_AI_STREAM_STOP_OP_REVOKE=1]="V2NIM_MESSAGE_AI_STREAM_STOP_OP_REVOKE",e[e.V2NIM_MESSAGE_AI_STREAM_STOP_OP_UPDATE=2]="V2NIM_MESSAGE_AI_STREAM_STOP_OP_UPDATE"}(O||(O={})),function(e){e[e.V2NIM_MESSAGE_AI_REGEN_OP_UPDATE=1]="V2NIM_MESSAGE_AI_REGEN_OP_UPDATE",e[e.V2NIM_MESSAGE_AI_REGEN_OP_NEW=2]="V2NIM_MESSAGE_AI_REGEN_OP_NEW"}(M||(M={})),function(e){e[e.V2NIM_MESSAGE_AI_STATUS_UNKNOW=0]="V2NIM_MESSAGE_AI_STATUS_UNKNOW",e[e.V2NIM_MESSAGE_AI_STATUS_AT=1]="V2NIM_MESSAGE_AI_STATUS_AT",e[e.V2NIM_MESSAGE_AI_STATUS_RESPONSE=2]="V2NIM_MESSAGE_AI_STATUS_RESPONSE"}(f||(f={})),function(e){e[e.V2NIM_MESSAGE_TYPE_INVALID=-1]="V2NIM_MESSAGE_TYPE_INVALID",e[e.V2NIM_MESSAGE_TYPE_TEXT=0]="V2NIM_MESSAGE_TYPE_TEXT",e[e.V2NIM_MESSAGE_TYPE_IMAGE=1]="V2NIM_MESSAGE_TYPE_IMAGE",e[e.V2NIM_MESSAGE_TYPE_AUDIO=2]="V2NIM_MESSAGE_TYPE_AUDIO",e[e.V2NIM_MESSAGE_TYPE_VIDEO=3]="V2NIM_MESSAGE_TYPE_VIDEO",e[e.V2NIM_MESSAGE_TYPE_LOCATION=4]="V2NIM_MESSAGE_TYPE_LOCATION",e[e.V2NIM_MESSAGE_TYPE_NOTIFICATION=5]="V2NIM_MESSAGE_TYPE_NOTIFICATION",e[e.V2NIM_MESSAGE_TYPE_FILE=6]="V2NIM_MESSAGE_TYPE_FILE",e[e.V2NIM_MESSAGE_TYPE_AVCHAT=7]="V2NIM_MESSAGE_TYPE_AVCHAT",e[e.V2NIM_MESSAGE_TYPE_TIPS=10]="V2NIM_MESSAGE_TYPE_TIPS",e[e.V2NIM_MESSAGE_TYPE_ROBOT=11]="V2NIM_MESSAGE_TYPE_ROBOT",e[e.V2NIM_MESSAGE_TYPE_CALL=12]="V2NIM_MESSAGE_TYPE_CALL",e[e.V2NIM_MESSAGE_TYPE_CUSTOM=100]="V2NIM_MESSAGE_TYPE_CUSTOM"}(S||(S={})),function(e){e[e.V2NIM_SEARCH_KEYWORD_MATCH_TYPE_OR=0]="V2NIM_SEARCH_KEYWORD_MATCH_TYPE_OR",e[e.V2NIM_SEARCH_KEYWORD_MATCH_TYPE_AND=1]="V2NIM_SEARCH_KEYWORD_MATCH_TYPE_AND"}(R||(R={})),function(e){e[e.V2NIM_SEARCH_DIRECTION_BACKWARD=0]="V2NIM_SEARCH_DIRECTION_BACKWARD",e[e.V2NIM_SEARCH_DIRECTION_FORWARD=1]="V2NIM_SEARCH_DIRECTION_FORWARD"}(C||(C={})),function(e){e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_UNDEFINED=-1]="V2NIM_MESSAGE_NOTIFICATION_TYPE_UNDEFINED",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_INVITE=0]="V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_INVITE",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_KICK=1]="V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_KICK",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_LEAVE=2]="V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_LEAVE",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_UPDATE_TINFO=3]="V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_UPDATE_TINFO",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_DISMISS=4]="V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_DISMISS",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_APPLY_PASS=5]="V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_APPLY_PASS",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_OWNER_TRANSFER=6]="V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_OWNER_TRANSFER",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_ADD_MANAGER=7]="V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_ADD_MANAGER",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_REMOVE_MANAGER=8]="V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_REMOVE_MANAGER",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_INVITE_ACCEPT=9]="V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_INVITE_ACCEPT",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_BANNED_TEAM_MEMBER=10]="V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_BANNED_TEAM_MEMBER",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_INVITE=401]="V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_INVITE",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_KICK=402]="V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_KICK",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_LEAVE=403]="V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_LEAVE",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_UPDATE_TINFO=404]="V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_UPDATE_TINFO",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_DISMISS=405]="V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_DISMISS",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_APPLY_PASS=410]="V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_APPLY_PASS",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_OWNER_TRANSFER=406]="V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_OWNER_TRANSFER",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_ADD_MANAGER=407]="V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_ADD_MANAGER",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_REMOVE_MANAGER=408]="V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_REMOVE_MANAGER",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_INVITE_ACCEPT=411]="V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_INVITE_ACCEPT",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_BANNED_TEAM_MEMBER=409]="V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_BANNED_TEAM_MEMBER"}(A||(A={})),function(e){e[e.V2NIM_MESSAGE_ATTACHMENT_UPLOAD_STATE_UNKNOWN=0]="V2NIM_MESSAGE_ATTACHMENT_UPLOAD_STATE_UNKNOWN",e[e.V2NIM_MESSAGE_ATTACHMENT_UPLOAD_STATE_SUCCESS=1]="V2NIM_MESSAGE_ATTACHMENT_UPLOAD_STATE_SUCCESS",e[e.V2NIM_MESSAGE_ATTACHMENT_UPLOAD_STATE_FAILED=2]="V2NIM_MESSAGE_ATTACHMENT_UPLOAD_STATE_FAILED",e[e.V2NIM_MESSAGE_ATTACHMENT_UPLOAD_STATE_UPLOADING=3]="V2NIM_MESSAGE_ATTACHMENT_UPLOAD_STATE_UPLOADING"}(v||(v={})),function(e){e[e.V2NIM_MESSAGE_SENDING_STATE_UNKNOWN=0]="V2NIM_MESSAGE_SENDING_STATE_UNKNOWN",e[e.V2NIM_MESSAGE_SENDING_STATE_SUCCEEDED=1]="V2NIM_MESSAGE_SENDING_STATE_SUCCEEDED",e[e.V2NIM_MESSAGE_SENDING_STATE_FAILED=2]="V2NIM_MESSAGE_SENDING_STATE_FAILED",e[e.V2NIM_MESSAGE_SENDING_STATE_SENDING=3]="V2NIM_MESSAGE_SENDING_STATE_SENDING"}(y||(y={})),function(e){e[e.V2NIM_QUERY_DIRECTION_DESC=0]="V2NIM_QUERY_DIRECTION_DESC",e[e.V2NIM_QUERY_DIRECTION_ASC=1]="V2NIM_QUERY_DIRECTION_ASC"}(D||(D={})),function(e){e[e.V2NIM_CLEAR_HISTORY_MODE_ALL=0]="V2NIM_CLEAR_HISTORY_MODE_ALL",e[e.V2NIM_CLEAR_HISTORY_MODE_LOCAL=1]="V2NIM_CLEAR_HISTORY_MODE_LOCAL",e[e.V2NIM_CLEAR_HISTORY_MODE_LOCAL_IRREPARABLY=2]="V2NIM_CLEAR_HISTORY_MODE_LOCAL_IRREPARABLY"}(V||(V={})),function(e){e[e.V2NIM_MESSAGE_REVOKE_TYPE_UNDEFINED=0]="V2NIM_MESSAGE_REVOKE_TYPE_UNDEFINED",e[e.V2NIM_MESSAGE_REVOKE_TYPE_P2P_BOTHWAY=1]="V2NIM_MESSAGE_REVOKE_TYPE_P2P_BOTHWAY",e[e.V2NIM_MESSAGE_REVOKE_TYPE_TEAM_BOTHWAY=2]="V2NIM_MESSAGE_REVOKE_TYPE_TEAM_BOTHWAY",e[e.V2NIM_MESSAGE_REVOKE_TYPE_SUPERTEAM_BOTHWAY=3]="V2NIM_MESSAGE_REVOKE_TYPE_SUPERTEAM_BOTHWAY",e[e.V2NIM_MESSAGE_REVOKE_TYPE_P2P_ONEWAY=4]="V2NIM_MESSAGE_REVOKE_TYPE_P2P_ONEWAY",e[e.V2NIM_MESSAGE_REVOKE_TYPE_TEAM_ONEWAY=5]="V2NIM_MESSAGE_REVOKE_TYPE_TEAM_ONEWAY"}(L||(L={})),function(e){e[e.V2NIM_MESSAGE_PIN_STATE_NOT_PINNED=0]="V2NIM_MESSAGE_PIN_STATE_NOT_PINNED",e[e.V2NIM_MESSAGE_PIN_STATE_PINNED=1]="V2NIM_MESSAGE_PIN_STATE_PINNED",e[e.V2NIM_MESSAGE_PIN_STATE_UPDATED=2]="V2NIM_MESSAGE_PIN_STATE_UPDATED"}(b||(b={})),function(e){e[e.V2NIM_QUICK_COMMENT_STATE_ADD=1]="V2NIM_QUICK_COMMENT_STATE_ADD",e[e.V2NIM_QUICK_COMMENT_STATE_REMOVE=2]="V2NIM_QUICK_COMMENT_STATE_REMOVE"}(P||(P={})),function(e){e[e.V2NIM_CLIENT_ANTISPAM_OPERATE_NONE=0]="V2NIM_CLIENT_ANTISPAM_OPERATE_NONE",e[e.V2NIM_CLIENT_ANTISPAM_OPERATE_REPLACE=1]="V2NIM_CLIENT_ANTISPAM_OPERATE_REPLACE",e[e.V2NIM_CLIENT_ANTISPAM_OPERATE_CLIENT_SHIELD=2]="V2NIM_CLIENT_ANTISPAM_OPERATE_CLIENT_SHIELD",e[e.V2NIM_CLIENT_ANTISPAM_OPERATE_SERVER_SHIELD=3]="V2NIM_CLIENT_ANTISPAM_OPERATE_SERVER_SHIELD"}(k||(k={})),function(e){e[e.V2NIM_SORT_ORDER_DESC=0]="V2NIM_SORT_ORDER_DESC",e[e.V2NIM_SORT_ORDER_ASC=1]="V2NIM_SORT_ORDER_ASC"}(w||(w={})),function(e){e[e.P2P_DELETE_MSG=7]="P2P_DELETE_MSG",e[e.TEAM_DELETE_MSG=8]="TEAM_DELETE_MSG",e[e.SUPERTEAM_DELETE_MSG=12]="SUPERTEAM_DELETE_MSG",e[e.P2P_ONE_WAY_DELETE_MSG=13]="P2P_ONE_WAY_DELETE_MSG",e[e.TEAM_ONE_WAY_DELETE_MSG=14]="TEAM_ONE_WAY_DELETE_MSG",e[e.CUSTOM_P2P_MSG=100]="CUSTOM_P2P_MSG",e[e.CUSTOM_TEAM_MSG=101]="CUSTOM_TEAM_MSG",e[e.CUSTOM_SUPERTEAM_MSG=103]="CUSTOM_SUPERTEAM_MSG"}(U||(U={})),function(e){e[e.NIM_MESSAGE_STREAM_STATUS_STREAMING=-1]="NIM_MESSAGE_STREAM_STATUS_STREAMING",e[e.NIM_MESSAGE_STREAM_STATUS_NONE=0]="NIM_MESSAGE_STREAM_STATUS_NONE",e[e.NIM_MESSAGE_STREAM_STATUS_PLACEHOLDER=1]="NIM_MESSAGE_STREAM_STATUS_PLACEHOLDER",e[e.NIM_MESSAGE_STREAM_STATUS_CANCEL=2]="NIM_MESSAGE_STREAM_STATUS_CANCEL",e[e.NIM_MESSAGE_AI_STREAM_STATUS_UPDATE=3]="NIM_MESSAGE_AI_STREAM_STATUS_UPDATE",e[e.NIM_MESSAGE_STREAM_STATUS_COMPLETE=4]="NIM_MESSAGE_STREAM_STATUS_COMPLETE",e[e.NIM_MESSAGE_STREAM_STATUS_EXCEPTION=5]="NIM_MESSAGE_STREAM_STATUS_EXCEPTION"}(x||(x={})),function(e){e[e.V2NIM_MESSAGE_SOURCE_UNKNOWN=0]="V2NIM_MESSAGE_SOURCE_UNKNOWN",e[e.V2NIM_MESSAGE_SOURCE_ONLINE=1]="V2NIM_MESSAGE_SOURCE_ONLINE",e[e.V2NIM_MESSAGE_SOURCE_OFFLINE=2]="V2NIM_MESSAGE_SOURCE_OFFLINE",e[e.V2NIM_MESSAGE_SOURCE_ROAMING=3]="V2NIM_MESSAGE_SOURCE_ROAMING"}(G||(G={})),function(e){e[e.V2NIM_TEAM_MESSAGE_MUTE_MODE_OFF=0]="V2NIM_TEAM_MESSAGE_MUTE_MODE_OFF",e[e.V2NIM_TEAM_MESSAGE_MUTE_MODE_ON=1]="V2NIM_TEAM_MESSAGE_MUTE_MODE_ON",e[e.V2NIM_TEAM_MESSAGE_MUTE_MODE_NORMAL_ON=2]="V2NIM_TEAM_MESSAGE_MUTE_MODE_NORMAL_ON"}(B||(B={})),function(e){e[e.V2NIM_P2P_MESSAGE_MUTE_MODE_OFF=0]="V2NIM_P2P_MESSAGE_MUTE_MODE_OFF",e[e.V2NIM_P2P_MESSAGE_MUTE_MODE_ON=1]="V2NIM_P2P_MESSAGE_MUTE_MODE_ON"}(H||(H={})),function(e){e[e.V2NIM_TEAM_MEMBER_ROLE_QUERY_TYPE_ALL=0]="V2NIM_TEAM_MEMBER_ROLE_QUERY_TYPE_ALL",e[e.V2NIM_TEAM_MEMBER_ROLE_QUERY_TYPE_NORMAL=1]="V2NIM_TEAM_MEMBER_ROLE_QUERY_TYPE_NORMAL",e[e.V2NIM_TEAM_MEMBER_ROLE_QUERY_TYPE_MANAGER=2]="V2NIM_TEAM_MEMBER_ROLE_QUERY_TYPE_MANAGER"}(Y||(Y={})),function(e){e[e.V2NIM_TEAM_TYPE_INVALID=0]="V2NIM_TEAM_TYPE_INVALID",e[e.V2NIM_TEAM_TYPE_ADVANCED=1]="V2NIM_TEAM_TYPE_ADVANCED",e[e.V2NIM_TEAM_TYPE_SUPER=2]="V2NIM_TEAM_TYPE_SUPER"}($||($={})),function(e){e[e.V2NIM_TEAM_JOIN_MODE_FREE=0]="V2NIM_TEAM_JOIN_MODE_FREE",e[e.V2NIM_TEAM_JOIN_MODE_APPLY=1]="V2NIM_TEAM_JOIN_MODE_APPLY",e[e.V2NIM_TEAM_JOIN_MODE_INVITE=2]="V2NIM_TEAM_JOIN_MODE_INVITE"}(j||(j={})),function(e){e[e.V2NIM_TEAM_AGREE_MODE_AUTH=0]="V2NIM_TEAM_AGREE_MODE_AUTH",e[e.V2NIM_TEAM_AGREE_MODE_NO_AUTH=1]="V2NIM_TEAM_AGREE_MODE_NO_AUTH"}(K||(K={})),function(e){e[e.V2NIM_TEAM_INVITE_MODE_MANAGER=0]="V2NIM_TEAM_INVITE_MODE_MANAGER",e[e.V2NIM_TEAM_INVITE_MODE_ALL=1]="V2NIM_TEAM_INVITE_MODE_ALL"}(q||(q={})),function(e){e[e.V2NIM_TEAM_UPDATE_INFO_MODE_MANAGER=0]="V2NIM_TEAM_UPDATE_INFO_MODE_MANAGER",e[e.V2NIM_TEAM_UPDATE_INFO_MODE_ALL=1]="V2NIM_TEAM_UPDATE_INFO_MODE_ALL"}(W||(W={})),function(e){e[e.V2NIM_TEAM_CHAT_BANNED_MODE_UNBAN=0]="V2NIM_TEAM_CHAT_BANNED_MODE_UNBAN",e[e.V2NIM_TEAM_CHAT_BANNED_MODE_BANNED_NORMAL=1]="V2NIM_TEAM_CHAT_BANNED_MODE_BANNED_NORMAL",e[e.V2NIM_TEAM_CHAT_BANNED_MODE_BANNED_ALL=3]="V2NIM_TEAM_CHAT_BANNED_MODE_BANNED_ALL"}(z||(z={})),function(e){e[e.V2NIM_TEAM_UPDATE_EXTENSION_MODE_MANAGER=0]="V2NIM_TEAM_UPDATE_EXTENSION_MODE_MANAGER",e[e.V2NIM_TEAM_UPDATE_EXTENSION_MODE_ALL=1]="V2NIM_TEAM_UPDATE_EXTENSION_MODE_ALL"}(J||(J={})),function(e){e[e.V2NIM_TEAM_MEMBER_ROLE_NORMAL=0]="V2NIM_TEAM_MEMBER_ROLE_NORMAL",e[e.V2NIM_TEAM_MEMBER_ROLE_OWNER=1]="V2NIM_TEAM_MEMBER_ROLE_OWNER",e[e.V2NIM_TEAM_MEMBER_ROLE_MANAGER=2]="V2NIM_TEAM_MEMBER_ROLE_MANAGER"}(Q||(Q={})),function(e){e[e.V2NIM_TEAM_JOIN_ACTION_TYPE_APPLICATION=0]="V2NIM_TEAM_JOIN_ACTION_TYPE_APPLICATION",e[e.V2NIM_TEAM_JOIN_ACTION_TYPE_REJECT_APPLICATION=1]="V2NIM_TEAM_JOIN_ACTION_TYPE_REJECT_APPLICATION",e[e.V2NIM_TEAM_JOIN_ACTION_TYPE_INVITATION=2]="V2NIM_TEAM_JOIN_ACTION_TYPE_INVITATION",e[e.V2NIM_TEAM_JOIN_ACTION_TYPE_REJECT_INVITATION=3]="V2NIM_TEAM_JOIN_ACTION_TYPE_REJECT_INVITATION"}(X||(X={})),function(e){e[e.V2NIM_TEAM_JOIN_ACTION_STATUS_INIT=0]="V2NIM_TEAM_JOIN_ACTION_STATUS_INIT",e[e.V2NIM_TEAM_JOIN_ACTION_STATUS_AGREED=1]="V2NIM_TEAM_JOIN_ACTION_STATUS_AGREED",e[e.V2NIM_TEAM_JOIN_ACTION_STATUS_REJECTED=2]="V2NIM_TEAM_JOIN_ACTION_STATUS_REJECTED",e[e.V2NIM_TEAM_JOIN_ACTION_STATUS_EXPIRED=3]="V2NIM_TEAM_JOIN_ACTION_STATUS_EXPIRED"}(Z||(Z={})),function(e){e[e.teamApply=0]="teamApply",e[e.teamApplyReject=1]="teamApplyReject",e[e.teamInvite=2]="teamInvite",e[e.teamInviteReject=3]="teamInviteReject",e[e.tlistUpdate=4]="tlistUpdate",e[e.superTeamApply=15]="superTeamApply",e[e.superTeamApplyReject=16]="superTeamApplyReject",e[e.superTeamInvite=17]="superTeamInvite",e[e.superTeamInviteReject=18]="superTeamInviteReject"}(ee||(ee={})),function(e){e[e.V2NIM_AI_MODEL_TYPE_UNKNOW=0]="V2NIM_AI_MODEL_TYPE_UNKNOW",e[e.V2NIM_AI_MODEL_TYPE_QWEN=1]="V2NIM_AI_MODEL_TYPE_QWEN",e[e.V2NIM_AI_MODEL_TYPE_AZURE=2]="V2NIM_AI_MODEL_TYPE_AZURE",e[e.V2NIM_AI_MODEL_TYPE_PRIVATE=3]="V2NIM_AI_MODEL_TYPE_PRIVATE"}(te||(te={})),function(e){e[e.V2NIM_AI_MODEL_STREAM_CALL_STATUS_NONE=0]="V2NIM_AI_MODEL_STREAM_CALL_STATUS_NONE",e[e.V2NIM_AI_MODEL_STREAM_CALL_STATUS_CANCEL=2]="V2NIM_AI_MODEL_STREAM_CALL_STATUS_CANCEL",e[e.V2NIM_AI_MODEL_STREAM_CALL_STATUS_COMPLETE=4]="V2NIM_AI_MODEL_STREAM_CALL_STATUS_COMPLETE",e[e.V2NIM_AI_MODEL_STREAM_CALL_STATUS_EXCEPTION=5]="V2NIM_AI_MODEL_STREAM_CALL_STATUS_EXCEPTION"}(re||(re={})),function(e){e.V2NIM_AI_MODEL_ROLE_TYPE_SYSTEM="system",e.V2NIM_AI_MODEL_ROLE_TYPE_USER="user",e.V2NIM_AI_MODEL_ROLE_TYPE_ASSISTANT="assistant"}(oe||(oe={})),function(e){e[e.V2NIM_SIGNALLING_EVENT_TYPE_UNKNOWN=0]="V2NIM_SIGNALLING_EVENT_TYPE_UNKNOWN",e[e.V2NIM_SIGNALLING_EVENT_TYPE_CLOSE=1]="V2NIM_SIGNALLING_EVENT_TYPE_CLOSE",e[e.V2NIM_SIGNALLING_EVENT_TYPE_JOIN=2]="V2NIM_SIGNALLING_EVENT_TYPE_JOIN",e[e.V2NIM_SIGNALLING_EVENT_TYPE_INVITE=3]="V2NIM_SIGNALLING_EVENT_TYPE_INVITE",e[e.V2NIM_SIGNALLING_EVENT_TYPE_CANCEL_INVITE=4]="V2NIM_SIGNALLING_EVENT_TYPE_CANCEL_INVITE",e[e.V2NIM_SIGNALLING_EVENT_TYPE_REJECT=5]="V2NIM_SIGNALLING_EVENT_TYPE_REJECT",e[e.V2NIM_SIGNALLING_EVENT_TYPE_ACCEPT=6]="V2NIM_SIGNALLING_EVENT_TYPE_ACCEPT",e[e.V2NIM_SIGNALLING_EVENT_TYPE_LEAVE=7]="V2NIM_SIGNALLING_EVENT_TYPE_LEAVE",e[e.V2NIM_SIGNALLING_EVENT_TYPE_CONTROL=8]="V2NIM_SIGNALLING_EVENT_TYPE_CONTROL",e[e.V2NIM_SIGNALLING_EVENT_TYPE_KICK=9]="V2NIM_SIGNALLING_EVENT_TYPE_KICK"}(ie||(ie={})),function(e){e[e.V2NIM_SIGNALLING_CHANNEL_TYPE_AUDIO=1]="V2NIM_SIGNALLING_CHANNEL_TYPE_AUDIO",e[e.V2NIM_SIGNALLING_CHANNEL_TYPE_VIDEO=2]="V2NIM_SIGNALLING_CHANNEL_TYPE_VIDEO",e[e.V2NIM_SIGNALLING_CHANNEL_TYPE_CUSTOM=3]="V2NIM_SIGNALLING_CHANNEL_TYPE_CUSTOM"}(ne||(ne={})),function(e){e[e.V2NIM_USER_STATUS_TYPE_UNKNOWN=0]="V2NIM_USER_STATUS_TYPE_UNKNOWN",e[e.V2NIM_USER_STATUS_TYPE_LOGIN=1]="V2NIM_USER_STATUS_TYPE_LOGIN",e[e.V2NIM_USER_STATUS_TYPE_LOGOUT=2]="V2NIM_USER_STATUS_TYPE_LOGOUT",e[e.V2NIM_USER_STATUS_TYPE_DISCONNECT=3]="V2NIM_USER_STATUS_TYPE_DISCONNECT"}(se||(se={}));var ce={V2NIM_ERROR_CODE_UNKNOWN:{code:0,message:"unknown error"},V2NIM_ERROR_CODE_SUCCESS:{code:200,message:"success"},V2NIM_ERROR_CODE_HANDSHAKE:{code:201,message:"handshake error"},V2NIM_ERROR_CODE_REQUEST_TEMPERARY_FORBIDDEN:{code:398,message:"request temprary forbidden"},V2NIM_ERROR_CODE_SERVER_UNIT_ERROR:{code:399,message:"server unit error"},V2NIM_ERROR_CODE_FORBIDDEN:{code:403,message:"forbidden"},V2NIM_ERROR_CODE_NOT_FOUND:{code:404,message:"not found"},V2NIM_ERROR_CODE_PARAMETER_ERROR:{code:414,message:"parameter error"},V2NIM_ERROR_CODE_RATE_LIMIT_REACHED:{code:416,message:"rate limit reached"},V2NIM_ERROR_CODE_MULTI_LOGIN_FORBIDDEN:{code:417,message:"multi login forbidden"},V2NIM_ERROR_CODE_SERVER_INTERNAL_ERROR:{code:500,message:"server internal error"},V2NIM_ERROR_CODE_SERVER_BUSY:{code:503,message:"server busy"},V2NIM_ERROR_CODE_APP_UNREACHABLE:{code:511,message:"app server unreachable"},V2NIM_ERROR_CODE_SERVICE_UNAVAILABLE:{code:514,message:"service unavailable"},V2NIM_ERROR_CODE_PROTOCOL_BLACKHOLE_FILTERED:{code:599,message:"protocol filtered by blackhole rule"},V2NIM_ERROR_CODE_NO_PERMISSION:{code:997,message:"appid has no permission to call the protocol"},V2NIM_ERROR_CODE_UNPACK_ERROR:{code:998,message:"unpack error"},V2NIM_ERROR_CODE_PACK_ERROR:{code:999,message:"pack error"},V2NIM_ERROR_CODE_IM_DISABLED:{code:101301,message:"IM disabled"},V2NIM_ERROR_CODE_SERVICE_ADDRESS_INVALID:{code:101302,message:"service address invalid"},V2NIM_ERROR_CODE_APPKEY_NOT_EXIST:{code:101303,message:"appkey not exist"},V2NIM_ERROR_CODE_BUNDLEID_CHECK_FAILED:{code:101304,message:"bundleid check failed"},V2NIM_ERROR_CODE_APPKEY_BLOCKED:{code:101403,message:"appkey blocked"},V2NIM_ERROR_CODE_INVALID_TOKEN:{code:102302,message:"invalid token"},V2NIM_ERROR_CODE_ROBOT_NOT_ALLOWED:{code:102303,message:"robot not allowed"},V2NIM_ERROR_CODE_ACCOUNT_NOT_EXIST:{code:102404,message:"account not exist"},V2NIM_ERROR_CODE_ACCOUNT_CHAT_BANNED:{code:102421,message:"account chat banned"},V2NIM_ERROR_CODE_ACCOUNT_BANNED:{code:102422,message:"account banned"},V2NIM_ERROR_CODE_ACCOUNT_IN_BLOCK_LIST:{code:102426,message:"account in block list"},V2NIM_ERROR_CODE_USER_PROFILE_NOT_EXIST:{code:103404,message:"user profile not exist"},V2NIM_ERROR_CODE_USER_PROFILE_HIT_ANTISPAM:{code:103451,message:"user profile hit antispam"},V2NIM_ERROR_CODE_PEER_FRIEND_LIMIT:{code:104301,message:"peer friend limit"},V2NIM_ERROR_CODE_FRIEND_APPLICATION_NOT_EXIST:{code:104302,message:"friend application not exist"},V2NIM_ERROR_CODE_FRIEND_NOT_EXIST:{code:104404,message:"friend not exist"},V2NIM_ERROR_CODE_FRIEND_ALREADY_EXIST:{code:104405,message:"friend already exist"},V2NIM_ERROR_CODE_SELF_FRIEND_OPERATION_NOT_ALLOWED:{code:104429,message:"self friend operation not allowed"},V2NIM_ERROR_CODE_FRIEND_LIMIT:{code:104435,message:"friend limit"},V2NIM_ERROR_CODE_FRIEND_OPERATION_RATE_LIMIT:{code:104449,message:"friend operation rate limit"},V2NIM_ERROR_CODE_FRIEND_HIT_ANTISPAM:{code:104451,message:"friend hit antispam"},V2NIM_ERROR_CODE_SELF_MUTE_OPERATION_NOT_ALLOWED:{code:105429,message:"self mute operation not allowed"},V2NIM_ERROR_CODE_MUTE_LIST_LIMIT:{code:105435,message:"mute list limit"},V2NIM_ERROR_CODE_SELF_BLOCK_LIST_OPERATION_NOT_ALLOWED:{code:106429,message:"self block list operation not allowed"},V2NIM_ERROR_CODE_BLOCK_LIST_LIMIT:{code:106435,message:"block list limit"},V2NIM_ERROR_CODE_REVOKE_THIRD_PARTY_MESSAGE_NOT_ALLOWED:{code:107301,message:"revoke third party message not allowed"},V2NIM_ERROR_CODE_SHORT_TO_LONG_URL_FAILED:{code:107307,message:"short to long URL failed"},V2NIM_ERROR_CODE_URL_INVALID:{code:107308,message:"URL invalid"},V2NIM_ERROR_CODE_DURATION_OUT_OF_RANGE:{code:107309,message:"duration out of range"},V2NIM_ERROR_CODE_GET_FILE_META_INFO_FAILED:{code:107310,message:"get file meta info failed"},V2NIM_ERROR_CODE_AUDIO_FILE_SIZE_LIMIT:{code:107311,message:"audio file size limit"},V2NIM_ERROR_CODE_VOICE_TO_TEXT_TIMEOUT:{code:107312,message:"voice to text timeout"},V2NIM_ERROR_CODE_VOICE_TO_TEXT_FAILED:{code:107313,message:"voice to text failed"},V2NIM_ERROR_CODE_REVOKE_EXCEED_TIME_LIMIT:{code:107314,message:"revoke message exceed time limit"},V2NIM_ERROR_CODE_REVOKE_MESSAGE_NOT_ALLOWED:{code:107315,message:"revoke specific message not allowed"},V2NIM_ERROR_CODE_FORCE_PUSH_LIST_LIMIT:{code:107316,message:"force push list limit"},V2NIM_ERROR_CODE_TEAM_MESSAGE_RECEIPT_RATE_LIMIT:{code:107317,message:"team message receipt rate limit"},V2NIM_ERROR_CODE_SNAPSHOT_NOT_EXIST:{code:107318,message:"snapshot not exist"},V2NIM_ERROR_CODE_PIN_LIMIT:{code:107319,message:"pin limit"},V2NIM_ERROR_CODE_PIN_NOT_EXIST:{code:107320,message:"pin not exist"},V2NIM_ERROR_CODE_QUICK_COMMENT_LIMIT:{code:107321,message:"quick comment limit"},V2NIM_ERROR_CODE_PIN_ALREADY_EXIST:{code:107322,message:"pin already exist"},V2NIM_ERROR_CODE_VOICE_TO_TEXT_FUNCTION_DISABLED:{code:107333,message:"voice to text function disabled"},V2NIM_ERROR_CODE_CLOUD_SEARCH_FUNCTION_DISABLED:{code:107334,message:"cloud search function disabled"},V2NIM_ERROR_CODE_ONE_WAY_DELETE_FUNCTION_DISABLED:{code:107335,message:"one-way delete function disabled"},V2NIM_ERRPR_CODE_ONEWAY_DELETION_NOT_ALLOW_FOR_TARGET_MESSAGES:{code:107338,message:"one-way deletion is not allowed for target messages"},V2NIM_ERRPR_CODE_SENDER_CANNOT_INCLUDED_IN_TARGET_LIST:{code:107339,message:"The message sender cannot be included in the target list"},V2NIM_ERROR_CODE_ROBOT_CANNOT_SEND_TARGET_MESSAGE:{code:107340,message:"Robot can not send target message"},V2NIM_ERROR_CODE_PIN_TARGET_MESSAGE_NOT_ALLOWED:{code:107345,message:"Pin target message is not allowed"},V2NIM_ERROR_CODE_TARGET_MESSAGE_NOT_ALLOWED_REPLY:{code:107346,message:"Target message not allowed reply"},V2NIM_ERROR_CODE_TARGET_MESSAGE_NOT_ALLOWED_QUICK_COMMENT:{code:107347,message:"Target message not allowed quick comment"},V2NIM_ERROR_CODE_REVOKE_MESSAGE_TO_SELF_NOT_ALLOWED:{code:107429,message:"revoke message to self not allowed"},V2NIM_ERROR_CODE_APP_CHAT_BANNED:{code:107410,message:"app chat banned"},V2NIM_ERROR_CODE_QUICK_COMMENT_FUNCTION_DISABLED:{code:107326,message:"quick comment function disabled"},V2NIM_ERROR_CODE_PIN_FUNCTION_DISABLED:{code:107327,message:"PIN function disabled"},V2NIM_ERROR_CODE_TEAM_READ_RECEIPT_FUNCTION_DISABLED:{code:107324,message:"read receipt for team messages function disabled"},V2NIM_ERROR_CODE_P2P_READ_RECEIPT_FUNCTION_DISABLED:{code:107325,message:"read receipt for p2p messages function disabled"},V2NIM_ERROR_CODE_RATE_LIMIT_FOR_MESSAGING_REACHED:{code:107323,message:"rate limit for messaging reached"},V2NIM_ERROR_CODE_MESSAGE_HIT_ANTISPAM:{code:107451,message:"message hit antispam"},V2NIM_ERROR_CODE_MESSAGE_NOT_EXIST:{code:107404,message:"message not exist"},V2NIM_ERROR_CODE_UNSENDING_MESSAGE_EXPIRED:{code:107406,message:"unsending message expired"},V2NIM_ERROR_CODE_TEAM_MARK_READ_FAILED:{code:107302,message:"sending message failed for marking message read failed for too many team members"},V2NIM_ERROR_CODE_SENDER_OR_MANAGER_PERMISSION_ONLY_REVOKE:{code:107303,message:"only sender or manager can revoke message"},V2NIM_ERROR_CODE_DELETE_SELF_MESSAGE_NOT_ALLOWED:{code:107328,message:"delete self message not allowed"},V2NIM_ERROR_CODE_NOT_CHATBOT_ACCOUNT:{code:107329,message:"is not chatbot account"},V2NIM_ERROR_CODE_MESSAGE_SENSE_REQUIRED:{code:107330,message:"sender or receiver must sense message"},V2NIM_ERROR_CODE_HIGH_PRIORITY_MESSAGE_RATE_LIMIT:{code:107304,message:"rate limit of high-priority messages exceeded"},ACK_MESSAGE_BE_HIGH_PRIORITY:{code:107305,message:"ack message should be high-priority"},V2NIM_ERROR_CODE_DUPLICATE_CLIENT_MESSAGE_ID:{code:107306,message:"duplicate client message ID"},V2NIM_ERROR_CODE_INVALID_TIME_RANGE:{code:107439,message:"invalid time range"},V2NIM_ERROR_CODE_NOT_ADVANCED_TEAM:{code:108302,message:"not advanced team"},V2NIM_ERROR_CODE_TEAM_MANAGER_LIMIT:{code:108303,message:"team manager limit"},V2NIM_ERROR_CODE_JOINED_TEAM_LIMIT:{code:108305,message:"joined team limit"},V2NIM_ERROR_CODE_TEAM_NORMAL_MEMBER_CHAT_BANNED:{code:108306,message:"team normal member chat banned"},V2NIM_ERROR_CODE_INVITED_ACCOUNT_NOT_FRIEND:{code:108307,message:"invited account not friend"},V2NIM_ERROR_CODE_REJECT_ALL_TEAM_APPLICATIONS:{code:108308,message:"reject all team applications"},V2NIM_ERROR_CODE_TARGETING_MESSAGE_FOR_TEAM_DISABLED:{code:108318,message:"Targeting messages for group chat is disabled"},V2NIM_ERROR_CODE_INCLUSIVE_AS_FALSE_NOT_ALLOWED_FOR_SUPER_TEAM:{code:108319,message:'Setting "inclusive" to false for super teams is not allowed'},V2NIM_ERROR_CODE_CANNOT_MAKE_SUPER_TEAM_MESSAGE_VISIBLE_TO_NEW_MEMBERS:{code:108320,message:"Cannot make super team targeted messages visible to new members"},V2NIM_ERROR_CODE_CANNOT_ALLOW_TARGETED_MESSAGES_INCLUSIVE_TO_NEW_MEMBERS:{code:108321,message:"Cannot allow targeted messages inclusive to new members"},V2NIM_ERROR_CODE_TEAM_NOT_EXIST:{code:108404,message:"team not exist"},V2NIM_ERROR_CODE_TEAM_ALREADY_CHAT_BANNED:{code:108420,message:"team already chat banned"},V2NIM_ERROR_CODE_ALL_TEAM_MEMBER_CHAT_BANNED:{code:108423,message:"all team member chat banned"},V2NIM_ERROR_CODE_EXTENDED_SUPER_TEAM_LIMIT:{code:108434,message:"extended super team limit"},V2NIM_ERROR_CODE_CREATED_TEAM_LIMIT:{code:108435,message:"created team limit"},V2NIM_ERROR_CODE_TEAM_INVITATION_LIMIT:{code:108437,message:"team invitation limit"},V2NIM_ERROR_CODE_TEAM_HIT_ANTISPAM:{code:108451,message:"team hit antispam"},V2NIM_ERROR_CODE_EXTENDED_SUPER_TEAM_LIMIT_NOT_CONFIGURED:{code:108304,message:"extended super team limit not configured"},V2NIM_ERROR_CODE_SUPER_TEAM_SERVICE_DISABLED:{code:108311,message:"super team service disabled"},V2NIM_ERROR_CODE_TEAM_READ_RECEIPT_RECORD_NOT_FOUND:{code:108301,message:"read receipt record for the team message not found"},V2NIM_ERROR_CODE_NOT_MANAGER:{code:108430,message:"unable to assign owner manager"},V2NIM_ERROR_CODE_ONLINE_MEMBER_COUNT_DISABLED:{code:108406,message:"number of online users service disabled"},V2NIM_ERROR_CODE_TRANSFER_DISABLED:{code:108310,message:"unable to transfer the ownership to owner"},V2NIM_ERROR_CODE_CREATE_TEAM_DISABLED:{code:108309,message:"unable to create team with more than %s people"},V2NIM_ERROR_CODE_EXTENDED_SUPER_TEAM_CREATE_FAILED:{code:108313,message:"/ extended super team creation failed,use open api to create the team"},V2NIM_ERROR_CODE_TEAM_MESSAGE_READ_RECEIPT_DISABLED:{code:108312,message:"read receipt for team messages function disabled"},V2NIM_ERROR_CODE_RETRY:{code:108449,message:"an error occurred, try again"},V2NIM_ERROR_CODE_CHAT_BAN_LIST_CONTAIN_NOT_TEAM_MEMBER:{code:109301,message:"list of chat banned users contains non team members"},V2NIM_ERROR_CODE_CHAT_BAN_LIST_CONTAIN_OPERATOR:{code:109303,message:"list of chat banned users contains the operator"},V2NIM_ERROR_CODE_CHAT_BAN_LIST_CONTAIN_TEAM_OWNER:{code:109304,message:"list of chat banned users contains the team owner"},V2NIM_ERROR_CODE_OPERATION_ON_TEAM_MANAGER_NOT_ALLOWED:{code:109305,message:"operation on team manager not allowed"},V2NIM_ERROR_CODE_NO_TEAM_INVITE_PERMISSION:{code:109306,message:"no team invite permission"},V2NIM_ERROR_CODE_TEAM_OWNER_QUIT_NOT_ALLOWED:{code:109307,message:"team owner quit not allowed"},V2NIM_ERROR_CODE_TEAM_OWNER_IN_KICK_LIST:{code:109308,message:"list of kicked user contains the team owner"},V2NIM_ERROR_CODE_INVITE_ROBOT_ACCOUNT_NOT_ALLOWED:{code:109309,message:"invite robot account not allowed"},V2NIM_ERROR_CODE_KICK_OPERATOR_NOT_ALLOWED:{code:109310,message:"kick operator not allowed"},V2NIM_ERROR_CODE_TEAM_MEMBER_ALREADY_EXIST:{code:109311,message:"team member already exist"},V2NIM_ERROR_CODE_TEAM_INVITATION_OR_APPLICATION_NOT_EXIST:{code:109313,message:"team invitation or application not exist"},V2NIM_ERROR_CODE_OPERATION_ON_TEAM_OWNER_NOT_ALLOWED:{code:109314,message:"operation on team owner not allowed"},V2NIM_ERROR_CODE_FORCED_PUSH_LIST_INCLUDES_NON_TARGETED_ACCOUNTS:{code:109318,message:"The forced push list includes non-targeted accounts"},V2NIM_ERROR_CODE_TEAM_MEMBER_NOT_EXIST:{code:109404,message:"team member not exist"},V2NIM_ERROR_CODE_TEAM_MEMBER_CHAT_BANNED:{code:109424,message:"team member chat banned"},V2NIM_ERROR_CODE_TEAM_OWNER_OPERATION_PERMISSION_REQUIRED:{code:109427,message:"team owner operation permission required"},V2NIM_ERROR_CODE_TEAM_OWNER_OR_MANAGER_OPERATION_PERMISSION_REQUIRED:{code:109432,message:"team owner or manager operation permission required"},V2NIM_ERROR_CODE_TEAM_MEMBER_CONCURRENT_OPERATION_FAILED:{code:109449,message:"team member concurrent operation failed"},V2NIM_ERROR_CODE_TEAM_MEMBER_HIT_ANTISPAM:{code:109451,message:"team member hit antispam"},V2NIM_ERROR_CODE_CONVERSATION_AND_ACCOUNT_MISMATCH:{code:110302,message:"conversation and account mismatch"},V2NIM_ERROR_CODE_CONVERSATION_STICK_TOP_LIMIT:{code:110303,message:"conversation stick top limit"},V2NIM_ERROR_CODE_CONVERSATION_BELONGED_GROUP_LIMIT:{code:110304,message:"conversation belonged group limit"},V2NIM_ERROR_CODE_CONVERSATION_IS_NOT_STICK_TOP:{code:110305,message:"conversation is not stick top"},V2NIM_ERROR_CODE_STICK_TOP_DISABLED:{code:110306,message:"conversation stick top disabled"},V2NIM_ERROR_CODE_CONVERSATION_NOT_EXIST:{code:110404,message:"conversation not exist"},V2NIM_ERROR_CODE_CHATROOM_LINK_UNAVAILABLE:{code:113304,message:"chatroom link unavailable"},V2NIM_ERROR_CODE_IM_CONNECTION_ABNORMAL:{code:113305,message:"IM connection abnormal"},V2NIM_ERROR_CODE_CHATROOM_NOT_EXIST:{code:113404,message:"chatroom not exist"},V2NIM_ERROR_CODE_CHATROOM_CLOSED:{code:113406,message:"chatroom closed"},V2NIM_ERROR_CODE_CHATROOM_REPEATED_OPERATION:{code:113409,message:"chatroom repeated operation"},V2NIM_ERROR_CODE_CHATROOM_DISABLED:{code:113410,message:"chatroom disabled"},V2NIM_ERROR_CODE_ALL_CHATROOM_MEMBER_CHAT_BANNED:{code:113423,message:"all chatroom member chat banned"},V2NIM_ERROR_CODE_CHATROOM_HIT_ANTISPAM:{code:113451,message:"chatroom hit antispam"},V2NIM_ERROR_CODE_ANONYMOUS_MEMBER_FORBIDDEN:{code:114303,message:"anonymous member forbidden"},V2NIM_ERROR_CODE_CHATROOM_MEMBER_NOT_EXIST:{code:114404,message:"chatroom member not exist"},V2NIM_ERROR_CODE_CHATROOM_MEMBER_REPEATED_OPERATION:{code:114405,message:"chatroom member repeated operation"},V2NIM_ERROR_CODE_CHATROOM_MEMBER_CHAT_BANNED:{code:114421,message:"chatroom member chat banned"},V2NIM_ERROR_CODE_ACCOUNT_IN_CHATROOM_BLOCK_LIST:{code:114426,message:"account in chatroom block list"},V2NIM_ERROR_CODE_CHATROOM_OWNER_OPERATION_PERMISSION_REQUIRED:{code:114427,message:"chatroom owner operation permission required"},V2NIM_ERROR_CODE_SELF_IN_CHATROOM_MEMBER_OPERATION_LIST:{code:114429,message:"self in chatroom member operation list"},V2NIM_ERROR_CODE_CHATROOM_OWNER_OR_MANAGER_OPERATION_PERMISSION_REQUIRED:{code:114432,message:"chatroom owner or manager operation permission required"},V2NIM_ERROR_CODE_CHATROOM_MEMBER_LIMIT:{code:114437,message:"chatroom member limit"},V2NIM_ERROR_CODE_CHATROOM_MEMBER_CONCURRENT_OPERATION_FAILED:{code:114449,message:"chatroom member concurrent operation failed"},V2NIM_ERROR_CODE_CHATROOM_MEMBER_HIT_ANTISPAM:{code:114451,message:"chatroom member hit antispam"},V2NIM_ERROR_CODE_CONVERSATION_GROUP_NOT_EXIST:{code:116404,message:"conversation group not exist"},V2NIM_ERROR_CODE_CONVERSATION_GROUP_LIMIT:{code:116435,message:"conversation group limit"},V2NIM_ERROR_CODE_CONVERSATIONS_IN_GROUP_LIMIT:{code:116437,message:"conversations in group limit"},V2NIM_ERROR_CODE_COLLECTION_LIMIT:{code:189301,message:"collection limit"},V2NIM_ERROR_CODE_COLLECTION_NOT_EXIST:{code:189302,message:"collection not exist"},V2NIM_ERROR_CODE_COLLECTION_CONCURRENT_OPERATION_FAILED:{code:189449,message:"collection concurrent operation failed"},V2NIM_ERROR_CODE_INTERNAL:{code:190001,message:"internal error"},V2NIM_ERROR_CODE_ILLEGAL_STATE:{code:190002,message:"illegal state"},V2NIM_ERROR_CODE_MISUSE:{code:191001,message:"misuse"},V2NIM_ERROR_CODE_CANCELLED:{code:191002,message:"operation cancelled"},V2NIM_ERROR_CODE_CALLBACK_FAILED:{code:191003,message:"callback failed"},V2NIM_ERROR_CODE_INVALID_PARAMETER:{code:191004,message:"invalid parameter"},V2NIM_ERROR_CODE_TIMEOUT:{code:191005,message:"timeout"},V2NIM_ERROR_CODE_RESOURCE_NOT_EXIST:{code:191006,message:"resource not exist"},V2NIM_ERROR_CODE_RESOURCE_ALREADY_EXIST:{code:191007,message:"resource already exist"},V2NIM_ERROR_CODE_CONNECT_FAILED:{code:192001,message:"connect failed"},V2NIM_ERROR_CODE_CONNECT_TIMEOUT:{code:192002,message:"connect timeout"},V2NIM_ERROR_CODE_DISCONNECT:{code:192003,message:"disconnect"},V2NIM_ERROR_CODE_PROTOCOL_TIMEOUT:{code:192004,message:"protocol timeout"},V2NIM_ERROR_CODE_PROTOCOL_SEND_FAILED:{code:192005,message:"protocol send failed"},V2NIM_ERROR_CODE_REQUEST_FAILED:{code:192006,message:"request failed"},V2NIM_ERROR_CODE_FILE_NOT_FOUND:{code:194001,message:"file not found"},V2NIM_ERROR_CODE_FILE_CREATE_FAILED:{code:194002,message:"file create failed"},V2NIM_ERROR_CODE_FILE_OPEN_FAILED:{code:194003,message:"file open failed"},V2NIM_ERROR_CODE_FILE_WRITE_FAILED:{code:194004,message:"file write failed"},V2NIM_ERROR_CODE_FILE_READ_FAILED:{code:194005,message:"file read failed"},V2NIM_ERROR_CODE_FILE_UPLOAD_FAILED:{code:194006,message:"file upload failed"},V2NIM_ERROR_CODE_FILE_DOWNLOAD_FAILED:{code:194007,message:"file download failed"},V2NIM_ERROR_CODE_CLIENT_ANTISPAM:{code:195001,message:"client anti-spam"},V2NIM_ERROR_CODE_SERVER_ANTISPAM:{code:195002,message:"server anti-spam"},V2NIM_ERROR_CODE_STREAM_OUTPUT_STOPPED:{code:189318,message:"Streaming text response stopped"},V2NIM_ERROR_CODE_STREAM_OUTPUT_GENERATED:{code:189319,message:"Streaming text response generated"},V2NIM_ERROR_CODE_STREAM_OUTPUT_ABORTED:{code:189320,message:"Streaming text response aborted due to exception"},V2NIM_ERROR_CODE_INTERRUPTION_REJECTED:{code:189321,message:"Non-streaming messages cannot be interrupted"}},le=Object.keys(ce),_e=le.reduce((function(e,t){var r=ce[t];return e[t]=r.code,e}),{}),de=le.reduce((function(e,t){var r=ce[t];return e[r.code]=r.message,e}),{});class V2NIMErrorImpl extends Error{constructor(e){super(e.desc),this.name="V2NIMError",this.code=e.code||0,this.desc=e.desc||de[this.code]||Ee[this.code]||"",this.message=this.desc,this.detail=e.detail||{}}toString(){var e,t=`${this.name}\n code: ${this.code}\n message: "${this.message}"\n detail: ${this.detail?JSON.stringify(this.detail):""}`;return(null===(e=null==this?void 0:this.detail)||void 0===e?void 0:e.rawError)&&(t+=`\n rawError: ${this.detail.rawError.message}`),t}}class ValidateError extends V2NIMErrorImpl{constructor(e,t={},r){super({code:_e.V2NIM_ERROR_CODE_PARAMETER_ERROR,detail:{reason:e,rules:r,data:t}}),this.name="validateError",this.message=this.message+"\n"+JSON.stringify(this.detail,null,2),this.data=t,this.rules=r}}class ValidateErrorV2 extends V2NIMErrorImpl{constructor(e){var t,r,o;super({code:_e.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:null===(t=e.detail)||void 0===t?void 0:t.reason,rules:null===(r=e.detail)||void 0===r?void 0:r.rules,data:null===(o=e.detail)||void 0===o?void 0:o.data}}),this.name="ValidateErrorV2"}}class UploadError extends V2NIMErrorImpl{constructor(e){super(Object.assign({code:400},e)),this.desc=this.desc||"upload file error",this.message=this.desc,this.name="uploadError"}}var Ee={200:null,406:null,808:null,810:null,302:"The user name or password is incorrect.",405:"Parameter length too long",408:"Client request timed out",415:"Client network unavailable",422:"Account disabled",508:"Expiration date",509:"Invalid",7101:"Be pulled black",700:"Partial failure of batch operation",801:"The number of people in the team has reached the upper limit",802:"No permission",803:"The team does not exist or has not changed",804:"The user is not in the team",805:"Team type mismatch",806:"The number of teams created has reached the limit",807:"Team member not valid",809:"Already in the team",811:"The number of accounts in the forced push list exceeds the limit",812:"The team is muted",813:"Due to the limited number of team, some pull people successfully",814:"Disable team message read service",815:"Maximum number of team administrators",816:"Batch operation partial failure",9102:"Channel failure",9103:"This call has been answered / rejected at another end",10201:"Signaling: target NIM client is offline",10202:"Signaling: push is unreachable",10404:"Signaling: channel not exists",10405:"Signaling: channel already exists",10406:"Signaling: member of channel not exists",10407:"Signaling: member of channel already exists",10408:"Signaling: the invitation request does not exist or has expired",10409:"Signaling: the invitation request has been rejected",10410:"Signaling: the invitation request has been accepted",10414:"Signaling: request parameter error",10417:"Signaling: uid conflict",10419:"Signaling: the number of members of channel exceed the limit",10420:"Signaling: member is already in the channel on other client",10700:"Signaling: phased success",13002:"Abnormal chatroom status",13003:"In the blacklist",13004:"In the mute list",13006:"All members are muted, and only the administrator can speak"},he=["error","warn","log","debug"],emptyFunc=function(){},ue=["off","error","warn","log","debug"];class Logger{constructor(e,t={}){this.storageArr=[],this.debugLevel="off",this.timer=0,this.strategies={debug:{name:"debg",func:console.log},log:{name:"info",func:console.log},warn:{name:"warn",func:console.warn},error:{name:"erro",func:console.error}},this.debug=emptyFunc,this.log=emptyFunc,this.warn=emptyFunc,this.error=emptyFunc,this.iid=Math.round(1e3*Math.random()),this.debugLevel=ue.includes(e)?e:"off",t.debugLevel&&(this.debugLevel=ue.includes(t.debugLevel)?t.debugLevel:this.debugLevel),this.logStorage=!1===t.storageEnable?null:new ae.logStorage(null==t?void 0:t.storageName),this.setOptions(t),this.setLogFunc(this.debugLevel),this.setTimer(),ae.setLogger(this),this.open()}getDebugMode(){return"debug"===this.debugLevel}open(){this.logStorage&&this.logStorage.open().then((()=>{this.log("Logger::open success")})).catch((e=>{this.warn("Logger::open failed",e)}))}setOptions(e){if(e&&e.logFunc){var t=e.logFunc;for(var r in t){var o=r,i=t[o];i&&(this.strategies[o].func=i)}}}setLogFunc(e,t="log"){var r=he.findIndex((t=>t===e)),o=he.findIndex((e=>e===t));he.forEach(((e,t)=>{this[e]=function(){if(!(t>r&&t>o)){var i=Array.prototype.slice.call(arguments),n=this.strategies[e],s=this.formatArgs(i,n.name);t<=o&&this.logStorage&&this.prepareSaveLog(s,e),t<=r&&n.func(s)}}}))}extractLogs(){var e;return this.logStorage?null===(e=this.logStorage)||void 0===e?void 0:e.extractLogs():Promise.resolve("")}afterUpload(){var e;return this.logStorage?null===(e=this.logStorage)||void 0===e?void 0:e.afterUpload():Promise.resolve("")}prepareSaveLog(e,t){this.storageArr.push({text:e,level:t,time:Date.now(),iid:this.iid}),this.timer||this.setTimer(),this.storageArr.length>=100&&(this.triggerTimer(),this.storageArr=[])}saveLogs(){return __awaiter(this,void 0,void 0,(function*(){if(this.logStorage){var e=this.storageArr;this.storageArr=[];try{yield this.logStorage.addLogs(e)}catch(e){}}}))}clearTimer(){this.timer&&clearTimeout(this.timer),this.timer=0}setTimer(){this.clearTimer(),this.timer=setTimeout(this.triggerTimer.bind(this),5e3)}triggerTimer(){this.clearTimer(),this.saveLogs()}formatArgs(e,t){var r=new Date;return`[NIM ${this.iid} ${t} ${`${r.getMonth()+1}-${r.getDate()} ${r.getHours()}:${r.getMinutes()}:${r.getSeconds()}:${r.getMilliseconds()}`}] `+e.map((e=>e instanceof V2NIMErrorImpl?e.toString():e instanceof Error?e&&e.message?e.message:e:"object"==typeof e?JSON.stringify(e):e)).join(" ")}destroy(){this.debug=emptyFunc,this.log=emptyFunc,this.warn=emptyFunc,this.error=emptyFunc,this.saveLogs(),this.clearTimer(),this.storageArr=[],this.logStorage&&this.logStorage.close()}}var me="https://abt-online.netease.im/v1/api/abt/client/getExperimentInfo",ge="imElite_sdk_abtest_web",pe=Backoff;function Backoff(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}Backoff.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),r=Math.floor(t*this.jitter*e);e=0==(1&Math.floor(10*t))?e-r:e+r}return 0|Math.min(e,this.max)},Backoff.prototype.reset=function(){this.attempts=0},Backoff.prototype.setMin=function(e){this.ms=e},Backoff.prototype.setMax=function(e){this.max=e},Backoff.prototype.setJitter=function(e){this.jitter=e};var Ie=createCommonjsModule((function(e){var t=Object.prototype.hasOwnProperty,r="~";function Events(){}function EE(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function addListener(e,t,o,i,n){if("function"!=typeof o)throw new TypeError("The listener must be a function");var s=new EE(o,i||e,n),a=r?r+t:t;return e._events[a]?e._events[a].fn?e._events[a]=[e._events[a],s]:e._events[a].push(s):(e._events[a]=s,e._eventsCount++),e}function clearEvent(e,t){0==--e._eventsCount?e._events=new Events:delete e._events[t]}function EventEmitter(){this._events=new Events,this._eventsCount=0}Object.create&&(Events.prototype=Object.create(null),(new Events).__proto__||(r=!1)),EventEmitter.prototype.eventNames=function eventNames(){var e,o,i=[];if(0===this._eventsCount)return i;for(o in e=this._events)t.call(e,o)&&i.push(r?o.slice(1):o);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i},EventEmitter.prototype.listeners=function listeners(e){var t=r?r+e:e,o=this._events[t];if(!o)return[];if(o.fn)return[o.fn];for(var i=0,n=o.length,s=new Array(n);i<n;i++)s[i]=o[i].fn;return s},EventEmitter.prototype.listenerCount=function listenerCount(e){var t=r?r+e:e,o=this._events[t];return o?o.fn?1:o.length:0},EventEmitter.prototype.emit=function emit(e,t,o,i,n,s){var a=r?r+e:e;if(!this._events[a])return!1;var c,l,_=this._events[a],d=arguments.length;if(_.fn){switch(_.once&&this.removeListener(e,_.fn,void 0,!0),d){case 1:return _.fn.call(_.context),!0;case 2:return _.fn.call(_.context,t),!0;case 3:return _.fn.call(_.context,t,o),!0;case 4:return _.fn.call(_.context,t,o,i),!0;case 5:return _.fn.call(_.context,t,o,i,n),!0;case 6:return _.fn.call(_.context,t,o,i,n,s),!0}for(l=1,c=new Array(d-1);l<d;l++)c[l-1]=arguments[l];_.fn.apply(_.context,c)}else{var E,h=_.length;for(l=0;l<h;l++)switch(_[l].once&&this.removeListener(e,_[l].fn,void 0,!0),d){case 1:_[l].fn.call(_[l].context);break;case 2:_[l].fn.call(_[l].context,t);break;case 3:_[l].fn.call(_[l].context,t,o);break;case 4:_[l].fn.call(_[l].context,t,o,i);break;default:if(!c)for(E=1,c=new Array(d-1);E<d;E++)c[E-1]=arguments[E];_[l].fn.apply(_[l].context,c)}}return!0},EventEmitter.prototype.on=function on(e,t,r){return addListener(this,e,t,r,!1)},EventEmitter.prototype.once=function once(e,t,r){return addListener(this,e,t,r,!0)},EventEmitter.prototype.removeListener=function removeListener(e,t,o,i){var n=r?r+e:e;if(!this._events[n])return this;if(!t)return clearEvent(this,n),this;var s=this._events[n];if(s.fn)s.fn!==t||i&&!s.once||o&&s.context!==o||clearEvent(this,n);else{for(var a=0,c=[],l=s.length;a<l;a++)(s[a].fn!==t||i&&!s[a].once||o&&s[a].context!==o)&&c.push(s[a]);c.length?this._events[n]=1===c.length?c[0]:c:clearEvent(this,n)}return this},EventEmitter.prototype.removeAllListeners=function removeAllListeners(e){var t;return e?(t=r?r+e:e,this._events[t]&&clearEvent(this,t)):(this._events=new Events,this._eventsCount=0),this},EventEmitter.prototype.off=EventEmitter.prototype.removeListener,EventEmitter.prototype.addListener=EventEmitter.prototype.on,EventEmitter.prefixed=r,EventEmitter.EventEmitter=EventEmitter,e.exports=EventEmitter}));function get(e,t){if("object"!=typeof e||null===e)return e;for(var r=(t=t||"").split("."),o=0;o<r.length;o++){var i=r[o],n=e[i],s=i.indexOf("["),a=i.indexOf("]");if(-1!==s&&-1!==a&&s<a){var c=i.slice(0,s),l=parseInt(i.slice(s+1,a));n=e[c],n=Array.isArray(n)?n[l]:void 0}if(null==n)return n;e=n}return e}var abs=function(e){var t;if(void 0!==e)return(t=BigNumber(e)).sign=1,t},isArray=function(e){return"[object Array]"===Object.prototype.toString.call(e)},isValidType=function(e){return["number"==typeof e,"string"==typeof e&&e.length>0,isArray(e)&&e.length>0,e instanceof BigNumber].some((function(e){return!0===e}))},Ne="Invalid Number",Te="Invalid Number - Division By Zero";function BigNumber(e){var t;if(!(this instanceof BigNumber))return new BigNumber(e);if(this.number=[],this.sign=1,this.rest=0,isValidType(e)){if(isArray(e)){for((e.length&&"-"===e[0]||"+"===e[0])&&(this.sign="+"===e[0]?1:-1,e.shift(0)),t=e.length-1;t>=0;t--)if(!this.addDigit(e[t]))return}else for("-"!==(e=e.toString()).charAt(0)&&"+"!==e.charAt(0)||(this.sign="+"===e.charAt(0)?1:-1,e=e.substring(1)),t=e.length-1;t>=0;t--)if(!this.addDigit(parseInt(e.charAt(t),10)))return}else this.number=Ne}BigNumber.prototype.addDigit=function(e){return function(e){return/^\d$/.test(e)}(e)?(this.number.push(e),this):(this.number=Ne,!1)},BigNumber.prototype._compare=function(e){var t,r;if(!isValidType(e))return null;if(t=BigNumber(e),this.sign!==t.sign)return this.sign;if(this.number.length>t.number.length)return this.sign;if(this.number.length<t.number.length)return-1*this.sign;for(r=this.number.length-1;r>=0;r--){if(this.number[r]>t.number[r])return this.sign;if(this.number[r]<t.number[r])return-1*this.sign}return 0},BigNumber.prototype.gt=function(e){return this._compare(e)>0},BigNumber.prototype.gte=function(e){return this._compare(e)>=0},BigNumber.prototype.equals=function(e){return 0===this._compare(e)},BigNumber.prototype.lte=function(e){return this._compare(e)<=0},BigNumber.prototype.lt=function(e){return this._compare(e)<0},BigNumber.prototype.subtract=function(e){var t;return void 0===e?this:(t=BigNumber(e),this.sign!==t.sign?(this.number=BigNumber._add(this,t),this):(this.sign=this.lt(t)?-1:1,this.number=abs(this).lt(abs(t))?BigNumber._subtract(t,this):BigNumber._subtract(this,t),this))},BigNumber._add=function(e,t){var r,o=0,i=Math.max(e.number.length,t.number.length);for(r=0;r<i||o>0;r++)e.number[r]=(o+=(e.number[r]||0)+(t.number[r]||0))%10,o=Math.floor(o/10);return e.number},BigNumber._subtract=function(e,t){var r,o=0,i=e.number.length;for(r=0;r<i;r++)e.number[r]-=(t.number[r]||0)+o,e.number[r]+=10*(o=e.number[r]<0?1:0);for(r=0,i=e.number.length-1;0===e.number[i-r]&&i-r>0;)r++;return r>0&&e.number.splice(-r),e.number},BigNumber.prototype.multiply=function(e){if(void 0===e)return this;var t,r,o=BigNumber(e),i=0,n=[];if(this.isZero()||o.isZero())return BigNumber(0);for(this.sign*=o.sign,t=0;t<this.number.length;t++)for(i=0,r=0;r<o.number.length||i>0;r++)n[t+r]=(i+=(n[t+r]||0)+this.number[t]*(o.number[r]||0))%10,i=Math.floor(i/10);return this.number=n,this},BigNumber.prototype.divide=function(e){if(void 0===e)return this;var t,r,o=BigNumber(e),i=[],n=BigNumber(0);if(o.isZero())return this.number=Te,this;if(this.isZero())return this.rest=BigNumber(0),this;if(this.sign*=o.sign,o.sign=1,1===o.number.length&&1===o.number[0])return this.rest=BigNumber(0),this;for(t=this.number.length-1;t>=0;t--)for(n.multiply(10),n.number[0]=this.number[t],i[t]=0;o.lte(n);)i[t]++,n.subtract(o);for(t=0,r=i.length-1;0===i[r-t]&&r-t>0;)t++;return t>0&&i.splice(-t),this.rest=n,this.number=i,this},BigNumber.prototype.mod=function(e){return this.divide(e).rest},BigNumber.prototype.isZero=function(){var e;for(e=0;e<this.number.length;e++)if(0!==this.number[e])return!1;return!0},BigNumber.prototype.toString=function(){var e,t="";if("string"==typeof this.number)return this.number;for(e=this.number.length-1;e>=0;e--)t+=this.number[e];return this.sign>0?t:"-"+t};var Oe=Math.pow(2,32);function varintToBytes(e){for(var t=new Uint8Array(5),r=new DataView(t.buffer),o=0;0!=(4294967168&e);)r.setUint8(o++,127&e|128),e>>>=7;return r.setUint8(o++,127&e),t.slice(0,o)}function decodeText(e){return"function"==typeof TextDecoder?new TextDecoder("utf-8").decode(e):function textDecoder(e){for(var t="",r=0;r<e.length;){var o=e[r],i=0,n=0;if(o<=127?(i=0,n=255&o):o<=223?(i=1,n=31&o):o<=239?(i=2,n=15&o):o<=244&&(i=3,n=7&o),e.length-r-i>0)for(var s=0;s<i;)n=n<<6|63&(o=e[r+s+1]),s+=1;else n=65533,i=e.length-r;t+=String.fromCodePoint(n),r+=i+1}return t}(e)}class Unpack{constructor(e){this.offset=0,this.buffer=new Uint8Array(e),this.view=new DataView(e)}checkBufferBoundaryAccess(){return this.offset>=this.buffer.byteLength}length(){var e;return(null===(e=this.view)||void 0===e?void 0:e.byteLength)||0}getBuffer(){return this.view.buffer}getOffset(){return this.offset}popRaw(e){try{var t=this.buffer.slice(this.offset,this.offset+e);return this.offset+=e,t}catch(e){throw new Error(`UnpackException raw ${e&&e.message}`)}}popByte(){try{var e=this.view.getUint8(this.offset);return this.offset+=1,e}catch(e){throw new Error(`UnpackException byte ${e&&e.message}`)}}popVarbin(){return this.popRaw(this.popVarInt())}popString(){try{return decodeText(this.popVarbin())}catch(e){throw new Error(`UnpackException string ${e&&e.message}`)}}popInt(){try{var e=this.view.getUint32(this.offset,!0);return this.offset+=4,e}catch(e){throw new Error(`UnpackException int ${e&&e.message}`)}}popVarInt(){var e=1,t=0,r=0,o=0;do{if(t+=(127&(r=this.popByte()))*e,e*=128,(o+=1)>5)throw new Error("Variable length quantity is too long")}while(0!=(128&r));return t}popLong(){try{var e=function getBigUint64(e,t=!1){var r=new DataView(e.buffer),[o,i]=t?[4,0]:[0,4],n=r.getUint32(o,t),s=r.getUint32(i,t);return n>0?n*Oe+s:s}(this.buffer.slice(this.offset,this.offset+8),!0);return this.offset+=8,Number(e)}catch(e){throw new Error(`UnpackException long ${e&&e.message}`)}}popShort(){try{var e=this.view.getUint16(this.offset,!0);return this.offset+=2,e}catch(e){throw new Error(`UnpackException short ${e&&e.message}`)}}popBoolean(){return this.popByte()>0}toString(){return Array.from(new Uint8Array(this.buffer)).toString()}reset(){this.offset=0,this.buffer=null,this.view=null}}class PacketDecoder{constructor(e){this.packetLength=0,this.serviceId=0,this.commandId=0,this.serialId=0,this.tag=0,this.resCode=200,this.innerHeader=null,this.msgId=0,this.bodyArr=[],this.unpack=new Unpack(e)}reset(){this.innerHeader=null,this.bodyArr=[],this.unpack.reset()}getBodyDetail(){return this.bodyArr.join("")}unmarshalHeader(){var e=this._unmarshalHeader();this.packetLength=e.packetLength,this.serviceId=e.serviceId,this.commandId=e.commandId,this.serialId=e.serialId,this.tag=e.tag,this.resCode=e.resCode,4===e.serviceId&&[1,2,10,11].includes(e.commandId)&&(this.msgId=this.unmarshalLong(),this.innerHeader=this._unmarshalHeader())}_unmarshalHeader(){var e=this.unpack.popVarInt(),t=this.unpack.popByte(),r=this.unpack.popByte(),o=this.unpack.popShort(),i=this.unpack.popByte(),n=200;return this.hasRescode(i)&&(n=this.unpack.popShort()),{packetLength:e,serviceId:t,commandId:r,serialId:o,tag:i,resCode:n}}hasRescode(e){return 0!=((e=e||this.tag)&PacketDecoder.RES_CODE)}getHeader(){return{packetLength:this.packetLength,sid:this.serviceId,cid:this.commandId,ser:this.serialId,code:this.resCode}}getInnerHeader(){return this.innerHeader?{sid:this.innerHeader.serviceId,cid:this.innerHeader.commandId}:null}unmarshalProperty(){var e=this.unpack.popVarInt(),t={};this.bodyArr.push(`\nProperty(${e}) {`);for(var r=0;r<e;r++){var o=this.unpack.popVarInt();this.bodyArr.push(`${o}:`);var i=this.unpack.popString();this.bodyArr.push(`"${i.length} ${this.unpack.getOffset()}",`),t[o]=i}return this.bodyArr.push("},"),t}unmarshalPropertyArray(){var e=this.unpack.popVarInt(),t=[];this.bodyArr.push(`\nPropertyArray(${e}) [`);for(var r=0;r<e;r++)t.push(this.unmarshalProperty());return this.bodyArr.push("],"),t}unmarshalLong(){var e=this.unpack.popLong();return this.bodyArr.push(`\nLong:${e}`),e}unmarshalLongArray(){var e=this.unpack.popVarInt(),t=[];this.bodyArr.push(`\nLongArray ${e}:`);for(var r=0;r<e;r++){var o=this.unpack.popLong();this.bodyArr.push(`${o},`),t.push(o)}return t}unmarshalStrArray(){var e=this.unpack.popVarInt(),t=[];this.bodyArr.push(`\nStrArray ${e}:`);for(var r=0;r<e;r++){var o=this.unpack.popString();this.bodyArr.push(`${o},`),t.push(o)}return t}unmarshalStrLongMap(){var e=this.unpack.popVarInt(),t={};this.bodyArr.push(`\nStrLongMap ${e}:`);for(var r=0;r<e;r++){var o=this.unpack.popString();this.bodyArr.push(`${o},`);var i=this.unpack.popLong();this.bodyArr.push(`${i};`),t[o]=i}return t}unmarshalStrStrMap(){var e=this.unpack.popVarInt(),t={};this.bodyArr.push(`\nStrStrMap ${e}:`);for(var r=0;r<e;r++){var o=this.unpack.popString();this.bodyArr.push(`${o},`);var i=this.unpack.popString();this.bodyArr.push(`${i};`),t[o]=i}return t}unmarshalLongLongMap(){var e=this.unpack.popVarInt(),t={};this.bodyArr.push(`\nStrLongLongMap ${e}:`);for(var r=0;r<e;r++){var o=this.unpack.popLong();this.bodyArr.push(`${o},`);var i=this.unpack.popLong();this.bodyArr.push(`${i};`),t[o]=i}return{m_map:t}}unmarshalKVArray(){var e=this.unpack.popVarInt(),t=[];this.bodyArr.push(`\nKVArray ${e}:`);for(var r=0;r<e;r++)t.push(this.unmarshalStrStrMap());return t}unmarshal(e){var t=Object.assign(Object.assign({},this.getHeader()),{r:[]});if(this.innerHeader&&(t.r[0]=this.msgId,t.r[1]={body:[],headerPacket:this.getInnerHeader()}),![200,406,808,810,7101].includes(t.code))return JSON.stringify(t);if(this.packetLength>0&&this.packetLength>this.unpack.length())throw new Error(`UnpackException packetLength(${this.packetLength}) greater than bufferLength(${this.unpack.length()})`);var r=[];return e&&e.forEach((e=>{if(!this.unpack.checkBufferBoundaryAccess())switch(e.type){case"PropertyArray":r.push(this.unmarshalPropertyArray());break;case"Property":r.push(this.unmarshalProperty());break;case"Byte":r.push(this.unpack.popByte());break;case"Int":r.push(this.unpack.popInt());break;case"Bool":r.push(this.unpack.popBoolean());break;case"Long":r.push(this.unmarshalLong());break;case"LongArray":r.push(this.unmarshalLongArray());break;case"String":r.push(this.unpack.popString());break;case"StrArray":r.push(this.unmarshalStrArray());break;case"StrStrMap":r.push(this.unmarshalStrStrMap());break;case"StrLongMap":r.push(this.unmarshalStrLongMap());break;case"LongLongMap":r.push(this.unmarshalLongLongMap());break;case"KVArray":r.push(this.unmarshalKVArray())}})),this.innerHeader?t.r[1].body=r:t.r=r,JSON.stringify(t)}}PacketDecoder.RES_CODE=2;class PromiseManager{constructor(){this.abortFns=[]}add(e){var t=function getPromiseWithAbort(e){var t={},r=new Promise((function(e,r){t.abort=r}));return t.promise=Promise.race([e,r]),t}(e);return this.abortFns.push(t.abort),t.promise}clear(e){this.abortFns.forEach((t=>t(e||new V2NIMErrorImpl({code:_e.V2NIM_ERROR_CODE_CANCELLED,detail:{reason:"Aborted"}})))),this.abortFns=[]}destroy(){this.clear()}}var Me={tolerantRTT:3e3,bestRTT:100,maxChances:5,enable:!0},fe={timestamp:0,rtt:0,baseClock:0,baseTime:0};class TimeOrigin{constructor(e,t,r="getServerTime"){this.serverOrigin=fe,this.config=Me,this.isSettingNTP=!1,this.currentChance=0,this.failedDelay=2e3,this.successDelay=3e5,this.timer=0,this.cmdName="getServerTime",this.core=e,this.logger=e.logger,this.promiseManager=new PromiseManager,this.cmdName=r,t&&this.setOptions(t)}setOptions(e){this.config=Object.assign({},Me,this.config,e)}reset(){this.timer&&clearTimeout(this.timer),this.promiseManager.clear(),this.serverOrigin=fe,this.currentChance=0}setOriginTimetick(){return __awaiter(this,void 0,void 0,(function*(){if(this.config.enable&&!(this.isSettingNTP||this.currentChance>=this.config.maxChances)){var e=get(this.core,"auth.status"),t=get(this.core,"status"),r=get(this.core,"V2NIMLoginService.lifeCycle.loginStatus");if("logined"===e||"logined"===t||1===r){this.isSettingNTP=!0,this.currentChance++,this.timer&&clearTimeout(this.timer),this.timer=0;var o,i="TimeOrigin::setOriginTimetick:",n=Date.now();this.core.logger.debug(`${i} getServerTime start, times ${this.currentChance}`);try{o=get(yield this.promiseManager.add(this.core.sendCmd(this.cmdName)),"content.time"),this.isSettingNTP=!1}catch(e){var s=e;return this.isSettingNTP=!1,this.logger.warn(`${i} Calculate Delay time, getServerTime error`,s),void(s.code!==_e.V2NIM_ERROR_CODE_CANCELLED&&(clearTimeout(this.timer),this.timer=setTimeout(this.setOriginTimetick.bind(this),this.failedDelay)))}if(!o)return this.core.logger.warn(`${i} Calculate Delay time incorrect format`),void(this.config.enable=!1);var a=Date.now()-n;this.doSet(o,a)}}}))}doSet(e,t){var r="TimeOrigin::setOriginTimetick:";t>this.config.tolerantRTT?(this.logger.warn(`${r} denied RTT:${t}`),clearTimeout(this.timer),this.timer=setTimeout(this.setOriginTimetick.bind(this),this.failedDelay)):t>this.config.bestRTT?(this.serverOrigin.rtt&&t>=this.serverOrigin.rtt?this.logger.warn(`${r} ignore RTT:${t}`):(this.setServerOrigin(t,e),this.logger.log(`${r} accept reluctantly RTT:${t}`)),clearTimeout(this.timer),this.timer=setTimeout(this.setOriginTimetick.bind(this),this.failedDelay)):(this.setServerOrigin(t,e),this.logger.debug(`${r} accept best RTT:${t}`),this.currentChance=0,clearTimeout(this.timer),this.timer=setTimeout(this.setOriginTimetick.bind(this),this.successDelay))}getNTPTime(e){if(void 0===e&&(e=this.getTimeNode()),this.checkNodeReliable(e)){var t=Math.floor(e.time-this.serverOrigin.baseTime);return this.serverOrigin.timestamp+t}return Date.now()}checkNodeReliable(e){if(void 0===e&&(e=this.getTimeNode()),this.serverOrigin.timestamp){if(0===this.serverOrigin.baseClock)return!0;var t=e.clock-this.serverOrigin.baseClock,r=e.time-this.serverOrigin.baseTime;return Math.abs(r-t)<500}return!1}checkPerformance(){return"BROWSER"===ae.platform&&!("undefined"==typeof performance||!performance.now)}static checkPerformance(){return"BROWSER"===ae.platform&&!("undefined"==typeof performance||!performance.now)}getTimeNode(){return{clock:this.checkPerformance()?performance.now():0,time:Date.now()}}static getTimeNode(){return{clock:TimeOrigin.checkPerformance()?performance.now():0,time:Date.now()}}setServerOrigin(e,t){this.serverOrigin={timestamp:t+Math.floor(e/2),rtt:e,baseClock:this.checkPerformance()?performance.now():0,baseTime:Date.now()}}}var Se={},Re={};function createCmd(e,t,r,o){var i=Se[e];if(!i)return r.error("createCmd:: can not find cmd config: ",e),null;var n={SER:t,SID:i.sid,CID:i.cid,Q:[]};return i.params&&o&&i.params.forEach((function(e){var t=o[e.name];if(null!=t){var r=e.type,{reflectMapper:i,select:s}=e;switch(e.type){case"PropertyArray":r="ArrayMable",t=t.map((e=>({t:"Property",v:i?serialize(e,i,s):e})));break;case"Property":t=i?serialize(t,i,s):t;break;case"Bool":t=t?"true":"false"}n.Q.push({t:r,v:t})}})),{packet:n,hasPacketResponse:"boolean"!=typeof i.hasPacketResponse||i.hasPacketResponse,hasPacketTimer:"boolean"!=typeof i.hasPacketTimer||i.hasPacketTimer}}function parseCmd(e,t){var r;try{r=JSON.parse(e)}catch(r){return void t.error(`Parse command error:"${e}"`)}var o=r.sid+"_"+r.cid,i=r.r;if(["4_1","4_2","4_10","4_11"].includes(o)){var n=r.r[1].headerPacket;o=`${n.sid}_${n.cid}`,r.sid=n.sid,r.cid=n.cid,i=r.r[1].body}var s=Re[o],a=[];if(s&&s.length>0){for(var c of s)a.push(parseEachCmd(r,c.config,c.cmd,i,t));return a}t.error("parseCmd:: mapper not exist",o,r.code)}function parseEachCmd(e,t,r,o,i){var n,s={cmd:r,raw:e,error:null,service:null==t?void 0:t.service,content:{},__receiveTimeNode:TimeOrigin.getTimeNode()};(18===t.sid||t.sid>=26&&t.sid<100)&&(e.code=function toReadableCode(e){if("number"!=typeof e||e!=e)throw new V2NIMErrorImpl({code:_e.V2NIM_ERROR_CODE_INTERNAL,detail:{reason:"Read code failed",rawData:`${e}`}});if(e<0||e>=0&&e<1e3||e>=2e4&&e<=20099)return e;var t=(65535&e)>>9;t-=t<=38?1:2;return 1e5+1e3*t+(511&e)}(e.code));var a=function genCmdError(e,t){var r=de[e],o=Ee[e];return null===o?null:new V2NIMErrorImpl({code:e,desc:r||o||e,detail:{cmd:t,timetag:Date.now()}})}(e.code,r);if(s.error=a,s.error){if(s.error.detail.cmd=r,!(null===(n=null==t?void 0:t.ignoreErrCodes)||void 0===n?void 0:n.includes(e.code)))return s;i.warn("parseCmd:: ignore error ",s.error),s.error.detail.ignore=!0}return t.response&&t.response.forEach(((e,t)=>{var r=o[t],i=e.type,n=e.name,a=e.reflectMapper;if(void 0!==r)switch(i){case"Property":s.content[n]=a?deserialize(r,a):r;break;case"PropertyArray":s.content[n]=r.map((e=>a?deserialize(e,a):e));break;case"Int":case"Long":case"Byte":s.content[n]=+r;break;case"Bool":s.content[n]="true"===r||!0===r||1===r;break;default:s.content[n]=r}})),s}function serialize(e,t,r){var o={};for(var i in e=function flattenObjByMapper(e,t){var r={};for(var o in t){var i=t[o],n="number"==typeof i?o:i.access?i.access:o,s=n.split("."),a=e;for(var c of s){if(void 0===a[c]||null===a[c]){a=void 0;break}a=a[c]}void 0!==a&&(r[n]=a)}return r}(e,t),t){var n=t[i],s="number"==typeof n?i:n.access?n.access:i;if(!r||r.includes(i))if(s in e){if("number"==typeof n)o[n]=e[s];else if("object"==typeof n)if(n.converter){var a=n.converter(e[s],e);void 0!==a&&(o[n.id]=a)}else o[n.id]=e[s]}else"object"==typeof n&&n.def&&("function"==typeof n.def?o[n.id]=n.def(e):o[n.id]=n.def)}return o}function deserialize(e,t){var r={};for(var o in e){var i=t[o];if("string"==typeof i)r[i]=e[o];else if("object"==typeof i&&"prop"in i){var n=i.access?i.access:i.prop;if(i.converter){var s=i.converter(e[o],e);void 0!==s&&(r[n]=s)}else i.type&&"number"===i.type?r[n]=+e[o]:i.type&&"boolean"===i.type?r[n]=!("0"===e[o]||!e[o]):r[n]=e[o]}}for(var a in t){var c=t[a];if(c&&void 0!==c.def){var l=c.access?c.access:c.prop;l in r||("function"==typeof c.def?r[l]=c.def(e):r[l]=c.def)}}return r=function unflattenObj(e){var t={},_loop=function(r){var o=r.split(".");o.reduce((function(t,i,n){return t[i]||(t[i]=isNaN(Number(o[n+1]))?o.length-1==n?e[r]:{}:[])}),t)};for(var r in e)_loop(r);return t}(r),r}function registerParser(e){for(var t in Object.assign(Se,e.cmdConfig),e.cmdMap){var r=e.cmdMap[t],o=e.cmdConfig[r];if(o)if(Array.isArray(Re[t])){var i=!1;for(var n of Re[t])if(n.cmd===r&&n.config.service===o.service){i=!0;break}i||Re[t].push({config:o,cmd:r})}else Re[t]=[{config:o,cmd:r}]}}function invertSerializeItem(e){var t={};for(var r in e){var o=e[r];"number"==typeof o?t[o]=r:"object"==typeof o&&(t[o.id]={prop:r,type:o.retType,access:o.retAccess?o.retAccess:o.access?o.access:r,def:o.retDef,converter:o.retConverter})}return t}function boolToInt(e){return e?1:0}function objectToJSONString(e){if(e&&"object"==typeof e)try{return JSON.stringify(e)}catch(e){return}}function stringToJSONObject(e){if(e&&"string"==typeof e)try{return JSON.parse(e)}catch(e){return}}class Pack{constructor(){this.offset=0,this.pageSize=1024,this.capacity=1048576,this.buffer=new Uint8Array(this.pageSize),this.view=new DataView(this.buffer.buffer)}reset(){this.offset=0,this.buffer=null,this.view=null}size(){return this.offset}getBuffer(){return this.buffer.slice(0,this.offset).buffer}ensureCapacity(e){var t=this.offset+e;if(t>this.capacity)throw new Error("PackException over limit");if(t>this.buffer.byteLength){var r=Math.ceil(t/this.pageSize)*this.pageSize,o=new Uint8Array(r);o.set(this.buffer),this.buffer=o,this.view=new DataView(this.buffer.buffer)}}putRaw(e){this.ensureCapacity(e.length);try{this.buffer.set(e,this.offset),this.offset+=e.length}catch(e){throw new Error("PackException raw")}}putByte(e){this.ensureCapacity(1);try{this.view.setUint8(this.offset++,e)}catch(e){throw new Error("PackException byte")}}putString(e){try{var t=function encodeText(e){if("function"==typeof TextEncoder)return(new TextEncoder).encode(e);var t=function textEncoder(e){for(var t=[],r=e.length,o=0;o<r;){var i=e.codePointAt(o),n=0,s=0;for(i<=127?(n=0,s=0):i<=2047?(n=6,s=192):i<=65535?(n=12,s=224):i<=2097151&&(n=18,s=240),t.push(s|i>>n),n-=6;n>=0;)t.push(128|i>>n&63),n-=6;o+=i>=65536?2:1}return t}(e);return new Uint8Array(t)}(e);this.putVarbin(t)}catch(e){throw new Error("PackException string")}}putInt(e){this.ensureCapacity(4);try{this.view.setInt32(this.offset,e,!0),this.offset+=4}catch(e){throw new Error("PackException int")}}putVarInt(e){var t=varintToBytes(e);this.putRaw(t)}putBoolean(e){this.ensureCapacity(1);try{this.view.setUint8(this.offset++,e?1:0)}catch(e){throw new Error("PackException boolean")}}putLong(e){this.ensureCapacity(8);try{var t=function setBigUint64(e,t=!1){var r=new Uint8Array(8),o=new DataView(r.buffer),i=Number(e>Oe-1?e/Oe:0),n=Number(4294967295&e),[s,a]=t?[4,0]:[0,4];return o.setUint32(s,i,t),o.setUint32(a,n,t),r}(e,!0);this.buffer.set(t,this.offset),this.offset+=8}catch(e){throw new Error("PackException long")}}putStringAsLong(e){this.ensureCapacity(8);try{var t=function setBigUint64ForNumberOverflow(e,t=!1){var r=new Uint8Array(8),o=new DataView(r.buffer),i=BigNumber(e).divide(Oe).number.reverse().join(""),n=BigNumber(e).mod(Oe).number.reverse().join(""),s=Number(i),a=Number(n),[c,l]=t?[4,0]:[0,4];return o.setUint32(c,s,t),o.setUint32(l,a,t),r}(e,!0);this.buffer.set(t,this.offset),this.offset+=8}catch(e){throw new Error("PackException stringAsLong")}}putShort(e){this.ensureCapacity(2);try{this.view.setInt16(this.offset,e,!0),this.offset+=2}catch(e){throw new Error("PackException short")}}putVarbin(e){if(!e)return this.ensureCapacity(1),this.putVarInt(0);if(e.byteLength>Math.pow(2,31)-2)throw new Error("PackException varbin. too long");var t=varintToBytes(e.length);this.ensureCapacity(t.length+e.length);try{this.buffer.set(t,this.offset),this.offset+=t.length,this.buffer.set(e,this.offset),this.offset+=e.length}catch(e){throw new Error("PackException varbin")}}}function isConvertibleToNumber(e){if("number"!=typeof e){if(null==e)return!1;e=Number(e)}if(isNaN(e))throw new Error("Number type conversion error");return!0}function isUndefinedOrNull(e){return null==e}class PacketEncoder{constructor(e,t,r){this.pack=new Pack,this.packetLength=0,this.serviceId=0,this.commandId=0,this.serialId=0,this.tag=0,this.serviceId=e,this.commandId=t,this.serialId=r}marshalHeader(){this.pack.putVarInt(this.packetLength),this.pack.putByte(this.serviceId),this.pack.putByte(this.commandId),this.pack.putShort(this.serialId),this.pack.putByte(this.tag)}marshalProperty(e){var t=Object.keys(e).filter((e=>!isUndefinedOrNull(e)));this.pack.putVarInt(t.length),t.forEach((t=>{this.pack.putVarInt(Number(t)),Array.isArray(e[t])||"[object Object]"===Object.prototype.toString.call(e[t])?this.pack.putString(JSON.stringify(e[t])):this.pack.putString(String(e[t]))}))}marshalPropertyArray(e){var t=e.length;this.pack.putVarInt(t),e.forEach((e=>{this.marshalProperty(null==e?void 0:e.v)}))}marshalStrArray(e){var t=e.filter((e=>!isUndefinedOrNull(e))),r=t.length;this.pack.putVarInt(r),t.forEach((e=>{this.pack.putString(String(e))}))}marshalLongArray(e){var t=e.filter((e=>isConvertibleToNumber(e))),r=t.length;this.pack.putVarInt(r),t.forEach((e=>{this.putLong(e)}))}marshalStrStrMap(e){var t=Object.keys(e).filter((t=>!isUndefinedOrNull(e[t])&&!isUndefinedOrNull(t)));this.pack.putVarInt(t.length),t.forEach((t=>{this.pack.putString(String(t)),this.pack.putString(String(e[t]))}))}marshalStrLongMap(e){var t=Object.keys(e).filter((t=>isConvertibleToNumber(e[t])&&!isUndefinedOrNull(t)));this.pack.putVarInt(t.length),t.forEach((t=>{this.pack.putString(String(t)),this.putLong(e[t])}))}marshalLongLongMap(e){var t=Object.keys(e).filter((t=>{var r=Number(t);return isConvertibleToNumber(r)&&isConvertibleToNumber(e[r])}));this.pack.putVarInt(t.length),t.forEach((t=>{var r=Number(t);this.putLong(r),this.putLong(e[r])}))}marshalKVArray(e){var t=e.length;this.pack.putVarInt(t),e.forEach((e=>{this.marshalStrStrMap(e)}))}putLong(e){"string"==typeof e&&e.length>15?this.pack.putStringAsLong(e):this.pack.putLong(Number(e))}marshal(e,t){return this.marshalHeader(),t&&t.forEach(((t,r)=>{var o,i=t.type,n=null===(o=e[r])||void 0===o?void 0:o.v;if(!isUndefinedOrNull(n))switch(i){case"PropertyArray":this.marshalPropertyArray(n);break;case"Property":this.marshalProperty(n);break;case"Byte":if(!isConvertibleToNumber(n))return;this.pack.putByte(Number(n));break;case"Int":if(!isConvertibleToNumber(n))return;this.pack.putInt(Number(n));break;case"Bool":"false"===n?n=!1:"true"===n&&(n=!0),this.pack.putBoolean(n);break;case"Long":if(!isConvertibleToNumber(n))return;this.putLong(n);break;case"LongArray":this.marshalLongArray(n);break;case"String":this.pack.putString(String(n));break;case"StrArray":this.marshalStrArray(n);break;case"StrStrMap":this.marshalStrStrMap(n);break;case"StrLongMap":this.marshalStrLongMap(n);break;case"LongLongMap":this.marshalLongLongMap(n);break;case"KVArray":this.marshalKVArray(n)}})),this.pack.getBuffer()}reset(){this.pack.reset()}}var Ce,Ae,ve=(Ce=function(){return(65536*(1+Math.random())|0).toString(16).substring(1)},function(){return Ce()+Ce()+Ce()+Ce()+Ce()+Ce()+Ce()+Ce()});function assignOptions(e,t){return function assignWith(e,t,r,o){for(var i in e=e||{},r=r||{},o=o||(()=>{}),t=t||{}){var n=o(e[i],t[i]);e[i]=void 0===n?t[i]:n}for(var s in r){var a=o(e[s],r[s]);e[s]=void 0===a?r[s]:a}return e}({},e,t,(function(e,t){return void 0===t?e:t}))}function getFileExtension(e){var t=e.lastIndexOf("."),r=t>-1?e.slice(t+1):"";return/^\d+$/.test(r.trim())&&(r=""),r}class BaseWebsocket$1 extends Ie{constructor(e,t,r){super(),this.websocket=null,this.socketConnectTimer=0,this.linkSSL=!0,this.url="",this.core=e,this.url=t,this.linkSSL=r,this.status="disconnected",this.logger=e.logger,this.connect()}connect(){"connecting"!==this.status&&"connected"!==this.status?(this.status="connecting",this._createWebsocket(`${this.linkSSL?"wss":"ws"}://${this.url}/websocket`)):this.logger.warn("imsocket::socket is connecting or connected",this.status)}close(){if(this.status="disconnected",this.websocket){this.logger.log("imsocket:: close websocket");try{this.websocket.close()}catch(e){this.logger.warn("imsocket::attempt to close websocket error",e)}this.clean(),this.emit("disconnect")}}clean(){this.status="disconnected",clearTimeout(this.socketConnectTimer),this.websocket&&(this.socketUrl=void 0,this.websocket.onmessage=null,this.websocket.onopen=null,this.websocket.onerror=null,this.websocket.onclose=null,this.websocket=null)}onConnect(){this.status="connected",this.emit("connect"),clearTimeout(this.socketConnectTimer)}_createWebsocket(e){this.socketConnectTimer=setTimeout((()=>{this.logger.error("imsocket::Websocket connect timeout. url: ",e),this.emit("connectFailed",new V2NIMErrorImpl({code:"v2"===get(this.core,"options.apiVersion")?_e.V2NIM_ERROR_CODE_CONNECT_TIMEOUT:415,detail:{reason:`imsocket::Websocket connect timeout. url: ${e}`}}))}),this.core.options.socketConnectTimeout||8e3),this.socketUrl=e,this.websocket=new ae.WebSocket(e),this.websocket.binaryType="arraybuffer",this.websocket.onmessage=this.onMessage.bind(this),this.websocket.onclose=e=>{e=e||{},this.logger.log(`imsocket::Websocket onclose done ${e.wasClean}/${e.code}/${e.reason}`),"connected"===this.status?(this.clean(),this.emit("disconnect")):(this.clean(),this.emit("connectFailed",new V2NIMErrorImpl({code:"v2"===get(this.core,"options.apiVersion")?_e.V2NIM_ERROR_CODE_CONNECT_FAILED:414,detail:{reason:"imsocket::Websocket onclose done"}})))},this.websocket.onerror=e=>{this.logger.error("imsocket::Websocket onerror",e),"connected"===this.status?(this.clean(),this.emit("disconnect")):(this.clean(),this.emit("connectFailed",new V2NIMErrorImpl({code:"v2"===get(this.core,"options.apiVersion")?_e.V2NIM_ERROR_CODE_CONNECT_FAILED:414,detail:{reason:"imsocket::Websocket onerror."}})))},this.websocket.onopen=()=>{this.onConnect()}}onMessage(e){if(e.data){var t=new PacketDecoder(e.data),r={sid:-1,cid:-1,ser:-1,packetLength:-1},o=null;try{t.unmarshalHeader(),r=t.getHeader(),o=t.getInnerHeader()}catch(t){this.reportBinaryError({err:t,sid:o?o.sid:null==r?void 0:r.sid,cid:o?o.cid:null==r?void 0:r.cid,rawBuf:e.data,type:"decode"})}var i=o?o.sid:r.sid,n=o?o.cid:r.cid,s=`${i}_${n}`,a=Re[s];if(a&&a.length>0){var c,l=a[0].config;try{c=t.unmarshal(l.response)}catch(o){var _=t.getBodyDetail();this.reportBinaryError({err:o,rawBuf:e.data,sid:i,cid:n,parseDetail:_,type:"decode"}),t.reset();var d=Object.assign(Object.assign({},r),{sid:i,cid:n,code:_e.V2NIM_ERROR_CODE_UNPACK_ERROR});return this.logger.error(`imsocket::onMessage "${d.sid}_${d.cid}", ser ${d.ser}, packetLength ${d.packetLength} unmarshal error. ${_} \n`,o),void this.emit("message",JSON.stringify(d))}this.emit("message",c)}else this.core.logger.warn("imsocket::onMessage cmd not found",s);t.reset()}}send(e,t,r,o,i){var n,s,a=new PacketEncoder(e,t,r),c=Se[o],l="";try{l=JSON.stringify(i),s=a.marshal(JSON.parse(l),c.params)}catch(o){throw this.reportBinaryError({err:o,sid:e,cid:t,rawStr:l,type:"encode"}),a.reset(),new V2NIMErrorImpl({code:_e.V2NIM_ERROR_CODE_PACK_ERROR,detail:{reason:`${e}-${t}, ser ${r} marshal error`,rawError:o}})}null===(n=this.websocket)||void 0===n||n.send(s),a.reset()}reportBinaryError(e){var t,r,o,{err:i,rawStr:n,sid:s,cid:a,type:c,parseDetail:l}=e,_=e.rawBuf;if(_){try{o=function arrayBufferToBase64(e){if("function"!=typeof btoa)return"";for(var t="",r=new Uint8Array(e),o=r.byteLength,i=0;i<o;i++)t+=String.fromCharCode(r[i]);return r=null,btoa(t)}(_)}catch(e){o=`reportBinaryError::arrayBufferToBase64 parsing failed, error: ${null==e?void 0:e.message}, sid: ${s}, cid: ${a}`,this.core.logger.error(o)}_=null}this.core.reporter.reportTraceStart("exceptions",{user_id:null===(t=this.core.auth)||void 0===t?void 0:t.account,trace_id:null===(r=this.core.clientSocket.socket)||void 0===r?void 0:r.sessionId,start_time:Date.now(),action:2,exception_service:9});var d=i?(`${i.message};;;`||`${i.code};;;`)+(l?`parseDetail: ${l};;;`:"")+(n?` rawStr: ${n}`:"")+(o?` rawBuf: ${o}`:""):"";this.core.reporter.reportTraceUpdateV2("exceptions",{code:"encode"===c?_e.V2NIM_ERROR_CODE_PACK_ERROR:_e.V2NIM_ERROR_CODE_UNPACK_ERROR,description:d,operation_type:"encode"===c?3:4,target:`${s}-${a}`},{asyncParams:ae.net.getNetworkStatus()}),this.core.reporter.reportTraceEnd("exceptions",1)}}!function(e){e[e.ACTIVE=1]="ACTIVE",e[e.KICKED=2]="KICKED",e[e.OFFLINE=3]="OFFLINE"}(Ae||(Ae={}));class V2BinaryClientSocket{constructor(e){this.isReconnect=!1,this.packetTimeout=8e3,this.linkSSL=!0,this.packetSer=1,this.backoff=new pe({max:8e3,min:1600,jitter:.01}),this.sendingCmdMap=new Map,this.pingTimer=0,this.hasNetworkListener=!1,this.core=e,this.auth=e.auth,this.logger=e.logger,this.reporter=e.reporter,this.timerManager=e.timerManager,this.eventBus=e.eventBus,this.setListener()}setListener(){this.core.eventBus.on("V2NIMLoginService/loginLifeCycleLoginSucc",(()=>{this.isReconnect=!0}))}setSessionId(e){this.socket&&(this.socket.sessionId=e)}setLinkSSL(e){this.linkSSL=e}connect(e,t=!1){var r,o;return __awaiter(this,void 0,void 0,(function*(){this.isReconnect=t;var i=this.core.auth.getConnectStatus();if(1===i){var n=`clientSocket::connect status is ${i}, and would not repeat connect`,s=new V2NIMErrorImpl({code:_e.V2NIM_ERROR_CODE_ILLEGAL_STATE,detail:{reason:n}});return this.logger.warn(n),Promise.reject(s)}this.auth.lifeCycle.processEvent("connect");try{yield this.auth.doLoginStepsManager.add(this.doConnect(e)),this.logger.log(`clientSocketV2:: connect success with link url: ${e}, isReconnect: ${t}`),this.core.reporter.reportTraceUpdateV2("login",{operation_type:"TCP",target:e,code:200,mixlink:!0,succeed:!0},{asyncParams:ae.net.getNetworkStatus()}),this.auth.lifeCycle.processEvent("connectSucc")}catch(t){var a=t;if(this.core.reporter.reportTraceUpdateV2("login",{operation_type:"TCP",target:e,code:a.code||0,description:`connectFailed:${a.message}`,mixlink:!0,succeed:!1},{asyncParams:ae.net.getNetworkStatus()}),a.code===_e.V2NIM_ERROR_CODE_CANCELLED||a.code===_e.V2NIM_ERROR_CODE_TIMEOUT)throw null===(r=this.socket)||void 0===r||r.close(),null===(o=this.socket)||void 0===o||o.removeAllListeners(),this.socket=void 0,t;throw this.logger.warn(`clientSocketV2::connect failed with link url: ${e}`,a),this.auth.lifeCycle.processEvent("connectFail",a),t}}))}doConnect(e){var t=!1;return new Promise(((r,o)=>{this.socket=new BaseWebsocket$1(this.core,e,this.linkSSL),this.socket.on("connect",(()=>{this.logger.log("clientSocketV2::socket on connect",e),this.core.reporterHookLinkKeep.start(),this.core.reporterHookLinkKeep.update({code:0,description:"connection begin",operation_type:0,target:e}),t=!0,r()})),this.socket.on("message",this.onMessage.bind(this)),this.socket.on("disconnect",(r=>__awaiter(this,void 0,void 0,(function*(){t=!0,this.logger.log(`clientSocketV2::socket on disconnect ${e}`,r),yield this.core.reporterHookLinkKeep.update({code:(null==r?void 0:r.code)||0,description:(null==r?void 0:r.reason)||"socket on disconnect",operation_type:1,target:e}),this.core.reporterHookLinkKeep.end(!1),this.doDisconnect(Ae.OFFLINE,"SocketOnDisconnect")})))),this.socket.on("connectFailed",(r=>{t?this.ping():(this.logger.error(`clientSocketV2::connectFailed:${e}, reason:${r&&r.message}`),this.cleanSocket()),t=!0,o(r)}))}))}cleanSocket(){this.socket&&("function"==typeof this.socket.removeAllListeners&&this.socket.removeAllListeners(),"function"==typeof this.socket.close&&this.socket.close(),this.socket=void 0)}resetSocketConfig(){this.backoff.reset(),this.initOnlineListener()}doDisconnect(e,t){if(this.logger.log(`clientSocketV2::doDisconnect:type:${e},reason:`,t),0!==this.core.auth.getConnectStatus()){var r={1:"close",2:"kicked",3:"broken"}[e]||"";this.markAllCmdInvaild(new V2NIMErrorImpl({code:_e.V2NIM_ERROR_CODE_DISCONNECT,detail:{reason:"Packet timeout due to instance disconnect",disconnect_reason:r}})),this.timerManager.destroy(),clearTimeout(this.pingTimer),this.cleanSocket(),e===Ae.ACTIVE||e===Ae.KICKED?this.destroyOnlineListener():e===Ae.OFFLINE&&(this.auth.lifeCycle.processEvent("connectionBroken",new V2NIMErrorImpl({code:_e.V2NIM_ERROR_CODE_DISCONNECT,detail:{reason:"connection broken due to internal reasons"}})),this.logger.log(`clientSocketV2::doDisconnect: pending reconnect ${this.isReconnect}`),this.isReconnect&&this.auth.lifeCycle.processEvent("waiting"))}else this.logger.warn("clientSocketV2::doDisconnect:already disconnected")}sendCmd(e,t,r){var o=this.core.auth.getLoginStatus(),i={cmd:e};if(1!==o&&!["v2Login","login","chatroomLogin","v2ChatroomLogin"].includes(e))return this.logger.warn(`clientSocketV2::NIM login status is ${o}, so can not sendCmd ${e}`),Promise.reject(new V2NIMErrorImpl({code:_e.V2NIM_ERROR_CODE_ILLEGAL_STATE,detail:Object.assign({reason:"Can not sendCmd due to no logined"},i)}));var n="heartbeat"!==e,s=n?this.packetSer++:0,a=createCmd(e,s,this.logger,t);if(!a){var c=new V2NIMErrorImpl({code:_e.V2NIM_ERROR_CODE_INTERNAL,detail:Object.assign(Object.assign({},i),{reason:`SendCmd::createCmd error: ${s} ${e}`})});return this.logger.error(c),Promise.reject(c)}var{packet:l,hasPacketResponse:_,hasPacketTimer:d}=a,E=JSON.stringify(l);n&&(this.logger.getDebugMode()?this.logger.debug(`clientSocketV2::sendCmd: ${l.SID}_${l.CID},${e},ser:${s}`,E):this.logger.log(`clientSocketV2::sendCmd: ${l.SID}_${l.CID},${e},ser:${s}`));var h=(new Date).getTime();return new Promise(((o,n)=>{_&&this.sendingCmdMap.set(s,{cmd:e,params:t,callback:[o,n],timer:d?setTimeout((()=>{var t=new V2NIMErrorImpl({code:_e.V2NIM_ERROR_CODE_PROTOCOL_TIMEOUT,detail:Object.assign({ser:s,reason:`Packet Timeout: ser ${s} cmd ${e}`,timetag:(new Date).getTime()},i)});this.markCmdInvalid(s,t,e)}),r&&r.timeout?r.timeout:this.packetTimeout):null});try{this.socket.send(l.SID,l.CID,s,e,l.Q),_||o(l)}catch(t){var a=new V2NIMErrorImpl({code:_e.V2NIM_ERROR_CODE_PROTOCOL_SEND_FAILED,detail:Object.assign({ser:s,reason:"Unable to send packet"+(t&&t.message?": "+t.message:""),timetag:(new Date).getTime(),rawError:t},i)});this.markCmdInvalid(s,a,e),n(a)}})).catch((e=>__awaiter(this,void 0,void 0,(function*(){var t=e;return[_e.V2NIM_ERROR_CODE_DISCONNECT,_e.V2NIM_ERROR_CODE_PROTOCOL_TIMEOUT,_e.V2NIM_ERROR_CODE_PROTOCOL_SEND_FAILED].includes(t.code)?(this.reportSendCmdFailed(t,{sid:l.SID,cid:l.CID,ser:s},h),Promise.reject(t)):Promise.reject(t)}))))}reportSendCmdFailed(e,t,r){var o;this.reporter.reportTraceStart("exceptions",{user_id:this.core.auth.getLoginUser(),trace_id:null===(o=this.socket)||void 0===o?void 0:o.sessionId,start_time:r,action:2,exception_service:6});var i=get(e,"detail.disconnect_reason")||"",n=e.code===_e.V2NIM_ERROR_CODE_DISCONNECT?JSON.stringify({disconnect_reason:i}):e.detail.reason;this.reporter.reportTraceUpdateV2("exceptions",{code:e.code,description:n,operation_type:1,target:`${t.sid}-${t.cid}`,context:`${t.ser}`},{asyncParams:ae.net.getNetworkStatus()}),this.reporter.reportTraceEnd("exceptions",1)}onMessage(e){var t=parseCmd(e,this.logger);if(t&&t.length>0){var r=t[0],o=r.raw.ser;for(var i of(r.error&&(this.logger.error("clientSocketV2::onMessage packet error",`${r.raw.sid}_${r.raw.cid}, ser:${o},`,r.error),r.error.code===_e.V2NIM_ERROR_CODE_UNPACK_ERROR&&this.core.eventBus.emit("BinaryClientSocket/unpackError")),"heartbeat"!==r.cmd&&(this.logger.getDebugMode()?this.logger.debug(`clientSocketV2::recvCmd ${r.raw.sid}_${r.raw.cid},${r.cmd},ser:${o}`,e):this.logger.log(`clientSocketV2::recvCmd ${r.raw.sid}_${r.raw.cid},${r.cmd},ser:${o},code:${r.raw.code}`)),t))this.packetHandler(i)}}packetHandler(e){var t,r,o,i;if(e){var n=e.raw.ser,s=this.sendingCmdMap.get(n);if(s&&s.cmd===e.cmd){var{callback:a,timer:c,params:l}=s;if(clearTimeout(c),e.params=l,this.sendingCmdMap.delete(n),"heartbeat"===e.cmd)return void a[0]();var _=null===(r=null===(t=this.core[e.service])||void 0===t?void 0:t.process)||void 0===r?void 0:r.call(t,e);_&&"function"==typeof _.then?_.then((e=>{a[0](e)})).catch((e=>{a[1](e)})):(this.logger.log("clientSocketV2::handlerFn without promise",e.service,e.cmd),a[0](e))}else{var d=null===(i=null===(o=this.core[e.service])||void 0===o?void 0:o.process)||void 0===i?void 0:i.call(o,e);d&&"function"==typeof d.then&&d.catch((e=>{this.logger.error("clientSocketV2::no obj cache, no process handler",e)}))}}}markCmdInvalid(e,t,r){var o=this.sendingCmdMap.get(e);if(o){var{callback:i,timer:n}=o;n&&clearTimeout(n),this.sendingCmdMap.delete(e),this.logger.warn(`clientSocketV2::packet ${e}, ${r} is invalid:`,t),i[1](t)}}markAllCmdInvaild(e){this.logger.log("markAllCmdInvaild",e),this.sendingCmdMap.forEach((t=>{var{callback:r,timer:o,cmd:i}=t;this.logger.log(`clientSocketV2::markAllCmdInvaild:cmd ${i}`),o&&clearTimeout(o),r[1](e)})),this.sendingCmdMap.clear()}ping(){var e;return __awaiter(this,void 0,void 0,(function*(){clearTimeout(this.pingTimer);try{yield this.sendCmd("heartbeat")}catch(t){if(t.code===_e.V2NIM_ERROR_CODE_DISCONNECT)return;if(yield this.testHeartBeat5Timeout())return yield this.core.reporterHookLinkKeep.update({code:0,description:"Heartbeat-discovered link failure",operation_type:1,target:null===(e=this.socket)||void 0===e?void 0:e.url}),this.core.reporterHookLinkKeep.end(!0),void this.doDisconnect(Ae.OFFLINE,"PingError")}this.pingTimer=setTimeout((()=>{this.ping()}),3e4)}))}testHeartBeat5Timeout(){return __awaiter(this,void 0,void 0,(function*(){clearTimeout(this.pingTimer);for(var e=0;e<5;e++)try{return yield this.sendCmd("heartbeat",{},{timeout:3e3}),!1}catch(t){this.logger.log(`clientSocketV2::test heartbeat ${e} Timeout`)}return!0}))}initOnlineListener(){this.hasNetworkListener||(this.logger.log("clientSocketV2::onlineListener:init"),this.hasNetworkListener=!0,ae.net.onNetworkStatusChange((e=>{this.logger.log("clientSocketV2::onlineListener:network change",e);var t=this.auth.getLoginStatus();e.isConnected&&1===t?this.ping():e.isConnected&&3===t?(this.logger.log("clientSocketV2::onlineListener:online and connectStatus is waiting, do reLogin"),this.auth.reconnect.clearReconnectTimer(),this.auth.reconnect.doReLogin()):e.isConnected||this.doDisconnect(Ae.OFFLINE,"OfflineListener")})))}destroyOnlineListener(){this.logger.log("clientSocketV2::onlineListener:destroy"),ae.net.offNetworkStatusChange(),this.hasNetworkListener=!1}}var ye,De=["disconnect","connect","heartbeat","message","json","event","ack","error","noop"],Ve=["transport not supported","client not handshaken","unauthorized"],Le=["reconnect"];class BaseWebsocket extends Ie{constructor(e,t,r){super(),this.websocket=null,this.socketConnectTimer=0,this.url="",this.linkSSL=!0,this.core=e,this.url=t,this.linkSSL=r,this.status="disconnected",this.logger=e.logger,this.connect()}connect(){"connecting"!==this.status&&"connected"!==this.status?(this.status="connecting",this.core.adapters.request(`${this.linkSSL?"https":"http"}://${this.url}/socket.io/1/?t=${Date.now()}`,{method:"GET",dataType:"text",timeout:this.core.options.xhrConnectTimeout||8e3},{exception_service:6}).then((e=>{if("connecting"===this.status){var[t,r]=e.data.split(":");return this.sessionId=t,this.logger.log(`imsocket::XHR success. status ${this.status}, ${"connecting"===this.status?"continue websocket connection":"stop websocket connection"}`),this._createWebsocket(`${this.linkSSL?"wss":"ws"}://${this.url}/socket.io/1/websocket/${t}`)}})).catch((e=>{if("connecting"===this.status){var t=`imsocket::XHR fail. raw message: "${(e=e||{}).message}", code: "${e.code}"`,r=e.code;r="v2"===get(this.core,"options.apiVersion")?e.code===_e.V2NIM_ERROR_CODE_CONNECT_TIMEOUT?_e.V2NIM_ERROR_CODE_CONNECT_TIMEOUT:_e.V2NIM_ERROR_CODE_CONNECT_FAILED:408===e.code?408:415;var o=new V2NIMErrorImpl({code:r,detail:{reason:t,rawError:e}});this.logger.error(t),this.status="disconnected",this.emit("handshakeFailed",o)}}))):this.logger.warn("imsocket::socket is connecting or connected",this.status)}close(){if(this.status="disconnected",this.websocket){this.logger.log("imsocket:: close websocket");try{this.websocket.send(this.encodePacket({type:"disconnect"}))}catch(e){this.logger.warn("imsocket::attempt to send encodePacket error",e)}try{this.websocket.close()}catch(e){this.logger.warn("imsocket::attempt to close websocket error",e)}this.clean(),this.emit("disconnect",{code:0,reason:"Active close websocket"})}}clean(){this.status="disconnected",clearTimeout(this.socketConnectTimer),this.websocket&&(this.socketUrl=void 0,this.websocket.onmessage=null,this.websocket.onopen=null,this.websocket.onerror=null,this.websocket.onclose=null,this.websocket=null)}onConnect(){this.status="connected",this.emit("connect"),clearTimeout(this.socketConnectTimer)}_createWebsocket(e){this.socketConnectTimer=setTimeout((()=>{this.logger.error("imsocket::Websocket connect timeout. url: ",this.socketUrl),this.emit("handshakeFailed",new V2NIMErrorImpl({code:"v2"===get(this.core,"options.apiVersion")?_e.V2NIM_ERROR_CODE_CONNECT_TIMEOUT:415,detail:{reason:`imsocket::Websocket connect timeout. url: ${this.socketUrl}`}}))}),this.core.options.socketConnectTimeout||8e3),this.socketUrl=e,this.websocket=new ae.WebSocket(e),this.websocket.onmessage=this.onMessage.bind(this),this.websocket.onclose=e=>{e=e||{},this.logger.log(`imsocket::Websocket onclose done ${e.wasClean}/${e.code}/${e.reason}`),this.clean(),this.emit("disconnect",{code:e.code||0,reason:e.reason})},this.websocket.onerror=e=>{this.logger.error("imsocket::Websocket onerror",e),"logined"===this.core.status&&this.core.clientSocket.ping()}}onMessage(e){var t,r=this.decodePacket(e.data);if(r)switch(r.type){case"connect":this.onConnect();break;case"disconnect":this.close(),this.emit("disconnect",{code:0,reason:"MessageEvent type disconnect"});break;case"message":case"json":this.emit("message",r.data);break;case"event":r.name&&this.emit(r.name,r.args);break;case"error":"unauthorized"===r.reason?this.emit("connect_failed",r.reason):this.emit("error",r.reason),this.logger.error("imsocket::Websocket connect failed, onmessage type error. url: ",this.socketUrl),clearTimeout(this.socketConnectTimer),this.emit("handshakeFailed",new V2NIMErrorImpl({code:"v2"===get(this.core,"options.apiVersion")?_e.V2NIM_ERROR_CODE_CONNECT_FAILED:408,detail:{reason:`imsocket::Websocket connect failed, onMessage socket error. url: ${this.socketUrl}`}}));break;case"heartbeat":null===(t=this.websocket)||void 0===t||t.send(this.encodePacket({type:"heartbeat"}));break;default:this.logger.warn("imsocket::Websocket no handler type",r.type)}}encodePacket(e){var t,r,{type:o,id:i="",endpoint:n="",ack:s}=e,a=null;if(!o)return"";switch(o){case"error":t=e.reason?Ve.indexOf(e.reason):"",r=e.advice?Le.indexOf(e.advice):"",""===t&&""===r||(a=t+(""!==r?"+"+r:""));break;case"message":""!==e.data&&(a=e.data);break;case"event":t={name:e.name},t=e.args&&e.args.length?{name:e.name,args:e.args}:{name:e.name},a=JSON.stringify(t);break;case"json":a=JSON.stringify(e.data);break;case"connect":e.qs&&(a=e.qs);break;case"ack":a=e.ackId+(e.args&&e.args.length?"+"+JSON.stringify(e.args):"")}var c=[De.indexOf(o),i+("data"===s?"+":""),n];return null!=a&&c.push(a),c.join(":")}decodePacket(e){if(e)if("�"!=e.charAt(0)){var t=e.match(/([^:]+):([0-9]+)?(\+)?:([^:]+)?:?([\s\S]*)?/);if(t){var r,[,o,i,n,s,a]=t,c={type:De[+o],endpoint:s};switch(i&&(c.id=i,c.ack=!n||"data"),c.type){case"error":r=a.split("+"),c.reason=Ve[+r[0]]||"";break;case"message":c.data=a||"";break;case"connect":c.qs=a||"";break;case"event":try{var l=JSON.parse(a);c.name=l.name,c.args=l.args}catch(e){this.logger.error("imsocket::parseData::type::event error",e)}c.args=c.args||[];break;case"json":try{c.data=JSON.parse(a)}catch(e){this.logger.error("imsocket::parseData::type::json error",e)}break;case"ack":if((r=a.match(/^([0-9]+)(\+)?(.*)/))&&(c.ackId=r[1],c.args=[],r[3]))try{c.args=r[3]?JSON.parse(r[3]):[]}catch(e){this.logger.error("imsocket::parseData::type::ack error",e)}}return c}}else this.logger.error("imsocket::unrecognize dataStr",e.slice(0,20))}send(e){var t,r={data:e,type:"message",endpoint:""};null===(t=this.websocket)||void 0===t||t.send(this.encodePacket(r))}}!function(e){e[e.ACTIVE=1]="ACTIVE",e[e.KICKED=2]="KICKED",e[e.OFFLINE=3]="OFFLINE"}(ye||(ye={}));class V2ClientSocket{constructor(e){this.isReconnect=!1,this.packetTimeout=8e3,this.linkSSL=!0,this.packetSer=1,this.backoff=new pe({max:8e3,min:1600,jitter:.01}),this.sendingCmdMap=new Map,this.pingTimer=0,this.hasNetworkListener=!1,this.core=e,this.auth=e.auth,this.logger=e.logger,this.reporter=e.reporter,this.timerManager=e.timerManager,this.eventBus=e.eventBus,this.setListener()}setListener(){this.core.eventBus.on("V2NIMLoginService/loginLifeCycleLoginSucc",(()=>{this.isReconnect=!0}))}setSessionId(e){this.socket&&(this.socket.sessionId=e)}setLinkSSL(e){this.linkSSL=e}connect(e,t=!1){var r,o;return __awaiter(this,void 0,void 0,(function*(){this.isReconnect=t;var i=this.core.auth.getConnectStatus();if(1===i){var n=`clientSocket::connect status is ${i}, and would not repeat connect`,s=new V2NIMErrorImpl({code:_e.V2NIM_ERROR_CODE_ILLEGAL_STATE,detail:{reason:n}});return this.logger.warn(n),Promise.reject(s)}this.auth.lifeCycle.processEvent("connect");try{yield this.auth.doLoginStepsManager.add(this.doConnect(e)),this.logger.log(`clientSocketV2:: connect success with link url: ${e}, isReconnect: ${t}`),this.core.reporter.reportTraceUpdateV2("login",{operation_type:"TCP",target:e,code:200,mixlink:!0,succeed:!0},{asyncParams:ae.net.getNetworkStatus()}),this.auth.lifeCycle.processEvent("connectSucc")}catch(t){var a=t;if(this.core.reporter.reportTraceUpdateV2("login",{operation_type:"TCP",target:e,code:a.code||0,description:`connectFailed:${a.message}`,mixlink:!0,succeed:!1},{asyncParams:ae.net.getNetworkStatus()}),a.code===_e.V2NIM_ERROR_CODE_CANCELLED||a.code===_e.V2NIM_ERROR_CODE_TIMEOUT)throw null===(r=this.socket)||void 0===r||r.close(),null===(o=this.socket)||void 0===o||o.removeAllListeners(),this.socket=void 0,t;throw this.logger.warn(`clientSocketV2::connect failed with link url: ${e}`,a),this.auth.lifeCycle.processEvent("connectFail",a),t}}))}doConnect(e){var t=!1;return new Promise(((r,o)=>{this.socket=new BaseWebsocket(this.core,e,this.linkSSL),this.socket.on("connect",(()=>{this.logger.log("clientSocketV2::socket on connect",e),this.core.reporterHookLinkKeep.start(),this.core.reporterHookLinkKeep.update({code:0,description:"connection begin",operation_type:0,target:e}),t=!0,r()})),this.socket.on("message",this.onMessage.bind(this)),this.socket.on("disconnect",(r=>__awaiter(this,void 0,void 0,(function*(){t=!0,this.logger.log("clientSocketV2::socket on disconnect",r),yield this.core.reporterHookLinkKeep.update({code:(null==r?void 0:r.code)||0,description:(null==r?void 0:r.reason)||"socket on disconnect",operation_type:1,target:e}),this.core.reporterHookLinkKeep.end(!1),this.doDisconnect(ye.OFFLINE,"SocketOnDisconnect")})))),this.socket.on("handshakeFailed",(e=>{t?this.ping():(this.logger.error(`clientSocketV2::handshake failed: "${e&&e.message}"`),this.cleanSocket()),t=!0,o(e)}))}))}cleanSocket(){this.socket&&("function"==typeof this.socket.removeAllListeners&&this.socket.removeAllListeners(),"function"==typeof this.socket.close&&this.socket.close(),this.socket=void 0)}resetSocketConfig(){this.backoff.reset(),this.initOnlineListener()}doDisconnect(e,t){if(this.logger.log(`clientSocketV2::doDisconnect:type:${e},reason:`,t),0!==this.core.auth.getConnectStatus()){var r={1:"close",2:"kicked",3:"broken"}[e]||"";this.markAllCmdInvaild(new V2NIMErrorImpl({code:_e.V2NIM_ERROR_CODE_DISCONNECT,detail:{reason:"Packet timeout due to instance disconnect",disconnect_reason:r}})),this.timerManager.destroy(),clearTimeout(this.pingTimer),this.cleanSocket(),e===ye.ACTIVE||e===ye.KICKED?this.destroyOnlineListener():e===ye.OFFLINE&&(this.auth.lifeCycle.processEvent("connectionBroken",new V2NIMErrorImpl({code:_e.V2NIM_ERROR_CODE_DISCONNECT,detail:{reason:"connection broken due to internal reasons"}})),this.logger.log(`clientSocketV2::doDisconnect: pending reconnect ${this.isReconnect}`),this.isReconnect&&this.auth.lifeCycle.processEvent("waiting"))}else this.logger.warn("clientSocketV2::doDisconnect:already disconnected")}sendCmd(e,t,r){var o=this.core.auth.getLoginStatus(),i={cmd:e};if(1!==o&&!["v2Login","login","chatroomLogin","v2ChatroomLogin"].includes(e))return this.logger.warn(`clientSocketV2::NIM login status is ${o}, so can not sendCmd ${e}`),Promise.reject(new V2NIMErrorImpl({code:_e.V2NIM_ERROR_CODE_ILLEGAL_STATE,detail:Object.assign({reason:"Can not sendCmd due to no logined"},i)}));var n="heartbeat"!==e,s=n?this.packetSer++:0,a=createCmd(e,s,this.logger,t);if(!a){var c=new V2NIMErrorImpl({code:_e.V2NIM_ERROR_CODE_INTERNAL,detail:Object.assign(Object.assign({},i),{reason:`SendCmd::createCmd error: ${s} ${e}`})});return this.logger.error(c),Promise.reject(c)}var{packet:l,hasPacketResponse:_,hasPacketTimer:d}=a,E=JSON.stringify(l);n&&(this.logger.getDebugMode()?this.logger.debug(`clientSocketV2::sendCmd: ${l.SID}_${l.CID},${e},ser:${s}`,E):this.logger.log(`clientSocketV2::sendCmd: ${l.SID}_${l.CID},${e},ser:${s}`));var h=(new Date).getTime();return new Promise(((o,n)=>{_&&this.sendingCmdMap.set(s,{cmd:e,params:t,callback:[o,n],timer:d?setTimeout((()=>{var t=new V2NIMErrorImpl({code:_e.V2NIM_ERROR_CODE_PROTOCOL_TIMEOUT,detail:Object.assign({ser:s,reason:`Packet Timeout: ser ${s} cmd ${e}`,timetag:(new Date).getTime()},i)});this.markCmdInvalid(s,t,e)}),r&&r.timeout?r.timeout:this.packetTimeout):null});try{this.socket.send(E),_||o(l)}catch(t){var a=new V2NIMErrorImpl({code:_e.V2NIM_ERROR_CODE_PROTOCOL_SEND_FAILED,detail:Object.assign({ser:s,reason:"Unable to send packet"+(t&&t.message?": "+t.message:""),timetag:(new Date).getTime(),rawError:t},i)});this.markCmdInvalid(s,a,e),n(a)}})).catch((e=>__awaiter(this,void 0,void 0,(function*(){var t,r=e;if(![_e.V2NIM_ERROR_CODE_DISCONNECT,_e.V2NIM_ERROR_CODE_PROTOCOL_TIMEOUT,_e.V2NIM_ERROR_CODE_PROTOCOL_SEND_FAILED].includes(r.code))return Promise.reject(r);this.reporter.reportTraceStart("exceptions",{user_id:this.core.auth.getLoginUser(),trace_id:null===(t=this.socket)||void 0===t?void 0:t.sessionId,start_time:h,action:2,exception_service:6});var o=get(r,"detail.disconnect_reason")||"",i=r.code===_e.V2NIM_ERROR_CODE_DISCONNECT?JSON.stringify({disconnect_reason:o}):r.detail.reason;return this.reporter.reportTraceUpdateV2("exceptions",{code:r.code,description:i,operation_type:1,target:`${l.SID}-${l.CID}`,context:`${l.SER}`},{asyncParams:ae.net.getNetworkStatus()}),this.reporter.reportTraceEnd("exceptions",1),Promise.reject(r)}))))}onMessage(e){var t=parseCmd(e,this.logger);if(t&&t.length>0){var r=t[0],o=r.raw.ser;for(var i of(r.error&&this.logger.error("clientSocketV2::onMessage packet error",`${r.raw.sid}_${r.raw.cid}, ser:${o},`,r.error),"heartbeat"!==r.cmd&&(this.logger.getDebugMode()?this.logger.debug(`clientSocketV2::recvCmd ${r.raw.sid}_${r.raw.cid},${r.cmd},ser:${o}`,r.content):this.logger.log(`clientSocketV2::recvCmd ${r.raw.sid}_${r.raw.cid},${r.cmd},ser:${o};code:${r.raw.code}`)),t))this.packetHandler(i)}}packetHandler(e){var t,r,o,i;if(e){var n=e.raw.ser,s=this.sendingCmdMap.get(n);if(s&&s.cmd===e.cmd){var{callback:a,timer:c,params:l}=s;if(clearTimeout(c),e.params=l,this.sendingCmdMap.delete(n),"heartbeat"===e.cmd)return void a[0]();var _=null===(r=null===(t=this.core[e.service])||void 0===t?void 0:t.process)||void 0===r?void 0:r.call(t,e);_&&"function"==typeof _.then?_.then((e=>{a[0](e)})).catch((e=>{a[1](e)})):(this.logger.log("clientSocketV2::handlerFn without promise",e.service,e.cmd),a[0](e))}else{var d=null===(i=null===(o=this.core[e.service])||void 0===o?void 0:o.process)||void 0===i?void 0:i.call(o,e);d&&"function"==typeof d.then&&d.catch((e=>{this.logger.error("clientSocketV2::no obj cache, no process handler",e)}))}}}markCmdInvalid(e,t,r){var o=this.sendingCmdMap.get(e);if(o){var{callback:i,timer:n}=o;n&&clearTimeout(n),this.sendingCmdMap.delete(e),this.logger.warn(`clientSocketV2::packet ${e}, ${r} is invalid:`,t),i[1](t)}}markAllCmdInvaild(e){this.logger.log("markAllCmdInvaild",e),this.sendingCmdMap.forEach((t=>{var{callback:r,timer:o,cmd:i}=t;this.logger.log(`clientSocketV2::markAllCmdInvaild:cmd ${i}`),o&&clearTimeout(o),r[1](e)})),this.sendingCmdMap.clear()}ping(){var e;return __awaiter(this,void 0,void 0,(function*(){clearTimeout(this.pingTimer);try{yield this.sendCmd("heartbeat")}catch(t){if(t.code===_e.V2NIM_ERROR_CODE_DISCONNECT)return;if(yield this.testHeartBeat5Timeout())return yield this.core.reporterHookLinkKeep.update({code:0,description:"Heartbeat-discovered link failure",operation_type:1,target:null===(e=this.socket)||void 0===e?void 0:e.url}),this.core.reporterHookLinkKeep.end(!0),void this.doDisconnect(ye.OFFLINE,"PingError")}this.pingTimer=setTimeout((()=>{this.ping()}),3e4)}))}testHeartBeat5Timeout(){return __awaiter(this,void 0,void 0,(function*(){clearTimeout(this.pingTimer);for(var e=0;e<5;e++)try{return yield this.sendCmd("heartbeat",{},{timeout:3e3}),!1}catch(t){this.logger.log(`clientSocketV2::test heartbeat ${e} Timeout`)}return!0}))}initOnlineListener(){this.hasNetworkListener||(this.logger.log("clientSocketV2::onlineListener:init"),this.hasNetworkListener=!0,ae.net.onNetworkStatusChange((e=>{this.logger.log("clientSocketV2::onlineListener:network change",e);var t=this.auth.getConnectStatus(),r=this.auth.getLoginStatus();e.isConnected&&1===r?this.ping():e.isConnected&&3===t?(this.logger.log("clientSocketV2::onlineListener:online and connectStatus is waiting, do reLogin"),this.auth.reconnect.clearReconnectTimer(),this.auth.reconnect.doReLogin()):e.isConnected||this.doDisconnect(ye.OFFLINE,"OfflineListener")})))}destroyOnlineListener(){this.logger.log("clientSocketV2::onlineListener:destroy"),ae.net.offNetworkStatusChange(),this.hasNetworkListener=!1}}class TimerManager{constructor(){this.timerList=[],this.id=1,this.timer=null,this.timeout=0}addTimer(e,t=0,r=1){var o=(new Date).getTime(),i=this.id;return this.timerList.push({id:i,loop:r,count:0,timeout:o+t,interval:t,callback:e}),this.id++,this.checkTimer(o),i}checkTimer(e=(new Date).getTime()){if(this.removeFinished(),0!==this.timerList.length||null==this.timer){var t=0;for(var r of this.timerList)(0===t||t>r.timeout)&&(t=r.timeout);0!==this.timerList.length&&(null===this.timer||t<this.timeout||this.timeout<e)&&(this.timer=setTimeout(this.nowTime.bind(this),t-e),this.timeout=t)}}nowTime(){var e=(new Date).getTime();for(var t of this.timerList)e>=t.timeout&&(t.callback(),t.count++,t.timeout=e+t.interval);this.clerTime(),this.checkTimer(e)}clerTime(){null!==this.timer&&(clearTimeout(this.timer),this.timer=null)}deleteTimer(e){for(var t=this.timerList.length-1;t>=0;t--){this.timerList[t].id===e&&this.timerList.splice(t,1)}}removeFinished(){for(var e=this.timerList.length-1;e>=0;e--){var t=this.timerList[e];t.loop>=0&&t.count>=t.loop&&this.timerList.splice(e,1)}}destroy(){this.clerTime(),this.timerList=[],this.id=1,this.timer=null}}class CoreAdapters{constructor(e){this.lastSuccUploadHost="",this.core=e}getFileUploadInformation(e){return ae.getFileUploadInformation(e)}request(e,t,r){var o=(new Date).getTime(),i=(null==r?void 0:r.exception_service)||0;return ae.request(e,t).catch((r=>{var n,s,a,c,l=r;throw this.core.reporter.reportTraceStart("exceptions",{user_id:this.core.options.account||(null===(s=null===(n=this.core)||void 0===n?void 0:n.auth)||void 0===s?void 0:s.account),trace_id:null===(c=null===(a=this.core.clientSocket)||void 0===a?void 0:a.socket)||void 0===c?void 0:c.sessionId,start_time:o,action:1,exception_service:i}),this.core.reporter.reportTraceUpdateV2("exceptions",{code:"number"==typeof l.code?l.code:0,description:l.message||`${l.code}`,operation_type:0,target:e,context:t?JSON.stringify(t):""},{asyncParams:ae.net.getNetworkStatus()}),this.core.reporter.reportTraceEnd("exceptions",1),r}))}uploadFile(e){var t,r,o,i;return __awaiter(this,void 0,void 0,(function*(){for(var n="BROWSER"===ae.platform,s=n?e.chunkUploadHostBackupList:e.commonUploadHostBackupList,a=n?e.chunkUploadHost:e.commonUploadHost,c=s.indexOf(a),l=-1===c?[a,...s]:[a,...s.slice(0,c),...s.slice(c+1)],_=Math.max(l.indexOf(this.lastSuccUploadHost),0),d=null,E=0;E<l.length;E++){var h=(new Date).getTime(),u=l[(E+_)%l.length];try{var m=yield ae.uploadFile(Object.assign(Object.assign({},e),n?{chunkUploadHost:u}:{commonUploadHost:u}));return this.lastSuccUploadHost=u,"string"==typeof m.size&&(m.size=parseInt(m.size)),"string"==typeof m.dur&&(m.dur=parseInt(m.dur)),"string"==typeof m.w&&(m.w=parseInt(m.w)),"string"==typeof m.h&&(m.h=parseInt(m.h)),m}catch(e){this.core.cloudStorage.nos.nosErrorCount--,d=e;var g=e;this.core.reporter.reportTraceStart("exceptions",{user_id:this.core.options.account||(null===(r=null===(t=this.core)||void 0===t?void 0:t.auth)||void 0===r?void 0:r.account),trace_id:null===(i=null===(o=this.core.clientSocket)||void 0===o?void 0:o.socket)||void 0===i?void 0:i.sessionId,start_time:h,action:1,exception_service:3}),this.core.reporter.reportTraceUpdateV2("exceptions",{code:"number"==typeof g.code?g.code:0,description:g.message||`${g.code}`,operation_type:1,target:u},{asyncParams:ae.net.getNetworkStatus()}),this.core.reporter.reportTraceEnd("exceptions",1),this._uploadFileErrHanler(e)}}throw d}))}_uploadFileErrHanler(e){if(e&&(e.code>200||e.errCode>200))throw e}}class ABTest{constructor(e,t){this.abtInfo={},this.core=e,this.config=assignOptions({isAbtestEnable:!0,abtestUrl:me,abtestProjectKey:ge},t)}setOptions(e){this.config=assignOptions(this.config,e)}abtRequest(){var e,t;return __awaiter(this,void 0,void 0,(function*(){if(this.config.isAbtestEnable&&!this.abtInfo.experiments&&this.config.abtestUrl){var r;try{r=yield this.core.adapters.request(this.config.abtestUrl,{method:"POST",dataType:"json",headers:{sdktype:"ABTest"},data:{clientInfo:{projectKey:this.config.abtestProjectKey,appKey:this.core.options.appkey,osType:"Web",sdkVersion:"10.9.41",deviceId:this.core.config.deviceId},useLocalCache:!0}},{exception_service:7})}catch(e){this.core.logger.warn("ABTest request failed")}this.abtInfo=(null===(t=null===(e=null==r?void 0:r.data)||void 0===e?void 0:e.data)||void 0===t?void 0:t.abtInfo)||{}}}))}}function pickBy(e,t){e=e||{},t=t||(()=>!0);var r={};for(var o in e)t(e[o])&&(r[o]=e[o]);return r}function formatQueueElementsFromKVObject(e){return Object.keys(e).map((t=>({key:t,value:e[t]})))}function formatQueueElementsFromElements(e){return e&&e.length>0?e.map((e=>({key:e.key,value:e.value,accountId:e.accid,nick:e.nick}))):[]}function formatMessage(e,t,r){return t.isSelf=t.senderId===r,delete t.resend,0!==t.messageType&&10!==t.messageType||(t.text=t.text||t.attachment,delete t.attachment),5===t.messageType?t.attachment=function formatNotificationAttachment(e,t){var r,o,i,n,s,a,c,l,_,d,E,h,u,m,g,p,I,N,T={type:"number"==typeof be[e.id]?be[e.id]:e.id,targetIds:null===(r=e.data)||void 0===r?void 0:r.target,targetNicks:null===(o=e.data)||void 0===o?void 0:o.tarNick,targetTag:null===(i=e.data)||void 0===i?void 0:i.targetTag,operatorId:null===(n=e.data)||void 0===n?void 0:n.operator,operatorNick:null===(s=e.data)||void 0===s?void 0:s.opeNick,notificationExtension:null===(a=e.data)||void 0===a?void 0:a.ext,tags:null===(c=e.data)||void 0===c?void 0:c.tags,messageClientId:null===(l=e.data)||void 0===l?void 0:l.msgId,messageTime:null===(_=e.data)||void 0===_?void 0:_.msgTime,chatBanned:void 0!==(null===(d=e.data)||void 0===d?void 0:d.muted)?Boolean(null===(E=e.data)||void 0===E?void 0:E.muted):void 0,tempChatBanned:void 0!==(null===(h=e.data)||void 0===h?void 0:h.tempMuted)?Boolean(null===(u=e.data)||void 0===u?void 0:u.tempMuted):void 0,previousRole:null===(m=e.data)||void 0===m?void 0:m.previousRole,tempChatBannedDuration:"number"==typeof(null===(g=e.data)||void 0===g?void 0:g.muteTtl)?e.data.muteTtl:null===(p=e.data)||void 0===p?void 0:p.muteDuration};14===(T=pickBy(T,(e=>void 0!==e))).type?T.tempChatBanned=!0:15===T.type&&(T.tempChatBanned=!1);if(null===(I=e.data)||void 0===I?void 0:I.member){var O=e.data.member;T.currentMember=pickBy({roomId:t,accountId:O.accountId,memberRole:O.memberRole,memberLevel:O.memberLevel,roomNick:O.nick,roomAvatar:O.avatar,serverExtension:O.ext,isOnline:!!O.onlineStat,blocked:!!O.blockList,chatBanned:!!O.chatBanned,tempChatBanned:!!O.tempChatBanned,tempChatBannedDuration:"number"==typeof O.muteTtl?O.muteTtl:O.muteDuration,tags:stringToJSONObject(O.tags),notifyTargetTags:O.notifyTargetTags,enterTime:O.enterTime,updateTime:O.updateTime,valid:void 0===O.valid||!!O.valid,multiEnterInfo:formatMultiEnterInfo(O.onlineList)},(e=>void 0!==e))}if(null===(N=e.data)||void 0===N?void 0:N.queueChange){var{elements:M,queueChangeType:f}=function formatNotificationAttachmentForQueue(e){try{var t=JSON.parse(e);if("OFFER"===t._e)return{elements:[{key:t.key,value:t.content}],queueChangeType:1};if("POLL"===t._e)return{elements:[{key:t.key,value:t.content}],queueChangeType:2};if("DROP"===t._e)return{elements:[],queueChangeType:3};if("BATCH_UPDATE"===t._e)return{elements:formatQueueElementsFromKVObject(t.kvObject),queueChangeType:5};if("PARTCLEAR"===t._e)return{elements:formatQueueElementsFromKVObject(t.kvObject),queueChangeType:4};if("BATCH_OFFER"===t._e)return{elements:formatQueueElementsFromElements(t.elements),queueChangeType:6}}catch(e){}return{elements:[],queueChangeType:0}}(e.data.queueChange);T.elements=M,f>0&&(T.queueChangeType=f)}return T.raw=e.raw,T}(t.attachment,t.roomId):100===t.messageType&&(t=function formatCustomAttachment(e,t){var r,o,i;if("string"==typeof(null===(r=t.attachment)||void 0===r?void 0:r.raw)&&(null===(i=null===(o=e.V2NIMChatroomMessageService)||void 0===o?void 0:o.customAttachmentParsers)||void 0===i?void 0:i.length)>0){var n=t.subType||0,s=e.V2NIMChatroomMessageService.customAttachmentParsers,a=t.attachment.raw;s.some((r=>{try{var o=r(n,a);if(isPlainObject(o))return o.raw=a,t.attachment=o,!0}catch(t){return e.logger.warn(`customAttachmentParser: subType ${n}, raw: ${a}. parse error with ${t}`),!1}}))}return t}(e,t)),t}function formatMultiEnterInfo(e){if(e&&"string"==typeof e)try{return JSON.parse(e).map((e=>({roomNick:e.room_nick,roomAvatar:e.room_avatar,enterTime:e.enter_time,clientType:e.client_type})))}catch(e){return}}var be={301:0,302:1,303:2,304:3,305:4,306:5,312:6,313:7,314:8,315:9,316:10,317:11,320:11,324:11,318:12,319:13,321:14,322:15,323:16,325:17,326:18};function attachmentToRaw(e,t){if(!t)return"";switch(e){case 100:return t.raw||"";case 1:case 3:case 2:case 6:return function mediaAttachmentToRaw(e){var t=e,{width:r,height:o,duration:i,path:n,file:s,raw:a,ctx:c,payload:l,bucketName:_,objectName:d,token:E,ext:h}=t,u=__rest(t,["width","height","duration","path","file","raw","ctx","payload","bucketName","objectName","token","ext"]),m="string"==typeof h&&"."===h[0]?h.slice(1):h;return JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},u),void 0===h?{}:{ext:m}),void 0===r?{}:{w:r}),void 0===o?{}:{h:o}),void 0===i?{}:{dur:i}))}(t);case 4:return function locationAttachmentToRaw(e){return JSON.stringify({lat:e.latitude,lng:e.longitude,title:e.address})}(t);case 12:return function callAttachmentToRaw(e){var t=__rest(e,["raw"]);try{return JSON.stringify(Object.assign(Object.assign({},t),{durations:e.durations.map((e=>({accid:e.accountId,duration:e.duration})))}))}catch(t){return JSON.stringify(e)}}(t);default:return"string"==typeof t?t:JSON.stringify(t)}}function rawToAttachment(e,t){var r;try{switch(r=JSON.parse(e),t){case 100:return{raw:e};case 4:return function locationRawToAttachment(e,t){return{latitude:t.lat,longitude:t.lng,address:t.title,raw:e}}(e,r);case 2:case 3:case 1:case 6:return function mediaRawToAttachment(e,t){var{w:r,h:o,dur:i,ext:n}=t,s=__rest(t,["w","h","dur","ext"]),a="string"==typeof n&&"."!==n[0]?`.${n}`:n;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},s),void 0===n?{}:{ext:a}),void 0===r?{}:{width:r}),void 0===o?{}:{height:o}),void 0===i?{}:{duration:i}),{raw:e})}(e,r);case 12:return function callRawToAttachment(e,t){return Object.assign(Object.assign({},t),{durations:t.durations.map((e=>({accountId:e.accid,duration:e.duration}))),raw:e})}(e,r);default:return"object"==typeof r&&r?Object.assign(Object.assign({},r),{raw:e}):{raw:e}}}catch(t){return"object"==typeof r&&r?Object.assign(Object.assign({},r),{raw:e}):{raw:e}}}var Pe,ke,we,Ue,xe,Ge,Fe,Be,He,Ye,$e,je,Ke,qe,We,ze,Je,Qe="V2NIMChatroomMemberService",Xe={"36_15":"v2ChatroomUpdateSelfMemberInfo","36_16":"v2ChatroomGetMemberByIds","36_17":"v2ChatroomKickMember","36_19":"v2ChatroomSetMemberTempChatBanned","36_41":"v2ChatroomGetMemberListByTag","36_32":"v2ChatroomGetMemberCountByTag","36_37":"v2ChatroomGetMemberListByOption","36_38":"v2ChatroomUpdateMemberRole","36_39":"v2ChatroomSetMemberBlockedStatus","36_40":"v2ChatroomSetMemberChatBannedStatus","13_101":"v2ChatroomOnMemberTagUpdated"},Ze={roomId:1,accountId:2,memberRole:{id:3,retType:"number"},memberLevel:{id:4,retDef:0,retType:"number"},roomNick:5,roomAvatar:6,serverExtension:7,isOnline:{id:8,retType:"boolean"},enterTime:{id:10,retType:"number"},blocked:{id:12,retType:"boolean"},chatBanned:{id:13,retType:"boolean"},valid:{id:14,retDef:!0,retType:"boolean"},updateTime:{id:15,retDef:0,retType:"number"},tempChatBanned:{id:16,retType:"boolean",retDef:!1},tempChatBannedDuration:{id:17,retType:"number"},tags:{id:18,converter:objectToJSONString,retConverter:stringToJSONObject},notifyTargetTags:19,multiEnterInfo:{id:20,retConverter:formatMultiEnterInfo}},et={memberRoles:{id:1,converter:e=>e.join(",")},onlyBlocked:{id:2,converter:boolToInt},onlyChatBanned:{id:3,converter:boolToInt},onlyOnline:{id:4,converter:boolToInt},pageToken:5,limit:6},rt={v2ChatroomGetMemberByIds:{sid:36,cid:16,service:Qe,params:[{type:"StrArray",name:"accountIds"}],response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Ze)}]},v2ChatroomGetMemberListByOption:{sid:36,cid:37,service:Qe,params:[{type:"Property",name:"tag",reflectMapper:et}],response:[{type:"Int",name:"hasMore"},{type:"String",name:"pageToken"},{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Ze)}]},v2ChatroomUpdateSelfMemberInfo:{sid:36,cid:15,service:Qe,params:[{type:"Property",name:"tag",reflectMapper:Ze},{type:"Bool",name:"notificationEnabled"},{type:"String",name:"notificationExtension"},{type:"Bool",name:"persistence"},{type:"Property",name:"antispamConfig",reflectMapper:{antispamBusinessId:1}}]},v2ChatroomSetMemberTempChatBanned:{sid:36,cid:19,service:Qe,params:[{type:"String",name:"accountId"},{type:"Long",name:"tempChatBannedDuration"},{type:"Bool",name:"notificationEnabled"},{type:"String",name:"notificationExtension"}]},v2ChatroomGetMemberListByTag:{sid:36,cid:41,service:Qe,params:[{type:"Property",name:"tag",reflectMapper:{tag:1,pageToken:2,limit:3}}],response:[{type:"Int",name:"hasMore"},{type:"String",name:"pageToken"},{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Ze)}]},v2ChatroomGetMemberCountByTag:{sid:36,cid:32,service:Qe,params:[{type:"String",name:"tag"}],response:[{type:"Long",name:"data"}]},v2ChatroomKickMember:{sid:36,cid:17,service:Qe,params:[{type:"String",name:"accountId"},{type:"String",name:"notificationExtension"}]},v2ChatroomUpdateMemberRole:{sid:36,cid:38,service:Qe,params:[{type:"Property",name:"tag",reflectMapper:{accountId:1,memberRole:2,memberLevel:3,notificationExtension:4}}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Ze)}]},v2ChatroomSetMemberBlockedStatus:{sid:36,cid:39,service:Qe,params:[{type:"String",name:"accountId"},{type:"Bool",name:"blocked"},{type:"String",name:"notificationExtension"}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Ze)}]},v2ChatroomSetMemberChatBannedStatus:{sid:36,cid:40,service:Qe,params:[{type:"String",name:"accountId"},{type:"Bool",name:"chatBanned"},{type:"String",name:"notificationExtension"}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Ze)}]},v2ChatroomOnMemberTagUpdated:{sid:36,cid:101,service:Qe,response:[{type:"Property",name:"data",reflectMapper:{1:"tag"}}]}},ot="V2NIMChatroomLoginService",it={"1_2":"heartbeat","36_2":"v2ChatroomLogin","13_3":"v2ChatroomBeKicked","36_4":"v2ChatroomLogout"},nt={roomId:1,roomName:3,announcement:4,liveUrl:5,isValidRoom:{id:9,retType:"boolean"},serverExtension:12,queueLevelMode:{id:16,retType:"number"},creatorAccountId:100,onlineUserCount:{id:101,retType:"number"},chatBanned:{id:102,retType:"boolean"}},st={enabled:{id:1,retType:"boolean"},cdnUrls:{id:2,retConverter(e){if("string"==typeof e&&""!==e)return e.split("|")}},timestamp:{id:3,retType:"number"},pollingIntervalSeconds:{id:4,retType:"number"},decryptType:{id:5,retType:"number"},decryptKey:6,pollingTimeoutMillis:{id:7,retType:"number"}},at={heartbeat:{sid:1,cid:2,service:ot},v2ChatroomLogin:{sid:36,cid:2,service:ot,params:[{type:"Byte",name:"type"},{type:"Property",name:"chatroomLogin",reflectMapper:{appkey:1,account:2,deviceId:3,chatroomId:5,appLogin:8,chatroomNick:20,chatroomAvatar:21,serverExtension:22,notificationExtension:23,clientSession:26,isAnonymous:{id:38,converter:e=>+e},tags:{id:39,converter:e=>{if(Array.isArray(e)&&e.length>0)return JSON.stringify(e)}},notifyTargetTags:40,authType:41,loginExt:42,x:43,y:44,z:45,distance:46,antiSpamBusinessId:47,env:49,isRoutable:{id:50,converter:boolToInt}}},{type:"Property",name:"chatroomIMLogin",reflectMapper:{clientType:3,os:4,sdkVersion:6,appLogin:8,protocolVersion:9,pushTokenName:10,pushToken:11,deviceId:13,appkey:18,account:19,browser:24,clientSession:26,deviceInfo:32,customTag:38,customClientType:39,sdkHumanVersion:40,hostEnv:41,userAgent:42,libEnv:44,isReactNative:{id:112,converter:e=>+e},authType:115,loginExt:116,token:1e3}}],response:[{type:"Property",name:"chatroomInfo",reflectMapper:invertSerializeItem(nt)},{type:"Property",name:"chatroomMember",reflectMapper:invertSerializeItem(Ze)},{type:"Property",name:"chatroomCdnInfo",reflectMapper:invertSerializeItem(st)}]},v2ChatroomLogout:{sid:36,cid:4,service:ot,params:[]},v2ChatroomBeKicked:{sid:13,cid:3,service:ot,response:[{type:"Int",name:"kickedReason"},{type:"String",name:"serverExtension"}]}};!function(e){e[e.V2NIM_LOGIN_AUTH_TYPE_DEFAULT=0]="V2NIM_LOGIN_AUTH_TYPE_DEFAULT",e[e.V2NIM_LOGIN_AUTH_TYPE_DYNAMIC_TOKEN=1]="V2NIM_LOGIN_AUTH_TYPE_DYNAMIC_TOKEN",e[e.V2NIM_LOGIN_AUTH_TYPE_THIRD_PARTY=2]="V2NIM_LOGIN_AUTH_TYPE_THIRD_PARTY"}(Pe||(Pe={})),function(e){e[e.V2NIM_LOGIN_STATUS_LOGOUT=0]="V2NIM_LOGIN_STATUS_LOGOUT",e[e.V2NIM_LOGIN_STATUS_LOGINED=1]="V2NIM_LOGIN_STATUS_LOGINED",e[e.V2NIM_LOGIN_STATUS_LOGINING=2]="V2NIM_LOGIN_STATUS_LOGINING",e[e.V2NIM_LOGIN_STATUS_UNLOGIN=3]="V2NIM_LOGIN_STATUS_UNLOGIN"}(ke||(ke={})),function(e){e[e.V2NIM_LOGIN_CLIENT_TYPE_UNKNOWN=0]="V2NIM_LOGIN_CLIENT_TYPE_UNKNOWN",e[e.V2NIM_LOGIN_CLIENT_TYPE_ANDROID=1]="V2NIM_LOGIN_CLIENT_TYPE_ANDROID",e[e.V2NIM_LOGIN_CLIENT_TYPE_IOS=2]="V2NIM_LOGIN_CLIENT_TYPE_IOS",e[e.V2NIM_LOGIN_CLIENT_TYPE_PC=4]="V2NIM_LOGIN_CLIENT_TYPE_PC",e[e.V2NIM_LOGIN_CLIENT_TYPE_WP=8]="V2NIM_LOGIN_CLIENT_TYPE_WP",e[e.V2NIM_LOGIN_CLIENT_TYPE_WEB=16]="V2NIM_LOGIN_CLIENT_TYPE_WEB",e[e.V2NIM_LOGIN_CLIENT_TYPE_RESTFUL=32]="V2NIM_LOGIN_CLIENT_TYPE_RESTFUL",e[e.V2NIM_LOGIN_CLIENT_TYPE_MAC_OS=64]="V2NIM_LOGIN_CLIENT_TYPE_MAC_OS",e[e.V2NIM_LOGIN_CLIENT_TYPE_HARMONY_OS=65]="V2NIM_LOGIN_CLIENT_TYPE_HARMONY_OS"}(we||(we={})),function(e){e[e.V2NIM_LOGIN_CLIENT_CHANGE_LIST=1]="V2NIM_LOGIN_CLIENT_CHANGE_LIST",e[e.V2NIM_LOGIN_CLIENT_CHANGE_LOGIN=2]="V2NIM_LOGIN_CLIENT_CHANGE_LOGIN",e[e.V2NIM_LOGIN_CLIENT_CHANGE_LOGOUT=3]="V2NIM_LOGIN_CLIENT_CHANGE_LOGOUT"}(Ue||(Ue={})),function(e){e[e.V2NIM_CONNECT_STATUS_DISCONNECTED=0]="V2NIM_CONNECT_STATUS_DISCONNECTED",e[e.V2NIM_CONNECT_STATUS_CONNECTED=1]="V2NIM_CONNECT_STATUS_CONNECTED",e[e.V2NIM_CONNECT_STATUS_CONNECTING=2]="V2NIM_CONNECT_STATUS_CONNECTING",e[e.V2NIM_CONNECT_STATUS_WAITING=3]="V2NIM_CONNECT_STATUS_WAITING"}(xe||(xe={})),function(e){e[e.V2NIM_CHATROOM_KICKED_REASON_UNKNOWN=-1]="V2NIM_CHATROOM_KICKED_REASON_UNKNOWN",e[e.V2NIM_CHATROOM_KICKED_REASON_CHATROOM_INVALID=1]="V2NIM_CHATROOM_KICKED_REASON_CHATROOM_INVALID",e[e.V2NIM_CHATROOM_KICKED_REASON_BY_MANAGER=2]="V2NIM_CHATROOM_KICKED_REASON_BY_MANAGER",e[e.V2NIM_CHATROOM_KICKED_REASON_BY_CONFLICT_LOGIN=3]="V2NIM_CHATROOM_KICKED_REASON_BY_CONFLICT_LOGIN",e[e.V2NIM_CHATROOM_KICKED_REASON_SILENTLY=4]="V2NIM_CHATROOM_KICKED_REASON_SILENTLY",e[e.V2NIM_CHATROOM_KICKED_REASON_BE_BLOCKED=5]="V2NIM_CHATROOM_KICKED_REASON_BE_BLOCKED"}(Ge||(Ge={})),function(e){e[e.V2NIM_CHATROOM_MEMBER_ROLE_NORMAL=0]="V2NIM_CHATROOM_MEMBER_ROLE_NORMAL",e[e.V2NIM_CHATROOM_MEMBER_ROLE_CREATOR=1]="V2NIM_CHATROOM_MEMBER_ROLE_CREATOR",e[e.V2NIM_CHATROOM_MEMBER_ROLE_MANAGER=2]="V2NIM_CHATROOM_MEMBER_ROLE_MANAGER",e[e.V2NIM_CHATROOM_MEMBER_ROLE_NORMAL_GUEST=3]="V2NIM_CHATROOM_MEMBER_ROLE_NORMAL_GUEST",e[e.V2NIM_CHATROOM_MEMBER_ROLE_ANONYMOUS_GUEST=4]="V2NIM_CHATROOM_MEMBER_ROLE_ANONYMOUS_GUEST",e[e.V2NIM_CHATROOM_MEMBER_ROLE_VIRTUAL=5]="V2NIM_CHATROOM_MEMBER_ROLE_VIRTUAL"}(Fe||(Fe={})),function(e){e[e.V2NIM_MESSAGE_SENDING_STATE_UNKNOWN=0]="V2NIM_MESSAGE_SENDING_STATE_UNKNOWN",e[e.V2NIM_MESSAGE_SENDING_STATE_SUCCEEDED=1]="V2NIM_MESSAGE_SENDING_STATE_SUCCEEDED",e[e.V2NIM_MESSAGE_SENDING_STATE_FAILED=2]="V2NIM_MESSAGE_SENDING_STATE_FAILED",e[e.V2NIM_MESSAGE_SENDING_STATE_SENDING=3]="V2NIM_MESSAGE_SENDING_STATE_SENDING"}(Be||(Be={})),function(e){e[e.V2NIM_MESSAGE_ATTACHMENT_UPLOAD_STATE_UNKNOWN=0]="V2NIM_MESSAGE_ATTACHMENT_UPLOAD_STATE_UNKNOWN",e[e.V2NIM_MESSAGE_ATTACHMENT_UPLOAD_STATE_SUCCESS=1]="V2NIM_MESSAGE_ATTACHMENT_UPLOAD_STATE_SUCCESS",e[e.V2NIM_MESSAGE_ATTACHMENT_UPLOAD_STATE_FAILED=2]="V2NIM_MESSAGE_ATTACHMENT_UPLOAD_STATE_FAILED",e[e.V2NIM_MESSAGE_ATTACHMENT_UPLOAD_STATE_UPLOADING=3]="V2NIM_MESSAGE_ATTACHMENT_UPLOAD_STATE_UPLOADING"}(He||(He={})),function(e){e[e.V2NIM_MESSAGE_TYPE_INVALID=-1]="V2NIM_MESSAGE_TYPE_INVALID",e[e.V2NIM_MESSAGE_TYPE_TEXT=0]="V2NIM_MESSAGE_TYPE_TEXT",e[e.V2NIM_MESSAGE_TYPE_IMAGE=1]="V2NIM_MESSAGE_TYPE_IMAGE",e[e.V2NIM_MESSAGE_TYPE_AUDIO=2]="V2NIM_MESSAGE_TYPE_AUDIO",e[e.V2NIM_MESSAGE_TYPE_VIDEO=3]="V2NIM_MESSAGE_TYPE_VIDEO",e[e.V2NIM_MESSAGE_TYPE_LOCATION=4]="V2NIM_MESSAGE_TYPE_LOCATION",e[e.V2NIM_MESSAGE_TYPE_NOTIFICATION=5]="V2NIM_MESSAGE_TYPE_NOTIFICATION",e[e.V2NIM_MESSAGE_TYPE_FILE=6]="V2NIM_MESSAGE_TYPE_FILE",e[e.V2NIM_MESSAGE_TYPE_AVCHAT=7]="V2NIM_MESSAGE_TYPE_AVCHAT",e[e.V2NIM_MESSAGE_TYPE_TIPS=10]="V2NIM_MESSAGE_TYPE_TIPS",e[e.V2NIM_MESSAGE_TYPE_ROBOT=11]="V2NIM_MESSAGE_TYPE_ROBOT",e[e.V2NIM_MESSAGE_TYPE_CALL=12]="V2NIM_MESSAGE_TYPE_CALL",e[e.V2NIM_MESSAGE_TYPE_CUSTOM=100]="V2NIM_MESSAGE_TYPE_CUSTOM"}(Ye||(Ye={})),function(e){e[e.V2NIM_QUERY_DIRECTION_DESC=0]="V2NIM_QUERY_DIRECTION_DESC",e[e.V2NIM_QUERY_DIRECTION_ASC=1]="V2NIM_QUERY_DIRECTION_ASC"}($e||($e={})),function(e){e[e.V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MEMBER_ENTER=0]="V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MEMBER_ENTER",e[e.V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MEMBER_EXIT=1]="V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MEMBER_EXIT",e[e.V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MEMBER_BLOCK_ADDED=2]="V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MEMBER_BLOCK_ADDED",e[e.V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MEMBER_BLOCK_REMOVED=3]="V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MEMBER_BLOCK_REMOVED",e[e.V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MEMBER_CHAT_BANNED_ADDED=4]="V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MEMBER_CHAT_BANNED_ADDED",e[e.V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MEMBER_CHAT_BANNED_REMOVED=5]="V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MEMBER_CHAT_BANNED_REMOVED",e[e.V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_ROOM_INFO_UPDATED=6]="V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_ROOM_INFO_UPDATED",e[e.V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MEMBER_KICKED=7]="V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MEMBER_KICKED",e[e.V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MEMBER_TEMP_CHAT_BANNED_ADDED=8]="V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MEMBER_TEMP_CHAT_BANNED_ADDED",e[e.V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MEMBER_TEMP_CHAT_BANNED_REMOVED=9]="V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MEMBER_TEMP_CHAT_BANNED_REMOVED",e[e.V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MEMBER_INFO_UPDATED=10]="V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MEMBER_INFO_UPDATED",e[e.V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_QUEUE_CHANGE=11]="V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_QUEUE_CHANGE",e[e.V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_CHAT_BANNED=12]="V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_CHAT_BANNED",e[e.V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_CHAT_BANNED_REMOVED=13]="V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_CHAT_BANNED_REMOVED",e[e.V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_TAG_TEMP_CHAT_BANNED_ADDED=14]="V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_TAG_TEMP_CHAT_BANNED_ADDED",e[e.V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_TAG_TEMP_CHAT_BANNED_REMOVED=15]="V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_TAG_TEMP_CHAT_BANNED_REMOVED",e[e.V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MESSAGE_REVOKE=16]="V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MESSAGE_REVOKE",e[e.V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_TAGS_UPDATE=17]="V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_TAGS_UPDATE",e[e.V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_ROLE_UPDATE=18]="V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_ROLE_UPDATE"}(je||(je={})),function(e){e[e.V2NIM_CLIENT_ANTISPAM_OPERATE_NONE=0]="V2NIM_CLIENT_ANTISPAM_OPERATE_NONE",e[e.V2NIM_CLIENT_ANTISPAM_OPERATE_REPLACE=1]="V2NIM_CLIENT_ANTISPAM_OPERATE_REPLACE",e[e.V2NIM_CLIENT_ANTISPAM_OPERATE_CLIENT_SHIELD=2]="V2NIM_CLIENT_ANTISPAM_OPERATE_CLIENT_SHIELD",e[e.V2NIM_CLIENT_ANTISPAM_OPERATE_SERVER_SHIELD=3]="V2NIM_CLIENT_ANTISPAM_OPERATE_SERVER_SHIELD"}(Ke||(Ke={})),function(e){e[e.V2NIM_CHATROOM_STATUS_DISCONNECTED=0]="V2NIM_CHATROOM_STATUS_DISCONNECTED",e[e.V2NIM_CHATROOM_STATUS_WAITING=1]="V2NIM_CHATROOM_STATUS_WAITING",e[e.V2NIM_CHATROOM_STATUS_CONNECTING=2]="V2NIM_CHATROOM_STATUS_CONNECTING",e[e.V2NIM_CHATROOM_STATUS_CONNECTED=3]="V2NIM_CHATROOM_STATUS_CONNECTED",e[e.V2NIM_CHATROOM_STATUS_ENTERING=4]="V2NIM_CHATROOM_STATUS_ENTERING",e[e.V2NIM_CHATROOM_STATUS_ENTERED=5]="V2NIM_CHATROOM_STATUS_ENTERED",e[e.V2NIM_CHATROOM_STATUS_EXITED=6]="V2NIM_CHATROOM_STATUS_EXITED"}(qe||(qe={})),function(e){e.off="off",e.error="error",e.warn="warn",e.log="log",e.debug="debug"}(We||(We={})),function(e){e[e.V2NIM_CHATROOM_QUEUE_CHANGE_TYPE_UNKNOWN=0]="V2NIM_CHATROOM_QUEUE_CHANGE_TYPE_UNKNOWN",e[e.V2NIM_CHATROOM_QUEUE_CHANGE_TYPE_OFFER=1]="V2NIM_CHATROOM_QUEUE_CHANGE_TYPE_OFFER",e[e.V2NIM_CHATROOM_QUEUE_CHANGE_TYPE_POLL=2]="V2NIM_CHATROOM_QUEUE_CHANGE_TYPE_POLL",e[e.V2NIM_CHATROOM_QUEUE_CHANGE_TYPE_DROP=3]="V2NIM_CHATROOM_QUEUE_CHANGE_TYPE_DROP",e[e.V2NIM_CHATROOM_QUEUE_CHANGE_TYPE_PARTCLEAR=4]="V2NIM_CHATROOM_QUEUE_CHANGE_TYPE_PARTCLEAR",e[e.V2NIM_CHATROOM_QUEUE_CHANGE_TYPE_BATCH_UPDATE=5]="V2NIM_CHATROOM_QUEUE_CHANGE_TYPE_BATCH_UPDATE",e[e.V2NIM_CHATROOM_QUEUE_CHANGE_TYPE_BATCH_OFFER=6]="V2NIM_CHATROOM_QUEUE_CHANGE_TYPE_BATCH_OFFER"}(ze||(ze={})),function(e){e[e.V2NIM_CHATROOM_QUEUE_LEVEL_MODE_ANY=0]="V2NIM_CHATROOM_QUEUE_LEVEL_MODE_ANY",e[e.V2NIM_CHATROOM_QUEUE_LEVEL_MODE_MANAGER=1]="V2NIM_CHATROOM_QUEUE_LEVEL_MODE_MANAGER"}(Je||(Je={}));var ct={V2NIM_ERROR_CODE_UNKNOWN:{code:0,message:"unknown error"},V2NIM_ERROR_CODE_SUCCESS:{code:200,message:"success"},V2NIM_ERROR_CODE_HANDSHAKE:{code:201,message:"handshake error"},V2NIM_ERROR_CODE_REQUEST_TEMPERARY_FORBIDDEN:{code:398,message:"request temprary forbidden"},V2NIM_ERROR_CODE_SERVER_UNIT_ERROR:{code:399,message:"server unit error"},V2NIM_ERROR_CODE_FORBIDDEN:{code:403,message:"forbidden"},V2NIM_ERROR_CODE_NOT_FOUND:{code:404,message:"not found"},V2NIM_ERROR_CODE_PARAMETER_ERROR:{code:414,message:"parameter error"},V2NIM_ERROR_CODE_RATE_LIMIT_REACHED:{code:416,message:"rate limit reached"},V2NIM_ERROR_CODE_MULTI_LOGIN_FORBIDDEN:{code:417,message:"multi login forbidden"},V2NIM_ERROR_CODE_SERVER_INTERNAL_ERROR:{code:500,message:"server internal error"},V2NIM_ERROR_CODE_SERVER_BUSY:{code:503,message:"server busy"},V2NIM_ERROR_CODE_APP_UNREACHABLE:{code:511,message:"app server unreachable"},V2NIM_ERROR_CODE_SERVICE_UNAVAILABLE:{code:514,message:"service unavailable"},V2NIM_ERROR_CODE_PROTOCOL_BLACKHOLE_FILTERED:{code:599,message:"protocol filtered by blackhole rule"},V2NIM_ERROR_CODE_NO_PERMISSION:{code:997,message:"appid has no permission to call the protocol"},V2NIM_ERROR_CODE_UNPACK_ERROR:{code:998,message:"unpack error"},V2NIM_ERROR_CODE_PACK_ERROR:{code:999,message:"pack error"},V2NIM_ERROR_CODE_IM_DISABLED:{code:101301,message:"IM disabled"},V2NIM_ERROR_CODE_SERVICE_ADDRESS_INVALID:{code:101302,message:"service address invalid"},V2NIM_ERROR_CODE_APPKEY_NOT_EXIST:{code:101303,message:"appkey not exist"},V2NIM_ERROR_CODE_BUNDLEID_CHECK_FAILED:{code:101304,message:"bundleid check failed"},V2NIM_ERROR_CODE_APPKEY_BLOCKED:{code:101403,message:"appkey blocked"},V2NIM_ERROR_CODE_INVALID_TOKEN:{code:102302,message:"invalid token"},V2NIM_ERROR_CODE_ROBOT_NOT_ALLOWED:{code:102303,message:"robot not allowed"},V2NIM_ERROR_CODE_ACCOUNT_NOT_EXIST:{code:102404,message:"account not exist"},V2NIM_ERROR_CODE_ACCOUNT_CHAT_BANNED:{code:102421,message:"account chat banned"},V2NIM_ERROR_CODE_ACCOUNT_BANNED:{code:102422,message:"account banned"},V2NIM_ERROR_CODE_ACCOUNT_IN_BLOCK_LIST:{code:102426,message:"account in block list"},V2NIM_ERROR_CODE_USER_PROFILE_NOT_EXIST:{code:103404,message:"user profile not exist"},V2NIM_ERROR_CODE_USER_PROFILE_HIT_ANTISPAM:{code:103451,message:"user profile hit antispam"},V2NIM_ERROR_CODE_PEER_FRIEND_LIMIT:{code:104301,message:"peer friend limit"},V2NIM_ERROR_CODE_FRIEND_APPLICATION_NOT_EXIST:{code:104302,message:"friend application not exist"},V2NIM_ERROR_CODE_FRIEND_NOT_EXIST:{code:104404,message:"friend not exist"},V2NIM_ERROR_CODE_FRIEND_ALREADY_EXIST:{code:104405,message:"friend already exist"},V2NIM_ERROR_CODE_SELF_FRIEND_OPERATION_NOT_ALLOWED:{code:104429,message:"self friend operation not allowed"},V2NIM_ERROR_CODE_FRIEND_LIMIT:{code:104435,message:"friend limit"},V2NIM_ERROR_CODE_FRIEND_OPERATION_RATE_LIMIT:{code:104449,message:"friend operation rate limit"},V2NIM_ERROR_CODE_FRIEND_HIT_ANTISPAM:{code:104451,message:"friend hit antispam"},V2NIM_ERROR_CODE_SELF_MUTE_OPERATION_NOT_ALLOWED:{code:105429,message:"self mute operation not allowed"},V2NIM_ERROR_CODE_MUTE_LIST_LIMIT:{code:105435,message:"mute list limit"},V2NIM_ERROR_CODE_SELF_BLOCK_LIST_OPERATION_NOT_ALLOWED:{code:106429,message:"self block list operation not allowed"},V2NIM_ERROR_CODE_BLOCK_LIST_LIMIT:{code:106435,message:"block list limit"},V2NIM_ERROR_CODE_REVOKE_THIRD_PARTY_MESSAGE_NOT_ALLOWED:{code:107301,message:"revoke third party message not allowed"},V2NIM_ERROR_CODE_SHORT_TO_LONG_URL_FAILED:{code:107307,message:"short to long URL failed"},V2NIM_ERROR_CODE_URL_INVALID:{code:107308,message:"URL invalid"},V2NIM_ERROR_CODE_DURATION_OUT_OF_RANGE:{code:107309,message:"duration out of range"},V2NIM_ERROR_CODE_GET_FILE_META_INFO_FAILED:{code:107310,message:"get file meta info failed"},V2NIM_ERROR_CODE_AUDIO_FILE_SIZE_LIMIT:{code:107311,message:"audio file size limit"},V2NIM_ERROR_CODE_VOICE_TO_TEXT_TIMEOUT:{code:107312,message:"voice to text timeout"},V2NIM_ERROR_CODE_VOICE_TO_TEXT_FAILED:{code:107313,message:"voice to text failed"},V2NIM_ERROR_CODE_REVOKE_EXCEED_TIME_LIMIT:{code:107314,message:"revoke message exceed time limit"},V2NIM_ERROR_CODE_REVOKE_MESSAGE_NOT_ALLOWED:{code:107315,message:"revoke specific message not allowed"},V2NIM_ERROR_CODE_FORCE_PUSH_LIST_LIMIT:{code:107316,message:"force push list limit"},V2NIM_ERROR_CODE_TEAM_MESSAGE_RECEIPT_RATE_LIMIT:{code:107317,message:"team message receipt rate limit"},V2NIM_ERROR_CODE_SNAPSHOT_NOT_EXIST:{code:107318,message:"snapshot not exist"},V2NIM_ERROR_CODE_PIN_LIMIT:{code:107319,message:"pin limit"},V2NIM_ERROR_CODE_PIN_NOT_EXIST:{code:107320,message:"pin not exist"},V2NIM_ERROR_CODE_QUICK_COMMENT_LIMIT:{code:107321,message:"quick comment limit"},V2NIM_ERROR_CODE_PIN_ALREADY_EXIST:{code:107322,message:"pin already exist"},V2NIM_ERROR_CODE_VOICE_TO_TEXT_FUNCTION_DISABLED:{code:107333,message:"voice to text function disabled"},V2NIM_ERROR_CODE_CLOUD_SEARCH_FUNCTION_DISABLED:{code:107334,message:"cloud search function disabled"},V2NIM_ERROR_CODE_ONE_WAY_DELETE_FUNCTION_DISABLED:{code:107335,message:"one-way delete function disabled"},V2NIM_ERROR_CODE_REVOKE_MESSAGE_TO_SELF_NOT_ALLOWED:{code:107429,message:"revoke message to self not allowed"},V2NIM_ERROR_CODE_APP_CHAT_BANNED:{code:107410,message:"app chat banned"},V2NIM_ERROR_CODE_QUICK_COMMENT_FUNCTION_DISABLED:{code:107326,message:"quick comment function disabled"},V2NIM_ERROR_CODE_PIN_FUNCTION_DISABLED:{code:107327,message:"PIN function disabled"},V2NIM_ERROR_CODE_TEAM_READ_RECEIPT_FUNCTION_DISABLED:{code:107324,message:"read receipt for team messages function disabled"},V2NIM_ERROR_CODE_P2P_READ_RECEIPT_FUNCTION_DISABLED:{code:107325,message:"read receipt for p2p messages function disabled"},V2NIM_ERROR_CODE_RATE_LIMIT_FOR_MESSAGING_REACHED:{code:107323,message:"rate limit for messaging reached"},V2NIM_ERROR_CODE_MESSAGE_HIT_ANTISPAM:{code:107451,message:"message hit antispam"},V2NIM_ERROR_CODE_MESSAGE_NOT_EXIST:{code:107404,message:"message not exist"},V2NIM_ERROR_CODE_UNSENDING_MESSAGE_EXPIRED:{code:107406,message:"unsending message expired"},V2NIM_ERROR_CODE_TEAM_MARK_READ_FAILED:{code:107302,message:"sending message failed for marking message read failed for too many team members"},V2NIM_ERROR_CODE_SENDER_OR_MANAGER_PERMISSION_ONLY_REVOKE:{code:107303,message:"only sender or manager can revoke message"},V2NIM_ERROR_CODE_DELETE_SELF_MESSAGE_NOT_ALLOWED:{code:107328,message:"delete self message not allowed"},V2NIM_ERROR_CODE_NOT_CHATBOT_ACCOUNT:{code:107329,message:"is not chatbot account"},V2NIM_ERROR_CODE_MESSAGE_SENSE_REQUIRED:{code:107330,message:"sender or receiver must sense message"},V2NIM_ERROR_CODE_HIGH_PRIORITY_MESSAGE_RATE_LIMIT:{code:107304,message:"rate limit of high-priority messages exceeded"},ACK_MESSAGE_BE_HIGH_PRIORITY:{code:107305,message:"ack message should be high-priority"},V2NIM_ERROR_CODE_DUPLICATE_CLIENT_MESSAGE_ID:{code:107306,message:"duplicate client message ID"},V2NIM_ERROR_CODE_INVALID_TIME_RANGE:{code:107439,message:"invalid time range"},V2NIM_ERROR_CODE_NOT_ADVANCED_TEAM:{code:108302,message:"not advanced team"},V2NIM_ERROR_CODE_TEAM_MANAGER_LIMIT:{code:108303,message:"team manager limit"},V2NIM_ERROR_CODE_JOINED_TEAM_LIMIT:{code:108305,message:"joined team limit"},V2NIM_ERROR_CODE_TEAM_NORMAL_MEMBER_CHAT_BANNED:{code:108306,message:"team normal member chat banned"},V2NIM_ERROR_CODE_INVITED_ACCOUNT_NOT_FRIEND:{code:108307,message:"invited account not friend"},V2NIM_ERROR_CODE_REJECT_ALL_TEAM_APPLICATIONS:{code:108308,message:"reject all team applications"},V2NIM_ERROR_CODE_TEAM_NOT_EXIST:{code:108404,message:"team not exist"},V2NIM_ERROR_CODE_TEAM_ALREADY_CHAT_BANNED:{code:108420,message:"team already chat banned"},V2NIM_ERROR_CODE_ALL_TEAM_MEMBER_CHAT_BANNED:{code:108423,message:"all team member chat banned"},V2NIM_ERROR_CODE_EXTENDED_SUPER_TEAM_LIMIT:{code:108434,message:"extended super team limit"},V2NIM_ERROR_CODE_CREATED_TEAM_LIMIT:{code:108435,message:"created team limit"},V2NIM_ERROR_CODE_TEAM_INVITATION_LIMIT:{code:108437,message:"team invitation limit"},V2NIM_ERROR_CODE_TEAM_HIT_ANTISPAM:{code:108451,message:"team hit antispam"},V2NIM_ERROR_CODE_EXTENDED_SUPER_TEAM_LIMIT_NOT_CONFIGURED:{code:108304,message:"extended super team limit not configured"},V2NIM_ERROR_CODE_SUPER_TEAM_SERVICE_DISABLED:{code:108311,message:"super team service disabled"},V2NIM_ERROR_CODE_TEAM_READ_RECEIPT_RECORD_NOT_FOUND:{code:108301,message:"read receipt record for the team message not found"},V2NIM_ERROR_CODE_NOT_MANAGER:{code:108430,message:"unable to assign owner manager"},V2NIM_ERROR_CODE_ONLINE_MEMBER_COUNT_DISABLED:{code:108406,message:"number of online users service disabled"},V2NIM_ERROR_CODE_TRANSFER_DISABLED:{code:108310,message:"unable to transfer the ownership to owner"},V2NIM_ERROR_CODE_CREATE_TEAM_DISABLED:{code:108309,message:"unable to create team with more than %s people"},V2NIM_ERROR_CODE_EXTENDED_SUPER_TEAM_CREATE_FAILED:{code:108313,message:"/ extended super team creation failed,use open api to create the team"},V2NIM_ERROR_CODE_TEAM_MESSAGE_READ_RECEIPT_DISABLED:{code:108312,message:"read receipt for team messages function disabled"},V2NIM_ERROR_CODE_RETRY:{code:108449,message:"an error occurred, try again"},V2NIM_ERROR_CODE_CHAT_BAN_LIST_CONTAIN_NOT_TEAM_MEMBER:{code:109301,message:"list of chat banned users contains non team members"},V2NIM_ERROR_CODE_CHAT_BAN_LIST_CONTAIN_OPERATOR:{code:109303,message:"list of chat banned users contains the operator"},V2NIM_ERROR_CODE_CHAT_BAN_LIST_CONTAIN_TEAM_OWNER:{code:109304,message:"list of chat banned users contains the team owner"},V2NIM_ERROR_CODE_OPERATION_ON_TEAM_MANAGER_NOT_ALLOWED:{code:109305,message:"operation on team manager not allowed"},V2NIM_ERROR_CODE_NO_TEAM_INVITE_PERMISSION:{code:109306,message:"no team invite permission"},V2NIM_ERROR_CODE_TEAM_OWNER_QUIT_NOT_ALLOWED:{code:109307,message:"team owner quit not allowed"},V2NIM_ERROR_CODE_TEAM_OWNER_IN_KICK_LIST:{code:109308,message:"list of kicked user contains the team owner"},V2NIM_ERROR_CODE_INVITE_ROBOT_ACCOUNT_NOT_ALLOWED:{code:109309,message:"invite robot account not allowed"},V2NIM_ERROR_CODE_KICK_OPERATOR_NOT_ALLOWED:{code:109310,message:"kick operator not allowed"},V2NIM_ERROR_CODE_TEAM_MEMBER_ALREADY_EXIST:{code:109311,message:"team member already exist"},V2NIM_ERROR_CODE_TEAM_MEMBER_CAN_NOT_MODIFY_SELF:{code:109312,message:"operation on self not allowed"},V2NIM_ERROR_CODE_TEAM_INVITATION_OR_APPLICATION_NOT_EXIST:{code:109313,message:"team invitation or application not exist"},V2NIM_ERROR_CODE_OPERATION_ON_TEAM_OWNER_NOT_ALLOWED:{code:109314,message:"operation on team owner not allowed"},V2NIM_ERROR_CODE_TEAM_MEMBER_NOT_EXIST:{code:109404,message:"team member not exist"},V2NIM_ERROR_CODE_TEAM_MEMBER_CHAT_BANNED:{code:109424,message:"team member chat banned"},V2NIM_ERROR_CODE_TEAM_OWNER_OPERATION_PERMISSION_REQUIRED:{code:109427,message:"team owner operation permission required"},V2NIM_ERROR_CODE_TEAM_OWNER_OR_MANAGER_OPERATION_PERMISSION_REQUIRED:{code:109432,message:"team owner or manager operation permission required"},V2NIM_ERROR_CODE_TEAM_MEMBER_CONCURRENT_OPERATION_FAILED:{code:109449,message:"team member concurrent operation failed"},V2NIM_ERROR_CODE_TEAM_MEMBER_HIT_ANTISPAM:{code:109451,message:"team member hit antispam"},V2NIM_ERROR_CODE_CONVERSATION_AND_ACCOUNT_MISMATCH:{code:110302,message:"conversation and account mismatch"},V2NIM_ERROR_CODE_CONVERSATION_STICK_TOP_LIMIT:{code:110303,message:"conversation stick top limit"},V2NIM_ERROR_CODE_CONVERSATION_BELONGED_GROUP_LIMIT:{code:110304,message:"conversation belonged group limit"},V2NIM_ERROR_CODE_CONVERSATION_NOT_EXIST:{code:110404,message:"conversation not exist"},V2NIM_ERROR_CODE_CHATROOM_LINK_UNAVAILABLE:{code:113304,message:"chatroom link unavailable"},V2NIM_ERROR_CODE_IM_CONNECTION_ABNORMAL:{code:113305,message:"IM connection abnormal"},V2NIM_ERROR_CODE_CHATROOM_NOT_EXIST:{code:113404,message:"chatroom not exist"},V2NIM_ERROR_CODE_CHATROOM_CLOSED:{code:113406,message:"chatroom closed"},V2NIM_ERROR_CODE_CHATROOM_REPEATED_OPERATION:{code:113409,message:"chatroom repeated operation"},V2NIM_ERROR_CODE_CHATROOM_DISABLED:{code:113410,message:"chatroom disabled"},V2NIM_ERROR_CODE_ALL_CHATROOM_MEMBER_CHAT_BANNED:{code:113423,message:"all chatroom member chat banned"},V2NIM_ERROR_CODE_CHATROOM_HIT_ANTISPAM:{code:113451,message:"chatroom hit antispam"},V2NIM_ERROR_CODE_ANONYMOUS_MEMBER_FORBIDDEN:{code:114303,message:"anonymous member forbidden"},V2NIM_ERROR_CODE_CHATROOM_MEMBER_NOT_EXIST:{code:114404,message:"chatroom member not exist"},V2NIM_ERROR_CODE_CHATROOM_MEMBER_REPEATED_OPERATION:{code:114405,message:"chatroom member repeated operation"},V2NIM_ERROR_CODE_CHATROOM_MEMBER_CHAT_BANNED:{code:114421,message:"chatroom member chat banned"},V2NIM_ERROR_CODE_ACCOUNT_IN_CHATROOM_BLOCK_LIST:{code:114426,message:"account in chatroom block list"},V2NIM_ERROR_CODE_CHATROOM_OWNER_OPERATION_PERMISSION_REQUIRED:{code:114427,message:"chatroom owner operation permission required"},V2NIM_ERROR_CODE_SELF_IN_CHATROOM_MEMBER_OPERATION_LIST:{code:114429,message:"self in chatroom member operation list"},V2NIM_ERROR_CODE_CHATROOM_OWNER_OR_MANAGER_OPERATION_PERMISSION_REQUIRED:{code:114432,message:"chatroom owner or manager operation permission required"},V2NIM_ERROR_CODE_CHATROOM_MEMBER_LIMIT:{code:114437,message:"chatroom member limit"},V2NIM_ERROR_CODE_CHATROOM_MEMBER_CONCURRENT_OPERATION_FAILED:{code:114449,message:"chatroom member concurrent operation failed"},V2NIM_ERROR_CODE_CHATROOM_MEMBER_HIT_ANTISPAM:{code:114451,message:"chatroom member hit antispam"},V2NIM_ERROR_CODE_CONVERSATION_GROUP_NOT_EXIST:{code:116404,message:"conversation group not exist"},V2NIM_ERROR_CODE_CONVERSATION_GROUP_LIMIT:{code:116435,message:"conversation group limit"},V2NIM_ERROR_CODE_CONVERSATIONS_IN_GROUP_LIMIT:{code:116437,message:"conversations in group limit"},V2NIM_ERROR_CODE_COLLECTION_LIMIT:{code:189301,message:"collection limit"},V2NIM_ERROR_CODE_COLLECTION_NOT_EXIST:{code:189302,message:"collection not exist"},V2NIM_ERROR_CODE_COLLECTION_CONCURRENT_OPERATION_FAILED:{code:189449,message:"collection concurrent operation failed"},V2NIM_ERROR_CODE_INTERNAL:{code:190001,message:"internal error"},V2NIM_ERROR_CODE_ILLEGAL_STATE:{code:190002,message:"illegal state"},V2NIM_ERROR_CODE_MISUSE:{code:191001,message:"misuse"},V2NIM_ERROR_CODE_CANCELLED:{code:191002,message:"operation cancelled"},V2NIM_ERROR_CODE_CALLBACK_FAILED:{code:191003,message:"callback failed"},V2NIM_ERROR_CODE_INVALID_PARAMETER:{code:191004,message:"invalid parameter"},V2NIM_ERROR_CODE_TIMEOUT:{code:191005,message:"timeout"},V2NIM_ERROR_CODE_RESOURCE_NOT_EXIST:{code:191006,message:"resource not exist"},V2NIM_ERROR_CODE_RESOURCE_ALREADY_EXIST:{code:191007,message:"resource already exist"},V2NIM_ERROR_CODE_CONNECT_FAILED:{code:192001,message:"connect failed"},V2NIM_ERROR_CODE_CONNECT_TIMEOUT:{code:192002,message:"connect timeout"},V2NIM_ERROR_CODE_DISCONNECT:{code:192003,message:"disconnect"},V2NIM_ERROR_CODE_PROTOCOL_TIMEOUT:{code:192004,message:"protocol timeout"},V2NIM_ERROR_CODE_PROTOCOL_SEND_FAILED:{code:192005,message:"protocol send failed"},V2NIM_ERROR_CODE_REQUEST_FAILED:{code:192006,message:"request failed"},V2NIM_ERROR_CODE_FILE_NOT_FOUND:{code:194001,message:"file not found"},V2NIM_ERROR_CODE_FILE_CREATE_FAILED:{code:194002,message:"file create failed"},V2NIM_ERROR_CODE_FILE_OPEN_FAILED:{code:194003,message:"file open failed"},V2NIM_ERROR_CODE_FILE_WRITE_FAILED:{code:194004,message:"file write failed"},V2NIM_ERROR_CODE_FILE_READ_FAILED:{code:194005,message:"file read failed"},V2NIM_ERROR_CODE_FILE_UPLOAD_FAILED:{code:194006,message:"file upload failed"},V2NIM_ERROR_CODE_FILE_DOWNLOAD_FAILED:{code:194007,message:"file download failed"},V2NIM_ERROR_CODE_CLIENT_ANTISPAM:{code:195001,message:"client anti-spam"},V2NIM_ERROR_CODE_SERVER_ANTISPAM:{code:195002,message:"server anti-spam"}},lt=Object.keys(ct),_t=lt.reduce((function(e,t){var r=ct[t];return e[t]=r.code,e}),{}),dt=lt.reduce((function(e,t){var r=ct[t];return e[r.code]=r.message,e}),{}),Et=Object.freeze({__proto__:null,V2NIMErrorCode:_t,V2NIMErrorDesc:dt,get V2NIMLoginAuthType(){return Pe},get V2NIMLoginStatus(){return ke},get V2NIMLoginClientType(){return we},get V2NIMLoginClientChange(){return Ue},get V2NIMConnectStatus(){return xe},get V2NIMChatroomKickedReason(){return Ge},get V2NIMChatroomMemberRole(){return Fe},get V2NIMMessageSendingState(){return Be},get V2NIMMessageAttachmentUploadState(){return He},get V2NIMMessageType(){return Ye},get V2NIMQueryDirection(){return $e},get V2NIMChatroomMessageNotificationType(){return je},get V2NIMClientAntispamOperateType(){return Ke},get V2NIMChatroomStatus(){return qe},get V2NIMChatroomQueueLevelMode(){return Je}});class V2NIMLoginReconnect{constructor(e){this.currenRetryCount=0,this.reconnectTimer=0,this.backoffIntervals=[1e3,2e3,3e3],this.currReconnectInterval=0,this.core=e,this.auth=e.auth}reset(){this.currenRetryCount=0,this.reconnectTimer&&clearTimeout(this.reconnectTimer)}clearReconnectTimer(){this.reconnectTimer&&clearTimeout(this.reconnectTimer)}attempToReLogin(){var e=this.backoffIntervals[this.currReconnectInterval];return this.currReconnectInterval=(this.currReconnectInterval+1)%this.backoffIntervals.length,this.currenRetryCount++,this.core.logger.log(`reconnect::reconnect timer is about to be set, delay ${e} ms, current retry count is ${this.currenRetryCount}`),this.clearReconnectTimer(),this.reconnectTimer=setTimeout((()=>{this.core.logger.log("reconnect::reconnect timer is now triggered");var e=this.auth.getConnectStatus();3===e?this.doReLogin():this.core.logger.warn(`reconnect::reconnect timer is over because connect status now is ${e}`)}),e),!0}doReLogin(){return __awaiter(this,void 0,void 0,(function*(){this.auth.connectParams.forceMode=!1;try{yield this.auth.updateDynamicParamters(!1)}catch(e){return this.auth.lifeCycle.processEvent("waiting")}var e=this.core.timeOrigin.getTimeNode();this.auth.originLoginPromise=this.auth.doLogin(!0);try{yield this.auth.previousLoginManager.add(this.auth.originLoginPromise),this.currReconnectInterval=0,this.auth.reportLoginSucc(e)}catch(r){var t=r;if(this.core.logger.warn("reconnect::try login but failed due to",t),this.auth.reportLoginFail(e,t),this.auth.checkLoginTerminalCode(t&&t.code))return this.auth.clientSocket.doDisconnect(Ae.ACTIVE,"ReloginTerminated}"),void this.auth.lifeCycle.processEvent("exited",t);t&&t.code===_t.V2NIM_ERROR_CODE_SERVER_UNIT_ERROR?this.auth.updateLinkAddress().then((()=>{this.auth.lifeCycle.processEvent("waiting")})).catch((e=>{this.auth.lifeCycle.processEvent("reconnectFail",e)})):this.auth.lifeCycle.processEvent("waiting")}}))}}class V2NIMLoginAuthenticator{constructor(e){this.lastLoginClientKey="__NIM_LAST_LOGIN_CLIENT__",this.loginClients=[],this.loginClientOfThisConnection={},this.core=e,this.auth=e.auth}verifyAuthentication(e){var t,r,o,i,n,s,a,c,l,_,d,E,h,u;return __awaiter(this,void 0,void 0,(function*(){var m,g=ae.getSystemInfo(),p={clientType:16,os:g.os,sdkVersion:100941,appLogin:e?0:1,protocolVersion:1,deviceId:this.auth.deviceId,appkey:this.auth.appkey,account:this.auth.account,browser:g.browser,clientSession:this.auth.clientSession,customClientType:this.core.options.customClientType,sdkHumanVersion:"10.9.41",userAgent:this.core.options.loginSDKTypeParamCompat?"Native/10.9.41":g.userAgent.replace("{{appkey}}",this.auth.appkey).slice(0,299),libEnv:this.core.options.loginSDKTypeParamCompat?void 0:g.libEnv,hostEnv:this.core.options.loginSDKTypeParamCompat?0:g.hostEnvEnum,authType:this.auth.authType,loginExt:this.auth.loginExt,token:this.auth.token},I=Object.assign(Object.assign({appkey:this.auth.appkey,account:this.auth.account,deviceId:this.auth.deviceId,chatroomId:this.auth.roomId,appLogin:e?0:1,chatroomNick:null===(t=this.auth.enterParams)||void 0===t?void 0:t.roomNick,chatroomAvatar:(null===(r=this.auth.enterParams)||void 0===r?void 0:r.roomAvatar)||"",serverExtension:null===(o=this.auth.enterParams)||void 0===o?void 0:o.serverExtension,notificationExtension:null===(i=this.auth.enterParams)||void 0===i?void 0:i.notificationExtension,clientSession:this.auth.clientSession,isAnonymous:this.auth.isAnonymous,tags:null===(s=null===(n=this.auth.enterParams)||void 0===n?void 0:n.tagConfig)||void 0===s?void 0:s.tags,notifyTargetTags:null===(c=null===(a=this.auth.enterParams)||void 0===a?void 0:a.tagConfig)||void 0===c?void 0:c.notifyTargetTags,authType:this.auth.authType,loginExt:this.auth.loginExt},null===(_=null===(l=this.auth.enterParams)||void 0===l?void 0:l.locationConfig)||void 0===_?void 0:_.locationInfo),{distance:null===(E=null===(d=this.auth.enterParams)||void 0===d?void 0:d.locationConfig)||void 0===E?void 0:E.distance,antiSpamBusinessId:null===(u=null===(h=this.auth.enterParams)||void 0===h?void 0:h.antispamConfig)||void 0===u?void 0:u.antispamBusinessId,isRoutable:!1===get(this.auth,"enterParams.loginOption.routeConfig.routeEnabled")?0:1,env:get(this.auth,"enterParams.loginOption.routeConfig.routeEnvironment")});try{this.auth.lifeCycle.processEvent("loginStart"),m=yield this.auth.doLoginStepsManager.add(this.auth.clientSocket.sendCmd("v2ChatroomLogin",{type:1,chatroomLogin:I,chatroomIMLogin:p}))}catch(e){var N=e;if(this.core.reporter.reportTraceUpdateV2("login",{operation_type:"protocol",target:"26-3",code:N.code||0,succeed:!1,description:N.message},{asyncParams:ae.net.getNetworkStatus()}),N.code===_t.V2NIM_ERROR_CODE_CANCELLED||N.code===_t.V2NIM_ERROR_CODE_TIMEOUT)throw N;throw this.processLoginFailed(N),N}var{chatroomInfo:T,chatroomMember:O,chatroomCdnInfo:M}=m.content;return this.core.V2NIMChatroomMessageService.cdnUtil.setOptions(M),{chatroom:T,selfMember:O}}))}processLoginFailed(e){this.auth.clientSocket.doDisconnect(Ae.ACTIVE,e),this.checkLoginTerminalCode(e.code)&&(this.auth.authenticator.reset(),this.auth.authenticator.clearLastLoginClient()),this.auth.lifeCycle.processEvent("loginFail",e)}changeLoginClient(e,t){}checkAutoLogin(e){if(e)return!1;var t=ae.localStorage.getItem(this.lastLoginClientKey);if(!t)return!1;var r="",o="";try{var i=JSON.parse(t);r=get(i,"clientId"),o=get(i,"account")}catch(e){return!1}return r===this.auth.deviceId&&o===this.auth.account}checkLoginTerminalCode(e){return[_t.V2NIM_ERROR_CODE_CANCELLED,_t.V2NIM_ERROR_CODE_TIMEOUT,_t.V2NIM_ERROR_CODE_HANDSHAKE,302,317,_t.V2NIM_ERROR_CODE_FORBIDDEN,_t.V2NIM_ERROR_CODE_NOT_FOUND,_t.V2NIM_ERROR_CODE_PARAMETER_ERROR,_t.V2NIM_ERROR_CODE_MULTI_LOGIN_FORBIDDEN,422,_t.V2NIM_ERROR_CODE_IM_DISABLED,_t.V2NIM_ERROR_CODE_APPKEY_NOT_EXIST,_t.V2NIM_ERROR_CODE_BUNDLEID_CHECK_FAILED,_t.V2NIM_ERROR_CODE_APPKEY_BLOCKED,_t.V2NIM_ERROR_CODE_INVALID_TOKEN,_t.V2NIM_ERROR_CODE_ROBOT_NOT_ALLOWED,_t.V2NIM_ERROR_CODE_ACCOUNT_NOT_EXIST,_t.V2NIM_ERROR_CODE_ACCOUNT_BANNED,_t.V2NIM_ERROR_CODE_SERVICE_ADDRESS_INVALID,_t.V2NIM_ERROR_CODE_CHATROOM_DISABLED,_t.V2NIM_ERROR_CODE_CHATROOM_NOT_EXIST,_t.V2NIM_ERROR_CODE_CHATROOM_CLOSED,_t.V2NIM_ERROR_CODE_ACCOUNT_IN_CHATROOM_BLOCK_LIST].includes(e)}reset(){this.loginClients=[],this.loginClientOfThisConnection={}}clearLastLoginClient(){ae.localStorage.removeItem(this.lastLoginClientKey)}}class V2NIMLoginLifeCycle{constructor(e){this.name="V2NIMLoginLifeCycle",this.chatroomStatus=6,this.entered=!1,this.core=e,this.auth=e.auth,this.logger=e.logger}processEvent(e,t,r){var o=this.getConnectStatus();switch(e){case"connect":this.logger.log(`${this.name}::connecting`),this.setChatroomStatus(2);break;case"connectSucc":this.logger.log(`${this.name}::connect success`),this.setChatroomStatus(3);break;case"connectFail":this.logger.log(`${this.name}::connect fail`,t),this.setChatroomStatus(0,t);break;case"connectionBroken":this.logger.log(`${this.name}::connectionBroken`,t),this.setChatroomStatus(0,t);break;case"loginStart":this.logger.log(`${this.name}::login start`),this.setChatroomStatus(4);break;case"loginSucc":this.logger.log(`${this.name}::login success, verify authentication success`),this.setChatroomStatus(5),this.core.eventBus.emit("V2NIMLoginService/loginLifeCycleLoginSucc",r);break;case"loginFail":this.logger.log(`${this.name}::login fail due to verify authentication failed:`,t),this.setChatroomStatus(0,t);break;case"logout":this.logger.log(`${this.name}::logout`),this.setChatroomStatus(6),this.core.eventBus.emit("V2NIMLoginService/loginLifeCycleLogout");break;case"kicked":this.logger.log(`${this.name}::kicked`,r),this.setChatroomStatus(6,t),this.core.eventBus.emit("V2NIMLoginService/loginLifeCycleKicked");break;case"reconnectFail":this.logger.log(`${this.name}::reconnect fail`,t),this.setChatroomStatus(6,t),this.core.eventBus.emit("V2NIMLoginService/loginLifeCycleLogout");break;case"exited":if(this.logger.log(`${this.name}::exited, isEntered: ${this.entered}`,t),6===this.chatroomStatus)return;this.setChatroomStatus(this.entered?6:0,t);break;case"waiting":this.logger.log(`${this.name}::waiting to reconnect`),this.setChatroomStatus(1),2!==o&&this.auth.reconnect.attempToReLogin()}}getConnectStatus(){switch(this.chatroomStatus){case 6:case 0:return 0;case 5:case 4:case 3:return 1;case 2:return 2;case 1:return 3}}getLoginStatus(){switch(this.chatroomStatus){case 1:return 3;case 6:case 0:return 0;case 3:case 2:case 4:return 2;case 5:return 1}}setChatroomStatus(e,t){5===e&&(this.entered=!0),this.chatroomStatus!==e&&(this.chatroomStatus=e,6===e&&this.core._clearModuleData(),this.core.emit("onChatroomStatus",e,t),6===e&&this.entered&&(this.entered=!1,this.core.emit("onChatroomExited",t)))}}function replacer(e,t){return t instanceof RegExp?"__REGEXP "+t.toString():t}function validate(e,t={},r,o=!1){var i={};return Object.keys(e).forEach((n=>{var s=e[n].type,a=r?`In ${r}, `:"";if(null==t){var c=`${a}param is null or undefined`;throw o?new ValidateErrorV2({detail:{reason:c,data:{key:n},rules:"required"}}):new ValidateError(c,{key:n},"required")}if(void 0===t[n]){if(!1===e[n].required)return void(i[n]=t[n]);var l=`${a}param '${n}' is required`;throw o?new ValidateErrorV2({detail:{reason:l,data:{key:n},rules:"required"}}):new ValidateError(l,{key:n},"required")}var _=ht[s];if(_&&!_(t,n,e[n],o)){var d=`${a}param '${n}' unexpected`,E={key:n,value:t[n]};throw o?new ValidateErrorV2({detail:{reason:d,data:E,rules:JSON.stringify(e[n],replacer)}}):new ValidateError(d,E,JSON.stringify(e[n],replacer))}i[n]=t[n]})),i}var ht={string:function(e,t,r){var{allowEmpty:o,max:i,min:n,regExp:s}=r,a=e[t];return"string"==typeof a&&((!1!==o||""!==a)&&(!("number"==typeof i&&a.length>i)&&(!("number"==typeof n&&a.length<n)&&!(function isRegExp(e){return"[object RegExp]"===Object.prototype.toString.call(e)}(s)&&!s.test(a)))))},number:function(e,t,r){var{min:o,max:i}=r,n=e[t];return"number"==typeof n&&(!("number"==typeof o&&n<o)&&!("number"==typeof i&&n>i))},boolean:function(e,t){return"boolean"==typeof e[t]},file:function(e,t){return!0},enum:function(e,t,r){var{values:o}=r,i=e[t];return!o||o.indexOf(i)>-1},jsonstr:function(e,t){try{var r=JSON.parse(e[t]);return"object"==typeof r&&null!==r}catch(e){return!1}},func:function(e,t){return"function"==typeof e[t]},array:function(e,t,r,o=!1){var{itemType:i,itemRules:n,rules:s,min:a,max:c,values:l}=r,_=e[t];if(!Array.isArray(_))return!1;if("number"==typeof c&&_.length>c)return!1;if("number"==typeof a&&_.length<a)return!1;if(n)_.forEach(((e,r)=>{validate({[r]:n},{[r]:e},`${t}[${r}]`,o)}));else if(s)_.forEach(((e,r)=>validate(s,e,`${t}[${r}]`,o)));else if("enum"===i){if(l&&function difference(e,t){return t=t||[],(e=e||[]).filter((e=>-1===t.indexOf(e)))}(_,l).length)return!1}else if(i&&!_.every((e=>typeof e===i)))return!1;return!0},object:function(e,t,r,o=!1){var{rules:i,allowEmpty:n}=r,s=e[t];if("object"!=typeof s||null===s)return!1;if(i){var a=Object.keys(i),c=Object.keys(s).filter((e=>a.indexOf(e)>-1));if(!1===n&&0===c.length)return!1;validate(i,s,t,o)}return!0}},ut={updateParams:{type:"object",allowEmpty:!1,rules:{roomName:{type:"string",required:!1,allowEmpty:!1},announcement:{type:"string",required:!1},liveUrl:{type:"string",required:!1},serverExtension:{type:"string",required:!1},notificationEnabled:{type:"boolean",required:!1},notificationExtension:{type:"string",required:!1}}},antispamConfig:{type:"object",required:!1,rules:{antispamBusinessId:{type:"string",required:!1}}}},mt={locationInfo:{type:"object",rules:{x:{type:"number"},y:{type:"number"},z:{type:"number"}}},distance:{type:"number"}},gt={updateParams:{type:"object",allowEmpty:!1,rules:{tags:{type:"array",required:!1,itemType:"string"},notifyTargetTags:{type:"string",required:!1},notificationEnabled:{type:"boolean",required:!1},notificationExtension:{type:"string",required:!1}}}},pt={targetTag:{type:"string",required:!0,allowEmpty:!1},notifyTargetTags:{type:"string",required:!1},duration:{type:"number",required:!1},notificationEnabled:{type:"boolean",required:!1},notificationExtension:{type:"string",required:!1}},It={roomId:{allowEmpty:!1,type:"string"},enterParams:{type:"object",required:!0,rules:{anonymousMode:{required:!1,type:"boolean"},accountId:{required:!1,type:"string",allowEmpty:!1},token:{required:!1,type:"string",allowEmpty:!1},roomNick:{required:!1,type:"string"},roomAvatar:{required:!1,type:"string"},loginOption:{type:"object",required:!1,rules:{authType:{type:"enum",required:!1,values:[0,1,2]},tokenProvider:{required:!1,type:"func"},loginExtensionProvider:{required:!1,type:"func"},routeConfig:{type:"object",required:!1,rules:{routeEnabled:{type:"boolean",required:!1},routeEnv:{type:"string",required:!1}}}}},linkProvider:{type:"func"},serverExtension:{type:"string",required:!1,allowEmpty:!1},notificationExtension:{type:"string",required:!1,allowEmpty:!1},tagConfig:{type:"object",required:!1,rules:{notifyTargetTags:{type:"string",required:!1},tags:{type:"array",required:!1,itemType:"string"}}},locationConfig:{type:"object",required:!1,rules:mt},antispamConfig:{type:"object",required:!1,rules:{antispamBusinessId:{type:"string",required:!1,allowEmpty:!1}}}}}};class V2ChatroomService extends Ie{constructor(e,t){super(),this.name=e,this.logger=t.logger,this.core=t}emit(e,...t){this.logger.debug(`${this.name}::emit event: '${e.toString()}',`,void 0!==t[0]?t[0]:"",void 0!==t[1]?t[1]:"",void 0!==t[2]?t[2]:"");try{return super.emit(e,...t)}catch(t){return setTimeout((()=>{throw this.logger.error(`${this.name}::emit throw error in setTimeout. event: ${e.toString()}. Error`,t),t}),0),!1}}process(e){var t=this[e.cmd+"Handler"];if("function"==typeof t){if(e.error)return this.logger.error(`${e.cmd}::recvError`,e.error),Promise.reject(e.error);try{var r=t.call(this,e);return Promise.resolve(r)}catch(e){return Promise.reject(e)}}var o=get(e,"error.detail.ignore");return e.error&&!o?Promise.reject(e.error):Promise.resolve(e)}}class V2NIMChatroomLoginServiceImpl extends V2ChatroomService{constructor(e){super("V2NIMChatroomLoginService",e),this.roomId="",this.token="",this.loginExt="",this.authType=0,this.linkAddressArray=[],this.currLinkIdx=-1,this.isAnonymous=!1,this.processId="",this.connectParams={forceMode:!1},registerParser({cmdMap:it,cmdConfig:at}),e.auth=this,this.previousLoginManager=new PromiseManager,this.doLoginStepsManager=new PromiseManager,this.loginTimerManager=new TimerManager,this.lifeCycle=new V2NIMLoginLifeCycle(e),this.reconnect=new V2NIMLoginReconnect(e),this.authenticator=new V2NIMLoginAuthenticator(e)}get clientSocket(){return this.core.clientSocket}get account(){return this.core.options.account}get appkey(){return this.core.options.appkey}get deviceId(){return this.core.config.deviceId}get clientSession(){return this.core.config.clientSession}getNextLink(){return this.currLinkIdx=(this.currLinkIdx+1)%this.linkAddressArray.length,this.linkAddressArray[this.currLinkIdx]}getCurrLink(){return this.linkAddressArray[this.currLinkIdx]}reset(){this.roomId="",this.token="",this.loginExt="",this.processId="",this.reconnect.reset(),this.authenticator.reset(),this.authenticator.clearLastLoginClient()}login(e,t,r){return __awaiter(this,void 0,void 0,(function*(){if(validate(It,{appkey:e,roomId:t,enterParams:r},"",!0),0===this.getLoginStatus())this.logger.log(`V2NIMChatroomLoginService::login:allowLogin. appkey:${e};roomId:${t};accountId:${r.accountId} `);else{if(1===this.getLoginStatus())return this.smoothForLogined(e,t,r);if(2===this.getLoginStatus())return this.smoothForLogining(e,t,r)}this.processId=ve(),yield this.setLoginParams(e,t,r),this.loginTimerManager.destroy(),this.loginTimerManager.addTimer((()=>{var e=new V2NIMErrorImpl({code:_t.V2NIM_ERROR_CODE_TIMEOUT,detail:{reason:"Login API timeout"}});this.doLoginStepsManager.clear(e),this.previousLoginManager.clear(e),this.originLoginPromise=void 0,this.lifeCycle.processEvent("exited",e)}),r.timeout?1e3*r.timeout:6e4,1);try{var o=yield this.multiTryDoLogin();return this.core.emit("onChatroomEntered"),this.loginTimerManager.destroy(),o}catch(e){throw this.loginTimerManager.destroy(),e}}))}multiTryDoLogin(e){return __awaiter(this,void 0,void 0,(function*(){for(var t=this.core.timeOrigin.getTimeNode(),r=new V2NIMErrorImpl({code:_t.V2NIM_ERROR_CODE_INTERNAL,detail:{reason:"loginFailed"}}),o=0;o<this.linkAddressArray.length;o++){var i=`V2NIMChatroomLoginService:: ${o+1}th login attempt.`;o>0?this.logger.warn(i):this.logger.log(i);try{this.originLoginPromise=e||this.doLogin(!1),e=void 0;var n=yield this.previousLoginManager.add(this.originLoginPromise);return this.doLoginStepsManager.clear(),this.previousLoginManager.clear(),this.originLoginPromise=void 0,this.reportLoginSucc(t),n}catch(e){if(r=e||r,this.logger.error(`V2NIMChatroomLoginService::login failed, times of login try: ${o}, err.code: ${null==r?void 0:r.code}, err.message: "${null==r?void 0:r.message}"`),this.reportLoginFail(t,r),this.reconnect.clearReconnectTimer(),this.checkLoginTerminalCode(r&&r.code)||r&&r.code===_t.V2NIM_ERROR_CODE_SERVER_UNIT_ERROR)throw this.lifeCycle.processEvent("exited",r),r}}throw this.lifeCycle.processEvent("exited",r),r}))}doLogin(e){var t;return __awaiter(this,void 0,void 0,(function*(){var r=!!e||this.authenticator.checkAutoLogin(this.connectParams.forceMode);yield this.doLoginStepsManager.add(this.clientSocket.connect(this.getNextLink(),e));var o=yield this.doLoginStepsManager.add(this.authenticator.verifyAuthentication(r));this.lifeCycle.processEvent("loginSucc",void 0,Object.assign(Object.assign({},o),{isReconnect:e})),this.clientSocket.resetSocketConfig(),this.reconnect.reset(),this.clientSocket.ping(),this.core.abtest.abtRequest(),this.core.V2NIMClientAntispamUtil.downloadLocalAntiSpamVocabs();try{yield this.core.cloudStorage.init(null===(t=o.selfMember)||void 0===t?void 0:t.enterTime)}catch(e){this.logger.warn("doLogin::cloudStorage init error",e)}return this.prevLoginResult=o,o}))}reportLoginSucc(e){return __awaiter(this,void 0,void 0,(function*(){var t=this.core.timeOrigin.getNTPTime(),r=Date.now()-e.time;this.core.timeOrigin.checkNodeReliable(e)&&(r=t-this.core.timeOrigin.getNTPTime(e));var{net_connect:o}=yield ae.net.getNetworkStatus();this.core.reporter.report("chatroomLogin",{accid:this.account,roomId:this.roomId,serverIps:this.linkAddressArray,currentServerIp:this.getCurrLink(),rt:r,result:200,failReason:"",time:t,net_connect:o,binary_websocket:this.core.config.binaryWebsocket})}))}reportLoginFail(e,t){return __awaiter(this,void 0,void 0,(function*(){var r=get(t,"code")||get(t,"detail.rawError.code")||0,o=get(t,"detail.rawError.message")||get(t,"message")||"login failed";if(r!==_t.V2NIM_ERROR_CODE_CANCELLED){var i=this.core.timeOrigin.getNTPTime(),n=Date.now()-e.time;this.core.timeOrigin.checkNodeReliable(e)&&(n=i-this.core.timeOrigin.getNTPTime(e));var{net_connect:s}=yield ae.net.getNetworkStatus();this.core.reporter.report("chatroomLogin",{accid:this.account,roomId:this.roomId,serverIps:this.linkAddressArray,currentServerIp:this.getCurrLink(),rt:n,result:r,failReason:o,time:i,net_connect:s,binary_websocket:this.core.config.binaryWebsocket})}}))}smoothForLogined(e,t,r){return __awaiter(this,void 0,void 0,(function*(){var o=this.checkIsSameLogin(e,t,r);return this.logger.warn(`V2NIMChatroomLoginService::smoothForLogined:Logined, isSameLogin ${o}`),o?this.prevLoginResult:(yield this.logout(),this.login(e,t,r))}))}smoothForLogining(e,t,r){return __awaiter(this,void 0,void 0,(function*(){var o=this.checkIsSameLogin(e,t,r);if(this.previousLoginManager.clear(),this.reconnect.reset(),o){if(!this.originLoginPromise)throw new V2NIMErrorImpl({code:_t.V2NIM_ERROR_CODE_INTERNAL,detail:{reason:"NoPreviousLoginExists"}});return this.reconnect.reset(),yield Promise.resolve(),yield this.multiTryDoLogin(this.originLoginPromise)}return this.doLoginStepsManager.clear(),this.clientSocket.doDisconnect(Ae.ACTIVE,"Aborted"),this.reset(),this.lifeCycle.processEvent("logout",new V2NIMErrorImpl({code:_t.V2NIM_ERROR_CODE_DISCONNECT,detail:{reason:"disconnect due to logout. aborted previous login."}})),yield Promise.resolve(),this.login(e,t,r)}))}checkIsSameLogin(e,t,r){var o,i,n,s,a,c,l,_=void 0!==r.anonymousMode&&r.anonymousMode,d=(null===(o=r.loginOption)||void 0===o?void 0:o.authType)||0,E=JSON.stringify((null===(n=null===(i=this.enterParams)||void 0===i?void 0:i.tagConfig)||void 0===n?void 0:n.tags)||[]),h=JSON.stringify((null===(s=r.tagConfig)||void 0===s?void 0:s.tags)||[]),u=JSON.stringify((null===(a=this.enterParams)||void 0===a?void 0:a.locationConfig)||{}),m=JSON.stringify(r.locationConfig||{});return this.appkey===e&&this.roomId===t&&this.authType===d&&this.isAnonymous===_&&this.account===r.accountId&&(null===(c=this.enterParams)||void 0===c?void 0:c.roomNick)===r.roomNick&&(null===(l=this.enterParams)||void 0===l?void 0:l.roomAvatar)===r.roomAvatar&&E===h&&u===m}logout(){return __awaiter(this,void 0,void 0,(function*(){this.doLoginStepsManager.clear(),this.previousLoginManager.clear(),this.loginTimerManager.destroy(),this.originLoginPromise=void 0;var e=this.getConnectStatus(),t=this.getLoginStatus(),r=new V2NIMErrorImpl({code:_t.V2NIM_ERROR_CODE_DISCONNECT,detail:{reason:"disconnect due to logout"}});switch(t){case 1:try{yield this.clientSocket.sendCmd("v2ChatroomLogout",void 0,{timeout:1e3}),this.clientSocket.doDisconnect(Ae.ACTIVE,"UserActiveDisconnect"),this.lifeCycle.processEvent("logout",r)}catch(e){this.logger.error("Instance::disconnect sendCmd:logout error",e),this.clientSocket.doDisconnect(Ae.ACTIVE,"UserActiveDisconnect"),this.lifeCycle.processEvent("logout",r)}break;case 2:this.clientSocket.doDisconnect(Ae.ACTIVE,"UserActiveDisconnect"),this.lifeCycle.processEvent("logout",r);break;case 3:this.clientSocket.doDisconnect(Ae.ACTIVE,"UserActiveDisconnect"),this.core._clearModuleData(),this.lifeCycle.processEvent("logout",r);break;case 0:throw this.core._clearModuleData(),new V2NIMErrorImpl({code:_t.V2NIM_ERROR_CODE_ILLEGAL_STATE,detail:{reason:`Illegal logout. loginStatus ${t}. connectStatus ${e}`}});default:throw this.core._clearModuleData(),new V2NIMErrorImpl({code:_t.V2NIM_ERROR_CODE_ILLEGAL_STATE,detail:{reason:`Illegal logout. illegal status: loginStatus ${t}. connectStatus ${e}`}})}}))}getConnectStatus(){return this.lifeCycle.getConnectStatus()}getLoginStatus(){return this.lifeCycle.getLoginStatus()}getLoginUser(){return this.account}getRoomId(){return this.roomId}checkLoginTerminalCode(e){return this.authenticator.checkLoginTerminalCode(e)}updateLinkAddress(){var e;return __awaiter(this,void 0,void 0,(function*(){if(null===(e=this.enterParams)||void 0===e?void 0:e.linkProvider)try{this.linkAddressArray=yield this.enterParams.linkProvider(this.account,this.roomId),this.currLinkIdx=-1,(e=>{if(!Array.isArray(e))throw new V2NIMErrorImpl({code:400,message:"linkAddressArray must be an array"});if(0===e.length)throw new V2NIMErrorImpl({code:400,message:"linkAddressArray must not be empty"});e.forEach((e=>{if(!e)throw new V2NIMErrorImpl({code:400,message:"linkAddress must not be empty"})}))})(this.linkAddressArray)}catch(e){throw new V2NIMErrorImpl({code:_t.V2NIM_ERROR_CODE_INTERNAL,detail:{reason:"linkProvider error: "+e}})}}))}updateDynamicParamters(e){var t,r,o,i;return __awaiter(this,void 0,void 0,(function*(){if(this.enterParams){if(e&&(yield this.updateLinkAddress()),0!==this.authType&&(null===(r=null===(t=this.enterParams)||void 0===t?void 0:t.loginOption)||void 0===r?void 0:r.tokenProvider)){try{this.token=yield this.enterParams.loginOption.tokenProvider(this.appkey,this.roomId,this.account)}catch(e){throw new V2NIMErrorImpl({code:_t.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"tokenProvider error: "+e}})}if(null===this.token||void 0===this.token)throw new V2NIMErrorImpl({code:_t.V2NIM_ERROR_CODE_CALLBACK_FAILED,detail:{reason:"tokenProvider should not return null or undefined when authType === 1 or authType === 2"}});if(!this.token&&1===this.authType)throw new V2NIMErrorImpl({code:_t.V2NIM_ERROR_CODE_CALLBACK_FAILED,detail:{reason:"tokenProvider should not return empty string when authType === 1"}})}if(null===(i=null===(o=this.enterParams)||void 0===o?void 0:o.loginOption)||void 0===i?void 0:i.loginExtensionProvider){try{this.loginExt=yield this.enterParams.loginOption.loginExtensionProvider(this.appkey,this.roomId,this.account)}catch(e){throw new V2NIMErrorImpl({code:_t.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"loginExtensionProvider error: "+e}})}if((null===this.loginExt||void 0===this.loginExt)&&2===this.authType)throw new V2NIMErrorImpl({code:_t.V2NIM_ERROR_CODE_CALLBACK_FAILED,detail:{reason:"loginExtensionProvider should not return null or undefined when authType === 2"}})}}}))}setLoginParams(e,t,r){var o,i;return __awaiter(this,void 0,void 0,(function*(){if(this.reset(),this.roomId=t,this.enterParams=r,this.core.options.appkey=e,this.core.options.tags=(null===(o=r.tagConfig)||void 0===o?void 0:o.tags)||[],r.token&&(this.token=r.token),r.anonymousMode&&!r.accountId?this.core.options.account=`nimanon_${ve()}`:this.core.options.account=r.accountId,this.isAnonymous=void 0!==r.anonymousMode&&r.anonymousMode,this.isAnonymous&&!r.roomNick){if(void 0!==r.roomNick)throw new V2NIMErrorImpl({code:_t.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"roomNick is required when anonymousMode is true"}});r.roomNick=this.core.options.account}this.authType=(null===(i=r.loginOption)||void 0===i?void 0:i.authType)||0,yield this.updateDynamicParamters(!0)}))}v2LoginHandler(e){if(e.error)throw this.clientSocket.doDisconnect(Ae.ACTIVE,e.error),e.error;return e}v2LoginClientChangeHandler(e){this.authenticator.changeLoginClient(parseInt(e.content.state),e.content.datas)}nimLoginClientChangeHandler(e){this.authenticator.changeLoginClient(parseInt(e.content.state),e.content.datas)}v2ChatroomBeKickedHandler(e){var t=e.content,{kickedReason:r,serverExtension:o}=t;this.clientSocket.doDisconnect(Ae.KICKED,r),this.core._clearModuleData(),this.lifeCycle.processEvent("kicked",new V2NIMErrorImpl({code:_t.V2NIM_ERROR_CODE_DISCONNECT,detail:{reason:"disconnect due to kicked"}}),r),this.core.emit("onChatroomKicked",{kickedReason:r,serverExtension:o})}}var Nt={user_id:"",trace_id:"",action:7,exception_service:6,duration:0,start_time:0,state:1,extension:[]};class ReporterHookLinkKeep{constructor(e,t){this.traceData=Nt,this.core=e,this.traceData=Object.assign({},Nt,t),this.traceData.extension=[]}reset(){this.traceData=Object.assign({},Nt),this.traceData.extension=[]}start(){var e,t;this.reset(),this.traceData.user_id=this.core.account,this.traceData.trace_id=(null===(t=null===(e=this.core.clientSocket)||void 0===e?void 0:e.socket)||void 0===t?void 0:t.sessionId)||"",this.traceData.start_time=(new Date).getTime()}update(e){return __awaiter(this,void 0,void 0,(function*(){var{net_type:t,net_connect:r}=yield ae.net.getNetworkStatus();this.traceData.extension.push(Object.assign({code:0,foreground:!0,foreg_backg_switch:!1,net_type:t,net_connect:r},e))}))}end(e){var t=this.traceData.extension[0],r=this.traceData.extension[1];if(t&&0===t.operation_type&&r&&1===r.operation_type){var o=t.net_type!==r.net_type||t.net_connect!==r.net_connect;if(e||!o)return this.traceData.duration=(new Date).getTime()-this.traceData.start_time,this.core.reporter.report("exceptions",this.traceData),void this.reset();this.reset()}else this.reset()}}var Tt="V2NIMChatroomInfoService",Ot={"36_13":"v2GetChatroomInfo","36_14":"v2UpdateChatroomInfo","36_30":"v2SetTempChatBannedByTag","13_33":"v2UpdateChatroomLocation","36_34":"v2UpdateChatroomTags"},Mt={tags:{id:1,converter:e=>JSON.stringify(e)},notifyTargetTags:2,notificationEnabled:{id:3,converter:e=>+e},notificationExtension:4},ft={v2GetChatroomInfo:{sid:36,cid:13,service:Tt,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(nt)}]},v2UpdateChatroomInfo:{sid:36,cid:14,service:Tt,params:[{type:"Property",name:"chatroom",reflectMapper:nt},{type:"Bool",name:"notificationEnabled"},{type:"String",name:"notificationExtension"}]},v2SetTempChatBannedByTag:{sid:36,cid:30,service:Tt,params:[{type:"Property",name:"tag",reflectMapper:{targetTag:1,duration:2,notificationEnabled:{id:3,converter:e=>+e},notificationExtension:4,notifyTargetTags:5}}]},v2UpdateChatroomLocation:{sid:13,cid:33,service:Tt,params:[{type:"Property",name:"tag",reflectMapper:{x:1,y:2,z:3,distance:4}}]},v2UpdateChatroomTags:{sid:36,cid:34,service:Tt,params:[{type:"Property",name:"tag",reflectMapper:Mt}]}};class Service{constructor(e,t){this.name=e,this.core=t,this.name=e,this.logger=t.logger,this.core=t}process(e){var t=this[e.cmd+"Handler"];if("function"==typeof t)return t.call(this,e);var r=get(e,"error.detail.ignore");return e.error&&!r?Promise.reject(e.error):Promise.resolve(e)}}class V2NIMChatroomInfoModel{constructor(){this.chatroomInfo=null}reset(){this.chatroomInfo=null}}class V2NIMChatroomInfoServiceImpl extends Service{constructor(e){super("V2NIMChatroomInfoService",e),registerParser({cmdMap:Ot,cmdConfig:ft}),this.model=new V2NIMChatroomInfoModel,this.setListener()}setListener(){this.core.eventBus.on("V2NIMChatroomMessageService/onReceiveNotification",((e,t)=>__awaiter(this,void 0,void 0,(function*(){var r,o;if(6===e.attachment.type){var i=null===(r=t.data.roomInfo)||void 0===r?void 0:r.extension,n=null===(o=t.data.roomInfo)||void 0===o?void 0:o.queueLevel,s=Object.assign(Object.assign(Object.assign({},t.data.roomInfo||{}),void 0!==i?{serverExtension:i}:{}),void 0!==n?{queueLevelMode:n}:{});delete s.extension,delete s.queueLevel;var a=yield this._updateChatroomInfo(s);this.core.V2NIMChatroomService.emit("onChatroomInfoUpdated",a)}}))))}reset(){this.model.reset()}getChatroomInfo(){return this.model.chatroomInfo}updateChatroomInfo(e,t){return __awaiter(this,void 0,void 0,(function*(){if(validate(ut,{updateParams:e,antispamConfig:t},"",!0),!(e.announcement||e.liveUrl||e.roomName||e.serverExtension))throw new V2NIMErrorImpl({code:_t.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"updateParams.announcement, updateParams.liveUrl, updateParams.roomName, updateParams.serverExtension 至少有一个不为空"}});var r=void 0===e.notificationEnabled||e.notificationEnabled;yield this.core.sendCmd("v2UpdateChatroomInfo",{chatroom:e,notificationEnabled:r,notificationExtension:e.notificationExtension||""}),this._updateChatroomInfo(function pick(e,t){e=e||{};var r={};return(t=t||[]).forEach((t=>{void 0!==e[t]&&(r[t]=e[t])})),r}(e,["announcement","liveUrl","roomName","serverExtension"]))}))}updateChatroomLocationInfo(e){return __awaiter(this,void 0,void 0,(function*(){validate(mt,e,"",!0),yield this.core.sendCmd("v2UpdateChatroomLocation",{tag:Object.assign(Object.assign({},e.locationInfo),{distance:e.distance})})}))}updateChatroomTags(e){return __awaiter(this,void 0,void 0,(function*(){if(validate(gt,{updateParams:e},"",!0),!e.tags&&void 0===e.notifyTargetTags)throw new V2NIMErrorImpl({code:_t.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"updateParams.tags, updateParams.notifyTargetTags 至少有一个不为空"}});e.notificationEnabled=void 0===e.notificationEnabled||e.notificationEnabled,yield this.core.sendCmd("v2UpdateChatroomTags",{tag:e})}))}setTempChatBannedByTag(e){return __awaiter(this,void 0,void 0,(function*(){validate(pt,e,"",!0),e.notificationEnabled=void 0===e.notificationEnabled||e.notificationEnabled,yield this.core.sendCmd("v2SetTempChatBannedByTag",{tag:e})}))}_updateChatroomInfo(e){return __awaiter(this,void 0,void 0,(function*(){return this.model.chatroomInfo?Object.assign(this.model.chatroomInfo,e):yield this._getChatroomInfoAsync(),this.model.chatroomInfo}))}_getChatroomInfoAsync(){return __awaiter(this,void 0,void 0,(function*(){var e=yield this.core.sendCmd("v2GetChatroomInfo");this._setChatroomInfo(e.content.data)}))}_setChatroomInfo(e){this.model.chatroomInfo=e}}var St,Rt,Ct={file:{md5:"$(Etag)",size:"$(ObjectSize)"},image:{md5:"$(Etag)",size:"$(ObjectSize)",w:"$(ImageInfo.Width)",h:"$(ImageInfo.Height)",orientation:"$(ImageInfo.Orientation)"},audio:{md5:"$(Etag)",size:"$(ObjectSize)",dur:"$(AVinfo.Audio.Duration)"},video:{md5:"$(Etag)",size:"$(ObjectSize)",dur:"$(AVinfo.Video.Duration)",w:"$(AVinfo.Video.Width)",h:"$(AVinfo.Video.Height)"}},At={accessKeyId:"",secretAccessKey:"",sessionToken:"",region:"",maxRetries:0,bucket:"",objectName:"",token:"",shortUrl:""};function getUploadResponseFormat(e="file"){var t=Ct[e]||{};return JSON.stringify(t).replace(/"/gi,'\\"')}!function(e){e[e.nos=1]="nos",e[e.s3=2]="s3"}(St||(St={})),function(e){e[e.dontNeed=-1]="dontNeed",e[e.time=2]="time",e[e.urls=3]="urls"}(Rt||(Rt={}));var vt={chunkUploadHost:"https://wannos-web.127.net",chunkUploadHostBackupList:["https://fileup.chatnos.com","https://oss.chatnos.com"],commonUploadHost:"https://fileup.chatnos.com",commonUploadHostBackupList:["https://oss.chatnos.com"],chunkMaxSize:4194304e4,commonMaxSize:104857600,uploadReplaceFormat:"https://{host}/{object}",cdn:{defaultCdnDomain:"nim-nosdn.netease.im",cdnDomain:"",bucket:"",objectNamePrefix:""},downloadUrl:"https://{bucket}-nosdn.netease.im/{object}",downloadHostList:["nos.netease.com"],nosCdnEnable:!0,isNeedToGetUploadPolicyFromServer:!0};class NOS{constructor(e,t){this.nosCdnHostTimer=0,this.nosErrorCount=0,this.core=e,this.cloudStorage=t}get config(){return this.cloudStorage.config}reset(){this.nosErrorCount=0}getNosAccessToken(e){return __awaiter(this,void 0,void 0,(function*(){var t=get(yield this.core.sendCmd("getNosAccessToken",{tag:e}),"content.nosAccessTokenTag.token"),r=e.url;return{token:t,url:-1!==r.indexOf("?")?r+"&token="+t:r+"?token="+t}}))}deleteNosAccessToken(e){return __awaiter(this,void 0,void 0,(function*(){yield this.core.sendCmd("deleteNosAccessToken",{tag:e})}))}nosUpload(e,t){var r,o,i,n,s,a,c,l;return __awaiter(this,void 0,void 0,(function*(){var _=get(this.core,"config.cdn.bucket"),d={tag:e.nosScenes||_||"nim"};e.nosSurvivalTime&&(d.expireSec=e.nosSurvivalTime);var E,h=this.core.adapters.getFileUploadInformation(e);if(!t&&!h)try{E=yield this.core.sendCmd("getNosToken",{responseBody:getUploadResponseFormat(e.type),nosToken:d})}catch(e){if(this.core.logger.error("uploadFile:: getNosToken error",e),e instanceof V2NIMErrorImpl)throw e;throw new UploadError({code:"v2"===get(this.core,"options.apiVersion")?_e.V2NIM_ERROR_CODE_FILE_UPLOAD_FAILED:400,detail:{reason:"getNosToken error",rawError:e,curProvider:1}})}var u=this.config.uploadReplaceFormat.replace("{host}",this.config.cdn.cdnDomain||this.config.cdn.defaultCdnDomain).replace("{object}",h?null===(r=h.uploadInfo)||void 0===r?void 0:r.objectName:t?null==t?void 0:t.objectName:E.content.nosToken.objectName),m="";t&&t.shortUrl&&(m=t.shortUrl),(null===(n=null===(i=null===(o=null==h?void 0:h.uploadInfo)||void 0===o?void 0:o.payload)||void 0===i?void 0:i.mixStoreToken)||void 0===n?void 0:n.shortUrl)&&(m=h.uploadInfo.payload.mixStoreToken.shortUrl);var g,p=m||u;try{var I=h?{token:null===(s=null==h?void 0:h.uploadInfo)||void 0===s?void 0:s.token,bucket:null===(a=null==h?void 0:h.uploadInfo)||void 0===a?void 0:a.bucketName,objectName:null===(c=null==h?void 0:h.uploadInfo)||void 0===c?void 0:c.objectName}:t||E.content.nosToken;this.core.logger.log("uploadFile:: uploadFile params",{nosToken:I,chunkUploadHost:this.config.chunkUploadHost,chunkUploadHostBackupList:this.config.chunkUploadHostBackupList,commonUploadHost:this.config.commonUploadHost,commonUploadHostBackupList:this.config.commonUploadHostBackupList,platform:ae.platform});var N="BROWSER"===ae.platform?this.config.chunkUploadHost:`${this.config.commonUploadHost}/${I&&I.bucket}`;this.core.reporterHookCloudStorage.update({remote_addr:N,operation_type:t?2:0}),g=yield this.core.adapters.uploadFile(Object.assign(Object.assign(Object.assign({},e),{nosToken:I,chunkUploadHost:this.config.chunkUploadHost,chunkUploadHostBackupList:this.config.chunkUploadHostBackupList,commonUploadHost:this.config.commonUploadHost,commonUploadHostBackupList:this.config.commonUploadHostBackupList,maxSize:e.maxSize||this.config.chunkMaxSize}),t?{payload:{mixStoreToken:t}}:{}))}catch(r){this.core.logger.error("uploadFile::nos uploadFile error:",r);var T="v2"===get(this.core,"options.apiVersion");if(r.code===_e.V2NIM_ERROR_CODE_CANCELLED||10499===r.errCode)throw new UploadError({code:T?_e.V2NIM_ERROR_CODE_CANCELLED:400,detail:{reason:get(r,"message")||"Request abort",rawError:r,curProvider:1}});if(T&&r.errCode===_e.V2NIM_ERROR_CODE_FILE_OPEN_FAILED)throw new V2NIMErrorImpl({code:_e.V2NIM_ERROR_CODE_FILE_OPEN_FAILED,detail:{reason:get(r,"message")||"Read file failed",rawError:r,curProvider:1}});var{net_connect:O}=yield ae.net.getNetworkStatus();if(!1===O)throw new UploadError({code:"v2"===get(this.core,"options.apiVersion")?_e.V2NIM_ERROR_CODE_FILE_UPLOAD_FAILED:400,detail:{reason:"No network",rawError:r,curProvider:1}});if(t){if(this.nosErrorCount<=0){try{this.cloudStorage.mixStorage._addCircuitTimer()}catch(t){throw new UploadError({code:"v2"===get(this.core,"options.apiVersion")?_e.V2NIM_ERROR_CODE_FILE_UPLOAD_FAILED:400,detail:{reason:"All upload attempts failed",rawError:t,curProvider:this.cloudStorage.mixStorage.curProvider,mixStorePolicy:this.cloudStorage.mixStorage.mixStorePolicy,file:e.file||e.filePath}})}return this.nosErrorCount=get(this.cloudStorage,"mixStorePolicy.nosPolicy.uploadConfig.retryPolicy.retry"),this.cloudStorage._uploadFile(e)}return this.nosErrorCount--,this.nosUpload(e,t)}throw new UploadError({code:"v2"===get(this.core,"options.apiVersion")?_e.V2NIM_ERROR_CODE_FILE_UPLOAD_FAILED:400,detail:{reason:"NOS attempts failed",rawError:r,curProvider:1}})}var M=null==g?void 0:g.type,f=M&&M.indexOf("/")>-1?M.slice(0,M.indexOf("/")):"";f||(f=e.type||"");var S,R={image:"imageInfo",video:"vinfo",audio:"vinfo"};if(!R[f])return Object.assign({url:p},g);try{S=yield this.core.adapters.request(`${u}?${R[f]}`,{method:"GET",dataType:"json",timeout:5e3},{exception_service:3})}catch(e){return this.core.logger.error("uploadFile:: fetch file info error",e),Object.assign({url:p},g)}if(S){var{data:C}=S,A="imageInfo"===R[f]?C:null===(l=null==C?void 0:C.GetVideoInfo)||void 0===l?void 0:l.VideoInfo;return pickBy({url:p,name:g.name,size:g.size,ext:g.ext,w:null==A?void 0:A.Width,h:null==A?void 0:A.Height,orientation:null==A?void 0:A.Orientation,dur:null==A?void 0:A.Duration,audioCodec:null==A?void 0:A.AudioCodec,videoCodec:null==A?void 0:A.VideoCodec,container:null==A?void 0:A.Container},(function(e){return void 0!==e}))}return Object.assign({url:p},g)}))}_getNosCdnHost(){var e;return __awaiter(this,void 0,void 0,(function*(){var t;try{t=yield this.core.sendCmd("getNosCdnHost")}catch(e){return void this.core.logger.error("getNosCdnHost::error",e)}if(t){var r=null===(e=null==t?void 0:t.content)||void 0===e?void 0:e.nosConfigTag,o=parseInt(null==r?void 0:r.expire);0!==o&&r.cdnDomain?-1===o?(this.config.cdn.bucket=r.bucket,this.config.cdn.cdnDomain=r.cdnDomain,this.config.cdn.objectNamePrefix=r.objectNamePrefix):(this.config.cdn.bucket=r.bucket,this.config.cdn.cdnDomain=r.cdnDomain,this.config.cdn.objectNamePrefix=r.objectNamePrefix,this.nosCdnHostTimer=this.core.timerManager.addTimer((()=>{this._getNosCdnHost()}),1e3*o)):(this.config.cdn.bucket="",this.config.cdn.cdnDomain="",this.config.cdn.objectNamePrefix="")}}))}}var yt={"6_2":"getNosToken","6_22":"getOriginUrl","6_24":"getNosAccessToken","6_25":"deleteNosAccessToken","6_26":"getNosCdnHost","6_27":"getGrayscaleConfig","6_28":"getMixStorePolicy","6_29":"getMixStoreToken","6_30":"getFileAuthToken"},Dt={nosToken:{objectName:1,token:2,bucket:3,expireTime:4,expireSec:7,tag:8,shortUrl:9},mixStoreTokenReqTag:{provider:0,tokenCount:1,nosSurvivalTime:2,tag:3,returnBody:4,policyVersion:5},nosConfigTag:{bucket:1,cdnDomain:2,expire:3,objectNamePrefix:4},grayConfigTag:{config:0,ttl:1},mixStorePolicyTag:{providers:0,ttl:1,mixEnable:2,nosPolicy:3,s3Policy:4,policyVersion:5},mixStoreTokenResTag:{provider:0,accessKeyId:1,secretAccessKey:2,sessionToken:3,token:4,expireTime:5,bucket:6,objectName:7,fileExpireSec:8,tag:9,shortUrl:10,region:11},nosSafeUrlTag:{safeUrl:0,originUrl:1},mixStoreAuthTokenReqTag:{type:1,urls:2},mixStoreAuthTokenResTag:{type:1,tokens:2,token:3,ttl:4},nosAccessTokenTag:{token:0,url:1,userAgent:2,ext:3}},Vt={getNosToken:{sid:6,cid:2,service:"cloudStorage",params:[{type:"String",name:"responseBody"},{type:"Property",name:"nosToken",entity:"nosToken",reflectMapper:Dt.nosToken}],response:[{type:"Property",name:"nosToken",reflectMapper:invertSerializeItem(Dt.nosToken)}]},getOriginUrl:{sid:6,cid:22,service:"cloudStorage",params:[{type:"Property",name:"nosSafeUrlTag",reflectMapper:Dt.nosSafeUrlTag}],response:[{type:"Property",name:"nosSafeUrlTag",reflectMapper:invertSerializeItem(Dt.nosSafeUrlTag)}]},getNosCdnHost:{sid:6,cid:26,service:"cloudStorage",response:[{type:"Property",name:"nosConfigTag",reflectMapper:invertSerializeItem(Dt.nosConfigTag)}]},getGrayscaleConfig:{sid:6,cid:27,service:"cloudStorage",params:[{type:"Property",name:"config"}],response:[{type:"Property",name:"grayConfigTag",reflectMapper:invertSerializeItem(Dt.grayConfigTag)}]},getMixStorePolicy:{sid:6,cid:28,service:"cloudStorage",params:[{type:"LongArray",name:"supportType"}],response:[{type:"Property",name:"mixStorePolicyTag",reflectMapper:invertSerializeItem(Dt.mixStorePolicyTag)}]},getMixStoreToken:{sid:6,cid:29,service:"cloudStorage",params:[{type:"Property",name:"mixStoreTokenReqTag",reflectMapper:Dt.mixStoreTokenReqTag}],response:[{type:"Property",name:"mixStoreTokenResTag",reflectMapper:invertSerializeItem(Dt.mixStoreTokenResTag)}]},getFileAuthToken:{sid:6,cid:30,service:"cloudStorage",params:[{type:"Property",name:"mixStoreAuthTokenReqTag",reflectMapper:Dt.mixStoreAuthTokenReqTag}],response:[{type:"Property",name:"mixStoreAuthTokenResTag",reflectMapper:invertSerializeItem(Dt.mixStoreAuthTokenResTag)}]},getNosAccessToken:{sid:6,cid:24,service:"cloudStorage",params:[{type:"Property",name:"tag",reflectMapper:Dt.nosAccessTokenTag}],response:[{type:"Property",name:"tag",reflectMapper:invertSerializeItem(Dt.nosAccessTokenTag)}]},deleteNosAccessToken:{sid:6,cid:25,service:"cloudStorage",params:[{type:"Property",name:"tag",reflectMapper:Dt.nosAccessTokenTag}]}};class MixStorage{constructor(e,t){this.GRAYKEY="AllGrayscaleConfig",this.MIXSTOREKEY="AllMixStorePolicy",this.grayConfig={mixStoreEnable:!1,timeStamp:0,ttl:0},this.mixStorePolicy={providers:[],timeStamp:0,ttl:0,s3Policy:null,nosPolicy:null,policyVersion:void 0},this.curProvider=1,this.mixStoreErrorCount=10,this.circuitTimer=0,this.core=e,this.cloudStorage=t,this.logger=e.logger}reset(){this.grayConfig=null,this.mixStorePolicy={providers:[],timeStamp:0,ttl:0,s3Policy:null,nosPolicy:null,policyVersion:void 0},this.curProvider=1,this.mixStoreErrorCount=10}getGrayscaleConfig(e,t){var r;return __awaiter(this,void 0,void 0,(function*(){if(ae.localStorage)try{ae.localStorage.getItem&&ae.localStorage.getItem(this.GRAYKEY)&&(this.grayConfig=JSON.parse(ae.localStorage.getItem(this.GRAYKEY))[e])}catch(e){ae.localStorage.getItem(this.GRAYKEY)&&this.core.logger.error("uploadFile:: JSON.parse grayscaleConfig error ",e)}if(!this.grayConfig||this.grayConfig.timeStamp+1e3*this.grayConfig.ttl<t){var o=yield this.core.sendCmd("getGrayscaleConfig",{config:{}});if(o.content&&o.content.grayConfigTag){this.logger.log("uploadFile::getAppGrayConfigRequest success ");try{this.grayConfig=JSON.parse(o.content.grayConfigTag.config),this.grayConfig.ttl=JSON.parse(o.content.grayConfigTag.ttl)}catch(e){this.logger.error("getGrayscaleConfig error",e)}if(!this.grayConfig)return;var i=ae.localStorage.getItem(this.GRAYKEY)?JSON.parse(ae.localStorage.getItem(this.GRAYKEY)):{};this.grayConfig.timeStamp=(new Date).getTime(),i[e]=this.grayConfig,ae.localStorage.setItem(this.GRAYKEY,JSON.stringify(i))}else this.logger.log("uploadFile:: result grayConfig:",o.content)}(null===(r=this.grayConfig)||void 0===r?void 0:r.mixStoreEnable)&&(yield this._getMixStorePolicy(e))}))}_getMixStorePolicy(e){return __awaiter(this,void 0,void 0,(function*(){var t=(new Date).getTime();if(ae.localStorage)try{if(this.mixStorePolicy=JSON.parse(ae.localStorage.getItem(this.MIXSTOREKEY))[e],this.curProvider=parseInt(this.mixStorePolicy.providers[0]),this.mixStorePolicy.timeStamp&&this.mixStorePolicy.timeStamp+1e3*this.mixStorePolicy.ttl>t){var r=this.mixStorePolicy.timeStamp+1e3*this.mixStorePolicy.ttl-t;this.core.timerManager.addTimer(this._getMixStorePolicy.bind(this,e),r)}}catch(t){ae.localStorage.getItem(this.MIXSTOREKEY)&&JSON.parse(ae.localStorage.getItem(this.MIXSTOREKEY))[e]&&this.core.logger.error("uploadFile:: JSON.parse mixStorePolicy error ",t)}if(!this.mixStorePolicy||this.mixStorePolicy.timeStamp+1e3*this.mixStorePolicy.ttl<=t)try{var o=(yield this.core.sendCmd("getMixStorePolicy",{supportType:this.cloudStorage.aws.s3?[1,2]:[1]})).content.mixStorePolicyTag;this.mixStorePolicy={providers:[],timeStamp:0,ttl:0,s3Policy:null,nosPolicy:null,policyVersion:void 0},this.mixStorePolicy.policyVersion=o.policyVersion,this.mixStorePolicy.ttl=Number(o.ttl),this.mixStorePolicy.providers=o.providers.split(","),this.circuitTimer&&this.core.timerManager.deleteTimer(this.circuitTimer),this.curProvider=parseInt(this.mixStorePolicy.providers[0]),this.mixStorePolicy.nosPolicy=o.nosPolicy?JSON.parse(o.nosPolicy):null,this.mixStorePolicy.s3Policy=o.s3Policy?JSON.parse(o.s3Policy):null,null===this.mixStorePolicy.s3Policy?this.mixStorePolicy.providers=["1"]:null===this.mixStorePolicy.nosPolicy?this.mixStorePolicy.providers=["2"]:this.mixStorePolicy.providers=this.mixStorePolicy.s3Policy.priority<this.mixStorePolicy.nosPolicy.priority?["2","1"]:["1","2"],this.core.timerManager.addTimer(this._getMixStorePolicy.bind(this,e),1e3*this.mixStorePolicy.ttl);var i=ae.localStorage.getItem(this.MIXSTOREKEY)?JSON.parse(ae.localStorage.getItem(this.MIXSTOREKEY)):{};this.mixStorePolicy.timeStamp=(new Date).getTime(),i[e]=this.mixStorePolicy,ae.localStorage.setItem(this.MIXSTOREKEY,JSON.stringify(i))}catch(t){if(this.logger.error("getMixStorePolicy error",t),0===this.mixStoreErrorCount)throw new Error("getMixStorePolicy all count error");this._getMixStorePolicy(e),this.mixStoreErrorCount--}this.mixStorePolicy.nosPolicy&&(this.cloudStorage.nos.nosErrorCount=this.mixStorePolicy.nosPolicy.uploadConfig.retryPolicy.retry)}))}_addCircuitTimer(){var e=this.mixStorePolicy.providers,t=e[(e.indexOf(String(this.curProvider))+1)%e.length];if(!t)throw new Error("uploadFile nextProvider error");if(t===e[0])throw new Error("uploadFile all policy fail");if(this.logger.log(`uploadFile:: upload policy will change,now policy:${this.curProvider} nextProvider:${t}`),this.curProvider=parseInt(t),this.mixStorePolicy.nosPolicy&&this.mixStorePolicy.s3Policy){var r=this.mixStorePolicy[1===this.curProvider?"nosPolicy":"s3Policy"].uploadConfig.retryPolicy.circuit;if(!r||0===r)throw new Error("uploadFile circuit error");this.circuitTimer=this.core.timerManager.addTimer((()=>{this.logger.log(`uploadFile:: upload policy will change,now policy:${this.curProvider} nextProvider:${parseInt(this.mixStorePolicy.providers[0])}`),this.curProvider=parseInt(this.mixStorePolicy.providers[0]),this.core.timerManager.deleteTimer(this.circuitTimer)}),1e3*r)}throw new Error("uploadFile will not retry again")}getFileAuthToken(e){return __awaiter(this,void 0,void 0,(function*(){return(yield this.core.sendCmd("getFileAuthToken",{mixStoreAuthTokenReqTag:e})).content.mixStoreAuthTokenResTag}))}}var Lt=-1;class AWS{constructor(e,t){this.s3=null,this.core=e,this.cloudStorage=t,this.logger=e.logger}get mixStorePolicy(){return this.cloudStorage.mixStorage.mixStorePolicy}s3Upload(e,t){return __awaiter(this,void 0,void 0,(function*(){var r;if(Lt+=1,e.file)r=e.file;else if("string"==typeof e.fileInput){this.logger.warn("fileInput will abandon,Please use file or filepath");var o=document.getElementById(e.fileInput);if(!(o&&o.files&&o.files[0]))throw new Error("Can not get file from fileInput");r=o.files[0]}else{if(!(e.fileInput&&e.fileInput.files&&e.fileInput.files[0]))throw new Error(`Can not get file from fileInput ${e.fileInput}`);r=e.fileInput.files[0]}if(!this.mixStorePolicy.s3Policy)throw new Error("dont get s3 policy");var i={accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey,sessionToken:t.sessionToken,region:t.region,maxRetries:this.mixStorePolicy.s3Policy.uploadConfig.retryPolicy.retry},n=this.s3,s=decodeURIComponent(t.bucket),a=decodeURIComponent(t.objectName),c=r,l=`https://${s}.s3.amazonaws.com/${a}`,_={},d=this.mixStorePolicy.s3Policy;if(d&&d.uploadConfig&&Array.isArray(d.uploadConfig.uploadUrl)&&d.uploadConfig.uploadUrl.length>0){var E=d.uploadConfig.uploadUrl.length;Lt%=E,_.endpoint=d.uploadConfig.uploadUrl[Lt],_.s3ForcePathStyle=!0,l=`${_.endpoint}/${s}/${a}`}this.core.reporterHookCloudStorage.update({remote_addr:l,operation_type:1});var h=new n(_);h.config.update(i);var u={Bucket:s,Key:a,Body:c,Metadata:{token:t.token},ContentType:c.type||"application/octet-stream"};this.core.logger.log("uploadFile:: s3 upload params:",u);var m=h.upload(u);return m.on("httpUploadProgress",(t=>{var r=parseFloat((t.loaded/t.total).toFixed(2));e.onUploadProgress&&e.onUploadProgress({total:t.total,loaded:t.loaded,percentage:r,percentageText:Math.round(100*r)+"%"})})),new Promise(((r,o)=>{var i=(new Date).getTime();m.send(((n,l)=>__awaiter(this,void 0,void 0,(function*(){var _,d,E;if(n&&"RequestAbortedError"===n.code)this.logger.error("uploadFile:","api::s3:upload file abort.",n),o(new UploadError({code:"v2"===get(this.core,"options.apiVersion")?_e.V2NIM_ERROR_CODE_CANCELLED:400,detail:{reason:"S3RequestAbortedError",rawError:n,curProvider:2}}));else{if(!n){var h=this.mixStorePolicy.s3Policy.cdnSchema;h=(h=h.replace("{cdnDomain}",this.mixStorePolicy.s3Policy.dlcdn)).replace("{objectName}",l.Key);var u={size:c.size,name:c.name,url:t.shortUrl?t.shortUrl:h,ext:c.name.split(".")[1]||"unknown"},m=e.type||"",g={image:"imageInfo"};return r(g[m]?yield this.getS3FileInfo({url:h,infoSuffix:g[m],s3Result:u}):u)}this.logger.error("uploadFile:","api::s3:upload file failed.",n),this.core.reporter.reportTraceStart("exceptions",{user_id:this.core.options.account||(null===(d=null===(_=this.core)||void 0===_?void 0:_.auth)||void 0===d?void 0:d.account),trace_id:null===(E=this.core.clientSocket.socket)||void 0===E?void 0:E.sessionId,start_time:i,action:1,exception_service:4}),this.core.reporter.reportTraceUpdateV2("exceptions",{code:"number"==typeof n.status?n.status:"number"==typeof n.code?n.code:0,description:n.message||`${n.code}`,operation_type:1,target:JSON.stringify({bucket:s,object:a})},{asyncParams:ae.net.getNetworkStatus()}),this.core.reporter.reportTraceEnd("exceptions",1);var{net_connect:p}=yield ae.net.getNetworkStatus();if(!1===p)return o(new UploadError({code:"v2"===get(this.core,"options.apiVersion")?_e.V2NIM_ERROR_CODE_FILE_UPLOAD_FAILED:400,detail:{reason:"No network",rawError:n,curProvider:this.cloudStorage.mixStorage.curProvider}}));try{this.cloudStorage.mixStorage._addCircuitTimer()}catch(t){return o(new UploadError({code:"v2"===get(this.core,"options.apiVersion")?_e.V2NIM_ERROR_CODE_FILE_UPLOAD_FAILED:400,detail:{reason:"All upload attempts failed",rawError:t,curProvider:this.cloudStorage.mixStorage.curProvider,mixStorePolicy:this.mixStorePolicy,file:e.file||e.filePath}}))}r(this.cloudStorage._uploadFile(e))}})))),e.onUploadStart&&e.onUploadStart(m)}))}))}getS3FileInfo(e){var t;return __awaiter(this,void 0,void 0,(function*(){var r,{url:o,infoSuffix:i,s3Result:n}=e;try{r=yield this.core.adapters.request(`${o}?${i}`,{method:"GET",dataType:"text",timeout:5e3},{exception_service:3})}catch(e){return this.core.logger.error("uploadFile:: fetch file info error",e),n}if(r){var{data:s}=r,a="imageInfo"===i?s:null===(t=null==s?void 0:s.GetVideoInfo)||void 0===t?void 0:t.VideoInfo;return pickBy(Object.assign(Object.assign({},n),{w:null==a?void 0:a.Width,h:null==a?void 0:a.Height,orientation:null==a?void 0:a.Orientation,dur:null==a?void 0:a.Duration,audioCodec:null==a?void 0:a.AudioCodec,videoCodec:null==a?void 0:a.VideoCodec,container:null==a?void 0:a.Container}),(function(e){return void 0!==e}))}return this.core.logger.error("uploadFile:: fetch s3 file info no result",`${o}?${i}`),n}))}}class CloudStorageService{constructor(e,t={}){this.config={},this.uploadTaskMap={},this.name="cloudStorage",this.logger=e.logger,this.core=e,this.nos=new NOS(e,this),this.mixStorage=new MixStorage(e,this),this.aws=new AWS(e,this),registerParser({cmdMap:yt,cmdConfig:Vt}),this.setOptions(t),this.setListeners()}setOptions(e={}){var t=e.storageKeyPrefix||"NIMClient";this.mixStorage.GRAYKEY=t+"-AllGrayscaleConfig",this.mixStorage.MIXSTOREKEY=t+"-AllMixStorePolicy";var{s3:r}=e,o=__rest(e,["s3"]),i=Object.assign({},vt,this.config);if(o&&Object.prototype.hasOwnProperty.call(o,"cdn")){var n=Object.assign(Object.assign({},i.cdn),o.cdn);this.config=Object.assign({},i,o),this.config.cdn=n}else this.config=Object.assign({},i,o);r&&(this.aws.s3=r)}setListeners(){this.core.eventBus.on("kicked",this._clearUnCompleteTask.bind(this)),this.core.eventBus.on("disconnect",this._clearUnCompleteTask.bind(this)),this.core.eventBus.on("V2NIMLoginService/loginLifeCycleLogout",this._clearUnCompleteTask.bind(this)),this.core.eventBus.on("V2NIMLoginService/loginLifeCycleKicked",this._clearUnCompleteTask.bind(this))}_clearUnCompleteTask(){Object.keys(this.uploadTaskMap).forEach((e=>{var t=this.uploadTaskMap[e];t&&t.abort&&t.abort()})),this.uploadTaskMap={}}init(e=Date.now()){return __awaiter(this,void 0,void 0,(function*(){this.mixStorage.reset(),this.nos.reset(),this.config.isNeedToGetUploadPolicyFromServer&&(yield this.mixStorage.getGrayscaleConfig(this.core.options.appkey,e)),yield this.nos._getNosCdnHost()}))}processCallback(e,t){var r=e.onUploadProgress,o=e.onUploadDone,i=e.onUploadStart;return{onUploadStart:"function"==typeof i?e=>{this.uploadTaskMap[t]=e;try{i(e)}catch(e){this.logger.error("CloudStorage::uploadFile:options.onUploadStart execute error",e)}}:e=>{this.uploadTaskMap[t]=e},onUploadProgress:"function"==typeof r?e=>{this.core.reporterHookCloudStorage.update({transferred_size:e.loaded,full_size:e.total});try{r(e)}catch(e){this.logger.error("CloudStorage::uploadFile:options.onUploadProgress execute error",e)}}:e=>{this.core.reporterHookCloudStorage.update({transferred_size:e.loaded,full_size:e.total})},onUploadDone:"function"==typeof o?e=>{this.core.reporterHookCloudStorage.end(0);try{o(e)}catch(e){this.logger.error("CloudStorage::uploadFile:options.onUploadDone execute error",e)}}:()=>{this.core.reporterHookCloudStorage.end(0)},taskKey:t}}uploadFile(e){return __awaiter(this,void 0,void 0,(function*(){if(validate({maxSize:{type:"number",required:!1},type:{type:"enum",values:["file","image","audio","video"]}},e),!e.fileInput&&!e.file&&!e.filePath)throw new Error("uploadFile needs target file object or a filePath");if(e.type&&"file"!==e.type){var t=get(e,"file.type");if(t&&"string"==typeof t&&-1===t.indexOf(e.type))throw new Error(`The meta type "${t}" does not match "${e.type}"`)}if(this.core.reporterHookCloudStorage.start(),e.file)this.core.reporterHookCloudStorage.update({full_size:e.file.size});else if("string"==typeof e.fileInput){var r=document.getElementById(e.fileInput);r&&r.files&&r.files[0]&&this.core.reporterHookCloudStorage.update({full_size:r.files[0].size})}else e.fileInput&&e.fileInput.files&&e.fileInput.files[0]&&this.core.reporterHookCloudStorage.update({full_size:e.fileInput.files[0].size});var o=ve(),{onUploadStart:i,onUploadProgress:n,onUploadDone:s}=this.processCallback(e,o);e.onUploadStart=i,e.onUploadProgress=n,e.onUploadDone=s;var a=null;try{a=yield this._uploadFile(e),e.md5&&(a.md5=e.md5),delete this.uploadTaskMap[o]}catch(e){throw delete this.uploadTaskMap[o],this.core.reporterHookCloudStorage.end((e&&e.code)===_e.V2NIM_ERROR_CODE_CANCELLED?3:1),e}return a&&(a.size=void 0===a.size?void 0:Number(a.size),a.w=void 0===a.w?void 0:Number(a.w),a.h=void 0===a.h?void 0:Number(a.h),a.dur=void 0===a.dur?void 0:Number(a.dur)),a.url=decodeURIComponent(a.url),e.onUploadDone({size:a.size,name:a.name,url:a.url,ext:a.name.split(".")[1]||"unknown"}),a}))}_uploadFile(e){var t,r;return __awaiter(this,void 0,void 0,(function*(){if(!get(this.mixStorage,"grayConfig.mixStoreEnable")||!get(this.mixStorage,"mixStorePolicy.providers.length"))return this.logger.log("uploadFile:: uploadFile begin, use old nos"),this.nos.nosUpload(e);this.logger.log(`uploadFile::_uploadFile, grayConfig enable:${get(this.mixStorage,"grayConfig.mixStoreEnable")} curProvider:${get(this.mixStorage,"curProvider")}`);var o=this.core.adapters.getFileUploadInformation(e),i=!0;o?!1===o.complete&&2===this.mixStorage.curProvider&&(i=!1):i=!1,this.aws.s3||(this.mixStorage.curProvider=1);var n=At;if(!i)try{n=(yield this.core.sendCmd("getMixStoreToken",{mixStoreTokenReqTag:{provider:this.mixStorage.curProvider,tokenCount:1,tag:"qchat",nosSurvivalTime:e.nosSurvivalTime,returnBody:getUploadResponseFormat(e.type),policyVersion:this.mixStorage.mixStorePolicy.policyVersion}})).content.mixStoreTokenResTag}catch(e){if(this.core.logger.error("uploadFile:: getMixStoreToken error",e),e instanceof V2NIMErrorImpl)throw e;throw new UploadError({code:"v2"===get(this.core,"options.apiVersion")?_e.V2NIM_ERROR_CODE_FILE_UPLOAD_FAILED:400,detail:{reason:"getMixStoreToken error",rawError:e,curProvider:this.mixStorage.curProvider,mixStorePolicy:this.mixStorage.mixStorePolicy}})}return i?this.nos.nosUpload(e,null===(r=null===(t=null==o?void 0:o.uploadInfo)||void 0===t?void 0:t.payload)||void 0===r?void 0:r.mixStoreToken):2===this.mixStorage.curProvider?this.aws.s3Upload(e,n):this.nos.nosUpload(e,n)}))}getThumbUrl(e,t){var r,o,i,n,s;if(!new RegExp(/http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- ./?%&=]*)?/).test(e))return this.logger.error("illegal file url:"+e),e;var[a,c,l,_,d,E,h,u]=/^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/.exec(e);if(null===(r=this.grayConfig)||void 0===r?void 0:r.mixStoreEnable){var m=this._getUrlType(e);if(2===m&&this.mixStorePolicy.s3Policy&&get(this.mixStorePolicy,"s3Policy.thumbPolicy.imagethumb"))return(null===(i=null===(o=this.mixStorePolicy.s3Policy)||void 0===o?void 0:o.thumbPolicy)||void 0===i?void 0:i.imagethumb).replace("{cdnDomain}",this.mixStorePolicy.s3Policy.dlcdn).replace("{objectName}",E).replace("{x}",t.width.toString()).replace("{y}",t.height.toString());if(1===m&&this.mixStorePolicy.nosPolicy&&get(this.mixStorePolicy,"nosPolicy.thumbPolicy.imagethumb"))return(null===(s=null===(n=this.mixStorePolicy.nosPolicy)||void 0===n?void 0:n.thumbPolicy)||void 0===s?void 0:s.imagethumb).replace("{cdnDomain}",this.mixStorePolicy.nosPolicy.dlcdn).replace("{objectName}",E).replace("{x}",t.width.toString()).replace("{y}",t.height.toString())}return e.includes("?")?e+`&imageView&thumbnail=${t.width}x${t.height}`:e+`?imageView&thumbnail=${t.width}x${t.height}`}getVideoCoverUrl(e,t){var r,o,i,n,s;if(!new RegExp(/http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- ./?%&=]*)?/).test(e))return this.logger.error("illegal file url:"+e),e;var[a,c,l,_,d,E,h,u]=/^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/.exec(e);if(null===(r=this.grayConfig)||void 0===r?void 0:r.mixStoreEnable){var m=this._getUrlType(e);if(2===m&&this.mixStorePolicy.s3Policy&&get(this.mixStorePolicy,"s3Policy.thumbPolicy.vframe"))return(null===(i=null===(o=this.mixStorePolicy.s3Policy)||void 0===o?void 0:o.thumbPolicy)||void 0===i?void 0:i.vframe).replace("{cdnDomain}",this.mixStorePolicy.s3Policy.dlcdn).replace("{objectName}",E).replace("{x}",t.width.toString()).replace("{y}",t.height.toString()).replace("{offset}","0").replace("{type}","png");if(1===m&&this.mixStorePolicy.nosPolicy&&get(this.mixStorePolicy,"nosPolicy.thumbPolicy.vframe"))return(null===(s=null===(n=this.mixStorePolicy.nosPolicy)||void 0===n?void 0:n.thumbPolicy)||void 0===s?void 0:s.vframe).replace("{cdnDomain}",this.mixStorePolicy.nosPolicy.dlcdn).replace("{objectName}",E).replace("{x}",t.width.toString()).replace("{y}",t.height.toString()).replace("{offset}","0").replace("{type}","png")}return e.includes("?")?e+`&vframe&offset=0&resize=${t.width}x${t.height}&type=png`:e+`?vframe&offset=0&resize=${t.width}x${t.height}&type=png`}getPrivateUrl(e){var t;if(!new RegExp(/http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- ./?%&=]*)?/).test(e))return this.logger.error("illegal file url:"+e),"";var[r,o,i,n,s,a,c,l]=/^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/.exec(e);if(null===(t=this.grayConfig)||void 0===t?void 0:t.mixStoreEnable){var _=this._getUrlType(e);return 2===_&&this.mixStorePolicy.s3Policy&&(e=this.mixStorePolicy.s3Policy.cdnSchema.replace("{cdnDomain}",this.mixStorePolicy.s3Policy.dlcdn).replace("{objectName}",a)),1===_&&this.mixStorePolicy.nosPolicy&&(e=this.mixStorePolicy.nosPolicy.cdnSchema.replace("{cdnDomain}",this.mixStorePolicy.nosPolicy.dlcdn).replace("{objectName}",a)),e}var{downloadUrl:d,downloadHostList:E,nosCdnEnable:h}=this.config,u=this.config.cdn.cdnDomain,m=this.config.cdn.objectNamePrefix?decodeURIComponent(this.config.cdn.objectNamePrefix):"",g=decodeURIComponent(a),p=g.indexOf(m);if(u&&p>-1&&h)return`${o}${u}/${g.slice(p)}`;if(E.includes(n)&&a.includes("/")){var I=a.indexOf("/"),N=a.substring(0,I),T=a.substring(I+1);return d.replace("{bucket}",N).replace("{object}",T)}var O=E.filter((e=>"string"==typeof n&&n.includes(e)))[0],M=O?n.replace(O,"").replace(/\W/g,""):null;return M?d.replace("{bucket}",M).replace("{object}",a):e}getOriginUrl(e){return __awaiter(this,void 0,void 0,(function*(){return"string"==typeof e&&e.includes("_im_url=1")?(yield this.core.sendCmd("getOriginUrl",{nosSafeUrlTag:{safeUrl:e}})).content.nosSafeUrlTag.originUrl:e}))}getFileToken(e){return __awaiter(this,void 0,void 0,(function*(){validate({type:{type:"number",min:2,max:3},urls:{type:"array",required:!1,itemType:"string"}},e);var t=this.mixStorePolicy.nosPolicy?this.mixStorePolicy.nosPolicy.authPolicy.policyType:null,r=this.mixStorePolicy.s3Policy?this.mixStorePolicy.s3Policy.authPolicy.policyType:null;if(t===String(-1)&&r===String(-1))throw this.logger.error("don't need token"),new Error("don't need token");if(2===e.type){if(t&&t.indexOf(String(2))>=0||r&&r.indexOf(String(2))>0)return this.mixStorage.getFileAuthToken(e);throw this.logger.error("don't support time token "),new Error("don't support type time token ")}if(!e.urls||!e.urls.length)throw this.logger.error("urls is required when urls token"),new Error("urls is required when urls token");var o=[],i=[];if(e.urls.forEach((e=>{var t=this._getUrlType(e);1===t&&i.push(e),2===t&&o.push(e)})),(!r||0!==o.length&&r.indexOf(String(3))<0)&&(this.logger.warn("s3 url don't support url token"),o=[]),(!t||0!==i.length&&t.indexOf(String(3))<0)&&(this.logger.warn("nos url don't support url token"),i=[]),0===o.length&&0===i.length)throw this.logger.error("not support urls"),new Error("not support urls");if(0===o.length||0===i.length)return e.urls=JSON.stringify(e.urls),this.mixStorage.getFileAuthToken(e)}))}_getUrlType(e){return this.mixStorePolicy.nosPolicy&&this.mixStorePolicy.nosPolicy.dlcdns.some((t=>e.indexOf(t)>=0))?1:this.mixStorePolicy.s3Policy&&this.mixStorePolicy.s3Policy.dlcdns.some((t=>e.indexOf(t)>=0))?2:null}getNosAccessToken(e){return validate({url:{type:"string",allowEmpty:!1}},e),this.nos.getNosAccessToken(e)}deleteNosAccessToken(e){return validate({token:{type:"string",allowEmpty:!1}},e),this.nos.deleteNosAccessToken(e)}get grayConfig(){return this.mixStorage.grayConfig}get mixStorePolicy(){return this.mixStorage.mixStorePolicy}process(e){var t=get(e,"error.detail.ignore");return e.error&&!t?Promise.reject(e.error):Promise.resolve(e)}}function getFileOrPath(e){var t="object"==typeof e?e:void 0,r="string"==typeof e?e:void 0;if(!t&&!r)throw new V2NIMErrorImpl({code:_e.V2NIM_ERROR_CODE_MISUSE,detail:{reason:"getFileOrPath::incorrect file and path"}});if("string"==typeof r)if(0===r.indexOf("nim-external")){var o=document.getElementById(r);if(!(o&&o.files&&o.files[0]))throw new V2NIMErrorImpl({code:_e.V2NIM_ERROR_CODE_FILE_NOT_FOUND,detail:{reason:`getFileOrPath::file not exist: ${r}`}});t=o.files[0]}else if("BROWSER"===ae.platform)throw new V2NIMErrorImpl({code:_e.V2NIM_ERROR_CODE_MISUSE,detail:{reason:`getFileOrPath::incorrect path: ${r}`}});if("object"==typeof t&&void 0===t.size)throw new V2NIMErrorImpl({code:_e.V2NIM_ERROR_CODE_MISUSE,detail:{reason:"getFileOrPath::file no size"}});return{file:t,path:r}}class V2Service extends Ie{constructor(e,t){super(),this.name=e,this.logger=t.logger,this.core=t}checkV2(){var e=this.core.options.apiVersion;if("v2"===e)return!0;throw new V2NIMErrorImpl({code:_e.V2NIM_ERROR_CODE_MISUSE,detail:{reason:`The version "${e}" of client is not supported.`}})}checkLogin(){if(0===this.core.V2NIMLoginService.getLoginStatus())throw new V2NIMErrorImpl({code:_e.V2NIM_ERROR_CODE_ILLEGAL_STATE,detail:{reason:"Client logout."}})}emit(e,...t){this.logger.debug(`${this.name}::emit event: '${e.toString()}',`,void 0!==t[0]?t[0]:"",void 0!==t[1]?t[1]:"",void 0!==t[2]?t[2]:"");try{return super.emit(e,...t)}catch(t){return setTimeout((()=>{throw this.logger.error(`${this.name}::emit throw error in setTimeout. event: ${e.toString()}. Error`,t),t}),0),!1}}process(e){var t=this[e.cmd+"Handler"],r=this.handler&&this.handler[e.cmd+"Handler"];if("function"==typeof t||"function"==typeof r){if(e.error)return this.logger.error(`${e.cmd}::recvError`,e.error),Promise.reject(e.error);try{var o=t?t.call(this,e):r.call(this.handler,e);return Promise.resolve(o)}catch(e){return Promise.reject(e)}}var i=get(e,"error.detail.ignore");return e.error&&!i?Promise.reject(e.error):Promise.resolve(e)}}var bt={attachment:{type:"object",rules:{url:{type:"string",allowEmpty:!1}}},thumbSize:{type:"object",rules:{width:{type:"number",required:!1,min:0},height:{type:"number",required:!1,min:0}}}};class V2NIMStorageUtil extends V2Service{constructor(e){super("V2NIMStorageUtil",e),this.core=e}imageThumbUrl(e,t){return e+`?imageView&thumbnail=${t}z${t}`}videoCoverUrl(e,t){return e+`?vframe&offset=${t}`}getImageThumbUrl(e,t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2();var r=e;validate(bt,{attachment:r,thumbSize:t},"",!0),t.width=t.width||0,t.height=t.height||0,0===t.width&&0===t.height&&(t.width=150);var o=r.url;try{o=yield this.core.V2NIMStorageService.shortUrlToLong(r.url)}catch(e){this.core.logger.warn("shortUrlToLong error:",e)}return{url:this.core.cloudStorage.getThumbUrl(o,t)}}))}getVideoCoverUrl(e,t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2();var r=e;validate(bt,{attachment:r,thumbSize:t},"",!0),t.width=t.width||0,t.height=t.height||0,0===t.width&&0===t.height&&(t.width=150);var o=r.url;try{o=yield this.core.V2NIMStorageService.shortUrlToLong(r.url)}catch(e){this.core.logger.warn("shortUrlToLong error:",e)}return{url:this.core.cloudStorage.getVideoCoverUrl(o,t)}}))}}class V2NIMStorageServiceImpl extends V2Service{constructor(e){super("V2NIMStorageService",e),this.sceneMap={nim_default_profile_icon:{sceneName:"nim_default_profile_icon",expireTime:0},nim_default_im:{sceneName:"nim_default_im",expireTime:0},nim_system_nos_scene:{sceneName:"nim_system_nos_scene",expireTime:0},nim_security:{sceneName:"nim_security",expireTime:0}},this.uploadingMessageInfo={},this.core=e,this.core._registerDep(CloudStorageService,"cloudStorage"),this.core._registerDep(V2NIMStorageUtil,"V2NIMStorageUtil")}addCustomStorageScene(e,t){return this.checkV2(),validate({sceneName:{type:"string",allowEmpty:!1},expireTime:{type:"number",min:0}},{sceneName:e,expireTime:t},"",!0),this.sceneMap[e]={sceneName:e,expireTime:t},{sceneName:e,expireTime:t}}getStorageSceneList(){return this.checkV2(),Object.values(this.sceneMap)}getStorageScene(e){return e&&this.sceneMap[e]||this.sceneMap.nim_default_im}hasStorageScene(e){return void 0!==this.sceneMap[e]}createUploadFileTask(e){if(this.checkV2(),"string"==typeof e.fileObj&&0===e.fileObj.indexOf("nim-external")){var t=document.getElementById(e.fileObj);t&&t.files&&t.files[0]&&(e.fileObj=t.files[0])}return{taskId:ve(),uploadParams:e}}uploadFile(e,t){return __awaiter(this,void 0,void 0,(function*(){return this.checkV2(),validate({taskId:{type:"string",allowEmpty:!1}},e,"fileTask",!0),(yield this._uploadFile(e,t))[0]}))}uploadFileWithMetaInfo(e,t){return __awaiter(this,void 0,void 0,(function*(){return this.checkV2(),validate({taskId:{type:"string",allowEmpty:!1}},e,"fileTask",!0),function formatV2NIMFileMetaInfo(e){var{url:t,name:r,size:o,ext:i,md5:n,h:s,w:a,orientation:c,dur:l,audioCodec:_,videoCodec:d,container:E}=e;return JSON.parse(JSON.stringify({url:t,name:r,size:o,ext:i,md5:n,height:s,width:a,orientation:c,duration:l,audioCodec:_,videoCodec:d,container:E}))}((yield this._uploadFile(e,t))[1])}))}_uploadFile(e,t,r){var o;return __awaiter(this,void 0,void 0,(function*(){if(!this.core.cloudStorage||!this.core.cloudStorage.uploadFile)throw new Error('Service "cloudStorage" does not exist');var{uploadParams:i,taskId:n}=e,{file:s,path:a}=getFileOrPath(i.fileObj),{fileType:c}=r||{};if(this.uploadingMessageInfo[n])throw new V2NIMErrorImpl({code:_e.V2NIM_ERROR_CODE_RESOURCE_ALREADY_EXIST,detail:{reason:"V2NIMStorageService.uploadFile: repeat upload"}});try{var l={};s?l.file=s:a&&(0===(null==a?void 0:a.indexOf("nim-external"))?l.fileInput=a:l.filePath=a);var _=this.getStorageScene(i.sceneName);if(l.nosScenes=_.sceneName,l.nosSurvivalTime=_.expireTime,l.type=1===c?"image":2===c?"audio":3===c?"video":"file",l.file&&this.core.pluginMap["browser-md5-file"]){var d=yield this.getFileMd5(this.core.pluginMap["browser-md5-file"],n,l.file);l.md5=d}l.onUploadProgress=e=>{"function"==typeof t&&t(Math.round(100*e.percentage))},l.onUploadStart=e=>{var t;if(null===(t=this.uploadingMessageInfo[n])||void 0===t?void 0:t.abort)return e.abort(),void delete this.uploadingMessageInfo[n];this.uploadingMessageInfo[n]={abort:!1,task:e}},this.uploadingMessageInfo[n]={abort:!1};var E=yield this.core.cloudStorage.uploadFile(l);if(null===(o=this.uploadingMessageInfo[n])||void 0===o?void 0:o.abort)throw new V2NIMErrorImpl({code:_e.V2NIM_ERROR_CODE_CANCELLED,detail:{reason:"upload file aborted"}});return delete this.uploadingMessageInfo[n],[E.url,E]}catch(e){throw delete this.uploadingMessageInfo[n],this.core.logger.error("sendFile:: upload File error or abort.",e),e}}))}cancelUploadFile(e){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),yield this._cancelUploadFile(e.taskId)}))}_cancelUploadFile(e){return __awaiter(this,void 0,void 0,(function*(){this.checkV2();var t=this.uploadingMessageInfo[e];if(null==t?void 0:t.task)try{this.logger.log("V2NIMStorageService.cancelUploadFile: uploadInfo task exist"),yield t.task.abort(),delete this.uploadingMessageInfo[e]}catch(t){delete this.uploadingMessageInfo[e],this.core.logger.error("cancelMessageAttachmentUpload::abort error.",t)}else{if(!t)throw new V2NIMErrorImpl({code:_e.V2NIM_ERROR_CODE_RESOURCE_NOT_EXIST,detail:{reason:"V2NIMStorageService.cancelUploadFile: uploadInfo not exist"}});this.logger.log("V2NIMStorageService.cancelUploadFile: uploadInfo task not exist"),t.abort=!0}}))}getFileMd5(e,t,r){return __awaiter(this,void 0,void 0,(function*(){return new Promise(((o,i)=>{var n,s=new e;(null===(n=this.uploadingMessageInfo[t])||void 0===n?void 0:n.abort)?i(new V2NIMErrorImpl({code:_e.V2NIM_ERROR_CODE_CANCELLED,detail:{reason:"upload file aborted"}})):this.uploadingMessageInfo[t]={abort:!1,task:s};try{s.md5(r,((e,t)=>{"aborted"===e?i(new V2NIMErrorImpl({code:_e.V2NIM_ERROR_CODE_CANCELLED,detail:{reason:e}})):e?i(new V2NIMErrorImpl({code:_e.V2NIM_ERROR_CODE_INTERNAL,detail:{reason:"md5 calculate error in callback",rawError:e}})):o(t)}))}catch(e){i(new V2NIMErrorImpl({code:_e.V2NIM_ERROR_CODE_INTERNAL,detail:{reason:"md5 calculate error",rawError:e}}))}}))}))}shortUrlToLong(e){return __awaiter(this,void 0,void 0,(function*(){return this.checkV2(),this.core.cloudStorage.getOriginUrl(e)}))}getImageThumbUrl(e,t){return __awaiter(this,void 0,void 0,(function*(){return this.core.V2NIMStorageUtil.getImageThumbUrl(e,t)}))}getVideoCoverUrl(e,t){return __awaiter(this,void 0,void 0,(function*(){return this.core.V2NIMStorageUtil.getVideoCoverUrl(e,t)}))}}class FileUtil{constructor(e,t){this.core=e,this.service=t}doSendFile(e,t){return __awaiter(this,void 0,void 0,(function*(){var r=e.attachment;try{var[o,i]=yield this.core.V2NIMStorageService._uploadFile({taskId:e.messageClientId,uploadParams:{fileObj:(null==r?void 0:r.file)||(null==r?void 0:r.path),sceneName:null==r?void 0:r.sceneName}},t,{fileType:e.messageType}),n=Object.assign(Object.assign({},r),{uploadState:1});i.w&&(n.width=n.width||i.w),i.h&&(n.height=n.height||i.h),i.dur&&(n.duration=n.duration||i.dur),n.ext=n.ext&&-1===n.ext.indexOf(".")?`.${n.ext}`:n.ext;var s=["w","h","dur","ext","name"];for(var a in i)s.includes(a)||(n[a]=i[a]);var{raw:c,file:l,path:_}=n,d=__rest(n,["raw","file","path"]);e.attachment=JSON.parse(JSON.stringify(d)),e.attachment&&(e.attachment.raw=attachmentToRaw(e.messageType,e.attachment))}catch(t){throw e.attachment&&(e.attachment.uploadState=2),t}}))}cancelMessageAttachmentUpload(e){return __awaiter(this,void 0,void 0,(function*(){if(validate({messageClientId:{type:"string",allowEmpty:!1}},e,"",!0),![2,6,1,3].includes(e.messageType))throw new V2NIMErrorImpl({code:_t.V2NIM_ERROR_CODE_MISUSE,detail:{reason:`cancelMessageAttachmentUpload: messageType ${e.messageType} incorrect`}});if(2===e.sendingState||1===e.sendingState)throw new V2NIMErrorImpl({code:_t.V2NIM_ERROR_CODE_RESOURCE_NOT_EXIST,detail:{reason:"cancelMessageAttachmentUpload: message is already failed or succeeded"}});yield this.core.V2NIMStorageService._cancelUploadFile(e.messageClientId)}))}}class SendUtil{constructor(e,t){this.msgs=[],this.maxIdCount=100,this.core=e,this.service=t}reset(){this.msgs=[]}prepareMessage(e,t={}){var r=this.checkIfResend(e),o=this.generateSendMessage({message:e,params:t,resend:r}),{clientAntispamResult:i,text:n}=this.checkIfAntispam(t,o);return o.text=n,o.clientAntispamHit=!!i&&3===i.operateType,{messageBeforeSend:o,clientAntispamResult:i}}doSendMessage(e,t,r,o){return __awaiter(this,void 0,void 0,(function*(){var i,n={enabled:!1};if(!t.attachment||"object"!=typeof t.attachment||!("uploadState"in t.attachment)||t.attachment.url||0!==t.attachment.uploadState&&2!==t.attachment.uploadState)this.core.V2NIMChatroomService.emit("onSendMessage",t);else{var s=Date.now();try{t.attachmentUploadState=3,t.attachment.uploadState=3,this.core.V2NIMChatroomService.emit("onSendMessage",t),yield this.service.fileUtil.doSendFile(t,o),t.attachmentUploadState=1,t.attachment.uploadState=1,this.core.V2NIMChatroomService.emit("onSendMessage",t)}catch(r){throw t.attachmentUploadState=2,t.attachment.uploadState=2,t.sendingState=2,this.core.V2NIMChatroomService.emit("onSendMessage",t),n.attachUploadDuration=Date.now()-s,this.doMsgSendReport(e,n,t,r),r}n.attachUploadDuration=Date.now()-s}this.cacheMsg(t),this.core.timeOrigin.checkNodeReliable(e)&&(n.apiCallingTime=this.core.timeOrigin.getNTPTime(e),n.sendTime=this.core.timeOrigin.getNTPTime(),t.__clientExt={statistics:n});try{i=yield this.core.clientSocket.sendCmd("v2ChatroomSendMessage",{tag:t})}catch(r){throw t.sendingState=2,this.core.V2NIMChatroomService.emit("onSendMessage",t),this.doMsgSendReport(e,n,t,r),r}var a=formatMessage(this.core,Object.assign(Object.assign(Object.assign({},t),i.content.data),{sendingState:1}),this.core.account);this.doMsgSendReport(e,n,t);var c=a.antispamResult;return delete a.antispamResult,delete a.__clientExt,this.core.V2NIMChatroomService.emit("onSendMessage",a),Object.assign(Object.assign({message:a},c?{antispamResult:c}:{}),r?{clientAntispamResult:r}:{})}))}doMsgSendReport(e,t,r,o){t.apiCallingTime=this.core.timeOrigin.getNTPTime(e),t.sendTime=this.core.timeOrigin.getNTPTime();var i=this.core.timeOrigin.getNTPTime(),n=get(o,"detail.reason");this.core.reporter.report("msgSend",{clientId:r.messageClientId,msgTime:r.createTime,fromAccid:r.senderId,type:4,roomId:r.roomId,result:o?o.code:200,failReason:n||(null==o?void 0:o.message)||"",rt:i-t.apiCallingTime,apiCallingTime:t.apiCallingTime,sendTime:t.sendTime,attachUploadDuration:t.attachUploadDuration,apiCallbackTime:i})}doMsgReceiveReport(e,t){if(e.senderId!==this.core.account){var r=get(e,"__clientExt.statistics.apiCallingTime")||0,o=get(e,"__clientExt.statistics.sendTime")||0,i=get(e,"__clientExt.statistics.attachUploadDuration")||0,n=this.core.timeOrigin.getNTPTime(),s=e.createTime,a=this.core.timeOrigin.checkNodeReliable(t.__receiveTimeNode)?this.core.timeOrigin.getNTPTime(t.__receiveTimeNode):n;this.core.reporter.report("msgReceive",{clientId:e.messageClientId,receiveTime:a,serverTime:s,apiCallingTime:r,sendTime:o,attachUploadDuration:i,callbackTime:n,preHandleTime:n,fromAccid:e.senderId,type:4,roomId:e.roomId,result:200,failReason:"",rt:n-s})}}cacheMsg(e){this.msgs.push({messageClientId:e.messageClientId,senderId:e.senderId}),this.msgs.length>this.maxIdCount&&this.msgs.shift()}checkIfResend(e){return this.msgs.some((t=>t.messageClientId===e.messageClientId))}generateSendMessage(e){var t,r,o,{message:i,params:n,resend:s}=e,a={};(i.locationInfo||n.locationInfo)&&(a.x=(null===(t=i.locationInfo||n.locationInfo)||void 0===t?void 0:t.x)||0,a.y=(null===(r=i.locationInfo||n.locationInfo)||void 0===r?void 0:r.y)||0,a.z=(null===(o=i.locationInfo||n.locationInfo)||void 0===o?void 0:o.z)||0);var c=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},i),n),{messageConfig:Object.assign(Object.assign({},i.messageConfig),n.messageConfig),routeConfig:Object.assign(Object.assign({},i.routeConfig),n.routeConfig),antispamConfig:Object.assign(Object.assign({},i.antispamConfig),n.antispamConfig)}),i.attachment?{attachment:Object.assign({},i.attachment)}:{}),{locationInfo:a,resend:s,sendingState:3});return 0!==c.messageType&&10!==c.messageType||(c.attachment=c.text),c}checkIfAntispam(e,t){var r,o=t.text;if(e.clientAntispamEnabled&&100!==t.messageType&&t.text)if(1===(r=this.core.V2NIMClientAntispamUtil.checkTextAntispam(t.text||"",e.clientAntispamReplace)).operateType)o=r.replacedText;else if(2===r.operateType)throw this.core.V2NIMChatroomService.emit("onSendMessage",Object.assign(Object.assign({},t),{sendingState:2})),new V2NIMErrorImpl({code:_t.V2NIM_ERROR_CODE_CLIENT_ANTISPAM,detail:{reason:"sendMessage: text intercepted by client antispam"}});return{clientAntispamResult:r,text:o}}}var Pt=[2,7,12,100,6,1,-1,4,5,11,0,10,3],kt={message:{type:"object",rules:{messageClientId:{type:"string",allowEmpty:!1},senderId:{type:"string",allowEmpty:!1},roomId:{type:"string",allowEmpty:!1},text:{type:"string",required:!1},attachment:{type:"object",required:!1,rules:{file:{type:"file",required:!1}}}}}},wt={params:{type:"object",required:!1,rules:{messageConfig:{type:"object",required:!1,rules:{readReceiptEnabled:{type:"boolean",required:!1},lastMessageUpdateEnabled:{type:"boolean",required:!1},historyEnabled:{type:"boolean",required:!1},roamingEnabled:{type:"boolean",required:!1},onlineSyncEnabled:{type:"boolean",required:!1},offlineEnabled:{type:"boolean",required:!1},unreadEnabled:{type:"boolean",required:!1}}},routeConfig:{type:"object",required:!1,rules:{routeEnabled:{type:"boolean",required:!1},routeEnvironment:{type:"string",required:!1}}},antiSpamConfig:{type:"object",required:!1,rules:{antispamEnabled:{type:"boolean",required:!1},antispamBusinessId:{type:"string",required:!1},antispamCustomMessage:{type:"string",required:!1},antispamCheating:{type:"string",required:!1},antispamExtension:{type:"string",required:!1}}},receiverIds:{type:"array",required:!1},notifyTargetTags:{type:"string",required:!1},locationInfo:{type:"object",required:!1,rules:{x:{type:"number"},y:{type:"number"},z:{type:"number"}}}}}},Ut={sceneName:{type:"string",required:!1},name:{type:"string",required:!1}},xt=Object.assign(Object.assign({},Ut),{duration:{type:"number",required:!1}}),Gt=Object.assign(Object.assign({},xt),{width:{type:"number",required:!1},height:{type:"number",required:!1}}),Ft=Object.assign(Object.assign({},Ut),{width:{type:"number",required:!1},height:{type:"number",required:!1}}),Bt={option:{type:"object",rules:{direction:{type:"enum",values:[1,0],required:!1},messageTypes:{type:"array",required:!1,itemType:"enum",values:Pt},beginTime:{type:"number",min:0,required:!1},limit:{type:"number",min:1,required:!1}}}},Ht={messageOption:{type:"object",rules:{tags:{type:"array",min:1,itemType:"string"},direction:{type:"enum",values:[1,0],required:!1},messageTypes:{type:"array",required:!1,itemType:"enum",values:Pt},beginTime:{type:"number",min:0,required:!1},endTime:{type:"number",min:0,required:!1},limit:{type:"number",min:1,required:!1}}}},Yt="V2NIMChatroomMessageService",$t={"36_6":"v2ChatroomSendMessage","36_9":"v2ChatroomGetMessageList","36_35":"v2ChatroomMessageAck","36_36":"v2ChatroomGetMessageListByTag","13_7":"v2ChatroomOnMessage","29_17":"v2ChatroomDownloadLocalAntiSpamVocabs","6_23":"v2ChatroomGetServerTime","13_99":"v2ChatroomUpdateCDNInfo"},jt={version:1,md5:2,nosurl:3,thesaurus:4},Kt={messageClientId:1,messageType:{id:2,retType:"number"},attachment:{id:3,converter:(e,t)=>attachmentToRaw(t.messageType,e),retConverter:(e,t)=>rawToAttachment(e,Number(t[2]))},serverExtension:4,resend:{id:5,converter:boolToInt,retType:"boolean"},userInfoTimestamp:{id:6,access:"userInfoConfig.userInfoTimestamp",retType:"number"},senderNick:{id:7,access:"userInfoConfig.senderNick"},senderAvatar:{id:8,access:"userInfoConfig.senderAvatar"},senderExtension:{id:9,access:"userInfoConfig.senderExtension"},antispamCustomMessageEnabled:{id:10,def:e=>get(e,"antispamConfig.antispamCustomMessage")?1:void 0,retConverter:()=>{}},antispamCustomMessage:{id:11,access:"antispamConfig.antispamCustomMessage"},historyEnabled:{id:12,access:"messageConfig.historyEnabled",converter:e=>e?0:1,retConverter:e=>!parseInt(e)},text:13,antiSpamBusinessId:{id:14,access:"antispamConfig.antispamBusinessId"},clientAntispamHit:{id:15,access:"clientAntispamHit",converter:boolToInt,retType:"boolean"},antispamEnabled:{id:16,access:"antispamConfig.antispamEnabled",converter:boolToInt,retType:"boolean"},createTime:{id:20,retType:"number"},senderId:21,roomId:22,senderClientType:{id:23,retType:"number"},highPriority:{id:25,access:"messageConfig.highPriority",converter:boolToInt,retType:"boolean"},callbackExtension:27,subType:{id:28,retType:"number"},antispamCheating:{id:29,access:"antispamConfig.antispamCheating"},routeEnvironment:{id:30,access:"routeConfig.routeEnvironment"},notifyTargetTags:31,antispamExtension:{id:32,access:"antispamConfig.antispamExtension"},antispamResult:33,x:{id:34,access:"locationInfo.x",retType:"number"},y:{id:35,access:"locationInfo.y",retType:"number"},z:{id:36,access:"locationInfo.z",retType:"number"},receiverIds:{id:37,converter:objectToJSONString},__clientExt:{id:39,converter:objectToJSONString,retConverter:stringToJSONObject},routeEnabled:{id:100,access:"routeConfig.routeEnabled",converter:boolToInt,retType:"boolean",retDef:!0}},qt={v2ChatroomSendMessage:{sid:36,cid:6,service:Yt,params:[{type:"Property",name:"tag",reflectMapper:Kt}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Kt)}]},v2ChatroomOnMessage:{sid:13,cid:7,service:Yt,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Kt)}]},v2ChatroomGetMessageList:{sid:36,cid:9,service:Yt,params:[{type:"Long",name:"beginTime"},{type:"Int",name:"limit"},{type:"Bool",name:"reverse"},{type:"LongArray",name:"messageTypes"}],response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Kt)}]},v2ChatroomMessageAck:{sid:36,cid:35,service:Yt,params:[{type:"Property",name:"tag",reflectMapper:{messageClientId:1,roomId:2}}]},v2ChatroomGetMessageListByTag:{sid:36,cid:36,service:Yt,params:[{type:"Property",name:"tag",reflectMapper:{tags:1,messageTypes:2,beginTime:3,endTime:4,limit:5,reverse:6}}],response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Kt)}]},v2ChatroomDownloadLocalAntiSpamVocabs:{sid:29,cid:17,service:Yt,params:[{type:"Property",name:"tag",reflectMapper:jt}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(jt)}]},v2ChatroomGetServerTime:{sid:6,cid:23,service:Yt,response:[{type:"Long",name:"time"}]},v2ChatroomUpdateCDNInfo:{sid:13,cid:99,service:Yt,response:[{type:"Property",name:"chatroomCdnInfo",reflectMapper:invertSerializeItem(st)}]}},Wt=Wt||function(e){var t;"undefined"!=typeof window&&window.crypto&&(t=window.crypto),"undefined"!=typeof self&&self.crypto&&(t=self.crypto),"undefined"!=typeof globalThis&&globalThis.crypto&&(t=globalThis.crypto),!t&&"undefined"!=typeof window&&window.msCrypto&&(t=window.msCrypto),!t&&"undefined"!=typeof global&&global.crypto&&(t=global.crypto);var cryptoSecureRandomInt=function(){if(t){if("function"==typeof t.getRandomValues)try{return t.getRandomValues(new Uint32Array(1))[0]}catch(e){}if("function"==typeof t.randomBytes)try{return t.randomBytes(4).readInt32LE()}catch(e){}}throw new Error("Native crypto module could not be used to get secure random number.")},r=Object.create||function(){function F(){}return function(e){var t;return F.prototype=e,t=new F,F.prototype=null,t}}(),o={},i=o.lib={},n=i.Base={extend:function(e){var t=r(this);return e&&t.mixIn(e),t.hasOwnProperty("init")&&this.init!==t.init||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},s=i.WordArray=n.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||c).stringify(this)},concat:function(e){var t=this.words,r=e.words,o=this.sigBytes,i=e.sigBytes;if(this.clamp(),o%4)for(var n=0;n<i;n++){var s=r[n>>>2]>>>24-n%4*8&255;t[o+n>>>2]|=s<<24-(o+n)%4*8}else for(var a=0;a<i;a+=4)t[o+a>>>2]=r[a>>>2];return this.sigBytes+=i,this},clamp:function(){var t=this.words,r=this.sigBytes;t[r>>>2]&=4294967295<<32-r%4*8,t.length=e.ceil(r/4)},clone:function(){var e=n.clone.call(this);return e.words=this.words.slice(0),e},random:function(e){for(var t=[],r=0;r<e;r+=4)t.push(cryptoSecureRandomInt());return new s.init(t,e)}}),a=o.enc={},c=a.Hex={stringify:function(e){for(var t=e.words,r=e.sigBytes,o=[],i=0;i<r;i++){var n=t[i>>>2]>>>24-i%4*8&255;o.push((n>>>4).toString(16)),o.push((15&n).toString(16))}return o.join("")},parse:function(e){for(var t=e.length,r=[],o=0;o<t;o+=2)r[o>>>3]|=parseInt(e.substr(o,2),16)<<24-o%8*4;return new s.init(r,t/2)}},l=a.Latin1={stringify:function(e){for(var t=e.words,r=e.sigBytes,o=[],i=0;i<r;i++){var n=t[i>>>2]>>>24-i%4*8&255;o.push(String.fromCharCode(n))}return o.join("")},parse:function(e){for(var t=e.length,r=[],o=0;o<t;o++)r[o>>>2]|=(255&e.charCodeAt(o))<<24-o%4*8;return new s.init(r,t)}},_=a.Utf8={stringify:function(e){try{return decodeURIComponent(escape(l.stringify(e)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(e){return l.parse(unescape(encodeURIComponent(e)))}},d=i.BufferedBlockAlgorithm=n.extend({reset:function(){this._data=new s.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=_.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var r,o=this._data,i=o.words,n=o.sigBytes,a=this.blockSize,c=n/(4*a),l=(c=t?e.ceil(c):e.max((0|c)-this._minBufferSize,0))*a,_=e.min(4*l,n);if(l){for(var d=0;d<l;d+=a)this._doProcessBlock(i,d);r=i.splice(0,l),o.sigBytes-=_}return new s.init(r,_)},clone:function(){var e=n.clone.call(this);return e._data=this._data.clone(),e},_minBufferSize:0});i.Hasher=d.extend({cfg:n.extend(),init:function(e){this.cfg=this.cfg.extend(e),this.reset()},reset:function(){d.reset.call(this),this._doReset()},update:function(e){return this._append(e),this._process(),this},finalize:function(e){return e&&this._append(e),this._doFinalize()},blockSize:16,_createHelper:function(e){return function(t,r){return new e.init(r).finalize(t)}},_createHmacHelper:function(e){return function(t,r){return new E.HMAC.init(e,r).finalize(t)}}});var E=o.algo={};return o}(Math),zt=Wt,Jt=zt.lib,Qt=Jt.Base,Xt=Jt.WordArray,Zt=zt.algo,er=Zt.MD5,tr=Zt.EvpKDF=Qt.extend({cfg:Qt.extend({keySize:4,hasher:er,iterations:1}),init:function(e){this.cfg=this.cfg.extend(e)},compute:function(e,t){for(var r,o=this.cfg,i=o.hasher.create(),n=Xt.create(),s=n.words,a=o.keySize,c=o.iterations;s.length<a;){r&&i.update(r),r=i.update(e).finalize(t),i.reset();for(var l=1;l<c;l++)r=i.finalize(r),i.reset();n.concat(r)}return n.sigBytes=4*a,n}});zt.EvpKDF=function(e,t,r){return tr.create(r).compute(e,t)},Wt.EvpKDF;var rr=Wt,or=rr.lib.WordArray;rr.enc.Base64={stringify:function(e){var t=e.words,r=e.sigBytes,o=this._map;e.clamp();for(var i=[],n=0;n<r;n+=3)for(var s=(t[n>>>2]>>>24-n%4*8&255)<<16|(t[n+1>>>2]>>>24-(n+1)%4*8&255)<<8|t[n+2>>>2]>>>24-(n+2)%4*8&255,a=0;a<4&&n+.75*a<r;a++)i.push(o.charAt(s>>>6*(3-a)&63));var c=o.charAt(64);if(c)for(;i.length%4;)i.push(c);return i.join("")},parse:function(e){var t=e.length,r=this._map,o=this._reverseMap;if(!o){o=this._reverseMap=[];for(var i=0;i<r.length;i++)o[r.charCodeAt(i)]=i}var n=r.charAt(64);if(n){var s=e.indexOf(n);-1!==s&&(t=s)}return function parseLoop(e,t,r){for(var o=[],i=0,n=0;n<t;n++)if(n%4){var s=r[e.charCodeAt(n-1)]<<n%4*2|r[e.charCodeAt(n)]>>>6-n%4*2;o[i>>>2]|=s<<24-i%4*8,i++}return or.create(o,i)}(e,t,o)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="};var ir=Wt.enc.Base64;!function(e){e.lib.Cipher||function(){var t=e,r=t.lib,o=r.Base,i=r.WordArray,n=r.BufferedBlockAlgorithm,s=t.enc;s.Utf8;var a=s.Base64,c=t.algo.EvpKDF,l=r.Cipher=n.extend({cfg:o.extend(),createEncryptor:function(e,t){return this.create(this._ENC_XFORM_MODE,e,t)},createDecryptor:function(e,t){return this.create(this._DEC_XFORM_MODE,e,t)},init:function(e,t,r){this.cfg=this.cfg.extend(r),this._xformMode=e,this._key=t,this.reset()},reset:function(){n.reset.call(this),this._doReset()},process:function(e){return this._append(e),this._process()},finalize:function(e){return e&&this._append(e),this._doFinalize()},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(){function selectCipherStrategy(e){return"string"==typeof e?I:g}return function(e){return{encrypt:function(t,r,o){return selectCipherStrategy(r).encrypt(e,t,r,o)},decrypt:function(t,r,o){return selectCipherStrategy(r).decrypt(e,t,r,o)}}}}()});r.StreamCipher=l.extend({_doFinalize:function(){return this._process(!0)},blockSize:1});var _=t.mode={},d=r.BlockCipherMode=o.extend({createEncryptor:function(e,t){return this.Encryptor.create(e,t)},createDecryptor:function(e,t){return this.Decryptor.create(e,t)},init:function(e,t){this._cipher=e,this._iv=t}}),E=_.CBC=function(){var e=d.extend();function xorBlock(e,t,r){var o,i=this._iv;i?(o=i,this._iv=void 0):o=this._prevBlock;for(var n=0;n<r;n++)e[t+n]^=o[n]}return e.Encryptor=e.extend({processBlock:function(e,t){var r=this._cipher,o=r.blockSize;xorBlock.call(this,e,t,o),r.encryptBlock(e,t),this._prevBlock=e.slice(t,t+o)}}),e.Decryptor=e.extend({processBlock:function(e,t){var r=this._cipher,o=r.blockSize,i=e.slice(t,t+o);r.decryptBlock(e,t),xorBlock.call(this,e,t,o),this._prevBlock=i}}),e}(),h=(t.pad={}).Pkcs7={pad:function(e,t){for(var r=4*t,o=r-e.sigBytes%r,n=o<<24|o<<16|o<<8|o,s=[],a=0;a<o;a+=4)s.push(n);var c=i.create(s,o);e.concat(c)},unpad:function(e){var t=255&e.words[e.sigBytes-1>>>2];e.sigBytes-=t}};r.BlockCipher=l.extend({cfg:l.cfg.extend({mode:E,padding:h}),reset:function(){var e;l.reset.call(this);var t=this.cfg,r=t.iv,o=t.mode;this._xformMode==this._ENC_XFORM_MODE?e=o.createEncryptor:(e=o.createDecryptor,this._minBufferSize=1),this._mode&&this._mode.__creator==e?this._mode.init(this,r&&r.words):(this._mode=e.call(o,this,r&&r.words),this._mode.__creator=e)},_doProcessBlock:function(e,t){this._mode.processBlock(e,t)},_doFinalize:function(){var e,t=this.cfg.padding;return this._xformMode==this._ENC_XFORM_MODE?(t.pad(this._data,this.blockSize),e=this._process(!0)):(e=this._process(!0),t.unpad(e)),e},blockSize:4});var u=r.CipherParams=o.extend({init:function(e){this.mixIn(e)},toString:function(e){return(e||this.formatter).stringify(this)}}),m=(t.format={}).OpenSSL={stringify:function(e){var t=e.ciphertext,r=e.salt;return(r?i.create([1398893684,1701076831]).concat(r).concat(t):t).toString(a)},parse:function(e){var t,r=a.parse(e),o=r.words;return 1398893684==o[0]&&1701076831==o[1]&&(t=i.create(o.slice(2,4)),o.splice(0,4),r.sigBytes-=16),u.create({ciphertext:r,salt:t})}},g=r.SerializableCipher=o.extend({cfg:o.extend({format:m}),encrypt:function(e,t,r,o){o=this.cfg.extend(o);var i=e.createEncryptor(r,o),n=i.finalize(t),s=i.cfg;return u.create({ciphertext:n,key:r,iv:s.iv,algorithm:e,mode:s.mode,padding:s.padding,blockSize:e.blockSize,formatter:o.format})},decrypt:function(e,t,r,o){return o=this.cfg.extend(o),t=this._parse(t,o.format),e.createDecryptor(r,o).finalize(t.ciphertext)},_parse:function(e,t){return"string"==typeof e?t.parse(e,this):e}}),p=(t.kdf={}).OpenSSL={execute:function(e,t,r,o){o||(o=i.random(8));var n=c.create({keySize:t+r}).compute(e,o),s=i.create(n.words.slice(t),4*r);return n.sigBytes=4*t,u.create({key:n,iv:s,salt:o})}},I=r.PasswordBasedCipher=g.extend({cfg:g.cfg.extend({kdf:p}),encrypt:function(e,t,r,o){var i=(o=this.cfg.extend(o)).kdf.execute(r,e.keySize,e.ivSize);o.iv=i.iv;var n=g.encrypt.call(this,e,t,i.key,o);return n.mixIn(i),n},decrypt:function(e,t,r,o){o=this.cfg.extend(o),t=this._parse(t,o.format);var i=o.kdf.execute(r,e.keySize,e.ivSize,t.salt);return o.iv=i.iv,g.decrypt.call(this,e,t,i.key,o)}})}()}(Wt);var nr=Wt,sr=nr.lib.BlockCipher,ar=nr.algo,cr=[],lr=[],_r=[],dr=[],Er=[],hr=[],ur=[],mr=[],gr=[],pr=[];!function(){for(var e=[],t=0;t<256;t++)e[t]=t<128?t<<1:t<<1^283;var r=0,o=0;for(t=0;t<256;t++){var i=o^o<<1^o<<2^o<<3^o<<4;i=i>>>8^255&i^99,cr[r]=i,lr[i]=r;var n=e[r],s=e[n],a=e[s],c=257*e[i]^16843008*i;_r[r]=c<<24|c>>>8,dr[r]=c<<16|c>>>16,Er[r]=c<<8|c>>>24,hr[r]=c;c=16843009*a^65537*s^257*n^16843008*r;ur[i]=c<<24|c>>>8,mr[i]=c<<16|c>>>16,gr[i]=c<<8|c>>>24,pr[i]=c,r?(r=n^e[e[e[a^n]]],o^=e[e[o]]):r=o=1}}();var Ir=[0,1,2,4,8,16,32,64,128,27,54],Nr=ar.AES=sr.extend({_doReset:function(){if(!this._nRounds||this._keyPriorReset!==this._key){for(var e=this._keyPriorReset=this._key,t=e.words,r=e.sigBytes/4,o=4*((this._nRounds=r+6)+1),i=this._keySchedule=[],n=0;n<o;n++)n<r?i[n]=t[n]:(c=i[n-1],n%r?r>6&&n%r==4&&(c=cr[c>>>24]<<24|cr[c>>>16&255]<<16|cr[c>>>8&255]<<8|cr[255&c]):(c=cr[(c=c<<8|c>>>24)>>>24]<<24|cr[c>>>16&255]<<16|cr[c>>>8&255]<<8|cr[255&c],c^=Ir[n/r|0]<<24),i[n]=i[n-r]^c);for(var s=this._invKeySchedule=[],a=0;a<o;a++){n=o-a;if(a%4)var c=i[n];else c=i[n-4];s[a]=a<4||n<=4?c:ur[cr[c>>>24]]^mr[cr[c>>>16&255]]^gr[cr[c>>>8&255]]^pr[cr[255&c]]}}},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._keySchedule,_r,dr,Er,hr,cr)},decryptBlock:function(e,t){var r=e[t+1];e[t+1]=e[t+3],e[t+3]=r,this._doCryptBlock(e,t,this._invKeySchedule,ur,mr,gr,pr,lr);r=e[t+1];e[t+1]=e[t+3],e[t+3]=r},_doCryptBlock:function(e,t,r,o,i,n,s,a){for(var c=this._nRounds,l=e[t]^r[0],_=e[t+1]^r[1],d=e[t+2]^r[2],E=e[t+3]^r[3],h=4,u=1;u<c;u++){var m=o[l>>>24]^i[_>>>16&255]^n[d>>>8&255]^s[255&E]^r[h++],g=o[_>>>24]^i[d>>>16&255]^n[E>>>8&255]^s[255&l]^r[h++],p=o[d>>>24]^i[E>>>16&255]^n[l>>>8&255]^s[255&_]^r[h++],I=o[E>>>24]^i[l>>>16&255]^n[_>>>8&255]^s[255&d]^r[h++];l=m,_=g,d=p,E=I}m=(a[l>>>24]<<24|a[_>>>16&255]<<16|a[d>>>8&255]<<8|a[255&E])^r[h++],g=(a[_>>>24]<<24|a[d>>>16&255]<<16|a[E>>>8&255]<<8|a[255&l])^r[h++],p=(a[d>>>24]<<24|a[E>>>16&255]<<16|a[l>>>8&255]<<8|a[255&_])^r[h++],I=(a[E>>>24]<<24|a[l>>>16&255]<<16|a[_>>>8&255]<<8|a[255&d])^r[h++];e[t]=m,e[t+1]=g,e[t+2]=p,e[t+3]=I},keySize:8});nr.AES=sr._createHelper(Nr);var Tr,Or=Wt.AES;Wt.mode.ECB=((Tr=Wt.lib.BlockCipherMode.extend()).Encryptor=Tr.extend({processBlock:function(e,t){this._cipher.encryptBlock(e,t)}}),Tr.Decryptor=Tr.extend({processBlock:function(e,t){this._cipher.decryptBlock(e,t)}}),Tr);var Mr=Wt.mode.ECB,fr=Wt.enc.Utf8,Sr=Wt.pad.Pkcs7;var Rr={enabled:!1,cdnUrls:[],timestamp:Date.now(),pollingIntervalSeconds:5,pollingTimeoutMillis:1e3},Cr=invertSerializeItem(Kt);class CDNUtil{constructor(e,t){this.config=Rr,this.lastSuccessTimestamp=0,this.pollingTimer=0,this.msgBufferInterval=300,this.emitTimer=0,this.core=e,this.service=t,this.promiseManager=new PromiseManager}reset(){this.config=Rr,this.lastSuccessTimestamp=0,this.pollingTimer&&clearInterval(this.pollingTimer),this.pollingTimer=0,this.emitTimer&&clearInterval(this.emitTimer),this.emitTimer=0}setOptions(e){this.config=Object.assign({},this.config,e),this.core.logger.log("CDNUtil::setOptions",this.config),this.polling()}polling(){this.pollingTimer&&clearInterval(this.pollingTimer),this.pollingTimer=0,this.config.enabled&&(this.pollingTimer=setInterval(this.fetchMsgs.bind(this),1e3*this.config.pollingIntervalSeconds))}fetchMsgs(e=0){return __awaiter(this,void 0,void 0,(function*(){var t=this.config.cdnUrls;if(t&&t.length>0){var r=t.shift();if(r){this.config.cdnUrls.push(r);var o=this.core.timeOrigin.getNTPTime();if(o-=o%(1e3*this.config.pollingIntervalSeconds),this.lastSuccessTimestamp!==o){r=r.replace("#time",`${o}`);var i=this.config.pollingTimeoutMillis||1e3*this.config.pollingIntervalSeconds/2;this.core.logger.log("CDNUtil::fetchMsgs start:",r);var n={};try{n=yield this.promiseManager.add(this.core.adapters.request(r,{method:"GET",dataType:"json",timeout:i},{exception_service:8}))}catch(t){this.core.logger.warn("CDNUtil::fetchMsgs failed:",t);var s=t;if(s.code===_t.V2NIM_ERROR_CODE_CANCELLED)return;if(e>=3)return;return 404===s.code&&this.core.timeOrigin.setOriginTimetick(),this.fetchMsgs(e+1)}this.requestSuccess(n,o)}}}}))}requestSuccess(e,t){if(this.lastSuccessTimestamp>t)return this.core.logger.warn("CDNUtil::fetchMsgs:ignore",this.lastSuccessTimestamp,t),void(this.lastSuccessTimestamp=0);this.lastSuccessTimestamp=t;var r=get(e,"data.data");if(r){if(e.data.ptm&&(this.config.pollingTimeoutMillis=e.data.ptm),e.data.pis){var o=this.config.pollingIntervalSeconds;this.config.pollingIntervalSeconds=e.data.pis,e.data.pis!==o&&this.polling()}var i=!0===e.data.e?this.decryptAES(r,this.config.decryptKey):r,n=this.formatMessages(i);n=function uniqBy(e,t){e=e||[],t=t||"";for(var r=[],o=[],i=0;i<e.length;i++){var n=e[i][t];-1===o.indexOf(n)&&(o.push(n),r.push(e[i]))}return r}(n,"messageClientId"),n=n.filter((e=>!this.service.sendUtil.checkIfResend(e)&&(this.service.sendUtil.cacheMsg(e),!0))),this.core.logger.log(`CDNUtil::fetchMsgs success at ${t}, msg.length: ${n.length}`),this.emitSmoothly(n,1e3*e.data.c)}}decryptAES(e,t){if(!e||!t)return"[]";try{return Or.decrypt(e,ir.parse(t),{mode:Mr,padding:Sr}).toString(fr)}catch(e){var r=e;throw new V2NIMErrorImpl({code:_t.V2NIM_ERROR_CODE_INTERNAL,detail:{reason:"Decrypt AES failed",rawError:r}})}}formatMessages(e){var t=[];try{t=JSON.parse(e)}catch(t){var r=t;throw new V2NIMErrorImpl({code:_t.V2NIM_ERROR_CODE_INTERNAL,detail:{reason:"JSON parse error",rawData:e,rawError:r}})}return t.map((e=>formatMessage(this.core,deserialize(e,Cr),this.core.account)))}emitSmoothly(e,t){if(e&&e.length>0){var r=Math.ceil(t/this.msgBufferInterval),o=Math.ceil(e.length*this.msgBufferInterval/t);this.core.logger.log(`CDNUtil::emitSmoothly total length: ${e.length}, group length: ${o}, times: ${r}`),this.emitTimer&&clearInterval(this.emitTimer),this.emitTimer=0,this.emitTimer=setInterval((()=>{var t=e.splice(0,o);if(0===t.length)return this.emitTimer&&clearInterval(this.emitTimer),void(this.emitTimer=0);this.core.V2NIMChatroomService.emit("onReceiveMessages",t)}),this.msgBufferInterval)}}}class V2NIMChatroomMessageServiceImpl extends Service{constructor(e){super("V2NIMChatroomMessageService",e),this.customAttachmentParsers=[],registerParser({cmdMap:$t,cmdConfig:qt}),this.fileUtil=new FileUtil(this.core,this),this.sendUtil=new SendUtil(this.core,this),this.cdnUtil=new CDNUtil(this.core,this),this.setListener()}reset(e){this.sendUtil.reset(),this.cdnUtil.reset(),this.core.V2NIMClientAntispamUtil.reset(e)}setListener(){this.core.eventBus.on("V2NIMLoginService/loginLifeCycleLoginSucc",(()=>{this.core.timeOrigin.setOriginTimetick()})),this.core.eventBus.on("V2NIMChatroomMessageService/onReceiveNotification",((e,t)=>{16===get(e,"attachment.type")&&this.core.V2NIMChatroomService.emit("onMessageRevokedNotification",t.data.msgId,t.data.msgTime)}))}getMessageList(e){return __awaiter(this,void 0,void 0,(function*(){validate(Bt,{option:e},"",!0);var t=(yield this.core.clientSocket.sendCmd("v2ChatroomGetMessageList",Object.assign(Object.assign({beginTime:0,limit:100},e),{reverse:1===e.direction}))).content.datas;return t.map((e=>formatMessage(this.core,e,this.core.account))),t}))}getMessageListByTag(e){return __awaiter(this,void 0,void 0,(function*(){if(validate(Ht,{messageOption:e},"",!0),"number"==typeof(null==e?void 0:e.beginTime)&&"number"==typeof(null==e?void 0:e.endTime)&&e.beginTime>e.endTime)throw new V2NIMErrorImpl({code:_t.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"beginTime must be less than endTime"}});var t=(yield this.core.clientSocket.sendCmd("v2ChatroomGetMessageListByTag",{tag:Object.assign(Object.assign({},e),{tags:JSON.stringify(e.tags),messageType:e.messageTypes?JSON.stringify(e.messageTypes):void 0,reverse:1===e.direction?0:1})})).content.datas;return t.map((e=>formatMessage(this.core,e,this.core.account))),t}))}sendMessage(e,t={},r){return __awaiter(this,void 0,void 0,(function*(){if(validate(kt,{message:e},"",!0),validate(wt,{params:t},"",!0),e.senderId!==this.core.account)throw new V2NIMErrorImpl({code:_t.V2NIM_ERROR_CODE_MISUSE,detail:{reason:"message.senderId must be self"}});var o=this.core.timeOrigin.getTimeNode(),{messageBeforeSend:i,clientAntispamResult:n}=this.sendUtil.prepareMessage(e,t);return yield this.sendUtil.doSendMessage(o,i,n,r)}))}registerCustomAttachmentParser(e){"function"==typeof e&&-1===this.customAttachmentParsers.indexOf(e)&&this.customAttachmentParsers.unshift(e)}unregisterCustomAttachmentParser(e){var t=this.customAttachmentParsers.indexOf(e);t>-1&&this.customAttachmentParsers.splice(t,1)}v2ChatroomMessageAck(e,t){this.core.clientSocket.sendCmd("v2ChatroomMessageAck",{tag:{messageClientId:e,roomId:t}})}v2ChatroomOnMessageHandler(e){var t=e.content.data,r=t.attachment,o=formatMessage(this.core,t,this.core.account);this.sendUtil.checkIfResend(o)||(5===t.messageType?this.core.eventBus.emit("V2NIMChatroomMessageService/onReceiveNotification",o,r):this.sendUtil.cacheMsg(o),this.sendUtil.doMsgReceiveReport(o,e),delete o.__clientExt,this.core.V2NIMChatroomService.emit("onReceiveMessages",[o]))}v2ChatroomUpdateCDNInfoHandler(e){var t=e.content.chatroomCdnInfo;this.cdnUtil.setOptions(t)}}class V2NIMChatroomMessageCreatorImpl{constructor(e){this.name="V2NIMChatroomMessageCreator",this.defaultNosSceneName="nim_default_im",this.core=e}createMessage(e,t){return Object.assign(Object.assign(Object.assign({messageClientId:ve(),createTime:this.core.timeOrigin.getNTPTime(),senderId:this.core.auth.getLoginUser(),roomId:this.core.auth.getRoomId(),isSelf:!0,sendingState:0,messageType:e,senderClientType:16},t),t.attachment?{attachment:Object.assign(Object.assign({},t.attachment),{raw:attachmentToRaw(e,t.attachment)})}:{}),{messageConfig:Object.assign({historyEnabled:!0,highPriority:!1},t.messageConfig),routeConfig:Object.assign({routeEnabled:!0},t.routeConfig),antispamConfig:Object.assign({antispamEnabled:!0},t.antispamConfig)})}createTextMessage(e){return validate({text:{type:"string",allowEmpty:!1}},{text:e},"",!0),this.createMessage(0,{text:e})}createImageMessage(e,t,r,o,i){validate(Ft,{name:t,sceneName:r,width:o,height:i},"",!0);var n=this.createGenericFileMessageAttachment(e,t,r,void 0,o,i,"jpeg");return this.createMessage(1,{attachment:n,attachmentUploadState:0})}createAudioMessage(e,t,r,o){validate(xt,{name:t,sceneName:r,duration:o},"",!0);var i=this.createGenericFileMessageAttachment(e,t,r,o,void 0,void 0,"aac");return this.createMessage(2,{attachment:i,attachmentUploadState:0})}createVideoMessage(e,t,r,o,i,n){validate(Gt,{name:t,sceneName:r,duration:o,width:i,height:n},"",!0);var s=this.createGenericFileMessageAttachment(e,t,r,o,i,n,"mp4");return this.createMessage(3,{attachment:s,attachmentUploadState:0})}createFileMessage(e,t,r){validate(Ut,{name:t,sceneName:r},"",!0);var o=this.createGenericFileMessageAttachment(e,t,r,void 0,void 0,void 0,"txt");return this.createMessage(6,{attachment:o,attachmentUploadState:0})}createGenericFileMessageAttachment(e,t,r,o,i,n,s){if(r=r||this.defaultNosSceneName,!this.core.V2NIMStorageService.hasStorageScene(r))throw new V2NIMErrorImpl({code:_t.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"sceneName: "+r+" has not been added"}});var{file:a,path:c}=getFileOrPath(e),l=Object.assign(Object.assign(Object.assign({name:t,uploadState:0,sceneName:r||this.defaultNosSceneName},o?{duration:o}:{}),i?{width:i}:{}),n?{height:n}:{});if(a){var _=a.name.lastIndexOf("."),d=-1===_?a.name:a.name.substring(0,_);l.name=l.name||d,l.size=a.size,l.ext=`.${getFileExtension(a.name)||getFileExtension(t||"")||s}`}else if(c){var E=c.lastIndexOf("/"),h=c.lastIndexOf("."),u=-1===h?c.substring(E+1):c.substring(E+1,h);l.name=l.name||u,l.ext=`.${getFileExtension(c)||getFileExtension(t||"")||s}`}return l=JSON.parse(JSON.stringify(l)),c?l.path=c:a&&(l.file=a),l}createLocationMessage(e,t,r){return validate({latitude:{type:"number",allowEmpty:!1},longitude:{type:"number",allowEmpty:!1},address:{type:"string",allowEmpty:!1}},{latitude:e,longitude:t,address:r},"",!0),this.createMessage(4,{attachment:{latitude:e,longitude:t,address:r}})}createCustomMessage(e){return validate({rawAttachment:{type:"string"}},{rawAttachment:e},"",!0),this.createMessage(100,{attachment:{raw:e}})}createCustomMessageWithAttachment(e,t){return validate({raw:{type:"string"}},e,"attachment",!0),validate({subType:{type:"number",min:0,required:!1}},{subType:t},"",!0),this.createMessage(100,t?{attachment:e,subType:t}:{attachment:e})}createForwardMessage(e){if([11,5,7,10].includes(e.messageType))return null;var t={messageClientId:ve(),messageType:e.messageType};return e.text&&(t.text=e.text),e.attachment&&(t.attachment=e.attachment),e.attachment&&"uploadState"in e.attachment&&(t.attachmentUploadState=e.attachment.uploadState),this.createMessage(e.messageType,t)}createTipsMessage(e){return validate({text:{type:"string",allowEmpty:!1}},{text:e},"",!0),this.createMessage(10,{text:e})}}var Ar={option:{type:"object",rules:{memberRoles:{type:"array",itemType:"enum",values:[4,1,2,0,3,5],required:!1},onlyBlocked:{type:"boolean",required:!1},onlyChatBanned:{type:"boolean",required:!1},onlyOnline:{type:"boolean",required:!1},pageToken:{type:"string",required:!1},limit:{type:"number",min:1,required:!1}}}},vr={accountId:{type:"string",allowEmpty:!1},updateParams:{type:"object",rules:{memberRole:{type:"enum",values:[2,0,3]},memberLevel:{type:"number",min:0,required:!1},notificationExtension:{type:"string",required:!1}}}},yr={accountId:{type:"string",allowEmpty:!1},blocked:{type:"boolean"},notificationExtension:{type:"string",required:!1}},Dr={accountId:{type:"string",allowEmpty:!1},chatBanned:{type:"boolean"},notificationExtension:{type:"string",required:!1}},Vr={updateParams:{type:"object",rules:{roomNick:{type:"string",allowEmpty:!1,required:!1},roomAvatar:{type:"string",required:!1},serverExtension:{type:"string",required:!1},notificationEnabled:{type:"boolean",required:!1},notificationExtension:{type:"string",required:!1},persistence:{type:"boolean",required:!1}}},antispamConfig:{type:"object",required:!1,rules:{antispamBusinessId:{type:"string",required:!1}}}},Lr={accountId:{type:"string",allowEmpty:!1},tempChatBannedDuration:{type:"number",min:0},notificationEnabled:{type:"boolean"},notificationExtension:{type:"string",required:!1}},br={option:{type:"object",rules:{tag:{type:"string",allowEmpty:!1},pageToken:{type:"string",required:!1},limit:{type:"number",min:1,required:!1}}}};class V2NIMChatroomMemberServiceImpl extends Service{constructor(e){super("V2NIMChatroomMemberService",e),registerParser({cmdMap:Xe,cmdConfig:rt})}getMemberListByOption(e){return __awaiter(this,void 0,void 0,(function*(){validate(Ar,{option:e},"",!0);var t=yield this.core.clientSocket.sendCmd("v2ChatroomGetMemberListByOption",{tag:e});return{finished:!t.content.hasMore,pageToken:t.content.pageToken,memberList:t.content.datas}}))}updateMemberRole(e,t){return __awaiter(this,void 0,void 0,(function*(){validate(vr,{accountId:e,updateParams:t},"",!0),yield this.core.sendCmd("v2ChatroomUpdateMemberRole",{tag:Object.assign(Object.assign({notificationExtension:""},t),{accountId:e})})}))}setMemberBlockedStatus(e,t,r){return __awaiter(this,void 0,void 0,(function*(){var o={accountId:e,blocked:t,notificationExtension:r};validate(yr,o,"",!0),yield this.core.sendCmd("v2ChatroomSetMemberBlockedStatus",o)}))}setMemberChatBannedStatus(e,t,r){return __awaiter(this,void 0,void 0,(function*(){var o={accountId:e,chatBanned:t,notificationExtension:r};validate(Dr,o,"",!0),yield this.core.sendCmd("v2ChatroomSetMemberChatBannedStatus",o)}))}setMemberTempChatBanned(e,t,r,o){return __awaiter(this,void 0,void 0,(function*(){var i={accountId:e,tempChatBannedDuration:t,notificationEnabled:r,notificationExtension:o};validate(Lr,i,"",!0),i.notificationExtension=i.notificationExtension||"",yield this.core.sendCmd("v2ChatroomSetMemberTempChatBanned",i)}))}updateSelfMemberInfo(e,t){return __awaiter(this,void 0,void 0,(function*(){if(validate(Vr,{updateParams:e,antispamConfig:t},"",!0),void 0===e.roomAvatar&&void 0===e.roomNick&&void 0===e.serverExtension)throw new V2NIMErrorImpl({code:_t.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"updateSelfMemberInfo: nothing to update"}});yield this.core.clientSocket.sendCmd("v2ChatroomUpdateSelfMemberInfo",{tag:e,notificationEnabled:"boolean"!=typeof e.notificationEnabled||e.notificationEnabled,notificationExtension:e.notificationExtension||"",persistence:"boolean"==typeof e.persistence&&e.persistence,antispamConfig:t})}))}getMemberByIds(e){return __awaiter(this,void 0,void 0,(function*(){return validate({accountIds:{type:"array",itemType:"string",min:1}},{accountIds:e},"",!0),(yield this.core.clientSocket.sendCmd("v2ChatroomGetMemberByIds",{accountIds:e})).content.datas}))}kickMember(e,t){return __awaiter(this,void 0,void 0,(function*(){validate({accountId:{type:"string",allowEmpty:!1}},{accountId:e},"",!0),validate({notificationExtension:{type:"string",required:!1}},{notificationExtension:t},"",!0),yield this.core.clientSocket.sendCmd("v2ChatroomKickMember",{accountId:e,notificationExtension:t})}))}getMemberListByTag(e){return __awaiter(this,void 0,void 0,(function*(){validate(br,{option:e},"",!0);var t=yield this.core.clientSocket.sendCmd("v2ChatroomGetMemberListByTag",{tag:Object.assign({limit:100},e)});return{finished:!t.content.hasMore,pageToken:t.content.pageToken,memberList:t.content.datas}}))}getMemberCountByTag(e){return __awaiter(this,void 0,void 0,(function*(){return validate({tag:{type:"string",allowEmpty:!1}},{tag:e},"",!0),(yield this.core.clientSocket.sendCmd("v2ChatroomGetMemberCountByTag",{tag:e})).content.data}))}v2ChatroomOnMemberTagUpdatedHandler(e){var t;if(null===(t=e.content.data)||void 0===t?void 0:t.tag){var r=JSON.parse(e.content.data.tag);this.core.V2NIMChatroomService.emit("onChatroomTagsUpdated",r)}}}class V2NIMChatroomServiceEventImpl{constructor(e,t){this.core=e,this.service=t,this.logger=this.core.logger}setListener(){this.core.eventBus.on("V2NIMChatroomMessageService/onReceiveNotification",this.onReceiveNotification.bind(this))}onReceiveNotification(e,t){return __awaiter(this,void 0,void 0,(function*(){var r=e.attachment;switch(get(e,"attachment.type")){case 0:var o=e.attachment.currentMember;o&&this.service.emit("onChatroomMemberEnter",o),r.operatorId!==this.core.account&&this.core.V2NIMChatroomInfoService.model.chatroomInfo&&this.core.V2NIMChatroomInfoService.model.chatroomInfo.onlineUserCount++;break;case 7:if(Array.isArray(r.targetIds))for(var i=0;i<r.targetIds.length;i++)this.service.emit("onChatroomMemberExit",r.targetIds[i]);break;case 1:this.service.emit("onChatroomMemberExit",r.operatorId),r.operatorId!==this.core.account&&this.core.V2NIMChatroomInfoService.model.chatroomInfo&&this.core.V2NIMChatroomInfoService.model.chatroomInfo.onlineUserCount--;break;case 3:break;case 4:r.targetIds&&r.targetIds.includes(this.core.account)&&this.service.emit("onSelfChatBannedUpdated",!0);break;case 5:r.targetIds&&r.targetIds.includes(this.core.account)&&this.service.emit("onSelfChatBannedUpdated",!1);break;case 18:"currentMember"in r&&"previousRole"in r&&this.service.emit("onChatroomMemberRoleUpdated",r.previousRole,r.currentMember);break;case 8:if(e.attachment.targetIds.includes(this.core.account)){var n=t.data.muteDuration;this.service.emit("onSelfTempChatBannedUpdated",!0,n)}break;case 14:if(this.core.tags.includes(t.data.targetTag)){var s=t.data.muteDuration;this.service.emit("onSelfTempChatBannedUpdated",!0,s)}break;case 9:e.attachment.targetIds.includes(this.core.account)&&this.service.emit("onSelfTempChatBannedUpdated",!1,0);break;case 15:this.service.emit("onSelfTempChatBannedUpdated",!1,0);break;case 12:this.service.emit("onChatroomChatBannedUpdated",!0),this.core.V2NIMChatroomInfoService.model.chatroomInfo&&(this.core.V2NIMChatroomInfoService.model.chatroomInfo.chatBanned=!0);break;case 13:this.service.emit("onChatroomChatBannedUpdated",!1),this.core.V2NIMChatroomInfoService.model.chatroomInfo&&(this.core.V2NIMChatroomInfoService.model.chatroomInfo.chatBanned=!1);break;case 17:this.core.options.tags=t.data.tags||[],this.service.emit("onChatroomTagsUpdated",t.data.tags);break;case 10:var a=e.attachment.currentMember;a.memberLevel=a.memberLevel||0,this.service.emit("onChatroomMemberInfoUpdated",a)}}))}beforeEmit(e,...t){var r=`${this.service.name}::emit ${e.toString()}`;if("onSendMessage"===e){var o=t[0];this.logger.log(`${r}`,`${o.messageClientId};createTime:${o.createTime};`,`sendingState:${o.sendingState};attachmentUploadState:${o.attachmentUploadState||0}`)}else if("onReceiveMessages"===e){var i=t[0];this.logger.log(`${r}`,i.map((e=>`${e.messageClientId};createTime:${e.createTime}`)))}else if("onChatroomMemberEnter"===e||"onChatroomMemberInfoUpdated"===e){var n=t[0];this.logger.log(`${r}`,`accountId:${n.accountId}`)}else if("onChatroomMemberRoleUpdated"===e){var s=t[1];this.logger.log(`${r}`,t[0],`accountId:${s.accountId};memberRole:${s.memberRole}`)}else this.logger.log(`${r}`,...t)}}class V2NIMChatroomServiceImpl extends V2ChatroomService{constructor(e){super("V2NIMChatroomService",e),this.event=new V2NIMChatroomServiceEventImpl(e,this),this.setListener()}setListener(){this.event.setListener()}emit(e,...t){return this.event.beforeEmit(e,...t),super.emit(e,...t)}sendMessage(e,t,r){return this.core.V2NIMChatroomMessageService.sendMessage(e,t,r)}cancelMessageAttachmentUpload(e){return this.core.V2NIMChatroomMessageService.fileUtil.cancelMessageAttachmentUpload(e)}registerCustomAttachmentParser(e){this.core.V2NIMChatroomMessageService.registerCustomAttachmentParser(e)}unregisterCustomAttachmentParser(e){this.core.V2NIMChatroomMessageService.unregisterCustomAttachmentParser(e)}getMessageList(e){return this.core.V2NIMChatroomMessageService.getMessageList(e)}getMessageListByTag(e){return this.core.V2NIMChatroomMessageService.getMessageListByTag(e)}getMemberListByOption(e){return this.core.V2NIMChatroomMemberService.getMemberListByOption(e)}updateMemberRole(e,t){return this.core.V2NIMChatroomMemberService.updateMemberRole(e,t)}setMemberBlockedStatus(e,t,r){return this.core.V2NIMChatroomMemberService.setMemberBlockedStatus(e,t,r)}setMemberChatBannedStatus(e,t,r){return this.core.V2NIMChatroomMemberService.setMemberChatBannedStatus(e,t,r)}setMemberTempChatBanned(e,t,r,o){return this.core.V2NIMChatroomMemberService.setMemberTempChatBanned(e,t,r,o)}updateSelfMemberInfo(e,t){return this.core.V2NIMChatroomMemberService.updateSelfMemberInfo(e,t)}getMemberByIds(e){return this.core.V2NIMChatroomMemberService.getMemberByIds(e)}kickMember(e,t){return this.core.V2NIMChatroomMemberService.kickMember(e,t)}getMemberListByTag(e){return this.core.V2NIMChatroomMemberService.getMemberListByTag(e)}getMemberCountByTag(e){return this.core.V2NIMChatroomMemberService.getMemberCountByTag(e)}getChatroomInfo(){return this.core.V2NIMChatroomInfoService.getChatroomInfo()}updateChatroomInfo(e,t){return __awaiter(this,void 0,void 0,(function*(){return this.core.V2NIMChatroomInfoService.updateChatroomInfo(e,t)}))}updateChatroomLocationInfo(e){return __awaiter(this,void 0,void 0,(function*(){return this.core.V2NIMChatroomInfoService.updateChatroomLocationInfo(e)}))}updateChatroomTags(e){return __awaiter(this,void 0,void 0,(function*(){return this.core.V2NIMChatroomInfoService.updateChatroomTags(e)}))}setTempChatBannedByTag(e){return __awaiter(this,void 0,void 0,(function*(){return this.core.V2NIMChatroomInfoService.setTempChatBannedByTag(e)}))}}class V2NIMClientAntispamUtilImpl{constructor(e,t){this.config={enable:!1},this.core=e,t&&this.setOptions(t)}setOptions(e){this.config=Object.assign(this.config,e)}reset(e){"destroy"===e&&(this.vocabInfo=void 0)}downloadLocalAntiSpamVocabs(){return __awaiter(this,void 0,void 0,(function*(){if(this.config.enable&&!this.vocabInfo)try{var e=yield this.core.sendCmd("v2ChatroomDownloadLocalAntiSpamVocabs",{tag:{version:0,md5:""}});this.vocabInfo=Object.assign(Object.assign({},e.content.data),{thesaurus:JSON.parse(e.content.data.thesaurus).thesaurus})}catch(e){this.core.logger.warn("V2NIMLocalAntispamUtil::downloadLocalAntiSpamVocabs error",e)}}))}checkTextAntispam(e,t="**"){if(!this.config.enable)return{operateType:0,replacedText:e};if(validate({text:{type:"string",required:!0,allowEmpty:!1},replace:{type:"string"}},{text:e,replace:t},"",!0),!this.vocabInfo)return{operateType:0,replacedText:e};for(var r=e,o=0;o<this.vocabInfo.thesaurus.length;o++){var i=this.filterContent(r,this.vocabInfo.thesaurus[o],t);if(r=i.replacedText,2===i.operateType||3===i.operateType)return i}return{operateType:r===e?0:1,replacedText:r}}filterContent(e,t,r){for(var o=0;o<t.keys.length;o++){var i=t.keys[o],n=i.match||t.match,s=i.operate||t.operate,a=void 0;try{a=this.matchContent(e,i.key,n,s,r)}catch(e){}if(a&&(e=a.replacedText,2===a.operateType||3===a.operateType))return a}return{operateType:1,replacedText:e}}matchContent(e,t,r,o,i){var n=!1,s=null;if(1===r){if(e.indexOf(t)>=0){n=!0;var a=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");s=new RegExp(a,"g")}}else 2===r&&(s=new RegExp(t,"g")).test(e)&&(n=!0);if(n&&s)switch(o){case 1:return{operateType:1,replacedText:e.replace(s,i)};case 2:return{operateType:2,replacedText:e};case 3:return{operateType:3,replacedText:e}}return{operateType:0,replacedText:e}}}var Pr={initParams:{type:"object",rules:{appkey:{type:"string",allowEmpty:!1},customClientType:{type:"number",required:!1},isFixedDeviceId:{type:"boolean",required:!1},debugLevel:{type:"enum",values:["off","error","warn","log","debug"],required:!1}}},otherParams:{type:"object",rules:{cloudStorageConfig:{type:"object",required:!1,rules:{commonUploadHost:{type:"string",required:!1},commonUploadHostBackupList:{type:"array",required:!1,itemType:"string"},chunkUploadHost:{type:"string",required:!1},uploadReplaceFormat:{type:"string",required:!1},downloadUrl:{type:"string",required:!1},downloadHostList:{type:"array",required:!1},nosCdnEnable:{type:"boolean",required:!1},storageKeyPrefix:{type:"string",required:!1},isNeedToGetUploadPolicyFromServer:{type:"boolean",required:!1},cdn:{type:"object",required:!1,allowEmpty:!1,rules:{defaultCdnDomain:{type:"string",required:!1},cdnDomain:{type:"string",required:!1},bucket:{type:"string",required:!1},objectNamePrefix:{type:"string",required:!1}}}}},reporterConfig:{type:"object",allowEmpty:!1,required:!1,rules:{enableCompass:{type:"boolean",required:!1},compassDataEndpoint:{type:"string",required:!1},isDataReportEnable:{type:"boolean",required:!1}}},abtestConfig:{type:"object",allowEmpty:!1,required:!1,rules:{isAbtestEnable:{type:"boolean",required:!1},abtestUrl:{type:"string",required:!1}}}}}},kr={user_id:"",trace_id:"",action:0,state:0,duration:0,start_time:0,offset:0,full_size:0,transferred_size:0,operation_type:0,remote_addr:""},wr="ReporterHook::setMonitorForResources:";class ReporterHookCloudStorage{constructor(e,t){this.traceData=kr,this.core=e,this.traceData=Object.assign({},kr,t)}reset(){this.traceData=Object.assign({},kr)}start(){var e,t;this.reset(),this.traceData.user_id=this.core.account,this.traceData.trace_id=(null===(t=null===(e=this.core.clientSocket)||void 0===e?void 0:e.socket)||void 0===t?void 0:t.sessionId)||"",this.traceData.start_time="timeOrigin"in this.core?this.core.timeOrigin.getNTPTime():Date.now()}update(e){return __awaiter(this,void 0,void 0,(function*(){this.traceData.user_id&&(this.core.logger.log(`${wr} upload update`,e),Object.assign(this.traceData,e))}))}end(e){this.traceData.user_id&&(this.core.logger.log(`${wr} upload end cause of ${e}`),this.traceData.state=e,this.traceData.duration=("timeOrigin"in this.core?this.core.timeOrigin.getNTPTime():Date.now())-this.traceData.start_time,this.core.reporter.report("nim_sdk_resources",this.traceData),this.traceData=kr)}}function getIsDataReportEnable(e){var t,r,o=!0;return"boolean"==typeof(null===(t=null==e?void 0:e.reporterConfig)||void 0===t?void 0:t.enableCompass)?o=e.reporterConfig.enableCompass:"boolean"==typeof(null===(r=null==e?void 0:e.reporterConfig)||void 0===r?void 0:r.isDataReportEnable)&&(o=e.reporterConfig.isDataReportEnable),o}function getCompassDataEndpoint(e,t){var r,o,i=null===(r=null==t?void 0:t.reporterConfig)||void 0===r?void 0:r.compassDataEndpoint,n=null===(o=null==t?void 0:t.reporterConfig)||void 0===o?void 0:o.reportConfigUrl;if(i)return i;if(n){var s=n.match(/^https:\/\/([^/]+)\/*/);if(Array.isArray(s)&&s.length>=1)return`https://${s[1]}`;e.error(`Invalid reportConfigUrl: ${n}`)}return function pendingIsMiniappEnv(){var{hostEnvEnum:e}=ae.getSystemInfo();return 6===e||102===e||103===e||104===e}()?"https://statistic.live.126.net":"https://statistic.live.126.net,https://statistic-overseas.yunxinfw.com"}var Ur="V2NIMChatroomQueueService",xr={"36_20":"v2ChatroomQueueOffer","36_21":"v2ChatroomQueuePoll","36_22":"v2ChatroomQueueList","36_23":"v2ChatroomQueuePeek","36_24":"v2ChatroomQueueDrop","36_25":"v2ChatroomQueueInit","36_26":"v2ChatroomQueueBatchUpdate"},Gr={v2ChatroomQueueOffer:{sid:36,cid:20,service:Ur,params:[{type:"String",name:"elementKey"},{type:"String",name:"elementValue"},{type:"Bool",name:"transient"},{type:"String",name:"elementOwnerAccountId"}]},v2ChatroomQueuePoll:{sid:36,cid:21,service:Ur,params:[{type:"String",name:"elementKey"}],response:[{type:"String",name:"elementKey"},{type:"String",name:"elementValue"}]},v2ChatroomQueueList:{sid:36,cid:22,service:Ur,params:[],response:[{type:"KVArray",name:"datas"}]},v2ChatroomQueuePeek:{sid:36,cid:23,service:Ur,params:[],response:[{type:"String",name:"elementKey"},{type:"String",name:"elementValue"}]},v2ChatroomQueueDrop:{sid:36,cid:24,service:Ur,params:[]},v2ChatroomQueueInit:{sid:36,cid:25,service:Ur,params:[{type:"Int",name:"size"}]},v2ChatroomQueueBatchUpdate:{sid:36,cid:26,service:Ur,params:[{type:"StrStrMap",name:"keyValues"},{type:"Bool",name:"notificationEnabled"},{type:"String",name:"notificationExtension"}],response:[{type:"StrArray",name:"datas"}]}},Fr={elementKey:{type:"string",required:!0,allowEmpty:!1},elementValue:{type:"string",required:!0,allowEmpty:!1},transient:{type:"boolean",required:!1},elementOwnerAccountId:{type:"string",required:!1,allowEmpty:!1}},Br={elements:{type:"array",min:1,max:100,rules:{key:{type:"string",required:!0,allowEmpty:!1},value:{type:"string",required:!0,allowEmpty:!1}},required:!0},notificationEnabled:{type:"boolean",required:!1},notificationExtension:{type:"string",required:!1}};class V2NIMChatroomQueueServiceImpl extends V2ChatroomService{constructor(e){super("V2NIMChatroomQueueService",e),registerParser({cmdMap:xr,cmdConfig:Gr}),this.setListeners()}setListeners(){this.core.eventBus.on("V2NIMChatroomMessageService/onReceiveNotification",(e=>__awaiter(this,void 0,void 0,(function*(){if(11===e.attachment.type)try{var t=JSON.parse(e.attachment.raw),r=JSON.parse(t.data.queueChange);if("OFFER"===r._e)this.emit("onChatroomQueueOffered",{key:r.key,value:r.content});else if("POLL"===r._e)this.emit("onChatroomQueuePolled",{key:r.key,value:r.content});else if("DROP"===r._e)this.emit("onChatroomQueueDropped");else if("BATCH_UPDATE"===r._e){var o=formatQueueElementsFromKVObject(r.kvObject);o.length>0&&this.emit("onChatroomQueueBatchUpdated",o)}else if("PARTCLEAR"===r._e){var i=formatQueueElementsFromKVObject(r.kvObject);i.length>0&&this.emit("onChatroomQueuePartCleared",i)}else if("BATCH_OFFER"===r._e){var n=formatQueueElementsFromElements(r.elements);n.length>0&&this.emit("onChatroomQueueBatchOffered",n)}}catch(t){this.logger.error("V2NIMChatroomQueueServiceImpl json parse error",t," raw = ",e.attachment.raw)}}))))}emit(e,...t){var r=`${this.name}::emit ${e.toString()}`;return this.logger.log(`${r}`,...t),super.emit(e,...t)}queueOffer(e){return __awaiter(this,void 0,void 0,(function*(){validate(Fr,e,"",!0),yield this.core.sendCmd("v2ChatroomQueueOffer",e)}))}queuePoll(e){return __awaiter(this,void 0,void 0,(function*(){e="string"==typeof e?e:"";var t=yield this.core.sendCmd("v2ChatroomQueuePoll",{elementKey:e});return{key:t.content.elementKey,value:t.content.elementValue}}))}queueList(){return __awaiter(this,void 0,void 0,(function*(){return function formatQueueElements(e){return e&&e.length>0?e.map((e=>{var t=Object.keys(e)[0];return{key:t,value:e[t]}})):[]}((yield this.core.sendCmd("v2ChatroomQueueList")).content.datas)}))}queuePeek(){return __awaiter(this,void 0,void 0,(function*(){var e=yield this.core.sendCmd("v2ChatroomQueuePeek");return{key:e.content.elementKey,value:e.content.elementValue}}))}queueDrop(){return __awaiter(this,void 0,void 0,(function*(){yield this.core.sendCmd("v2ChatroomQueueDrop")}))}queueInit(e){return __awaiter(this,void 0,void 0,(function*(){validate({size:{type:"number",min:0,max:1e3}},{size:e},"",!0),yield this.core.sendCmd("v2ChatroomQueueInit",{size:e})}))}queueBatchUpdate(e,t=!0,r){return __awaiter(this,void 0,void 0,(function*(){validate(Br,{elements:e,notificationEnabled:t,notificationExtension:r},"",!0);var o=e.reduce(((e,t)=>(e[t.key]=t.value,e)),{});return(yield this.core.sendCmd("v2ChatroomQueueBatchUpdate",{keyValues:o,notificationEnabled:t,notificationExtension:r})).content.datas}))}}var Hr=1,Yr={};class V2NIMChatroomClient extends Ie{constructor(e,r={}){var o,i,n;super(),this.pluginMap={},this.eventBus=new Ie,this.options={appkey:"",account:"",tags:[],debugLevel:"debug",xhrConnectTimeout:8e3,socketConnectTimeout:8e3,apiVersion:"v2",isFixedDeviceId:!1,loginSDKTypeParamCompat:!1,binaryWebsocket:!0},this.config={deviceId:"",clientSession:"",binaryWebsocket:!0},this.options.appkey=e.appkey,this.options.customClientType=e.customClientType,this.options.isFixedDeviceId=e.isFixedDeviceId,this.options.loginSDKTypeParamCompat=e.loginSDKTypeParamCompat,this.instanceId=Hr,Hr+=1,this.logger=new Logger(e.debugLevel||"debug",r.loggerConfig),this.timerManager=new TimerManager,this.adapters=new CoreAdapters(this),this.timeOrigin=new TimeOrigin(this,{},"v2ChatroomGetServerTime"),this.reporterHookLinkKeep=new ReporterHookLinkKeep(this),this.reporterHookCloudStorage=new ReporterHookCloudStorage(this),"boolean"==typeof e.binaryWebsocket&&(this.options.binaryWebsocket=e.binaryWebsocket),this.options.isFixedDeviceId?(this.config.deviceId=ae.localStorage.getItem("__CHATROOM_DEVC_ID__")||ve(),this.config.clientSession=ae.localStorage.getItem("__CHATROOM_CLIENT_SESSION_ID__")||ve(),ae.localStorage.setItem("__CHATROOM_DEVC_ID__",this.config.deviceId),ae.localStorage.setItem("__CHATROOM_CLIENT_SESSION_ID__",this.config.clientSession)):(this.config.deviceId=ve(),this.config.clientSession=ve()),this.abtest=new ABTest(this,{isAbtestEnable:void 0===(null===(o=r.abtestConfig)||void 0===o?void 0:o.isAbtestEnable)||(null===(i=r.abtestConfig)||void 0===i?void 0:i.isAbtestEnable),abtestUrl:(null===(n=r.abtestConfig)||void 0===n?void 0:n.abtestUrl)||me,abtestProjectKey:ge});var s=ae.getSystemInfo(),a=getCompassDataEndpoint(this.logger,r);this.reporter=new t(Object.assign(Object.assign({},a?{compassDataEndpoint:a}:{}),{isDataReportEnable:getIsDataReportEnable(r),common:{app_key:e.appkey,dev_id:this.config.deviceId,platform:"Web",sdk_ver:"10.9.41",env:"online",os_name:s.os,os_ver:s.osVer,lib_env:s.libEnv,host_env:s.hostEnv,host_env_ver:s.hostEnvVer,manufactor:s.manufactor,model:s.model,v2:!0},request:ae.request,logger:this.logger,autoStart:!0})),ae.setLogger(this.logger),this.auth=new V2NIMChatroomLoginServiceImpl(this),this.V2NIMChatroomLoginService=this.auth,!1!==this.options.binaryWebsocket&&"function"==typeof Uint8Array?(this.config.binaryWebsocket=!0,this.clientSocket=new V2BinaryClientSocket(this)):(this.config.binaryWebsocket=!1,this.clientSocket=new V2ClientSocket(this)),this.cloudStorage=new CloudStorageService(this,Object.assign({storageKeyPrefix:"V2NIMChatroomClient"},r.cloudStorageConfig)),this.V2NIMChatroomQueueService=new V2NIMChatroomQueueServiceImpl(this),this.V2NIMChatroomInfoService=new V2NIMChatroomInfoServiceImpl(this),this.V2NIMStorageService=new V2NIMStorageServiceImpl(this),this.V2NIMStorageUtil=new V2NIMStorageUtil(this),this.V2NIMChatroomMessageService=new V2NIMChatroomMessageServiceImpl(this),this.V2NIMChatroomMessageCreator=new V2NIMChatroomMessageCreatorImpl(this),this.V2NIMClientAntispamUtil=new V2NIMClientAntispamUtilImpl(this,r.V2NIMClientAntispamUtilConfig),this.V2NIMChatroomMemberService=new V2NIMChatroomMemberServiceImpl(this),this.V2NIMChatroomService=new V2NIMChatroomServiceImpl(this),this.logger.log(`NIM chatroom init, version:10.9.41, sdk version:100941, appkey:${e.appkey}`)}static getInstanceList(){return Object.values(Yr)}static getInstance(e){return validate({instanceId:{type:"number",allowEmpty:!1}},{instanceId:e},"",!0),Yr[e]}static newInstance(e,t={}){validate(Pr,{initParams:e,otherParams:t},"",!0);var r=new V2NIMChatroomClient(e,t);return Yr[r.instanceId]=r,r}static destroyInstance(e){var t=this.getInstance(e);if(t)return delete Yr[e],t._exitAsync().then((()=>{t._clear()})).catch((()=>{t._clear()}))}static destroyAll(){for(var e in Yr)this.destroyInstance(Number(e))}getInstanceId(){return this.instanceId}_clearModuleData(e="logout"){Object.values(this).forEach((t=>{t&&"function"==typeof t.reset&&t.reset(e)}))}_removeAllModuleListeners(){Object.values(this).forEach((e=>{e&&"function"==typeof e.removeAllListeners&&e.removeAllListeners()}))}_clear(){this.removeAllListeners(),this.eventBus.removeAllListeners(),this.logger.destroy(),this.reporter.destroy(),this.timerManager.destroy(),this._clearModuleData("destroy"),this._removeAllModuleListeners()}enter(e,t){var r;return __awaiter(this,void 0,void 0,(function*(){if(validate(It,{roomId:e,enterParams:t},"",!0),!t.accountId&&!t.anonymousMode)throw new V2NIMErrorImpl({code:_t.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"accountId is required"}});var o=get(t,"loginOption.authType")||0;if(t.loginOption=t.loginOption||{authType:o},0===o&&!t.anonymousMode&&!t.token)throw new V2NIMErrorImpl({code:_t.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"token is required when authType == 0"}});if(1===o&&!(null===(r=t.loginOption)||void 0===r?void 0:r.tokenProvider))throw new V2NIMErrorImpl({code:_t.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"tokenProvider is required when authType == 1"}});var i=yield this.auth.login(this.options.appkey,e,t);return this.V2NIMChatroomInfoService._setChatroomInfo(i.chatroom),i}))}_exitAsync(){return __awaiter(this,void 0,void 0,(function*(){this.auth.reset();try{return void(yield this.auth.logout())}catch(e){return Promise.resolve()}}))}exit(){this._exitAsync()}sendCmd(e,t,r){return this.clientSocket.sendCmd(e,t,r)}get account(){return this.options.account}get tags(){return this.options.tags}get status(){return 5===this.auth.lifeCycle.chatroomStatus?"logined":""}getChatroomInfo(){return this.V2NIMChatroomInfoService.getChatroomInfo()}_registerDep(e,t){}emit(e,...t){var r=`core::emit ${e.toString()}`;return this.logger.log(`${r}`,...t),super.emit(e,...t)}}V2NIMChatroomClient.sdkVersion=100941,V2NIMChatroomClient.sdkVersionFormat="10.9.41";var $r={wifi:2,"2g":3,"3g":4,"4g":5,"5g":6,ethernet:1,unknown:0,none:0,notreachable:0,wwan:0};function getNetFn(e){var t=null;return{getNetworkStatus:()=>new Promise(((t,r)=>{e.getNetworkType({success:function(e){var r=!1;r="boolean"==typeof e.networkAvailable?e.networkAvailable:"none"!==e.networkType.toLowerCase(),t({net_type:$r[e.networkType.toLowerCase()],net_connect:r})},fail:function(){r(new Error("getNetworkType failed"))}})})),onNetworkStatusChange(r){this.offNetworkStatusChange(),e.onNetworkStatusChange&&(t=function(e){var t=e.networkType.toLowerCase();r({isConnected:e.isConnected||"none"!==t,networkType:$r[t]})},e.onNetworkStatusChange(t))},offNetworkStatusChange(){e.offNetworkStatusChange&&(t&&e.offNetworkStatusChange(t),t=null)}}}var jr={debug(...e){},log(...e){},warn(...e){},error(...e){}};function setLogger(e){jr=e}function getLogger(){return jr}function base64ToArrayBuffer(e){for(var t=function base64Decode(e){var t=String(e).replace(/[=]+$/,"");if(t.length%4==1)throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");for(var r,o="",i=0,n=0,s=0;r=t.charAt(s++);~r&&(n=i%4?64*n+r:r,i++%4)?o+=String.fromCharCode(255&n>>(-2*i&6)):0)r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(r);return o}(e),r=t.length,o=new Uint8Array(r),i=0;i<r;i++)o[i]=t.charCodeAt(i);return o.buffer}var Kr=getLogger();class PowerMonitor extends Ie{constructor(e){super(),this.env=e,this.status=0,this.appShowListener=null,this.appHideListener=null,this.flag=!1,this._initAppLifecycleListener()}isActive(){return 0===this.status}getStatus(){return this.status}setStatus(e){var t=this.status;e!==t&&(this.status=e,0===e&&1===t&&this.emit("onPowerMonitorTurnActive"),Kr.log("Adapter powerMonitor::setStatus: ",e))}destroy(){this.status=0,this.flag=!1,this._canIUse()&&(this.appShowListener&&(this.env.offAppShow(this.appShowListener),this.appShowListener=null),this.appHideListener&&(this.env.offAppHide(this.appHideListener),this.appHideListener=null))}_initAppLifecycleListener(){this.flag||(!1!==this._canIUse()?(this.appShowListener=()=>{var e=this.status;this.status=0,1===e&&this.emit("onPowerMonitorTurnActive"),Kr.log("Adapter powerMonitor::onAppShow status:",this.status)},this.appHideListener=()=>{this.status=1,Kr.log("Adapter powerMonitor::onAppHide status:",this.status)},this.env.onAppShow(this.appShowListener),this.env.onAppHide(this.appHideListener),this.flag=!0,Kr.log("Adapter powerMonitor::_initAppLifecycleListener success")):Kr.warn("Adapter powerMonitor::_initAppLifecycleListener env.onAppShow/env.onAppHide not available"))}_canIUse(){return void 0!==this.env&&"function"==typeof this.env.onAppShow&&"function"==typeof this.env.onAppHide&&"function"==typeof this.env.offAppShow&&"function"==typeof this.env.offAppHide}}function getAPIEnv(){return"undefined"!=typeof tt&&tt.getSystemInfoSync?tt:"undefined"!=typeof swan&&swan.getSystemInfoSync?swan:"undefined"!=typeof my&&my.getSystemInfoSync?my:"undefined"!=typeof wx&&wx.getAppBaseInfo?wx:void 0}class LogStorageImpl{constructor(e="nim_logs"){this.dirPath="",this.filePath="",this.copyFilePath="",this.maxCapacity=26214400,this.remainCapacity=8388608,this.count=0,this.maxCount=60,this.lastErrorMsg=void 0;var t=getAPIEnv();t&&(this.dirPath=`${t.env.USER_DATA_PATH}/__nim`,this.filePath=`${this.dirPath}/${e}.log`,this.copyFilePath=`${this.dirPath}/${e}_copy.log`)}makeDir(){var e=getAPIEnv();if(e){var t=getLogger(),r=e.getFileSystemManager();try{var o=r.accessSync(this.dirPath);t.log("logStorage::access dir:",o),("object"==typeof o&&null!==o?o.error||o.errno||o.errCode||o.errNo:0)>200&&r.mkdirSync(this.dirPath,!0)}catch(e){r.mkdirSync(this.dirPath,!0)}try{var i=r.accessSync(this.filePath);t.log("logStorage::access file:",i),("object"==typeof i&&null!==i?i.error||i.errno||i.errCode||i.errNo:0)>200&&r.writeFileSync(this.filePath,"===","utf8")}catch(e){r.writeFileSync(this.filePath,"===","utf8")}}}open(){return __awaiter(this,void 0,void 0,(function*(){if(getAPIEnv()){var e=getLogger();try{this.makeDir(),e.log(`logStorage::open log file success:${this.filePath}`)}catch(t){e.warn(`logStorage::open log file failed:${this.filePath}`,t)}yield this.checkCapacity(this.remainCapacity)}}))}checkCapacity(e){return __awaiter(this,void 0,void 0,(function*(){var t=getAPIEnv();if(t){var r=getLogger(),o=t.getFileSystemManager(),i=this.getSize();if(i>this.maxCapacity){r.log(`logStorage::checksize:exceed,${i} byte`);var n="";try{n=yield this.readLogs(i-e)}catch(e){return void r.log("logStorage::checkCapacity:read failed",e)}r.log(`logStorage::checksize:read success ${i-e} byte`);try{o.unlinkSync(this.filePath)}catch(e){return void r.log("logStorage::checkCapacity:unlink failed",e)}try{o.writeFileSync(this.filePath,n,"utf8")}catch(e){return void r.log("logStorage::checkCapacity:write failed",e)}}else r.log(`logStorage::checkCapacity:not exceeding,${i} byte`)}}))}getSize(){var e,t=getAPIEnv();if(!t)return 0;var r,o=getLogger(),i=t.getFileSystemManager();try{r=i.statSync(this.filePath,!1)}catch(e){return o.warn("logStorage::stat failed",e),0}return r.size||(null===(e=r.stats)||void 0===e?void 0:e.size)}readLogs(e=0){var t=getAPIEnv();if(!t)return Promise.resolve("");var r=getLogger(),o=t.getFileSystemManager();return new Promise(((t,i)=>{o.readFile({filePath:this.filePath,encoding:"utf8",position:e,success:e=>{var o=e.data;"string"==typeof o?(r.warn(`logStorage::readLogs success ${o.length}`),t(o)):(r.warn("logStorage::readLogs empty"),i(new Error("logStorage::readLogs empty")))},fail:e=>{var t=e.errMsg||e.errorMessage||e.message;r.warn(`logStorage::readLogs failed ${t}`);var o={code:e.errCode||0,message:t};i(o)}})}))}close(){}addLogs(e){var t=getAPIEnv();if(!t)return Promise.resolve();var r=getLogger(),o=e.map((e=>e.text)).concat("").join("\n");try{t.getFileSystemManager().appendFileSync(this.filePath,o,"utf8")}catch(e){var i=e.errMsg||e.errorMessage||e.message;this.lastErrorMsg!==i&&r.warn("logStorage::append failed",e),this.lastErrorMsg=i}return this.count+=1,this.count>this.maxCount&&(this.count=0,this.checkCapacity(this.remainCapacity)),Promise.resolve()}extractLogs(){return __awaiter(this,void 0,void 0,(function*(){var e=getAPIEnv();if(e){var t=getLogger(),r=this.getSize(),o=e.getFileSystemManager();if(r>0){try{o.copyFileSync(this.filePath,this.copyFilePath)}catch(e){return void t.warn("logStorage::copyFileSync failed",e)}return this.copyFilePath}t.warn("logStorage::extractLogs empty")}}))}afterUpload(){return __awaiter(this,void 0,void 0,(function*(){var e=getAPIEnv();if(e){var t=getLogger(),r=e.getFileSystemManager();try{r.unlinkSync(this.copyFilePath)}catch(e){return void t.log("logStorage::delete copyFilePath failed",e)}}}))}}var qr={clear(){my.clearStorageSync()},getItem:e=>my.getStorageSync({key:e}).data,setItem:(e,t)=>my.setStorageSync({key:e,data:t}),removeItem:e=>my.removeStorageSync({key:e})};function requestFn$3(e,t){return t&&(t.data=t.data||(null==t?void 0:t.params)||{}),new Promise(((r,o)=>{my.request(Object.assign(Object.assign({url:e},t),{success:function(t){"number"==typeof(t=t||{}).status&&t.status.toString().startsWith("2")?(t={data:t.data,status:t.status,errMsg:t.errMsg,header:t.header},r(t)):o({code:t.status||0,message:t.data||`ali request fail. url: ${e}`})},fail:function(t){var r=`ali request fail. url: ${e}`;o(t?{code:13===t.error?_e.V2NIM_ERROR_CODE_TIMEOUT:t.error,message:t.errorMessage||r}:{code:0,message:r})}}))}))}function getSystemInfoFn$3(){var e=my.getSystemInfoSync()||{};return{libEnv:"MINIAPP",os:e.platform||"",osVer:e.system||"",browser:"",browserVer:"",hostEnv:"Ali",hostEnvEnum:102,hostEnvVer:e.version,userAgent:`NIM/Web/AliMiniApp(${my.SDKVersion})/V10.9.41/{{appkey}}`,model:my.SDKVersion,manufactor:"Ali",pushDeviceInfo:{PRODUCT:e.model,DEVICE:e.model,MANUFACTURER:e.brand}}}function uploadFileFn$3(e){var t=getLogger(),r=e.headers||{};return e.md5&&(r["Content-MD5"]=e.md5),new Promise(((o,i)=>{var n=my.uploadFile(Object.assign(Object.assign({url:`${e.commonUploadHost}/${e.nosToken.bucket}`},Object.keys(r).length>0?{header:r}:{}),{formData:{Object:decodeURIComponent(e.nosToken.objectName),"x-nos-token":e.nosToken.token,"x-nos-entity-type":"json"},fileType:e.type,fileName:"file",filePath:e.filePath,success(t){if(200==t.statusCode)try{var r=JSON.parse(t.data);r.name=e.filePath,r.ext=r.name.lastIndexOf(".")>-1?r.name.slice(r.name.lastIndexOf(".")+1).toLowerCase():"",o(r)}catch(e){i({code:t.statusCode,message:t.errMsg,rawData:t.data})}else i({code:t.statusCode,message:t.errMsg,rawData:t.data})},fail(e){e.code=9===e.error?_e.V2NIM_ERROR_CODE_CANCELLED:e.error,e.message=e.errorMessage,i(e)}}));try{e.onUploadStart&&e.onUploadStart(n)}catch(e){t.error("uploadFile: options.onUploadStart error",e),n.abort(),i(e)}e.onUploadProgress&&n.onProgressUpdate((function(t){e.onUploadProgress&&e.onUploadProgress({total:t.totalBytesExpectedToWrite,loaded:t.totalBytesWritten,percentage:parseFloat((t.totalBytesWritten/t.totalBytesExpectedToWrite).toFixed(2)),percentageText:t.progress+"%"})}))}))}function getFileUploadInformationFn$3(e){return null}class WebSocketFn$3{constructor(e,t=""){if(this.CONNECTING=0,this.OPEN=1,this.CLOSING=2,this.CLOSED=3,this.binaryType="",this.onclose=function(e){getLogger().log("my-app: sockets on close ",e)},this.onerror=function(e){getLogger().error("my-app: sockets error ",e)},this.onmessage=function(e){},this.onopen=function(){},!e)throw new Error("Failed to construct 'socket': url required");this.url=e.replace(/:443(\/|$)/,"$1"),this.protocol=t,this.readyState=this.CONNECTING,this.socketTask=my.connectSocket({url:this.url,multiple:!0,fail:e=>{this.errorHandler(e)},success:()=>{this.readyState=this.OPEN}}),this.socketTask.onOpen((e=>{this.readyState=this.OPEN,this.binaryType?this.onopen():this.onmessage&&this.onmessage({type:"open",header:e})})),this.socketTask.onError((e=>{this.errorHandler(e)})),this.socketTask.onClose((e=>{this.readyState=this.CLOSED;var{code:t,reason:r,wasClean:o}=e;"function"==typeof this.onclose&&this.onclose&&this.onclose({code:t,reason:r,wasClean:o,type:"close"}),this.socketTask=null})),this.socketTask.onMessage((e=>{var t,r=null===(t=e.data)||void 0===t?void 0:t.data,o=r;e.data.isBuffer&&(o=base64ToArrayBuffer(r)),this.onmessage&&this.onmessage({data:o})}))}close(){this.socketTask&&this.socketTask.close({code:1e3,reason:"user force close websocket",complete:()=>{this.socketTask=null}})}send(e){if(this.readyState!==this.OPEN)throw new Error(`my-app: socket sendMsg when readyState=${this.readyState}`);if(!("string"==typeof e||e instanceof ArrayBuffer))throw new TypeError("my-app: socket sendMsg only String/ArrayBuffer supported");this.socketTask&&this.socketTask.send({data:e,isBuffer:e instanceof ArrayBuffer})}errorHandler(e){getLogger().error("my-app::ws: onerror ",e),this.readyState=this.CLOSED,this.onerror&&this.onerror({type:"error",code:null==e?void 0:e.error,message:null==e?void 0:e.errorMessage})}}var Wr={clear:()=>wx.clearStorageSync(),getItem:e=>wx.getStorageSync(e),setItem:(e,t)=>wx.setStorageSync(e,t),removeItem:e=>wx.removeStorageSync(e)};function requestFn$2(e,t){return t&&(t.header=t.headers,t.data=t.data||(null==t?void 0:t.params)||{}),new Promise(((r,o)=>{wx.request(Object.assign(Object.assign({url:e},t),{success:function(t){"number"==typeof(t=t||{}).statusCode&&t.statusCode.toString().startsWith("2")?(t={data:t.data,status:t.statusCode,errMsg:t.errMsg,header:t.header},r(t)):o({code:t.statusCode||0,message:t.data||`wechat request fail. url: ${e}`})},fail:function(t){var r=`wechat request fail. url: ${e}`;o(t?{code:5===t.errno?_e.V2NIM_ERROR_CODE_TIMEOUT:t.errno,message:t.errMsg||r}:{code:0,message:r})}}))}))}function getSystemInfoFn$2(){var e=wx.getSystemInfoSync()||{};return{os:e.platform||"",osVer:e.system||"",browser:"",browserVer:"",libEnv:"MINIAPP",hostEnv:"WeiXin",hostEnvEnum:6,hostEnvVer:e.version,model:e.SDKVersion,manufactor:"WeiXin",userAgent:`NIM/Web/WeChatMiniApp(${e.SDKVersion})/V10.9.41/{{appkey}}`,pushDeviceInfo:{PRODUCT:e.model,DEVICE:e.model,MANUFACTURER:e.brand}}}function uploadFileFn$2(e){var t=getLogger(),r=e.headers||{};return e.md5&&(r["Content-MD5"]=e.md5),new Promise(((o,i)=>{var n=wx.uploadFile(Object.assign(Object.assign({url:`${e.commonUploadHost}/${e.nosToken.bucket}`,header:r},Object.keys(r).length>0?{header:r}:{}),{formData:{Object:decodeURIComponent(e.nosToken.objectName),"x-nos-token":e.nosToken.token,"x-nos-entity-type":"json"},name:"file",filePath:e.filePath,success(t){if(200==t.statusCode)try{var r=JSON.parse(t.data);r.name=e.filePath,r.ext=r.name.lastIndexOf(".")>-1?r.name.slice(r.name.lastIndexOf(".")+1).toLowerCase():"",o(r)}catch(e){i({code:t.statusCode,message:t.errMsg,rawData:t.data})}else i({code:t.statusCode,message:t.errMsg,rawData:t.data})},fail(e){e.code="uploadFile:fail abort"===e.errMsg?_e.V2NIM_ERROR_CODE_CANCELLED:e.errno,e.message=e.errMsg,i(e)}}));try{e.onUploadStart&&e.onUploadStart(n)}catch(e){t.error("uploadFile: options.onUploadStart error",e),n.abort(),i(e)}e.onUploadProgress&&n.onProgressUpdate((function(t){e.onUploadProgress&&e.onUploadProgress({total:t.totalBytesExpectedToSend,loaded:t.totalBytesSent,percentage:parseFloat((t.totalBytesSent/t.totalBytesExpectedToSend).toFixed(2)),percentageText:t.progress+"%"})}))}))}function getFileUploadInformationFn$2(e){return null}class WebSocketFn$2{constructor(e,t=""){if(this.CONNECTING=0,this.OPEN=1,this.CLOSING=2,this.CLOSED=3,this.binaryType="",this.onclose=function(e){getLogger().log("wx-app: sockets on close ",e)},this.onerror=function(e){getLogger().error("wx-app: sockets error ",e)},this.onmessage=function(e){},this.onopen=function(){},!e)throw new Error("Failed to construct 'socket': url required");this.url=e.replace(/:443(\/|$)/,"$1"),this.protocol=t,this.readyState=this.CONNECTING;var r=this.protocol?{protocols:[this.protocol]}:{};this.socketTask=wx.connectSocket(Object.assign(Object.assign({url:this.url},r),{fail:e=>{this.errorHandler(e)},success:()=>{}})),this.socketTask.onOpen((e=>{this.readyState=this.OPEN,this.binaryType?this.onopen():this.onmessage&&this.onmessage({type:"open",header:e})})),this.socketTask.onError((e=>{this.errorHandler(e)})),this.socketTask.onClose((e=>{this.readyState=this.CLOSED;var{code:t,reason:r,wasClean:o}=e;"function"==typeof this.onclose&&this.onclose&&this.onclose({code:t,reason:r,wasClean:o,type:"close"})})),this.socketTask.onMessage((e=>{this.onmessage&&this.onmessage(e)}))}close(){this.socketTask.close({code:1e3,reason:"user force close websocket",complete:()=>{this.socketTask=null}})}send(e){if(this.readyState!==this.OPEN)throw new Error(`wx-app: socket sendMsg when readyState=${this.readyState}`);if(!("string"==typeof e||e instanceof ArrayBuffer))throw new TypeError("wx-app: socket sendMsg only String/ArrayBuffer supported");this.socketTask.send({data:e})}errorHandler(e){getLogger().error("wx-app::ws: onerror ",e),this.readyState=this.CLOSED,this.onerror&&this.onerror({type:"error",message:e&&e.errMsg})}}var zr={clear(){swan.clearStorageSync()},getItem:e=>swan.getStorageSync(e),setItem:(e,t)=>swan.setStorageSync(e,t),removeItem:e=>swan.removeStorageSync(e)};function requestFn$1(e,t){return t&&(t.header=t.headers,t.data=t.data||(null==t?void 0:t.params)||{}),new Promise(((r,o)=>{swan.request(Object.assign(Object.assign({url:e},t),{success:function(t){"number"==typeof(t=t||{}).statusCode&&t.statusCode.toString().startsWith("2")?(t={data:t.data,status:t.statusCode,errMsg:t.errMsg,header:t.header},r(t)):o({code:t.statusCode||0,message:t.data||`baidu request fail. url: ${e}`})},fail:function(t){var r=`baidu request fail. url: ${e}`;o(t?{code:1===t.errCode?_e.V2NIM_ERROR_CODE_TIMEOUT:t.errCode,message:t.errMsg||r}:{code:0,message:r})}}))}))}function getSystemInfoFn$1(){var e=swan.getSystemInfoSync()||{};return{os:e.platform||"",osVer:e.system||"",browser:"",browserVer:"",libEnv:"MINIAPP",hostEnv:"Baidu",userAgent:`NIM/Web/BaiduMiniApp(${e.SDKVersion})/V10.9.41/{{appkey}}`,hostEnvVer:e.version,hostEnvEnum:103,model:e.SDKVersion,manufactor:"Baidu",pushDeviceInfo:{PRODUCT:e.model,DEVICE:e.model,MANUFACTURER:e.brand}}}function uploadFileFn$1(e){var t=getLogger(),r=e.headers||{};return e.md5&&(r["Content-MD5"]=e.md5),new Promise(((o,i)=>{var n=swan.uploadFile(Object.assign(Object.assign({url:`${e.commonUploadHost}/${e.nosToken.bucket}`},Object.keys(r).length>0?{header:r}:{}),{formData:{Object:decodeURIComponent(e.nosToken.objectName),"x-nos-token":e.nosToken.token,"x-nos-entity-type":"json"},name:"file",filePath:e.filePath,success(t){if(200==t.statusCode)try{var r=JSON.parse(t.data);r.name=e.filePath,r.ext=r.name.lastIndexOf(".")>-1?r.name.slice(r.name.lastIndexOf(".")+1).toLowerCase():"",o(r)}catch(e){i({code:t.statusCode,message:t.errMsg,rawData:t.data})}else i({code:t.statusCode,message:t.errMsg,rawData:t.data})},fail(e){e.code="uploadFile:fail abort"===e.errMsg?_e.V2NIM_ERROR_CODE_CANCELLED:e.errCode,e.message=e.errMsg,i(e)}}));try{e.onUploadStart&&e.onUploadStart(n)}catch(e){t.error("uploadFile: options.onUploadStart error",e),n.abort(),i(e)}e.onUploadProgress&&n.onProgressUpdate((function(t){e.onUploadProgress&&e.onUploadProgress({total:t.totalBytesExpectedToSend,loaded:t.totalBytesSent,percentage:parseFloat((t.totalBytesSent/t.totalBytesExpectedToSend).toFixed(2)),percentageText:t.progress+"%"})}))}))}function getFileUploadInformationFn$1(e){return null}class WebSocketFn$1{constructor(e,t=""){if(this.CONNECTING=0,this.OPEN=1,this.CLOSING=2,this.CLOSED=3,this.binaryType="",this.onclose=function(e){getLogger().log("baidu-app: sockets on close ",e)},this.onerror=function(e){getLogger().error("baidu-app: sockets error ",e)},this.onmessage=function(e){},this.onopen=function(){},!e)throw new Error("Failed to construct 'socket': url required");this.url=e.replace(/:443(\/|$)/,"$1"),this.protocol=t,this.readyState=this.CONNECTING;var r=this.protocol?{protocols:[this.protocol]}:{};this.socketTask=swan.connectSocket(Object.assign(Object.assign({url:this.url},r),{fail:e=>{this.errorHandler(e)},success:()=>{}})),this.socketTask.onOpen((e=>{this.readyState=this.OPEN,this.binaryType?this.onopen():this.onmessage&&this.onmessage({type:"open",header:e})})),this.socketTask.onError((e=>{this.errorHandler(e)})),this.socketTask.onClose((e=>{this.readyState=this.CLOSED;var{code:t,reason:r,wasClean:o}=e;"function"==typeof this.onclose&&this.onclose&&this.onclose({code:t,reason:r,wasClean:o,type:"close"})})),this.socketTask.onMessage((e=>{this.onmessage&&this.onmessage({data:e.data})}))}close(){this.socketTask.close({code:1e3,reason:"user force close websocket",complete:()=>{this.socketTask=null}})}send(e){if(this.readyState!==this.OPEN)throw new Error(`wx-app: socket sendMsg when readyState=${this.readyState}`);if(!("string"==typeof e||e instanceof ArrayBuffer))throw new TypeError("wx-app: socket sendMsg only String/ArrayBuffer supported");this.socketTask.send({data:e})}errorHandler(e){this.readyState=this.CLOSED,this.onerror&&this.onerror({type:"error",message:e&&e.errMsg})}}var Jr={clear(){tt.clearStorageSync()},getItem:e=>tt.getStorageSync(e),setItem:(e,t)=>tt.setStorageSync(e,t),removeItem:e=>tt.removeStorageSync(e)};function requestFn(e,t){return t&&(t.header=t.headers,t.data=t.data||(null==t?void 0:t.params)||{}),new Promise(((r,o)=>{tt.request(Object.assign(Object.assign({url:e},t),{success:function(t){"number"==typeof(t=t||{}).statusCode&&t.statusCode.toString().startsWith("2")?(t={data:t.data,status:t.statusCode,errMsg:t.errMsg,header:t.header},r(t)):o({code:t.statusCode||0,message:t.data||`tt request fail. url: ${e}`})},fail:function(t){var r=`tt request fail. url: ${e}`;o(t?{code:21103===t.errNo?_e.V2NIM_ERROR_CODE_TIMEOUT:t.errNo,message:t.errMsg||r}:{code:0,message:r})}}))}))}function getSystemInfoFn(){var e=tt.getSystemInfoSync()||{};return{os:e.platform||"",osVer:e.system||"",browser:"",browserVer:"",libEnv:"MINIAPP",hostEnv:"Tiktok",hostEnvEnum:104,hostEnvVer:e.version,model:e.SDKVersion,manufactor:"Tiktok",userAgent:`NIM/Web/TiktokMiniApp(${e.SDKVersion})/V10.9.41/{{appkey}}`,pushDeviceInfo:{PRODUCT:e.model,DEVICE:e.model,MANUFACTURER:e.brand}}}function uploadFileFn(e){var t=getLogger(),r=e.headers||{};return e.md5&&(r["Content-MD5"]=e.md5),new Promise(((o,i)=>{var n=tt.uploadFile(Object.assign(Object.assign({url:`${e.commonUploadHost}/${e.nosToken.bucket}`},Object.keys(r).length>0?{header:r}:{}),{formData:{Object:decodeURIComponent(e.nosToken.objectName),"x-nos-token":e.nosToken.token,"x-nos-entity-type":"json"},name:"file",filePath:e.filePath,success(t){if(200==t.statusCode)try{var r=JSON.parse(t.data);r.name=e.filePath,r.ext=r.name.lastIndexOf(".")>-1?r.name.slice(r.name.lastIndexOf(".")+1).toLowerCase():"",o(r)}catch(e){i({code:t.statusCode,message:t.errMsg,rawData:t.data})}else i({code:t.statusCode,message:t.errMsg,rawData:t.data})},fail(e){e.code=21104===e.errNo?_e.V2NIM_ERROR_CODE_CANCELLED:e.errNo,e.message=e.errMsg,i(e)}}));try{e.onUploadStart&&e.onUploadStart(n)}catch(e){t.error("uploadFile: options.onUploadStart error",e),n.abort(),i(e)}e.onUploadProgress&&n.onProgressUpdate((function(t){e.onUploadProgress&&e.onUploadProgress({total:t.totalBytesExpectedToSend,loaded:t.totalBytesSent,percentage:parseFloat((t.totalBytesSent/t.totalBytesExpectedToSend).toFixed(2)),percentageText:t.progress+"%"})}))}))}function getFileUploadInformationFn(e){return null}class WebSocketFn{constructor(e,t=""){if(this.CONNECTING=0,this.OPEN=1,this.CLOSING=2,this.CLOSED=3,this.binaryType="",this.onclose=function(e){getLogger().log("wx-app: sockets on close ",e)},this.onerror=function(e){getLogger().error("wx-app: sockets error ",e)},this.onmessage=function(e){},this.onopen=function(){},!e)throw new Error("Failed to construct 'socket': url required");this.url=e.replace(/:443(\/|$)/,"$1"),this.protocol=t,this.readyState=this.CONNECTING;var r=this.protocol?{protocols:[this.protocol]}:{};this.socketTask=tt.connectSocket(Object.assign(Object.assign({url:this.url},r),{fail:e=>{this.errorHandler(e)},success:()=>{}})),this.socketTask.onOpen((e=>{this.readyState=this.OPEN,this.binaryType?this.onopen():this.onmessage&&this.onmessage({type:"open",header:e.header})})),this.socketTask.onError((e=>{this.errorHandler(e)})),this.socketTask.onClose((e=>{this.readyState=this.CLOSED;var{code:t,reason:r,wasClean:o}=e;"function"==typeof this.onclose&&this.onclose&&this.onclose({code:t,reason:r,wasClean:o,type:"close"})})),this.socketTask.onMessage((e=>{this.onmessage&&this.onmessage({data:e.data})}))}close(){this.socketTask&&this.socketTask.close({code:1e3,reason:"user force close websocket",complete:()=>{}})}send(e){if(this.readyState!==this.OPEN)throw new Error(`tt-app: socket sendMsg when readyState=${this.readyState}`);if(!("string"==typeof e||e instanceof ArrayBuffer))throw new TypeError("tt-app: socket sendMsg only String/ArrayBuffer supported");this.socketTask&&this.socketTask.send({data:e})}errorHandler(e){getLogger().error("tt-app::ws: onerror ",e),this.readyState=this.CLOSED,this.onerror&&this.onerror({type:"error",message:e&&e.errMsg})}}!function setAdapters(e){merge(ae,e())}((function getAdapter(){if("undefined"!=typeof tt&&tt.getSystemInfo)return{setLogger:setLogger,platform:"TTAPP",localStorage:Jr,request:requestFn,WebSocket:WebSocketFn,uploadFile:uploadFileFn,getSystemInfo:getSystemInfoFn,getFileUploadInformation:getFileUploadInformationFn,net:getNetFn(tt)};if("undefined"!=typeof swan&&swan.getSystemInfo)return{setLogger:setLogger,platform:"BAIDUAPP",localStorage:zr,request:requestFn$1,WebSocket:WebSocketFn$1,uploadFile:uploadFileFn$1,getFileUploadInformation:getFileUploadInformationFn$1,getSystemInfo:getSystemInfoFn$1,net:getNetFn(swan)};if("undefined"!=typeof my&&my.getSystemInfo)return{setLogger:setLogger,platform:"ALIAPP",localStorage:qr,request:requestFn$3,WebSocket:WebSocketFn$3,uploadFile:uploadFileFn$3,getSystemInfo:getSystemInfoFn$3,getFileUploadInformation:getFileUploadInformationFn$3,net:getNetFn(my),powerMonitor:new PowerMonitor(my),logStorage:LogStorageImpl};if("undefined"!=typeof wx&&wx.getSystemInfo)return{setLogger:setLogger,platform:"WXAPP",localStorage:Wr,request:requestFn$2,WebSocket:WebSocketFn$2,uploadFile:uploadFileFn$2,getFileUploadInformation:getFileUploadInformationFn$2,getSystemInfo:getSystemInfoFn$2,net:getNetFn(wx),powerMonitor:new PowerMonitor(wx),logStorage:LogStorageImpl};throw new Error("No adapter found!")})),e.V2NIMChatroomConst=Et,e.default=V2NIMChatroomClient,Object.defineProperty(e,"__esModule",{value:!0})}));