!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define("leancloud-realtime",["exports"],t):t((e=e||self).AV=e.AV||{})}(this,(function(e){"use strict";var t="undefined"!=typeof window&&window.process||{};t.env=t.env||{};var n="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function r(e,t,n){return e(n={path:t,exports:{},require:function(e,t){return i(null==t&&n.path)}},n.exports),n.exports}function i(){throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs")}var s,o=r((function(e){ /** * @license long.js (c) 2013 Daniel Wirtz * Released under the Apache License, Version 2.0 * see: https://github.com/dcodeIO/long.js for details */ !function(t,n){e&&e.exports?e.exports=n():(t.dcodeIO=t.dcodeIO||{}).Long=n()}(n,(function(){function e(e,t,n){this.low=0|e,this.high=0|t,this.unsigned=!!n}function t(e){return!0===(e&&e.__isLong__)}e.prototype.__isLong__,Object.defineProperty(e.prototype,"__isLong__",{value:!0,enumerable:!1,configurable:!1}),e.isLong=t;var n={},r={};function i(e,t){var i,s,a;return t?(a=0<=(e>>>=0)&&e<256)&&(s=r[e])?s:(i=o(e,(0|e)<0?-1:0,!0),a&&(r[e]=i),i):(a=-128<=(e|=0)&&e<128)&&(s=n[e])?s:(i=o(e,e<0?-1:0,!1),a&&(n[e]=i),i)}function s(e,t){if(isNaN(e)||!isFinite(e))return t?m:p;if(t){if(e<0)return m;if(e>=f)return w}else{if(e<=-h)return E;if(e+1>=h)return b}return e<0?s(-e,t).neg():o(e%c|0,e/c|0,t)}function o(t,n,r){return new e(t,n,r)}e.fromInt=i,e.fromNumber=s,e.fromBits=o;var a=Math.pow;function l(e,t,n){if(0===e.length)throw Error("empty string");if("NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return p;if("number"==typeof t?(n=t,t=!1):t=!!t,(n=n||10)<2||360)throw Error("interior hyphen");if(0===r)return l(e.substring(1),t,n).neg();for(var i=s(a(n,8)),o=p,u=0;u>>0:this.low},_.toNumber=function(){return this.unsigned?(this.high>>>0)*c+(this.low>>>0):this.high*c+(this.low>>>0)},_.toString=function(e){if((e=e||10)<2||36>>0).toString(e);if((o=u).isZero())return c+l;for(;c.length<6;)c="0"+c;l=""+c+l}},_.getHighBits=function(){return this.high},_.getHighBitsUnsigned=function(){return this.high>>>0},_.getLowBits=function(){return this.low},_.getLowBitsUnsigned=function(){return this.low>>>0},_.getNumBitsAbs=function(){if(this.isNegative())return this.eq(E)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&0==(e&1<=0},_.isOdd=function(){return 1==(1&this.low)},_.isEven=function(){return 0==(1&this.low)},_.equals=function(e){return t(e)||(e=u(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&(this.high===e.high&&this.low===e.low)},_.eq=_.equals,_.notEquals=function(e){return!this.eq(e)},_.neq=_.notEquals,_.lessThan=function(e){return this.comp(e)<0},_.lt=_.lessThan,_.lessThanOrEqual=function(e){return this.comp(e)<=0},_.lte=_.lessThanOrEqual,_.greaterThan=function(e){return this.comp(e)>0},_.gt=_.greaterThan,_.greaterThanOrEqual=function(e){return this.comp(e)>=0},_.gte=_.greaterThanOrEqual,_.compare=function(e){if(t(e)||(e=u(e)),this.eq(e))return 0;var n=this.isNegative(),r=e.isNegative();return n&&!r?-1:!n&&r?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1},_.comp=_.compare,_.negate=function(){return!this.unsigned&&this.eq(E)?E:this.not().add(g)},_.neg=_.negate,_.add=function(e){t(e)||(e=u(e));var n=this.high>>>16,r=65535&this.high,i=this.low>>>16,s=65535&this.low,a=e.high>>>16,l=65535&e.high,c=e.low>>>16,f=0,h=0,d=0,p=0;return d+=(p+=s+(65535&e.low))>>>16,h+=(d+=i+c)>>>16,f+=(h+=r+l)>>>16,f+=n+a,o((d&=65535)<<16|(p&=65535),(f&=65535)<<16|(h&=65535),this.unsigned)},_.subtract=function(e){return t(e)||(e=u(e)),this.add(e.neg())},_.sub=_.subtract,_.multiply=function(e){if(this.isZero())return p;if(t(e)||(e=u(e)),e.isZero())return p;if(this.eq(E))return e.isOdd()?E:p;if(e.eq(E))return this.isOdd()?E:p;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(d)&&e.lt(d))return s(this.toNumber()*e.toNumber(),this.unsigned);var n=this.high>>>16,r=65535&this.high,i=this.low>>>16,a=65535&this.low,l=e.high>>>16,c=65535&e.high,f=e.low>>>16,h=65535&e.low,m=0,g=0,y=0,v=0;return y+=(v+=a*h)>>>16,g+=(y+=i*h)>>>16,y&=65535,g+=(y+=a*f)>>>16,m+=(g+=r*h)>>>16,g&=65535,m+=(g+=i*f)>>>16,g&=65535,m+=(g+=a*c)>>>16,m+=n*h+r*f+i*c+a*l,o((y&=65535)<<16|(v&=65535),(m&=65535)<<16|(g&=65535),this.unsigned)},_.mul=_.multiply,_.divide=function(e){if(t(e)||(e=u(e)),e.isZero())throw Error("division by zero");if(this.isZero())return this.unsigned?m:p;var n,r,i;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return m;if(e.gt(this.shru(1)))return y;i=m}else{if(this.eq(E))return e.eq(g)||e.eq(v)?E:e.eq(E)?g:(n=this.shr(1).div(e).shl(1)).eq(p)?e.isNegative()?g:v:(r=this.sub(e.mul(n)),i=n.add(r.div(e)));if(e.eq(E))return this.unsigned?m:p;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();i=p}for(r=this;r.gte(e);){n=Math.max(1,Math.floor(r.toNumber()/e.toNumber()));for(var o=Math.ceil(Math.log(n)/Math.LN2),l=o<=48?1:a(2,o-48),c=s(n),f=c.mul(e);f.isNegative()||f.gt(r);)f=(c=s(n-=l,this.unsigned)).mul(e);c.isZero()&&(c=g),i=i.add(c),r=r.sub(f)}return i},_.div=_.divide,_.modulo=function(e){return t(e)||(e=u(e)),this.sub(this.div(e).mul(e))},_.mod=_.modulo,_.not=function(){return o(~this.low,~this.high,this.unsigned)},_.and=function(e){return t(e)||(e=u(e)),o(this.low&e.low,this.high&e.high,this.unsigned)},_.or=function(e){return t(e)||(e=u(e)),o(this.low|e.low,this.high|e.high,this.unsigned)},_.xor=function(e){return t(e)||(e=u(e)),o(this.low^e.low,this.high^e.high,this.unsigned)},_.shiftLeft=function(e){return t(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?o(this.low<>>32-e,this.unsigned):o(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):o(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},_.shr=_.shiftRight,_.shiftRightUnsigned=function(e){if(t(e)&&(e=e.toInt()),0===(e&=63))return this;var n=this.high;return e<32?o(this.low>>>e|n<<32-e,n>>>e,this.unsigned):o(32===e?n:n>>>e-32,0,this.unsigned)},_.shru=_.shiftRightUnsigned,_.toSigned=function(){return this.unsigned?o(this.low,this.high,!1):this},_.toUnsigned=function(){return this.unsigned?this:o(this.low,this.high,!0)},_.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},_.toBytesLE=function(){var e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24&255,255&e,e>>>8&255,e>>>16&255,e>>>24&255]},_.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24&255,e>>>16&255,e>>>8&255,255&e,t>>>24&255,t>>>16&255,t>>>8&255,255&t]},e}))})),a=r((function(e){ /** * @license bytebuffer.js (c) 2015 Daniel Wirtz * Backing buffer: ArrayBuffer, Accessor: Uint8Array * Released under the Apache License, Version 2.0 * see: https://github.com/dcodeIO/bytebuffer.js for details */ !function(t,n){e&&e.exports?e.exports=function(){var e;try{e=o}catch(e){}return n(e)}():(t.dcodeIO=t.dcodeIO||{}).ByteBuffer=n(t.dcodeIO.Long)}(n,(function(e){var t=function(e,n,i){if(void 0===e&&(e=t.DEFAULT_CAPACITY),void 0===n&&(n=t.DEFAULT_ENDIAN),void 0===i&&(i=t.DEFAULT_NOASSERT),!i){if((e|=0)<0)throw RangeError("Illegal capacity");n=!!n,i=!!i}this.buffer=0===e?r:new ArrayBuffer(e),this.view=0===e?null:new Uint8Array(this.buffer),this.offset=0,this.markedOffset=-1,this.limit=e,this.littleEndian=n,this.noAssert=i};t.VERSION="5.0.1",t.LITTLE_ENDIAN=!0,t.BIG_ENDIAN=!1,t.DEFAULT_CAPACITY=16,t.DEFAULT_ENDIAN=t.BIG_ENDIAN,t.DEFAULT_NOASSERT=!1,t.Long=e||null;var n=t.prototype;n.__isByteBuffer__,Object.defineProperty(n,"__isByteBuffer__",{value:!0,enumerable:!1,configurable:!1});var r=new ArrayBuffer(0),i=String.fromCharCode;function s(e){var t=0;return function(){return t1024&&(t.push(i.apply(String,e)),e.length=0),Array.prototype.push.apply(e,arguments)}}function a(e,t,n,r,i){var s,o,a=8*i-r-1,l=(1<>1,c=-7,f=n?i-1:0,h=n?-1:1,d=e[t+f];for(f+=h,s=d&(1<<-c)-1,d>>=-c,c+=a;c>0;s=256*s+e[t+f],f+=h,c-=8);for(o=s&(1<<-c)-1,s>>=-c,c+=r;c>0;o=256*o+e[t+f],f+=h,c-=8);if(0===s)s=1-u;else{if(s===l)return o?NaN:1/0*(d?-1:1);o+=Math.pow(2,r),s-=u}return(d?-1:1)*o*Math.pow(2,s-r)}function l(e,t,n,r,i,s){var o,a,l,u=8*s-i-1,c=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,d=r?0:s-1,p=r?1:-1,m=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,o=c):(o=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-o))<1&&(o--,l*=2),(t+=o+f>=1?h/l:h*Math.pow(2,1-f))*l>=2&&(o++,l/=2),o+f>=c?(a=0,o=c):o+f>=1?(a=(t*l-1)*Math.pow(2,i),o+=f):(a=t*Math.pow(2,f-1)*Math.pow(2,i),o=0));i>=8;e[n+d]=255&a,d+=p,a/=256,i-=8);for(o=o<0;e[n+d]=255&o,d+=p,o/=256,u-=8);e[n+d-p]|=128*m}t.accessor=function(){return Uint8Array},t.allocate=function(e,n,r){return new t(e,n,r)},t.concat=function(e,n,r,i){"boolean"!=typeof n&&"string"==typeof n||(i=r,r=n,n=void 0);for(var s,o=0,a=0,l=e.length;a0&&(o+=s);if(0===o)return new t(0,r,i);var u,c=new t(o,r,i);for(a=0;a0&&(o.buffer=e.buffer,o.offset=e.byteOffset,o.limit=e.byteOffset+e.byteLength,o.view=new Uint8Array(e.buffer));else if(e instanceof ArrayBuffer)o=new t(0,i,s),e.byteLength>0&&(o.buffer=e,o.offset=0,o.limit=e.byteLength,o.view=e.byteLength>0?new Uint8Array(e):null);else{if("[object Array]"!==Object.prototype.toString.call(e))throw TypeError("Illegal buffer");(o=new t(e.length,i,s)).limit=e.length;for(var a=0;a>>=0)<0||t+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+t+" (+0) <= "+this.buffer.byteLength)}var r,i=t,s=e.length,o=s>>3,a=0;for(t+=this.writeVarint32(s,t);o--;)r=1&!!e[a++]|(1&!!e[a++])<<1|(1&!!e[a++])<<2|(1&!!e[a++])<<3|(1&!!e[a++])<<4|(1&!!e[a++])<<5|(1&!!e[a++])<<6|(1&!!e[a++])<<7,this.writeByte(r,t++);if(a>3,o=0,a=[];for(e+=r.length;s--;)n=this.readByte(e++),a[o++]=!!(1&n),a[o++]=!!(2&n),a[o++]=!!(4&n),a[o++]=!!(8&n),a[o++]=!!(16&n),a[o++]=!!(32&n),a[o++]=!!(64&n),a[o++]=!!(128&n);if(o>l++&1)}return t&&(this.offset=e),a},n.readBytes=function(e,t){var n=void 0===t;if(n&&(t=this.offset),!this.noAssert){if("number"!=typeof t||t%1!=0)throw TypeError("Illegal offset: "+t+" (not an integer)");if((t>>>=0)<0||t+e>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+t+" (+"+e+") <= "+this.buffer.byteLength)}var r=this.slice(t,t+e);return n&&(this.offset+=e),r},n.writeBytes=n.append,n.writeInt8=function(e,t){var n=void 0===t;if(n&&(t=this.offset),!this.noAssert){if("number"!=typeof e||e%1!=0)throw TypeError("Illegal value: "+e+" (not an integer)");if(e|=0,"number"!=typeof t||t%1!=0)throw TypeError("Illegal offset: "+t+" (not an integer)");if((t>>>=0)<0||t+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+t+" (+0) <= "+this.buffer.byteLength)}t+=1;var r=this.buffer.byteLength;return t>r&&this.resize((r*=2)>t?r:t),t-=1,this.view[t]=e,n&&(this.offset+=1),this},n.writeByte=n.writeInt8,n.readInt8=function(e){var t=void 0===e;if(t&&(e=this.offset),!this.noAssert){if("number"!=typeof e||e%1!=0)throw TypeError("Illegal offset: "+e+" (not an integer)");if((e>>>=0)<0||e+1>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+e+" (+1) <= "+this.buffer.byteLength)}var n=this.view[e];return 128==(128&n)&&(n=-(255-n+1)),t&&(this.offset+=1),n},n.readByte=n.readInt8,n.writeUint8=function(e,t){var n=void 0===t;if(n&&(t=this.offset),!this.noAssert){if("number"!=typeof e||e%1!=0)throw TypeError("Illegal value: "+e+" (not an integer)");if(e>>>=0,"number"!=typeof t||t%1!=0)throw TypeError("Illegal offset: "+t+" (not an integer)");if((t>>>=0)<0||t+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+t+" (+0) <= "+this.buffer.byteLength)}t+=1;var r=this.buffer.byteLength;return t>r&&this.resize((r*=2)>t?r:t),t-=1,this.view[t]=e,n&&(this.offset+=1),this},n.writeUInt8=n.writeUint8,n.readUint8=function(e){var t=void 0===e;if(t&&(e=this.offset),!this.noAssert){if("number"!=typeof e||e%1!=0)throw TypeError("Illegal offset: "+e+" (not an integer)");if((e>>>=0)<0||e+1>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+e+" (+1) <= "+this.buffer.byteLength)}var n=this.view[e];return t&&(this.offset+=1),n},n.readUInt8=n.readUint8,n.writeInt16=function(e,t){var n=void 0===t;if(n&&(t=this.offset),!this.noAssert){if("number"!=typeof e||e%1!=0)throw TypeError("Illegal value: "+e+" (not an integer)");if(e|=0,"number"!=typeof t||t%1!=0)throw TypeError("Illegal offset: "+t+" (not an integer)");if((t>>>=0)<0||t+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+t+" (+0) <= "+this.buffer.byteLength)}t+=2;var r=this.buffer.byteLength;return t>r&&this.resize((r*=2)>t?r:t),t-=2,this.littleEndian?(this.view[t+1]=(65280&e)>>>8,this.view[t]=255&e):(this.view[t]=(65280&e)>>>8,this.view[t+1]=255&e),n&&(this.offset+=2),this},n.writeShort=n.writeInt16,n.readInt16=function(e){var t=void 0===e;if(t&&(e=this.offset),!this.noAssert){if("number"!=typeof e||e%1!=0)throw TypeError("Illegal offset: "+e+" (not an integer)");if((e>>>=0)<0||e+2>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+e+" (+2) <= "+this.buffer.byteLength)}var n=0;return this.littleEndian?(n=this.view[e],n|=this.view[e+1]<<8):(n=this.view[e]<<8,n|=this.view[e+1]),32768==(32768&n)&&(n=-(65535-n+1)),t&&(this.offset+=2),n},n.readShort=n.readInt16,n.writeUint16=function(e,t){var n=void 0===t;if(n&&(t=this.offset),!this.noAssert){if("number"!=typeof e||e%1!=0)throw TypeError("Illegal value: "+e+" (not an integer)");if(e>>>=0,"number"!=typeof t||t%1!=0)throw TypeError("Illegal offset: "+t+" (not an integer)");if((t>>>=0)<0||t+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+t+" (+0) <= "+this.buffer.byteLength)}t+=2;var r=this.buffer.byteLength;return t>r&&this.resize((r*=2)>t?r:t),t-=2,this.littleEndian?(this.view[t+1]=(65280&e)>>>8,this.view[t]=255&e):(this.view[t]=(65280&e)>>>8,this.view[t+1]=255&e),n&&(this.offset+=2),this},n.writeUInt16=n.writeUint16,n.readUint16=function(e){var t=void 0===e;if(t&&(e=this.offset),!this.noAssert){if("number"!=typeof e||e%1!=0)throw TypeError("Illegal offset: "+e+" (not an integer)");if((e>>>=0)<0||e+2>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+e+" (+2) <= "+this.buffer.byteLength)}var n=0;return this.littleEndian?(n=this.view[e],n|=this.view[e+1]<<8):(n=this.view[e]<<8,n|=this.view[e+1]),t&&(this.offset+=2),n},n.readUInt16=n.readUint16,n.writeInt32=function(e,t){var n=void 0===t;if(n&&(t=this.offset),!this.noAssert){if("number"!=typeof e||e%1!=0)throw TypeError("Illegal value: "+e+" (not an integer)");if(e|=0,"number"!=typeof t||t%1!=0)throw TypeError("Illegal offset: "+t+" (not an integer)");if((t>>>=0)<0||t+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+t+" (+0) <= "+this.buffer.byteLength)}t+=4;var r=this.buffer.byteLength;return t>r&&this.resize((r*=2)>t?r:t),t-=4,this.littleEndian?(this.view[t+3]=e>>>24&255,this.view[t+2]=e>>>16&255,this.view[t+1]=e>>>8&255,this.view[t]=255&e):(this.view[t]=e>>>24&255,this.view[t+1]=e>>>16&255,this.view[t+2]=e>>>8&255,this.view[t+3]=255&e),n&&(this.offset+=4),this},n.writeInt=n.writeInt32,n.readInt32=function(e){var t=void 0===e;if(t&&(e=this.offset),!this.noAssert){if("number"!=typeof e||e%1!=0)throw TypeError("Illegal offset: "+e+" (not an integer)");if((e>>>=0)<0||e+4>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+e+" (+4) <= "+this.buffer.byteLength)}var n=0;return this.littleEndian?(n=this.view[e+2]<<16,n|=this.view[e+1]<<8,n|=this.view[e],n+=this.view[e+3]<<24>>>0):(n=this.view[e+1]<<16,n|=this.view[e+2]<<8,n|=this.view[e+3],n+=this.view[e]<<24>>>0),n|=0,t&&(this.offset+=4),n},n.readInt=n.readInt32,n.writeUint32=function(e,t){var n=void 0===t;if(n&&(t=this.offset),!this.noAssert){if("number"!=typeof e||e%1!=0)throw TypeError("Illegal value: "+e+" (not an integer)");if(e>>>=0,"number"!=typeof t||t%1!=0)throw TypeError("Illegal offset: "+t+" (not an integer)");if((t>>>=0)<0||t+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+t+" (+0) <= "+this.buffer.byteLength)}t+=4;var r=this.buffer.byteLength;return t>r&&this.resize((r*=2)>t?r:t),t-=4,this.littleEndian?(this.view[t+3]=e>>>24&255,this.view[t+2]=e>>>16&255,this.view[t+1]=e>>>8&255,this.view[t]=255&e):(this.view[t]=e>>>24&255,this.view[t+1]=e>>>16&255,this.view[t+2]=e>>>8&255,this.view[t+3]=255&e),n&&(this.offset+=4),this},n.writeUInt32=n.writeUint32,n.readUint32=function(e){var t=void 0===e;if(t&&(e=this.offset),!this.noAssert){if("number"!=typeof e||e%1!=0)throw TypeError("Illegal offset: "+e+" (not an integer)");if((e>>>=0)<0||e+4>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+e+" (+4) <= "+this.buffer.byteLength)}var n=0;return this.littleEndian?(n=this.view[e+2]<<16,n|=this.view[e+1]<<8,n|=this.view[e],n+=this.view[e+3]<<24>>>0):(n=this.view[e+1]<<16,n|=this.view[e+2]<<8,n|=this.view[e+3],n+=this.view[e]<<24>>>0),t&&(this.offset+=4),n},n.readUInt32=n.readUint32,e&&(n.writeInt64=function(t,n){var r=void 0===n;if(r&&(n=this.offset),!this.noAssert){if("number"==typeof t)t=e.fromNumber(t);else if("string"==typeof t)t=e.fromString(t);else if(!(t&&t instanceof e))throw TypeError("Illegal value: "+t+" (not an integer or Long)");if("number"!=typeof n||n%1!=0)throw TypeError("Illegal offset: "+n+" (not an integer)");if((n>>>=0)<0||n+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+n+" (+0) <= "+this.buffer.byteLength)}"number"==typeof t?t=e.fromNumber(t):"string"==typeof t&&(t=e.fromString(t)),n+=8;var i=this.buffer.byteLength;n>i&&this.resize((i*=2)>n?i:n),n-=8;var s=t.low,o=t.high;return this.littleEndian?(this.view[n+3]=s>>>24&255,this.view[n+2]=s>>>16&255,this.view[n+1]=s>>>8&255,this.view[n]=255&s,n+=4,this.view[n+3]=o>>>24&255,this.view[n+2]=o>>>16&255,this.view[n+1]=o>>>8&255,this.view[n]=255&o):(this.view[n]=o>>>24&255,this.view[n+1]=o>>>16&255,this.view[n+2]=o>>>8&255,this.view[n+3]=255&o,n+=4,this.view[n]=s>>>24&255,this.view[n+1]=s>>>16&255,this.view[n+2]=s>>>8&255,this.view[n+3]=255&s),r&&(this.offset+=8),this},n.writeLong=n.writeInt64,n.readInt64=function(t){var n=void 0===t;if(n&&(t=this.offset),!this.noAssert){if("number"!=typeof t||t%1!=0)throw TypeError("Illegal offset: "+t+" (not an integer)");if((t>>>=0)<0||t+8>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+t+" (+8) <= "+this.buffer.byteLength)}var r=0,i=0;this.littleEndian?(r=this.view[t+2]<<16,r|=this.view[t+1]<<8,r|=this.view[t],r+=this.view[t+3]<<24>>>0,t+=4,i=this.view[t+2]<<16,i|=this.view[t+1]<<8,i|=this.view[t],i+=this.view[t+3]<<24>>>0):(i=this.view[t+1]<<16,i|=this.view[t+2]<<8,i|=this.view[t+3],i+=this.view[t]<<24>>>0,t+=4,r=this.view[t+1]<<16,r|=this.view[t+2]<<8,r|=this.view[t+3],r+=this.view[t]<<24>>>0);var s=new e(r,i,!1);return n&&(this.offset+=8),s},n.readLong=n.readInt64,n.writeUint64=function(t,n){var r=void 0===n;if(r&&(n=this.offset),!this.noAssert){if("number"==typeof t)t=e.fromNumber(t);else if("string"==typeof t)t=e.fromString(t);else if(!(t&&t instanceof e))throw TypeError("Illegal value: "+t+" (not an integer or Long)");if("number"!=typeof n||n%1!=0)throw TypeError("Illegal offset: "+n+" (not an integer)");if((n>>>=0)<0||n+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+n+" (+0) <= "+this.buffer.byteLength)}"number"==typeof t?t=e.fromNumber(t):"string"==typeof t&&(t=e.fromString(t)),n+=8;var i=this.buffer.byteLength;n>i&&this.resize((i*=2)>n?i:n),n-=8;var s=t.low,o=t.high;return this.littleEndian?(this.view[n+3]=s>>>24&255,this.view[n+2]=s>>>16&255,this.view[n+1]=s>>>8&255,this.view[n]=255&s,n+=4,this.view[n+3]=o>>>24&255,this.view[n+2]=o>>>16&255,this.view[n+1]=o>>>8&255,this.view[n]=255&o):(this.view[n]=o>>>24&255,this.view[n+1]=o>>>16&255,this.view[n+2]=o>>>8&255,this.view[n+3]=255&o,n+=4,this.view[n]=s>>>24&255,this.view[n+1]=s>>>16&255,this.view[n+2]=s>>>8&255,this.view[n+3]=255&s),r&&(this.offset+=8),this},n.writeUInt64=n.writeUint64,n.readUint64=function(t){var n=void 0===t;if(n&&(t=this.offset),!this.noAssert){if("number"!=typeof t||t%1!=0)throw TypeError("Illegal offset: "+t+" (not an integer)");if((t>>>=0)<0||t+8>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+t+" (+8) <= "+this.buffer.byteLength)}var r=0,i=0;this.littleEndian?(r=this.view[t+2]<<16,r|=this.view[t+1]<<8,r|=this.view[t],r+=this.view[t+3]<<24>>>0,t+=4,i=this.view[t+2]<<16,i|=this.view[t+1]<<8,i|=this.view[t],i+=this.view[t+3]<<24>>>0):(i=this.view[t+1]<<16,i|=this.view[t+2]<<8,i|=this.view[t+3],i+=this.view[t]<<24>>>0,t+=4,r=this.view[t+1]<<16,r|=this.view[t+2]<<8,r|=this.view[t+3],r+=this.view[t]<<24>>>0);var s=new e(r,i,!0);return n&&(this.offset+=8),s},n.readUInt64=n.readUint64),n.writeFloat32=function(e,t){var n=void 0===t;if(n&&(t=this.offset),!this.noAssert){if("number"!=typeof e)throw TypeError("Illegal value: "+e+" (not a number)");if("number"!=typeof t||t%1!=0)throw TypeError("Illegal offset: "+t+" (not an integer)");if((t>>>=0)<0||t+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+t+" (+0) <= "+this.buffer.byteLength)}t+=4;var r=this.buffer.byteLength;return t>r&&this.resize((r*=2)>t?r:t),t-=4,l(this.view,e,t,this.littleEndian,23,4),n&&(this.offset+=4),this},n.writeFloat=n.writeFloat32,n.readFloat32=function(e){var t=void 0===e;if(t&&(e=this.offset),!this.noAssert){if("number"!=typeof e||e%1!=0)throw TypeError("Illegal offset: "+e+" (not an integer)");if((e>>>=0)<0||e+4>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+e+" (+4) <= "+this.buffer.byteLength)}var n=a(this.view,e,this.littleEndian,23,4);return t&&(this.offset+=4),n},n.readFloat=n.readFloat32,n.writeFloat64=function(e,t){var n=void 0===t;if(n&&(t=this.offset),!this.noAssert){if("number"!=typeof e)throw TypeError("Illegal value: "+e+" (not a number)");if("number"!=typeof t||t%1!=0)throw TypeError("Illegal offset: "+t+" (not an integer)");if((t>>>=0)<0||t+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+t+" (+0) <= "+this.buffer.byteLength)}t+=8;var r=this.buffer.byteLength;return t>r&&this.resize((r*=2)>t?r:t),t-=8,l(this.view,e,t,this.littleEndian,52,8),n&&(this.offset+=8),this},n.writeDouble=n.writeFloat64,n.readFloat64=function(e){var t=void 0===e;if(t&&(e=this.offset),!this.noAssert){if("number"!=typeof e||e%1!=0)throw TypeError("Illegal offset: "+e+" (not an integer)");if((e>>>=0)<0||e+8>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+e+" (+8) <= "+this.buffer.byteLength)}var n=a(this.view,e,this.littleEndian,52,8);return t&&(this.offset+=8),n},n.readDouble=n.readFloat64,t.MAX_VARINT32_BYTES=5,t.calculateVarint32=function(e){return(e>>>=0)<128?1:e<16384?2:e<1<<21?3:e<1<<28?4:5},t.zigZagEncode32=function(e){return((e|=0)<<1^e>>31)>>>0},t.zigZagDecode32=function(e){return e>>>1^-(1&e)|0},n.writeVarint32=function(e,n){var r=void 0===n;if(r&&(n=this.offset),!this.noAssert){if("number"!=typeof e||e%1!=0)throw TypeError("Illegal value: "+e+" (not an integer)");if(e|=0,"number"!=typeof n||n%1!=0)throw TypeError("Illegal offset: "+n+" (not an integer)");if((n>>>=0)<0||n+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+n+" (+0) <= "+this.buffer.byteLength)}var i,s=t.calculateVarint32(e);n+=s;var o=this.buffer.byteLength;for(n>o&&this.resize((o*=2)>n?o:n),n-=s,e>>>=0;e>=128;)i=127&e|128,this.view[n++]=i,e>>>=7;return this.view[n++]=e,r?(this.offset=n,this):s},n.writeVarint32ZigZag=function(e,n){return this.writeVarint32(t.zigZagEncode32(e),n)},n.readVarint32=function(e){var t=void 0===e;if(t&&(e=this.offset),!this.noAssert){if("number"!=typeof e||e%1!=0)throw TypeError("Illegal offset: "+e+" (not an integer)");if((e>>>=0)<0||e+1>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+e+" (+1) <= "+this.buffer.byteLength)}var n,r=0,i=0;do{if(!this.noAssert&&e>this.limit){var s=Error("Truncated");throw s.truncated=!0,s}n=this.view[e++],r<5&&(i|=(127&n)<<7*r),++r}while(0!=(128&n));return i|=0,t?(this.offset=e,i):{value:i,length:r}},n.readVarint32ZigZag=function(e){var n=this.readVarint32(e);return"object"==typeof n?n.value=t.zigZagDecode32(n.value):n=t.zigZagDecode32(n),n},e&&(t.MAX_VARINT64_BYTES=10,t.calculateVarint64=function(t){"number"==typeof t?t=e.fromNumber(t):"string"==typeof t&&(t=e.fromString(t));var n=t.toInt()>>>0,r=t.shiftRightUnsigned(28).toInt()>>>0,i=t.shiftRightUnsigned(56).toInt()>>>0;return 0==i?0==r?n<16384?n<128?1:2:n<1<<21?3:4:r<16384?r<128?5:6:r<1<<21?7:8:i<128?9:10},t.zigZagEncode64=function(t){return"number"==typeof t?t=e.fromNumber(t,!1):"string"==typeof t?t=e.fromString(t,!1):!1!==t.unsigned&&(t=t.toSigned()),t.shiftLeft(1).xor(t.shiftRight(63)).toUnsigned()},t.zigZagDecode64=function(t){return"number"==typeof t?t=e.fromNumber(t,!1):"string"==typeof t?t=e.fromString(t,!1):!1!==t.unsigned&&(t=t.toSigned()),t.shiftRightUnsigned(1).xor(t.and(e.ONE).toSigned().negate()).toSigned()},n.writeVarint64=function(n,r){var i=void 0===r;if(i&&(r=this.offset),!this.noAssert){if("number"==typeof n)n=e.fromNumber(n);else if("string"==typeof n)n=e.fromString(n);else if(!(n&&n instanceof e))throw TypeError("Illegal value: "+n+" (not an integer or Long)");if("number"!=typeof r||r%1!=0)throw TypeError("Illegal offset: "+r+" (not an integer)");if((r>>>=0)<0||r+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+r+" (+0) <= "+this.buffer.byteLength)}"number"==typeof n?n=e.fromNumber(n,!1):"string"==typeof n?n=e.fromString(n,!1):!1!==n.unsigned&&(n=n.toSigned());var s=t.calculateVarint64(n),o=n.toInt()>>>0,a=n.shiftRightUnsigned(28).toInt()>>>0,l=n.shiftRightUnsigned(56).toInt()>>>0;r+=s;var u=this.buffer.byteLength;switch(r>u&&this.resize((u*=2)>r?u:r),r-=s,s){case 10:this.view[r+9]=l>>>7&1;case 9:this.view[r+8]=9!==s?128|l:127&l;case 8:this.view[r+7]=8!==s?a>>>21|128:a>>>21&127;case 7:this.view[r+6]=7!==s?a>>>14|128:a>>>14&127;case 6:this.view[r+5]=6!==s?a>>>7|128:a>>>7&127;case 5:this.view[r+4]=5!==s?128|a:127&a;case 4:this.view[r+3]=4!==s?o>>>21|128:o>>>21&127;case 3:this.view[r+2]=3!==s?o>>>14|128:o>>>14&127;case 2:this.view[r+1]=2!==s?o>>>7|128:o>>>7&127;case 1:this.view[r]=1!==s?128|o:127&o}return i?(this.offset+=s,this):s},n.writeVarint64ZigZag=function(e,n){return this.writeVarint64(t.zigZagEncode64(e),n)},n.readVarint64=function(t){var n=void 0===t;if(n&&(t=this.offset),!this.noAssert){if("number"!=typeof t||t%1!=0)throw TypeError("Illegal offset: "+t+" (not an integer)");if((t>>>=0)<0||t+1>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+t+" (+1) <= "+this.buffer.byteLength)}var r=t,i=0,s=0,o=0,a=0;if(i=127&(a=this.view[t++]),128&a&&(i|=(127&(a=this.view[t++]))<<7,(128&a||this.noAssert&&void 0===a)&&(i|=(127&(a=this.view[t++]))<<14,(128&a||this.noAssert&&void 0===a)&&(i|=(127&(a=this.view[t++]))<<21,(128&a||this.noAssert&&void 0===a)&&(s=127&(a=this.view[t++]),(128&a||this.noAssert&&void 0===a)&&(s|=(127&(a=this.view[t++]))<<7,(128&a||this.noAssert&&void 0===a)&&(s|=(127&(a=this.view[t++]))<<14,(128&a||this.noAssert&&void 0===a)&&(s|=(127&(a=this.view[t++]))<<21,(128&a||this.noAssert&&void 0===a)&&(o=127&(a=this.view[t++]),(128&a||this.noAssert&&void 0===a)&&(o|=(127&(a=this.view[t++]))<<7,128&a||this.noAssert&&void 0===a))))))))))throw Error("Buffer overrun");var l=e.fromBits(i|s<<28,s>>>4|o<<24,!1);return n?(this.offset=t,l):{value:l,length:t-r}},n.readVarint64ZigZag=function(n){var r=this.readVarint64(n);return r&&r.value instanceof e?r.value=t.zigZagDecode64(r.value):r=t.zigZagDecode64(r),r}),n.writeCString=function(e,t){var n=void 0===t;n&&(t=this.offset);var r,i=e.length;if(!this.noAssert){if("string"!=typeof e)throw TypeError("Illegal str: Not a string");for(r=0;r>>=0)<0||t+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+t+" (+0) <= "+this.buffer.byteLength)}i=c.calculateUTF16asUTF8(s(e))[1],t+=i+1;var o=this.buffer.byteLength;return t>o&&this.resize((o*=2)>t?o:t),t-=i+1,c.encodeUTF16toUTF8(s(e),function(e){this.view[t++]=e}.bind(this)),this.view[t++]=0,n?(this.offset=t,this):i},n.readCString=function(e){var t=void 0===e;if(t&&(e=this.offset),!this.noAssert){if("number"!=typeof e||e%1!=0)throw TypeError("Illegal offset: "+e+" (not an integer)");if((e>>>=0)<0||e+1>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+e+" (+1) <= "+this.buffer.byteLength)}var n,r=e,i=-1;return c.decodeUTF8toUTF16(function(){if(0===i)return null;if(e>=this.limit)throw RangeError("Illegal range: Truncated data, "+e+" < "+this.limit);return 0===(i=this.view[e++])?null:i}.bind(this),n=o(),!0),t?(this.offset=e,n()):{string:n(),length:e-r}},n.writeIString=function(e,t){var n=void 0===t;if(n&&(t=this.offset),!this.noAssert){if("string"!=typeof e)throw TypeError("Illegal str: Not a string");if("number"!=typeof t||t%1!=0)throw TypeError("Illegal offset: "+t+" (not an integer)");if((t>>>=0)<0||t+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+t+" (+0) <= "+this.buffer.byteLength)}var r,i=t;r=c.calculateUTF16asUTF8(s(e),this.noAssert)[1],t+=4+r;var o=this.buffer.byteLength;if(t>o&&this.resize((o*=2)>t?o:t),t-=4+r,this.littleEndian?(this.view[t+3]=r>>>24&255,this.view[t+2]=r>>>16&255,this.view[t+1]=r>>>8&255,this.view[t]=255&r):(this.view[t]=r>>>24&255,this.view[t+1]=r>>>16&255,this.view[t+2]=r>>>8&255,this.view[t+3]=255&r),t+=4,c.encodeUTF16toUTF8(s(e),function(e){this.view[t++]=e}.bind(this)),t!==i+4+r)throw RangeError("Illegal range: Truncated data, "+t+" == "+(t+4+r));return n?(this.offset=t,this):t-i},n.readIString=function(e){var n=void 0===e;if(n&&(e=this.offset),!this.noAssert){if("number"!=typeof e||e%1!=0)throw TypeError("Illegal offset: "+e+" (not an integer)");if((e>>>=0)<0||e+4>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+e+" (+4) <= "+this.buffer.byteLength)}var r=e,i=this.readUint32(e),s=this.readUTF8String(i,t.METRICS_BYTES,e+=4);return e+=s.length,n?(this.offset=e,s.string):{string:s.string,length:e-r}},t.METRICS_CHARS="c",t.METRICS_BYTES="b",n.writeUTF8String=function(e,t){var n,r=void 0===t;if(r&&(t=this.offset),!this.noAssert){if("number"!=typeof t||t%1!=0)throw TypeError("Illegal offset: "+t+" (not an integer)");if((t>>>=0)<0||t+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+t+" (+0) <= "+this.buffer.byteLength)}var i=t;n=c.calculateUTF16asUTF8(s(e))[1],t+=n;var o=this.buffer.byteLength;return t>o&&this.resize((o*=2)>t?o:t),t-=n,c.encodeUTF16toUTF8(s(e),function(e){this.view[t++]=e}.bind(this)),r?(this.offset=t,this):t-i},n.writeString=n.writeUTF8String,t.calculateUTF8Chars=function(e){return c.calculateUTF16asUTF8(s(e))[0]},t.calculateUTF8Bytes=function(e){return c.calculateUTF16asUTF8(s(e))[1]},t.calculateString=t.calculateUTF8Bytes,n.readUTF8String=function(e,n,r){"number"==typeof n&&(r=n,n=void 0);var i=void 0===r;if(i&&(r=this.offset),void 0===n&&(n=t.METRICS_CHARS),!this.noAssert){if("number"!=typeof e||e%1!=0)throw TypeError("Illegal length: "+e+" (not an integer)");if(e|=0,"number"!=typeof r||r%1!=0)throw TypeError("Illegal offset: "+r+" (not an integer)");if((r>>>=0)<0||r+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+r+" (+0) <= "+this.buffer.byteLength)}var s,a=0,l=r;if(n===t.METRICS_CHARS){if(s=o(),c.decodeUTF8(function(){return a>>=0)<0||r+e>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+r+" (+"+e+") <= "+this.buffer.byteLength)}var u=r+e;if(c.decodeUTF8toUTF16(function(){return r>>=0)<0||n+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+n+" (+0) <= "+this.buffer.byteLength)}var i,o,a=n;i=c.calculateUTF16asUTF8(s(e),this.noAssert)[1],o=t.calculateVarint32(i),n+=o+i;var l=this.buffer.byteLength;if(n>l&&this.resize((l*=2)>n?l:n),n-=o+i,n+=this.writeVarint32(i,n),c.encodeUTF16toUTF8(s(e),function(e){this.view[n++]=e}.bind(this)),n!==a+i+o)throw RangeError("Illegal range: Truncated data, "+n+" == "+(n+i+o));return r?(this.offset=n,this):n-a},n.readVString=function(e){var n=void 0===e;if(n&&(e=this.offset),!this.noAssert){if("number"!=typeof e||e%1!=0)throw TypeError("Illegal offset: "+e+" (not an integer)");if((e>>>=0)<0||e+1>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+e+" (+1) <= "+this.buffer.byteLength)}var r=e,i=this.readVarint32(e),s=this.readUTF8String(i.value,t.METRICS_BYTES,e+=i.length);return e+=s.length,n?(this.offset=e,s.string):{string:s.string,length:e-r}},n.append=function(e,n,r){"number"!=typeof n&&"string"==typeof n||(r=n,n=void 0);var i=void 0===r;if(i&&(r=this.offset),!this.noAssert){if("number"!=typeof r||r%1!=0)throw TypeError("Illegal offset: "+r+" (not an integer)");if((r>>>=0)<0||r+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+r+" (+0) <= "+this.buffer.byteLength)}e instanceof t||(e=t.wrap(e,n));var s=e.limit-e.offset;if(s<=0)return this;r+=s;var o=this.buffer.byteLength;return r>o&&this.resize((o*=2)>r?o:r),r-=s,this.view.set(e.view.subarray(e.offset,e.limit),r),e.offset+=s,i&&(this.offset+=s),this},n.appendTo=function(e,t){return e.append(this,t),this},n.assert=function(e){return this.noAssert=!e,this},n.capacity=function(){return this.buffer.byteLength},n.clear=function(){return this.offset=0,this.limit=this.buffer.byteLength,this.markedOffset=-1,this},n.clone=function(e){var n=new t(0,this.littleEndian,this.noAssert);return e?(n.buffer=new ArrayBuffer(this.buffer.byteLength),n.view=new Uint8Array(n.buffer)):(n.buffer=this.buffer,n.view=this.view),n.offset=this.offset,n.markedOffset=this.markedOffset,n.limit=this.limit,n},n.compact=function(e,t){if(void 0===e&&(e=this.offset),void 0===t&&(t=this.limit),!this.noAssert){if("number"!=typeof e||e%1!=0)throw TypeError("Illegal begin: Not an integer");if(e>>>=0,"number"!=typeof t||t%1!=0)throw TypeError("Illegal end: Not an integer");if(t>>>=0,e<0||e>t||t>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+e+" <= "+t+" <= "+this.buffer.byteLength)}if(0===e&&t===this.buffer.byteLength)return this;var n=t-e;if(0===n)return this.buffer=r,this.view=null,this.markedOffset>=0&&(this.markedOffset-=e),this.offset=0,this.limit=0,this;var i=new ArrayBuffer(n),s=new Uint8Array(i);return s.set(this.view.subarray(e,t)),this.buffer=i,this.view=s,this.markedOffset>=0&&(this.markedOffset-=e),this.offset=0,this.limit=n,this},n.copy=function(e,n){if(void 0===e&&(e=this.offset),void 0===n&&(n=this.limit),!this.noAssert){if("number"!=typeof e||e%1!=0)throw TypeError("Illegal begin: Not an integer");if(e>>>=0,"number"!=typeof n||n%1!=0)throw TypeError("Illegal end: Not an integer");if(n>>>=0,e<0||e>n||n>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+e+" <= "+n+" <= "+this.buffer.byteLength)}if(e===n)return new t(0,this.littleEndian,this.noAssert);var r=n-e,i=new t(r,this.littleEndian,this.noAssert);return i.offset=0,i.limit=r,i.markedOffset>=0&&(i.markedOffset-=e),this.copyTo(i,0,e,n),i},n.copyTo=function(e,n,r,i){var s,o;if(!this.noAssert&&!t.isByteBuffer(e))throw TypeError("Illegal target: Not a ByteBuffer");if(n=(o=void 0===n)?e.offset:0|n,r=(s=void 0===r)?this.offset:0|r,i=void 0===i?this.limit:0|i,n<0||n>e.buffer.byteLength)throw RangeError("Illegal target range: 0 <= "+n+" <= "+e.buffer.byteLength);if(r<0||i>this.buffer.byteLength)throw RangeError("Illegal source range: 0 <= "+r+" <= "+this.buffer.byteLength);var a=i-r;return 0===a?e:(e.ensureCapacity(n+a),e.view.set(this.view.subarray(r,i),n),s&&(this.offset+=a),o&&(e.offset+=a),this)},n.ensureCapacity=function(e){var t=this.buffer.byteLength;return te?t:e):this},n.fill=function(e,t,n){var r=void 0===t;if(r&&(t=this.offset),"string"==typeof e&&e.length>0&&(e=e.charCodeAt(0)),void 0===t&&(t=this.offset),void 0===n&&(n=this.limit),!this.noAssert){if("number"!=typeof e||e%1!=0)throw TypeError("Illegal value: "+e+" (not an integer)");if(e|=0,"number"!=typeof t||t%1!=0)throw TypeError("Illegal begin: Not an integer");if(t>>>=0,"number"!=typeof n||n%1!=0)throw TypeError("Illegal end: Not an integer");if(n>>>=0,t<0||t>n||n>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+t+" <= "+n+" <= "+this.buffer.byteLength)}if(t>=n)return this;for(;t>>=0)<0||e+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+e+" (+0) <= "+this.buffer.byteLength)}return this.markedOffset=e,this},n.order=function(e){if(!this.noAssert&&"boolean"!=typeof e)throw TypeError("Illegal littleEndian: Not a boolean");return this.littleEndian=!!e,this},n.LE=function(e){return this.littleEndian=void 0===e||!!e,this},n.BE=function(e){return this.littleEndian=void 0!==e&&!e,this},n.prepend=function(e,n,r){"number"!=typeof n&&"string"==typeof n||(r=n,n=void 0);var i=void 0===r;if(i&&(r=this.offset),!this.noAssert){if("number"!=typeof r||r%1!=0)throw TypeError("Illegal offset: "+r+" (not an integer)");if((r>>>=0)<0||r+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+r+" (+0) <= "+this.buffer.byteLength)}e instanceof t||(e=t.wrap(e,n));var s=e.limit-e.offset;if(s<=0)return this;var o=s-r;if(o>0){var a=new ArrayBuffer(this.buffer.byteLength+o),l=new Uint8Array(a);l.set(this.view.subarray(r,this.buffer.byteLength),s),this.buffer=a,this.view=l,this.offset+=o,this.markedOffset>=0&&(this.markedOffset+=o),this.limit+=o,r+=o}else new Uint8Array(this.buffer);return this.view.set(e.view.subarray(e.offset,e.limit),r-s),e.offset=e.limit,i&&(this.offset-=s),this},n.prependTo=function(e,t){return e.prepend(this,t),this},n.printDebug=function(e){"function"!=typeof e&&(e=console.log.bind(console)),e(this.toString()+"\n-------------------------------------------------------------------\n"+this.toDebug(!0))},n.remaining=function(){return this.limit-this.offset},n.reset=function(){return this.markedOffset>=0?(this.offset=this.markedOffset,this.markedOffset=-1):this.offset=0,this},n.resize=function(e){if(!this.noAssert){if("number"!=typeof e||e%1!=0)throw TypeError("Illegal capacity: "+e+" (not an integer)");if((e|=0)<0)throw RangeError("Illegal capacity: 0 <= "+e)}if(this.buffer.byteLength>>=0,"number"!=typeof t||t%1!=0)throw TypeError("Illegal end: Not an integer");if(t>>>=0,e<0||e>t||t>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+e+" <= "+t+" <= "+this.buffer.byteLength)}return e===t||Array.prototype.reverse.call(this.view.subarray(e,t)),this},n.skip=function(e){if(!this.noAssert){if("number"!=typeof e||e%1!=0)throw TypeError("Illegal length: "+e+" (not an integer)");e|=0}var t=this.offset+e;if(!this.noAssert&&(t<0||t>this.buffer.byteLength))throw RangeError("Illegal length: 0 <= "+this.offset+" + "+e+" <= "+this.buffer.byteLength);return this.offset=t,this},n.slice=function(e,t){if(void 0===e&&(e=this.offset),void 0===t&&(t=this.limit),!this.noAssert){if("number"!=typeof e||e%1!=0)throw TypeError("Illegal begin: Not an integer");if(e>>>=0,"number"!=typeof t||t%1!=0)throw TypeError("Illegal end: Not an integer");if(t>>>=0,e<0||e>t||t>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+e+" <= "+t+" <= "+this.buffer.byteLength)}var n=this.clone();return n.offset=e,n.limit=t,n},n.toBuffer=function(e){var t=this.offset,n=this.limit;if(!this.noAssert){if("number"!=typeof t||t%1!=0)throw TypeError("Illegal offset: Not an integer");if(t>>>=0,"number"!=typeof n||n%1!=0)throw TypeError("Illegal limit: Not an integer");if(n>>>=0,t<0||t>n||n>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+t+" <= "+n+" <= "+this.buffer.byteLength)}if(!e&&0===t&&n===this.buffer.byteLength)return this.buffer;if(t===n)return r;var i=new ArrayBuffer(n-t);return new Uint8Array(i).set(new Uint8Array(this.buffer).subarray(t,n),0),i},n.toArrayBuffer=n.toBuffer,n.toString=function(e,t,n){if(void 0===e)return"ByteBufferAB(offset="+this.offset+",markedOffset="+this.markedOffset+",limit="+this.limit+",capacity="+this.capacity()+")";switch("number"==typeof e&&(n=t=e="utf8"),e){case"utf8":return this.toUTF8(t,n);case"base64":return this.toBase64(t,n);case"hex":return this.toHex(t,n);case"binary":return this.toBinary(t,n);case"debug":return this.toDebug();case"columns":return this.toColumns();default:throw Error("Unsupported encoding: "+e)}};var u=function(){for(var e={},t=[65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,48,49,50,51,52,53,54,55,56,57,43,47],n=[],r=0,i=t.length;r>2&63]),i=(3&r)<<4,null!==(r=e())?(n(t[63&((i|=r>>4&15)|r>>4&15)]),i=(15&r)<<2,null!==(r=e())?(n(t[63&(i|r>>6&3)]),n(t[63&r])):(n(t[63&i]),n(61))):(n(t[63&i]),n(61),n(61))},e.decode=function(e,t){var r,i,s;function o(e){throw Error("Illegal character code: "+e)}for(;null!==(r=e());)if(void 0===(i=n[r])&&o(r),null!==(r=e())&&(void 0===(s=n[r])&&o(r),t(i<<2>>>0|(48&s)>>4),null!==(r=e()))){if(void 0===(i=n[r])){if(61===r)break;o(r)}if(t((15&s)<<4>>>0|(60&i)>>2),null!==(r=e())){if(void 0===(s=n[r])){if(61===r)break;o(r)}t((3&i)<<6>>>0|s)}}},e.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)},e}();n.toBase64=function(e,t){if(void 0===e&&(e=this.offset),void 0===t&&(t=this.limit),t|=0,(e|=0)<0||t>this.capacity||e>t)throw RangeError("begin, end");var n;return u.encode(function(){return ethis.capacity()||e>t)throw RangeError("begin, end");if(e===t)return"";for(var n=[],r=[];e=1024&&(r.push(String.fromCharCode.apply(String,n)),n=[]);return r.join("")+String.fromCharCode.apply(String,n)},t.fromBinary=function(e,n){if("string"!=typeof e)throw TypeError("str");for(var r,i=0,s=e.length,o=new t(s,n);i255)throw RangeError("illegal char code: "+r);o.view[i++]=r}return o.limit=s,o},n.toDebug=function(e){for(var t,n=-1,r=this.buffer.byteLength,i="",s="",o="";n32&&t<127?String.fromCharCode(t):".")),++n,e&&n>0&&n%16==0&&n!==r){for(;i.length<51;)i+=" ";o+=i+s+"\n",i=s=""}n===this.offset&&n===this.limit?i+=n===this.markedOffset?"!":"|":n===this.offset?i+=n===this.markedOffset?"[":"<":n===this.limit?i+=n===this.markedOffset?"]":">":i+=n===this.markedOffset?"'":e||0!==n&&n!==r?" ":""}if(e&&" "!==i){for(;i.length<51;)i+=" ";o+=i+s+"\n"}return e?o:i},t.fromDebug=function(e,n,r){for(var i,s,o=e.length,a=new t((o+1)/3|0,n,r),l=0,u=0,c=!1,f=!1,h=!1,d=!1,p=!1;l":if(!r){if(d){p=!0;break}d=!0}a.limit=u,c=!1;break;case"'":if(!r){if(h){p=!0;break}h=!0}a.markedOffset=u,c=!1;break;case" ":c=!1;break;default:if(!r&&c){p=!0;break}if(s=parseInt(i+e.charAt(l++),16),!r&&(isNaN(s)||s<0||s>255))throw TypeError("Illegal str: Not a debug encoded string");a.view[u++]=s,c=!0}if(p)throw TypeError("Illegal str: Invalid symbol at "+l)}if(!r){if(!f||!d)throw TypeError("Illegal str: Missing offset or limit");if(u>>=0,"number"!=typeof t||t%1!=0)throw TypeError("Illegal end: Not an integer");if(t>>>=0,e<0||e>t||t>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+e+" <= "+t+" <= "+this.buffer.byteLength)}for(var n,r=new Array(t-e);e255))throw TypeError("Illegal str: Contains non-hex characters");o.view[l++]=i}return o.limit=l,o};var c=function(){var e={MAX_CODEPOINT:1114111,encodeUTF8:function(e,t){var n=null;for("number"==typeof e&&(n=e,e=function(){return null});null!==n||null!==(n=e());)n<128?t(127&n):n<2048?(t(n>>6&31|192),t(63&n|128)):n<65536?(t(n>>12&15|224),t(n>>6&63|128),t(63&n|128)):(t(n>>18&7|240),t(n>>12&63|128),t(n>>6&63|128),t(63&n|128)),n=null},decodeUTF8:function(e,t){for(var n,r,i,s,o=function(e){e=e.slice(0,e.indexOf(null));var t=Error(e.toString());throw t.name="TruncatedError",t.bytes=e,t};null!==(n=e());)if(0==(128&n))t(n);else if(192==(224&n))null===(r=e())&&o([n,r]),t((31&n)<<6|63&r);else if(224==(240&n))(null===(r=e())||null===(i=e()))&&o([n,r,i]),t((15&n)<<12|(63&r)<<6|63&i);else{if(240!=(248&n))throw RangeError("Illegal starting byte: "+n);(null===(r=e())||null===(i=e())||null===(s=e()))&&o([n,r,i,s]),t((7&n)<<18|(63&r)<<12|(63&i)<<6|63&s)}},UTF16toUTF8:function(e,t){for(var n,r=null;null!==(n=null!==r?r:e());)n>=55296&&n<=57343&&null!==(r=e())&&r>=56320&&r<=57343?(t(1024*(n-55296)+r-56320+65536),r=null):t(n);null!==r&&t(r)},UTF8toUTF16:function(e,t){var n=null;for("number"==typeof e&&(n=e,e=function(){return null});null!==n||null!==(n=e());)n<=65535?t(n):(t(55296+((n-=65536)>>10)),t(n%1024+56320)),n=null},encodeUTF16toUTF8:function(t,n){e.UTF16toUTF8(t,(function(t){e.encodeUTF8(t,n)}))},decodeUTF8toUTF16:function(t,n){e.decodeUTF8(t,(function(t){e.UTF8toUTF16(t,n)}))},calculateCodePoint:function(e){return e<128?1:e<2048?2:e<65536?3:4},calculateUTF8:function(e){for(var t,n=0;null!==(t=e());)n+=t<128?1:t<2048?2:t<65536?3:4;return n},calculateUTF16asUTF8:function(t){var n=0,r=0;return e.UTF16toUTF8(t,(function(e){++n,r+=e<128?1:e<2048?2:e<65536?3:4})),[n,r]}};return e}();return n.toUTF8=function(e,t){if(void 0===e&&(e=this.offset),void 0===t&&(t=this.limit),!this.noAssert){if("number"!=typeof e||e%1!=0)throw TypeError("Illegal begin: Not an integer");if(e>>>=0,"number"!=typeof t||t%1!=0)throw TypeError("Illegal end: Not an integer");if(t>>>=0,e<0||e>t||t>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+e+" <= "+t+" <= "+this.buffer.byteLength)}var n;try{c.decodeUTF8toUTF16(function(){return e * Released under the Apache License, Version 2.0 * see: https://github.com/dcodeIO/protobuf.js for details */ !function(t,n){e&&e.exports?e.exports=n(a,!0):(t.dcodeIO=t.dcodeIO||{}).ProtoBuf=n(t.dcodeIO.ByteBuffer)}(n,(function(e,n){var r,i={};return i.ByteBuffer=e,i.Long=e.Long||null,i.VERSION="5.0.3",i.WIRE_TYPES={},i.WIRE_TYPES.VARINT=0,i.WIRE_TYPES.BITS64=1,i.WIRE_TYPES.LDELIM=2,i.WIRE_TYPES.STARTGROUP=3,i.WIRE_TYPES.ENDGROUP=4,i.WIRE_TYPES.BITS32=5,i.PACKABLE_WIRE_TYPES=[i.WIRE_TYPES.VARINT,i.WIRE_TYPES.BITS64,i.WIRE_TYPES.BITS32],i.TYPES={int32:{name:"int32",wireType:i.WIRE_TYPES.VARINT,defaultValue:0},uint32:{name:"uint32",wireType:i.WIRE_TYPES.VARINT,defaultValue:0},sint32:{name:"sint32",wireType:i.WIRE_TYPES.VARINT,defaultValue:0},int64:{name:"int64",wireType:i.WIRE_TYPES.VARINT,defaultValue:i.Long?i.Long.ZERO:void 0},uint64:{name:"uint64",wireType:i.WIRE_TYPES.VARINT,defaultValue:i.Long?i.Long.UZERO:void 0},sint64:{name:"sint64",wireType:i.WIRE_TYPES.VARINT,defaultValue:i.Long?i.Long.ZERO:void 0},bool:{name:"bool",wireType:i.WIRE_TYPES.VARINT,defaultValue:!1},double:{name:"double",wireType:i.WIRE_TYPES.BITS64,defaultValue:0},string:{name:"string",wireType:i.WIRE_TYPES.LDELIM,defaultValue:""},bytes:{name:"bytes",wireType:i.WIRE_TYPES.LDELIM,defaultValue:null},fixed32:{name:"fixed32",wireType:i.WIRE_TYPES.BITS32,defaultValue:0},sfixed32:{name:"sfixed32",wireType:i.WIRE_TYPES.BITS32,defaultValue:0},fixed64:{name:"fixed64",wireType:i.WIRE_TYPES.BITS64,defaultValue:i.Long?i.Long.UZERO:void 0},sfixed64:{name:"sfixed64",wireType:i.WIRE_TYPES.BITS64,defaultValue:i.Long?i.Long.ZERO:void 0},float:{name:"float",wireType:i.WIRE_TYPES.BITS32,defaultValue:0},enum:{name:"enum",wireType:i.WIRE_TYPES.VARINT,defaultValue:0},message:{name:"message",wireType:i.WIRE_TYPES.LDELIM,defaultValue:null},group:{name:"group",wireType:i.WIRE_TYPES.STARTGROUP,defaultValue:null}},i.MAP_KEY_TYPES=[i.TYPES.int32,i.TYPES.sint32,i.TYPES.sfixed32,i.TYPES.uint32,i.TYPES.fixed32,i.TYPES.int64,i.TYPES.sint64,i.TYPES.sfixed64,i.TYPES.uint64,i.TYPES.fixed64,i.TYPES.bool,i.TYPES.string,i.TYPES.bytes],i.ID_MIN=1,i.ID_MAX=536870911,i.convertFieldsToCamelCase=!1,i.populateAccessors=!0,i.populateDefaults=!0,i.Util=((r={}).IS_NODE=!("object"!=typeof t||t+""!="[object process]"||t.browser),r.XHR=function(){for(var e=[function(){return new XMLHttpRequest},function(){return new ActiveXObject("Msxml2.XMLHTTP")},function(){return new ActiveXObject("Msxml3.XMLHTTP")},function(){return new ActiveXObject("Microsoft.XMLHTTP")}],t=null,n=0;n]/g,RULE:/^(?:required|optional|repeated|map)$/,TYPE:/^(?:double|float|int32|uint32|sint32|int64|uint64|sint64|fixed32|sfixed32|fixed64|sfixed64|bool|string|bytes)$/,NAME:/^[a-zA-Z_][a-zA-Z_0-9]*$/,TYPEDEF:/^[a-zA-Z][a-zA-Z_0-9]*$/,TYPEREF:/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/,FQTYPEREF:/^(?:\.[a-zA-Z_][a-zA-Z_0-9]*)+$/,NUMBER:/^-?(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+|([0-9]*(\.[0-9]*)?([Ee][+-]?[0-9]+)?)|inf|nan)$/,NUMBER_DEC:/^(?:[1-9][0-9]*|0)$/,NUMBER_HEX:/^0[xX][0-9a-fA-F]+$/,NUMBER_OCT:/^0[0-7]+$/,NUMBER_FLT:/^([0-9]*(\.[0-9]*)?([Ee][+-]?[0-9]+)?|inf|nan)$/,BOOL:/^(?:true|false)$/i,ID:/^(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+)$/,NEGID:/^\-?(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+)$/,WHITESPACE:/\s/,STRING:/(?:"([^"\\]*(?:\\.[^"\\]*)*)")|(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,STRING_DQ:/(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,STRING_SQ:/(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g},i.Reflect=function(t){var n={},r=function(e,t,n){this.builder=e,this.parent=t,this.name=n,this.className},i=r.prototype;i.fqn=function(){for(var e=this.name,t=this;;){if(null==(t=t.parent))break;e=t.name+"."+e}return e},i.toString=function(e){return(e?this.className+" ":"")+this.fqn()},i.build=function(){throw Error(this.toString(!0)+" cannot be built directly")},n.T=r;var s=function(e,t,n,i,s){r.call(this,e,t,n),this.className="Namespace",this.children=[],this.options=i||{},this.syntax=s||"proto2"},o=s.prototype=Object.create(r.prototype);o.getChildren=function(e){if(null==(e=e||null))return this.children.slice();for(var t=[],n=0,r=this.children.length;n4294967295?0|n:n;case t.TYPES.uint32:case t.TYPES.fixed32:return("number"!=typeof n||n==n&&n%1!=0)&&i(typeof n,"not an integer"),n<0?n>>>0:n;case t.TYPES.int64:case t.TYPES.sint64:case t.TYPES.sfixed64:if(t.Long)try{return u(n,!1)}catch(e){i(typeof n,e.message)}else i(typeof n,"requires Long.js");case t.TYPES.uint64:case t.TYPES.fixed64:if(t.Long)try{return u(n,!0)}catch(e){i(typeof n,e.message)}else i(typeof n,"requires Long.js");case t.TYPES.bool:return"boolean"!=typeof n&&i(typeof n,"not a boolean"),n;case t.TYPES.float:case t.TYPES.double:return"number"!=typeof n&&i(typeof n,"not a number"),n;case t.TYPES.string:return"string"==typeof n||n&&n instanceof String||i(typeof n,"not a string"),""+n;case t.TYPES.bytes:return e.isByteBuffer(n)?n:e.wrap(n,"base64");case t.TYPES.enum:var s=this.resolvedType.getChildren(t.Reflect.Enum.Value);for(a=0;a4294967295||n<0)&&i(typeof n,"not in range for uint32"),n;i(n,"not a valid enum value");case t.TYPES.group:case t.TYPES.message:if(n&&"object"==typeof n||i(typeof n,"object expected"),n instanceof this.resolvedType.clazz)return n;if(n instanceof t.Builder.Message){var o={};for(var a in n)n.hasOwnProperty(a)&&(o[a]=n[a]);n=o}return new this.resolvedType.clazz(n)}throw Error("[INTERNAL] Illegal value for "+this.toString(!0)+": "+n+" (undefined type "+this.type+")")},l.calculateLength=function(n,r){if(null===r)return 0;var i;switch(this.type){case t.TYPES.int32:return r<0?e.calculateVarint64(r):e.calculateVarint32(r);case t.TYPES.uint32:return e.calculateVarint32(r);case t.TYPES.sint32:return e.calculateVarint32(e.zigZagEncode32(r));case t.TYPES.fixed32:case t.TYPES.sfixed32:case t.TYPES.float:return 4;case t.TYPES.int64:case t.TYPES.uint64:return e.calculateVarint64(r);case t.TYPES.sint64:return e.calculateVarint64(e.zigZagEncode64(r));case t.TYPES.fixed64:case t.TYPES.sfixed64:return 8;case t.TYPES.bool:return 1;case t.TYPES.enum:return e.calculateVarint32(r);case t.TYPES.double:return 8;case t.TYPES.string:return i=e.calculateUTF8Bytes(r),e.calculateVarint32(i)+i;case t.TYPES.bytes:if(r.remaining()<0)throw Error("Illegal value for "+this.toString(!0)+": "+r.remaining()+" bytes remaining");return e.calculateVarint32(r.remaining())+r.remaining();case t.TYPES.message:return i=this.resolvedType.calculate(r),e.calculateVarint32(i)+i;case t.TYPES.group:return(i=this.resolvedType.calculate(r))+e.calculateVarint32(n<<3|t.WIRE_TYPES.ENDGROUP)}throw Error("[INTERNAL] Illegal value to encode in "+this.toString(!0)+": "+r+" (unknown type)")},l.encodeValue=function(n,r,i){if(null===r)return i;switch(this.type){case t.TYPES.int32:r<0?i.writeVarint64(r):i.writeVarint32(r);break;case t.TYPES.uint32:i.writeVarint32(r);break;case t.TYPES.sint32:i.writeVarint32ZigZag(r);break;case t.TYPES.fixed32:i.writeUint32(r);break;case t.TYPES.sfixed32:i.writeInt32(r);break;case t.TYPES.int64:case t.TYPES.uint64:i.writeVarint64(r);break;case t.TYPES.sint64:i.writeVarint64ZigZag(r);break;case t.TYPES.fixed64:i.writeUint64(r);break;case t.TYPES.sfixed64:i.writeInt64(r);break;case t.TYPES.bool:"string"==typeof r?i.writeVarint32("false"===r.toLowerCase()?0:!!r):i.writeVarint32(r?1:0);break;case t.TYPES.enum:i.writeVarint32(r);break;case t.TYPES.float:i.writeFloat32(r);break;case t.TYPES.double:i.writeFloat64(r);break;case t.TYPES.string:i.writeVString(r);break;case t.TYPES.bytes:if(r.remaining()<0)throw Error("Illegal value for "+this.toString(!0)+": "+r.remaining()+" bytes remaining");var s=r.offset;i.writeVarint32(r.remaining()),i.append(r),r.offset=s;break;case t.TYPES.message:var o=(new e).LE();this.resolvedType.encode(r,o),i.writeVarint32(o.offset),i.append(o.flip());break;case t.TYPES.group:this.resolvedType.encode(r,i),i.writeVarint32(n<<3|t.WIRE_TYPES.ENDGROUP);break;default:throw Error("[INTERNAL] Illegal value to encode in "+this.toString(!0)+": "+r+" (unknown type)")}return i},l.decode=function(e,n,r){if(n!=this.type.wireType)throw Error("Unexpected wire type for element");var i,s;switch(this.type){case t.TYPES.int32:return 0|e.readVarint32();case t.TYPES.uint32:return e.readVarint32()>>>0;case t.TYPES.sint32:return 0|e.readVarint32ZigZag();case t.TYPES.fixed32:return e.readUint32()>>>0;case t.TYPES.sfixed32:return 0|e.readInt32();case t.TYPES.int64:return e.readVarint64();case t.TYPES.uint64:return e.readVarint64().toUnsigned();case t.TYPES.sint64:return e.readVarint64ZigZag();case t.TYPES.fixed64:return e.readUint64();case t.TYPES.sfixed64:return e.readInt64();case t.TYPES.bool:return!!e.readVarint32();case t.TYPES.enum:return e.readVarint32();case t.TYPES.float:return e.readFloat();case t.TYPES.double:return e.readDouble();case t.TYPES.string:return e.readVString();case t.TYPES.bytes:if(s=e.readVarint32(),e.remaining()>>3;switch(i){case t.WIRE_TYPES.VARINT:do{r=n.readUint8()}while(128==(128&r));break;case t.WIRE_TYPES.BITS64:n.offset+=8;break;case t.WIRE_TYPES.LDELIM:r=n.readVarint32(),n.offset+=r;break;case t.WIRE_TYPES.STARTGROUP:h(s,n);break;case t.WIRE_TYPES.ENDGROUP:if(s===e)return!1;throw Error("Illegal GROUPEND after unknown group: "+s+" ("+e+" expected)");case t.WIRE_TYPES.BITS32:n.offset+=4;break;default:throw Error("Illegal wire type in unknown group "+e+": "+i)}return!0}f.build=function(n){if(this.clazz&&!n)return this.clazz;var r=function(t,n){var r=n.getChildren(t.Reflect.Message.Field),i=n.getChildren(t.Reflect.Message.OneOf),s=function(o,a){t.Builder.Message.call(this);for(var l=0,u=i.length;l0)if(1!==arguments.length||null===o||"object"!=typeof o||!("function"!=typeof o.encode||o instanceof s)||Array.isArray(o)||o instanceof t.Map||e.isByteBuffer(o)||o instanceof ArrayBuffer||t.Long&&o instanceof t.Long)for(l=0,u=arguments.length;l0;){if(o=(i=e.readVarint32())>>>3,(s=7&i)===t.WIRE_TYPES.ENDGROUP){if(o!==r)throw Error("Illegal group end indicator for "+this.toString(!0)+": "+o+" ("+(r?r+" expected":"not a group")+")");break}if(a=this._fieldsById[o]){if(a.repeated&&!a.options.packed)u[a.name].push(a.decode(s,e));else if(a.map){var c=a.decode(s,e);u[a.name].set(c[0],c[1])}else if(u[a.name]=a.decode(s,e),a.oneof){var f=u[a.oneof.name];null!==f&&f!==a.name&&(u[f]=null),u[a.oneof.name]=a.name}}else switch(s){case t.WIRE_TYPES.VARINT:e.readVarint32();break;case t.WIRE_TYPES.BITS32:e.offset+=4;break;case t.WIRE_TYPES.BITS64:e.offset+=8;break;case t.WIRE_TYPES.LDELIM:var d=e.readVarint32();e.offset+=d;break;case t.WIRE_TYPES.STARTGROUP:for(;h(o,e););break;default:throw Error("Illegal wire type for unknown field "+o+" in "+this.toString(!0)+"#decode: "+s)}}for(var p=0,m=this._fields.length;p0;case t.TYPES.bytes:return e.remaining()>0;case t.TYPES.enum:return 0!==e;case t.TYPES.message:return null!==e;default:return!0}},p.encode=function(n,r,i){if(null===this.type||"object"!=typeof this.type)throw Error("[INTERNAL] Unresolved type in "+this.toString(!0)+": "+this.type);if(null===n||this.repeated&&0==n.length)return r;try{var s;if(this.repeated)if(this.options.packed&&t.PACKABLE_WIRE_TYPES.indexOf(this.type.wireType)>=0){r.writeVarint32(this.id<<3|t.WIRE_TYPES.LDELIM),r.ensureCapacity(r.offset+=1);var o=r.offset;for(s=0;s1){var u=r.slice(o,r.offset);o+=l-1,r.offset=o,r.append(u)}r.writeVarint32(a,o-l)}else for(s=0;s=0){for(i+=e.calculateVarint32(this.id<<3|t.WIRE_TYPES.LDELIM),o=0,s=0;s=0&&!r){s=n.readVarint32(),s=n.offset+s;for(var o=[];n.offset0;){var c=u.readVarint32();e=7&c;var f=c>>>3;if(1===f)l=this.keyElement.decode(u,e,f);else{if(2!==f)throw Error("Unexpected tag in map field key/value submessage");i=this.element.decode(u,e,f)}}return[l,i]}return this.element.decode(n,e,this.id)},n.Message.Field=d;var m=function(e,t,n,r,i,s,o){d.call(this,e,t,n,null,r,i,s,o),this.extension};m.prototype=Object.create(d.prototype),n.Message.ExtensionField=m;n.Message.OneOf=function(e,t,n){r.call(this,e,t,n),this.fields=[]};var g=function(e,t,n,r,i){s.call(this,e,t,n,r,i),this.className="Enum",this.object=null};g.getName=function(e,t){for(var n,r=Object.keys(e),i=0;i0;){if(t=i.pop(),!Array.isArray(t))throw Error("not a valid namespace: "+JSON.stringify(t));for(;t.length>0;){var s=t.shift();if(r.isMessage(s)){var o=new n.Message(this,this.ptr,s.name,s.options,s.isGroup,s.syntax),a={};s.oneofs&&Object.keys(s.oneofs).forEach((function(e){o.addChild(a[e]=new n.Message.OneOf(this,o,e))}),this),s.fields&&s.fields.forEach((function(e){if(null!==o.getChild(0|e.id))throw Error("duplicate or invalid field id in "+o.name+": "+e.id);if(e.options&&"object"!=typeof e.options)throw Error("illegal field options in "+o.name+"#"+e.name);var t=null;if("string"==typeof e.oneof&&!(t=a[e.oneof]))throw Error("illegal oneof in "+o.name+"#"+e.name+": "+e.oneof);e=new n.Message.Field(this,o,e.rule,e.keytype,e.type,e.name,e.id,e.options,t,s.syntax),t&&t.fields.push(e),o.addChild(e)}),this);var l=[];if(s.enums&&s.enums.forEach((function(e){l.push(e)})),s.messages&&s.messages.forEach((function(e){l.push(e)})),s.services&&s.services.forEach((function(e){l.push(e)})),s.extensions&&("number"==typeof s.extensions[0]?o.extensions=[s.extensions]:o.extensions=s.extensions),this.ptr.addChild(o),l.length>0){i.push(t),t=l,l=null,this.ptr=o,o=null;continue}l=null}else if(r.isEnum(s))o=new n.Enum(this,this.ptr,s.name,s.options,s.syntax),s.values.forEach((function(e){o.addChild(new n.Enum.Value(this,o,e.name,e.id))}),this),this.ptr.addChild(o);else if(r.isService(s))o=new n.Service(this,this.ptr,s.name,s.options),Object.keys(s.rpc).forEach((function(e){var t=s.rpc[e];o.addChild(new n.Service.RPCMethod(this,o,e,t.request,t.response,!!t.request_stream,!!t.response_stream,t.options))}),this),this.ptr.addChild(o);else{if(!r.isExtend(s))throw Error("not a valid definition: "+JSON.stringify(s));if(o=this.ptr.resolve(s.ref,!0))s.fields.forEach((function(t){if(null!==o.getChild(0|t.id))throw Error("duplicate extended field id in "+o.name+": "+t.id);if(o.extensions){var r=!1;if(o.extensions.forEach((function(e){t.id>=e[0]&&t.id<=e[1]&&(r=!0)})),!r)throw Error("illegal extended field id in "+o.name+": "+t.id+" (not within valid ranges)")}var i=t.name;this.options.convertFieldsToCamelCase&&(i=e.Util.toCamelCase(i));var s=new n.Message.ExtensionField(this,o,t.rule,t.type,this.ptr.fqn()+"."+i,t.id,t.options),a=new n.Extension(this,this.ptr,t.name,s);s.extension=a,this.ptr.addChild(a),o.addChild(s)}),this);else if(!/\.?google\.protobuf\./.test(s.ref))throw Error("extended message "+s.ref+" is not defined")}s=null,o=null}t=null,this.ptr=this.ptr.parent}return this.resolved=!1,this.result=null,this},i.import=function(t,n){var r="/";if("string"==typeof n){if(e.Util.IS_NODE&&(n=l.resolve(n)),!0===this.files[n])return this.reset();this.files[n]=!0}else if("object"==typeof n){var i,s=n.root;if(e.Util.IS_NODE&&(s=l.resolve(s)),(s.indexOf("\\")>=0||n.file.indexOf("\\")>=0)&&(r="\\"),i=e.Util.IS_NODE?l.join(s,n.file):s+r+n.file,!0===this.files[i])return this.reset();this.files[i]=!0}if(t.imports&&t.imports.length>0){var o,a=!1;"object"==typeof n?(this.importRoot=n.root,a=!0,o=this.importRoot,n=n.file,(o.indexOf("\\")>=0||n.indexOf("\\")>=0)&&(r="\\")):"string"==typeof n?this.importRoot?o=this.importRoot:n.indexOf("/")>=0?""===(o=n.replace(/\/[^\/]*$/,""))&&(o="/"):n.indexOf("\\")>=0?(o=n.replace(/\\[^\\]*$/,""),r="\\"):o=".":o=null;for(var u=0;u0)return function(e){if((e=String(e)).length>100)return;var t=/^((?:\d+)?\-?\d?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!t)return;var n=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*n;case"weeks":case"week":case"w":return 6048e5*n;case"days":case"day":case"d":return n*V;case"hours":case"hour":case"hrs":case"hr":case"h":return n*B;case"minutes":case"minute":case"mins":case"min":case"m":return n*U;case"seconds":case"second":case"secs":case"sec":case"s":return n*F;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}(e);if("number"===n&&!1===isNaN(e))return t.long?function(e){var t=Math.abs(e);if(t>=V)return $(e,t,V,"day");if(t>=B)return $(e,t,B,"hour");if(t>=U)return $(e,t,U,"minute");if(t>=F)return $(e,t,F,"second");return e+" ms"}(e):function(e){var t=Math.abs(e);if(t>=V)return Math.round(e/V)+"d";if(t>=B)return Math.round(e/B)+"h";if(t>=U)return Math.round(e/U)+"m";if(t>=F)return Math.round(e/F)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function $(e,t,n,r){var i=t>=1.5*n;return Math.round(e/n)+" "+r+(i?"s":"")}var q=function(e){function t(e){for(var t=0,r=0;r=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},n.storage=function(){try{return localStorage}catch(e){}}(),n.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"],e.exports=q(n),e.exports.formatters.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}));z.log,z.formatArgs,z.save,z.load,z.useColors,z.storage,z.colors;var W=function(e,t){var n=-1,r=e.length;for(t||(t=Array(r));++n-1&&e%1==0&&e-1&&e%1==0&&e<=9007199254740991},Ie={};Ie["[object Float32Array]"]=Ie["[object Float64Array]"]=Ie["[object Int8Array]"]=Ie["[object Int16Array]"]=Ie["[object Int32Array]"]=Ie["[object Uint8Array]"]=Ie["[object Uint8ClampedArray]"]=Ie["[object Uint16Array]"]=Ie["[object Uint32Array]"]=!0,Ie["[object Arguments]"]=Ie["[object Array]"]=Ie["[object ArrayBuffer]"]=Ie["[object Boolean]"]=Ie["[object DataView]"]=Ie["[object Date]"]=Ie["[object Error]"]=Ie["[object Function]"]=Ie["[object Map]"]=Ie["[object Number]"]=Ie["[object Object]"]=Ie["[object RegExp]"]=Ie["[object Set]"]=Ie["[object String]"]=Ie["[object WeakMap]"]=!1;var Ce=function(e){return pe(e)&&Ae(e.length)&&!!Ie[de(e)]};var Me=function(e){return function(t){return e(t)}},Oe=r((function(e,t){var n=t&&!t.nodeType&&t,r=n&&e&&!e.nodeType&&e,i=r&&r.exports===n&&te.process,s=function(){try{var e=r&&r.require&&r.require("util").types;return e||i&&i.binding&&i.binding("util")}catch(e){}}();e.exports=s})),Re=Oe&&Oe.isTypedArray,Ne=Re?Me(Re):Ce,Pe=Object.prototype.hasOwnProperty;var Le=function(e,t){var n=we(e),r=!n&&be(e),i=!n&&!r&&_e(e),s=!n&&!r&&!i&&Ne(e),o=n||r||i||s,a=o?ee(e.length,String):[],l=a.length;for(var u in e)!t&&!Pe.call(e,u)||o&&("length"==u||i&&("offset"==u||"parent"==u)||s&&("buffer"==u||"byteLength"==u||"byteOffset"==u)||Se(u,l))||a.push(u);return a},xe=Object.prototype;var ke=function(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||xe)};var je=function(e,t){return function(n){return e(t(n))}},De=je(Object.keys,Object),Fe=Object.prototype.hasOwnProperty;var Ue=function(e){if(!ke(e))return De(e);var t=[];for(var n in Object(e))Fe.call(e,n)&&"constructor"!=n&&t.push(n);return t};var Be=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)};var Ve=function(e){if(!Be(e))return!1;var t=de(e);return"[object Function]"==t||"[object GeneratorFunction]"==t||"[object AsyncFunction]"==t||"[object Proxy]"==t};var Ye=function(e){return null!=e&&Ae(e.length)&&!Ve(e)};var $e=function(e){return Ye(e)?Le(e):Ue(e)};var qe=function(e){return null==e?[]:H(e,$e(e))};var ze=function(e){return K(qe(e))};var We=function(e){return(we(e)?X:ze)(e)};function Ge(e,t,n,r,i){var s={};return Object.keys(r).forEach((function(e){s[e]=r[e]})),s.enumerable=!!s.enumerable,s.configurable=!!s.configurable,("value"in s||s.initializer)&&(s.writable=!0),s=n.slice().reverse().reduce((function(n,r){return r(e,t,n)||n}),s),i&&void 0!==s.initializer&&(s.value=s.initializer?s.initializer.call(i):void 0,s.initializer=void 0),void 0===s.initializer&&(Object.defineProperty(e,t,s),s=null),s}var Je=r((function(e,t){var n;n={VERSION:"2.4.0",Result:{SUCCEEDED:1,NOTRANSITION:2,CANCELLED:3,PENDING:4},Error:{INVALID_TRANSITION:100,PENDING_TRANSITION:200,INVALID_CALLBACK:300},WILDCARD:"*",ASYNC:"async",create:function(e,t){var r="string"==typeof e.initial?{state:e.initial}:e.initial,i=e.terminal||e.final,s=t||e.target||{},o=e.events||[],a=e.callbacks||{},l={},u={},c=function(e){var t=Array.isArray(e.from)?e.from:e.from?[e.from]:[n.WILDCARD];l[e.name]=l[e.name]||{};for(var r=0;r=0:this.current===e},s.can=function(e){return!this.transition&&void 0!==l[e]&&(l[e].hasOwnProperty(this.current)||l[e].hasOwnProperty(n.WILDCARD))},s.cannot=function(e){return!this.can(e)},s.transitions=function(){return(u[this.current]||[]).concat(u[n.WILDCARD]||[])},s.isFinished=function(){return this.is(i)},s.error=e.error||function(e,t,n,r,i,s,o){throw o||s},s.states=function(){return Object.keys(u).sort()},r&&!r.defer&&s[r.event](),s},doCallback:function(e,t,r,i,s,o){if(t)try{return t.apply(e,[r,i,s].concat(o))}catch(t){return e.error(r,i,s,o,n.Error.INVALID_CALLBACK,"an exception occurred in a caller-provided callback function",t)}},beforeAnyEvent:function(e,t,r,i,s){return n.doCallback(e,e.onbeforeevent,t,r,i,s)},afterAnyEvent:function(e,t,r,i,s){return n.doCallback(e,e.onafterevent||e.onevent,t,r,i,s)},leaveAnyState:function(e,t,r,i,s){return n.doCallback(e,e.onleavestate,t,r,i,s)},enterAnyState:function(e,t,r,i,s){return n.doCallback(e,e.onenterstate||e.onstate,t,r,i,s)},changeState:function(e,t,r,i,s){return n.doCallback(e,e.onchangestate,t,r,i,s)},beforeThisEvent:function(e,t,r,i,s){return n.doCallback(e,e["onbefore"+t],t,r,i,s)},afterThisEvent:function(e,t,r,i,s){return n.doCallback(e,e["onafter"+t]||e["on"+t],t,r,i,s)},leaveThisState:function(e,t,r,i,s){return n.doCallback(e,e["onleave"+r],t,r,i,s)},enterThisState:function(e,t,r,i,s){return n.doCallback(e,e["onenter"+i]||e["on"+i],t,r,i,s)},beforeEvent:function(e,t,r,i,s){if(!1===n.beforeThisEvent(e,t,r,i,s)||!1===n.beforeAnyEvent(e,t,r,i,s))return!1},afterEvent:function(e,t,r,i,s){n.afterThisEvent(e,t,r,i,s),n.afterAnyEvent(e,t,r,i,s)},leaveState:function(e,t,r,i,s){var o=n.leaveThisState(e,t,r,i,s),a=n.leaveAnyState(e,t,r,i,s);return!1!==o&&!1!==a&&(n.ASYNC===o||n.ASYNC===a?n.ASYNC:void 0)},enterState:function(e,t,r,i,s){n.enterThisState(e,t,r,i,s),n.enterAnyState(e,t,r,i,s)},buildEvent:function(e,t){return function(){var r=this.current,i=t[r]||(t[n.WILDCARD]!=n.WILDCARD?t[n.WILDCARD]:r)||r,s=Array.prototype.slice.call(arguments);if(this.transition)return this.error(e,r,i,s,n.Error.PENDING_TRANSITION,"event "+e+" inappropriate because previous transition did not complete");if(this.cannot(e))return this.error(e,r,i,s,n.Error.INVALID_TRANSITION,"event "+e+" inappropriate in current state "+this.current);if(!1===n.beforeEvent(this,e,r,i,s))return n.Result.CANCELLED;if(r===i)return n.afterEvent(this,e,r,i,s),n.Result.NOTRANSITION;var o=this;this.transition=function(){return o.transition=null,o.current=i,n.enterState(o,e,r,i,s),n.changeState(o,e,r,i,s),n.afterEvent(o,e,r,i,s),n.Result.SUCCEEDED},this.transition.cancel=function(){o.transition=null,n.afterEvent(o,e,r,i,s)};var a=n.leaveState(this,e,r,i,s);return!1===a?(this.transition=null,n.Result.CANCELLED):n.ASYNC===a?n.Result.PENDING:this.transition?this.transition():void 0}}},e.exports&&(t=e.exports=n),t.StateMachine=n}));Je.StateMachine;const Ze={},Ke=e=>{const t=Ze[e];if(void 0===t)throw new Error(`${e} adapter is not configured`);return t};var Xe=je(Object.getPrototypeOf,Object),Qe=Function.prototype,He=Object.prototype,et=Qe.toString,tt=He.hasOwnProperty,nt=et.call(Object);var rt=function(e){if(!pe(e)||"[object Object]"!=de(e))return!1;var t=Xe(e);if(null===t)return!0;var n=tt.call(t,"constructor")&&t.constructor;return"function"==typeof n&&n instanceof n&&et.call(n)==nt},it="undefined"!=typeof global?global:"undefined"!=typeof window?window:{};const st=Symbol("expired"),ot=z("LC:Expirable");class at{constructor(e,t){this.originalValue=e,"number"==typeof t&&(this.expiredAt=Date.now()+t)}get value(){const e=this.expiredAt&&this.expiredAt<=Date.now();return e&&ot(`expired: ${this.originalValue}`),e?st:this.originalValue}}at.EXPIRED=st;const lt=z("LC:Cache");class ut{constructor(e="anonymous"){this.name=e,this._map={}}get(e){const t=this._map[e];if(t){const{value:n}=t;if(n!==at.EXPIRED)return lt("[%s] hit: %s",this.name,e),n;delete this._map[e]}return lt(`[${this.name}] missed: ${e}`),null}set(e,t,n){lt("[%s] set: %s %d",this.name,e,n),this._map[e]=new at(t,n)}}const ct={enable:(e="LC*")=>z.enable(e),disable:z.disable},ft=e=>{const t=new Promise(e[0]);return 1===e.length?t:t.catch(()=>ft(e.slice(1)))},ht=e=>t=>(e(t),t),dt=e=>e?"string"==typeof e||"number"==typeof e?new Date(e):"Date"===e.__type&&e.iso?new Date(e.iso):"function"==typeof e.toNumber?new Date(e.toNumber()):e:e,pt=e=>e&&e.getTime?e.getTime():void 0,mt=e=>e?"Date"===e.__type&&e.iso?new Date(e.iso):Array.isArray(e)?e.map(mt):rt(e)?Object.keys(e).reduce((t,n)=>({...t,[n]:mt(e[n])}),{}):e:e,gt=e=>e instanceof Date?{__type:"Date",iso:e.toJSON()}:Array.isArray(e)?e.map(gt):rt(e)?Object.keys(e).reduce((t,n)=>({...t,[n]:gt(e[n])}),{}):e,yt=(e,t)=>Object.keys(t).reduce((n,r)=>{const i=e[r]||r;return Object.assign(n,{[i]:t[r]})},{}),vt=it.navigator&&it.navigator.userAgent&&-1!==it.navigator.userAgent.indexOf("MSIE 10."),bt=(e,t)=>e[t]||(e.__proto__?bt(e.__proto__,t):void 0),wt=(e,t)=>Array.from(new Set([...e,...t])),Et=(e,t)=>{return Array.from((n=new Set(t),new Set(e.filter(e=>!n.has(e)))));var n},_t=new WeakMap,Tt=e=>(_t.has(e)||_t.set(e,{}),_t.get(e)),St=(e,t)=>{if(!rt(e))return e;const n={...e};return Object.keys(n).forEach(e=>{const r=n[e];r===t?delete n[e]:n[e]=St(r,t)}),n},At=e=>{return t=JSON.parse(JSON.stringify(e)),St(t,null);var t},It=e=>Array.isArray(e)?e:null==e?[]:[e],Ct=(e,t,n)=>{const r=t.split("."),i=r.pop();let s=e;return r.forEach(e=>{void 0===s[e]&&(s[e]={}),s=s[e]}),s[i]=n,e},Mt="object"==typeof wx&&"function"==typeof wx.connectSocket,Ot=e=>(t,n,r)=>{const i=r.value;if(i.length)throw new Error("throttled function should not accept any arguments");return{...r,value(){let{throttleMeta:t}=Tt(this);t||(t={},Tt(this).throttleMeta=t);let{[n]:r}=t;r||(r={},t[n]=r);const{previouseTimestamp:s=0,timeout:o}=r,a=Date.now(),l=e-(a-s);l<=0?(t[n].previouseTimestamp=a,i.apply(this)):o||(r.timeout=setTimeout(()=>{r.previouseTimestamp=Date.now(),delete r.timeout,i.apply(this)},l))}}};var Rt;const Nt=z("LC:WebSocketPlus"),Pt="disconnect",Lt="reconnect",xt="retry",kt="schedule",jt="offline",Dt="online",Ft=e=>Math.min(1e3*2**e,3e5),Ut=(e,t,n)=>({...n,value:function(...e){return this.checkConnectionAvailability(t),n.value.call(this,...e)}});let Bt=(Ge((Rt=class extends D{get urls(){return this._urls}set urls(e){this._urls=It(e)}constructor(e,t){super(),this.init(),this._protocol=t,Promise.resolve("function"==typeof e?e():e).then(It).then(e=>(this._urls=e,this._open())).then(()=>{this.__postponeTimeoutTimer=this._postponeTimeoutTimer.bind(this),it.addEventListener&&(this.__pause=()=>{this.can("pause")&&this.pause()},this.__resume=()=>{this.can("resume")&&this.resume()},it.addEventListener("offline",this.__pause),it.addEventListener("online",this.__resume)),this.open()}).catch(this.throw.bind(this))}_open(){return this._createWs(this._urls,this._protocol).then(e=>{const[t,...n]=this._urls;return this._urls=[...n,t],e})}_createWs(e,t){return ft(e.map(e=>(n,r)=>{Nt(`connect [${e}] ${t}`);const i=Ke("WebSocket"),s=t?new i(e,t):new i(e);s.binaryType=this.binaryType||"arraybuffer",s.onopen=()=>n(s),s.onclose=t=>t instanceof Error?r(t):r(new Error(`Failed to connect [${e}]`)),s.onerror=s.onclose})).then(e=>(this._ws=e,this._ws.onclose=this._handleClose.bind(this),this._ws.onmessage=this._handleMessage.bind(this),e))}_destroyWs(){const e=this._ws;e&&(e.onopen=null,e.onclose=null,e.onerror=null,e.onmessage=null,this._ws=null,e.close())}onbeforeevent(e,t,n,...r){Nt(`${e}: ${t} -> ${n} %o`,r)}onopen(){this.emit("open")}onconnected(){this._startConnectionKeeper()}onleaveconnected(e,t,n){this._stopConnectionKeeper(),this._destroyWs(),"offline"!==n&&"disconnected"!==n||this.emit(Pt)}onpause(){this.emit(jt)}onbeforeresume(){this.emit(Dt)}onreconnect(){this.emit(Lt)}ondisconnected(e,t,n,r=0){const i=t===jt?0:Ft.call(null,r);Nt(`schedule attempt=${r} delay=${i}`),this.emit(kt,r,i),this.__scheduledRetry&&clearTimeout(this.__scheduledRetry),this.__scheduledRetry=setTimeout(()=>{this.is("disconnected")&&this.retry(r)},i)}onretry(e,t,n,r=0){this.emit(xt,r),this._open().then(()=>this.can("reconnect")&&this.reconnect(),()=>this.can("fail")&&this.fail(r+1))}onerror(e,t,n,r){this.emit("error",r)}onclose(){it.removeEventListener&&(this.__pause&&it.removeEventListener("offline",this.__pause),this.__resume&&it.removeEventListener("online",this.__resume))}checkConnectionAvailability(e="API"){if(!this.is("connected")){const t=this.current;throw console.warn(`${e} should not be called when the connection is ${t}`),(this.is("disconnected")||this.is("reconnecting"))&&console.warn("disconnect and reconnect event should be handled to avoid such calls."),new Error("Connection unavailable")}}_ping(){Nt("ping");try{this.ping()}catch(e){console.warn(`websocket ping error: ${e.message}`)}}ping(){this._ws.ping?this._ws.ping():console.warn("The WebSocket implement does not support sending ping frame.\n Override ping method to use application defined ping/pong mechanism.")}_postponeTimeoutTimer(){Nt("_postponeTimeoutTimer"),this._clearTimeoutTimers(),this._timeoutTimer=setTimeout(()=>{Nt("timeout"),this.disconnect()},38e4)}_clearTimeoutTimers(){this._timeoutTimer&&clearTimeout(this._timeoutTimer)}_startConnectionKeeper(){Nt("start connection keeper"),this._heartbeatTimer=setInterval(this._ping.bind(this),18e4);const e=this._ws.addListener||this._ws.addEventListener;e?(e.call(this._ws,"message",this.__postponeTimeoutTimer),e.call(this._ws,"pong",this.__postponeTimeoutTimer),this._postponeTimeoutTimer()):Nt("connection keeper disabled due to the lack of #addEventListener.")}_stopConnectionKeeper(){Nt("stop connection keeper");const e=this._ws.removeListener||this._ws.removeEventListener;e&&(e.call(this._ws,"message",this.__postponeTimeoutTimer),e.call(this._ws,"pong",this.__postponeTimeoutTimer),this._clearTimeoutTimers()),this._heartbeatTimer&&clearInterval(this._heartbeatTimer)}_handleClose(e){Nt(`ws closed [${e.code}] ${e.reason}`),this.isFinished()||this.handleClose(e)}handleClose(){this.disconnect()}send(e){Nt("send",e),this._ws.send(e)}_handleMessage(e){Nt("message",e.data),this.handleMessage(e.data)}handleMessage(e){this.emit("message",e)}}).prototype,"_ping",[Ut],Object.getOwnPropertyDescriptor(Rt.prototype,"_ping"),Rt.prototype),Ge(Rt.prototype,"send",[Ut],Object.getOwnPropertyDescriptor(Rt.prototype,"send"),Rt.prototype),Rt);Je.create({target:Bt.prototype,initial:{state:"initialized",event:"init",defer:!0},terminal:"closed",events:[{name:"open",from:"initialized",to:"connected"},{name:"disconnect",from:"connected",to:"disconnected"},{name:"retry",from:"disconnected",to:"reconnecting"},{name:"fail",from:"reconnecting",to:"disconnected"},{name:"reconnect",from:"reconnecting",to:"connected"},{name:"pause",from:["connected","disconnected","reconnecting"],to:"offline"},{},{name:"resume",from:"offline",to:"disconnected"},{name:"close",from:["connected","disconnected","reconnecting","offline"],to:"closed"},{name:"throw",from:"*",to:"error"}]});const Vt=Object.freeze({1e3:{name:"CLOSE_NORMAL"},1006:{name:"CLOSE_ABNORMAL"},4100:{name:"APP_NOT_AVAILABLE",message:"App not exists or realtime message service is disabled."},4102:{name:"SIGNATURE_FAILED",message:"Login signature mismatch."},4103:{name:"INVALID_LOGIN",message:"Malformed clientId."},4105:{name:"SESSION_REQUIRED",message:"Message sent before session opened."},4107:{name:"READ_TIMEOUT"},4108:{name:"LOGIN_TIMEOUT"},4109:{name:"FRAME_TOO_LONG"},4110:{name:"INVALID_ORIGIN",message:"Access denied by domain whitelist."},4111:{name:"SESSION_CONFLICT"},4112:{name:"SESSION_TOKEN_EXPIRED"},4113:{name:"APP_QUOTA_EXCEEDED",message:"The daily active users limit exceeded."},4116:{name:"MESSAGE_SENT_QUOTA_EXCEEDED",message:"Command sent too fast."},4200:{name:"INTERNAL_ERROR",message:"Internal error, please contact LeanCloud for support."},4301:{name:"CONVERSATION_API_FAILED",message:"Upstream Conversatoin API failed, see error.detail for details."},4302:{name:"CONVERSATION_SIGNATURE_FAILED",message:"Conversation action signature mismatch."},4303:{name:"CONVERSATION_NOT_FOUND"},4304:{name:"CONVERSATION_FULL"},4305:{name:"CONVERSATION_REJECTED_BY_APP",message:"Conversation action rejected by hook."},4306:{name:"CONVERSATION_UPDATE_FAILED"},4307:{name:"CONVERSATION_READ_ONLY"},4308:{name:"CONVERSATION_NOT_ALLOWED"},4309:{name:"CONVERSATION_UPDATE_REJECTED",message:"Conversation update rejected because the client is not a member."},4310:{name:"CONVERSATION_QUERY_FAILED",message:"Conversation query failed because it is too expansive."},4311:{name:"CONVERSATION_LOG_FAILED"},4312:{name:"CONVERSATION_LOG_REJECTED",message:"Message query rejected because the client is not a member of the conversation."},4313:{name:"SYSTEM_CONVERSATION_REQUIRED"},4314:{name:"NORMAL_CONVERSATION_REQUIRED"},4315:{name:"CONVERSATION_BLACKLISTED",message:"Blacklisted in the conversation."},4316:{name:"TRANSIENT_CONVERSATION_REQUIRED"},4317:{name:"CONVERSATION_MEMBERSHIP_REQUIRED"},4318:{name:"CONVERSATION_API_QUOTA_EXCEEDED",message:"LeanCloud API quota exceeded. You may upgrade your plan."},4323:{name:"TEMPORARY_CONVERSATION_EXPIRED",message:"Temporary conversation expired or does not exist."},4401:{name:"INVALID_MESSAGING_TARGET",message:"Conversation does not exist or client is not a member."},4402:{name:"MESSAGE_REJECTED_BY_APP",message:"Message rejected by hook."},4403:{name:"MESSAGE_OWNERSHIP_REQUIRED"},4404:{name:"MESSAGE_NOT_FOUND"},4405:{name:"MESSAGE_UPDATE_REJECTED_BY_APP",message:"Message update rejected by hook."},4406:{name:"MESSAGE_EDIT_DISABLED"},4407:{name:"MESSAGE_RECALL_DISABLED"},5130:{name:"OWNER_PROMOTION_NOT_ALLOWED",message:"Updating a member's role to owner is not allowed."}}),Yt=Object.freeze(Object.keys(Vt).reduce((e,t)=>Object.assign(e,{[Vt[t].name]:Number(t)}),{})),$t=({code:e,reason:t,appCode:n,detail:r,error:i})=>{let s=t||r||i,o=t;!s&&Vt[e]&&(({name:o}=Vt[e]),s=Vt[e].message||o),s||(s=`Unknow Error: ${e}`);const a=new Error(s);return Object.assign(a,{code:e,appCode:n,detail:r,name:o})},qt=z("LC:Connection"),zt=Symbol("expire");class Wt extends Bt{constructor(e,{format:t,version:n}){qt("initializing Connection"),super(e,`lc.${t}.${n}`),this._protocolFormat=t,this._commands={},this._serialId=0}async send(e,t=!0){let n,r,i;if(t){if((e=>!(e.cmd===L.direct||e.cmd===L.session&&e.op===x.open||e.cmd===L.conv&&(e.op===x.start||e.op===x.update||e.op===x.members)))(e)){n=e.toArrayBuffer();const t=qe(this._commands).find(({buffer:t,command:r})=>r.cmd===e.cmd&&r.op===e.op&&((e,t)=>{if(!e||!t)return!1;if(e.byteLength!==t.byteLength)return!1;const n=new Uint8Array(e),r=new Uint8Array(t);return!n.some((e,t)=>e!==r[t])})(t,n));if(t)return console.warn(`Duplicated command [cmd:${e.cmd} op:${e.op}] is throttled.`),t.promise}this._serialId+=1,r=this._serialId,e.i=r}if(qt.enabled&&qt("↑ %O sent",At(e)),"proto2base64"===this._protocolFormat?i=e.toBase64():e.toArrayBuffer&&(i=e.toArrayBuffer()),!i)throw new TypeError(`${e} is not a GenericCommand`);if(super.send(i),!t)return;const s=new Promise((t,i)=>{this._commands[r]={command:e,buffer:n,resolve:t,reject:i,timeout:setTimeout(()=>{this._commands[r]&&(qt.enabled&&qt("✗ %O timeout",At(e)),i($t({error:`Command Timeout [cmd:${e.cmd} op:${e.op}]`,name:"COMMAND_TIMEOUT"})),delete this._commands[r])},2e4)}});return this._commands[r].promise=s,s}handleMessage(e){let t;try{t=M.decode(e),qt.enabled&&qt("↓ %O received",At(t))}catch(t){return void console.warn("Decode message failed:",t.message,e)}const n=t.i;if(n)this._commands[n]?(clearTimeout(this._commands[n].timeout),t.cmd===L.error?this._commands[n].reject($t(t.errorMessage)):this._commands[n].resolve(t),delete this._commands[n]):console.warn(`Unexpected command received with serialId [${n}],\n which have timed out or never been requested.`);else switch(t.cmd){case L.error:return void this.emit("error",$t(t.errorMessage));case L.goaway:return void this.emit(zt);default:this.emit("message",t)}}ping(){return this.send(new M({cmd:L.echo})).catch(e=>qt("ping failed:",e))}}var Gt=r((function(e){var t;e.exports.timeout=function(e,n){var r,i=new t;return Promise.race([e,new Promise((function(e,t){r=setTimeout((function(){t(i)}),n)}))]).then((function(e){return clearTimeout(r),e}),(function(e){throw clearTimeout(r),e}))};(t=e.exports.TimeoutError=function(){Error.call(this),this.stack=Error().stack,this.message="Timeout"}).prototype=Object.create(Error.prototype),t.prototype.name="TimeoutError"})),Jt=Gt.timeout;Gt.TimeoutError;const Zt=z("LC:request");var Kt=({method:e="GET",url:t,query:n,headers:r,data:i,timeout:s})=>{let o=t;if(n){const e=Object.keys(n).map(e=>{const t=n[e];if(void 0===t)return;const r=rt(t)?JSON.stringify(t):t;return`${encodeURIComponent(e)}=${encodeURIComponent(r)}`}).filter(e=>e).join("&");o=`${o}?${e}`}Zt("Req: %O %O %O",e,o,{headers:r,data:i});const a=Ke("request")(o,{method:e,headers:r,data:i}).then(e=>{if(!1===e.ok){const t=$t(e.data);throw t.response=e,t}return Zt("Res: %O %O %O",o,e.status,e.data),e.data}).catch(e=>{throw e.response&&Zt("Error: %O %O %O",o,e.response.status,e.response.data),e});return s?Jt(a,s):a};const Xt=(e,t)=>{e&&e.forEach(e=>{try{e(t)}catch(t){throw e._pluginName&&(t.message+=`[${e._pluginName}]`),t}})},Qt=e=>t=>It(e).reduce((e,t)=>e.then((e=>t=>{const{constructor:n}=t;return Promise.resolve(t).then(e).then(ht(r=>null==r?console.warn(`Middleware[${e._pluginName||"anonymous plugin"}:${e.name||"anonymous middleware"}] param/return types not match. It returns ${r} while a ${t.constructor.name} expected.`):r instanceof n?0:console.warn(`Middleware[${e._pluginName||"anonymous plugin"}:${e.name||"anonymous middleware"}] param/return types not match. It returns a ${r.constructor.name} while a ${t.constructor.name} expected.`)))})(t)).catch(e=>{throw t._pluginName&&(e.message+=`[${t._pluginName}]`),e}),Promise.resolve(t)),Ht=(e,t)=>It(e).reduce((e,n)=>e.then(e=>!1!==e&&n(...t)).catch(e=>{throw n._pluginName&&(e.message+=`[${n._pluginName}]`),e}),Promise.resolve(!0));const en=z("LC:Realtime"),tn=new ut("push-router"),nn={};class rn extends D{constructor({plugins:e,...n}){en("initializing Realtime %s %O","5.0.0-rc.7",n),super();const{appId:r}=n;if("string"!=typeof r)throw new TypeError(`appId [${r}] is not a string`);if(nn[r])throw new Error(`App [${r}] is already initialized.`);if(nn[r]=!0,"string"!=typeof n.appKey)throw new TypeError(`appKey [${n.appKey}] is not a string`);if((e=>"-MdYXbMMI"!==e.slice(-9))(r)&&!n.server)throw new TypeError("server option is required for apps from CN region");this._options={appId:void 0,appKey:void 0,noBinary:!1,ssl:!0,RTMServerName:void 0!==t?t.env.RTM_SERVER_NAME:void 0,...n},this._cache=new ut("endpoints");const i=Tt(this);i.clients=new Set,i.pendingClients=new Set;const s=[...It(rn.__preRegisteredPlugins),...It(e)];en("Using plugins %o",s.map(e=>e.name)),this._plugins=s.reduce((e,t)=>(Object.keys(t).forEach(n=>{({}).hasOwnProperty.call(t,n)&&"name"!==n&&(t.name&&It(t[n]).forEach(e=>{e._pluginName=t.name}),e[n]=It(e[n]).concat(t[n]))}),e),{}),Xt(this._plugins.onRealtimeCreate,this)}async _request({method:e,url:t,version:n="1.1",path:r,query:i,headers:s,data:o}){let a=t;if(!a){const{appId:e,server:t}=this._options,{api:i}=await this.constructor._getServerUrls({appId:e,server:t});a=`${i}/${n}${r}`}return Kt({url:a,method:e,query:i,headers:{"X-LC-Id":this._options.appId,"X-LC-Key":this._options.appKey,...s},data:o})}_open(){if(this._openPromise)return this._openPromise;let e="protobuf2";this._options.noBinary&&(e="proto2base64");const t={format:e,version:3};return this._openPromise=new Promise((e,n)=>{en("No connection established, create a new one.");const r=new Wt(()=>this._getRTMServers(this._options),t);r.on("open",()=>e(r)).on("error",e=>{delete this._openPromise,n(e)}).on(zt,async()=>{en("Connection expired. Refresh endpoints."),this._cache.set("endpoints",null,0),r.urls=await this._getRTMServers(this._options),r.disconnect()}).on("message",this._dispatchCommand.bind(this)),[Pt,Lt,xt,kt,jt,Dt].forEach(e=>r.on(e,(...t)=>{en(`${e} event emitted. %o`,t),this.emit(e,...t),e!==Lt&&Tt(this).clients.forEach(n=>{n.emit(e,...t)})})),r.handleClose=function(e){[Yt.APP_NOT_AVAILABLE,Yt.INVALID_LOGIN,Yt.INVALID_ORIGIN].some(t=>t===e.code)?this.throw($t(e)):this.disconnect()},Tt(this).connection=r}),this._openPromise}async _getRTMServers(e){if(e.RTMServers)return We(It(e.RTMServers));let t;const n=this._cache.get("endpoints");if(n)t=n;else{t=await this.constructor._fetchRTMServers(e);const{server:n,secondary:r,ttl:i}=t;if("string"!=typeof n&&"string"!=typeof r&&"number"!=typeof i)throw new Error(`malformed RTM route response: ${JSON.stringify(t)}`);this._cache.set("endpoints",t,1e3*t.ttl)}return en("endpoint info: %O",t),[t.server,t.secondary]}static async _getServerUrls({appId:e,server:t}){if(en("fetch server urls"),t)return"string"!=typeof t?t:{RTMRouter:t,api:t};const n=tn.get(e);if(n)return n;return Kt({url:"https://app-router.com/2/route",query:{appId:e},timeout:2e4}).then(ht(en)).then(({rtm_router_server:t,api_server:n,ttl:r=3600})=>{if(!t)throw new Error("rtm router not exists");const i={RTMRouter:`https://${t}`,api:`https://${n}`};return tn.set(e,i,1e3*r),i}).catch(()=>{const t=e.slice(0,8).toLowerCase();return{RTMRouter:`https://${t}.rtm.lncldglobal.com`,api:`https://${t}.api.lncldglobal.com`}})}static _fetchRTMServers({appId:e,ssl:t,server:n,RTMServerName:r}){return en("fetch endpoint info"),this._getServerUrls({appId:e,server:n}).then(ht(en)).then(({RTMRouter:n})=>Kt({url:`${n}/v1/route`,query:{appId:e,secure:t,features:Mt?"wechat":void 0,server:r,_t:Date.now()},timeout:2e4}).then(ht(en)))}_close(){this._openPromise&&this._openPromise.then(e=>e.close()),delete this._openPromise}retry(){const{connection:e}=Tt(this);if(!e)throw new Error("no connection established");if(e.cannot("retry"))throw new Error(`retrying not allowed when not disconnected. the connection is now ${e.current}`);return e.retry()}pause(){const{connection:e}=Tt(this);e&&e.can("pause")&&e.pause()}resume(){const{connection:e}=Tt(this);e&&e.can("resume")&&e.resume()}_registerPending(e){Tt(this).pendingClients.add(e)}_deregisterPending(e){Tt(this).pendingClients.delete(e)}_register(e){Tt(this).clients.add(e)}_deregister(e){const t=Tt(this);t.clients.delete(e),t.clients.size+t.pendingClients.size===0&&this._close()}_dispatchCommand(e){return Ht(this._plugins.beforeCommandDispatch,[e,this]).then(t=>!!t&&en("[WARN] Unexpected message received: %O",At(e)))}}const sn=Promise;for(var on=r((function(e){var t="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof window.msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto);if(t){var n=new Uint8Array(16);e.exports=function(){return t(n),n}}else{var r=new Array(16);e.exports=function(){for(var e,t=0;t<16;t++)0==(3&t)&&(e=4294967296*Math.random()),r[t]=e>>>((3&t)<<3)&255;return r}}})),an=[],ln=0;ln<256;++ln)an[ln]=(ln+256).toString(16).substr(1);var un=function(e,t){var n=t||0,r=an;return[r[e[n++]],r[e[n++]],r[e[n++]],r[e[n++]],"-",r[e[n++]],r[e[n++]],"-",r[e[n++]],r[e[n++]],"-",r[e[n++]],r[e[n++]],"-",r[e[n++]],r[e[n++]],r[e[n++]],r[e[n++]],r[e[n++]],r[e[n++]]].join("")};var cn=function(e,t,n){var r=t&&n||0;"string"==typeof e&&(t="binary"===e?new Array(16):null,e=null);var i=(e=e||{}).random||(e.rng||on)();if(i[6]=15&i[6]|64,i[8]=63&i[8]|128,t)for(var s=0;s<16;++s)t[r+s]=i[s];return t||un(i)},fn=r((function(e,t){!function(){for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n=new Uint8Array(256),r=0;r>2],s+=e[(3&r[n])<<4|r[n+1]>>4],s+=e[(15&r[n+1])<<2|r[n+2]>>6],s+=e[63&r[n+2]];return i%3==2?s=s.substring(0,s.length-1)+"=":i%3==1&&(s=s.substring(0,s.length-2)+"=="),s},t.decode=function(e){var t,r,i,s,o,a=.75*e.length,l=e.length,u=0;"="===e[e.length-1]&&(a--,"="===e[e.length-2]&&a--);var c=new ArrayBuffer(a),f=new Uint8Array(c);for(t=0;t>4,f[u++]=(15&i)<<4|s>>2,f[u++]=(3&s)<<6|63&o;return c}}()})),hn=fn.encode,dn=fn.decode;var pn=function(){this.__data__=[],this.size=0};var mn=function(e,t){return e===t||e!=e&&t!=t};var gn=function(e,t){for(var n=e.length;n--;)if(mn(e[n][0],t))return n;return-1},yn=Array.prototype.splice;var vn=function(e){var t=this.__data__,n=gn(t,e);return!(n<0)&&(n==t.length-1?t.pop():yn.call(t,n,1),--this.size,!0)};var bn=function(e){var t=this.__data__,n=gn(t,e);return n<0?void 0:t[n][1]};var wn=function(e){return gn(this.__data__,e)>-1};var En=function(e,t){var n=this.__data__,r=gn(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this};function _n(e){var t=-1,n=null==e?0:e.length;for(this.clear();++ta))return!1;var u=s.get(e),c=s.get(t);if(u&&c)return u==t&&c==e;var f=-1,h=!0,d=2&n?new mr:void 0;for(s.set(e,t),s.set(t,e);++fi?0:i+t),(n=n>i?i:n)<0&&(n+=i),i=t>n?0:n-t>>>0,t>>>=0;for(var s=Array(i);++r-1?i[s?t[o]:o]:void 0}};var _s=function(e,t,n,r){for(var i=e.length,s=n+(r?1:-1);r?s--:++s-1)}getMentionList(){return this.mentionList}setMentionList(e){return this.mentionList=It(e),this}mentionAll(e=!0){return this.mentionedAll=Boolean(e),this}static validate(){return!0}static parse(e,t){return t||new this(e)}}const Bs=e=>{if("number"!=typeof e)throw new TypeError(`${e} is not a Number`);return t=>{t.TYPE=e,t.validate=t=>t._lctype===e,t.prototype._getType=()=>({_lctype:e})}},Vs=e=>{if("string"!=typeof e){if(!Array.isArray(e))throw new TypeError(`${e} is not an Array`);if(e.some(e=>"string"!=typeof e))throw new TypeError("fields contains non-string typed member")}return t=>{let n=vt?bt(t,"_customFields"):t._customFields;n=Array.isArray(n)?n:[],t._customFields=n.concat(e)}},Ys=e=>{vt&&(e.parse=bt(e,"parse"))};var $s;let qs=Vs(["_lctext","_lcattrs"])($s=class extends Us{get type(){return this.constructor.TYPE}set text(e){return this.setText(e)}get text(){return this.getText()}set attributes(e){return this.setAttributes(e)}get attributes(){return this.getAttributes()}get summary(){return this.text}setText(e){return this._lctext=e,this}getText(){return this._lctext}setAttributes(e){return this._lcattrs=e,this}getAttributes(){return this._lcattrs}_getCustomFields(){return(Array.isArray(this.constructor._customFields)?this.constructor._customFields:[]).reduce((e,t)=>("string"!=typeof t||(e[t]=this[t]),e),{})}_getType(){throw new Error("not implemented")}getPayload(){return St({_lctext:this.getText(),_lcattrs:this.getAttributes(),...this._getCustomFields(),...this._getType()})}toJSON(){const{type:e,text:t,attributes:n,summary:r}=this;return{...super._toJSON(),type:e,text:t,attributes:n,summary:r}}toFullJSON(){return{...super.toFullJSON(),data:this.getPayload()}}static parse(e,t=new this){t.content=e;const n=vt?bt(t.constructor,"_customFields"):t.constructor._customFields;let r=Array.isArray(n)?n:[];return r=r.reduce((t,n)=>("string"!=typeof n||(t[n]=e[n]),t),{}),Object.assign(t,r),super.parse(e,t)}})||$s;var zs;let Ws=Bs(-127)(zs=Ys(zs=class extends qs{get summary(){return"[该消息已撤回]"}})||zs)||zs;const Gs=z("LC:Conversation"),Js=e=>{const t=e.getPayload();let n,r;return t instanceof ArrayBuffer?r=t:n="string"!=typeof t?JSON.stringify(t):t,{msg:n,binaryMsg:r}},{NEW:Zs,OLD:Ks}=E.QueryDirection,Xs={NEW_TO_OLD:Ks,OLD_TO_NEW:Zs};Object.freeze(Xs);class Qs extends D{constructor({id:e,lastMessageAt:t,lastMessage:n,lastDeliveredAt:r,lastReadAt:i,unreadMessagesCount:s=0,members:o=[],mentioned:a=!1,...l},u){super(),Object.assign(this,{id:e,lastMessageAt:t,lastMessage:n,members:o,...l}),this.members=Array.from(new Set(this.members)),Object.assign(Tt(this),{messagesWaitingForReceipt:{},lastDeliveredAt:r,lastReadAt:i,unreadMessagesCount:s,mentioned:a}),this._client=u,Gs.enabled&&qe(js).forEach(e=>this.on(e,(...t)=>this._debug(`${e} event emitted. %o`,t))),Xt(this._client._plugins.onConversationCreate,this)}get unreadMessagesMentioned(){return Tt(this).unreadMessagesMentioned}_setUnreadMessagesMentioned(e){Tt(this).unreadMessagesMentioned=Boolean(e)}set unreadMessagesCount(e){e!==this.unreadMessagesCount&&(Tt(this).unreadMessagesCount=e,this._client.emit("unreadmessagescountupdate",[this]))}get unreadMessagesCount(){return Tt(this).unreadMessagesCount}set lastMessageAt(e){const t=dt(e);t<=this._lastMessageAt||(this._lastMessageAt=t)}get lastMessageAt(){return this._lastMessageAt}get lastDeliveredAt(){return 2!==this.members.length?null:Tt(this).lastDeliveredAt}_setLastDeliveredAt(e){const t=dt(e);t2&&console.warn("receipt option is recommended to be used in one-on-one conversation.")),i&&!this.transient&&console.warn("priority option is ignored as the conversation is not transient."),Object.assign(e,{cid:this.id,from:this._client.id}),e._setStatus(Ds.SENDING);const{msg:a,binaryMsg:l}=Js(e),u=new M({cmd:"direct",directMessage:new g({msg:a,binaryMsg:l,cid:this.id,r:r,transient:n,dt:e.id,pushData:JSON.stringify(s),will:o,mentionPids:e.mentionList,mentionAll:e.mentionedAll}),priority:i});try{const t=await this._send(u),{ackMessage:{uid:i,t:s,code:o,reason:a,appCode:l}}=t;if(null!==o)throw $t({code:o,reason:a,appCode:l});return Object.assign(e,{id:i,timestamp:s}),n||(this.lastMessage=e,this.lastMessageAt=e.timestamp),e._setStatus(Ds.SENT),r&&(Tt(this).messagesWaitingForReceipt[e.id]=e),e}catch(t){throw e._setStatus(Ds.FAILED),t}}async _update(e,t,n){if(this._debug("patch %O %O %O",e,t,n),e instanceof Us){if(e.from!==this._client.id)throw new Error("Updating message from others is not allowed");if(e.status!==Ds.SENT&&e.status!==Ds.DELIVERED)throw new Error("Message is not sent")}else if(!e.id||!e.timestamp)throw new TypeError(`${e} is not a Message`);let r,i;if(!n){const e=Js(t);({msg:r,binaryMsg:i}=e)}await this._send(new M({cmd:L.patch,op:x.modify,patchMessage:new R({patches:[new N({cid:this.id,mid:e.id,timestamp:Number(e.timestamp),recall:n,data:r,binaryMsg:i,mentionPids:t.mentionList,mentionAll:t.mentionedAll})],lastPatchTime:this._client._lastPatchTime})}));const{id:s,cid:o,timestamp:a,from:l,_status:u}=e;return Object.assign(t,{id:s,cid:o,timestamp:a,from:l,_status:u}),this.lastMessage&&this.lastMessage.id===t.id&&(this.lastMessage=t),t}async count(){return this._debug("count"),(await this._send(new M({op:"count"}))).convMessage.count}_addMembers(){}_removeMembers(){}async update(e,t){if(!(t instanceof Us))throw new TypeError(`${t} is not a Message`);return this._update(e,t,!1)}async recall(e){return this._update(e,new Ws,!0)}async queryMessages(e={}){this._debug("query messages %O",e);const{beforeTime:t,beforeMessageId:n,afterTime:r,afterMessageId:i,limit:s,direction:o,type:a,startTime:l,startMessageId:u,startClosed:c,endTime:f,endMessageId:h,endClosed:d}=e;if(n||t||i||r)return console.warn("DEPRECATION: queryMessages options beforeTime, beforeMessageId, afterTime and afterMessageId are deprecated in favor of startTime, startMessageId, endTime and endMessageId."),this.queryMessages({startTime:t,startMessageId:n,endTime:r,endMessageId:i,limit:s});if(u&&!l)throw new Error("query option startMessageId must be used with option startTime");if(h&&!f)throw new Error("query option endMessageId must be used with option endTime");const p={t:l,mid:u,tIncluded:c,tt:f,tmid:h,ttIncluded:d,l:s,lctype:a};p.t instanceof Date&&(p.t=p.t.getTime()),p.tt instanceof Date&&(p.tt=p.tt.getTime()),void 0!==o?p.direction=o:p.tt>p.t&&(p.direction=Xs.OLD_TO_NEW);const m=await this._send(new M({cmd:"logs",logsMessage:new E(Object.assign(p,{cid:this.id}))}));return Promise.all(m.logsMessage.logs.map(async({msgId:e,timestamp:t,patchTimestamp:n,from:r,ackAt:i,readAt:s,data:o,mentionAll:a,mentionPids:l,bin:u})=>{const c={data:o,bin:u,id:e,cid:this.id,timestamp:t,from:r,deliveredAt:i,updatedAt:n,mentionList:l,mentionedAll:a},f=await this._client.parseMessage(c);let h=Ds.SENT;return 2===this.members.length&&(i&&(h=Ds.DELIVERED),i&&this._setLastDeliveredAt(i),s&&this._setLastReadAt(s)),f._setStatus(h),f}))}createMessagesIterator({beforeTime:e,beforeMessageId:t,limit:n}={}){let r;return{next:()=>(r=void 0===r?this.queryMessages({limit:n,startTime:e,startMessageId:t}):r.then(e=>0===e.length||e.length({value:Array.from(e),done:0===e.length||e.lengthe.filter(e=>e.maxAckTimestamp||e.maxReadTimestamp).map(({pid:e,maxAckTimestamp:t,maxReadTimestamp:n})=>({pid:e,lastDeliveredAt:dt(t),lastReadAt:dt(n)})))}}const Hs=z("LC:SignatureFactoryRunner");function eo(e={}){const{signature:t,timestamp:n,nonce:r}=e;if("string"!=typeof t||"number"!=typeof n||"string"!=typeof r)throw new Error("malformed signature");return{signature:t,timestamp:n,nonce:r}}var to=(e,t)=>Promise.resolve().then(()=>(Hs("call signatureFactory with %O",t),e(...t))).then(ht(e=>Hs("sign result %O",e)),e=>{throw e.message=`sign error: ${e.message}`,Hs(e),e}).then(eo);const no=({allowedPids:e,failedPids:t})=>({successfulClientIds:e,failures:t.map(({pids:e,...t})=>Object.assign($t(t),{clientIds:e}))});class ro extends Qs{constructor(e,{creator:t,createdAt:n,updatedAt:r,transient:i=!1,system:s=!1,muted:o=!1,mutedMembers:a=[],...l},u){super({...e,creator:t,createdAt:n,updatedAt:r,mutedMembers:a,transient:i,system:s,muted:o,_attributes:l},u),this._reset()}set createdAt(e){this._createdAt=dt(e)}get createdAt(){return this._createdAt}set updatedAt(e){this._updatedAt=dt(e)}get updatedAt(){return this._updatedAt}get name(){return this.get("name")}set name(e){this.set("name",e)}get(e){return gi(Tt(this).currentAttributes,e)}set(e,t){this._debug(`set [${e}]: ${t}`);const{pendingAttributes:n}=Tt(this),r=Object.keys(n),i=new RegExp(`^${e}`),s=r.filter(i.test.bind(i));if(s.forEach(e=>{delete n[e]}),s.length)n[e]=t;else{const i=ks(r,t=>0===e.indexOf(t));i?Ct(n[i],e.slice(i.length+1),t):n[e]=t}return this._buildCurrentAttributes(),this}_buildCurrentAttributes(){const{pendingAttributes:e}=Tt(this);Tt(this).currentAttributes=Object.keys(e).reduce((t,n)=>Ct(t,n,e[n]),ws(this._attributes))}_updateServerAttributes(e){Object.keys(e).forEach(t=>Ct(this._attributes,t,e[t])),this._buildCurrentAttributes()}_reset(){Object.assign(Tt(this),{pendingAttributes:{},currentAttributes:this._attributes})}async save(){this._debug("save");const e=Tt(this).pendingAttributes;if(xi(e))return this._debug("nothing touched, resolve with self"),this;this._debug("attr: %O",e);const t=new b({attr:new c({data:JSON.stringify(gt(e))})}),n=await this._send(new M({op:"update",convMessage:t}));return this.updatedAt=n.convMessage.udate,this._attributes=Tt(this).currentAttributes,Tt(this).pendingAttributes={},this}async fetch(){const e=this._client.getQuery().equalTo("objectId",this.id);return await e.find(),this}async mute(){return this._debug("mute"),await this._send(new M({op:"mute"})),this.transient||(this.muted=!0,this.mutedMembers=wt(this.mutedMembers,[this._client.id])),this}async unmute(){return this._debug("unmute"),await this._send(new M({op:"unmute"})),this.transient||(this.muted=!1,this.mutedMembers=Et(this.mutedMembers,[this._client.id])),this}async _appendConversationSignature(e,t,n){if(this._client.options.conversationSignatureFactory){const r=[this.id,this._client.id,n.sort(),t],i=await to(this._client.options.conversationSignatureFactory,r);Object.assign(e.convMessage,yt({signature:"s",timestamp:"t",nonce:"n"},i))}}async _appendBlacklistSignature(e,t,n){if(this._client.options.blacklistSignatureFactory){const r=[this.id,this._client.id,n.sort(),t],i=await to(this._client.options.blacklistSignatureFactory,r);Object.assign(e.blacklistMessage,yt({signature:"s",timestamp:"t",nonce:"n"},i))}}async add(e){this._debug("add",e),"string"==typeof e&&(e=[e]);const t=new M({op:"add",convMessage:new b({m:e})});await this._appendConversationSignature(t,"invite",e);const{convMessage:n,convMessage:{allowedPids:r}}=await this._send(t);return this._addMembers(r),no(n)}async remove(e){this._debug("remove",e),"string"==typeof e&&(e=[e]);const t=new M({op:"remove",convMessage:new b({m:e})});await this._appendConversationSignature(t,"kick",e);const{convMessage:n,convMessage:{allowedPids:r}}=await this._send(t);return this._removeMembers(r),no(n)}async join(){return this._debug("join"),this.add(this._client.id).then(({failures:e})=>{if(e[0])throw e[0];return this})}async quit(){return this._debug("quit"),this.remove(this._client.id).then(({failures:e})=>{if(e[0])throw e[0];return this})}async muteMembers(e){this._debug("mute",e),e=It(e);const t=new M({op:x.add_shutup,convMessage:new b({m:e})}),{convMessage:n}=await this._send(t);return no(n)}async unmuteMembers(e){this._debug("unmute",e),e=It(e);const t=new M({op:x.remove_shutup,convMessage:new b({m:e})}),{convMessage:n}=await this._send(t);return no(n)}async queryMutedMembers({limit:e,next:t}={}){this._debug("query muted: limit %O, next: %O",e,t);const n=new M({op:x.query_shutup,convMessage:new b({limit:e,next:t})}),{convMessage:{m:r,next:i}}=await this._send(n);return{results:r,next:i}}async blockMembers(e){this._debug("block",e),e=It(e);const t=new M({cmd:"blacklist",op:x.block,blacklistMessage:new O({srcCid:this.id,toPids:e})});await this._appendBlacklistSignature(t,"conversation-block-clients",e);const{blacklistMessage:n}=await this._send(t);return no(n)}async unblockMembers(e){this._debug("unblock",e),e=It(e);const t=new M({cmd:"blacklist",op:x.unblock,blacklistMessage:new O({srcCid:this.id,toPids:e})});await this._appendBlacklistSignature(t,"conversation-unblock-clients",e);const{blacklistMessage:n}=await this._send(t);return no(n)}async queryBlockedMembers({limit:e,next:t}={}){this._debug("query blocked: limit %O, next: %O",e,t);const n=new M({cmd:"blacklist",op:x.query,blacklistMessage:new O({srcCid:this.id,limit:e,next:t})}),{blacklistMessage:{blockedPids:r,next:i}}=await this._send(n);return{results:r,next:i}}toFullJSON(){const{creator:e,system:t,transient:n,createdAt:r,updatedAt:i,_attributes:s}=this;return{...super.toFullJSON(),creator:e,system:t,transient:n,createdAt:pt(r),updatedAt:pt(i),...s}}toJSON(){const{creator:e,system:t,transient:n,muted:r,mutedMembers:i,createdAt:s,updatedAt:o,_attributes:a}=this;return{...super.toJSON(),creator:e,system:t,transient:n,muted:r,mutedMembers:i,createdAt:s,updatedAt:o,...a}}}const io={OWNER:"Owner",MANAGER:"Manager",MEMBER:"Member"};Object.freeze(io);class so{constructor({conversation:e,memberId:t,role:n}){if(!e)throw new Error("conversation requried");if(!t)throw new Error("memberId requried");Object.assign(Tt(this),{conversation:e,memberId:t,role:n})}get conversationId(){return Tt(this).conversation.id}get memberId(){return Tt(this).memberId}get role(){return this.isOwner?io.OWNER:Tt(this).role}get isOwner(){return this.memberId===Tt(this).conversation.creator}toJSON(){const{conversationId:e,memberId:t,role:n,isOwner:r}=this;return{conversationId:e,memberId:t,role:n,isOwner:r}}}class oo extends ro{_addMembers(e){super._addMembers(e),this.members=wt(this.members,e);const{memberInfoMap:t}=Tt(this);t&&e.forEach(e=>{t[e]=t[e]||new so({conversation:this,memberId:e,role:io.MEMBER})})}_removeMembers(e){super._removeMembers(e),this.members=Et(this.members,e);const{memberInfoMap:t}=Tt(this);t&&e.forEach(e=>{delete t[e]})}async _fetchAllMemberInfo(){const e=(await this._client._requestWithSessionToken({method:"GET",path:"/classes/_ConversationMemberInfo",query:{where:{cid:this.id}}})).results.map(e=>new so({conversation:this,memberId:e.clientId,role:e.role})),t={};return e.forEach(e=>{t[e.memberId]=e}),this.members.forEach(e=>{t[e]=t[e]||new so({conversation:this,memberId:e,role:io.MEMBER})}),Tt(this).memberInfoMap=t,t}async getAllMemberInfo({noCache:e=!1}={}){let{memberInfoMap:t}=Tt(this);return t&&!e||(t=await this._fetchAllMemberInfo()),this.members.map(e=>t[e])}async getMemberInfo(e){if(-1===this.members.indexOf(e))throw new Error(`${e} is not the mumber of conversation[${this.id}]`);const{memberInfoMap:t}=Tt(this);return t&&t[e]||await this.getAllMemberInfo(),Tt(this).memberInfoMap[e]}async updateMemberRole(e,t){if(this._debug("update member role"),t===io.OWNER)throw $t({code:Yt.OWNER_PROMOTION_NOT_ALLOWED});await this._send(new M({op:x.member_info_update,convMessage:new b({targetClientId:e,info:new P({pid:e,role:t})})}));const{memberInfos:n}=Tt(this);return n&&n[e]&&(Tt(n[e]).role=t),this}}class ao extends ro{}class lo extends ro{async subscribe(){return this.join()}async unsubscribe(){return this.quit()}}const uo=e=>e.code===Yt.CONVERSATION_NOT_FOUND?$t({code:Yt.TEMPORARY_CONVERSATION_EXPIRED}):e;class co extends Qs{constructor(e,{expiredAt:t},n){super({...e,expiredAt:t},n)}set expiredAt(e){this._expiredAt=dt(e)}get expiredAt(){return this._expiredAt}get expired(){return this.expiredAt(t<<1)+Boolean(e[n]),0)}static and(...e){if(e.length<2)throw new Error("The queries must contain at least two elements");if(!e.every(e=>e instanceof ho))throw new Error("The element of queries must be an instance of ConversationQuery");const t=new ho(e[0]._client);return t._where.$and=e.map(e=>e._where),t}static or(...e){const t=ho.and(...e);return t._where.$or=t._where.$and,delete t._where.$and,t}constructor(e){this._client=e,this._where={},this._extraOptions={}}_addCondition(e,t,n){return this._where[e]||(this._where[e]={}),this._where[e][t]=this.constructor._encode(n),this}toJSON(){const e={where:this._where,flag:this.constructor._calculateFlag(this._extraOptions)};return void 0!==this._skip&&(e.skip=this._skip),void 0!==this._limit&&(e.limit=this._limit),void 0!==this._order&&(e.sort=this._order),fo(e),e}containsMembers(e){return this.containsAll("m",e)}withMembers(e,t){const n=new Set(e);return t&&n.add(this._client.id),this.sizeEqualTo("m",n.size),this.containsMembers(Array.from(n))}equalTo(e,t){return this._where[e]=this.constructor._encode(t),this}lessThan(e,t){return this._addCondition(e,"$lt",t)}lessThanOrEqualTo(e,t){return this._addCondition(e,"$lte",t)}greaterThan(e,t){return this._addCondition(e,"$gt",t)}greaterThanOrEqualTo(e,t){return this._addCondition(e,"$gte",t)}notEqualTo(e,t){return this._addCondition(e,"$ne",t)}exists(e){return this._addCondition(e,"$exists",!0)}doesNotExist(e){return this._addCondition(e,"$exists",!1)}containedIn(e,t){return this._addCondition(e,"$in",t)}notContainsIn(e,t){return this._addCondition(e,"$nin",t)}containsAll(e,t){return this._addCondition(e,"$all",t)}contains(e,t){return this._addCondition(e,"$regex",ho._quote(t))}startsWith(e,t){return this._addCondition(e,"$regex",`^${ho._quote(t)}`)}endsWith(e,t){return this._addCondition(e,"$regex",`${ho._quote(t)}$`)}matches(e,t){this._addCondition(e,"$regex",t);let n="";return t.ignoreCase&&(n+="i"),t.multiline&&(n+="m"),n&&n.length&&this._addCondition(e,"$options",n),this}sizeEqualTo(e,t){return this._addCondition(e,"$size",t)}limit(e){return this._limit=e,this}skip(e){return this._skip=e,this}ascending(e){return this._order=e,this}addAscending(e){return this._order?this._order+=`,${e}`:this._order=e,this}descending(e){return this._order=`-${e}`,this}addDescending(e){return this._order?this._order+=`,-${e}`:this._order=`-${e}`,this}withLastMessagesRefreshed(e=!0){return this._extraOptions.withLastMessagesRefreshed=e,this}compact(e=!0){return this._extraOptions.compact=e,this}async find(){return this._client._executeQuery(this)}async first(){return(await this.limit(1).find())[0]}}const po=z("LC:SessionManager");class mo{constructor({refresh:e,onBeforeGetSessionToken:t}={}){this.refresh=e,this._onBeforeGetSessionToken=t,this.setSessionToken(null,0)}setSessionToken(e,t){po("set session token",e,t);const n=new at(e,1e3*t);return this._sessionToken=n,delete this._pendingSessionTokenPromise,n}async setSessionTokenAsync(e){const t=this._sessionToken;return this._pendingSessionTokenPromise=e.catch(e=>{throw this._sessionToken=t,e}),this.setSessionToken(...await this._pendingSessionTokenPromise)}async getSessionToken({autoRefresh:e=!0}={}){po("get session token"),this._onBeforeGetSessionToken&&this._onBeforeGetSessionToken(this);const{value:t,originalValue:n}=this._sessionToken||await this._pendingSessionTokenPromise;if(t===at.EXPIRED&&e&&this.refresh){po("refresh expired session token");const{value:e}=await this.setSessionTokenAsync(this.refresh(this,n));return po("session token",e),e}return po("session token",t),t}revoke(){this._sessionToken&&(this._sessionToken.expiredAt=-1)}}var go,yo,vo;const bo=z("LC:IMClient"),{INVITED:wo,KICKED:Eo,MEMBERS_JOINED:_o,MEMBERS_LEFT:To,MEMBER_INFO_UPDATED:So,BLOCKED:Ao,UNBLOCKED:Io,MEMBERS_BLOCKED:Co,MEMBERS_UNBLOCKED:Mo,MUTED:Oo,UNMUTED:Ro,MEMBERS_MUTED:No,MEMBERS_UNMUTED:Po,MESSAGE:Lo,UNREAD_MESSAGES_COUNT_UPDATE:xo,CLOSE:ko,CONFLICT:jo,UNHANDLED_MESSAGE:Do,CONVERSATION_INFO_UPDATED:Fo,MESSAGE_RECALL:Uo,MESSAGE_UPDATE:Bo,INFO_UPDATED:Vo}=js,Yo=e=>/^_tmp:/.test(e);let $o=(go=Ot(1e3),yo=Ot(1e3),Ge((vo=class extends D{constructor(e,t={},n){if(void 0!==e&&"string"!=typeof e)throw new TypeError(`Client id [${e}] is not a String`);if(super(),Object.assign(this,{id:e,options:t},n),!this._messageParser)throw new Error("IMClient must be initialized with a MessageParser");this._conversationCache=new ut(`client:${this.id}`),this._ackMessageBuffer={},Tt(this).lastPatchTime=Date.now(),Tt(this).lastNotificationTime=void 0,Tt(this)._eventemitter=new D,bo.enabled&&qe(js).forEach(e=>this.on(e,(...t)=>this._debug(`${e} event emitted. %o`,t))),Xt(this._plugins.onIMClientCreate,this)}_debug(...e){bo(...e,`[${this.id}]`)}async _dispatchCommand(e){switch(this._debug(At(e),"received"),e.serverTs&&1===e.notificationType&&(Tt(this).lastNotificationTime=pt(dt(e.serverTs))),e.cmd){case L.conv:return this._dispatchConvMessage(e);case L.direct:return this._dispatchDirectMessage(e);case L.session:return this._dispatchSessionMessage(e);case L.unread:return this._dispatchUnreadMessage(e);case L.rcp:return this._dispatchRcpMessage(e);case L.patch:return this._dispatchPatchMessage(e);default:return this.emit(Do,e)}}async _dispatchSessionMessage(e){const{sessionMessage:{code:t,reason:n}}=e;switch(e.op){case x.closed:return Tt(this)._eventemitter.emit("close"),t===Yt.SESSION_CONFLICT?this.emit(jo,{reason:n}):this.emit(ko,{code:t,reason:n});default:throw this.emit(Do,e),new Error("Unrecognized session command")}}_dispatchUnreadMessage({unreadMessage:{convs:e,notifTime:t}}){return Tt(this).lastUnreadNotifTime=t,this.getConversations(e.map(e=>e.cid)).then(()=>Promise.all(e.map(({cid:e,unread:t,mid:n,timestamp:r,from:i,data:s,binaryMsg:o,patchTimestamp:a,mentioned:l})=>{const u=this._conversationCache.get(e);if(!u)return null;let c;return r&&(c=dt(r),u.lastMessageAt=c),(n?this._messageParser.parse(o||s).then(t=>{const r={id:n,cid:e,timestamp:c,updatedAt:a,from:i};Object.assign(t,r),u.lastMessage=t}):Promise.resolve()).then(()=>(u._setUnreadMessagesMentioned(l),t===Tt(u).unreadMessagesCount?null:(Tt(u).unreadMessagesCount=t,u)))})).then(e=>e.filter(e=>e))).then(e=>{e.length&&this.emit(xo,e)})}async _dispatchRcpMessage(e){const{rcpMessage:t,rcpMessage:{read:n}}=e,r=t.cid,i=t.id,s=dt(t.t),o=this._conversationCache.get(r);o&&o._handleReceipt({messageId:i,timestamp:s,read:n})}_dispatchPatchMessage({patchMessage:{patches:e}}){return this.getConversations(e.map(e=>e.cid)).then(()=>Promise.all(e.map(({cid:e,mid:t,timestamp:n,recall:r,data:i,patchTimestamp:s,from:o,binaryMsg:a,mentionAll:l,mentionPids:u,patchCode:c,patchReason:f})=>{const h=this._conversationCache.get(e);return h?this._messageParser.parse(a||i).then(i=>{const a=pt(dt(s)),d={id:t,cid:e,timestamp:n,updatedAt:a,from:o,mentionList:u,mentionedAll:l};let p;Object.assign(i,d),i._setStatus(Ds.SENT),i._updateMentioned(this.id),Tt(this).lastPatchTime{if(!e)return;const c={id:n,cid:r,timestamp:s,updatedAt:a,from:i,mentionList:l,mentionedAll:u};return Object.assign(t,c),t._updateMentioned(this.id),t._setStatus(Ds.SENT),t.from!==this.id&&(o||e.transient||this._sendAck(t)),this._dispatchParsedMessage(t,e)})}_dispatchParsedMessage(e,t){return Ht(this._plugins.beforeMessageDispatch,[e,t]).then(n=>{!1!==n&&(t.lastMessage=e,t.lastMessageAt=e.timestamp,e.from!==this.id&&(t.unreadMessagesCount+=1,e.mentioned&&t._setUnreadMessagesMentioned(!0)),this.emit(Lo,e,t),t.emit(Lo,e))})}_sendAck(e){this._debug("send ack for %O",e);const{cid:t}=e;if(!t)throw new Error("missing cid");return this._ackMessageBuffer[t]||(this._ackMessageBuffer[t]=[]),this._ackMessageBuffer[t].push(e),this._doSendAck()}_doSendAck(){this._connection.is("connected")&&(this._debug("do send ack %O",this._ackMessageBuffer),Promise.all(Object.keys(this._ackMessageBuffer).map(e=>{const t=this._ackMessageBuffer[e],n=t.map(e=>e.timestamp),r=new M({cmd:"ack",ackMessage:new y({cid:e,fromts:Math.min.apply(null,n),tots:Math.max.apply(null,n)})});return delete this._ackMessageBuffer[e],this._send(r,!1).catch(n=>{this._debug("send ack failed: %O",n),this._ackMessageBuffer[e]=t})})))}_omitPeerId(e){Tt(this).peerIdOmittable=e}_send(e,...t){const n=e;return!Tt(this).peerIdOmittable&&this.id&&(n.peerId=this.id),this._connection.send(n,...t)}async _open(e,t,n,r=!1){this._debug("open session");const{lastUnreadNotifTime:i,lastPatchTime:s,lastNotificationTime:o}=Tt(this),a=new M({cmd:"session",op:"open",appId:e,peerId:this.id,sessionMessage:new p({ua:"js/5.0.0-rc.7",r:r,lastUnreadNotifTime:i,lastPatchTime:s,configBitmap:187})});if(r){const e=await this._sessionManager.getSessionToken({autoRefresh:!1});e&&e!==at.EXPIRED&&Object.assign(a.sessionMessage,{st:e})}else if(Object.assign(a.sessionMessage,At({tag:t,deviceId:n})),this.options.signatureFactory){const e=await to(this.options.signatureFactory,[this._identity]);Object.assign(a.sessionMessage,yt({signature:"s",timestamp:"t",nonce:"n"},e))}let l;try{l=await this._send(a)}catch(i){if(i.code===Yt.SESSION_TOKEN_EXPIRED){if(!this._sessionManager)throw new Error("Unexpected session expiration");return bo("Session token expired, reopening"),this._sessionManager.revoke(),this._open(e,t,n,r)}throw i}const{peerId:u,sessionMessage:c,sessionMessage:{st:f,stTtl:h,code:d},serverTs:m}=l;if(d)throw $t(c);if(u){this.id=u,this._identity||(this._identity=u),f&&(this._sessionManager=this._sessionManager||this._createSessionManager(),this._sessionManager.setSessionToken(f,h));const e=pt(dt(m));m&&(Tt(this).lastPatchTime=e),o?this._syncNotifications(o).catch(e=>console.warn("Syncing notifications failed:",e)):Tt(this).lastNotificationTime=e}else console.warn("Unexpected session opened without peerId.")}async _syncNotifications(e){const{hasMore:t,notifications:n}=await this._fetchNotifications(e);if(n.forEach(e=>{const{cmd:t,op:n,serverTs:r,notificationType:i,...s}=e;this._dispatchCommand({cmd:L[t],op:x[n],serverTs:r,notificationType:i,[`${t}Message`]:s})}),t)return this._syncNotifications(Tt(this).lastNotificationTime)}async _fetchNotifications(e){return this._requestWithSessionToken({method:"GET",path:"/rtm/notifications",query:{start_ts:e,notification_type:"permanent"}})}_createSessionManager(){return bo("create SessionManager"),new mo({onBeforeGetSessionToken:this._connection.checkConnectionAvailability.bind(this._connection),refresh:(e,t)=>e.setSessionTokenAsync(Promise.resolve(new M({cmd:"session",op:"refresh",sessionMessage:new p({ua:"js/5.0.0-rc.7",st:t})})).then(async e=>{if(this.options.signatureFactory){const t=await to(this.options.signatureFactory,[this._identity]);Object.assign(e.sessionMessage,yt({signature:"s",timestamp:"t",nonce:"n"},t))}return e}).then(this._send.bind(this)).then(({sessionMessage:{st:e,stTtl:t}})=>[e,t]))})}async _requestWithSessionToken({headers:e,query:t,...n}){const r=await this._sessionManager.getSessionToken();return this._request({headers:{"X-LC-IM-Session-Token":r,...e},query:{client_id:this.id,...t},...n})}async close(){this._debug("close session");const e=Tt(this)._eventemitter;if(e.emit("beforeclose"),this._connection.is("connected")){const e=new M({cmd:"session",op:"close"});await this._send(e)}e.emit("close"),this.emit(ko,{code:0})}async ping(e){if(this._debug("ping"),!(e instanceof Array))throw new TypeError(`clientIds ${e} is not an Array`);if(!e.length)return Promise.resolve([]);const t=new M({cmd:"session",op:"query",sessionMessage:new p({sessionPeerIds:e})});return(await this._send(t)).sessionMessage.onlineSessionPeerIds}async getConversation(e,t=!1){if("string"!=typeof e)throw new TypeError(`${e} is not a String`);if(!t){const t=this._conversationCache.get(e);if(t)return t}return Yo(e)?(await this._getTemporaryConversations([e]))[0]||null:this.getQuery().equalTo("objectId",e).find().then(e=>e[0]||null)}async getConversations(e,t=!1){const n=t?e:e.filter(e=>null===this._conversationCache.get(e));if(n.length){const e=Pi(n,Yo),t=[];if(n.length&&t.push(this.getQuery().containedIn("objectId",n).limit(999).find()),e.length){const n=e.map(this._getTemporaryConversations.bind(this));t.push(...n)}await Promise.all(t)}return e.map(e=>this._conversationCache.get(e))}async _getTemporaryConversations(e){const t=new M({cmd:"conv",op:"query",convMessage:new b({tempConvIds:e})}),n=await this._send(t);return this._handleQueryResults(n)}getQuery(){return new ho(this)}getChatRoomQuery(){return this.getQuery().equalTo("tr",!0)}getServiceConversationQuery(){return this.getQuery().equalTo("sys",!0)}async _executeQuery(e){const t=e.toJSON();t.where=new c({data:JSON.stringify(gt(t.where))});const n=new M({cmd:"conv",op:"query",convMessage:new b(t)}),r=await this._send(n);return this._handleQueryResults(r)}async _handleQueryResults(e){let t;try{t=mt(JSON.parse(e.convMessage.results.data))}catch(t){const n=JSON.stringify(At(e));throw new Error(`Parse query result failed: ${t.message}. Command: ${n}`)}return t=await Promise.all(t.map(this._parseConversationFromRawData.bind(this))),t.map(this._upsertConversationToCache.bind(this))}_upsertConversationToCache(e){let t=this._conversationCache.get(e.id);return t?(this._debug("update cached conversation"),["creator","createdAt","updatedAt","lastMessageAt","lastMessage","mutedMembers","members","_attributes","transient","muted"].forEach(n=>{const r=e[n];void 0!==r&&(t[n]=r)}),t._reset&&t._reset()):(t=e,this._debug("no match, set cache"),this._conversationCache.set(e.id,e)),t}async parseMessage({data:e,bin:t=!1,...n}){const r=t?dn(e):e,i=await this._messageParser.parse(r);return Object.assign(i,n),i._updateMentioned(this.id),i}async parseConversation({id:e,lastMessageAt:t,lastMessage:n,lastDeliveredAt:r,lastReadAt:i,unreadMessagesCount:s,members:o,mentioned:a,...l}){const u={id:e,lastMessageAt:t,lastMessage:n,lastDeliveredAt:r,lastReadAt:i,unreadMessagesCount:s,members:o,mentioned:a};n&&(u.lastMessage=await this.parseMessage(n),u.lastMessage._setStatus(Ds.SENT));const{transient:c,system:f,expiredAt:h}=l;return c?new ao(u,l,this):f?new lo(u,l,this):h||Yo(e)?new co(u,{expiredAt:h},this):new oo(u,l,this)}async _parseConversationFromRawData(e){const t=yt({objectId:"id",lm:"lastMessageAt",m:"members",tr:"transient",sys:"system",c:"creator",mu:"mutedMembers"},e);t.msg&&(t.lastMessage={data:t.msg,bin:t.bin,from:t.msg_from,id:t.msg_mid,timestamp:t.msg_timestamp,updatedAt:t.patch_timestamp},delete t.lastMessageFrom,delete t.lastMessageId,delete t.lastMessageTimestamp,delete t.lastMessagePatchTimestamp);const{ttl:n}=t;return n&&(t.expiredAt=Date.now()+1e3*n),this.parseConversation(t)}async createConversation({members:e,name:t,transient:n,unique:r=!0,_tempConv:i,_tempConvTTL:s,...o}={}){if(!n&&!Array.isArray(e))throw new TypeError(`conversation members ${e} is not an array`);let a=new Set(e);a.add(this.id),a=Array.from(a).sort();let l=o||{};if(t){if("string"!=typeof t)throw new TypeError(`conversation name ${t} is not a string`);l.name=t}l=new c({data:JSON.stringify(gt(l))});const u=new M({cmd:"conv",op:"start",convMessage:new b({m:a,attr:l,transient:n,unique:r,tempConv:i,tempConvTTL:s})});if(this.options.conversationSignatureFactory){const e=[null,this._identity,a,"create"],t=await to(this.options.conversationSignatureFactory,e);Object.assign(u.convMessage,yt({signature:"s",timestamp:"t",nonce:"n"},t))}const{convMessage:{cid:f,cdate:h,tempConvTTL:d}}=await this._send(u),p={name:t,transient:n,unique:r,id:f,createdAt:h,updatedAt:h,lastMessageAt:null,creator:this.id,members:n?[]:a,...o};d&&(p.expiredAt=Date.now()+1e3*d);const m=await this.parseConversation(p);return this._upsertConversationToCache(m)}async createChatRoom(e){return this.createConversation({...e,transient:!0,members:null,unique:!1,_tempConv:!1})}async createTemporaryConversation({ttl:e,...t}){return this.createConversation({...t,_tempConv:!0,_tempConvTTL:e})}_doSendRead(){if(!this._connection.is("connected"))return;const e=Tt(this).readConversationsBuffer,t=Array.from(e);if(!t.length)return;const n=t.map(e=>{if(!(e instanceof Qs))throw new TypeError(`${e} is not a Conversation`);return e.id});this._debug(`mark [${n}] as read`),e.clear(),this._sendReadCommand(t).catch(n=>{this._debug("send read failed: %O",n),t.forEach(e.add.bind(e))})}_sendReadCommand(e){return this._send(new M({cmd:"read",readMessage:new A({convs:e.map(e=>new T({cid:e.id,mid:e.lastMessage&&e.lastMessage.from!==this.id?e.lastMessage.id:void 0,timestamp:(e.lastMessageAt||new Date).getTime()}))})}),!1)}}).prototype,"_doSendAck",[go],Object.getOwnPropertyDescriptor(vo.prototype,"_doSendAck"),vo.prototype),Ge(vo.prototype,"_doSendRead",[yo],Object.getOwnPropertyDescriptor(vo.prototype,"_doSendRead"),vo.prototype),vo);var qo,zo=Object.freeze({__proto__:null,RECONNECT_ERROR:"reconnecterror",DISCONNECT:Pt,RECONNECT:Lt,RETRY:xt,SCHEDULE:kt,OFFLINE:jt,ONLINE:Dt});let Wo=Ys(qo=class extends Us{constructor(e){if(!(e instanceof ArrayBuffer))throw new TypeError(`${e} is not an ArrayBuffer`);super(e)}get buffer(){return this.content}set buffer(e){this.content=e}static validate(e){return e instanceof ArrayBuffer}toJSON(){return{...super._toJSON(),data:hn(this.content)}}toFullJSON(){return{...super.toFullJSON(),bin:!0,data:hn(this.content)}}})||qo;var Go;let Jo=Bs(-1)(Go=Ys(Go=class extends qs{constructor(e=""){if("string"!=typeof e)throw new TypeError(`${e} is not a string`);super(),this.setText(e)}})||Go)||Go;var Zo;const Ko=z("LC:MessageParser");let Xo=(Ge((Zo=class{constructor(e={}){this._plugins=e,this._messageClasses=[],this.register(e.messageClasses)}register(e){It(e).map(e=>this._register(e))}_register(e){if(!(e&&e.parse&&e.prototype&&e.prototype.getPayload))throw new TypeError("Invalid messageClass");this._messageClasses.unshift(e)}parse(e){Ko("parsing message: %O",e);for(const t of this._messageClasses){const n=rt(e)?{...e}:e;let r,i;try{r=t.validate(n)}catch(e){}if(r){try{i=t.parse(n)}catch(e){console.warn("parsing a valid message content error",{error:e,Klass:t,content:n})}if(void 0!==i)return Ko("parse result: %O",i),i}}throw new Error("No Message Class matched")}}).prototype,"parse",[(e,t,n)=>{const r=n.value;n.value=function(e){let t;if("string"!=typeof e)t=e;else try{t=JSON.parse(e)}catch(n){t=e}return r.call(this,t)}},(e,t,n)=>{const r=n.value;n.value=function(e){return Promise.resolve(e).then(Qt(this._plugins.beforeMessageParse)).then(e=>r.call(this,e)).then(Qt(this._plugins.afterMessageParse))}}],Object.getOwnPropertyDescriptor(Zo.prototype,"parse"),Zo.prototype),Zo);const Qo=z("LC:IMPlugin"),Ho={HIGH:1,NORMAL:2,LOW:3};Object.freeze(Ho);const ea=(e,t={get(){return this.get(e)},set(t){this.set(e,t)}})=>{Object.defineProperty(oo.prototype,e,t)},ta={name:"leancloud-realtime-plugin-im",onRealtimeCreate:e=>{const t=cn();e._IMClients={},e._IMClientsCreationCount=0;const n=new Xo(e._plugins);e._messageParser=n;const r=async t=>e._request({method:"POST",path:"/rtm/sign",data:{session_token:t.getSessionToken()}}),i=n.register.bind(n);Object.assign(e,{register:i,createIMClient:async(i,{tag:s,isReconnect:o,...a}={},l)=>{let u;const c={};if(i){if("string"==typeof i)u=i;else{if(!i.id||!i.getSessionToken)throw new TypeError("Identity must be a String or an AV.User");if(({id:u}=i),!i.getSessionToken())throw new Error("User must be authenticated");c.signatureFactory=r}if(void 0!==e._IMClients[u])return e._IMClients[u]}l&&console.warn("DEPRECATION createIMClient tag param: Use options.tag instead.");const f=s||l,h=e._open().then(r=>{const s=new $o(u,{...c,...a},{_connection:r,_request:e._request.bind(e),_messageParser:n,_plugins:e._plugins,_identity:i});return r.on(Lt,()=>s._open(e._options.appId,f,t,!0).then(()=>s.emit(Lt),e=>s.emit("reconnecterror",e))),Tt(s)._eventemitter.on("beforeclose",()=>{delete e._IMClients[s.id],e._firstIMClient===s&&delete e._firstIMClient},e),Tt(s)._eventemitter.on("close",()=>{e._deregister(s)},e),s._open(e._options.appId,f,t,o).then(()=>(e._IMClients[s.id]=s,e._IMClientsCreationCount+=1,1===e._IMClientsCreationCount?(s._omitPeerId(!0),e._firstIMClient=s):e._IMClientsCreationCount>1&&e._firstIMClient&&e._firstIMClient._omitPeerId(!1),e._register(s),s)).catch(t=>{throw delete e._IMClients[s.id],t})}).then(...(d=()=>{e._deregisterPending(h)},[e=>(d(),e),e=>{throw d(),e}])).catch(t=>{throw delete e._IMClients[u],t});var d;return i&&(e._IMClients[u]=h),e._registerPending(h),h}})},beforeCommandDispatch:(e,t)=>{if(!(null===e.service||2===e.service))return!0;const n=e.peerId?t._IMClients[e.peerId]:t._firstIMClient;return n?Promise.resolve(n).then(t=>t._dispatchCommand(e)).catch(Qo):Qo("[WARN] Unexpected message received without any live client match: %O",At(e)),!1},messageClasses:[Us,Wo,Ws,Jo]};rn.defineConversationProperty=ea,rn.__preRegisteredPlugins=[ta];const na={...zo,...js};e.BinaryMessage=Wo,e.ChatRoom=ao,e.Conversation=oo,e.ConversationMemberRole=io,e.ConversationQuery=ho,e.ErrorCode=Yt,e.Event=na,e.EventEmitter=D,e.IE10Compatible=Ys,e.IMPlugin=ta,e.Message=Us,e.MessageParser=Xo,e.MessagePriority=Ho,e.MessageQueryDirection=Xs,e.MessageStatus=Ds,e.Promise=sn,e.Protocals=j,e.Protocols=j,e.Realtime=rn,e.RecalledMessage=Ws,e.ServiceConversation=lo,e.TemporaryConversation=co,e.TextMessage=Jo,e.TypedMessage=qs,e.debug=ct,e.defineConversationProperty=ea,e.getAdapter=Ke,e.messageField=Vs,e.messageType=Bs,e.setAdapters=e=>{Object.assign(Ze,e)},Object.defineProperty(e,"__esModule",{value:!0})})); //# sourceMappingURL=im.min.js.map