goeasy-2.13.21.esm.min.js 185 KB

12
  1. var e,t;!function(e){e.UNIAPP="uniapp",e.REACT_NATIVE="rn",e.COCOS="cocos",e.UNKNOWN="unknown"}(e||(e={}));class s{constructor(){this.framework=null,this.methods={[e.UNIAPP]:this.isUniApp,[e.REACT_NATIVE]:this.isReactNative,[e.COCOS]:this.isCocos};const t=this.methods,s=Object.keys(t);for(const e of s){if((0,t[e])()){this.framework=e;break}}this.framework=this.framework||e.UNKNOWN,this.framework}static currentFramework(){return this.instance||(this.instance=new s),this.instance.framework}isUniApp(){try{return"function"==typeof uni.getSystemInfoSync}catch(e){return!1}}isReactNative(){try{return"object"==typeof navigator&&"ReactNative"===navigator.product}catch(e){return!1}}isTaro(){try{return void 0!==process.env.TARO_ENV}catch(e){return!1}}isCocos(){try{return void 0!==cc.sys.localStorage}catch(e){return!1}}}class i{static init(t){if(s.currentFramework()===e.REACT_NATIVE){if(!t)throw new Error("'reactNativeOptions' is missing when calling GoEasy.getInstance()");this.platform=t.platform,this.asyncStorage=t.asyncStorage}}}!function(e){e.DISCONNECTED="disconnected",e.DISCONNECTING="disconnecting",e.CONNECTING="connecting",e.CONNECTED="connected",e.RECONNECTING="reconnecting",e.RECONNECTED="reconnected",e.EXPIRED_RECONNECTED="reconnected",e.CONNECT_FAILED="connect_failed"}(t||(t={}));const n="2.13.21";var o,r;!function(e){e.PRIVATE="private",e.GROUP="group",e.SYSTEM="system",e.CS="cs"}(o||(o={})),function(e){e.NEW="new",e.SENDING="sending",e.SUCCESS="success",e.FAIL="fail"}(r||(r={}));class a{}class c{constructor(e,t){this.id=e,this.data=t}}let u=new class{isDef(e){return!this.isUndef(e)}isUndef(e){return null==e}isPrimitive(e){return"string"==typeof e||"number"==typeof e||"symbol"==typeof e||"boolean"==typeof e}isObject(e){return null!==e&&"object"==typeof e}isPlainObject(e){return"[object Object]"===Object.prototype.toString.call(e)}isRegExp(e){return"[object RegExp]"===Object.prototype.toString.call(e)}isValidArrayIndex(e){let t=parseFloat(String(e));return t>=0&&Math.floor(t)===t&&isFinite(e)}isString(e){return"string"==typeof e}isNumber(e){return"number"==typeof e}isStringOrNumber(e){return this.isString(e)||this.isNumber(e)}isArray(e){return"[object Array]"===Object.prototype.toString.call(e)}isEmpty(e){return this.isArray(e)?0===e.length:this.isObject(e)?!this.isDef(e):!this.isNumber(e)&&(this.isString(e)?""===e.trim():!this.isDef(e))}isNative(e){return"function"==typeof e&&/native code/.test(e.toString())}isFunction(e){return"function"==typeof e}isBoolean(e){return"boolean"==typeof e}isTrue(e){return!0===e}isFalse(e){return!1===e}isNull(e){return null===e}};var l;!function(e){e.MP_WX="mp-wx",e.MP_WGAME="mp-wgame",e.MP_BYTE="mp-byte",e.MP_BAIDU="mp-baidu",e.MP_ALI="mp-ali",e.BROWSER="browser",e.NODE="node",e.UNI_IOS="uni-ios",e.UNI_ANDROID="uni-android",e.COCOS_IOS="cocos-ios",e.COCOS_ANDROID="cocos-android",e.RN_IOS="rn-ios",e.RN_ANDROID="rn-android",e.UNKNOWN="unknown"}(l||(l={}));class d{constructor(){this.platform=null,this.methods={[l.BROWSER]:this.isBrowser,[l.MP_WX]:this.isMPWX,[l.MP_WGAME]:this.isMPWeGame,[l.MP_BYTE]:this.isMPByte,[l.MP_BAIDU]:this.isMPBaidu,[l.MP_ALI]:this.isMPAli,[l.NODE]:this.isNode,[l.UNI_IOS]:this.isUniAppIOS,[l.UNI_ANDROID]:this.isUniAppAndroid,[l.COCOS_IOS]:this.isCocosIOS,[l.COCOS_ANDROID]:this.isCocosAndroid,[l.RN_IOS]:this.isRNiOS,[l.RN_ANDROID]:this.isRNAndroid};const e=this.methods,t=Object.keys(e);for(const s of t){if((0,e[s])()){this.platform=s;break}}this.platform=this.platform||l.UNKNOWN,this.platform}static currentPlatform(){return this.instance||(this.instance=new d),d.instance.platform}isBrowser(){return"undefined"!=typeof navigator&&"Taro"!==navigator.product&&"ReactNative"!==navigator.product&&"undefined"==typeof GameGlobal&&("undefined"==typeof cc||null!==cc.sys.browserType)&&"undefined"==typeof my&&"undefined"==typeof tt&&"undefined"==typeof swan}isMPWX(){return"object"==typeof wx&&"function"==typeof wx.getSystemInfoSync&&"undefined"==typeof WebSocket&&"undefined"==typeof XMLHttpRequest&&"undefined"==typeof plus&&"undefined"==typeof tt}isMPWeGame(){return"object"==typeof GameGlobal}isMPByte(){return"object"==typeof tt&&"function"==typeof tt.getSystemInfoSync}isMPBaidu(){return"object"==typeof swan&&"function"==typeof swan.getSystemInfoSync}isMPAli(){return"object"==typeof my&&"function"==typeof my.getSystemInfoSync}isNode(){try{return"node"===process.release.name}catch(e){return!1}}isUniAppIOS(){try{return"ios"===uni.getSystemInfoSync().platform&&"app"===uni.getSystemInfoSync().uniPlatform}catch(e){return!1}}isUniAppAndroid(){try{return"android"===uni.getSystemInfoSync().platform&&"app"===uni.getSystemInfoSync().uniPlatform}catch(e){return!1}}isCocosIOS(){try{return"iOS"===cc.sys.os}catch(e){return!1}}isCocosAndroid(){try{return"Android"===cc.sys.os}catch(e){return!1}}isRNiOS(){try{return"ios"===i.platform.OS}catch(e){return!1}}isRNAndroid(){try{return"android"===i.platform.OS}catch(e){return!1}}}class h{}h.type=l,h.current=d.currentPlatform();class p{onFrontend(e){this.onFrontendCallback=e}}class m extends p{constructor(){super(...arguments),this.runningBackend=!1}startCheck(){"object"==typeof plus&&(plus.globalEvent.addEventListener("resume",(()=>{this.runningBackend=!1,this.runningBackend,this.onFrontendCallback&&this.onFrontendCallback()}),!1),plus.globalEvent.addEventListener("pause",(()=>{this.runningBackend=!0,this.runningBackend}),!1))}isBackend(){return this.runningBackend}support(){const e=d.currentPlatform();return[l.UNI_IOS,l.UNI_ANDROID].includes(e)}}class f extends p{constructor(){super(...arguments),this.runningBackend=!1}startCheck(){wx.onAppShow((()=>{this.runningBackend=!1})),wx.onAppHide((()=>{this.runningBackend=!0}))}isBackend(){return this.runningBackend}support(){return d.currentPlatform()===l.MP_WX}}const g=new class{constructor(){[new m,new f].forEach((e=>{if(e.support())return this.checker=e,void this.checker.startCheck()}))}isBackend(){return this.checker&&this.checker.isBackend()}onFrontend(e){this.checker.onFrontend(e)}};var y,S,E=Object.freeze({__proto__:null,runStatus:g});!function(e){e.authorize="authorize",e.manualDisconnect="manualDisconnect",e.subscribe="subscribe",e.unsubscribe="unsubscribe",e.publish="publish",e.ack="ack",e.historyMessages="historyMessages",e.hereNow="hereNow",e.hereNowByUserIds="hereNowByUserIds",e.PUBSUB_PRESENCE_SUBSCRIBE="PUBSUB_PRESENCE_SUBSCRIBE",e.PUBSUB_PRESENCE_UNSUBSCRIBE="PUBSUB_PRESENCE_UNSUBSCRIBE",e.PUBSUB_PRESENCE_HERENOW="PUBSUB_PRESENCE_HERENOW",e.imLastConversations="imLastConversations",e.markPrivateMessageAsRead="markPrivateMessageAsRead",e.markGroupMessageAsRead="markGroupMessageAsRead",e.imGroupOnlineCount="imGroupOnlineCount",e.imHereNow="imHereNow",e.imGroupHereNow="imGroupHereNow",e.publishIM="publishIM",e.subscribeUserPresence="subscribeUserPresence",e.unsubscribeUserPresence="unsubscribeUserPresence",e.subscribeGroupPresence="subscribeGroupPresence",e.unsubscribeGroupPresence="unsubscribeGroupPresence",e.removeConversation="removeConversation",e.topConversation="topConversation",e.imData="imData",e.subscribeGroups="subscribeGroups",e.unsubscribeGroup="unsubscribeGroup",e.IM_DELETE_MESSAGE="IM_DELETE_MESSAGE",e.IM_HISTORY="IM_HISTORY",e.IM_HISTORY_CHANGE="IM_HISTORY_CHANGE",e.IM_RECALL_MESSAGE="IM_RECALL_MESSAGE",e.IM_MARK_AS_READ="IM_MARK_AS_READ",e.CS_PENDING_CONVERSATION="CS_PENDING_CONVERSATION",e.CS_ACCEPT="CS_ACCEPT",e.CS_END="CS_END",e.CS_TRANSFER="CS_TRANSFER",e.CS_AGENTS="CS_AGENTS",e.CS_CUSTOMER_STATUS="CS_CUSTOMER_STATUS",e.CS_MY_TEAMS="CS_MY_TEAMS",e.CS_ONLINE="CS_ONLINE",e.CS_OFFLINE="CS_OFFLINE",e.CS_LIVE_SESSION="CS_LIVE_SESSION",e.CS_QUIT_LIVE="CS_QUIT_LIVE",e.SET_IOS_BADGE="SET_IOS_BADGE",e.MD_CMD="MD_CMD"}(y||(y={})),function(e){e[e.connect=3e3]="connect",e[e.reconnectionDelayMax=3e3]="reconnectionDelayMax",e[e.commonQuerySingle=2500]="commonQuerySingle",e[e.commonQueryTotal=12e3]="commonQueryTotal",e[e.commonRequestSingle=1700]="commonRequestSingle",e[e.commonRequestTotal=12e3]="commonRequestTotal",e[e.commonInfiniteSingle=1700]="commonInfiniteSingle",e[e.commonInfiniteTotal=864e5]="commonInfiniteTotal"}(S||(S={}));class v{static onSuccess(e,t){u.isFunction(e.onSuccess)&&e.onSuccess(t)}static onFailed(e,t){if(!u.isObject(e)||!u.isFunction(e.onFailed))throw t;e.onFailed(t)}}function b(e,t,s,i){return new(s||(s=Promise))((function(n,o){function r(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(r,a)}c((i=i.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;var C="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function M(e){if(e.__esModule)return e;var t=Object.defineProperty({},"__esModule",{value:!0});return Object.keys(e).forEach((function(s){var i=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,i.get?i:{enumerable:!0,get:function(){return e[s]}})})),t}var w={exports:{}};!function(e){function t(e){if(e)return function(e){for(var s in t.prototype)e[s]=t.prototype[s];return e}(e)}w.exports=t,t.prototype.on=t.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},t.prototype.once=function(e,t){function s(){this.off(e,s),t.apply(this,arguments)}return s.fn=t,this.on(e,s),this},t.prototype.off=t.prototype.removeListener=t.prototype.removeAllListeners=t.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var s,i=this._callbacks["$"+e];if(!i)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var n=0;n<i.length;n++)if((s=i[n])===t||s.fn===t){i.splice(n,1);break}return this},t.prototype.emit=function(e){this._callbacks=this._callbacks||{};var t=[].slice.call(arguments,1),s=this._callbacks["$"+e];if(s)for(var i=0,n=(s=s.slice(0)).length;i<n;++i)s[i].apply(this,t);return this},t.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},t.prototype.hasListeners=function(e){return!!this.listeners(e).length}}();var I=w.exports,N={exports:{}},T="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof window.msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto);if(T){var R=new Uint8Array(16);N.exports=function(){return T(R),R}}else{var k=new Array(16);N.exports=function(){for(var e,t=0;t<16;t++)0==(3&t)&&(e=4294967296*Math.random()),k[t]=e>>>((3&t)<<3)&255;return k}}for(var A=[],O=0;O<256;++O)A[O]=(O+256).toString(16).substr(1);var P,_,D=function(e,t){var s=t||0,i=A;return[i[e[s++]],i[e[s++]],i[e[s++]],i[e[s++]],"-",i[e[s++]],i[e[s++]],"-",i[e[s++]],i[e[s++]],"-",i[e[s++]],i[e[s++]],"-",i[e[s++]],i[e[s++]],i[e[s++]],i[e[s++]],i[e[s++]],i[e[s++]]].join("")},x=N.exports,U=D,G=0,F=0;var L=function(e,t,s){var i=t&&s||0,n=t||[],o=(e=e||{}).node||P,r=void 0!==e.clockseq?e.clockseq:_;if(null==o||null==r){var a=x();null==o&&(o=P=[1|a[0],a[1],a[2],a[3],a[4],a[5]]),null==r&&(r=_=16383&(a[6]<<8|a[7]))}var c=void 0!==e.msecs?e.msecs:(new Date).getTime(),u=void 0!==e.nsecs?e.nsecs:F+1,l=c-G+(u-F)/1e4;if(l<0&&void 0===e.clockseq&&(r=r+1&16383),(l<0||c>G)&&void 0===e.nsecs&&(u=0),u>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");G=c,F=u,_=r;var d=(1e4*(268435455&(c+=122192928e5))+u)%4294967296;n[i++]=d>>>24&255,n[i++]=d>>>16&255,n[i++]=d>>>8&255,n[i++]=255&d;var h=c/4294967296*1e4&268435455;n[i++]=h>>>8&255,n[i++]=255&h,n[i++]=h>>>24&15|16,n[i++]=h>>>16&255,n[i++]=r>>>8|128,n[i++]=255&r;for(var p=0;p<6;++p)n[i+p]=o[p];return t||U(n)},B=N.exports,q=D;var j=function(e,t,s){var i=t&&s||0;"string"==typeof e&&(t="binary"===e?new Array(16):null,e=null);var n=(e=e||{}).random||(e.rng||B)();if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,t)for(var o=0;o<16;++o)t[i+o]=n[o];return t||q(n)},V=L,H=j,z=H;z.v1=V,z.v4=H;var W=z;class J{support(){return!0}getParams(){return this.params}setData(e){this.active=e.a,this.data=e.d}preConnect(e){}postConnect(){}}class X{static initModule(e){e.support()&&this.modules.set(e.name,e)}static getParams(){return b(this,void 0,void 0,(function*(){let e={};for(const[t,s]of this.modules)e[t]=(yield s.getParams())||null;return e}))}static setDatas(e){Object.keys(e).forEach((t=>{this.modules.get(t).setData(e[t])}))}static preConnect(e){this.modules.forEach(((t,s)=>{t.preConnect(e)}))}static postConnect(){this.modules.forEach(((e,t)=>{e.postConnect()}))}}X.Module=J,X.modules=new Map;const $=I;class Y{constructor(){this.emitter=new $}on(e,t){return this.emitter.on(e,t),this}once(e,t){return this.emitter.once(e,t),this}off(e,t){return this.emitter.off(e,t),this}fire(e,t){return this.emitter.emit(e,t),this}}class Q{constructor(){this.eventDriver=new Y}on(e,t){this.eventDriver.on(e,t)}off(e,t){this.eventDriver.off(e,t)}fire(e,t){this.eventDriver.fire(e,t)}}let K=new class{isDef(e){return!this.isUndef(e)}isUndef(e){return null==e}isPrimitive(e){return"string"==typeof e||"number"==typeof e||"symbol"==typeof e||"boolean"==typeof e}isObject(e){return null!==e&&"object"==typeof e}isPlainObject(e){return"[object Object]"===Object.prototype.toString.call(e)}isRegExp(e){return"[object RegExp]"===Object.prototype.toString.call(e)}isValidArrayIndex(e){let t=parseFloat(String(e));return t>=0&&Math.floor(t)===t&&isFinite(e)}isString(e){return"string"==typeof e}isNumber(e){return"number"==typeof e}isStringOrNumber(e){return this.isString(e)||this.isNumber(e)}isArray(e){return"[object Array]"===Object.prototype.toString.call(e)}isEmpty(e){return this.isArray(e)?0===e.length:this.isObject(e)?!this.isDef(e):!this.isNumber(e)&&(this.isString(e)?""===e.trim():!this.isDef(e))}isNative(e){return"function"==typeof e&&/native code/.test(e.toString())}isFunction(e){return"function"==typeof e}isBoolean(e){return"boolean"==typeof e}isTrue(e){return!0===e}isFalse(e){return!1===e}isNull(e){return null===e}};const Z=I;class ee{constructor(){this.emitter=new Z}on(e,t){if(!K.isString(e))throw Error("event require a string.");if(!K.isFunction(t))throw Error("callback must be a function");this.emitter.on(e,t)}fire(e,t){this.emitter.emit(e,t)}off(e,t){this.emitter.off(e,t)}}class te{static init(e,t,s,i,n,o){this.Socket=e,this.N=t,this.Member=s,this.v=i,this.Platform=n,this.GModules=o}}const se=W;class ie{static get(){return se.v1().replace(/-/g,"")}}var ne,oe,re,ae,ce,ue;(oe=ne||(ne={})).WRITE="WRITE",oe.READ="READ",oe.NONE="NONE";class le{constructor(e){this.permission=ne.NONE,this.singleTimeout=0,this.totalTimeout=0,this.startTime=0,this.complete=!1,this.retried=0,this.unique=!1,this.uuid=ie.get(),this.name=e.name,this.params=e.params,this.permission=e.permission,this.totalTimeout=e.totalTimeout,this.singleTimeout=e.singleTimeout,e.unique&&(this.unique=e.unique),this.success=t=>{this.complete||(this.end(),e.success(t))},this.fail=t=>{this.complete||(this.end(),e.fail(t))}}start(){this.startTime=Date.now(),this.initAutoTimeout()}end(){this.complete=!0,clearTimeout(this.timeoutHandler)}initAutoTimeout(){this.timeoutHandler=setTimeout((()=>{this.complete||this.fail({resultCode:408,content:"Host unreachable or timeout"})}),this.totalTimeout)}}class de extends J{static init(){return this.module=new de,this.module.name=this.GN_MODULE_NAME,this.module}static setRegId(e,t){if(e){this.module.regIdPromise=e;let s=t;this.module.params={v:{npv:s}}}}preConnect(e){this.wxmpId=e.wxmpId}getParams(){return b(this,void 0,void 0,(function*(){if(this.params=this.params||{},this.regIdPromise)try{const e=new Promise(((e,t)=>{setTimeout((()=>t("timeout")),1e3)}));this.params.regId=yield Promise.race([this.regIdPromise,e])}catch(e){console.warn("Failed to register the Manufacturers Push service:"+JSON.stringify(e))}return this.params.wxmpId=this.wxmpId,this.params}))}}de.GN_MODULE_NAME="GN";class he{static init(e){this.allowNotification=!0===e;let t=de.init();X.initModule(t),this.supportAppNotification()&&(this.uniappPlugin=uni.requireNativePlugin("GoEasy-Uniapp"),this.uniappPlugin?(this.regIdPromise=this.askRegId(),this.v=this.uniappPlugin.v(),de.setRegId(this.regIdPromise,this.v)):console.warn("No GoEasy-Uniapp Native Plugin."),this.setClientBadge(0))}static addAssembler(e){this.payloadAssemblers.push(e)}static assemblePayload(e){let t=this.payloadAssemblers.find((t=>t.support(e)));return t?t.assemble(e):e}static createLocalNotification(e,t,s,i,n){g.isBackend()&&(s.g=1,"undefined"!=typeof plus&&(i?(this.uniappPlugin&&this.uniappPlugin.playSound(i),plus.push.createMessage(t,JSON.stringify(s),{title:e,sound:"none"})):plus.push.createMessage(t,JSON.stringify(s),{title:e}),"+1"===n&&this.setClientBadge(he.badge+1)))}static setBadge(e){if(!Number.isInteger(e.badge)||e.badge<0)v.onFailed(e,"badge must be an integer greater than or equal to 0.");else if(he.supportAppNotification())if(this.uniappPlugin&&d.currentPlatform()===l.UNI_IOS){let t=new le({name:y.SET_IOS_BADGE,params:{badge:e.badge},unique:!0,singleTimeout:S.commonRequestSingle,totalTimeout:S.commonRequestTotal,permission:ne.WRITE,success:()=>{v.onSuccess(e),this.setClientBadge(e.badge)},fail:t=>{v.onFailed(e,t.content)}});te.Socket.e(t)}else v.onSuccess(e),this.setClientBadge(e.badge)}static setClientBadge(e){"vivo"!==plus.device.vendor&&(he.badge=e,plus.runtime.setBadgeNumber(e))}static askRegId(){let e=null,t=0;const s=()=>new Promise(((i,n)=>{this.uniappPlugin.regId((e=>{i(e)}),(i=>{if(!(1e6===i.data.code&&t<=10))return clearTimeout(e),n(i);e=setTimeout((()=>{t++,this.regIdPromise=s()}),3500)}))}));return s()}static getRegIdPromise(){return this.regIdPromise}static supportAppNotification(){const e=d.currentPlatform();return this.allowNotification&&(e===l.UNI_ANDROID||e===l.UNI_IOS)}static listenPlusClickNotification(){plus.push.addEventListener("click",(e=>{try{if(e){const t="string"==typeof e.payload?JSON.parse(e.payload):e.payload;if(this.availableIntent(t)){let e=this.assemblePayload(t);plus.push.clear(),this.onClickNotificationCallback(e)}}}catch(e){}}))}static availableIntent(e){return e&&Object.keys(e).length&&e.g&&1===parseInt(e.g)}static getIntentData(){this.uniappPlugin.getIntentData((e=>{if(!this.availableIntent(e))return;let t=this.assemblePayload(e);const s=d.currentPlatform();plus.push.clear(),s===l.UNI_ANDROID&&this.uniappPlugin.clearAll(),this.onClickNotificationCallback(t)}))}static listenClick(){this.listenPlusClickNotification();const e=d.currentPlatform();this.uniappPlugin&&e===l.UNI_ANDROID&&(this.getIntentData(),g.onFrontend((()=>{this.getIntentData()})))}static onClickNotification(e){if(he.supportAppNotification()){if(!u.isFunction(e))throw new Error("The arguments must be a function.");null===this.onClickNotificationCallback?(this.onClickNotificationCallback=e,this.listenClick()):console.warn("The onClickNotification event has been listened on. Please do not listen to it more than once.")}else console.warn("The current environment doesn't support or allowNotification is false.")}}function pe(e){if(null===e||"object"!=typeof e||"isActiveClone"in e)return e;let t=e instanceof Array?[]:{};for(let s in e)"object"==typeof e[s]?t[s]=pe(e[s]):t[s]=e[s];return t}function me(e){return{lang:e?.lang??re?.lang,message:e?.message,abortEarly:e?.abortEarly??re?.abortEarly,abortPipeEarly:e?.abortPipeEarly??re?.abortPipeEarly}}function fe(e){const t=typeof e;return"string"===t?`"${e}"`:"number"===t||"bigint"===t||"boolean"===t?`${e}`:"object"===t||"function"===t?(e&&Object.getPrototypeOf(e)?.constructor?.name)??"null":t}function ge(e,t,s,i,n){const o=n&&"input"in n?n.input:s.value,r=n?.expected??e.expects??null,a=n?.received??fe(o),c={kind:e.kind,type:e.type,input:o,expected:r,received:a,message:`Invalid ${t}: ${r?`Expected ${r} but r`:"R"}eceived ${a}`,requirement:e.requirement,path:n?.path,issues:n?.issues,lang:i.lang,abortEarly:i.abortEarly,abortPipeEarly:i.abortPipeEarly},u="schema"===e.kind,l=n?.message??e.message??(d=e.reference,h=c.lang,ue?.get(d)?.get(h))??(u?function(e){return ce?.get(e)}(c.lang):null)??i.message??function(e){return ae?.get(e)}(c.lang);var d,h;void 0!==l&&(c.message="function"==typeof l?l(c):l),u&&(s.typed=!1),s.issues?s.issues.push(c):s.issues=[c]}function ye(e){return{version:1,vendor:"valibot",validate:t=>e["~run"]({value:t},me())}}function Se(e,t){const s=[...new Set(e)];return s.length>1?`(${s.join(` ${t} `)})`:s[0]??"never"}he.uniappPlugin=null,he.v=null,he.regIdPromise=null,he.onClickNotificationCallback=null,he.payloadAssemblers=new Array;var Ee,ve=class extends Error{constructor(e){super(e[0].message),this.name="ValiError",this.issues=e}};function be(e,t){return{kind:"validation",type:"max_length",reference:be,async:!1,expects:`<=${e}`,requirement:e,message:t,"~run"(e,t){return e.typed&&e.value.length>this.requirement&&ge(this,"length",e,t,{received:`${e.value.length}`}),e}}}function Ce(e){return{kind:"validation",type:"non_empty",reference:Ce,async:!1,expects:"!0",message:e,"~run"(e,t){return e.typed&&0===e.value.length&&ge(this,"length",e,t,{received:"0"}),e}}}function Me(e,t,s){return{kind:"validation",type:"partial_check",reference:Me,async:!1,expects:null,paths:e,requirement:t,message:s,"~run"(t,s){return!t.typed&&!function(e,t){if(e.issues)for(const s of t)for(const t of e.issues){let e=!1;const i=Math.min(s.length,t.path?.length??0);for(let n=0;n<i;n++)if(s[n]!==t.path[n].key&&("$"!==s[n]||"array"!==t.path[n].type)){e=!0;break}if(!e)return!1}return!0}(t,e)||this.requirement(t.value)||ge(this,"input",t,s),t}}}function we(e,t,s){return"function"==typeof e.fallback?e.fallback(t,s):e.fallback}function Ie(e,t){return{...e,"~run"(s,i){const n=s.issues&&[...s.issues];if((s=e["~run"](s,i)).issues)for(const e of s.issues)if(!n?.includes(e)){let i=s.value;for(const s of t){const t=i[s],n={type:"unknown",origin:"value",input:i,key:s,value:t};if(e.path?e.path.push(n):e.path=[n],!t)break;i=t}}return s}}}function Ne(e,t,s){return"function"==typeof e.default?e.default(t,s):e.default}function Te(){return{kind:"schema",type:"any",reference:Te,expects:"any",async:!1,get"~standard"(){return ye(this)},"~run":e=>(e.typed=!0,e)}}function Re(e,t){return{kind:"schema",type:"array",reference:Re,expects:"Array",async:!1,item:e,message:t,get"~standard"(){return ye(this)},"~run"(e,t){const s=e.value;if(Array.isArray(s)){e.typed=!0,e.value=[];for(let i=0;i<s.length;i++){const n=s[i],o=this.item["~run"]({value:n},t);if(o.issues){const r={type:"array",origin:"value",input:s,key:i,value:n};for(const t of o.issues)t.path?t.path.unshift(r):t.path=[r],e.issues?.push(t);if(e.issues||(e.issues=o.issues),t.abortEarly){e.typed=!1;break}}o.typed||(e.typed=!1),e.value.push(o.value)}}else ge(this,"type",e,t);return e}}}function ke(e){return{kind:"schema",type:"boolean",reference:ke,expects:"boolean",async:!1,message:e,get"~standard"(){return ye(this)},"~run"(e,t){return"boolean"==typeof e.value?e.typed=!0:ge(this,"type",e,t),e}}}function Ae(e,t){return{kind:"schema",type:"custom",reference:Ae,expects:"unknown",async:!1,check:e,message:t,get"~standard"(){return ye(this)},"~run"(e,t){return this.check(e.value)?e.typed=!0:ge(this,"type",e,t),e}}}function Oe(e){return{kind:"schema",type:"function",reference:Oe,expects:"Function",async:!1,message:e,get"~standard"(){return ye(this)},"~run"(e,t){return"function"==typeof e.value?e.typed=!0:ge(this,"type",e,t),e}}}function Pe(e,t){return{kind:"schema",type:"instance",reference:Pe,expects:e.name,async:!1,class:e,message:t,get"~standard"(){return ye(this)},"~run"(e,t){return e.value instanceof this.class?e.typed=!0:ge(this,"type",e,t),e}}}function _e(e,t){return{kind:"schema",type:"literal",reference:_e,expects:fe(e),async:!1,literal:e,message:t,get"~standard"(){return ye(this)},"~run"(e,t){return e.value===this.literal?e.typed=!0:ge(this,"type",e,t),e}}}function De(e){return{kind:"schema",type:"number",reference:De,expects:"number",async:!1,message:e,get"~standard"(){return ye(this)},"~run"(e,t){return"number"!=typeof e.value||isNaN(e.value)?ge(this,"type",e,t):e.typed=!0,e}}}function xe(e,t){return{kind:"schema",type:"object",reference:xe,expects:"Object",async:!1,entries:e,message:t,get"~standard"(){return ye(this)},"~run"(e,t){const s=e.value;if(s&&"object"==typeof s){e.typed=!0,e.value={};for(const i in this.entries){const n=this.entries[i];if(i in s||("exact_optional"===n.type||"optional"===n.type||"nullish"===n.type)&&void 0!==n.default){const o=i in s?s[i]:Ne(n),r=n["~run"]({value:o},t);if(r.issues){const n={type:"object",origin:"value",input:s,key:i,value:o};for(const t of r.issues)t.path?t.path.unshift(n):t.path=[n],e.issues?.push(t);if(e.issues||(e.issues=r.issues),t.abortEarly){e.typed=!1;break}}r.typed||(e.typed=!1),e.value[i]=r.value}else if(void 0!==n.fallback)e.value[i]=we(n);else if("exact_optional"!==n.type&&"optional"!==n.type&&"nullish"!==n.type&&(ge(this,"key",e,t,{input:void 0,expected:`"${i}"`,path:[{type:"object",origin:"key",input:s,key:i,value:s[i]}]}),t.abortEarly))break}}else ge(this,"type",e,t);return e}}}function Ue(e,t){return{kind:"schema",type:"optional",reference:Ue,expects:`(${e.expects} | undefined)`,async:!1,wrapped:e,default:t,get"~standard"(){return ye(this)},"~run"(e,t){return void 0===e.value&&(void 0!==this.default&&(e.value=Ne(this,e,t)),void 0===e.value)?(e.typed=!0,e):this.wrapped["~run"](e,t)}}}function Ge(e,t){return{kind:"schema",type:"picklist",reference:Ge,expects:Se(e.map(fe),"|"),async:!1,options:e,message:t,get"~standard"(){return ye(this)},"~run"(e,t){return this.options.includes(e.value)?e.typed=!0:ge(this,"type",e,t),e}}}function Fe(e){return{kind:"schema",type:"string",reference:Fe,expects:"string",async:!1,message:e,get"~standard"(){return ye(this)},"~run"(e,t){return"string"==typeof e.value?e.typed=!0:ge(this,"type",e,t),e}}}function Le(e){let t;if(e)for(const s of e)t?t.push(...s.issues):t=s.issues;return t}function Be(e,t){return{kind:"schema",type:"union",reference:Be,expects:Se(e.map((e=>e.expects)),"|"),async:!1,options:e,message:t,get"~standard"(){return ye(this)},"~run"(e,t){let s,i,n;for(const o of this.options){const r=o["~run"]({value:e.value},t);if(r.typed){if(!r.issues){s=r;break}i?i.push(r):i=[r]}else n?n.push(r):n=[r]}if(s)return s;if(i){if(1===i.length)return i[0];ge(this,"type",e,t,{issues:Le(i)}),e.typed=!0}else{if(1===n?.length)return n[0];ge(this,"type",e,t,{issues:Le(n)})}return e}}}function qe(...e){return{...e[0],pipe:e,get"~standard"(){return ye(this)},"~run"(t,s){for(const i of e)if("metadata"!==i.kind){if(t.issues&&("schema"===i.kind||"transformation"===i.kind)){t.typed=!1;break}t.issues&&(s.abortEarly||s.abortPipeEarly)||(t=i["~run"](t,s))}return t}}}!function(e){e.TEXT="text",e.IMAGE="image",e.FILE="file",e.VIDEO="video",e.AUDIO="audio"}(Ee||(Ee={}));class je{constructor(e,t,s){this.scene=e,this.id=t,u.isDef(s)&&(this.teamId=s)}toString(){return o.PRIVATE===this.scene||o.GROUP===this.scene?this.scene+"#"+this.id:this.scene+"#"+this.id+"#"+this.teamId}customerId(){if(o.CS===this.scene)return this.id===this.teamId?te.Socket.user().id:this.id}static byScene(e,t,s){return new je(e,t,s)}static byIMMessage(e){let t,s,i=e.scene();if(i===o.PRIVATE){let t=e.senderId,i=e.targetId();s=te.Socket.user().id===t?i:t}else if(i===o.GROUP)s=e.targetId();else{if(i!==o.CS)throw{code:400,content:`scene ${i} not exists`};s=e.targetId(),t=e.teamId}return new je(i,s,t)}static byMessageReadRemoteEvent(e){let t,s=e.scene,i=e.targetId,n=e.markerId,r=e.teamId;return s===o.PRIVATE?t=te.Socket.user().id===n?i:n:s===o.GROUP?t=i:s===o.CS&&(t=i===r?n===te.Socket.user().id?r:n:n===te.Socket.user().id?i:r),new je(s,t,r)}static byIMMessageDeletedEvent(e){let t=e.scene,s=e.deleterId;if(t===o.PRIVATE){let i=te.Socket.user().id===s?e.targetId:s;return new je(t,i)}if(t===o.GROUP)return new je(t,e.targetId)}static byConversationDTO(e){let t=e.lastMessage;return this.byIMMessage(t)}static byConversationId(e,t){let s;if(e===o.PRIVATE){let e=t.split(":",2);s=e[0]===te.Socket.user().id?e[1]:e[0]}else s=t;return new je(e,s)}}class Ve{clearUseLessAttribute(){delete this.buildOptions}isOtherSent(){return this.senderId!==te.Socket.user().id}}class He extends Ve{constructor(){super(...arguments),this.read=!1}scene(){return o.PRIVATE}targetId(){return this.receiverId}}class ze extends Ve{scene(){return o.GROUP}targetId(){return this.groupId}}class We extends Ve{constructor(){super(...arguments),this.accepted=!1}scene(){return o.CS}targetId(){return te.Socket.user().id===this.customerId()?this.teamId:this.customerId()}sendByCustomer(){return this.to===this.teamId}customerId(){return this.sendByCustomer()?this.senderId:this.to}isOtherSent(){return te.Socket.user().id===this.customerId()?this.senderId!==te.Socket.user().id:this.senderId===this.customerId()}}const Je={maxString:e=>qe(Fe(),Ce(),be(e)),nonEmptyString:qe(Fe(),Ce()),object:Ae((e=>"object"==typeof e&&null!==e&&!Array.isArray(e)),"must be an object."),userId:qe(Fe(),Ce(),be(60),Ae((e=>{if(te.Socket.user().id===e)throw new Error("id can not be the same as your id");return e}))),sceneType:qe(Fe(),Ge([o.PRIVATE,o.GROUP,o.CS]))},Xe={onSuccess:Ue(Oe()),onFailed:Ue(Oe())},$e=xe({appkey:Je.nonEmptyString,host:Je.nonEmptyString,modules:Re(Je.nonEmptyString),allowNotification:Ue(ke()),forceTLS:Ue(ke()),supportOldBrowser:Ue(ke()),reactNativeOptions:Ue(xe({platform:Te(),asyncStorage:Te()})),customProvider:Ue(xe({loadConversations:Oe(),loadHistory:Oe()}))}),Ye=qe(xe(Object.assign({id:Ue(Je.nonEmptyString),data:Ue(Je.object),otp:Ue(Je.nonEmptyString),wxmpId:Ue(xe({appid:Je.nonEmptyString,openid:Je.nonEmptyString})),onProgress:Ue(Oe())},Xe)),Ie(Me([["id"],["data"]],(e=>!X.modules.get("GIM")||e.id&&e.data),"id and data are required for IM module"),["data"])),Qe=xe({id:Je.userId,data:Je.object}),Ke=qe(Be([xe({type:Je.sceneType,id:Je.userId,data:Je.object}),xe({type:Je.sceneType,receivers:Re(Qe)})]),Ae((e=>{if(!e.receivers)return!0;const t=e.receivers.map((e=>e.id));if(Array.from(new Set(t)).length<t.length)throw new Error("receivers cannot have duplicate ids");if(e.type===o.PRIVATE&&e.receivers.length>200)throw new Error("private message cannot have more than 200 receivers");if(e.type===o.GROUP&&e.receivers.length>3)throw new Error("group message cannot have more than 3 receivers");return!0}))),Ze=Ue(xe({template_id:Fe(),url:Ue(Fe()),miniprogram:Ue(xe({appid:Fe(),pagepath:Fe()})),data:Je.object})),et=Ue(xe({title:Je.maxString(32),body:Je.maxString(50),sound:Ue(Fe()),badge:Ue(Fe()),vendorOptions:Ue(xe({huawei:Ue(xe({category:Fe()})),xiaomi:Ue(xe({channel_id:Fe()})),oppo:Ue(xe({channel_id:Fe()})),vivo:Ue(xe({classification:De(),category:Fe()}))}))})),st={image:["gif","jpg","png","jpeg"],video:["avi","mov","rmvb","rm","flv","mp4","3gp","quicktime"],audio:["mp3","ogg","wav","wma","ape","acc","mpeg"]},it=(e=30,t)=>qe(Te(),Ce(),Ae((s=>{var i;if(s.size&&s.size>1024*e*1024)throw new Error(`File size must be <= ${e}MB.`);if(t){const e=s.type||s.tempFile&&s.tempFile.type;if(!e)return!0;const n=null===(i=e.split("/")[1])||void 0===i?void 0:i.toLowerCase();if(n&&!st[t].includes(n))throw new Error(`Only ${st[t].join(",")} is supported for ${t}.`)}return!0})));function nt(e){return xe(Object.assign(Object.assign(Object.assign({},e),{to:Ke,notification:et,wxmpTemplateMsg:Ze,beforeSend:Ue(Oe()),onProgress:Ue(Oe())}),Xe))}const ot=function e(t,s,i){return{kind:"schema",type:"variant",reference:e,expects:"Object",async:!1,key:t,options:s,message:i,get"~standard"(){return ye(this)},"~run"(e,t){const s=e.value;if(s&&"object"==typeof s){let i,n=0,o=this.key,r=[];const a=(e,c)=>{for(const u of e.options){if("variant"===u.type)a(u,new Set(c).add(u.key));else{let e=!0,a=0;for(const i of c){const c=u.entries[i];if(i in s?c["~run"]({typed:!1,value:s[i]},t).issues:"exact_optional"!==c.type&&"optional"!==c.type&&"nullish"!==c.type){e=!1,o!==i&&(n<a||n===a&&i in s&&!(o in s))&&(n=a,o=i,r=[]),o===i&&r.push(u.entries[i].expects);break}a++}if(e){const e=u["~run"]({value:s},t);(!i||!i.typed&&e.typed)&&(i=e)}}if(i&&!i.issues)break}};if(a(this,new Set([this.key])),i)return i;ge(this,"type",e,t,{input:s[o],expected:Se(r,"|"),path:[{type:"object",origin:"value",input:s,key:o,value:s[o]}]})}else ge(this,"type",e,t);return e}}}("type",[nt({type:_e(Ee.TEXT),text:Je.maxString(2500)}),nt({type:_e(Ee.IMAGE),file:it(30,"image")}),nt({type:_e(Ee.VIDEO),file:it(30,"video")}),nt({type:_e(Ee.AUDIO),file:it(30,"audio")}),nt({type:_e(Ee.FILE),file:it(500)}),nt({type:Fe(),payload:Be([Je.maxString(2500),Je.object])})]),rt=xe(Object.assign({messages:qe(Re(Be([Pe(He),Pe(ze)])),Ce(),be(20),Ae((e=>{const t=je.byIMMessage(e[0]);for(let s=1;s<e.length;s++){const i=je.byIMMessage(e[s]);if(i.scene!==t.scene||i.id!==t.id)throw new Error("each message must be from the same friend or group");const n=e[s];if(n.status!==r.SUCCESS)throw new Error(`message[${s}] is '${n.status}' and cannot be recalled`);if(n.recalled)throw new Error(`message[${s}] has been recalled`);if(n.senderId!==te.Socket.user().id)throw new Error("it is not allowed to recall messages sent by others")}return!0})))},Xe)),at=xe(Object.assign({messages:qe(Re(Be([Pe(He),Pe(ze),Pe(We)])),Ce(),be(20),Ae((e=>{const t=je.byIMMessage(e[0]);for(let s=1;s<e.length;s++){const i=je.byIMMessage(e[s]);if(i.scene!==t.scene||i.id!==t.id)throw new Error("each message must be from the same friend or group");const n=e[s];if(n.status===r.SENDING)throw new Error(`message[${s}] is '${n.status}' and cannot be deleted`)}return!0})))},Xe)),ct=e=>qe(Fe(),Ce(),Ae((t=>{if(!t)throw new Error(`${e} is required.`);return t}))),ut=ct("customId"),lt=ct("id"),dt=xe({userId:Je.nonEmptyString}),ht=xe({groupId:Je.nonEmptyString}),pt=xe({type:Je.sceneType,id:Je.nonEmptyString}),mt=Be([dt,ht,pt]),ft=xe({customer:Qe}),gt=xe({customerId:Je.nonEmptyString,agentId:Je.nonEmptyString}),yt=qe(Be([Fe(),De()]),Ae((e=>{if(!e&&0!==e)throw new Error("param require string or number.");return!0}))),St=(e=100)=>qe(Re(yt),Ce(),be(e),Ae((e=>{if(e.some((e=>0===e.length)))throw new Error("array has empty item.");if(Array.from(new Set(e)).length<e.length)throw new Error("Duplicate element found in array");return!0}))),Et=xe(Object.assign({channel:yt,message:Je.maxString(2500),qos:Ue(Ge([0,1])),notification:et,wxmpTemplateMsg:Ze,accessToken:Ue(Fe())},Xe)),vt=qe(xe({channel:Ue(yt),channels:Ue(St(100)),presence:Ue(xe({enable:ke()})),accessToken:Ue(Fe()),onMessage:Oe()}),Ie(Me([["channel"],["channels"]],(e=>!e.channel!=!e.channels),"Must provide either channel or channels, but not both or neither"),["channels"]),Ie(Me([["channel"],["presence"]],(e=>{var t;return!(null===(t=e.presence)||void 0===t?void 0:t.enable)||!!te.Socket.user().id}),"Subscription failed. If presence is enable, the id must be specified when calling the connect method"),["presence"])),bt=xe({userIds:St(100)}),Ct=xe({groupIds:St(100)}),Mt=xe({channel:yt}),wt=xe({channel:yt,membersLimit:Ue(qe(De(),function e(t,s){return{kind:"validation",type:"max_value",reference:e,async:!1,expects:`<=${t instanceof Date?t.toJSON():fe(t)}`,requirement:t,message:s,"~run"(e,t){return!e.typed||e.value<=this.requirement||ge(this,"value",e,t,{received:e.value instanceof Date?e.value.toJSON():fe(e.value)}),e}}}(100))),onPresence:Oe()}),It=xe({groupId:yt});function Nt(e,t){var s;try{return function(e,t,s){const i=e["~run"]({value:t},me(s));if(i.issues)throw new ve(i.issues);return i.value}(e,t)}catch(e){if(e instanceof ve){const t=e.issues[0],i=null===(s=t.path)||void 0===s?void 0:s.map((e=>e.key)).filter(Boolean),n=(null==i?void 0:i.join("."))||"value";throw{code:400,content:{string:`TypeError: ${n} must be a string.`,number:`TypeError: ${n} must be a number.`,non_empty:`${n} cannot be empty.`,max_length:`${n} over max length.`,picklist:`${n} has invalid value.`}[t.type]||`${n}: ${t.message}`}}throw e}}const Tt=e=>Nt(ut,e),Rt=e=>Nt(lt,e),kt=e=>Nt(dt,e),At=e=>Nt(ht,e),Ot=e=>Nt(bt,e),Pt=e=>Nt(Ct,e),_t=e=>Nt(Mt,e);class Dt{publish(e){Nt(Et,e),e.channel=e.channel.toString();let t={channel:e.channel,content:e.message,nt:e.notification,at:e.accessToken,guid:ie.get(),q:e.qos};e.wxmpTemplateMsg&&(t.wxmpTemplateMsg=pe(e.wxmpTemplateMsg),t.wxmpTemplateMsg.data=JSON.stringify(t.wxmpTemplateMsg.data));let s=new le({name:y.publish,params:t,unique:!0,singleTimeout:S.commonRequestSingle,totalTimeout:S.commonRequestTotal,permission:ne.WRITE,success:function(t){v.onSuccess(e,{code:200,content:"ok"})},fail:function(t){v.onFailed(e,{code:t.resultCode,content:t.content})}});te.Socket.e(s)}}class xt{constructor(e){if(this.options=e,this.channels=e.channels||[e.channel],!u.isEmpty(e.channel)){let t=e.channel.toString();this.channels=[t]}u.isEmpty(e.channels)||(this.channels=e.channels.toString().split(","))}}var Ut,Gt,Ft;!function(e){e.message="message",e.imMessage="imMessage",e.IM_MSG_SYNC="im:msg:sync",e.IM_MSG_NEW="im:msg:new",e.userPresence="userPresence",e.groupPresence="groupPresence",e.PS_PRESENCE_EVENT="PS_PRESENCE_EVENT",e.IM_MSG_READ="IM_MSG_READ",e.IM_MSG_DELETED="IM_MSG_DELETED",e.IM_MSG_RECALLED="IM_MSG_RECALLED",e.CS_ONLINE_CHANGED="CS_ONLINE_CHANGED"}(Ut||(Ut={})),function(e){e.CONNECTED="CONNECTED",e.RECONNECTED="RECONNECTED",e.DISCONNECTED="DISCONNECTED",e.LOST="LOST",e.EXPIRED_RECONNECTED="EXPIRED_RECONNECTED",e.NEW_MESSAGE="NEW_MESSAGE",e.CONNECTING="CONNECTING"}(Gt||(Gt={}));class Lt{constructor(){this.subscriptions=[],te.Socket.onMessage(Ut.message,this.onNewMessage.bind(this)),te.Socket.on(Gt.EXPIRED_RECONNECTED,this.expiredResubscribe.bind(this)),te.Socket.on(Gt.RECONNECTED,this.resubscribePresenceChannel.bind(this))}expiredResubscribe(){this.subscriptions.forEach((e=>{this.doSubscribe(e,!1)}))}resubscribePresenceChannel(){this.subscriptions.forEach((e=>{let t=e.options;t.presence&&t.presence.enable&&this.doSubscribe(e,!0)}))}onNewMessage(e){if(e.n.indexOf("_presence")>-1)return;e.a&&te.Socket.sendAck("ack",{i:e.i,c:e.n});let t={time:e.t,channel:e.n,content:e.c};this.createNotification(e),this.findSubscriptionByChannel(t.channel).options.onMessage(t)}createNotification(e){const t=te.N.supportAppNotification();if(!u.isObject(e.nt)||!t)return;const s={ch:e.n,ctt:e.c};te.N.createLocalNotification(e.nt.t,e.nt.c,s,e.nt.sound,e.nt.badge)}subscribe(e){Nt(vt,e);let t=new xt(e);this.doSubscribe(t,!1).then((()=>{this.subscriptions.push(t),v.onSuccess(e,{code:200,content:"ok"})})).catch((t=>{v.onFailed(e,{code:t.resultCode,content:t.content})}))}doSubscribe(e,t){let s=e.options;return new Promise(((i,n)=>{let o=new le({name:y.subscribe,permission:ne.READ,singleTimeout:S.commonRequestSingle,totalTimeout:S.commonRequestTotal,params:{channels:e.channels,accessToken:s.accessToken,presence:s.presence,resubscribe:t},success:()=>{i()},fail:e=>{n(e)}});te.Socket.e(o)}))}unsubscribe(e){_t(e),e.channel=e.channel.toString();const t=this.findSubscriptionByChannel(e.channel);if(!t)return void e.onFailed({code:400,content:"channel["+e.channel+"] is not subscribed"});let s=new le({name:y.unsubscribe,params:{channel:e.channel,presence:t.options.presence},permission:ne.READ,singleTimeout:S.commonRequestSingle,totalTimeout:S.commonRequestTotal,success:()=>{e.onSuccess({code:200,content:"ok"}),this.removeChannel(e.channel)},fail:function(t){e.onFailed({code:t.resultCode,content:t.content})}});te.Socket.e(s)}removeChannel(e){for(let t=this.subscriptions.length-1;t>=0;t--){const s=this.subscriptions[t].channels,i=s.indexOf(e);if(i>-1){s.splice(i,1),0===s.length&&this.subscriptions.splice(t,1);break}}}findSubscriptionByChannel(e){let t=!1,s=null;for(let i=this.subscriptions.length-1;i>=0;i--){let n=this.subscriptions[i].channels;for(let o=0;o<n.length;o++)if(n[o]==e){t=!0,s=this.subscriptions[i];break}if(t)break}return s}}class Bt{get(e){_t(e),e.channel=e.channel.toString();let t=new le({name:y.historyMessages,permission:ne.READ,params:e,singleTimeout:S.commonQuerySingle,totalTimeout:S.commonQueryTotal,success:t=>{v.onSuccess(e,{code:t.resultCode||t.code||200,content:t.content})},fail:t=>{v.onFailed(e,{code:t.resultCode||t.code,content:t.content})}});te.Socket.e(t)}}class qt{constructor(){this.channelPresenceMap=new Map,this.onPresenceEvent=e=>{let t=this.channelPresenceMap.get(e.channel);null==t||t.onPresence(e)},this.expireAllChannelPresences=()=>{this.channelPresenceMap.forEach(((e,t)=>{e.expire()}))},this.resubscribe=()=>{this.channelPresenceMap.forEach(((e,t)=>{e.subscribed()&&e.doSubscribe()}))},te.Socket.on(Gt.LOST,this.expireAllChannelPresences),te.Socket.on(Gt.RECONNECTED,this.resubscribe),te.Socket.onMessage(Ut.PS_PRESENCE_EVENT,this.onPresenceEvent)}hereNow(e){_t(e);let t,s=this.channelPresenceMap.get(e.channel.toString());s&&s.queryPromise?(e.limit&&e.limit>s.membersLimit&&s.doQuery(e.limit),t=s.queryPromise):t=Vt(e.channel,e.limit),t.then((t=>{e.onSuccess(t)})).catch((t=>{e.onFailed(t)}))}subscribe(e){Nt(wt,e);let t=e.channel.toString(),s=this.channelPresenceMap.get(t);s||(s=new jt(t),this.channelPresenceMap.set(t,s)),s.subscribe(e)}unsubscribe(e){_t(e);let t=e.channel.toString();if(this.channelPresenceMap.get(t)){let s=new le({name:y.PUBSUB_PRESENCE_UNSUBSCRIBE,permission:ne.READ,singleTimeout:S.commonRequestSingle,totalTimeout:S.commonRequestTotal,params:{channel:t},success:s=>{this.channelPresenceMap.delete(t),e.onSuccess()},fail:t=>{e.onFailed(t)}});te.Socket.e(s)}else e.onSuccess()}}class jt{constructor(e){this.membersLimit=10,this.queried=!1,this.channel=e}onPresence(e){return b(this,void 0,void 0,(function*(){this.queried?this.update(e):yield this.queryPromise,this.on({channel:this.channel,action:e.action,member:e.member,time:e.time,amount:this.amount,members:this.membersByLimit()})}))}membersByLimit(){return this.members.slice(0,this.membersLimit)}subscribe(e){return b(this,void 0,void 0,(function*(){if(e.membersLimit&&(this.membersLimit=Math.min(e.membersLimit,300)),!this.subscribed())try{yield this.doSubscribe()}catch(t){return void e.onFailed(t)}this.on=e.onPresence,e.onSuccess()}))}doSubscribe(){return this.doQuery(this.membersLimit),new Promise(((e,t)=>{let s=new le({name:y.PUBSUB_PRESENCE_SUBSCRIBE,permission:ne.READ,params:{channel:this.channel},singleTimeout:S.commonRequestSingle,totalTimeout:S.commonRequestTotal,success:t=>{e()},fail:e=>{t(e)}});te.Socket.e(s)}))}doQuery(e){this.queryPromise=Vt(this.channel,e),this.queryPromise.then((e=>{this.members=e.content.members,this.amount=e.content.amount,this.queried=!0})).catch((e=>{throw e}))}update(e){if(["join","back"].includes(e.action))this.members.unshift(e.member);else if(["leave","timeout"].includes(e.action)){let t=this.members.findIndex((t=>t.id===e.member.id));t>-1&&this.members.splice(t,1)}this.amount=e.amount}expire(){this.queried=!1,this.queryPromise=null}subscribed(){return void 0!==this.on}}function Vt(e,t){return t||(t=10),new Promise(((s,i)=>{let n={channel:e,limit:t},o=new le({name:y.PUBSUB_PRESENCE_HERENOW,permission:ne.READ,params:n,singleTimeout:S.commonQuerySingle,totalTimeout:S.commonQueryTotal,success:e=>{s(e)},fail:e=>{i(e)}});te.Socket.e(o)}))}class Ht{constructor(){this.publisher=new Dt,this.subscriber=new Lt,this.presence2=new qt,this.histories=new Bt}static init(){this.instance=new Ht}publish(e){this.publisher.publish(e)}subscribe(e){this.subscriber.subscribe(e)}unsubscribe(e){this.subscriber.unsubscribe(e)}subscribePresence(e){this.presence2.subscribe(e)}unsubscribePresence(e){this.presence2.unsubscribe(e)}history(e){this.histories.get(e)}hereNow(e){this.presence2.hereNow(e)}}class zt extends J{static init(){return this.module=new zt,this.module.name=this.GWS_MODULE_NAME,this.initGN(),this.module}static initGN(){he.addAssembler(new class{assemble(e){return{channel:e.ch,content:e.ctt}}support(e){return!!e.ch}})}postConnect(){Ht.init()}static check(){if(!this.module)throw{code:400,content:"PubSub not initialized. Please include 'PUBSUB' in the 'modules' during GoEasy initialization."}}}zt.GWS_MODULE_NAME="GWS";class Wt{constructor(){}}!function(e){e.aliYun="ALI",e.qiNiu="QN",e.tencent="TX",e.s3="S3"}(Ft||(Ft={}));let Jt=new class extends Wt{constructor(){super()}upload(e,t){try{return e.storageLocation===Ft.s3?this.uploadToS3(e,t):(delete e.parameters.fileRes,new Promise(((s,i)=>{uni.uploadFile({url:e.host,filePath:this.getTempFilePath(e),name:"file",formData:e.parameters,success(e){200===e.statusCode?s():i({code:e.statusCode,content:e.errMsg})},fail(e){i({code:500,content:e.errMsg})}}).onProgressUpdate((e=>{t&&t(e)}))})))}catch(e){return new Promise(((t,s)=>{s({code:500,content:e})}))}}getTempFilePath(e){let t=e.file;return t.tempFilePath||t.fullPath||t.path}uploadToS3(e,t){return new Promise(((t,s)=>b(this,void 0,void 0,(function*(){const i=yield this.fileToArrayBuffer(e);uni.request({url:e.url,method:"PUT",header:e.headers,data:i,success(i){200===i.statusCode?(e.storageLocation===Ft.s3&&(e.url=e.url.split("?")[0]),t()):s({code:i.statusCode,content:i.errMsg})},fail(e){s({code:500,content:e.errMsg})}})}))))}fileToArrayBuffer(e){return new Promise(((t,s)=>{const i=this.getTempFilePath(e);if("undefined"!=typeof plus)plus.io.resolveLocalFileSystemURL(i,(e=>{e.file((e=>{let i=new plus.io.FileReader;i.onloadend=e=>{const s=uni.base64ToArrayBuffer(e.target.result.split(",")[1]);t(s)},i.onerror=function(e){s(e)},i.readAsDataURL(e)}))}),(e=>{s("Resolve file URL failed: "+e.message)}));else if("undefined"!=typeof FileReader){const i=new FileReader;i.onload=()=>{t(i.result)},i.onerror=e=>{s(e)},i.readAsArrayBuffer(e.file)}else if("object"==typeof wx&&wx.canIUse("getFileSystemManager"))try{const e=wx.getFileSystemManager().readFileSync(i);t(e)}catch(e){s(e)}}))}};const Xt=new class extends Wt{upload(e,t){try{return e.storageLocation===Ft.s3?this.uploadToS3(e,t):new Promise(((s,i)=>{wx.uploadFile({url:e.host,filePath:this.getTempFilePath(e),name:"file",formData:e.parameters,success(e){200===e.statusCode?s():i({code:e.statusCode,content:e.errMsg})},fail(e){i({code:500,content:e.errMsg})}}).onProgressUpdate((e=>{t&&t(e)}))}))}catch(e){return new Promise(((t,s)=>{s({code:500,content:e})}))}}getTempFilePath(e){let t=e.file||e.fileRes;return t.path||t.tempFilePath}uploadToS3(e,t){return new Promise(((t,s)=>b(this,void 0,void 0,(function*(){const i=yield this.fileToArrayBuffer(this.getTempFilePath(e));wx.request({url:e.url,method:"PUT",header:e.headers,data:i,success(i){200===i.statusCode?(e.storageLocation===Ft.s3&&(e.url=e.url.split("?")[0]),t()):s({code:i.statusCode,content:i.errMsg})},fail(e){s({code:500,content:e.errMsg})}})}))))}fileToArrayBuffer(e){return new Promise(((t,s)=>{try{const s=wx.getFileSystemManager();t(s.readFileSync(e))}catch(e){s(e)}}))}};const $t=new class extends Wt{constructor(){super()}upload(e,t){return new Promise(((s,i)=>{try{const n=new XMLHttpRequest,o=e.storageLocation===Ft.s3,r=o?"PUT":"POST",a=o?e.url:e.host;n.open(r,a,!0);for(let t in e.headers)n.setRequestHeader(t,e.headers[t]);n.upload.onprogress=function(e){t&&t(e)},n.upload.onloadstart=function(e){t&&t(e)},n.upload.onloadend=function(e){t&&t(e)};let c=new FormData;for(let t in e.parameters)"fileRes"==t?c.append("file",e.parameters[t]):c.append(t,e.parameters[t]);const u=o?e.file:c;n.send(u),n.onreadystatechange=function(){4==n.readyState&&(n.status>=200&&n.status<300||304==n.status?(o&&(e.url=e.url.split("?")[0]),s()):i({code:n.status,content:n.responseText}))}}catch(e){i({code:500,content:e})}}))}fileToArrayBuffer(e){return new Promise(((t,s)=>{const i=new FileReader;i.onload=()=>{t(i.result)},i.onerror=e=>{s(e)},i.readAsArrayBuffer(e)}))}};const Yt=new class extends Wt{upload(e,t){try{return e.storageLocation===Ft.s3?this.uploadToS3(e,t):(delete e.parameters.fileRes,new Promise(((s,i)=>{my.uploadFile({url:e.host,filePath:this.getTempFilePath(e),fileType:"image",name:"file",formData:e.parameters,success(e){200===e.statusCode?s():i({code:e.statusCode,content:e.errMsg})},fail(e){i({code:500,content:e.errMsg})}}).onProgressUpdate((e=>{t&&t(e)}))})))}catch(e){return new Promise(((t,s)=>{s({code:500,content:e})}))}}getTempFilePath(e){let t=e.file;return t.path||t.tempFilePath}uploadToS3(e,t){return new Promise(((t,s)=>b(this,void 0,void 0,(function*(){const i=yield this.fileToArrayBuffer(this.getTempFilePath(e));my.request({url:e.url,method:"PUT",header:e.headers,data:i,success(i){200===i.statusCode?(e.storageLocation===Ft.s3&&(e.url=e.url.split("?")[0]),t()):s({code:i.statusCode,content:i.errMsg})},fail(e){s({code:500,content:e.errMsg})}})}))))}fileToArrayBuffer(e){return new Promise(((t,s)=>{my.getFileSystemManager().readFile({filePath:e,success:e=>{t(e.data)},fail(e){s(e)}})}))}};const Qt=new class extends Wt{upload(e,t){try{return e.storageLocation===Ft.s3?this.uploadToS3(e,t):(delete e.parameters.fileRes,new Promise(((s,i)=>{swan.uploadFile({url:e.host,filePath:this.getTempFilePath(e),name:"file",formData:e.parameters,success(e){200===e.statusCode?s():i({code:e.statusCode,content:e.errMsg})},fail(e){i({code:500,content:e.errMsg})}}).onProgressUpdate((e=>{t&&t(e)}))})))}catch(e){return new Promise(((t,s)=>{s({code:500,content:e})}))}}getTempFilePath(e){let t=e.file;return t.path||t.tempFilePath}uploadToS3(e,t){return new Promise(((t,s)=>b(this,void 0,void 0,(function*(){const i=yield this.fileToArrayBuffer(this.getTempFilePath(e));swan.request({url:e.url,method:"PUT",header:e.headers,data:i,success(i){200===i.statusCode?(e.storageLocation===Ft.s3&&(e.url=e.url.split("?")[0]),t()):s({code:i.statusCode,content:i.errMsg})},fail(e){s({code:500,content:e.errMsg})}})}))))}fileToArrayBuffer(e){return new Promise(((t,s)=>{swan.getFileSystemManager().readFile({filePath:e,success:e=>{t(e.data)},fail:e=>{s(e)}})}))}};class Kt{constructor(e,t,s){this.storageLocation=e,this.url=t,this.name=s}}const Zt=new class{constructor(){this.uploader={[e.UNIAPP]:Jt,[l.MP_WX]:Xt,[l.BROWSER]:$t,[l.MP_ALI]:Yt,[l.MP_BAIDU]:Qt,[e.REACT_NATIVE]:$t,[l.MP_BYTE]:Xt}}upload(t,i){return b(this,void 0,void 0,(function*(){const n=s.currentFramework(),o=d.currentPlatform(),r=n===e.UNKNOWN?o:n;let a=this.uploader[r];return yield a.upload(t,i),new Kt(t.storageLocation,t.url,t.newFileName)}))}};class es{resolve(e){return new Promise(((t,s)=>{let i=new le({name:"uploadToken",params:{filename:e},permission:ne.WRITE,singleTimeout:S.commonRequestSingle,totalTimeout:S.commonRequestTotal,fail(e){s(e.content)},success(e){200===e.code?t(e.content):s(e.content)}});te.Socket.e(i)}))}}class ts{constructor(e,t,s,i,n,o,r){this.storageLocation=e,this.host=t,this.headers=s,this.parameters=i,this.file=n,this.newFileName=o,this.url=r}}class ss{constructor(){}newFileName(e){return e&&e.newFilename||""}}let is=new class extends ss{constructor(){super()}url(e){return e.host+"/"+e.dir+"/"+this.newFileName(e)}build(e,t,s){let i,n=this.newFileName(e);return i={key:e.dir+"/"+n,OSSAccessKeyId:e.accessKeyId,policy:e.policy,signature:e.signature,success_action_status:"200",fileRes:t},s&&(i={key:e.dir+"/"+n,OSSAccessKeyId:e.accessKeyId,policy:e.policy,signature:e.signature,success_action_status:"200","Content-Disposition":"attachment;filename="+t.name,fileRes:t}),new ts(Ft.aliYun,e.host,null,i,t,n,this.url(e))}};let ns=new class extends ss{constructor(){super()}url(e){return e.host+"/"+e.key}build(e,t,s){let i={"q-sign-algorithm":e.qSignAlgorithm,"q-ak":e.qAk,"q-key-time":e.qKeyTime,"q-signature":e.qSignature,policy:e.policy,"x-cos-security-token":e.xCosSecurityToken,success_action_status:"200",key:e.key,fileRes:t};return s&&(i={"q-sign-algorithm":e.qSignAlgorithm,"q-ak":e.qAk,"q-key-time":e.qKeyTime,"q-signature":e.qSignature,policy:e.policy,"x-cos-security-token":e.xCosSecurityToken,success_action_status:"200",key:e.key,"Content-Disposition":`attachment;filename=${t.name}`,fileRes:t}),new ts(Ft.tencent,e.host,null,i,t,e.key,this.url(e))}};let os=new class extends ss{constructor(){super()}url(e){return e.uploadUrl}build(e,t,s){const i={file:t};return new ts(Ft.s3,null,{"Content-Type":"application/octet-stream"},i,t,t.name,this.url(e))}};class rs{constructor(){this.uploadTokenResolver=new es}builder(e){if(e===Ft.aliYun)return is;if(e===Ft.tencent)return ns;if(e===Ft.s3)return os;throw new Error("Only Ali OSS and Tencent COS are supported, unknown storage location:"+e)}build(e,t,s){return b(this,void 0,void 0,(function*(){try{let i=yield this.uploadTokenResolver.resolve(t),n=this.builder(i.vendor).build(i,e,s);return Promise.resolve(n)}catch(e){return Promise.reject(e)}}))}}class as{constructor(){this.requestBuilder=new rs,this.fileUploader=Zt}upload(e,t,s,i){return b(this,void 0,void 0,(function*(){try{let n=yield this.requestBuilder.build(e,t,i);return this.fileUploader.upload(n,s)}catch(e){return Promise.reject(e)}}))}}var cs,us,ls;!function(e){e.MESSAGE_SENDING="IM_INTERNAL_MESSAGE_SENDING",e.MESSAGE_SEND_SUCCESS="IM_INTERNAL_MESSAGE_SEND_SUCCESS",e.MESSAGE_SEND_FAILED="IM_INTERNAL_MESSAGE_SEND_FAILED",e.MESSAGE_RECEIVED="IM_INTERNAL_MESSAGE_RECEIVED",e.MESSAGE_RECALLED="IM_INTERNAL_MESSAGE_RECALLED",e.MAX_MESSAGE_CHANGED="IM_INTERNAL_MAX_MESSAGE_CHANGED",e.MAX_MESSAGE_DELETED="IM_INTERNAL_MAX_MESSAGE_DELETED",e.UNREAD_AMOUNT_CHANGED="IM_INTERNAL_UNREAD_MESSAGE_CHANGED",e.CS_ONLINE_SUCCESS="CS_ONLINE_SUCCESS",e.CS_OFFLINE_SUCCESS="CS_OFFLINE_SUCCESS",e.CS_ACCEPTED="CS_ACCEPTED",e.CS_ENDED="CS_ENDED",e.CS_TRANSFER="CS_TRANSFER",e.CS_AGENT_MESSAGE_RECEIVED="CS_AGENT_MESSAGE_RECEIVED"}(cs||(cs={}));class ds{}class hs extends ds{constructor(){super(...arguments),this.goEasyUploader=new as}improve(e){let t=e.message;return new Promise(((e,s)=>{let i,n,o=t.buildOptions.createOptions;t.type===Ee.VIDEO?(n=t.payload,i=n.video.name):(n=t.payload,i=n.name),this.goEasyUploader.upload(o.file,i,o.onProgress,t.type===Ee.FILE).then((s=>{s.storageLocation!==Ft.s3&&(s.url=encodeURI(s.url)),this.setPayload(s,t),e()})).catch((e=>{s(e)}))}))}setPayload(e,t){t.payload.url=e.url}}class ps extends hs{setPayload(e,t){let s,i=t.payload;switch(i.video.url=e.url,i.video.name=e.name,i.thumbnail.height>200&&(i.thumbnail.height=200,i.thumbnail.width=200*i.video.width/i.video.height),e.storageLocation){case Ft.aliYun:s="?x-oss-process=video/snapshot,t_0000,f_jpg,h_"+i.thumbnail.height+",m_fast,ar_auto";break;case Ft.tencent:s="?ci-process=snapshot&time=1&format=jpg&height="+i.thumbnail.height;break;case Ft.s3:s="?process=video&height="+i.thumbnail.height;break;default:throw new Error("Only Ali OSS and Tencent COS are supported, unknown storage location:"+e.storageLocation)}i.thumbnail.url=e.url+s}}class ms extends hs{setPayload(e,t){let s,i=t.payload;i.url=e.url;const n=i.height>200?200:i.height;switch(e.storageLocation){case Ft.aliYun:s="?x-oss-process=image/resize,m_lfit,h_"+n;break;case Ft.tencent:s=`?imageMogr2/thumbnail/x${n}`;break;case Ft.s3:s=`?process=image&height=${n}`;break;default:throw new Error("Only Ali OSS and Tencent COS are supported, unknown storage location:"+e.storageLocation)}i.thumbnail=e.url+s}}class fs{constructor(){this.improvers={[Ee.FILE]:new hs,[Ee.AUDIO]:new hs,[Ee.IMAGE]:new ms,[Ee.VIDEO]:new ps}}improve(e){let t=this.improvers[e.message.type];if(t)try{return t.improve(e)}catch(e){return Promise.reject(e)}return Promise.resolve()}}class gs extends Q{static init(){this.i=new gs}}class ys{constructor(e,t,s,i,n){this.validate(e),this.mt=e.type,"receivers"in t?this.receivers=t.receivers:(this.to=t.id,this.d=JSON.stringify(t.data)),this.p=JSON.stringify(e.payload),s&&(this.nt=s),n&&(this.at=n),i&&(this.wxmpTemplateMsg=pe(i),this.wxmpTemplateMsg.data=JSON.stringify(this.wxmpTemplateMsg.data));let r=t.type;if(this.t=r,r===o.CS){let t=e;this.tid=t.teamId}this.guid=e.messageId}validate(e){if(e.type===Ee.TEXT){if(JSON.stringify(e.payload).length>3072)throw Error("message-length limit 3kb")}}}class Ss{constructor(){this.payloadImprover=new fs}send(e){this.validate(e);let t=e.message,s=e.accessToken,i=t.buildOptions,n=i.createOptions,a=n.notification,c=n.wxmpTemplateMsg,u=n.to;t.status=r.SENDING;let l=i.complete,d=this.payloadImprover.improve(e);Promise.all([l,d]).then((()=>b(this,void 0,void 0,(function*(){if(n.beforeSend){const e=JSON.parse(JSON.stringify(t));yield n.beforeSend(e)}if("receivers"in n.to){const i=new Array;u.receivers.forEach((e=>{const s=Object.assign(Object.create(Object.getPrototypeOf(t)),t);u.type===o.PRIVATE?s.receiverId=e.id:u.type===o.GROUP&&(s.groupId=e.id),i.push(s);const n={message:s,receiver:e.data};gs.i.fire(cs.MESSAGE_SENDING,n)})),this.doSend(u,a,c,s,e,i,t)}else{const i={message:t,receiver:u.data};gs.i.fire(cs.MESSAGE_SENDING,i),this.doSend(u,a,c,s,e,[t])}})))).catch((s=>{t.status=r.FAIL,v.onFailed(e,{code:s&&s.code||400,content:s&&s.content||s})}))}doSend(e,t,s,i,n,a,c){let u=new ys(a[0],e,t,s,i),l=new le({name:y.publishIM,params:u,unique:!0,permission:ne.WRITE,singleTimeout:S.commonRequestSingle,totalTimeout:S.commonRequestTotal,fail:e=>{a.forEach((e=>{e.status=r.FAIL,gs.i.fire(cs.MESSAGE_SEND_FAILED,e)})),c&&(c.status=r.FAIL),v.onFailed(n,{code:e.resultCode,content:e.content})},success:e=>{a.forEach((t=>{if(t.status=r.SUCCESS,t.timestamp=e.content.timestamp,t.messageId=JSON.stringify(e.content.id),t.scene()===o.CS){let s=t;s.customerId()!==te.Socket.user().id&&(s.sessionId=e.content.sessionId)}t.clearUseLessAttribute(),gs.i.fire(cs.MESSAGE_SEND_SUCCESS,t)})),c&&(c.status=r.SUCCESS,c.timestamp=e.content.timestamp,c.messageId=JSON.stringify(e.content.id),c.clearUseLessAttribute()),v.onSuccess(n)}});te.Socket.e(l)}validate(e){let t=e.message;if(!(t instanceof Ve))throw new Error("it is invalid message");if(t.status!==r.NEW)throw new Error("Please create a new message, a message can only be sent once")}}class Es{insert(e,t){let s=this.binarySearch(e,t);if(s>=0)e.splice(s,1,t);else{let i=-s-1;e.splice(i,0,t)}}binarySearch(e,t){let s=0,i=e.length-1;for(;s<=i;){let n=i+s>>1,o=this.compare(t,e[n]);if(o>0)s=n+1;else{if(!(o<0))return n;i=n-1}}return-s-1}}class vs{constructor(e){this.messages=new Array,this.allLoaded=!1,this.target=e}all(){return this.messages}sliceOverLengthMessages(){this.messages.length>vs.CACHE_MAX_LENGTH&&(this.messages=this.messages.slice(-vs.CACHE_MAX_LENGTH),!0===this.allLoaded&&(this.allLoaded=!1))}getMaxMessage(){return this.messages[this.messages.length-1]}loadLocalMessages(e,t){let s=[],i=this.messages.length;if(t){if(i>0){let n=this.messages[0].timestamp,o=this.messages[i-1].timestamp;if(t>=n&&t<=o)for(let n=i-1;n>=0;n--){let i=this.messages[n];if(i.timestamp<t){if(!(s.length<e))break;s.unshift(i)}}}}else s=this.messages.slice(-e);return s}cacheServerMessages(e,t){let s=this.messages[0];this.messages.length<vs.CACHE_MAX_LENGTH&&(!e.lastTimestamp||this.messages.length>0&&s.timestamp===e.lastTimestamp)&&(t.forEach((e=>{vs.sortedInserter.insert(this.messages,e)})),t.length<e.limit&&(this.allLoaded=!0))}findMessageByTime(e){return this.messages.find((t=>e===t.timestamp))}findMessagesByTimes(e){let t=[];return e.forEach((e=>{let s=this.findMessageByTime(e);u.isDef(s)&&t.push(s)})),t}existsMessage(e){return this.findMessageIndexById(e)>-1}findMessageIndexById(e){return this.messages.findIndex((t=>e===t.messageId))}deleteMessage(e){let t=this.findMessageIndexById(e);t>=0&&this.messages.splice(t,1)}recallMessage(e){return e.times.map((e=>this.findMessageByTime(e))).filter((e=>u.isDef(e))).map((t=>(t.recalled=!0,t.recaller=e.recaller,t)))}isEmpty(){return 0===this.messages.length}deleteMessages(e){e.forEach((e=>{this.deleteMessage(e.messageId)}))}saveMessage(e){vs.sortedInserter.insert(this.messages,e),this.deleteGroupConversationMessage(),this.sliceOverLengthMessages()}deleteGroupConversationMessage(){this.target.scene===o.GROUP&&this.messages.length>=2&&1===this.messages[0].x&&this.messages.shift()}maxSuccessMessageTime(){for(let e=this.messages.length-1;e>=0;e--)if(this.messages[e].status===r.SUCCESS)return this.messages[e].timestamp;return 0}minTime(){return this.isEmpty()?0:this.messages[0].timestamp}correctPosition(e){this.deleteMessage(e.messageId),this.saveMessage(e)}}vs.CACHE_MAX_LENGTH=200,vs.sortedInserter=new class extends Es{compare(e,t){let s=e.timestamp-t.timestamp;return s>0?1:0===s?0:-1}};class bs{constructor(e){this.times=new Array;let t=e[0],s=je.byIMMessage(t);this.scene=s.scene,this.targetId=s.id,e.forEach((e=>{e.status===r.SUCCESS&&this.times.push(e.timestamp)})),this.times.sort(((e,t)=>e<t?-1:e==t?0:1))}}class Cs{static deleteServerMessages(e){let t=new bs(e);return t.times.length<0?Promise.resolve():new Promise(((e,s)=>{let i=new le({name:y.IM_DELETE_MESSAGE,params:t,permission:ne.WRITE,singleTimeout:S.commonQuerySingle,totalTimeout:S.commonQueryTotal,success:t=>{200===t.code?e(t):s(t)},fail:e=>{s(e)}});te.Socket.e(i)}))}}class Ms{constructor(e,t,s,i,n){this.scene=e,this.id=t,this.after=s,this.min=i,this.teamId=n}}class ws{constructor(e,t,s,i){this.id=e,this.scene=t,this.lastTimestamp=s,this.teamId=i}}!function(e){e.ACCEPT="CS_ACCEPT",e.END="CS_END",e.TRANSFER="CS_TRANSFER"}(us||(us={}));class Is{build(e){let t,s=e.t;s===o.PRIVATE?(t=new He,t.read=!1,e.r?t.receiverId=e.r:t.receiverId=te.Socket.user().id):s===o.GROUP?(t=new ze,t.groupId=e.r,t.senderData=e.d?JSON.parse(e.d):{}):s===o.CS&&(t=new We,t.to=e.r,t.teamId=e.tid,t.senderData=e.d?JSON.parse(e.d):{},t.accepted=e.accepted,t.customerId()!==te.Socket.user().id&&(t.sessionId=e.sessionId)),t.senderId=e.s,t.messageId=e.i,t.timestamp=e.ts,t.type=e.mt;let i=e.p;if(u.isDef(i))if(s===o.CS&&t.type===us.TRANSFER){let e=JSON.parse(i);e.transferTo.data=JSON.parse(e.transferTo.data),t.payload=e}else t.payload=JSON.parse(i);let n=e.rc;return u.isDef(n)&&!0===n?(t.recalled=n,t.recaller=e.recaller):t.recalled=!1,t.status=r.SUCCESS,t}}class Ns{constructor(){this.builder=new Is}sync(e,t,s,i,n){let o=new Ms(e,t,s,i,n);return new Promise(((e,t)=>{let s=new le({name:y.IM_HISTORY_CHANGE,params:o,permission:ne.READ,singleTimeout:S.commonQuerySingle,totalTimeout:S.commonQueryTotal,fail:e=>{t(e)},success:t=>{let s=t.content;e(s)}});te.Socket.e(s)}))}loadServerMessages(e,t){return new Promise(((s,i)=>{let n=new le({name:y.IM_HISTORY,params:t,permission:ne.READ,singleTimeout:S.commonQuerySingle,totalTimeout:S.commonQueryTotal,fail:e=>{s({messages:[],userOffsets:[]})},success:t=>{let i=t.content;i.messages=this.convertServerMessages(e,i.messages),s(i)}});te.Socket.e(n)}))}convertServerMessages(e,t){let s=[],i=e.scene,n=e.id;return t.forEach((t=>{if(t.t=i,o.PRIVATE===i)t.r=t.s===te.Socket.user().id?n:te.Socket.user().id;else if(o.GROUP===i)t.r=n;else if(o.CS===i){let s=e.customerId(),i=e.teamId;s===te.Socket.user().id?t.r=i:t.r=s}let r=this.builder.build(t);s.push(r)})),s}updateServerOffsets(e,t){return b(this,void 0,void 0,(function*(){let s=new ws(t.id,t.scene,e,t.teamId);return new Promise(((e,t)=>{let i=new le({name:y.IM_MARK_AS_READ,params:s,permission:ne.WRITE,singleTimeout:S.commonRequestSingle,totalTimeout:S.commonRequestTotal,success:t=>{e(t)},fail:e=>{t(e)}});te.Socket.e(i)}))}))}}Ns.instance=new Ns;class Ts{constructor(){this.offsetMap=new Map,this.markingTime=0,this.userId=te.Socket.user().id}updateOffset(e,t){let s=this.offsetMap.get(e);return u.isDef(s)?t>s&&(this.offsetMap.set(e,t),!0):(this.offsetMap.set(e,t),!0)}updateUserOffsets(e){e.forEach((e=>{let t=e.userId,s=e.offset;this.updateOffset(t,s)}))}updateMyOffset(e){return this.updateOffset(this.userId,e)}myOffset(){return this.getOffset(this.userId)}getOffset(e){let t=this.offsetMap.get(e);return t||0}}class Rs{constructor(e,t,s,i,n){this.id=e,this.scene=t,this.lastTimestamp=s,this.limit=i,this.teamId=n}}class ks{constructor(e){this.history=e}pre(){this.oldLastMessage=this.history.getMaxMessage(),this.oldUnreadAmount=this.history.unreadAmount(),this.oldLastMessage&&(this.oldLastMessageRecalled=this.oldLastMessage.recalled,this.oldLastMessageRead=this.oldLastMessage.read,this.oldLastMessageStatus=this.oldLastMessage.status)}post(){let e,t,s,i=this.history.unreadAmount(),n=this.history.getMaxMessage();n&&(s=n.status,e=n.read,t=n.recalled);let o=this.history.target;if(this.oldLastMessage!==n||this.oldLastMessageRead!==e||this.oldLastMessageRecalled!==t||this.oldLastMessageStatus!==s)if(n){const e={message:n,receiver:this.history.to};gs.i.fire(cs.MAX_MESSAGE_CHANGED,e)}else gs.i.fire(cs.MAX_MESSAGE_DELETED,o);else this.oldUnreadAmount!==i&&gs.i.fire(cs.UNREAD_AMOUNT_CHANGED,o)}}class As{constructor(e,t,s,i){this.scene=e,this.conversationId=t,this.recaller=s,this.times=i}}class Os{static init(){this.eventCenter=new ee}static on(e,t){this.eventCenter.on(e,t)}static fire(e,t){this.eventCenter.fire(e,t)}static off(e,t){this.eventCenter.off(e,t)}}!function(e){e.PRIVATE_MESSAGE_RECEIVED="PRIVATE_MESSAGE_RECEIVED",e.GROUP_MESSAGE_RECEIVED="GROUP_MESSAGE_RECEIVED",e.SYSTEM_MESSAGE_RECEIVED="SYSTEM_MESSAGE_RECEIVED",e.CONVERSATIONS_UPDATED="CONVERSATIONS_UPDATED",e.HISTORY_EXPIRED="HISTORY_EXPIRED",e.USER_PRESENCE="USER_PRESENCE",e.GROUP_PRESENCE="GROUP_PRESENCE",e.MESSAGE_DELETED="MESSAGE_DELETED",e.MESSAGE_READ="MESSAGE_READ",e.MESSAGE_RECALLED="MESSAGE_RECALLED",e.CS_MESSAGE_RECEIVED="CS_MESSAGE_RECEIVED",e.PENDING_CONVERSATIONS_UPDATED="PENDING_CONVERSATIONS_UPDATED"}(ls||(ls={}));class Ps{static init(e){Ps.instance=e}static loadCustomMessages(e,t,s){return b(this,void 0,void 0,(function*(){let i=t?t.messageId:"";return(yield this.instance.loadHistory(te.Socket.user().id,e.scene,e.id,i,s)).map((e=>this.convertAbstractMessage(e)))}))}static convertAbstractMessage(e){const t={type:e.type,timestamp:e.timestamp,senderId:e.senderId,messageId:e.messageId,payload:e.payload};if(e.groupId){const s=new ze;return s.groupId=e.groupId,s.senderData=e.senderData,Object.assign(s,Object.assign(Object.assign({},t),{recalled:!1,status:r.SUCCESS})),s}{const s=new He;return s.receiverId=e.receiverId,Object.assign(s,Object.assign(Object.assign({},t),{read:!0,recalled:!1,status:r.SUCCESS})),s}}}class _s{constructor(e){this.expiredTime=0,this.remoteHistory=Ns.instance,this.target=e,this.userOffsets=new Ts,this.messageCache=new vs(e)}initMaxMessageAndOffsets(e,t){this.existsMessage(e)||(this.messageCache.saveMessage(e),t.forEach((e=>{this.markLocalMessagesRead(this.messageCache.all(),e.userId,e.offset,!1)})))}existsMessage(e){return this.messageCache.existsMessage(e.messageId)}loadHistory(e,t){return b(this,void 0,void 0,(function*(){return this.expiredTime>0&&!this.messageCache.isEmpty()&&(yield this.updateByServerChange()),u.isUndef(t)?t=10:t>30&&(t=30),yield this.loadServerMessages(e,t)}))}loadCustomMessages(e,t,s){return b(this,void 0,void 0,(function*(){if(s>0&&void 0!==Ps.instance){let i=e;return t&&(i=this.messageCache.findMessageByTime(t)),yield Ps.loadCustomMessages(this.target,i,s)}return[]}))}loadServerMessages(e,t){return b(this,void 0,void 0,(function*(){let s=this.messageCache.loadLocalMessages(t,e);if(!1===this.messageCache.allLoaded&&s.length!==t){let i=t-s.length,n=s[0]?s[0].timestamp:e,o=new Rs(this.target.id.toString(),this.target.scene,n,i,this.target.teamId),r=yield this.remoteHistory.loadServerMessages(this.target,o),a=r.messages;s=a.concat(s);const c=yield this.loadCustomMessages(s[0],e,t-s.length);a=a.concat(c),s=[...c,...s],this.messageCache.cacheServerMessages(o,a),r.userOffsets.forEach((e=>{this.userOffsets.updateOffset(e.userId,e.offset)})),this.userOffsets.offsetMap.forEach(((e,t)=>{this.markLocalMessagesRead(a,t,e,!1)}))}return s}))}deleteMessages(e){return b(this,void 0,void 0,(function*(){yield this.aopUnreadAmountMaxMessage((()=>b(this,void 0,void 0,(function*(){let t=e.messages;yield Cs.deleteServerMessages(t),this.messageCache.deleteMessages(t),v.onSuccess(e)}))))}))}syncDeletedMessage(e,t){this.aopUnreadAmountMaxMessage((()=>{this.doSyncDeletedMessage(e,t)}))}doSyncDeletedMessage(e,t){if(e===te.Socket.user().id){let e=this.messageCache.findMessagesByTimes(t);this.messageCache.deleteMessages(e),e.length>0&&Os.fire(ls.MESSAGE_DELETED,e)}}recallMessages(e){return b(this,void 0,void 0,(function*(){yield this.aopUnreadAmountMaxMessage((()=>b(this,void 0,void 0,(function*(){this.doRecall(e)}))))}))}doRecall(e){let t=this.messageCache.recallMessage(e);t.length>0&&Os.fire(ls.MESSAGE_RECALLED,t)}expire(){this.messageCache.isEmpty()||(this.expiredTime=this.messageCache.maxSuccessMessageTime())}updateByServerChange(){return b(this,void 0,void 0,(function*(){yield this.aopUnreadAmountMaxMessage((()=>b(this,void 0,void 0,(function*(){let e=yield this.remoteHistory.sync(this.target.scene,this.target.id,this.expiredTime,this.messageCache.minTime(),this.target.teamId);e.userOffsets.forEach((e=>{this.markLocalMessagesRead(this.messageCache.all(),e.userId,e.offset,!0)}));let t=e.deletedMessageTimes;t.length>0&&this.doSyncDeletedMessage(te.Socket.user().id,t);let s=e.recalledMessages;s.length>0&&s.forEach((e=>{let t=new As(this.target.scene,this.target.id,e.recaller,e.times);this.doRecall(t)})),this.expiredTime=0}))))}))}markRead(){return b(this,void 0,void 0,(function*(){yield this.aopUnreadAmountMaxMessage((()=>b(this,void 0,void 0,(function*(){let e=this.messageCache.maxSuccessMessageTime();e>this.userOffsets.myOffset()&&(this.userOffsets.markingTime=e,yield this.remoteHistory.updateServerOffsets(e,this.target),e===this.userOffsets.markingTime&&this.markLocalMessagesRead(this.messageCache.all(),te.Socket.user().id,e,!0))}))))}))}syncMarkedMessage(e){this.aopUnreadAmountMaxMessage((()=>{this.markLocalMessagesRead(this.messageCache.all(),e.markerId,e.time,!0)}))}onMessageSending(e){this.aopUnreadAmountMaxMessage((()=>{this.messageCache.saveMessage(e)}))}onMessageSendSuccess(e){this.aopUnreadAmountMaxMessage((()=>{this.messageCache.correctPosition(e),this.markLocalMessagesRead(this.messageCache.all(),te.Socket.user().id,e.timestamp,!0)}))}onMessageSendFailed(e){this.getMaxMessage()===e&&gs.i.fire(cs.MAX_MESSAGE_CHANGED,{message:e,receiver:this.to})}onMessageReceived(e){this.aopUnreadAmountMaxMessage((()=>{this.messageCache.saveMessage(e),this.markLocalMessagesRead(this.messageCache.all(),e.senderId,e.timestamp,!0)}))}aopUnreadAmountMaxMessage(e,t){return b(this,void 0,void 0,(function*(){try{let t=new ks(this);t.pre(),yield e(),t.post()}catch(e){v.onFailed(t,e)}}))}markLocalMessagesRead(e,t,s,i){if(this.userOffsets.updateOffset(t,s),this.isOtherUserId(t)){let t=this.markMySentRead(e,s);i&&t.length>0&&Os.fire(ls.MESSAGE_READ,t)}else t===te.Socket.user().id&&this.markOthersSentRead(e,s)}markOthersSentRead(e,t){if(this.target.scene===o.PRIVATE)for(let s=e.length-1;s>=0;s--){let i=e[s];if(i.isOtherSent()&&i.timestamp<=t){if(i.read)break;i.read=!0}}}markMySentRead(e,t){let s=new Array;if(this.target.scene===o.PRIVATE)for(let i=e.length-1;i>=0;i--){let n=e[i];if(!n.isOtherSent()&&n.timestamp<=t&&n.status===r.SUCCESS){if(n.read)break;n.read=!0,s.push(n)}}return s}isOtherUserId(e){if(this.target.scene===o.CS){let t=this.target.customerId();return te.Socket.user().id===t?e!==te.Socket.user().id:e===t}return e!==te.Socket.user().id}unreadAmount(e){let t=0,s=this.userOffsets.myOffset(),i=this.messageCache.all();for(const e of i)e.isOtherSent()&&!1===e.recalled&&e.timestamp>s&&(t+=1);return t}getMaxMessage(e){return this.messageCache.getMaxMessage()}maxTime(e){let t=this.getMaxMessage();return u.isDef(t)?t.timestamp:0}}class Ds{constructor(e,t){this.teamId=e,this.customerId=t}}class xs{}class Us{constructor(e,t,s){this.teamId=e,this.teamData=JSON.stringify(t),this.agentData=JSON.stringify(s)}}class Gs{constructor(e){this.teamId=e}}class Fs{constructor(e){this.teamId=e}}var Ls={exports:{}},Bs=/^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,qs=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],js=function(e){var t=e,s=e.indexOf("["),i=e.indexOf("]");-1!=s&&-1!=i&&(e=e.substring(0,s)+e.substring(s,i).replace(/:/g,";")+e.substring(i,e.length));for(var n=Bs.exec(e||""),o={},r=14;r--;)o[qs[r]]=n[r]||"";return-1!=s&&-1!=i&&(o.source=t,o.host=o.host.substring(1,o.host.length-1).replace(/;/g,":"),o.authority=o.authority.replace("[","").replace("]","").replace(/;/g,":"),o.ipv6uri=!0),o},Vs={exports:{}},Hs={exports:{}},zs=1e3,Ws=60*zs,Js=60*Ws,Xs=24*Js,$s=365.25*Xs,Ys=function(e,t){t=t||{};var s=typeof e;if("string"===s&&e.length>0)return function(e){if(e=String(e),e.length>100)return;var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(!t)return;var s=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return s*$s;case"days":case"day":case"d":return s*Xs;case"hours":case"hour":case"hrs":case"hr":case"h":return s*Js;case"minutes":case"minute":case"mins":case"min":case"m":return s*Ws;case"seconds":case"second":case"secs":case"sec":case"s":return s*zs;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return s;default:return}}(e);if("number"===s&&!1===isNaN(e))return t.long?function(e){return Qs(e,Xs,"day")||Qs(e,Js,"hour")||Qs(e,Ws,"minute")||Qs(e,zs,"second")||e+" ms"}(e):function(e){if(e>=Xs)return Math.round(e/Xs)+"d";if(e>=Js)return Math.round(e/Js)+"h";if(e>=Ws)return Math.round(e/Ws)+"m";if(e>=zs)return Math.round(e/zs)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function Qs(e,t,s){if(!(e<t))return e<1.5*t?Math.floor(e/t)+" "+s:Math.ceil(e/t)+" "+s+"s"}!function(e,t){function s(e){var s;function n(){if(n.enabled){var e=n,i=+new Date,o=i-(s||i);e.diff=o,e.prev=s,e.curr=i,s=i;for(var r=new Array(arguments.length),a=0;a<r.length;a++)r[a]=arguments[a];r[0]=t.coerce(r[0]),"string"!=typeof r[0]&&r.unshift("%O");var c=0;r[0]=r[0].replace(/%([a-zA-Z%])/g,(function(s,i){if("%%"===s)return s;c++;var n=t.formatters[i];if("function"==typeof n){var o=r[c];s=n.call(e,o),r.splice(c,1),c--}return s})),t.formatArgs.call(e,r),(n.log||t.log||console.log.bind(console)).apply(e,r)}}return n.namespace=e,n.enabled=t.enabled(e),n.useColors=t.useColors(),n.color=function(e){var s,i=0;for(s in e)i=(i<<5)-i+e.charCodeAt(s),i|=0;return t.colors[Math.abs(i)%t.colors.length]}(e),n.destroy=i,"function"==typeof t.init&&t.init(n),t.instances.push(n),n}function i(){var e=t.instances.indexOf(this);return-1!==e&&(t.instances.splice(e,1),!0)}(t=Hs.exports=s.debug=s.default=s).coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){t.enable("")},t.enable=function(e){var s;t.save(e),t.names=[],t.skips=[];var i=("string"==typeof e?e:"").split(/[\s,]+/),n=i.length;for(s=0;s<n;s++)i[s]&&("-"===(e=i[s].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.substr(1)+"$")):t.names.push(new RegExp("^"+e+"$")));for(s=0;s<t.instances.length;s++){var o=t.instances[s];o.enabled=t.enabled(o.namespace)}},t.enabled=function(e){if("*"===e[e.length-1])return!0;var s,i;for(s=0,i=t.skips.length;s<i;s++)if(t.skips[s].test(e))return!1;for(s=0,i=t.names.length;s<i;s++)if(t.names[s].test(e))return!0;return!1},t.humanize=Ys,t.instances=[],t.names=[],t.skips=[],t.formatters={}}(0,Hs.exports),function(e,t){function s(){var e;try{e=t.storage.debug}catch(e){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e}(t=e.exports=Hs.exports).log=function(){return"object"==typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)},t.formatArgs=function(e){var s=this.useColors;if(e[0]=(s?"%c":"")+this.namespace+(s?" %c":" ")+e[0]+(s?"%c ":" ")+"+"+t.humanize(this.diff),!s)return;var i="color: "+this.color;e.splice(1,0,i,"color: inherit");var n=0,o=0;e[0].replace(/%[a-zA-Z%]/g,(function(e){"%%"!==e&&(n++,"%c"===e&&(o=n))})),e.splice(o,0,i)},t.save=function(e){try{null==e?t.storage.removeItem("debug"):t.storage.debug=e}catch(e){}},t.load=s,t.useColors=function(){if("undefined"!=typeof window&&window.process&&"renderer"===window.process.type)return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage="undefined"!=typeof chrome&&void 0!==chrome.storage?chrome.storage.local:function(){try{return window.localStorage}catch(e){}}(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.formatters.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}},t.enable(s())}(Vs,Vs.exports);var Ks=js,Zs=Vs.exports("socket.io-client:url"),ei=function(e,t){var s=e;t=t||"undefined"!=typeof location&&location,null==e&&(e=t.protocol+"//"+t.host);"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?t.protocol+e:t.host+e),/^(https?|wss?):\/\//.test(e)||(Zs("protocol-less url %s",e),e=void 0!==t?t.protocol+"//"+e:"https://"+e),Zs("parse %s",e),s=Ks(e));s.port||(/^(http|ws)$/.test(s.protocol)?s.port="80":/^(http|ws)s$/.test(s.protocol)&&(s.port="443"));s.path=s.path||"/";var i=-1!==s.host.indexOf(":")?"["+s.host+"]":s.host;return s.id=s.protocol+"://"+i+":"+s.port,s.href=s.protocol+"://"+i+(t&&t.port===s.port?"":":"+s.port),s};var ti={},si={}.toString,ii=Array.isArray||function(e){return"[object Array]"==si.call(e)};!function(e){Vs.exports("socket.io-parser");var t=w.exports,s=ii;function i(){}e.protocol=4,e.types=["CONNECT","DISCONNECT","EVENT","ACK","ERROR","BINARY_EVENT","BINARY_ACK"],e.CONNECT=0,e.DISCONNECT=1,e.EVENT=2,e.ACK=3,e.ERROR=4,e.BINARY_EVENT=5,e.BINARY_ACK=6,e.Encoder=i,e.Decoder=o;var n=e.ERROR+'"encode error"';function o(){this.reconstructor=null}function r(t){return{type:e.ERROR,data:"parser error: "+t}}i.prototype.encode=function(t,s){var i=function(t){var s=""+t.type;e.BINARY_EVENT!==t.type&&e.BINARY_ACK!==t.type||(s+=t.attachments+"-");t.nsp&&"/"!==t.nsp&&(s+=t.nsp+",");null!=t.id&&(s+=t.id);if(null!=t.data){var i=function(e){try{return JSON.stringify(e)}catch(e){return!1}}(t.data);if(!1===i)return n;s+=i}return s}(t);s([i])},t(o.prototype),o.prototype.add=function(t){var i;if("string"!=typeof t)throw new Error("Unknown type: "+t);i=function(t){var i=0,n={type:Number(t.charAt(0))};if(null==e.types[n.type])return r("unknown packet type "+n.type);if(e.BINARY_EVENT===n.type||e.BINARY_ACK===n.type){for(var o="";"-"!==t.charAt(++i)&&(o+=t.charAt(i),i!=t.length););if(o!=Number(o)||"-"!==t.charAt(i))throw new Error("Illegal attachments");n.attachments=Number(o)}if("/"===t.charAt(i+1))for(n.nsp="";++i;){if(","===(c=t.charAt(i)))break;if(n.nsp+=c,i===t.length)break}else n.nsp="/";var a=t.charAt(i+1);if(""!==a&&Number(a)==a){for(n.id="";++i;){var c;if(null==(c=t.charAt(i))||Number(c)!=c){--i;break}if(n.id+=t.charAt(i),i===t.length)break}n.id=Number(n.id)}if(t.charAt(++i)){var u=function(e){try{return JSON.parse(e)}catch(e){return!1}}(t.substr(i));if(!(!1!==u&&(n.type===e.ERROR||s(u))))return r("invalid payload");n.data=u}return n}(t),this.emit("decoded",i)},o.prototype.destroy=function(){this.reconstructor&&this.reconstructor.finishedReconstruction()}}(ti);var ni={exports:{}},oi={},ri={},ai=Object.keys||function(e){var t=[],s=Object.prototype.hasOwnProperty;for(var i in e)s.call(e,i)&&t.push(i);return t},ci=ii,ui=Object.prototype.toString,li="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===ui.call(Blob),di="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===ui.call(File),hi=function e(t){if(!t||"object"!=typeof t)return!1;if(ci(t)){for(var s=0,i=t.length;s<i;s++)if(e(t[s]))return!0;return!1}if("function"==typeof Buffer&&Buffer.isBuffer&&Buffer.isBuffer(t)||"function"==typeof ArrayBuffer&&t instanceof ArrayBuffer||li&&t instanceof Blob||di&&t instanceof File)return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return e(t.toJSON(),!0);for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&e(t[n]))return!0;return!1};var pi=function(e,t,s){var i=!1;return s=s||mi,n.count=e,0===e?t():n;function n(e,o){if(n.count<=0)throw new Error("after called too many times");--n.count,e?(i=!0,t(e),t=s):0!==n.count||i||t(null,o)}};function mi(){}var fi,gi,yi,Si=String.fromCharCode;function Ei(e){for(var t,s,i=[],n=0,o=e.length;n<o;)(t=e.charCodeAt(n++))>=55296&&t<=56319&&n<o?56320==(64512&(s=e.charCodeAt(n++)))?i.push(((1023&t)<<10)+(1023&s)+65536):(i.push(t),n--):i.push(t);return i}function vi(e,t){if(e>=55296&&e<=57343){if(t)throw Error("Lone surrogate U+"+e.toString(16).toUpperCase()+" is not a scalar value");return!1}return!0}function bi(e,t){return Si(e>>t&63|128)}function Ci(e,t){if(0==(4294967168&e))return Si(e);var s="";return 0==(4294965248&e)?s=Si(e>>6&31|192):0==(4294901760&e)?(vi(e,t)||(e=65533),s=Si(e>>12&15|224),s+=bi(e,6)):0==(4292870144&e)&&(s=Si(e>>18&7|240),s+=bi(e,12),s+=bi(e,6)),s+=Si(63&e|128)}function Mi(){if(yi>=gi)throw Error("Invalid byte index");var e=255&fi[yi];if(yi++,128==(192&e))return 63&e;throw Error("Invalid continuation byte")}function wi(e){var t,s;if(yi>gi)throw Error("Invalid byte index");if(yi==gi)return!1;if(t=255&fi[yi],yi++,0==(128&t))return t;if(192==(224&t)){if((s=(31&t)<<6|Mi())>=128)return s;throw Error("Invalid continuation byte")}if(224==(240&t)){if((s=(15&t)<<12|Mi()<<6|Mi())>=2048)return vi(s,e)?s:65533;throw Error("Invalid continuation byte")}if(240==(248&t)&&(s=(7&t)<<18|Mi()<<12|Mi()<<6|Mi())>=65536&&s<=1114111)return s;throw Error("Invalid UTF-8 detected")}var Ii={version:"2.1.2",encode:function(e,t){for(var s=!1!==(t=t||{}).strict,i=Ei(e),n=i.length,o=-1,r="";++o<n;)r+=Ci(i[o],s);return r},decode:function(e,t){var s=!1!==(t=t||{}).strict;fi=Ei(e),gi=fi.length,yi=0;for(var i,n=[];!1!==(i=wi(s));)n.push(i);return function(e){for(var t,s=e.length,i=-1,n="";++i<s;)(t=e[i])>65535&&(n+=Si((t-=65536)>>>10&1023|55296),t=56320|1023&t),n+=Si(t);return n}(n)}},Ni=void 0!==Ni?Ni:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:"undefined"!=typeof MSBlobBuilder?MSBlobBuilder:"undefined"!=typeof MozBlobBuilder&&MozBlobBuilder,Ti=function(){try{return 2===new Blob(["hi"]).size}catch(e){return!1}}(),Ri=Ti&&function(){try{return 2===new Blob([new Uint8Array([1,2])]).size}catch(e){return!1}}(),ki=Ni&&Ni.prototype.append&&Ni.prototype.getBlob;function Ai(e){return e.map((function(e){if(e.buffer instanceof ArrayBuffer){var t=e.buffer;if(e.byteLength!==t.byteLength){var s=new Uint8Array(e.byteLength);s.set(new Uint8Array(t,e.byteOffset,e.byteLength)),t=s.buffer}return t}return e}))}function Oi(e,t){t=t||{};var s=new Ni;return Ai(e).forEach((function(e){s.append(e)})),t.type?s.getBlob(t.type):s.getBlob()}function Pi(e,t){return new Blob(Ai(e),t||{})}"undefined"!=typeof Blob&&(Oi.prototype=Blob.prototype,Pi.prototype=Blob.prototype);var _i=Ti?Ri?Blob:Pi:ki?Oi:void 0;!function(e){var t=ai,s=hi,i=pi,n=Ii;"undefined"!=typeof navigator&&/Android/i.test(navigator.userAgent),"undefined"!=typeof navigator&&/PhantomJS/i.test(navigator.userAgent),e.protocol=3;var o=e.packets={open:0,close:1,ping:2,pong:3,message:4,upgrade:5,noop:6},r=t(o),a={type:"error",data:"parser error"},c=_i;e.encodePacket=function(e,t,s,i){"function"==typeof t&&(i=t,t=!1),"function"==typeof s&&(i=s,s=null),void 0===e.data||e.data.buffer||e.data;var r=o[e.type];return void 0!==e.data&&(r+=s?n.encode(String(e.data),{strict:!1}):String(e.data)),i(""+r)},e.decodePacket=function(e,t,s){if(void 0===e)return a;if("string"==typeof e){if(s&&!1===(e=function(e){try{e=n.decode(e,{strict:!1})}catch(e){return!1}return e}(e)))return a;var i=e.charAt(0);return Number(i)==i&&r[i]?e.length>1?{type:r[i],data:e.substring(1)}:{type:r[i]}:a}i=new Uint8Array(e)[0];var o=sliceBuffer(e,1);return c&&"blob"===t&&(o=new c([o])),{type:r[i],data:o}},e.encodePayload=function(t,n,o){"function"==typeof n&&(o=n,n=null);var r=s(t);if(!t.length)return o("0:");!function(e,t,s){for(var n=new Array(e.length),o=i(e.length,s),r=function(e,s,i){t(s,(function(t,s){n[e]=s,i(t,n)}))},a=0;a<e.length;a++)r(a,e[a],o)}(t,(function(t,s){e.encodePacket(t,!!r&&n,!0,(function(e){s(null,function(e){return e.length+":"+e}(e))}))}),(function(e,t){return o(t.join(""))}))},e.decodePayload=function(t,s,i){var n;if("function"==typeof s&&(i=s,s=null),""===t)return i(a,0,1);for(var o,r,c="",u=0,l=t.length;u<l;u++){var d=t.charAt(u);if(":"===d){if(""===c||c!=(o=Number(c)))return i(a,0,1);if(c!=(r=t.substr(u+1,o)).length)return i(a,0,1);if(r.length){if(n=e.decodePacket(r,s,!0),a.type===n.type&&a.data===n.data)return i(a,0,1);if(!1===i(n,u+o,l))return}u+=o,c=""}else c+=d}return""!==c?i(a,0,1):void 0}}(ri);var Di=ri,xi=Ui;function Ui(e){this.path=e.path,this.hostname=e.hostname,this.port=e.port,this.secure=e.secure,this.query=e.query,this.timestampParam=e.timestampParam,this.timestampRequests=e.timestampRequests,this.readyState="",this.agent=e.agent||!1,this.socket=e.socket,this.enablesXDR=e.enablesXDR,this.pfx=e.pfx,this.key=e.key,this.passphrase=e.passphrase,this.cert=e.cert,this.ca=e.ca,this.ciphers=e.ciphers,this.rejectUnauthorized=e.rejectUnauthorized,this.forceNode=e.forceNode,this.isReactNative=e.isReactNative,this.extraHeaders=e.extraHeaders,this.localAddress=e.localAddress}(0,w.exports)(Ui.prototype),Ui.prototype.onError=function(e,t){var s=new Error(e);return s.type="TransportError",s.description=t,this.emit("error",s),this},Ui.prototype.open=function(){return"closed"!==this.readyState&&""!==this.readyState||(this.readyState="opening",this.doOpen()),this},Ui.prototype.close=function(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this},Ui.prototype.send=function(e){if("open"!==this.readyState)throw new Error("Transport not open");this.write(e)},Ui.prototype.onOpen=function(){this.readyState="open",this.writable=!0,this.emit("open")},Ui.prototype.onData=function(e){var t=Di.decodePacket(e,this.socket.binaryType);this.onPacket(t)},Ui.prototype.onPacket=function(e){this.emit("packet",e)},Ui.prototype.onClose=function(){this.readyState="closed",this.emit("close")};var Gi,Fi={encode:function(e){var t="";for(var s in e)e.hasOwnProperty(s)&&(t.length&&(t+="&"),t+=encodeURIComponent(s)+"="+encodeURIComponent(e[s]));return t},decode:function(e){for(var t={},s=e.split("&"),i=0,n=s.length;i<n;i++){var o=s[i].split("=");t[decodeURIComponent(o[0])]=decodeURIComponent(o[1])}return t}},Li=function(e,t){var s=function(){};s.prototype=t.prototype,e.prototype=new s,e.prototype.constructor=e},Bi="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),qi=64,ji={},Vi=0,Hi=0;function zi(e){var t="";do{t=Bi[e%qi]+t,e=Math.floor(e/qi)}while(e>0);return t}function Wi(){var e=zi(+new Date);return e!==Gi?(Vi=0,Gi=e):e+"."+zi(Vi++)}for(;Hi<qi;Hi++)ji[Bi[Hi]]=Hi;Wi.encode=zi,Wi.decode=function(e){var t=0;for(Hi=0;Hi<e.length;Hi++)t=t*qi+ji[e.charAt(Hi)];return t};var Ji=Wi,Xi={exports:{}};try{Xi.exports="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(e){Xi.exports=!1}var $i=Xi.exports,Yi=function(e){var t=e.xdomain,s=e.xscheme,i=e.enablesXDR;try{if("undefined"!=typeof XMLHttpRequest&&(!t||$i))return new XMLHttpRequest}catch(e){}try{if("undefined"!=typeof XDomainRequest&&!s&&i)return new XDomainRequest}catch(e){}if(!t)try{return new(self[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}},Qi=xi,Ki=Fi,Zi=ri,en=Li,tn=Ji,sn=Vs.exports("engine.io-client:polling"),nn=rn,on=null!=new Yi({xdomain:!1}).responseType;function rn(e){var t=e&&e.forceBase64;on&&!t||(this.supportsBinary=!1),Qi.call(this,e)}en(rn,Qi),rn.prototype.name="polling",rn.prototype.doOpen=function(){this.poll()},rn.prototype.pause=function(e){var t=this;function s(){sn("paused"),t.readyState="paused",e()}if(this.readyState="pausing",this.polling||!this.writable){var i=0;this.polling&&(sn("we are currently polling - waiting to pause"),i++,this.once("pollComplete",(function(){sn("pre-pause polling complete"),--i||s()}))),this.writable||(sn("we are currently writing - waiting to pause"),i++,this.once("drain",(function(){sn("pre-pause writing complete"),--i||s()})))}else s()},rn.prototype.poll=function(){sn("polling"),this.polling=!0,this.doPoll(),this.emit("poll")},rn.prototype.onData=function(e){var t=this;sn("polling got data %s",e);Zi.decodePayload(e,this.socket.binaryType,(function(e,s,i){if("opening"===t.readyState&&t.onOpen(),"close"===e.type)return t.onClose(),!1;t.onPacket(e)})),"closed"!==this.readyState&&(this.polling=!1,this.emit("pollComplete"),"open"===this.readyState?this.poll():sn('ignoring poll - transport state "%s"',this.readyState))},rn.prototype.doClose=function(){var e=this;function t(){sn("writing close packet"),e.write([{type:"close"}])}"open"===this.readyState?(sn("transport open - closing"),t()):(sn("transport not open - deferring close"),this.once("open",t))},rn.prototype.write=function(e){var t=this;this.writable=!1;var s=function(){t.writable=!0,t.emit("drain")};Zi.encodePayload(e,this.supportsBinary,(function(e){t.doWrite(e,s)}))},rn.prototype.uri=function(){var e=this.query||{},t=this.secure?"https":"http",s="";return!1!==this.timestampRequests&&(e[this.timestampParam]=tn()),this.supportsBinary||e.sid||(e.b64=1),e=Ki.encode(e),this.port&&("https"===t&&443!==Number(this.port)||"http"===t&&80!==Number(this.port))&&(s=":"+this.port),e.length&&(e="?"+e),t+"://"+(-1!==this.hostname.indexOf(":")?"["+this.hostname+"]":this.hostname)+s+this.path+e};var an,cn=nn,un=mn,ln=/\n/g,dn=/\\n/g;function hn(){}function pn(){return"undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0!==C?C:{}}function mn(e){if(cn.call(this,e),this.query=this.query||{},!an){var t=pn();an=t.___eio=t.___eio||[]}this.index=an.length;var s=this;an.push((function(e){s.onData(e)})),this.query.j=this.index,"function"==typeof addEventListener&&addEventListener("beforeunload",(function(){s.script&&(s.script.onerror=hn)}),!1)}Li(mn,cn),mn.prototype.supportsBinary=!1,mn.prototype.doClose=function(){this.script&&(this.script.parentNode.removeChild(this.script),this.script=null),this.form&&(this.form.parentNode.removeChild(this.form),this.form=null,this.iframe=null),cn.prototype.doClose.call(this)},mn.prototype.doPoll=function(){var e=this,t=document.createElement("script");this.script&&(this.script.parentNode.removeChild(this.script),this.script=null),t.async=!0,t.src=this.uri(),t.onerror=function(t){e.onError("jsonp poll error",t)};var s=document.getElementsByTagName("script")[0];s?s.parentNode.insertBefore(t,s):(document.head||document.body).appendChild(t),this.script=t,"undefined"!=typeof navigator&&/gecko/i.test(navigator.userAgent)&&setTimeout((function(){var e=document.createElement("iframe");document.body.appendChild(e),document.body.removeChild(e)}),100)},mn.prototype.doWrite=function(e,t){var s=this;if(!this.form){var i,n=document.createElement("form"),o=document.createElement("textarea"),r=this.iframeId="eio_iframe_"+this.index;n.className="socketio",n.style.position="absolute",n.style.top="-1000px",n.style.left="-1000px",n.target=r,n.method="POST",n.setAttribute("accept-charset","utf-8"),o.name="d",n.appendChild(o),document.body.appendChild(n),this.form=n,this.area=o}function a(){c(),t()}function c(){if(s.iframe)try{s.form.removeChild(s.iframe)}catch(e){s.onError("jsonp polling iframe removal error",e)}try{var e='<iframe src="javascript:0" name="'+s.iframeId+'">';i=document.createElement(e)}catch(e){(i=document.createElement("iframe")).name=s.iframeId,i.src="javascript:0"}i.id=s.iframeId,s.form.appendChild(i),s.iframe=i}this.form.action=this.uri(),c(),e=e.replace(dn,"\\\n"),this.area.value=e.replace(ln,"\\n");try{this.form.submit()}catch(e){}this.iframe.attachEvent?this.iframe.onreadystatechange=function(){"complete"===s.iframe.readyState&&a()}:this.iframe.onload=a};var fn,gn,yn=xi,Sn=ri,En=Fi,vn=Li,bn=Ji,Cn=Vs.exports("engine.io-client:websocket");("undefined"==typeof uni&&"undefined"==typeof wx&&"undefined"==typeof my&&"undefined"==typeof swan||"undefined"!=typeof WebSocket)&&("undefined"!=typeof WebSocket?fn=WebSocket:"undefined"!=typeof self&&(fn=self.WebSocket||self.MozWebSocket));var Mn=fn||gn;("undefined"==typeof uni&&"undefined"==typeof wx&&"undefined"==typeof my&&"undefined"==typeof swan||"undefined"!=typeof WebSocket)&&"undefined"==typeof GameGlobal||(Mn=function(e){var t=this;if(t.onopen=function(){},t.onclose=function(){},t.onmessage=function(e){},t.onerror=function(e){},"object"==typeof tt&&tt.getSystemInfo){let s=tt.connectSocket({url:e});t.send=function(e){s.send({data:e})},t.close=function(){s.close()},s.onOpen((function(){t.onopen()})),s.onError((function(e){t.onerror(e)})),s.onMessage((function(e){t.onmessage(e)})),s.onClose((function(){t.onclose()}))}else if("undefined"!=typeof my)my.connectSocket({url:e}),t.send=function(e){my.sendSocketMessage({data:e})},t.close=function(e){my.closeSocket()},my.onSocketOpen((function(e){t.onopen()})),my.onSocketError((function(e){t.onerror(e)})),my.onSocketMessage((function(e){t.onmessage(e)})),my.onSocketClose((e=>{t.onclose(e)}));else if("undefined"!=typeof swan)swan.connectSocket({url:e}),t.send=function(e){swan.sendSocketMessage({data:e})},t.close=function(e){swan.closeSocket()},swan.onSocketOpen((function(e){t.onopen()})),swan.onSocketError((function(e){t.onerror(e)})),swan.onSocketMessage((function(e){t.onmessage(e)})),swan.onSocketClose((e=>{t.onclose(e)}));else if("undefined"!=typeof uni){var s=uni.connectSocket({url:e,complete:()=>{}});t.send=function(e){s.send({data:e})},t.close=function(){s.close()},s.onOpen((function(e){t.onopen()})),s.onError((function(e){t.onerror(e)})),s.onMessage((function(e){t.onmessage(e)})),s.onClose((function(e){t.onclose()}))}else{var i=wx.connectSocket({url:e});t.send=function(e){i.send({data:e})},t.close=function(e){i.close({code:1e3})},i.onOpen((function(){t.onopen()})),i.onError((function(e){t.onerror(e)})),i.onMessage((function(e){t.onmessage(e)})),i.onClose((function(e){t.onclose(e)}))}});var wn=In;function In(e){e&&e.forceBase64&&(this.supportsBinary=!1),("undefined"==typeof uni&&"undefined"==typeof wx&&"undefined"==typeof my&&"undefined"==typeof swan||"undefined"!=typeof WebSocket)&&(this.perMessageDeflate=e.perMessageDeflate,this.usingBrowserWebSocket=fn&&!e.forceNode,this.protocols=e.protocols,this.usingBrowserWebSocket||(Mn=gn)),yn.call(this,e)}vn(In,yn),In.prototype.name="websocket",In.prototype.supportsBinary=!1,In.prototype.doOpen=function(){if(this.check()){var e,t,s=this.uri();if(("undefined"==typeof uni&&"undefined"==typeof wx&&"undefined"==typeof my&&"undefined"==typeof swan||"undefined"!=typeof WebSocket)&&(e=this.protocols),(t="undefined"==typeof uni&&"undefined"==typeof wx&&"undefined"==typeof my&&"undefined"==typeof swan||"undefined"!=typeof WebSocket?{agent:this.agent,perMessageDeflate:this.perMessageDeflate}:{agent:this.agent}).pfx=this.pfx,t.key=this.key,t.passphrase=this.passphrase,t.cert=this.cert,t.ca=this.ca,t.ciphers=this.ciphers,t.rejectUnauthorized=this.rejectUnauthorized,"object"==typeof navigator&&"ReactNative"===navigator.product&&(t={}),this.extraHeaders&&(t.headers=this.extraHeaders),this.localAddress&&(t.localAddress=this.localAddress),"undefined"!=typeof cc&&"Windows"===cc.sys.os)cc.resources.load("cacert",((e,t)=>{const i=t.nativeUrl;this.ws=new Mn(s,[],i),this.ws.binaryType="arraybuffer",this.addEventListeners()}));else{try{"undefined"==typeof uni&&"undefined"==typeof wx&&"undefined"==typeof my&&"undefined"==typeof swan||"undefined"!=typeof WebSocket?this.ws=this.usingBrowserWebSocket&&!this.isReactNative?e?new Mn(s,e):new Mn(s):new Mn(s,e,t):this.ws=new Mn(s)}catch(e){return this.emit("error",e)}void 0===this.ws.binaryType&&(this.supportsBinary=!1),this.ws.supports&&this.ws.supports.binary?(this.supportsBinary=!0,this.ws.binaryType="nodebuffer"):this.ws.binaryType="arraybuffer",this.addEventListeners()}}},In.prototype.addEventListeners=function(){var e=this;this.ws.onopen=function(){e.onOpen()},this.ws.onclose=function(){e.onClose()},this.ws.onmessage=function(t){e.onData(t.data)},this.ws.onerror=function(t){e.onError("websocket error",t)}},In.prototype.write=function(e){var t=this;this.writable=!1;for(var s=e.length,i=0,n=s;i<n;i++)!function(e){Sn.encodePacket(e,t.supportsBinary,(function(i){if("undefined"==typeof uni&&"undefined"==typeof wx&&"undefined"==typeof my&&"undefined"==typeof swan||"undefined"!=typeof WebSocket){if(!t.usingBrowserWebSocket){var n={};if(e.options&&(n.compress=e.options.compress),t.perMessageDeflate)("string"==typeof i?Buffer.byteLength(i):i.length)<t.perMessageDeflate.threshold&&(n.compress=!1)}try{t.usingBrowserWebSocket?t.ws.send(i):t.ws.send(i,n)}catch(e){Cn("websocket closed before onclose event")}}else try{t.ws.send(i)}catch(e){Cn("websocket closed before onclose event")}--s||o()}))}(e[i]);function o(){t.emit("flush"),setTimeout((function(){t.writable=!0,t.emit("drain")}),0)}},In.prototype.onClose=function(){yn.prototype.onClose.call(this)},In.prototype.doClose=function(){void 0!==this.ws&&this.ws.close()},In.prototype.uri=function(){var e=this.query||{},t=this.secure?"wss":"ws",s="";return this.port&&("wss"===t&&443!==Number(this.port)||"ws"===t&&80!==Number(this.port))&&(s=":"+this.port),this.timestampRequests&&(e[this.timestampParam]=bn()),this.supportsBinary||(e.b64=1),(e=En.encode(e)).length&&(e="?"+e),t+"://"+(-1!==this.hostname.indexOf(":")?"["+this.hostname+"]":this.hostname)+s+this.path+e},In.prototype.check=function(){return!(!Mn||"__initialize"in Mn&&this.name===In.prototype.name)};var Nn=un,Tn=wn;oi.polling=function(e){var t=!1,s=!1;if(e.jsonp,"undefined"!=typeof location){var i="https:"===location.protocol,n=location.port;n||(n=i?443:80),t=e.hostname!==location.hostname||n!==e.port,s=e.secure!==i}return e.xdomain=t,e.xscheme=s,new Nn(e)},oi.websocket=Tn;var Rn=[].indexOf,kn=function(e,t){if(Rn)return e.indexOf(t);for(var s=0;s<e.length;++s)if(e[s]===t)return s;return-1},An=oi,On=w.exports,Pn=Vs.exports("engine.io-client:socket"),_n=kn,Dn=ri,xn=js,Un=Fi,Gn=Fn;function Fn(e,t){if(!(this instanceof Fn))return new Fn(e,t);t=t||{},e&&"object"==typeof e&&(t=e,e=null),e?(e=xn(e),t.hostname=e.host,t.secure="https"===e.protocol||"wss"===e.protocol,t.port=e.port,e.query&&(t.query=e.query)):t.host&&(t.hostname=xn(t.host).host),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.agent=t.agent||!1,this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?443:80),this.query=t.query||{},"string"==typeof this.query&&(this.query=Un.decode(this.query)),this.upgrade=!1!==t.upgrade,this.path=(t.path||"/engine.io").replace(/\/$/,"")+"/",this.forceJSONP=!!t.forceJSONP,this.jsonp=!1!==t.jsonp,this.forceBase64=!!t.forceBase64,this.enablesXDR=!!t.enablesXDR,this.timestampParam=t.timestampParam||"t",this.timestampRequests=t.timestampRequests,this.transports=t.transports||["polling","websocket"],this.transportOptions=t.transportOptions||{},this.readyState="",this.writeBuffer=[],this.prevBufferLen=0,this.policyPort=t.policyPort||843,this.rememberUpgrade=t.rememberUpgrade||!1,this.binaryType=null,this.onlyBinaryUpgrades=t.onlyBinaryUpgrades,this.perMessageDeflate=!1!==t.perMessageDeflate&&(t.perMessageDeflate||{}),!0===this.perMessageDeflate&&(this.perMessageDeflate={}),this.perMessageDeflate&&null==this.perMessageDeflate.threshold&&(this.perMessageDeflate.threshold=1024),this.pfx=t.pfx||null,this.key=t.key||null,this.passphrase=t.passphrase||null,this.cert=t.cert||null,this.ca=t.ca||null,this.ciphers=t.ciphers||null,this.rejectUnauthorized=void 0===t.rejectUnauthorized||t.rejectUnauthorized,this.forceNode=!!t.forceNode,this.isReactNative="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase(),("undefined"==typeof self||this.isReactNative)&&(t.extraHeaders&&Object.keys(t.extraHeaders).length>0&&(this.extraHeaders=t.extraHeaders),t.localAddress&&(this.localAddress=t.localAddress)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingIntervalTimer=null,this.pingTimeoutTimer=null,this.open()}Fn.priorWebsocketSuccess=!1,On(Fn.prototype),Fn.protocol=Dn.protocol,Fn.Socket=Fn,Fn.Transport=xi,Fn.transports=oi,Fn.parser=ri,Fn.prototype.createTransport=function(e){Pn('creating transport "%s"',e);var t=function(e){var t={};for(var s in e)e.hasOwnProperty(s)&&(t[s]=e[s]);return t}(this.query);t.EIO=Dn.protocol,t.transport=e;var s=this.transportOptions[e]||{};return this.id&&(t.sid=this.id),new An[e]({query:t,socket:this,agent:s.agent||this.agent,hostname:s.hostname||this.hostname,port:s.port||this.port,secure:s.secure||this.secure,path:s.path||this.path,forceJSONP:s.forceJSONP||this.forceJSONP,jsonp:s.jsonp||this.jsonp,forceBase64:s.forceBase64||this.forceBase64,enablesXDR:s.enablesXDR||this.enablesXDR,timestampRequests:s.timestampRequests||this.timestampRequests,timestampParam:s.timestampParam||this.timestampParam,policyPort:s.policyPort||this.policyPort,pfx:s.pfx||this.pfx,key:s.key||this.key,passphrase:s.passphrase||this.passphrase,cert:s.cert||this.cert,ca:s.ca||this.ca,ciphers:s.ciphers||this.ciphers,rejectUnauthorized:s.rejectUnauthorized||this.rejectUnauthorized,perMessageDeflate:s.perMessageDeflate||this.perMessageDeflate,extraHeaders:s.extraHeaders||this.extraHeaders,forceNode:s.forceNode||this.forceNode,localAddress:s.localAddress||this.localAddress,requestTimeout:s.requestTimeout||this.requestTimeout,protocols:s.protocols||void 0,isReactNative:this.isReactNative})},Fn.prototype.open=function(){var e;if(this.rememberUpgrade&&Fn.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))e="websocket";else{if(0===this.transports.length){var t=this;return void setTimeout((function(){t.emit("error","No transports available")}),0)}e=this.transports[0]}this.readyState="opening";try{e=this.createTransport(e)}catch(e){return this.transports.shift(),void this.open()}e.open(),this.setTransport(e)},Fn.prototype.setTransport=function(e){Pn("setting transport %s",e.name);var t=this;this.transport&&(Pn("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=e,e.on("drain",(function(){t.onDrain()})).on("packet",(function(e){t.onPacket(e)})).on("error",(function(e){t.onError(e)})).on("close",(function(){t.onClose("transport close")}))},Fn.prototype.probe=function(e){Pn('probing transport "%s"',e);var t=this.createTransport(e,{probe:1}),s=!1,i=this;function n(){if(i.onlyBinaryUpgrades){var n=!this.supportsBinary&&i.transport.supportsBinary;s=s||n}s||(Pn('probe transport "%s" opened',e),t.send([{type:"ping",data:"probe"}]),t.once("packet",(function(n){if(!s)if("pong"===n.type&&"probe"===n.data){if(Pn('probe transport "%s" pong',e),i.upgrading=!0,i.emit("upgrading",t),!t)return;Fn.priorWebsocketSuccess="websocket"===t.name,Pn('pausing current transport "%s"',i.transport.name),i.transport.pause((function(){s||"closed"!==i.readyState&&(Pn("changing transport and sending upgrade packet"),l(),i.setTransport(t),t.send([{type:"upgrade"}]),i.emit("upgrade",t),t=null,i.upgrading=!1,i.flush())}))}else{Pn('probe transport "%s" failed',e);var o=new Error("probe error");o.transport=t.name,i.emit("upgradeError",o)}})))}function o(){s||(s=!0,l(),t.close(),t=null)}function r(s){var n=new Error("probe error: "+s);n.transport=t.name,o(),Pn('probe transport "%s" failed because of error: %s',e,s),i.emit("upgradeError",n)}function a(){r("transport closed")}function c(){r("socket closed")}function u(e){t&&e.name!==t.name&&(Pn('"%s" works - aborting "%s"',e.name,t.name),o())}function l(){t.removeListener("open",n),t.removeListener("error",r),t.removeListener("close",a),i.removeListener("close",c),i.removeListener("upgrading",u)}Fn.priorWebsocketSuccess=!1,t.once("open",n),t.once("error",r),t.once("close",a),this.once("close",c),this.once("upgrading",u),t.open()},Fn.prototype.onOpen=function(){if(Pn("socket open"),this.readyState="open",Fn.priorWebsocketSuccess="websocket"===this.transport.name,this.emit("open"),this.flush(),"open"===this.readyState&&this.upgrade&&this.transport.pause){Pn("starting upgrade probes");for(var e=0,t=this.upgrades.length;e<t;e++)this.probe(this.upgrades[e])}},Fn.prototype.onPacket=function(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(Pn('socket receive: type "%s", data "%s"',e.type,e.data),this.emit("packet",e),this.emit("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"pong":this.setPing(),this.emit("pong");break;case"error":var t=new Error("server error");t.code=e.data,this.onError(t);break;case"message":this.emit("data",e.data),this.emit("message",e.data)}else Pn('packet received with socket readyState "%s"',this.readyState)},Fn.prototype.onHandshake=function(e){this.emit("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this.upgrades=this.filterUpgrades(e.upgrades),this.pingInterval=e.pingInterval,this.pingTimeout=e.pingTimeout,this.onOpen(),"closed"!==this.readyState&&(this.setPing(),this.removeListener("heartbeat",this.onHeartbeat),this.on("heartbeat",this.onHeartbeat))},Fn.prototype.onHeartbeat=function(e){clearTimeout(this.pingTimeoutTimer);var t=this;t.pingTimeoutTimer=setTimeout((function(){"closed"!==t.readyState&&t.onClose("ping timeout")}),e||t.pingInterval+t.pingTimeout)},Fn.prototype.setPing=function(){var e=this;clearTimeout(e.pingIntervalTimer),e.pingIntervalTimer=setTimeout((function(){Pn("writing ping packet - expecting pong within %sms",e.pingTimeout),e.ping(),e.onHeartbeat(e.pingTimeout)}),e.pingInterval)},Fn.prototype.ping=function(){var e=this;this.sendPacket("ping",(function(){e.emit("ping")}))},Fn.prototype.onDrain=function(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emit("drain"):this.flush()},Fn.prototype.flush=function(){"closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length&&(Pn("flushing %d packets in socket",this.writeBuffer.length),this.transport.send(this.writeBuffer),this.prevBufferLen=this.writeBuffer.length,this.emit("flush"))},Fn.prototype.write=Fn.prototype.send=function(e,t,s){return this.sendPacket("message",e,t,s),this},Fn.prototype.sendPacket=function(e,t,s,i){if("function"==typeof t&&(i=t,t=void 0),"function"==typeof s&&(i=s,s=null),"closing"!==this.readyState&&"closed"!==this.readyState){(s=s||{}).compress=!1!==s.compress;var n={type:e,data:t,options:s};this.emit("packetCreate",n),this.writeBuffer.push(n),i&&this.once("flush",i),this.flush()}},Fn.prototype.close=function(){if("opening"===this.readyState||"open"===this.readyState){this.readyState="closing";var e=this;this.writeBuffer.length?this.once("drain",(function(){this.upgrading?i():t()})):this.upgrading?i():t()}function t(){e.onClose("forced close"),Pn("socket closing - telling transport to close"),e.transport.close()}function s(){e.removeListener("upgrade",s),e.removeListener("upgradeError",s),t()}function i(){e.once("upgrade",s),e.once("upgradeError",s)}return this},Fn.prototype.onError=function(e){Pn("socket error %j",e),Fn.priorWebsocketSuccess=!1,this.emit("error",e),this.onClose("transport error",e)},Fn.prototype.onClose=function(e,t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){Pn('socket close with reason: "%s"',e);clearTimeout(this.pingIntervalTimer),clearTimeout(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),this.readyState="closed",this.id=null,this.emit("close",e,t),this.writeBuffer=[],this.prevBufferLen=0}},Fn.prototype.filterUpgrades=function(e){for(var t=[],s=0,i=e.length;s<i;s++)~_n(this.transports,e[s])&&t.push(e[s]);return t},ni.exports=Gn,ni.exports.parser=ri;var Ln={exports:{}},Bn=function(e,t){for(var s=[],i=(t=t||0)||0;i<e.length;i++)s[i-t]=e[i];return s};var qn=function(e,t,s){return e.on(t,s),{destroy:function(){e.removeListener(t,s)}}};var jn=[].slice,Vn=function(e,t){if("string"==typeof t&&(t=e[t]),"function"!=typeof t)throw new Error("bind() requires a function");var s=jn.call(arguments,2);return function(){return t.apply(e,s.concat(jn.call(arguments)))}};!function(e,t){var s=ti,i=w.exports,n=Bn,o=qn,r=Vn,a=(Vs.exports("socket.io-client:socket"),Fi),c=hi;e.exports=d;var u={connect:1,connect_error:1,connect_timeout:1,connecting:1,disconnect:1,error:1,reconnect:1,reconnect_attempt:1,reconnect_failed:1,reconnect_error:1,reconnecting:1,ping:1,pong:1},l=i.prototype.emit;function d(e,t,s){this.io=e,this.nsp=t,this.json=this,this.ids=0,this.acks={},this.receiveBuffer=[],this.sendBuffer=[],this.connected=!1,this.disconnected=!0,this.flags={},s&&s.query&&(this.query=s.query),this.io.autoConnect&&this.open()}i(d.prototype),d.prototype.subEvents=function(){if(!this.subs){var e=this.io;this.subs=[o(e,"open",r(this,"onopen")),o(e,"packet",r(this,"onpacket")),o(e,"close",r(this,"onclose"))]}},d.prototype.open=d.prototype.connect=function(){return this.connected||(this.subEvents(),this.io.open(),"open"===this.io.readyState&&this.onopen(),this.emit("connecting")),this},d.prototype.send=function(){var e=n(arguments);return e.unshift("message"),this.emit.apply(this,e),this},d.prototype.emit=function(e){if(u.hasOwnProperty(e))return l.apply(this,arguments),this;var t=n(arguments),i={type:(void 0!==this.flags.binary?this.flags.binary:c(t))?s.BINARY_EVENT:s.EVENT,data:t,options:{}};return i.options.compress=!this.flags||!1!==this.flags.compress,"function"==typeof t[t.length-1]&&(this.ids,this.acks[this.ids]=t.pop(),i.id=this.ids++),this.connected?this.packet(i):this.sendBuffer.push(i),this.flags={},this},d.prototype.packet=function(e){e.nsp=this.nsp,this.io.packet(e)},d.prototype.onopen=function(){if("/"!==this.nsp)if(this.query){var e="object"==typeof this.query?a.encode(this.query):this.query;this.packet({type:s.CONNECT,query:e})}else this.packet({type:s.CONNECT})},d.prototype.onclose=function(e){this.connected=!1,this.disconnected=!0,delete this.id,this.emit("disconnect",e)},d.prototype.onpacket=function(e){var t=e.nsp===this.nsp,i=e.type===s.ERROR&&"/"===e.nsp;if(t||i)switch(e.type){case s.CONNECT:this.onconnect();break;case s.EVENT:case s.BINARY_EVENT:this.onevent(e);break;case s.ACK:case s.BINARY_ACK:this.onack(e);break;case s.DISCONNECT:this.ondisconnect();break;case s.ERROR:this.emit("error",e.data)}},d.prototype.onevent=function(e){var t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?l.apply(this,t):this.receiveBuffer.push(t)},d.prototype.ack=function(e){var t=this,i=!1;return function(){if(!i){i=!0;var o=n(arguments);t.packet({type:c(o)?s.BINARY_ACK:s.ACK,id:e,data:o})}}},d.prototype.onack=function(e){var t=this.acks[e.id];"function"==typeof t?(e.id,e.data,t.apply(this,e.data),delete this.acks[e.id]):e.id},d.prototype.onconnect=function(){this.connected=!0,this.disconnected=!1,this.emit("connect"),this.emitBuffered()},d.prototype.emitBuffered=function(){var e;for(e=0;e<this.receiveBuffer.length;e++)l.apply(this,this.receiveBuffer[e]);for(this.receiveBuffer=[],e=0;e<this.sendBuffer.length;e++)this.packet(this.sendBuffer[e]);this.sendBuffer=[]},d.prototype.ondisconnect=function(){this.nsp,this.destroy(),this.onclose("io server disconnect")},d.prototype.destroy=function(){if(this.subs){for(var e=0;e<this.subs.length;e++)this.subs[e].destroy();this.subs=null}this.io.destroy(this)},d.prototype.close=d.prototype.disconnect=function(){return this.connected&&(this.nsp,this.packet({type:s.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this},d.prototype.compress=function(e){return this.flags.compress=e,this},d.prototype.binary=function(e){return this.flags.binary=e,this}}(Ln);var Hn=zn;function zn(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}zn.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),s=Math.floor(t*this.jitter*e);e=0==(1&Math.floor(10*t))?e-s:e+s}return 0|Math.min(e,this.max)},zn.prototype.reset=function(){this.attempts=0},zn.prototype.setMin=function(e){this.ms=e},zn.prototype.setMax=function(e){this.max=e},zn.prototype.setJitter=function(e){this.jitter=e};class Wn{static init(e,t,s){this.host=e,(void 0!==t&&!1===t||!0===s)&&(this.https=!1)}static isMP(){return[l.MP_WX,l.MP_ALI,l.MP_BYTE,l.MP_WGAME,l.MP_BAIDU].includes(d.currentPlatform())}static uri(){let e="http";return this.https&&(e+="s"),e+"://"+this.index()+this.host}static index(){return 0==this.i?this.i=Math.floor(Math.random()*this.max)+1:this.i=this.i%this.max+1,this.i}}Wn.i=0,Wn.max=5,Wn.https=!0;var Jn=M(Object.freeze({__proto__:null,URIResolver:Wn})),Xn=M(E),$n=ni.exports,Yn=Ln.exports,Qn=w.exports,Kn=ti,Zn=qn,eo=Vn,to=(Vs.exports("socket.io-client:manager"),kn),so=Hn;const{URIResolver:io}=Jn;var no=Xn.runStatus,oo=Object.prototype.hasOwnProperty,ro=ao;function ao(e,t){if(!(this instanceof ao))return new ao(e,t);e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.nsps={},this.subs=[],this.opts=t,this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(t.randomizationFactor||.5),this.backoff=new so({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this.readyState="closed",this.uri=e,this.connecting=[],this.lastPing=null,this.encoding=!1,this.packetBuffer=[];var s=t.parser||Kn;this.encoder=new s.Encoder,this.decoder=new s.Decoder,this.autoConnect=!1!==t.autoConnect,this.autoConnect&&this.open()}ao.prototype.emitAll=function(){for(var e in this.emit.apply(this,arguments),this.nsps)oo.call(this.nsps,e)&&this.nsps[e].emit.apply(this.nsps[e],arguments)},ao.prototype.updateSocketIds=function(){for(var e in this.nsps)oo.call(this.nsps,e)&&(this.nsps[e].id=this.generateId(e))},ao.prototype.generateId=function(e){return("/"===e?"":e+"#")+this.engine.id},Qn(ao.prototype),ao.prototype.reconnection=function(e){return arguments.length?(this._reconnection=!!e,this):this._reconnection},ao.prototype.reconnectionAttempts=function(e){return arguments.length?(this._reconnectionAttempts=e,this):this._reconnectionAttempts},ao.prototype.reconnectionDelay=function(e){return arguments.length?(this._reconnectionDelay=e,this.backoff&&this.backoff.setMin(e),this):this._reconnectionDelay},ao.prototype.randomizationFactor=function(e){return arguments.length?(this._randomizationFactor=e,this.backoff&&this.backoff.setJitter(e),this):this._randomizationFactor},ao.prototype.reconnectionDelayMax=function(e){return arguments.length?(this._reconnectionDelayMax=e,this.backoff&&this.backoff.setMax(e),this):this._reconnectionDelayMax},ao.prototype.timeout=function(e){return arguments.length?(this._timeout=e,this):this._timeout},ao.prototype.maybeReconnectOnOpen=function(){!this.reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()},ao.prototype.open=ao.prototype.connect=function(e,t){if(this.readyState,~this.readyState.indexOf("open"))return this;this.uri,this.engine=$n(this.uri,this.opts);var s=this.engine,i=this;this.readyState="opening",this.skipReconnect=!1;var n=Zn(s,"open",(function(){i.onopen(),e&&e()})),o=Zn(s,"error",(async function(t){if(i.uri=io.uri(),i.cleanup(),i.readyState="closed",i.emitAll("connect_error",t),e){var s=new Error("Connection error");s.data=t,e(s)}else i.maybeReconnectOnOpen()}));if(!1!==this._timeout){var r=this._timeout,a=setTimeout((function(){n.destroy(),s.close(),s.emit("error","timeout"),i.emitAll("connect_timeout",r)}),r);this.subs.push({destroy:function(){clearTimeout(a)}})}return this.subs.push(n),this.subs.push(o),this},ao.prototype.onopen=function(){this.cleanup(),this.readyState="open",this.emit("open");var e=this.engine;this.subs.push(Zn(e,"data",eo(this,"ondata"))),this.subs.push(Zn(e,"ping",eo(this,"onping"))),this.subs.push(Zn(e,"pong",eo(this,"onpong"))),this.subs.push(Zn(e,"error",eo(this,"onerror"))),this.subs.push(Zn(e,"close",eo(this,"onclose"))),this.subs.push(Zn(this.decoder,"decoded",eo(this,"ondecoded")))},ao.prototype.onping=function(){this.lastPing=new Date,this.emitAll("ping")},ao.prototype.onpong=function(){this.emitAll("pong",new Date-this.lastPing)},ao.prototype.ondata=function(e){this.decoder.add(e)},ao.prototype.ondecoded=function(e){this.emit("packet",e)},ao.prototype.onerror=function(e){this.emitAll("error",e)},ao.prototype.socket=function(e,t){var s=this.nsps[e];if(!s){s=new Yn(this,e,t),this.nsps[e]=s;var i=this;s.on("connecting",n),s.on("connect",(function(){s.id=i.generateId(e)})),this.autoConnect&&n()}function n(){~to(i.connecting,s)||i.connecting.push(s)}return s},ao.prototype.destroy=function(e){var t=to(this.connecting,e);~t&&this.connecting.splice(t,1),this.connecting.length||this.close()},ao.prototype.packet=function(e){var t=this;e.query&&0===e.type&&(e.nsp+="?"+e.query),t.encoding?t.packetBuffer.push(e):(t.encoding=!0,this.encoder.encode(e,(function(s){for(var i=0;i<s.length;i++)t.engine.write(s[i],e.options);t.encoding=!1,t.processPacketQueue()})))},ao.prototype.processPacketQueue=function(){if(this.packetBuffer.length>0&&!this.encoding){var e=this.packetBuffer.shift();this.packet(e)}},ao.prototype.cleanup=function(){for(var e=this.subs.length,t=0;t<e;t++){this.subs.shift().destroy()}this.packetBuffer=[],this.encoding=!1,this.lastPing=null,this.decoder.destroy()},ao.prototype.close=ao.prototype.disconnect=function(){this.skipReconnect=!0,this.reconnecting=!1,"opening"===this.readyState&&this.cleanup(),this.backoff.reset(),this.readyState="closed",this.engine&&this.engine.close()},ao.prototype.onclose=function(e){this.cleanup(),this.backoff.reset(),this.readyState="closed",this.emit("close",e),this._reconnection&&!this.skipReconnect&&this.reconnect()},ao.prototype.reconnect=function(){if(no.isBackend(),this.reconnecting||this.skipReconnect)return this;var e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitAll("reconnect_failed"),this.reconnecting=!1;else{var t=this.backoff.duration();this.reconnecting=!0;var s=setTimeout((function(){if(no.isBackend())return e.reconnecting=!1,e.reconnect(),void e.emitAll("reconnect_error","Uniapp running backend, skipped reconnect...");e.skipReconnect||(e.emitAll("reconnect_attempt",e.backoff.attempts),e.emitAll("reconnecting",e.backoff.attempts),e.skipReconnect||e.open((function(t){t?(e.reconnecting=!1,e.reconnect(),e.emitAll("reconnect_error",t.data)):e.onreconnect()})))}),t);this.subs.push({destroy:function(){clearTimeout(s)}})}},ao.prototype.onreconnect=function(){var e=this.backoff.attempts;this.reconnecting=!1,this.backoff.reset(),this.updateSocketIds(),this.emitAll("reconnect",e)},function(e,t){var s=ei,i=ti,n=ro;Vs.exports("socket.io-client");e.exports=t=r;var o=t.managers={};function r(e,t){"object"==typeof e&&(t=e,e=void 0),t=t||{};var i,r=s(e),a=r.source,c=r.id,u=r.path,l=o[c]&&u in o[c].nsps;return t.forceNew||t["force new connection"]||!1===t.multiplex||l?i=n(a,t):(o[c]||(o[c]=n(a,t)),i=o[c]),r.query&&!t.query&&(t.query=r.query),i.socket(r.path,t)}t.protocol=i.protocol,t.connect=r,t.Manager=ro,t.Socket=Ln.exports}(Ls,Ls.exports);const co=Ls.exports;class uo{constructor(){this.io=co,this.status=t.DISCONNECTED,this.permissions=[ne.NONE],this.connectedObservers=[],this.disconnectedObservers=[]}connect(){this.status=t.CONNECTING}socketio(){return this.io}on(e,t){this.io.on(e,t)}disconnect(){this.io.disconnect()}getStatus(){return this.status}addConnectedObserver(e){u.isFunction(e)&&this.connectedObservers.push(e)}addDisconnectedObserver(e){u.isFunction(e)&&this.disconnectedObservers.push(e)}notify(e,t){for(let s=0;s<e.length;s++)e[s](t)}}class lo extends uo{constructor(e){super(),this.reconnectingObservers=[],this.addReconnectingObserver(e.onReconnecting),this.addDisconnectedObserver(e.onDisconnected)}connect(e){super.connect(),this.io=this.io.connect(e.uri,e.opts),this.initListener()}initListener(){this.io.on("connect",(()=>{this.status=t.CONNECTED,this.notify(this.connectedObservers)})),this.io.on("reconnecting",(e=>{this.status=t.CONNECTING,this.notify(this.reconnectingObservers,e)})),this.io.on("disconnect",(()=>{this.status=t.DISCONNECTED,this.notify(this.disconnectedObservers)})),this.io.on("connect_error",(function(e){}))}addReconnectingObserver(e){this.reconnectingObservers.push(e)}}class ho{static get(e){const t=encodeURIComponent(e)+"=",s=document.cookie.split("; ");for(const e of s)if(e.startsWith(t))return decodeURIComponent(e.substring(t.length));return null}static set(e,t,s,i,n="/",o=!1){let r=encodeURIComponent(e)+"="+encodeURIComponent(t);s instanceof Date&&(r+="; expires="+s.toGMTString()),n&&(r+="; path="+n),i&&(r+="; domain="+i),o&&(r+="; secure"),document.cookie=r}static remove(e,t,s="/",i=!1){ho.set(e,"",new Date(0),t,s,i)}}class po{asyncGet(e){let t=this.get(e);return Promise.resolve(t)}asyncPut(e,t){return this.put(e,t),Promise.resolve()}get(e){let t=this.doGet(e);return t=JSON.parse(t),t}put(e,t){this.doPut(e,JSON.stringify(t))}}class mo extends po{constructor(){super(),this.domain=null;this.domain="undefined"!=typeof location&&/^(?:[A-za-z0-9-]+\.)+[A-za-z]{2,4}(?:[\/\?#][\/=\?%\-&~`@[\]\':+!\.#\w]*)?$/.test(location.host)?location.host.split(".").slice(-2).join("."):null}doGet(e){return ho.get(e)||null}doPut(e,t){const s=new Date(2030,12,31,0,0,0,0),i=this.domain;ho.set(e,t,s,i)}remove(e){const t=this.domain;ho.remove(e,t)}support(){return"undefined"!=typeof navigator&&!0===navigator.cookieEnabled}}class fo extends po{doGet(e){return localStorage.getItem(e)||null}doPut(e,t){localStorage.setItem(e,t)}remove(e){localStorage.removeItem(e)}support(){return!("undefined"!=typeof GameGlobal||"undefined"==typeof localStorage||!localStorage.setItem)}}class go extends po{doGet(e){return uni.getStorageSync(e)||null}doPut(e,t){uni.setStorageSync(e,t)}remove(e){uni.removeStorageSync(e)}support(){return!("object"!=typeof uni||!uni.getStorageSync)}}class yo extends po{doGet(e){return cc.sys.localStorage.getItem(e)||null}doPut(e,t){cc.sys.localStorage.setItem(e,t)}remove(e){cc.sys.localStorage.removeItem(e)}support(){return"undefined"!=typeof cc&&void 0!==cc.sys.localStorage}}class So extends po{doGet(e){return wx.getStorageSync(e)||null}doPut(e,t){wx.setStorageSync(e,t)}remove(e){wx.removeStorageSync(e)}support(){return!("object"!=typeof wx||!wx.getStorageSync||"undefined"!=typeof tt)}}class Eo extends po{asyncGet(e){return b(this,void 0,void 0,(function*(){const t=yield i.asyncStorage.getItem(e);return JSON.parse(t)}))}asyncPut(e,t){return i.asyncStorage.setItem(e,JSON.stringify(t))}doPut(e,t){throw new Error("Method not implemented.")}remove(e){i.asyncStorage.removeItem(e)}support(){return s.currentFramework()===e.REACT_NATIVE}doGet(e){throw new Error("Method not implemented.")}}class vo extends po{doGet(e){const t=my.getStorageSync({key:e}).data||null;return"string"==typeof JSON.parse(t)?JSON.parse(t):t}doPut(e,t){my.setStorageSync({key:e,data:JSON.stringify(t)})}remove(e){my.removeStorageSync({key:e})}support(){return!("undefined"==typeof my||!my.getStorageSync)}}class bo extends po{doGet(e){return tt.getStorageSync(e)||null}doPut(e,t){tt.setStorageSync(e,t)}remove(e){tt.removeStorageSync(e)}support(){return!("object"!=typeof tt||!tt.getStorageSync)}}class Co extends po{doGet(e){return swan.getStorageSync(e)||null}doPut(e,t){swan.setStorageSync(e,t)}remove(e){swan.removeStorageSync(e)}support(){return!("undefined"==typeof swan||!swan.getStorageSync)}}class Mo{constructor(){this.supportedStorage=null;const e=Mo.storages;e.push(new go),e.push(new yo),e.push(new fo),e.push(new So),e.push(new Eo),e.push(new vo),e.push(new Co),e.push(new bo),e.push(new mo),this.dispatch(),this.supportedStorage}static localStorage(){return this.instance.supportedStorage}dispatch(){for(let e of Mo.storages)if(e.support()){this.supportedStorage=e;break}}}Mo.storages=new Array,Mo.instance=new Mo;class wo{static get(){return b(this,void 0,void 0,(function*(){let e,t=Mo.localStorage();return null!==t&&(e=yield t.asyncGet(wo.SM_KEY)),e}))}static put(e){return b(this,void 0,void 0,(function*(){var t=Mo.localStorage();let s=e.sm;null!==t&&s&&t.asyncPut(wo.SM_KEY,s)}))}}wo.SM_KEY="GE-SM";class Io{static e(e,t){function s(e){return function(e){return e>=32&&e<=126}(e)?String.fromCharCode(function(e){let s=e+t;return s>126?s-126+32:s}(e)):String.fromCharCode(e)}let i="";for(let t=0;t<e.length;t++){i+=s(e.charCodeAt(t))}return i}}class No{static initRNUniqueId(){if(s.currentFramework()===e.REACT_NATIVE){let e=i.platform,t=e.constants,s={os:e.OS};return"android"===s.os?s.f=t.Fingerprint:s.v=e.Version,JSON.stringify(s)}return null}static initPlusDeviceId(){return new Promise(((e,t)=>{"undefined"!=typeof plus?plus.device.getInfo({success:t=>{e(t.uuid)},fail:e=>{t(e)}}):e(null)}))}static getVideoCard(){var e;if(d.currentPlatform()===l.BROWSER&&"undefined"!=typeof document){const t=document.createElement("canvas"),s=null!==(e=t.getContext("webgl"))&&void 0!==e?e:t.getContext("experimental-webgl");if(s&&"getExtension"in s){let e=0,t=0;if(navigator.userAgent.indexOf("Firefox")>-1)t=s.VENDOR,e=s.RENDERER;else{let i=s.getExtension("WEBGL_debug_renderer_info");if(!i)return null;t=i.UNMASKED_VENDOR_WEBGL,e=i.UNMASKED_RENDERER_WEBGL}const i={vendor:(s.getParameter(t)||"").toString(),renderer:(s.getParameter(e)||"").toString()};return JSON.stringify(i)}}return null}static z(){return b(this,void 0,void 0,(function*(){const e={p:d.currentPlatform(),f:s.currentFramework(),vc:this.getVideoCard(),rfp:this.initRNUniqueId()};return Io.e(JSON.stringify(e),5)}))}}class To{constructor(e){this.rocketsBuffer=new Set,this.socket=e,this.socket.addConnectedObserver(this.onSocketConnected.bind(this))}emit(e){this.socket.status!==t.DISCONNECTED?(e.start(),this.doEmit(e)):e.fail({resultCode:"409",content:"Please connect first"})}doEmit(e){if(!e.complete)if(this.socket.status!==t.CONNECT_FAILED)if(this.isConnected())if(this.hasPermission(e)){let t=setTimeout((()=>{this.doEmit(e)}),e.singleTimeout);e.unique&&(e.params.retried=e.retried),this.socket.socketio().emit(e.name,e.params,(s=>{clearTimeout(t),200===s.resultCode||200==s.code?e.success(s):e.fail(s)})),e.retried++}else e.fail({resultCode:401,content:"No permission"});else this.isConnecting()&&this.rocketsBuffer.add(e);else e.fail({resultCode:408,content:"Failed to connect GoEasy."})}hasPermission(e){return!!this.socket.permissions.find((t=>t===e.permission))}isConnected(){return[t.CONNECTED,t.RECONNECTED,t.EXPIRED_RECONNECTED,t.DISCONNECTING].includes(this.socket.status)}isConnecting(){return[t.CONNECTING,t.RECONNECTING].includes(this.socket.status)}onSocketConnected(){this.emitBuffer()}emitBuffer(){Array.from(this.rocketsBuffer).forEach((e=>{this.rocketsBuffer.delete(e),this.doEmit(e)}))}}class Ro extends Q{static init(){Ro.i=new Ro}static fire(e,t){this.i.fire(e,t)}static on(e,t){this.i.on(e,t)}static off(e,t){this.i.off(e,t)}}class ko extends uo{constructor(e,t){super(),this.ioSocket=null,this.sid=null,this.anonymous=!1,this.userId=null,this.artifactVersion=n,this.vname=null,this.uri=null,this.ioOpts=null,this.reconnectingTimes=0,this.messageObservers=new Map,this.connectFailedObservers=[],this.connectingObservers=[],this.expiredReconnectedObservers=[],this.options=e,this.ioSocket=new lo({onDisconnected:this.onIoDisconnected.bind(this),onReconnecting:this.onIoReconnecting.bind(this)}),this.ioSocketEmitter=new To(this.ioSocket),this.ioSocket.addConnectedObserver(this.onIoReconnected.bind(this)),this.initOptions(t),this.connect()}initUserId(){let e=this.connectOptions.id;u.isEmpty(e)?this.anonymous=!0:this.userId=e.toString()}socketio(){return this.ioSocket.socketio()}extendOptions(){let e=this.connectOptions;if(u.isNull(e.data)||u.isDef(e.data)&&!u.isObject(e.data))throw{code:400,content:"TypeError: data requires an object."};if((u.isDef(e.data)?String(e.data).length:0)>300&&u.isObject(e)&&u.isFunction(e.onFailed))throw{code:400,content:"user.data-length limit 300 byte."};if(u.isObject(e.wxmpId)){if(u.isEmpty(e.wxmpId.appid))throw{code:400,content:"wxmpId.appid is required."};if(u.isEmpty(e.wxmpId.openid))throw{code:400,content:"wxmpId.openid is required. requires string."}}else if(u.isPrimitive(e.wxmpId))throw{code:400,content:"TypeError: wxmpId requires an object."}}initUriAndOpts(){let e=this.options;Wn.init(e.host,e.forceTLS,e.supportOldBrowser),this.uri=Wn.uri();let t=["websocket"];!0===e.supportOldBrowser&&t.push("polling"),this.ioOpts={transports:t,timeout:S.connect,reconnectionDelayMax:S.reconnectionDelayMax}}onIoReconnected(){this.status===t.RECONNECTING&&this.authorize()}sendAck(e,t){this.ioSocket.io.emit(e,t)}initOptions(e){this.connectOptions=e,this.addConnectedObserver(e.onSuccess),this.addConnectFailedObserver(e.onFailed),this.addConnectingObserver(e.onProgress),this.initUserId()}connect(){this.initUriAndOpts(),this.extendOptions(),super.connect(),this.onConnecting(),this.ioSocket.connect({uri:this.uri,opts:this.ioOpts}),this.authorize()}disconnect(){return new Promise(((e,s)=>{this.status=t.DISCONNECTING;let i=()=>{this.ioSocket.disconnect(),this.status=t.DISCONNECTED,Ro.fire(Gt.DISCONNECTED),e()};const n=X.modules.get("GN");if(n&&(n.params.regId||this.connectOptions.wxmpId)){let e=e=>{s(e)},t=new le({name:y.manualDisconnect,params:{},permission:ne.READ,singleTimeout:S.commonRequestSingle,totalTimeout:S.commonRequestTotal,fail:e,success:i});te.Socket.e(t)}else i()}))}authorize(){return b(this,void 0,void 0,(function*(){let e=this.connectOptions,t={appkey:this.options.appkey,userId:this.userId,userData:JSON.stringify(e.data),otp:e.otp,artifactVersion:this.artifactVersion,sid:this.sid,mP:yield X.getParams(),a:this.anonymous,z:yield No.z(),sm:yield wo.get(),c:{n:this.vname,v:this.artifactVersion}};JSON.stringify(t);let s=new le({name:y.authorize,params:t,permission:ne.NONE,singleTimeout:S.commonInfiniteSingle,totalTimeout:S.commonInfiniteTotal,success:e=>{this.onAuthorizeSuccess(e)},fail:e=>{this.onAuthorizeFailed(e)}});this.ioSocketEmitter.emit(s)}))}onConnecting(){Ro.fire(Gt.CONNECTING,this.reconnectingTimes),this.notify(this.connectingObservers,this.reconnectingTimes)}onIoReconnecting(){this.reconnectingTimes++,this.status==t.CONNECTED||this.status==t.EXPIRED_RECONNECTED||this.status==t.RECONNECTING?this.status=t.RECONNECTING:this.status=t.CONNECTING,this.onConnecting()}onIoDisconnected(){this.status!==t.DISCONNECTING&&(this.status=t.RECONNECTING,Ro.fire(Gt.LOST),this.notify(this.disconnectedObservers))}onAuthorizeSuccess(e){if(wo.put(e),X.setDatas(e.mD),this.status===t.RECONNECTING){this.sid!==e.sid?(this.status=t.EXPIRED_RECONNECTED,this.sid=e.sid,Ro.fire(Gt.EXPIRED_RECONNECTED),this.notify(this.expiredReconnectedObservers)):(this.status=t.RECONNECTED,Ro.fire(Gt.RECONNECTED))}else this.status=t.CONNECTED,this.sid=e.sid;e.enablePublish&&(this.permissions.find((e=>e==ne.WRITE))||this.permissions.push(ne.WRITE)),e.enableSubscribe&&(this.permissions.find((e=>e==ne.READ))||this.permissions.push(ne.READ)),this.reconnectingTimes=0,Ro.fire(Gt.CONNECTED),this.notify(this.connectedObservers)}onAuthorizeFailed(e){this.ioSocket.disconnect(),this.status=t.CONNECT_FAILED;let s={code:e.resultCode||408,content:e.content||"Host unreachable or timeout"};this.notify(this.connectFailedObservers,s)}addConnectingObserver(e){u.isFunction(e)&&this.connectingObservers.push(e)}addConnectFailedObserver(e){u.isFunction(e)&&this.connectFailedObservers.push(e)}addExpiredReconnectedObserver(e){u.isFunction(e)&&this.expiredReconnectedObservers.push(e)}onMessage(e,t){this.ioSocket.io._callbacks.hasOwnProperty("$"+e)||this.ioSocket.io.on(e,t)}user(){let e=this.connectOptions;return e?{id:e.id,data:e.data}:null}}class Ao{constructor(e){this.guidList=[],this.socket=e}offMessage(e,t){Ro.off(Gt.NEW_MESSAGE+"_"+e,t)}onMessage(e,t){Ro.on(Gt.NEW_MESSAGE+"_"+e,t),this.socket.onMessage(e,(t=>{this.fire(e,t)}))}fire(e,t){let s=this.filter(t);s&&Ro.fire(Gt.NEW_MESSAGE+"_"+e,s)}filter(e){if("string"==typeof e&&(e=JSON.parse(e)),e.i){const t=`${e.i}_${e.r}`;if(this.guidList.findIndex((e=>e===t))>-1)return;this.guidList.unshift(t),this.guidList.length>300&&this.guidList.pop()}return e}}class Oo{static init(e){this.i=new Oo(e)}constructor(e){this.goeasyOptions=e}static connect(e,s){if(this.status()!==t.DISCONNECTED&&u.isObject(e)&&u.isFunction(e.onFailed))return void e.onFailed({code:408,content:"It is already connected, don't try again until disconnect() is called. "});Nt(Ye,e),Ro.init();let i=this.i;X.preConnect(e),i.socket=new ko(i.goeasyOptions,e),i.socket.vname=s,i.emitter=new To(i.socket),i.messageListener=new Ao(i.socket),X.postConnect()}static e(e){this.i.emitter.emit(e)}static sendAck(e,t){this.i.socket.sendAck(e,t)}static status(){return this.i&&this.i.socket?this.i.socket.getStatus():t.DISCONNECTED}static on(e,t){Ro.on(e,t)}static off(e,t){Ro.off(e,t)}static offMessage(e,t){this.i.messageListener.offMessage(e,t)}static onMessage(e,t){this.i.messageListener.onMessage(e,t)}static disconnect(e){this.status()===t.CONNECTED||this.status()===t.RECONNECTED?this.i.socket.disconnect().then((()=>{v.onSuccess(e)})).catch((t=>{v.onFailed(e,t)})):v.onFailed(e,{code:408,content:"Host unreachable or timeout"})}static user(){return this.i.socket.user()}}Oo.EVENT=Gt;class Po{static getInstance(){return Po.instance||(Po.instance=new Po),Po.instance}constructor(){this.synchronized=!0,this.onlineChanged=e=>{e.online?this.teamIds.add(e.teamId):this.teamIds.delete(e.teamId)},this.onDisconnected=()=>{this.queryMyTeamPromise=null,this.teamIds=null},this.onConnected=()=>{this.synchronized&&(this.queryMyTeamPromise=this.queryTeams())},Oo.on(Oo.EVENT.LOST,this.onDisconnected),Oo.on(Oo.EVENT.RECONNECTED,this.onConnected),Oo.onMessage(Ut.CS_ONLINE_CHANGED,this.onlineChanged)}queryTeams(){return this.queryMyTeamPromise||(this.queryMyTeamPromise=new Promise(((e,t)=>{let s=new le({name:y.CS_MY_TEAMS,params:{},permission:ne.READ,singleTimeout:S.commonQuerySingle,totalTimeout:S.commonQueryTotal,fail:e=>{t(e)},success:t=>{this.teamIds=new Set(t.content),this.synchronized=!0,e(this.teamIds)}});te.Socket.e(s)}))),this.queryMyTeamPromise}myTeams(){if(this.synchronized&&this.queryMyTeamPromise)return this.teamIds;throw"please query team first."}isOnline(e,t){return b(this,void 0,void 0,(function*(){yield this.queryTeams(),v.onSuccess(t,this.teamIds.has(e))}))}online(e,t){if(!u.isObject(t.agentData)||!u.isObject(t.teamData))throw{code:400,content:"agentData and teamData require an object"};let s=new Us(e,t.teamData,t.agentData),i=new le({name:y.CS_ONLINE,params:s,permission:ne.WRITE,singleTimeout:S.commonRequestSingle,totalTimeout:S.commonRequestTotal,fail:e=>{v.onFailed(t,e)},success:s=>{this.teamIds.add(e),v.onSuccess(t),gs.i.fire(cs.CS_ONLINE_SUCCESS)}});te.Socket.e(i)}offline(e,t){let s=new Gs(e),i=new le({name:y.CS_OFFLINE,params:s,permission:ne.WRITE,singleTimeout:S.commonRequestSingle,totalTimeout:S.commonRequestTotal,fail:e=>{v.onFailed(t,e)},success:s=>{this.teamIds.delete(e),v.onSuccess(t),gs.i.fire(cs.CS_OFFLINE_SUCCESS)}});te.Socket.e(i)}agents(e,t){let s=new Fs(e),i=new le({name:y.CS_AGENTS,params:s,permission:ne.READ,singleTimeout:S.commonQuerySingle,totalTimeout:S.commonQueryTotal,fail:e=>{v.onFailed(t,e)},success:e=>{e.content.forEach((e=>{e.data=JSON.parse(e.data)})),v.onSuccess(t,e)}});te.Socket.e(i)}}class _o{constructor(e){this.onMessageReceived=e=>{let t=_o.session;if(e.scene()===o.CS&&t.liveOptions){let s=e,i=t.liveOptions.customerId;t.teamId===s.teamId&&s.customerId()===i&&(t.tryUpdateStatus(s),t.liveOptions.onNewMessage(s))}},this.teamId=e,gs.i.on(cs.CS_AGENT_MESSAGE_RECEIVED,this.onMessageReceived),gs.i.on(cs.CS_ACCEPTED,this.onMessageReceived),gs.i.on(cs.CS_ENDED,this.onMessageReceived),gs.i.on(cs.CS_TRANSFER,this.onMessageReceived),Oo.on(Gt.DISCONNECTED,_o.destroy)}static live(e,t){return b(this,void 0,void 0,(function*(){let s=t.customerId;Tt(s);let i=new Ds(e,s);yield Po.getInstance().queryTeams();let n=new le({name:y.CS_LIVE_SESSION,params:i,permission:ne.WRITE,singleTimeout:S.commonRequestSingle,totalTimeout:S.commonRequestTotal,fail:e=>{v.onFailed(t,e)},success:s=>{_o.destroy(),this.session=new _o(e),this.session.liveOptions=t;let i=s.content.customerStatus;"ACCEPTED"===i.status&&(i.agent.data=JSON.parse(i.agent.data)),this.session.status=i,this.session.liveOptions.onStatusUpdated(this.session.status),v.onSuccess(t)}});te.Socket.e(n)}))}customerId(){return this.liveOptions.customerId}static isMyCustomer(e){let t=_o.session;if(t&&t.teamId===e.teamId&&t.customerId()===e.customerId()){let s=Po.getInstance().myTeams(),i=t.status.agent;return s.has(e.teamId)&&(!i||i.id===te.Socket.user().id)}return!0}static isMyMessage(e){let t=je.byIMMessage(e);return e.type===us.TRANSFER&&e.payload.transferTo.id===te.Socket.user().id||this.isMyCustomer(t)}static quit(e){let t=_o.session;if(t){let s=t.liveOptions.customerId;Tt(s);let i=new Ds(t.teamId,s),n=new le({name:y.CS_QUIT_LIVE,params:i,permission:ne.WRITE,singleTimeout:S.commonRequestSingle,totalTimeout:S.commonRequestTotal,fail:t=>{v.onFailed(e,t)},success:t=>{_o.destroy(),v.onSuccess(e)}});te.Socket.e(n)}}tryUpdateStatus(e){if("FREE"!==this.status.status&&this.status.sessionId>e.sessionId)return;let t;switch(e.type){case us.ACCEPT:t=new xs,t.status="ACCEPTED",t.start=e.payload.sessionStart,t.sessionId=e.sessionId,t.agent=new c(e.senderId,e.senderData);break;case us.END:t=new xs,t.status="FREE";break;case us.TRANSFER:t=new xs,t.status="ACCEPTED",t.start=e.payload.sessionStart,t.sessionId=e.sessionId,t.agent=e.payload.transferTo;break;default:"FREE"===this.status.status&&(t=new xs,t.status="PENDING",t.start=e.timestamp,t.sessionId=e.sessionId)}t&&(this.status=t,this.liveOptions.onStatusUpdated(t))}}_o.destroy=()=>{let e=_o.session;e&&(gs.i.off(cs.CS_AGENT_MESSAGE_RECEIVED,e.onMessageReceived),gs.i.off(cs.CS_ACCEPTED,e.onMessageReceived),gs.i.off(cs.CS_ENDED,e.onMessageReceived),gs.i.off(cs.CS_TRANSFER,e.onMessageReceived),Oo.off(Gt.DISCONNECTED,_o.destroy),_o.session=null)};class Do extends _s{constructor(e){super(e),this.unread=0,this.markingAmount=0}loadHistory(e,t){return b(this,void 0,void 0,(function*(){return u.isUndef(t)?t=10:t>30&&(t=30),yield this.loadServerMessages(e,t)}))}loadServerMessages(e,t){return b(this,void 0,void 0,(function*(){let s=new Rs(this.target.id.toString(),this.target.scene,e,t,this.target.teamId),i=yield this.remoteHistory.loadServerMessages(this.target,s);return i.userOffsets.forEach((e=>{this.userOffsets.updateOffset(e.userId,e.offset)})),i.messages}))}deleteMessages(e){return b(this,void 0,void 0,(function*(){v.onFailed(e,"Delete CS message is not supported yet")}))}initMaxMessageAndOffsets(e,t){t.forEach((e=>{this.userOffsets.updateOffset(e.userId,e.offset)})),(u.isUndef(this.acceptedMaxMessage)||this.acceptedMaxMessage.timestamp<e.timestamp)&&this.increaseUnreadAmount(e),this.saveAcceptedMessage(e)}initPendingMaxMessageAndOffsets(e,t){t.forEach((e=>{this.userOffsets.updateOffset(e.userId,e.offset)})),this.savePendingMessage(e)}savePendingMessage(e){this.pendingMaxMessage?this.pendingMaxMessage.timestamp<e.timestamp&&(this.pendingMaxMessage=e):this.pendingMaxMessage=e}saveAcceptedMessage(e){this.acceptedMaxMessage?this.acceptedMaxMessage.timestamp<e.timestamp&&(this.acceptedMaxMessage=e):this.acceptedMaxMessage=e}onMessageSending(e){this.saveAcceptedMessage(e),gs.i.fire(cs.MAX_MESSAGE_CHANGED,{message:e,receiver:this.to})}onMessageSendSuccess(e){this.saveAcceptedMessage(e),this.userOffsets.updateOffset(e.senderId,e.timestamp),this.acceptedMaxMessage===e&&gs.i.fire(cs.MAX_MESSAGE_CHANGED,{message:e,receiver:this.to})}onMessageSendFailed(e){this.acceptedMaxMessage===e&&gs.i.fire(cs.MAX_MESSAGE_CHANGED,{message:e,receiver:this.to})}onMessageReceived(e){_o.isMyMessage(e)&&(!e.accepted||e.senderId!==te.Socket.user().id&&e.type===us.ACCEPT?this.savePendingMessage(e):this.saveAcceptedMessage(e),this.userOffsets.updateOffset(e.senderId,e.timestamp),this.increaseUnreadAmount(e),gs.i.fire(cs.MAX_MESSAGE_CHANGED,{message:e,receiver:this.to}))}increaseUnreadAmount(e){if(e.sendByCustomer()||e.type===us.TRANSFER&&e.senderId!==te.Socket.user().id){this.userOffsets.myOffset()<e.timestamp&&e.accepted&&(this.unread+=1)}}markRead(){return b(this,void 0,void 0,(function*(){let e=this.maxAcceptedMessageTime();_o.isMyCustomer(this.target)&&this.preMark(e)&&(yield this.remoteHistory.updateServerOffsets(e,this.target),this.postMark(e))}))}preMark(e){let t=this.userOffsets.myOffset();return e>this.userOffsets.markingTime&&e>t&&(this.userOffsets.markingTime=e,this.markingAmount=this.unread,!0)}postMark(e){e===this.userOffsets.markingTime&&(this.unread-=this.markingAmount,this.markingAmount=0,this.userOffsets.updateOffset(te.Socket.user().id,e),gs.i.fire(cs.UNREAD_AMOUNT_CHANGED,this.target))}syncMarkedMessage(e){}getMaxMessage(e){return e?this.acceptedMaxMessage:this.pendingMaxMessage}unreadAmount(e){return e?this.unread:0}existsMessage(e){return this.acceptedMaxMessage&&this.acceptedMaxMessage.messageId===e.messageId||this.pendingMaxMessage&&this.pendingMaxMessage.messageId===e.messageId}maxAcceptedMessageTime(){return this.acceptedMaxMessage?this.acceptedMaxMessage.timestamp:0}maxTime(e){let t=this.getMaxMessage(e);return t?t.timestamp:0}}class xo extends _s{constructor(e){super(e)}deleteMessages(e){return b(this,void 0,void 0,(function*(){v.onFailed(e,"Delete CS message is not supported yet")}))}}class Uo{static init(){return Uo.instance=new Uo,Uo.instance}constructor(){this.map=new Map,this.onMessageSending=e=>{let t=je.byIMMessage(e.message),s=this.findOrCreateHistory(t);s.to=e.receiver,s.onMessageSending(e.message)},this.onMessageSendSuccess=e=>{let t=je.byIMMessage(e);this.findHistory(t).onMessageSendSuccess(e)},this.onMessageSendFailed=e=>{let t=je.byIMMessage(e);this.findHistory(t).onMessageSendFailed(e)},this.onMessageReceived=e=>{let t=je.byIMMessage(e),s=this.findOrCreateHistory(t);s.expiredTime>0&&(this.map.delete(t.toString()),s=this.findOrCreateHistory(t)),s.onMessageReceived(e)},this.onRemoteMarkRead=e=>{let t=je.byMessageReadRemoteEvent(e),s=this.findHistory(t);s&&s.syncMarkedMessage(e)},this.onRemoteMessageDeleted=e=>{let t=je.byIMMessageDeletedEvent(e),s=this.findHistory(t);s&&s.syncDeletedMessage(e.deleterId,e.times)},this.onMessageRecalled=e=>{let t=je.byConversationId(e.scene,e.conversationId),s=this.findHistory(t);s&&s.recallMessages(e)},this.onDisconnected=()=>{this.map.forEach(((e,t)=>{e.expire()}))},this.onReconnected=()=>{Os.fire(ls.HISTORY_EXPIRED)},this.destroy=()=>{},this.initialListeners()}initialListeners(){gs.i.on(cs.MESSAGE_SENDING,this.onMessageSending),gs.i.on(cs.MESSAGE_SEND_SUCCESS,this.onMessageSendSuccess),gs.i.on(cs.MESSAGE_SEND_FAILED,this.onMessageSendFailed),gs.i.on(cs.MESSAGE_RECEIVED,this.onMessageReceived),gs.i.on(cs.CS_AGENT_MESSAGE_RECEIVED,this.onMessageReceived),gs.i.on(cs.CS_ACCEPTED,this.onMessageReceived),gs.i.on(cs.CS_ENDED,this.onMessageReceived),gs.i.on(cs.CS_TRANSFER,this.onMessageReceived),gs.i.on(cs.MESSAGE_RECALLED,this.onMessageRecalled),Oo.onMessage(Ut.IM_MSG_READ,this.onRemoteMarkRead),Oo.onMessage(Ut.IM_MSG_DELETED,this.onRemoteMessageDeleted),Oo.on(Oo.EVENT.LOST,this.onDisconnected),Oo.on(Oo.EVENT.RECONNECTED,this.onReconnected)}loadHistory(e,t){return b(this,void 0,void 0,(function*(){Nt(mt,e);let s=this.queryToTarget(e,t),i=this.findOrCreateHistory(s);i.expiredTime>0&&(this.map.delete(s.toString()),i=this.findOrCreateHistory(s));let n=yield i.loadHistory(e.lastTimestamp,e.limit);v.onSuccess(e,{code:200,content:n})}))}queryToTarget(e,t){return e.userId?new je(o.PRIVATE,e.userId):e.groupId?new je(o.GROUP,e.groupId):(o.CS===e.type&&u.isUndef(t)&&(t=e.id),new je(e.type,e.id,t))}privateMarkAsRead(e){return b(this,void 0,void 0,(function*(){kt(e);let t=je.byScene(o.PRIVATE,e.userId);yield this.markAsRead(t,e)}))}groupMarkAsRead(e){return b(this,void 0,void 0,(function*(){At(e);let t=je.byScene(o.GROUP,e.groupId);yield this.markAsRead(t,e)}))}markMessageAsRead(e,t){return b(this,void 0,void 0,(function*(){Nt(pt,e),o.CS==e.type&&u.isUndef(t)&&(t=e.id);let s=je.byScene(e.type,e.id,t);yield this.markAsRead(s,e)}))}markAsRead(e,t){return b(this,void 0,void 0,(function*(){let s=this.findHistory(e);s&&(yield s.markRead()),v.onSuccess(t)}))}deleteMessage(e){return b(this,void 0,void 0,(function*(){Nt(at,e);let t=e.messages[0],s=je.byIMMessage(t),i=this.findHistory(s);if(!i)throw{code:400,content:"No message that could be deleted"};yield i.deleteMessages(e)}))}findOrCreateHistory(e){let t=this.findHistory(e);return t||(t=e.scene===o.CS?te.Socket.user().id===e.customerId()?new xo(e):new Do(e):new _s(e),this.map.set(e.toString(),t),t)}static get(e){return Uo.instance.findOrCreateHistory(e)}findHistory(e){return this.map.get(e.toString())}}class Go{constructor(e){this.top=!1,this.data=null,this.dataLoaded=!1,this.target=e}toDto(){let e=this.target.scene,t=this.target.id,s=new a;return e===o.PRIVATE?s.userId=t:e===o.GROUP?s.groupId=t:e===o.CS&&(s.id=this.target.teamId),s.type=e,s.lastMessage=this.getMaxMessage(),s.unread=this.getUnreadAmount(),s.top=this.top,s.data=this.data,s}getMaxMessage(){return Uo.get(this.target).getMaxMessage()}getUnreadAmount(){return Uo.get(this.target).unreadAmount()}maxMessageTime(){return Uo.get(this.target).maxTime()}}class Fo extends Go{constructor(e){super(e),this.accepted=!1}toDto(){let e=new a,t=this.target.scene,s=this.target.id,i=this.target.teamId;return e.id=s,e.teamId=i,e.type=t,e.lastMessage=this.getMaxMessage(),e.unread=this.getUnreadAmount(),e.top=this.top,e.data=this.data,e.ended=this.isEnded(),e}isEnded(){let e=this.getMaxMessage(),t=e.type,s=e.payload;return t===us.END||t===us.TRANSFER&&s.transferTo.id!==te.Socket.user().id}getMaxMessage(){return Uo.get(this.target).getMaxMessage(this.accepted)}getUnreadAmount(){return Uo.get(this.target).unreadAmount(this.accepted)}maxMessageTime(){return Uo.get(this.target).maxTime(this.accepted)}}class Lo{constructor(e,t,s,i){this.type=e,this.top=t,this.targetId=s,this.teamId=i}}class Bo{constructor(e,t,s){this.type=e,this.targetId=t,this.teamId=s}}class qo{constructor(e,t,s){this.type=e,this.targetId=t,this.teamId=s}}class jo{top(e,t){let s=new Lo(e.scene,t,e.id,e.teamId);return new Promise(((e,t)=>{let i=new le({name:y.topConversation,params:s,permission:ne.WRITE,singleTimeout:S.commonRequestSingle,totalTimeout:S.commonRequestTotal,success:s=>{200===s.code?e(s):t(s)},fail:e=>{t(e)}});te.Socket.e(i)}))}remove(e){let t=new Bo(e.scene,e.id,e.teamId);return new Promise(((e,s)=>{let i=new le({name:y.removeConversation,params:t,permission:ne.WRITE,singleTimeout:S.commonRequestSingle,totalTimeout:S.commonRequestTotal,success:t=>{200==t.code?e(t):s(t)},fail:e=>{s(e)}});te.Socket.e(i)}))}query(e){return new Promise(((t,s)=>{let i=new le({name:e,params:{},permission:ne.READ,singleTimeout:S.commonQuerySingle,totalTimeout:S.commonQueryTotal,fail:e=>{s(e)},success:e=>b(this,void 0,void 0,(function*(){t(e)}))});te.Socket.e(i)}))}loadData(e){let t=new qo(e.scene,e.id,e.teamId);return new Promise(((e,s)=>{let i=new le({name:y.imData,params:t,permission:ne.READ,singleTimeout:S.commonQuerySingle,totalTimeout:S.commonQueryTotal,success:t=>{let s=JSON.parse(t.content);e(s)},fail:e=>{s(e)}});te.Socket.e(i)}))}}jo.instance=new jo;class Vo{constructor(){this.list=new Array,this.builder=new Is,this.remoteConversations=jo.instance,this.synchronized=!1,gs.i.on(cs.MAX_MESSAGE_CHANGED,this.onMaxMessageChanged.bind(this)),gs.i.on(cs.UNREAD_AMOUNT_CHANGED,this.onUnreadMessageChanged.bind(this)),gs.i.on(cs.MAX_MESSAGE_DELETED,this.onMaxMessageDeleted.bind(this))}onUnreadMessageChanged(e){this.findConversation(e)&&this.fireUpdated()}fireUpdated(){this.debounce(this.triggerUpdate.bind(this))}triggerUpdate(){let e=this.loadLocalConversations(),t=this.getUpdatedEventName();Os.fire(t,{unreadTotal:e.content.unreadTotal,conversations:e.content.conversations})}getUpdatedEventName(){return ls.CONVERSATIONS_UPDATED}latestConversations(e){return b(this,void 0,void 0,(function*(){this.synchronized||(yield this.loadServerConversations());let t=this.loadLocalConversations();v.onSuccess(e,t)}))}loadServerConversations(){return b(this,void 0,void 0,(function*(){var e,t;let s=this.rocketName(),i=yield this.remoteConversations.query(s);this.convertAbbrConversation(i.content);const n=null===(t=null===(e=i.content[i.content.length-1])||void 0===e?void 0:e.lmsg)||void 0===t?void 0:t.i;yield this.loadCustomConversation(n),this.synchronized=!0}))}loadCustomConversation(e){return b(this,void 0,void 0,(function*(){if(void 0!==Ps.instance){const t=yield Ps.instance.loadConversations(te.Socket.user().id,e);for(const e of t){e.lastMessage=Ps.convertAbstractMessage(e.lastMessage);const t=e.lastMessage,s=je.byIMMessage(t);let i=this.findConversation(s);u.isUndef(i)&&(i=new Go(s),i.dataLoaded=!0,i.top=e.top,i.data=e.data,this.insertOne(i)),Uo.get(s).initMaxMessageAndOffsets(t,[]),this.correctPosition(i)}}}))}rocketName(){return y.imLastConversations}convertAbbrConversation(e){let t=e;for(const e of t){let t=e.t,s=e.top,i=e.d?JSON.parse(e.d):{},n=e.userOffsets;e.lmsg.t=t;let r=e.lmsg,a=this.builder.build(r),c=je.byIMMessage(a),l=this.findConversation(c);u.isUndef(l)?(l=this.buildByAbbr(e,a),this.insertOne(l)):(l.top=s,l.data=i),c.scene===o.GROUP&&(a.x=1),Uo.get(c).initMaxMessageAndOffsets(a,n),this.correctPosition(l)}}onMaxMessageDeleted(e){this.removeConversation(e)}onMaxMessageChanged(e){return b(this,void 0,void 0,(function*(){const t=e.message;if(t.scene()===o.CS){let e=t;if(te.Socket.user().id!=e.customerId()&&(!1===e.accepted||e.type===us.ACCEPT&&e.senderId!=te.Socket.user().id))return}yield this.saveOrUpdateConversation(e)}))}saveOrUpdateConversation(e){return b(this,void 0,void 0,(function*(){const t=e.message;let s=t.status,i=je.byIMMessage(t),n=this.findConversation(i);u.isUndef(n)&&s!==r.FAIL&&(n=this.buildByMessage(t),this.insertOne(n),s===r.SUCCESS&&(n.data=yield this.remoteConversations.loadData(i),n.dataLoaded=!0)),s===r.SENDING&&(n.data=e.receiver,n.dataLoaded=!0),n&&n.dataLoaded&&(this.correctPosition(n),this.fireUpdated())}))}debounce(e){clearTimeout(this.timer),this.timer=setTimeout((()=>{e()}),500)}loadLocalConversations(){let e=0,t=new Array;for(const s of this.list)if(s.dataLoaded&&s.getMaxMessage()){e+=s.getUnreadAmount();let i=s.toDto();t.push(i)}return{code:200,content:{unreadTotal:e,conversations:t}}}findConversationIndex(e){return this.list.findIndex((t=>e.toString()===t.target.toString()))}findConversation(e){let t=this.findConversationIndex(e);return this.list[t]}removeLocalConversation(e){let t=this.findConversationIndex(e.target);this.list.splice(t,1)}insertOne(e){Vo.sortedInserter.insert(this.list,e)}correctPosition(e){this.removeLocalConversation(e),this.insertOne(e)}removeConversation(e){let t=this.findConversation(e);t&&(this.removeLocalConversation(t),this.fireUpdated())}top(e,t,s){return b(this,void 0,void 0,(function*(){if(!u.isBoolean(t))throw new Error("top must be boolean.");let i=this.findConversation(e);if(!i)throw new Error("conversation does not exist.");i.top!=t&&(yield this.remoteConversations.top(e,t),i.top=t,this.correctPosition(i)),this.fireUpdated(),v.onSuccess(s)}))}remove(e,t){return b(this,void 0,void 0,(function*(){let s=this.findConversation(e);if(!s)throw new Error("conversation does not exist.");if(s instanceof Fo&&!s.isEnded())throw new Error("CS conversation can only be deleted after it ends");yield this.remoteConversations.remove(e),this.removeLocalConversation(s),this.fireUpdated(),v.onSuccess(t)}))}buildByAbbr(e,t){let s,i=je.byIMMessage(t);if(e.t===o.CS){let e=t;te.Socket.user().id===e.customerId()?s=new Go(i):(s=new Fo(i),s.accepted=e.accepted)}else s=new Go(i);return s.dataLoaded=!0,s.top=e.top,s.data=e.d?JSON.parse(e.d):{},s}buildByMessage(e){let t,s=je.byIMMessage(e);if(e.scene()===o.CS){let i=e;te.Socket.user().id===i.customerId()?t=new Go(s):(t=new Fo(s),t.accepted=i.accepted)}else t=new Go(s);return t}}Vo.sortedInserter=new class extends Es{compare(e,t){if(e.target.scene===t.target.scene&&e.target.id===t.target.id)return 0;let s;if(e.top==t.top){let i=e.maxMessageTime();s=t.maxMessageTime()-i}else s=e.top?-1:1;return s>0?1:-1}};class Ho extends J{static init(){return this.module=new Ho,this.module.name=this.GIM_MODULE_NAME,this.initGN(),this.module}static initGN(){he.addAssembler(new class{assemble(e){let t={messageId:e.id,timestamp:e.tm,type:e.t,senderId:e.sid,toType:e.tt};return e.tt===o.GROUP&&(t.groupId=e.gid),t}support(e){return!!e.sid}})}postConnect(){Xr.init()}static check(){if(!this.module)throw{code:400,content:"IM not initialized. Please include 'IM' in the 'modules' during GoEasy initialization."}}}Ho.GIM_MODULE_NAME="GIM";class zo extends Vo{constructor(){super(),this.expired=!1,gs.i.on(cs.CS_ONLINE_SUCCESS,this.onCSOnlineSuccess.bind(this)),gs.i.on(cs.CS_OFFLINE_SUCCESS,this.onCSOfflineSuccess.bind(this)),Oo.on(Oo.EVENT.LOST,this.onDisconnected.bind(this)),Oo.on(Oo.EVENT.RECONNECTED,this.onConnected.bind(this))}onMaxMessageChanged(e){return b(this,void 0,void 0,(function*(){const t=e.message;if(t.scene()===o.CS){let s=t;if(s.customerId()!=te.Socket.user().id&&(!1===s.accepted||s.type===us.ACCEPT))if(us.ACCEPT===t.type){let e=je.byIMMessage(t);this.removeConversation(e)}else yield this.saveOrUpdateConversation(e)}}))}latestConversations(e){const t=Object.create(null,{latestConversations:{get:()=>super.latestConversations}});return b(this,void 0,void 0,(function*(){let s=this.synchronized;yield t.latestConversations.call(this,e),this.list.length>0&&!s&&this.fireUpdated()}))}onUnreadMessageChanged(e){}onCSOnlineSuccess(){return b(this,void 0,void 0,(function*(){yield this.loadServerConversations(),this.fireUpdated()}))}onCSOfflineSuccess(){this.list=[],this.fireUpdated()}getUpdatedEventName(){return ls.PENDING_CONVERSATIONS_UPDATED}rocketName(){return y.CS_PENDING_CONVERSATION}convertAbbrConversation(e){return b(this,void 0,void 0,(function*(){let t=e;for(const e of t){e.lastMessage.t=o.CS;let t=e.customerData,s=e.lastMessage,i=e.userOffsets,n=t?JSON.parse(t):{},r=this.builder.build(s),a=je.byIMMessage(r),c=this.findConversation(a);u.isUndef(c)&&(c=new Fo(a),c.accepted=r.accepted,c.dataLoaded=!0,this.insertOne(c)),c.top=!1,c.data=n,Uo.get(a).initPendingMaxMessageAndOffsets(r,i),this.correctPosition(c)}}))}onDisconnected(){this.expired=!0}onConnected(){return b(this,void 0,void 0,(function*(){this.expired&&Ho.module&&Ho.module.active&&(this.expired=!1,this.list=[],yield this.loadServerConversations(),this.fireUpdated())}))}}class Wo{constructor(){this.conversations=new Vo,this.pendingConversations=new zo}latestConversations(e){this.conversations.latestConversations(e)}latestPendingConversations(e){this.pendingConversations.latestConversations(e)}topPrivateConversation(e){let t=je.byScene(o.PRIVATE,e.userId);this.conversations.top(t,e.top,e)}topGroupConversation(e){let t=je.byScene(o.GROUP,e.groupId);this.conversations.top(t,e.top,e)}topConversation(e){let t=e.conversation;this.validateConversationDTO(t);let s=je.byConversationDTO(t);this.conversations.top(s,e.top,e)}removePrivateConversation(e){let t=je.byScene(o.PRIVATE,e.userId);this.conversations.remove(t,e)}removeGroupConversation(e){let t=je.byScene(o.GROUP,e.groupId);this.conversations.remove(t,e)}removeConversation(e){let t=e.conversation;this.validateConversationDTO(t);let s=je.byConversationDTO(t);this.conversations.remove(s,e)}validateConversationDTO(e){if(!(e instanceof a))throw new Error("Incorrect conversation object.");{let t=e.lastMessage;if(t instanceof We&&t.customerId()!==te.Socket.user().id&&!1===t.accepted)throw new Error("pending conversation cannot be topped or removed.")}}}class Jo{constructor(){this.builder=new Is,te.Socket.onMessage(Ut.imMessage,this.onMessageReceived.bind(this))}sendAck(e){te.Socket.sendAck("imAck",{publishGuid:e})}createNotification(e){const t=te.N.supportAppNotification();if(!u.isObject(e.nt)||e.s===te.Socket.user().id||!t)return;let s={id:e.i,tm:e.ts,t:e.mt,sid:e.s,tt:e.t};s.tt===o.GROUP&&(s.gid=e.r),te.N.createLocalNotification(e.nt.t,e.nt.c,s,e.nt.sound,e.nt.badge)}}class Xo extends Jo{constructor(){super(),te.Socket.onMessage(Ut.IM_MSG_SYNC,this.onSyncMessageReceived.bind(this)),te.Socket.onMessage(Ut.IM_MSG_NEW,this.onNewMessageReceived.bind(this))}onMessageReceived(e){if(e.t!==o.CS){let t=this.builder.build(e);this.sendAck(t.messageId);let s=je.byIMMessage(t),i=s.scene;Uo.get(s).existsMessage(t)||(this.createNotification(e),gs.i.fire(cs.MESSAGE_RECEIVED,t),i===o.PRIVATE?Os.fire(ls.PRIVATE_MESSAGE_RECEIVED,t):i===o.GROUP&&Os.fire(ls.GROUP_MESSAGE_RECEIVED,t))}}onSyncMessageReceived(e){this.sendAck(e.i),e.rs.forEach((t=>{const s=Object.assign({},e);s.t=o.PRIVATE,s.r=t,s.s=te.Socket.user().id,delete s.rs;let i=this.builder.build(s),n=je.byIMMessage(i),r=n.scene;Uo.get(n).existsMessage(i)||(this.createNotification(s),gs.i.fire(cs.MESSAGE_RECEIVED,i),r===o.PRIVATE?Os.fire(ls.PRIVATE_MESSAGE_RECEIVED,i):r===o.GROUP&&Os.fire(ls.GROUP_MESSAGE_RECEIVED,i))}))}onNewMessageReceived(e){let t=this.builder.build(e);this.sendAck(t.messageId);let s=je.byIMMessage(t),i=s.scene;Uo.get(s).existsMessage(t)||(this.createNotification(e),gs.i.fire(cs.MESSAGE_RECEIVED,t),i===o.PRIVATE?Os.fire(ls.PRIVATE_MESSAGE_RECEIVED,t):i===o.GROUP&&Os.fire(ls.GROUP_MESSAGE_RECEIVED,t))}}class $o{constructor(){this.subscribedGroups=[],te.Socket.on(Gt.EXPIRED_RECONNECTED,this.expiredResubscribeGroups.bind(this))}expiredResubscribeGroups(){this.subscribedGroups.forEach((e=>b(this,void 0,void 0,(function*(){yield this.doSubscribeGroup(e)}))))}subscribe(e){Pt(e);let t=new Yo(e.groupIds,e.accessToken);this.doSubscribeGroup(t).then((()=>{this.subscribedGroups.push(t),v.onSuccess(e,{code:200,content:"ok"})})).catch((t=>{v.onFailed(e,{code:t.resultCode||408,content:t.content||"Failed to subscribe group message"})}))}doSubscribeGroup(e){return new Promise(((t,s)=>{let i=e.groupIds.toString().split(","),n=new le({name:y.subscribeGroups,params:{groupIds:i,at:e.accessToken},permission:ne.WRITE,singleTimeout:S.commonRequestSingle,totalTimeout:S.commonRequestTotal,success:()=>{t()},fail:e=>{s(e)}});te.Socket.e(n)}))}unsubscribe(e){At(e),e.groupId=e.groupId.toString();let t=new le({name:y.unsubscribeGroup,params:{groupId:e.groupId},permission:ne.READ,singleTimeout:S.commonRequestSingle,totalTimeout:S.commonRequestTotal,success:()=>{this.deleteSubscriptionByGroupId(e.groupId),v.onSuccess(e,{code:200,content:"ok"})},fail:t=>{v.onFailed(e,{code:t.resultCode||408,content:t.content||"Failed to unsubscribe group message"})}});te.Socket.e(t)}deleteSubscriptionByGroupId(e){this.subscribedGroups=this.subscribedGroups.filter((t=>{const s=t.groupIds.findIndex((t=>t==e));return s>-1&&t.groupIds.splice(s,1),t.groupIds.length>0}))}}class Yo{constructor(e,t){this.groupIds=e,this.accessToken=t}}class Qo{constructor(){this.newMessageReceived=e=>{let t=null;e.c&&(t=JSON.parse(e.c)),t&&t.events&&t.events.map((e=>{let s=e.userData?JSON.parse(e.userData):{},i={time:e.time,action:e.action,groupOnlineCount:t.userAmount,groupId:t.groupId,id:e.userId,data:s};Os.fire(ls.GROUP_PRESENCE,i)}))},Oo.onMessage(Ut.groupPresence,this.newMessageReceived)}presence(e){Pt(e),e.groupIds.toString().split(",");let t={groupIds:e.groupIds};this.emitRocket(y.subscribeGroupPresence,t,(()=>{v.onSuccess(e,{code:200,content:"ok"})}),(t=>{v.onFailed(e,{code:t.code||408,content:t.content||"Failed to subscribe group message"})}),S.commonRequestSingle,S.commonRequestTotal)}unPresence(e){Nt(It,e),e.groupId=e.groupId.toString();let t={groupId:e.groupId};this.emitRocket(y.unsubscribeGroupPresence,t,(()=>{v.onSuccess(e,{code:200,content:"ok"})}),(t=>{v.onFailed(e,{code:t.code||408,content:t.content||"Failed to unsubscribe presence"})}),S.commonRequestSingle,S.commonRequestTotal)}emitRocket(e,t,s,i,n,o){let r=new le({name:e,params:t,singleTimeout:n,totalTimeout:o,permission:ne.WRITE,success:s,fail:i});te.Socket.e(r)}}class Ko{get(e){At(e),e.groupId=e.groupId.toString();let t=new le({name:y.imGroupOnlineCount,params:{groupId:e.groupId},permission:ne.READ,singleTimeout:S.commonQuerySingle,totalTimeout:S.commonQueryTotal,fail:function(t){v.onFailed(e,t||{code:408,content:"Failed to query online group users"})},success:function(t){200==t.code?v.onSuccess(e,t):v.onFailed(e,t)}});te.Socket.e(t)}}class Zo{doHereNow(e,t,s){let i=new le({name:e,params:t,permission:ne.READ,singleTimeout:S.commonQuerySingle,totalTimeout:S.commonQueryTotal,fail:e=>{v.onFailed(s,e)},success:e=>{let t=e.content;e.content=t.map((e=>{let t=e.userData?JSON.parse(e.userData):{};return{id:e.userId,data:t}})),v.onSuccess(s,e)}});te.Socket.e(i)}}class er extends Zo{hereNow(e){At(e),e.groupId=e.groupId.toString();let t={groupId:e.groupId};this.doHereNow(y.imGroupHereNow,t,e)}}class tr{constructor(){this.newMessageReceived=e=>{let t=[];e.c&&(t=JSON.parse(e.c).events||[]),t.map((e=>{let t=e.userData?JSON.parse(e.userData):{},s={time:e.time,action:e.action,id:e.userId,data:t};Os.fire(ls.USER_PRESENCE,s)}))},Oo.onMessage(Ut.userPresence,this.newMessageReceived)}presence(e){Ot(e),e.userIds.toString().split(",");let t={userIds:e.userIds};this.emitRocket(y.subscribeUserPresence,t,(()=>{v.onSuccess(e,{code:200,content:"ok"})}),(t=>{v.onFailed(e,{code:t.code||408,content:t.content||"Failed to subscribe group message"})}),S.commonRequestSingle,S.commonRequestTotal)}unPresence(e){kt(e),e.userId=e.userId.toString();let t={userId:e.userId};this.emitRocket(y.unsubscribeUserPresence,t,(()=>{v.onSuccess(e,{code:200,content:"ok"})}),(t=>{v.onFailed(e,{code:t.code||408,content:t.content||"Failed to unsubscribe presence"})}),S.commonRequestSingle,S.commonRequestTotal)}emitRocket(e,t,s,i,n,o){let r=new le({name:e,params:t,singleTimeout:n,totalTimeout:o,permission:ne.WRITE,success:s,fail:i});te.Socket.e(r)}}class sr extends Zo{hereNow(e){Ot(e),e.userIds.toString().split(","),this.doHereNow(y.imHereNow,e,e)}}const ir=new class{fileExtension(e,t){if(u.isString(e))try{let s=e.split(t);return s[s.length-1]}catch(e){throw Error(e)}}};class nr{}class or extends nr{constructor(){super(...arguments),this.contentType="",this.name="",this.size=0,this.url=""}}class rr extends or{constructor(){super(...arguments),this.width=0,this.height=0}}class ar{build(e){let t=this.create();return this.setPayload(e,t),t}}class cr extends ar{create(){return new or}setPayload(e,t){let s=t,i=e.createOptions.file;s.url=i.path,s.name=i.name,s.size=i.size,s.contentType=i.type,e.complete=Promise.resolve()}}class ur extends cr{create(){return new rr}setPayload(e,t){super.setPayload(e,t);let s=e.createOptions.file,i=t,n=s.path||s.tempFilePath,o=u.isEmpty(s.name)||void 0===s.name?n:s.name;i.name="wx-image."+ir.fileExtension(o,"."),i.contentType="image/"+ir.fileExtension(o,"."),i.url=n,i.size=s.size,e.complete=new Promise(((e,t)=>{wx.getImageInfo({src:i.url,success(t){i.width=t.width,i.height=t.height,e()},fail(e){t(e)}})}))}}class lr extends or{constructor(){super(...arguments),this.duration=0}}class dr extends cr{create(){return new lr}setPayload(e,t){super.setPayload(e,t);let s=e.createOptions.file,i=t,n=s.tempFilePath,o=u.isEmpty(s.name)||null==s.name?n:s.name,r=s.duration,a=s.fileSize;i.url=n,i.size=a,i.duration=r/1e3,i.name="wx-audio."+ir.fileExtension(o,"."),i.contentType="audio/"+ir.fileExtension(o,"."),e.complete=Promise.resolve()}}class hr extends nr{constructor(){super(...arguments),this.text=""}}class pr extends ar{create(){return new hr}setPayload(e,t){let s=t,i=e.createOptions;s.text=i.text,e.complete=Promise.resolve()}}class mr extends nr{constructor(){super(...arguments),this.video=new gr,this.thumbnail=new fr}}class fr{constructor(){this.name="",this.url="",this.width=0,this.height=0,this.contentType=""}initURL(e){d.currentPlatform()===l.BROWSER&&this.htmlUrl(e)}htmlUrl(e){let t=document.createElement("canvas");t.width=e.videoWidth,t.height=e.videoHeight,t.getContext("2d").drawImage(e,0,0,t.width,t.height),this.url=t.toDataURL("image/png")}}class gr{constructor(){this.name="",this.url="",this.width=0,this.height=0,this.contentType="",this.size=0,this.duration=0}}class yr extends ar{create(){return new mr}setPayload(e,t){let s=e.createOptions.file,i=t,n=i.video,o=i.thumbnail,{duration:r,height:a,size:c,tempFilePath:l,thumbTempFilePath:d,width:h,name:p=""}=s,m=u.isEmpty(p)?l:p;n.contentType="video/"+ir.fileExtension(m,"."),n.name="wx-video."+ir.fileExtension(m,"."),n.url=l,n.width=o.width=h,n.height=o.height=a,n.size=c,n.duration=r,o.url=d,o.contentType="image/jpg",o.name="wx-thumbnail.jpg",e.complete=Promise.resolve()}}class Sr extends ar{create(){return new or}setPayload(e,t){let s=t,i=e.createOptions.file;s.url=i.fullPath||i.path,s.name=i.name,s.size=i.size,s.contentType=i.type,i.type,e.complete=Promise.resolve()}}class Er extends Sr{create(){return new rr}setPayload(e,t){let s=t,i=e.createOptions.file;s.url=i.path,s.size=i.size;let n=u.isEmpty(i.name)||void 0===i.name?i.path:i.name;s.contentType="image/"+ir.fileExtension(n,"."),s.name="uni-image."+ir.fileExtension(n,"."),e.complete=new Promise(((e,t)=>{uni.getImageInfo({src:i.path,success(t){s.width=t.width,s.height=t.height,e()},fail(e){t(e)}})}))}}class vr extends Sr{create(){return new lr}setPayload(e,t){let s=e.createOptions,i=t,n=s.file,o=n.tempFilePath,r=u.isEmpty(n.name)||null==n.name?o:n.name;i.url=o,i.name="uni-audio."+ir.fileExtension(r,"."),i.contentType="audio/"+ir.fileExtension(r,"."),e.complete=new Promise(((e,t)=>{uni.getFileInfo({filePath:o,success:n=>{let r=n.size;if(i.size=r,0===r)e();else if(u.isDef(s.file.duration))i.duration=s.file.duration/1e3,e();else{const s=uni.createInnerAudioContext();s.src=o,s.onCanplay((function(n){n.errCode?(s.destroy(),t(n)):(i.duration=s.duration,s.destroy(),e())})),s.onError((i=>{s.destroy(),-99===i.errCode?e():t(i)}))}},fail(e){t(e)}})}))}}class br extends ar{create(){return new mr}setPayload(e,t){let s=e.createOptions.file,i=t,n=i.video,o=i.thumbnail,{duration:r,height:a,size:c,tempFilePath:l,width:d,name:h=""}=s,p=u.isEmpty(h)?l:h;n.size=c,n.width=d,n.height=a,n.url=l,n.duration=r,n.contentType="video/"+ir.fileExtension(p,"."),n.name="uni-video."+ir.fileExtension(p,"."),o.url=l,o.height=200,o.width=Number((n.width*o.height/n.height).toFixed(0)),o.contentType="image/jpg",o.name="uni-thumbnail.jpg",e.complete=Promise.resolve()}}class Cr extends ar{create(){return new or}setPayload(e,t){let s=t,i=e.createOptions.file,n=window.URL||window.webkitURL;s.url=n.createObjectURL(i),s.name=i.name,s.size=i.size,s.contentType=i.type,e.complete=Promise.resolve()}}class Mr extends Cr{create(){return new rr}setPayload(e,t){super.setPayload(e,t);let s=e.createOptions.file,i=t,n=window.URL||window.webkitURL,o=new Image;o.src=n.createObjectURL(s),e.complete=new Promise(((e,t)=>{o.onload=function(){i.width=o.width,i.height=o.height,n.revokeObjectURL(o.src),e()},o.onerror=function(e){n.revokeObjectURL(o.src),t(e)}}))}}class wr extends Cr{create(){return new lr}setPayload(e,t){super.setPayload(e,t);let s=e.createOptions.file,i=t,n=window.URL||window.webkitURL,o=document.createElement("audio");o.src=n.createObjectURL(s),e.complete=new Promise(((e,t)=>{o.onloadedmetadata=()=>{i.duration=o.duration,n.revokeObjectURL(o.src),e()},o.onerror=e=>{n.revokeObjectURL(o.src),t(e)}}))}}class Ir extends ar{create(){return new mr}setPayload(e,t){let s=e.createOptions.file,i=t,n=i.video,o=i.thumbnail,r=window.URL||window.webkitURL,a=document.createElement("video");a.src=r.createObjectURL(s),n.size=s.size,n.name=s.name,n.contentType=s.type,n.url=a.src,o.name=s.name,o.contentType="image/jpg",e.complete=new Promise(((e,t)=>{a.onloadedmetadata=()=>{n.duration=a.duration,n.width=a.videoWidth,n.height=a.videoHeight,o.width=a.videoWidth,o.height=a.videoHeight,o.url=this.getThumbnailUrl(a),r.revokeObjectURL(a.src),e()},a.onerror=function(e){r.revokeObjectURL(a.src),t(e)}}))}getThumbnailUrl(e){let t=document.createElement("canvas");return t.width=e.videoWidth,t.height=e.videoHeight,t.getContext("2d").drawImage(e,0,0,t.width,t.height),t.toDataURL("image/png")}}class Nr extends ar{create(){return new mr}setPayload(e,t){let s=e.createOptions.file,i=t,n=i.video,o=i.thumbnail,{duration:r,height:a,size:c,tempFilePath:u,tempVideoThumbPath:l,width:d}=s;n.size=c,n.width=d,n.height=a,n.url=u,n.duration=r,n.contentType="video/mp4",n.name="ali-video.mp4",o.url=l,o.height=200,o.width=Number((n.width*o.height/n.height).toFixed(0)),o.contentType="image/jpg",o.name="ali-thumbnail.jpg",e.complete=Promise.resolve()}}class Tr extends ar{create(){return new or}setPayload(e,t){e.complete=Promise.reject("Alipay not support file message.")}}class Rr extends Tr{create(){return new rr}setPayload(e,t){let s=t,i=e.createOptions.file;s.url=i.path,s.size=i.size,e.complete=new Promise(((e,t)=>{my.getImageInfo({src:i.path,success(t){s.width=t.width,s.height=t.height,s.contentType="image/"+t.type,s.name="ali-image."+t.type,e()},fail(e){t(e)}})}))}}class kr extends Tr{create(){return new lr}setPayload(e,t){let s=t,i=e.createOptions.file,n=i.tempFilePath;s.url=n,s.name="ali-audio."+ir.fileExtension(n,"."),s.contentType="audio/"+ir.fileExtension(n,"."),s.duration=i.duration,s.size=i.fileSize,e.complete=Promise.resolve()}}class Ar extends ar{create(){return new mr}setPayload(e,t){let s=e.createOptions.file,i=t,n=i.video,o=i.thumbnail,{duration:r,height:a,size:c,tempFilePath:u,thumbTempFilePath:l,width:d}=s;n.size=c,n.width=d,n.height=a,n.url=u,n.duration=r,n.contentType="video/"+ir.fileExtension(u,"."),n.name="baidu-video."+ir.fileExtension(u,"."),o.url=l,o.height=200,o.width=Number((n.width*o.height/n.height).toFixed(0)),o.contentType="image/"+ir.fileExtension(l,"."),o.name="baidu-thumbnail."+ir.fileExtension(u,"."),e.complete=Promise.resolve()}}class Or extends ar{create(){return new or}setPayload(e,t){e.complete=Promise.reject("Baidu app not support file message.")}}class Pr extends Or{create(){return new lr}setPayload(e,t){let s=t,i=e.createOptions.file,n=i.tempFilePath;s.url=n,s.name="baidu-audio."+ir.fileExtension(n,"."),s.contentType="audio/"+ir.fileExtension(n,"."),s.duration=i.duration/1e3,s.size=i.fileSize,e.complete=Promise.resolve()}}class _r extends Or{create(){return new rr}setPayload(e,t){let s=t,i=e.createOptions.file;s.url=i.path,s.size=i.size,e.complete=new Promise(((e,t)=>{swan.getImageInfo({src:i.path,success(t){s.width=t.width,s.height=t.height,s.contentType="image/"+t.type,s.name="baidu-image."+t.type,e()},fail(e){t(e)}})}))}}class Dr extends ar{create(){return new or}setPayload(e,t){let s=t,i=e.createOptions.file;const{uri:n,type:o,size:r,name:a}=i;s.url=decodeURIComponent(n),s.name=a,s.size=r,s.contentType=o,e.complete=Promise.resolve()}}class xr extends Dr{create(){return new rr}setPayload(e,t){let s=t,i=e.createOptions.file;const{uri:n,fileSize:o,type:r,fileName:a,width:c,height:u}=i;s.url=n,s.size=o,s.contentType=r,s.name=a,s.width=c,s.height=u,e.complete=Promise.resolve()}}class Ur extends ar{create(){return new mr}setPayload(e,t){let s=e.createOptions.file;const i=t,{video:n,thumbnail:o}=i,{uri:r,type:a,fileSize:c,fileName:u,duration:l,height:d,width:h}=s;n.size=c,n.width=h,n.height=d,n.url=r,n.duration=l,n.contentType=a,n.name=u,o.url=r,o.name="rn-thumbnail.jpg",o.height=200,o.width=Number((n.width*o.height/n.height).toFixed(0)),o.contentType="image/jpg",e.complete=Promise.resolve()}}class Gr extends Dr{create(){return new lr}setPayload(e,t){let s=e.createOptions,i=t,n=s.file;const{uri:o,name:r,duration:a,size:c}=n;i.url=o,i.duration=Number((a/1e3).toFixed(2)),i.size=c,i.name=r||"rn-audio."+ir.fileExtension(o,"."),i.contentType="audio/"+ir.fileExtension(o,"."),s.file={uri:o,type:i.contentType,name:i.name},e.complete=Promise.resolve()}}class Fr extends nr{}class Lr extends ar{create(){return new Fr}setPayload(e,t){let s=e.createOptions;t.payload=s.payload,e.complete=Promise.resolve()}}class Br{constructor(e,t){this.type=e,this.createOptions=t}}class qr{constructor(){this.framework=s.currentFramework(),this.platform=d.currentPlatform(),this.payloadBuilders={[e.UNIAPP]:{image:new Er,file:new Sr,audio:new vr,video:new br,text:new pr},[l.MP_WX]:{image:new ur,file:new cr,audio:new dr,video:new yr,text:new pr},[l.BROWSER]:{image:new Mr,file:new Cr,audio:new wr,video:new Ir,text:new pr},[l.MP_ALI]:{image:new Rr,file:new Tr,audio:new kr,video:new Nr,text:new pr},[l.MP_BAIDU]:{image:new _r,file:new Or,audio:new Pr,video:new Ar,text:new pr},[e.REACT_NATIVE]:{image:new xr,file:new Dr,audio:new Gr,video:new Ur,text:new pr},[l.MP_BYTE]:{image:new ur,file:new cr,audio:new dr,video:new yr,text:new pr}}}buildMessage(t,s){this.validate(s,t);const i=this.framework===e.UNKNOWN?this.platform:this.framework;let n=this.payloadBuilders[i][t],o=new Br(t,s);if(n){let e=n.build(o);o.payload=e}else{let e=(new Lr).build(o);o.payload=e.payload}let r=this.build(o);return o.complete.then((()=>{v.onSuccess(s,r)})).catch((e=>{v.onFailed(s,e)})),r}build(e){let t,s=e.type,i=e.payload,n=e.createOptions.to,a=n.type;return a===o.GROUP?(t=new ze,t.senderData=te.Socket.user().data,n.id&&(t.groupId=n.id)):a===o.PRIVATE?(t=new He,t.read=!1,n.id&&(t.receiverId=n.id)):a===o.CS&&(t=new We,t.to=n.id.toString(),t.teamId=n.id.toString(),t.senderData=te.Socket.user().data),t.senderId=te.Socket.user().id,t.messageId=ie.get(),t.payload=i,t.timestamp=Date.now(),t.type=s,t.recalled=!1,t.status=r.NEW,t.buildOptions=e,t}validate(e,t){var s;s=Object.assign(Object.assign({},e),{type:t}),Nt(ot,s)}}class jr extends Jo{onMessageReceived(e){if(e.t===o.CS){let t=this.builder.build(e);this.sendAck(t.messageId);let s=je.byIMMessage(t);if(!Uo.get(s).existsMessage(t)){if(t.customerId()===te.Socket.user().id)this.createNotification(e),gs.i.fire(cs.MESSAGE_RECEIVED,t),Os.fire(ls.CS_MESSAGE_RECEIVED,t);else{Po.getInstance().queryTeams().then((()=>{_o.isMyMessage(t)&&this.createNotification(e),gs.i.fire(cs.CS_AGENT_MESSAGE_RECEIVED,t)}))}}}}}class Vr{constructor(e){this.times=new Array;let t=e[0],s=je.byIMMessage(t);this.scene=s.scene,this.targetId=s.id,e.forEach((e=>{this.times.push(e.timestamp)})),this.times.sort(((e,t)=>e<t?-1:e==t?0:1))}}class Hr{constructor(){this.onRemoteRecalled=e=>{gs.i.fire(cs.MESSAGE_RECALLED,e)},Oo.onMessage(Ut.IM_MSG_RECALLED,this.onRemoteRecalled)}recallMessage(e){return b(this,void 0,void 0,(function*(){Nt(rt,e);let t=e.messages;yield this.recallServerMessages(t);let s=t[0],i=s.scene(),n=this.toConversationId(i,s.senderId,s.targetId()),o={id:te.Socket.user().id,data:te.Socket.user().data},r=t.map((e=>e.timestamp)),a=new As(i,n,o,r);gs.i.fire(cs.MESSAGE_RECALLED,a),v.onSuccess(e)}))}toConversationId(e,t,s){if(o.PRIVATE===e)return function(e,t){return e.localeCompare(t)>0?`${e}:${t}`:`${t}:${e}`}(t,s);if(o.GROUP===e)return s;throw{code:400,content:`scene: ${e} not support`}}recallServerMessages(e){let t=new Vr(e);return 0===t.times.length?Promise.resolve():new Promise(((e,s)=>{let i=new le({name:y.IM_RECALL_MESSAGE,params:t,permission:ne.WRITE,singleTimeout:S.commonRequestSingle,totalTimeout:S.commonRequestTotal,fail:e=>{s(e)},success:t=>{200===t.code?e(t):s(t)}});te.Socket.e(i)}))}}class zr{constructor(){this.map=new Map}getData(e){return this.map.get(e)}setData(e,t){this.map.set(e,t)}}class Wr{constructor(){this.dataCache=new zr}static init(){this.i=new Wr}getData(...e){return b(this,void 0,void 0,(function*(){let t=[],s=new Map;return e.forEach((e=>{let i=this.dataCache.getData(e);i?s.set(e,i):t.push(e)})),0===t.length||(yield this.fetchData(...t)).forEach(((e,t)=>{this.dataCache.setData(t,e),s.set(t,e)})),Promise.resolve(s)}))}fetchData(...e){return new Promise(((t,s)=>{let i=new le({name:y.MD_CMD,permission:ne.READ,singleTimeout:S.commonRequestSingle,totalTimeout:S.commonRequestTotal,params:{name:"GET",data:{ids:e}},success:e=>{if(200===e.code){const s=new Map;e.content.forEach((e=>{s.set(e.id,e.data)})),t(s)}else s(e)},fail:e=>{s(e)}});te.Socket.e(i)}))}setData(e,t){this.dataCache.setData(e,t)}}class Jr{constructor(){gs.i.on(cs.MESSAGE_RECEIVED,this.onMessageReceived),gs.i.on(cs.MESSAGE_SENDING,this.onMessageSending)}onMessageSending(e){let t=je.byIMMessage(e.message);t.scene===o.PRIVATE&&Wr.i.setData(t.id,e.receiver)}onMessageReceived(e){if(je.byIMMessage(e).scene===o.GROUP){let t=e;Wr.i.setData(t.senderId,t.senderData)}}}class Xr{constructor(){this._iMReceiver=new Xo,this.csMessageReceiver=new jr,this.memberDataUpdator=new Jr,this._userHereNow=new sr,this.goEasyUploader=new as,this._groupHereNow=new er,this._groupOnlineCount=new Ko,this.groupMessageSubscriber=new $o,this.messageBuilder=new qr,this.messageSender=new Ss,this.recaller=new Hr,this._groupPresenceSubscriber=new Qo,this._userPresenceSubscriber=new tr,this.conversations=new Wo,this.histories=Uo.init()}static init(){gs.init(),Os.init(),Xr.instance=new Xr}static i(){if(Xr.instance)return Xr.instance;throw Error("Please connect first.")}validateModules(){if(Oo.status()===t.DISCONNECTED)throw Error("Please call connect() first.");Ho.check()}catch(e,t){return b(this,void 0,void 0,(function*(){try{this.validateModules(),yield e()}catch(e){v.onFailed(t,e)}}))}on(e,t){Os.on(e,t)}off(e,t){Os.off(e,t)}createTextMessage(e){return this.validateModules(),this.messageBuilder.buildMessage(Ee.TEXT,e)}createImageMessage(e){return this.validateModules(),this.messageBuilder.buildMessage(Ee.IMAGE,e)}createFileMessage(e){return this.validateModules(),this.messageBuilder.buildMessage(Ee.FILE,e)}createAudioMessage(e){return this.validateModules(),this.messageBuilder.buildMessage(Ee.AUDIO,e)}createVideoMessage(e){return this.validateModules(),this.messageBuilder.buildMessage(Ee.VIDEO,e)}createCustomMessage(e){return this.validateModules(),this.messageBuilder.buildMessage(e.type,e)}sendMessage(e){this.catch((()=>{this.messageSender.send(e)}),e)}recallMessage(e){this.catch((()=>{this.recaller.recallMessage(e)}),e)}deleteMessage(e){this.catch((()=>{this.histories.deleteMessage(e)}),e)}markGroupMessageAsRead(e){this.catch((()=>b(this,void 0,void 0,(function*(){yield this.histories.groupMarkAsRead(e)}))),e)}markPrivateMessageAsRead(e){this.catch((()=>b(this,void 0,void 0,(function*(){yield this.histories.privateMarkAsRead(e)}))),e)}markMessageAsRead(e,t){this.catch((()=>b(this,void 0,void 0,(function*(){yield this.histories.markMessageAsRead(e,t)}))),e)}latestConversations(e){this.validateModules(),this.conversations.latestConversations(e)}removePrivateConversation(e){this.catch((()=>this.conversations.removePrivateConversation(e)),e)}removeGroupConversation(e){this.catch((()=>this.conversations.removeGroupConversation(e)),e)}topPrivateConversation(e){this.catch((()=>this.conversations.topPrivateConversation(e)),e)}topGroupConversation(e){this.catch((()=>this.conversations.topGroupConversation(e)),e)}history(e,t){this.catch((()=>{this.histories.loadHistory(e,t)}),e)}subscribeUserPresence(e){this.catch((()=>this._userPresenceSubscriber.presence(e)),e)}unsubscribeUserPresence(e){this.catch((()=>this._userPresenceSubscriber.unPresence(e)),e)}hereNow(e){this.catch((()=>this._userHereNow.hereNow(e)),e)}subscribeGroup(e){this.catch((()=>this.groupMessageSubscriber.subscribe(e)),e)}unsubscribeGroup(e){this.catch((()=>this.groupMessageSubscriber.unsubscribe(e)),e)}subscribeGroupPresence(e){this.catch((()=>this._groupPresenceSubscriber.presence(e)),e)}unsubscribeGroupPresence(e){this.catch((()=>this._groupPresenceSubscriber.unPresence(e)),e)}groupHereNow(e){this.catch((()=>this._groupHereNow.hereNow(e)),e)}groupOnlineCount(e){this.catch((()=>this._groupOnlineCount.get(e)),e)}latestPendingConversations(e){this.validateModules(),this.conversations.latestPendingConversations(e)}topConversation(e){this.validateModules(),this.conversations.topConversation(e)}removeConversation(e){this.validateModules(),this.conversations.removeConversation(e)}}class $r{constructor(e,t){this.customerId=e,this.teamId=t}}class Yr{constructor(e,t){this.teamId=e;let s=new c(t.id.toString(),JSON.stringify(t.data));this.customer=s}}class Qr{constructor(e,t,s){this.customerId=e,this.teamId=t,this.agentId=s}}class Kr{constructor(e,t){this.customerId=e,this.teamId=t}}class Zr{constructor(e){this.builder=new Is,this.teamId=e}accept(e,t){Nt(ft,t);let s=new Yr(e,t.customer),i=new le({name:y.CS_ACCEPT,params:s,permission:ne.WRITE,singleTimeout:S.commonRequestSingle,totalTimeout:S.commonRequestTotal,fail:e=>{v.onFailed(t,e)},success:e=>{let s=this.builder.build(e.content.message);gs.i.fire(cs.CS_ACCEPTED,s),v.onSuccess(t)}});te.Socket.e(i)}end(e,t){Rt(t.id);let s=t.id.toString(),i=new Kr(s,e),n=new le({name:y.CS_END,params:i,permission:ne.WRITE,singleTimeout:S.commonRequestSingle,totalTimeout:S.commonRequestTotal,fail:e=>{v.onFailed(t,e)},success:e=>{let s=this.builder.build(e.content.message);gs.i.fire(cs.CS_ENDED,s),v.onSuccess(t)}});te.Socket.e(n)}queryCustomerStatus(e,t){return b(this,void 0,void 0,(function*(){Rt(t.id);let s=yield this.doCustomerStatus(e,t.id);this.activeCustomerStatus=s,this.activeCustomerStatusOptions=t,v.onSuccess(t,s)}))}doCustomerStatus(e,t){let s=t.toString(),i=new $r(s,e);return new Promise(((e,t)=>{let s=new le({name:y.CS_CUSTOMER_STATUS,params:i,permission:ne.READ,singleTimeout:S.commonQuerySingle,totalTimeout:S.commonQueryTotal,fail:e=>{t(e)},success:t=>{let s=t.content;s.agent&&(s.agent.data=JSON.parse(s.agent.data)),e(s)}});te.Socket.e(s)}))}transfer(e,t){Nt(gt,t);let s=t.customerId.toString(),i=t.agentId.toString(),n=new Qr(s,e,i),o=new le({name:y.CS_TRANSFER,params:n,permission:ne.WRITE,singleTimeout:S.commonRequestSingle,totalTimeout:S.commonRequestTotal,fail:e=>{v.onFailed(t,e)},success:e=>{let s=this.builder.build(e.content.message);gs.i.fire(cs.CS_TRANSFER,s),v.onSuccess(t)}});te.Socket.e(o)}}class ea{createTextMessage(e,t){let s=Xr.i().createTextMessage(t);this.extendProps(e,s)}createImageMessage(e,t){let s=Xr.i().createImageMessage(t);this.extendProps(e,s)}createFileMessage(e,t){let s=Xr.i().createFileMessage(t);this.extendProps(e,s)}createAudioMessage(e,t){let s=Xr.i().createAudioMessage(t);this.extendProps(e,s)}createVideoMessage(e,t){let s=Xr.i().createVideoMessage(t);this.extendProps(e,s)}createCustomMessage(e,t){let s=Xr.i().createCustomMessage(t);this.extendProps(e,s)}extendProps(e,t){if(t.scene()===o.CS){let s=t;s.teamId=e,s.accepted=!0}}}class ta{constructor(e){this.teamId=e,this.agentStatus=Po.getInstance(),this.conversationHandler=new Zr(e),this.messageCreator=new ea}catch(e,t){return b(this,void 0,void 0,(function*(){try{yield e()}catch(e){v.onFailed(t,e)}}))}isOnline(e){this.catch((()=>{this.agentStatus.isOnline(this.teamId,e)}),e)}online(e){this.catch((()=>{this.agentStatus.online(this.teamId,e)}),e)}offline(e){this.catch((()=>{this.agentStatus.offline(this.teamId,e)}),e)}customerStatus(e){this.catch((()=>{this.conversationHandler.queryCustomerStatus(this.teamId,e)}),e)}accept(e){this.catch((()=>{this.conversationHandler.accept(this.teamId,e)}),e)}end(e){this.catch((()=>{this.conversationHandler.end(this.teamId,e)}),e)}history(e){Xr.i().history(e,this.teamId)}markMessageAsRead(e){Xr.i().markMessageAsRead(e,this.teamId)}createTextMessage(e){this.messageCreator.createTextMessage(this.teamId,e)}createImageMessage(e){this.messageCreator.createImageMessage(this.teamId,e)}createFileMessage(e){this.messageCreator.createFileMessage(this.teamId,e)}createAudioMessage(e){this.messageCreator.createAudioMessage(this.teamId,e)}createVideoMessage(e){this.messageCreator.createVideoMessage(this.teamId,e)}createCustomMessage(e){this.messageCreator.createCustomMessage(this.teamId,e)}transfer(e){this.catch((()=>{this.conversationHandler.transfer(this.teamId,e)}),e)}agents(e){this.catch((()=>{this.agentStatus.agents(this.teamId,e)}),e)}liveSession(e){this.catch((()=>{_o.live(this.teamId,e)}),e)}quitLiveSession(e){this.catch((()=>{_o.quit(e)}),e)}listenCustomer(e){let t={customerId:e.id,onNewMessage:e.onNewMessage,onStatusUpdated:e.onStatusUpdated,onFailed:e.onFailed,onSuccess:e.onSuccess};this.catch((()=>{_o.live(this.teamId,t)}),e)}cancelListenCustomer(e){this.catch((()=>{_o.quit(e)}),e)}}class sa{static team(e){Tt(e);let t=this.teams.get(e);return t||(t=new ta(e.toString()),this.teams.set(e.toString(),t)),t}}sa.teams=new Map;class ia{constructor(e){this.id=e}isOnline(e){sa.team(this.id).isOnline(e)}online(e){sa.team(this.id).online(e)}offline(e){sa.team(this.id).offline(e)}customerStatus(e){sa.team(this.id).customerStatus(e)}accept(e){sa.team(this.id).accept(e)}end(e){sa.team(this.id).end(e)}history(e){sa.team(this.id).history(e)}markMessageAsRead(e){sa.team(this.id).markMessageAsRead(e)}createTextMessage(e){sa.team(this.id).createTextMessage(e)}createImageMessage(e){sa.team(this.id).createImageMessage(e)}createFileMessage(e){sa.team(this.id).createFileMessage(e)}createAudioMessage(e){sa.team(this.id).createAudioMessage(e)}createVideoMessage(e){sa.team(this.id).createVideoMessage(e)}createCustomMessage(e){sa.team(this.id).createCustomMessage(e)}transfer(e){sa.team(this.id).transfer(e)}agents(e){sa.team(this.id).agents(e)}liveSession(e){sa.team(this.id).liveSession(e)}quitLiveSession(e){sa.team(this.id).quitLiveSession(e)}listenCustomer(e){sa.team(this.id).listenCustomer(e)}cancelListenCustomer(e){sa.team(this.id).cancelListenCustomer(e)}}class na{static getInstance(e){return this.init(e),na}static init(e){if(this.getConnectionStatus()!==t.DISCONNECTED)throw new Error("Initialization failed. Please disconnect and try again.");Nt($e,e),e.modules=e.modules.map((e=>e.toUpperCase())),i.init(e.reactNativeOptions),this.options=e,Oo.init(e),e.allowNotification&&he.init(e.allowNotification),e.modules&&(e.modules.includes("PUBSUB")&&X.initModule(zt.init()),e.modules.includes("IM")&&X.initModule(Ho.init())),Wr.init(),te.init(Oo,he,Wr,n,h,X),this.options.customProvider&&Ps.init(this.options.customProvider)}static setBadge(e){he.setBadge(e)}static connect(e){Oo.connect(e,"JS")}static disconnect(e){Oo.disconnect(e)}static getConnectionStatus(){return Oo.status()}static onClickNotification(e){he.onClickNotification(e)}static c(e){e.init(te.Socket,te.N,te.Member,te.v,te.Platform,X)}}na.version=n,na.IM_EVENT=ls,na.IM_SCENE=o,na.im=class{static on(e,t){Xr.i().on(e,t)}static off(e,t){Xr.i().off(e,t)}static createTextMessage(e){return Xr.i().createTextMessage(e)}static createImageMessage(e){return Xr.i().createImageMessage(e)}static createFileMessage(e){return Xr.i().createFileMessage(e)}static createAudioMessage(e){return Xr.i().createAudioMessage(e)}static createVideoMessage(e){return Xr.i().createVideoMessage(e)}static createCustomMessage(e){return Xr.i().createCustomMessage(e)}static sendMessage(e){Xr.i().sendMessage(e)}static recallMessage(e){Xr.i().recallMessage(e)}static deleteMessage(e){Xr.i().deleteMessage(e)}static markGroupMessageAsRead(e){Xr.i().markGroupMessageAsRead(e)}static markPrivateMessageAsRead(e){Xr.i().markPrivateMessageAsRead(e)}static latestConversations(e){Xr.i().latestConversations(e)}static removePrivateConversation(e){Xr.i().removePrivateConversation(e)}static removeGroupConversation(e){Xr.i().removeGroupConversation(e)}static topPrivateConversation(e){Xr.i().topPrivateConversation(e)}static topGroupConversation(e){Xr.i().topGroupConversation(e)}static history(e){Xr.i().history(e)}static subscribeUserPresence(e){Xr.i().subscribeUserPresence(e)}static unsubscribeUserPresence(e){Xr.i().unsubscribeUserPresence(e)}static hereNow(e){Xr.i().hereNow(e)}static subscribeGroup(e){Xr.i().subscribeGroup(e)}static unsubscribeGroup(e){Xr.i().unsubscribeGroup(e)}static subscribeGroupPresence(e){Xr.i().subscribeGroupPresence(e)}static unsubscribeGroupPresence(e){Xr.i().unsubscribeGroupPresence(e)}static groupHereNow(e){Xr.i().groupHereNow(e)}static groupOnlineCount(e){Xr.i().groupOnlineCount(e)}static markMessageAsRead(e){Xr.i().markMessageAsRead(e)}static csteam(e){return new ia(e)}static pendingConversations(e){Xr.i().latestPendingConversations(e)}static topConversation(e){Xr.i().topConversation(e)}static removeConversation(e){Xr.i().removeConversation(e)}},na.pubsub=class{static publish(e){this.catch((()=>{Ht.instance.publish(e)}),e)}static subscribe(e){this.catch((()=>{Ht.instance.subscribe(e)}),e)}static unsubscribe(e){this.catch((()=>{Ht.instance.unsubscribe(e)}),e)}static subscribePresence(e){this.catch((()=>{Ht.instance.subscribePresence(e)}),e)}static unsubscribePresence(e){this.catch((()=>{Ht.instance.unsubscribePresence(e)}),e)}static history(e){this.catch((()=>{Ht.instance.history(e)}),e)}static hereNow(e){this.catch((()=>{Ht.instance.hereNow(e)}),e)}static catch(e,s){try{if(zt.check(),[t.DISCONNECTED,t.DISCONNECTING,t.CONNECT_FAILED].includes(te.Socket.status()))throw new Error("Please call connect() first.");e()}catch(e){v.onFailed(s,e)}}};export{na as default};