diff --git a/webmanager/acebase-client-browser.min.js b/webmanager/acebase-client-browser.min.js new file mode 100644 index 0000000..fb517d0 --- /dev/null +++ b/webmanager/acebase-client-browser.min.js @@ -0,0 +1,16 @@ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.acebaseclient=f()}})((function(){var define,module,exports;return function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,(function(r){var n=e[i][1][r];return o(n||r)}),p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i0){throw new Error("Invalid string. Length must be a multiple of 4")}var validLen=b64.indexOf("=");if(validLen===-1)validLen=len;var placeHoldersLen=validLen===len?0:4-validLen%4;return[validLen,placeHoldersLen]}function byteLength(b64){var lens=getLens(b64);var validLen=lens[0];var placeHoldersLen=lens[1];return(validLen+placeHoldersLen)*3/4-placeHoldersLen}function _byteLength(b64,validLen,placeHoldersLen){return(validLen+placeHoldersLen)*3/4-placeHoldersLen}function toByteArray(b64){var tmp;var lens=getLens(b64);var validLen=lens[0];var placeHoldersLen=lens[1];var arr=new Arr(_byteLength(b64,validLen,placeHoldersLen));var curByte=0;var len=placeHoldersLen>0?validLen-4:validLen;var i;for(i=0;i>16&255;arr[curByte++]=tmp>>8&255;arr[curByte++]=tmp&255}if(placeHoldersLen===2){tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4;arr[curByte++]=tmp&255}if(placeHoldersLen===1){tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2;arr[curByte++]=tmp>>8&255;arr[curByte++]=tmp&255}return arr}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[num&63]}function encodeChunk(uint8,start,end){var tmp;var output=[];for(var i=start;ilen2?len2:i+maxChunkLength))}if(extraBytes===1){tmp=uint8[len-1];parts.push(lookup[tmp>>2]+lookup[tmp<<4&63]+"==")}else if(extraBytes===2){tmp=(uint8[len-2]<<8)+uint8[len-1];parts.push(lookup[tmp>>10]+lookup[tmp>>4&63]+lookup[tmp<<2&63]+"=")}return parts.join("")}},{}],2:[function(require,module,exports){},{}],3:[function(require,module,exports){(function(Buffer){(function(){ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +"use strict";var base64=require("base64-js");var ieee754=require("ieee754");exports.Buffer=Buffer;exports.SlowBuffer=SlowBuffer;exports.INSPECT_MAX_BYTES=50;var K_MAX_LENGTH=2147483647;exports.kMaxLength=K_MAX_LENGTH;Buffer.TYPED_ARRAY_SUPPORT=typedArraySupport();if(!Buffer.TYPED_ARRAY_SUPPORT&&typeof console!=="undefined"&&typeof console.error==="function"){console.error("This browser lacks typed array (Uint8Array) support which is required by "+"`buffer` v5.x. Use `buffer` v4.x if you require old browser support.")}function typedArraySupport(){try{var arr=new Uint8Array(1);arr.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}};return arr.foo()===42}catch(e){return false}}Object.defineProperty(Buffer.prototype,"parent",{enumerable:true,get:function(){if(!Buffer.isBuffer(this))return undefined;return this.buffer}});Object.defineProperty(Buffer.prototype,"offset",{enumerable:true,get:function(){if(!Buffer.isBuffer(this))return undefined;return this.byteOffset}});function createBuffer(length){if(length>K_MAX_LENGTH){throw new RangeError('The value "'+length+'" is invalid for option "size"')}var buf=new Uint8Array(length);buf.__proto__=Buffer.prototype;return buf}function Buffer(arg,encodingOrOffset,length){if(typeof arg==="number"){if(typeof encodingOrOffset==="string"){throw new TypeError('The "string" argument must be of type string. Received type number')}return allocUnsafe(arg)}return from(arg,encodingOrOffset,length)}if(typeof Symbol!=="undefined"&&Symbol.species!=null&&Buffer[Symbol.species]===Buffer){Object.defineProperty(Buffer,Symbol.species,{value:null,configurable:true,enumerable:false,writable:false})}Buffer.poolSize=8192;function from(value,encodingOrOffset,length){if(typeof value==="string"){return fromString(value,encodingOrOffset)}if(ArrayBuffer.isView(value)){return fromArrayLike(value)}if(value==null){throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, "+"or Array-like Object. Received type "+typeof value)}if(isInstance(value,ArrayBuffer)||value&&isInstance(value.buffer,ArrayBuffer)){return fromArrayBuffer(value,encodingOrOffset,length)}if(typeof value==="number"){throw new TypeError('The "value" argument must not be of type number. Received type number')}var valueOf=value.valueOf&&value.valueOf();if(valueOf!=null&&valueOf!==value){return Buffer.from(valueOf,encodingOrOffset,length)}var b=fromObject(value);if(b)return b;if(typeof Symbol!=="undefined"&&Symbol.toPrimitive!=null&&typeof value[Symbol.toPrimitive]==="function"){return Buffer.from(value[Symbol.toPrimitive]("string"),encodingOrOffset,length)}throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, "+"or Array-like Object. Received type "+typeof value)}Buffer.from=function(value,encodingOrOffset,length){return from(value,encodingOrOffset,length)};Buffer.prototype.__proto__=Uint8Array.prototype;Buffer.__proto__=Uint8Array;function assertSize(size){if(typeof size!=="number"){throw new TypeError('"size" argument must be of type number')}else if(size<0){throw new RangeError('The value "'+size+'" is invalid for option "size"')}}function alloc(size,fill,encoding){assertSize(size);if(size<=0){return createBuffer(size)}if(fill!==undefined){return typeof encoding==="string"?createBuffer(size).fill(fill,encoding):createBuffer(size).fill(fill)}return createBuffer(size)}Buffer.alloc=function(size,fill,encoding){return alloc(size,fill,encoding)};function allocUnsafe(size){assertSize(size);return createBuffer(size<0?0:checked(size)|0)}Buffer.allocUnsafe=function(size){return allocUnsafe(size)};Buffer.allocUnsafeSlow=function(size){return allocUnsafe(size)};function fromString(string,encoding){if(typeof encoding!=="string"||encoding===""){encoding="utf8"}if(!Buffer.isEncoding(encoding)){throw new TypeError("Unknown encoding: "+encoding)}var length=byteLength(string,encoding)|0;var buf=createBuffer(length);var actual=buf.write(string,encoding);if(actual!==length){buf=buf.slice(0,actual)}return buf}function fromArrayLike(array){var length=array.length<0?0:checked(array.length)|0;var buf=createBuffer(length);for(var i=0;i=K_MAX_LENGTH){throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+K_MAX_LENGTH.toString(16)+" bytes")}return length|0}function SlowBuffer(length){if(+length!=length){length=0}return Buffer.alloc(+length)}Buffer.isBuffer=function isBuffer(b){return b!=null&&b._isBuffer===true&&b!==Buffer.prototype};Buffer.compare=function compare(a,b){if(isInstance(a,Uint8Array))a=Buffer.from(a,a.offset,a.byteLength);if(isInstance(b,Uint8Array))b=Buffer.from(b,b.offset,b.byteLength);if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b)){throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array')}if(a===b)return 0;var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i2&&arguments[2]===true;if(!mustMatch&&len===0)return 0;var loweredCase=false;for(;;){switch(encoding){case"ascii":case"latin1":case"binary":return len;case"utf8":case"utf-8":return utf8ToBytes(string).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return len*2;case"hex":return len>>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase){return mustMatch?-1:utf8ToBytes(string).length}encoding=(""+encoding).toLowerCase();loweredCase=true}}}Buffer.byteLength=byteLength;function slowToString(encoding,start,end){var loweredCase=false;if(start===undefined||start<0){start=0}if(start>this.length){return""}if(end===undefined||end>this.length){end=this.length}if(end<=0){return""}end>>>=0;start>>>=0;if(end<=start){return""}if(!encoding)encoding="utf8";while(true){switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"latin1":case"binary":return latin1Slice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase();loweredCase=true}}}Buffer.prototype._isBuffer=true;function swap(b,n,m){var i=b[n];b[n]=b[m];b[m]=i}Buffer.prototype.swap16=function swap16(){var len=this.length;if(len%2!==0){throw new RangeError("Buffer size must be a multiple of 16-bits")}for(var i=0;imax)str+=" ... ";return""};Buffer.prototype.compare=function compare(target,start,end,thisStart,thisEnd){if(isInstance(target,Uint8Array)){target=Buffer.from(target,target.offset,target.byteLength)}if(!Buffer.isBuffer(target)){throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. '+"Received type "+typeof target)}if(start===undefined){start=0}if(end===undefined){end=target?target.length:0}if(thisStart===undefined){thisStart=0}if(thisEnd===undefined){thisEnd=this.length}if(start<0||end>target.length||thisStart<0||thisEnd>this.length){throw new RangeError("out of range index")}if(thisStart>=thisEnd&&start>=end){return 0}if(thisStart>=thisEnd){return-1}if(start>=end){return 1}start>>>=0;end>>>=0;thisStart>>>=0;thisEnd>>>=0;if(this===target)return 0;var x=thisEnd-thisStart;var y=end-start;var len=Math.min(x,y);var thisCopy=this.slice(thisStart,thisEnd);var targetCopy=target.slice(start,end);for(var i=0;i2147483647){byteOffset=2147483647}else if(byteOffset<-2147483648){byteOffset=-2147483648}byteOffset=+byteOffset;if(numberIsNaN(byteOffset)){byteOffset=dir?0:buffer.length-1}if(byteOffset<0)byteOffset=buffer.length+byteOffset;if(byteOffset>=buffer.length){if(dir)return-1;else byteOffset=buffer.length-1}else if(byteOffset<0){if(dir)byteOffset=0;else return-1}if(typeof val==="string"){val=Buffer.from(val,encoding)}if(Buffer.isBuffer(val)){if(val.length===0){return-1}return arrayIndexOf(buffer,val,byteOffset,encoding,dir)}else if(typeof val==="number"){val=val&255;if(typeof Uint8Array.prototype.indexOf==="function"){if(dir){return Uint8Array.prototype.indexOf.call(buffer,val,byteOffset)}else{return Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset)}}return arrayIndexOf(buffer,[val],byteOffset,encoding,dir)}throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir){var indexSize=1;var arrLength=arr.length;var valLength=val.length;if(encoding!==undefined){encoding=String(encoding).toLowerCase();if(encoding==="ucs2"||encoding==="ucs-2"||encoding==="utf16le"||encoding==="utf-16le"){if(arr.length<2||val.length<2){return-1}indexSize=2;arrLength/=2;valLength/=2;byteOffset/=2}}function read(buf,i){if(indexSize===1){return buf[i]}else{return buf.readUInt16BE(i*indexSize)}}var i;if(dir){var foundIndex=-1;for(i=byteOffset;iarrLength)byteOffset=arrLength-valLength;for(i=byteOffset;i>=0;i--){var found=true;for(var j=0;jremaining){length=remaining}}var strLen=string.length;if(length>strLen/2){length=strLen/2}for(var i=0;i>>0;if(isFinite(length)){length=length>>>0;if(encoding===undefined)encoding="utf8"}else{encoding=length;length=undefined}}else{throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported")}var remaining=this.length-offset;if(length===undefined||length>remaining)length=remaining;if(string.length>0&&(length<0||offset<0)||offset>this.length){throw new RangeError("Attempt to write outside buffer bounds")}if(!encoding)encoding="utf8";var loweredCase=false;for(;;){switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":return asciiWrite(this,string,offset,length);case"latin1":case"binary":return latin1Write(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase();loweredCase=true}}};Buffer.prototype.toJSON=function toJSON(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function base64Slice(buf,start,end){if(start===0&&end===buf.length){return base64.fromByteArray(buf)}else{return base64.fromByteArray(buf.slice(start,end))}}function utf8Slice(buf,start,end){end=Math.min(buf.length,end);var res=[];var i=start;while(i239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:if(firstByte<128){codePoint=firstByte}break;case 2:secondByte=buf[i+1];if((secondByte&192)===128){tempCodePoint=(firstByte&31)<<6|secondByte&63;if(tempCodePoint>127){codePoint=tempCodePoint}}break;case 3:secondByte=buf[i+1];thirdByte=buf[i+2];if((secondByte&192)===128&&(thirdByte&192)===128){tempCodePoint=(firstByte&15)<<12|(secondByte&63)<<6|thirdByte&63;if(tempCodePoint>2047&&(tempCodePoint<55296||tempCodePoint>57343)){codePoint=tempCodePoint}}break;case 4:secondByte=buf[i+1];thirdByte=buf[i+2];fourthByte=buf[i+3];if((secondByte&192)===128&&(thirdByte&192)===128&&(fourthByte&192)===128){tempCodePoint=(firstByte&15)<<18|(secondByte&63)<<12|(thirdByte&63)<<6|fourthByte&63;if(tempCodePoint>65535&&tempCodePoint<1114112){codePoint=tempCodePoint}}}}if(codePoint===null){codePoint=65533;bytesPerSequence=1}else if(codePoint>65535){codePoint-=65536;res.push(codePoint>>>10&1023|55296);codePoint=56320|codePoint&1023}res.push(codePoint);i+=bytesPerSequence}return decodeCodePointsArray(res)}var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH){return String.fromCharCode.apply(String,codePoints)}var res="";var i=0;while(ilen)end=len;var out="";for(var i=start;ilen){start=len}if(end<0){end+=len;if(end<0)end=0}else if(end>len){end=len}if(endlength)throw new RangeError("Trying to access beyond buffer length")}Buffer.prototype.readUIntLE=function readUIntLE(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i>>0;byteLength=byteLength>>>0;if(!noAssert){checkOffset(offset,byteLength,this.length)}var val=this[offset+--byteLength];var mul=1;while(byteLength>0&&(mul*=256)){val+=this[offset+--byteLength]*mul}return val};Buffer.prototype.readUInt8=function readUInt8(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,1,this.length);return this[offset]};Buffer.prototype.readUInt16LE=function readUInt16LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8};Buffer.prototype.readUInt16BE=function readUInt16BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1]};Buffer.prototype.readUInt32LE=function readUInt32LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*16777216};Buffer.prototype.readUInt32BE=function readUInt32BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*16777216+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])};Buffer.prototype.readIntLE=function readIntLE(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readIntBE=function readIntBE(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var i=byteLength;var mul=1;var val=this[offset+--i];while(i>0&&(mul*=256)){val+=this[offset+--i]*mul}mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readInt8=function readInt8(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&128))return this[offset];return(255-this[offset]+1)*-1};Buffer.prototype.readInt16LE=function readInt16LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt16BE=function readInt16BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt32LE=function readInt32LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24};Buffer.prototype.readInt32BE=function readInt32BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]};Buffer.prototype.readFloatLE=function readFloatLE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4)};Buffer.prototype.readFloatBE=function readFloatBE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4)};Buffer.prototype.readDoubleLE=function readDoubleLE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8)};Buffer.prototype.readDoubleBE=function readDoubleBE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,false,52,8)};function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(value>max||valuebuf.length)throw new RangeError("Index out of range")}Buffer.prototype.writeUIntLE=function writeUIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var mul=1;var i=0;this[offset]=value&255;while(++i>>0;byteLength=byteLength>>>0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var i=byteLength-1;var mul=1;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){this[offset+i]=value/mul&255}return offset+byteLength};Buffer.prototype.writeUInt8=function writeUInt8(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,255,0);this[offset]=value&255;return offset+1};Buffer.prototype.writeUInt16LE=function writeUInt16LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);this[offset]=value&255;this[offset+1]=value>>>8;return offset+2};Buffer.prototype.writeUInt16BE=function writeUInt16BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);this[offset]=value>>>8;this[offset+1]=value&255;return offset+2};Buffer.prototype.writeUInt32LE=function writeUInt32LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value&255;return offset+4};Buffer.prototype.writeUInt32BE=function writeUInt32BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255;return offset+4};Buffer.prototype.writeIntLE=function writeIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=0;var mul=1;var sub=0;this[offset]=value&255;while(++i>0)-sub&255}return offset+byteLength};Buffer.prototype.writeIntBE=function writeIntBE(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=byteLength-1;var mul=1;var sub=0;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){if(value<0&&sub===0&&this[offset+i+1]!==0){sub=1}this[offset+i]=(value/mul>>0)-sub&255}return offset+byteLength};Buffer.prototype.writeInt8=function writeInt8(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,127,-128);if(value<0)value=255+value+1;this[offset]=value&255;return offset+1};Buffer.prototype.writeInt16LE=function writeInt16LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);this[offset]=value&255;this[offset+1]=value>>>8;return offset+2};Buffer.prototype.writeInt16BE=function writeInt16BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);this[offset]=value>>>8;this[offset+1]=value&255;return offset+2};Buffer.prototype.writeInt32LE=function writeInt32LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);this[offset]=value&255;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24;return offset+4};Buffer.prototype.writeInt32BE=function writeInt32BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(value<0)value=4294967295+value+1;this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255;return offset+4};function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(offset<0)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){value=+value;offset=offset>>>0;if(!noAssert){checkIEEE754(buf,value,offset,4,34028234663852886e22,-34028234663852886e22)}ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4}Buffer.prototype.writeFloatLE=function writeFloatLE(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert)};Buffer.prototype.writeFloatBE=function writeFloatBE(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)};function writeDouble(buf,value,offset,littleEndian,noAssert){value=+value;offset=offset>>>0;if(!noAssert){checkIEEE754(buf,value,offset,8,17976931348623157e292,-17976931348623157e292)}ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8}Buffer.prototype.writeDoubleLE=function writeDoubleLE(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert)};Buffer.prototype.writeDoubleBE=function writeDoubleBE(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert)};Buffer.prototype.copy=function copy(target,targetStart,start,end){if(!Buffer.isBuffer(target))throw new TypeError("argument should be a Buffer");if(!start)start=0;if(!end&&end!==0)end=this.length;if(targetStart>=target.length)targetStart=target.length;if(!targetStart)targetStart=0;if(end>0&&end=this.length)throw new RangeError("Index out of range");if(end<0)throw new RangeError("sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-targetStart=0;--i){target[i+targetStart]=this[i+start]}}else{Uint8Array.prototype.set.call(target,this.subarray(start,end),targetStart)}return len};Buffer.prototype.fill=function fill(val,start,end,encoding){if(typeof val==="string"){if(typeof start==="string"){encoding=start;start=0;end=this.length}else if(typeof end==="string"){encoding=end;end=this.length}if(encoding!==undefined&&typeof encoding!=="string"){throw new TypeError("encoding must be a string")}if(typeof encoding==="string"&&!Buffer.isEncoding(encoding)){throw new TypeError("Unknown encoding: "+encoding)}if(val.length===1){var code=val.charCodeAt(0);if(encoding==="utf8"&&code<128||encoding==="latin1"){val=code}}}else if(typeof val==="number"){val=val&255}if(start<0||this.length>>0;end=end===undefined?this.length:end>>>0;if(!val)val=0;var i;if(typeof val==="number"){for(i=start;i55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){if((units-=3)>-1)bytes.push(239,191,189);continue}else if(i+1===length){if((units-=3)>-1)bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){if((units-=3)>-1)bytes.push(239,191,189);leadSurrogate=codePoint;continue}codePoint=(leadSurrogate-55296<<10|codePoint-56320)+65536}else if(leadSurrogate){if((units-=3)>-1)bytes.push(239,191,189)}leadSurrogate=null;if(codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,codePoint&63|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,codePoint&63|128)}else if(codePoint<1114112){if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,codePoint&63|128)}else{throw new Error("Invalid code point")}}return bytes}function asciiToBytes(str){var byteArray=[];for(var i=0;i>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}function isInstance(obj,type){return obj instanceof type||obj!=null&&obj.constructor!=null&&obj.constructor.name!=null&&obj.constructor.name===type.name}function numberIsNaN(obj){return obj!==obj}}).call(this)}).call(this,require("buffer").Buffer)},{"base64-js":1,buffer:3,ieee754:4}],4:[function(require,module,exports){ +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ +exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var nBits=-7;var i=isLE?nBytes-1:0;var d=isLE?-1:1;var s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8){}m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8){}if(e===0){e=1-eBias}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity}else{m=m+Math.pow(2,mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)};exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0;var i=isLE?0:nBytes-1;var d=isLE?1:-1;var s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1){value+=rt/c}else{value+=rt*Math.pow(2,1-eBias)}if(value*c>=2){e++;c/=2}if(e+eBias>=eMax){m=0;e=eMax}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8){}e=e<0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8){}buffer[offset+i-d]|=s*128}},{}],5:[function(require,module,exports){(function(Buffer){(function(){ +/*! + * Socket.IO v2.4.0 + * (c) 2014-2021 Guillermo Rauch + * Released under the MIT License. + */ +!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.io=e():t.io=e()}(this,(function(){return function(t){function e(n){if(r[n])return r[n].exports;var o=r[n]={exports:{},id:n,loaded:!1};return t[n].call(o.exports,o,o.exports,e),o.loaded=!0,o.exports}var r={};return e.m=t,e.c=r,e.p="",e(0)}([function(t,e,r){"use strict";function n(t,e){"object"===("undefined"==typeof t?"undefined":o(t))&&(e=t,t=void 0),e=e||{};var r,n=i(t),s=n.source,p=n.id,h=n.path,u=c[p]&&h in c[p].nsps,f=e.forceNew||e["force new connection"]||!1===e.multiplex||u;return f?r=a(s,e):(c[p]||(c[p]=a(s,e)),r=c[p]),n.query&&!e.query&&(e.query=n.query),r.socket(n.path,e)}var o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},i=r(1),s=r(4),a=r(9);r(3)("socket.io-client");t.exports=e=n;var c=e.managers={};e.protocol=s.protocol,e.connect=n,e.Manager=r(9),e.Socket=r(34)},function(t,e,r){"use strict";function n(t,e){var r=t;e=e||"undefined"!=typeof location&&location,null==t&&(t=e.protocol+"//"+e.host),"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?e.protocol+t:e.host+t),/^(https?|wss?):\/\//.test(t)||(t="undefined"!=typeof e?e.protocol+"//"+t:"https://"+t),r=o(t)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";var n=r.host.indexOf(":")!==-1,i=n?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+i+":"+r.port,r.href=r.protocol+"://"+i+(e&&e.port===r.port?"":":"+r.port),r}var o=r(2);r(3)("socket.io-client:url");t.exports=n},function(t,e){function r(t,e){var r=/\/{2,9}/g,n=e.replace(r,"/").split("/");return"/"!=e.substr(0,1)&&0!==e.length||n.splice(0,1),"/"==e.substr(e.length-1,1)&&n.splice(n.length-1,1),n}function n(t,e){var r={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(t,e,n){e&&(r[e]=n)})),r}var o=/^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,i=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];t.exports=function(t){var e=t,s=t.indexOf("["),a=t.indexOf("]");s!=-1&&a!=-1&&(t=t.substring(0,s)+t.substring(s,a).replace(/:/g,";")+t.substring(a,t.length));for(var c=o.exec(t||""),p={},h=14;h--;)p[i[h]]=c[h]||"";return s!=-1&&a!=-1&&(p.source=e,p.host=p.host.substring(1,p.host.length-1).replace(/;/g,":"),p.authority=p.authority.replace("[","").replace("]","").replace(/;/g,":"),p.ipv6uri=!0),p.pathNames=r(p,p.path),p.queryKey=n(p,p.query),p}},function(t,e){"use strict";t.exports=function(){return function(){}}},function(t,e,r){function n(){}function o(t){var r=""+t.type;if(e.BINARY_EVENT!==t.type&&e.BINARY_ACK!==t.type||(r+=t.attachments+"-"),t.nsp&&"/"!==t.nsp&&(r+=t.nsp+","),null!=t.id&&(r+=t.id),null!=t.data){var n=i(t.data);if(n===!1)return m;r+=n}return r}function i(t){try{return JSON.stringify(t)}catch(t){return!1}}function s(t,e){function r(t){var r=l.deconstructPacket(t),n=o(r.packet),i=r.buffers;i.unshift(n),e(i)}l.removeBlobs(t,r)}function a(){this.reconstructor=null}function c(t){var r=0,n={type:Number(t.charAt(0))};if(null==e.types[n.type])return u("unknown packet type "+n.type);if(e.BINARY_EVENT===n.type||e.BINARY_ACK===n.type){for(var o="";"-"!==t.charAt(++r)&&(o+=t.charAt(r),r!=t.length););if(o!=Number(o)||"-"!==t.charAt(r))throw new Error("Illegal attachments");n.attachments=Number(o)}if("/"===t.charAt(r+1))for(n.nsp="";++r;){var i=t.charAt(r);if(","===i)break;if(n.nsp+=i,r===t.length)break}else n.nsp="/";var s=t.charAt(r+1);if(""!==s&&Number(s)==s){for(n.id="";++r;){var i=t.charAt(r);if(null==i||Number(i)!=i){--r;break}if(n.id+=t.charAt(r),r===t.length)break}n.id=Number(n.id)}if(t.charAt(++r)){var a=p(t.substr(r)),c=a!==!1&&(n.type===e.ERROR||d(a));if(!c)return u("invalid payload");n.data=a}return n}function p(t){try{return JSON.parse(t)}catch(t){return!1}}function h(t){this.reconPack=t,this.buffers=[]}function u(t){return{type:e.ERROR,data:"parser error: "+t}}var f=(r(3)("socket.io-parser"),r(5)),l=r(6),d=r(7),y=r(8);e.protocol=4,e.types=["CONNECT","DISCONNECT","EVENT","ACK","ERROR","BINARY_EVENT","BINARY_ACK"],e.CONNECT=0,e.DISCONNECT=1,e.EVENT=2,e.ACK=3,e.ERROR=4,e.BINARY_EVENT=5,e.BINARY_ACK=6,e.Encoder=n,e.Decoder=a;var m=e.ERROR+'"encode error"';n.prototype.encode=function(t,r){if(e.BINARY_EVENT===t.type||e.BINARY_ACK===t.type)s(t,r);else{var n=o(t);r([n])}},f(a.prototype),a.prototype.add=function(t){var r;if("string"==typeof t)r=c(t),e.BINARY_EVENT===r.type||e.BINARY_ACK===r.type?(this.reconstructor=new h(r),0===this.reconstructor.reconPack.attachments&&this.emit("decoded",r)):this.emit("decoded",r);else{if(!y(t)&&!t.base64)throw new Error("Unknown type: "+t);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");r=this.reconstructor.takeBinaryData(t),r&&(this.reconstructor=null,this.emit("decoded",r))}},a.prototype.destroy=function(){this.reconstructor&&this.reconstructor.finishedReconstruction()},h.prototype.takeBinaryData=function(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){var e=l.reconstructPacket(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null},h.prototype.finishedReconstruction=function(){this.reconPack=null,this.buffers=[]}},function(t,e,r){function n(t){if(t)return o(t)}function o(t){for(var e in n.prototype)t[e]=n.prototype[e];return t}t.exports=n,n.prototype.on=n.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},n.prototype.once=function(t,e){function r(){this.off(t,r),e.apply(this,arguments)}return r.fn=e,this.on(t,r),this},n.prototype.off=n.prototype.removeListener=n.prototype.removeAllListeners=n.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r=this._callbacks["$"+t];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var n,o=0;o0&&!this.encoding){var t=this.packetBuffer.shift();this.packet(t)}},n.prototype.cleanup=function(){for(var t=this.subs.length,e=0;e=this._reconnectionAttempts)this.backoff.reset(),this.emitAll("reconnect_failed"),this.reconnecting=!1;else{var e=this.backoff.duration();this.reconnecting=!0;var r=setTimeout((function(){t.skipReconnect||(t.emitAll("reconnect_attempt",t.backoff.attempts),t.emitAll("reconnecting",t.backoff.attempts),t.skipReconnect||t.open((function(e){e?(t.reconnecting=!1,t.reconnect(),t.emitAll("reconnect_error",e.data)):t.onreconnect()})))}),e);this.subs.push({destroy:function(){clearTimeout(r)}})}},n.prototype.onreconnect=function(){var t=this.backoff.attempts;this.reconnecting=!1,this.backoff.reset(),this.updateSocketIds(),this.emitAll("reconnect",t)}},function(t,e,r){t.exports=r(11),t.exports.parser=r(19)},function(t,e,r){function n(t,e){return this instanceof n?(e=e||{},t&&"object"==typeof t&&(e=t,t=null),t?(t=p(t),e.hostname=t.host,e.secure="https"===t.protocol||"wss"===t.protocol,e.port=t.port,t.query&&(e.query=t.query)):e.host&&(e.hostname=p(e.host).host),this.secure=null!=e.secure?e.secure:"undefined"!=typeof location&&"https:"===location.protocol,e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.agent=e.agent||!1,this.hostname=e.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=e.port||("undefined"!=typeof location&&location.port?location.port:this.secure?443:80),this.query=e.query||{},"string"==typeof this.query&&(this.query=h.decode(this.query)),this.upgrade=!1!==e.upgrade,this.path=(e.path||"/engine.io").replace(/\/$/,"")+"/",this.forceJSONP=!!e.forceJSONP,this.jsonp=!1!==e.jsonp,this.forceBase64=!!e.forceBase64,this.enablesXDR=!!e.enablesXDR,this.withCredentials=!1!==e.withCredentials,this.timestampParam=e.timestampParam||"t",this.timestampRequests=e.timestampRequests,this.transports=e.transports||["polling","websocket"],this.transportOptions=e.transportOptions||{},this.readyState="",this.writeBuffer=[],this.prevBufferLen=0,this.policyPort=e.policyPort||843,this.rememberUpgrade=e.rememberUpgrade||!1,this.binaryType=null,this.onlyBinaryUpgrades=e.onlyBinaryUpgrades,this.perMessageDeflate=!1!==e.perMessageDeflate&&(e.perMessageDeflate||{}),!0===this.perMessageDeflate&&(this.perMessageDeflate={}),this.perMessageDeflate&&null==this.perMessageDeflate.threshold&&(this.perMessageDeflate.threshold=1024),this.pfx=e.pfx||null,this.key=e.key||null,this.passphrase=e.passphrase||null,this.cert=e.cert||null,this.ca=e.ca||null,this.ciphers=e.ciphers||null,this.rejectUnauthorized=void 0===e.rejectUnauthorized||e.rejectUnauthorized,this.forceNode=!!e.forceNode,this.isReactNative="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase(),("undefined"==typeof self||this.isReactNative)&&(e.extraHeaders&&Object.keys(e.extraHeaders).length>0&&(this.extraHeaders=e.extraHeaders),e.localAddress&&(this.localAddress=e.localAddress)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingIntervalTimer=null,this.pingTimeoutTimer=null,void this.open()):new n(t,e)}function o(t){var e={};for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r]);return e}var i=r(12),s=r(5),a=(r(3)("engine.io-client:socket"),r(33)),c=r(19),p=r(2),h=r(27);t.exports=n,n.priorWebsocketSuccess=!1,s(n.prototype),n.protocol=c.protocol,n.Socket=n,n.Transport=r(18),n.transports=r(12),n.parser=r(19),n.prototype.createTransport=function(t){var e=o(this.query);e.EIO=c.protocol,e.transport=t;var r=this.transportOptions[t]||{};this.id&&(e.sid=this.id);var n=new i[t]({query:e,socket:this,agent:r.agent||this.agent,hostname:r.hostname||this.hostname,port:r.port||this.port,secure:r.secure||this.secure,path:r.path||this.path,forceJSONP:r.forceJSONP||this.forceJSONP,jsonp:r.jsonp||this.jsonp,forceBase64:r.forceBase64||this.forceBase64,enablesXDR:r.enablesXDR||this.enablesXDR,withCredentials:r.withCredentials||this.withCredentials,timestampRequests:r.timestampRequests||this.timestampRequests,timestampParam:r.timestampParam||this.timestampParam,policyPort:r.policyPort||this.policyPort,pfx:r.pfx||this.pfx,key:r.key||this.key,passphrase:r.passphrase||this.passphrase,cert:r.cert||this.cert,ca:r.ca||this.ca,ciphers:r.ciphers||this.ciphers,rejectUnauthorized:r.rejectUnauthorized||this.rejectUnauthorized,perMessageDeflate:r.perMessageDeflate||this.perMessageDeflate,extraHeaders:r.extraHeaders||this.extraHeaders,forceNode:r.forceNode||this.forceNode,localAddress:r.localAddress||this.localAddress,requestTimeout:r.requestTimeout||this.requestTimeout,protocols:r.protocols||void 0,isReactNative:this.isReactNative});return n},n.prototype.open=function(){var t;if(this.rememberUpgrade&&n.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1)t="websocket";else{if(0===this.transports.length){var e=this;return void setTimeout((function(){e.emit("error","No transports available")}),0)}t=this.transports[0]}this.readyState="opening";try{t=this.createTransport(t)}catch(t){return this.transports.shift(),void this.open()}t.open(),this.setTransport(t)},n.prototype.setTransport=function(t){var e=this;this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",(function(){e.onDrain()})).on("packet",(function(t){e.onPacket(t)})).on("error",(function(t){e.onError(t)})).on("close",(function(){e.onClose("transport close")}))},n.prototype.probe=function(t){function e(){if(u.onlyBinaryUpgrades){var t=!this.supportsBinary&&u.transport.supportsBinary;h=h||t}h||(p.send([{type:"ping",data:"probe"}]),p.once("packet",(function(t){if(!h)if("pong"===t.type&&"probe"===t.data){if(u.upgrading=!0,u.emit("upgrading",p),!p)return;n.priorWebsocketSuccess="websocket"===p.name,u.transport.pause((function(){h||"closed"!==u.readyState&&(c(),u.setTransport(p),p.send([{type:"upgrade"}]),u.emit("upgrade",p),p=null,u.upgrading=!1,u.flush())}))}else{var e=new Error("probe error");e.transport=p.name,u.emit("upgradeError",e)}})))}function r(){h||(h=!0,c(),p.close(),p=null)}function o(t){var e=new Error("probe error: "+t);e.transport=p.name,r(),u.emit("upgradeError",e)}function i(){o("transport closed")}function s(){o("socket closed")}function a(t){p&&t.name!==p.name&&r()}function c(){p.removeListener("open",e),p.removeListener("error",o),p.removeListener("close",i),u.removeListener("close",s),u.removeListener("upgrading",a)}var p=this.createTransport(t,{probe:1}),h=!1,u=this;n.priorWebsocketSuccess=!1,p.once("open",e),p.once("error",o),p.once("close",i),this.once("close",s),this.once("upgrading",a),p.open()},n.prototype.onOpen=function(){if(this.readyState="open",n.priorWebsocketSuccess="websocket"===this.transport.name,this.emit("open"),this.flush(),"open"===this.readyState&&this.upgrade&&this.transport.pause)for(var t=0,e=this.upgrades.length;t1?{type:b[o],data:t.substring(1)}:{type:b[o]}:k}var i=new Uint8Array(t),o=i[0],s=f(t,1);return w&&"blob"===r&&(s=new w([s])),{type:b[o],data:s}},e.decodeBase64Packet=function(t,e){var r=b[t.charAt(0)];if(!p)return{type:r,data:{base64:!0,data:t.substr(1)}};var n=p.decode(t.substr(1));return"blob"===e&&w&&(n=new w([n])),{type:r,data:n}},e.encodePayload=function(t,r,n){function o(t){return t.length+":"+t}function i(t,n){e.encodePacket(t,!!s&&r,!1,(function(t){n(null,o(t))}))}"function"==typeof r&&(n=r,r=null);var s=u(t);return r&&s?w&&!g?e.encodePayloadAsBlob(t,n):e.encodePayloadAsArrayBuffer(t,n):t.length?void c(t,i,(function(t,e){return n(e.join(""))})):n("0:")},e.decodePayload=function(t,r,n){if("string"!=typeof t)return e.decodePayloadAsBinary(t,r,n);"function"==typeof r&&(n=r,r=null);var o;if(""===t)return n(k,0,1);for(var i,s,a="",c=0,p=t.length;c0;){for(var s=new Uint8Array(o),a=0===s[0],c="",p=1;255!==s[p];p++){if(c.length>310)return n(k,0,1);c+=s[p]}o=f(o,2+c.length),c=parseInt(c);var h=f(o,0,c);if(a)try{h=String.fromCharCode.apply(null,new Uint8Array(h))}catch(t){var u=new Uint8Array(h);h="";for(var p=0;pn&&(r=n),e>=n||e>=r||0===n)return new ArrayBuffer(0);for(var o=new Uint8Array(t),i=new Uint8Array(r-e),s=e,a=0;s=55296&&e<=56319&&o65535&&(e-=65536,o+=d(e>>>10&1023|55296),e=56320|1023&e),o+=d(e);return o}function o(t,e){if(t>=55296&&t<=57343){if(e)throw Error("Lone surrogate U+"+t.toString(16).toUpperCase()+" is not a scalar value");return!1}return!0}function i(t,e){return d(t>>e&63|128)}function s(t,e){if(0==(4294967168&t))return d(t);var r="";return 0==(4294965248&t)?r=d(t>>6&31|192):0==(4294901760&t)?(o(t,e)||(t=65533),r=d(t>>12&15|224),r+=i(t,6)):0==(4292870144&t)&&(r=d(t>>18&7|240),r+=i(t,12),r+=i(t,6)),r+=d(63&t|128)}function a(t,e){e=e||{};for(var n,o=!1!==e.strict,i=r(t),a=i.length,c=-1,p="";++c=f)throw Error("Invalid byte index");var t=255&u[l];if(l++,128==(192&t))return 63&t;throw Error("Invalid continuation byte")}function p(t){var e,r,n,i,s;if(l>f)throw Error("Invalid byte index");if(l==f)return!1;if(e=255&u[l],l++,0==(128&e))return e;if(192==(224&e)){if(r=c(),s=(31&e)<<6|r,s>=128)return s;throw Error("Invalid continuation byte")}if(224==(240&e)){if(r=c(),n=c(),s=(15&e)<<12|r<<6|n,s>=2048)return o(s,t)?s:65533;throw Error("Invalid continuation byte")}if(240==(248&e)&&(r=c(),n=c(),i=c(),s=(7&e)<<18|r<<12|n<<6|i,s>=65536&&s<=1114111))return s;throw Error("Invalid UTF-8 detected")}function h(t,e){e=e||{};var o=!1!==e.strict;u=r(t),f=u.length,l=0;for(var i,s=[];(i=p(o))!==!1;)s.push(i);return n(s)}/*! https://mths.be/utf8js v2.1.2 by @mathias */var u,f,l,d=String.fromCharCode;t.exports={version:"2.1.2",encode:a,decode:h}},function(t,e){!function(t){"use strict";e.encode=function(e){var r,n=new Uint8Array(e),o=n.length,i="";for(r=0;r>2],i+=t[(3&n[r])<<4|n[r+1]>>4],i+=t[(15&n[r+1])<<2|n[r+2]>>6],i+=t[63&n[r+2]];return o%3===2?i=i.substring(0,i.length-1)+"=":o%3===1&&(i=i.substring(0,i.length-2)+"=="),i},e.decode=function(e){var r,n,o,i,s,a=.75*e.length,c=e.length,p=0;"="===e[e.length-1]&&(a--,"="===e[e.length-2]&&a--);var h=new ArrayBuffer(a),u=new Uint8Array(h);for(r=0;r>4,u[p++]=(15&o)<<4|i>>2,u[p++]=(3&i)<<6|63&s;return h}}("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")},function(t,e){function r(t){return t.map((function(t){if(t.buffer instanceof ArrayBuffer){var e=t.buffer;if(t.byteLength!==e.byteLength){var r=new Uint8Array(t.byteLength);r.set(new Uint8Array(e,t.byteOffset,t.byteLength)),e=r.buffer}return e}return t}))}function n(t,e){e=e||{};var n=new i;return r(t).forEach((function(t){n.append(t)})),e.type?n.getBlob(e.type):n.getBlob()}function o(t,e){return new Blob(r(t),e||{})}var i="undefined"!=typeof i?i:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:"undefined"!=typeof MSBlobBuilder?MSBlobBuilder:"undefined"!=typeof MozBlobBuilder&&MozBlobBuilder,s=function(){try{var t=new Blob(["hi"]);return 2===t.size}catch(t){return!1}}(),a=s&&function(){try{var t=new Blob([new Uint8Array([1,2])]);return 2===t.size}catch(t){return!1}}(),c=i&&i.prototype.append&&i.prototype.getBlob;"undefined"!=typeof Blob&&(n.prototype=Blob.prototype,o.prototype=Blob.prototype),t.exports=function(){return s?a?Blob:o:c?n:void 0}()},function(t,e){e.encode=function(t){var e="";for(var r in t)t.hasOwnProperty(r)&&(e.length&&(e+="&"),e+=encodeURIComponent(r)+"="+encodeURIComponent(t[r]));return e},e.decode=function(t){for(var e={},r=t.split("&"),n=0,o=r.length;n0);return e}function n(t){var e=0;for(h=0;h';i=document.createElement(t)}catch(t){i=document.createElement("iframe"),i.name=o.iframeId,i.src="javascript:0"}i.id=o.iframeId,o.form.appendChild(i),o.iframe=i}var o=this;if(!this.form){var i,s=document.createElement("form"),a=document.createElement("textarea"),c=this.iframeId="eio_iframe_"+this.index;s.className="socketio",s.style.position="absolute",s.style.top="-1000px",s.style.left="-1000px",s.target=c,s.method="POST",s.setAttribute("accept-charset","utf-8"),a.name="d",s.appendChild(a),document.body.appendChild(s),this.form=s,this.area=a}this.form.action=this.uri(),n(),t=t.replace(h,"\\\n"),this.area.value=t.replace(p,"\\n");try{this.form.submit()}catch(t){}this.iframe.attachEvent?this.iframe.onreadystatechange=function(){"complete"===o.iframe.readyState&&r()}:this.iframe.onload=r}},function(t,e,r){function n(t){var e=t&&t.forceBase64;e&&(this.supportsBinary=!1),this.perMessageDeflate=t.perMessageDeflate,this.usingBrowserWebSocket=o&&!t.forceNode,this.protocols=t.protocols,this.usingBrowserWebSocket||(u=i),s.call(this,t)}var o,i,s=r(18),a=r(19),c=r(27),p=r(28),h=r(29);r(3)("engine.io-client:websocket");if("undefined"!=typeof WebSocket?o=WebSocket:"undefined"!=typeof self&&(o=self.WebSocket||self.MozWebSocket),"undefined"==typeof window)try{i=r(32)}catch(t){}var u=o||i;t.exports=n,p(n,s),n.prototype.name="websocket",n.prototype.supportsBinary=!0,n.prototype.doOpen=function(){if(this.check()){var t=this.uri(),e=this.protocols,r={};this.isReactNative||(r.agent=this.agent,r.perMessageDeflate=this.perMessageDeflate,r.pfx=this.pfx,r.key=this.key,r.passphrase=this.passphrase,r.cert=this.cert,r.ca=this.ca,r.ciphers=this.ciphers,r.rejectUnauthorized=this.rejectUnauthorized),this.extraHeaders&&(r.headers=this.extraHeaders),this.localAddress&&(r.localAddress=this.localAddress);try{this.ws=this.usingBrowserWebSocket&&!this.isReactNative?e?new u(t,e):new u(t):new u(t,e,r)}catch(t){return this.emit("error",t)}void 0===this.ws.binaryType&&(this.supportsBinary=!1),this.ws.supports&&this.ws.supports.binary?(this.supportsBinary=!0,this.ws.binaryType="nodebuffer"):this.ws.binaryType="arraybuffer",this.addEventListeners()}},n.prototype.addEventListeners=function(){var t=this;this.ws.onopen=function(){t.onOpen()},this.ws.onclose=function(){t.onClose()},this.ws.onmessage=function(e){t.onData(e.data)},this.ws.onerror=function(e){t.onError("websocket error",e)}},n.prototype.write=function(t){function e(){r.emit("flush"),setTimeout((function(){r.writable=!0,r.emit("drain")}),0)}var r=this;this.writable=!1;for(var n=t.length,o=0,i=n;o0&&t.jitter<=1?t.jitter:0,this.attempts=0}t.exports=r,r.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),r=Math.floor(e*this.jitter*t);t=0==(1&Math.floor(10*e))?t-r:t+r}return 0|Math.min(t,this.max)},r.prototype.reset=function(){this.attempts=0},r.prototype.setMin=function(t){this.ms=t},r.prototype.setMax=function(t){this.max=t},r.prototype.setJitter=function(t){this.jitter=t}}])}))}).call(this)}).call(this,require("buffer").Buffer)},{buffer:3}],6:[function(require,module,exports){const{AceBaseBase:AceBaseBase,DebugLogger:DebugLogger,ColorStyle:ColorStyle,DataSnapshot:DataSnapshot}=require("acebase-core");const{WebApi:WebApi}=require("./api-web");const{AceBaseClientAuth:AceBaseClientAuth}=require("./auth");const{setServerBias:setServerBias}=require("./server-date");class AceBaseClientConnectionSettings{constructor(settings){this.dbname=settings.dbname;this.host=settings.host;this.port=settings.port;this.https=typeof settings.https==="boolean"?settings.https:true;this.autoConnect=typeof settings.autoConnect==="boolean"?settings.autoConnect:true;this.autoConnectDelay=typeof settings.autoConnectDelay==="number"?settings.autoConnectDelay:0;this.cache=typeof settings.cache==="object"&&typeof settings.cache.db==="object"?settings.cache:null;this.logLevel=typeof settings.logLevel==="string"?settings.logLevel:"log";this.sponsor=typeof settings.sponsor==="boolean"?settings.sponsor:false;this.sync=settings.sync;if(this.sync===null||typeof this.sync!=="object"){this.sync={}}if(!["connect","signin","auto","manual"].includes(this.sync.timing)){this.sync.timing="auto"}if(typeof this.sync.useCursor!=="boolean"){this.sync.useCursor=true}this.network=settings.network;if(this.network===null||typeof this.network!=="object"){this.network={}}if(!(this.network.transports instanceof Array)){this.network.transports=["websocket"]}if(typeof this.network.realtime!=="boolean"){this.network.realtime=true}if(typeof this.network.monitor!=="boolean"){this.network.monitor=!this.network.realtime}if(typeof this.network.interval!=="number"){this.network.interval=60}}}class AceBaseClient extends AceBaseBase{constructor(settings){if(typeof settings!=="object"){settings={};settings.host=arguments[0];settings.port=arguments[1];settings.dbname=arguments[2];settings.https=arguments[3]}if(!(settings instanceof AceBaseClientConnectionSettings)){settings=new AceBaseClientConnectionSettings(settings)}super(settings.dbname,{info:"realtime database client",sponsor:settings.sponsor});const cacheDb=settings.cache&&settings.cache.db;const cacheReadyPromise=cacheDb?cacheDb.ready():Promise.resolve();let ready=false;this.on("ready",(()=>{ready=true}));this.debug=new DebugLogger(settings.logLevel,`[${settings.dbname}]`.colorize(ColorStyle.blue));const synchronizeClocks=async()=>{const info=await this.api.getServerInfo();const now=Date.now(),bias=info.time-now;setServerBias(bias)};this.on("connect",(()=>{if(cacheDb){cacheDb.settings.ipcEvents=false}synchronizeClocks()}));this.on("disconnect",(()=>{if(cacheDb){cacheDb.settings.ipcEvents=true}}));this.sync=()=>syncPendingChanges(true);let syncRunning=false,firstSync=true;const syncPendingChanges=async(throwErrors=false)=>{if(syncRunning){if(throwErrors){throw new Error("sync already running")}return}if(!this.api.isConnected){if(throwErrors){throw new Error("not connected")}return}syncRunning=true;try{await cacheReadyPromise;return await this.api.sync({firstSync:firstSync,fetchFreshData:!firstSync,eventCallback:(eventName,args)=>{this.debug.log(eventName,args||"");this.emit(eventName,args)}})}catch(err){if(throwErrors){throw err}else{console.error(`Failed to synchronize:`,err)}}finally{syncRunning=false;firstSync=false}};let syncTimeout=0;this.on("connect",(()=>{if(settings.sync.timing==="connect"||settings.sync.timing==="signin"&&this.auth.accessToken){syncPendingChanges()}else if(settings.sync.timing==="auto"){syncTimeout&&clearTimeout(syncTimeout);syncTimeout=setTimeout(syncPendingChanges,2500)}}));this.on("signin",(()=>{if(settings.sync.timing==="auto"){syncTimeout&&clearTimeout(syncTimeout)}if(["auto","signin"].includes(settings.sync.timing)){syncPendingChanges()}}));const emitClientReady=async()=>{if(cacheDb){await cacheDb.ready()}this.emit("ready")};this.api=new WebApi(settings.dbname,{network:settings.network,sync:settings.sync,logLevel:settings.logLevel,debug:this.debug,url:`http${settings.https?"s":""}://${settings.host}:${settings.port}`,autoConnect:settings.autoConnect,autoConnectDelay:settings.autoConnectDelay,cache:settings.cache},((evt,data)=>{if(evt==="connect"){this.emit("connect");if(!ready){emitClientReady()}}else if(evt==="connect_error"){this.emit("connect_error",data);if(!ready&&cacheDb){emitClientReady()}}else if(evt==="disconnect"){this.emit("disconnect")}}));this.auth=new AceBaseClientAuth(this,((event,arg)=>{this.emit(event,arg)}))}get connected(){return this.api.isConnected}get connectionState(){return this.api.connectionState}connect(){return this.api.connect()}disconnect(){this.api.disconnect()}close(){this.disconnect()}callExtension(method,path,data){return this.api.callExtension(method,path,data)}getCursor(){return this.api._syncCursor}setCursor(cursor){this.api._syncCursor=cursor}get cache(){const clear=async(path="")=>{await this.api.clearCache(path)};const update=(path,cursor)=>this.api.updateCache(path,cursor);const get=async(path,cursor)=>this.ref(path).get({cache_mode:cursor?"allow":"force",cache_cursor:cursor});return{clear:clear,update:update,get:get}}}module.exports={AceBaseClient:AceBaseClient,AceBaseClientConnectionSettings:AceBaseClientConnectionSettings}},{"./api-web":7,"./auth":8,"./server-date":17,"acebase-core":30}],7:[function(require,module,exports){const{Api:Api,Transport:Transport,ID:ID,PathInfo:PathInfo,ColorStyle:ColorStyle,SchemaDefinition:SchemaDefinition,SimpleEventEmitter:SimpleEventEmitter}=require("acebase-core");const connectSocket=require("socket.io-client");const Base64=require("./base64");const{AceBaseRequestError:AceBaseRequestError,NOT_CONNECTED_ERROR_MESSAGE:NOT_CONNECTED_ERROR_MESSAGE}=require("./request/error");const{CachedValueUnavailableError:CachedValueUnavailableError}=require("./errors");const{promiseTimeout:promiseTimeout}=require("./promise-timeout");const _request=require("./request");const _websocketRequest=(socket,event,data,accessToken)=>{const requestId=ID.generate();const request=data;request.req_id=requestId;request.access_token=accessToken;return new Promise(((resolve,reject)=>{if(!socket){return reject(new AceBaseRequestError(request,null,"websocket","No open websocket connection"))}let timeout;const send=(retry=0)=>{socket.emit(event,request);timeout=setTimeout((()=>{if(retry<2){return send(retry+1)}socket.off("result",handle);const err=new AceBaseRequestError(request,null,"timeout",`Server did not respond to "${event}" request after ${retry+1} tries`);reject(err)}),1e3)};const handle=response=>{if(response.req_id===requestId){clearTimeout(timeout);socket.off("result",handle);if(response.success){return resolve(response)}const code=typeof response.reason==="object"?response.reason.code:response.reason;const message=typeof response.reason==="object"?response.reason.message:`request failed: ${code}`;const err=new AceBaseRequestError(request,response,code,message);reject(err)}};socket.on("result",handle);send()}))};class EventSubscription{constructor(path,event,callback,settings){this.path=path;this.event=event;this.callback=callback;this.settings=settings;this.state="requested";this.added=Date.now();this.activated=0;this.lastEvent=0;this.lastSynced=0;this.cursor=null;this.cacheCallback=null;this.tempCallback=null}activate(){this.state="active";if(this.activated===0){this.activated=Date.now()}}cancel(reason){this.state="canceled";this.settings.cancelCallback(reason)}}const CONNECTION_STATE_DISCONNECTED="disconnected";const CONNECTION_STATE_CONNECTING="connecting";const CONNECTION_STATE_CONNECTED="connected";const CONNECTION_STATE_DISCONNECTING="disconnecting";class WebApi extends Api{constructor(dbname="default",settings,callback){super();this._id=ID.generate();this.url=settings.url;this.socket=null;this._autoConnect=typeof settings.autoConnect==="boolean"?settings.autoConnect:true;this._autoConnectDelay=typeof settings.autoConnectDelay==="number"?settings.autoConnectDelay:0;this.dbname=dbname;this._connectionState=CONNECTION_STATE_DISCONNECTED;this._serverVersion="unknown";this._cursor={current:null,sync:null};this._updateCursor=async cursor=>{if(!cursor||this._cursor.current&&cursor{if(settings.network.realtime&&!this.isConnected){return}if(!settings.network.realtime&&![CONNECTION_STATE_CONNECTING,CONNECTION_STATE_CONNECTED].includes(this._connectionState)){return}const wasConnected=this.isConnected;try{await this._request({url:this.serverPingUrl,ignoreConnectionState:true});if(!wasConnected){manualConnectionMonitor.emit("connect")}}catch(err){}};this._handleDetectedDisconnect=()=>{if(settings.network.realtime){this._connectionState===CONNECTION_STATE_DISCONNECTED;this.connect().catch((()=>{}))}else{if(this._connectionState===CONNECTION_STATE_CONNECTING){manualConnectionMonitor.emit("connect_error",err)}else if(this._connectionState===CONNECTION_STATE_CONNECTED){manualConnectionMonitor.emit("disconnect")}}};if(settings.network.monitor){const interval=setInterval(checkConnection,settings.network.interval*1e3);interval.unref&&interval.unref()}this.settings=settings;this._realtimeQueries={};this.debug=settings.debug;const eventCallback=(event,...args)=>{if(event==="disconnect"){this._cursor.sync=this._cursor.current}callback&&callback(event,...args)};let subscriptions=this._subscriptions={};let accessToken;this.connect=()=>{if(this.socket!==null&&typeof this.socket==="object"){this.disconnect()}this._connectionState=CONNECTION_STATE_CONNECTING;this.debug.log(`Connecting to AceBase server "${this.url}"`);if(!this.url.startsWith("https")){this.debug.warn(`WARNING: The server you are connecting to does not use https, any data transferred may be intercepted!`.colorize(ColorStyle.red))}const transports=settings.network&&settings.network.transports instanceof Array?settings.network.transports:["websocket"];this.debug.log(`Using ${transports.join(",")} transport${transports.length>1?"s":""} for socket.io`);return new Promise(((resolve,reject)=>{if(!settings.network.realtime){manualConnectionMonitor.off("connect");manualConnectionMonitor.off("connect_error");manualConnectionMonitor.off("disconnect");manualConnectionMonitor.on("connect",(()=>{this._connectionState=CONNECTION_STATE_CONNECTED;this._eventTimeline.connect=Date.now();manualConnectionMonitor.off("connect_error");eventCallback("connect");resolve()}));manualConnectionMonitor.on("connect_error",(err=>{this.debug.error(`API connection error: ${err.message||err}`);eventCallback("connect_error",err);reject(err)}));manualConnectionMonitor.on("disconnect",(()=>{if(this._connectionState===CONNECTION_STATE_DISCONNECTING){this._connectionState=CONNECTION_STATE_DISCONNECTED;manualConnectionMonitor.off("connect");manualConnectionMonitor.off("disconnect");manualConnectionMonitor.off("connect_error")}else{this._connectionState=CONNECTION_STATE_CONNECTING;this._eventTimeline.disconnect=Date.now()}eventCallback("disconnect")}));this._connectionState=CONNECTION_STATE_CONNECTING;return setTimeout((()=>checkConnection()),0)}const socket=this.socket=connectSocket(this.url,{autoConnect:true,reconnection:true,reconnectionAttempts:Infinity,reconnectionDelay:1e3,reconnectionDelayMax:5e3,timeout:2e4,randomizationFactor:.5,transports:transports});socket.on("connect_error",(err=>{this.debug.error(`Websocket connection error: ${err}`);eventCallback("connect_error",err);reject(err)}));socket.on("connect",(async data=>{this._connectionState=CONNECTION_STATE_CONNECTED;this._eventTimeline.connect=Date.now();if(accessToken){const isFirstSignIn=this._eventTimeline.signIn===0;try{await this.signInWithToken(accessToken,isFirstSignIn)}catch(err){this.debug.error(`Could not automatically sign in user with access token upon reconnect: ${err.code||err.message}`)}}const subscribeTo=async sub=>{const subs=subscriptions[sub.path].filter((s=>s.event===sub.event));try{const result=await _websocketRequest(this.socket,"subscribe",{path:sub.path,event:sub.event},accessToken);subs.forEach((s=>s.activate()))}catch(err){if(err.code==="access_denied"&&!accessToken){this.debug.error(`Could not subscribe to event "${sub.event}" on path "${sub.path}" because you are not signed in. If you added this event while offline and have a user access token, you can prevent this by using client.auth.setAccessToken(token) to automatically try signing in after connecting`)}else{this.debug.error(err)}subs.forEach((s=>s.cancel(err)))}};const subscribePromises=[];Object.keys(subscriptions).forEach((path=>{const events=[];subscriptions[path].forEach((sub=>{if(sub.event==="mutated"){return}const serverAlreadyNotifying=events.includes(sub.event);if(!serverAlreadyNotifying){events.push(sub.event);const promise=subscribeTo(sub);subscribePromises.push(promise)}}))}));const subscribeToMutatedEvents=async()=>{let retry=false;const promises=Object.keys(subscriptions).filter((path=>subscriptions[path].some((sub=>sub.event==="mutated"&&sub.state!=="canceled")))).filter(((path,i,arr)=>!arr.some((otherPath=>PathInfo.get(otherPath).isAncestorOf(path))))).reduce(((topPaths,path)=>(topPaths.includes(path)||topPaths.push(path))&&topPaths),[]).map((topEventPath=>{const sub=subscriptions[topEventPath].find((s=>s.event==="mutated"));const promise=subscribeTo(sub).then((()=>{if(sub.state==="canceled"){retry=true}}));return promise}));await Promise.all(promises);if(retry){return subscribeToMutatedEvents()}};subscribePromises.push(subscribeToMutatedEvents());await Promise.all(subscribePromises);eventCallback("connect");resolve()}));socket.on("disconnect",(reason=>{this.debug.warn(`Websocket disconnected: ${reason}`);if(this._connectionState===CONNECTION_STATE_DISCONNECTING){this._connectionState=CONNECTION_STATE_DISCONNECTED}else{this._connectionState=CONNECTION_STATE_CONNECTING;this._eventTimeline.disconnect=Date.now();if(reason==="io server disconnect"){this.socket=null;this.connect().catch((err=>{}))}}eventCallback("disconnect")}));socket.on("data-event",(data=>{const val=Transport.deserialize(data.val);const context=data.context||{};context.acebase_event_source="server";this._updateCursor(context.acebase_cursor);const causedByUs=context.acebase_mutation&&context.acebase_mutation.client_id===this._id;const cacheEnabled=!!(this._cache&&this._cache.db);const fireThisEvent=!causedByUs||!cacheEnabled;const updateCache=!causedByUs&&cacheEnabled;const fireCacheEvents=false;const pathSubs=subscriptions[data.subscr_path];if(!pathSubs&&data.event!=="mutated"){return}if(updateCache){if(data.path.startsWith("__")){}else if(data.event==="mutations"){const mutations=val.current;mutations.forEach((m=>{const path=m.target.reduce(((path,key)=>PathInfo.getChildPath(path,key)),PathInfo.getChildPath(`${this.dbname}/cache`,data.path));this._cache.db.api.set(path,m.val,{suppress_events:!fireCacheEvents,context:context})}))}else if(data.event==="notify_child_removed"){this._cache.db.api.set(PathInfo.getChildPath(`${this.dbname}/cache`,data.path),null,{suppress_events:!fireCacheEvents,context:context})}else if(!data.event.startsWith("notify_")){this._cache.db.api.set(PathInfo.getChildPath(`${this.dbname}/cache`,data.path),val.current,{suppress_events:!fireCacheEvents,context:context})}}if(!fireThisEvent){return}const targetSubs=data.event==="mutated"?Object.keys(subscriptions).filter((path=>{const pathInfo=PathInfo.get(path);return path===data.path||pathInfo.equals(data.subscr_path)||pathInfo.isAncestorOf(data.path)})).reduce(((subs,path)=>{const add=subscriptions[path].filter((sub=>sub.event==="mutated"));subs.push(...add);return subs}),[]):pathSubs.filter((sub=>sub.event===data.event));targetSubs.forEach((subscr=>{subscr.lastEvent=Date.now();subscr.cursor=context.acebase_cursor;subscr.callback(null,data.path,val.current,val.previous,context)}))}));socket.on("query-event",(data=>{data=Transport.deserialize(data);const query=this._realtimeQueries[data.query_id];let keepMonitoring=true;try{keepMonitoring=query.options.eventHandler(data)}catch(err){keepMonitoring=false}if(keepMonitoring===false){delete this._realtimeQueries[data.query_id];socket.emit("query-unsubscribe",{query_id:data.query_id})}}))}))};if(this._autoConnect){if(this._autoConnectDelay){setTimeout((()=>this.connect().catch((()=>{}))),this._autoConnectDelay)}else{this.connect().catch((()=>{}))}}this.disconnect=()=>{if(!settings.network.realtime){this._connectionState=CONNECTION_STATE_DISCONNECTING;this._eventTimeline.disconnect=Date.now();manualConnectionMonitor.emit("disconnect")}else if(this.socket!==null&&typeof this.socket==="object"){this._connectionState=CONNECTION_STATE_DISCONNECTING;this._eventTimeline.disconnect=Date.now();this.socket.disconnect();this.socket=null}};this.subscribe=async(path,event,callback,settings)=>{if(!this.settings.network.realtime){throw new Error(`Cannot subscribe to realtime events because it has been disabled in the network settings`)}let pathSubs=subscriptions[path];if(!pathSubs){pathSubs=subscriptions[path]=[]}let serverAlreadyNotifying=pathSubs.some((sub=>sub.event===event))||event==="mutated"&&Object.keys(subscriptions).some((otherPath=>PathInfo.get(otherPath).isAncestorOf(path)&&subscriptions[otherPath].some((sub=>sub.event===event&&sub.state==="active"))));const subscr=new EventSubscription(path,event,callback,settings);pathSubs.push(subscr);if(this._cache){subscr.cacheCallback=(err,path,newValue,oldValue,context)=>subscr.callback(err,path.slice(`${this.dbname}/cache/`.length),newValue,oldValue,context);this._cache.db.api.subscribe(PathInfo.getChildPath(`${this.dbname}/cache`,path),event,subscr.cacheCallback)}if(serverAlreadyNotifying||!this.isConnected){return}if(event==="mutated"){Object.keys(subscriptions).filter((otherPath=>PathInfo.get(otherPath).isDescendantOf(path)&&subscriptions[otherPath].some((sub=>sub.event==="mutated")))).map((path=>_websocketRequest(this.socket,"unsubscribe",{path:path,event:"mutated"},accessToken))).map((promise=>promise.catch((err=>console.error(err)))))}const result=await _websocketRequest(this.socket,"subscribe",{path:path,event:event},accessToken);subscr.activate();return result};this.unsubscribe=(path,event=undefined,callback=undefined)=>{if(!this.settings.network.realtime){throw new Error(`Cannot unsubscribe from realtime events because it has been disabled in the network settings`)}let pathSubs=subscriptions[path];if(!pathSubs){return Promise.resolve()}const unsubscribeFrom=subscriptions=>{subscriptions.forEach((subscr=>{pathSubs.splice(pathSubs.indexOf(subscr),1);if(this._cache){console.assert(typeof subscr.cacheCallback!=="undefined","When subscription was added, cacheCallback must have been set");this._cache.db.api.unsubscribe(PathInfo.getChildPath(`${this.dbname}/cache`,path),subscr.event,subscr.cacheCallback)}}))};const hadMutatedEvents=pathSubs.some((sub=>sub.event==="mutated"));if(!event){unsubscribeFrom(pathSubs)}else if(!callback){const subscriptions=pathSubs.filter((subscr=>subscr.event===event));unsubscribeFrom(subscriptions)}else{const subscriptions=pathSubs.filter((subscr=>subscr.event===event&&subscr.callback===callback));unsubscribeFrom(subscriptions)}const hasMutatedEvents=pathSubs.some((sub=>sub.event==="mutated"));let promise=Promise.resolve();if(pathSubs.length===0){delete subscriptions[path];if(this.isConnected){promise=_websocketRequest(this.socket,"unsubscribe",{path:path,access_token:accessToken},accessToken).catch((err=>this.debug.error(`Failed to unsubscribe from event(s) on "${path}": ${err.message}`)))}}else if(this.isConnected&&!pathSubs.some((subscr=>subscr.event===event))){promise=_websocketRequest(this.socket,"unsubscribe",{path:path,event:event,access_token:accessToken},accessToken).catch((err=>this.debug.error(`Failed to unsubscribe from event "${event}" on "${path}": ${err.message}`)))}if(this.isConnected&&hadMutatedEvents&&!hasMutatedEvents){const promises=Object.keys(subscriptions).filter((otherPath=>PathInfo.get(otherPath).isDescendantOf(path)&&subscriptions[otherPath].some((sub=>sub.event==="mutated")))).map((path=>_websocketRequest(this.socket,"subscribe",{path:path,event:"mutated"},accessToken))).map((promise=>promise.catch((err=>this.debug.error(`Failed to subscribe to event "${event}" on path "${path}": ${err.message}`)))));promise=Promise.all([promise,...promises])}return promise};this.transaction=(path,callback,options={context:{}})=>{const id=ID.generate();options.context=options.context||{};options.context.acebase_mutation={client_id:this._id,id:id,op:"transaction",path:path,flow:"server"};const cachePath=PathInfo.getChildPath(`${this.dbname}/cache`,path);return new Promise((async(resolve,reject)=>{let cacheUpdateVal;const handleSuccess=async context=>{if(this._cache&&typeof cacheUpdateVal!=="undefined"){await this._cache.db.api.set(cachePath,cacheUpdateVal)}resolve({cursor:context&&context.acebase_cursor})};if(this.isConnected&&settings.network.realtime){const startedCallback=async data=>{if(data.id===id){this.socket.off("tx_started",startedCallback);const currentValue=Transport.deserialize(data.value);let newValue=callback(currentValue);if(newValue instanceof Promise){newValue=await newValue}this.socket.emit("transaction",{action:"finish",id:id,path:path,value:Transport.serialize(newValue),access_token:accessToken});if(this._cache){cacheUpdateVal=newValue}}};const completedCallback=data=>{if(data.id===id){this.socket.off("tx_completed",completedCallback);this.socket.off("tx_error",errorCallback);handleSuccess(data.context)}};const errorCallback=data=>{if(data.id===id){this.socket.off("tx_started",startedCallback);this.socket.off("tx_completed",completedCallback);this.socket.off("tx_error",errorCallback);reject(new Error(data.reason))}};this.socket.on("tx_started",startedCallback);this.socket.on("tx_completed",completedCallback);this.socket.on("tx_error",errorCallback);this.socket.emit("transaction",{action:"start",id:id,path:path,access_token:accessToken,context:options.context})}else{const startData=JSON.stringify({path:path});try{const tx=await this._request({ignoreConnectionState:true,method:"POST",url:`${this.url}/transaction/${this.dbname}/start`,data:startData,context:options.context});const id=tx.id;const currentValue=Transport.deserialize(tx.value);let newValue=callback(currentValue);if(newValue instanceof Promise){newValue=await newValue}if(this._cache){cacheUpdateVal=newValue}const finishData=JSON.stringify({id:id,value:Transport.serialize(newValue)});const{context:context}=await this._request({ignoreConnectionState:true,method:"POST",url:`${this.url}/transaction/${this.dbname}/finish`,data:finishData,context:options.context,includeContext:true});await handleSuccess(context)}catch(err){if(["ETIMEDOUT","ENOTFOUND","ECONNRESET","ECONNREFUSED","EPIPE","fetch_failed"].includes(err.code)){err.message=NOT_CONNECTED_ERROR_MESSAGE}reject(err)}}}))};this._request=async options=>{if(this.isConnected||options.ignoreConnectionState===true){const result=await(async()=>{try{return await _request(options.method||"GET",options.url,{data:options.data,accessToken:accessToken,dataReceivedCallback:options.dataReceivedCallback,dataRequestCallback:options.dataRequestCallback,context:options.context})}catch(err){if(this.isConnected&&err.isNetworkError){this.debug.warn(`A network error occurred loading ${options.url}`);this._handleDetectedDisconnect()}throw err}})();if(result.context&&result.context.acebase_cursor){this._updateCursor(result.context.acebase_cursor)}if(options.includeContext===true){if(!result.context){result.context={}}return result}else{return result.data}}else{if(!this.isConnecting||!settings.network.realtime){throw new Error(NOT_CONNECTED_ERROR_MESSAGE)}const connectPromise=new Promise((resolve=>this.socket.once("connect",resolve)));await promiseTimeout(connectPromise,1e3,"Waiting for connection").catch((err=>{throw new Error(NOT_CONNECTED_ERROR_MESSAGE)}));return this._request(options)}};const handleSignInResult=(result,emitEvent=true)=>{this._eventTimeline.signIn=Date.now();const details={user:result.user,accessToken:result.access_token,provider:result.provider||"acebase"};accessToken=details.accessToken;this.socket&this.socket.emit("signin",details.accessToken);emitEvent&&eventCallback("signin",details);return details};this.signIn=async(username,password)=>{if(!this.isConnected){throw new Error(NOT_CONNECTED_ERROR_MESSAGE)}const result=await this._request({method:"POST",url:`${this.url}/auth/${this.dbname}/signin`,data:{method:"account",username:username,password:password,client_id:this.socket&&this.socket.id}});return handleSignInResult(result)};this.signInWithEmail=async(email,password)=>{if(!this.isConnected){throw new Error(NOT_CONNECTED_ERROR_MESSAGE)}const result=await this._request({method:"POST",url:`${this.url}/auth/${this.dbname}/signin`,data:{method:"email",email:email,password:password,client_id:this.socket&&this.socket.id}});return handleSignInResult(result)};this.signInWithToken=async(token,emitEvent=true)=>{if(!this.isConnected){throw new Error("Cannot sign in because client is not connected to the server. If you want to automatically sign in the user with this access token once a connection is established, use client.auth.setAccessToken(token)")}const result=await this._request({method:"POST",url:`${this.url}/auth/${this.dbname}/signin`,data:{method:"token",access_token:token,client_id:this.socket&&this.socket.id}});return handleSignInResult(result,emitEvent)};this.setAccessToken=token=>{accessToken=token};this.startAuthProviderSignIn=async(providerName,callbackUrl,options)=>{if(!this.isConnected){throw new Error(NOT_CONNECTED_ERROR_MESSAGE)}const optionParams=typeof options==="object"?"&"+Object.keys(options).map((key=>`option_${key}=${encodeURIComponent(options[key])}`)).join("&"):"";const result=await this._request({url:`${this.url}/oauth2/${this.dbname}/init?provider=${providerName}&callbackUrl=${callbackUrl}${optionParams}`});return{redirectUrl:result.redirectUrl}};this.finishAuthProviderSignIn=async callbackResult=>{let result;try{result=JSON.parse(Base64.decode(callbackResult))}catch(err){throw new Error(`Invalid result`)}if(!result.user){accessToken=result.access_token;const authState=await this._request({url:`${this.url}/auth/${this.dbname}/state`});if(!authState.signed_in){accessToken=null;throw new Error(`Invalid access token received: not signed in`)}result.user=authState.user}return handleSignInResult(result)};this.refreshAuthProviderToken=async(providerName,refreshToken)=>{if(!this.isConnected){throw new Error(NOT_CONNECTED_ERROR_MESSAGE)}return this._request({url:`${this.url}/oauth2/${this.dbname}/refresh?provider=${providerName}&refresh_token=${refreshToken}`})};this.signOut=async(options={everywhere:false,clearCache:false})=>{if(typeof options==="boolean"){options={everywhere:options}}else if(typeof options!=="object"){throw new TypeError("options must be an object")}if(typeof options.everywhere!=="boolean"){options.everywhere=false}if(typeof options.clearCache!=="boolean"){options.clearCache=false}if(!accessToken){return}if(!this.isConnected){throw new Error(NOT_CONNECTED_ERROR_MESSAGE)}const result=await this._request({method:"POST",url:`${this.url}/auth/${this.dbname}/signout`,data:{client_id:this.socket&&this.socket.id,everywhere:options.everywhere}});this.socket&&this.socket.emit("signout",accessToken);accessToken=null;if(this._cache&&options.clearCache){this.clearCache().catch((err=>{console.error(`Could not clear cache:`,err)}))}eventCallback("signout")};this.changePassword=async(uid,currentPassword,newPassword)=>{if(!accessToken){throw new Error(`not_signed_in`)}if(!this.isConnected){throw new Error(NOT_CONNECTED_ERROR_MESSAGE)}const result=await this._request({method:"POST",url:`${this.url}/auth/${this.dbname}/change_password`,data:{uid:uid,password:currentPassword,new_password:newPassword}});accessToken=result.access_token;return{accessToken:accessToken}};this.forgotPassword=async email=>{if(!this.isConnected){throw new Error(NOT_CONNECTED_ERROR_MESSAGE)}const result=await this._request({method:"POST",url:`${this.url}/auth/${this.dbname}/forgot_password`,data:{email:email}});return result};this.verifyEmailAddress=async verificationCode=>{if(!this.isConnected){throw new Error(NOT_CONNECTED_ERROR_MESSAGE)}const result=await this._request({method:"POST",url:`${this.url}/auth/${this.dbname}/verify_email`,data:{code:verificationCode}});return result};this.resetPassword=async(resetCode,newPassword)=>{if(!this.isConnected){throw new Error(NOT_CONNECTED_ERROR_MESSAGE)}const result=await this._request({method:"POST",url:`${this.url}/auth/${this.dbname}/reset_password`,data:{code:resetCode,password:newPassword}});return result};this.signUp=async(details,signIn=true)=>{if(!this.isConnected){throw new Error(NOT_CONNECTED_ERROR_MESSAGE)}const result=await this._request({method:"POST",url:`${this.url}/auth/${this.dbname}/signup`,data:details});if(signIn){return handleSignInResult(result)}return{user:result.user,accessToken:accessToken}};this.updateUserDetails=async details=>{if(!this.isConnected){throw new Error(NOT_CONNECTED_ERROR_MESSAGE)}const result=await this._request({method:"POST",url:`${this.url}/auth/${this.dbname}/update`,data:details});return{user:result.user}};this.deleteAccount=async(uid,signOut=true)=>{if(!this.isConnected){throw new Error(NOT_CONNECTED_ERROR_MESSAGE)}const result=await this._request({method:"POST",url:`${this.url}/auth/${this.dbname}/delete`,data:{uid:uid}});if(signOut){this.socket&&this.socket.emit("signout",accessToken);accessToken=null;eventCallback("signout")}return true}}get isConnected(){return this._connectionState===CONNECTION_STATE_CONNECTED}get isConnecting(){return this._connectionState===CONNECTION_STATE_CONNECTING}get connectionState(){return this._connectionState}stats(options=undefined){return this._request({url:`${this.url}/stats/${this.dbname}`})}async sync(options={firstSync:false,fetchFreshData:true,eventCallback:null}){if(!this.isConnected){throw new Error(NOT_CONNECTED_ERROR_MESSAGE)}if(this._cache&&!this._cache.db.isReady){throw new Error(`cache database is not ready yet`)}this._eventTimeline.sync=Date.now();options.eventCallback&&options.eventCallback("sync_start");const handleStatsUpdateError=err=>{this.debug.error(`Failed to update cache db stats:`,err)};try{let totalPendingChanges=0;const useCursor=this.settings.sync.useCursor!==false;const cursor=useCursor?this._cursor.sync:null;const cacheApi=this._cache&&this._cache.db.api;if(this._cache){const{value:pendingChanges,context:context}=await cacheApi.get(`${this.dbname}/pending`);cacheApi.set(`${this.dbname}/stats/last_sync_start`,new Date).catch(handleStatsUpdateError);try{const ids=Object.keys(pendingChanges||{}).sort();const compatibilityMode=ids.map((id=>pendingChanges[id])).some((m=>m.type==="update"));const mutations=compatibilityMode?ids.map((id=>{const mutation=pendingChanges[id];mutation.id=id;return mutation})):ids.reduce(((mutations,id)=>{const change=pendingChanges[id];console.assert(["set","remove"].includes(change.type),'Only "set" and "remove" mutations should be present');if(change.path===""){const rootUpdate=mutations.find((u=>u.path===""));if(rootUpdate){rootUpdate.data=change.data}else{change.id=id;mutations.push(change)}}else{const pathInfo=PathInfo.get(change.path);const parentPath=pathInfo.parentPath;const parentUpdate=mutations.find((u=>u.path===parentPath));const value=change.type==="remove"||change.data===null||typeof change.data==="undefined"?null:change.data;if(!parentUpdate){mutations.push({ids:[id],type:"update",path:parentPath,data:{[pathInfo.key]:value},context:change.context})}else{parentUpdate.data[pathInfo.key]=value;parentUpdate.ids.push(id)}}return mutations}),[]);for(let m of mutations){const ids=m.ids;this.debug.verbose(`SYNC pushing mutations ${ids.join(",")}: `,m);totalPendingChanges++;try{if(m.type==="update"){await this.update(m.path,m.data,{allow_cache:false,context:m.context})}else if(m.type==="set"){if(!m.data){m.data=null}await this.set(m.path,m.data,{allow_cache:false,context:m.context})}else if(m.type==="remove"){await this.set(m.path,null,{allow_cache:false,context:m.context})}else{throw new Error(`unsupported mutation type "${m.type}"`)}this.debug.verbose(`SYNC mutation ${ids.join(",")} processed ok`);const updates=ids.reduce(((updates,id)=>(updates[id]=null,updates)),{});cacheApi.update(`${this.dbname}/pending`,updates)}catch(err){this.debug.error(`SYNC mutations ${ids.join(",")} failed: ${err.message}`);if(!this.isConnected){throw err}if(typeof err==="string"){err={code:"unknown",message:err,stack:"n/a"}}const errorReport={date:new Date,code:err.code||"unknown",message:err.message,stack:err.stack};ids.forEach((id=>{cacheApi.transaction(`${this.dbname}/pending/${id}`,(m=>{if(!m.error){m.error={first:errorReport,last:errorReport,retries:0}}else{m.error.last=errorReport;m.error.retries++}if(m.error.retries===3){cacheApi.set(`${this.dbname}/failed/${id}`,m);return null}return m}))}));cacheApi.set(`${this.dbname}/stats/last_sync_error`,errorReport).catch(handleStatsUpdateError);options.eventCallback&&options.eventCallback("sync_change_error",{error:err,change:m})}}this.debug.verbose(`SYNC push done`);cacheApi.set(`${this.dbname}/stats/last_sync_end`,new Date).catch(handleStatsUpdateError)}catch(err){this.debug.error(`SYNC push error: ${err.message}`);if(typeof err==="string"){err={code:"unknown",message:err,stack:"n/a"}}cacheApi.set(`${this.dbname}/stats/last_sync_error`,{date:new Date,code:err.code||"unknown",message:err.message,stack:err.stack}).catch(handleStatsUpdateError);throw err}}let totalRemoteChanges=0,usedSyncMethod="reload";const subscriptionPaths=Object.keys(this._subscriptions);const subscriptions=subscriptionPaths.reduce(((subs,path)=>{this._subscriptions[path].forEach((sub=>subs.push(sub)));return subs}),[]);subscriptions.for=function(path){return this.filter((sub=>sub.path===path))};if(this._cache){subscriptions.forEach((sub=>{sub.tempCallback=(err,path,newValue,oldValue,context)=>{totalRemoteChanges++};cacheApi.subscribe(PathInfo.getChildPath(`${this.dbname}/cache`,sub.path),sub.event,sub.tempCallback)}));let strategy={reload:[],cursor:[],fallback:[],warn:[],noop:[]};const hasStaleValue=sub=>{const addedWhileOffline=sub.added>this._eventTimeline.disconnect&&sub.added{if(path.includes("*")||path.includes("$")){return false}return subscriptions.for(path).some((sub=>{if(hasStaleValue(sub)){if(typeof sub.settings.syncFallback==="function"){return false}if(sub.settings.syncFallback==="reload"){return true}if(sub.event==="value"){return true}if(sub.event==="child_added"&&!sub.settings.newOnly){return true}}return false}))})).reduce(((reloadPaths,path)=>{!reloadPaths.some((p=>p===path||PathInfo.get(p).isAncestorOf(path)))&&reloadPaths.push(path);return reloadPaths}),[]);strategy.fallback=subscriptionPaths.filter((path=>!strategy.reload.some((p=>p===path||PathInfo.get(p).isAncestorOf(path))))).reduce(((fallbackItems,path)=>{subscriptions.for(path).forEach((sub=>{if(hasStaleValue(sub)&&typeof sub.settings.syncFallback==="function"){fallbackItems.push(sub)}}));return fallbackItems}),[]);strategy.cursor=!cursor?[]:subscriptionPaths.filter((path=>!strategy.reload.some((p=>p===path||PathInfo.get(p).isAncestorOf(path))))).reduce(((cursorItems,path)=>{const subs=subscriptions.for(path);const events=subs.filter((sub=>!hasStaleValue(sub)&&!strategy.fallback.includes(sub))).reduce(((events,sub)=>(events.includes(sub.event)||events.push(sub.event))&&events),[]);events.length>0&&cursorItems.push({path:path,events:events});return cursorItems}),[]);strategy.warn=subscriptionPaths.filter((path=>!strategy.reload.some((p=>p===path||PathInfo.get(p).isAncestorOf(path))))).reduce(((warnItems,path)=>{const subs=subscriptions.for(path).filter((sub=>!strategy.fallback.includes(sub)));subs.forEach((sub=>{if(typeof sub.settings.syncFallback==="function"||sub.added>this._eventTimeline.connect){strategy.noop.push(sub)}else if(!strategy.cursor.some((item=>item.path===sub.path&&item.events.includes(sub.event)))){let item=warnItems.find((item=>item.path===sub.path));if(!item){warnItems.push({path:sub.path,events:[sub.event]})}else if(!item.events.includes(sub.event)){item.events.push(sub.event)}}}));return warnItems}),[]);console.log(`SYNC strategy`,strategy);const syncPromises=[];if(strategy.cursor.length>0){this.debug.log(`SYNC using cursor "${cursor}" for event(s) ${strategy.cursor.map((item=>`${item.events.join(", ")} on "/${item.path}"`)).join(", ")}`);const cursorPromise=(async()=>{let remoteMutations;try{const result=await this.getChanges({for:strategy.cursor,cursor:cursor});remoteMutations=result.changes;this._updateCursor(result.new_cursor)}catch(err){this.debug.error(`SYNC: Could not load remote changes`,err);options.eventCallback&&options.eventCallback("sync_cursor_error",err);if(err.code==="no_transaction_logging"){this._updateCursor(null)}strategy.cursor.forEach((item=>{if(item.events.includes("value")){strategy.reload.push(item.path)}else{strategy.warn.push(item)}}))}if(remoteMutations){usedSyncMethod="cursor";this.debug.log(`SYNC: Got ${remoteMutations.length} remote mutations`,remoteMutations);const promises=remoteMutations.map((m=>{const cachePath=`${this.dbname}/cache/${m.path}`;if(m.type==="update"){return cacheApi.update(cachePath,m.value,{context:m.context})}else if(m.type==="set"){return cacheApi.set(cachePath,m.value,{context:m.context})}}));await Promise.all(promises)}})();syncPromises.push(cursorPromise)}if(strategy.reload.length>0){this.debug.log(`SYNC reloading data for event paths ${strategy.reload.map((path=>`"/${path}"`)).join(", ")}`);const reloadPromise=(async()=>{const promises=strategy.reload.map((path=>{this.debug.verbose(`SYNC: load "/${path}"`);return this.get(path,{allow_cache:false}).catch((err=>{this.debug.error(`SYNC: could not load "/${path}"`,err);options.eventCallback&&options.eventCallback("sync_pull_error",err)}))}));await Promise.all(promises)})();syncPromises.push(reloadPromise)}if(strategy.fallback.length>0){this.debug.log(`SYNC using fallback functions for event(s) ${strategy.fallback.map((sub=>`${sub.event} on "/${sub.path}"`)).join(", ")}`);const fallbackPromise=(async()=>{const promises=strategy.fallback.map((async sub=>{this.debug.verbose(`SYNC: running fallback for event ${sub.event} on "/${sub.path}"`);try{await sub.settings.syncFallback()}catch(err){this.debug.error(`SYNC: error running fallback function for ${sub.event} on "/${sub.path}"`,err);options.eventCallback&&options.eventCallback("sync_fallback_error",err)}}));await Promise.all(promises)})();syncPromises.push(fallbackPromise)}if(strategy.warn.length>0){this.debug.warn(`SYNC warning: unable to sync event(s) ${strategy.warn.map((item=>`${item.events.map((event=>`"${event}"`)).join(", ")} on "/${item.path}"`)).join(", ")}. To resolve this, provide syncFallback functions for these events`)}await Promise.all(syncPromises);await new Promise((resolve=>setTimeout(resolve,10)));subscriptions.forEach((sub=>{console.assert(typeof sub.tempCallback==="function");cacheApi.unsubscribe(PathInfo.getChildPath(`${this.dbname}/cache`,sub.path),sub.event,sub.tempCallback);delete sub.tempCallback}))}else if(!this._cache){const syncPromises=[];subscriptionPaths.forEach((path=>{const subs=subscriptions.for(path);const warnEvents=[];subs.filter((sub=>sub.event!=="value")).forEach((sub=>{if(typeof sub.settings.syncFallback==="function"){syncPromises.push(sub.settings.syncFallback())}else{!warnEvents.includes(sub.event)&&warnEvents.push(sub.event)}}));if(warnEvents.length>0){this.debug.warn(`Subscriptions ${warnEvents.join(", ")} on path "${path}" might have missed events while offline. Data should be reloaded!`)}const valueSubscriptions=subs.filter((sub=>sub.event==="value"));if(valueSubscriptions.length>0){const p=this.get(path,{allow_cache:false}).then((value=>{valueSubscriptions.forEach((subscr=>subscr.callback(null,path,value)))}));syncPromises.push(p)}}));await Promise.all(syncPromises)}subscriptions.forEach((sub=>sub.lastSynced=Date.now()));this.debug.verbose(`SYNC done`);const info={local:totalPendingChanges,remote:totalRemoteChanges,method:usedSyncMethod,cursor:cursor};options.eventCallback&&options.eventCallback("sync_done",info);return info}catch(err){this.debug.error(`SYNC error`,err);options.eventCallback&&options.eventCallback("sync_error",err);throw err}}async getMutations(filter){if(typeof filter!=="object"){throw new Error("No filter specified")}if(typeof filter.cursor!=="string"&&typeof filter.timestamp!=="number"){throw new Error("No cursor or timestamp given")}const query=Object.keys(filter).map((key=>{let val=filter[key];if(key==="for"){val=encodeURIComponent(JSON.stringify(val))}return typeof val!=="undefined"?`${key}=${val}`:null})).filter((p=>p!=null)).join("&");const{data:data,context:context}=await this._request({url:`${this.url}/sync/mutations/${this.dbname}?${query}`,includeContext:true});const mutations=Transport.deserialize2(data);return{used_cursor:filter.cursor,new_cursor:context.acebase_cursor,mutations:mutations}}async getChanges(filter){if(typeof filter!=="object"){throw new Error("No filter specified")}if(typeof filter.cursor!=="string"&&typeof filter.timestamp!=="number"){throw new Error("No cursor or timestamp given")}const query=Object.keys(filter).map((key=>{let val=filter[key];if(key==="for"){val=encodeURIComponent(JSON.stringify(val))}return typeof val!=="undefined"?`${key}=${val}`:null})).filter((p=>p!=null)).join("&");const{data:data,context:context}=await this._request({url:`${this.url}/sync/changes/${this.dbname}?${query}`,includeContext:true});const changes=Transport.deserialize2(data);return{used_cursor:filter.cursor,new_cursor:context.acebase_cursor,changes:changes}}async _addCacheSetMutation(path,value,context){const escapedPath=path.replace(/([.*+?\\$^\(\)\[\]\{\}])/g,"\\$1");const re=new RegExp(`^${escapedPath}(?:\\[|/|$)`);await this._cache.db.query(`${this.dbname}/pending`).filter("path","matches",re).remove();return this._cache.db.api.set(`${this.dbname}/pending/${ID.generate()}`,{type:value!==null?"set":"remove",path:path,data:value,context:context})}set(path,value,options={allow_cache:true,context:{}}){if(!options.context){options.context={}}const useCache=this._cache&&options.allow_cache!==false;const useServer=this.isConnected;options.context.acebase_mutation=options.context.acebase_mutation||{client_id:this._id,id:ID.generate(),op:"set",path:path,flow:useCache?useServer?"parallel":"cache":"server"};const updateServer=async()=>{const data=JSON.stringify(Transport.serialize(value));const{context:context}=await this._request({method:"PUT",url:`${this.url}/data/${this.dbname}/${path}`,data:data,context:options.context,includeContext:true});Object.assign(options.context,context);const cursor=context&&context.acebase_cursor;return{cursor:cursor}};if(!useCache){return updateServer()}const cachePath=PathInfo.getChildPath(`${this.dbname}/cache`,path);let rollbackValue;const updateCache=()=>this._cache.db.api.transaction(cachePath,(currentValue=>{rollbackValue=currentValue;return value}),{context:options.context});const rollbackCache=()=>this._cache.db.api.set(cachePath,rollbackValue,{context:options.context});const addPendingTransaction=async()=>{await this._addCacheSetMutation(path,value,options.context)};const cachePromise=updateCache();const tryCachePromise=cachePromise.then((()=>({success:true}))).catch((err=>({success:false,error:err})));const serverPromise=!useServer?null:updateServer();const tryServerPromise=!useServer?null:serverPromise.then((()=>({success:true}))).catch((err=>({success:false,error:err})));Promise.all([tryCachePromise,tryServerPromise]).then((([cacheResult,serverResult])=>{const networkError=serverPromise&&!serverResult.success&&serverResult.error.isNetworkError===true;if(serverPromise&&!networkError){if(serverResult.success){if(!cacheResult.success){this.debug.error(`Failed to set cache for "${path}". Error: `,cacheResult.error)}}else{if(cacheResult.success){this.debug.error(`Failed to set server value for "${path}", rolling back cache to previous value. Error:`,serverResult.error);rollbackCache().catch((err=>{this.debug.error(`Failed to roll back cache? Error:`,err)}))}}}else if(cacheResult.success){addPendingTransaction().catch((err=>{this.debug.error(`Failed to add pending sync action for "${path}", rolling back cache to previous value. Error:`,err);rollbackCache().catch((err=>{this.debug.error(`Failed to roll back cache? Error:`,err)}))}))}}));if(!useServer){return cachePromise}return this._cache.priority==="cache"?cachePromise:serverPromise}update(path,updates,options={allow_cache:true,context:{}}){const useCache=this._cache&&options&&options.allow_cache!==false;const useServer=this.isConnected;options.context.acebase_mutation=options.context.acebase_mutation||{client_id:this._id,id:ID.generate(),op:"update",path:path,flow:useCache?useServer?"parallel":"cache":"server"};const updateServer=async()=>{const data=JSON.stringify(Transport.serialize(updates));const{context:context}=await this._request({method:"POST",url:`${this.url}/data/${this.dbname}/${path}`,data:data,context:options.context,includeContext:true});Object.assign(options.context,context);const cursor=context&&context.acebase_cursor;return{cursor:cursor}};if(!useCache){return updateServer()}const cacheApi=this._cache.db.api;const cachePath=PathInfo.getChildPath(`${this.dbname}/cache`,path);let rollbackUpdates;const updateCache=()=>{const properties=Object.keys(updates);return cacheApi.get(cachePath,{include:properties}).then((result=>{rollbackUpdates=result.value;return cacheApi.update(cachePath,updates,{context:options.context})}))};const rollbackCache=()=>cacheApi.update(cachePath,rollbackUpdates,{context:options.context});const addPendingTransaction=async()=>{const pathInfo=PathInfo.get(path);const mutations=Object.keys(updates).map((prop=>{if(updates instanceof Array){prop=parseInt(prop)}return{path:pathInfo.childPath(prop),value:updates[prop]}}));const promises=mutations.map((m=>this._addCacheSetMutation(m.path,m.value,options.context)));await Promise.all(promises)};const cachePromise=updateCache();const tryCachePromise=cachePromise.then((()=>({success:true}))).catch((err=>({success:false,error:err})));const serverPromise=!useServer?null:updateServer();const tryServerPromise=!useServer?null:serverPromise.then((()=>({success:true}))).catch((err=>({success:false,error:err})));Promise.all([tryCachePromise,tryServerPromise]).then((([cacheResult,serverResult])=>{const networkError=serverPromise&&!serverResult.success&&serverResult.error.isNetworkError===true;if(serverPromise&&!networkError){if(serverResult.success){if(!cacheResult.success){this.debug.error(`Failed to update cache for "${path}". Error: `,cacheResult.error)}}else{if(cacheResult.success){this.debug.error(`Failed to update server value for "${path}", rolling back cache to previous value. Error:`,serverResult.error);rollbackCache().catch((err=>{this.debug.error(`Failed to roll back cache? Error:`,err)}))}}}else if(cacheResult.success){addPendingTransaction().catch((err=>{this.debug.error(`Failed to add pending sync action for "${path}", rolling back cache to previous value. Error:`,err);rollbackCache().catch((err=>{this.debug.error(`Failed to roll back cache? Error:`,err)}))}))}}));if(!useServer){return cachePromise}return this._cache.priority==="cache"?cachePromise:serverPromise}async get(path,options={cache_mode:"allow"}){if(typeof options.cache_mode!=="string"){options.cache_mode="allow"}const useCache=this._cache&&options.cache_mode!=="bypass";const getServerValue=async()=>{let url=`${this.url}/data/${this.dbname}/${path}`;let filtered=false;if(options){let query=[];if(options.exclude instanceof Array){query.push(`exclude=${options.exclude.join(",")}`)}if(options.include instanceof Array){query.push(`include=${options.include.join(",")}`)}if(typeof options.child_objects==="boolean"){query.push(`child_objects=${options.child_objects}`)}if(query.length>0){filtered=true;url+=`?${query.join("&")}`}}const result=await this._request({url:url,includeContext:true});const context=result.context;const cursor=context&&context.acebase_cursor;const value=Transport.deserialize(result.data);if(this._cache){if(!filtered){const cachePath=PathInfo.getChildPath(`${this.dbname}/cache`,path);this._cache.db.api.set(cachePath,value,{context:{acebase_operation:"update_cache",acebase_server_context:context}}).catch((err=>{this.debug.error(`Error caching data for "/${path}"`,err)}))}}return{value:value,context:context,cursor:cursor}};const getCacheValue=async(throwOnNull=false)=>{const result=await this._cache.db.api.get(PathInfo.getChildPath(`${this.dbname}/cache`,path),options);let{value:value,context:context}=result;if(!("value"in result&&"context"in result)){console.warn(`Missing context from cache results. Update your acebase package`);value=result,context={}}if(value===null&&throwOnNull){throw new CachedValueUnavailableError(path)}delete context.acebase_cursor;return{value:value,context:context}};if(options.cache_mode==="force"){const{value:value,context:context}=await getCacheValue(false);context.acebase_origin="cache";return{value:value,context:context}}if(useCache&&typeof options.cache_cursor==="string"){const syncResult=await this.updateCache(path,options.cache_cursor);const{value:value,context:context}=await getCacheValue(false);context.acebase_cursor=syncResult.new_cursor;context.acebase_origin="hybrid";return{value:value,context:context,cursor:context.acebase_cursor}}if(!useCache){const{value:value,context:context,cursor:cursor}=await getServerValue();context.acebase_origin="server";return{value:value,context:context,cursor:cursor}}if(!this.isConnected||this._cache.priority==="cache"){const throwOnNull=this._cache.priority!=="cache";const{value:value,context:context}=await getCacheValue(throwOnNull);context.acebase_origin="cache";return{value:value,context:context}}return new Promise(((resolve,reject)=>{let wait=true,done=false;const gotValue=(source,val)=>{this.debug.verbose(`Got ${source} value of "${path}":`,val);if(done){return}const{value:value,context:context,cursor:cursor}=val;if(source==="server"){done=true;this.debug.verbose(`Using server value for "${path}"`);context.acebase_origin="server";resolve({value:value,context:context,cursor:cursor})}else if(value===null){if(!wait){const serverError=errors.find((e=>e.source==="server")).error;if(serverError.isNetworkError){return reject(new CachedValueUnavailableError(path))}const error=new CachedValueUnavailableError(path,`Value for "${path}" not found in cache, and server value could not be loaded. See serverError for more details`);error.serverError=serverError;return reject(error)}}else if(!wait){done=true;this.debug.verbose(`Using cache value for "${path}"`);context.acebase_origin="cache";resolve({value:value,context:context})}else{setTimeout((()=>{if(done){return}this.debug.verbose(`Using (delayed) cache value for "${path}"`);done=true;context.acebase_origin="cache";resolve({value:value,context:context})}),1e3)}};let errors=[];const gotError=(source,error)=>{errors.push({source:source,error:error});if(errors.length===2){reject(errors.find((e=>e.source==="server")).error)}};getServerValue().then((val=>gotValue("server",val))).catch((err=>(wait=false,gotError("server",err))));getCacheValue(false).then((val=>gotValue("cache",val))).catch((err=>gotError("cache",err)))}))}exists(path,options={allow_cache:true}){const useCache=this._cache&&options.allow_cache!==false;const getCacheExists=()=>this._cache.db.api.exists(PathInfo.getChildPath(`${this.dbname}/cache`,path));const getServerExists=()=>this._request({url:`${this.url}/exists/${this.dbname}/${path}`}).then((res=>res.exists)).catch((err=>{throw err}));if(!useCache){return getServerExists()}else if(!this.isConnected){return getCacheExists()}else{return new Promise(((resolve,reject)=>{let wait=true,done=false;const gotExists=(source,exists)=>{if(done){return}if(source==="server"){done=true;resolve(exists)}else if(!wait){done=true;resolve(exists)}else{setTimeout((()=>{if(done){return}done=true;resolve(exists)}),1e3)}};let errors=[];const gotError=(source,error)=>{errors.push({source:source,error:error});if(errors.length===2){reject(errors.find((e=>e.source==="server")))}};getServerExists().then((exists=>gotExists("server",exists))).catch((err=>(wait=false,gotError("server",err))));getCacheExists().then((exists=>gotExists("cache",exists))).catch((err=>gotError("cache",err)))}))}}callExtension(method,path,data){method=method.toUpperCase();const postData=["PUT","POST"].includes(method)?data:null;let url=`${this.url}/ext/${this.dbname}/${path}`;if(data&&!["PUT","POST"].includes(method)){if(typeof data==="object"){data=Object.keys(data).filter((key=>typeof data[key]!=="undefined")).map((key=>key+"="+encodeURIComponent(JSON.stringify(data[key])))).join("&")}else if(typeof data!=="string"||!data.includes("=")){throw new Error('data must be an object, or a string with query parameters, like "index=3&name=Something"')}url+=`?`+data}return this._request({method:method,url:url,data:postData,ignoreConnectionState:true})}async clearCache(path=""){if(this._cache){const value=path===""?{}:null;const cachePath=PathInfo.getChildPath(`${this.dbname}/cache`,path);return this._cache.db.api.set(cachePath,value,{suppress_events:true})}}async updateCache(path="",cursor){if(!this._cache){throw new Error(`No cache database used`)}const cachePath=PathInfo.getChildPath(`${this.dbname}/cache`,path);const cacheApi=this._cache.db.api;let loadValue=cursor===null||typeof cursor==="undefined"||!await cacheApi.exists(cachePath);if(loadValue){const{value:value,context:context}=await this.get(path,{cache_mode:"bypass"});return{path:path,used_cursor:cursor,new_cursor:context.acebase_cursor,loaded_value:true,changes:[]}}const{changes:changes,new_cursor:new_cursor}=await this.getChanges({path:path,cursor:cursor});for(let ch of changes){const cachePath=PathInfo.getChildPath(`${this.dbname}/cache`,ch.path);const options={context:ch.context,suppress_events:false};if(ch.type==="update"){await cacheApi.update(cachePath,ch.value,options)}else if(ch.type==="set"){await cacheApi.set(cachePath,ch.value,options)}}return{path:path,used_cursor:cursor,new_cursor:new_cursor,loaded_value:false,changes:changes}}async query(path,query,options={snapshots:false,cache_mode:"allow",eventListener:undefined,monitor:{add:false,change:false,remove:false}}){const useCache=this._cache&&(options.cache_mode==="force"||options.cache_mode==="allow"&&!this.isConnected);if(useCache){const data=await this._cache.db.api.query(PathInfo.getChildPath(`${this.dbname}/cache`,path),query,options);let{results:results,context:context}=data;if(!("results"in data&&"context"in data)){console.warn(`Missing context from local query results. Update your acebase package`);results=data;context={}}context.acebase_origin="cache";delete context.acebase_cursor;return{results:results,context:context}}const request={query:query,options:options};if(options.monitor===true||typeof options.monitor==="object"&&(options.monitor.add||options.monitor.change||options.monitor.remove)){console.assert(typeof options.eventHandler==="function",`no eventHandler specified to handle realtime changes`);if(!this.socket){throw new Error(`Cannot create realtime query because websocket is not connected. Check your AceBaseClient network.realtime setting`)}request.query_id=ID.generate();request.client_id=this.socket.id;this._realtimeQueries[request.query_id]={query:query,options:options}}const reqData=JSON.stringify(Transport.serialize(request));try{const{data:data,context:context}=await this._request({method:"POST",url:`${this.url}/query/${this.dbname}/${path}`,data:reqData,includeContext:true});let results=Transport.deserialize(data);context.acebase_origin="server";const stop=async()=>{delete this._realtimeQueries[request.query_id];await _websocketRequest(socket,"query-unsubscribe",{query_id:request.query_id})};return{results:results.list,context:context,stop:stop}}catch(err){throw err}}async createIndex(path,key,options){if(options&&options.config&&Object.values(options.config).find((val=>typeof val==="function"))){throw new Error(`Cannot create an index with callback functions through a client. Move your code serverside`)}const version=this._serverVersion.split(".");if(version.length===3&&+version[0]>=1&&+version[1]>=10){const data=JSON.stringify({path:path,key:key,options:options});return await this._request({method:"POST",url:`${this.url}/index/${this.dbname}/create`,data:data})}else{const data=JSON.stringify({action:"create",path:path,key:key,options:options});return await this._request({method:"POST",url:`${this.url}/index/${this.dbname}`,data:data})}}getIndexes(){return this._request({url:`${this.url}/index/${this.dbname}`})}async deleteIndex(fileName){const version=this._serverVersion.split(".");if(version.length===3&&+version[0]>=1&&+version[1]>=10){const data=JSON.stringify({fileName:fileName});return this._request({method:"POST",url:`${this.url}/index/${this.dbname}/delete`,data:data})}else{throw new Error(`not supported, requires acebase-server 1.10 or higher`)}}reflect(path,type,args){let url=`${this.url}/reflect/${this.dbname}/${path}?type=${type}`;if(typeof args==="object"){let query=Object.keys(args).map((key=>`${key}=${args[key]}`));if(query.length>0){url+=`&${query.join("&")}`}}return this._request({url:url})}export(path,write,options={format:"json",type_safe:true}){options.format="json";options.type_safe=options.type_safe!==false;if(typeof write!="function"){write=write.write.bind(write)}const url=`${this.url}/export/${this.dbname}/${path}?format=${options.format}&type_safe=${options.type_safe?1:0}`;return this._request({url:url,dataReceivedCallback:chunk=>write(chunk)})}import(path,read,options={format:"json",suppress_events:false}){options.format="json";options.suppress_events=options.suppress_events===true;const url=`${this.url}/import/${this.dbname}/${path}?format=${options.format}&suppress_events=${options.suppress_events?1:0}`;return this._request({method:"POST",url:url,dataRequestCallback:length=>read(length)})}get serverPingUrl(){return`${this.url}/ping/${this.dbname}`}async getServerInfo(){const info=await this._request({url:`${this.url}/info/${this.dbname}`}).catch((err=>{if(!err.isNetworkError){this.debug.warn(`Could not get server info, update your acebase server version`)}return{version:"unknown",time:Date.now()}}));this._serverVersion=info.version;return info}setSchema(path,schema){if(schema!==null){schema=new SchemaDefinition(schema).text}const data=JSON.stringify({action:"set",path:path,schema:schema});return this._request({method:"POST",url:`${this.url}/schema/${this.dbname}`,data:data}).catch((err=>{throw err}))}getSchema(path){return this._request({url:`${this.url}/schema/${this.dbname}/${path}`}).catch((err=>{throw err}))}getSchemas(){return this._request({url:`${this.url}/schema/${this.dbname}`}).catch((err=>{throw err}))}validateSchema(path,value,isUpdate){throw new Error(`Manual schema validation can only be used on standalone databases`)}}module.exports={WebApi:WebApi}},{"./base64":9,"./errors":11,"./promise-timeout":14,"./request":15,"./request/error":16,"acebase-core":30,"socket.io-client":5}],8:[function(require,module,exports){const{AceBaseUser:AceBaseUser,AceBaseSignInResult:AceBaseSignInResult,AceBaseAuthResult:AceBaseAuthResult}=require("./user");class AceBaseClientAuth{constructor(client,eventCallback){this.client=client;this.eventCallback=eventCallback;this.user=null;this.accessToken=null}async signIn(username,password){if(!this.client.isReady){await this.client.ready()}const details=await this.client.api.signIn(username,password);if(this.user){this.eventCallback("signout",{source:"signin",user:this.user})}this.accessToken=details.accessToken;this.user=new AceBaseUser(details.user);this.eventCallback("signin",{source:"signin",user:this.user,accessToken:this.accessToken});return{user:this.user,accessToken:this.accessToken}}async signInWithEmail(email,password){if(!this.client.isReady){await this.client.ready()}const details=await this.client.api.signInWithEmail(email,password);if(this.user){this.eventCallback("signout",{source:"email_signin",user:this.user})}this.accessToken=details.accessToken;this.user=new AceBaseUser(details.user);this.eventCallback("signin",{source:"email_signin",user:this.user,accessToken:this.accessToken});return{user:this.user,accessToken:this.accessToken}}async signInWithToken(accessToken){if(!this.client.isReady){await this.client.ready()}const details=await this.client.api.signInWithToken(accessToken);if(this.user){this.eventCallback("signout",{source:"token_signin",user:this.user})}this.accessToken=details.accessToken;this.user=new AceBaseUser(details.user);this.eventCallback("signin",{source:"token_signin",user:this.user,accessToken:this.accessToken});return{user:this.user,accessToken:this.accessToken}}setAccessToken(accessToken){this.client.api.setAccessToken(accessToken)}async startAuthProviderSignIn(providerName,callbackUrl,options){if(!this.client.isReady){await this.client.ready()}const details=await this.client.api.startAuthProviderSignIn(providerName,callbackUrl,options);return details.redirectUrl}async finishAuthProviderSignIn(callbackResult){if(!this.client.isReady){await this.client.ready()}const details=await this.client.api.finishAuthProviderSignIn(callbackResult);const isOtherUser=!this.user||this.user.uid!==details.user.uid;isOtherUser&&this.eventCallback("signout",{source:"oauth_signin",user:this.user});this.accessToken=details.accessToken;this.user=new AceBaseUser(details.user);isOtherUser&&this.eventCallback("signin",{source:"oauth_signin",user:this.user,accessToken:this.accessToken});return{user:this.user,accessToken:this.accessToken,provider:details.provider}}async refreshAuthProviderToken(providerName,refreshToken){if(!this.client.isReady){await this.client.ready()}const details=await this.client.api.refreshAuthProviderToken(providerName,refreshToken);return{provider:details.provider}}async signInWithRedirect(providerName){if(typeof window==="undefined"){throw new Error(`signInWithRedirect can only be used within a browser context`)}const redirectUrl=await this.startAuthProviderSignIn(providerName,window.location.href);window.location.href=redirectUrl}async getRedirectResult(){if(typeof window==="undefined"){throw new Error(`getRedirectResult can only be used within a browser context`)}const match=window.location.search.match(/[?&]result=(.*?)(?:&|$)/);const callbackResult=match&&decodeURIComponent(match[1]);if(!callbackResult){return null}return await this.finishAuthProviderSignIn(callbackResult)}async signOut(options){if(!this.client.isReady){await this.client.ready()}else if(!this.user){throw{code:"not_signed_in",message:"Not signed in!"}}if(this.client.isConnected){await this.client.api.signOut(options)}this.accessToken=null;let user=this.user;this.user=null;this.eventCallback("signout",{source:"signout",user:user})}async changePassword(oldPassword,newPassword){if(!this.client.isReady){await this.client.ready()}else if(!this.user){throw{code:"not_signed_in",message:"Not signed in!"}}const result=await this.client.api.changePassword(this.user.uid,oldPassword,newPassword);this.accessToken=result.accessToken;this.eventCallback("signin",{source:"password_change",user:this.user,accessToken:this.accessToken});return{accessToken:result.accessToken}}async forgotPassword(email){if(!this.client.isReady){await this.client.ready()}return await this.client.api.forgotPassword(email)}async resetPassword(resetCode,newPassword){if(!this.client.isReady){await this.client.ready()}return await this.client.api.resetPassword(resetCode,newPassword)}async verifyEmailAddress(verificationCode){if(!this.client.isReady){await this.client.ready()}return await this.client.api.verifyEmailAddress(verificationCode)}async updateUserDetails(details){if(!this.client.isReady){await this.client.ready()}if(!this.user){throw{code:"not_signed_in",message:"Not signed in!"}}if(typeof details!=="object"){throw{code:"invalid_details",message:"details must be an object"}}const result=await this.client.api.updateUserDetails(details);Object.keys(result.user).forEach((key=>{this.user[key]=result.user[key]}));return{user:this.user}}async changeUsername(newUsername){return await this.updateUserDetails({username:newUsername})}async changeDisplayName(newName){return await this.updateUserDetails({display_name:newName})}async changeEmail(newEmail){return await this.updateUserDetails({email:newEmail})}async changePicture(newPicture){return await this.updateUserDetails({picture:newPicture})}async updateUserSettings(settings){return await this.updateUserDetails({settings:settings})}async signUp(details){if(!details.username&&!details.email){throw{code:"invalid_details",message:"No username or email set"}}if(!details.password){throw{code:"invalid_details",message:"No password given"}}if(!this.client.isReady){await this.client.ready()}const isAdmin=this.user&&this.user.uid==="admin";if(this.user&&!isAdmin){let user=this.user;this.user=null;this.eventCallback("signout",{source:"signup",user:user})}const result=await this.client.api.signUp(details,!isAdmin);if(isAdmin){return{user:result.user}}else{this.accessToken=result.accessToken;this.user=new AceBaseUser(result.user);this.eventCallback("signin",{source:"signup",user:this.user,accessToken:this.accessToken});return{user:this.user,accessToken:this.accessToken}}}async deleteAccount(uid){if(!this.client.isReady){await this.client.ready()}if(!this.user){throw{code:"not_signed_in",message:"Not signed in!"}}if(uid&&this.user.uid!=="admin"){throw{code:"not_admin",message:"Cannot remove other accounts than signed into account, unless you are admin"}}const deleteUid=uid||this.user.uid;if(deleteUid==="admin"){throw{code:"not_allowed",message:"Cannot remove admin user"}}const signOut=this.user.uid!=="admin";const result=await this.client.api.deleteAccount(deleteUid,signOut);if(signOut){this.accessToken=null;let user=this.user;this.user=null;this.eventCallback("signout",{source:"delete_account",user:user})}}}module.exports={AceBaseClientAuth:AceBaseClientAuth}},{"./user":18}],9:[function(require,module,exports){const Base64={encode(str){return btoa(unescape(encodeURIComponent(str)))},decode(base64){return decodeURIComponent(escape(atob(base64)))}};module.exports=Base64},{}],10:[function(require,module,exports){const acebaseclient=require("./index");window.acebaseclient=acebaseclient;window.AceBaseClient=acebaseclient.AceBaseClient;module.exports=acebaseclient},{"./index":12}],11:[function(require,module,exports){class CachedValueUnavailableError extends Error{constructor(path,message){super(message||`Value for path "/${path}" is not available in cache`);this.path=path}}module.exports={CachedValueUnavailableError:CachedValueUnavailableError}},{}],12:[function(require,module,exports){const{DataReference:DataReference,DataSnapshot:DataSnapshot,EventSubscription:EventSubscription,PathReference:PathReference,TypeMappings:TypeMappings,ID:ID,proxyAccess:proxyAccess,ObjectCollection:ObjectCollection,PartialArray:PartialArray,Transport:Transport}=require("acebase-core");const{AceBaseClient:AceBaseClient}=require("./acebase-client");const{ServerDate:ServerDate}=require("./server-date");const{CachedValueUnavailableError:CachedValueUnavailableError}=require("./errors");module.exports={AceBaseClient:AceBaseClient,DataReference:DataReference,DataSnapshot:DataSnapshot,EventSubscription:EventSubscription,PathReference:PathReference,TypeMappings:TypeMappings,ID:ID,proxyAccess:proxyAccess,ServerDate:ServerDate,ObjectCollection:ObjectCollection,CachedValueUnavailableError:CachedValueUnavailableError,PartialArray:PartialArray,Transport:Transport}},{"./acebase-client":6,"./errors":11,"./server-date":17,"acebase-core":30}],13:[function(require,module,exports){module.exports=performance},{}],14:[function(require,module,exports){class PromiseTimeoutError extends Error{}function promiseTimeout(promise,ms,comment){return new Promise(((resolve,reject)=>{let timeout;function success(result){clearTimeout(timeout);resolve(result)}promise.then(success).catch(reject);timeout=setTimeout((()=>reject(new PromiseTimeoutError(`Promise ${comment?`"${comment}" `:""}timed out after ${ms}ms`))),ms)}))}module.exports={PromiseTimeoutError:PromiseTimeoutError,promiseTimeout:promiseTimeout}},{}],15:[function(require,module,exports){const{AceBaseRequestError:AceBaseRequestError}=require("./error");async function request(method,url,options={accessToken:null,data:null,dataReceivedCallback:null,dataRequestCallback:null,context:null}){let postData=options.data;if(typeof postData==="undefined"||postData===null){postData=""}else if(typeof postData==="object"){postData=JSON.stringify(postData)}const headers={"AceBase-Context":JSON.stringify(options.context||null)};const init={method:method,headers:headers};if(typeof options.dataRequestCallback==="function"){headers["Content-Type"]="text/plain";const supportsStreaming=false;if(supportsStreaming){let canceled=false;init.body=new ReadableStream({async pull(controller){const chunkSize=controller.desiredSize||1024*16;let chunk=await options.dataRequestCallback(chunkSize);if(canceled||[null,""].includes(chunk)){controller.close()}else{controller.enqueue(chunk)}},async start(controller){},cancel(){canceled=true}})}else{postData="";const chunkSize=1024*512;let chunk;while(chunk=await options.dataRequestCallback(chunkSize)){postData+=chunk}init.body=postData}}else if(postData.length>0){headers["Content-Type"]="application/json";init.body=postData}if(options.accessToken){headers["Authorization"]=`Bearer ${options.accessToken}`}const request={url:url,method:method,headers:headers};const res=await fetch(request.url,init).catch((err=>{throw new AceBaseRequestError(request,null,"fetch_failed",err.message)}));let data="";if(typeof options.dataReceivedCallback==="function"){const reader=res.body.getReader();await new Promise(((resolve,reject)=>{(function readNext(){reader.read().then((result=>{options.dataReceivedCallback(result.value);if(result.done){return resolve()}readNext()})).catch((err=>{reader.cancel("error");reject(err)}))})()}))}else{data=await res.text()}const isJSON=data[0]==="{"||data[0]==="[";if(res.status===200){let context=res.headers.get("AceBase-Context");if(context&&context[0]==="{"){context=JSON.parse(context)}else{context={}}if(isJSON){data=JSON.parse(data)}return{context:context,data:data}}else{request.body=postData;const response={statusCode:res.status,statusMessage:res.statusText,headers:res.headers,body:data};let code=res.status,message=res.statusText;if(isJSON){let err=JSON.parse(data);if(err.code){code=err.code}if(err.message){message=err.message}}throw new AceBaseRequestError(request,response,code,message)}}module.exports=request},{"./error":16}],16:[function(require,module,exports){class AceBaseRequestError extends Error{get isNetworkError(){return this.response===null}constructor(request,response,code,message){super(message);this.code=code;this.request=request;this.response=response}}const NOT_CONNECTED_ERROR_MESSAGE="remote database is not connected";module.exports={AceBaseRequestError:AceBaseRequestError,NOT_CONNECTED_ERROR_MESSAGE:NOT_CONNECTED_ERROR_MESSAGE}},{}],17:[function(require,module,exports){const{ID:ID}=require("acebase-core");const performance=require("./performance");let time={serverBias:0,localBias:0,lastTime:Date.now(),lastPerf:performance.now(),get bias(){return this.serverBias+this.localBias}};function biasChanged(){console.log(`Bias changed. server bias = ${time.serverBias}ms, local bias = ${time.localBias}ms`);ID.timeBias=time.bias}const interval=1e4;function checkLocalTime(){const now=Date.now(),perf=performance.now(),msPassed=perf-time.lastPerf,expected=time.lastTime+Math.round(msPassed),diff=expected-now;if(Math.abs(diff)>1){console.log(`Local time changed. diff = ${diff}ms`);time.localBias+=diff;biasChanged()}time.lastTime=now;time.lastPerf=perf;scheduleLocalTimeCheck()}function scheduleLocalTimeCheck(){const timeout=setTimeout(checkLocalTime,interval);timeout.unref&&timeout.unref()}scheduleLocalTimeCheck();function setServerBias(bias){if(typeof bias==="number"){time.serverBias=bias;time.localBias=0;biasChanged()}}class ServerDate extends Date{constructor(){const biasedTime=Date.now()+time.bias;super(biasedTime)}}module.exports={ServerDate:ServerDate,setServerBias:setServerBias}},{"./performance":13,"acebase-core":30}],18:[function(require,module,exports){class AceBaseUser{constructor(user){Object.assign(this,user)}}class AceBaseSignInResult{constructor(result){this.success=result.success;if(result.success){this.user=result.user;this.accessToken=result.accessToken}else{this.reason=result.reason}}}class AceBaseAuthResult{constructor(result){this.success=result.success;if(!result.success){this.reason=result.reason}}}module.exports={AceBaseUser:AceBaseUser,AceBaseSignInResult:AceBaseSignInResult,AceBaseAuthResult:AceBaseAuthResult}},{}],19:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AceBaseBase=exports.AceBaseBaseSettings=void 0;const simple_event_emitter_1=require("./simple-event-emitter");const data_reference_1=require("./data-reference");const type_mappings_1=require("./type-mappings");const optional_observable_1=require("./optional-observable");const debug_1=require("./debug");const simple_colors_1=require("./simple-colors");class AceBaseBaseSettings{constructor(options){if(typeof options!=="object"){options={}}this.logLevel=options.logLevel||"log";this.logColors=typeof options.logColors==="boolean"?options.logColors:true;this.info=typeof options.info==="string"?options.info:undefined;this.sponsor=typeof options.sponsor==="boolean"?options.sponsor:false}}exports.AceBaseBaseSettings=AceBaseBaseSettings;class AceBaseBase extends simple_event_emitter_1.SimpleEventEmitter{constructor(dbname,options){super();options=new AceBaseBaseSettings(options||{});this.name=dbname;this.debug=new debug_1.DebugLogger(options.logLevel,`[${dbname}]`);(0,simple_colors_1.SetColorsEnabled)(options.logColors);const logoStyle=[simple_colors_1.ColorStyle.magenta,simple_colors_1.ColorStyle.bold];const logo=" ___ ______ "+"\n"+" / _ \\ | ___ \\ "+"\n"+" / /_\\ \\ ___ ___| |_/ / __ _ ___ ___ "+"\n"+" | _ |/ __/ _ \\ ___ \\/ _` / __|/ _ \\"+"\n"+" | | | | (_| __/ |_/ / (_| \\__ \\ __/"+"\n"+" \\_| |_/\\___\\___\\____/ \\__,_|___/\\___|";const info=options.info?"".padStart(40-options.info.length," ")+options.info+"\n":"";if(!options.sponsor){this.debug.write(logo.colorize(logoStyle));info&&this.debug.write(info.colorize(simple_colors_1.ColorStyle.magenta))}this.types=new type_mappings_1.TypeMappings(this);this.once("ready",(()=>{this._ready=true}))}ready(callback=undefined){if(this._ready===true){callback&&callback();return Promise.resolve()}else{let resolve;const promise=new Promise((res=>resolve=res));this.on("ready",(()=>{resolve();callback&&callback()}));return promise}}get isReady(){return this._ready===true}setObservable(Observable){(0,optional_observable_1.setObservable)(Observable)}ref(path){return new data_reference_1.DataReference(this,path)}get root(){return this.ref("")}query(path){const ref=new data_reference_1.DataReference(this,path);return new data_reference_1.DataReferenceQuery(ref)}get indexes(){return{get:()=>this.api.getIndexes(),create:(path,key,options)=>this.api.createIndex(path,key,options),delete:async filePath=>this.api.deleteIndex(filePath)}}get schema(){return{get:path=>this.api.getSchema(path),set:(path,schema)=>this.api.setSchema(path,schema),all:()=>this.api.getSchemas(),check:(path,value,isUpdate)=>this.api.validateSchema(path,value,isUpdate)}}}exports.AceBaseBase=AceBaseBase},{"./data-reference":26,"./debug":28,"./optional-observable":32,"./simple-colors":39,"./simple-event-emitter":40,"./type-mappings":43}],20:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Api=void 0;class NotImplementedError extends Error{constructor(name){super(`${name} is not implemented`)}}class Api{constructor(dbname,settings,readyCallback){}stats(options){throw new NotImplementedError("stats")}subscribe(path,event,callback,settings){throw new NotImplementedError("subscribe")}unsubscribe(path,event,callback){throw new NotImplementedError("unsubscribe")}update(path,updates,options){throw new NotImplementedError("update")}set(path,value,options){throw new NotImplementedError("set")}get(path,options){throw new NotImplementedError("get")}transaction(path,callback,options){throw new NotImplementedError("transaction")}exists(path){throw new NotImplementedError("exists")}query(path,query,options){throw new NotImplementedError("query")}reflect(path,type,args){throw new NotImplementedError("reflect")}export(path,arg,options){throw new NotImplementedError("export")}import(path,stream,options){throw new NotImplementedError("import")}createIndex(path,key,options){throw new NotImplementedError("createIndex")}getIndexes(){throw new NotImplementedError("getIndexes")}deleteIndex(filePath){throw new NotImplementedError("deleteIndex")}setSchema(path,schema){throw new NotImplementedError("setSchema")}getSchema(path){throw new NotImplementedError("getSchema")}getSchemas(){throw new NotImplementedError("getSchemas")}validateSchema(path,value,isUpdate){throw new NotImplementedError("validateSchema")}getMutations(filter){throw new NotImplementedError("getMutations")}getChanges(filter){throw new NotImplementedError("getChanges")}}exports.Api=Api},{}],21:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ascii85=void 0;const c=function(input,length,result){var i,j,n,b=[0,0,0,0,0];for(i=0;i";return ret}exports.ascii85={encode:function(arr){if(arr instanceof ArrayBuffer){arr=new Uint8Array(arr,0,arr.byteLength)}return encode(arr)},decode:function(input){if(!input.startsWith("<~")||!input.endsWith("~>")){throw new Error("Invalid input string")}input=input.substr(2,input.length-4);var n=input.length,r=[],b=[0,0,0,0,0],i,j,t,x,y,d;for(i=0;i>>=8;y=t&255;t>>>=8;r.push(t>>>8,t&255,y,x);for(j=d;j<5;++j,r.pop());i+=4}const data=new Uint8Array(r);return data.buffer.slice(data.byteOffset,data.byteOffset+data.byteLength)}}},{}],22:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});const pad_1=require("../pad");const env=typeof window==="object"?window:self,globalCount=Object.keys(env).length,mimeTypesLength=navigator.mimeTypes?navigator.mimeTypes.length:0,clientId=(0,pad_1.default)((mimeTypesLength+navigator.userAgent.length).toString(36)+globalCount.toString(36),4);function fingerprint(){return clientId}exports.default=fingerprint},{"../pad":24}],23:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});const fingerprint_1=require("./fingerprint");const pad_1=require("./pad");var c=0,blockSize=4,base=36,discreteValues=Math.pow(base,blockSize);function randomBlock(){return(0,pad_1.default)((Math.random()*discreteValues<<0).toString(base),blockSize)}function safeCounter(){c=ct2[i]===key))}static isAncestor(ancestor,other){return ancestor.lengthother[i]===key))}static isDescendant(descendant,other){return descendant.length>other.length&&other.every(((key,i)=>descendant[i]===key))}}const isProxy=Symbol("isProxy");class LiveDataProxy{static async create(ref,options){var _a;ref=new data_reference_1.DataReference(ref.db,ref.path);let cache,loaded=false;let latestCursor=options===null||options===void 0?void 0:options.cursor;let proxy;const proxyId=id_1.ID.generate();const clientSubscriptions=[];const clientEventEmitter=new simple_event_emitter_1.SimpleEventEmitter;clientEventEmitter.on("cursor",(cursor=>latestCursor=cursor));clientEventEmitter.on("error",(err=>{console.error(err.message,err.details)}));const applyChange=(keys,newValue)=>{if(keys.length===0){cache=newValue;return true}const allowCreation=false;if(allowCreation){cache=typeof keys[0]==="number"?[]:{}}let target=cache;const trailKeys=keys.slice();while(trailKeys.length>1){const key=trailKeys.shift();if(!(key in target)){if(allowCreation){target[key]=typeof key==="number"?[]:{}}else{return false}}target=target[key]}const prop=trailKeys.shift();if(newValue===null){target instanceof Array?target.splice(prop,1):delete target[prop]}else{target[prop]=newValue}return true};const syncFallback=async()=>{if(!loaded){return}await reload()};const subscription=ref.on("mutations",{syncFallback:syncFallback}).subscribe((async snap=>{var _a;if(!loaded){return}const context=snap.context();const isRemote=((_a=context.acebase_proxy)===null||_a===void 0?void 0:_a.id)!==proxyId;if(!isRemote){return}const mutations=snap.val(false);const proceed=mutations.every((mutation=>{if(!applyChange(mutation.target,mutation.val)){return false}const changeRef=mutation.target.reduce(((ref,key)=>ref.child(key)),ref);const changeSnap=new data_snapshot_1.DataSnapshot(changeRef,mutation.val,false,mutation.prev,snap.context());clientEventEmitter.emit("mutation",{snapshot:changeSnap,isRemote:isRemote});return true}));if(proceed){clientEventEmitter.emit("cursor",context.acebase_cursor);localMutationsEmitter.emit("mutations",{origin:"remote",snap:snap})}else{console.warn(`Cached value of live data proxy on "${ref.path}" appears outdated, will be reloaded`);await reload()}}));let processPromise=Promise.resolve();const mutationQueue=[];const transactions=[];const pushLocalMutations=async()=>{const mutations=[];for(let i=0,m=mutationQueue[0];iRelativeNodeTarget.areEqual(t.target,m.target)||RelativeNodeTarget.isAncestor(t.target,m.target)))){mutationQueue.splice(i,1);i--;mutations.push(m)}}if(mutations.length===0){return}mutations.forEach((mutation=>{mutation.value=(0,utils_1.cloneObject)(getTargetValue(cache,mutation.target))}));process_1.default.nextTick((()=>{const context={acebase_proxy:{id:proxyId,source:"update"}};mutations.forEach((mutation=>{const mutationRef=mutation.target.reduce(((ref,key)=>ref.child(key)),ref);const mutationSnap=new data_snapshot_1.DataSnapshot(mutationRef,mutation.value,false,mutation.previous,context);clientEventEmitter.emit("mutation",{snapshot:mutationSnap,isRemote:false})}));const snap=new data_snapshot_1.MutationsDataSnapshot(ref,mutations.map((m=>({target:m.target,val:m.value,prev:m.previous}))),context);localMutationsEmitter.emit("mutations",{origin:"local",snap:snap})}));processPromise=mutations.reduce(((mutations,m,i,arr)=>{if(!arr.some((other=>RelativeNodeTarget.isAncestor(other.target,m.target)))){mutations.push(m)}return mutations}),[]).reduce(((updates,m,i,arr)=>{const target=m.target;if(target.length===0){updates.push({ref:ref,value:cache,type:"set"})}else{const parentTarget=target.slice(0,-1);const key=target.slice(-1)[0];const parentRef=parentTarget.reduce(((ref,key)=>ref.child(key)),ref);const parentUpdate=updates.find((update=>update.ref.path===parentRef.path));const cacheValue=getTargetValue(cache,target);if(parentUpdate){parentUpdate.value[key]=cacheValue}else{updates.push({ref:parentRef,value:{[key]:cacheValue},type:"update"})}}return updates}),[]).reduce((async(promise,update,i,updates)=>{const context={acebase_proxy:{id:proxyId,source:update.type}};await promise;await update.ref.context(context)[update.type](update.value).catch((err=>{clientEventEmitter.emit("error",{source:"update",message:`Error processing update of "/${ref.path}"`,details:err})}));if(update.ref.cursor){clientEventEmitter.emit("cursor",update.ref.cursor)}}),processPromise);await processPromise};let syncInProgress=false;const syncPromises=[];const syncCompleted=()=>{let resolve;const promise=new Promise((rs=>resolve=rs));syncPromises.push({resolve:resolve});return promise};let processQueueTimeout=null;const scheduleSync=()=>{if(!processQueueTimeout){processQueueTimeout=setTimeout((async()=>{syncInProgress=true;processQueueTimeout=null;await pushLocalMutations();syncInProgress=false;syncPromises.splice(0).forEach((p=>p.resolve()))}),0)}};const flagOverwritten=target=>{if(!mutationQueue.find((m=>RelativeNodeTarget.areEqual(m.target,target)))){mutationQueue.push({target:target,previous:(0,utils_1.cloneObject)(getTargetValue(cache,target))})}scheduleSync()};const localMutationsEmitter=new simple_event_emitter_1.SimpleEventEmitter;const addOnChangeHandler=(target,callback)=>{const isObject=val=>val!==null&&typeof val==="object";const mutationsHandler=async details=>{var _a;const{snap:snap,origin:origin}=details;const context=snap.context();const causedByOurProxy=((_a=context.acebase_proxy)===null||_a===void 0?void 0:_a.id)===proxyId;if(details.origin==="remote"&&causedByOurProxy){console.error("DEV ISSUE: mutationsHandler was called from remote event originating from our own proxy");return}const mutations=snap.val(false).filter((mutation=>mutation.target.slice(0,target.length).every(((key,i)=>target[i]===key))));if(mutations.length===0){return}let newValue,previousValue;const singleMutation=mutations.find((m=>m.target.length<=target.length));if(singleMutation){const trailKeys=target.slice(singleMutation.target.length);newValue=trailKeys.reduce(((val,key)=>!isObject(val)||!(key in val)?null:val[key]),singleMutation.val);previousValue=trailKeys.reduce(((val,key)=>!isObject(val)||!(key in val)?null:val[key]),singleMutation.prev)}else{const currentValue=getTargetValue(cache,target);newValue=(0,utils_1.cloneObject)(currentValue);previousValue=(0,utils_1.cloneObject)(newValue);mutations.forEach((mutation=>{const trailKeys=mutation.target.slice(target.length);for(let i=0,val=newValue,prev=previousValue;i{let keepSubscription=true;try{keepSubscription=false!==callback(Object.freeze(newValue),Object.freeze(previousValue),!causedByOurProxy,context)}catch(err){clientEventEmitter.emit("error",{source:origin==="remote"?"remote_update":"local_update",message:`Error running subscription callback`,details:err})}if(keepSubscription===false){stop()}}))};localMutationsEmitter.on("mutations",mutationsHandler);const stop=()=>{localMutationsEmitter.off("mutations").off("mutations",mutationsHandler);clientSubscriptions.splice(clientSubscriptions.findIndex((cs=>cs.stop===stop)),1)};clientSubscriptions.push({target:target,stop:stop});return{stop:stop}};const handleFlag=(flag,target,args)=>{if(flag==="write"){return flagOverwritten(target)}else if(flag==="onChange"){return addOnChangeHandler(target,args.callback)}else if(flag==="subscribe"||flag==="observe"){const subscribe=subscriber=>{const currentValue=getTargetValue(cache,target);subscriber.next(currentValue);const subscription=addOnChangeHandler(target,((value,previous,isRemote,context)=>{subscriber.next(value)}));return function unsubscribe(){subscription.stop()}};if(flag==="subscribe"){return subscribe}const Observable=(0,optional_observable_1.getObservable)();return new Observable(subscribe)}else if(flag==="transaction"){const hasConflictingTransaction=transactions.some((t=>RelativeNodeTarget.areEqual(target,t.target)||RelativeNodeTarget.isAncestor(target,t.target)||RelativeNodeTarget.isDescendant(target,t.target)));if(hasConflictingTransaction){return Promise.reject(new Error("Cannot start transaction because it conflicts with another transaction"))}return new Promise((async resolve=>{const hasPendingMutations=mutationQueue.some((m=>RelativeNodeTarget.areEqual(target,m.target)||RelativeNodeTarget.isAncestor(target,m.target)));if(hasPendingMutations){if(!syncInProgress){scheduleSync()}await syncCompleted()}const tx={target:target,status:"started",transaction:null};transactions.push(tx);tx.transaction={get status(){return tx.status},get completed(){return tx.status!=="started"},get mutations(){return mutationQueue.filter((m=>RelativeNodeTarget.areEqual(tx.target,m.target)||RelativeNodeTarget.isAncestor(tx.target,m.target)))},get hasMutations(){return this.mutations.length>0},async commit(){if(this.completed){throw new Error(`Transaction has completed already (status '${tx.status}')`)}tx.status="finished";transactions.splice(transactions.indexOf(tx),1);if(syncInProgress){await syncCompleted()}scheduleSync();await syncCompleted()},rollback(){if(this.completed){throw new Error(`Transaction has completed already (status '${tx.status}')`)}tx.status="canceled";const mutations=[];for(let i=0;i{if(m.target.length===0){cache=m.previous}else{setTargetValue(cache,m.target,m.previous)}}));transactions.splice(transactions.indexOf(tx),1)}};resolve(tx.transaction)}))}};const snap=await ref.get({cache_mode:"allow",cache_cursor:options===null||options===void 0?void 0:options.cursor});if(snap.context().acebase_origin!=="cache"){clientEventEmitter.emit("cursor",(_a=ref.cursor)!==null&&_a!==void 0?_a:null)}loaded=true;cache=snap.val();if(cache===null&&typeof(options===null||options===void 0?void 0:options.defaultValue)!=="undefined"){cache=options.defaultValue;const context={acebase_proxy:{id:proxyId,source:"default"}};await ref.context(context).set(cache)}proxy=createProxy({root:{ref:ref,get cache(){return cache}},target:[],id:proxyId,flag:handleFlag});const assertProxyAvailable=()=>{if(proxy===null){throw new Error(`Proxy was destroyed`)}};const reload=async()=>{assertProxyAvailable();mutationQueue.splice(0);const snap=await ref.get({allow_cache:false});const oldVal=cache,newVal=snap.val();cache=newVal;const mutations=(0,utils_1.getMutations)(oldVal,newVal);if(mutations.length===0){return}const context=snap.context();context.acebase_proxy={id:proxyId,source:"reload"};mutations.forEach((m=>{const targetRef=getTargetRef(ref,m.target);const newSnap=new data_snapshot_1.DataSnapshot(targetRef,m.val,m.val===null,m.prev,context);clientEventEmitter.emit("mutation",{snapshot:newSnap,isRemote:true})}));const mutationsSnap=new data_snapshot_1.MutationsDataSnapshot(ref,mutations,context);localMutationsEmitter.emit("mutations",{origin:"local",snap:mutationsSnap})};return{async destroy(){await processPromise;const promises=[subscription.stop(),...clientSubscriptions.map((cs=>cs.stop()))];await Promise.all(promises);["cursor","mutation","error"].forEach((event=>clientEventEmitter.off(event)));cache=null;proxy=null},stop(){this.destroy()},get value(){assertProxyAvailable();return proxy},get hasValue(){assertProxyAvailable();return cache!==null},set value(val){assertProxyAvailable();if(val!==null&&typeof val==="object"&&val[isProxy]){val=val.valueOf()}flagOverwritten([]);cache=val},get ref(){return ref},get cursor(){return latestCursor},reload:reload,onMutation(callback){assertProxyAvailable();clientEventEmitter.off("mutation");clientEventEmitter.on("mutation",(({snapshot:snapshot,isRemote:isRemote})=>{try{callback(snapshot,isRemote)}catch(err){clientEventEmitter.emit("error",{source:"mutation_callback",message:"Error in dataproxy onMutation callback",details:err})}}))},onError(callback){assertProxyAvailable();clientEventEmitter.off("error");clientEventEmitter.on("error",(err=>{try{callback(err)}catch(err){console.error(`Error in dataproxy onError callback: ${err.message}`)}}))},on(event,callback){clientEventEmitter.on(event,callback)},off(event,callback){clientEventEmitter.off(event,callback)}}}}exports.LiveDataProxy=LiveDataProxy;function getTargetValue(obj,target){let val=obj;for(let key of target){val=typeof val==="object"&&val!==null&&key in val?val[key]:null}return val}function setTargetValue(obj,target,value){if(target.length===0){throw new Error(`Cannot update root target, caller must do that itself!`)}const targetObject=target.slice(0,-1).reduce(((obj,key)=>obj[key]),obj);const prop=target.slice(-1)[0];if(value===null||typeof value==="undefined"){targetObject instanceof Array?targetObject.splice(prop,1):delete targetObject[prop]}else{targetObject[prop]=value}}function getTargetRef(ref,target){const path=path_info_1.PathInfo.get(ref.path).childPath(target);return new data_reference_1.DataReference(ref.db,path)}function createProxy(context){const targetRef=getTargetRef(context.root.ref,context.target);const childProxies=[];const handler={get(target,prop,receiver){target=getTargetValue(context.root.cache,context.target);if(typeof prop==="symbol"){if(prop.toString()===Symbol.iterator.toString()){prop="values"}else if(prop.toString()===isProxy.toString()){return true}else{return Reflect.get(target,prop,receiver)}}if(prop==="valueOf"){return function valueOf(){return target}}if(target===null||typeof target!=="object"){throw new Error(`Cannot read property "${prop}" of ${target}. Value of path "/${targetRef.path}" is not an object (anymore)`)}if(target instanceof Array&&typeof prop==="string"&&/^[0-9]+$/.test(prop)){prop=parseInt(prop)}const value=target[prop];if(value===null){delete target[prop];return}const childProxy=childProxies.find((proxy=>proxy.prop===prop));if(childProxy){if(childProxy.typeof===typeof value){return childProxy.value}childProxies.splice(childProxies.indexOf(childProxy),1)}const proxifyChildValue=prop=>{const value=target[prop];let childProxy=childProxies.find((child=>child.prop===prop));if(childProxy){if(childProxy.typeof===typeof value){return childProxy.value}childProxies.splice(childProxies.indexOf(childProxy),1)}if(typeof value!=="object"){return value}const newChildProxy=createProxy({root:context.root,target:context.target.concat(prop),id:context.id,flag:context.flag});childProxies.push({typeof:typeof value,prop:prop,value:newChildProxy});return newChildProxy};const unproxyValue=value=>value!==null&&typeof value==="object"&&value[isProxy]?value.getTarget():value;if(["string","number","boolean"].includes(typeof value)||value instanceof Date||value instanceof path_reference_1.PathReference||value instanceof ArrayBuffer||typeof value==="object"&&"buffer"in value){return value}const isArray=target instanceof Array;if(prop==="toString"){return function toString(){return`[LiveDataProxy for "${targetRef.path}"]`}}if(typeof value==="undefined"){if(prop==="push"){return function push(item){const childRef=targetRef.push();context.flag("write",context.target.concat(childRef.key));target[childRef.key]=item;return childRef.key}}if(prop==="getTarget"){return function(warn=true){warn&&console.warn(`Use getTarget with caution - any changes will not be synchronized!`);return target}}if(prop==="getRef"){return function getRef(){const ref=getTargetRef(context.root.ref,context.target);return ref}}if(prop==="forEach"){return function forEach(callback){const keys=Object.keys(target);let stop=false;for(let i=0;!stop&&iproxifyChildValue(key)));if(sortFn){arr.sort(sortFn)}return arr}}if(prop==="onChanged"){return function onChanged(callback){return context.flag("onChange",context.target,{callback:callback})}}if(prop==="subscribe"){return function subscribe(){return context.flag("subscribe",context.target)}}if(prop==="getObservable"){return function getObservable(){return context.flag("observe",context.target)}}if(prop==="getOrderedCollection"){return function getOrderedCollection(orderProperty,orderIncrement){return new OrderedCollectionProxy(this,orderProperty,orderIncrement)}}if(prop==="startTransaction"){return function startTransaction(){return context.flag("transaction",context.target)}}if(prop==="remove"&&!isArray){return function remove(){if(context.target.length===0){throw new Error(`Can't remove proxy root value`)}const parent=getTargetValue(context.root.cache,context.target.slice(0,-1));const key=context.target.slice(-1)[0];context.flag("write",context.target);delete parent[key]}}return}else if(typeof value==="function"){if(isArray){const writeArray=action=>{context.flag("write",context.target);return action()};const cleanArrayValues=values=>values.map((value=>{value=unproxyValue(value);removeVoidProperties(value);return value}));if(prop==="push"){return function push(...items){items=cleanArrayValues(items);return writeArray((()=>target.push(...items)))}}if(prop==="pop"){return function pop(){return writeArray((()=>target.pop()))}}if(prop==="splice"){return function splice(start,deleteCount,...items){items=cleanArrayValues(items);return writeArray((()=>target.splice(start,deleteCount,...items)))}}if(prop==="shift"){return function shift(){return writeArray((()=>target.shift()))}}if(prop==="unshift"){return function unshift(...items){items=cleanArrayValues(items);return writeArray((()=>target.unshift(...items)))}}if(prop==="sort"){return function sort(compareFn){return writeArray((()=>target.sort(compareFn)))}}if(prop==="reverse"){return function reverse(){return writeArray((()=>target.reverse()))}}if(["indexOf","lastIndexOf"].includes(prop)){return function indexOf(item,start){if(item!==null&&typeof item==="object"&&item[isProxy]){item=item.getTarget(false)}return target[prop](item,start)}}if(["forEach","every","some","filter","map"].includes(prop)){return function iterate(callback){return target[prop](((value,i)=>callback(proxifyChildValue(i),i,proxy)))}}if(["reduce","reduceRight"].includes(prop)){return function reduce(callback,initialValue){return target[prop](((prev,value,i)=>callback(prev,proxifyChildValue(i),i,proxy)),initialValue)}}if(["find","findIndex"].includes(prop)){return function find(callback){let value=target[prop](((value,i)=>callback(proxifyChildValue(i),i,proxy)));if(prop==="find"&&value){let index=target.indexOf(value);value=proxifyChildValue(index)}return value}}if(["values","entries","keys"].includes(prop)){return function*generator(){for(let i=0;itypeof key==="number"))){context.flag("write",context.target.slice(0,context.target.findIndex((key=>typeof key==="number"))))}else if(target instanceof Array){context.flag("write",context.target)}else{context.flag("write",context.target.concat(prop))}if(value===null){delete target[prop]}else{removeVoidProperties(value);target[prop]=value}return true},deleteProperty(target,prop){target=getTargetValue(context.root.cache,context.target);if(target===null){throw new Error(`Cannot delete property ${prop.toString()} of null`)}if(typeof prop==="symbol"){return Reflect.deleteProperty(target,prop)}if(!(prop in target)){return true}context.flag("write",context.target.concat(prop));delete target[prop];return true},ownKeys(target){target=getTargetValue(context.root.cache,context.target);return Reflect.ownKeys(target)},has(target,prop){target=getTargetValue(context.root.cache,context.target);return Reflect.has(target,prop)},getOwnPropertyDescriptor(target,prop){target=getTargetValue(context.root.cache,context.target);const descriptor=Reflect.getOwnPropertyDescriptor(target,prop);if(descriptor){descriptor.configurable=true}return descriptor},getPrototypeOf(target){target=getTargetValue(context.root.cache,context.target);return Reflect.getPrototypeOf(target)}};const proxy=new Proxy({},handler);return proxy}function removeVoidProperties(obj){if(typeof obj!=="object"){return}Object.keys(obj).forEach((key=>{const val=obj[key];if(val===null||typeof val==="undefined"){delete obj[key]}else if(typeof val==="object"){removeVoidProperties(val)}}))}function proxyAccess(proxiedValue){if(typeof proxiedValue!=="object"||!proxiedValue[isProxy]){throw new Error(`Given value is not proxied. Make sure you are referencing the value through the live data proxy.`)}return proxiedValue}exports.proxyAccess=proxyAccess;class OrderedCollectionProxy{constructor(collection,orderProperty="order",orderIncrement=10){this.collection=collection;this.orderProperty=orderProperty;this.orderIncrement=orderIncrement;if(typeof collection!=="object"||!collection[isProxy]){throw new Error(`Collection is not proxied`)}if(collection.valueOf()instanceof Array){throw new Error(`Collection is an array, not an object collection`)}if(!Object.keys(collection).every((key=>typeof collection[key]==="object"))){throw new Error(`Collection has non-object children`)}const ok=Object.keys(collection).every((key=>typeof collection[key][orderProperty]==="number"));if(!ok){const keys=Object.keys(collection);for(let i=0;i{const subscription=this.getObservable().subscribe((value=>{const newArray=this.getArray();subscriber.next(newArray)}));return function unsubscribe(){subscription.unsubscribe()}}))}getArray(){const arr=proxyAccess(this.collection).toArray(((a,b)=>a[this.orderProperty]-b[this.orderProperty]));return arr}add(item,index,from){let arr=this.getArray();let minOrder=Number.POSITIVE_INFINITY,maxOrder=Number.NEGATIVE_INFINITY;for(let i=0;ithis.collection[key]===item));if(!fromKey){throw new Error(`item not found in collection`)}if(from===index){return{key:fromKey,index:index}}if(Math.abs(from-index)===1){const otherItem=arr[index];const otherOrder=otherItem[this.orderProperty];otherItem[this.orderProperty]=item[this.orderProperty];item[this.orderProperty]=otherOrder;return{key:fromKey,index:index}}else{arr.splice(from,1)}}if(typeof index!=="number"||index>=arr.length){index=arr.length;item[this.orderProperty]=arr.length==0?0:maxOrder+this.orderIncrement}else if(index===0){item[this.orderProperty]=arr.length==0?0:minOrder-this.orderIncrement}else{const orders=arr.map((item=>item[this.orderProperty]));const gap=orders[index]-orders[index-1];if(gap>1){item[this.orderProperty]=orders[index]-Math.floor(gap/2)}else{arr.splice(index,0,item);for(let i=0;ithis.collection[key]===item));if(!key){throw new Error(`Cannot find target object to delete`)}this.collection[key]=null;return{key:key,index:index}}move(fromIndex,toIndex){const arr=this.getArray();return this.add(arr[fromIndex],toIndex,fromIndex)}sort(sortFn){const arr=this.getArray();arr.sort(sortFn);for(let i=0;i{newContext[key]=context[key]}))}this[_private].context=newContext;return this}else if(typeof context==="undefined"){console.warn(`Use snap.context() instead of snap.ref.context() to get updating context in event callbacks`);return currentContext}else{throw new Error("Invalid context argument")}}get cursor(){return this[_private].cursor}set cursor(value){var _a;this[_private].cursor=value;(_a=this.onCursor)===null||_a===void 0?void 0:_a.call(this,value)}get path(){return this[_private].path}get key(){return this[_private].key}get parent(){let currentPath=path_info_1.PathInfo.fillVariables2(this.path,this.vars);const info=path_info_1.PathInfo.get(currentPath);if(info.parentPath===null){return null}return new DataReference(this.db,info.parentPath).context(this[_private].context)}get vars(){return this[_private].vars}child(childPath){childPath=typeof childPath==="number"?childPath:childPath.replace(/^\/|\/$/g,"");const currentPath=path_info_1.PathInfo.fillVariables2(this.path,this.vars);const targetPath=path_info_1.PathInfo.getChildPath(currentPath,childPath);return new DataReference(this.db,targetPath).context(this[_private].context)}async set(value,onComplete){try{if(this.isWildcardPath){throw new Error(`Cannot set the value of wildcard path "/${this.path}"`)}if(this.parent===null){throw new Error(`Cannot set the root object. Use update, or set individual child properties`)}if(typeof value==="undefined"){throw new TypeError(`Cannot store undefined value in "/${this.path}"`)}if(!this.db.isReady){await this.db.ready()}value=this.db.types.serialize(this.path,value);const{cursor:cursor}=await this.db.api.set(this.path,value,{context:this[_private].context});this.cursor=cursor;if(typeof onComplete==="function"){try{onComplete(null,this)}catch(err){console.error(`Error in onComplete callback:`,err)}}}catch(err){if(typeof onComplete==="function"){try{onComplete(err,this)}catch(err){console.error(`Error in onComplete callback:`,err)}}else{throw err}}return this}async update(updates,onComplete){try{if(this.isWildcardPath){throw new Error(`Cannot update the value of wildcard path "/${this.path}"`)}if(!this.db.isReady){await this.db.ready()}if(typeof updates!=="object"||updates instanceof Array||updates instanceof ArrayBuffer||updates instanceof Date){await this.set(updates)}else if(Object.keys(updates).length===0){console.warn(`update called on path "/${this.path}", but there is nothing to update`)}else{updates=this.db.types.serialize(this.path,updates);const{cursor:cursor}=await this.db.api.update(this.path,updates,{context:this[_private].context});this.cursor=cursor}if(typeof onComplete==="function"){try{onComplete(null,this)}catch(err){console.error(`Error in onComplete callback:`,err)}}}catch(err){if(typeof onComplete==="function"){try{onComplete(err,this)}catch(err){console.error(`Error in onComplete callback:`,err)}}else{throw err}}return this}async transaction(callback){if(this.isWildcardPath){throw new Error(`Cannot start a transaction on wildcard path "/${this.path}"`)}if(!this.db.isReady){await this.db.ready()}let throwError;let cb=currentValue=>{currentValue=this.db.types.deserialize(this.path,currentValue);const snap=new data_snapshot_1.DataSnapshot(this,currentValue);let newValue;try{newValue=callback(snap)}catch(err){throwError=err;return}if(newValue instanceof Promise){return newValue.then((val=>this.db.types.serialize(this.path,val))).catch((err=>{throwError=err;return}))}else{return this.db.types.serialize(this.path,newValue)}};const{cursor:cursor}=await this.db.api.transaction(this.path,cb,{context:this[_private].context});this.cursor=cursor;if(throwError){throw throwError}return this}on(event,callback,cancelCallback){if(this.path===""&&["value","child_changed"].includes(event)){console.warn(`WARNING: Listening for value and child_changed events on the root node is a bad practice. These events require loading of all data (value event), or potentially lots of data (child_changed event) each time they are fired`)}let eventPublisher=null;const eventStream=new subscription_1.EventStream((publisher=>{eventPublisher=publisher}));const cb={event:event,stream:eventStream,userCallback:typeof callback==="function"&&callback,ourCallback:(err,path,newValue,oldValue,eventContext)=>{if(err){this.db.debug.error(`Error getting data for event ${event} on path "${path}"`,err);return}let ref=this.db.ref(path);ref[_private].vars=path_info_1.PathInfo.extractVariables(this.path,path);let callbackObject;if(event.startsWith("notify_")){callbackObject=ref.context(eventContext||{})}else{const values={previous:this.db.types.deserialize(path,oldValue),current:this.db.types.deserialize(path,newValue)};if(event==="child_removed"){callbackObject=new data_snapshot_1.DataSnapshot(ref,values.previous,true,values.previous,eventContext)}else if(event==="mutations"){callbackObject=new data_snapshot_1.MutationsDataSnapshot(ref,values.current,eventContext)}else{const isRemoved=event==="mutated"&&values.current===null;callbackObject=new data_snapshot_1.DataSnapshot(ref,values.current,isRemoved,values.previous,eventContext)}}eventPublisher.publish(callbackObject);if(eventContext===null||eventContext===void 0?void 0:eventContext.acebase_cursor){this.cursor=eventContext.acebase_cursor}}};this[_private].callbacks.push(cb);const subscribe=()=>{if(typeof callback==="function"){eventStream.subscribe(callback,((activated,cancelReason)=>{if(!activated){cancelCallback&&cancelCallback(cancelReason)}}))}const advancedOptions=typeof callback==="object"?callback:{newOnly:!callback};if(typeof advancedOptions.newOnly!=="boolean"){advancedOptions.newOnly=false}if(this.isWildcardPath){advancedOptions.newOnly=true}const cancelSubscription=err=>{let callbacks=this[_private].callbacks;callbacks.splice(callbacks.indexOf(cb),1);this.db.api.unsubscribe(this.path,event,cb.ourCallback);this.db.debug.error(`Subscription "${event}" on path "/${this.path}" canceled because of an error: ${err.message}`);eventPublisher.cancel(err.message)};let authorized=this.db.api.subscribe(this.path,event,cb.ourCallback,{newOnly:advancedOptions.newOnly,cancelCallback:cancelSubscription,syncFallback:advancedOptions.syncFallback});const allSubscriptionsStoppedCallback=()=>{let callbacks=this[_private].callbacks;callbacks.splice(callbacks.indexOf(cb),1);return this.db.api.unsubscribe(this.path,event,cb.ourCallback)};if(authorized instanceof Promise){authorized.then((()=>{eventPublisher.start(allSubscriptionsStoppedCallback)})).catch(cancelSubscription)}else{eventPublisher.start(allSubscriptionsStoppedCallback)}if(!advancedOptions.newOnly){if(event==="value"){this.get((snap=>{eventPublisher.publish(snap)}))}else if(event==="child_added"){this.get((snap=>{const val=snap.val();if(val===null||typeof val!=="object"){return}Object.keys(val).forEach((key=>{let childSnap=new data_snapshot_1.DataSnapshot(this.child(key),val[key]);eventPublisher.publish(childSnap)}))}))}else if(event==="notify_child_added"){const step=100;let limit=step,skip=0;const more=()=>{this.db.api.reflect(this.path,"children",{limit:limit,skip:skip}).then((children=>{children.list.forEach((child=>{const childRef=this.child(child.key);eventPublisher.publish(childRef)}));if(children.more){skip+=step;more()}}))};more()}}};if(this.db.isReady){subscribe()}else{this.db.ready(subscribe)}return eventStream}off(event,callback){const subscriptions=this[_private].callbacks;const stopSubs=subscriptions.filter((sub=>(!event||sub.event===event)&&(!callback||sub.userCallback===callback)));if(stopSubs.length===0){this.db.debug.warn(`Can't find event subscriptions to stop (path: "${this.path}", event: ${event||"(any)"}, callback: ${callback})`)}stopSubs.forEach((sub=>{sub.stream.stop()}));return this}get(optionsOrCallback,callback){if(!this.db.isReady){const promise=this.db.ready().then((()=>this.get(optionsOrCallback,callback)));return typeof optionsOrCallback!=="function"&&typeof callback!=="function"?promise:undefined}callback=typeof optionsOrCallback==="function"?optionsOrCallback:typeof callback==="function"?callback:undefined;if(this.isWildcardPath){const error=new Error(`Cannot get value of wildcard path "/${this.path}". Use .query() instead`);if(typeof callback==="function"){throw error}return Promise.reject(error)}const options=new DataRetrievalOptions(typeof optionsOrCallback==="object"?optionsOrCallback:{cache_mode:"allow"});const promise=this.db.api.get(this.path,options).then((result=>{var _a;const isNewApiResult="context"in result&&"value"in result;if(!isNewApiResult){console.warn(`AceBase api.get method returned an old response value. Update your acebase or acebase-client package`);result={value:result,context:{}}}const value=this.db.types.deserialize(this.path,result.value);const snapshot=new data_snapshot_1.DataSnapshot(this,value,undefined,undefined,result.context);if((_a=result.context)===null||_a===void 0?void 0:_a.acebase_cursor){this.cursor=result.context.acebase_cursor}return snapshot}));if(callback){promise.then(callback).catch((err=>{console.error(`Uncaught error:`,err)}));return}else{return promise}}once(event,options){if(event==="value"&&!this.isWildcardPath){return this.get(options)}return new Promise(((resolve,reject)=>{const callback=snap=>{this.off(event,callback);resolve(snap)};this.on(event,callback)}))}push(value,onComplete){if(this.isWildcardPath){const error=new Error(`Cannot push to wildcard path "/${this.path}"`);if(typeof value==="undefined"||typeof onComplete==="function"){throw error}return Promise.reject(error)}const id=id_1.ID.generate();const ref=this.child(id);ref[_private].pushed=true;if(typeof value!=="undefined"){return ref.set(value,onComplete).then((res=>ref))}else{return ref}}async remove(){if(this.isWildcardPath){throw new Error(`Cannot remove wildcard path "/${this.path}". Use query().remove instead`)}if(this.parent===null){throw new Error(`Cannot remove the root node`)}return this.set(null)}async exists(){if(this.isWildcardPath){throw new Error(`Cannot check wildcard path "/${this.path}" existence`)}if(!this.db.isReady){await this.db.ready()}return this.db.api.exists(this.path)}get isWildcardPath(){return this.path.indexOf("*")>=0||this.path.indexOf("$")>=0}query(){return new DataReferenceQuery(this)}async count(){const info=await this.reflect("info",{child_count:true});return info.children.count}async reflect(type,args){if(this.isWildcardPath){throw new Error(`Cannot reflect on wildcard path "/${this.path}"`)}if(!this.db.isReady){await this.db.ready()}return this.db.api.reflect(this.path,type,args)}async export(write,options={format:"json",type_safe:true}){if(this.isWildcardPath){throw new Error(`Cannot export wildcard path "/${this.path}"`)}if(!this.db.isReady){await this.db.ready()}return this.db.api.export(this.path,write,options)}async import(read,options={format:"json",suppress_events:false}){if(this.isWildcardPath){throw new Error(`Cannot import to wildcard path "/${this.path}"`)}if(!this.db.isReady){await this.db.ready()}return this.db.api.import(this.path,read,options)}proxy(options){const isOptionsArg=typeof options==="object"&&(typeof options.cursor!=="undefined"||typeof options.defaultValue!=="undefined");if(typeof options!=="undefined"&&!isOptionsArg){this.db.debug.warn(`Warning: live data proxy is being initialized with a deprecated method signature. Use ref.proxy(options) instead of ref.proxy(defaultValue)`);options={defaultValue:options}}return data_proxy_1.LiveDataProxy.create(this,options)}observe(options){if(options){throw new Error("observe does not support data retrieval options yet")}if(this.isWildcardPath){throw new Error(`Cannot observe wildcard path "/${this.path}"`)}const Observable=(0,optional_observable_1.getObservable)();return new Observable((observer=>{let cache,resolved=false;let promise=this.get(options).then((snap=>{resolved=true;cache=snap.val();observer.next(cache)}));const updateCache=snap=>{if(!resolved){promise=promise.then((()=>updateCache(snap)));return}const mutatedPath=snap.ref.path;if(mutatedPath===this.path){cache=snap.val();return observer.next(cache)}const trailKeys=path_info_1.PathInfo.getPathKeys(mutatedPath).slice(path_info_1.PathInfo.getPathKeys(this.path).length);let target=cache;while(trailKeys.length>1){const key=trailKeys.shift();if(!(key in target)){target[key]=typeof trailKeys[0]==="number"?[]:{}}target=target[key]}const prop=trailKeys.shift();const newValue=snap.val();if(newValue===null){target instanceof Array&&typeof prop==="number"?target.splice(prop,1):delete target[prop]}else{target[prop]=newValue}observer.next(cache)};this.on("mutated",updateCache);return()=>{this.off("mutated",updateCache)}}))}async forEach(callbackOrOptions,callback){let options;if(typeof callbackOrOptions==="function"){callback=callbackOrOptions}else{options=callbackOrOptions}if(typeof callback!=="function"){throw new TypeError(`No callback function given`)}const info=await this.reflect("children",{limit:0,skip:0});const summary={canceled:false,total:info.list.length,processed:0};for(let i=0;ithis.get(optionsOrCallback,callback)));return typeof optionsOrCallback!=="function"&&typeof callback!=="function"?promise:undefined}callback=typeof optionsOrCallback==="function"?optionsOrCallback:typeof callback==="function"?callback:undefined;const options=new QueryDataRetrievalOptions(typeof optionsOrCallback==="object"?optionsOrCallback:{snapshots:true,cache_mode:"allow"});options.allow_cache=options.cache_mode!=="bypass";options.eventHandler=ev=>{if(!this[_private].events[ev.name]){return false}const listeners=this[_private].events[ev.name];if(typeof listeners!=="object"||listeners.length===0){return false}if(["add","change","remove"].includes(ev.name)){const ref=new DataReference(this.ref.db,ev.path);const eventData={name:ev.name};if(options.snapshots&&ev.name!=="remove"){const val=db.types.deserialize(ev.path,ev.value);eventData.snapshot=new data_snapshot_1.DataSnapshot(ref,val,false)}else{eventData.ref=ref}ev=eventData}listeners.forEach((callback=>{try{callback(ev)}catch(e){}}))};options.monitor={add:false,change:false,remove:false};if(this[_private].events){if(this[_private].events["add"]&&this[_private].events["add"].length>0){options.monitor.add=true}if(this[_private].events["change"]&&this[_private].events["change"].length>0){options.monitor.change=true}if(this[_private].events["remove"]&&this[_private].events["remove"].length>0){options.monitor.remove=true}}this.stop();const db=this.ref.db;return db.api.query(this.ref.path,this[_private],options).catch((err=>{throw new Error(err)})).then((res=>{let{results:results,context:context,stop:stop}=res;this.stop=async()=>{await stop()};if(!("results"in res&&"context"in res)){console.warn(`Query results missing context. Update your acebase and/or acebase-client packages`);results=res,context={}}if(options.snapshots){const snaps=results.map((result=>{const val=db.types.deserialize(result.path,result.val);return new data_snapshot_1.DataSnapshot(db.ref(result.path),val,false,undefined,context)}));return DataSnapshotsArray.from(snaps)}else{const refs=results.map((path=>db.ref(path)));return DataReferencesArray.from(refs)}})).then((results=>{callback&&callback(results);return results}))}async stop(){}getRefs(callback){return this.get({snapshots:false},callback)}find(){return this.get({snapshots:false})}count(){return this.get({snapshots:false}).then((refs=>refs.length))}exists(){return this.count().then((count=>count>0))}remove(callback){const promise=this.get({snapshots:false}).then((refs=>Promise.all(refs.map((ref=>ref.remove().then((()=>({success:true,ref:ref}))).catch((err=>({success:false,error:err,ref:ref})))))).then((results=>{callback&&callback(results);return results}))));if(!callback){return promise}}on(event,callback){if(!this[_private].events[event]){this[_private].events[event]=[]}this[_private].events[event].push(callback);return this}off(event,callback){if(typeof event==="undefined"){this[_private].events={};return this}if(!this[_private].events[event]){return this}if(typeof callback==="undefined"){delete this[_private].events[event];return this}const index=this[_private].events[event].indexOf(callback);if(!~index){return this}this[_private].events[event].splice(index,1);return this}async forEach(callbackOrOptions,callback){let options;if(typeof callbackOrOptions==="function"){callback=callbackOrOptions}else{options=callbackOrOptions}if(typeof callback!=="function"){throw new TypeError(`No callback function given`)}const refs=await this.getRefs();const summary={canceled:false,total:refs.length,processed:0};for(let i=0;iarr[i]=snap));return arr}getValues(){return this.map((snap=>snap.val()))}}exports.DataSnapshotsArray=DataSnapshotsArray;class DataReferencesArray extends Array{static from(refs){const arr=new DataReferencesArray(refs.length);refs.forEach(((ref,i)=>arr[i]=ref));return arr}getPaths(){return this.map((ref=>ref.path))}}exports.DataReferencesArray=DataReferencesArray},{"./data-proxy":25,"./data-snapshot":27,"./id":29,"./optional-observable":32,"./path-info":34,"./subscription":41}],27:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.MutationsDataSnapshot=exports.DataSnapshot=void 0;const path_info_1=require("./path-info");function getChild(snapshot,path,previous=false){if(!snapshot.exists()){return null}let child=previous?snapshot.previous():snapshot.val();if(typeof path==="number"){return child[path]}path_info_1.PathInfo.getPathKeys(path).every((key=>{child=child[key];return typeof child!=="undefined"}));return child||null}function getChildren(snapshot){if(!snapshot.exists()){return[]}let value=snapshot.val();if(value instanceof Array){return new Array(value.length).map(((v,i)=>i))}if(typeof value==="object"){return Object.keys(value)}return[]}class DataSnapshot{constructor(ref,value,isRemoved=false,prevValue,context){this.ref=ref;this.val=()=>value;this.previous=()=>prevValue;this.exists=()=>{if(isRemoved){return false}return value!==null&&typeof value!=="undefined"};this.context=()=>context||{}}val(){}previous(){}exists(){return false}context(){}static for(ref,value){return new DataSnapshot(ref,value)}child(path){let val=getChild(this,path,false);let prev=getChild(this,path,true);return new DataSnapshot(this.ref.child(path),val,false,prev)}hasChild(path){return getChild(this,path)!==null}hasChildren(){return getChildren(this).length>0}numChildren(){return getChildren(this).length}forEach(callback){const value=this.val();const prev=this.previous();return getChildren(this).every(((key,i)=>{const snap=new DataSnapshot(this.ref.child(key),value[key],false,prev[key]);return callback(snap)}))}get key(){return this.ref.key}}exports.DataSnapshot=DataSnapshot;class MutationsDataSnapshot extends DataSnapshot{val(warn=true){return[]}previous(){throw new Error("Iterate values to get previous values for each mutation")}constructor(ref,mutations,context){super(ref,mutations,false,undefined,context);this.val=(warn=true)=>{if(warn){console.warn(`Unless you know what you are doing, it is best not to use the value of a mutations snapshot directly. Use child methods and forEach to iterate the mutations instead`)}return mutations}}forEach(callback){const mutations=this.val();return mutations.every((mutation=>{const ref=mutation.target.reduce(((ref,key)=>ref.child(key)),this.ref);const snap=new DataSnapshot(ref,mutation.val,false,mutation.prev);return callback(snap)}))}child(index){if(typeof index!=="number"){throw new Error(`child index must be a number`)}const mutation=this.val()[index];const ref=mutation.target.reduce(((ref,key)=>ref.child(key)),this.ref);return new DataSnapshot(ref,mutation.val,false,mutation.prev)}}exports.MutationsDataSnapshot=MutationsDataSnapshot},{"./path-info":34}],28:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.DebugLogger=void 0;const process_1=require("./process");class DebugLogger{constructor(level="log",prefix=""){this.prefix=prefix;this.setLevel(level)}setLevel(level){const prefix=this.prefix?this.prefix+" %s":"";this.level=level;this.verbose=["verbose"].includes(level)?prefix?console.log.bind(console,prefix):console.log.bind(console):()=>{};this.log=["verbose","log"].includes(level)?prefix?console.log.bind(console,prefix):console.log.bind(console):()=>{};this.warn=["verbose","log","warn"].includes(level)?prefix?console.warn.bind(console,prefix):console.warn.bind(console):()=>{};this.error=["verbose","log","warn","error"].includes(level)?prefix?console.error.bind(console,prefix):console.error.bind(console):()=>{};this.write=text=>{const isRunKit=typeof process_1.default!=="undefined"&&process_1.default.env&&typeof process_1.default.env.RUNKIT_ENDPOINT_PATH==="string";if(text&&isRunKit){text.split("\n").forEach((line=>console.log(line)))}else{console.log(text)}}}}exports.DebugLogger=DebugLogger},{"./process":36}],29:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ID=void 0;const cuid_1=require("./cuid");let timeBias=0;class ID{static set timeBias(bias){if(typeof bias!=="number"){return}timeBias=bias}static generate(){return(0,cuid_1.default)(timeBias).slice(1)}}exports.ID=ID},{"./cuid":23}],30:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.PartialArray=exports.ObjectCollection=exports.SchemaDefinition=exports.Colorize=exports.ColorStyle=exports.SimpleEventEmitter=exports.proxyAccess=exports.SimpleCache=exports.ascii85=exports.PathInfo=exports.Utils=exports.TypeMappings=exports.Transport=exports.EventSubscription=exports.EventPublisher=exports.EventStream=exports.PathReference=exports.ID=exports.DebugLogger=exports.MutationsDataSnapshot=exports.DataSnapshot=exports.DataReferencesArray=exports.DataSnapshotsArray=exports.QueryDataRetrievalOptions=exports.DataRetrievalOptions=exports.DataReferenceQuery=exports.DataReference=exports.Api=exports.AceBaseBaseSettings=exports.AceBaseBase=void 0;var acebase_base_1=require("./acebase-base");Object.defineProperty(exports,"AceBaseBase",{enumerable:true,get:function(){return acebase_base_1.AceBaseBase}});Object.defineProperty(exports,"AceBaseBaseSettings",{enumerable:true,get:function(){return acebase_base_1.AceBaseBaseSettings}});var api_1=require("./api");Object.defineProperty(exports,"Api",{enumerable:true,get:function(){return api_1.Api}});var data_reference_1=require("./data-reference");Object.defineProperty(exports,"DataReference",{enumerable:true,get:function(){return data_reference_1.DataReference}});Object.defineProperty(exports,"DataReferenceQuery",{enumerable:true,get:function(){return data_reference_1.DataReferenceQuery}});Object.defineProperty(exports,"DataRetrievalOptions",{enumerable:true,get:function(){return data_reference_1.DataRetrievalOptions}});Object.defineProperty(exports,"QueryDataRetrievalOptions",{enumerable:true,get:function(){return data_reference_1.QueryDataRetrievalOptions}});Object.defineProperty(exports,"DataSnapshotsArray",{enumerable:true,get:function(){return data_reference_1.DataSnapshotsArray}});Object.defineProperty(exports,"DataReferencesArray",{enumerable:true,get:function(){return data_reference_1.DataReferencesArray}});var data_snapshot_1=require("./data-snapshot");Object.defineProperty(exports,"DataSnapshot",{enumerable:true,get:function(){return data_snapshot_1.DataSnapshot}});Object.defineProperty(exports,"MutationsDataSnapshot",{enumerable:true,get:function(){return data_snapshot_1.MutationsDataSnapshot}});var debug_1=require("./debug");Object.defineProperty(exports,"DebugLogger",{enumerable:true,get:function(){return debug_1.DebugLogger}});var id_1=require("./id");Object.defineProperty(exports,"ID",{enumerable:true,get:function(){return id_1.ID}});var path_reference_1=require("./path-reference");Object.defineProperty(exports,"PathReference",{enumerable:true,get:function(){return path_reference_1.PathReference}});var subscription_1=require("./subscription");Object.defineProperty(exports,"EventStream",{enumerable:true,get:function(){return subscription_1.EventStream}});Object.defineProperty(exports,"EventPublisher",{enumerable:true,get:function(){return subscription_1.EventPublisher}});Object.defineProperty(exports,"EventSubscription",{enumerable:true,get:function(){return subscription_1.EventSubscription}});exports.Transport=require("./transport");var type_mappings_1=require("./type-mappings");Object.defineProperty(exports,"TypeMappings",{enumerable:true,get:function(){return type_mappings_1.TypeMappings}});exports.Utils=require("./utils");var path_info_1=require("./path-info");Object.defineProperty(exports,"PathInfo",{enumerable:true,get:function(){return path_info_1.PathInfo}});var ascii85_1=require("./ascii85");Object.defineProperty(exports,"ascii85",{enumerable:true,get:function(){return ascii85_1.ascii85}});var simple_cache_1=require("./simple-cache");Object.defineProperty(exports,"SimpleCache",{enumerable:true,get:function(){return simple_cache_1.SimpleCache}});var data_proxy_1=require("./data-proxy");Object.defineProperty(exports,"proxyAccess",{enumerable:true,get:function(){return data_proxy_1.proxyAccess}});var simple_event_emitter_1=require("./simple-event-emitter");Object.defineProperty(exports,"SimpleEventEmitter",{enumerable:true,get:function(){return simple_event_emitter_1.SimpleEventEmitter}});var simple_colors_1=require("./simple-colors");Object.defineProperty(exports,"ColorStyle",{enumerable:true,get:function(){return simple_colors_1.ColorStyle}});Object.defineProperty(exports,"Colorize",{enumerable:true,get:function(){return simple_colors_1.Colorize}});var schema_1=require("./schema");Object.defineProperty(exports,"SchemaDefinition",{enumerable:true,get:function(){return schema_1.SchemaDefinition}});var object_collection_1=require("./object-collection");Object.defineProperty(exports,"ObjectCollection",{enumerable:true,get:function(){return object_collection_1.ObjectCollection}});var partial_array_1=require("./partial-array");Object.defineProperty(exports,"PartialArray",{enumerable:true,get:function(){return partial_array_1.PartialArray}})},{"./acebase-base":19,"./api":20,"./ascii85":21,"./data-proxy":25,"./data-reference":26,"./data-snapshot":27,"./debug":28,"./id":29,"./object-collection":31,"./partial-array":33,"./path-info":34,"./path-reference":35,"./schema":37,"./simple-cache":38,"./simple-colors":39,"./simple-event-emitter":40,"./subscription":41,"./transport":42,"./type-mappings":43,"./utils":44}],31:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ObjectCollection=void 0;const id_1=require("./id");class ObjectCollection{static from(array){const collection={};array.forEach((child=>{collection[id_1.ID.generate()]=child}));return collection}}exports.ObjectCollection=ObjectCollection},{"./id":29}],32:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ObservableShim=exports.setObservable=exports.getObservable=void 0;let _observable;function getObservable(){if(_observable){return _observable}if(typeof window!=="undefined"&&window.Observable){_observable=window.Observable;return _observable}try{const{Observable:Observable}=require("rxjs");if(!Observable){throw new Error("not loaded")}_observable=Observable;return Observable}catch(err){throw new Error(`RxJS Observable could not be loaded. If you are using a browser build, add it to AceBase using db.setObservable. For node.js builds, add it to your project with: npm i rxjs`)}}exports.getObservable=getObservable;function setObservable(Observable){if(Observable==="shim"){console.warn(`Using AceBase's simple Observable shim. Only use this if you know what you're doing.`);Observable=ObservableShim}_observable=Observable}exports.setObservable=setObservable;class ObservableShim{constructor(create){this._active=false;this._subscribers=[];this._create=create}subscribe(subscriber){if(!this._active){const next=value=>{this._subscribers.forEach((s=>{try{s(value)}catch(err){console.error(`Error in subscriber callback:`,err)}}))};const observer={next:next};this._cleanup=this._create(observer);this._active=true}this._subscribers.push(subscriber);const unsubscribe=()=>{this._subscribers.splice(this._subscribers.indexOf(subscriber),1);if(this._subscribers.length===0){this._active=false;this._cleanup()}};const subscription={unsubscribe:unsubscribe};return subscription}}exports.ObservableShim=ObservableShim},{rxjs:2}],33:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.PartialArray=void 0;class PartialArray{constructor(sparseArray){if(sparseArray instanceof Array){for(let i=0;ikey.startsWith("[")?parseInt(key.slice(1,-1)):key))}class PathInfo{constructor(path){if(typeof path==="string"){this.keys=getPathKeys(path)}else if(path instanceof Array){this.keys=path}this.path=this.keys.reduce(((path,key,i)=>i===0?`${key}`:typeof key==="string"?`${path}/${key}`:`${path}[${key}]`),"")}static get(path){return new PathInfo(path)}static getChildPath(path,childKey){return PathInfo.get(path).child(childKey).path}static getPathKeys(path){return getPathKeys(path)}get key(){return this.keys.length===0?null:this.keys.slice(-1)[0]}get parent(){if(this.keys.length==0){return null}const parentKeys=this.keys.slice(0,-1);return new PathInfo(parentKeys)}get parentPath(){return this.keys.length===0?null:this.parent.path}child(childKey){if(typeof childKey==="string"){childKey=getPathKeys(childKey)}return new PathInfo(this.keys.concat(childKey))}childPath(childKey){return this.child(childKey).path}get pathKeys(){return this.keys}static extractVariables(varPath,fullPath){if(!varPath.includes("*")&&!varPath.includes("$")){return[]}const keys=getPathKeys(varPath);const pathKeys=getPathKeys(fullPath);let count=0;const variables={get length(){return count}};keys.forEach(((key,index)=>{const pathKey=pathKeys[index];if(key==="*"){variables[count++]=pathKey}else if(typeof key==="string"&&key[0]==="$"){variables[count++]=pathKey;variables[key]=pathKey;const varName=key.slice(1);if(typeof variables[varName]==="undefined"){variables[varName]=pathKey}}}));return variables}static fillVariables(varPath,fullPath){if(varPath.indexOf("*")<0&&varPath.indexOf("$")<0){return varPath}const keys=getPathKeys(varPath);const pathKeys=getPathKeys(fullPath);let merged=keys.map(((key,index)=>{if(key===pathKeys[index]||index>=pathKeys.length){return key}else if(typeof key==="string"&&(key==="*"||key[0]==="$")){return pathKeys[index]}else{throw new Error(`Path "${fullPath}" cannot be used to fill variables of path "${varPath}" because they do not match`)}}));let mergedPath="";merged.forEach((key=>{if(typeof key==="number"){mergedPath+=`[${key}]`}else{if(mergedPath.length>0){mergedPath+="/"}mergedPath+=key}}));return mergedPath}static fillVariables2(varPath,vars){if(typeof vars!=="object"||Object.keys(vars).length===0){return varPath}let pathKeys=getPathKeys(varPath);let n=0;const targetPath=pathKeys.reduce(((path,key)=>{if(typeof key==="string"&&(key==="*"||key.startsWith("$"))){return PathInfo.getChildPath(path,vars[n++])}else{return PathInfo.getChildPath(path,key)}}),"");return targetPath}equals(otherPath){const other=otherPath instanceof PathInfo?otherPath:new PathInfo(otherPath);if(this.path===other.path){return true}if(this.keys.length!==other.keys.length){return false}return this.keys.every(((key,index)=>{const otherKey=other.keys[index];return otherKey===key||typeof otherKey==="string"&&(otherKey==="*"||otherKey[0]==="$")||typeof key==="string"&&(key==="*"||key[0]==="$")}))}isAncestorOf(descendantPath){const descendant=descendantPath instanceof PathInfo?descendantPath:new PathInfo(descendantPath);if(descendant.path===""||this.path===descendant.path){return false}if(this.path===""){return true}if(this.keys.length>=descendant.keys.length){return false}return this.keys.every(((key,index)=>{const otherKey=descendant.keys[index];return otherKey===key||typeof otherKey==="string"&&(otherKey==="*"||otherKey[0]==="$")||typeof key==="string"&&(key==="*"||key[0]==="$")}))}isDescendantOf(ancestorPath){const ancestor=ancestorPath instanceof PathInfo?ancestorPath:new PathInfo(ancestorPath);if(this.path===""||this.path===ancestor.path){return false}if(ancestorPath===""){return true}if(ancestor.keys.length>=this.keys.length){return false}return ancestor.keys.every(((key,index)=>{const otherKey=this.keys[index];return otherKey===key||typeof otherKey==="string"&&(otherKey==="*"||otherKey[0]==="$")||typeof key==="string"&&(key==="*"||key[0]==="$")}))}isOnTrailOf(otherPath){const other=otherPath instanceof PathInfo?otherPath:new PathInfo(otherPath);if(this.path.length===0||other.path.length===0){return true}if(this.path===other.path){return true}return this.pathKeys.every(((key,index)=>{if(index>=other.keys.length){return true}const otherKey=other.keys[index];return otherKey===key||typeof otherKey==="string"&&(otherKey==="*"||otherKey[0]==="$")||typeof key==="string"&&(key==="*"||key[0]==="$")}))}isChildOf(otherPath){const other=otherPath instanceof PathInfo?otherPath:new PathInfo(otherPath);if(this.path===""){return false}return this.parent.equals(other)}isParentOf(otherPath){const other=otherPath instanceof PathInfo?otherPath:new PathInfo(otherPath);if(other.path===""){return false}return this.equals(other.parent)}}exports.PathInfo=PathInfo},{}],35:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.PathReference=void 0;class PathReference{constructor(path){this.path=path}}exports.PathReference=PathReference},{}],36:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default={nextTick(fn){setTimeout(fn,0)}}},{}],37:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SchemaDefinition=void 0;function parse(definition){let pos=0;function consumeSpaces(){let c;while(c=definition[pos],[" ","\r","\n","\t"].includes(c)){pos++}}function consumeCharacter(c){if(definition[pos]!==c){throw new Error(`Unexpected character at position ${pos}. Expected: '${c}', found '${definition[pos]}'`)}pos++}function readProperty(){consumeSpaces();let prop={name:"",optional:false,wildcard:false},c;while(c=definition[pos],c==="_"||c==="$"||c>="a"&&c<="z"||c>="A"&&c<="Z"||prop.name.length>0&&c>="0"&&c<="9"||prop.name.length===0&&c==="*"){prop.name+=c;pos++}if(prop.name.length===0){throw new Error(`Property name expected at position ${pos}, found: ${definition.slice(pos,pos+10)}..`)}if(definition[pos]==="?"){prop.optional=true;pos++}if(prop.name==="*"||prop.name[0]==="$"){prop.optional=true;prop.wildcard=true}consumeSpaces();consumeCharacter(":");return prop}function readType(){consumeSpaces();let type={typeOf:"any"},c;let name="";while(c=definition[pos],c>="a"&&c<="z"||c>="A"&&c<="Z"){name+=c;pos++}if(name.length===0){if(definition[pos]==="*"){consumeCharacter("*");type.typeOf="any"}else if([`'`,`"`,"`"].includes(definition[pos])){type.typeOf="string";type.value="";const quote=definition[pos];consumeCharacter(quote);while(c=definition[pos],c&&c!==quote){type.value+=c;pos++}consumeCharacter(quote)}else if(definition[pos]>="0"&&definition[pos]<="9"){type.typeOf="number";let nr="";while(c=definition[pos],c==="."||c>="0"&&c<="9"){nr+=c;pos++}type.value=nr.includes(".")?parseFloat(nr):parseInt(nr)}else if(definition[pos]==="{"){consumeCharacter("{");type.typeOf="object";type.instanceOf=Object;type.children=[];while(true){const prop=readProperty();const types=readTypes();type.children.push({name:prop.name,optional:prop.optional,wildcard:prop.wildcard,types:types});consumeSpaces();if(definition[pos]==="}"){break}consumeCharacter(",")}consumeCharacter("}")}else if(definition[pos]==="/"){consumeCharacter("/");let pattern="",flags="";while(c=definition[pos],c!=="/"||pattern.endsWith("\\")){pattern+=c;pos++}consumeCharacter("/");while(c=definition[pos],["g","i","m","s","u","y","d"].includes(c)){flags+=c;pos++}type.typeOf="string";type.matches=new RegExp(pattern,flags)}else{throw new Error(`Expected a type definition at position ${pos}, found character '${definition[pos]}'`)}}else if(["string","number","boolean","undefined","String","Number","Boolean"].includes(name)){type.typeOf=name.toLowerCase()}else if(name==="Object"||name==="object"){type.typeOf="object";type.instanceOf=Object}else if(name==="Date"){type.typeOf="object";type.instanceOf=Date}else if(name==="Binary"||name==="binary"){type.typeOf="object";type.instanceOf=ArrayBuffer}else if(name==="any"){type.typeOf="any"}else if(name==="null"){type.typeOf="object";type.value=null}else if(name==="Array"){consumeCharacter("<");type.typeOf="object";type.instanceOf=Array;type.genericTypes=readTypes();consumeCharacter(">")}else if(["true","false"].includes(name)){type.typeOf="boolean";type.value=name==="true"}else{throw new Error(`Unknown type at position ${pos}: "${type}"`)}consumeSpaces();while(definition[pos]==="["){consumeCharacter("[");consumeCharacter("]");type={typeOf:"object",instanceOf:Array,genericTypes:[type]}}return type}function readTypes(){consumeSpaces();const types=[readType()];while(definition[pos]==="|"){consumeCharacter("|");types.push(readType());consumeSpaces()}return types}return readType()}function checkObject(path,properties,obj,partial){const invalidProperties=properties.find((prop=>prop.name==="*"||prop.name[0]==="$"))?[]:Object.keys(obj).filter((key=>![null,undefined].includes(obj[key])&&!properties.find((prop=>prop.name===key))));if(invalidProperties.length>0){return{ok:false,reason:`Object at path "${path}" cannot have propert${invalidProperties.length===1?"y":"ies"} ${invalidProperties.map((p=>`"${p}"`)).join(", ")}`}}function checkProperty(property){const hasValue=![null,undefined].includes(obj[property.name]);if(!property.optional&&(partial?obj[property.name]===null:!hasValue)){return{ok:false,reason:`Property at path "${path}/${property.name}" is not optional`}}if(hasValue&&property.types.length===1){return checkType(`${path}/${property.name}`,property.types[0],obj[property.name],false)}if(hasValue&&!property.types.some((type=>checkType(`${path}/${property.name}`,type,obj[property.name],false).ok))){return{ok:false,reason:`Property at path "${path}/${property.name}" does not match any of ${property.types.length} allowed types`}}return{ok:true}}const namedProperties=properties.filter((prop=>!prop.wildcard));const failedProperty=namedProperties.find((prop=>!checkProperty(prop).ok));if(failedProperty){const reason=checkProperty(failedProperty).reason;return{ok:false,reason:reason}}const wildcardProperty=properties.find((prop=>prop.wildcard));if(!wildcardProperty){return{ok:true}}const wildcardChildKeys=Object.keys(obj).filter((key=>!namedProperties.find((prop=>prop.name===key))));let result={ok:true};for(let i=0;i0){if(type.typeOf!=="object"){return{ok:false,reason:`path "${path}" must be typeof ${type.typeOf}`}}if(!type.children){return ok}const childKey=trailKeys[0];let property=type.children.find((prop=>prop.name===childKey));if(!property){property=type.children.find((prop=>prop.name==="*"||prop.name[0]==="$"))}if(!property){return{ok:false,reason:`Object at path "${path}" cannot have property "${childKey}"`}}if(property.optional&&value===null&&trailKeys.length===1){return ok}let result;property.types.some((type=>{const childPath=typeof childKey==="number"?`${path}[${childKey}]`:`${path}/${childKey}`;result=checkType(childPath,type,value,partial,trailKeys.slice(1));return result.ok}));return result}if(value===null){return ok}if(type.instanceOf===Object&&(typeof value!=="object"||value instanceof Array||value instanceof Date)){return{ok:false,reason:`path "${path}" must be an object collection`}}if(type.instanceOf&&(typeof value!=="object"||value.constructor!==type.instanceOf)){return{ok:false,reason:`path "${path}" must be an instance of ${type.instanceOf.name}`}}if("value"in type&&value!==type.value){return{ok:false,reason:`path "${path}" must be value: ${type.value}`}}if(typeof value!==type.typeOf){return{ok:false,reason:`path "${path}" must be typeof ${type.typeOf}`}}if(type.instanceOf===Array&&type.genericTypes&&!value.every((v=>type.genericTypes.some((t=>checkType(path,t,v,false).ok))))){return{ok:false,reason:`every array value of path "${path}" must match one of the specified types`}}if(type.typeOf==="object"&&type.children){return checkObject(path,type.children,value,partial)}if(type.matches&&!type.matches.test(value)){return{ok:false,reason:`path "${path}" must match regular expression /${type.matches.source}/${type.matches.flags}`}}return ok}function getConstructorType(val){switch(val){case String:return"string";case Number:return"number";case Boolean:return"boolean";case Date:return"Date";case Array:throw new Error(`Schema error: Array cannot be used without a type. Use string[] or Array instead`);default:throw new Error(`Schema error: unknown type used: ${val.name}`)}}class SchemaDefinition{constructor(definition){this.source=definition;if(typeof definition==="object"){const toTS=obj=>"{"+Object.keys(obj).map((key=>{let val=obj[key];if(val===undefined){val="undefined"}else if(val instanceof RegExp){val=`/${val.source}/${val.flags}`}else if(typeof val==="object"){val=toTS(val)}else if(typeof val==="function"){val=getConstructorType(val)}else if(!["string","number","boolean"].includes(typeof val)){throw new Error(`Type definition for key "${key}" must be a string, number, boolean, object, regular expression, or one of these classes: String, Number, Boolean, Date`)}return`${key}:${val}`})).join(",")+"}";this.text=toTS(definition)}else if(typeof definition==="string"){this.text=definition}else{throw new Error(`Type definiton must be a string or an object`)}this.type=parse(this.text)}check(path,value,partial,trailKeys){return checkType(path,this.type,value,partial,trailKeys)}}exports.SchemaDefinition=SchemaDefinition},{}],38:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SimpleCache=void 0;const utils_1=require("./utils");const calculateExpiryTime=expirySeconds=>expirySeconds>0?Date.now()+expirySeconds*1e3:Infinity;class SimpleCache{constructor(options){var _a;this.enabled=true;if(typeof options==="number"){options={expirySeconds:options}}options.cloneValues=options.cloneValues!==false;if(typeof options.expirySeconds!=="number"&&typeof options.maxEntries!=="number"){throw new Error(`Either expirySeconds or maxEntries must be specified`)}this.options=options;this.cache=new Map;const interval=setInterval((()=>{this.cleanUp()}),60*1e3);(_a=interval.unref)===null||_a===void 0?void 0:_a.call(interval)}get size(){return this.cache.size}has(key){if(!this.enabled){return false}return this.cache.has(key)}get(key){if(!this.enabled){return null}const entry=this.cache.get(key);if(!entry){return null}entry.expires=calculateExpiryTime(this.options.expirySeconds);entry.accessed=Date.now();return this.options.cloneValues?(0,utils_1.cloneObject)(entry.value):entry.value}set(key,value){if(this.options.maxEntries>0&&this.cache.size>=this.options.maxEntries&&!this.cache.has(key)){let oldest=null;const now=Date.now();for(let[key,entry]of this.cache.entries()){if(entry.expires<=now){this.cache.delete(key);oldest=null;break}if(!oldest||entry.accessed{if(entry.expires<=now){this.cache.delete(key)}}))}}exports.SimpleCache=SimpleCache},{"./utils":44}],39:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Colorize=exports.SetColorsEnabled=exports.ColorsSupported=exports.ColorStyle=void 0;const process_1=require("./process");const FontCode={bold:1,dim:2,italic:3,underline:4,inverse:7,hidden:8,strikethrough:94};const ColorCode={black:30,red:31,green:32,yellow:33,blue:34,magenta:35,cyan:36,white:37,grey:90,brightRed:91};const BgColorCode={bgBlack:40,bgRed:41,bgGreen:42,bgYellow:43,bgBlue:44,bgMagenta:45,bgCyan:46,bgWhite:47,bgGrey:100,bgBrightRed:101};const ResetCode={all:0,color:39,background:49,bold:22,dim:22,italic:23,underline:24,inverse:27,hidden:28,strikethrough:29};var ColorStyle;(function(ColorStyle){ColorStyle["reset"]="reset";ColorStyle["bold"]="bold";ColorStyle["dim"]="dim";ColorStyle["italic"]="italic";ColorStyle["underline"]="underline";ColorStyle["inverse"]="inverse";ColorStyle["hidden"]="hidden";ColorStyle["strikethrough"]="strikethrough";ColorStyle["black"]="black";ColorStyle["red"]="red";ColorStyle["green"]="green";ColorStyle["yellow"]="yellow";ColorStyle["blue"]="blue";ColorStyle["magenta"]="magenta";ColorStyle["cyan"]="cyan";ColorStyle["grey"]="grey";ColorStyle["bgBlack"]="bgBlack";ColorStyle["bgRed"]="bgRed";ColorStyle["bgGreen"]="bgGreen";ColorStyle["bgYellow"]="bgYellow";ColorStyle["bgBlue"]="bgBlue";ColorStyle["bgMagenta"]="bgMagenta";ColorStyle["bgCyan"]="bgCyan";ColorStyle["bgWhite"]="bgWhite";ColorStyle["bgGrey"]="bgGrey"})(ColorStyle=exports.ColorStyle||(exports.ColorStyle={}));function ColorsSupported(){if(typeof process_1.default==="undefined"||!process_1.default.stdout||!process_1.default.env||!process_1.default.platform||process_1.default.platform==="browser"){return false}if(process_1.default.platform==="win32"){return true}const env=process_1.default.env;if(env.COLORTERM){return true}if(env.TERM==="dumb"){return false}if(env.CI||env.TEAMCITY_VERSION){return!!env.TRAVIS}if(["iTerm.app","HyperTerm","Hyper","MacTerm","Apple_Terminal","vscode"].includes(env.TERM_PROGRAM)){return true}if(/^xterm-256|^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(env.TERM)){return true}return false}exports.ColorsSupported=ColorsSupported;let _enabled=ColorsSupported();function SetColorsEnabled(enabled){_enabled=ColorsSupported()&&enabled}exports.SetColorsEnabled=SetColorsEnabled;function Colorize(str,style){if(!_enabled){return str}const openCodes=[],closeCodes=[];const addStyle=style=>{if(style===ColorStyle.reset){openCodes.push(ResetCode.all)}else if(style in FontCode){openCodes.push(FontCode[style]);closeCodes.push(ResetCode[style])}else if(style in ColorCode){openCodes.push(ColorCode[style]);closeCodes.push(ResetCode.color)}else if(style in BgColorCode){openCodes.push(BgColorCode[style]);closeCodes.push(ResetCode.background)}};if(style instanceof Array){style.forEach(addStyle)}else{addStyle(style)}const open=openCodes.map((code=>"["+code+"m")).join("");const close=closeCodes.map((code=>"["+code+"m")).join("");return str.split("\n").map((line=>open+line+close)).join("\n")}exports.Colorize=Colorize;String.prototype.colorize=function(style){return Colorize(this,style)}},{"./process":36}],40:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SimpleEventEmitter=void 0;function runCallback(callback,data){try{callback(data)}catch(err){console.error(`Error in subscription callback`,err)}}class SimpleEventEmitter{constructor(){this._subscriptions=[];this._oneTimeEvents=new Map}on(event,callback){if(this._oneTimeEvents.has(event)){return runCallback(callback,this._oneTimeEvents.get(event))}this._subscriptions.push({event:event,callback:callback,once:false});return this}off(event,callback){this._subscriptions=this._subscriptions.filter((s=>s.event!==event||callback&&s.callback!==callback));return this}once(event,callback){let resolve;let promise=new Promise((rs=>{if(!callback){resolve=rs}else{resolve=data=>{rs(data);callback(data)}}}));if(this._oneTimeEvents.has(event)){runCallback(resolve,this._oneTimeEvents.get(event))}else{this._subscriptions.push({event:event,callback:resolve,once:true})}return promise}emit(event,data){if(this._oneTimeEvents.has(event)){throw new Error(`Event "${event}" was supposed to be emitted only once`)}for(let i=0;i{if(this._internal.state==="active"){return resolve()}else if(this._internal.state==="canceled"&&!callback){return reject(new Error(this._internal.cancelReason))}this._internal.activatePromises.push({resolve:resolve,reject:callback?()=>{}:reject})}))}_setActivationState(activated,cancelReason){this._internal.cancelReason=cancelReason;this._internal.state=activated?"active":"canceled";while(this._internal.activatePromises.length>0){const p=this._internal.activatePromises.shift();if(activated){p.callback&&p.callback(true);p.resolve&&p.resolve()}else{p.callback&&p.callback(false,cancelReason);p.reject&&p.reject(cancelReason)}}}}exports.EventSubscription=EventSubscription;class EventPublisher{constructor(publish,start,cancel){this.publish=publish;this.start=start;this.cancel=cancel}}exports.EventPublisher=EventPublisher;class EventStream{constructor(eventPublisherCallback){const subscribers=[];let noMoreSubscribersCallback;let activationState;const _stoppedState="stopped (no more subscribers)";this.subscribe=(callback,activationCallback)=>{if(typeof callback!=="function"){throw new TypeError("callback must be a function")}else if(activationState===_stoppedState){throw new Error("stream can't be used anymore because all subscribers were stopped")}const sub={callback:callback,activationCallback:function(activated,cancelReason){activationCallback&&activationCallback(activated,cancelReason);this.subscription._setActivationState(activated,cancelReason)},subscription:new EventSubscription((function stop(){subscribers.splice(subscribers.indexOf(this),1);return checkActiveSubscribers()}))};subscribers.push(sub);if(typeof activationState!=="undefined"){if(activationState===true){activationCallback&&activationCallback(true);sub.subscription._setActivationState(true)}else if(typeof activationState==="string"){activationCallback&&activationCallback(false,activationState);sub.subscription._setActivationState(false,activationState)}}return sub.subscription};const checkActiveSubscribers=()=>{let ret;if(subscribers.length===0){ret=noMoreSubscribersCallback&&noMoreSubscribersCallback();activationState=_stoppedState}return Promise.resolve(ret)};this.unsubscribe=callback=>{const remove=callback?subscribers.filter((sub=>sub.callback===callback)):subscribers;remove.forEach((sub=>{const i=subscribers.indexOf(sub);subscribers.splice(i,1)}));checkActiveSubscribers()};this.stop=()=>{subscribers.splice(0);checkActiveSubscribers()};const publish=val=>{subscribers.forEach((sub=>{try{sub.callback(val)}catch(err){console.error(`Error running subscriber callback: ${err.message}`)}}));if(subscribers.length===0){checkActiveSubscribers()}return subscribers.length>0};const start=allSubscriptionsStoppedCallback=>{activationState=true;noMoreSubscribersCallback=allSubscriptionsStoppedCallback;subscribers.forEach((sub=>{sub.activationCallback&&sub.activationCallback(true)}))};const cancel=reason=>{activationState=reason;subscribers.forEach((sub=>{sub.activationCallback&&sub.activationCallback(false,reason||new Error("unknown reason"))}));subscribers.splice(0)};const publisher=new EventPublisher(publish,start,cancel);eventPublisherCallback(publisher)}}exports.EventStream=EventStream},{}],42:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.deserialize2=exports.serialize2=exports.serialize=exports.detectSerializeVersion=exports.deserialize=void 0;const path_reference_1=require("./path-reference");const utils_1=require("./utils");const ascii85_1=require("./ascii85");const path_info_1=require("./path-info");const partial_array_1=require("./partial-array");const deserialize=data=>{if(data.map===null||typeof data.map==="undefined"){if(typeof data.val==="undefined"){throw new Error(`serialized value must have a val property`)}return data.val}const deserializeValue=(type,val)=>{if(type==="date"){return new Date(val)}else if(type==="binary"){return ascii85_1.ascii85.decode(val)}else if(type==="reference"){return new path_reference_1.PathReference(val)}else if(type==="regexp"){return new RegExp(val.pattern,val.flags)}else if(type==="array"){return new partial_array_1.PartialArray(val)}return val};if(typeof data.map==="string"){return deserializeValue(data.map,data.val)}Object.keys(data.map).forEach((path=>{const type=data.map[path];const keys=path_info_1.PathInfo.getPathKeys(path);let parent=data;let key="val";let val=data.val;keys.forEach((k=>{key=k;parent=val;val=val[key]}));parent[key]=deserializeValue(type,val)}));return data.val};exports.deserialize=deserialize;const detectSerializeVersion=data=>{if(typeof data!=="object"||data===null){return 2}if("map"in data&&"val"in data){return 1}else if("val"in data){if(Object.keys(data).length>1){return 2}return 1}return 2};exports.detectSerializeVersion=detectSerializeVersion;const serialize=obj=>{var _a;if(obj===null||typeof obj!=="object"||obj instanceof Date||obj instanceof ArrayBuffer||obj instanceof path_reference_1.PathReference||obj instanceof RegExp){const ser=(0,exports.serialize)({value:obj});return{map:(_a=ser.map)===null||_a===void 0?void 0:_a.value,val:ser.val.value}}obj=(0,utils_1.cloneObject)(obj);const process=(obj,mappings,prefix)=>{if(obj instanceof partial_array_1.PartialArray){mappings[prefix]="array"}Object.keys(obj).forEach((key=>{const val=obj[key];const path=prefix.length===0?key:`${prefix}/${key}`;if(val instanceof Date){obj[key]=val.toISOString();mappings[path]="date"}else if(val instanceof ArrayBuffer){obj[key]=ascii85_1.ascii85.encode(val);mappings[path]="binary"}else if(val instanceof path_reference_1.PathReference){obj[key]=val.path;mappings[path]="reference"}else if(val instanceof RegExp){obj[key]={pattern:val.source,flags:val.flags};mappings[path]="regexp"}else if(typeof val==="object"&&val!==null){process(val,mappings,path)}}))};const mappings={};process(obj,mappings,"");const serialized={val:obj};if(Object.keys(mappings).length>0){serialized.map=mappings}return serialized};exports.serialize=serialize;const serialize2=obj=>{const getSerializedValue=val=>{if(val instanceof Date){return{".type":"date",".val":val.toISOString()}}else if(val instanceof ArrayBuffer){return{".type":"binary",".val":ascii85_1.ascii85.encode(val)}}else if(val instanceof path_reference_1.PathReference){return{".type":"reference",".val":val.path}}else if(val instanceof RegExp){return{".type":"regexp",".val":`/${val.source}/${val.flags}`}}else if(typeof val==="object"&&val!==null){if(val instanceof Array){const copy=[];for(let i=0;i{if(typeof data!=="object"||data===null){return data}switch(data[".type"]){case undefined:{if(data instanceof Array){const copy=[];const arr=data;for(let i=0;i{const mkeys=path_info_1.PathInfo.getPathKeys(mpath);if(mkeys.length!==keys.length){return false}return mkeys.every(((mkey,index)=>{if(mkey==="*"||mkey[0]==="$"){return true}return mkey===keys[index]}))}));const mapping=mappings[mappedPath];return mapping}function map(mappings,path){const targetPath=path_info_1.PathInfo.get(path).parentPath;if(targetPath===null){return}return get(mappings,targetPath)}function mapDeep(mappings,entryPath){entryPath=entryPath.replace(/^\/|\/$/g,"");const pathInfo=path_info_1.PathInfo.get(entryPath);const startPath=pathInfo.parentPath;const keys=startPath?path_info_1.PathInfo.getPathKeys(startPath):[];const matches=Object.keys(mappings).reduce(((m,mpath)=>{const mkeys=path_info_1.PathInfo.getPathKeys(mpath);if(mkeys.length{if(index>=keys.length){return false}else if(mkey==="*"||mkey[0]==="$"||mkey===keys[index]){return true}else{isMatch=false;return false}}))}if(isMatch){const mapping=mappings[mpath];m.push({path:mpath,type:mapping})}return m}),[]);return matches}function process(db,mappings,path,obj,action){if(obj===null||typeof obj!=="object"){return obj}const keys=path_info_1.PathInfo.getPathKeys(path);const m=mapDeep(mappings,path);const changes=[];m.sort(((a,b)=>path_info_1.PathInfo.getPathKeys(a.path).length>path_info_1.PathInfo.getPathKeys(b.path).length?-1:1));m.forEach((mapping=>{const mkeys=path_info_1.PathInfo.getPathKeys(mapping.path);mkeys.push("*");const mTrailKeys=mkeys.slice(keys.length);if(mTrailKeys.length===0){const vars=path_info_1.PathInfo.extractVariables(mapping.path,path);const ref=new data_reference_1.DataReference(db,path,vars);if(action==="serialize"){obj=mapping.type.serialize(obj,ref)}else if(action==="deserialize"){const snap=new data_snapshot_1.DataSnapshot(ref,obj);obj=mapping.type.deserialize(snap)}return}const process=(parentPath,parent,keys)=>{if(obj===null||typeof obj!=="object"){return obj}const key=keys[0];let children=[];if(key==="*"||key[0]==="$"){if(parent instanceof Array){children=parent.map(((val,index)=>({key:index,val:val})))}else{children=Object.keys(parent).map((k=>({key:k,val:parent[k]})))}}else{const child=parent[key];if(typeof child==="object"){children.push({key:key,val:child})}}children.forEach((child=>{const childPath=path_info_1.PathInfo.getChildPath(parentPath,child.key);const vars=path_info_1.PathInfo.extractVariables(mapping.path,childPath);const ref=new data_reference_1.DataReference(db,childPath,vars);if(keys.length===1){if(action==="serialize"){changes.push({parent:parent,key:child.key,original:parent[child.key]});parent[child.key]=mapping.type.serialize(child.val,ref)}else if(action==="deserialize"){const snap=new data_snapshot_1.DataSnapshot(ref,child.val);parent[child.key]=mapping.type.deserialize(snap)}}else{process(childPath,child.val,keys.slice(1))}}))};process(path,obj,mTrailKeys)}));if(action==="serialize"){obj=(0,utils_1.cloneObject)(obj);if(changes.length>0){changes.forEach((change=>{change.parent[change.key]=change.original}))}}return obj}const _mappings=Symbol("mappings");class TypeMappings{constructor(db){this.db=db;this[_mappings]={}}get mappings(){return this[_mappings]}map(path){return map(this[_mappings],path)}bind(path,type,options={}){if(typeof path!=="string"){throw new TypeError("path must be a string")}if(typeof type!=="function"){throw new TypeError("constructor must be a function")}if(typeof options.serializer==="undefined"){}else if(typeof options.serializer==="string"){if(typeof type.prototype[options.serializer]==="function"){options.serializer=type.prototype[options.serializer]}else{throw new TypeError(`${type.name}.prototype.${options.serializer} is not a function, cannot use it as serializer`)}}else if(typeof options.serializer!=="function"){throw new TypeError(`serializer for class ${type.name} must be a function, or the name of a prototype method`)}if(typeof options.creator==="undefined"){if(typeof type.create==="function"){options.creator=type.create}}else if(typeof options.creator==="string"){if(typeof type[options.creator]==="function"){options.creator=type[options.creator]}else{throw new TypeError(`${type.name}.${options.creator} is not a function, cannot use it as creator`)}}else if(typeof options.creator!=="function"){throw new TypeError(`creator for class ${type.name} must be a function, or the name of a static method`)}path=path.replace(/^\/|\/$/g,"");this[_mappings][path]={db:this.db,type:type,creator:options.creator,serializer:options.serializer,deserialize(snap){let obj;if(this.creator){obj=this.creator.call(this.type,snap)}else{obj=new this.type(snap)}return obj},serialize(obj,ref){if(this.serializer){obj=this.serializer.call(obj,ref,obj)}else if(obj&&typeof obj.serialize==="function"){obj=obj.serialize(ref,obj)}return obj}}}serialize(path,obj){return process(this.db,this[_mappings],path,obj,"serialize")}deserialize(path,obj){return process(this.db,this[_mappings],path,obj,"deserialize")}}exports.TypeMappings=TypeMappings},{"./data-reference":26,"./data-snapshot":27,"./path-info":34,"./utils":44}],44:[function(require,module,exports){(function(Buffer){(function(){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.defer=exports.getChildValues=exports.getMutations=exports.compareValues=exports.ObjectDifferences=exports.valuesAreEqual=exports.cloneObject=exports.concatTypedArrays=exports.decodeString=exports.encodeString=exports.bytesToNumber=exports.numberToBytes=void 0;const path_reference_1=require("./path-reference");const process_1=require("./process");const partial_array_1=require("./partial-array");function numberToBytes(number){const bytes=new Uint8Array(8);const view=new DataView(bytes.buffer);view.setFloat64(0,number);return new Array(...bytes)}exports.numberToBytes=numberToBytes;function bytesToNumber(bytes){if(bytes.length<8){throw new TypeError("must be 8 bytes")}const bin=new Uint8Array(bytes);const view=new DataView(bin.buffer);const nr=view.getFloat64(0);return nr}exports.bytesToNumber=bytesToNumber;function encodeString(str){if(typeof TextEncoder!=="undefined"){const encoder=new TextEncoder;return encoder.encode(str)}else if(typeof Buffer==="function"){const buf=Buffer.from(str,"utf-8");return new Uint8Array(buf.buffer,buf.byteOffset,buf.byteLength)}else{let arr=[];for(let i=0;i128){if((code&55296)===55296){const nextCode=str.charCodeAt(i+1);if((nextCode&56320)!==56320){throw new Error("follow-up utf-16 character does not start with 0xDC00")}i++;const p1=code&1023;const p2=nextCode&1023;code=65536|p1<<10|p2}if(code<2048){const b1=192|code>>6&31;const b2=128|code&63;arr.push(b1,b2)}else if(code<65536){const b1=224|code>>12&15;const b2=128|code>>6&63;const b3=128|code&63;arr.push(b1,b2,b3)}else if(code<2097152){const b1=240|code>>18&7;const b2=128|code>>12&63;const b3=128|code>>6&63;const b4=128|code&63;arr.push(b1,b2,b3,b4)}else{throw new Error(`Cannot convert character ${str.charAt(i)} (code ${code}) to utf-8`)}}else{arr.push(code<128?code:63)}}return new Uint8Array(arr)}}exports.encodeString=encodeString;function decodeString(buffer){if(typeof TextDecoder!=="undefined"){const decoder=new TextDecoder;if(buffer instanceof Uint8Array){return decoder.decode(buffer)}const buf=Uint8Array.from(buffer);return decoder.decode(buf)}else if(typeof Buffer==="function"){if(buffer instanceof Array){buffer=Uint8Array.from(buffer)}if(!(buffer instanceof Buffer)&&"buffer"in buffer&&buffer.buffer instanceof ArrayBuffer){buffer=Buffer.from(buffer.buffer,buffer.byteOffset,buffer.byteLength)}if(!(buffer instanceof Buffer)){throw new Error(`Unsupported buffer argument`)}return buffer.toString("utf-8")}else{if(!(buffer instanceof Uint8Array)&&"buffer"in buffer&&buffer["buffer"]instanceof ArrayBuffer){buffer=new Uint8Array(buffer["buffer"],buffer.byteOffset,buffer.byteLength)}if(buffer instanceof Buffer||buffer instanceof Array||buffer instanceof Uint8Array){let str="";for(let i=0;i128){if((code&240)===240){const b1=code,b2=buffer[i+1],b3=buffer[i+2],b4=buffer[i+3];code=(b1&7)<<18|(b2&63)<<12|(b3&63)<<6|b4&63;i+=3}else if((code&224)===224){const b1=code,b2=buffer[i+1],b3=buffer[i+2];code=(b1&15)<<12|(b2&63)<<6|b3&63;i+=2}else if((code&192)===192){const b1=code,b2=buffer[i+1];code=(b1&31)<<6|b2&63;i++}else{throw new Error(`invalid utf-8 data`)}}if(code>=65536){code^=65536;const p1=55296|code>>10;const p2=56320|code&1023;str+=String.fromCharCode(p1);str+=String.fromCharCode(p2)}else{str+=String.fromCharCode(code)}}return str}else{throw new Error(`Unsupported buffer argument`)}}}exports.decodeString=decodeString;function concatTypedArrays(a,b){const c=new a.constructor(a.length+b.length);c.set(a);c.set(b,a.length);return c}exports.concatTypedArrays=concatTypedArrays;function cloneObject(original,stack){var _a;if(((_a=original===null||original===void 0?void 0:original.constructor)===null||_a===void 0?void 0:_a.name)==="DataSnapshot"){throw new TypeError(`Object to clone is a DataSnapshot (path "${original.ref.path}")`)}const checkAndFixTypedArray=obj=>{if(obj!==null&&typeof obj==="object"&&typeof obj.constructor==="function"&&typeof obj.constructor.name==="string"&&["Buffer","Uint8Array","Int8Array","Uint16Array","Int16Array","Uint32Array","Int32Array","BigUint64Array","BigInt64Array"].includes(obj.constructor.name)){obj=obj.buffer.slice(obj.byteOffset,obj.byteOffset+obj.byteLength)}return obj};original=checkAndFixTypedArray(original);if(typeof original!=="object"||original===null||original instanceof Date||original instanceof ArrayBuffer||original instanceof path_reference_1.PathReference||original instanceof RegExp){return original}const cloneValue=val=>{if(stack.indexOf(val)>=0){throw new ReferenceError(`object contains a circular reference`)}val=checkAndFixTypedArray(val);if(val===null||val instanceof Date||val instanceof ArrayBuffer||val instanceof path_reference_1.PathReference||val instanceof RegExp){return val}else if(typeof val==="object"){stack.push(val);val=cloneObject(val,stack);stack.pop();return val}else{return val}};if(typeof stack==="undefined"){stack=[original]}const clone=original instanceof Array?[]:original instanceof partial_array_1.PartialArray?new partial_array_1.PartialArray:{};Object.keys(original).forEach((key=>{let val=original[key];if(typeof val==="function"){return}clone[key]=cloneValue(val)}));return clone}exports.cloneObject=cloneObject;const isTypedArray=val=>typeof val==="object"&&["ArrayBuffer","Buffer","Uint8Array","Uint16Array","Uint32Array","Int8Array","Int16Array","Int32Array"].includes(val.constructor.name);function valuesAreEqual(val1,val2){if(val1===val2){return true}if(typeof val1!==typeof val2){return false}if(typeof val1==="object"||typeof val2==="object"){if(val1===null||val2===null){return false}if(val1 instanceof path_reference_1.PathReference||val2 instanceof path_reference_1.PathReference){return val1 instanceof path_reference_1.PathReference&&val2 instanceof path_reference_1.PathReference&&val1.path===val2.path}if(val1 instanceof Date||val2 instanceof Date){return val1 instanceof Date&&val2 instanceof Date&&val1.getTime()===val2.getTime()}if(val1 instanceof Array||val2 instanceof Array){return val1 instanceof Array&&val2 instanceof Array&&val1.length===val2.length&&val1.every(((item,i)=>valuesAreEqual(val1[i],val2[i])))}if(isTypedArray(val1)||isTypedArray(val2)){if(!isTypedArray(val1)||!isTypedArray(val2)||val1.byteLength===val2.byteLength){return false}const typed1=val1 instanceof ArrayBuffer?new Uint8Array(val1):new Uint8Array(val1.buffer,val1.byteOffset,val1.byteLength),typed2=val2 instanceof ArrayBuffer?new Uint8Array(val2):new Uint8Array(val2.buffer,val2.byteOffset,val2.byteLength);return typed1.every(((val,i)=>typed2[i]===val))}const keys1=Object.keys(val1),keys2=Object.keys(val2);return keys1.length===keys2.length&&keys1.every((key=>keys2.includes(key)))&&keys1.every((key=>valuesAreEqual(val1[key],val2[key])))}return false}exports.valuesAreEqual=valuesAreEqual;class ObjectDifferences{constructor(added,removed,changed){this.added=added;this.removed=removed;this.changed=changed}forChild(key){if(this.added.includes(key)){return"added"}if(this.removed.includes(key)){return"removed"}const changed=this.changed.find((ch=>ch.key===key));return changed?changed.change:"identical"}}exports.ObjectDifferences=ObjectDifferences;function compareValues(oldVal,newVal,sortedResults=false){const voids=[undefined,null];if(oldVal===newVal){return"identical"}else if(voids.indexOf(oldVal)>=0&&voids.indexOf(newVal)<0){return"added"}else if(voids.indexOf(oldVal)<0&&voids.indexOf(newVal)>=0){return"removed"}else if(typeof oldVal!==typeof newVal){return"changed"}else if(isTypedArray(oldVal)||isTypedArray(newVal)){if(!isTypedArray(oldVal)||!isTypedArray(newVal)){return"changed"}const typed1=oldVal instanceof Uint8Array?oldVal:oldVal instanceof ArrayBuffer?new Uint8Array(oldVal):new Uint8Array(oldVal.buffer,oldVal.byteOffset,oldVal.byteLength);const typed2=newVal instanceof Uint8Array?newVal:newVal instanceof ArrayBuffer?new Uint8Array(newVal):new Uint8Array(newVal.buffer,newVal.byteOffset,newVal.byteLength);return typed1.byteLength===typed2.byteLength&&typed1.every(((val,i)=>typed2[i]===val))?"identical":"changed"}else if(oldVal instanceof Date||newVal instanceof Date){return oldVal instanceof Date&&newVal instanceof Date&&oldVal.getTime()===newVal.getTime()?"identical":"changed"}else if(oldVal instanceof path_reference_1.PathReference||newVal instanceof path_reference_1.PathReference){return oldVal instanceof path_reference_1.PathReference&&newVal instanceof path_reference_1.PathReference&&oldVal.path===newVal.path?"identical":"changed"}else if(typeof oldVal==="object"){const isArray=oldVal instanceof Array;const getKeys=obj=>{let keys=Object.keys(obj).filter((key=>!voids.includes(obj[key])));if(isArray){keys=keys.map((v=>parseInt(v)))}return keys};const oldKeys=getKeys(oldVal);const newKeys=getKeys(newVal);const removedKeys=oldKeys.filter((key=>!newKeys.includes(key)));const addedKeys=newKeys.filter((key=>!oldKeys.includes(key)));const changedKeys=newKeys.reduce(((changed,key)=>{if(oldKeys.includes(key)){const val1=oldVal[key];const val2=newVal[key];const c=compareValues(val1,val2);if(c!=="identical"){changed.push({key:key,change:c})}}return changed}),[]);if(addedKeys.length===0&&removedKeys.length===0&&changedKeys.length===0){return"identical"}else{return new ObjectDifferences(addedKeys,removedKeys,sortedResults?changedKeys.sort(((a,b)=>a.key{switch(compareResult){case"identical":return[];case"changed":return[{target:target,prev:prev,val:val}];case"added":return[{target:target,prev:null,val:val}];case"removed":return[{target:target,prev:prev,val:null}];default:{let changes=[];compareResult.added.forEach((key=>changes.push({target:target.concat(key),prev:null,val:val[key]})));compareResult.removed.forEach((key=>changes.push({target:target.concat(key),prev:prev[key],val:null})));compareResult.changed.forEach((item=>{const childChanges=process(target.concat(item.key),item.change,prev[item.key],val[item.key]);changes=changes.concat(childChanges)}));return changes}}};const compareResult=compareValues(oldVal,newVal,sortedResults);return process([],compareResult,oldVal,newVal)}exports.getMutations=getMutations;function getChildValues(childKey,oldValue,newValue){oldValue=oldValue===null?null:oldValue[childKey];if(typeof oldValue==="undefined"){oldValue=null}newValue=newValue===null?null:newValue[childKey];if(typeof newValue==="undefined"){newValue=null}return{oldValue:oldValue,newValue:newValue}}exports.getChildValues=getChildValues;function defer(fn){process_1.default.nextTick(fn)}exports.defer=defer}).call(this)}).call(this,require("buffer").Buffer)},{"./partial-array":33,"./path-reference":35,"./process":36,buffer:3}]},{},[10])(10)})); \ No newline at end of file diff --git a/webmanager/index.html b/webmanager/index.html index 488a61e..1c11f7c 100644 --- a/webmanager/index.html +++ b/webmanager/index.html @@ -263,8 +263,8 @@ M.AutoInit(); - - + +