!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("cloudbase_database",[],t):"object"==typeof exports?exports.cloudbase_database=t():e.cloudbase_database=t()}("undefined"!=typeof window?window:this,(function(){return function(e){var t={};function r(n){if(t[n])return t[n].exports;var i=t[n]={i:n,l:!1,exports:{}};return e[n].call(i.exports,i,i.exports,r),i.l=!0,i.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)r.d(n,i,function(t){return e[t]}.bind(null,i));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=12)}([function(module,__webpack_exports__,__webpack_require__){"use strict";(function(global,Buffer){__webpack_require__.d(__webpack_exports__,"a",(function(){return bson_54}));var long__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(2),long__WEBPACK_IMPORTED_MODULE_0___default=__webpack_require__.n(long__WEBPACK_IMPORTED_MODULE_0__),buffer__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(1),buffer__WEBPACK_IMPORTED_MODULE_1___default=__webpack_require__.n(buffer__WEBPACK_IMPORTED_MODULE_1__),commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==global?global:"undefined"!=typeof self?self:{};function createCommonjsModule(e,t){return e(t={exports:{}},t.exports),t.exports}var map=createCommonjsModule((function(e){if(void 0!==commonjsGlobal.Map)e.exports=commonjsGlobal.Map,e.exports.Map=commonjsGlobal.Map;else{var t=function(e){this._keys=[],this._values={};for(var t=0;t>>0,i:this.low>>>0}}}}],[{key:"fromInt",value:function(e){return new t(long_1.fromInt(e,!0))}},{key:"fromNumber",value:function(e){return new t(long_1.fromNumber(e,!0))}},{key:"fromBits",value:function(e,r){return new t(e,r)}},{key:"fromString",value:function(e,r){return new t(long_1.fromString(e,r,!0))}},{key:"fromExtendedJSON",value:function(e){return new t(e.$timestamp.i,e.$timestamp.t)}}]),t}(long_1);Object.defineProperty(Timestamp.prototype,"_bsontype",{value:"Timestamp"}),Timestamp.MAX_VALUE=Timestamp.MAX_UNSIGNED_VALUE;var timestamp=Timestamp,require$$0={};function normalizedFunctionString(e){return e.toString().replace("function(","function (")}function insecureRandomBytes(e){for(var t=new Uint8Array(e),r=0;r1)for(var r=1;r=i)return e;switch(e){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(e){return"[Circular]"}default:return e}})),s=n[r];r=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),isBoolean(t)?r.showHidden=t:t&&_extend(r,t),isUndefined(r.showHidden)&&(r.showHidden=!1),isUndefined(r.depth)&&(r.depth=2),isUndefined(r.colors)&&(r.colors=!1),isUndefined(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=stylizeWithColor),formatValue(r,e,r.depth)}function stylizeWithColor(e,t){var r=inspect.styles[t];return r?"["+inspect.colors[r][0]+"m"+e+"["+inspect.colors[r][1]+"m":e}function stylizeNoColor(e,t){return e}function arrayToHash(e){var t={};return e.forEach((function(e,r){t[e]=!0})),t}function formatValue(e,t,r){if(e.customInspect&&t&&isFunction(t.inspect)&&t.inspect!==inspect&&(!t.constructor||t.constructor.prototype!==t)){var n=t.inspect(r,e);return isString(n)||(n=formatValue(e,n,r)),n}var i=formatPrimitive(e,t);if(i)return i;var o=Object.keys(t),s=arrayToHash(o);if(e.showHidden&&(o=Object.getOwnPropertyNames(t)),isError(t)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return formatError(t);if(0===o.length){if(isFunction(t)){var a=t.name?": "+t.name:"";return e.stylize("[Function"+a+"]","special")}if(isRegExp(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(isDate(t))return e.stylize(Date.prototype.toString.call(t),"date");if(isError(t))return formatError(t)}var u,c="",l=!1,f=["{","}"];(isArray(t)&&(l=!0,f=["[","]"]),isFunction(t))&&(c=" [Function"+(t.name?": "+t.name:"")+"]");return isRegExp(t)&&(c=" "+RegExp.prototype.toString.call(t)),isDate(t)&&(c=" "+Date.prototype.toUTCString.call(t)),isError(t)&&(c=" "+formatError(t)),0!==o.length||l&&0!=t.length?r<0?isRegExp(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special"):(e.seen.push(t),u=l?formatArray(e,t,r,s,o):o.map((function(n){return formatProperty(e,t,r,s,n,l)})),e.seen.pop(),reduceToSingleString(u,c,f)):f[0]+c+f[1]}function formatPrimitive(e,t){if(isUndefined(t))return e.stylize("undefined","undefined");if(isString(t)){var r="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(r,"string")}return isNumber(t)?e.stylize(""+t,"number"):isBoolean(t)?e.stylize(""+t,"boolean"):isNull(t)?e.stylize("null","null"):void 0}function formatError(e){return"["+Error.prototype.toString.call(e)+"]"}function formatArray(e,t,r,n,i){for(var o=[],s=0,a=t.length;s-1&&(a=o?a.split("\n").map((function(e){return" "+e})).join("\n").substr(2):"\n"+a.split("\n").map((function(e){return" "+e})).join("\n")):a=e.stylize("[Circular]","special")),isUndefined(s)){if(o&&i.match(/^\d+$/))return a;(s=JSON.stringify(""+i)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(s=s.substr(1,s.length-2),s=e.stylize(s,"name")):(s=s.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),s=e.stylize(s,"string"))}return s+": "+a}function reduceToSingleString(e,t,r){return e.reduce((function(e,t){return t.indexOf("\n"),e+t.replace(/\u001b\[\d\d?m/g,"").length+1}),0)>60?r[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+r[1]:r[0]+t+" "+e.join(", ")+" "+r[1]}function isArray(e){return Array.isArray(e)}function isBoolean(e){return"boolean"==typeof e}function isNull(e){return null===e}function isNullOrUndefined(e){return null==e}function isNumber(e){return"number"==typeof e}function isString(e){return"string"==typeof e}function isSymbol(e){return"symbol"===_typeof$1(e)}function isUndefined(e){return void 0===e}function isRegExp(e){return isObject(e)&&"[object RegExp]"===objectToString(e)}function isObject(e){return"object"===_typeof$1(e)&&null!==e}function isDate(e){return isObject(e)&&"[object Date]"===objectToString(e)}function isError(e){return isObject(e)&&("[object Error]"===objectToString(e)||e instanceof Error)}function isFunction(e){return"function"==typeof e}function isPrimitive(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"===_typeof$1(e)||void 0===e}function isBuffer(e){return Buffer.isBuffer(e)}function objectToString(e){return Object.prototype.toString.call(e)}function pad(e){return e<10?"0"+e.toString(10):e.toString(10)}inspect.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},inspect.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function timestamp$1(){var e=new Date,t=[pad(e.getHours()),pad(e.getMinutes()),pad(e.getSeconds())].join(":");return[e.getDate(),months[e.getMonth()],t].join(" ")}function log(){console.log("%s - %s",timestamp$1(),format.apply(null,arguments))}function _extend(e,t){if(!t||!isObject(t))return e;for(var r=Object.keys(t),n=r.length;n--;)e[r[n]]=t[r[n]];return e}function hasOwnProperty(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var util={inherits:inherits$1,_extend:_extend,log:log,isBuffer:isBuffer,isPrimitive:isPrimitive,isFunction:isFunction,isError:isError,isDate:isDate,isObject:isObject,isRegExp:isRegExp,isUndefined:isUndefined,isSymbol:isSymbol,isString:isString,isNumber:isNumber,isNullOrUndefined:isNullOrUndefined,isNull:isNull,isBoolean:isBoolean,isArray:isArray,inspect:inspect,deprecate:deprecate,format:format,debuglog:debuglog};function _classCallCheck$2(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties$2(e,t){for(var r=0;r>8&255,n[1]=t>>16&255,n[0]=t>>24&255,n[4]=PROCESS_UNIQUE[0],n[5]=PROCESS_UNIQUE[1],n[6]=PROCESS_UNIQUE[2],n[7]=PROCESS_UNIQUE[3],n[8]=PROCESS_UNIQUE[4],n[11]=255&r,n[10]=r>>8&255,n[9]=r>>16&255,n}},{key:"createPk",value:function(){return new e}},{key:"createFromTime",value:function(t){var r=Buffer$1.from([0,0,0,0,0,0,0,0,0,0,0,0]);return r[3]=255&t,r[2]=t>>8&255,r[1]=t>>16&255,r[0]=t>>24&255,new e(r)}},{key:"createFromHexString",value:function(t){if(void 0===t||null!=t&&24!==t.length)throw new TypeError("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters");if(hasBufferType)return new e(Buffer$1.from(t,"hex"));for(var r=new _Buffer(12),n=0,i=0;i<24;)r[n++]=decodeLookup[t.charCodeAt(i++)]<<4|decodeLookup[t.charCodeAt(i++)];return new e(r)}},{key:"isValid",value:function(t){return null!=t&&("number"==typeof t||("string"==typeof t?12===t.length||24===t.length&&checkForHexRegExp.test(t):t instanceof e||(t instanceof _Buffer&&12===t.length||!!t.toHexString&&(12===t.id.length||24===t.id.length&&checkForHexRegExp.test(t.id)))))}},{key:"fromExtendedJSON",value:function(t){return new e(t.$oid)}}]),e}();ObjectId.get_inc=deprecate$1((function(){return ObjectId.getInc()}),"Please use the static `ObjectId.getInc()` instead"),ObjectId.prototype.get_inc=deprecate$1((function(){return ObjectId.getInc()}),"Please use the static `ObjectId.getInc()` instead"),ObjectId.prototype.getInc=deprecate$1((function(){return ObjectId.getInc()}),"Please use the static `ObjectId.getInc()` instead"),ObjectId.prototype.generate=deprecate$1((function(e){return ObjectId.generate(e)}),"Please use the static `ObjectId.generate(time)` instead"),Object.defineProperty(ObjectId.prototype,"generationTime",{enumerable:!0,get:function(){return this.id[3]|this.id[2]<<8|this.id[1]<<16|this.id[0]<<24},set:function(e){this.id[3]=255&e,this.id[2]=e>>8&255,this.id[1]=e>>16&255,this.id[0]=e>>24&255}}),ObjectId.prototype[util.inspect.custom||"inspect"]=ObjectId.prototype.toString,ObjectId.index=~~(16777215*Math.random()),Object.defineProperty(ObjectId.prototype,"_bsontype",{value:"ObjectID"});var objectid=ObjectId;function _classCallCheck$3(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties$3(e,t){for(var r=0;r>>0,n=t.high>>>0;return r>>0>>0}function invalidErr(e,t){throw new TypeError('"'.concat(e,'" is not a valid Decimal128 string - ').concat(t))}function Decimal128(e){this.bytes=e}Decimal128.fromString=function(e){var t,r=!1,n=!1,i=!1,o=0,s=0,a=0,u=0,c=0,l=[0],f=0,h=0,d=0,p=0,_=0,g=0,y=[0,0],m=[0,0],b=0;if(e.length>=7e3)throw new TypeError(e+" not a valid Decimal128 string");var w=e.match(PARSE_STRING_REGEXP),v=e.match(PARSE_INF_REGEXP),E=e.match(PARSE_NAN_REGEXP);if(!w&&!v&&!E||0===e.length)throw new TypeError(e+" not a valid Decimal128 string");if(w){var S=w[2],A=w[4],N=w[5],O=w[6];A&&void 0===O&&invalidErr(e,"missing exponent power"),A&&void 0===S&&invalidErr(e,"missing exponent base"),void 0===A&&(N||O)&&invalidErr(e,"missing e before exponent")}if("+"!==e[b]&&"-"!==e[b]||(r="-"===e[b++]),!isDigit(e[b])&&"."!==e[b]){if("i"===e[b]||"I"===e[b])return new Decimal128(Buffer$2.from(r?INF_NEGATIVE_BUFFER:INF_POSITIVE_BUFFER));if("N"===e[b])return new Decimal128(Buffer$2.from(NAN_BUFFER))}for(;isDigit(e[b])||"."===e[b];)"."!==e[b]?(f<34&&("0"!==e[b]||i)&&(i||(c=s),i=!0,l[h++]=parseInt(e[b],10),f+=1),i&&(a+=1),n&&(u+=1),s+=1,b+=1):(n&&invalidErr(e,"contains multiple periods"),n=!0,b+=1);if(n&&!s)throw new TypeError(e+" not a valid Decimal128 string");if("e"===e[b]||"E"===e[b]){var T=e.substr(++b).match(EXPONENT_REGEX);if(!T||!T[2])return new Decimal128(Buffer$2.from(NAN_BUFFER));_=parseInt(T[0],10),b+=T[0].length}if(e[b])return new Decimal128(Buffer$2.from(NAN_BUFFER));if(d=0,f){if(p=f-1,1!==(o=a))for(;"0"===e[c+o-1];)o-=1}else d=0,p=0,l[0]=0,a=1,f=1,o=0;for(_<=u&&u-_>16384?_=EXPONENT_MIN:_-=u;_>EXPONENT_MAX;){if((p+=1)-d>MAX_DIGITS){if(l.join("").match(/^0+$/)){_=EXPONENT_MAX;break}invalidErr(e,"overflow")}_-=1}for(;_=5&&(R=1,5===B))for(R=l[p]%2==1,g=c+p+2;g=0;D--)if(++l[D]>9&&(l[D]=0,0===D)){if(!(_>8&255,L[b++]=M.low.low>>16&255,L[b++]=M.low.low>>24&255,L[b++]=255&M.low.high,L[b++]=M.low.high>>8&255,L[b++]=M.low.high>>16&255,L[b++]=M.low.high>>24&255,L[b++]=255&M.high.low,L[b++]=M.high.low>>8&255,L[b++]=M.high.low>>16&255,L[b++]=M.high.low>>24&255,L[b++]=255&M.high.high,L[b++]=M.high.high>>8&255,L[b++]=M.high.high>>16&255,L[b++]=M.high.high>>24&255,new Decimal128(L)};var COMBINATION_MASK=31,EXPONENT_MASK=16383,COMBINATION_INFINITY=30,COMBINATION_NAN=31;Decimal128.prototype.toString=function(){for(var e,t,r,n,i,o,s=0,a=new Array(36),u=0;u>26&COMBINATION_MASK)>>3==3){if(i===COMBINATION_INFINITY)return y.join("")+"Infinity";if(i===COMBINATION_NAN)return"NaN";o=e>>15&EXPONENT_MASK,f=8+(e>>14&1)}else f=e>>14&7,o=e>>17&EXPONENT_MASK;if(c=o-EXPONENT_BIAS,g.parts[0]=(16383&e)+((15&f)<<14),g.parts[1]=t,g.parts[2]=r,g.parts[3]=n,0===g.parts[0]&&0===g.parts[1]&&0===g.parts[2]&&0===g.parts[3])_=!0;else for(d=3;d>=0;d--){var b=0,w=divideu128(g);if(g=w.quotient,b=w.rem.low)for(h=8;h>=0;h--)a[9*d+h]=b%10,b=Math.floor(b/10)}if(_)s=1,a[p]=0;else for(s=36;!a[p];)s-=1,p+=1;if((l=s-1+c)>=34||l<=-7||c>0){if(s>34)return y.push(0),c>0?y.push("E+"+c):c<0&&y.push("E"+c),y.join("");y.push(a[p++]),(s-=1)&&y.push(".");for(var v=0;v0?y.push("+"+l):y.push(l)}else if(c>=0)for(var E=0;E0)for(var A=0;A255)throw new TypeError("only accepts number in a valid unsigned byte range 0-255");var r=null;if(r="string"==typeof t?t.charCodeAt(0):null!=t.length?t[0]:t,this.buffer.length>this.position)this.buffer[this.position++]=r;else if(void 0!==Buffer$3&&Buffer$3.isBuffer(this.buffer)){var n=Buffer$3.alloc(e.BUFFER_SIZE+this.buffer.length);this.buffer.copy(n,0,0,this.buffer.length),this.buffer=n,this.buffer[this.position++]=r}else{var i=null;i=isUint8Array(this.buffer)?new Uint8Array(new ArrayBuffer(e.BUFFER_SIZE+this.buffer.length)):new Array(e.BUFFER_SIZE+this.buffer.length);for(var o=0;othis.position?t+e.length:this.position;else if(void 0!==Buffer$3&&"string"==typeof e&&Buffer$3.isBuffer(this.buffer))this.buffer.write(e,t,"binary"),this.position=t+e.length>this.position?t+e.length:this.position;else if(isUint8Array(e)||Array.isArray(e)&&"string"!=typeof e){for(var i=0;ithis.position?t:this.position}else if("string"==typeof e){for(var o=0;othis.position?t:this.position}}},{key:"read",value:function(e,t){if(t=t&&t>0?t:this.position,this.buffer.slice)return this.buffer.slice(e,e+t);for(var r="undefined"!=typeof Uint8Array?new Uint8Array(new ArrayBuffer(t)):new Array(t),n=0;n=BSON_INT32_MIN&&r<=BSON_INT32_MAX)return new int_32(r);if(r>=BSON_INT64_MIN&&r<=BSON_INT64_MAX)return new long_1.fromNumber(r)}return new double_1(r)}if(null==r||"object"!==_typeof$2(r))return r;if(r.$undefined)return null;for(var i=Object.keys(r).filter((function(e){return e.startsWith("$")&&null!=r[e]})),o=0;o-1&&r<2534023188e5;return t.legacy?t.relaxed&&n?{$date:e.getTime()}:{$date:getISOString(e)}:t.relaxed&&n?{$date:getISOString(e)}:{$date:{$numberLong:e.getTime().toString()}}}if("number"==typeof e&&!t.relaxed){if(Math.floor(e)===e){var i=e>=BSON_INT64_MIN&&e<=BSON_INT64_MAX;if(e>=BSON_INT32_MIN&&e<=BSON_INT32_MAX)return{$numberInt:e.toString()};if(i)return{$numberLong:e.toString()}}return{$numberDouble:e.toString()}}if(e instanceof RegExp){var o=e.flags;return void 0===o&&(o=e.toString().match(/[gimuy]*$/)[0]),new regexp(e.source,o).toExtendedJSON(t)}return null!=e&&"object"===_typeof$2(e)?serializeDocument(e,t):e}var BSON_TYPE_MAPPINGS={Binary:function(e){return new binary(e.value(),e.subtype)},Code:function(e){return new code(e.code,e.scope)},DBRef:function(e){return new db_ref(e.collection||e.namespace,e.oid,e.db,e.fields)},Decimal128:function(e){return new decimal128(e.bytes)},Double:function(e){return new double_1(e.value)},Int32:function(e){return new int_32(e.value)},Long:function(e){return long_1.fromBits(null!=e.low?e.low:e.low_,null!=e.low?e.high:e.high_,null!=e.low?e.unsigned:e.unsigned_)},MaxKey:function(){return new max_key},MinKey:function(){return new min_key},ObjectID:function(e){return new objectid(e)},ObjectId:function(e){return new objectid(e)},BSONRegExp:function(e){return new regexp(e.pattern,e.options)},Symbol:function(e){return new symbol(e.value)},Timestamp:function(e){return timestamp.fromBits(e.low,e.high)}};function serializeDocument(e,t){if(null==e||"object"!==_typeof$2(e))throw new Error("not an object instance");var r=e._bsontype;if(void 0===r){var n={};for(var i in e)n[i]=serializeValue(e[i],t);return n}if("string"==typeof r){var o=e;if("function"!=typeof o.toExtendedJSON){var s=BSON_TYPE_MAPPINGS[r];if(!s)throw new TypeError("Unrecognized or invalid _bsontype: "+r);o=s(o)}return"Code"===r&&o.scope?o=new code(o.code,serializeValue(o.scope,t)):"DBRef"===r&&o.oid&&(o=new db_ref(o.collection,serializeValue(o.oid,t),o.db,o.fields)),o.toExtendedJSON(t)}throw new Error("_bsontype must be a string, but was: "+_typeof$2(r))}var extended_json={parse:parse,deserialize:deserialize,serialize:serialize,stringify:stringify},FIRST_BIT=128,FIRST_TWO_BITS=192,FIRST_THREE_BITS=224,FIRST_FOUR_BITS=240,FIRST_FIVE_BITS=248,TWO_BIT_CHAR=192,THREE_BIT_CHAR=224,FOUR_BIT_CHAR=240,CONTINUING_CHAR=128;function validateUtf8(e,t,r){for(var n=0,i=t;i= 5, is ".concat(i));if(t.allowObjectSmallerThanBufferSize&&e.length= bson size ").concat(i));if(!t.allowObjectSmallerThanBufferSize&&e.length!==i)throw new Error("buffer length ".concat(e.length," must === bson size ").concat(i));if(i+n>e.length)throw new Error("(bson size ".concat(i," + options.index ").concat(n," must be <= buffer length ").concat(Buffer$4.byteLength(e),")"));if(0!==e[n+i-1])throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00");return deserializeObject(e,n,t,r)}function deserializeObject(e,t,r,n){var i=null!=r.evalFunctions&&r.evalFunctions,o=null!=r.cacheFunctions&&r.cacheFunctions,s=null!=r.cacheFunctionsCrc32&&r.cacheFunctionsCrc32;if(!s)var a=null;var u=null==r.fieldsAsRaw?null:r.fieldsAsRaw,c=null!=r.raw&&r.raw,l="boolean"==typeof r.bsonRegExp&&r.bsonRegExp,f=null!=r.promoteBuffers&&r.promoteBuffers,h=null==r.promoteLongs||r.promoteLongs,d=null==r.promoteValues||r.promoteValues,p=t;if(e.length<5)throw new Error("corrupt bson message < 5 bytes long");var _=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(_<5||_>e.length)throw new Error("corrupt bson message");for(var g=n?[]:{},y=0;;){var m=e[t++];if(0===m)break;for(var b=t;0!==e[b]&&b=Buffer$4.byteLength(e))throw new Error("Bad BSON Document: illegal CString");var w=n?y++:e.toString("utf8",t,b);if(t=b+1,m===constants.BSON_DATA_STRING){var v=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(v<=0||v>e.length-t||0!==e[t+v-1])throw new Error("bad string length in bson");if(!validateUtf8$1(e,t,t+v-1))throw new Error("Invalid UTF-8 string in BSON document");var E=e.toString("utf8",t,t+v-1);g[w]=E,t+=v}else if(m===constants.BSON_DATA_OID){var S=Buffer$4.alloc(12);e.copy(S,0,t,t+12),g[w]=new objectid(S),t+=12}else if(m===constants.BSON_DATA_INT&&!1===d)g[w]=new int_32(e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24);else if(m===constants.BSON_DATA_INT)g[w]=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;else if(m===constants.BSON_DATA_NUMBER&&!1===d)g[w]=new double_1(e.readDoubleLE(t)),t+=8;else if(m===constants.BSON_DATA_NUMBER)g[w]=e.readDoubleLE(t),t+=8;else if(m===constants.BSON_DATA_DATE){var A=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,N=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;g[w]=new Date(new long_1(A,N).toNumber())}else if(m===constants.BSON_DATA_BOOLEAN){if(0!==e[t]&&1!==e[t])throw new Error("illegal boolean type value");g[w]=1===e[t++]}else if(m===constants.BSON_DATA_OBJECT){var O=t,T=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24;if(T<=0||T>e.length-t)throw new Error("bad embedded document length in bson");g[w]=c?e.slice(t,t+T):deserializeObject(e,O,r,!1),t+=T}else if(m===constants.BSON_DATA_ARRAY){var I=t,B=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24,R=r,D=t+B;if(u&&u[w]){for(var C in R={},r)R[C]=r[C];R.raw=!0}if(g[w]=deserializeObject(e,I,R,!0),0!==e[(t+=B)-1])throw new Error("invalid array terminator byte");if(t!==D)throw new Error("corrupted array bson")}else if(m===constants.BSON_DATA_UNDEFINED)g[w]=void 0;else if(m===constants.BSON_DATA_NULL)g[w]=null;else if(m===constants.BSON_DATA_LONG){var P=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,$=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,M=new long_1(P,$);g[w]=h&&!0===d&&M.lessThanOrEqual(JS_INT_MAX_LONG)&&M.greaterThanOrEqual(JS_INT_MIN_LONG)?M.toNumber():M}else if(m===constants.BSON_DATA_DECIMAL128){var L=Buffer$4.alloc(16);e.copy(L,0,t,t+16),t+=16;var j=new decimal128(L);g[w]=j.toObject?j.toObject():j}else if(m===constants.BSON_DATA_BINARY){var x=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,U=x,k=e[t++];if(x<0)throw new Error("Negative binary type element size found");if(x>Buffer$4.byteLength(e))throw new Error("Binary type size larger than document size");if(null!=e.slice){if(k===binary.SUBTYPE_BYTE_ARRAY){if((x=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24)<0)throw new Error("Negative binary type element size found for subtype 0x02");if(x>U-4)throw new Error("Binary type with subtype 0x02 contains to long binary size");if(xU-4)throw new Error("Binary type with subtype 0x02 contains to long binary size");if(x=e.length)throw new Error("Bad BSON Document: illegal CString");var F=e.toString("utf8",t,b);for(b=t=b+1;0!==e[b]&&b=e.length)throw new Error("Bad BSON Document: illegal CString");var q=e.toString("utf8",t,b);t=b+1;var W=new Array(q.length);for(b=0;b=e.length)throw new Error("Bad BSON Document: illegal CString");var Y=e.toString("utf8",t,b);for(b=t=b+1;0!==e[b]&&b=e.length)throw new Error("Bad BSON Document: illegal CString");var H=e.toString("utf8",t,b);t=b+1,g[w]=new regexp(Y,H)}else if(m===constants.BSON_DATA_SYMBOL){var K=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(K<=0||K>e.length-t||0!==e[t+K-1])throw new Error("bad string length in bson");var G=e.toString("utf8",t,t+K-1);g[w]=d?G:new symbol(G),t+=K}else if(m===constants.BSON_DATA_TIMESTAMP){var J=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,V=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;g[w]=new timestamp(J,V)}else if(m===constants.BSON_DATA_MIN_KEY)g[w]=new min_key;else if(m===constants.BSON_DATA_MAX_KEY)g[w]=new max_key;else if(m===constants.BSON_DATA_CODE){var X=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(X<=0||X>e.length-t||0!==e[t+X-1])throw new Error("bad string length in bson");var Q=e.toString("utf8",t,t+X-1);if(i)if(o){var Z=s?a(Q):Q;g[w]=isolateEvalWithHash(functionCache,Z,Q,g)}else g[w]=isolateEval(Q);else g[w]=new code(Q);t+=X}else if(m===constants.BSON_DATA_CODE_W_SCOPE){var ee=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(ee<13)throw new Error("code_w_scope total size shorter minimum expected length");var te=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(te<=0||te>e.length-t||0!==e[t+te-1])throw new Error("bad string length in bson");var re=e.toString("utf8",t,t+te-1),ne=t+=te,ie=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24,oe=deserializeObject(e,ne,r,!1);if(t+=ie,ee<8+ie+te)throw new Error("code_w_scope total size is to short, truncating scope");if(ee>8+ie+te)throw new Error("code_w_scope total size is to long, clips outer document");if(i){if(o){var se=s?a(re):re;g[w]=isolateEvalWithHash(functionCache,se,re,g)}else g[w]=isolateEval(re);g[w].scope=oe}else g[w]=new code(re,oe)}else{if(m!==constants.BSON_DATA_DBPOINTER)throw new Error("Detected unknown BSON type "+m.toString(16)+' for fieldname "'+w+'", are you using the latest BSON parser?');var ae=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(ae<=0||ae>e.length-t||0!==e[t+ae-1])throw new Error("bad string length in bson");if(!validateUtf8$1(e,t,t+ae-1))throw new Error("Invalid UTF-8 string in BSON document");var ue=e.toString("utf8",t,t+ae-1);t+=ae;var ce=Buffer$4.alloc(12);e.copy(ce,0,t,t+12);var le=new objectid(ce);t+=12,g[w]=new db_ref(ue,le)}}if(_!==t-p){if(n)throw new Error("corrupt array bson");throw new Error("corrupt object bson")}var fe=Object.keys(g).filter((function(e){return e.startsWith("$")})),he=!0;if(fe.forEach((function(e){-1===["$ref","$id","$db"].indexOf(e)&&(he=!1)})),!he)return g;if(null!=g.$id&&null!=g.$ref){var de=Object.assign({},g);return delete de.$ref,delete de.$id,delete de.$db,new db_ref(g.$ref,g.$id,g.$db||null,de)}return g}function isolateEvalWithHash(functionCache,hash,functionString,object){var value=null;return null==functionCache[hash]&&(eval("value = "+functionString),functionCache[hash]=value),functionCache[hash].bind(object)}function isolateEval(functionString){var value=null;return eval("value = "+functionString),value}var deserializer=deserialize$1;function readIEEE754(e,t,r,n,i){var o,s,a="big"===r,u=8*i-n-1,c=(1<>1,f=-7,h=a?0:i-1,d=a?1:-1,p=e[t+h];for(h+=d,o=p&(1<<-f)-1,p>>=-f,f+=u;f>0;o=256*o+e[t+h],h+=d,f-=8);for(s=o&(1<<-f)-1,o>>=-f,f+=n;f>0;s=256*s+e[t+h],h+=d,f-=8);if(0===o)o=1-l;else{if(o===c)return s?NaN:1/0*(p?-1:1);s+=Math.pow(2,n),o-=l}return(p?-1:1)*s*Math.pow(2,o-n)}function writeIEEE754(e,t,r,n,i,o){var s,a,u,c="big"===n,l=8*o-i-1,f=(1<>1,d=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=c?o-1:0,_=c?-1:1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=f):(s=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-s))<1&&(s--,u*=2),(t+=s+h>=1?d/u:d*Math.pow(2,1-h))*u>=2&&(s++,u/=2),s+h>=f?(a=0,s=f):s+h>=1?(a=(t*u-1)*Math.pow(2,i),s+=h):(a=t*Math.pow(2,h-1)*Math.pow(2,i),s=0)),isNaN(t)&&(a=0);i>=8;)e[r+p]=255&a,p+=_,a/=256,i-=8;for(s=s<0;)e[r+p]=255&s,p+=_,s/=256,l-=8;e[r+p-_]|=128*g}var float_parser={readIEEE754:readIEEE754,writeIEEE754:writeIEEE754};function _typeof$3(e){return(_typeof$3="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var Buffer$5=buffer__WEBPACK_IMPORTED_MODULE_1___default.a.Buffer,writeIEEE754$1=float_parser.writeIEEE754,normalizedFunctionString$1=utils.normalizedFunctionString,regexp$1=/\x00/,ignoreKeys=new Set(["$db","$ref","$id","$clusterTime"]),isDate$1=function(e){return"object"===_typeof$3(e)&&"[object Date]"===Object.prototype.toString.call(e)},isRegExp$1=function(e){return"[object RegExp]"===Object.prototype.toString.call(e)};function serializeString(e,t,r,n,i){e[n++]=constants.BSON_DATA_STRING;var o=i?e.write(t,n,"ascii"):e.write(t,n,"utf8");e[(n=n+o+1)-1]=0;var s=e.write(r,n+4,"utf8");return e[n+3]=s+1>>24&255,e[n+2]=s+1>>16&255,e[n+1]=s+1>>8&255,e[n]=s+1&255,n=n+4+s,e[n++]=0,n}function serializeNumber(e,t,r,n,i){if(Math.floor(r)===r&&r>=constants.JS_INT_MIN&&r<=constants.JS_INT_MAX)if(r>=constants.BSON_INT32_MIN&&r<=constants.BSON_INT32_MAX)e[n++]=constants.BSON_DATA_INT,n+=i?e.write(t,n,"ascii"):e.write(t,n,"utf8"),e[n++]=0,e[n++]=255&r,e[n++]=r>>8&255,e[n++]=r>>16&255,e[n++]=r>>24&255;else if(r>=constants.JS_INT_MIN&&r<=constants.JS_INT_MAX){e[n++]=constants.BSON_DATA_NUMBER,n+=i?e.write(t,n,"ascii"):e.write(t,n,"utf8"),e[n++]=0,writeIEEE754$1(e,r,n,"little",52,8),n+=8}else{e[n++]=constants.BSON_DATA_LONG,n+=i?e.write(t,n,"ascii"):e.write(t,n,"utf8"),e[n++]=0;var o=long_1.fromNumber(r),s=o.getLowBits(),a=o.getHighBits();e[n++]=255&s,e[n++]=s>>8&255,e[n++]=s>>16&255,e[n++]=s>>24&255,e[n++]=255&a,e[n++]=a>>8&255,e[n++]=a>>16&255,e[n++]=a>>24&255}else e[n++]=constants.BSON_DATA_NUMBER,n+=i?e.write(t,n,"ascii"):e.write(t,n,"utf8"),e[n++]=0,writeIEEE754$1(e,r,n,"little",52,8),n+=8;return n}function serializeNull(e,t,r,n,i){return e[n++]=constants.BSON_DATA_NULL,n+=i?e.write(t,n,"ascii"):e.write(t,n,"utf8"),e[n++]=0,n}function serializeBoolean(e,t,r,n,i){return e[n++]=constants.BSON_DATA_BOOLEAN,n+=i?e.write(t,n,"ascii"):e.write(t,n,"utf8"),e[n++]=0,e[n++]=r?1:0,n}function serializeDate(e,t,r,n,i){e[n++]=constants.BSON_DATA_DATE,n+=i?e.write(t,n,"ascii"):e.write(t,n,"utf8"),e[n++]=0;var o=long_1.fromNumber(r.getTime()),s=o.getLowBits(),a=o.getHighBits();return e[n++]=255&s,e[n++]=s>>8&255,e[n++]=s>>16&255,e[n++]=s>>24&255,e[n++]=255&a,e[n++]=a>>8&255,e[n++]=a>>16&255,e[n++]=a>>24&255,n}function serializeRegExp(e,t,r,n,i){if(e[n++]=constants.BSON_DATA_REGEXP,n+=i?e.write(t,n,"ascii"):e.write(t,n,"utf8"),e[n++]=0,r.source&&null!=r.source.match(regexp$1))throw Error("value "+r.source+" must not contain null bytes");return n+=e.write(r.source,n,"utf8"),e[n++]=0,r.ignoreCase&&(e[n++]=105),r.global&&(e[n++]=115),r.multiline&&(e[n++]=109),e[n++]=0,n}function serializeBSONRegExp(e,t,r,n,i){if(e[n++]=constants.BSON_DATA_REGEXP,n+=i?e.write(t,n,"ascii"):e.write(t,n,"utf8"),e[n++]=0,null!=r.pattern.match(regexp$1))throw Error("pattern "+r.pattern+" must not contain null bytes");return n+=e.write(r.pattern,n,"utf8"),e[n++]=0,n+=e.write(r.options.split("").sort().join(""),n,"utf8"),e[n++]=0,n}function serializeMinMax(e,t,r,n,i){return null===r?e[n++]=constants.BSON_DATA_NULL:"MinKey"===r._bsontype?e[n++]=constants.BSON_DATA_MIN_KEY:e[n++]=constants.BSON_DATA_MAX_KEY,n+=i?e.write(t,n,"ascii"):e.write(t,n,"utf8"),e[n++]=0,n}function serializeObjectId(e,t,r,n,i){if(e[n++]=constants.BSON_DATA_OID,n+=i?e.write(t,n,"ascii"):e.write(t,n,"utf8"),e[n++]=0,"string"==typeof r.id)e.write(r.id,n,"binary");else{if(!r.id||!r.id.copy)throw new TypeError("object ["+JSON.stringify(r)+"] is not a valid ObjectId");r.id.copy(e,n,0,12)}return n+12}function serializeBuffer(e,t,r,n,i){e[n++]=constants.BSON_DATA_BINARY,n+=i?e.write(t,n,"ascii"):e.write(t,n,"utf8"),e[n++]=0;var o=r.length;return e[n++]=255&o,e[n++]=o>>8&255,e[n++]=o>>16&255,e[n++]=o>>24&255,e[n++]=constants.BSON_BINARY_SUBTYPE_DEFAULT,r.copy(e,n,0,o),n+=o}function serializeObject(e,t,r,n,i,o,s,a,u,c){for(var l=0;l>8&255,e[n++]=o>>16&255,e[n++]=o>>24&255,e[n++]=255&s,e[n++]=s>>8&255,e[n++]=s>>16&255,e[n++]=s>>24&255,n}function serializeInt32(e,t,r,n,i){return e[n++]=constants.BSON_DATA_INT,n+=i?e.write(t,n,"ascii"):e.write(t,n,"utf8"),e[n++]=0,e[n++]=255&r,e[n++]=r>>8&255,e[n++]=r>>16&255,e[n++]=r>>24&255,n}function serializeDouble(e,t,r,n,i){return e[n++]=constants.BSON_DATA_NUMBER,n+=i?e.write(t,n,"ascii"):e.write(t,n,"utf8"),e[n++]=0,writeIEEE754$1(e,r.value,n,"little",52,8),n+=8}function serializeFunction(e,t,r,n,i,o,s){e[n++]=constants.BSON_DATA_CODE,n+=s?e.write(t,n,"ascii"):e.write(t,n,"utf8"),e[n++]=0;var a=normalizedFunctionString$1(r),u=e.write(a,n+4,"utf8")+1;return e[n]=255&u,e[n+1]=u>>8&255,e[n+2]=u>>16&255,e[n+3]=u>>24&255,n=n+4+u-1,e[n++]=0,n}function serializeCode(e,t,r,n,i,o,s,a,u){if(r.scope&&"object"===_typeof$3(r.scope)){e[n++]=constants.BSON_DATA_CODE_W_SCOPE,n+=u?e.write(t,n,"ascii"):e.write(t,n,"utf8"),e[n++]=0;var c=n,l="string"==typeof r.code?r.code:r.code.toString();n+=4;var f=e.write(l,n+4,"utf8")+1;e[n]=255&f,e[n+1]=f>>8&255,e[n+2]=f>>16&255,e[n+3]=f>>24&255,e[n+4+f-1]=0,n=n+f+4;var h=serializeInto(e,r.scope,i,n,o+1,s,a);n=h-1;var d=h-c;e[c++]=255&d,e[c++]=d>>8&255,e[c++]=d>>16&255,e[c++]=d>>24&255,e[n++]=0}else{e[n++]=constants.BSON_DATA_CODE,n+=u?e.write(t,n,"ascii"):e.write(t,n,"utf8"),e[n++]=0;var p=r.code.toString(),_=e.write(p,n+4,"utf8")+1;e[n]=255&_,e[n+1]=_>>8&255,e[n+2]=_>>16&255,e[n+3]=_>>24&255,n=n+4+_-1,e[n++]=0}return n}function serializeBinary(e,t,r,n,i){e[n++]=constants.BSON_DATA_BINARY,n+=i?e.write(t,n,"ascii"):e.write(t,n,"utf8"),e[n++]=0;var o=r.value(!0),s=r.position;return r.sub_type===binary.SUBTYPE_BYTE_ARRAY&&(s+=4),e[n++]=255&s,e[n++]=s>>8&255,e[n++]=s>>16&255,e[n++]=s>>24&255,e[n++]=r.sub_type,r.sub_type===binary.SUBTYPE_BYTE_ARRAY&&(s-=4,e[n++]=255&s,e[n++]=s>>8&255,e[n++]=s>>16&255,e[n++]=s>>24&255),o.copy(e,n,0,r.position),n+=r.position}function serializeSymbol(e,t,r,n,i){e[n++]=constants.BSON_DATA_SYMBOL,n+=i?e.write(t,n,"ascii"):e.write(t,n,"utf8"),e[n++]=0;var o=e.write(r.value,n+4,"utf8")+1;return e[n]=255&o,e[n+1]=o>>8&255,e[n+2]=o>>16&255,e[n+3]=o>>24&255,n=n+4+o-1,e[n++]=0,n}function serializeDBRef(e,t,r,n,i,o,s){e[n++]=constants.BSON_DATA_OBJECT,n+=s?e.write(t,n,"ascii"):e.write(t,n,"utf8"),e[n++]=0;var a,u=n,c={$ref:r.collection||r.namespace,$id:r.oid};null!=r.db&&(c.$db=r.db);var l=(a=serializeInto(e,c=Object.assign(c,r.fields),!1,n,i+1,o))-u;return e[u++]=255&l,e[u++]=l>>8&255,e[u++]=l>>16&255,e[u++]=l>>24&255,a}function serializeInto(e,t,r,n,i,o,s,a){n=n||0,(a=a||[]).push(t);var u=n+4;if(Array.isArray(t))for(var c=0;c>8&255,e[n++]=E>>16&255,e[n++]=E>>24&255,u}var serializer=serializeInto;function _typeof$4(e){return(_typeof$4="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var Buffer$6=buffer__WEBPACK_IMPORTED_MODULE_1___default.a.Buffer,normalizedFunctionString$2=utils.normalizedFunctionString;function isDate$2(e){return"object"===_typeof$4(e)&&"[object Date]"===Object.prototype.toString.call(e)}function calculateObjectSize(e,t,r){var n=5;if(Array.isArray(e))for(var i=0;i=constants.JS_INT_MIN&&t<=constants.JS_INT_MAX&&t>=constants.BSON_INT32_MIN&&t<=constants.BSON_INT32_MAX?(null!=e?Buffer$6.byteLength(e,"utf8")+1:0)+5:(null!=e?Buffer$6.byteLength(e,"utf8")+1:0)+9;case"undefined":return n||!i?(null!=e?Buffer$6.byteLength(e,"utf8")+1:0)+1:0;case"boolean":return(null!=e?Buffer$6.byteLength(e,"utf8")+1:0)+2;case"object":if(null==t||"MinKey"===t._bsontype||"MaxKey"===t._bsontype)return(null!=e?Buffer$6.byteLength(e,"utf8")+1:0)+1;if("ObjectId"===t._bsontype||"ObjectID"===t._bsontype)return(null!=e?Buffer$6.byteLength(e,"utf8")+1:0)+13;if(t instanceof Date||isDate$2(t))return(null!=e?Buffer$6.byteLength(e,"utf8")+1:0)+9;if(void 0!==Buffer$6&&Buffer$6.isBuffer(t))return(null!=e?Buffer$6.byteLength(e,"utf8")+1:0)+6+t.length;if("Long"===t._bsontype||"Double"===t._bsontype||"Timestamp"===t._bsontype)return(null!=e?Buffer$6.byteLength(e,"utf8")+1:0)+9;if("Decimal128"===t._bsontype)return(null!=e?Buffer$6.byteLength(e,"utf8")+1:0)+17;if("Code"===t._bsontype)return null!=t.scope&&Object.keys(t.scope).length>0?(null!=e?Buffer$6.byteLength(e,"utf8")+1:0)+1+4+4+Buffer$6.byteLength(t.code.toString(),"utf8")+1+calculateObjectSize(t.scope,r,i):(null!=e?Buffer$6.byteLength(e,"utf8")+1:0)+1+4+Buffer$6.byteLength(t.code.toString(),"utf8")+1;if("Binary"===t._bsontype)return t.sub_type===binary.SUBTYPE_BYTE_ARRAY?(null!=e?Buffer$6.byteLength(e,"utf8")+1:0)+(t.position+1+4+1+4):(null!=e?Buffer$6.byteLength(e,"utf8")+1:0)+(t.position+1+4+1);if("Symbol"===t._bsontype)return(null!=e?Buffer$6.byteLength(e,"utf8")+1:0)+Buffer$6.byteLength(t.value,"utf8")+4+1+1;if("DBRef"===t._bsontype){var o=Object.assign({$ref:t.collection,$id:t.oid},t.fields);return null!=t.db&&(o.$db=t.db),(null!=e?Buffer$6.byteLength(e,"utf8")+1:0)+1+calculateObjectSize(o,r,i)}return t instanceof RegExp||"[object RegExp]"===Object.prototype.toString.call(t)?(null!=e?Buffer$6.byteLength(e,"utf8")+1:0)+1+Buffer$6.byteLength(t.source,"utf8")+1+(t.global?1:0)+(t.ignoreCase?1:0)+(t.multiline?1:0)+1:"BSONRegExp"===t._bsontype?(null!=e?Buffer$6.byteLength(e,"utf8")+1:0)+1+Buffer$6.byteLength(t.pattern,"utf8")+1+Buffer$6.byteLength(t.options,"utf8")+1:(null!=e?Buffer$6.byteLength(e,"utf8")+1:0)+calculateObjectSize(t,r,i)+1;case"function":if(t instanceof RegExp||"[object RegExp]"===Object.prototype.toString.call(t)||"[object RegExp]"===String.call(t))return(null!=e?Buffer$6.byteLength(e,"utf8")+1:0)+1+Buffer$6.byteLength(t.source,"utf8")+1+(t.global?1:0)+(t.ignoreCase?1:0)+(t.multiline?1:0)+1;if(r&&null!=t.scope&&Object.keys(t.scope).length>0)return(null!=e?Buffer$6.byteLength(e,"utf8")+1:0)+1+4+4+Buffer$6.byteLength(normalizedFunctionString$2(t),"utf8")+1+calculateObjectSize(t.scope,r,i);if(r)return(null!=e?Buffer$6.byteLength(e,"utf8")+1:0)+1+4+Buffer$6.byteLength(normalizedFunctionString$2(t),"utf8")+1}return 0}var calculate_size=calculateObjectSize,Buffer$7=buffer__WEBPACK_IMPORTED_MODULE_1___default.a.Buffer,ensure_buffer=function(e){if(e instanceof Buffer$7)return e;if(e instanceof Uint8Array)return Buffer$7.from(e.buffer);throw new TypeError("Must use either Buffer or Uint8Array")},Buffer$8=buffer__WEBPACK_IMPORTED_MODULE_1___default.a.Buffer,MAXSIZE=17825792,buffer$1=Buffer$8.alloc(MAXSIZE);function setInternalBufferSize(e){buffer$1.length * @license MIT */ var n=r(14),i=r(15),o=r(16);function s(){return u.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function a(e,t){if(s()=s())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s().toString(16)+" bytes");return 0|e}function p(e,t){if(u.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var r=e.length;if(0===r)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return k(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return z(e).length;default:if(n)return k(e).length;t=(""+t).toLowerCase(),n=!0}}function _(e,t,r){var n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return B(this,t,r);case"utf8":case"utf-8":return O(this,t,r);case"ascii":return T(this,t,r);case"latin1":case"binary":return I(this,t,r);case"base64":return N(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return R(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function g(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function y(e,t,r,n,i){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=i?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(i)return-1;r=e.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof t&&(t=u.from(t,n)),u.isBuffer(t))return 0===t.length?-1:m(e,t,r,n,i);if("number"==typeof t)return t&=255,u.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):m(e,[t],r,n,i);throw new TypeError("val must be string, number or Buffer")}function m(e,t,r,n,i){var o,s=1,a=e.length,u=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;s=2,a/=2,u/=2,r/=2}function c(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(i){var l=-1;for(o=r;oa&&(r=a-u),o=r;o>=0;o--){for(var f=!0,h=0;hi&&(n=i):n=i;var o=t.length;if(o%2!=0)throw new TypeError("Invalid hex string");n>o/2&&(n=o/2);for(var s=0;s>8,i=r%256,o.push(i),o.push(n);return o}(t,e.length-r),e,r,n)}function N(e,t,r){return 0===t&&r===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,r))}function O(e,t,r){r=Math.min(e.length,r);for(var n=[],i=t;i239?4:c>223?3:c>191?2:1;if(i+f<=r)switch(f){case 1:c<128&&(l=c);break;case 2:128==(192&(o=e[i+1]))&&(u=(31&c)<<6|63&o)>127&&(l=u);break;case 3:o=e[i+1],s=e[i+2],128==(192&o)&&128==(192&s)&&(u=(15&c)<<12|(63&o)<<6|63&s)>2047&&(u<55296||u>57343)&&(l=u);break;case 4:o=e[i+1],s=e[i+2],a=e[i+3],128==(192&o)&&128==(192&s)&&128==(192&a)&&(u=(15&c)<<18|(63&o)<<12|(63&s)<<6|63&a)>65535&&u<1114112&&(l=u)}null===l?(l=65533,f=1):l>65535&&(l-=65536,n.push(l>>>10&1023|55296),l=56320|1023&l),n.push(l),i+=f}return function(e){var t=e.length;if(t<=4096)return String.fromCharCode.apply(String,e);var r="",n=0;for(;n0&&(e=this.toString("hex",0,r).match(/.{2}/g).join(" "),this.length>r&&(e+=" ... ")),""},u.prototype.compare=function(e,t,r,n,i){if(!u.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),t<0||r>e.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&t>=r)return 0;if(n>=i)return-1;if(t>=r)return 1;if(this===e)return 0;for(var o=(i>>>=0)-(n>>>=0),s=(r>>>=0)-(t>>>=0),a=Math.min(o,s),c=this.slice(n,i),l=e.slice(t,r),f=0;fi)&&(r=i),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return b(this,e,t,r);case"utf8":case"utf-8":return w(this,e,t,r);case"ascii":return v(this,e,t,r);case"latin1":case"binary":return E(this,e,t,r);case"base64":return S(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function T(e,t,r){var n="";r=Math.min(e.length,r);for(var i=t;in)&&(r=n);for(var i="",o=t;or)throw new RangeError("Trying to access beyond buffer length")}function C(e,t,r,n,i,o){if(!u.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}function P(e,t,r,n){t<0&&(t=65535+t+1);for(var i=0,o=Math.min(e.length-r,2);i>>8*(n?i:1-i)}function $(e,t,r,n){t<0&&(t=4294967295+t+1);for(var i=0,o=Math.min(e.length-r,4);i>>8*(n?i:3-i)&255}function M(e,t,r,n,i,o){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function L(e,t,r,n,o){return o||M(e,0,r,4),i.write(e,t,r,n,23,4),r+4}function j(e,t,r,n,o){return o||M(e,0,r,8),i.write(e,t,r,n,52,8),r+8}u.prototype.slice=function(e,t){var r,n=this.length;if((e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t0&&(i*=256);)n+=this[e+--t]*i;return n},u.prototype.readUInt8=function(e,t){return t||D(e,1,this.length),this[e]},u.prototype.readUInt16LE=function(e,t){return t||D(e,2,this.length),this[e]|this[e+1]<<8},u.prototype.readUInt16BE=function(e,t){return t||D(e,2,this.length),this[e]<<8|this[e+1]},u.prototype.readUInt32LE=function(e,t){return t||D(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},u.prototype.readUInt32BE=function(e,t){return t||D(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},u.prototype.readIntLE=function(e,t,r){e|=0,t|=0,r||D(e,t,this.length);for(var n=this[e],i=1,o=0;++o=(i*=128)&&(n-=Math.pow(2,8*t)),n},u.prototype.readIntBE=function(e,t,r){e|=0,t|=0,r||D(e,t,this.length);for(var n=t,i=1,o=this[e+--n];n>0&&(i*=256);)o+=this[e+--n]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*t)),o},u.prototype.readInt8=function(e,t){return t||D(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},u.prototype.readInt16LE=function(e,t){t||D(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt16BE=function(e,t){t||D(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt32LE=function(e,t){return t||D(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},u.prototype.readInt32BE=function(e,t){return t||D(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},u.prototype.readFloatLE=function(e,t){return t||D(e,4,this.length),i.read(this,e,!0,23,4)},u.prototype.readFloatBE=function(e,t){return t||D(e,4,this.length),i.read(this,e,!1,23,4)},u.prototype.readDoubleLE=function(e,t){return t||D(e,8,this.length),i.read(this,e,!0,52,8)},u.prototype.readDoubleBE=function(e,t){return t||D(e,8,this.length),i.read(this,e,!1,52,8)},u.prototype.writeUIntLE=function(e,t,r,n){(e=+e,t|=0,r|=0,n)||C(this,e,t,r,Math.pow(2,8*r)-1,0);var i=1,o=0;for(this[t]=255&e;++o=0&&(o*=256);)this[t+i]=e/o&255;return t+r},u.prototype.writeUInt8=function(e,t,r){return e=+e,t|=0,r||C(this,e,t,1,255,0),u.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},u.prototype.writeUInt16LE=function(e,t,r){return e=+e,t|=0,r||C(this,e,t,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):P(this,e,t,!0),t+2},u.prototype.writeUInt16BE=function(e,t,r){return e=+e,t|=0,r||C(this,e,t,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):P(this,e,t,!1),t+2},u.prototype.writeUInt32LE=function(e,t,r){return e=+e,t|=0,r||C(this,e,t,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):$(this,e,t,!0),t+4},u.prototype.writeUInt32BE=function(e,t,r){return e=+e,t|=0,r||C(this,e,t,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):$(this,e,t,!1),t+4},u.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t|=0,!n){var i=Math.pow(2,8*r-1);C(this,e,t,r,i-1,-i)}var o=0,s=1,a=0;for(this[t]=255&e;++o>0)-a&255;return t+r},u.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t|=0,!n){var i=Math.pow(2,8*r-1);C(this,e,t,r,i-1,-i)}var o=r-1,s=1,a=0;for(this[t+o]=255&e;--o>=0&&(s*=256);)e<0&&0===a&&0!==this[t+o+1]&&(a=1),this[t+o]=(e/s>>0)-a&255;return t+r},u.prototype.writeInt8=function(e,t,r){return e=+e,t|=0,r||C(this,e,t,1,127,-128),u.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},u.prototype.writeInt16LE=function(e,t,r){return e=+e,t|=0,r||C(this,e,t,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):P(this,e,t,!0),t+2},u.prototype.writeInt16BE=function(e,t,r){return e=+e,t|=0,r||C(this,e,t,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):P(this,e,t,!1),t+2},u.prototype.writeInt32LE=function(e,t,r){return e=+e,t|=0,r||C(this,e,t,4,2147483647,-2147483648),u.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):$(this,e,t,!0),t+4},u.prototype.writeInt32BE=function(e,t,r){return e=+e,t|=0,r||C(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):$(this,e,t,!1),t+4},u.prototype.writeFloatLE=function(e,t,r){return L(this,e,t,!0,r)},u.prototype.writeFloatBE=function(e,t,r){return L(this,e,t,!1,r)},u.prototype.writeDoubleLE=function(e,t,r){return j(this,e,t,!0,r)},u.prototype.writeDoubleBE=function(e,t,r){return j(this,e,t,!1,r)},u.prototype.copy=function(e,t,r,n){if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t=0;--i)e[i+t]=this[i+r];else if(o<1e3||!u.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(o=t;o55295&&r<57344){if(!i){if(r>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(s+1===n){(t-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;o.push(r)}else if(r<2048){if((t-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function z(e){return n.toByteArray(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(x,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function F(e,t,r,n){for(var i=0;i=t.length||i>=e.length);++i)t[i+r]=e[i];return i}}).call(this,r(3))},function(e,t){e.exports=n;var r=null;try{r=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch(e){}function n(e,t,r){this.low=0|e,this.high=0|t,this.unsigned=!!r}function i(e){return!0===(e&&e.__isLong__)}n.prototype.__isLong__,Object.defineProperty(n.prototype,"__isLong__",{value:!0}),n.isLong=i;var o={},s={};function a(e,t){var r,n,i;return t?(i=0<=(e>>>=0)&&e<256)&&(n=s[e])?n:(r=c(e,(0|e)<0?-1:0,!0),i&&(s[e]=r),r):(i=-128<=(e|=0)&&e<128)&&(n=o[e])?n:(r=c(e,e<0?-1:0,!1),i&&(o[e]=r),r)}function u(e,t){if(isNaN(e))return t?m:y;if(t){if(e<0)return m;if(e>=p)return S}else{if(e<=-_)return A;if(e+1>=_)return E}return e<0?u(-e,t).neg():c(e%d|0,e/d|0,t)}function c(e,t,r){return new n(e,t,r)}n.fromInt=a,n.fromNumber=u,n.fromBits=c;var l=Math.pow;function f(e,t,r){if(0===e.length)throw Error("empty string");if("NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return y;if("number"==typeof t?(r=t,t=!1):t=!!t,(r=r||10)<2||360)throw Error("interior hyphen");if(0===n)return f(e.substring(1),t,r).neg();for(var i=u(l(r,8)),o=y,s=0;s>>0:this.low},N.toNumber=function(){return this.unsigned?(this.high>>>0)*d+(this.low>>>0):this.high*d+(this.low>>>0)},N.toString=function(e){if((e=e||10)<2||36>>0).toString(e);if((o=a).isZero())return c+s;for(;c.length<6;)c="0"+c;s=""+c+s}},N.getHighBits=function(){return this.high},N.getHighBitsUnsigned=function(){return this.high>>>0},N.getLowBits=function(){return this.low},N.getLowBitsUnsigned=function(){return this.low>>>0},N.getNumBitsAbs=function(){if(this.isNegative())return this.eq(A)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&0==(e&1<=0},N.isOdd=function(){return 1==(1&this.low)},N.isEven=function(){return 0==(1&this.low)},N.equals=function(e){return i(e)||(e=h(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&(this.high===e.high&&this.low===e.low)},N.eq=N.equals,N.notEquals=function(e){return!this.eq(e)},N.neq=N.notEquals,N.ne=N.notEquals,N.lessThan=function(e){return this.comp(e)<0},N.lt=N.lessThan,N.lessThanOrEqual=function(e){return this.comp(e)<=0},N.lte=N.lessThanOrEqual,N.le=N.lessThanOrEqual,N.greaterThan=function(e){return this.comp(e)>0},N.gt=N.greaterThan,N.greaterThanOrEqual=function(e){return this.comp(e)>=0},N.gte=N.greaterThanOrEqual,N.ge=N.greaterThanOrEqual,N.compare=function(e){if(i(e)||(e=h(e)),this.eq(e))return 0;var t=this.isNegative(),r=e.isNegative();return t&&!r?-1:!t&&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},N.comp=N.compare,N.negate=function(){return!this.unsigned&&this.eq(A)?A:this.not().add(b)},N.neg=N.negate,N.add=function(e){i(e)||(e=h(e));var t=this.high>>>16,r=65535&this.high,n=this.low>>>16,o=65535&this.low,s=e.high>>>16,a=65535&e.high,u=e.low>>>16,l=0,f=0,d=0,p=0;return d+=(p+=o+(65535&e.low))>>>16,f+=(d+=n+u)>>>16,l+=(f+=r+a)>>>16,l+=t+s,c((d&=65535)<<16|(p&=65535),(l&=65535)<<16|(f&=65535),this.unsigned)},N.subtract=function(e){return i(e)||(e=h(e)),this.add(e.neg())},N.sub=N.subtract,N.multiply=function(e){if(this.isZero())return y;if(i(e)||(e=h(e)),r)return c(r.mul(this.low,this.high,e.low,e.high),r.get_high(),this.unsigned);if(e.isZero())return y;if(this.eq(A))return e.isOdd()?A:y;if(e.eq(A))return this.isOdd()?A:y;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(g)&&e.lt(g))return u(this.toNumber()*e.toNumber(),this.unsigned);var t=this.high>>>16,n=65535&this.high,o=this.low>>>16,s=65535&this.low,a=e.high>>>16,l=65535&e.high,f=e.low>>>16,d=65535&e.low,p=0,_=0,m=0,b=0;return m+=(b+=s*d)>>>16,_+=(m+=o*d)>>>16,m&=65535,_+=(m+=s*f)>>>16,p+=(_+=n*d)>>>16,_&=65535,p+=(_+=o*f)>>>16,_&=65535,p+=(_+=s*l)>>>16,p+=t*d+n*f+o*l+s*a,c((m&=65535)<<16|(b&=65535),(p&=65535)<<16|(_&=65535),this.unsigned)},N.mul=N.multiply,N.divide=function(e){if(i(e)||(e=h(e)),e.isZero())throw Error("division by zero");var t,n,o;if(r)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?c((this.unsigned?r.div_u:r.div_s)(this.low,this.high,e.low,e.high),r.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?m:y;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return m;if(e.gt(this.shru(1)))return w;o=m}else{if(this.eq(A))return e.eq(b)||e.eq(v)?A:e.eq(A)?b:(t=this.shr(1).div(e).shl(1)).eq(y)?e.isNegative()?b:v:(n=this.sub(e.mul(t)),o=t.add(n.div(e)));if(e.eq(A))return this.unsigned?m:y;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();o=y}for(n=this;n.gte(e);){t=Math.max(1,Math.floor(n.toNumber()/e.toNumber()));for(var s=Math.ceil(Math.log(t)/Math.LN2),a=s<=48?1:l(2,s-48),f=u(t),d=f.mul(e);d.isNegative()||d.gt(n);)d=(f=u(t-=a,this.unsigned)).mul(e);f.isZero()&&(f=b),o=o.add(f),n=n.sub(d)}return o},N.div=N.divide,N.modulo=function(e){return i(e)||(e=h(e)),r?c((this.unsigned?r.rem_u:r.rem_s)(this.low,this.high,e.low,e.high),r.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},N.mod=N.modulo,N.rem=N.modulo,N.not=function(){return c(~this.low,~this.high,this.unsigned)},N.and=function(e){return i(e)||(e=h(e)),c(this.low&e.low,this.high&e.high,this.unsigned)},N.or=function(e){return i(e)||(e=h(e)),c(this.low|e.low,this.high|e.high,this.unsigned)},N.xor=function(e){return i(e)||(e=h(e)),c(this.low^e.low,this.high^e.high,this.unsigned)},N.shiftLeft=function(e){return i(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?c(this.low<>>32-e,this.unsigned):c(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):c(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},N.shr=N.shiftRight,N.shiftRightUnsigned=function(e){if(i(e)&&(e=e.toInt()),0===(e&=63))return this;var t=this.high;return e<32?c(this.low>>>e|t<<32-e,t>>>e,this.unsigned):c(32===e?t:t>>>e-32,0,this.unsigned)},N.shru=N.shiftRightUnsigned,N.shr_u=N.shiftRightUnsigned,N.toSigned=function(){return this.unsigned?c(this.low,this.high,!1):this},N.toUnsigned=function(){return this.unsigned?this:c(this.low,this.high,!0)},N.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},N.toBytesLE=function(){var e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]},N.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,255&e,t>>>24,t>>>16&255,t>>>8&255,255&t]},n.fromBytes=function(e,t,r){return r?n.fromBytesLE(e,t):n.fromBytesBE(e,t)},n.fromBytesLE=function(e,t){return new n(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},n.fromBytesBE=function(e,t){return new n(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)}},function(e,t){var r;r=function(){return this}();try{r=r||new Function("return this")()}catch(e){"object"==typeof window&&(r=window)}e.exports=r},function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.throwError=t.printInfo=t.printError=t.printWarn=t.execCallback=t.createPromiseCallback=t.removeParam=t.getHash=t.getQuery=t.toQueryString=t.createSign=t.formatUrl=t.genSeqId=t.isFormData=t.isInstanceOf=t.isNull=t.isPalinObject=t.isUndefined=t.isString=t.isArray=void 0;var i=n(r(21)),o=n(r(24)),s=n(r(25)),a=r(6);function u(e){var t=o.default.stringify(e);return t=(t=(t=t.replace(/=+$/,"")).replace(/\+/g,"-")).replace(/\//g,"_")}t.isArray=function(e){return"[object Array]"===Object.prototype.toString.call(e)},t.isString=function(e){return"string"==typeof e},t.isUndefined=function(e){return void 0===e},t.isPalinObject=function(e){return"[object Object]"===Object.prototype.toString.call(e)},t.isNull=function(e){return"[object Null]"===Object.prototype.toString.call(e)},t.isInstanceOf=function(e,t){return e instanceof t},t.isFormData=function(e){return"[object FormData]"===Object.prototype.toString.call(e)},t.genSeqId=function(){return Math.random().toString(16).slice(2)},t.formatUrl=function(e,t,r){void 0===r&&(r={});var n=/\?/.test(t),i="";for(var o in r)""===i?!n&&(t+="?"):i+="&",i+=o+"="+encodeURIComponent(r[o]);return/^http(s)?\:\/\//.test(t+=i)?t:""+e+t},t.createSign=function(e,t){var r=u(s.default.parse(JSON.stringify({alg:"HS256",typ:"JWT"})))+"."+u(s.default.parse(JSON.stringify(e)));return r+"."+u(i.default(r,t))},t.toQueryString=function(e){void 0===e&&(e={});var t=[];for(var r in e)t.push(r+"="+encodeURIComponent(e[r]));return t.join("&")},t.getQuery=function(e,t){if("undefined"==typeof window)return!1;var r=t||window.location.search,n=new RegExp("(^|&)"+e+"=([^&]*)(&|$)"),i=r.substr(r.indexOf("?")+1).match(n);return null!=i?i[2]:""},t.getHash=function(e){if("undefined"==typeof window)return"";var t=window.location.hash.match(new RegExp("[#?&/]"+e+"=([^&#]*)"));return t?t[1]:""},t.removeParam=function(e,t){var r=t.split("?")[0],n=[],i=-1!==t.indexOf("?")?t.split("?")[1]:"";if(""!==i){for(var o=(n=i.split("&")).length-1;o>=0;o-=1)n[o].split("=")[0]===e&&n.splice(o,1);r=r+"?"+n.join("&")}return r},t.createPromiseCallback=function(){var e;if(!Promise){(e=function(){}).promise={};var t=function(){throw new Error('Your Node runtime does support ES6 Promises. Set "global.Promise" to your preferred implementation of promises.')};return Object.defineProperty(e.promise,"then",{get:t}),Object.defineProperty(e.promise,"catch",{get:t}),e}var r=new Promise((function(t,r){e=function(e,n){return e?r(e):t(n)}}));return e.promise=r,e},t.execCallback=function(e,t,r){if(void 0===r&&(r=null),e&&"function"==typeof e)return e(t,r);if(t)throw t;return r},t.printWarn=function(e,t){console.warn("["+a.getSdkName()+"]["+e+"]:"+t)},t.printError=function(e,t){console.error({code:e,msg:"["+a.getSdkName()+"]["+e+"]:"+t})},t.printInfo=function(e,t){console.log("["+a.getSdkName()+"]["+e+"]:"+t)},t.throwError=function(e,t){throw new Error(JSON.stringify({code:e,msg:"["+a.getSdkName()+"]["+e+"]:"+t}))}},function(e,t,r){var n;e.exports=(n=n||function(e,t){var r=Object.create||function(){function e(){}return function(t){var r;return e.prototype=t,r=new e,e.prototype=null,r}}(),n={},i=n.lib={},o=i.Base={extend:function(e){var t=r(this);return e&&t.mixIn(e),t.hasOwnProperty("init")&&this.init!==t.init||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},s=i.WordArray=o.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||u).stringify(this)},concat:function(e){var t=this.words,r=e.words,n=this.sigBytes,i=e.sigBytes;if(this.clamp(),n%4)for(var o=0;o>>2]>>>24-o%4*8&255;t[n+o>>>2]|=s<<24-(n+o)%4*8}else for(o=0;o>>2]=r[o>>>2];return this.sigBytes+=i,this},clamp:function(){var t=this.words,r=this.sigBytes;t[r>>>2]&=4294967295<<32-r%4*8,t.length=e.ceil(r/4)},clone:function(){var e=o.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var r,n=[],i=function(t){t=t;var r=987654321,n=4294967295;return function(){var i=((r=36969*(65535&r)+(r>>16)&n)<<16)+(t=18e3*(65535&t)+(t>>16)&n)&n;return i/=4294967296,(i+=.5)*(e.random()>.5?1:-1)}},o=0;o>>2]>>>24-i%4*8&255;n.push((o>>>4).toString(16)),n.push((15&o).toString(16))}return n.join("")},parse:function(e){for(var t=e.length,r=[],n=0;n>>3]|=parseInt(e.substr(n,2),16)<<24-n%8*4;return new s.init(r,t/2)}},c=a.Latin1={stringify:function(e){for(var t=e.words,r=e.sigBytes,n=[],i=0;i>>2]>>>24-i%4*8&255;n.push(String.fromCharCode(o))}return n.join("")},parse:function(e){for(var t=e.length,r=[],n=0;n>>2]|=(255&e.charCodeAt(n))<<24-n%4*8;return new s.init(r,t)}},l=a.Utf8={stringify:function(e){try{return decodeURIComponent(escape(c.stringify(e)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(e){return c.parse(unescape(encodeURIComponent(e)))}},f=i.BufferedBlockAlgorithm=o.extend({reset:function(){this._data=new s.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=l.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var r=this._data,n=r.words,i=r.sigBytes,o=this.blockSize,a=i/(4*o),u=(a=t?e.ceil(a):e.max((0|a)-this._minBufferSize,0))*o,c=e.min(4*u,i);if(u){for(var l=0;l-1&&e%1==0&&e-1},B.prototype.set=function(e,t){var r=this.__data__,n=C(r,e);return n<0?r.push([e,t]):r[n][1]=t,this},R.prototype.clear=function(){this.__data__={hash:new I,map:new(A||B),string:new I}},R.prototype.delete=function(e){return M(this,e).delete(e)},R.prototype.get=function(e){return M(this,e).get(e)},R.prototype.has=function(e){return M(this,e).has(e)},R.prototype.set=function(e,t){return M(this,e).set(e,t),this};var x=k((function(e){var t;e=null==(t=e)?"":function(e){if("string"==typeof e)return e;if(W(e))return T?T.call(e):"";var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}(t);var r=[];return i.test(e)&&r.push(""),e.replace(o,(function(e,t,n,i){r.push(n?i.replace(s,"$1"):t||e)})),r}));function U(e){if("string"==typeof e||W(e))return e;var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}function k(e,t){if("function"!=typeof e||t&&"function"!=typeof t)throw new TypeError("Expected a function");var r=function(){var n=arguments,i=t?t.apply(this,n):n[0],o=r.cache;if(o.has(i))return o.get(i);var s=e.apply(this,n);return r.cache=o.set(i,s),s};return r.cache=new(k.Cache||R),r}function z(e,t){return e===t||e!=e&&t!=t}k.Cache=R;var F=Array.isArray;function q(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function W(e){return"symbol"==typeof e||function(e){return!!e&&"object"==typeof e}(e)&&"[object Symbol]"==w.call(e)}e.exports=function(e,t,r){return null==e?e:$(e,t,r)}}).call(this,r(3))},function(e,t,r){(function(t){var r=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,n=/^\w*$/,i=/^\./,o=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,s=/\\(\\)?/g,a=/^\[object .+?Constructor\]$/,u="object"==typeof t&&t&&t.Object===Object&&t,c="object"==typeof self&&self&&self.Object===Object&&self,l=u||c||Function("return this")();var f,h=Array.prototype,d=Function.prototype,p=Object.prototype,_=l["__core-js_shared__"],g=(f=/[^.]+$/.exec(_&&_.keys&&_.keys.IE_PROTO||""))?"Symbol(src)_1."+f:"",y=d.toString,m=p.hasOwnProperty,b=p.toString,w=RegExp("^"+y.call(m).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),v=l.Symbol,E=h.splice,S=M(l,"Map"),A=M(Object,"create"),N=v?v.prototype:void 0,O=N?N.toString:void 0;function T(e){var t=-1,r=e?e.length:0;for(this.clear();++ti?0:i+t),(r=r>i?i:r)<0&&(r+=i),i=t>r?0:r-t>>>0,t>>>=0;for(var o=Array(i);++n-1},I.prototype.set=function(e,t){var r=this.__data__,n=R(r,e);return n<0?r.push([e,t]):r[n][1]=t,this},B.prototype.clear=function(){this.__data__={hash:new T,map:new(S||I),string:new T}},B.prototype.delete=function(e){return $(this,e).delete(e)},B.prototype.get=function(e){return $(this,e).get(e)},B.prototype.has=function(e){return $(this,e).has(e)},B.prototype.set=function(e,t){return $(this,e).set(e,t),this};var j=U((function(e){var t;e=null==(t=e)?"":function(e){if("string"==typeof e)return e;if(F(e))return O?O.call(e):"";var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}(t);var r=[];return i.test(e)&&r.push(""),e.replace(o,(function(e,t,n,i){r.push(n?i.replace(s,"$1"):t||e)})),r}));function x(e){if("string"==typeof e||F(e))return e;var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}function U(e,t){if("function"!=typeof e||t&&"function"!=typeof t)throw new TypeError("Expected a function");var r=function(){var n=arguments,i=t?t.apply(this,n):n[0],o=r.cache;if(o.has(i))return o.get(i);var s=e.apply(this,n);return r.cache=o.set(i,s),s};return r.cache=new(U.Cache||B),r}U.Cache=B;var k=Array.isArray;function z(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function F(e){return"symbol"==typeof e||function(e){return!!e&&"object"==typeof e}(e)&&"[object Symbol]"==b.call(e)}e.exports=function(e,t){return null==e||C(e,t)}}).call(this,r(3))},function(e,t,r){(function(e,r){var n="[object Arguments]",i="[object Function]",o="[object GeneratorFunction]",s="[object Map]",a="[object Set]",u=/\w*$/,c=/^\[object .+?Constructor\]$/,l=/^(?:0|[1-9]\d*)$/,f={};f[n]=f["[object Array]"]=f["[object ArrayBuffer]"]=f["[object DataView]"]=f["[object Boolean]"]=f["[object Date]"]=f["[object Float32Array]"]=f["[object Float64Array]"]=f["[object Int8Array]"]=f["[object Int16Array]"]=f["[object Int32Array]"]=f[s]=f["[object Number]"]=f["[object Object]"]=f["[object RegExp]"]=f[a]=f["[object String]"]=f["[object Symbol]"]=f["[object Uint8Array]"]=f["[object Uint8ClampedArray]"]=f["[object Uint16Array]"]=f["[object Uint32Array]"]=!0,f["[object Error]"]=f[i]=f["[object WeakMap]"]=!1;var h="object"==typeof e&&e&&e.Object===Object&&e,d="object"==typeof self&&self&&self.Object===Object&&self,p=h||d||Function("return this")(),_=t&&!t.nodeType&&t,g=_&&"object"==typeof r&&r&&!r.nodeType&&r,y=g&&g.exports===_;function m(e,t){return e.set(t[0],t[1]),e}function b(e,t){return e.add(t),e}function w(e,t,r,n){var i=-1,o=e?e.length:0;for(n&&o&&(r=e[++i]);++i-1},oe.prototype.set=function(e,t){var r=this.__data__,n=le(r,e);return n<0?r.push([e,t]):r[n][1]=t,this},se.prototype.clear=function(){this.__data__={hash:new ie,map:new(H||oe),string:new ie}},se.prototype.delete=function(e){return _e(this,e).delete(e)},se.prototype.get=function(e){return _e(this,e).get(e)},se.prototype.has=function(e){return _e(this,e).has(e)},se.prototype.set=function(e,t){return _e(this,e).set(e,t),this},ae.prototype.clear=function(){this.__data__=new oe},ae.prototype.delete=function(e){return this.__data__.delete(e)},ae.prototype.get=function(e){return this.__data__.get(e)},ae.prototype.has=function(e){return this.__data__.has(e)},ae.prototype.set=function(e,t){var r=this.__data__;if(r instanceof oe){var n=r.__data__;if(!H||n.length<199)return n.push([e,t]),this;r=this.__data__=new se(n)}return r.set(e,t),this};var ye=F?S(F,Object):function(){return[]},me=function(e){return P.call(e)};function be(e,t){return!!(t=null==t?9007199254740991:t)&&("number"==typeof e||l.test(e))&&e>-1&&e%1==0&&e-1&&e%1==0&&e<=9007199254740991}(e.length)&&!Oe(e)}var Ne=q||function(){return!1};function Oe(e){var t=Te(e)?P.call(e):"";return t==i||t==o}function Te(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function Ie(e){return Ae(e)?ue(e):function(e){if(!we(e))return W(e);var t=[];for(var r in Object(e))C.call(e,r)&&"constructor"!=r&&t.push(r);return t}(e)}r.exports=function(e){return fe(e,!0,!0)}}).call(this,r(3),r(13)(e))},function(e,t,r){"use strict";var n=this&&this.__assign||function(){return(n=Object.assign||function(e){for(var t,r=1,n=arguments.length;r0?s-4:s;for(r=0;r>16&255,u[l++]=t>>8&255,u[l++]=255&t;2===a&&(t=i[e.charCodeAt(r)]<<2|i[e.charCodeAt(r+1)]>>4,u[l++]=255&t);1===a&&(t=i[e.charCodeAt(r)]<<10|i[e.charCodeAt(r+1)]<<4|i[e.charCodeAt(r+2)]>>2,u[l++]=t>>8&255,u[l++]=255&t);return u},t.fromByteArray=function(e){for(var t,r=e.length,i=r%3,o=[],s=0,a=r-i;sa?a:s+16383));1===i?(t=e[r-1],o.push(n[t>>2]+n[t<<4&63]+"==")):2===i&&(t=(e[r-2]<<8)+e[r-1],o.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"="));return o.join("")};for(var n=[],i=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,u=s.length;a0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function l(e,t,r){for(var i,o,s=[],a=t;a>18&63]+n[o>>12&63]+n[o>>6&63]+n[63&o]);return s.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},function(e,t){t.read=function(e,t,r,n,i){var o,s,a=8*i-n-1,u=(1<>1,l=-7,f=r?i-1:0,h=r?-1:1,d=e[t+f];for(f+=h,o=d&(1<<-l)-1,d>>=-l,l+=a;l>0;o=256*o+e[t+f],f+=h,l-=8);for(s=o&(1<<-l)-1,o>>=-l,l+=n;l>0;s=256*s+e[t+f],f+=h,l-=8);if(0===o)o=1-c;else{if(o===u)return s?NaN:1/0*(d?-1:1);s+=Math.pow(2,n),o-=c}return(d?-1:1)*s*Math.pow(2,o-n)},t.write=function(e,t,r,n,i,o){var s,a,u,c=8*o-i-1,l=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:o-1,p=n?1:-1,_=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=l):(s=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-s))<1&&(s--,u*=2),(t+=s+f>=1?h/u:h*Math.pow(2,1-f))*u>=2&&(s++,u/=2),s+f>=l?(a=0,s=l):s+f>=1?(a=(t*u-1)*Math.pow(2,i),s+=f):(a=t*Math.pow(2,f-1)*Math.pow(2,i),s=0));i>=8;e[r+d]=255&a,d+=p,a/=256,i-=8);for(s=s<0;e[r+d]=255&s,d+=p,s/=256,c-=8);e[r+d-p]|=128*_}},function(e,t){var r={}.toString;e.exports=Array.isArray||function(e){return"[object Array]"==r.call(e)}},function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r),Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[r]}})}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.hasOwnProperty.call(e,r)&&n(t,e,r);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.utils=t.events=t.cache=t.adapters=t.constants=void 0;var s=o(r(6));t.constants=s;var a=o(r(19));t.adapters=a;var u=o(r(26));t.cache=u;var c=o(r(28));t.events=c;var l=o(r(4));t.utils=l},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ERRORS=void 0,t.ERRORS={INVALID_PARAMS:"INVALID_PARAMS",INVALID_SYNTAX:"INVALID_SYNTAX",INVALID_OPERATION:"INVALID_OPERATION",OPERATION_FAIL:"OPERATION_FAIL",NETWORK_ERROR:"NETWORK_ERROR",UNKOWN_ERROR:"UNKOWN_ERROR"}},function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r),Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[r]}})}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.hasOwnProperty.call(e,r)&&n(t,e,r);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.useDefaultAdapter=t.useAdapters=t.RUNTIME=void 0;var s,a=o(r(20)),u=r(4);!function(e){e.WEB="web",e.WX_MP="wx_mp"}(s=t.RUNTIME||(t.RUNTIME={})),t.useAdapters=function(e){for(var t=0,r=u.isArray(e)?e:[e];t0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]>>7)^(p<<14|p>>>18)^p>>>3,g=c[d-2],y=(g<<15|g>>>17)^(g<<13|g>>>19)^g>>>10;c[d]=_+c[d-7]+y+c[d-16]}var m=n&i^n&o^i&o,b=(n<<30|n>>>2)^(n<<19|n>>>13)^(n<<10|n>>>22),w=h+((a<<26|a>>>6)^(a<<21|a>>>11)^(a<<7|a>>>25))+(a&l^~a&f)+u[d]+c[d];h=f,f=l,l=a,a=s+w|0,s=o,o=i,i=n,n=w+(b+m)|0}r[0]=r[0]+n|0,r[1]=r[1]+i|0,r[2]=r[2]+o|0,r[3]=r[3]+s|0,r[4]=r[4]+a|0,r[5]=r[5]+l|0,r[6]=r[6]+f|0,r[7]=r[7]+h|0},_doFinalize:function(){var t=this._data,r=t.words,n=8*this._nDataBytes,i=8*t.sigBytes;return r[i>>>5]|=128<<24-i%32,r[14+(i+64>>>9<<4)]=e.floor(n/4294967296),r[15+(i+64>>>9<<4)]=n,t.sigBytes=4*r.length,this._process(),this._hash},clone:function(){var e=o.clone.call(this);return e._hash=this._hash.clone(),e}});t.SHA256=o._createHelper(l),t.HmacSHA256=o._createHmacHelper(l)}(Math),n.SHA256)},function(e,t,r){var n,i,o,s;e.exports=(n=r(5),o=(i=n).lib.Base,s=i.enc.Utf8,void(i.algo.HMAC=o.extend({init:function(e,t){e=this._hasher=new e.init,"string"==typeof t&&(t=s.parse(t));var r=e.blockSize,n=4*r;t.sigBytes>n&&(t=e.finalize(t)),t.clamp();for(var i=this._oKey=t.clone(),o=this._iKey=t.clone(),a=i.words,u=o.words,c=0;c>>2]>>>24-o%4*8&255)<<16|(t[o+1>>>2]>>>24-(o+1)%4*8&255)<<8|t[o+2>>>2]>>>24-(o+2)%4*8&255,a=0;a<4&&o+.75*a>>6*(3-a)&63));var u=n.charAt(64);if(u)for(;i.length%4;)i.push(u);return i.join("")},parse:function(e){var t=e.length,r=this._map,n=this._reverseMap;if(!n){n=this._reverseMap=[];for(var o=0;o>>6-s%4*2;n[o>>>2]|=(a|u)<<24-o%4*8,o++}return i.create(n,o)}(e,t,n)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="},o.enc.Base64)},function(e,t,r){var n;e.exports=(n=r(5),n.enc.Utf8)},function(e,t,r){"use strict";(function(e){var n,i=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),o=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{u(n.next(e))}catch(e){o(e)}}function a(e){try{u(n.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}u((n=n.apply(e,t||[])).next())}))},s=this&&this.__generator||function(e,t){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=0?JSON.parse(i).content:""}u.printWarn(c.ERRORS.INVALID_OPERATION,"current platform's storage is asynchronous, please use getStoreAsync insteed")},t.prototype.getStoreAsync=function(t,r){var n;return o(this,void 0,void 0,(function(){var i;return s(this,(function(o){switch(o.label){case 0:try{if(void 0!==e&&(null===(n=e.env)||void 0===n?void 0:n.tcb_token))return[2,e.env.tcb_token];if(!this._storage)return[2,""]}catch(e){return[2,""]}return r=r||"localCachev1",[4,this._storage.getItem(t)];case 1:return(i=o.sent())&&i.indexOf(r)>=0?[2,JSON.parse(i).content]:[2,""]}}))}))},t.prototype.removeStore=function(e){"async"!==this.mode?this._storage.removeItem(e):u.printWarn(c.ERRORS.INVALID_OPERATION,"current platform's storage is asynchronous, please use removeStoreAsync insteed")},t.prototype.removeStoreAsync=function(e){return o(this,void 0,void 0,(function(){return s(this,(function(t){switch(t.label){case 0:return[4,this._storage.removeItem(e)];case 1:return t.sent(),[2]}}))}))},t}();t.CloudbaseCache=h}).call(this,r(27))},function(e,t){var r,n,i=e.exports={};function o(){throw new Error("setTimeout has not been defined")}function s(){throw new Error("clearTimeout has not been defined")}function a(e){if(r===setTimeout)return setTimeout(e,0);if((r===o||!r)&&setTimeout)return r=setTimeout,setTimeout(e,0);try{return r(e,0)}catch(t){try{return r.call(null,e,0)}catch(t){return r.call(this,e,0)}}}!function(){try{r="function"==typeof setTimeout?setTimeout:o}catch(e){r=o}try{n="function"==typeof clearTimeout?clearTimeout:s}catch(e){n=s}}();var u,c=[],l=!1,f=-1;function h(){l&&u&&(l=!1,u.length?c=u.concat(c):f=-1,c.length&&d())}function d(){if(!l){var e=a(h);l=!0;for(var t=c.length;t;){for(u=c,c=[];++f1)for(var r=1;r0},e}();t.CloudbaseEventEmitter=c;var l=new c;t.addEventListener=function(e,t){l.on(e,t)},t.activateEvent=function(e,t){void 0===t&&(t={}),l.fire(e,t)},t.removeEventListener=function(e,t){l.off(e,t)}},function(e,t,r){"use strict";r.r(t),r.d(t,"Query",(function(){return Ge})),r.d(t,"CollectionReference",(function(){return Xe})),r.d(t,"DocumentReference",(function(){return Ye})),r.d(t,"Db",(function(){return ft}));var n,i={};r.r(i),r.d(i,"Point",(function(){return J})),r.d(i,"LineString",(function(){return V})),r.d(i,"Polygon",(function(){return X})),r.d(i,"MultiPoint",(function(){return Q})),r.d(i,"MultiLineString",(function(){return Z})),r.d(i,"MultiPolygon",(function(){return ee})),function(e){e.DocIDError="文档ID不合法",e.CollNameError="集合名称不合法",e.OpStrError="操作符不合法",e.DirectionError="排序字符不合法",e.IntergerError="must be integer",e.QueryParamTypeError="查询参数必须为对象",e.QueryParamValueError="查询参数对象值不能均为undefined"}(n||(n={}));const o="Number",s="Object",a="Array",u="GeoPoint",c="GeoLineString",l="GeoPolygon",f="GeoMultiPoint",h="GeoMultiLineString",d="GeoMultiPolygon",p="Date",_="ServerDate",g="BsonDate",y=["desc","asc"],m=["<","<=","==",">=",">"];var b;!function(e){e.lt="<",e.gt=">",e.lte="<=",e.gte=">=",e.eq="=="}(b||(b={}));b.eq,b.lt,b.lte,b.gt,b.gte;var w;!function(e){e.WHERE="WHERE",e.DOC="DOC"}(w||(w={}));const v=[],E={};class S extends class{constructor(e){Object.defineProperties(this,{target:{enumerable:!1,writable:!1,configurable:!1,value:e}})}}{constructor(e,t){if(t!==E)throw new TypeError("InternalSymbol cannot be constructed with new operator");super(e)}static for(e){for(let t=0,r=v.length;te.map(e=>U.formatField(e)),U.formatField=e=>{const t=Object.keys(e);let r={};return Array.isArray(e)&&(r=[]),t.forEach(t=>{const n=e[t];let i;switch(U.whichType(n)){case u:i=new J(n.coordinates[0],n.coordinates[1]);break;case c:i=new V(n.coordinates.map(e=>new J(e[0],e[1])));break;case l:i=new X(n.coordinates.map(e=>new V(e.map(([e,t])=>new J(e,t)))));break;case f:i=new Q(n.coordinates.map(e=>new J(e[0],e[1])));break;case h:i=new Z(n.coordinates.map(e=>new V(e.map(([e,t])=>new J(e,t)))));break;case d:i=new ee(n.coordinates.map(e=>new X(e.map(e=>new V(e.map(([e,t])=>new J(e,t)))))));break;case p:i=new Date(1e3*n.$timestamp);break;case s:case a:i=U.formatField(n);break;case _:i=new Date(n.$date);break;default:i=n}Array.isArray(r)?r.push(i):r[t]=i}),r},U.whichType=e=>{let t=Object.prototype.toString.call(e).slice(8,-1);if(t===p)return g;if(t===s){if(e instanceof J)return u;if(e instanceof Date)return p;if(e instanceof j)return _;e.$timestamp?t=p:e.$date?t=_:J.validate(e)?t=u:V.validate(e)?t=c:X.validate(e)?t=l:Q.validate(e)?t=f:Z.validate(e)?t=h:ee.validate(e)&&(t=d)}return t},U.generateDocId=()=>{let e="ABCDEFabcdef0123456789",t="";for(let r=0;r<24;r++)t+=e.charAt(Math.floor(Math.random()*e.length));return t};class k{static isGeopoint(e,t){if(U.whichType(t)!==o)throw new Error("Geo Point must be number type");const r=Math.abs(t);if("latitude"===e&&r>90)throw new Error("latitude should be a number ranges from -90 to 90");if("longitude"===e&&r>180)throw new Error("longitude should be a number ranges from -180 to 180");return!0}static isInteger(e,t){if(!Number.isInteger(t))throw new Error(e+n.IntergerError);return!0}static isFieldOrder(e){if(-1===y.indexOf(e))throw new Error(n.DirectionError);return!0}static isFieldPath(e){if(!/^[a-zA-Z0-9-_\.]/.test(e))throw new Error;return!0}static isOperator(e){if(-1===m.indexOf(e))throw new Error(n.OpStrError);return!0}static isCollName(e){if(!/^[a-zA-Z0-9]([a-zA-Z0-9-_]){1,32}$/.test(e))throw new Error(n.CollNameError);return!0}static isDocID(e){if(!/^([a-fA-F0-9]){24}$/.test(e))throw new Error(n.DocIDError);return!0}}const z=e=>Object.prototype.toString.call(e).slice(8,-1).toLowerCase(),F=e=>"object"===z(e),q=e=>"string"===z(e),W=e=>"number"===z(e),Y=e=>Array.isArray(e),H=e=>"date"===z(e),K=e=>"regexp"===z(e),G=e=>e&&e._internalType instanceof S;class J{constructor(e,t){k.isGeopoint("longitude",e),k.isGeopoint("latitude",t),this.longitude=e,this.latitude=t}parse(e){return{[e]:{type:"Point",coordinates:[this.longitude,this.latitude]}}}toJSON(){return{type:"Point",coordinates:[this.longitude,this.latitude]}}toReadableString(){return`[${this.longitude},${this.latitude}]`}static validate(e){return"Point"===e.type&&Y(e.coordinates)&&k.isGeopoint("longitude",e.coordinates[0])&&k.isGeopoint("latitude",e.coordinates[1])}get _internalType(){return B}}class V{constructor(e){if(!Y(e))throw new TypeError('"points" must be of type Point[]. Received type '+typeof e);if(e.length<2)throw new Error('"points" must contain 2 points at least');e.forEach(e=>{if(!(e instanceof J))throw new TypeError(`"points" must be of type Point[]. Received type ${typeof e}[]`)}),this.points=e}parse(e){return{[e]:{type:"LineString",coordinates:this.points.map(e=>e.toJSON().coordinates)}}}toJSON(){return{type:"LineString",coordinates:this.points.map(e=>e.toJSON().coordinates)}}static validate(e){if("LineString"!==e.type||!Y(e.coordinates))return!1;for(let t of e.coordinates)if(!W(t[0])||!W(t[1]))return!1;return!0}static isClosed(e){const t=e.points[0],r=e.points[e.points.length-1];if(t.latitude===r.latitude&&t.longitude===r.longitude)return!0}get _internalType(){return R}}class X{constructor(e){if(!Y(e))throw new TypeError('"lines" must be of type LineString[]. Received type '+typeof e);if(0===e.length)throw new Error("Polygon must contain 1 linestring at least");e.forEach(e=>{if(!(e instanceof V))throw new TypeError(`"lines" must be of type LineString[]. Received type ${typeof e}[]`);if(!V.isClosed(e))throw new Error(`LineString ${e.points.map(e=>e.toReadableString())} is not a closed cycle`)}),this.lines=e}parse(e){return{[e]:{type:"Polygon",coordinates:this.lines.map(e=>e.points.map(e=>[e.longitude,e.latitude]))}}}toJSON(){return{type:"Polygon",coordinates:this.lines.map(e=>e.points.map(e=>[e.longitude,e.latitude]))}}static validate(e){if("Polygon"!==e.type||!Y(e.coordinates))return!1;for(let t of e.coordinates){if(!this.isCloseLineString(t))return!1;for(let e of t)if(!W(e[0])||!W(e[1]))return!1}return!0}static isCloseLineString(e){const t=e[0],r=e[e.length-1];return t[0]===r[0]&&t[1]===r[1]}get _internalType(){return $}}class Q{constructor(e){if(!Y(e))throw new TypeError('"points" must be of type Point[]. Received type '+typeof e);if(0===e.length)throw new Error('"points" must contain 1 point at least');e.forEach(e=>{if(!(e instanceof J))throw new TypeError(`"points" must be of type Point[]. Received type ${typeof e}[]`)}),this.points=e}parse(e){return{[e]:{type:"MultiPoint",coordinates:this.points.map(e=>e.toJSON().coordinates)}}}toJSON(){return{type:"MultiPoint",coordinates:this.points.map(e=>e.toJSON().coordinates)}}static validate(e){if("MultiPoint"!==e.type||!Y(e.coordinates))return!1;for(let t of e.coordinates)if(!W(t[0])||!W(t[1]))return!1;return!0}get _internalType(){return C}}class Z{constructor(e){if(!Y(e))throw new TypeError('"lines" must be of type LineString[]. Received type '+typeof e);if(0===e.length)throw new Error("Polygon must contain 1 linestring at least");e.forEach(e=>{if(!(e instanceof V))throw new TypeError(`"lines" must be of type LineString[]. Received type ${typeof e}[]`)}),this.lines=e}parse(e){return{[e]:{type:"MultiLineString",coordinates:this.lines.map(e=>e.points.map(e=>[e.longitude,e.latitude]))}}}toJSON(){return{type:"MultiLineString",coordinates:this.lines.map(e=>e.points.map(e=>[e.longitude,e.latitude]))}}static validate(e){if("MultiLineString"!==e.type||!Y(e.coordinates))return!1;for(let t of e.coordinates)for(let e of t)if(!W(e[0])||!W(e[1]))return!1;return!0}get _internalType(){return P}}class ee{constructor(e){if(!Y(e))throw new TypeError('"polygons" must be of type Polygon[]. Received type '+typeof e);if(0===e.length)throw new Error("MultiPolygon must contain 1 polygon at least");for(let t of e)if(!(t instanceof X))throw new TypeError(`"polygon" must be of type Polygon[]. Received type ${typeof t}[]`);this.polygons=e}parse(e){return{[e]:{type:"MultiPolygon",coordinates:this.polygons.map(e=>e.lines.map(e=>e.points.map(e=>[e.longitude,e.latitude])))}}}toJSON(){return{type:"MultiPolygon",coordinates:this.polygons.map(e=>e.lines.map(e=>e.points.map(e=>[e.longitude,e.latitude])))}}static validate(e){if("MultiPolygon"!==e.type||!Y(e.coordinates))return!1;for(let t of e.coordinates)for(let e of t)for(let t of e)if(!W(t[0])||!W(t[1]))return!1;return!0}get _internalType(){return D}}const te=()=>{let e;if(!Promise){e=()=>{},e.promise={};const t=()=>{throw new Error('Your Node runtime does support ES6 Promises. Set "global.Promise" to your preferred implementation of promises.')};return Object.defineProperty(e.promise,"then",{get:t}),Object.defineProperty(e.promise,"catch",{get:t}),e}const t=new Promise((t,r)=>{e=(e,n)=>e?r(e):t(n)});return e.promise=t,e};var re;!function(e){e.SET="set",e.REMOVE="remove",e.INC="inc",e.MUL="mul",e.PUSH="push",e.PULL="pull",e.PULL_ALL="pullAll",e.POP="pop",e.SHIFT="shift",e.UNSHIFT="unshift",e.ADD_TO_SET="addToSet",e.BIT="bit",e.RENAME="rename",e.MAX="max",e.MIN="min"}(re||(re={}));class ne{constructor(e,t,r){this._internalType=O,Object.defineProperties(this,{_internalType:{enumerable:!1,configurable:!1}}),this.operator=e,this.operands=t,this.fieldName=r||N}_setFieldName(e){return new ne(this.operator,this.operands,e)}}function ie(e){return e&&e instanceof ne&&e._internalType===O}var oe;!function(e){e.AND="and",e.OR="or",e.NOT="not",e.NOR="nor"}(oe||(oe={}));class se{constructor(e,t,r){if(this._internalType=I,Object.defineProperties(this,{_internalType:{enumerable:!1,configurable:!1}}),this.operator=e,this.operands=t,this.fieldName=r||N,this.fieldName!==N)if(Array.isArray(t)){t=t.slice(),this.operands=t;for(let e=0,r=t.length;et instanceof se?t._setFieldName(e):t);return new se(this.operator,t,e)}and(...e){const t=Array.isArray(arguments[0])?arguments[0]:Array.from(arguments);return t.unshift(this),new se(oe.AND,t,this.fieldName)}or(...e){const t=Array.isArray(arguments[0])?arguments[0]:Array.from(arguments);return t.unshift(this),new se(oe.OR,t,this.fieldName)}}function ae(e){return e&&e instanceof se&&e._internalType===I}var ue;!function(e){e.EQ="eq",e.NEQ="neq",e.GT="gt",e.GTE="gte",e.LT="lt",e.LTE="lte",e.IN="in",e.NIN="nin",e.ALL="all",e.ELEM_MATCH="elemMatch",e.EXISTS="exists",e.SIZE="size",e.MOD="mod",e.GEO_NEAR="geoNear",e.GEO_WITHIN="geoWithin",e.GEO_INTERSECTS="geoIntersects"}(ue||(ue={}));class ce extends se{constructor(e,t,r){super(e,t,r),this.operator=e,this._internalType=T}toJSON(){switch(this.operator){case ue.IN:case ue.NIN:return{["$"+this.operator]:this.operands};default:return{["$"+this.operator]:this.operands[0]}}}_setFieldName(e){return new ce(this.operator,this.operands,e)}eq(e){const t=new ce(ue.EQ,[e],this.fieldName);return this.and(t)}neq(e){const t=new ce(ue.NEQ,[e],this.fieldName);return this.and(t)}gt(e){const t=new ce(ue.GT,[e],this.fieldName);return this.and(t)}gte(e){const t=new ce(ue.GTE,[e],this.fieldName);return this.and(t)}lt(e){const t=new ce(ue.LT,[e],this.fieldName);return this.and(t)}lte(e){const t=new ce(ue.LTE,[e],this.fieldName);return this.and(t)}in(e){const t=new ce(ue.IN,e,this.fieldName);return this.and(t)}nin(e){const t=new ce(ue.NIN,e,this.fieldName);return this.and(t)}geoNear(e){if(!(e.geometry instanceof J))throw new TypeError('"geometry" must be of type Point. Received type '+typeof e.geometry);if(void 0!==e.maxDistance&&!W(e.maxDistance))throw new TypeError('"maxDistance" must be of type Number. Received type '+typeof e.maxDistance);if(void 0!==e.minDistance&&!W(e.minDistance))throw new TypeError('"minDistance" must be of type Number. Received type '+typeof e.minDistance);const t=new ce(ue.GEO_NEAR,[e],this.fieldName);return this.and(t)}geoWithin(e){if(!(e.geometry instanceof ee||e.geometry instanceof X))throw new TypeError('"geometry" must be of type Polygon or MultiPolygon. Received type '+typeof e.geometry);const t=new ce(ue.GEO_WITHIN,[e],this.fieldName);return this.and(t)}geoIntersects(e){if(!(e.geometry instanceof J||e.geometry instanceof V||e.geometry instanceof X||e.geometry instanceof Q||e.geometry instanceof Z||e.geometry instanceof ee))throw new TypeError('"geometry" must be of type Point, LineString, Polygon, MultiPoint, MultiLineString or MultiPolygon. Received type '+typeof e.geometry);const t=new ce(ue.GEO_INTERSECTS,[e],this.fieldName);return this.and(t)}}function le(e){return e&&e instanceof ce&&e._internalType===T}function fe(e){return le(e)}const he={};for(const e in ue)he[e]="$"+e;for(const e in oe)he[e]="$"+e;for(const e in re)he[e]="$"+e;function de(e){return he[e]||"$"+e}function pe(e){return function e(t,r){if(!G(t)){if(H(t))return{$date:+t};if(K(t))return{$regex:t.source,$options:t.flags};if(Y(t))return t.map(t=>{if(r.indexOf(t)>-1)throw new Error("Cannot convert circular structure to JSON");return e(t,[...r,t])});if(F(t)){const n=Object.assign({},t);for(const t in n){if(r.indexOf(n[t])>-1)throw new Error("Cannot convert circular structure to JSON");n[t]=e(n[t],[...r,n[t]])}return n}return t}switch(t._internalType){case B:return t.toJSON();case M:case L:return t.parse();default:return t.toJSON?t.toJSON():t}}(e,[e])}function _e(e,t,r,n){const i=Object.assign({},e);for(const o in e){if(/^\$/.test(o))continue;const s=e[o];if(s&&(F(s)&&!t(s))){if(n.indexOf(s)>-1)throw new Error("Cannot convert circular structure to JSON");const e=_e(s,t,[...r,o],[...n,s]);i[o]=e;let a=!1;for(const t in e)/^\$/.test(t)?a=!0:(i[`${o}.${t}`]=e[t],delete i[o][t]);a||delete i[o]}}return i}function ge(e){return _e(e,me,[],[e])}function ye(e,t,r){t[r]||delete e[r];for(const n in t)e[n]?Y(e[n])?e[n].push(t[n]):F(e[n])?F(t[n])?Object.assign(e[n],t[n]):(console.warn(`unmergable condition, query is object but condition is ${z(t)}, can only overwrite`,t,r),e[n]=t[n]):(console.warn(`to-merge query is of type ${z(e)}, can only overwrite`,e,t,r),e[n]=t[n]):e[n]=t[n]}function me(e){return G(e)||H(e)||K(e)}function be(e){return pe(e)}he[ue.NEQ]="$ne",he[re.REMOVE]="$unset",he[re.SHIFT]="$pop",he[re.UNSHIFT]="$push";class we{constructor(){}static encode(e){return(new we).encodeUpdate(e)}encodeUpdate(e){return ie(e)?this.encodeUpdateCommand(e):"object"===z(e)?this.encodeUpdateObject(e):e}encodeUpdateCommand(e){if(e.fieldName===N)throw new Error("Cannot encode a comparison command with unset field name");switch(e.operator){case re.PUSH:case re.PULL:case re.PULL_ALL:case re.POP:case re.SHIFT:case re.UNSHIFT:case re.ADD_TO_SET:return this.encodeArrayUpdateCommand(e);default:return this.encodeFieldUpdateCommand(e)}}encodeFieldUpdateCommand(e){const t=de(e.operator);switch(e.operator){case re.REMOVE:return{[t]:{[e.fieldName]:""}};default:return{[t]:{[e.fieldName]:e.operands[0]}}}}encodeArrayUpdateCommand(e){const t=de(e.operator);switch(e.operator){case re.PUSH:{let r;return r=Y(e.operands)?{$each:e.operands.map(be)}:e.operands,{[t]:{[e.fieldName]:r}}}case re.UNSHIFT:{const r={$each:e.operands.map(be),$position:0};return{[t]:{[e.fieldName]:r}}}case re.POP:return{[t]:{[e.fieldName]:1}};case re.SHIFT:return{[t]:{[e.fieldName]:-1}};default:return{[t]:{[e.fieldName]:be(e.operands)}}}}encodeUpdateObject(e){const t=ge(e);for(const e in t){if(/^\$/.test(e))continue;let r=t[e];if(ie(r)){t[e]=r._setFieldName(e),ye(t,this.encodeUpdateCommand(t[e]),e)}else{t[e]=r=be(r);const n=new ne(re.SET,[r],e);ye(t,this.encodeUpdateCommand(n),e)}}return t}}var ve=r(9),Ee=r.n(ve),Se=r(10),Ae=r.n(Se),Ne=r(11),Oe=r.n(Ne);function Te(e=""){return`${e?e+"_":""}${+new Date}_${Math.random()}`}const Ie={UNKNOWN_ERROR:"UNKNOWN_ERROR",SDK_DATABASE_REALTIME_LISTENER_INIT_WATCH_FAIL:"SDK_DATABASE_REALTIME_LISTENER_INIT_WATCH_FAIL",SDK_DATABASE_REALTIME_LISTENER_RECONNECT_WATCH_FAIL:"SDK_DATABASE_REALTIME_LISTENER_RECONNECT_WATCH_FAIL",SDK_DATABASE_REALTIME_LISTENER_REBUILD_WATCH_FAIL:"SDK_DATABASE_REALTIME_LISTENER_REBUILD_WATCH_FAIL",SDK_DATABASE_REALTIME_LISTENER_CLOSE_WATCH_FAIL:"SDK_DATABASE_REALTIME_LISTENER_CLOSE_WATCH_FAIL",SDK_DATABASE_REALTIME_LISTENER_SERVER_ERROR_MSG:"SDK_DATABASE_REALTIME_LISTENER_SERVER_ERROR_MSG",SDK_DATABASE_REALTIME_LISTENER_RECEIVE_INVALID_SERVER_DATA:"SDK_DATABASE_REALTIME_LISTENER_RECEIVE_INVALID_SERVER_DATA",SDK_DATABASE_REALTIME_LISTENER_WEBSOCKET_CONNECTION_ERROR:"SDK_DATABASE_REALTIME_LISTENER_WEBSOCKET_CONNECTION_ERROR",SDK_DATABASE_REALTIME_LISTENER_WEBSOCKET_CONNECTION_CLOSED:"SDK_DATABASE_REALTIME_LISTENER_WEBSOCKET_CONNECTION_CLOSED",SDK_DATABASE_REALTIME_LISTENER_CHECK_LAST_FAIL:"SDK_DATABASE_REALTIME_LISTENER_CHECK_LAST_FAIL",SDK_DATABASE_REALTIME_LISTENER_UNEXPECTED_FATAL_ERROR:"SDK_DATABASE_REALTIME_LISTENER_UNEXPECTED_FATAL_ERROR"};class Be extends Error{constructor(e){super(e.errMsg),this.errCode="UNKNOWN_ERROR",Object.defineProperties(this,{message:{get(){return`errCode: ${this.errCode} ${Ie[this.errCode]||""} | errMsg: `+this.errMsg},set(e){this.errMsg=e}}}),this.errCode=e.errCode||"UNKNOWN_ERROR",this.errMsg=e.errMsg}get message(){return`errCode: ${this.errCode} | errMsg: `+this.errMsg}set message(e){this.errMsg=e}}class Re extends Error{constructor(e){super(e),this.type="timeout",this.payload=null,this.generic=!0}}class De extends Error{constructor(e){super(e),this.type="cancelled",this.payload=null,this.generic=!0}}const Ce=(e=0)=>new Promise(t=>setTimeout(t,e));class Pe{constructor(e){this.close=e.close,this.onChange=e.onChange,this.onError=e.onError,e.debug&&Object.defineProperty(this,"virtualClient",{get:()=>e.virtualClient})}}class $e{constructor(e){const{id:t,docChanges:r,docs:n,msgType:i,type:o}=e;let s,a;Object.defineProperties(this,{id:{get:()=>t,enumerable:!0},docChanges:{get:()=>(s||(s=JSON.parse(JSON.stringify(r))),s),enumerable:!0},docs:{get:()=>(a||(a=JSON.parse(JSON.stringify(n))),a),enumerable:!0},msgType:{get:()=>i,enumerable:!0},type:{get:()=>o,enumerable:!0}})}}class Me extends Error{constructor(e){super(`Watch Error ${JSON.stringify(e.msgData)} (requestid: ${e.requestId})`),this.isRealtimeErrorMessageError=!0,this.payload=e}}const Le=e=>e&&e.isRealtimeErrorMessageError;var je;!function(e){e.LOGGINGIN="LOGGINGIN",e.INITING="INITING",e.REBUILDING="REBUILDING",e.ACTIVE="ACTIVE",e.ERRORED="ERRORED",e.CLOSING="CLOSING",e.CLOSED="CLOSED",e.PAUSED="PAUSED",e.RESUMING="RESUMING"}(je||(je={}));class xe{constructor(e){this.watchStatus=je.INITING,this._login=async(e,t)=>{this.watchStatus=je.LOGGINGIN;const r=await this.login(e,t);return this.envId||(this.envId=r.envId),r},this.initWatch=async e=>{if(this._initWatchPromise)return this._initWatchPromise;this._initWatchPromise=new Promise(async(t,r)=>{try{if(this.watchStatus===je.PAUSED)return console.log("[realtime] initWatch cancelled on pause"),t();const{envId:r}=await this._login(this.envId,e);if(this.watchStatus===je.PAUSED)return console.log("[realtime] initWatch cancelled on pause"),t();this.watchStatus=je.INITING;const n={watchId:this.watchId,requestId:Te(),msgType:"INIT_WATCH",msgData:{envId:r,collName:this.collectionName,query:this.query,limit:this.limit,orderBy:this.orderBy}},i=await this.send({msg:n,waitResponse:!0,skipOnMessage:!0,timeout:1e4}),{events:o,currEvent:s}=i.msgData;if(this.sessionInfo={queryID:i.msgData.queryID,currentEventId:s-1,currentDocs:[]},o.length>0){for(const e of o)e.ID=s;this.handleServerEvents(i)}else{this.sessionInfo.currentEventId=s;const e=new $e({id:s,docChanges:[],docs:[],type:"init"});this.listener.onChange(e),this.scheduleSendACK()}this.onWatchStart(this,this.sessionInfo.queryID),this.watchStatus=je.ACTIVE,this._availableRetries.INIT_WATCH=2,t()}catch(e){this.handleWatchEstablishmentError(e,{operationName:"INIT_WATCH",resolve:t,reject:r})}});let t=!1;try{await this._initWatchPromise,t=!0}finally{this._initWatchPromise=void 0}console.log("[realtime] initWatch "+(t?"success":"fail"))},this.rebuildWatch=async e=>{if(this._rebuildWatchPromise)return this._rebuildWatchPromise;this._rebuildWatchPromise=new Promise(async(t,r)=>{try{if(this.watchStatus===je.PAUSED)return console.log("[realtime] rebuildWatch cancelled on pause"),t();const{envId:r}=await this._login(this.envId,e);if(!this.sessionInfo)throw new Error("can not rebuildWatch without a successful initWatch (lack of sessionInfo)");if(this.watchStatus===je.PAUSED)return console.log("[realtime] rebuildWatch cancelled on pause"),t();this.watchStatus=je.REBUILDING;const n={watchId:this.watchId,requestId:Te(),msgType:"REBUILD_WATCH",msgData:{envId:r,collName:this.collectionName,queryID:this.sessionInfo.queryID,eventID:this.sessionInfo.currentEventId}},i=await this.send({msg:n,waitResponse:!0,skipOnMessage:!1,timeout:1e4});this.handleServerEvents(i),this.watchStatus=je.ACTIVE,this._availableRetries.REBUILD_WATCH=2,t()}catch(e){this.handleWatchEstablishmentError(e,{operationName:"REBUILD_WATCH",resolve:t,reject:r})}});let t=!1;try{await this._rebuildWatchPromise,t=!0}finally{this._rebuildWatchPromise=void 0}console.log("[realtime] rebuildWatch "+(t?"success":"fail"))},this.handleWatchEstablishmentError=async(e,t)=>{const r="INIT_WATCH"===t.operationName,n=()=>{this.closeWithError(new Be({errCode:r?Ie.SDK_DATABASE_REALTIME_LISTENER_INIT_WATCH_FAIL:Ie.SDK_DATABASE_REALTIME_LISTENER_REBUILD_WATCH_FAIL,errMsg:e})),t.reject(e)},i=e=>{this.useRetryTicket(t.operationName)?r?(this._initWatchPromise=void 0,t.resolve(this.initWatch(e))):(this._rebuildWatchPromise=void 0,t.resolve(this.rebuildWatch(e))):n()};this.handleCommonError(e,{onSignError:()=>i(!0),onTimeoutError:()=>i(!1),onNotRetryableError:n,onCancelledError:t.reject,onUnknownError:async()=>{try{const e=async()=>{this.pause(),await this.onceWSConnected(),i(!0)};this.isWSConnected()?(await Ce(100),this.watchStatus===je.PAUSED?t.reject(new De(t.operationName+" cancelled due to pause after unknownError")):this.isWSConnected()?i(!1):await e()):await e()}catch(e){i(!0)}}})},this.closeWatch=async()=>{const e=this.sessionInfo?this.sessionInfo.queryID:"";if(this.watchStatus!==je.ACTIVE)return this.watchStatus=je.CLOSED,void this.onWatchClose(this,e);try{this.watchStatus=je.CLOSING;const t={watchId:this.watchId,requestId:Te(),msgType:"CLOSE_WATCH",msgData:null};await this.send({msg:t}),this.sessionInfo=void 0,this.watchStatus=je.CLOSED}catch(e){this.closeWithError(new Be({errCode:Ie.SDK_DATABASE_REALTIME_LISTENER_CLOSE_WATCH_FAIL,errMsg:e}))}finally{this.onWatchClose(this,e)}},this.scheduleSendACK=()=>{this.clearACKSchedule(),this._ackTimeoutId=setTimeout(()=>{this._waitExpectedTimeoutId?this.scheduleSendACK():this.sendACK()},1e4)},this.clearACKSchedule=()=>{this._ackTimeoutId&&clearTimeout(this._ackTimeoutId)},this.sendACK=async()=>{try{if(this.watchStatus!==je.ACTIVE)return void this.scheduleSendACK();if(!this.sessionInfo)return void console.warn("[realtime listener] can not send ack without a successful initWatch (lack of sessionInfo)");const e={watchId:this.watchId,requestId:Te(),msgType:"CHECK_LAST",msgData:{queryID:this.sessionInfo.queryID,eventID:this.sessionInfo.currentEventId}};await this.send({msg:e}),this.scheduleSendACK()}catch(e){if(Le(e)){const t=e.payload;switch(t.msgData.code){case"CHECK_LOGIN_FAILED":case"SIGN_EXPIRED_ERROR":case"SIGN_INVALID_ERROR":case"SIGN_PARAM_INVALID":return void this.rebuildWatch();case"QUERYID_INVALID_ERROR":case"SYS_ERR":case"INVALIID_ENV":case"COLLECTION_PERMISSION_DENIED":return void this.closeWithError(new Be({errCode:Ie.SDK_DATABASE_REALTIME_LISTENER_CHECK_LAST_FAIL,errMsg:t.msgData.code}))}}this._availableRetries.CHECK_LAST&&this._availableRetries.CHECK_LAST>0?(this._availableRetries.CHECK_LAST--,this.scheduleSendACK()):this.closeWithError(new Be({errCode:Ie.SDK_DATABASE_REALTIME_LISTENER_CHECK_LAST_FAIL,errMsg:e}))}},this.handleCommonError=(e,t)=>{if(Le(e)){switch(e.payload.msgData.code){case"CHECK_LOGIN_FAILED":case"SIGN_EXPIRED_ERROR":case"SIGN_INVALID_ERROR":case"SIGN_PARAM_INVALID":return void t.onSignError(e);case"QUERYID_INVALID_ERROR":case"SYS_ERR":case"INVALIID_ENV":case"COLLECTION_PERMISSION_DENIED":default:return void t.onNotRetryableError(e)}}else{if((e=>"timeout"===e.type)(e))return void t.onTimeoutError(e);if((e=>"cancelled"===e.type)(e))return void t.onCancelledError(e)}t.onUnknownError(e)},this.watchId=`watchid_${+new Date}_${Math.random()}`,this.envId=e.envId,this.collectionName=e.collectionName,this.query=e.query,this.limit=e.limit,this.orderBy=e.orderBy,this.send=e.send,this.login=e.login,this.isWSConnected=e.isWSConnected,this.onceWSConnected=e.onceWSConnected,this.getWaitExpectedTimeoutLength=e.getWaitExpectedTimeoutLength,this.onWatchStart=e.onWatchStart,this.onWatchClose=e.onWatchClose,this.debug=e.debug,this._availableRetries={INIT_WATCH:2,REBUILD_WATCH:2,CHECK_LAST:2},this.listener=new Pe({close:this.closeWatch,onChange:e.onChange,onError:e.onError,debug:this.debug,virtualClient:this}),this.initWatch()}useRetryTicket(e){return!!(this._availableRetries[e]&&this._availableRetries[e]>0)&&(this._availableRetries[e]--,console.log(`[realtime] ${e} use a retry ticket, now only ${this._availableRetries[e]} retry left`),!0)}async handleServerEvents(e){try{this.scheduleSendACK(),await this._handleServerEvents(e),this._postHandleServerEventsValidityCheck(e)}catch(e){throw console.error("[realtime listener] internal non-fatal error: handle server events failed with error: ",e),e}}async _handleServerEvents(e){const{requestId:t}=e,{events:r}=e.msgData,{msgType:n}=e;if(!r.length||!this.sessionInfo)return;const i=this.sessionInfo;let o;try{o=r.map(Ue)}catch(e){return void this.closeWithError(new Be({errCode:Ie.SDK_DATABASE_REALTIME_LISTENER_RECEIVE_INVALID_SERVER_DATA,errMsg:e}))}let s=[...i.currentDocs],a=!1;for(let r=0,u=o.length;r=c.id)!o[r-1]||c.id>o[r-1].id?console.warn(`[realtime] duplicate event received, cur ${i.currentEventId} but got ${c.id}`):console.error(`[realtime listener] server non-fatal error: events out of order (the latter event's id is smaller than that of the former) (requestId ${t})`);else{if(i.currentEventId!==c.id-1)return console.warn(`[realtime listener] event received is out of order, cur ${this.sessionInfo.currentEventId} but got ${c.id}`),void await this.rebuildWatch();switch(c.dataType){case"update":if(!c.doc)switch(c.queueType){case"update":case"dequeue":{const e=s.find(e=>e._id===c.docId);if(e){const t=Oe()(e);if(c.updatedFields)for(const e in c.updatedFields)Ee()(t,e,c.updatedFields[e]);if(c.removedFields)for(const e of c.removedFields)Ae()(t,e);c.doc=t}else console.error("[realtime listener] internal non-fatal server error: unexpected update dataType event where no doc is associated.");break}case"enqueue":{const t=new Be({errCode:Ie.SDK_DATABASE_REALTIME_LISTENER_UNEXPECTED_FATAL_ERROR,errMsg:`HandleServerEvents: full doc is not provided with dataType="update" and queueType="enqueue" (requestId ${e.requestId})`});throw this.closeWithError(t),t}}break;case"replace":if(!c.doc){const t=new Be({errCode:Ie.SDK_DATABASE_REALTIME_LISTENER_UNEXPECTED_FATAL_ERROR,errMsg:`HandleServerEvents: full doc is not provided with dataType="replace" (requestId ${e.requestId})`});throw this.closeWithError(t),t}break;case"remove":{const e=s.find(e=>e._id===c.docId);e?c.doc=e:console.error("[realtime listener] internal non-fatal server error: unexpected remove event where no doc is associated.");break}case"limit":if(!c.doc)switch(c.queueType){case"dequeue":{const e=s.find(e=>e._id===c.docId);e?c.doc=e:console.error("[realtime listener] internal non-fatal server error: unexpected limit dataType event where no doc is associated.");break}case"enqueue":{const t=new Be({errCode:Ie.SDK_DATABASE_REALTIME_LISTENER_UNEXPECTED_FATAL_ERROR,errMsg:`HandleServerEvents: full doc is not provided with dataType="limit" and queueType="enqueue" (requestId ${e.requestId})`});throw this.closeWithError(t),t}}}switch(c.queueType){case"init":a?s.push(c.doc):(a=!0,s=[c.doc]);break;case"enqueue":s.push(c.doc);break;case"dequeue":{const e=s.findIndex(e=>e._id===c.docId);e>-1?s.splice(e,1):console.error("[realtime listener] internal non-fatal server error: unexpected dequeue event where no doc is associated.");break}case"update":{const e=s.findIndex(e=>e._id===c.docId);e>-1?s[e]=c.doc:console.error("[realtime listener] internal non-fatal server error: unexpected queueType update event where no doc is associated.");break}}if(r===u-1||o[r+1]&&o[r+1].id!==c.id){const e=[...s],t=o.slice(0,r+1).filter(e=>e.id===c.id);this.sessionInfo.currentEventId=c.id,this.sessionInfo.currentDocs=s;const i=new $e({id:c.id,docChanges:t,docs:e,msgType:n});this.listener.onChange(i)}}}}_postHandleServerEventsValidityCheck(e){this.sessionInfo?(this.sessionInfo.expectEventId&&this.sessionInfo.currentEventId>=this.sessionInfo.expectEventId&&this.clearWaitExpectedEvent(),this.sessionInfo.currentEventId{this.rebuildWatch()},this.getWaitExpectedTimeoutLength()),console.log("[realtime] waitExpectedTimeoutLength "+this.getWaitExpectedTimeoutLength()));break;case"ERROR":this.closeWithError(new Be({errCode:Ie.SDK_DATABASE_REALTIME_LISTENER_SERVER_ERROR_MSG,errMsg:`${e.msgData.code} - ${e.msgData.message}`}));break;default:console.warn(`[realtime listener] virtual client receive unexpected msg ${e.msgType}: `,e)}else console.warn("[realtime listener] internal non-fatal error: sessionInfo not found while message is received.")}closeWithError(e){this.watchStatus=je.ERRORED,this.clearACKSchedule(),this.listener.onError(e),this.onWatchClose(this,this.sessionInfo&&this.sessionInfo.queryID||""),console.log(`[realtime] client closed (${this.collectionName} ${this.query}) (watchId ${this.watchId})`)}pause(){this.watchStatus=je.PAUSED,console.log(`[realtime] client paused (${this.collectionName} ${this.query}) (watchId ${this.watchId})`)}async resume(){this.watchStatus=je.RESUMING,console.log(`[realtime] client resuming with ${this.sessionInfo?"REBUILD_WATCH":"INIT_WATCH"} (${this.collectionName} ${this.query}) (${this.watchId})`);try{await(this.sessionInfo?this.rebuildWatch():this.initWatch()),console.log(`[realtime] client successfully resumed (${this.collectionName} ${this.query}) (${this.watchId})`)}catch(e){console.error(`[realtime] client resume failed (${this.collectionName} ${this.query}) (${this.watchId})`,e)}}}function Ue(e){const t={id:e.ID,dataType:e.DataType,queueType:e.QueueType,docId:e.DocID,doc:e.Doc&&"{}"!==e.Doc?JSON.parse(e.Doc):void 0};return"update"===e.DataType&&(e.UpdatedFields&&(t.updatedFields=JSON.parse(e.UpdatedFields)),(e.removedFields||e.RemovedFields)&&(t.removedFields=JSON.parse(e.removedFields))),t}const ke={1e3:{code:1e3,name:"Normal Closure",description:"Normal closure; the connection successfully completed whatever purpose for which it was created."},1001:{code:1001,name:"Going Away",description:"The endpoint is going away, either because of a server failure or because the browser is navigating away from the page that opened the connection."},1002:{code:1002,name:"Protocol Error",description:"The endpoint is terminating the connection due to a protocol error."},1003:{code:1003,name:"Unsupported Data",description:"The connection is being terminated because the endpoint received data of a type it cannot accept (for example, a text-only endpoint received binary data)."},1005:{code:1005,name:"No Status Received",description:"Indicates that no status code was provided even though one was expected."},1006:{code:1006,name:"Abnormal Closure",description:"Used to indicate that a connection was closed abnormally (that is, with no close frame being sent) when a status code is expected."},1007:{code:1007,name:"Invalid frame payload data",description:"The endpoint is terminating the connection because a message was received that contained inconsistent data (e.g., non-UTF-8 data within a text message)."},1008:{code:1008,name:"Policy Violation",description:"The endpoint is terminating the connection because it received a message that violates its policy. This is a generic status code, used when codes 1003 and 1009 are not suitable."},1009:{code:1009,name:"Message too big",description:"The endpoint is terminating the connection because a data frame was received that is too large."},1010:{code:1010,name:"Missing Extension",description:"The client is terminating the connection because it expected the server to negotiate one or more extension, but the server didn't."},1011:{code:1011,name:"Internal Error",description:"The server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request."},1012:{code:1012,name:"Service Restart",description:"The server is terminating the connection because it is restarting."},1013:{code:1013,name:"Try Again Later",description:"The server is terminating the connection due to a temporary condition, e.g. it is overloaded and is casting off some of its clients."},1014:{code:1014,name:"Bad Gateway",description:"The server was acting as a gateway or proxy and received an invalid response from the upstream server. This is similar to 502 HTTP Status Code."},1015:{code:1015,name:"TLS Handshake",description:"Indicates that the connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified)."},3e3:{code:3e3,name:"Reconnect WebSocket",description:"The client is terminating the connection because it wants to reconnect"},3001:{code:3001,name:"No Realtime Listeners",description:"The client is terminating the connection because no more realtime listeners exist"},3002:{code:3002,name:"Heartbeat Ping Error",description:"The client is terminating the connection due to its failure in sending heartbeat messages"},3003:{code:3003,name:"Heartbeat Pong Timeout Error",description:"The client is terminating the connection because no heartbeat response is received from the server"},3050:{code:3050,name:"Server Close",description:"The client is terminating the connection because no heartbeat response is received from the server"}};var ze;!function(e){e[e.NormalClosure=1e3]="NormalClosure",e[e.GoingAway=1001]="GoingAway",e[e.ProtocolError=1002]="ProtocolError",e[e.UnsupportedData=1003]="UnsupportedData",e[e.NoStatusReceived=1005]="NoStatusReceived",e[e.AbnormalClosure=1006]="AbnormalClosure",e[e.InvalidFramePayloadData=1007]="InvalidFramePayloadData",e[e.PolicyViolation=1008]="PolicyViolation",e[e.MessageTooBig=1009]="MessageTooBig",e[e.MissingExtension=1010]="MissingExtension",e[e.InternalError=1011]="InternalError",e[e.ServiceRestart=1012]="ServiceRestart",e[e.TryAgainLater=1013]="TryAgainLater",e[e.BadGateway=1014]="BadGateway",e[e.TLSHandshake=1015]="TLSHandshake",e[e.ReconnectWebSocket=3e3]="ReconnectWebSocket",e[e.NoRealtimeListeners=3001]="NoRealtimeListeners",e[e.HeartbeatPingError=3002]="HeartbeatPingError",e[e.HeartbeatPongTimeoutError=3003]="HeartbeatPongTimeoutError",e[e.NoAuthentication=3050]="NoAuthentication"}(ze||(ze={}));const Fe=(e,t)=>{const r=ke[e],n=r?`${r.name}, code ${e}, reason ${t||r.description}`:"code "+e;return new Be({errCode:Ie.SDK_DATABASE_REALTIME_LISTENER_WEBSOCKET_CONNECTION_CLOSED,errMsg:n})},qe=1;class We{constructor(e){this._virtualWSClient=new Set,this._queryIdClientMap=new Map,this._watchIdClientMap=new Map,this._pingFailed=0,this._pongMissed=0,this._logins=new Map,this._wsReadySubsribers=[],this._wsResponseWait=new Map,this._rttObserved=[],this.initWebSocketConnection=async(e,t=this._maxReconnect)=>{if(!e||!this._reconnectState){if(e&&(this._reconnectState=!0),this._wsInitPromise)return this._wsInitPromise;e&&this.pauseClients(),this.close(ze.ReconnectWebSocket),this._wsInitPromise=new Promise(async(r,n)=>{try{const t=await this.getWsSign();await new Promise(e=>{const r=t.wsUrl||"wss://tcb-ws.tencentcloudapi.com";this._ws=ft.wsClass?new ft.wsClass(r):new WebSocket(r),e()}),this._ws.connect&&await this._ws.connect(),await this.initWebSocketEvent(),r(),e&&(this.resumeClients(),this._reconnectState=!1)}catch(i){if(console.error("[realtime] initWebSocketConnection connect fail",i),t>0){const n=!0;this._wsInitPromise=void 0,n&&(await Ce(this._reconnectInterval),e&&(this._reconnectState=!1)),r(this.initWebSocketConnection(e,t-1))}else n(i),e&&this.closeAllClients(new Be({errCode:Ie.SDK_DATABASE_REALTIME_LISTENER_RECONNECT_WATCH_FAIL,errMsg:i}))}});try{await this._wsInitPromise,this._wsReadySubsribers.forEach(({resolve:e})=>e())}catch(e){this._wsReadySubsribers.forEach(({reject:e})=>e())}finally{this._wsInitPromise=void 0,this._wsReadySubsribers=[]}}},this.initWebSocketEvent=()=>new Promise((e,t)=>{if(!this._ws)throw new Error("can not initWebSocketEvent, ws not exists");let r=!1;this._ws.onopen=t=>{console.warn("[realtime] ws event: open",t),r=!0,e()},this._ws.onerror=e=>{this._logins=new Map,r?(console.error("[realtime] ws event: error",e),this.clearHeartbeat(),this._virtualWSClient.forEach(t=>t.closeWithError(new Be({errCode:Ie.SDK_DATABASE_REALTIME_LISTENER_WEBSOCKET_CONNECTION_ERROR,errMsg:e})))):(console.error("[realtime] ws open failed with ws event: error",e),t(e))},this._ws.onclose=e=>{switch(console.warn("[realtime] ws event: close",e),this._logins=new Map,this.clearHeartbeat(),e.code){case ze.ReconnectWebSocket:case ze.NoRealtimeListeners:break;case ze.HeartbeatPingError:case ze.HeartbeatPongTimeoutError:case ze.NormalClosure:case ze.AbnormalClosure:this._maxReconnect>0?this.initWebSocketConnection(!0,this._maxReconnect):this.closeAllClients(Fe(e.code));break;case ze.NoAuthentication:this.closeAllClients(Fe(e.code,e.reason));break;default:this._maxReconnect>0?this.initWebSocketConnection(!0,this._maxReconnect):this.closeAllClients(Fe(e.code))}},this._ws.onmessage=e=>{const t=e.data;let r;this.heartbeat();try{r=JSON.parse(t)}catch(e){throw new Error("[realtime] onMessage parse res.data error: "+e)}if("ERROR"===r.msgType){let e=null;this._virtualWSClient.forEach(t=>{t.watchId===r.watchId&&(e=t)}),e&&e.listener.onError(r)}const n=this._wsResponseWait.get(r.requestId);if(n){try{"ERROR"===r.msgType?n.reject(new Me(r)):n.resolve(r)}catch(e){console.error("ws onMessage responseWaitSpec.resolve(msg) errored:",e)}finally{this._wsResponseWait.delete(r.requestId)}if(n.skipOnMessage)return}if("PONG"===r.msgType){if(this._lastPingSendTS){const e=Date.now()-this._lastPingSendTS;if(e>1e4)return void console.warn("[realtime] untrusted rtt observed: "+e);this._rttObserved.length>=3&&this._rttObserved.splice(0,this._rttObserved.length-3+1),this._rttObserved.push(e)}return}let i=r.watchId&&this._watchIdClientMap.get(r.watchId);if(i)i.onMessage(r);else switch(console.error(`[realtime] no realtime listener found responsible for watchId ${r.watchId}: `,r),r.msgType){case"INIT_EVENT":case"NEXT_EVENT":case"CHECK_EVENT":i=this._queryIdClientMap.get(r.msgData.queryID),i&&i.onMessage(r);break;default:for(const[,e]of this._watchIdClientMap){e.onMessage(r);break}}},this.heartbeat()}),this.isWSConnected=()=>Boolean(this._ws&&this._ws.readyState===qe),this.onceWSConnected=async()=>{if(!this.isWSConnected())return this._wsInitPromise?this._wsInitPromise:new Promise((e,t)=>{this._wsReadySubsribers.push({resolve:e,reject:t})})},this.webLogin=async(e,t)=>{if(!t)if(e){const t=this._logins.get(e);if(t){if(t.loggedIn&&t.loginResult)return t.loginResult;if(t.loggingInPromise)return t.loggingInPromise}}else{const e=this._logins.get("");if(e&&e.loggingInPromise)return e.loggingInPromise}const r=new Promise(async(e,t)=>{try{const r=await this.getWsSign(),n={envId:r.envId||"",accessToken:"",referrer:"web",sdkVersion:"",dataVersion:ft.dataVersion||""},i={watchId:void 0,requestId:Te(),msgType:"LOGIN",msgData:n,exMsgData:{runtime:ft.runtime,signStr:r.signStr,secretVersion:r.secretVersion}},o=await this.send({msg:i,waitResponse:!0,skipOnMessage:!0,timeout:5e3});o.msgData.code?t(new Error(`${o.msgData.code} ${o.msgData.message}`)):e({envId:r.envId})}catch(e){t(e)}});let n=e&&this._logins.get(e);const i=Date.now();n?(n.loggedIn=!1,n.loggingInPromise=r,n.loginStartTS=i):(n={loggedIn:!1,loggingInPromise:r,loginStartTS:i},this._logins.set(e||"",n));try{const t=await r,o=e&&this._logins.get(e);if(o&&o===n&&o.loginStartTS===i)return n.loggedIn=!0,n.loggingInPromise=void 0,n.loginStartTS=void 0,n.loginResult=t,t;if(o){if(o.loggedIn&&o.loginResult)return o.loginResult;if(o.loggingInPromise)return o.loggingInPromise;throw new Error("ws unexpected login info")}throw new Error("ws login info reset")}catch(e){throw n.loggedIn=!1,n.loggingInPromise=void 0,n.loginStartTS=void 0,n.loginResult=void 0,e}},this.getWsSign=async()=>{if(this._wsSign&&this._wsSign.expiredTs>Date.now())return this._wsSign;const e=Date.now()+6e4,t=await this._context.appConfig.request.send("auth.wsWebSign",{runtime:ft.runtime});if(t.code)throw new Error("[tcb-js-sdk] 获取实时数据推送登录票据失败: "+t.code);if(t.data){const{signStr:r,wsUrl:n,secretVersion:i,envId:o}=t.data;return{signStr:r,wsUrl:n,secretVersion:i,envId:o,expiredTs:e}}throw new Error("[tcb-js-sdk] 获取实时数据推送登录票据失败")},this.getWaitExpectedTimeoutLength=()=>this._rttObserved.length?this._rttObserved.reduce((e,t)=>e+t)/this._rttObserved.length*1.5:5e3,this.ping=async()=>{const e={watchId:void 0,requestId:Te(),msgType:"PING",msgData:null};await this.send({msg:e})},this.send=async e=>new Promise(async(t,r)=>{let n,i=!1,o=!1;const s=e=>{i=!0,n&&clearTimeout(n),t(e)},a=e=>{o=!0,n&&clearTimeout(n),r(e)};e.timeout&&(n=setTimeout(async()=>{i&&o||(await Ce(0),i&&o||a(new Re("wsclient.send timedout")))},e.timeout));try{if(this._wsInitPromise&&await this._wsInitPromise,!this._ws)return void a(new Error("invalid state: ws connection not exists, can not send message"));if(this._ws.readyState!==qe)return void a(new Error(`ws readyState invalid: ${this._ws.readyState}, can not send message`));e.waitResponse&&this._wsResponseWait.set(e.msg.requestId,{resolve:s,reject:a,skipOnMessage:e.skipOnMessage});try{await this._ws.send(JSON.stringify(e.msg)),e.waitResponse||s()}catch(t){t&&(a(t),e.waitResponse&&this._wsResponseWait.delete(e.msg.requestId))}}catch(e){a(e)}}),this.closeAllClients=e=>{this._virtualWSClient.forEach(t=>{t.closeWithError(e)})},this.pauseClients=e=>{(e||this._virtualWSClient).forEach(e=>{e.pause()})},this.resumeClients=e=>{(e||this._virtualWSClient).forEach(e=>{e.resume()})},this.onWatchStart=(e,t)=>{this._queryIdClientMap.set(t,e)},this.onWatchClose=(e,t)=>{t&&this._queryIdClientMap.delete(t),this._watchIdClientMap.delete(e.watchId),this._virtualWSClient.delete(e),this._virtualWSClient.size||this.close(ze.NoRealtimeListeners)},this._maxReconnect=e.maxReconnect||5,this._reconnectInterval=e.reconnectInterval||1e4,this._context=e.context}heartbeat(e){this.clearHeartbeat(),this._pingTimeoutId=setTimeout(async()=>{try{if(!this._ws||this._ws.readyState!==qe)return;this._lastPingSendTS=Date.now(),await this.ping(),this._pingFailed=0,this._pongTimeoutId=setTimeout(()=>{console.error("pong timed out"),this._pongMissed<2?(this._pongMissed++,this.heartbeat(!0)):this.initWebSocketConnection(!0)},this._context.appConfig.realtimePongWaitTimeout)}catch(e){this._pingFailed<2?(this._pingFailed++,this.heartbeat()):this.close(ze.HeartbeatPingError)}},e?0:this._context.appConfig.realtimePingInterval)}clearHeartbeat(){this._pingTimeoutId&&clearTimeout(this._pingTimeoutId),this._pongTimeoutId&&clearTimeout(this._pongTimeoutId)}close(e){this.clearHeartbeat(),this._ws&&(this._ws.close(e,ke[e].name),this._ws=void 0)}watch(e){this._ws||this._wsInitPromise||this.initWebSocketConnection(!1);const t=new xe(Object.assign(Object.assign({},e),{send:this.send,login:this.webLogin,isWSConnected:this.isWSConnected,onceWSConnected:this.onceWSConnected,getWaitExpectedTimeoutLength:this.getWaitExpectedTimeoutLength,onWatchStart:this.onWatchStart,onWatchClose:this.onWatchClose,debug:!0}));return this._virtualWSClient.add(t),this._watchIdClientMap.set(t.watchId,t),t.listener}}class Ye{constructor(e,t,r,n={}){this.watch=e=>(ft.ws||(ft.ws=new We({context:{appConfig:{docSizeLimit:1e3,realtimePingInterval:1e4,realtimePongWaitTimeout:5e3,request:this.request}}})),ft.ws.watch(Object.assign(Object.assign({},e),{envId:this._db.config.env,collectionName:this._coll,query:JSON.stringify({_id:this.id})}))),this._db=e,this._coll=t,this.id=r,this.request=new ft.reqClass(this._db.config),this.projection=n}create(e,t){t=t||te();let r={collectionName:this._coll,data:pe(e)};return this.id&&(r._id=this.id),this.request.send("database.addDocument",r).then(e=>{e.code?t(0,e):t(0,{id:e.data._id,requestId:e.requestId})}).catch(e=>{t(e)}),t.promise}set(e,t){if(t=t||te(),!this.id)return Promise.resolve({code:"INVALID_PARAM",message:"docId不能为空"});if(!e||"object"!=typeof e)return Promise.resolve({code:"INVALID_PARAM",message:"参数必需是非空对象"});if(e.hasOwnProperty("_id"))return Promise.resolve({code:"INVALID_PARAM",message:"不能更新_id的值"});let r=!1;const n=e=>{if("object"==typeof e)for(let t in e)e[t]instanceof ne?r=!0:"object"==typeof e[t]&&n(e[t])};if(n(e),r)return Promise.resolve({code:"DATABASE_REQUEST_FAILED",message:"update operator complicit"});let i={collectionName:this._coll,queryType:w.DOC,data:pe(e),multi:!1,merge:!1,upsert:!0};return this.id&&(i.query={_id:this.id}),this.request.send("database.updateDocument",i).then(e=>{e.code?t(0,e):t(0,{updated:e.data.updated,upsertedId:e.data.upserted_id,requestId:e.requestId})}).catch(e=>{t(e)}),t.promise}update(e,t){if(t=t||te(),!e||"object"!=typeof e)return Promise.resolve({code:"INVALID_PARAM",message:"参数必需是非空对象"});if(e.hasOwnProperty("_id"))return Promise.resolve({code:"INVALID_PARAM",message:"不能更新_id的值"});const r={_id:this.id},n={collectionName:this._coll,data:we.encode(e),query:r,queryType:w.DOC,multi:!1,merge:!0,upsert:!1};return this.request.send("database.updateDocument",n).then(e=>{e.code?t(0,e):t(0,{updated:e.data.updated,upsertedId:e.data.upserted_id,requestId:e.requestId})}).catch(e=>{t(e)}),t.promise}remove(e){e=e||te();const t={_id:this.id},r={collectionName:this._coll,query:t,queryType:w.DOC,multi:!1};return this.request.send("database.deleteDocument",r).then(t=>{t.code?e(0,t):e(0,{deleted:t.data.deleted,requestId:t.requestId})}).catch(t=>{e(t)}),e.promise}get(e){e=e||te();const t={_id:this.id},r={collectionName:this._coll,query:t,queryType:w.DOC,multi:!1,projection:this.projection};return this.request.send("database.queryDocument",r).then(t=>{if(t.code)e(0,t);else{const r=U.formatResDocumentData(t.data.list);e(0,{data:r,requestId:t.requestId,total:t.TotalCount,limit:t.Limit,offset:t.Offset})}}).catch(t=>{e(t)}),e.promise}field(e){for(let t in e)e[t]?e[t]=1:e[t]=0;return new Ye(this._db,this._coll,this.id,e)}}class He{constructor(){}static encode(e){return(new Ke).encodeQuery(e)}}class Ke{encodeQuery(e,t){return me(e)?ae(e)?this.encodeLogicCommand(e):le(e)?this.encodeQueryCommand(e):{[t]:this.encodeQueryObject(e)}:F(e)?this.encodeQueryObject(e):e}encodeRegExp(e){return{$regex:e.source,$options:e.flags}}encodeLogicCommand(e){switch(e.operator){case oe.NOR:case oe.AND:case oe.OR:return{[de(e.operator)]:e.operands.map(t=>this.encodeQuery(t,e.fieldName))};case oe.NOT:{const t=de(e.operator),r=e.operands[0];if(K(r))return{[e.fieldName]:{[t]:this.encodeRegExp(r)}};{const n=this.encodeQuery(r)[e.fieldName];return{[e.fieldName]:{[t]:n}}}}default:{const t=de(e.operator);if(1===e.operands.length){return{[t]:this.encodeQuery(e.operands[0])}}return{[t]:e.operands.map(this.encodeQuery.bind(this))}}}}encodeQueryCommand(e){return fe(e),this.encodeComparisonCommand(e)}encodeComparisonCommand(e){if(e.fieldName===N)throw new Error("Cannot encode a comparison command with unset field name");const t=de(e.operator);switch(e.operator){case ue.EQ:case ue.NEQ:case ue.LT:case ue.LTE:case ue.GT:case ue.GTE:case ue.ELEM_MATCH:case ue.EXISTS:case ue.SIZE:case ue.MOD:return{[e.fieldName]:{[t]:be(e.operands[0])}};case ue.IN:case ue.NIN:case ue.ALL:return{[e.fieldName]:{[t]:be(e.operands)}};case ue.GEO_NEAR:{const t=e.operands[0];return{[e.fieldName]:{$nearSphere:{$geometry:t.geometry.toJSON(),$maxDistance:t.maxDistance,$minDistance:t.minDistance}}}}case ue.GEO_WITHIN:{const t=e.operands[0];return{[e.fieldName]:{$geoWithin:{$geometry:t.geometry.toJSON()}}}}case ue.GEO_INTERSECTS:{const t=e.operands[0];return{[e.fieldName]:{$geoIntersects:{$geometry:t.geometry.toJSON()}}}}default:return{[e.fieldName]:{[t]:be(e.operands[0])}}}}encodeQueryObject(e){const t=ge(e);for(const e in t){const r=t[e];if(ae(r)){t[e]=r._setFieldName(e);const n=this.encodeLogicCommand(t[e]);this.mergeConditionAfterEncode(t,n,e)}else if(fe(r)){t[e]=r._setFieldName(e);const n=this.encodeComparisonCommand(t[e]);this.mergeConditionAfterEncode(t,n,e)}else me(r)&&(t[e]=be(r))}return t}mergeConditionAfterEncode(e,t,r){t[r]||delete e[r];for(const n in t)e[n]?Y(e[n])?e[n]=e[n].concat(t[n]):F(e[n])?F(t[n])?Object.assign(e,t):(console.warn(`unmergable condition, query is object but condition is ${z(t)}, can only overwrite`,t,r),e[n]=t[n]):(console.warn(`to-merge query is of type ${z(e)}, can only overwrite`,e,t,r),e[n]=t[n]):e[n]=t[n]}}class Ge{constructor(e,t,r,n,i){this.watch=e=>(ft.ws||(ft.ws=new We({context:{appConfig:{docSizeLimit:1e3,realtimePingInterval:1e4,realtimePongWaitTimeout:5e3,request:this._request}}})),ft.ws.watch(Object.assign(Object.assign({},e),{envId:this._db.config.env,collectionName:this._coll,query:JSON.stringify(this._fieldFilters),limit:this._queryOptions.limit,orderBy:this._fieldOrders?this._fieldOrders.reduce((e,t)=>(e[t.field]=t.direction,e),{}):void 0}))),this._db=e,this._coll=t,this._fieldFilters=r,this._fieldOrders=n||[],this._queryOptions=i||{},this._request=new ft.reqClass(this._db.config)}get(e){e=e||te();let t=[];this._fieldOrders&&this._fieldOrders.forEach(e=>{t.push(e)});let r={collectionName:this._coll,queryType:w.WHERE};return this._fieldFilters&&(r.query=this._fieldFilters),t.length>0&&(r.order=t),this._queryOptions.offset&&(r.offset=this._queryOptions.offset),this._queryOptions.limit?r.limit=this._queryOptions.limit<1e3?this._queryOptions.limit:1e3:r.limit=100,this._queryOptions.projection&&(r.projection=this._queryOptions.projection),this._request.send("database.queryDocument",r).then(t=>{if(t.code)e(0,t);else{const r={data:U.formatResDocumentData(t.data.list),requestId:t.requestId};t.TotalCount&&(r.total=t.TotalCount),t.Limit&&(r.limit=t.Limit),t.Offset&&(r.offset=t.Offset),e(0,r)}}).catch(t=>{e(t)}),e.promise}count(e){e=e||te();let t={collectionName:this._coll,queryType:w.WHERE};return this._fieldFilters&&(t.query=this._fieldFilters),this._request.send("database.countDocument",t).then(t=>{t.code?e(0,t):e(0,{requestId:t.requestId,total:t.data.total})}),e.promise}where(e){if("Object"!==Object.prototype.toString.call(e).slice(8,-1))throw Error(n.QueryParamTypeError);const t=Object.keys(e),r=t.some(t=>void 0!==e[t]);if(t.length&&!r)throw Error(n.QueryParamValueError);return new Ge(this._db,this._coll,He.encode(e),this._fieldOrders,this._queryOptions)}orderBy(e,t){k.isFieldPath(e),k.isFieldOrder(t);const r={field:e,direction:t},n=this._fieldOrders.concat(r);return new Ge(this._db,this._coll,this._fieldFilters,n,this._queryOptions)}limit(e){k.isInteger("limit",e);let t=Object.assign({},this._queryOptions);return t.limit=e,new Ge(this._db,this._coll,this._fieldFilters,this._fieldOrders,t)}skip(e){k.isInteger("offset",e);let t=Object.assign({},this._queryOptions);return t.offset=e,new Ge(this._db,this._coll,this._fieldFilters,this._fieldOrders,t)}update(e,t){if(t=t||te(),!e||"object"!=typeof e)return Promise.resolve({code:"INVALID_PARAM",message:"参数必需是非空对象"});if(e.hasOwnProperty("_id"))return Promise.resolve({code:"INVALID_PARAM",message:"不能更新_id的值"});let r={collectionName:this._coll,query:this._fieldFilters,queryType:w.WHERE,multi:!0,merge:!0,upsert:!1,data:we.encode(e)};return this._request.send("database.updateDocument",r).then(e=>{e.code?t(0,e):t(0,{requestId:e.requestId,updated:e.data.updated,upsertId:e.data.upsert_id})}),t.promise}field(e){for(let t in e)e[t]?"object"!=typeof e[t]&&(e[t]=1):e[t]=0;let t=Object.assign({},this._queryOptions);return t.projection=e,new Ge(this._db,this._coll,this._fieldFilters,this._fieldOrders,t)}remove(e){e=e||te(),Object.keys(this._queryOptions).length>0&&console.warn("`offset`, `limit` and `projection` are not supported in remove() operation"),this._fieldOrders.length>0&&console.warn("`orderBy` is not supported in remove() operation");const t={collectionName:this._coll,query:He.encode(this._fieldFilters),queryType:w.WHERE,multi:!0};return this._request.send("database.deleteDocument",t).then(t=>{t.code?e(0,t):e(0,{requestId:t.requestId,deleted:t.data.deleted})}),e.promise}}var Je=r(0);class Ve{constructor(e,t){this._stages=[],e&&t&&(this._db=e,this._request=new ft.reqClass(this._db.config),this._collectionName=t)}async end(){if(!this._collectionName||!this._db)throw new Error("Aggregation pipeline cannot send request");const e=await this._request.send("database.aggregate",{collectionName:this._collectionName,stages:this._stages});return e&&e.data&&e.data.list?{requestId:e.requestId,data:JSON.parse(e.data.list).map(Je.a.parse)}:e}unwrap(){return this._stages}done(){return this._stages.map(({stageKey:e,stageValue:t})=>({[e]:JSON.parse(t)}))}_pipe(e,t){return this._stages.push({stageKey:"$"+e,stageValue:JSON.stringify(t)}),this}addFields(e){return this._pipe("addFields",e)}bucket(e){return this._pipe("bucket",e)}bucketAuto(e){return this._pipe("bucketAuto",e)}count(e){return this._pipe("count",e)}geoNear(e){return this._pipe("geoNear",e)}group(e){return this._pipe("group",e)}limit(e){return this._pipe("limit",e)}match(e){return this._pipe("match",He.encode(e))}project(e){return this._pipe("project",e)}lookup(e){return this._pipe("lookup",e)}replaceRoot(e){return this._pipe("replaceRoot",e)}sample(e){return this._pipe("sample",e)}skip(e){return this._pipe("skip",e)}sort(e){return this._pipe("sort",e)}sortByCount(e){return this._pipe("sortByCount",e)}unwind(e){return this._pipe("unwind",e)}}class Xe extends Ge{constructor(e,t){super(e,t)}get name(){return this._coll}doc(e){if("string"!=typeof e&&"number"!=typeof e)throw new Error("docId必须为字符串或数字");return new Ye(this._db,this._coll,e)}add(e,t){return new Ye(this._db,this._coll,void 0).create(e,t)}aggregate(){return new Ve(this._db,this._coll)}}const Qe={eq:e=>new ce(ue.EQ,[e]),neq:e=>new ce(ue.NEQ,[e]),lt:e=>new ce(ue.LT,[e]),lte:e=>new ce(ue.LTE,[e]),gt:e=>new ce(ue.GT,[e]),gte:e=>new ce(ue.GTE,[e]),in:e=>new ce(ue.IN,e),nin:e=>new ce(ue.NIN,e),all:e=>new ce(ue.ALL,e),elemMatch:e=>new ce(ue.ELEM_MATCH,[e]),exists:e=>new ce(ue.EXISTS,[e]),size:e=>new ce(ue.SIZE,[e]),mod:e=>new ce(ue.MOD,[e]),geoNear:e=>new ce(ue.GEO_NEAR,[e]),geoWithin:e=>new ce(ue.GEO_WITHIN,[e]),geoIntersects:e=>new ce(ue.GEO_INTERSECTS,[e]),and(...e){const t=Y(arguments[0])?arguments[0]:Array.from(arguments);return new se(oe.AND,t)},nor(...e){const t=Y(arguments[0])?arguments[0]:Array.from(arguments);return new se(oe.NOR,t)},or(...e){const t=Y(arguments[0])?arguments[0]:Array.from(arguments);return new se(oe.OR,t)},not(...e){const t=Y(arguments[0])?arguments[0]:Array.from(arguments);return new se(oe.NOT,t)},set:e=>new ne(re.SET,[e]),remove:()=>new ne(re.REMOVE,[]),inc:e=>new ne(re.INC,[e]),mul:e=>new ne(re.MUL,[e]),push(...e){let t;if(F(e[0])&&e[0].hasOwnProperty("each")){const r=e[0];t={$each:r.each,$position:r.position,$sort:r.sort,$slice:r.slice}}else t=Y(e[0])?e[0]:Array.from(e);return new ne(re.PUSH,t)},pull:e=>new ne(re.PULL,e),pullAll:e=>new ne(re.PULL_ALL,e),pop:()=>new ne(re.POP,[]),shift:()=>new ne(re.SHIFT,[]),unshift(...e){const t=Y(arguments[0])?arguments[0]:Array.from(arguments);return new ne(re.UNSHIFT,t)},addToSet:e=>new ne(re.ADD_TO_SET,e),rename:e=>new ne(re.RENAME,[e]),bit:e=>new ne(re.BIT,[e]),max:e=>new ne(re.MAX,[e]),min:e=>new ne(re.MIN,[e]),expr:e=>({$expr:e}),jsonSchema:e=>({$jsonSchema:e}),text:e=>q(e)?{$search:e.search}:{$search:e.search,$language:e.language,$caseSensitive:e.caseSensitive,$diacriticSensitive:e.diacriticSensitive},aggregate:{pipeline:()=>new Ve,abs:e=>new Ze("abs",e),add:e=>new Ze("add",e),ceil:e=>new Ze("ceil",e),divide:e=>new Ze("divide",e),exp:e=>new Ze("exp",e),floor:e=>new Ze("floor",e),ln:e=>new Ze("ln",e),log:e=>new Ze("log",e),log10:e=>new Ze("log10",e),mod:e=>new Ze("mod",e),multiply:e=>new Ze("multiply",e),pow:e=>new Ze("pow",e),sqrt:e=>new Ze("sqrt",e),subtract:e=>new Ze("subtract",e),trunc:e=>new Ze("trunc",e),arrayElemAt:e=>new Ze("arrayElemAt",e),arrayToObject:e=>new Ze("arrayToObject",e),concatArrays:e=>new Ze("concatArrays",e),filter:e=>new Ze("filter",e),in:e=>new Ze("in",e),indexOfArray:e=>new Ze("indexOfArray",e),isArray:e=>new Ze("isArray",e),map:e=>new Ze("map",e),range:e=>new Ze("range",e),reduce:e=>new Ze("reduce",e),reverseArray:e=>new Ze("reverseArray",e),size:e=>new Ze("size",e),slice:e=>new Ze("slice",e),zip:e=>new Ze("zip",e),and:e=>new Ze("and",e),not:e=>new Ze("not",e),or:e=>new Ze("or",e),cmp:e=>new Ze("cmp",e),eq:e=>new Ze("eq",e),gt:e=>new Ze("gt",e),gte:e=>new Ze("gte",e),lt:e=>new Ze("lt",e),lte:e=>new Ze("lte",e),neq:e=>new Ze("ne",e),cond:e=>new Ze("cond",e),ifNull:e=>new Ze("ifNull",e),switch:e=>new Ze("switch",e),dateFromParts:e=>new Ze("dateFromParts",e),dateFromString:e=>new Ze("dateFromString",e),dayOfMonth:e=>new Ze("dayOfMonth",e),dayOfWeek:e=>new Ze("dayOfWeek",e),dayOfYear:e=>new Ze("dayOfYear",e),isoDayOfWeek:e=>new Ze("isoDayOfWeek",e),isoWeek:e=>new Ze("isoWeek",e),isoWeekYear:e=>new Ze("isoWeekYear",e),millisecond:e=>new Ze("millisecond",e),minute:e=>new Ze("minute",e),month:e=>new Ze("month",e),second:e=>new Ze("second",e),hour:e=>new Ze("hour",e),week:e=>new Ze("week",e),year:e=>new Ze("year",e),literal:e=>new Ze("literal",e),mergeObjects:e=>new Ze("mergeObjects",e),objectToArray:e=>new Ze("objectToArray",e),allElementsTrue:e=>new Ze("allElementsTrue",e),anyElementTrue:e=>new Ze("anyElementTrue",e),setDifference:e=>new Ze("setDifference",e),setEquals:e=>new Ze("setEquals",e),setIntersection:e=>new Ze("setIntersection",e),setIsSubset:e=>new Ze("setIsSubset",e),setUnion:e=>new Ze("setUnion",e),concat:e=>new Ze("concat",e),dateToString:e=>new Ze("dateToString",e),indexOfBytes:e=>new Ze("indexOfBytes",e),indexOfCP:e=>new Ze("indexOfCP",e),split:e=>new Ze("split",e),strLenBytes:e=>new Ze("strLenBytes",e),strLenCP:e=>new Ze("strLenCP",e),strcasecmp:e=>new Ze("strcasecmp",e),substr:e=>new Ze("substr",e),substrBytes:e=>new Ze("substrBytes",e),substrCP:e=>new Ze("substrCP",e),toLower:e=>new Ze("toLower",e),toUpper:e=>new Ze("toUpper",e),meta:e=>new Ze("meta",e),addToSet:e=>new Ze("addToSet",e),avg:e=>new Ze("avg",e),first:e=>new Ze("first",e),last:e=>new Ze("last",e),max:e=>new Ze("max",e),min:e=>new Ze("min",e),push:e=>new Ze("push",e),stdDevPop:e=>new Ze("stdDevPop",e),stdDevSamp:e=>new Ze("stdDevSamp",e),sum:e=>new Ze("sum",e),let:e=>new Ze("let",e)},project:{slice:e=>new et("slice",e),elemMatch:e=>new et("elemMatch",e)}};class Ze{constructor(e,t){this["$"+e]=t}}class et{constructor(e,t){this["$"+e]=t}}class tt{constructor({regexp:e,options:t}){if(!e)throw new TypeError("regexp must be a string");this.$regex=e,this.$options=t}parse(){return{$regex:this.$regex,$options:this.$options}}get _internalType(){return L}}function rt(e){return new tt(e)}const nt={code:"INSERT_DOC_FAIL",message:"insert document failed"},it={code:"DATABASE_TRANSACTION_CONFLICT",message:"database transaction conflict"},ot="database.updateDocInTransaction";class st{constructor(e,t,r){this._coll=t,this.id=r,this._transaction=e,this._request=this._transaction.getRequestMethod(),this._transactionId=this._transaction.getTransactionId()}async create(e){let t={collectionName:this._coll,transactionId:this._transactionId,data:Je.a.stringify(pe(e),{relaxed:!1})};this.id&&(t._id=this.id);const r=await this._request.send("database.insertDocInTransaction",t);if(r.code)throw r;const n=Je.a.parse(r.inserted),i=Je.a.parse(r.ok);if(1==i&&1==n)return Object.assign(Object.assign({},r),{ok:i,inserted:n});throw new Error(nt.message)}async get(){const e={collectionName:this._coll,transactionId:this._transactionId,query:{_id:{$eq:this.id}}},t=await this._request.send("database.getInTransaction",e);if(t.code)throw t;return{data:"null"!==t.data?U.formatField(Je.a.parse(t.data)):Je.a.parse(t.data),requestId:t.requestId}}async set(e){const t={collectionName:this._coll,transactionId:this._transactionId,query:{_id:{$eq:this.id}},data:Je.a.stringify(pe(e),{relaxed:!1}),upsert:!0},r=await this._request.send(ot,t);if(r.code)throw r;return Object.assign(Object.assign({},r),{updated:Je.a.parse(r.updated),upserted:r.upserted?JSON.parse(r.upserted):null})}async update(e){const t={collectionName:this._coll,transactionId:this._transactionId,query:{_id:{$eq:this.id}},data:Je.a.stringify(we.encode(e),{relaxed:!1})},r=await this._request.send(ot,t);if(r.code)throw r;return Object.assign(Object.assign({},r),{updated:Je.a.parse(r.updated)})}async delete(){const e={collectionName:this._coll,transactionId:this._transactionId,query:{_id:{$eq:this.id}}},t=await this._request.send("database.deleteDocInTransaction",e);if(t.code)throw t;return Object.assign(Object.assign({},t),{deleted:Je.a.parse(t.deleted)})}}class at extends class{constructor(e,t){this._coll=t,this._transaction=e}}{constructor(e,t){super(e,t)}get name(){return this._coll}doc(e){if("string"!=typeof e&&"number"!=typeof e)throw new Error("docId必须为字符串或数字");return new st(this._transaction,this._coll,e)}add(e){let t;return void 0!==e._id&&(t=e._id),new st(this._transaction,this._coll,t).create(e)}}class ut{constructor(e){this._db=e,this._request=new ft.reqClass(this._db.config),this.aborted=!1,this.commited=!1,this.inited=!1}async init(){const e=await this._request.send("database.startTransaction");if(e.code)throw e;this.inited=!0,this._id=e.transactionId}collection(e){if(!e)throw new Error("Collection name is required");return new at(this,e)}getTransactionId(){return this._id}getRequestMethod(){return this._request}async commit(){const e={transactionId:this._id},t=await this._request.send("database.commitTransaction",e);if(t.code)throw t;return this.commited=!0,t}async rollback(e){const t={transactionId:this._id},r=await this._request.send("database.abortTransaction",t);if(r.code)throw r;return this.aborted=!0,this.abortReason=e,r}}async function ct(){const e=new ut(this);return await e.init(),e}async function lt(e,t=3){let r;try{r=new ut(this),await r.init();const t=await e(r);if(!0===r.aborted)throw r.abortReason;return await r.commit(),t}catch(n){if(!1===r.inited)throw n;const i=async e=>{if(!r.aborted&&!r.commited){try{await r.rollback()}catch(e){}throw e}if(!0===r.aborted)throw r.abortReason;throw e};if(t<=0&&await i(n),n&&n.code===it.code)return await lt.bind(this)(e,--t);await i(n)}}class ft{constructor(e){this.config=e,this.Geo=i,this.serverDate=x,this.command=Qe,this.RegExp=rt,this.startTransaction=ct,this.runTransaction=lt,this.logicCommand=se,this.updateCommand=ne,this.queryCommand=ce}collection(e){if(!e)throw new Error("Collection name is required");return new Xe(this,e)}createCollection(e){const t={collectionName:e};return new ft.reqClass(this.config).send("database.addCollection",t)}}}])}));