goeasy-2.6.6.esm.min.js 167 KB

1
  1. var e;function t(e,t,s,n){return new(s||(s=Promise))((function(i,o){function r(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(r,a)}c((n=n.apply(e,t||[])).next())}))}!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"}(e||(e={}));var s="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function n(e){if(e.__esModule)return e;var t=Object.defineProperty({},"__esModule",{value:!0});return Object.keys(e).forEach((function(s){var n=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,n.get?n:{enumerable:!0,get:function(){return e[s]}})})),t}var i={exports:{}},o=/^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,r=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],a=function(e){var t=e,s=e.indexOf("["),n=e.indexOf("]");-1!=s&&-1!=n&&(e=e.substring(0,s)+e.substring(s,n).replace(/:/g,";")+e.substring(n,e.length));for(var i=o.exec(e||""),a={},c=14;c--;)a[r[c]]=i[c]||"";return-1!=s&&-1!=n&&(a.source=t,a.host=a.host.substring(1,a.host.length-1).replace(/;/g,":"),a.authority=a.authority.replace("[","").replace("]","").replace(/;/g,":"),a.ipv6uri=!0),a},c={exports:{}},u={exports:{}},l=1e3,d=60*l,h=60*d,p=24*h,m=365.25*p,f=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*m;case"days":case"day":case"d":return s*p;case"hours":case"hour":case"hrs":case"hr":case"h":return s*h;case"minutes":case"minute":case"mins":case"min":case"m":return s*d;case"seconds":case"second":case"secs":case"sec":case"s":return s*l;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 g(e,p,"day")||g(e,h,"hour")||g(e,d,"minute")||g(e,l,"second")||e+" ms"}(e):function(e){if(e>=p)return Math.round(e/p)+"d";if(e>=h)return Math.round(e/h)+"h";if(e>=d)return Math.round(e/d)+"m";if(e>=l)return Math.round(e/l)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function g(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 i(){if(i.enabled){var e=i,n=+new Date,o=n-(s||n);e.diff=o,e.prev=s,e.curr=n,s=n;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,n){if("%%"===s)return s;c++;var i=t.formatters[n];if("function"==typeof i){var o=r[c];s=i.call(e,o),r.splice(c,1),c--}return s})),t.formatArgs.call(e,r),(i.log||t.log||console.log.bind(console)).apply(e,r)}}return i.namespace=e,i.enabled=t.enabled(e),i.useColors=t.useColors(),i.color=function(e){var s,n=0;for(s in e)n=(n<<5)-n+e.charCodeAt(s),n|=0;return t.colors[Math.abs(n)%t.colors.length]}(e),i.destroy=n,"function"==typeof t.init&&t.init(i),t.instances.push(i),i}function n(){var e=t.instances.indexOf(this);return-1!==e&&(t.instances.splice(e,1),!0)}(t=u.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 n=("string"==typeof e?e:"").split(/[\s,]+/),i=n.length;for(s=0;s<i;s++)n[s]&&("-"===(e=n[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,n;for(s=0,n=t.skips.length;s<n;s++)if(t.skips[s].test(e))return!1;for(s=0,n=t.names.length;s<n;s++)if(t.names[s].test(e))return!0;return!1},t.humanize=f,t.instances=[],t.names=[],t.skips=[],t.formatters={}}(0,u.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=u.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 n="color: "+this.color;e.splice(1,0,n,"color: inherit");var i=0,o=0;e[0].replace(/%[a-zA-Z%]/g,(function(e){"%%"!==e&&(i++,"%c"===e&&(o=i))})),e.splice(o,0,n)},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())}(c,c.exports);var y=a,v=c.exports("socket.io-client:url"),E=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)||(v("protocol-less url %s",e),e=void 0!==t?t.protocol+"//"+e:"https://"+e),v("parse %s",e),s=y(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 n=-1!==s.host.indexOf(":")?"["+s.host+"]":s.host;return s.id=s.protocol+"://"+n+":"+s.port,s.href=s.protocol+"://"+n+(t&&t.port===s.port?"":":"+s.port),s};var C={},S={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)}S.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,n=this._callbacks["$"+e];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var i=0;i<n.length;i++)if((s=n[i])===t||s.fn===t){n.splice(i,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 n=0,i=(s=s.slice(0)).length;n<i;++n)s[n].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 b={}.toString,w=Array.isArray||function(e){return"[object Array]"==b.call(e)};!function(e){c.exports("socket.io-parser");var t=S.exports,s=w;function n(){}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=n,e.Decoder=o;var i=e.ERROR+'"encode error"';function o(){this.reconstructor=null}function r(t){return{type:e.ERROR,data:"parser error: "+t}}n.prototype.encode=function(t,s){var n=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 n=function(e){try{return JSON.stringify(e)}catch(e){return!1}}(t.data);if(!1===n)return i;s+=n}return s}(t);s([n])},t(o.prototype),o.prototype.add=function(t){var n;if("string"!=typeof t)throw new Error("Unknown type: "+t);n=function(t){var n=0,i={type:Number(t.charAt(0))};if(null==e.types[i.type])return r("unknown packet type "+i.type);if(e.BINARY_EVENT===i.type||e.BINARY_ACK===i.type){for(var o="";"-"!==t.charAt(++n)&&(o+=t.charAt(n),n!=t.length););if(o!=Number(o)||"-"!==t.charAt(n))throw new Error("Illegal attachments");i.attachments=Number(o)}if("/"===t.charAt(n+1))for(i.nsp="";++n;){if(","===(c=t.charAt(n)))break;if(i.nsp+=c,n===t.length)break}else i.nsp="/";var a=t.charAt(n+1);if(""!==a&&Number(a)==a){for(i.id="";++n;){var c;if(null==(c=t.charAt(n))||Number(c)!=c){--n;break}if(i.id+=t.charAt(n),n===t.length)break}i.id=Number(i.id)}if(t.charAt(++n)){var u=function(e){try{return JSON.parse(e)}catch(e){return!1}}(t.substr(n));if(!(!1!==u&&(i.type===e.ERROR||s(u))))return r("invalid payload");i.data=u}return i}(t),this.emit("decoded",n)},o.prototype.destroy=function(){this.reconstructor&&this.reconstructor.finishedReconstruction()}}(C);var I={exports:{}},M={},A={},T=Object.keys||function(e){var t=[],s=Object.prototype.hasOwnProperty;for(var n in e)s.call(e,n)&&t.push(n);return t},N=w,R=Object.prototype.toString,O="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===R.call(Blob),_="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===R.call(File),P=function e(t){if(!t||"object"!=typeof t)return!1;if(N(t)){for(var s=0,n=t.length;s<n;s++)if(e(t[s]))return!0;return!1}if("function"==typeof Buffer&&Buffer.isBuffer&&Buffer.isBuffer(t)||"function"==typeof ArrayBuffer&&t instanceof ArrayBuffer||O&&t instanceof Blob||_&&t instanceof File)return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return e(t.toJSON(),!0);for(var i in t)if(Object.prototype.hasOwnProperty.call(t,i)&&e(t[i]))return!0;return!1};var k=function(e,t,s){var n=!1;return s=s||D,i.count=e,0===e?t():i;function i(e,o){if(i.count<=0)throw new Error("after called too many times");--i.count,e?(n=!0,t(e),t=s):0!==i.count||n||t(null,o)}};function D(){}var x,F,U,L=String.fromCharCode;function G(e){for(var t,s,n=[],i=0,o=e.length;i<o;)(t=e.charCodeAt(i++))>=55296&&t<=56319&&i<o?56320==(64512&(s=e.charCodeAt(i++)))?n.push(((1023&t)<<10)+(1023&s)+65536):(n.push(t),i--):n.push(t);return n}function q(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 B(e,t){return L(e>>t&63|128)}function j(e,t){if(0==(4294967168&e))return L(e);var s="";return 0==(4294965248&e)?s=L(e>>6&31|192):0==(4294901760&e)?(q(e,t)||(e=65533),s=L(e>>12&15|224),s+=B(e,6)):0==(4292870144&e)&&(s=L(e>>18&7|240),s+=B(e,12),s+=B(e,6)),s+=L(63&e|128)}function V(){if(U>=F)throw Error("Invalid byte index");var e=255&x[U];if(U++,128==(192&e))return 63&e;throw Error("Invalid continuation byte")}function H(e){var t,s;if(U>F)throw Error("Invalid byte index");if(U==F)return!1;if(t=255&x[U],U++,0==(128&t))return t;if(192==(224&t)){if((s=(31&t)<<6|V())>=128)return s;throw Error("Invalid continuation byte")}if(224==(240&t)){if((s=(15&t)<<12|V()<<6|V())>=2048)return q(s,e)?s:65533;throw Error("Invalid continuation byte")}if(240==(248&t)&&(s=(7&t)<<18|V()<<12|V()<<6|V())>=65536&&s<=1114111)return s;throw Error("Invalid UTF-8 detected")}var W={version:"2.1.2",encode:function(e,t){for(var s=!1!==(t=t||{}).strict,n=G(e),i=n.length,o=-1,r="";++o<i;)r+=j(n[o],s);return r},decode:function(e,t){var s=!1!==(t=t||{}).strict;x=G(e),F=x.length,U=0;for(var n,i=[];!1!==(n=H(s));)i.push(n);return function(e){for(var t,s=e.length,n=-1,i="";++n<s;)(t=e[n])>65535&&(i+=L((t-=65536)>>>10&1023|55296),t=56320|1023&t),i+=L(t);return i}(i)}},z=void 0!==z?z:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:"undefined"!=typeof MSBlobBuilder?MSBlobBuilder:"undefined"!=typeof MozBlobBuilder&&MozBlobBuilder,X=function(){try{return 2===new Blob(["hi"]).size}catch(e){return!1}}(),J=X&&function(){try{return 2===new Blob([new Uint8Array([1,2])]).size}catch(e){return!1}}(),K=z&&z.prototype.append&&z.prototype.getBlob;function Q(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 Y(e,t){t=t||{};var s=new z;return Q(e).forEach((function(e){s.append(e)})),t.type?s.getBlob(t.type):s.getBlob()}function $(e,t){return new Blob(Q(e),t||{})}"undefined"!=typeof Blob&&(Y.prototype=Blob.prototype,$.prototype=Blob.prototype);var Z=X?J?Blob:$:K?Y:void 0;!function(e){var t=T,s=P,n=k,i=W;"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=Z;e.encodePacket=function(e,t,s,n){"function"==typeof t&&(n=t,t=!1),"function"==typeof s&&(n=s,s=null),void 0===e.data||e.data.buffer||e.data;var r=o[e.type];return void 0!==e.data&&(r+=s?i.encode(String(e.data),{strict:!1}):String(e.data)),n(""+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=i.decode(e,{strict:!1})}catch(e){return!1}return e}(e)))return a;var n=e.charAt(0);return Number(n)==n&&r[n]?e.length>1?{type:r[n],data:e.substring(1)}:{type:r[n]}:a}n=new Uint8Array(e)[0];var o=sliceBuffer(e,1);return c&&"blob"===t&&(o=new c([o])),{type:r[n],data:o}},e.encodePayload=function(t,i,o){"function"==typeof i&&(o=i,i=null);var r=s(t);if(!t.length)return o("0:");!function(e,t,s){for(var i=new Array(e.length),o=n(e.length,s),r=function(e,s,n){t(s,(function(t,s){i[e]=s,n(t,i)}))},a=0;a<e.length;a++)r(a,e[a],o)}(t,(function(t,s){e.encodePacket(t,!!r&&i,!0,(function(e){s(null,function(e){return e.length+":"+e}(e))}))}),(function(e,t){return o(t.join(""))}))},e.decodePayload=function(t,s,n){var i;if("function"==typeof s&&(n=s,s=null),""===t)return n(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 n(a,0,1);if(c!=(r=t.substr(u+1,o)).length)return n(a,0,1);if(r.length){if(i=e.decodePacket(r,s,!0),a.type===i.type&&a.data===i.data)return n(a,0,1);if(!1===n(i,u+o,l))return}u+=o,c=""}else c+=d}return""!==c?n(a,0,1):void 0}}(A);var ee=A,te=se;function se(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,S.exports)(se.prototype),se.prototype.onError=function(e,t){var s=new Error(e);return s.type="TransportError",s.description=t,this.emit("error",s),this},se.prototype.open=function(){return"closed"!==this.readyState&&""!==this.readyState||(this.readyState="opening",this.doOpen()),this},se.prototype.close=function(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this},se.prototype.send=function(e){if("open"!==this.readyState)throw new Error("Transport not open");this.write(e)},se.prototype.onOpen=function(){this.readyState="open",this.writable=!0,this.emit("open")},se.prototype.onData=function(e){var t=ee.decodePacket(e,this.socket.binaryType);this.onPacket(t)},se.prototype.onPacket=function(e){this.emit("packet",e)},se.prototype.onClose=function(){this.readyState="closed",this.emit("close")};var ne,ie={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("&"),n=0,i=s.length;n<i;n++){var o=s[n].split("=");t[decodeURIComponent(o[0])]=decodeURIComponent(o[1])}return t}},oe=function(e,t){var s=function(){};s.prototype=t.prototype,e.prototype=new s,e.prototype.constructor=e},re="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),ae=64,ce={},ue=0,le=0;function de(e){var t="";do{t=re[e%ae]+t,e=Math.floor(e/ae)}while(e>0);return t}function he(){var e=de(+new Date);return e!==ne?(ue=0,ne=e):e+"."+de(ue++)}for(;le<ae;le++)ce[re[le]]=le;he.encode=de,he.decode=function(e){var t=0;for(le=0;le<e.length;le++)t=t*ae+ce[e.charAt(le)];return t};var pe=he,me={exports:{}},fe={exports:{}},ge=1e3,ye=60*ge,ve=60*ye,Ee=24*ve,Ce=365.25*Ee,Se=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*Ce;case"days":case"day":case"d":return s*Ee;case"hours":case"hour":case"hrs":case"hr":case"h":return s*ve;case"minutes":case"minute":case"mins":case"min":case"m":return s*ye;case"seconds":case"second":case"secs":case"sec":case"s":return s*ge;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 be(e,Ee,"day")||be(e,ve,"hour")||be(e,ye,"minute")||be(e,ge,"second")||e+" ms"}(e):function(e){if(e>=Ee)return Math.round(e/Ee)+"d";if(e>=ve)return Math.round(e/ve)+"h";if(e>=ye)return Math.round(e/ye)+"m";if(e>=ge)return Math.round(e/ge)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function be(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 i(){if(i.enabled){var e=i,n=+new Date,o=n-(s||n);e.diff=o,e.prev=s,e.curr=n,s=n;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,n){if("%%"===s)return s;c++;var i=t.formatters[n];if("function"==typeof i){var o=r[c];s=i.call(e,o),r.splice(c,1),c--}return s})),t.formatArgs.call(e,r),(i.log||t.log||console.log.bind(console)).apply(e,r)}}return i.namespace=e,i.enabled=t.enabled(e),i.useColors=t.useColors(),i.color=function(e){var s,n=0;for(s in e)n=(n<<5)-n+e.charCodeAt(s),n|=0;return t.colors[Math.abs(n)%t.colors.length]}(e),i.destroy=n,"function"==typeof t.init&&t.init(i),t.instances.push(i),i}function n(){var e=t.instances.indexOf(this);return-1!==e&&(t.instances.splice(e,1),!0)}(t=fe.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 n=("string"==typeof e?e:"").split(/[\s,]+/),i=n.length;for(s=0;s<i;s++)n[s]&&("-"===(e=n[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,n;for(s=0,n=t.skips.length;s<n;s++)if(t.skips[s].test(e))return!1;for(s=0,n=t.names.length;s<n;s++)if(t.names[s].test(e))return!0;return!1},t.humanize=Se,t.instances=[],t.names=[],t.skips=[],t.formatters={}}(0,fe.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=fe.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 n="color: "+this.color;e.splice(1,0,n,"color: inherit");var i=0,o=0;e[0].replace(/%[a-zA-Z%]/g,(function(e){"%%"!==e&&(i++,"%c"===e&&(o=i))})),e.splice(o,0,n)},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())}(me,me.exports);var we={exports:{}};try{we.exports="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(e){we.exports=!1}var Ie=we.exports,Me=function(e){var t=e.xdomain,s=e.xscheme,n=e.enablesXDR;try{if("undefined"!=typeof XMLHttpRequest&&(!t||Ie))return new XMLHttpRequest}catch(e){}try{if("undefined"!=typeof XDomainRequest&&!s&&n)return new XDomainRequest}catch(e){}if(!t)try{return new(self[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}},Ae=te,Te=ie,Ne=A,Re=oe,Oe=pe,_e=me.exports("engine.io-client:polling"),Pe=De,ke=null!=new Me({xdomain:!1}).responseType;function De(e){var t=e&&e.forceBase64;ke&&!t||(this.supportsBinary=!1),Ae.call(this,e)}Re(De,Ae),De.prototype.name="polling",De.prototype.doOpen=function(){this.poll()},De.prototype.pause=function(e){var t=this;function s(){_e("paused"),t.readyState="paused",e()}if(this.readyState="pausing",this.polling||!this.writable){var n=0;this.polling&&(_e("we are currently polling - waiting to pause"),n++,this.once("pollComplete",(function(){_e("pre-pause polling complete"),--n||s()}))),this.writable||(_e("we are currently writing - waiting to pause"),n++,this.once("drain",(function(){_e("pre-pause writing complete"),--n||s()})))}else s()},De.prototype.poll=function(){_e("polling"),this.polling=!0,this.doPoll(),this.emit("poll")},De.prototype.onData=function(e){var t=this;_e("polling got data %s",e);Ne.decodePayload(e,this.socket.binaryType,(function(e,s,n){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():_e('ignoring poll - transport state "%s"',this.readyState))},De.prototype.doClose=function(){var e=this;function t(){_e("writing close packet"),e.write([{type:"close"}])}"open"===this.readyState?(_e("transport open - closing"),t()):(_e("transport not open - deferring close"),this.once("open",t))},De.prototype.write=function(e){var t=this;this.writable=!1;var s=function(){t.writable=!0,t.emit("drain")};Ne.encodePayload(e,this.supportsBinary,(function(e){t.doWrite(e,s)}))},De.prototype.uri=function(){var e=this.query||{},t=this.secure?"https":"http",s="";return!1!==this.timestampRequests&&(e[this.timestampParam]=Oe()),this.supportsBinary||e.sid||(e.b64=1),e=Te.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 xe,Fe=Pe,Ue=je,Le=/\n/g,Ge=/\\n/g;function qe(){}function Be(){return"undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0!==s?s:{}}function je(e){if(Fe.call(this,e),this.query=this.query||{},!xe){var t=Be();xe=t.___eio=t.___eio||[]}this.index=xe.length;var s=this;xe.push((function(e){s.onData(e)})),this.query.j=this.index,"function"==typeof addEventListener&&addEventListener("beforeunload",(function(){s.script&&(s.script.onerror=qe)}),!1)}oe(je,Fe),je.prototype.supportsBinary=!1,je.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),Fe.prototype.doClose.call(this)},je.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)},je.prototype.doWrite=function(e,t){var s=this;if(!this.form){var n,i=document.createElement("form"),o=document.createElement("textarea"),r=this.iframeId="eio_iframe_"+this.index;i.className="socketio",i.style.position="absolute",i.style.top="-1000px",i.style.left="-1000px",i.target=r,i.method="POST",i.setAttribute("accept-charset","utf-8"),o.name="d",i.appendChild(o),document.body.appendChild(i),this.form=i,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+'">';n=document.createElement(e)}catch(e){(n=document.createElement("iframe")).name=s.iframeId,n.src="javascript:0"}n.id=s.iframeId,s.form.appendChild(n),s.iframe=n}this.form.action=this.uri(),c(),e=e.replace(Ge,"\\\n"),this.area.value=e.replace(Le,"\\n");try{this.form.submit()}catch(e){}this.iframe.attachEvent?this.iframe.onreadystatechange=function(){"complete"===s.iframe.readyState&&a()}:this.iframe.onload=a};var Ve,He,We=te,ze=A,Xe=ie,Je=oe,Ke=pe,Qe=me.exports("engine.io-client:websocket");("undefined"==typeof uni&&"undefined"==typeof wx||"undefined"!=typeof WebSocket)&&("undefined"!=typeof WebSocket?Ve=WebSocket:"undefined"!=typeof self&&(Ve=self.WebSocket||self.MozWebSocket));var Ye=Ve||He;("undefined"==typeof uni&&"undefined"==typeof wx||"undefined"!=typeof WebSocket)&&"undefined"==typeof GameGlobal||(Ye=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 uni)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{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 n=wx.connectSocket({url:e});t.send=function(e){n.send({data:e})},t.close=function(e){n.close({code:1e3})},n.onOpen((function(){t.onopen()})),n.onError((function(e){t.onerror(e)})),n.onMessage((function(e){t.onmessage(e)})),n.onClose((function(e){t.onclose(e)}))}});var $e=Ze;function Ze(e){e&&e.forceBase64&&(this.supportsBinary=!1),("undefined"==typeof uni&&"undefined"==typeof wx||"undefined"!=typeof WebSocket)&&(this.perMessageDeflate=e.perMessageDeflate,this.usingBrowserWebSocket=Ve&&!e.forceNode,this.protocols=e.protocols,this.usingBrowserWebSocket||(Ye=He)),We.call(this,e)}Je(Ze,We),Ze.prototype.name="websocket",Ze.prototype.supportsBinary=!1,Ze.prototype.doOpen=function(){if(this.check()){var e,t,s=this.uri();("undefined"==typeof uni&&"undefined"==typeof wx||"undefined"!=typeof WebSocket)&&(e=this.protocols),(t="undefined"==typeof uni&&"undefined"==typeof wx||"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,this.extraHeaders&&(t.headers=this.extraHeaders),this.localAddress&&(t.localAddress=this.localAddress);try{"undefined"==typeof uni&&"undefined"==typeof wx||"undefined"!=typeof WebSocket?this.ws=this.usingBrowserWebSocket&&!this.isReactNative?e?new Ye(s,e):new Ye(s):new Ye(s,e,t):this.ws=new Ye(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()}},Ze.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)}},Ze.prototype.write=function(e){var t=this;this.writable=!1;for(var s=e.length,n=0,i=s;n<i;n++)!function(e){ze.encodePacket(e,t.supportsBinary,(function(n){if("undefined"==typeof uni&&"undefined"==typeof wx||"undefined"!=typeof WebSocket){if(!t.usingBrowserWebSocket){var i={};if(e.options&&(i.compress=e.options.compress),t.perMessageDeflate)("string"==typeof n?Buffer.byteLength(n):n.length)<t.perMessageDeflate.threshold&&(i.compress=!1)}try{t.usingBrowserWebSocket?t.ws.send(n):t.ws.send(n,i)}catch(e){Qe("websocket closed before onclose event")}}else try{t.ws.send(n)}catch(e){Qe("websocket closed before onclose event")}--s||o()}))}(e[n]);function o(){t.emit("flush"),setTimeout((function(){t.writable=!0,t.emit("drain")}),0)}},Ze.prototype.onClose=function(){We.prototype.onClose.call(this)},Ze.prototype.doClose=function(){void 0!==this.ws&&this.ws.close()},Ze.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]=Ke()),this.supportsBinary||(e.b64=1),(e=Xe.encode(e)).length&&(e="?"+e),t+"://"+(-1!==this.hostname.indexOf(":")?"["+this.hostname+"]":this.hostname)+s+this.path+e},Ze.prototype.check=function(){return!(!Ye||"__initialize"in Ye&&this.name===Ze.prototype.name)};var et=Ue,st=$e;M.polling=function(e){var t=!1,s=!1;if(e.jsonp,"undefined"!=typeof location){var n="https:"===location.protocol,i=location.port;i||(i=n?443:80),t=e.hostname!==location.hostname||i!==e.port,s=e.secure!==n}return e.xdomain=t,e.xscheme=s,new et(e)},M.websocket=st;var nt=[].indexOf,it=function(e,t){if(nt)return e.indexOf(t);for(var s=0;s<e.length;++s)if(e[s]===t)return s;return-1},ot=M,rt=S.exports,at=me.exports("engine.io-client:socket"),ct=it,ut=A,lt=a,dt=ie,ht=pt;function pt(e,t){if(!(this instanceof pt))return new pt(e,t);t=t||{},e&&"object"==typeof e&&(t=e,e=null),e?(e=lt(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=lt(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=dt.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()}pt.priorWebsocketSuccess=!1,rt(pt.prototype),pt.protocol=ut.protocol,pt.Socket=pt,pt.Transport=te,pt.transports=M,pt.parser=A,pt.prototype.createTransport=function(e){at('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=ut.protocol,t.transport=e;var s=this.transportOptions[e]||{};return this.id&&(t.sid=this.id),new ot[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})},pt.prototype.open=function(){var e;if(this.rememberUpgrade&&pt.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)},pt.prototype.setTransport=function(e){at("setting transport %s",e.name);var t=this;this.transport&&(at("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")}))},pt.prototype.probe=function(e){at('probing transport "%s"',e);var t=this.createTransport(e,{probe:1}),s=!1,n=this;function i(){if(n.onlyBinaryUpgrades){var i=!this.supportsBinary&&n.transport.supportsBinary;s=s||i}s||(at('probe transport "%s" opened',e),t.send([{type:"ping",data:"probe"}]),t.once("packet",(function(i){if(!s)if("pong"===i.type&&"probe"===i.data){if(at('probe transport "%s" pong',e),n.upgrading=!0,n.emit("upgrading",t),!t)return;pt.priorWebsocketSuccess="websocket"===t.name,at('pausing current transport "%s"',n.transport.name),n.transport.pause((function(){s||"closed"!==n.readyState&&(at("changing transport and sending upgrade packet"),l(),n.setTransport(t),t.send([{type:"upgrade"}]),n.emit("upgrade",t),t=null,n.upgrading=!1,n.flush())}))}else{at('probe transport "%s" failed',e);var o=new Error("probe error");o.transport=t.name,n.emit("upgradeError",o)}})))}function o(){s||(s=!0,l(),t.close(),t=null)}function r(s){var i=new Error("probe error: "+s);i.transport=t.name,o(),at('probe transport "%s" failed because of error: %s',e,s),n.emit("upgradeError",i)}function a(){r("transport closed")}function c(){r("socket closed")}function u(e){t&&e.name!==t.name&&(at('"%s" works - aborting "%s"',e.name,t.name),o())}function l(){t.removeListener("open",i),t.removeListener("error",r),t.removeListener("close",a),n.removeListener("close",c),n.removeListener("upgrading",u)}pt.priorWebsocketSuccess=!1,t.once("open",i),t.once("error",r),t.once("close",a),this.once("close",c),this.once("upgrading",u),t.open()},pt.prototype.onOpen=function(){if(at("socket open"),this.readyState="open",pt.priorWebsocketSuccess="websocket"===this.transport.name,this.emit("open"),this.flush(),"open"===this.readyState&&this.upgrade&&this.transport.pause){at("starting upgrade probes");for(var e=0,t=this.upgrades.length;e<t;e++)this.probe(this.upgrades[e])}},pt.prototype.onPacket=function(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(at('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 at('packet received with socket readyState "%s"',this.readyState)},pt.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))},pt.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)},pt.prototype.setPing=function(){var e=this;clearTimeout(e.pingIntervalTimer),e.pingIntervalTimer=setTimeout((function(){at("writing ping packet - expecting pong within %sms",e.pingTimeout),e.ping(),e.onHeartbeat(e.pingTimeout)}),e.pingInterval)},pt.prototype.ping=function(){var e=this;this.sendPacket("ping",(function(){e.emit("ping")}))},pt.prototype.onDrain=function(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emit("drain"):this.flush()},pt.prototype.flush=function(){"closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length&&(at("flushing %d packets in socket",this.writeBuffer.length),this.transport.send(this.writeBuffer),this.prevBufferLen=this.writeBuffer.length,this.emit("flush"))},pt.prototype.write=pt.prototype.send=function(e,t,s){return this.sendPacket("message",e,t,s),this},pt.prototype.sendPacket=function(e,t,s,n){if("function"==typeof t&&(n=t,t=void 0),"function"==typeof s&&(n=s,s=null),"closing"!==this.readyState&&"closed"!==this.readyState){(s=s||{}).compress=!1!==s.compress;var i={type:e,data:t,options:s};this.emit("packetCreate",i),this.writeBuffer.push(i),n&&this.once("flush",n),this.flush()}},pt.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?n():t()})):this.upgrading?n():t()}function t(){e.onClose("forced close"),at("socket closing - telling transport to close"),e.transport.close()}function s(){e.removeListener("upgrade",s),e.removeListener("upgradeError",s),t()}function n(){e.once("upgrade",s),e.once("upgradeError",s)}return this},pt.prototype.onError=function(e){at("socket error %j",e),pt.priorWebsocketSuccess=!1,this.emit("error",e),this.onClose("transport error",e)},pt.prototype.onClose=function(e,t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){at('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}},pt.prototype.filterUpgrades=function(e){for(var t=[],s=0,n=e.length;s<n;s++)~ct(this.transports,e[s])&&t.push(e[s]);return t},I.exports=ht,I.exports.parser=A;var mt={exports:{}},ft=function(e,t){for(var s=[],n=(t=t||0)||0;n<e.length;n++)s[n-t]=e[n];return s};var gt=function(e,t,s){return e.on(t,s),{destroy:function(){e.removeListener(t,s)}}};var yt=[].slice,vt=function(e,t){if("string"==typeof t&&(t=e[t]),"function"!=typeof t)throw new Error("bind() requires a function");var s=yt.call(arguments,2);return function(){return t.apply(e,s.concat(yt.call(arguments)))}};!function(e,t){var s=C,n=S.exports,i=ft,o=gt,r=vt,a=(c.exports("socket.io-client:socket"),ie),u=P;e.exports=h;var l={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},d=n.prototype.emit;function h(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()}n(h.prototype),h.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"))]}},h.prototype.open=h.prototype.connect=function(){return this.connected||(this.subEvents(),this.io.open(),"open"===this.io.readyState&&this.onopen(),this.emit("connecting")),this},h.prototype.send=function(){var e=i(arguments);return e.unshift("message"),this.emit.apply(this,e),this},h.prototype.emit=function(e){if(l.hasOwnProperty(e))return d.apply(this,arguments),this;var t=i(arguments),n={type:(void 0!==this.flags.binary?this.flags.binary:u(t))?s.BINARY_EVENT:s.EVENT,data:t,options:{}};return n.options.compress=!this.flags||!1!==this.flags.compress,"function"==typeof t[t.length-1]&&(this.ids,this.acks[this.ids]=t.pop(),n.id=this.ids++),this.connected?this.packet(n):this.sendBuffer.push(n),this.flags={},this},h.prototype.packet=function(e){e.nsp=this.nsp,this.io.packet(e)},h.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})},h.prototype.onclose=function(e){this.connected=!1,this.disconnected=!0,delete this.id,this.emit("disconnect",e)},h.prototype.onpacket=function(e){var t=e.nsp===this.nsp,n=e.type===s.ERROR&&"/"===e.nsp;if(t||n)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)}},h.prototype.onevent=function(e){var t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?d.apply(this,t):this.receiveBuffer.push(t)},h.prototype.ack=function(e){var t=this,n=!1;return function(){if(!n){n=!0;var o=i(arguments);t.packet({type:u(o)?s.BINARY_ACK:s.ACK,id:e,data:o})}}},h.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},h.prototype.onconnect=function(){this.connected=!0,this.disconnected=!1,this.emit("connect"),this.emitBuffered()},h.prototype.emitBuffered=function(){var e;for(e=0;e<this.receiveBuffer.length;e++)d.apply(this,this.receiveBuffer[e]);for(this.receiveBuffer=[],e=0;e<this.sendBuffer.length;e++)this.packet(this.sendBuffer[e]);this.sendBuffer=[]},h.prototype.ondisconnect=function(){this.nsp,this.destroy(),this.onclose("io server disconnect")},h.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)},h.prototype.close=h.prototype.disconnect=function(){return this.connected&&(this.nsp,this.packet({type:s.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this},h.prototype.compress=function(e){return this.flags.compress=e,this},h.prototype.binary=function(e){return this.flags.binary=e,this}}(mt);var Et,Ct,St=bt;function bt(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}bt.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)},bt.prototype.reset=function(){this.attempts=0},bt.prototype.setMin=function(e){this.ms=e},bt.prototype.setMax=function(e){this.max=e},bt.prototype.setJitter=function(e){this.jitter=e};class wt{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,n,i="/",o=!1){let r=encodeURIComponent(e)+"="+encodeURIComponent(t);s instanceof Date&&(r+="; expires="+s.toGMTString()),i&&(r+="; path="+i),n&&(r+="; domain="+n),o&&(r+="; secure"),document.cookie=r}static remove(e,t,s="/",n=!1){wt.set(e,"",new Date(0),t,s,n)}}!function(e){e.BROWSER="BROWSER",e.UNKNOWN="UNKNOWN",e.APP_IOS="APP_IOS",e.APP_ANDROID="APP_ANDROID",e.APPLET_WX="APPLET_WX",e.APPLET_WX_GAME="APPLET_WX_GAME",e.APPLET_ALIPAY="APPLET_ALIPAY",e.APPLET_BYTEDANCE="APPLET_BYTEDANCE"}(Et||(Et={}));class It{constructor(){this.platform=null,this.methods={[Et.BROWSER]:this.isBrowser,[Et.APP_IOS]:this.isAppiOS,[Et.APP_ANDROID]:this.isAppAndroid,[Et.APPLET_WX]:this.isWXApplet,[Et.APPLET_WX_GAME]:this.isWXGameApplet};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||Et.UNKNOWN,this.platform}static currentPlatform(){return It.instance.platform}isBrowser(){return"undefined"!=typeof navigator&&"Taro"!==navigator.product&&"ReactNative"!==navigator.product&&"undefined"==typeof GameGlobal&&("undefined"==typeof cc||null!==cc.sys.browserType)}isAppiOS(){return"undefined"!=typeof cc&&cc.sys.isNative&&cc.sys.isMobile&&"iOS"===cc.sys.os||"object"==typeof uni&&!!uni.getSystemInfoSync&&"ios"===uni.getSystemInfoSync().platform&&"object"==typeof plus}isAppAndroid(){return"undefined"!=typeof cc&&cc.sys.isNative&&cc.sys.isMobile&&"Android"===cc.sys.os||"object"==typeof uni&&!!uni.getSystemInfoSync&&"android"===uni.getSystemInfoSync().platform&&"object"==typeof plus}isWXApplet(){return"object"==typeof wx&&!!wx.getSystemInfoSync&&"undefined"==typeof WebSocket&&"undefined"==typeof XMLHttpRequest&&"undefined"==typeof plus}isWXGameApplet(){return"object"==typeof GameGlobal}isAlipayApplet(){return!1}isBytedanceApplet(){return!1}isQQApplet(){return!1}isBaiduApplet(){return!1}}It.instance=new It,function(e){e.UNIAPP="UNIAPP",e.REACT_NATIVE="REACT_NATIVE",e.COCOS="COCOS",e.TARO="TARO",e.IONIC="IONIC",e.NATIVE_APPLET_WX="NATIVE_APPLET_WX",e.NATIVE_APPLET_ALIPAY="NATIVE_APPLET_ALIPAY",e.UNKNOWN="UNKNOWN"}(Ct||(Ct={}));class Mt{constructor(){this.framework=null,this.methods={[Ct.UNIAPP]:this.isUniApp,[Ct.REACT_NATIVE]:this.isReactNative,[Ct.TARO]:this.isTaro,[Ct.NATIVE_APPLET_WX]:this.isWXApplet,[Ct.COCOS]:this.isCocos};const e=this.methods,t=Object.keys(e);for(const s of t){if((0,e[s])()){this.framework=s;break}}this.framework=this.framework||Ct.UNKNOWN,this.framework}static currentFramework(){return this.instance.framework}isUniApp(){return"object"==typeof uni&&!!uni.getSystemInfoSync}isReactNative(){return"undefined"!=typeof global&&global.__fbGenNativeModule}isTaro(){return"undefined"!=typeof process&&void 0!==process.env&&void 0!==process.env.TARO_ENV}isWXApplet(){return It.currentPlatform()===Et.APPLET_WX&&"undefined"==typeof uni}isCocos(){try{return void 0!==cc.sys.localStorage}catch(e){return!1}}}Mt.instance=new Mt;class At{static init(e){Mt.currentFramework()===Ct.REACT_NATIVE&&(this.validate(e),this.platform=e.platform,this.asyncStorage=e.asyncStorage)}static validate(e){if(!e)throw new Error("'reactNativeOptions' is missing when calling GoEasy.getInstance()");if(!e.platform)throw new Error("'platform' is missing in GoEasy 'reactNativeOptions'");if(!e.asyncStorage)throw new Error("'asyncStorage' is missing in GoEasy 'reactNativeOptions'")}}class Tt{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 Nt extends Tt{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 wt.get(e)||null}doPut(e,t){const s=new Date(2030,12,31,0,0,0,0),n=this.domain;wt.set(e,t,s,n)}remove(e){const t=this.domain;wt.remove(e,t)}support(){return"undefined"!=typeof navigator&&!0===navigator.cookieEnabled}}class Rt extends Tt{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 Ot extends Tt{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 _t extends Tt{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 Pt extends Tt{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)}}class kt extends Tt{asyncGet(e){return t(this,void 0,void 0,(function*(){const t=yield At.asyncStorage.getItem(e);return JSON.parse(t)}))}asyncPut(e,t){return At.asyncStorage.setItem(e,JSON.stringify(t))}doPut(e,t){throw new Error("Method not implemented.")}remove(e){At.asyncStorage.removeItem(e)}support(){return Mt.currentFramework()===Ct.REACT_NATIVE}doGet(e){throw new Error("Method not implemented.")}}class Dt{constructor(){this.supportedStorage=null;const e=Dt.storages;e.push(new Ot),e.push(new _t),e.push(new Rt),e.push(new Pt),e.push(new kt),e.push(new Nt),this.dispatch(),this.supportedStorage}static localStorage(){return this.instance.supportedStorage}dispatch(){for(let e of Dt.storages)if(e.support()){this.supportedStorage=e;break}}}Dt.storages=new Array,Dt.instance=new Dt;let xt=new class{init(){return t(this,void 0,void 0,(function*(){this.support()&&(this.index=Math.floor(Math.random()*(this.MAX-1)+1),null!==this.storage&&(this.index=parseInt(yield this.storage.asyncGet(this.INDEX_KEY))||this.index))}))}constructor(){this.INDEX_KEY="DOMAIN_INDEX",this.MAX=5,this.storage=Dt.localStorage(),this.init()}refresh(){let e=this.index;e>0&&e<this.MAX?e+=1:e===this.MAX&&(e=1),null!==this.storage&&(this.index=e,this.storage.asyncPut(this.INDEX_KEY,e))}i(){let e=this.index;return this.refresh(),e}support(){return[Et.BROWSER].includes(It.currentPlatform())}};var Ft=n(Object.freeze({__proto__:null,domainIndex:xt}));const Ut=new class{constructor(){this.uniAppRunningBackend=!1,this.listenAppRunning()}listenAppRunning(){Mt.currentFramework()===Ct.UNIAPP&&"object"==typeof plus&&(plus.globalEvent.addEventListener("resume",(()=>{this.uniAppRunningBackend=!1,this.uniAppRunningBackend}),!1),plus.globalEvent.addEventListener("pause",(()=>{this.uniAppRunningBackend=!0,this.uniAppRunningBackend}),!1))}runningBackend(){return this.uniAppRunningBackend}};var Lt=n(Object.freeze({__proto__:null,uniApp:Ut})),Gt=I.exports,qt=mt.exports,Bt=S.exports,jt=C,Vt=gt,Ht=vt,Wt=(c.exports("socket.io-client:manager"),it),zt=St;const{domainIndex:Xt}=Ft;var Jt,Kt=Lt.uniApp,Qt=Object.prototype.hasOwnProperty,Yt=$t;function $t(e,t){if(!(this instanceof $t))return new $t(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 zt({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||jt;this.encoder=new s.Encoder,this.decoder=new s.Decoder,this.autoConnect=!1!==t.autoConnect,this.autoConnect&&this.open()}function Zt(){var e=!1;return"object"==typeof uni&&uni.getSystemInfo&&(e=!0),e&&Kt.runningBackend()}$t.prototype.emitAll=function(){for(var e in this.emit.apply(this,arguments),this.nsps)Qt.call(this.nsps,e)&&this.nsps[e].emit.apply(this.nsps[e],arguments)},$t.prototype.updateSocketIds=function(){for(var e in this.nsps)Qt.call(this.nsps,e)&&(this.nsps[e].id=this.generateId(e))},$t.prototype.generateId=function(e){return("/"===e?"":e+"#")+this.engine.id},Bt($t.prototype),$t.prototype.reconnection=function(e){return arguments.length?(this._reconnection=!!e,this):this._reconnection},$t.prototype.reconnectionAttempts=function(e){return arguments.length?(this._reconnectionAttempts=e,this):this._reconnectionAttempts},$t.prototype.reconnectionDelay=function(e){return arguments.length?(this._reconnectionDelay=e,this.backoff&&this.backoff.setMin(e),this):this._reconnectionDelay},$t.prototype.randomizationFactor=function(e){return arguments.length?(this._randomizationFactor=e,this.backoff&&this.backoff.setJitter(e),this):this._randomizationFactor},$t.prototype.reconnectionDelayMax=function(e){return arguments.length?(this._reconnectionDelayMax=e,this.backoff&&this.backoff.setMax(e),this):this._reconnectionDelayMax},$t.prototype.timeout=function(e){return arguments.length?(this._timeout=e,this):this._timeout},$t.prototype.maybeReconnectOnOpen=function(){!this.reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()},$t.prototype.open=$t.prototype.connect=function(e,t){if(this.readyState,~this.readyState.indexOf("open"))return this;this.uri,this.engine=Gt(this.uri,this.opts);var s=this.engine,n=this;this.readyState="opening",this.skipReconnect=!1;var i=Vt(s,"open",(function(){n.onopen(),e&&e()})),o=Vt(s,"error",(function(t){if(Xt.support()){var s=parseInt(n.uri.match(/[1-9][0-9]*/g)[0]),i=Xt.i();n.uri=n.uri.replace(s,i)}if(n.cleanup(),n.readyState="closed",n.emitAll("connect_error",t),e){var o=new Error("Connection error");o.data=t,e(o)}else n.maybeReconnectOnOpen()}));if(!1!==this._timeout){var r=this._timeout,a=setTimeout((function(){i.destroy(),s.close(),s.emit("error","timeout"),n.emitAll("connect_timeout",r)}),r);this.subs.push({destroy:function(){clearTimeout(a)}})}return this.subs.push(i),this.subs.push(o),this},$t.prototype.onopen=function(){this.cleanup(),this.readyState="open",this.emit("open");var e=this.engine;this.subs.push(Vt(e,"data",Ht(this,"ondata"))),this.subs.push(Vt(e,"ping",Ht(this,"onping"))),this.subs.push(Vt(e,"pong",Ht(this,"onpong"))),this.subs.push(Vt(e,"error",Ht(this,"onerror"))),this.subs.push(Vt(e,"close",Ht(this,"onclose"))),this.subs.push(Vt(this.decoder,"decoded",Ht(this,"ondecoded")))},$t.prototype.onping=function(){this.lastPing=new Date,this.emitAll("ping")},$t.prototype.onpong=function(){this.emitAll("pong",new Date-this.lastPing)},$t.prototype.ondata=function(e){this.decoder.add(e)},$t.prototype.ondecoded=function(e){this.emit("packet",e)},$t.prototype.onerror=function(e){this.emitAll("error",e)},$t.prototype.socket=function(e,t){var s=this.nsps[e];if(!s){s=new qt(this,e,t),this.nsps[e]=s;var n=this;s.on("connecting",i),s.on("connect",(function(){s.id=n.generateId(e)})),this.autoConnect&&i()}function i(){~Wt(n.connecting,s)||n.connecting.push(s)}return s},$t.prototype.destroy=function(e){var t=Wt(this.connecting,e);~t&&this.connecting.splice(t,1),this.connecting.length||this.close()},$t.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 n=0;n<s.length;n++)t.engine.write(s[n],e.options);t.encoding=!1,t.processPacketQueue()})))},$t.prototype.processPacketQueue=function(){if(this.packetBuffer.length>0&&!this.encoding){var e=this.packetBuffer.shift();this.packet(e)}},$t.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()},$t.prototype.close=$t.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()},$t.prototype.onclose=function(e){this.cleanup(),this.backoff.reset(),this.readyState="closed",this.emit("close",e),this._reconnection&&!this.skipReconnect&&this.reconnect()},$t.prototype.reconnect=function(){if(Zt(),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(){e.skipReconnect||(e.emitAll("reconnect_attempt",e.backoff.attempts),e.emitAll("reconnecting",e.backoff.attempts),e.skipReconnect||(Zt()?(e.reconnecting=!1,e.reconnect(),e.emitAll("reconnect_error","Uniapp running backend, skipped reconnect...")):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)}})}},$t.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=E,n=C,i=Yt;c.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 n,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?n=i(a,t):(o[c]||(o[c]=i(a,t)),n=o[c]),r.query&&!t.query&&(t.query=r.query),n.socket(r.path,t)}t.protocol=n.protocol,t.connect=r,t.Manager=Yt,t.Socket=mt.exports}(i,i.exports),function(e){e.WRITE="WRITE",e.READ="READ",e.NONE="NONE"}(Jt||(Jt={}));let es=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}};const ts=i.exports;class ss{constructor(){this.io=ts,this.status=e.DISCONNECTED,this.permissions=[Jt.NONE],this.connectedObservers=[],this.disconnectedObservers=[]}connect(){this.status=e.CONNECTING}socketio(){return this.io}on(e,t){this.io.on(e,t)}disconnect(){this.io.disconnect()}getStatus(){return this.status}addConnectedObserver(e){es.isFunction(e)&&this.connectedObservers.push(e)}addDisconnectedObserver(e){es.isFunction(e)&&this.disconnectedObservers.push(e)}notify(e,t){for(let s=0;s<e.length;s++)e[s](t)}}class ns extends ss{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=e.CONNECTED,this.notify(this.connectedObservers)})),this.io.on("reconnecting",(t=>{this.status=e.CONNECTING,this.notify(this.reconnectingObservers,t)})),this.io.on("disconnect",(()=>{this.status=e.DISCONNECTED,this.notify(this.disconnectedObservers)})),this.io.on("connect_error",(function(e){}))}addReconnectingObserver(e){this.reconnectingObservers.push(e)}}var is={exports:{}},os="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof window.msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto);if(os){var rs=new Uint8Array(16);is.exports=function(){return os(rs),rs}}else{var as=new Array(16);is.exports=function(){for(var e,t=0;t<16;t++)0==(3&t)&&(e=4294967296*Math.random()),as[t]=e>>>((3&t)<<3)&255;return as}}for(var cs=[],us=0;us<256;++us)cs[us]=(us+256).toString(16).substr(1);var ls,ds,hs=function(e,t){var s=t||0,n=cs;return[n[e[s++]],n[e[s++]],n[e[s++]],n[e[s++]],"-",n[e[s++]],n[e[s++]],"-",n[e[s++]],n[e[s++]],"-",n[e[s++]],n[e[s++]],"-",n[e[s++]],n[e[s++]],n[e[s++]],n[e[s++]],n[e[s++]],n[e[s++]]].join("")},ps=is.exports,ms=hs,fs=0,gs=0;var ys=function(e,t,s){var n=t&&s||0,i=t||[],o=(e=e||{}).node||ls,r=void 0!==e.clockseq?e.clockseq:ds;if(null==o||null==r){var a=ps();null==o&&(o=ls=[1|a[0],a[1],a[2],a[3],a[4],a[5]]),null==r&&(r=ds=16383&(a[6]<<8|a[7]))}var c=void 0!==e.msecs?e.msecs:(new Date).getTime(),u=void 0!==e.nsecs?e.nsecs:gs+1,l=c-fs+(u-gs)/1e4;if(l<0&&void 0===e.clockseq&&(r=r+1&16383),(l<0||c>fs)&&void 0===e.nsecs&&(u=0),u>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");fs=c,gs=u,ds=r;var d=(1e4*(268435455&(c+=122192928e5))+u)%4294967296;i[n++]=d>>>24&255,i[n++]=d>>>16&255,i[n++]=d>>>8&255,i[n++]=255&d;var h=c/4294967296*1e4&268435455;i[n++]=h>>>8&255,i[n++]=255&h,i[n++]=h>>>24&15|16,i[n++]=h>>>16&255,i[n++]=r>>>8|128,i[n++]=255&r;for(var p=0;p<6;++p)i[n+p]=o[p];return t||ms(i)},vs=is.exports,Es=hs;var Cs=function(e,t,s){var n=t&&s||0;"string"==typeof e&&(t="binary"===e?new Array(16):null,e=null);var i=(e=e||{}).random||(e.rng||vs)();if(i[6]=15&i[6]|64,i[8]=63&i[8]|128,t)for(var o=0;o<16;++o)t[n+o]=i[o];return t||Es(i)},Ss=ys,bs=Cs,ws=bs;ws.v1=Ss,ws.v4=bs;const Is=ws;class Ms{static get(){return Is.v1().replace(/-/g,"")}}class As{constructor(e){this.permission=Jt.NONE,this.singleTimeout=0,this.totalTimeout=0,this.startTime=0,this.complete=!1,this.retried=0,this.unique=!1,this.uuid=Ms.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)}}function Ts(...e){}class Ns{constructor(e){this.callback=Ts,this.guidList=[],this.callback=e}onMessage(e,t){if("string"==typeof t&&(t=JSON.parse(t)),t.i){if(this.guidList.findIndex((e=>e===t.i))>-1)return;this.guidList.unshift(t.i),this.guidList.length>300&&this.guidList.pop()}this.callback(t)}}var Rs,Os;!function(e){e[e.connect=1500]="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"}(Rs||(Rs={})),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.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.RTC_ASK_NEW_TOKEN="RTC_ASK_NEW_TOKEN",e.RTC_DIAL="RTC_DIAL",e.RTC_ACCEPT="RTC_ACCEPT",e.RTC_ACCEPT_FAILED="RTC_ACCEPT_FAILED",e.RTC_MANUAL_END="RTC_MANUAL_END",e.RTC_CLIENT_BUSY="RTC_CLIENT_BUSY",e.RTC_TIMEOUT="RTC_TIMEOUT",e.RTC_CALL_DATA="RTC_CALL_DATA",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"}(Os||(Os={}));class _s{constructor(e){this.uniappPlugin=null,this.regIdPromise=null,this.onClickNotificationCallback=null,this.payloadAssemblers=new Array,this.allowNotification=e,this.supportNotification()&&(this.uniappPlugin=uni.requireNativePlugin("GoEasy-Uniapp"),this.uniappPlugin?this.regIdPromise=this.askRegId():console.warn("No GoEasy-Uniapp Native Plugin."))}static init(e){this.instance=new _s(e)}addAssembler(e){this.payloadAssemblers.push(e)}assemblePayload(e){let t=this.payloadAssemblers.find((t=>t.support(e)));return t?t.assemble(e):e}createLocalNotification(e,t,s){Ut.runningBackend()&&(s.g=1,"undefined"!=typeof plus&&plus.push.createMessage(t,JSON.stringify(s),{title:e}))}askRegId(){let e=null,t=0;const s=()=>new Promise(((n,i)=>{this.uniappPlugin.regId((e=>{n(e)}),(n=>{if(!(1e6===n.data.code&&t<=10))return clearTimeout(e),i(n);e=setTimeout((()=>{t++,this.regIdPromise=s()}),3500)}))}));return s()}getRegIdPromise(){return this.regIdPromise}supportNotification(){const e=It.currentPlatform(),t=Mt.currentFramework();return this.allowNotification&&t===Ct.UNIAPP&&(e===Et.APP_ANDROID||e===Et.APP_IOS)}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){}}))}availableIntent(e){return e&&Object.keys(e).length&&e.g&&1===parseInt(e.g)}getIntentData(){this.uniappPlugin.getIntentData((e=>{if(!this.availableIntent(e))return;let t=this.assemblePayload(e);const s=It.currentPlatform();plus.push.clear(),s===Et.APP_ANDROID&&this.uniappPlugin.clearAll(),this.onClickNotificationCallback(t)}))}listenClick(){this.listenPlusClickNotification();const e=It.currentPlatform();this.uniappPlugin&&e===Et.APP_ANDROID&&this.getIntentData()}onClickNotification(e){if(this.supportNotification()){if(!es.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.")}}const Ps=S.exports;class ks{constructor(){this.emitter=new Ps}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 Ds{static initial(){this.eventDriver=new ks}static on(e,t){this.eventDriver.on(e,t)}static off(e,t){this.eventDriver.off(e,t)}static once(e,t){this.eventDriver.once(e,t)}static fire(e,t){this.eventDriver.fire(e,t)}}var xs;!function(e){e.MANUAL_DISCONNECTED="MANUAL_DISCONNECTED"}(xs||(xs={}));class Fs{static get(){return t(this,void 0,void 0,(function*(){let e,t=Dt.localStorage();return null!==t&&(e=yield t.asyncGet(Fs.SM_KEY)),e}))}static put(e){return t(this,void 0,void 0,(function*(){var t=Dt.localStorage();let s=e.sm;null!==t&&s&&t.asyncPut(Fs.SM_KEY,s)}))}}Fs.SM_KEY="GE-SM";class Us{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 n="";for(let t=0;t<e.length;t++){n+=s(e.charCodeAt(t))}return n}}class Ls{static initRNUniqueId(){if(Mt.currentFramework()===Ct.REACT_NATIVE){let e=At.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(It.currentPlatform()===Et.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 n=s.getExtension("WEBGL_debug_renderer_info");if(!n)return null;t=n.UNMASKED_VENDOR_WEBGL,e=n.UNMASKED_RENDERER_WEBGL}const n={vendor:(s.getParameter(t)||"").toString(),renderer:(s.getParameter(e)||"").toString()};return JSON.stringify(n)}}return null}static z(){return t(this,void 0,void 0,(function*(){const e={p:It.currentPlatform(),f:Mt.currentFramework(),pdi:yield this.initPlusDeviceId(),vc:this.getVideoCard(),rfp:this.initRNUniqueId()};return Us.e(JSON.stringify(e),5)}))}}class Gs{constructor(e){this.rocketsBuffer=new Set,this.socket=e,this.socket.addConnectedObserver(this.onSocketConnected.bind(this))}emit(t){JSON.stringify(t),this.socket.status!==e.DISCONNECTED?(t.start(),this.doEmit(t)):t.fail({resultCode:"409",content:"Please connect first"})}doEmit(t){if(!t.complete)if(this.socket.status!==e.CONNECT_FAILED)if(this.socket.status,this.isConnected())if(this.hasPermission(t)){let e=setTimeout((()=>{this.doEmit(t)}),t.singleTimeout);t.unique&&(t.params.retried=t.retried),this.socket.socketio().emit(t.name,t.params,(s=>{clearTimeout(e),200===s.resultCode||200==s.code?t.success(s):t.fail(s)})),t.retried++}else t.fail({resultCode:401,content:"No permission"});else this.isConnecting()&&(this.rocketsBuffer.add(t),JSON.stringify(t));else t.fail({resultCode:408,content:"Failed to connect GoEasy."})}hasPermission(e){return!!this.socket.permissions.find((t=>t===e.permission))}isConnected(){return[e.CONNECTED,e.RECONNECTED,e.EXPIRED_RECONNECTED].includes(this.socket.status)}isConnecting(){return[e.CONNECTING,e.RECONNECTING].includes(this.socket.status)}onSocketConnected(){this.emitBuffer()}emitBuffer(){this.rocketsBuffer.size,Array.from(this.rocketsBuffer).forEach((e=>{this.rocketsBuffer.delete(e),this.doEmit(e)})),this.rocketsBuffer.size}}const qs="IM",Bs="PUBSUB";class js{static i(e){this.socket=e,this.emitter=new Gs(e)}static s(){if(this.socket)return this.socket;throw new Error("Please connect first.")}static e(e){this.emitter.emit(e)}static u(){return this.s().userId}static ud(){return this.s().connectOptions.data}static supportIM(){return this.s().options.modules.includes(qs)}}class Vs extends ss{constructor(e,t){super(),this.ioSocket=null,this.sid=null,this.anonymous=!1,this.userId=null,this.artifactVersion=yo.version,this.uri=null,this.ioOpts=null,this.reconnectingTimes=0,this.messageObservers={},this.connectFailedObservers=[],this.connectingObservers=[],this.expiredReconnectedObservers=[],this.options=e,this.connectOptions=t,this.ioSocket=new ns({onDisconnected:this.onIoDisconnected.bind(this),onReconnecting:this.onIoReconnecting.bind(this)}),this.ioSocketEmitter=new Gs(this.ioSocket),this.ioSocket.addConnectedObserver(this.onIoReconnected.bind(this)),this.initUserId(),this.addConnectedObserver(t.onSuccess),this.addConnectFailedObserver(t.onFailed),this.addConnectingObserver(t.onProgress)}initUserId(){let e=this.connectOptions.id;es.isEmpty(e)?this.anonymous=!0:this.userId=e.toString()}socketio(){return this.ioSocket.socketio()}extendOptions(){let e=this.connectOptions;if(es.isDef(e.data)&&!es.isObject(e.data))throw{code:400,content:"TypeError: data requires an object."};if((es.isDef(e.data)?String(e.data).length:0)>300&&es.isObject(e)&&es.isFunction(e.onFailed))throw{code:400,content:"user.data-length limit 300 byte."};if(es.isObject(e.wxmpId)){if(es.isEmpty(e.wxmpId.appid))throw{code:400,content:"wxmpId.appid is required."};if(es.isEmpty(e.wxmpId.openid))throw{code:400,content:"wxmpId.openid is required. requires string."}}else if(es.isPrimitive(e.wxmpId))throw{code:400,content:"TypeError: wxmpId requires an object."}}initUriAndOpts(){let e=this.options,t=!0;if(xt.support()){let s,n="://"+xt.i()+e.host;!0===e.supportOldBrowser?(s=["polling","websocket"],t=!1):s=["websocket"],!1!==e.forceTLS&&t?this.uri="https"+n+":443":this.uri="http"+n+":80",this.ioOpts={transports:s,timeout:Rs.connect}}else this.uri="https://wx-"+e.host+":443",this.ioOpts={transports:["websocket"],reconnectionDelayMax:Rs.reconnectionDelayMax}}onIoReconnected(){this.status===e.RECONNECTING&&this.authorize()}emit(e){js.e(e)}sendAck(e,t){this.ioSocket.io.emit(e,t)}connect(){this.initUriAndOpts(),this.extendOptions(),super.connect(),this.onConnecting(),this.ioSocket.connect({uri:this.uri,opts:this.ioOpts}),this.authorize()}disconnect(){return new Promise(((t,s)=>{let n=()=>{this.status=e.DISCONNECTED,this.ioSocket.disconnect(),Ds.fire(xs.MANUAL_DISCONNECTED),t()};if(this.options.allowNotification){let e=e=>{s(e)},t=new As({name:Os.manualDisconnect,params:{},permission:Jt.READ,singleTimeout:Rs.commonRequestSingle,totalTimeout:Rs.commonRequestTotal,fail:e,success:n});js.e(t)}else n()}))}initRegId(){return t(this,void 0,void 0,(function*(){let e=_s.instance;if(e&&e.supportNotification()&&e.getRegIdPromise())try{this.regId=yield e.getRegIdPromise(),this.regId}catch(e){console.warn("Failed to register the Manufacturers Push service:"+JSON.stringify(e))}}))}authorize(){return t(this,void 0,void 0,(function*(){this.initRegId().then((()=>t(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,allowNT:this.options.allowNotification,regId:this.regId,wxmpId:e.wxmpId,modules:this.options.modules,a:this.anonymous,z:yield Ls.z(),sm:yield Fs.get()};JSON.stringify(t);let s=new As({name:Os.authorize,params:t,permission:Jt.NONE,singleTimeout:Rs.commonInfiniteSingle,totalTimeout:Rs.commonInfiniteTotal,success:e=>{this.onAuthorizeSuccess(e)},fail:e=>{this.onAuthorizeFailed(e)}});this.ioSocketEmitter.emit(s)}))))}))}onConnecting(){this.notify(this.connectingObservers,this.reconnectingTimes)}onIoReconnecting(){this.reconnectingTimes++,this.status==e.CONNECTED||this.status==e.EXPIRED_RECONNECTED||this.status==e.RECONNECTING?this.status=e.RECONNECTING:this.status=e.CONNECTING,this.onConnecting()}onIoDisconnected(){this.status==e.DISCONNECTING&&(this.status=e.DISCONNECTED),this.notify(this.disconnectedObservers)}onAuthorizeSuccess(t){if(Fs.put(t),this.status===e.RECONNECTING){this.sid!==t.sid?(this.status=e.EXPIRED_RECONNECTED,this.notify(this.expiredReconnectedObservers)):this.status=e.RECONNECTED}else this.status=e.CONNECTED,this.sid=t.sid;t.enablePublish&&(this.permissions.find((e=>e==Jt.WRITE))||this.permissions.push(Jt.WRITE)),t.enableSubscribe&&(this.permissions.find((e=>e==Jt.READ))||this.permissions.push(Jt.READ)),this.reconnectingTimes=0,this.notify(this.connectedObservers)}onAuthorizeFailed(t){this.ioSocket.disconnect(),this.status=e.CONNECT_FAILED;let s={code:t.resultCode||408,content:t.content||"Host unreachable or timeout"};this.notify(this.connectFailedObservers,s)}addConnectingObserver(e){es.isFunction(e)&&this.connectingObservers.push(e)}addConnectFailedObserver(e){es.isFunction(e)&&this.connectFailedObservers.push(e)}addExpiredReconnectedObserver(e){es.isFunction(e)&&this.expiredReconnectedObservers.push(e)}addMessageObserver(e,t){this.messageObservers[e]||(this.messageObservers[e]=[],this.ioSocket.io.on(e,(t=>{this.notifyMessageObservers(e,t)}))),this.messageObservers[e].push(new Ns(t))}notifyMessageObservers(e,t){let s=this.messageObservers[e];for(let n=0;n<s.length;n++)s[n].onMessage(e,t)}}const Hs=new class{validateId(e,t){if(es.isEmpty(e))throw{code:400,content:` ${t} is required.`};if(!es.isStringOrNumber(e))throw{code:400,content:`TypeError: ${t} require string or number.`}}validateIdArray(e,t){if(!Array.isArray(e)||0===e.length)throw{code:400,content:`TypeError: ${t} require array.`};if(e.length>300)throw{code:400,content:`${t} is over max length 500.`};for(let s=0;s<e.length;s++){if(!es.isStringOrNumber(e[s]))throw{code:400,content:`TypeError: ${t} item require string or number.`};if(es.isNumber(e[s])&&(e[s]=e[s].toString()),0==e[s].length)throw{code:400,content:`${t} has empty item.`}}if(Array.from(new Set(e)).length<e.length)throw{code:400,content:`Duplicate element in ${t}`}}validateChannel(e,t){this.validateId(e,t)}validateChannelArray(e,t){this.validateIdArray(e,t)}validateChannelAndChannels(e,t){let s=!es.isEmpty(e),n=!es.isEmpty(t);if(!s&&!n)throw{code:400,content:"channel is required."};if(s&&n)throw{code:400,content:"subscribe to either channel or channels, not both."};s&&this.validateId(e,"channel"),n&&this.validateIdArray(t,"channels")}validateCallbackOptions(e){if(!es.isObject(e))throw{code:400,content:"bad parameters"}}validateNotification(e){function t(e,t,s){if(!(es.isString(e[t])&&e[t].length<=s))throw{code:400,content:`notification.${t} must be a string of no more than ${s} characters`}}function s(e,t,s){let n=e[t];if(es.isObject(n)&&es.isDef(n[s])){let e={code:400,content:`notification.vendorOptions.${t}.${s} require a `},i=n[s];if("vivo"===t&&!es.isNumber(i))throw e.content+="number.",e;if("vivo"!==t&&!es.isString(i))throw e.content+="string.",e}}if(!es.isObject(e))throw{code:400,content:"TypeError: notification requires an object."};{t(e,"title",32),t(e,"body",50);let n=e.vendorOptions;es.isObject(n)&&(s(n,"huawei","category"),s(n,"xiaomi","channel_id"),s(n,"oppo","channel_id"),s(n,"vivo","classification"))}}validateValIsEmpty(e,t){if(es.isUndef(e)||es.isEmpty(e))throw{code:400,content:`${t} is empty`}}validateWXMPTemplateMsg(e){if(es.isObject(e)){if(!es.isString(e.template_id))throw{code:400,content:"template_id must be string."};if(!es.isEmpty(e.url)&&!es.isString(e.url))throw{code:400,content:"url must be string"};if(!(es.isEmpty(e.miniprogram)||es.isString(e.miniprogram.appid)&&es.isString(e.miniprogram.pagepath)))throw{code:400,content:"miniprogram.appid and miniprogram.pagepath must be strings."};if(!es.isObject(e.data))throw{code:400,content:"data requires an object."}}else if(es.isPrimitive(e))throw{code:400,content:"wxmpTemplateMsg must be an object."}}};function Ws(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]=Ws(e[s]):t[s]=e[s];return t}class zs{publish(e){es.isFunction(e.onFailed)||(e.onFailed=Ts),es.isFunction(e.onSuccess)||(e.onSuccess=Ts),this.validate(e),e.channel=e.channel.toString();let t={channel:e.channel,content:e.message,nt:e.notification,at:e.accessToken,guid:Ms.get(),q:e.qos};e.wxmpTemplateMsg&&(t.wxmpTemplateMsg=Ws(e.wxmpTemplateMsg),t.wxmpTemplateMsg.data=JSON.stringify(t.wxmpTemplateMsg.data));let s=new As({name:Os.publish,params:t,unique:!0,singleTimeout:Rs.commonRequestSingle,totalTimeout:Rs.commonRequestTotal,permission:Jt.WRITE,success:function(t){e.onSuccess({code:200,content:"ok"})},fail:function(t){e.onFailed({code:t.resultCode,content:t.content})}});js.s().emit(s)}validate(e){if(Hs.validateChannel(e.channel,"channel"),es.isEmpty(e.message))throw{code:400,content:"message is required."};if(!es.isString(e.message))throw{code:400,content:"TypeError: message requires string."};if(e.message.length>1e4)throw{code:400,content:"Message over max length 10000."};if(e.qos&&!(e.qos in[0,1]))throw{code:400,content:"Qos must be 0 or 1."};e.wxmpTemplateMsg&&Hs.validateWXMPTemplateMsg(e.wxmpTemplateMsg),es.isDef(e.notification)&&Hs.validateNotification(e.notification)}}class Xs{constructor(e){this.channels=e.channels,this.accessToken=e.accessToken,this.onSuccess=e.onSuccess,this.onFailed=e.onFailed,this.onMessage=e.onMessage}empty(){}}var Js,Ks,Qs;!function(e){e.message="message",e.imMessage="imMessage",e.userPresence="userPresence",e.groupPresence="groupPresence",e.IM_MSG_READ="IM_MSG_READ",e.IM_MSG_DELETED="IM_MSG_DELETED",e.IM_MSG_RECALLED="IM_MSG_RECALLED",e.RTC_RING_EVENT="RTC_RING_EVENT",e.RTC_CANCEL_RING="RTC_CANCEL_RING",e.RTC_REMOTE_USER_LEFT="RTC_REMOTE_USER_LEFT",e.RTC_CALL_END="RTC_CALL_END",e.CS_ONLINE_CHANGED="CS_ONLINE_CHANGED"}(Js||(Js={}));class Ys{constructor(){this.subscriptions=[],_s.instance.addAssembler(new class{assemble(e){return{channel:e.ch,content:e.ctt}}support(e){return!!e.ch}})}initialGoEasySocket(){js.s().addMessageObserver(Js.message,this.onNewMessage.bind(this)),js.s().addExpiredReconnectedObserver(this.onExpiredReconnected.bind(this))}resubscribe(){let e=this.subscriptions.slice(0);this.subscriptions=[];for(let t=0;t<e.length;t++)0!=e[t].channels.length&&this.subscribe(e[t])}clearSubscriptions(){this.subscriptions=[]}onExpiredReconnected(){this.resubscribe()}onNewMessage(e){if(e.n.indexOf("_presence")>-1)return;e.a&&js.s().sendAck("ack",{publishGuid:e.i});let t={time:e.t,channel:e.n,content:e.c};this.createNotification(e),this.findSubscriptionByChannel(t.channel).onMessage(t)}createNotification(e){const t=_s.instance.supportNotification();if(!es.isObject(e.nt)||!t)return;const s={ch:e.n,ctt:e.c};_s.instance.createLocalNotification(e.nt.t,e.nt.c,s)}formatOptions(e){this.formatCallback(e),es.isFunction(e.onMessage)||(e.onMessage=Ts),e.channel&&(e.channel=e.channel.toString(),e.channels=[e.channel]),e.channels&&(e.channels=e.channels.toString().split(","))}formatCallback(e){es.isFunction(e.onSuccess)||(e.onSuccess=Ts),es.isFunction(e.onFailed)||(e.onFailed=Ts)}subscribe(e){Hs.validateChannelAndChannels(e.channel,e.channels),this.formatOptions(e);let t=new As({name:Os.subscribe,permission:Jt.READ,singleTimeout:Rs.commonRequestSingle,totalTimeout:Rs.commonRequestTotal,params:{channels:e.channels,accessToken:e.accessToken},success:()=>{let t=new Xs({channels:e.channels,accessToken:e.accessToken,onSuccess:e.onSuccess,onFailed:e.onFailed,onMessage:e.onMessage});this.subscriptions.push(t),e.onSuccess({code:200,content:"ok"})},fail:t=>{e.onFailed({code:t.resultCode,content:t.content})}});js.s().emit(t)}unsubscribe(e){if(Hs.validateChannel(e.channel,"channel"),e.channel=e.channel.toString(),!this.findSubscriptionByChannel(e.channel))return void e.onFailed({code:400,content:"channel["+e.channel+"] is not subscribed"});let t=new As({name:Os.unsubscribe,params:{channel:e.channel},permission:Jt.READ,singleTimeout:Rs.commonRequestSingle,totalTimeout:Rs.commonRequestTotal,success:()=>{e.onSuccess({code:200,content:"ok"}),this.removeChannel(e.channel)},fail:function(t){e.onFailed({code:t.resultCode,content:t.content})}});js.s().emit(t)}removeChannel(e){for(let t=0;t<this.subscriptions.length;t++){let s=this.subscriptions[t].channels;for(let n=0;n<s.length;n++)if(s[n]==e){this.subscriptions[t].channels.splice(n,1);break}}}findSubscriptionByChannel(e){let t=!1,s=null;for(let n=this.subscriptions.length-1;n>=0;n--){let i=this.subscriptions[n].channels;for(let o=0;o<i.length;o++)if(i[o]==e){t=!0,s=this.subscriptions[n];break}if(t)break}return s}}class $s{get(e){es.isFunction(e.onSuccess)||(e.onSuccess=Ts),es.isFunction(e.onFailed)||(e.onFailed=Ts),Hs.validateChannel(e.channel,"channel"),e.channel=e.channel.toString();let t=new As({name:Os.historyMessages,permission:Jt.READ,params:e,singleTimeout:Rs.commonQuerySingle,totalTimeout:Rs.commonQueryTotal,success:t=>{e.onSuccess({code:t.resultCode||t.code||200,content:t.content})},fail:t=>{e.onFailed({code:t.resultCode||t.code,content:t.content})}});js.s().emit(t)}}class Zs{constructor(e){this.channels=e.channels,this.onSuccess=e.onSuccess,this.onFailed=e.onFailed,this.onPresence=e.onPresence}}class en{constructor(){this.presenters=[]}initialGoEasySocket(){js.s().addMessageObserver(Js.message,this.onNewMessage.bind(this)),js.s().addExpiredReconnectedObserver(this.onExpiredReconnected.bind(this))}resubscribe(){let e=this.presenters.slice(0);this.presenters=[];for(let t=0;t<e.length;t++){for(let s=0;s<e[t].channels.length;s++){let n=e[t].channels[s].split("_presence");e[t].channels[s]=n[0]}0!=e[t].channels.length&&this.subscribePresence(e[t])}}onExpiredReconnected(){this.resubscribe()}onNewMessage(e){if(-1==e.n.indexOf("_presence"))return;let t=this.findPresenceByChannel(e.n);if(t){let s=JSON.parse(e.c);s.events=s.events.map((e=>{let t=e.userData?JSON.parse(e.userData):{};return{time:e.time,action:e.action,id:e.userId,data:t}})),t.onPresence(s)}}formatOptions(e){this.formatCallback(e),es.isFunction(e.onPresence)||(e.onPresence=Ts),e.channel&&(e.channel=e.channel.toString(),e.channels=[e.channel]),e.channels&&(e.channels=e.channels.toString().split(","))}formatCallback(e){es.isFunction(e.onSuccess)||(e.onSuccess=Ts),es.isFunction(e.onFailed)||(e.onFailed=Ts)}subscribePresence(e){Hs.validateChannelAndChannels(e.channel,e.channels),this.formatOptions(e),Array.isArray(e.channels)&&(e.channels=e.channels.map((e=>e+="_presence")));let t=new As({name:Os.subscribe,permission:Jt.READ,singleTimeout:Rs.commonRequestSingle,totalTimeout:Rs.commonRequestTotal,params:{channels:e.channels},success:()=>{let t=new Zs({channels:e.channels,onSuccess:e.onSuccess,onFailed:e.onFailed,onPresence:e.onPresence});this.presenters.push(t),e.onSuccess({code:200,content:"ok"})},fail:t=>{e.onFailed({code:t.resultCode,content:t.content})}});js.s().emit(t)}unsubscribePresence(e){if(this.formatCallback(e),!es.isDef(e.channel))return void e.onFailed({code:400,content:"channel is required"});if(e.channel+="_presence",!this.findPresenceByChannel(e.channel))return void e.onFailed({code:400,content:"channel["+e.channel+"] is not subscribed"});let t=new As({name:Os.unsubscribe,params:{channel:e.channel},permission:Jt.READ,singleTimeout:Rs.commonRequestSingle,totalTimeout:Rs.commonRequestTotal,success:()=>{e.onSuccess({code:200,content:"ok"}),this.removeChannel(e.channel)},fail:function(t){e.onFailed({code:t.resultCode,content:t.content})}});js.s().emit(t)}removeChannel(e){for(let t=0;t<this.presenters.length;t++){let s=this.presenters[t].channels;for(let n=0;n<s.length;n++)if(s[n]==e){this.presenters[t].channels.splice(n,1);break}}}findPresenceByChannel(e){let t=!1,s=null;for(let n=this.presenters.length-1;n>=0;n--){let i=this.presenters[n].channels;for(let o=0;o<i.length;o++)if(i[o]==e){t=!0,s=this.presenters[n];break}if(t)break}return s}}class tn{byChannel(e){let t={channels:[],includeUsers:!1,distinct:!1};es.isFunction(e.onSuccess)||(e.onSuccess=Ts),es.isFunction(e.onFailed)||(e.onFailed=Ts),Hs.validateChannelArray(e.channels,"channels"),t.channels=e.channels.toString().split(","),t.includeUsers=e.includeUsers||!1,t.distinct=e.distinct||!1;let s=new As({name:Os.hereNow,permission:Jt.READ,params:t,singleTimeout:Rs.commonQuerySingle,totalTimeout:Rs.commonQueryTotal,success:function(t){let s=t.content,n=s.channels;for(let e in n)if(n.hasOwnProperty(e)){let t=n[e];t.users&&(t.users=t.users.map((e=>(e.data=e.data?JSON.parse(e.data):{},e))))}e.onSuccess({code:t.resultCode||t.code||200,content:s})},fail:function(t){e.onFailed({code:t.resultCode||t.code||200,content:t.content})}});js.s().emit(s)}byUserId(e){let t={userIds:[],distinct:!0};es.isFunction(e.onSuccess)||(e.onSuccess=Ts),es.isFunction(e.onFailed)||(e.onFailed=Ts),Hs.validateIdArray(e.userIds,"userIds"),t.userIds=e.userIds.toString().split(","),0==e.distinct&&(t.distinct=!1);let s=new As({name:Os.hereNowByUserIds,permission:Jt.READ,params:t,singleTimeout:Rs.commonQuerySingle,totalTimeout:Rs.commonQueryTotal,success:function(t){let s=t.content;s=s.map((e=>({id:e.userId,data:e.userData?JSON.parse(e.userData):{}}))),e.onSuccess({code:t.resultCode||t.code||200,content:s})},fail:function(t){e.onFailed({code:t.resultCode||t.code||200,content:t.content})}});js.s().emit(s)}}class sn{static onSuccess(e,t){es.isFunction(e.onSuccess)&&e.onSuccess(t)}static onFailed(e,t){if(!es.isObject(e)||!es.isFunction(e.onFailed))throw t;e.onFailed(t)}}class nn{constructor(e){this.subscriber=new Ys,this.options=e}static init(e){nn.instance=new nn(e)}initialGoEasySocket(){this.publisher=new zs,this.histories=new $s,this.presence=new en,this.hereNows=new tn,this.subscriber.initialGoEasySocket(),this.presence.initialGoEasySocket()}initialBeforeConnect(){this.subscriber.clearSubscriptions()}catch(e,t){try{this.validateOptions(),e()}catch(e){sn.onFailed(t,e)}}validateOptions(){if(!js.s()||js.s().getStatus()!==e.CONNECTED)throw Error("Please call connect() first.");if(!this.options.modules||!this.options.modules.includes(Bs))throw{code:400,content:`Invalid options: module '${Bs}' is not enabled`}}publish(e){this.catch((()=>{this.publisher.publish(e)}),e)}subscribe(e){this.catch((()=>{this.subscriber.subscribe(e)}),e)}unsubscribe(e){this.catch((()=>{this.subscriber.unsubscribe(e)}),e)}subscribePresence(e){this.catch((()=>{this.presence.subscribePresence(e)}),e)}unsubscribePresence(e){this.catch((()=>{this.presence.unsubscribePresence(e)}),e)}history(e){this.catch((()=>{this.histories.get(e)}),e)}hereNow(e){this.catch((()=>{this.hereNows.byChannel(e)}),e)}hereNowByUserIds(e){this.catch((()=>{this.hereNows.byUserId(e)}),e)}}!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.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"}(Ks||(Ks={})),function(e){e.RING="RING",e.USER_ACCEPTED="USER_ACCEPTED",e.CALL_ENDED="CALL_ENDED",e.USER_QUITED="USER_QUITED"}(Qs||(Qs={}));const on=S.exports;class rn{constructor(){this.emitter=new on}on(e,t){if(!es.isString(e))throw Error("event require a string.");if(!es.isDef(Ks[e])&&!es.isDef(Qs[e]))throw Error("An event that is not defined");if(!es.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 an{constructor(){}upload(e,t){throw Error("Not implementation yet.")}}let cn=new class extends an{constructor(){super()}upload(e,t){try{return delete e.parameters.fileRes,new Promise(((s,n)=>{uni.uploadFile({url:e.host,filePath:this.getTempFilePath(e),name:"file",formData:e.parameters,success(t){if(200===t.statusCode){let n=e.payload;n.message=t.errMsg,s({code:200,content:n})}else n({code:t.statusCode,content:t.errMsg})},fail(e){n({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}};const un=new class extends an{upload(e,t){try{return new Promise(((s,n)=>{wx.uploadFile({url:e.host,filePath:this.getTempFilePath(e),name:"file",formData:e.parameters,success(t){if(200===t.statusCode){let n=e.payload;n.message=t.errMsg,s({code:200,content:n})}else n({code:t.statusCode,content:t.errMsg})},fail(e){n({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}};const ln=new class extends an{constructor(){super()}upload(e,t){try{return new Promise(((s,n)=>{let i=new XMLHttpRequest;i.open("post",e.host,!0);for(let t in e.headers)i.setRequestHeader(t,e.headers[t]);i.upload.onprogress=function(e){t&&t(e)},i.upload.onloadstart=function(e){t&&t(e)},i.upload.onloadend=function(e){t&&t(e)};let o=new FormData;for(let t in e.parameters)"fileRes"==t?o.append("file",e.parameters[t]):o.append(t,e.parameters[t]);i.send(o),i.onreadystatechange=function(){if(4==i.readyState)if(i.status>=200&&i.status<300||304==i.status){let t=e.payload;t.message=i.responseText,s({code:200,content:t})}else n({code:i.status,content:i.responseText})}}))}catch(e){return new Promise(((t,s)=>{s({code:500,content:e})}))}}};const dn=new class{constructor(){this.uploader={[Ct.UNIAPP]:cn,[Ct.NATIVE_APPLET_WX]:un,[Ct.TARO]:It.currentPlatform()===Et.APPLET_WX?un:ln,[Ct.UNKNOWN]:ln}}upload(e,t){const s=Mt.currentFramework();return this.uploader[s].upload(e,t)}};var hn,pn;!function(e){e.aliYun="ALI",e.qiNiu="QN",e.tencent="TX"}(hn||(hn={}));class mn{constructor(e,t,s,n,i){this.host=e,this.headers=t,this.parameters=s,this.file=n,this.payload=i}}class fn{constructor(){}build(e,t,s){}newFileName(e){return e&&e.newFilename||""}}!function(e){e.TEXT="text",e.IMAGE="image",e.FILE="file",e.VIDEO="video",e.AUDIO="audio"}(pn||(pn={}));let gn=new class extends fn{constructor(){super()}url(e){return e.host+"/"+e.dir+"/"+this.newFileName(e)}build(e,t,s){let n;n={key:e.dir+"/"+this.newFileName(e),OSSAccessKeyId:e.accessKeyId,policy:e.policy,signature:e.signature,success_action_status:"200",fileRes:t},pn.FILE===s&&(n={key:e.dir+"/"+this.newFileName(e),OSSAccessKeyId:e.accessKeyId,policy:e.policy,signature:e.signature,success_action_status:"200","Content-Disposition":"attachment;filename="+t.name,fileRes:t});let i={newFileName:this.newFileName(e),url:this.url(e)};return new mn(e.host,null,n,t,i)}};const yn=new class extends fn{constructor(){super()}url(e){return e.downloadUrl}build(e,t){let s={key:this.newFileName(e),token:e.token,file:t},n={newFileName:this.newFileName(e),url:this.url(e)};return new mn(e.host,null,s,t,n)}};let vn=new class extends fn{constructor(){super()}url(e){return e.host+"/"+e.key}build(e,t,s){let n={"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};pn.FILE===s&&(n={"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});let i={newFileName:e.key,url:this.url(e)};return new mn(e.host,null,n,t,i)}};class En{constructor(e){return e===hn.aliYun?gn:e===hn.tencent?vn:yn}build(e,t,s){}}class Cn{resolve(e){return new Promise(((t,s)=>{let n=new As({name:"uploadToken",params:{filename:e},permission:Jt.WRITE,singleTimeout:Rs.commonRequestSingle,totalTimeout:Rs.commonRequestTotal,fail(e){s(e)},success(e){200===e.code?t(e):s(e)}});js.s().emit(n)}))}}class Sn{constructor(){this.uploadTokenResolver=new Cn}build(e,t,s){return new Promise(((n,i)=>{this.uploadTokenResolver.resolve(t).then((t=>{let i=t.content;n(new En(i.vendor).build(i,e,s))})).catch((e=>{i(e)}))}))}}class bn{constructor(){this.requestBuilder=new Sn,this.fileUploader=dn}upload(e,t,s,n){return new Promise(((i,o)=>{this.requestBuilder.build(e,t,n).then((e=>{i(this.doUpload(e,s))})).catch((e=>{o(e)}))}))}customizeUpload(e,t){this.doUpload(e,t)}doUpload(e,t){return this.fileUploader.upload(e,t)}}class wn{}class In extends wn{constructor(){super(...arguments),this.goEasyUploader=new bn}improve(e){let t=e.message;return new Promise(((e,s)=>{let n,i,o=t.buildOptions.createOptions;t.type===pn.VIDEO?(i=t.payload,n=i.video.name):(i=t.payload,n=i.name),this.goEasyUploader.upload(o.file,n,o.onProgress,t.type).then((s=>{this.setPayload(s,t),e()})).catch((e=>{s(e)}))}))}setPayload(e,t){let{content:s={}}=e;t.payload.url=s.url}}class Mn extends In{setPayload(e,t){let s=t.payload,n="?x-oss-process=video/snapshot,t_0000,f_jpg,h_"+s.thumbnail.height+",m_fast,ar_auto";s.video.url=e.content.url,s.thumbnail.url=e.content.url+n,s.video.name=e.content.newFileName}}class An{constructor(){this.improvers={[pn.FILE]:new In,[pn.AUDIO]:new In,[pn.IMAGE]:new In,[pn.VIDEO]:new Mn}}improve(e){let t=this.improvers[e.message.type];return t?t.improve(e):Promise.resolve()}}class Tn{constructor(e,t,s,n,i){this.validate(e),this.mt=e.type,this.to=t.id.toString(),this.d=JSON.stringify(t.data),this.p=JSON.stringify(e.payload),s&&(this.nt=s),i&&(this.at=i),n&&(this.wxmpTemplateMsg=Ws(n),this.wxmpTemplateMsg.data=JSON.stringify(this.wxmpTemplateMsg.data));let o=t.type;if(this.t=o,o===co.CS){let t=e;this.tid=t.teamId}this.guid=e.messageId}validate(e){if(e.type===pn.TEXT){if(JSON.stringify(e.payload).length>3072)throw Error("message-length limit 3kb")}}}var Nn,Rn;!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.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"}(Nn||(Nn={}));class On{clearUseLessAttribute(){delete this.buildOptions}isOtherSent(){return this.senderId!==js.u()}getToData(){return this.buildOptions.createOptions.to.data}}class _n{constructor(){this.payloadImprover=new An}send(e){this.validate(e);let t=e.message,s=e.accessToken,n=t.buildOptions,i=n.createOptions,o=i.notification,r=i.wxmpTemplateMsg,a=i.to;a.data||(a.data={}),t.status=uo.SENDING;let c=n.complete,u=this.payloadImprover.improve(e);Promise.all([c,u]).then((()=>{this.doSend(t,a,o,r,s,e)})).catch((s=>{t.status=uo.FAIL,sn.onFailed(e,{code:s.code||400,content:s.content||s})}))}doSend(e,t,s,n,i,o){let r=new Tn(e,t,s,n,i);Ds.fire(Nn.MESSAGE_SENDING,e);let a=new As({name:Os.publishIM,params:r,unique:!0,permission:Jt.WRITE,singleTimeout:Rs.commonRequestSingle,totalTimeout:Rs.commonRequestTotal,fail:t=>{e.status=uo.FAIL,Ds.fire(Nn.MESSAGE_SEND_FAILED,e),sn.onFailed(o,{code:t.resultCode,content:t.content})},success:t=>{if(e.status=uo.SUCCESS,e.timestamp=t.content.timestamp,e.scene()===co.CS){let s=e;s.customerId()!==js.u()&&(s.sessionId=t.content.sessionId)}e.clearUseLessAttribute(),Ds.fire(Nn.MESSAGE_SEND_SUCCESS,e),sn.onSuccess(o,e)}});js.s().emit(a)}validate(e){let t=e.message;if(!(t instanceof On))throw new Error("it is invalid message");if(t.status!==uo.NEW)throw new Error("Please create a new message, a message can only be sent once")}}class Pn{insert(e,t){let s=this.binarySearch(e,t);if(s>=0)e.splice(s,1,t);else{let n=-s-1;e.splice(n,0,t)}}binarySearch(e,t){let s=0,n=e.length-1;for(;s<=n;){let i=n+s>>1,o=this.compare(t,e[i]);if(o>0)s=i+1;else{if(!(o<0))return i;n=i-1}}return-s-1}}class kn{constructor(e){this.messages=new Array,this.allLoaded=!1,this.target=e}all(){return this.messages}sliceOverLengthMessages(){this.messages.length>kn.CACHE_MAX_LENGTH&&(this.messages=this.messages.slice(-kn.CACHE_MAX_LENGTH),!0===this.allLoaded&&(this.allLoaded=!1))}getMaxMessage(){return this.messages[this.messages.length-1]}loadLocalMessages(e,t){let s=[],n=this.messages.length;if(t){if(n>0){let i=this.messages[0].timestamp,o=this.messages[n-1].timestamp;if(t>=i&&t<=o)for(let i=n-1;i>=0;i--){let n=this.messages[i];if(n.timestamp<t){if(!(s.length<e))break;s.unshift(n)}}}}else s=this.messages.slice(-e);return s}cacheServerMessages(e,t){let s=this.messages[0];this.messages.length<kn.CACHE_MAX_LENGTH&&(!e.lastTimestamp||this.messages.length>0&&s.timestamp===e.lastTimestamp)&&(t.forEach((e=>{kn.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);es.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)}recallMessages(e){e.forEach((e=>{let t=this.findMessageByTime(e.timestamp);es.isDef(t)&&(t.recalled=!0),e.recalled=!0}))}isEmpty(){return 0===this.messages.length}deleteMessages(e){e.forEach((e=>{this.deleteMessage(e.messageId)}))}saveMessage(e){kn.sortedInserter.insert(this.messages,e),this.sliceOverLengthMessages()}maxSuccessMessageTime(){for(let e=this.messages.length-1;e>=0;e--)if(this.messages[e].status===uo.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)}}kn.CACHE_MAX_LENGTH=200,kn.sortedInserter=new class extends Pn{compare(e,t){let s=e.timestamp-t.timestamp;return s>0?1:0===s?0:-1}};class Dn{constructor(e,t,s){this.scene=e,this.id=t,es.isDef(s)&&(this.teamId=s)}toString(){return co.PRIVATE===this.scene||co.GROUP===this.scene?this.scene+"#"+this.id:this.scene+"#"+this.id+"#"+this.teamId}customerId(){if(co.CS===this.scene)return this.id===this.teamId?js.u():this.id}static byScene(e,t,s){return new Dn(e,t,s)}static byIMMessage(e){let t,s,n=e.scene();if(n===co.PRIVATE){let t=e.senderId,n=e.targetId();s=js.u()===t?n:t}else if(n===co.GROUP)s=e.targetId();else{if(n!==co.CS)throw{code:400,content:`scene ${n} not exists`};s=e.targetId(),t=e.teamId}return new Dn(n,s,t)}static byMessageReadRemoteEvent(e){let t,s=e.scene,n=e.targetId,i=e.markerId,o=e.teamId;return s===co.PRIVATE?t=js.u()===i?n:i:s===co.GROUP?t=n:s===co.CS&&(t=n===o?i===js.u()?o:i:i===js.u()?n:o),new Dn(s,t,o)}static byIMMessageDeletedEvent(e){let t=e.scene,s=e.deleterId;if(t===co.PRIVATE){let n=js.u()===s?e.targetId:s;return new Dn(t,n)}if(t===co.GROUP)return new Dn(t,e.targetId)}static byConversationDTO(e){let t=e.lastMessage;return this.byIMMessage(t)}static byRemoteRecallEvent(e){let t;if(e.scene===co.PRIVATE){let s=e.conversationId.split(":",2);t=s[0]===js.u()?s[1]:s[0]}else t=e.conversationId;return new Dn(e.scene,t)}}class xn{constructor(e){this.times=new Array;let t=e[0],s=Dn.byIMMessage(t);this.scene=s.scene,this.targetId=s.id,e.forEach((e=>{e.status===uo.SUCCESS&&this.times.push(e.timestamp)})),this.times.sort(((e,t)=>e<t?-1:e==t?0:1))}}class Fn{static deleteServerMessages(e){let t=new xn(e);return t.times.length<0?Promise.resolve():new Promise(((e,s)=>{let n=new As({name:Os.IM_DELETE_MESSAGE,params:t,permission:Jt.WRITE,singleTimeout:Rs.commonQuerySingle,totalTimeout:Rs.commonQueryTotal,success:t=>{200===t.code?e(t):s(t)},fail:e=>{s(e)}});js.s().emit(n)}))}static validate(e){let t=e.messages;for(let e=0;e<t.length;e++){let s=t[e];if(s.status===uo.SENDING)throw{code:400,content:"message["+e+"] is '"+s.status+"' and cannot be deleted"}}}}class Un{constructor(e){this.times=new Array;let t=e[0],s=Dn.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 Ln{static recallServerMessages(e){let t=new Un(e);return 0===t.times.length?Promise.resolve():new Promise(((e,s)=>{let n=new As({name:Os.IM_RECALL_MESSAGE,params:t,permission:Jt.WRITE,singleTimeout:Rs.commonRequestSingle,totalTimeout:Rs.commonRequestTotal,fail:e=>{s(e)},success:t=>{200===t.code?e(t):s(t)}});js.s().emit(n)}))}static validate(e){let t=e.messages;for(let e=0;e<t.length;e++){let s=t[e];if(s.status!==uo.SUCCESS)throw{code:400,content:"message["+e+"] is '"+s.status+"' and cannot be recalled"};if(s.recalled)throw{code:400,content:"message["+e+"] has been recalled"};if(s.senderId!==js.u())throw{code:400,content:"it is not allowed to recall messages sent by others"}}}}class Gn{constructor(e,t,s,n,i){this.scene=e,this.id=t,this.after=s,this.min=n,this.teamId=i}}class qn{constructor(e,t,s,n){this.id=e,this.scene=t,this.lastTimestamp=s,this.teamId=n}}class Bn extends On{constructor(){super(...arguments),this.read=!1}scene(){return co.PRIVATE}targetId(){return this.receiverId}}class jn extends On{scene(){return co.GROUP}targetId(){return this.groupId}}class Vn extends On{constructor(){super(...arguments),this.accepted=!1}scene(){return co.CS}targetId(){return js.u()===this.customerId()?this.teamId:this.customerId()}sendByCustomer(){return this.to===this.teamId}customerId(){return this.sendByCustomer()?this.senderId:this.to}isOtherSent(){return js.u()===this.customerId()?this.senderId!==js.u():this.senderId===this.customerId()}}!function(e){e.ACCEPT="CS_ACCEPT",e.END="CS_END",e.TRANSFER="CS_TRANSFER"}(Rn||(Rn={}));class Hn{build(e){let t,s=e.t;s===co.PRIVATE?(t=new Bn,t.read=!1,t.receiverId=e.r):s===co.GROUP?(t=new jn,t.groupId=e.r,t.senderData=e.d?JSON.parse(e.d):{}):s===co.CS&&(t=new Vn,t.to=e.r,t.teamId=e.tid,t.senderData=e.d?JSON.parse(e.d):{},t.accepted=e.accepted,t.customerId()!==js.u()&&(t.sessionId=e.sessionId)),t.senderId=e.s,t.messageId=e.i,t.timestamp=e.ts,t.type=e.mt;let n=e.p;if(es.isDef(n))if(s===co.CS&&t.type===Rn.TRANSFER){let e=JSON.parse(n);e.transferTo.data=JSON.parse(e.transferTo.data),t.payload=e}else t.payload=JSON.parse(n);return t.recalled=e.rc,t.status=uo.SUCCESS,t}}class Wn{constructor(){this.builder=new Hn}sync(e,t,s,n,i){let o=new Gn(e,t,s,n,i);return new Promise(((e,t)=>{let s=new As({name:Os.IM_HISTORY_CHANGE,params:o,permission:Jt.READ,singleTimeout:Rs.commonQuerySingle,totalTimeout:Rs.commonQueryTotal,fail:e=>{t(e)},success:t=>{let s=t.content;e(s)}});js.s().emit(s)}))}loadServerMessages(e,t){return new Promise(((s,n)=>{let i=new As({name:Os.IM_HISTORY,params:t,permission:Jt.READ,singleTimeout:Rs.commonQuerySingle,totalTimeout:Rs.commonQueryTotal,fail:e=>{n(e)},success:t=>{let n=t.content;n.messages=this.convertServerMessages(e,n.messages),s(n)}});js.s().emit(i)}))}convertServerMessages(e,t){let s=[],n=e.scene,i=e.id;return t.forEach((t=>{if(t.t=n,co.PRIVATE===n)t.r=t.s===js.u()?i:js.u();else if(co.GROUP===n)t.r=i;else if(co.CS===n){let s=e.customerId(),n=e.teamId;s===js.u()?t.r=n:t.r=s}let o=this.builder.build(t);s.push(o)})),s}updateServerOffsets(e,s){return t(this,void 0,void 0,(function*(){let t=new qn(s.id,s.scene,e,s.teamId);return new Promise(((e,s)=>{let n=new As({name:Os.IM_MARK_AS_READ,params:t,permission:Jt.WRITE,singleTimeout:Rs.commonRequestSingle,totalTimeout:Rs.commonRequestTotal,success:t=>{e(t)},fail:e=>{s(e)}});js.s().emit(n)}))}))}}Wn.instance=new Wn;class zn{constructor(){this.offsetMap=new Map,this.markingTime=0,this.userId=js.u()}updateOffset(e,t){let s=this.offsetMap.get(e);return es.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 Xn{constructor(e,t,s,n,i){this.id=e,this.scene=t,this.lastTimestamp=s,this.limit=n,this.teamId=i}}class Jn{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,n=this.history.unreadAmount(),i=this.history.getMaxMessage();i&&(s=i.status,e=i.read,t=i.recalled);let o=this.history.target;this.oldLastMessage!==i||this.oldLastMessageRead!==e||this.oldLastMessageRecalled!==t||this.oldLastMessageStatus!==s?i?Ds.fire(Nn.MAX_MESSAGE_CHANGED,i):Ds.fire(Nn.MAX_MESSAGE_DELETED,o):this.oldUnreadAmount!==n&&Ds.fire(Nn.UNREAD_AMOUNT_CHANGED,o)}}class Kn{constructor(e){this.expiredTime=0,this.remoteHistory=Wn.instance,this.target=e,this.userOffsets=new zn,this.messageCache=new kn(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,s){return t(this,void 0,void 0,(function*(){return this.expiredTime>0&&!this.messageCache.isEmpty()&&(yield this.updateByServerChange()),es.isUndef(s)?s=10:s>30&&(s=30),yield this.loadServerMessages(e,s)}))}loadServerMessages(e,s){return t(this,void 0,void 0,(function*(){let t=this.messageCache.loadLocalMessages(s,e);if(!1===this.messageCache.allLoaded&&t.length!==s){let n=s-t.length,i=t[0]?t[0].timestamp:e,o=new Xn(this.target.id.toString(),this.target.scene,i,n,this.target.teamId),r=yield this.remoteHistory.loadServerMessages(this.target,o),a=r.messages;t=a.concat(t),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 t}))}deleteMessages(e){return t(this,void 0,void 0,(function*(){yield this.aopUnreadAmountMaxMessage((()=>t(this,void 0,void 0,(function*(){let t=e.messages;yield Fn.deleteServerMessages(t),this.messageCache.deleteMessages(t),sn.onSuccess(e)}))))}))}syncDeletedMessage(e,t){this.aopUnreadAmountMaxMessage((()=>{this.doSyncDeletedMessage(e,t)}))}doSyncDeletedMessage(e,t){if(e===js.u()){let e=this.messageCache.findMessagesByTimes(t);this.messageCache.deleteMessages(e),e.length>0&&Yi.aec.fire(Ks.MESSAGE_DELETED,e)}}recallMessage(e){return t(this,void 0,void 0,(function*(){yield this.aopUnreadAmountMaxMessage((()=>t(this,void 0,void 0,(function*(){let t=e.messages;yield Ln.recallServerMessages(t),this.messageCache.recallMessages(t),sn.onSuccess(e)}))))}))}syncRecalledMessage(e){this.aopUnreadAmountMaxMessage((()=>t(this,void 0,void 0,(function*(){this.doSyncRecalledMessage(e)}))))}doSyncRecalledMessage(e){let t=this.messageCache.findMessagesByTimes(e);t.length>0&&(this.messageCache.recallMessages(t),Yi.aec.fire(Ks.MESSAGE_RECALLED,t))}expire(){this.messageCache.isEmpty()||(this.expiredTime=this.messageCache.maxSuccessMessageTime())}updateByServerChange(){return t(this,void 0,void 0,(function*(){yield this.aopUnreadAmountMaxMessage((()=>t(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(js.u(),t);let s=e.recalled;s.length>0&&this.doSyncRecalledMessage(s),this.expiredTime=0}))))}))}markRead(){return t(this,void 0,void 0,(function*(){yield this.aopUnreadAmountMaxMessage((()=>t(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(),js.u(),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(),js.u(),e.timestamp,!0)}))}onMessageSendFailed(e){this.getMaxMessage()===e&&Ds.fire(Nn.MAX_MESSAGE_CHANGED,e)}onMessageReceived(e){this.aopUnreadAmountMaxMessage((()=>{this.messageCache.saveMessage(e),this.markLocalMessagesRead(this.messageCache.all(),e.senderId,e.timestamp,!0)}))}aopUnreadAmountMaxMessage(e,s){return t(this,void 0,void 0,(function*(){try{let t=new Jn(this);t.pre(),yield e(),t.post()}catch(e){sn.onFailed(s,e)}}))}markLocalMessagesRead(e,t,s,n){if(this.userOffsets.updateOffset(t,s),this.isOtherUserId(t)){let t=this.markMySentRead(e,s);n&&t.length>0&&Yi.aec.fire(Ks.MESSAGE_READ,t)}else t===js.u()&&this.markOthersSentRead(e,s)}markOthersSentRead(e,t){if(this.target.scene===co.PRIVATE)for(let s=e.length-1;s>=0;s--){let n=e[s];if(n.isOtherSent()&&n.timestamp<=t){if(n.read)break;n.read=!0}}}markMySentRead(e,t){let s=new Array;if(this.target.scene===co.PRIVATE)for(let n=e.length-1;n>=0;n--){let i=e[n];if(!i.isOtherSent()&&i.timestamp<=t&&i.status===uo.SUCCESS){if(i.read)break;i.read=!0,s.push(i)}}return s}isOtherUserId(e){if(this.target.scene===co.CS){let t=this.target.customerId();return js.u()===t?e!==js.u():e===t}return e!==js.u()}unreadAmount(e){let t=0,s=this.userOffsets.myOffset(),n=this.messageCache.all();for(const e of n)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 es.isDef(t)?t.timestamp:0}}class Qn{constructor(e,t){this.teamId=e,this.customerId=t}}class Yn{}class $n{constructor(e,t,s){this.teamId=e,this.teamData=JSON.stringify(t),this.agentData=JSON.stringify(s)}}class Zn{constructor(e){this.teamId=e}}class ei{constructor(e){this.teamId=e}}class ti{static getInstance(){return ti.instance||(ti.instance=new ti),ti.instance}constructor(){this.synchronized=!0,js.s().addDisconnectedObserver(this.onDisconnected.bind(this)),js.s().addConnectedObserver(this.onConnected.bind(this)),js.s().addMessageObserver(Js.CS_ONLINE_CHANGED,this.onlineChanged.bind(this))}queryTeams(){return this.queryMyTeamPromise||(this.queryMyTeamPromise=new Promise(((e,t)=>{let s=new As({name:Os.CS_MY_TEAMS,params:{},permission:Jt.READ,singleTimeout:Rs.commonQuerySingle,totalTimeout:Rs.commonQueryTotal,fail:e=>{t(e)},success:t=>{this.teamIds=new Set(t.content),this.synchronized=!0,e(this.teamIds)}});js.s().emit(s)}))),this.queryMyTeamPromise}myTeams(){if(this.synchronized&&this.queryMyTeamPromise)return this.teamIds;throw"please query team first."}isOnline(e,s){return t(this,void 0,void 0,(function*(){yield this.queryTeams(),sn.onSuccess(s,this.teamIds.has(e))}))}online(e,t){if(!es.isObject(t.agentData)||!es.isObject(t.teamData))throw{code:400,content:"agentData and teamData require an object"};let s=new $n(e,t.teamData,t.agentData),n=new As({name:Os.CS_ONLINE,params:s,permission:Jt.WRITE,singleTimeout:Rs.commonRequestSingle,totalTimeout:Rs.commonRequestTotal,fail:e=>{sn.onFailed(t,e)},success:s=>{this.teamIds.add(e),sn.onSuccess(t),Ds.fire(Nn.CS_ONLINE_SUCCESS)}});js.s().emit(n)}offline(e,t){let s=new Zn(e),n=new As({name:Os.CS_OFFLINE,params:s,permission:Jt.WRITE,singleTimeout:Rs.commonRequestSingle,totalTimeout:Rs.commonRequestTotal,fail:e=>{sn.onFailed(t,e)},success:s=>{this.teamIds.delete(e),sn.onSuccess(t),Ds.fire(Nn.CS_OFFLINE_SUCCESS)}});js.s().emit(n)}agents(e,t){let s=new ei(e),n=new As({name:Os.CS_AGENTS,params:s,permission:Jt.READ,singleTimeout:Rs.commonQuerySingle,totalTimeout:Rs.commonQueryTotal,fail:e=>{sn.onFailed(t,e)},success:e=>{e.content.forEach((e=>{e.data=JSON.parse(e.data)})),sn.onSuccess(t,e)}});js.s().emit(n)}onlineChanged(e){e.online?this.teamIds.add(e.teamId):this.teamIds.delete(e.teamId)}onDisconnected(){this.queryMyTeamPromise=null,this.teamIds=null}onConnected(){this.synchronized&&(this.queryMyTeamPromise=this.queryTeams())}}class si{constructor(e){this.teamId=e,Ds.on(Nn.CS_AGENT_MESSAGE_RECEIVED,this.onMessageReceived),Ds.on(Nn.CS_ACCEPTED,this.onMessageReceived),Ds.on(Nn.CS_ENDED,this.onMessageReceived),Ds.on(Nn.CS_TRANSFER,this.onMessageReceived),Ds.on(xs.MANUAL_DISCONNECTED,si.destroy)}static live(e,s){return t(this,void 0,void 0,(function*(){let t=s.customerId;Hs.validateId(t,"customerId");let n=new Qn(e,t);yield ti.getInstance().queryTeams();let i=new As({name:Os.CS_LIVE_SESSION,params:n,permission:Jt.WRITE,singleTimeout:Rs.commonRequestSingle,totalTimeout:Rs.commonRequestTotal,fail:e=>{sn.onFailed(s,e)},success:t=>{si.destroy(),this.session=new si(e),this.session.liveOptions=s;let n=t.content.customerStatus;"ACCEPTED"===n.status&&(n.agent.data=JSON.parse(n.agent.data)),this.session.status=n,this.session.liveOptions.onStatusUpdated(this.session.status),sn.onSuccess(s)}});js.s().emit(i)}))}customerId(){return this.liveOptions.customerId}static isMyCustomer(e){let t=si.session;if(t&&t.teamId===e.teamId&&t.customerId()===e.customerId()){let s=ti.getInstance().myTeams(),n=t.status.agent;return s.has(e.teamId)&&(!n||n.id===js.u())}return!0}static isMyMessage(e){let t=Dn.byIMMessage(e);return e.type===Rn.TRANSFER&&e.payload.transferTo.id===js.u()||this.isMyCustomer(t)}static quit(e){let t=si.session;if(t){let s=t.liveOptions.customerId;Hs.validateId(s,"customerId");let n=new Qn(t.teamId,s),i=new As({name:Os.CS_QUIT_LIVE,params:n,permission:Jt.WRITE,singleTimeout:Rs.commonRequestSingle,totalTimeout:Rs.commonRequestTotal,fail:t=>{sn.onFailed(e,t)},success:t=>{si.destroy(),sn.onSuccess(e)}});js.s().emit(i)}}static destroy(){let e=si.session;e&&(Ds.off(Nn.CS_AGENT_MESSAGE_RECEIVED,e.onMessageReceived),Ds.off(Nn.CS_ACCEPTED,e.onMessageReceived),Ds.off(Nn.CS_ENDED,e.onMessageReceived),Ds.off(Nn.CS_TRANSFER,e.onMessageReceived),Ds.off(xs.MANUAL_DISCONNECTED,si.destroy),si.session=null)}onMessageReceived(e){let t=si.session;if(e.scene()===co.CS&&t.liveOptions){let s=e,n=t.liveOptions.customerId;t.teamId===s.teamId&&s.customerId()===n&&(t.tryUpdateStatus(s),t.liveOptions.onNewMessage(s))}}tryUpdateStatus(e){if("FREE"!==this.status.status&&this.status.sessionId>e.sessionId)return;let t;switch(e.type){case Rn.ACCEPT:t=new Yn,t.status="ACCEPTED",t.start=e.payload.sessionStart,t.sessionId=e.sessionId,t.agent=new po(e.senderId,e.senderData);break;case Rn.END:t=new Yn,t.status="FREE";break;case Rn.TRANSFER:t=new Yn,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 Yn,t.status="PENDING",t.start=e.timestamp,t.sessionId=e.sessionId)}t&&(this.status=t,this.liveOptions.onStatusUpdated(t))}}class ni extends Kn{constructor(e){super(e),this.unread=0,this.markingAmount=0}loadHistory(e,s){return t(this,void 0,void 0,(function*(){return es.isUndef(s)?s=10:s>30&&(s=30),yield this.loadServerMessages(e,s)}))}loadServerMessages(e,s){return t(this,void 0,void 0,(function*(){let t=new Xn(this.target.id.toString(),this.target.scene,e,s,this.target.teamId),n=yield this.remoteHistory.loadServerMessages(this.target,t);return n.userOffsets.forEach((e=>{this.userOffsets.updateOffset(e.userId,e.offset)})),n.messages}))}deleteMessages(e){return t(this,void 0,void 0,(function*(){sn.onFailed(e,"Delete CS message is not supported yet")}))}recallMessage(e){return t(this,void 0,void 0,(function*(){sn.onFailed(e,"Recall CS message is not supported yet")}))}initMaxMessageAndOffsets(e,t){t.forEach((e=>{this.userOffsets.updateOffset(e.userId,e.offset)})),(es.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),Ds.fire(Nn.MAX_MESSAGE_CHANGED,e)}onMessageSendSuccess(e){this.saveAcceptedMessage(e),this.userOffsets.updateOffset(e.senderId,e.timestamp),this.acceptedMaxMessage===e&&Ds.fire(Nn.MAX_MESSAGE_CHANGED,e)}onMessageSendFailed(e){this.acceptedMaxMessage===e&&Ds.fire(Nn.MAX_MESSAGE_CHANGED,e)}onMessageReceived(e){si.isMyMessage(e)&&(!e.accepted||e.senderId!==js.u()&&e.type===Rn.ACCEPT?this.savePendingMessage(e):this.saveAcceptedMessage(e),this.userOffsets.updateOffset(e.senderId,e.timestamp),this.increaseUnreadAmount(e),Ds.fire(Nn.MAX_MESSAGE_CHANGED,e))}increaseUnreadAmount(e){if(e.sendByCustomer()||e.type===Rn.TRANSFER&&e.senderId!==js.u()){this.userOffsets.myOffset()<e.timestamp&&e.accepted&&(this.unread+=1)}}markRead(){return t(this,void 0,void 0,(function*(){let e=this.maxAcceptedMessageTime();si.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(js.u(),e),Ds.fire(Nn.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 ii extends Kn{constructor(e){super(e)}deleteMessages(e){return t(this,void 0,void 0,(function*(){sn.onFailed(e,"Delete CS message is not supported yet")}))}recallMessage(e){return t(this,void 0,void 0,(function*(){sn.onFailed(e,"Recall CS message is not supported yet")}))}}class oi{static init(){return oi.instance||(oi.instance=new oi),oi.instance.map=new Map,oi.instance}initialListeners(){Ds.on(Nn.MESSAGE_SENDING,(e=>this.onMessageSending(e))),Ds.on(Nn.MESSAGE_SEND_SUCCESS,(e=>this.onMessageSendSuccess(e))),Ds.on(Nn.MESSAGE_SEND_FAILED,(e=>this.onMessageSendFailed(e))),Ds.on(Nn.MESSAGE_RECEIVED,(e=>this.onMessageReceived(e))),Ds.on(Nn.CS_AGENT_MESSAGE_RECEIVED,(e=>this.onMessageReceived(e))),Ds.on(Nn.CS_ACCEPTED,(e=>this.onMessageReceived(e))),Ds.on(Nn.CS_ENDED,(e=>this.onMessageReceived(e))),Ds.on(Nn.CS_TRANSFER,(e=>this.onMessageReceived(e))),js.s().addMessageObserver(Js.IM_MSG_READ,this.onRemoteMarkRead.bind(this)),js.s().addMessageObserver(Js.IM_MSG_DELETED,this.onRemoteMessageDeleted.bind(this)),js.s().addMessageObserver(Js.IM_MSG_RECALLED,this.onRemoteMessageRecalled.bind(this)),js.s().addDisconnectedObserver(this.onDisconnected.bind(this))}loadHistory(e,s){return t(this,void 0,void 0,(function*(){let t=this.queryToTarget(e,s),n=this.findOrCreateHistory(t),i=yield n.loadHistory(e.lastTimestamp,e.limit);sn.onSuccess(e,{code:200,content:i})}))}queryToTarget(e,t){if(es.isDef(e.userId))return new Dn(co.PRIVATE,e.userId);if(es.isDef(e.groupId))return new Dn(co.GROUP,e.groupId);if(es.isDef(e.type)){if(!Object.values(co).includes(e.type))throw new Error("incorrect type, must be: "+Object.values(co));if(es.isUndef(e.id))throw new Error("If type is not empty, id is required.");return co.CS==e.type&&es.isUndef(t)&&(t=e.id),new Dn(e.type,e.id,t)}throw new Error("incorrect query options.")}onMessageSending(e){let t=Dn.byIMMessage(e);this.findOrCreateHistory(t).onMessageSending(e)}onMessageSendSuccess(e){let t=Dn.byIMMessage(e);this.findHistory(t).onMessageSendSuccess(e)}onMessageSendFailed(e){let t=Dn.byIMMessage(e);this.findHistory(t).onMessageSendFailed(e)}onMessageReceived(e){let t=Dn.byIMMessage(e);this.findOrCreateHistory(t).onMessageReceived(e)}privateMarkAsRead(e){return t(this,void 0,void 0,(function*(){if(es.isUndef(e.userId))throw new Error("userId could not be empty.");let t=Dn.byScene(co.PRIVATE,e.userId);yield this.markAsRead(t,e)}))}groupMarkAsRead(e){return t(this,void 0,void 0,(function*(){if(es.isUndef(e.groupId))throw new Error("groupId could not be empty.");let t=Dn.byScene(co.GROUP,e.groupId);yield this.markAsRead(t,e)}))}markMessageAsRead(e,s){return t(this,void 0,void 0,(function*(){if(es.isUndef(e.id))throw new Error("id could not be empty.");if(!Object.values(co).includes(e.type))throw new Error("incorrect type, must be: "+Object.values(co));co.CS==e.type&&es.isUndef(s)&&(s=e.id);let t=Dn.byScene(e.type,e.id,s);yield this.markAsRead(t,e)}))}markAsRead(e,s){return t(this,void 0,void 0,(function*(){let t=this.findHistory(e);t&&(yield t.markRead()),sn.onSuccess(s)}))}onRemoteMarkRead(e){let t=Dn.byMessageReadRemoteEvent(e),s=this.findHistory(t);s&&s.syncMarkedMessage(e)}deleteMessage(e){return t(this,void 0,void 0,(function*(){this.validateMessageArray(e.messages),Fn.validate(e);let t=e.messages[0],s=Dn.byIMMessage(t),n=this.findHistory(s);if(!n)throw{code:400,content:"No message that could be deleted"};yield n.deleteMessages(e)}))}onRemoteMessageDeleted(e){let t=Dn.byIMMessageDeletedEvent(e),s=this.findHistory(t);s&&s.syncDeletedMessage(e.deleterId,e.times)}recallMessage(e){return t(this,void 0,void 0,(function*(){this.validateMessageArray(e.messages),Ln.validate(e);let t=e.messages[0],s=Dn.byIMMessage(t),n=this.findHistory(s);if(!n)throw{code:400,content:"No message that could be recalled"};yield n.recallMessage(e)}))}onRemoteMessageRecalled(e){let t=Dn.byRemoteRecallEvent(e),s=this.findHistory(t);s&&s.syncRecalledMessage(e.times)}onDisconnected(){this.map.forEach(((e,t)=>{e.expire()}))}findOrCreateHistory(e){let t=this.findHistory(e);return t||(t=e.scene===co.CS?js.u()===e.customerId()?new ii(e):new ni(e):new Kn(e),this.map.set(e.toString(),t),t)}static get(e){return oi.instance.findOrCreateHistory(e)}findHistory(e){return this.map.get(e.toString())}validateMessageArray(e){if(!es.isArray(e)||es.isEmpty(e))throw{code:400,content:"messages requires non empty array"};if(e.length>50)throw{code:400,content:"The maximum number of messages is 50"};let t=Dn.byIMMessage(e[0]);for(let s=0;s<e.length;s++){let n=e[s];if(!(n instanceof On))throw{code:400,content:"message["+s+"] is not a correct message"};if(s>0){let e=Dn.byIMMessage(n);if(e.scene!==t.scene||e.id!==t.id)throw{code:400,content:"each message must be from the same friend or group"}}}}}class ri{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 lo;return e===co.PRIVATE?s.userId=t:e===co.GROUP?s.groupId=t:e===co.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 oi.get(this.target).getMaxMessage()}getUnreadAmount(){return oi.get(this.target).unreadAmount()}maxMessageTime(){return oi.get(this.target).maxTime()}}class ai extends ri{constructor(e){super(e),this.accepted=!1}toDto(){let e=new lo,t=this.target.scene,s=this.target.id,n=this.target.teamId;return e.id=s,e.teamId=n,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===Rn.END||t===Rn.TRANSFER&&s.transferTo.id!==js.u()}getMaxMessage(){return oi.get(this.target).getMaxMessage(this.accepted)}getUnreadAmount(){return oi.get(this.target).unreadAmount(this.accepted)}maxMessageTime(){return oi.get(this.target).maxTime(this.accepted)}}class ci{constructor(e,t,s,n){this.type=e,this.top=t,this.targetId=s,this.teamId=n}}class ui{constructor(e,t,s){this.type=e,this.targetId=t,this.teamId=s}}class li{constructor(e,t,s){this.type=e,this.targetId=t,this.teamId=s}}class di{top(e,t){let s=new ci(e.scene,t,e.id,e.teamId);return new Promise(((e,t)=>{let n=new As({name:Os.topConversation,params:s,permission:Jt.WRITE,singleTimeout:Rs.commonRequestSingle,totalTimeout:Rs.commonRequestTotal,success:s=>{200===s.code?e(s):t(s)},fail:e=>{t(e)}});js.s().emit(n)}))}remove(e){let t=new ui(e.scene,e.id,e.teamId);return new Promise(((e,s)=>{let n=new As({name:Os.removeConversation,params:t,permission:Jt.WRITE,singleTimeout:Rs.commonRequestSingle,totalTimeout:Rs.commonRequestTotal,success:t=>{200==t.code?e(t):s(t)},fail:e=>{s(e)}});js.s().emit(n)}))}query(e){return new Promise(((s,n)=>{let i=new As({name:e,params:{},permission:Jt.READ,singleTimeout:Rs.commonQuerySingle,totalTimeout:Rs.commonQueryTotal,fail:e=>{n(e)},success:e=>t(this,void 0,void 0,(function*(){s(e)}))});js.s().emit(i)}))}loadData(e){let t=new li(e.scene,e.id,e.teamId);return new Promise(((e,s)=>{let n=new As({name:Os.imData,params:t,permission:Jt.READ,singleTimeout:Rs.commonQuerySingle,totalTimeout:Rs.commonQueryTotal,success:t=>{let s=JSON.parse(t.content);e(s)},fail:e=>{s(e)}});js.s().emit(n)}))}}di.instance=new di;class hi{constructor(){this.list=new Array,this.builder=new Hn,this.remoteConversations=di.instance,this.synchronized=!1,Ds.on(Nn.MAX_MESSAGE_CHANGED,(e=>this.onMaxMessageChanged(e))),Ds.on(Nn.UNREAD_AMOUNT_CHANGED,(e=>this.onUnreadMessageChanged(e))),Ds.on(Nn.MAX_MESSAGE_DELETED,(e=>this.onMaxMessageDeleted(e)))}onUnreadMessageChanged(e){this.findConversation(e)&&this.fireUpdated()}fireUpdated(){let e=this.loadLocalConversations(),t=this.getUpdatedEventName();Yi.aec.fire(t,{unreadTotal:e.content.unreadTotal,conversations:e.content.conversations})}getUpdatedEventName(){return Ks.CONVERSATIONS_UPDATED}latestConversations(e){return t(this,void 0,void 0,(function*(){this.synchronized||(yield this.loadServerConversations());let t=this.loadLocalConversations();sn.onSuccess(e,t)}))}loadServerConversations(){return t(this,void 0,void 0,(function*(){let e=this.rocketName(),t=yield this.remoteConversations.query(e);this.convertAbbrConversation(t.content),this.synchronized=!0}))}rocketName(){return Os.imLastConversations}convertAbbrConversation(e){let t=e;for(const e of t){let t=e.t,s=e.top,n=e.d?JSON.parse(e.d):{},i=e.userOffsets;e.lmsg.t=t;let o=e.lmsg,r=this.builder.build(o),a=Dn.byIMMessage(r),c=this.findConversation(a);es.isUndef(c)?(c=this.buildByAbbr(e,r),this.insertOne(c)):(c.top=s,c.data=n),oi.get(a).initMaxMessageAndOffsets(r,i),this.correctPosition(c)}}onMaxMessageDeleted(e){this.removeConversation(e)}onMaxMessageChanged(e){return t(this,void 0,void 0,(function*(){if(e.scene()===co.CS){let t=e;if(js.u()!=t.customerId()&&(!1===t.accepted||t.type===Rn.ACCEPT&&t.senderId!=js.u()))return}yield this.saveOrUpdateConversation(e)}))}saveOrUpdateConversation(e){return t(this,void 0,void 0,(function*(){let t=e.status,s=Dn.byIMMessage(e),n=this.findConversation(s);es.isUndef(n)&&t!==uo.FAIL&&(n=this.buildByMessage(e),this.insertOne(n),t===uo.SUCCESS&&(n.data=yield this.remoteConversations.loadData(s),n.dataLoaded=!0)),t===uo.SENDING&&(n.data=e.getToData(),n.dataLoaded=!0),n&&n.dataLoaded&&(this.correctPosition(n),this.fireUpdated())}))}loadLocalConversations(){let e=0,t=new Array;for(const s of this.list)if(s.dataLoaded&&s.getMaxMessage()){e+=s.getUnreadAmount();let n=s.toDto();t.push(n)}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){hi.sortedInserter.insert(this.list,e),this.list.length>hi.CONVERSATIONS_MAX_LENGTH&&(this.list=this.list.slice(0,hi.CONVERSATIONS_MAX_LENGTH))}correctPosition(e){this.removeLocalConversation(e),this.insertOne(e)}removeConversation(e){let t=this.findConversation(e);t&&(this.removeLocalConversation(t),this.fireUpdated())}top(e,s,n){return t(this,void 0,void 0,(function*(){if(!es.isBoolean(s))throw new Error("top must be boolean.");let t=this.findConversation(e);if(!t)throw new Error("conversation does not exist.");t.top!=s&&(yield this.remoteConversations.top(e,s),t.top=s,this.correctPosition(t)),this.fireUpdated(),sn.onSuccess(n)}))}remove(e,s){return t(this,void 0,void 0,(function*(){let t=this.findConversation(e);if(!t)throw new Error("conversation does not exist.");if(t instanceof ai&&!t.isEnded())throw new Error("CS conversation can only be deleted after it ends");yield this.remoteConversations.remove(e),this.removeLocalConversation(t),this.fireUpdated(),sn.onSuccess(s)}))}buildByAbbr(e,t){let s,n=Dn.byIMMessage(t);if(e.t===co.CS){let e=t;js.u()===e.customerId()?s=new ri(n):(s=new ai(n),s.accepted=e.accepted)}else s=new ri(n);return s.dataLoaded=!0,s.top=e.top,s.data=e.d?JSON.parse(e.d):{},s}buildByMessage(e){let t,s=Dn.byIMMessage(e);if(e.scene()===co.CS){let n=e;js.u()===n.customerId()?t=new ri(s):(t=new ai(s),t.accepted=n.accepted)}else t=new ri(s);return t}}hi.CONVERSATIONS_MAX_LENGTH=200,hi.sortedInserter=new class extends Pn{compare(e,t){let s;if(e.top==t.top){let n=e.maxMessageTime();s=t.maxMessageTime()-n}else s=e.top?-1:1;return 0===s?0:s>0?1:-1}};class pi extends hi{constructor(){super(),this.expired=!1,Ds.on(Nn.CS_ONLINE_SUCCESS,(()=>this.onCSOnlineSuccess())),Ds.on(Nn.CS_OFFLINE_SUCCESS,(()=>this.onCSOfflineSuccess())),js.s().addDisconnectedObserver(this.onDisconnected.bind(this)),js.s().addConnectedObserver(this.onConnected.bind(this))}onMaxMessageChanged(e){return t(this,void 0,void 0,(function*(){if(e.scene()===co.CS){let t=e;if(t.customerId()!=js.u()&&(!1===t.accepted||t.type===Rn.ACCEPT))if(Rn.ACCEPT===e.type){let t=Dn.byIMMessage(e);this.removeConversation(t)}else yield this.saveOrUpdateConversation(e)}}))}latestConversations(e){const s=Object.create(null,{latestConversations:{get:()=>super.latestConversations}});return t(this,void 0,void 0,(function*(){let t=this.synchronized;yield s.latestConversations.call(this,e),this.list.length>0&&!t&&this.fireUpdated()}))}onUnreadMessageChanged(e){}onCSOnlineSuccess(){return t(this,void 0,void 0,(function*(){yield this.loadServerConversations(),this.fireUpdated()}))}onCSOfflineSuccess(){this.list=[],this.fireUpdated()}getUpdatedEventName(){return Ks.PENDING_CONVERSATIONS_UPDATED}rocketName(){return Os.CS_PENDING_CONVERSATION}convertAbbrConversation(e){return t(this,void 0,void 0,(function*(){let t=e;for(const e of t){e.lastMessage.t=co.CS;let t=e.customerData,s=e.lastMessage,n=e.userOffsets,i=t?JSON.parse(t):{},o=this.builder.build(s),r=Dn.byIMMessage(o),a=this.findConversation(r);es.isUndef(a)&&(a=new ai(r),a.accepted=o.accepted,a.dataLoaded=!0,this.insertOne(a)),a.top=!1,a.data=i,oi.get(r).initPendingMaxMessageAndOffsets(o,n),this.correctPosition(a)}}))}onDisconnected(){this.expired=!0}onConnected(){return t(this,void 0,void 0,(function*(){let e=js.supportIM();this.expired&&e&&(this.expired=!1,this.list=[],yield this.loadServerConversations(),this.fireUpdated())}))}}class mi{constructor(){this.conversations=new hi,this.pendingConversations=new pi}latestConversations(e){this.conversations.latestConversations(e)}latestPendingConversations(e){this.pendingConversations.latestConversations(e)}topPrivateConversation(e){let t=Dn.byScene(co.PRIVATE,e.userId);this.conversations.top(t,e.top,e)}topGroupConversation(e){let t=Dn.byScene(co.GROUP,e.groupId);this.conversations.top(t,e.top,e)}topConversation(e){let t=e.conversation;this.validateConversationDTO(t);let s=Dn.byConversationDTO(t);this.conversations.top(s,e.top,e)}removePrivateConversation(e){let t=Dn.byScene(co.PRIVATE,e.userId);this.conversations.remove(t,e)}removeGroupConversation(e){let t=Dn.byScene(co.GROUP,e.groupId);this.conversations.remove(t,e)}removeConversation(e){let t=e.conversation;this.validateConversationDTO(t);let s=Dn.byConversationDTO(t);this.conversations.remove(s,e)}validateConversationDTO(e){if(!(e instanceof lo))throw new Error("Incorrect conversation object.");{let t=e.lastMessage;if(t instanceof Vn&&t.customerId()!==js.u()&&!1===t.accepted)throw new Error("pending conversation cannot be topped or removed.")}}}class fi{constructor(){this.builder=new Hn,_s.instance.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===co.GROUP&&(t.groupId=e.gid),t}support(e){return!!e.sid}})}initialGoEasySocket(){js.s().addMessageObserver(Js.imMessage,this.onMessageReceived.bind(this))}onMessageReceived(e){if(e.t!==co.CS){let t=this.builder.build(e);this.sendAck(t);let s=Dn.byIMMessage(t),n=s.scene;oi.get(s).existsMessage(t)||(this.createNotification(e),Ds.fire(Nn.MESSAGE_RECEIVED,t),n===co.PRIVATE?Yi.aec.fire(Ks.PRIVATE_MESSAGE_RECEIVED,t):n===co.GROUP&&Yi.aec.fire(Ks.GROUP_MESSAGE_RECEIVED,t))}}sendAck(e){js.s().sendAck("imAck",{publishGuid:e.messageId})}createNotification(e){const t=_s.instance.supportNotification();if(!es.isObject(e.nt)||e.s===js.u()||!t)return;let s={id:e.i,tm:e.ts,t:e.mt,sid:e.s,tt:e.t};s.tt===co.GROUP&&(s.gid=e.r),_s.instance.createLocalNotification(e.nt.t,e.nt.c,s)}}class gi{subscribe(e){Hs.validateIdArray(e.groupIds,"groupIds"),e.groupIds=e.groupIds.toString().split(",");let t=new As({name:Os.subscribeGroups,params:{groupIds:e.groupIds,at:e.accessToken},permission:Jt.WRITE,singleTimeout:Rs.commonRequestSingle,totalTimeout:Rs.commonRequestTotal,success:function(){sn.onSuccess(e,{code:200,content:"ok"})},fail:function(t){sn.onFailed(e,{code:t.resultCode||408,content:t.content||"Failed to subscribe group message"})}});js.s().emit(t)}unsubscribe(e){Hs.validateId(e.groupId,"groupId"),e.groupId=e.groupId.toString();let t=new As({name:Os.unsubscribeGroup,params:{groupId:e.groupId},permission:Jt.READ,singleTimeout:Rs.commonRequestSingle,totalTimeout:Rs.commonRequestTotal,success:()=>{sn.onSuccess(e,{code:200,content:"ok"})},fail:t=>{sn.onFailed(e,{code:t.resultCode||408,content:t.content||"Failed to unsubscribe group message"})}});js.s().emit(t)}}class yi{constructor(){js.s().addMessageObserver(Js.groupPresence,this.newMessageReceived.bind(this))}presence(e){Hs.validateIdArray(e.groupIds,"groupIds"),e.groupIds.toString().split(",");let t={groupIds:e.groupIds};this.emitRocket(Os.subscribeGroupPresence,t,(()=>{sn.onSuccess(e,{code:200,content:"ok"})}),(t=>{sn.onFailed(e,{code:t.code||408,content:t.content||"Failed to subscribe group message"})}),Rs.commonRequestSingle,Rs.commonRequestTotal)}unPresence(e){Hs.validateId(e.groupId,"groupId"),e.groupId=e.groupId.toString();let t={groupId:e.groupId};this.emitRocket(Os.unsubscribeGroupPresence,t,(()=>{sn.onSuccess(e,{code:200,content:"ok"})}),(t=>{sn.onFailed(e,{code:t.code||408,content:t.content||"Failed to unsubscribe presence"})}),Rs.commonRequestSingle,Rs.commonRequestTotal)}emitRocket(e,t,s,n,i,o){let r=new As({name:e,params:t,singleTimeout:i,totalTimeout:o,permission:Jt.WRITE,success:s,fail:n});js.s().emit(r)}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):{},n={time:e.time,action:e.action,groupOnlineCount:t.userAmount,groupId:t.groupId,id:e.userId,data:s};Yi.aec.fire(Ks.GROUP_PRESENCE,n)}))}}class vi{get(e){Hs.validateId(e.groupId,"groupId"),e.groupId=e.groupId.toString();let t=new As({name:Os.imGroupOnlineCount,params:{groupId:e.groupId},permission:Jt.READ,singleTimeout:Rs.commonQuerySingle,totalTimeout:Rs.commonQueryTotal,fail:function(t){sn.onFailed(e,t||{code:408,content:"Failed to query online group users"})},success:function(t){200==t.code?sn.onSuccess(e,t):sn.onFailed(e,t)}});js.s().emit(t)}}class Ei{doHereNow(e,t,s){let n=new As({name:e,params:t,permission:Jt.READ,singleTimeout:Rs.commonQuerySingle,totalTimeout:Rs.commonQueryTotal,fail:e=>{sn.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}})),sn.onSuccess(s,e)}});js.s().emit(n)}}class Ci extends Ei{hereNow(e){Hs.validateId(e.groupId,"groupId"),e.groupId=e.groupId.toString();let t={groupId:e.groupId};this.doHereNow(Os.imGroupHereNow,t,e)}}class Si{constructor(){js.s().addMessageObserver(Js.userPresence,this.newMessageReceived.bind(this))}presence(e){Hs.validateIdArray(e.userIds,"userIds"),e.userIds.toString().split(",");let t={userIds:e.userIds};this.emitRocket(Os.subscribeUserPresence,t,(()=>{sn.onSuccess(e,{code:200,content:"ok"})}),(t=>{sn.onFailed(e,{code:t.code||408,content:t.content||"Failed to subscribe group message"})}),Rs.commonRequestSingle,Rs.commonRequestTotal)}unPresence(e){Hs.validateId(e.userId,"userId"),e.userId=e.userId.toString();let t={userId:e.userId};this.emitRocket(Os.unsubscribeUserPresence,t,(()=>{sn.onSuccess(e,{code:200,content:"ok"})}),(t=>{sn.onFailed(e,{code:t.code||408,content:t.content||"Failed to unsubscribe presence"})}),Rs.commonRequestSingle,Rs.commonRequestTotal)}emitRocket(e,t,s,n,i,o){let r=new As({name:e,params:t,singleTimeout:i,totalTimeout:o,permission:Jt.WRITE,success:s,fail:n});js.s().emit(r)}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};Yi.aec.fire(Ks.USER_PRESENCE,s)}))}}class bi extends Ei{hereNow(e){let t=e.userIds;Hs.validateIdArray(t,"userIds"),t.toString().split(","),this.doHereNow(Os.imHereNow,e,e)}}const wi=new class{fileExtension(e,t){if(es.isString(e))try{let s=e.split(t);return s[s.length-1]}catch(e){throw Error(e)}}};class Ii{}class Mi extends Ii{constructor(){super(...arguments),this.contentType="",this.name="",this.size=0,this.url=""}}class Ai extends Mi{constructor(){super(...arguments),this.width=0,this.height=0}}class Ti{build(e){this.validate(e.createOptions);let t=this.create();return this.setPayload(e,t),t}}class Ni extends Ti{create(){return new Mi}setPayload(e,t){let s=t,n=e.createOptions.file;s.url=n.path,s.name=n.name,s.size=n.size,s.contentType=n.type,e.complete=Promise.resolve()}validate(e){if(!es.isObject(e))throw Error("it is an empty message.");if(!es.isDef(e.file))throw Error("file is empty.")}}class Ri extends Ni{create(){return new Ai}setPayload(e,t){super.setPayload(e,t);let s=e.createOptions.file,n=t,i=s.path||s.tempFilePath,o=es.isEmpty(s.name)||void 0===s.name?i:s.name;n.name="wx-image."+wi.fileExtension(o,"."),n.contentType="image/"+wi.fileExtension(o,"."),n.url=i,n.size=s.size,e.complete=new Promise(((e,t)=>{wx.getImageInfo({src:n.url,success(t){n.width=t.width,n.height=t.height,e()},fail(e){t(e)}})}))}validate(e){super.validate(e)}}class Oi extends Mi{constructor(){super(...arguments),this.duration=0}}class _i extends Ni{create(){return new Oi}setPayload(e,t){super.setPayload(e,t);let s=e.createOptions.file,n=t,i=s.tempFilePath,o=es.isEmpty(s.name)||null==s.name?i:s.name,r=s.duration,a=s.fileSize;n.url=i,n.size=a,n.duration=r/1e3,n.name="wx-audio."+wi.fileExtension(o,"."),n.contentType="audio/"+wi.fileExtension(o,"."),e.complete=Promise.resolve()}validate(e){super.validate(e)}}class Pi extends Ii{constructor(){super(...arguments),this.text=""}}class ki extends Ti{create(){return new Pi}setPayload(e,t){let s=t,n=e.createOptions;s.text=n.text,e.complete=Promise.resolve()}validate(e){if(es.isEmpty(e.text))throw{code:400,content:"text is empty"};if(!es.isString(e.text))throw{code:400,content:"TypeError: text requires string."};if(""===e.text.trim())throw{code:400,content:"text is empty"};if(e.text.length>2500)throw{code:400,content:"Message text over max length 2500"}}}class Di extends Ii{constructor(){super(...arguments),this.video=new Fi,this.thumbnail=new xi}}class xi{constructor(){this.name="",this.url="",this.width=0,this.height=0,this.contentType=""}initURL(e){let t=It.currentPlatform();[Et.APP_IOS,Et.APP_ANDROID].includes(t)?this.appUrl(e):[Et.APPLET_WX,Et.APPLET_WX_GAME].includes(t)?this.wxUrl(e):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")}wxUrl(e){}appUrl(e){}}class Fi{constructor(){this.name="",this.url="",this.width=0,this.height=0,this.contentType="",this.size=0,this.duration=0}}class Ui extends Ti{create(){return new Di}setPayload(e,t){let s=e.createOptions.file,n=t,i=n.video,o=n.thumbnail,{duration:r,height:a,size:c,tempFilePath:u,thumbTempFilePath:l,width:d,name:h=""}=s,p=es.isEmpty(h)?u:h;i.contentType="video/"+wi.fileExtension(p,"."),i.name="wx-video."+wi.fileExtension(p,"."),i.url=u,i.width=o.width=d,i.height=o.height=a,i.size=c,i.duration=r,o.url=l,o.contentType="image/jpg",o.name="wx-thumbnail.jpg",e.complete=Promise.resolve()}validate(e){if(!es.isObject(e))throw Error("it is an empty message.");if(!es.isDef(e.file))throw Error("file is empty.")}}class Li extends Ti{create(){return new Mi}setPayload(e,t){let s=t,n=e.createOptions.file;s.url=n.fullPath,s.name=n.name,s.size=n.size,s.contentType=n.type,n.type,e.complete=Promise.resolve()}validate(e){if(!es.isObject(e))throw Error("it is an empty message.");if(!es.isDef(e.file))throw Error("file is empty.")}}class Gi extends Li{create(){return new Ai}setPayload(e,t){let s=t,n=e.createOptions.file;s.url=n.path,s.size=n.size;let i=es.isEmpty(n.name)||void 0===n.name?n.path:n.name;s.contentType="image/"+wi.fileExtension(i,"."),s.name="uni-image."+wi.fileExtension(i,"."),e.complete=new Promise(((e,t)=>{uni.getImageInfo({src:n.path,success(t){s.width=t.width,s.height=t.height,e()},fail(e){t(e)}})}))}validate(e){super.validate(e)}}class qi extends Li{create(){return new Oi}setPayload(e,t){let s=e.createOptions,n=t,i=s.file,o=i.tempFilePath,r=es.isEmpty(i.name)||null==i.name?o:i.name;n.url=o,n.name="uni-audio."+wi.fileExtension(r,"."),n.contentType="audio/"+wi.fileExtension(r,"."),e.complete=new Promise(((e,t)=>{uni.getFileInfo({filePath:o,success:i=>{let r=i.size;if(n.size=r,0===r)e();else if(es.isDef(s.file.duration))n.duration=s.file.duration/1e3,e();else{const s=uni.createInnerAudioContext();s.src=o,s.onCanplay((function(i){i.errCode?(s.destroy(),t(i)):(n.duration=s.duration,s.destroy(),e())})),s.onError((n=>{s.destroy(),-99===n.errCode?e():t(n)}))}},fail(e){t(e)}})}))}validate(e){super.validate(e)}}class Bi extends Ti{create(){return new Di}setPayload(e,t){let s=e.createOptions.file,n=t,i=n.video,o=n.thumbnail,{duration:r,height:a,size:c,tempFilePath:u,width:l,name:d=""}=s,h=es.isEmpty(d)?u:d;i.size=c,i.width=l,i.height=a,i.url=u,i.duration=r,i.contentType="video/"+wi.fileExtension(h,"."),i.name="uni-video."+wi.fileExtension(h,"."),o.url=u,o.height=200,o.width=Number((i.width*o.height/i.height).toFixed(0)),o.contentType="image/jpg",o.name="uni-thumbnail.jpg",e.complete=Promise.resolve()}validate(e){if(!es.isObject(e))throw Error("it is an empty message.");if(!es.isDef(e.file))throw Error("file is empty.")}}class ji extends Ti{create(){return new Mi}setPayload(e,t){let s=t,n=e.createOptions.file,i=window.URL||window.webkitURL;s.url=i.createObjectURL(n),s.name=n.name,s.size=n.size,s.contentType=n.type,e.complete=Promise.resolve()}validate(e){if(!es.isObject(e))throw Error("it is an empty message.");if(!(e.file instanceof File))throw Error("wrong file type.");if(0==e.file.size)throw Error("File size is 0.");if(e.file.size>524288e3)throw Error("message-length limit 30mib")}}class Vi extends ji{create(){return new Ai}setPayload(e,t){super.setPayload(e,t);let s=e.createOptions.file,n=t,i=window.URL||window.webkitURL,o=new Image;o.src=i.createObjectURL(s),e.complete=new Promise(((e,t)=>{o.onload=function(){n.width=o.width,n.height=o.height,i.revokeObjectURL(o.src),e()},o.onerror=function(e){i.revokeObjectURL(o.src),t(e)}}))}validate(e){super.validate(e);let t=["gif","jpg","png","jpeg"];if(!t.find((t=>t===e.file.type.split("/")[1].toLowerCase())))throw Error("Only "+t.join(",")+" is supported image.")}}class Hi extends ji{create(){return new Oi}setPayload(e,t){super.setPayload(e,t);let s=e.createOptions.file,n=t,i=window.URL||window.webkitURL,o=document.createElement("audio");o.src=i.createObjectURL(s),e.complete=new Promise(((e,t)=>{o.onloadedmetadata=()=>{n.duration=o.duration,i.revokeObjectURL(o.src),e()},o.onerror=e=>{i.revokeObjectURL(o.src),t(e)}}))}validate(e){super.validate(e);let t=["mp3","ogg","wav","wma","ape","acc","mpeg"];if(!t.find((t=>t===e.file.type.split("/")[1].toLowerCase())))throw Error("Only "+t.join(",")+" is supported audio.")}}class Wi extends Ti{create(){return new Di}setPayload(e,t){let s=e.createOptions.file,n=t,i=n.video,o=n.thumbnail,r=window.URL||window.webkitURL,a=document.createElement("video");a.src=r.createObjectURL(s),i.size=s.size,i.name=s.name,i.contentType=s.type,i.url=a.src,o.name=s.name,o.contentType="image/jpg",e.complete=new Promise(((e,t)=>{a.onloadedmetadata=()=>{i.duration=a.duration,i.width=a.videoWidth,i.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")}validate(e){if(!es.isObject(e))throw Error("it is an empty message.");if(!(e.file instanceof File))throw Error("wrong file type.");if(0==e.file.size)throw Error("File size is 0.");if(e.file.size>31457280)throw Error("message-length limit 30mib");let t=["avi","mov","rmvb","rm","flv","mp4","3gp","quicktime"];if(!t.find((t=>t===e.file.type.split("/")[1].toLowerCase())))throw Error("Only "+t.join(",")+" is supported video.")}}class zi extends Ii{}class Xi extends Ti{create(){return new zi}setPayload(e,t){let s=e.createOptions;t.payload=s.payload,e.complete=Promise.resolve()}validate(e){let t=e.type,s=e.payload;if(es.isEmpty(t))throw Error("type is empty.");if(!es.isString(t))throw Error("type require a string");if(es.isEmpty(s))throw Error("payload is empty.");if(!es.isPlainObject(s)&&!es.isStringOrNumber(s))throw Error("payload require object | string | number.")}}class Ji{constructor(e,t){this.type=e,this.createOptions=t}}class Ki{constructor(){this.framework=Mt.currentFramework();const e=It.currentPlatform()===Et.APPLET_WX;this.payloadBuilders={[Ct.UNIAPP]:{image:new Gi,file:new Li,audio:new qi,video:new Bi,text:new ki},[Ct.NATIVE_APPLET_WX]:{image:new Ri,file:new Ni,audio:new _i,video:new Ui,text:new ki},[Ct.UNKNOWN]:{image:new Vi,file:new ji,audio:new Hi,video:new Wi,text:new ki},[Ct.TARO]:{image:e?new Ri:new Vi,file:e?new Ni:new ji,audio:e?new _i:new Hi,video:e?new Ui:new Wi,text:new ki}}}buildMessage(e,t){let s=this.payloadBuilders[this.framework][e],n=new Ji(e,t);if(s){let e=s.build(n);n.payload=e}else{let e=(new Xi).build(n);n.payload=e.payload}let i=this.build(n);return n.complete.then((()=>{sn.onSuccess(t,i)})).catch((e=>{sn.onFailed(t,e)})),i}build(e){let t,s=e.type,n=e.payload,i=e.createOptions,o=i.to,r=o.type;return this.validate(i),r===co.GROUP?(t=new jn,t.groupId=o.id.toString(),t.senderData=js.ud()):r===co.PRIVATE?(t=new Bn,t.read=!1,t.receiverId=o.id.toString()):r===co.CS&&(t=new Vn,t.to=o.id.toString(),t.teamId=o.id.toString(),t.senderData=js.ud()),t.senderId=js.u(),t.messageId=Ms.get(),t.payload=n,t.timestamp=Date.now(),t.type=s,t.recalled=!1,t.status=uo.NEW,t.buildOptions=e,t}validate(e){const t=e.to;if(!t)throw new Error("message require property to.");if(!es.isObject(t))throw new Error("TypeError: to requires an object.");if(!es.isObject(t.data))throw new Error("TypeError: to.data requires an object.");if(!t.type||t.type!==co.GROUP&&t.type!==co.PRIVATE&&t.type!==co.CS)throw new Error("message require property to.type");if(es.isEmpty(t.id))throw new Error("message require property to.id");if(!es.isStringOrNumber(t.id))throw new Error("to.id should be a string or number.");if(js.u()===t.id)throw new Error("to.id can not be the same as your id.");es.isDef(e.notification)&&Hs.validateNotification(e.notification),e.wxmpTemplateMsg&&Hs.validateWXMPTemplateMsg(e.wxmpTemplateMsg)}}class Qi extends fi{onMessageReceived(e){if(e.t===co.CS){let t=this.builder.build(e);this.sendAck(t);let s=Dn.byIMMessage(t);if(!oi.get(s).existsMessage(t)){if(t.customerId()===js.u())this.createNotification(e),Ds.fire(Nn.MESSAGE_RECEIVED,t),Yi.aec.fire(Ks.CS_MESSAGE_RECEIVED,t);else{ti.getInstance().queryTeams().then((()=>{si.isMyMessage(t)&&this.createNotification(e),Ds.fire(Nn.CS_AGENT_MESSAGE_RECEIVED,t)}))}}}}}class Yi{constructor(e){this._iMReceiver=new fi,this.csMessageReceiver=new Qi,this.options=e,Yi.aec=new rn,this._userHereNow=new bi,this.goEasyUploader=new bn,this._groupHereNow=new Ci,this._groupOnlineCount=new vi,this.groupMessageSubscriber=new gi}static init(e){Yi.instance=new Yi(e)}afterConnect(){this._iMReceiver.initialGoEasySocket(),this.csMessageReceiver.initialGoEasySocket(),this.messageBuilder=new Ki,this.messageSender=new _n,this.histories=oi.init(),this.histories.initialListeners(),this.conversations=new mi,this._groupPresenceSubscriber=new yi,this._userPresenceSubscriber=new Si}validateModules(){if(es.isUndef(js.s()))throw Error("Please call connect() first.");if(!this.options.modules||!this.options.modules.includes(qs))throw Error(`Invalid options: module '${qs}' is not enabled`)}catch(e,s){return t(this,void 0,void 0,(function*(){try{this.validateModules(),Hs.validateCallbackOptions(s),yield e()}catch(e){sn.onFailed(s,e)}}))}on(e,t){Yi.aec.on(e,t)}off(e,t){Yi.aec.off(e,t)}createTextMessage(e){return this.validateModules(),this.messageBuilder.buildMessage(pn.TEXT,e)}createImageMessage(e){return this.validateModules(),this.messageBuilder.buildMessage(pn.IMAGE,e)}createFileMessage(e){return this.validateModules(),this.messageBuilder.buildMessage(pn.FILE,e)}createAudioMessage(e){return this.validateModules(),this.messageBuilder.buildMessage(pn.AUDIO,e)}createVideoMessage(e){return this.validateModules(),this.messageBuilder.buildMessage(pn.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.histories.recallMessage(e)}),e)}deleteMessage(e){this.catch((()=>{this.histories.deleteMessage(e)}),e)}markGroupMessageAsRead(e){this.catch((()=>t(this,void 0,void 0,(function*(){yield this.histories.groupMarkAsRead(e)}))),e)}markPrivateMessageAsRead(e){this.catch((()=>t(this,void 0,void 0,(function*(){yield this.histories.privateMarkAsRead(e)}))),e)}markMessageAsRead(e,s){this.catch((()=>t(this,void 0,void 0,(function*(){yield this.histories.markMessageAsRead(e,s)}))),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)}}var $i;!function(e){e.VIDEO="VIDEO",e.VOICE="VOICE"}($i||($i={}));class Zi{constructor(e,t){this.customerId=e,this.teamId=t}}class eo{constructor(e,t){this.teamId=e;let s=new po(t.id.toString(),JSON.stringify(t.data));this.customer=s}}class to{constructor(e,t,s){this.customerId=e,this.teamId=t,this.agentId=s}}class so{constructor(e,t){this.customerId=e,this.teamId=t}}class no{constructor(e){this.builder=new Hn,this.teamId=e}accept(e,t){let s=t.customer;if(es.isUndef(s))throw{code:400,content:"customer is required."};Hs.validateId(s.id,"customer.id");let n=s.data;if(es.isUndef(n)||!es.isObject(n))throw{code:400,content:"customer data must be non-empty object."};let i=new eo(e,s),o=new As({name:Os.CS_ACCEPT,params:i,permission:Jt.WRITE,singleTimeout:Rs.commonRequestSingle,totalTimeout:Rs.commonRequestTotal,fail:e=>{sn.onFailed(t,e)},success:e=>{let s=this.builder.build(e.content.message);Ds.fire(Nn.CS_ACCEPTED,s),sn.onSuccess(t)}});js.s().emit(o)}end(e,t){Hs.validateId(t.id,"id");let s=t.id.toString(),n=new so(s,e),i=new As({name:Os.CS_END,params:n,permission:Jt.WRITE,singleTimeout:Rs.commonRequestSingle,totalTimeout:Rs.commonRequestTotal,fail:e=>{sn.onFailed(t,e)},success:e=>{let s=this.builder.build(e.content.message);Ds.fire(Nn.CS_ENDED,s),sn.onSuccess(t)}});js.s().emit(i)}queryCustomerStatus(e,s){return t(this,void 0,void 0,(function*(){Hs.validateId(s.id,"id");let t=yield this.doCustomerStatus(e,s.id);this.activeCustomerStatus=t,this.activeCustomerStatusOptions=s,sn.onSuccess(s,t)}))}doCustomerStatus(e,t){let s=t.toString(),n=new Zi(s,e);return new Promise(((e,t)=>{let s=new As({name:Os.CS_CUSTOMER_STATUS,params:n,permission:Jt.READ,singleTimeout:Rs.commonQuerySingle,totalTimeout:Rs.commonQueryTotal,fail:e=>{t(e)},success:t=>{let s=t.content;s.agent&&(s.agent.data=JSON.parse(s.agent.data)),e(s)}});js.s().emit(s)}))}transfer(e,t){Hs.validateId(t.customerId,"customerId"),Hs.validateId(t.agentId,"agentId");let s=t.customerId.toString(),n=t.agentId.toString(),i=new to(s,e,n),o=new As({name:Os.CS_TRANSFER,params:i,permission:Jt.WRITE,singleTimeout:Rs.commonRequestSingle,totalTimeout:Rs.commonRequestTotal,fail:e=>{sn.onFailed(t,e)},success:e=>{let s=this.builder.build(e.content.message);Ds.fire(Nn.CS_TRANSFER,s),sn.onSuccess(t)}});js.s().emit(o)}}class io{static getInstance(){return io.instance||(io.instance=new io),io.instance}createTextMessage(e,t){let s=Yi.instance.createTextMessage(t);this.extendProps(e,s)}createImageMessage(e,t){let s=Yi.instance.createImageMessage(t);this.extendProps(e,s)}createFileMessage(e,t){let s=Yi.instance.createFileMessage(t);this.extendProps(e,s)}createAudioMessage(e,t){let s=Yi.instance.createAudioMessage(t);this.extendProps(e,s)}createVideoMessage(e,t){let s=Yi.instance.createVideoMessage(t);this.extendProps(e,s)}createCustomMessage(e,t){let s=Yi.instance.createCustomMessage(t);this.extendProps(e,s)}extendProps(e,t){if(t.scene()===co.CS){let s=t;s.teamId=e,s.accepted=!0}}}class oo{constructor(e){this.teamId=e,this.agentStatus=ti.getInstance(),this.conversationHandler=new no(e),this.messageCreator=io.getInstance()}catch(e,s){return t(this,void 0,void 0,(function*(){try{Hs.validateCallbackOptions(s),yield e()}catch(e){sn.onFailed(s,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){Yi.instance.history(e,this.teamId)}markMessageAsRead(e){Yi.instance.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((()=>{si.live(this.teamId,e)}),e)}quitLiveSession(e){this.catch((()=>{si.quit(e)}),e)}listenCustomer(e){let t={customerId:e.id,onNewMessage:e.onNewMessage,onStatusUpdated:e.onStatusUpdated,onFailed:e.onFailed,onSuccess:e.onSuccess};this.catch((()=>{si.live(this.teamId,t)}),e)}cancelListenCustomer(e){this.catch((()=>{si.quit(e)}),e)}}class ro{static team(e){Hs.validateId(e,"teamId");let t=this.teams.get(e);return t||(t=new oo(e.toString()),this.teams.set(e.toString(),t)),t}}ro.teams=new Map;class ao{}var co,uo;!function(e){e.PRIVATE="private",e.GROUP="group",e.SYSTEM="system",e.CS="cs"}(co||(co={})),function(e){e.NEW="new",e.SENDING="sending",e.SUCCESS="success",e.FAIL="fail"}(uo||(uo={}));class lo{}class ho extends ao{}class po{constructor(e,t){this.id=e,this.data=t}}class mo extends ao{}class fo{constructor(e){nn.init(e)}initialGoEasySocket(){nn.instance.initialGoEasySocket()}initialBeforeConnect(){nn.instance.initialBeforeConnect()}publish(e){nn.instance.publisher.publish(e)}subscribe(e){nn.instance.subscriber.subscribe(e)}unsubscribe(e){nn.instance.subscriber.unsubscribe(e)}subscribePresence(e){nn.instance.presence.subscribePresence(e)}unsubscribePresence(e){nn.instance.presence.unsubscribePresence(e)}history(e){nn.instance.histories.get(e)}hereNow(e){nn.instance.hereNows.byChannel(e)}hereNowByUserIds(e){nn.instance.hereNows.byUserId(e)}}class go{constructor(e){Yi.init(e)}afterConnect(){Yi.instance.afterConnect()}on(e,t){Yi.instance.on(e,t)}off(e,t){Yi.instance.off(e,t)}createTextMessage(e){return Yi.instance.createTextMessage(e)}createImageMessage(e){return Yi.instance.createImageMessage(e)}createFileMessage(e){return Yi.instance.createFileMessage(e)}createAudioMessage(e){return Yi.instance.createAudioMessage(e)}createVideoMessage(e){return Yi.instance.createVideoMessage(e)}createCustomMessage(e){return Yi.instance.createCustomMessage(e)}sendMessage(e){Yi.instance.sendMessage(e)}recallMessage(e){Yi.instance.recallMessage(e)}deleteMessage(e){Yi.instance.deleteMessage(e)}markGroupMessageAsRead(e){Yi.instance.markGroupMessageAsRead(e)}markPrivateMessageAsRead(e){Yi.instance.markPrivateMessageAsRead(e)}latestConversations(e){Yi.instance.latestConversations(e)}removePrivateConversation(e){Yi.instance.removePrivateConversation(e)}removeGroupConversation(e){Yi.instance.removeGroupConversation(e)}topPrivateConversation(e){Yi.instance.topPrivateConversation(e)}topGroupConversation(e){Yi.instance.topGroupConversation(e)}history(e){Yi.instance.history(e)}subscribeUserPresence(e){Yi.instance.subscribeUserPresence(e)}unsubscribeUserPresence(e){Yi.instance.unsubscribeUserPresence(e)}hereNow(e){Yi.instance.hereNow(e)}subscribeGroup(e){Yi.instance.subscribeGroup(e)}unsubscribeGroup(e){Yi.instance.unsubscribeGroup(e)}subscribeGroupPresence(e){Yi.instance.subscribeGroupPresence(e)}unsubscribeGroupPresence(e){Yi.instance.unsubscribeGroupPresence(e)}groupHereNow(e){Yi.instance.groupHereNow(e)}groupOnlineCount(e){Yi.instance.groupOnlineCount(e)}markMessageAsRead(e){Yi.instance.markMessageAsRead(e)}csteam(e){return new vo(e)}pendingConversations(e){Yi.instance.latestPendingConversations(e)}topConversation(e){Yi.instance.topConversation(e)}removeConversation(e){Yi.instance.removeConversation(e)}}class yo{constructor(t){if(es.isDef(yo.instance)&&yo.instance.getConnectionStatus()!==e.DISCONNECTED)return yo.instance;this.validateOptions(t),At.init(t.reactNativeOptions),this.options=t,_s.init(t.allowNotification),this.pubsub=new fo(this.options),this.im=new go(this.options)}static getInstance(e){return es.isUndef(yo.instance)&&(yo.instance=new yo(e)),yo.instance}connect(t){this.getConnectionStatus()!==e.DISCONNECTED&&es.isObject(t)&&es.isFunction(t.onFailed)?t.onFailed({code:408,content:"It is already connected, don't try again until disconnect() is called. "}):(this.confirmUserId(t),Ds.initial(),this.pubsub.initialBeforeConnect(),this.goEasySocket=new Vs(this.options,t),this.goEasySocket.connect(),js.i(this.goEasySocket),this.im.afterConnect(),this.pubsub.initialGoEasySocket())}disconnect(e){this.goEasySocket.disconnect().then((()=>{es.isObject(e)&&es.isFunction(e.onSuccess)&&e.onSuccess()})).catch((t=>{es.isObject(e)&&es.isFunction(e.onFailed)&&e.onFailed(t)}))}getConnectionStatus(){return this.goEasySocket?this.goEasySocket.getStatus():e.DISCONNECTED}validateOptions(e){let t="";if(!es.isObject(e))throw t="options is require an object.",Error(t);if(!es.isPrimitive(e.appkey)||0==e.appkey.length)throw t="Invalid options:'appkey' is empty.",Error(t);if(!es.isPrimitive(e.host)||0==e.host.length)throw t="Invalid options:'host' is empty.",Error(t);if(!es.isArray(e.modules))throw t="Invalid options: 'modules' must be nonempty array",Error(t);const s=[qs,Bs],n=e.modules.map((e=>{const n=e.toUpperCase();if(!s.includes(n))throw t=`Invalid options: module '${e}' is not support`,Error(t);return n}));e.modules=n}onClickNotification(e){_s.instance.onClickNotification(e)}confirmUserId(e){if(this.options.modules.includes(qs)&&(es.isEmpty(e.id)||!es.isStringOrNumber(e.id)))throw{code:400,content:"TypeError: id requires number or string."};if("string"==typeof e.id&&e.id.length>60)throw{code:400,content:"id over max length 60"}}}yo.version="2.6.6",yo.IM_EVENT=Ks,yo.IM_SCENE=co,yo.MEDIA_TYPE=$i;class vo{constructor(e){this.id=e}isOnline(e){ro.team(this.id).isOnline(e)}online(e){ro.team(this.id).online(e)}offline(e){ro.team(this.id).offline(e)}customerStatus(e){ro.team(this.id).customerStatus(e)}accept(e){ro.team(this.id).accept(e)}end(e){ro.team(this.id).end(e)}history(e){ro.team(this.id).history(e)}markMessageAsRead(e){ro.team(this.id).markMessageAsRead(e)}createTextMessage(e){ro.team(this.id).createTextMessage(e)}createImageMessage(e){ro.team(this.id).createImageMessage(e)}createFileMessage(e){ro.team(this.id).createFileMessage(e)}createAudioMessage(e){ro.team(this.id).createAudioMessage(e)}createVideoMessage(e){ro.team(this.id).createVideoMessage(e)}createCustomMessage(e){ro.team(this.id).createCustomMessage(e)}transfer(e){ro.team(this.id).transfer(e)}agents(e){ro.team(this.id).agents(e)}liveSession(e){ro.team(this.id).liveSession(e)}quitLiveSession(e){ro.team(this.id).quitLiveSession(e)}listenCustomer(e){ro.team(this.id).listenCustomer(e)}cancelListenCustomer(e){ro.team(this.id).cancelListenCustomer(e)}}export{ho as AgentOnlineOptions,vo as CSTeam,ao as CallBackOptions,lo as ConversationDTO,mo as CustomerStatusOptions,go as GoEasyIM,fo as GoEasyPubSub,uo as MessageStatus,co as Scene,po as User,yo as default};