@pixagram/lacerta-db 0.0.2 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser.min.js +1 -1
- package/dist/index.min.js +1 -1
- package/index.js +45 -31
- package/package.json +2 -2
package/dist/browser.min.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(t=>{var e={};function a(r){var s;return(e[r]||(s=e[r]={i:r,l:!1,exports:{}},t[r].call(s.exports,s,s.exports,a),s.l=!0,s)).exports}a.m=t,a.c=e,a.d=function(t,e,r){a.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:r})},a.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},a.t=function(t,e){if(1&e&&(t=a(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var r=Object.create(null);if(a.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var s in t)a.d(r,s,function(e){return t[e]}.bind(null,s));return r},a.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return a.d(e,"a",e),e},a.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},a.p="",a(a.s=2)})([function(t,e,a){a.r(e);var r=a(1);class s{constructor(t){this.arrayType=t,this.bitMask=this.calculateBitMask()}calculateBitMask(){var t={Uint8Array:255,Uint16Array:65535,Uint32Array:4294967295};if(this.arrayType.name in t)return t[this.arrayType.name];throw new Error("Unsupported array type: "+this.arrayType.name)}performDeltaEncoding(t){this.validateInputType(t,"performDeltaEncoding");var e,a=new this.arrayType(t.length),r=0|t.length,s=0;for(a[0]=0|t[0],s=1;(0|s)<(0|r);s=s+1|0)e=t[s]-t[s-1]&this.bitMask,a[s]=0|e;return a}performDeltaDecoding(t){this.validateInputType(t,"performDeltaDecoding");var e,a=new this.arrayType(t.length),r=0|t.length,s=0;for(a[0]=0|t[0],s=1;(0|s)<(0|r);s=s+1|0)e=a[s-1]+t[s]&this.bitMask,a[s]=0|e;return a}validateInputType(t,e){if(!(t instanceof this.arrayType))throw new Error(`Input data type does not match for method ${e}. Expected: `+this.arrayType.name)}}class i{constructor(t){this.bitArray=new Uint8Array(t+7>>3)}setBit(t,e){var a=1<<(t|=0)%8;this.bitArray[t=t/8|0]=(e|=0)?this.bitArray[t]|a:this.bitArray[t]&~a}getBit(t){return this.bitArray[(t|=0)/8|0]&1<<t%8?1:0}}var n=new class{constructor(){this.deltaEncoder8Bit=new s(Uint8Array),this.deltaEncoder16Bit=new s(Uint16Array),this.deltaEncoder32Bit=new s(Uint32Array)}getDeltaEncoder(t){switch(t){case"Uint8Array":case"Int8Array":case"Uint8ClampedArray":return this.deltaEncoder8Bit;case"Uint16Array":case"Int16Array":return this.deltaEncoder16Bit;case"Uint32Array":case"Int32Array":case"Float32Array":case"Float64Array":return this.deltaEncoder32Bit;default:throw new Error("Unknown TypedArray type.")}}compress(t){var e=t.constructor,a=e.name,r=t.length,s=this.getDeltaEncoder(a).performDeltaEncoding(new e(t.buffer)),n=new i(t.length),o=[];let c=s[0];o.push(c);for(let t=1;t<s.length;t++)s[t]===c?n.setBit(t,!0):(o.push(s[t]),c=s[t]);return this.packData(o,n,r,e.BYTES_PER_ELEMENT)}packData(t,e,a,r){r=t.length*r;var s=(e=e.bitArray).length;return(s=new Uint8Array(9+r+s))[0]=this.getDataTypeId(t),s.set(this.convertLengthToBytes(r),1),s.set(this.convertLengthToBytes(a),5),s.set(t,9),s.set(e,9+r),s}convertLengthToBytes(t){return Uint8Array.of(t>>0&255,t>>8&255,t>>16&255,t>>24&255)}getDataTypeId(t){return{Uint8Array:1,Int8Array:2,Uint8ClampedArray:3,Uint16Array:4,Int16Array:5,Uint32Array:6,Int32Array:7,Float32Array:8,Float64Array:9}[t.constructor.name]||0}decompress(t){var e=t[0],a=this.extractLengthFromBytes(t,1),r=this.extractLengthFromBytes(t,5),s=new Uint8Array(t.subarray(9,9+a)),n=(t=new Uint8Array(t.subarray(9+a)),new(a=this.getArrayConstructorByTypeId(e))(s.buffer)),o=new i(8*t.length),c=(o.bitArray=t,new a(r));let h=0;for(let t=0;(0|t)<(0|r);t=t+1|0)o.getBit(t)?c[t]=c[t-1|0]:c[t]=n[h++];return this.getDeltaEncoder(a.name).performDeltaDecoding(c)}extractLengthFromBytes(t,e){return t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24}getArrayConstructorByTypeId(t){return{1:Uint8Array,2:Int8Array,3:Uint8ClampedArray,4:Uint16Array,5:Int16Array,6:Uint32Array,7:Int32Array,8:Float32Array,9:Float64Array}[t]||Uint8Array}},o=class{constructor(t){this._buffers=new WeakMap,this._store={},this._nextId=0,this._compress=t?n.compress.bind(n):function(t){return t},this._decompress=t?n.decompress.bind(n):function(t){return t}}_generateId(){var t=this._nextId;return this._nextId++,t}clear(){this._buffers=new WeakMap,this._store={},this._nextId=0}insert(t,e){if(void 0===e){if(this._buffers.has(t))return this._buffers.get(t);e=this._generateId()}else if(this._store.hasOwnProperty(e))throw new Error(`ID ${e} is already in use.`);return e=parseInt(e),this._buffers.set(t,e),this._store[e]=t,e}retrieve(t){return this._store[parseInt(t)]}retrieveAll(){var t={},e=Object.entries(this._store);for(let s=0;s<e.length;s++){var[a,r]=e[s],r=this._compress(new Uint8Array(r)).buffer;t[parseInt(a)]=r}return t}insertAll(t){var e=Object.entries(t);for(let t=0;t<e.length;t++){var[a,r]=e[t],r=this._decompress(new Uint8Array(r)).buffer;this.insert(r,parseInt(a))}}},c=new class{constructor(){this._packBufferTemp8=new Uint8Array(15e3),this._headerByteLength=0,this._offset=0,this._b64=new r.B64chromium,this._b64Base64ToBytes=this._b64.base64ToBytes.bind(this._b64),this._b64BytesToBase64=this._b64.bytesToBase64.bind(this._b64),this._textDecoder=new TextDecoder,this._textDecoderFunction=this._textDecoder.decode.bind(this._textDecoder),this._textEncoder=new TextEncoder,this._textEncoderFunction=this._textEncoder.encode.bind(this._textEncoder),this._textEncoderIntoFunction=this._textEncoder.encodeInto.bind(this._textEncoder),this.encodeOtherBound=this.encodeOther.bind(this),this.decodeOtherBound=this.decodeOther.bind(this),this.stringifyBound=this._innerStringify.bind(this),this.parseBound=this._innerParse.bind(this),this.use_compressor=!1,this._setEngine()}_setEngine(){this.engine=new class{constructor(t,e,a,r,s,i,n,c,h){this._hasher=new class{constructor(t){this._chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",this._charLookup={};for(let t=0;t<this._chars.length;t++)this._charLookup[this._chars[t]]=t;this._bitPerChar=6,this._accumulatorBitNumber=32,this._outputLength=Math.max(1,Math.min(0|t,this._accumulatorBitNumber/this._bitPerChar|0)),this._primes=Uint32Array.of(2654435761,2246822519,3266489917,668265263),this._values=new Uint32Array(this._primes.length+2),this.imul=Math.imul,this.rotl=function(t,e){return(t>>>=0)<<(e&=31)|t>>>32-e}}get outputLength(){return this._outputLength}get chars(){return this._chars}get finalValue(){return this._values[4]}set finalValue(t){return this._values[4]=(0|t)>>>0}get primes(){return this._primes}get values(){return this._values}get accumulator(){return this._values}get charLookup(){return this._charLookup}getCharValue(t){return 63&this.charLookup[t]}aggregateCharValue(t,e,a,r){return t<<18|e<<12|a<<6|r}getCharByOffset(t){return this.chars[63&t]}hash(t){this.values.fill(0);for(var e=0,a=0,r=t.length,s=r>>2>>2;e<s;a=++e<<4)this.accumulator[0]=this.accumulator[0]+this.imul(this.aggregateCharValue(this.getCharValue(t[a]),this.getCharValue(t[a+1|0]),this.getCharValue(t[a+2|0]),this.getCharValue(t[a+3|0])),this.primes[0]),this.accumulator[1]=this.accumulator[1]+this.imul(this.aggregateCharValue(this.getCharValue(t[a+4|0]),this.getCharValue(t[a+5|0]),this.getCharValue(t[a+6|0]),this.getCharValue(t[a+7|0])),this.primes[1]),this.accumulator[2]=this.accumulator[2]+this.imul(this.aggregateCharValue(this.getCharValue(t[a+8|0]),this.getCharValue(t[a+9|0]),this.getCharValue(t[a+10|0]),this.getCharValue(t[a+11|0])),this.primes[2]),this.accumulator[3]=this.accumulator[3]+this.imul(this.aggregateCharValue(this.getCharValue(t[a+12|0]),this.getCharValue(t[a+13|0]),this.getCharValue(t[a+14|0]),this.getCharValue(t[a+15|0])),this.primes[3]);for(e<<=2;(0|e)<(0|r);a=(e=(e+1|0)>>>0)<<2)this.accumulator[3&e]=this.accumulator[3&e]+this.imul(this.aggregateCharValue(this.getCharValue(t[a])||0,this.getCharValue(t[a+1|0])||0,this.getCharValue(t[a+2|0])||0,this.getCharValue(t[a+3|0]))||0,this.primes[3&e]);this.finalValue=this.rotl(this.accumulator[0],1)+this.rotl(this.accumulator[1],7)+this.rotl(this.accumulator[2],12)+this.rotl(this.accumulator[3],18)>>>0;for(var i,n=0,o=new Array(this.outputLength);n<this.outputLength;n++)i=63&this.finalValue,o[n]=this.getCharByOffset(i),this.finalValue=(this.finalValue-i)/64>>>0;return o.join("")}}(1),this.hashThis=r||this._hasher.hash.bind(this._hasher),this.base=t||"data:joyson/",this.shortBase=e||"d:j/",this.baseLength=this.base.length,this.shortBaseLength=this.shortBase.length,this.encapsulate=a||function(t){return JSON.stringify(t)},this.encodeObjectOut=s||function(t){return t},this.decodeObjectOut=i||function(t){return t},this.stringifyOut=n||JSON.stringify,this.parseOut=c||JSON.parse,this._initializeErrorConstructors(),this.arrayBufferIDManager=new o(h),this._initializeBufferConstructors(),this._initializeDynamicTypes(["object","number","bigint","map","set","date","string","error","regexp","buffer","boolean","static"])}_initializeDynamicTypes(t){this.dynamicValues={},this.dynamicValuesIdKey={};for(var e=0;e<t.length;e++){var a=t[e];this.dynamicValues[a]={},this.dynamicValues[a].name=a,this.dynamicValues[a].str=this.base+this.dynamicValues[a].name+";",this.dynamicValues[a].id=this.hashThis(this.dynamicValues[a].name),this.dynamicValues[a].shortStr=this.shortBase+this.dynamicValues[a].id+";",this.dynamicValues[a].strCode=new Uint8Array(this.dynamicValues[a].str.split("").map((function(t){return t.charCodeAt(0)}))),this.dynamicValues[a].shortStrCode=new Uint8Array(this.dynamicValues[a].shortStr.split("").map((function(t){return t.charCodeAt(0)}))),this.dynamicValues[a].strLen=this.dynamicValues[a].str.length,this.dynamicValues[a].shortStrLen=this.dynamicValues[a].shortStr.length,this.dynamicValuesIdKey[this.dynamicValues[a].id]=this.dynamicValues[a].name}}_initializeErrorConstructors(){this.errorConstructors={Error:Error,TypeError:TypeError,SyntaxError:SyntaxError,ReferenceError:ReferenceError,RangeError:RangeError,EvalError:EvalError,URIError:URIError,DOMException:DOMException}}_initializeBufferConstructors(){this.bufferConstructors={ArrayBuffer:ArrayBuffer,Uint8Array:Uint8Array,Uint8ClampedArray:Uint8ClampedArray,Int8Array:Int8Array,Uint16Array:Uint16Array,Int16Array:Int16Array,Uint32Array:Uint32Array,Int32Array:Int32Array,Float32Array:Float32Array,Float64Array:Float64Array}}clear(){this.arrayBufferIDManager.clear()}getAllArrayBuffer(){var t=this.arrayBufferIDManager.retrieveAll();return this.clear(),t}setAllArrayBuffer(t){this.clear(),this.arrayBufferIDManager.insertAll(t)}_isNotNumber(t){return isNaN(t)}_isNotFiniteNumber(t){return!isFinite(t)}_isNotObject(t){return null===t}_isNotString(t){return t.includes("\0")}_isError(t){return void 0!==t.name&&t.name in this.errorConstructors}_isBuffer(t){return(t instanceof ArrayBuffer||"object"==typeof t.buffer)&&(t.constructor||{}).name in this.bufferConstructors}_mustDecodeOfType(t){if("string"==typeof t){if(t.startsWith(this.shortBase))return 2;if(t.startsWith(this.base))return 1}return 0}_dataTypeNameFromKey(t){return this.dynamicValuesIdKey[t]}_decode(t,e){var a=t.slice(e?this.shortBaseLength:this.baseLength).split(";"),r=a[0],s=a[1];switch(e?this._dataTypeNameFromKey(r):r){case"static":return this.decodeStatic(s);case"number":return this.decodeSpecialNumber(s);case"bigint":return this.decodeBigNumber(s);case"string":return this.decodeSpecialString(s);case"boolean":return this.decodeBoolean(s);case"map":return this.decodeMap(s);case"set":return this.decodeSet(s);case"date":return this.decodeDate(s);case"regexp":return this.decodeRegexp(s);case"error":return this.decodeError(s);case"buffer":return this.decodeBuffer(s);case"object":return this.decodeSpecialObject(s);default:return this.decodeObjectOut(t,e)}}decode(t,e){switch(this._mustDecodeOfType(t)){case 0:return"object"==typeof t?this.decodeObjectOut(t,e):t;case 1:return this._decode(t,!1);case 2:return this._decode(t,!0)}}decodeStatic(t){switch(t){case"nan":return NaN;case"null":return null;case"undefined":return}}decodeSpecialNumber(t){switch(t){case"nan":return NaN;case"infinity":return 1/0;case"-infinity":return-1/0;case"epsilon":return Number.EPSILON;case"-epsilon":return-Number.EPSILON;case"-0":return parseInt("-0");default:return Number(t)}}decodeBigNumber(t){return BigInt(t)}decodeSpecialString(t){return atob(t)}decodeBoolean(t){return"true"===t}decodeMap(t){return t=atob(t),t=this.parseOut(t),new Map(t)}decodeSet(t){return t=atob(t),t=this.parseOut(t),new Set(t)}decodeDate(t){return new Date(t)||new Date(NaN)}decodeRegexp(t){t=t.split(":");var e=atob(t[0]);t=atob(t[1]);return new RegExp(e,t)}decodeError(t){t=t.split(":");var e=atob(t[0]);t=atob(t[1]);return new this.errorConstructors[e](t)}decodeBuffer(t){var e="ArrayBuffer"===(a=(t=t.split(":"))[0]),a=this.bufferConstructors[a],r=parseInt(t[1],16),s=parseInt(t[2],16);t=parseInt(t[3],16),t=this.arrayBufferIDManager.retrieve(t);return e?t:new a(t,r,s)}decodeSpecialObject(t){return t=atob(t),t=this.parseOut(t),Object(t)}_encodeFinal(t,e,a){return a?this.dynamicValues[t].shortStr+e:this.encapsulate(this.dynamicValues[t].str+e)}encode(t,e){switch(typeof t){case"undefined":return this.encodeStatic(t,e);case"number":return this._isNotNumber(t)?this.encodeStatic(t,e):this.encodeNumber(t,e);case"bigint":return this.encodeBigNumber(t,e);case"string":return this._isNotString(t)?this.encodeSpecialString(t,e):this.encodeString(t,e);case"boolean":return this.encodeBoolean(t,e);case"object":return this._isNotObject(t)?this.encodeStatic(t,e):"function"==typeof t.get?this.encodeMap(t,e):"function"==typeof t.delete?this.encodeSet(t,e):"function"==typeof t.toISOString?this.encodeDate(t,e):"function"==typeof t.exec?this.encodeRegexp(t,e):t!==t.valueOf()?this.encodeSpecialObject(t,e):this._isError(t)?this.encodeError(t,e):this._isBuffer(t)?this.encodeBuffer(t,e):this.encodeObject(t,e)}}encodeStatic(t,e){var a;switch(typeof t){case"number":a="nan";break;case"object":a="null";break;case"undefined":a="undefined"}return this._encodeFinal("static",a,e)}encodeNumber(t,e){var a;switch(t){case NaN:a="nan";break;case 1/0:a="infinity";break;case-1/0:a="-infinity";break;case Number.EPSILON:a="epsilon";break;case-Number.EPSILON:a="-epsilon";break;default:if("-0"===Number(t).toLocaleString())a="-0";else{if(!this._isNotFiniteNumber(t))return e?t:""+t;a=t}}return this._encodeFinal("number",a,e)}encodeBigNumber(t,e){return t=t.toString(),this._encodeFinal("bigint",t,e)}encodeSpecialString(t,e){return t=btoa(t),this._encodeFinal("string",t,e)}encodeString(t,e){return e?""+t:this.encapsulate(t)}encodeBoolean(t,e){return this._encodeFinal("boolean",t?"true":"false",e)}encodeMap(t,e){return t=Object.entries(Object.fromEntries(t)),t=this.stringifyOut(t),t=btoa(t),this._encodeFinal("map",t,e)}encodeSet(t,e){return t=Array.from(t),t=this.stringifyOut(t),t=btoa(t),this._encodeFinal("set",t,e)}encodeDate(t,e){return t=t.toISOString(),this._encodeFinal("date",t,e)}encodeRegexp(t,e){return t=[btoa(t.source),btoa(t.flags)],this._encodeFinal("regexp",t.join(":"),e)}encodeSpecialObject(t,e){return t=this.stringifyOut(t.valueOf()),t=btoa(t),this._encodeFinal("object",t,e)}encodeError(t,e){return t=[btoa(t.name),btoa(t.message)],this._encodeFinal("error",t.join(":"),e)}encodeBuffer(t,e){var a=(i=void 0===t.buffer)?"ArrayBuffer":t.constructor.name,r=t.byteOffset,s=i?t.byteLength:t.length,i=i?t:t.buffer;t=this.arrayBufferIDManager.insert(i),i=[a,parseInt(r).toString(16),parseInt(s).toString(16),parseInt(t).toString(16)];return this._encodeFinal("buffer",i.join(":"),e)}encodeObject(t,e){return this.encodeObjectOut(t,e)}}(void 0,void 0,void 0,void 0,this.encodeOtherBound,this.decodeOtherBound,this.stringifyBound,this.parseBound,this.use_compressor)}get compress(){return this.use_compressor}set compress(t){this.use_compressor=Boolean(t),this._setEngine()}_getComparator(){return function(t){return function(e){return function(a,r){return a={key:a,value:e[a]},t(a,{key:r,value:e[r]})}}}}_stringifyObject(t){if(Array.isArray(t)){for(var e=0,a=t.length,r=((s=Object.keys(t)).length,new Array(a));(0|e)<(0|a);e=(e+1|0)>>>0)r[e]=this.engine.encode(t[e],!1);return"["+r.join(",")+"]"}for(var s,i,n=this._getComparator(),o="",c=(e=0,a=0|(s=Object.keys(t).sort(n&&n(t))).length,"");(0|e)<(0|a);e=(e+1|0)>>>0)if(o=s[e]+"",i=this.engine.encode(t[o],!1))switch(0<(0|c.length)&&(c+=","),0|(0===o.length||o.includes("\0")||o.startsWith("$"))){case 0:c+=this.engine.encode(o,!1)+":"+i;break;case 1:c+='"$'+btoa("$"+o)+'":'+i}return"{"+c+"}"}encodeOther(t,e){return e?this._packObject(t):this._stringifyObject(t)}decodeOther(t,e){return e?this._unpackObject(t):this._parseObject(t)}_stringify(t,e){var a={};if(a.header=this.engine.encode(t,!1),!e){var r,s=this.engine.getAllArrayBuffer();for(r in a.buffers={},s)a.buffers[r]=this._b64BytesToBase64(new Uint8Array(s[r]))}return JSON.stringify(a)}stringify(t){return this._stringify(t,!1)}_innerStringify(t){return this._stringify(t,!0)}_parseObject(t){if(Array.isArray(t)){for(var e=[],a=0,r=t.length;(0|a)<(0|r);a=(a+1|0)>>>0)e.push(this.engine.decode(t[a]));return e}var s,i,n={},o=Object.keys(t),c="";for(a=0,r=0|o.length;(0|a)<(0|r);a=(a+1|0)>>>0)switch(c=o[a],s=this._keyMustDecode(c),i=this.engine.decode(t[c]),0|s){case 0:n[c]=i;break;case 1:n[atob(c.slice(1)).slice(1)]=i}return n}_parse(t,e){var a,r;t=JSON.parse(t);return e||(a=this._b64Base64ToBytes,r={},Object.entries(t.buffers).forEach((function(t){var e=t[0];r[e]=a(t[1]).buffer})),this.engine.setAllArrayBuffer(r)),this.engine.decode(JSON.parse(t.header))}parse(t){return this._parse(t,!1)}_innerParse(t){return this._parse(t,!0)}_packObject(t){if(Array.isArray(t)){for(var e=[],a=0,r=t.length;(0|a)<(0|r);a=(a+1|0)>>>0)e.push(this.engine.encode(t[a],!0));return e}var s,i={},n=Object.keys(t),o="";for(a=0,r=0|n.length;(0|a)<(0|r);a=(a+1|0)>>>0)if(o=n[a]+"",s=this.engine.encode(t[o],!0))switch(0|(""===o||o.includes("\0")||o.startsWith("$"))){case 0:i[this.engine.encode(o,!0)]=s;break;case 1:i["$"+btoa("$"+o)]=s}return i}pack(t){t=JSON.stringify(this.engine.encode(t,!0));var e=this.engine.getAllArrayBuffer(),a=0,r=Object.keys(e).length;for(n in e)a+=e[n].byteLength;var s=2*t.length+5,i=s+a+4;if((i=(this._packBufferTemp8.length<i&&(this._packBufferTemp8=new Uint8Array(i)),this._textEncoderIntoFunction(t,this._packBufferTemp8.subarray(4,4+s)))).written>s)throw new Error("Header in json is too fat!");t=i.written;var n,o=(this._packBufferTemp8[0]=t>>0&255,this._packBufferTemp8[1]=t>>8&255,this._packBufferTemp8[2]=t>>16&255,this._packBufferTemp8[3]=t>>24&255,t);a=4;for(n in this._packBufferTemp8[o+a]=r>>0&255,this._packBufferTemp8[o+a+1]=r>>8&255,this._packBufferTemp8[o+a+2]=r>>16&255,this._packBufferTemp8[o+a+3]=r>>24&255,a+=4,e){var c=e[n],h=c.byteLength;this._packBufferTemp8[o+a]=h>>0&255,this._packBufferTemp8[o+a+1]=h>>8&255,this._packBufferTemp8[o+a+2]=h>>16&255,this._packBufferTemp8[o+a+3]=h>>24&255,a+=4,this._packBufferTemp8.set(new Uint8Array(c),o+a),a+=h}return this._packBufferTemp8.slice(0,o+a)}_keyMustDecode(t){return t.startsWith("$")}_unpackObject(t){if(Array.isArray(t)){for(var e=[],a=0,r=t.length;(0|a)<(0|r);a=(a+1|0)>>>0)e.push(this.engine.decode(t[a],!0));return e}var s,i,n={},o=Object.keys(t),c="";for(a=0,r=0|o.length;(0|a)<(0|r);a=(a+1|0)>>>0)switch(c=o[a],s=this._keyMustDecode(c),i=this.engine.decode(t[c],!0),0|s){case 0:n[c]=i;break;case 1:n[atob(c.slice(1)).slice(1)]=i}return n}unpack(t){for(var e=4+(t[0]<<0|t[1]<<8|t[2]<<16|t[3]<<24),a=4+e,r=JSON.parse(this._textDecoderFunction(t.subarray(4,e))),s=t[e]<<0|t[1+e]<<8|t[2+e]<<16|t[3+e]<<24,i={},n=a,o=0;o<s;o++){var c=t[n]<<0|t[n+1]<<8|t[n+2]<<16|t[n+3]<<24;n+=4,i[o]=t.buffer.slice(n,n+c),n+=c}return this.engine.setAllArrayBuffer(i),this.engine.decode(r,!0)}};a.d(e,"Database",(function(){return D})),a.d(e,"Document",(function(){return B})),a.d(e,"Collection",(function(){return T}));class h{static async saveAttachments(t,e,a,r){var s,i=[];let n=await navigator.storage.getDirectory();for(s of[t,e,a])n=await n.getDirectoryHandle(s,{create:!0});for(let s=0;s<r.length;s++){var o=s.toString(),c=await(await n.getFileHandle(o,{create:!0})).createWritable();c=(await c.write(r[s].data),await c.close(),t+`/${e}/${a}/`+o);i.push(c)}return i}static async getAttachments(t){var e,a=[],r=await navigator.storage.getDirectory();for(e of t)try{var s=e.split("/");let t=r;for(let e=0;e<s.length-1;e++)t=await t.getDirectoryHandle(s[e]);var i=await(await t.getFileHandle(s[s.length-1])).getFile();a.push({path:e,data:i})}catch(t){console.error(`Error retrieving attachment at "${e}": `+t.message)}return a}static async deleteAttachments(t,e,a){var r=[t,e,a];let s=await navigator.storage.getDirectory();for(let t=0;t<r.length-1;t++)s=await s.getDirectoryHandle(r[t]);try{await s.removeEntry(r[r.length-1],{recursive:!0})}catch(t){console.error(`Error deleting attachments for document "${a}": `+t.message)}}toString(){return"[OPFSUtility]"}}class d{static async compress(t){t="string"==typeof t?(new TextEncoder).encode(t):t;var e=new CompressionStream("deflate"),a=e.writable.getWriter();return a.write(t),a.close(),this._streamToUint8Array(e.readable)}static async decompress(t){var e=new DecompressionStream("deflate"),a=e.writable.getWriter();return a.write(t),a.close(),this._streamToUint8Array(e.readable)}static async _streamToUint8Array(t){var e=t.getReader(),a=[];let r=0;for(;;){var{value:s,done:i}=await e.read();if(i)break;a.push(s),r+=s.length}var n,o=new Uint8Array(r);let c=0;for(n of a)o.set(n,c),c+=n.length;return o}toString(){return"[BrowserCompressionUtility]"}}class u{static async encrypt(t,e){var a=crypto.getRandomValues(new Uint8Array(16)),r=(e=await this._deriveKey(e,a),crypto.getRandomValues(new Uint8Array(12))),s=await this._generateChecksum(t);t=this._combineDataAndChecksum(t,s),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},e,t);return this._wrapIntoUint8Array(a,r,new Uint8Array(s))}static async decrypt(t,e){var{salt:t,iv:a,encryptedData:r}=this._unwrapUint8Array(t),a=(e=await this._deriveKey(e,t),t=await crypto.subtle.decrypt({name:"AES-GCM",iv:a},e,r),new Uint8Array(t)),{data:e,checksum:r}=this._separateDataAndChecksum(a);t=await this._generateChecksum(e);if(this._verifyChecksum(t,r))return e;throw new Error("Data integrity check failed. The data has been tampered with.")}static async _deriveKey(t,e){var a=new TextEncoder;a=await crypto.subtle.importKey("raw",a.encode(t),{name:"PBKDF2"},!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"PBKDF2",salt:e,iterations:6e5,hash:"SHA-512"},a,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}static async _generateChecksum(t){return new Uint8Array(await crypto.subtle.digest("SHA-256",t))}static _verifyChecksum(t,e){if(t.length!==e.length)return!1;for(let a=0;a<t.length;a++)if(t[a]!==e[a])return!1;return!0}static _combineDataAndChecksum(t,e){var a=new Uint8Array(t.length+e.length);return a.set(t),a.set(e,t.length),a}static _separateDataAndChecksum(t){var e=t.length-32;return{data:t.slice(0,e),checksum:t.slice(e)}}static _wrapIntoUint8Array(t,e,a){var r=new Uint8Array(t.length+e.length+a.length);return r.set(t,0),r.set(e,t.length),r.set(a,t.length+e.length),r}static _unwrapUint8Array(t){return{salt:t.slice(0,16),iv:t.slice(16,28),encryptedData:t.slice(28)}}toString(){return"[BrowserEncryptionUtility]"}}class l{static openDatabase(t,e=null,a=null){return new Promise((r,s)=>{let i;(i=e?indexedDB.open(t,e):indexedDB.open(t)).onupgradeneeded=e=>{var r=e.target.result,s=e.oldVersion;e=e.newVersion;console.log(`Upgrading database "${t}" from version ${s} to `+e),a&&a(r,s,e)},i.onsuccess=e=>{(e=e.target.result).onclose=()=>{console.log(`Database "${t}" connection is closing.`)},r(e)},i.onerror=e=>{s(new Error(`Failed to open database "${t}": `+e.target.error.message))}})}static async performTransaction(t,e,a,r,s=3,i=null){let n=null;for(let h=0;h<=s;h++)try{if(!t)throw new Error("Database connection is not available.");let s=t.transaction(Array.isArray(e)?e:[e],a);var o=Array.isArray(e)?e.map(t=>s.objectStore(t)):[s.objectStore(e)],c=i||Date.now()+"_"+Math.random();let h=await r(...o,c);return new Promise((t,e)=>{s.oncomplete=()=>t(h),s.onerror=()=>{n=new Error("Transaction failed: "+(s.error?s.error.message:"unknown error")),e(n)},s.onabort=()=>{n=new Error("Transaction aborted: "+(s.error?s.error.message:"unknown reason")),e(n)}})}catch(t){n=t,h<s&&(console.warn(`Transaction failed, retrying... (${s-h} attempts left): `+t.message),await new Promise(t=>setTimeout(t,100*Math.pow(2,h))))}throw new Error(`Transaction ultimately failed after ${s+1} attempts: `+n.message)}static add(t,e){return new Promise((a,r)=>{var s=t.add(e);s.onsuccess=()=>a(),s.onerror=t=>r("Failed to insert record: "+t.target.error.message)})}static put(t,e){return new Promise((a,r)=>{var s=t.put(e);s.onsuccess=()=>a(),s.onerror=t=>r("Failed to put record: "+t.target.error.message)})}static delete(t,e){return new Promise((a,r)=>{var s=t.delete(e);s.onsuccess=()=>a(),s.onerror=t=>r("Failed to delete record: "+t.target.error.message)})}static get(t,e){return new Promise((a,r)=>{var s=t.get(e);s.onsuccess=t=>a(t.target.result),s.onerror=t=>r(`Failed to retrieve record with key ${e}: `+t.target.error.message)})}static getAll(t){return new Promise((e,a)=>{var r=t.getAll();r.onsuccess=t=>e(t.target.result),r.onerror=t=>a("Failed to retrieve records: "+t.target.error.message)})}static count(t){return new Promise((e,a)=>{var r=t.count();r.onsuccess=t=>e(t.target.result),r.onerror=t=>a("Failed to count records: "+t.target.error.message)})}static clear(t){return new Promise((e,a)=>{var r=t.clear();r.onsuccess=()=>e(),r.onerror=t=>a("Failed to clear store: "+t.target.error.message)})}static deleteDatabase(t){return new Promise((e,a)=>{var r=indexedDB.deleteDatabase(t);r.onsuccess=()=>e(),r.onerror=t=>a("Failed to delete database: "+t.target.error.message)})}static iterateCursor(t,e){return new Promise((a,r)=>{var s=t.openCursor();s.onsuccess=t=>{(t=t.target.result)?(e(t.value,t.key),t.continue()):a()},s.onerror=t=>r("Cursor iteration failed: "+t.target.error.message)})}toString(){return"[IndexedDBUtility]"}}class m{static getItem(t){return(t=localStorage.getItem(t))?c.parse(t):null}static setItem(t,e){localStorage.setItem(t,c.stringify(e))}static removeItem(t){localStorage.removeItem(t)}static clear(){localStorage.clear()}toString(){return"[LocalStorageUtility]"}}class _{constructor(){this.queue=[],this.locked=!1}async acquire(){return new Promise(t=>{this.locked?this.queue.push(t):(this.locked=!0,t())})}release(){0<this.queue.length?this.queue.shift()():this.locked=!1}async runExclusive(t){await this.acquire();try{return await t()}finally{this.release()}}toString(){return`[AsyncMutex locked:${this.locked} queue:${this.queue.length}]`}}class g{constructor(t){this._dbName=t,this._metadataKey=`lacertadb_${this._dbName}_metadata`,this._collections=new Map,this._metadata=this._loadMetadata(),this._mutex=new _}async saveMetadata(){return this._mutex.runExclusive(()=>{m.setItem(this.metadataKey,this.getRawMetadata())})}async adjustTotals(t,e){return this._mutex.runExclusive(()=>{this.data.totalSizeKB+=t,this.data.totalLength+=e,this.data.modifiedAt=Date.now()})}_loadMetadata(){var t=m.getItem(this.metadataKey);if(t){for(var e in t.collections){var a=t.collections[e];a=new b(e,this,a);this.collections.set(e,a)}return t}return{name:this._dbName,collections:{},totalSizeKB:0,totalLength:0,modifiedAt:Date.now()}}get data(){return this._metadata}set data(t){this._metadata=t}get name(){return this.data.name}get metadataKey(){return this._metadataKey}get collections(){return this._collections}set collections(t){this._collections=t}get totalSizeKB(){return this.data.totalSizeKB}get totalLength(){return this.data.totalLength}get modifiedAt(){return this.data.modifiedAt}getCollectionMetadata(t){var e;return this.collections.has(t)||(e=new b(t,this),this.collections.set(t,e),this.data.collections[t]=e.getRawMetadata(),this.data.modifiedAt=Date.now()),this.collections.get(t)}getCollectionMetadataData(t){return(t=this.getCollectionMetadata(t))?t.getRawMetadata():{}}removeCollectionMetadata(t){var e=this.collections.get(t);e&&(this.data.totalSizeKB-=e.sizeKB,this.data.totalLength-=e.length,this.collections.delete(t),delete this.data.collections[t],this.data.modifiedAt=Date.now())}getCollectionNames(){return Array.from(this.collections.keys())}getRawMetadata(){for(var[t,e]of this._collections.entries())this.data.collections[t]=e.getRawMetadata();return this.data}setRawMetadata(t){for(var e in this._metadata=t,this._collections.clear(),t.collections){var a=t.collections[e];a=new b(e,this,a);this._collections.set(e,a)}}get dbName(){return this._dbName}get key(){return this._metadataKey}toString(){return`[DatabaseMetadata: ${this.name} | Collections: ${this.collections.size} | Size: ${this.totalSizeKB.toFixed(2)}KB | Documents: ${this.totalLength}]`}}class f extends Error{constructor(t,e,a=null){super(t),this.name="LacertaDBError",this.code=e,this.originalError=a,this.timestamp=Date.now()}toString(){return`[LacertaDBError ${this.code}: ${this.message} at ${new Date(this.timestamp).toISOString()}]`}}let y="COLLECTION_NOT_FOUND",p="COLLECTION_EXISTS";class b{constructor(t,e,a=null){this._collectionName=t,this._databaseMetadata=e,a?this._metadata=a:(this._metadata={name:t,sizeKB:0,length:0,createdAt:Date.now(),modifiedAt:Date.now(),documentSizes:{},documentModifiedAt:{},documentPermanent:{},documentAttachments:{}},this._databaseMetadata.data.collections[t]=this._metadata,this._databaseMetadata.data.modifiedAt=Date.now())}get name(){return this._collectionName}get keys(){return Object.keys(this.documentSizes)}get collectionName(){return this.name}get sizeKB(){return this._metadata.sizeKB}get length(){return this._metadata.length}get modifiedAt(){return this._metadata.modifiedAt}get metadata(){return this._metadata}set metadata(t){return this._metadata=t}get data(){return this.metadata}set data(t){this.metadata=t}get databaseMetadata(){return this._databaseMetadata}set databaseMetadata(t){this._databaseMetadata=t}get documentSizes(){return this.metadata.documentSizes}get documentModifiedAt(){return this.metadata.documentModifiedAt}get documentPermanent(){return this.metadata.documentPermanent}get documentAttachments(){return this.metadata.documentAttachments}set documentSizes(t){this.metadata.documentSizes=t}set documentModifiedAt(t){this.metadata.documentModifiedAt=t}set documentPermanent(t){this.metadata.documentPermanent=t}set documentAttachments(t){this.metadata.documentAttachments=t}updateDocument(t,e,a=!1,r=0){var s=!this.keys.includes(t),i=e-(this.documentSizes[t]||0);s=s?1:0;this.documentSizes[t]=e,this.documentModifiedAt[t]=Date.now(),this.documentPermanent[t]=a?1:0,this.documentAttachments[t]=r,this.metadata.sizeKB+=i,this.metadata.length+=s,this.metadata.modifiedAt=Date.now(),this.databaseMetadata.adjustTotals(i,s)}deleteDocument(t){var e;return t in this.documentSizes&&(e=this.documentSizes[t],delete this.documentSizes[t],delete this.documentModifiedAt[t],delete this.documentPermanent[t],delete this.documentAttachments[t],this.metadata.sizeKB-=e,--this.metadata.length,this.metadata.modifiedAt=Date.now(),this.databaseMetadata.adjustTotals(-e,-1),!0)}updateDocuments(t){for(var{docId:e,docSizeKB:a,isPermanent:r,attachmentCount:s}of t)this.updateDocument(e,a,r,s||0)}getRawMetadata(){return this.metadata}setRawMetadata(t){this.metadata=t}toString(){return`[CollectionMetadata: ${this.name} | Size: ${this.sizeKB.toFixed(2)}KB | Documents: ${this.length}]`}}class w{constructor(t,e=null,a=null){this.success=t,this.data=e,this.error=a}toString(){return`[LacertaDBResult success:${this.success} ${this.error?"error:"+this.error:""}]`}}class A{constructor(t){this._dbName=t,this._metadataKey=`lacertadb_${this._dbName}_quickstore_metadata`,this._documentKeyPrefix=`lacertadb_${this._dbName}_quickstore_data_`,this._metadata=this._loadMetadata()}_loadMetadata(){return m.getItem(this._metadataKey)||{totalSizeKB:0,totalLength:0,documentSizesKB:{},documentModificationTime:{},documentPermanent:{}}}_saveMetadata(){m.setItem(this._metadataKey,this._metadata)}setDocumentSync(t,e=null){e=(t=new B(t,e)).packSync();var a=t._id,r=t._permanent||!1,s=(e=c.stringify({_id:t._id,_created:t._created,_modified:t._modified,_permanent:r,_encrypted:t._encrypted,_compressed:t._compressed,packedData:e}),this._documentKeyPrefix+a);localStorage.setItem(s,e),s=e.length/1024;return(e=!(a in this._metadata.documentSizesKB))?this._metadata.totalLength+=1:this._metadata.totalSizeKB-=this._metadata.documentSizesKB[a],this._metadata.documentSizesKB[a]=s,this._metadata.documentModificationTime[a]=t._modified,this._metadata.documentPermanent[a]=r,this._metadata.totalSizeKB+=s,this._saveMetadata(),e}deleteDocumentSync(t,e=!1){var a;return!(this._metadata.documentPermanent[t]&&!e||(e=this._documentKeyPrefix+t,a=this._metadata.documentSizesKB[t]||0,!localStorage.getItem(e))||(localStorage.removeItem(e),delete this._metadata.documentSizesKB[t],delete this._metadata.documentModificationTime[t],delete this._metadata.documentPermanent[t],this._metadata.totalSizeKB-=a,--this._metadata.totalLength,this._saveMetadata(),0))}getAllKeys(){return Object.keys(this._metadata.documentSizesKB)}getDocumentSync(t,e=null){t=this._documentKeyPrefix+t;return(t=localStorage.getItem(t))?(t=c.parse(t),new B(t,e).unpackSync()):null}toString(){return`[QuickStore: ${this._dbName} | Size: ${this._metadata.totalSizeKB.toFixed(2)}KB | Documents: ${this._metadata.totalLength}]`}}class v{constructor(){this.queue=[],this.processing=!1}async execute(t){return new Promise((e,a)=>{this.queue.push({operation:t,resolve:e,reject:a}),this.process()})}async process(){if(!this.processing&&0!==this.queue.length){for(this.processing=!0;0<this.queue.length;){var{operation:t,resolve:e,reject:a}=this.queue.shift();try{e(await t())}catch(t){a(t)}}this.processing=!1}}toString(){return`[TransactionManager processing:${this.processing} queue:${this.queue.length}]`}}class S{constructor(){this._listeners={beforeAdd:[],afterAdd:[],beforeDelete:[],afterDelete:[],beforeGet:[],afterGet:[]}}on(t,e){if(!this._listeners[t])throw new Error(`Event "${t}" is not supported.`);this._listeners[t].push(e)}off(t,e){this._listeners[t]&&-1<(e=this._listeners[t].indexOf(e))&&this._listeners[t].splice(e,1)}_emit(t,...e){if(this._listeners[t])for(var a of this._listeners[t])a(...e)}_cleanup(){for(var t in this._listeners)this._listeners[t]=[]}toString(){return`[Observer listeners:{${Object.entries(this._listeners).map(([t,e])=>t+":"+e.length).join(" ")}}]`}}class D{constructor(t,e={}){this._dbName=t,this._db=null,this._collections=new Map,this._metadata=new g(t),this._settings=new C(t,e),this._quickStore=new A(this._dbName),this._settings.init()}get quickStore(){return this._quickStore}async init(){var t;for(t of(this.db=await l.openDatabase(this.name,void 0,(t,e,a)=>{this._upgradeDatabase(t,e,a)}),this.data.getCollectionNames())){var e=new T(this,t,this.settings);await e.init(),this.collections.set(t,e)}}_createDataStores(t){for(var e of this.collections.keys())this._createDataStore(t,e)}_createDataStore(t,e){t.objectStoreNames.contains(e)||t.createObjectStore(e,{keyPath:"_id"})}_upgradeDatabase(t,e,a){console.log(`Upgrading database "${this.name}" from version ${e} to `+a),t.objectStoreNames.contains("_metadata")||t.createObjectStore("_metadata",{keyPath:"_id"})}async createCollection(t){var e;return this.collections.has(t)?(console.log(`Collection "${t}" already exists.`),new w(!1,this.collections.get(t),new f(`Collection "${t}" already exists`,p))):(this.db.objectStoreNames.contains(t)||(e=this.db.version+1,this.db.close(),this.db=await l.openDatabase(this.name,e,(e,a,r)=>{this._createDataStore(e,t)})),await(e=new T(this,t,this.settings)).init(),this.collections.set(t,e),this.data.getCollectionMetadata(t),await this.data.saveMetadata(),new w(!0,e))}async deleteCollection(t){var e;return this.collections.has(t)?(await(e=this.collections.get(t)).close(),e.observer._cleanup(),await l.performTransaction(this.db,t,"readwrite",t=>l.clear(t)),this.collections.delete(t),this.data.removeCollectionMetadata(t),await this.data.saveMetadata(),new w(!0,null)):new w(!1,null,new f(`Collection "${t}" does not exist`,y))}async getCollection(t){var e;return this.collections.has(t)?new w(!0,this.collections.get(t)):this.db.objectStoreNames.contains(t)?(await(e=new T(this,t,this.settings)).init(),this.collections.set(t,e),new w(!0,e)):new w(!1,null,new f(`Collection "${t}" does not exist`,y))}async close(){var t;for(t of this.collectionsArray)await t.close();this.db&&(this.db.close(),this.db=null)}async deleteDatabase(){await this.close(),await l.deleteDatabase(this.name),m.removeItem(this.data.metadataKey),this.settings.clear(),this.data=null}get name(){return this._dbName}get db(){return this._db}set db(t){this._db=t}get data(){return this.metadata}set data(t){this.metadata=t}get collectionsArray(){return Array.from(this.collections.values())}get collections(){return this._collections}get metadata(){return this._metadata}set metadata(t){this._metadata=t}get totalSizeKB(){return this.data.totalSizeKB}get totalLength(){return this.data.totalLength}get modifiedAt(){return this.data.modifiedAt}get settings(){return this._settings}get settingsData(){return this.settings.data}toString(){return`[Database: ${this.name} | Collections: ${this.collections.size} | Size: ${this.totalSizeKB.toFixed(2)}KB | Documents: ${this.totalLength}]`}}class B{constructor(t,e=null){this._id=t._id||this._generateId(),this._created=t._created||Date.now(),this._permanent=!!t._permanent,this._encrypted=t._encrypted||!!e,this._compressed=t._compressed||!1,this._attachments=t._attachments||t.attachments||[],t.packedData?(this._packedData=t.packedData,this._modified=t._modified||Date.now(),this._data=null):(this._data=t.data||{},this._modified=Date.now(),this._packedData=new Uint8Array(0)),this._encryptionKey=e||""}get attachments(){return this._attachments}set attachments(t){this._attachments=t}get data(){return this._data}get packedData(){return this._packedData}get encryptionKey(){return this._encryptionKey}set data(t){this._data=t}set packedData(t){this._packedData=t}set encryptionKey(t){this._encryptionKey=t}static hasAttachments(t){return t._attachments&&0<t._attachments.length||t.attachments&&0<t.attachments.length}static async getAttachments(t,e,a){var r;return B.hasAttachments(t)?(r=t._attachments||t.attachments,t.attachments=await h.getAttachments(r),Promise.resolve(t)):[]}static isEncrypted(t){return t._encrypted&&t.packedData}static async decryptDocument(t,e){if(B.isEncrypted(t))return e=await u.decrypt(t.packedData,e),e=c.unpack(e),{_id:t._id,_created:t._created,_modified:t._modified,_encrypted:!0,_compressed:t._compressed,_permanent:!!t._permanent,attachments:t.attachments,data:e};throw new Error("Document is not encrypted.")}async pack(){if(!this.data)throw new Error("No data to pack");let t=c.pack(this.data);return this._compressed&&(t=await this._compressData(t)),this._encrypted&&(t=await this._encryptData(t)),this.packedData=t}packSync(){if(!this.data)throw new Error("No data to pack");if(this._encrypted)throw new Error("Packing synchronously a document being encrypted is impossible.");if(this._compressed)throw new Error("Packing synchronously a document being compressed is impossible.");var t=c.pack(this.data);return this.packedData=t}async unpack(){if(!this.data&&0<this.packedData.length){let t=this.packedData;this._encrypted&&(t=await this._decryptData(t)),this._compressed&&(t=await this._decompressData(t)),this.data=c.unpack(t)}return this.data}unpackSync(){if(!this.data&&0<this.packedData.length){if(this._encrypted)throw new Error("Unpacking synchronously a document being encrypted is impossible.");if(this._compressed)throw new Error("Unpacking synchronously a document being compressed is impossible.");this.data=c.unpack(this.packedData)}return this.data}async _encryptData(t){var e=this.encryptionKey;return u.encrypt(t,e)}async _decryptData(t){var e=this.encryptionKey;return u.decrypt(t,e)}async _compressData(t){return d.compress(t)}async _decompressData(t){return d.decompress(t)}_generateId(){return"xxxx-xxxx-xxxx".replace(/[x]/g,()=>(16*Math.random()|0).toString(16))}async objectOutput(t=!1){this.data||await this.unpack();var e={_id:this._id,_created:this._created,_modified:this._modified,_permanent:this._permanent,_encrypted:this._encrypted,_compressed:this._compressed,attachments:this.attachments,data:this.data};return t&&0<this.attachments.length&&(t=await h.getAttachments(this.attachments),e.attachments=t),e}async databaseOutput(){return this.packedData&&0!==this.packedData.length||await this.pack(),{_id:this._id,_created:this._created,_modified:this._modified,_permanent:!!this._permanent,_compressed:this._compressed,_encrypted:this._encrypted,attachments:this.attachments,packedData:this.packedData}}toString(){return`[Document: ${this._id} | Created: ${new Date(this._created).toISOString()} | Encrypted: ${this._encrypted} | Compressed: ${this._compressed} | Permanent: ${this._permanent}]`}}class C{constructor(t,e={}){this._dbName=t,this._settingsKey=`lacertadb_${this._dbName}_settings`,this._data=this._loadSettings(),this._mergeSettings(e)}init(){if(this.set("sizeLimitKB",this.get("sizeLimitKB")||1/0),this.set("bufferLimitKB",this.get("bufferLimitKB")||-.2*this.get("sizeLimitKB")),this.get("bufferLimitKB")<-.8*this.get("sizeLimitKB"))throw new Error("Buffer limit cannot be below -80% of the size limit.");this.set("freeSpaceEvery",this._validateFreeSpaceSetting(this.get("freeSpaceEvery")))}_validateFreeSpaceSetting(t=1e4){if(void 0===t||!1===t||0===t)return 1/0;if(t<1e3&&0!==t)throw new Error("Invalid freeSpaceEvery value. It must be 0, Infinity, or above 1000.");return 1e3<=t&&t<1e4&&console.warn("Warning: freeSpaceEvery value is between 1000 and 10000, which may lead to frequent freeing."),t}_loadSettings(){return m.getItem(this.settingsKey)||{}}_saveSettings(){m.setItem(this.settingsKey,this.data)}_mergeSettings(t){this.data=Object.assign(this.data,t),this._saveSettings()}get(t){return this.data[t]}set(t,e){this.data[t]=e,this._saveSettings()}remove(t){delete this.data[t],this._saveSettings()}clear(){this.data={},this._saveSettings()}get dbName(){return this._dbName}get data(){return this._data}set data(t){this._data=t}get settingsKey(){return this._settingsKey}toString(){return`[Settings: ${this.dbName} | SizeLimit: ${this.get("sizeLimitKB")}KB | BufferLimit: ${this.get("bufferLimitKB")}KB]`}}class T{constructor(t,e,a){this._database=t,this._collectionName=e,this._settings=a,this._metadata=null,this._lastFreeSpaceTime=0,this._observer=new S,this._transactionManager=new v,this._freeSpaceInterval=null,this._freeSpaceHandler=null}get observer(){return this._observer}async createIndex(t,e={}){let a=e.name||t.replace(/\./g,"_");var r=this.database.db.version+1;this.database.db.close(),this.database.db=await l.openDatabase(this.database.name,r,r=>{r.objectStoreNames.contains(this.name)&&!(r=r.transaction([this.name]).objectStore(this.name)).indexNames.contains(a)&&r.createIndex(a,t,{unique:e.unique||!1,multiEntry:e.multiEntry||!1})})}async init(){this.metadata=this.database.metadata.getCollectionMetadata(this.name),this.settingsData.freeSpaceEvery!==1/0&&(this._freeSpaceHandler=()=>this._maybeFreeSpace(),this._freeSpaceInterval=setInterval(this._freeSpaceHandler,this.settingsData.freeSpaceEvery))}get name(){return this._collectionName}get sizes(){return this.metadataData.documentSizes||{}}get modifications(){return this.metadataData.documentModifiedAt||{}}get attachments(){return this.metadataData.documentAttachments||{}}get permanents(){return this.metadataData.documentPermanent||{}}get keys(){return Object.keys(this.sizes)}get documentsMetadata(){var t,e=this.keys,a=this.sizes,r=this.modifications,s=this.permanents,i=this.attachments,n=new Array(e.length),o=0;for(t of e)n[o++]={id:t,size:a[t],modified:r[t],permanent:s[t],attachment:i[t]};return n}get settings(){return this._settings}get settingsData(){return this.settings.data}set settings(t){this._settings=t}get lastFreeSpaceTime(){return this._lastFreeSpaceTime}set lastFreeSpaceTime(t){this._lastFreeSpaceTime=t}get database(){return this._database}get metadata(){return this.database.metadata.getCollectionMetadata(this.name)}get metadataData(){return this.metadata.getRawMetadata()}set metadata(t){this._metadata=t}get sizeKB(){return this.metadataData.sizeKB}get length(){return this.metadataData.length}get totalSizeKB(){return this.sizeKB}get totalLength(){return this.length}get modifiedAt(){return this.metadataData.modifiedAt}get isFreeSpaceEnabled(){return this.settingsData.freeSpaceEvery!==1/0}get shouldRunFreeSpaceSize(){return this.totalSizeKB>this.settingsData.sizeLimitKB+this.settingsData.bufferLimitKB}get shouldRunFreeSpaceTime(){return this.isFreeSpaceEnabled&&Date.now()-this.lastFreeSpaceTime>=this.settingsData.freeSpaceEvery}async _maybeFreeSpace(){if(this.shouldRunFreeSpaceSize||this.shouldRunFreeSpaceTime)return this.freeSpace(this.settingsData.sizeLimitKB)}async addDocument(t,e=null){return this._transactionManager.execute(async()=>{this.observer._emit("beforeAdd",t);var a=new B(t,e),r=[];if(B.hasAttachments(t)){var s=t._attachments||t.attachments;for(let t=0;t<s.length;t++)r.push(`${this.database.name}/${this.name}/${a._id}/`+t);a._attachments=r}let i=await a.databaseOutput();var n,o=i._id,c=i._permanent||!1,d=i.packedData.byteLength/1024;let u=!(o in this.metadataData.documentSizes);try{await l.performTransaction(this.database.db,this.name,"readwrite",t=>u?l.add(t,i):l.put(t,i)),0<r.length&&(n=t._attachments||t.attachments,await h.saveAttachments(this.database.name,this.name,a._id,n)),this.metadata.updateDocument(o,d,c,r.length),await this.database.metadata.saveMetadata()}catch(n){if(0<r.length)try{await h.deleteAttachments(this.database.name,this.name,a._id)}catch(n){}throw n}return await this._maybeFreeSpace(),this.observer._emit("afterAdd",t),u})}async getDocument(t,e=null,a=!1){if(this.observer._emit("beforeGet",t),t in this.metadataData.documentSizes){var r=await l.performTransaction(this.database.db,this.name,"readonly",e=>l.get(e,t));if(r){let t;if(B.isEncrypted(r)){if(!e)return!1;t=new B(r,e)}else t=new B(r);return e=await t.objectOutput(a),this.observer._emit("afterGet",e),e}}return!1}async getDocuments(t,e=null,a=!1){let r=[],s=t.filter(t=>t in this.metadataData.documentSizes);return 0!==s.length&&await l.performTransaction(this.database.db,this.name,"readonly",async t=>{var i,n=s.map(e=>l.get(t,e));for(i of await Promise.all(n))if(i){let t;if(B.isEncrypted(i)){if(!e)continue;t=new B(i,e)}else t=new B(i);var o=await t.objectOutput(a);r.push(o)}}),r}async deleteDocument(t,e=!1){return this.observer._emit("beforeDelete",t),!(this.permanents[t]&&!e)&&t in this.sizes&&(0<(this.metadata.documentAttachments[t]||0)&&await h.deleteAttachments(this.database.name,this.name,t),await l.performTransaction(this.database.db,this.name,"readwrite",e=>l.delete(e,t)),this.metadata.deleteDocument(t),await this.database.metadata.saveMetadata(),this.observer._emit("afterDelete",t),!0)}async freeSpace(t){let e;this.lastFreeSpaceTime=Date.now();var a,r=this.sizeKB;if(0<=t){if(r<=t)return 0;e=r-t}else t=r-(e=-t);let s=0;for([a]of Object.entries(this.metadataData.documentModifiedAt).filter(([t])=>!this.metadataData.documentPermanent[t]).sort((t,e)=>t[1]-e[1]))if(this.sizeKB>t){if(s+=this.metadataData.documentSizes[a],await this.deleteDocument(a,!0),s>=e)break}return s}async query(t={},e={}){let{encryptionKey:a=null,limit:r=1/0,offset:s=0,orderBy:i=null,index:n=null}=e,o=[],c=0,h=0;return await l.performTransaction(this.database.db,this.name,"readonly",async e=>{let d=e,u=(n&&e.indexNames.contains(n)&&(d=e.index(n)),i?d.openCursor(null,"asc"===i?"next":"prev"):d.openCursor());return new Promise((e,i)=>{u.onsuccess=async i=>{if(!(i=i.target.result)||c>=r)e(o);else{var n,d=i.value;if(h<s)h++;else{let e;if(B.isEncrypted(d)){if(!a)return void i.continue();e=new B(d,a)}else e=new B(d);if(0<Object.keys(t).length){var u,l=await e.objectOutput();let a=!0;for(u in t)if((u.includes(".")?(n=l.data,u.split(".").reduce((t,e)=>(t||{})[e],n)):l.data[u])!==t[u]){a=!1;break}if(!a)return void i.continue()}o.push(await e.objectOutput()),c++}i.continue()}},u.onerror=()=>i(u.error)})}),o}async close(){this._freeSpaceInterval&&(clearInterval(this._freeSpaceInterval),this._freeSpaceInterval=null,this._freeSpaceHandler=null)}toString(){return`[Collection: ${this.name} | Database: ${this.database.name} | Size: ${this.sizeKB.toFixed(2)}KB | Documents: ${this.length}]`}}},function(t,e,a){var r=(()=>{var t=new ArrayBuffer(2560),e=new Uint8Array(t,0,256),a=new Uint8Array(t,256,256),r=new Uint32Array(t,512,128),s=new Uint32Array(t,1024,128),i=new Uint32Array(t,1536,128),n=new Uint32Array(t,2048,128);e.set(Uint8Array.from("AAAABBBBCCCCDDDDEEEEFFFFGGGGHHHHIIIIJJJJKKKKLLLLMMMMNNNNOOOOPPPPQQQQRRRRSSSSTTTTUUUUVVVVWWWWXXXXYYYYZZZZaaaabbbbccccddddeeeeffffgggghhhhiiiijjjjkkkkllllmmmmnnnnooooppppqqqqrrrrssssttttuuuuvvvvwwwwxxxxyyyyzzzz0000111122223333444455556666777788889999++++////".split("").map((function(t){return 255&t.charCodeAt(0)})))),a.set(Uint8Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("").map((function(t){return 255&t.charCodeAt(0)})))),r.set(new Uint32Array(128).fill(33554431)),s.set(new Uint32Array(128).fill(33554431)),i.set(new Uint32Array(128).fill(33554431)),n.set(new Uint32Array(128).fill(33554431)),Object.entries({43:[248,57347,8392448,4063232],47:[252,61443,12586752,4128768],48:[208,16387,3328,3407872],49:[212,20483,4197632,3473408],50:[216,24579,8391936,3538944],51:[220,28675,12586240,3604480],52:[224,32771,3584,3670016],53:[228,36867,4197888,3735552],54:[232,40963,8392192,3801088],55:[236,45059,12586496,3866624],56:[240,49155,3840,3932160],57:[244,53251,4198144,3997696],65:[0,0,0,0],66:[4,4096,4194304,65536],67:[8,8192,8388608,131072],68:[12,12288,12582912,196608],69:[16,16384,256,262144],70:[20,20480,4194560,327680],71:[24,24576,8388864,393216],72:[28,28672,12583168,458752],73:[32,32768,512,524288],74:[36,36864,4194816,589824],75:[40,40960,8389120,655360],76:[44,45056,12583424,720896],77:[48,49152,768,786432],78:[52,53248,4195072,851968],79:[56,57344,8389376,917504],80:[60,61440,12583680,983040],81:[64,1,1024,1048576],82:[68,4097,4195328,1114112],83:[72,8193,8389632,1179648],84:[76,12289,12583936,1245184],85:[80,16385,1280,1310720],86:[84,20481,4195584,1376256],87:[88,24577,8389888,1441792],88:[92,28673,12584192,1507328],89:[96,32769,1536,1572864],90:[100,36865,4195840,1638400],97:[104,40961,8390144,1703936],98:[108,45057,12584448,1769472],99:[112,49153,1792,1835008],100:[116,53249,4196096,1900544],101:[120,57345,8390400,1966080],102:[124,61441,12584704,2031616],103:[128,2,2048,2097152],104:[132,4098,4196352,2162688],105:[136,8194,8390656,2228224],106:[140,12290,12584960,2293760],107:[144,16386,2304,2359296],108:[148,20482,4196608,2424832],109:[152,24578,8390912,2490368],110:[156,28674,12585216,2555904],111:[160,32770,2560,2621440],112:[164,36866,4196864,2686976],113:[168,40962,8391168,2752512],114:[172,45058,12585472,2818048],115:[176,49154,2816,2883584],116:[180,53250,4197120,2949120],117:[184,57346,8391424,3014656],118:[188,61442,12585728,3080192],119:[192,3,3072,3145728],120:[196,4099,4197376,3211264],121:[200,8195,8391680,3276800],122:[204,12291,12585984,3342336]}).forEach((function(t){r[parseInt(t[0])]=4294967295&t[1][0],s[parseInt(t[0])]=4294967295&t[1][1],i[parseInt(t[0])]=4294967295&t[1][2],n[parseInt(t[0])]=4294967295&t[1][3]}));class o{constructor(){this._CHNK_L_=Math.pow(108,2)/2|0,this._CHNK_L_STR_=3*this._CHNK_L_|0,this._CHNK_L_BUFF_=4*this._CHNK_L_|0,this._PAD_C_=255&"=".charCodeAt(0),this._E0_=e.slice(0,e.length),this._E1_=a.slice(0,a.length),this._D0_=r.slice(0,r.length),this._D1_=s.slice(0,s.length),this._D2_=i.slice(0,i.length),this._D3_=n.slice(0,n.length),this._AB_=new ArrayBuffer(this._CHNK_L_BUFF_+4|0),this._u32aT_=new Uint32Array(this._AB_,0,1),this._u8aT_=new Uint8Array(this._AB_,0,3),this._T_=new Uint8Array(this._AB_,4,0|this._CHNK_L_BUFF_)}get PAD_C(){return 255&this._PAD_C_}get CHNK_L_STR(){return 0|this._CHNK_L_STR_}get u32aT0(){return this._u32aT_[0]}set u32aT0(t){this._u32aT_[0]=(0|t)>>>0}get u8aTa(){return this._u8aT_[0]}get u8aTb(){return this._u8aT_[1]}get u8aTc(){return this._u8aT_[2]}_base64_decode_u32ax1(t,e){this.u32aT0=this._D0_[255&t.charCodeAt(e=(0|e)>>>0)]|this._D1_[255&t.charCodeAt(e+1|0)]|this._D2_[255&t.charCodeAt(e+2|0)]|this._D3_[255&t.charCodeAt(e+3|0)]}_base64_encode_u8ax4(t,e,a){this._T_[0|(e=(0|e)>>>0)]=this._E0_[t[(0|(a=(0|a)>>>0))>>>0]],this._T_[e+1|0]=this._E1_[(3&t[(0|a)>>>0])<<4|t[(a+1|0)>>>0]>>4&15],this._T_[e+2|0]=this._E1_[(15&t[(a+1|0)>>>0])<<2|t[(a+2|0)>>>0]>>6&3],this._T_[e+3|0]=this._E1_[t[(a+2|0)>>>0]]}_base64_encode_final(t,e,a,r){switch(r=(0|r)>>>0,((a=(0|a)>>>0)-(e=(0|e)>>>0)|0)>>>0){case 1:return this._T_[0|r]=this._E0_[t[(0|e)>>>0]],this._T_[r+1|0]=this._E1_[(3&t[(0|e)>>>0])<<4|t[(e+1|0)>>>0]>>4&15],this._T_[r+2|0]=this._PAD_C_,this._T_[r+3|0]=this._PAD_C_,this._T_.subarray(0,0|(r=r+4|0));case 2:return this._T_[0|r]=this._E0_[t[(0|e)>>>0]],this._T_[r+1|0]=this._E1_[(3&t[(0|e)>>>0])<<4|t[(e+1|0)>>>0]>>4&15],this._T_[r+2|0]=this._E1_[(15&t[(e+1|0)>>>0])<<2|t[(e+2|0)>>>0]>>6&3],this._T_[r+3|0]=this._PAD_C_,this._T_.subarray(0,0|(r=r+4|0));case 0:return this._T_.subarray(0,0|r);default:return this._T_}}_base64_decode_final(t,e,a,r,s){switch(a=(0|a)>>>0,r=(0|r)>>>0,0|(s=(0|s)>>>0)){case 0:return this.u32aT0=(this._D0_[e.charCodeAt(0|a)]|this._D1_[e.charCodeAt(a+1|0)]|this._D2_[e.charCodeAt(a+2|0)]|this._D3_[e.charCodeAt(a+3|0)]|0)>>>0,t[0|r]=255&this.u32aT0,t[r+1|0]=this.u32aT0>>8&255,t[r+2|0]=this.u32aT0>>16&255,r+3|0;case 1:return this.u32aT0=(0|this._D0_[e.charCodeAt(0|a)])>>>0,t[0|r]=255&this.u32aT0,r+1|0;case 2:return this.u32aT0=(this._D0_[e.charCodeAt(0|a)]|this._D1_[e.charCodeAt(a+1|0)]|0)>>>0,t[0|r]=255&this.u32aT0,r+1|0;default:return this.u32aT0=(this._D0_[e.charCodeAt(0|a)]|this._D1_[e.charCodeAt(a+1|0)]|this._D2_[e.charCodeAt(a+2|0)]|0)>>>0,t[0|r]=255&this.u32aT0,t[r+1|0]=this.u32aT0>>8&255,r+2|0}}_base64_store_u8ax3(t,e){t[e=(0|e)>>>0]=this.u8aTa,t[e+1|0]=this.u8aTb,t[e+2|0]=this.u8aTc}get_max_round_str(t){return 0|Math.ceil(t/this.CHNK_L_STR)}base64_encode(t,e){var a=0|t.length,r=(e|=0)*this.CHNK_L_STR|0,s=0,i=Math.min(r+this.CHNK_L_STR|0,0|a)-2|0;if(0<(0|i))for(;(0|r)<(0|i);r=(r+3|0)>>>0,s=s+4|0)this._base64_encode_u8ax4(t,s,r);return o.encodeChars_(this._base64_encode_final(t,r,a,s))}bytesToBase64(t){for(var e="",a=0,r=this.get_max_round_str(t.length);(0|a)<(0|r);a=(a+1|0)>>>0)e+=this.base64_encode(t,0|a);return e}base64ToBytes(t){var e,a,r=0|t.length,s=0,i=0,n=0;if(0==(0|r))return new Uint8Array(0);for(t.charCodeAt(r-1|0)===this.PAD_C&&(n=n+1|0,t.charCodeAt((r=r-1|0)-1|0)===this.PAD_C)&&(r=r-1|0,n=n+1|0),e=new Uint8Array(t.length/4*3-n),a=0==(0|(n=3&r))?(r>>>2)-1|0:r>>>2;(0|s)<(0|a);s=(s+1|0)>>>0)this._base64_decode_u32ax1(t,s<<2),this._base64_store_u8ax3(e,i),i=i+3|0;return this._base64_decode_final(e,t,s<<=2,i,n),e}}return o.charCode_=function(t){return 255&t.charCodeAt(0)},o.charCodeAt_=function(t,e){return 255&t.charCodeAt(0|e)},o.encodeChars_=function(t){return 0<(0|t.length)?String.fromCharCode.apply(null,t):""},o})();t.exports={B64chromium:r}},function(t,e,a){a.r(e),e=a(0),"undefined"!=typeof window?(window.Database=e.Database,window.Document=e.Document,window.Collection=e.Collection):(self.Database=e.Database,self.Document=e.Document,self.Collection=e.Collection)}]);
|
|
1
|
+
(t=>{var e={};function a(r){var i;return(e[r]||(i=e[r]={i:r,l:!1,exports:{}},t[r].call(i.exports,i,i.exports,a),i.l=!0,i)).exports}a.m=t,a.c=e,a.d=function(t,e,r){a.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:r})},a.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},a.t=function(t,e){if(1&e&&(t=a(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var r=Object.create(null);if(a.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var i in t)a.d(r,i,function(e){return t[e]}.bind(null,i));return r},a.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return a.d(e,"a",e),e},a.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},a.p="",a(a.s=1)})([function(t,e,a){a.r(e);let r=240,i=0,s=16,n=32,o=48,h=64,c=80,l=96,d=112,u=128,m=144,f=160,p=176,g=192,w=224,y=0,b=1,_=2,v=3,S=16,A=17,k=18,D=19,B=20,z=21,I=22,E=23,U=24,M=25,V=26,C=32,K=33,P=34,x=35,T=48,F=49,O=50,$=51,j=52,N=53,R=54,L=55,q=64,H=65,G=66,W=67,Y=68,X=69,J=70,Q=71,Z=72,tt=80,et=81,at=82,rt=83,it=96,st=97,nt=98,ot=99,ht=100,ct=101,lt=102,dt=103,ut=104,mt=105,ft=106,pt=107,gt=112,wt=113,yt=114,bt=128,_t=129,vt=130,St=131,At=144,kt=145,Dt=160,Bt=161,zt=162,It=163,Et=164,Ut=165,Mt=166,Vt=167,Ct=168,Kt=176,Pt=192,xt=193,Tt=208,Ft=209,Ot=224,$t=225,jt=16;var Nt=16-(15&(Rt=new ArrayBuffer(128)).byteLength)&15,Rt=Rt.slice(Nt);let Lt=new Float32Array(Rt,0,32),qt=new Float64Array(Rt,0,16);new Int32Array(Rt,0,32),new Int16Array(Rt,0,64),new Int8Array(Rt,0,128),new Uint32Array(Rt,0,32),new Uint16Array(Rt,0,64),new Uint8Array(Rt,0,128);let Ht=new Array(256),Gt=new Array(256),Wt=new Array(256);var Yt=[[A,2],[k,4],[D,4],[B,4],[z,8],[C,8],[K,8]];for(let t=0;t<Yt.length;t++){var[Xt,Jt]=Yt[t];Gt[Xt]=Jt}var Qt,Zt,te=[[it,1],[st,1],[nt,1],[ot,2],[ht,2],[ct,4],[lt,4],[dt,4],[ut,8],[mt,8],[ft,8],[W,1],[Y,2],[X,4],[J,4],[Q,8]];for(let t=0;t<te.length;t++){var[ee,ae]=te[t];Wt[ee]=ae}for([Qt,Zt]of[[it,"Uint8Array"],[st,"Int8Array"],[nt,"Uint8ClampedArray"],[ot,"Uint16Array"],[ht,"Int16Array"],[ct,"Uint32Array"],[lt,"Int32Array"],[dt,"Float32Array"],[ut,"Float64Array"],[mt,"BigInt64Array"],[ft,"BigUint64Array"],[pt,"DataView"]]){var re=globalThis[Zt];re&&(Ht[Qt]=re)}class ie{constructor(){this.blockSize=16,this.tempBuffer=new ArrayBuffer(1040),this.tempOffset=jt-(15&this.tempBuffer.byteLength)&15,this.alignedTempBuffer=this.tempBuffer.slice(this.tempOffset),this.tempF32=new Float32Array(this.alignedTempBuffer),this.tempF64=new Float64Array(this.alignedTempBuffer),this.tempI32=new Int32Array(this.alignedTempBuffer)}canOptimize(t){var e=t.length;if(!(8<=e&(0==(e&e-1)||16<=e)))return!1;var a=typeof t[0];if(!("number"==a|0))return!1;var r=1+(e>>>5);for(let i=0;i<r;i++)if(typeof t[i<<5&e-1]!=a)return!1;return!0}analyzeNumericArray(t){let e=1,a=1/0,r=-1/0,i=1;var s,n=t.length,o=n>>>4;for(let s=0;s<o;s++){var h=s<<4;for(let s=0;s<4;s++){var c=h+s;c<n&&(e&=(c=t[c])===(0|(Lt[s]=c))|0,a=a<c?a:c,r=r>c?r:c,i)&&Lt[s]!==c&&(i=0)}}for(let s=o<<4;s<n;s++){var l=t[s];e&=l===(0|l)|0,a=a<l?a:l,r=r>l?r:l,i&&(Lt[0]=l,Lt[0]!==l)&&(i=0)}return e?(s=Math.max(Math.abs(a),Math.abs(r)))<=127?{type:W,elementSize:1}:s<=32767?{type:Y,elementSize:2}:{type:X,elementSize:4}:i?{type:J,elementSize:4}:{type:Q,elementSize:8}}processInBlocks(t,e){var a=[],r=t.length,i=r+16-1>>>4;for(let o=0;o<i;o++){var s=o<<4,n=Math.min(16+s,r);s=this.process128BitBlock(t,s,n,e);a.push(...s)}return a}process128BitBlock(t,e,a,r){var i=a-e;if(i<=4){let a=new Array(i);for(let s=0;s<i;s++)a[s]=r(t[e+s]);return a}let s=new Array(i);var n=i>>>2;for(let a=0;a<n;a++){var o=a<<2;for(let a=0;a<4;a++)this.tempF32[a]=t[e+o+a];for(let t=0;t<4;t++)s[o+t]=r(this.tempF32[t])}for(let a=n<<2;a<i;a++)s[a]=r(t[e+a]);return s}}class se{constructor(t=65536){this.size=(t+15&-16)>>>0,this.buffer=new ArrayBuffer(this.size+jt),this.offset=jt-(15&this.buffer.byteLength)&15,this.alignedBuffer=this.buffer.slice(this.offset),this.u8=new Uint8Array(this.alignedBuffer),this.view=new DataView(this.alignedBuffer),this.pos=0,this.alignedViews={u16:null,u32:null,f32:null,f64:null,i64:null}}ensure(t){if(this.pos+(t|=0)>this.size){t=(Math.max(this.size<<1,this.size+t)+15&-16)>>>0;var e,a=new ArrayBuffer(t+jt),r=jt-(15&a.byteLength)&15,i=(r=a.slice(r),new Uint8Array(r)),s=(n=this.pos)>>>4,n=15&n;for(let t=0;t<s;t++){var o=t<<4,h=this.u8.subarray(o,16+o);i.set(h,o)}0<n&&(n=this.u8.subarray(e=s<<4,e+n),i.set(n,e)),this.buffer=a,this.alignedBuffer=r,this.u8=i,this.view=new DataView(r),this.size=t,this.alignedViews={u16:null,u32:null,f32:null,f64:null,i64:null}}}alignPos(t){t=t-1|0,this.pos=(this.pos+t&~t)>>>0}writeU8(t){this.ensure(1),this.u8[this.pos++]=255&t}writeU16(t){if(this.alignPos(2),this.ensure(2),!(0==(1&this.pos)|0))throw new Error("Alignment error: position not 2-byte aligned");this.view.setUint16(this.pos,65535&t,!0),this.pos=this.pos+2|0}writeI16(t){if(this.alignPos(2),this.ensure(2),!(0==(1&this.pos)|0))throw new Error("Alignment error: position not 2-byte aligned");this.view.setInt16(this.pos,t,!0),this.pos=this.pos+2|0}writeU32(t){if(this.alignPos(4),this.ensure(4),!(0==(3&this.pos)|0))throw new Error("Alignment error: position not 4-byte aligned");this.view.setUint32(this.pos,t>>>0,!0),this.pos=this.pos+4|0}writeI32(t){if(this.alignPos(4),this.ensure(4),!(0==(3&this.pos)|0))throw new Error("Alignment error: position not 4-byte aligned");this.view.setInt32(this.pos,t,!0),this.pos=this.pos+4|0}writeF32(t){if(this.alignPos(4),this.ensure(4),!(0==(3&this.pos)|0))throw new Error("Alignment error: position not 4-byte aligned");this.view.setFloat32(this.pos,+t,!0),this.pos=this.pos+4|0}writeF64(t){if(this.alignPos(8),this.ensure(8),!(0==(7&this.pos)|0))throw new Error("Alignment error: position not 8-byte aligned");this.view.setFloat64(this.pos,+t,!0),this.pos=this.pos+8|0}writeBigInt64(t){if(this.alignPos(8),this.ensure(8),!(0==(7&this.pos)|0))throw new Error("Alignment error: position not 8-byte aligned");this.view.setBigInt64(this.pos,t,!0),this.pos=this.pos+8|0}writeVarint(t){if(t>>>=0,this.ensure(5),t<128|0)this.u8[this.pos++]=t;else if(t<16384|0)this.u8[this.pos]=127&t|128,this.u8[this.pos+1]=t>>>7,this.pos+=2;else{let e=this.pos;for(;128<=t;)this.u8[e++]=127&t|128,t>>>=7;this.u8[e++]=t,this.pos=e}}writeBulkAligned(t,e){e=Math.min(e,jt);var a,r=(this.alignPos(e),t.byteLength||t.length);this.ensure(r),t.buffer?(a=t.byteOffset||0)%e==0|0?(e=new Uint8Array(t.buffer,a,r),this.copy128BitAligned(e,r)):((e=new Uint8Array(r)).set(new Uint8Array(t.buffer,a,r)),this.copy128BitAligned(e,r)):this.u8.set(t,this.pos),this.pos=this.pos+r|0}copy128BitAligned(t,e){var a,r=e>>>4;e&=15;for(let e=0;e<r;e++){var i=e<<4,s=this.pos+i;i=t.subarray(i,16+i);this.u8.set(i,s)}0<e&&(e=t.subarray(a=r<<4,a+e),this.u8.set(e,this.pos+a))}writePackedArray(t,e){var a=0|t.length,r=(this.writeVarint(a),Wt[e]);if(!r)throw new Error("Unknown element size for type: 0x"+e.toString(16));switch(this.alignPos(Math.min(r,8)),this.ensure(a*r),e){case W:for(let e=0;e<a;e++)this.view.setInt8(this.pos,t[e]),this.pos+=1;break;case Y:for(let e=0;e<a;e++)this.view.setInt16(this.pos,t[e],!0),this.pos+=2;break;case X:for(let e=0;e<a;e++)this.view.setInt32(this.pos,t[e],!0),this.pos+=4;break;case J:for(let e=0;e<a;e++)this.view.setFloat32(this.pos,t[e],!0),this.pos+=4;break;case Q:for(let e=0;e<a;e++)this.view.setFloat64(this.pos,t[e],!0),this.pos+=8;break;default:throw new Error("Unknown packed array type: 0x"+e.toString(16))}}reset(){this.pos=0}getResult(){return this.u8.subarray(0,this.pos)}}class ne{constructor(){this.simdProcessor=new ie,this.constructorMap=new Map,this.initConstructorMap(),this.TYPE_FLAGS={IS_ARRAY:1,IS_TYPED_ARRAY:2,IS_OBJECT:4,IS_COLLECTION:8,IS_ERROR:16,IS_DATE:32,IS_REGEXP:64,IS_BINARY:128}}initConstructorMap(){var t,e,a,r,i=[[Date,At],[RegExp,Kt],[Map,bt],[Set,_t],[WeakMap,vt],[WeakSet,St],[ArrayBuffer,gt],[DataView,pt]];for([t,e]of[["Uint8Array",it],["Int8Array",st],["Uint8ClampedArray",nt],["Uint16Array",ot],["Int16Array",ht],["Uint32Array",ct],["Int32Array",lt],["Float32Array",dt],["Float64Array",ut],["BigInt64Array",mt],["BigUint64Array",ft],["SharedArrayBuffer",yt]]){var s=globalThis[t];s&&i.push([s,e])}for([a,r]of i)this.constructorMap.set(a,r)}detect(t){if(null===t)return y;if(void 0===t)return b;var e=typeof t;switch(e){case"boolean":return t?v:_;case"number":return this.detectNumber(t);case"bigint":return this.detectBigInt(t);case"string":return this.detectString(t);case"symbol":return this.detectSymbol(t);case"object":return null===t?y:this.detectObject(t);case"function":return b;default:throw new Error("Unknown type: "+e)}}detectNumber(t){if(t!=t|0)return I;qt[0]=t;var e,a=(e=new Uint32Array(qt.buffer,qt.byteOffset))[0],r=2146435072;return((e=e[1])&r)==r&0===a&0==(1048575&e)?(2147483648&e)>>>31?U:E:0===t&(2147483648&e)>>>31?M:t===(0|t)|0?(r=Math.abs(t))<=127?S:r<=32767?A:r<=2147483647?k:V:(Lt[0]=t,Lt[0]===t|0?B:z)}detectBigInt(t){var e=t<0n|0;return((t=(e?-t:t)<=0x7fffffffffffffffn|0)?[C,K]:[P,x])[e]}detectString(t){if("string"!=typeof t)throw new Error("detectString called with non-string value: "+typeof t);var e=t.length;if(0===e)return T;let a=1;var r,i=e>>>4;for(let e=0;e<i&&a;e++){var s=e<<4;for(let e=0;e<16;e++){a&=t.charCodeAt(s+e)<=127|0}}for(let r=i<<4;r<e&&a;r++){a&=t.charCodeAt(r)<=127|0}return a?[$,O,F,F][r=e<16|(e<256)<<1]:(r=(r=(new TextEncoder).encode(t).length)<16|(r<256)<<1,[R,N,j,j][r])}detectSymbol(t){if("symbol"!=typeof t)throw new Error("detectSymbol called with non-symbol value: "+typeof t);return void 0!==Symbol.keyFor(t)|0?$t:Ot}detectObject(t){if(null===t)return y;var e,a=t.constructor,r=this.constructorMap.get(a);return void 0!==r?r===At?(e=t.getTime())==e|0?At:kt:r:0|Array.isArray(t)?this.detectArray(t):0|ArrayBuffer.isView(t)?this.detectTypedArrayType(t):t instanceof Error|0?this.detectErrorType(t):"undefined"!=typeof Blob&&t instanceof Blob|0?t instanceof File|0?xt:Pt:a===Object|void 0===a|null===a?0===Object.keys(t).length|0?tt:et:(e=Object.getPrototypeOf(t))===Object.prototype|null===e?0===Object.keys(t).length|0?tt:at:rt}detectArray(t){var e=t.length;if(0===e)return q;let a=0,r=!1;for(let i=0;i<e;i++)i in t?a++:r=!0;return r||a<3*e>>>2?G:this.simdProcessor.canOptimize(t)?this.simdProcessor.analyzeNumericArray(t).type:H}detectTypedArrayType(t){var e=t.constructor.name;t=e.length;switch(e.charCodeAt(0)<<8|e.charCodeAt(t-1)){case 21881:return"Uint8Array"===e?it:this.fallbackTypedArrayDetection(e);case 18809:return"Int8Array"===e?st:this.fallbackTypedArrayDetection(e);case 21860:return nt;case 18041:return e.includes("32")?dt:ut;case 17017:return e.startsWith("BigU")?ft:mt;default:return this.fallbackTypedArrayDetection(e)}}fallbackTypedArrayDetection(t){return{DataView:pt,Uint8Array:it,Int8Array:st,Uint8ClampedArray:nt,Uint16Array:ot,Int16Array:ht,Uint32Array:ct,Int32Array:lt,Float32Array:dt,Float64Array:ut,BigInt64Array:mt,BigUint64Array:ft}[t]||it}detectErrorType(t){var e=t.constructor.name;switch(e.charCodeAt(0)){case 69:return 114===e.charCodeAt(1)?Dt:Bt;case 82:return 110===e.charCodeAt(2)?zt:It;case 83:return Et;case 84:return Ut;case 85:return Mt;case 65:return Vt;default:return Ct}}}Nt=class{constructor(t={}){this.options={compression:t.compression||!1,deduplication:!1!==t.deduplication,shareArrayBuffers:!1!==t.shareArrayBuffers,simdOptimization:!1!==t.simdOptimization,detectCircular:!1!==t.detectCircular,memoryPoolSize:t.memoryPoolSize||65536,...t},this.pool=new se(this.options.memoryPoolSize),this.detector=new ne,this.simdProcessor=new ie,this.refs=new Map,this.circularRefs=new Set,this.strings=new Map,this.buffers=new Map,this.encoder=new TextEncoder,this.decoder=new TextDecoder}serialize(t){return this.resetState(),this.pool.writeU32(1413632565),this.pool.writeU8(5),this.options.detectCircular&&this.detectCircularReferences(t,new WeakSet),this.writeValue(t),this.pool.getResult()}resetState(){this.pool.reset(),this.refs.clear(),this.circularRefs.clear(),this.strings.clear(),this.buffers.clear()}detectCircularReferences(t,e){if("object"==typeof t&&null!==t)if(e.has(t))this.circularRefs.add(t);else{e.add(t);try{if(Array.isArray(t))for(let a=0;a<t.length;a++)a in t&&this.detectCircularReferences(t[a],e);else if(t instanceof Map)for(var[a,r]of t)this.detectCircularReferences(a,e),this.detectCircularReferences(r,e);else if(t instanceof Set)for(var i of t)this.detectCircularReferences(i,e);else for(var s in t)if(t.hasOwnProperty(s))try{this.detectCircularReferences(t[s],e)}catch(a){}}finally{e.delete(t)}}}writeValue(t){if(this.options.detectCircular&&"object"==typeof t&&null!==t&&this.circularRefs.has(t)){var e=this.refs.get(t);if(void 0!==e)return this.pool.writeU8(Ft),void this.pool.writeVarint(e);this.refs.set(t,this.refs.size)}if(this.options.deduplication&&"object"==typeof t&&null!==t&&!this.circularRefs.has(t)){if(void 0!==(e=this.refs.get(t)))return this.pool.writeU8(Tt),void this.pool.writeVarint(e);this.refs.set(t,this.refs.size)}if(this.options.deduplication&&"string"==typeof t&&3<t.length){if(void 0!==(e=this.strings.get(t)))return this.pool.writeU8(L),void this.pool.writeVarint(e);this.strings.set(t,this.strings.size)}if(this.options.shareArrayBuffers&&t instanceof ArrayBuffer){if(void 0!==(e=this.buffers.get(t)))return this.pool.writeU8(wt),void this.pool.writeVarint(e);this.buffers.set(t,this.buffers.size)}var a=this.detector.detect(t),y=(this.pool.writeU8(a),a&r);switch(y){case i:break;case s:this.writeNumber(t,a);break;case n:this.writeBigInt(t,a);break;case o:this.writeString(t,a);break;case h:this.writeArray(t,a);break;case c:this.writeObject(t,a);break;case l:this.writeTypedArray(t,a);break;case d:this.writeArrayBuffer(t,a);break;case u:this.writeCollection(t,a);break;case m:this.writeDate(t,a);break;case f:this.writeError(t,a);break;case p:this.writeRegExp(t);break;case g:this.writeBinary(t,a);break;case w:this.writeSpecial(t,a);break;default:throw new Error(`Unsupported type group: 0x${y.toString(16)} for type 0x`+a.toString(16))}}writeNumber(t,e){switch(e){case S:this.pool.writeU8(t);break;case A:this.pool.writeI16(t);break;case k:this.pool.writeI32(t);break;case D:this.pool.writeU32(t);break;case B:this.pool.writeF32(t);break;case z:this.pool.writeF64(t);break;case V:var a=t<0;this.pool.writeVarint(Math.abs(t)),this.pool.writeU8(a?1:0)}}writeBigInt(t,e){switch(e){case C:case K:this.pool.writeBigInt64(BigInt(t));break;case P:case x:this.writeLargeBigInt(t)}}writeLargeBigInt(t){var e,a=BigInt(t).toString(16).replace("-",""),r=[];for(let t=a.length-2;0<=t;t-=2)r.push(parseInt(a.substr(t,2),16));for(e of(a.length%2&&r.push(parseInt(a[0],16)),this.pool.writeVarint(r.length),r))this.pool.writeU8(e)}writeString(t,e){var a=t.length;switch(e){case T:break;case F:this.pool.writeU8(a);for(let e=0;e<a;e++)this.pool.writeU8(t.charCodeAt(e));break;case O:this.pool.writeU8(a);for(let e=0;e<a;e++)this.pool.writeU8(t.charCodeAt(e));break;case $:this.pool.writeVarint(a);for(let e=0;e<a;e++)this.pool.writeU8(t.charCodeAt(e));break;case j:case N:case R:var r=this.encoder.encode(t);e===j||e===N?this.pool.writeU8(r.length):this.pool.writeVarint(r.length),this.pool.writeBulkAligned(r,1)}}writeArray(t,e){var a=t.length;switch(e){case q:break;case H:this.pool.writeVarint(a);for(let e=0;e<a;e++)this.writeValue(t[e]);break;case G:this.writeSparseArray(t);break;case W:case Y:case X:case J:case Q:this.pool.writePackedArray(t,e);break;case Z:this.writeSIMDOptimizedArray(t)}}writeSparseArray(t){var e,a,r=t.length,i=[];for(let e=0;e<r;e++)e in t&&i.push([e,t[e]]);for([e,a]of(this.pool.writeVarint(r),this.pool.writeVarint(i.length),i))this.pool.writeVarint(e),this.writeValue(a)}writeSIMDOptimizedArray(t){var e=this.simdProcessor.analyzeNumericArray(t);this.pool.writeU8(e.type),this.pool.writePackedArray(t,e.type)}writeObject(t,e){var a=Object.keys(t);if(e!==tt){var r;e=a.filter(e=>{try{return"function"!=typeof t[e]}catch(e){return!1}});for(r of(e.sort(),this.pool.writeVarint(e.length),e))this.writeValue(r),this.writeValue(t[r])}}writeTypedArray(t,e){var a=t.buffer,r=t.byteOffset,i=t.length;if(this.options.shareArrayBuffers){if(void 0!==(s=this.buffers.get(a)))return this.pool.writeU8(1),this.pool.writeVarint(s),this.pool.writeVarint(r),void this.pool.writeVarint(i);this.buffers.set(a,this.buffers.size)}this.pool.writeU8(0),this.pool.writeVarint(r),this.pool.writeVarint(i);var s,n=i*(s=Wt[e]||1);if(e===mt||e===ft)for(let e=0;e<i;e++)this.pool.writeBigInt64(t[e]);else e=new Uint8Array(a,r,n),this.pool.writeBulkAligned(e,s)}writeArrayBuffer(t,e){t=new Uint8Array(t),this.pool.writeVarint(t.length),this.pool.writeBulkAligned(t,1)}writeCollection(t,e){switch(e){case bt:for(var[a,r]of(this.pool.writeVarint(t.size),t))this.writeValue(a),this.writeValue(r);break;case _t:for(var i of(this.pool.writeVarint(t.size),t))this.writeValue(i)}}writeDate(t,e){e===At&&this.pool.writeF64(t.getTime())}writeError(t,e){if(this.writeValue(t.message||""),this.writeValue(t.stack||""),e===Vt&&t.errors)for(var a of(this.pool.writeVarint(t.errors.length),t.errors))this.writeValue(a)}writeRegExp(t){this.writeValue(t.source),this.writeValue(t.flags)}writeBinary(t,e){this.pool.writeVarint(0),this.pool.writeVarint(0)}writeSpecial(t,e){switch(e){case Ot:var a=t.description;this.writeValue(void 0!==a?String(a):"");break;case $t:a=Symbol.keyFor(t),this.writeValue(void 0!==a?String(a):"")}}deserialize(t){if(this.buffer=new Uint8Array(t),this.view=new DataView(this.buffer.buffer,this.buffer.byteOffset),this.pos=0,this.deserializeRefs=[],this.deserializeStrings=[],this.deserializeBuffers=[],1413632565!==this.readU32())throw new Error("Invalid TurboSerial data: wrong magic number");if(5!==(t=this.readU8()))throw new Error("Unsupported TurboSerial version: "+t);return this.readValue()}readValue(){if(this.pos>=this.buffer.length)throw new Error("Unexpected end of buffer");var t=this.readU8();if(null==t)throw new Error("Invalid type byte read from buffer");if(t===Tt||t===Ft){var e=this.readVarint();if(e>=this.deserializeRefs.length)throw new Error("Invalid reference ID: "+e);return this.deserializeRefs[e]}if(t===L){if((e=this.readVarint())>=this.deserializeStrings.length)throw new Error("Invalid string reference: "+e);return this.deserializeStrings[e]}if(t===wt){if((e=this.readVarint())>=this.deserializeBuffers.length)throw new Error("Invalid buffer reference: "+e);return this.deserializeBuffers[e]}let a,y=!1;switch(e=t&r){case c:case h:case u:y=!0}if(y){switch(e){case h:a=[];break;case u:t===bt?a=new Map:t===_t&&(a=new Set);break;case c:a={}}switch(a&&this.deserializeRefs.push(a),e){case h:this.fillArray(a,t);break;case c:this.fillObject(a,t);break;case u:this.fillCollection(a,t)}}else{try{switch(e){case i:a=this.readPrimitive(t);break;case s:a=this.readNumber(t);break;case n:a=this.readBigInt(t);break;case o:a=this.readString(t);break;case l:a=this.readTypedArray(t);break;case d:a=this.readArrayBuffer(t);break;case m:a=this.readDate(t);break;case f:a=this.readError(t);break;case p:a=this.readRegExp();break;case g:a=this.readBinary(t);break;case w:a=this.readSpecial(t);break;default:throw new Error("Unknown type: 0x"+t.toString(16))}}catch(e){throw new Error(`Failed to deserialize type 0x${t.toString(16)}: `+e.message)}"object"!=typeof a||null===a||y||this.deserializeRefs.push(a)}return a}fillArray(t,e){switch(e){case q:break;case H:var a=this.readVarint();for(let e=0;e<a;e++)t[e]=this.readValue();break;case G:var r=this.readVarint(),i=this.readVarint();t.length=r;for(let e=0;e<i;e++){var s=this.readVarint(),n=this.readValue();t[s]=n}break;case W:case Y:case X:case J:case Q:r=this.readPackedArrayData(e),t.push(...r);break;case Z:r=this.readU8(),r=this.readPackedArrayData(r),t.push(...r)}}fillObject(t,e){if(e!==tt){var a=this.readVarint();for(let e=0;e<a;e++){var r=this.readValue(),i=this.readValue();t[r]=i}}}fillCollection(t,e){var a=this.readVarint();switch(e){case bt:for(let e=0;e<a;e++){var r=this.readValue(),i=this.readValue();t.set(r,i)}break;case _t:for(let e=0;e<a;e++)t.add(this.readValue())}}readPrimitive(t){switch(t){case y:return null;case b:return;case _:return!1;case v:return!0;default:throw new Error("Unknown primitive type: 0x"+(t?t.toString(16):"undefined"))}}readNumber(t){switch(t){case S:return this.view.getInt8(this.pos++);case A:return this.readI16();case k:return this.readI32();case D:return this.readU32();case B:return this.readF32();case z:return this.readF64();case I:return NaN;case E:return 1/0;case U:return-1/0;case M:return-0;case V:var e=this.readVarint();return this.readU8()?-e:e;default:throw new Error("Unknown number type: 0x"+t.toString(16))}}readBigInt(t){switch(t){case C:case K:return this.readBigInt64();case P:case x:return this.readLargeBigInt(t===x);default:throw new Error("Unknown BigInt type: 0x"+t.toString(16))}}readLargeBigInt(t){var e=this.readVarint(),a=(this.ensureBytes(e),this.buffer.subarray(this.pos,this.pos+e));this.pos+=e;let r="";for(let t=a.length-1;0<=t;t--)r+=a[t].toString(16).padStart(2,"0");return e=BigInt("0x"+r),t?-e:e}readString(t){if(t===T)return"";let e,a;switch(t){case F:case O:case j:case N:e=this.readU8();break;default:e=this.readVarint()}if(this.ensureBytes(e),t===F||t===O||t===$){a="";for(let t=0;t<e;t++)a+=String.fromCharCode(this.readU8())}else t=this.buffer.subarray(this.pos,this.pos+e),this.pos+=e,a=this.decoder.decode(t);return this.deserializeStrings.push(a),a}readArray(t){var e=[];return this.fillArray(e,t),e}readPackedArrayData(t){var e=this.readVarint(),a=new Array(e),r=Wt[t];if(!r)throw new Error("Unknown element size for packed array type: 0x"+t.toString(16));switch(this.alignPos(Math.min(r,8)),this.ensureBytes(e*r),t){case W:for(let t=0;t<e;t++)a[t]=this.view.getInt8(this.pos++);break;case Y:for(let t=0;t<e;t++)a[t]=this.view.getInt16(this.pos,!0),this.pos+=2;break;case X:for(let t=0;t<e;t++)a[t]=this.view.getInt32(this.pos,!0),this.pos+=4;break;case J:for(let t=0;t<e;t++)a[t]=this.view.getFloat32(this.pos,!0),this.pos+=4;break;case Q:for(let t=0;t<e;t++)a[t]=this.view.getFloat64(this.pos,!0),this.pos+=8;break;default:throw new Error("Unknown packed array type: 0x"+t.toString(16))}return a}readObject(t){var e={};return this.fillObject(e,t),e}readTypedArray(t){if(this.readU8()){var e=this.readVarint(),a=this.readVarint(),r=this.readVarint();if(e>=this.deserializeBuffers.length)throw new Error("Invalid buffer reference: "+e);return e=this.deserializeBuffers[e],this.createTypedArray(t,e,a,r)}this.readVarint();var i=this.readVarint();e=Wt[t]||1;if(t!==mt&&t!==ft)return a=i*e,this.alignPos(e),this.ensureBytes(a),r=this.buffer.subarray(this.pos,this.pos+a),this.pos+=a,e=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength),this.deserializeBuffers.push(e),this.createTypedArray(t,e,0,i);this.alignPos(8);var s=[];for(let t=0;t<i;t++)s.push(this.readBigInt64());return new Ht[t](s)}createTypedArray(t,e,a,r){var i=Ht[t];if(!i)throw new Error("Unknown typed array type: 0x"+t.toString(16));try{return new i(e,a,r)}catch(t){throw new Error("Failed to create typed array: "+t.message)}}readArrayBuffer(t){var e=this.readVarint(),a=(this.ensureBytes(e),this.buffer.subarray(this.pos,this.pos+e));this.pos+=e,e=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength);return this.deserializeBuffers.push(e),e}readCollection(t){var e=new(t===bt?Map:Set);return this.fillCollection(e,t),e}readDate(t){switch(t){case At:var e=this.readF64();return new Date(e);case kt:return new Date(NaN);default:throw new Error("Unknown date type: 0x"+t.toString(16))}}readError(t){var e=this.readValue(),a=this.readValue();let r;switch(t){case Dt:r=new Error(e);break;case Bt:r=new EvalError(e);break;case zt:r=new RangeError(e);break;case It:r=new ReferenceError(e);break;case Et:r=new SyntaxError(e);break;case Ut:r=new TypeError(e);break;case Mt:r=new URIError(e);break;case Vt:var i=this.readVarint(),s=[];for(let t=0;t<i;t++)s.push(this.readValue());r=new AggregateError(s,e);break;default:r=new Error(e)}return a&&(r.stack=a),r}readRegExp(){var t=this.readValue(),e=this.readValue();return new RegExp(t,e)}readBinary(t){return{_type:"Binary",size:this.readVarint(),typeStr:this.readVarint()}}readSpecial(t){switch(t){case Ot:var e=this.readValue();return Symbol(e);case $t:return e=this.readValue(),Symbol.for(e);default:throw new Error("Unknown special type: 0x"+t.toString(16))}}readU8(){return this.ensureBytes(1),this.buffer[this.pos++]}readI16(){this.alignPos(2),this.ensureBytes(2);var t=this.view.getInt16(this.pos,!0);return this.pos+=2,t}readU16(){this.alignPos(2),this.ensureBytes(2);var t=this.view.getUint16(this.pos,!0);return this.pos+=2,t}readI32(){this.alignPos(4),this.ensureBytes(4);var t=this.view.getInt32(this.pos,!0);return this.pos+=4,t}readU32(){this.alignPos(4),this.ensureBytes(4);var t=this.view.getUint32(this.pos,!0);return this.pos+=4,t}readF32(){this.alignPos(4),this.ensureBytes(4);var t=this.view.getFloat32(this.pos,!0);return this.pos+=4,t}readF64(){this.alignPos(8),this.ensureBytes(8);var t=this.view.getFloat64(this.pos,!0);return this.pos+=8,t}readBigInt64(){this.alignPos(8),this.ensureBytes(8);var t=this.view.getBigInt64(this.pos,!0);return this.pos+=8,t}readVarint(){let t=0,e=0;for(var a;this.ensureBytes(1),t|=(127&(a=this.buffer[this.pos++]))<<e,e+=7,128&a;);return t>>>0}alignPos(t){t=t-1|0,this.pos=(this.pos+t&~t)>>>0}ensureBytes(t){if(this.pos+t>this.buffer.length)throw new Error(`Not enough bytes in buffer: need ${t}, available `+(this.buffer.length-this.pos))}},a.d(e,"Database",(function(){return Ae})),a.d(e,"Document",(function(){return ke})),a.d(e,"Collection",(function(){return Be}));let oe=new Nt({compression:!1,deduplication:!0,shareArrayBuffers:!0,simdOptimization:!0,detectCircular:!0,memoryPoolSize:65536});class he{static async saveAttachments(t,e,a,r){var i,s=[];let n=await navigator.storage.getDirectory();for(i of[t,e,a])n=await n.getDirectoryHandle(i,{create:!0});for(let i=0;i<r.length;i++){var o=i.toString(),h=await(await n.getFileHandle(o,{create:!0})).createWritable();h=(await h.write(r[i].data),await h.close(),t+`/${e}/${a}/`+o);s.push(h)}return s}static async getAttachments(t){var e,a=[],r=await navigator.storage.getDirectory();for(e of t)try{var i=e.split("/");let t=r;for(let e=0;e<i.length-1;e++)t=await t.getDirectoryHandle(i[e]);var s=await(await t.getFileHandle(i[i.length-1])).getFile();a.push({path:e,data:s})}catch(t){console.error(`Error retrieving attachment at "${e}": `+t.message)}return a}static async deleteAttachments(t,e,a){var r=[t,e,a];let i=await navigator.storage.getDirectory();for(let t=0;t<r.length-1;t++)i=await i.getDirectoryHandle(r[t]);try{await i.removeEntry(r[r.length-1],{recursive:!0})}catch(t){console.error(`Error deleting attachments for document "${a}": `+t.message)}}toString(){return"[OPFSUtility]"}}class ce{static async compress(t){t="string"==typeof t?(new TextEncoder).encode(t):t;var e=new CompressionStream("deflate"),a=e.writable.getWriter();return a.write(t),a.close(),this._streamToUint8Array(e.readable)}static async decompress(t){var e=new DecompressionStream("deflate"),a=e.writable.getWriter();return a.write(t),a.close(),this._streamToUint8Array(e.readable)}static async _streamToUint8Array(t){var e=t.getReader(),a=[];let r=0;for(;;){var{value:i,done:s}=await e.read();if(s)break;a.push(i),r+=i.length}var n,o=new Uint8Array(r);let h=0;for(n of a)o.set(n,h),h+=n.length;return o}toString(){return"[BrowserCompressionUtility]"}}class le{static async encrypt(t,e){var a=crypto.getRandomValues(new Uint8Array(16)),r=(e=await this._deriveKey(e,a),crypto.getRandomValues(new Uint8Array(12))),i=await this._generateChecksum(t);t=this._combineDataAndChecksum(t,i),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},e,t);return this._wrapIntoUint8Array(a,r,new Uint8Array(i))}static async decrypt(t,e){var{salt:t,iv:a,encryptedData:r}=this._unwrapUint8Array(t),a=(e=await this._deriveKey(e,t),t=await crypto.subtle.decrypt({name:"AES-GCM",iv:a},e,r),new Uint8Array(t)),{data:e,checksum:r}=this._separateDataAndChecksum(a);t=await this._generateChecksum(e);if(this._verifyChecksum(t,r))return e;throw new Error("Data integrity check failed. The data has been tampered with.")}static async _deriveKey(t,e){var a=new TextEncoder;a=await crypto.subtle.importKey("raw",a.encode(t),{name:"PBKDF2"},!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"PBKDF2",salt:e,iterations:6e5,hash:"SHA-512"},a,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}static async _generateChecksum(t){return new Uint8Array(await crypto.subtle.digest("SHA-256",t))}static _verifyChecksum(t,e){if(t.length!==e.length)return!1;for(let a=0;a<t.length;a++)if(t[a]!==e[a])return!1;return!0}static _combineDataAndChecksum(t,e){var a=new Uint8Array(t.length+e.length);return a.set(t),a.set(e,t.length),a}static _separateDataAndChecksum(t){var e=t.length-32;return{data:t.slice(0,e),checksum:t.slice(e)}}static _wrapIntoUint8Array(t,e,a){var r=new Uint8Array(t.length+e.length+a.length);return r.set(t,0),r.set(e,t.length),r.set(a,t.length+e.length),r}static _unwrapUint8Array(t){return{salt:t.slice(0,16),iv:t.slice(16,28),encryptedData:t.slice(28)}}toString(){return"[BrowserEncryptionUtility]"}}class de{static openDatabase(t,e=null,a=null){return new Promise((r,i)=>{let s;(s=e?indexedDB.open(t,e):indexedDB.open(t)).onupgradeneeded=e=>{var r=e.target.result,i=e.oldVersion;e=e.newVersion;console.log(`Upgrading database "${t}" from version ${i} to `+e),a&&a(r,i,e)},s.onsuccess=e=>{(e=e.target.result).onclose=()=>{console.log(`Database "${t}" connection is closing.`)},r(e)},s.onerror=e=>{i(new Error(`Failed to open database "${t}": `+e.target.error.message))}})}static async performTransaction(t,e,a,r,i=3,s=null){let n=null;for(let h=0;h<=i;h++)try{if(!t||"done"!==t.readyState)throw new Error("Database connection is not available or ready.");let i=t.transaction(Array.isArray(e)?e:[e],a);var o=Array.isArray(e)?e.map(t=>i.objectStore(t)):[i.objectStore(e)];let h=setTimeout(()=>{i.abort()},3e4),c=await r(...o,s);return new Promise((t,e)=>{i.oncomplete=()=>{clearTimeout(h),t(c)},i.onerror=()=>{clearTimeout(h),n=new Error("Transaction failed: "+(i.error?i.error.message:"unknown error")),e(n)},i.onabort=()=>{clearTimeout(h),n=new Error("Transaction aborted: "+(i.error?i.error.message:"timeout or abort")),e(n)}})}catch(t){if(n=t,h<i){console.warn(`Transaction failed, retrying... (${i-h} attempts left): `+t.message);let e=100*Math.pow(2,h)+100*Math.random();await new Promise(t=>setTimeout(t,e))}}throw new Error(`Transaction ultimately failed after ${i+1} attempts: `+n.message)}static add(t,e){return new Promise((a,r)=>{var i=t.add(e);i.onsuccess=()=>a(),i.onerror=t=>r("Failed to insert record: "+t.target.error.message)})}static put(t,e){return new Promise((a,r)=>{var i=t.put(e);i.onsuccess=()=>a(),i.onerror=t=>r("Failed to put record: "+t.target.error.message)})}static delete(t,e){return new Promise((a,r)=>{var i=t.delete(e);i.onsuccess=()=>a(),i.onerror=t=>r("Failed to delete record: "+t.target.error.message)})}static get(t,e){return new Promise((a,r)=>{var i=t.get(e);i.onsuccess=t=>a(t.target.result),i.onerror=t=>r(`Failed to retrieve record with key ${e}: `+t.target.error.message)})}static getAll(t){return new Promise((e,a)=>{var r=t.getAll();r.onsuccess=t=>e(t.target.result),r.onerror=t=>a("Failed to retrieve records: "+t.target.error.message)})}static count(t){return new Promise((e,a)=>{var r=t.count();r.onsuccess=t=>e(t.target.result),r.onerror=t=>a("Failed to count records: "+t.target.error.message)})}static clear(t){return new Promise((e,a)=>{var r=t.clear();r.onsuccess=()=>e(),r.onerror=t=>a("Failed to clear store: "+t.target.error.message)})}static deleteDatabase(t){return new Promise((e,a)=>{var r=indexedDB.deleteDatabase(t);r.onsuccess=()=>e(),r.onerror=t=>a("Failed to delete database: "+t.target.error.message)})}static iterateCursor(t,e){return new Promise((a,r)=>{var i=t.openCursor();i.onsuccess=t=>{(t=t.target.result)?(e(t.value,t.key),t.continue()):a()},i.onerror=t=>r("Cursor iteration failed: "+t.target.error.message)})}static iterateCursorSafe(t,e,a={}){return new Promise((r,i)=>{var{index:s=null,direction:n="next",range:o=null}=a;let h=t,c=(h=s&&t.indexNames.contains(s)?t.index(s):h).openCursor(o,n),l=[];c.onsuccess=t=>{(t=t.target.result)&&!1!==e(t.value,t.key,l)?t.continue():r(l)},c.onerror=()=>i(c.error)})}toString(){return"[IndexedDBUtility]"}}class ue{static getItem(t){return(t=localStorage.getItem(t))?oe.serialize(t):null}static setItem(t,e){localStorage.setItem(t,oe.serialize(e))}static removeItem(t){localStorage.removeItem(t)}static clear(){localStorage.clear()}toString(){return"[LocalStorageUtility]"}}class me{constructor(){this.queue=[],this.locked=!1}async acquire(){return new Promise(t=>{this.locked?this.queue.push(t):(this.locked=!0,t())})}release(){0<this.queue.length?this.queue.shift()():this.locked=!1}async runExclusive(t){await this.acquire();try{return await t()}finally{this.release()}}toString(){return`[AsyncMutex locked:${this.locked} queue:${this.queue.length}]`}}class fe{constructor(t){this._dbName=t,this._metadataKey=`lacertadb_${this._dbName}_metadata`,this._collections=new Map,this._metadata=this._loadMetadata(),this._mutex=new me}async saveMetadata(){return this._mutex.runExclusive(()=>{ue.setItem(this.metadataKey,this.getRawMetadata())})}async adjustTotals(t,e){return this._mutex.runExclusive(()=>{this.data.totalSizeKB+=t,this.data.totalLength+=e,this.data.modifiedAt=Date.now()})}_loadMetadata(){var t=ue.getItem(this.metadataKey);if(t){for(var e in t.collections){var a=t.collections[e];a=new ye(e,this,a);this.collections.set(e,a)}return t}return{name:this._dbName,collections:{},totalSizeKB:0,totalLength:0,modifiedAt:Date.now()}}get data(){return this._metadata}set data(t){this._metadata=t}get name(){return this.data.name}get metadataKey(){return this._metadataKey}get collections(){return this._collections}set collections(t){this._collections=t}get totalSizeKB(){return this.data.totalSizeKB}get totalLength(){return this.data.totalLength}get modifiedAt(){return this.data.modifiedAt}getCollectionMetadata(t){var e;return this.collections.has(t)||(e=new ye(t,this),this.collections.set(t,e),this.data.collections[t]=e.getRawMetadata(),this.data.modifiedAt=Date.now()),this.collections.get(t)}getCollectionMetadataData(t){return(t=this.getCollectionMetadata(t))?t.getRawMetadata():{}}removeCollectionMetadata(t){var e=this.collections.get(t);e&&(this.data.totalSizeKB-=e.sizeKB,this.data.totalLength-=e.length,this.collections.delete(t),delete this.data.collections[t],this.data.modifiedAt=Date.now())}getCollectionNames(){return Array.from(this.collections.keys())}getRawMetadata(){for(var[t,e]of this._collections.entries())this.data.collections[t]=e.getRawMetadata();return this.data}setRawMetadata(t){for(var e in this._metadata=t,this._collections.clear(),t.collections){var a=t.collections[e];a=new ye(e,this,a);this._collections.set(e,a)}}get dbName(){return this._dbName}get key(){return this._metadataKey}toString(){return`[DatabaseMetadata: ${this.name} | Collections: ${this.collections.size} | Size: ${this.totalSizeKB.toFixed(2)}KB | Documents: ${this.totalLength}]`}}class pe extends Error{constructor(t,e,a=null){super(t),this.name="LacertaDBError",this.code=e,this.originalError=a,this.timestamp=Date.now()}toString(){return`[LacertaDBError ${this.code}: ${this.message} at ${new Date(this.timestamp).toISOString()}]`}}let ge="COLLECTION_NOT_FOUND",we="COLLECTION_EXISTS";class ye{constructor(t,e,a=null){this._collectionName=t,this._databaseMetadata=e,a?this._metadata=a:(this._metadata={name:t,sizeKB:0,length:0,createdAt:Date.now(),modifiedAt:Date.now(),documentSizes:{},documentModifiedAt:{},documentPermanent:{},documentAttachments:{}},this._databaseMetadata.data.collections[t]=this._metadata,this._databaseMetadata.data.modifiedAt=Date.now())}get name(){return this._collectionName}get keys(){return Object.keys(this.documentSizes)}get collectionName(){return this.name}get sizeKB(){return this._metadata.sizeKB}get length(){return this._metadata.length}get modifiedAt(){return this._metadata.modifiedAt}get metadata(){return this._metadata}set metadata(t){return this._metadata=t}get data(){return this.metadata}set data(t){this.metadata=t}get databaseMetadata(){return this._databaseMetadata}set databaseMetadata(t){this._databaseMetadata=t}get documentSizes(){return this.metadata.documentSizes}get documentModifiedAt(){return this.metadata.documentModifiedAt}get documentPermanent(){return this.metadata.documentPermanent}get documentAttachments(){return this.metadata.documentAttachments}set documentSizes(t){this.metadata.documentSizes=t}set documentModifiedAt(t){this.metadata.documentModifiedAt=t}set documentPermanent(t){this.metadata.documentPermanent=t}set documentAttachments(t){this.metadata.documentAttachments=t}updateDocument(t,e,a=!1,r=0){var i=!this.keys.includes(t),s=e-(this.documentSizes[t]||0);i=i?1:0;this.documentSizes[t]=e,this.documentModifiedAt[t]=Date.now(),this.documentPermanent[t]=a?1:0,this.documentAttachments[t]=r,this.metadata.sizeKB+=s,this.metadata.length+=i,this.metadata.modifiedAt=Date.now(),this.databaseMetadata.adjustTotals(s,i)}deleteDocument(t){var e;return t in this.documentSizes&&(e=this.documentSizes[t],delete this.documentSizes[t],delete this.documentModifiedAt[t],delete this.documentPermanent[t],delete this.documentAttachments[t],this.metadata.sizeKB-=e,--this.metadata.length,this.metadata.modifiedAt=Date.now(),this.databaseMetadata.adjustTotals(-e,-1),!0)}updateDocuments(t){for(var{docId:e,docSizeKB:a,isPermanent:r,attachmentCount:i}of t)this.updateDocument(e,a,r,i||0)}getRawMetadata(){return this.metadata}setRawMetadata(t){this.metadata=t}toString(){return`[CollectionMetadata: ${this.name} | Size: ${this.sizeKB.toFixed(2)}KB | Documents: ${this.length}]`}}class be{constructor(t,e=null,a=null){this.success=t,this.data=e,this.error=a}toString(){return`[LacertaDBResult success:${this.success} ${this.error?"error:"+this.error:""}]`}}class _e{constructor(t){this._dbName=t,this._metadataKey=`lacertadb_${this._dbName}_quickstore_metadata`,this._documentKeyPrefix=`lacertadb_${this._dbName}_quickstore_data_`,this._metadata=this._loadMetadata()}_loadMetadata(){return ue.getItem(this._metadataKey)||{totalSizeKB:0,totalLength:0,documentSizesKB:{},documentModificationTime:{},documentPermanent:{}}}_saveMetadata(){ue.setItem(this._metadataKey,this._metadata)}setDocumentSync(t,e=null){e=(t=new ke(t,e)).packSync();var a=t._id,r=t._permanent||!1,i=(e=oe.serialize({_id:t._id,_created:t._created,_modified:t._modified,_permanent:r,_encrypted:t._encrypted,_compressed:t._compressed,packedData:e}),this._documentKeyPrefix+a);localStorage.setItem(i,e),i=e.length/1024;return(e=!(a in this._metadata.documentSizesKB))?this._metadata.totalLength+=1:this._metadata.totalSizeKB-=this._metadata.documentSizesKB[a],this._metadata.documentSizesKB[a]=i,this._metadata.documentModificationTime[a]=t._modified,this._metadata.documentPermanent[a]=r,this._metadata.totalSizeKB+=i,this._saveMetadata(),e}deleteDocumentSync(t,e=!1){var a;return!(this._metadata.documentPermanent[t]&&!e||(e=this._documentKeyPrefix+t,a=this._metadata.documentSizesKB[t]||0,!localStorage.getItem(e))||(localStorage.removeItem(e),delete this._metadata.documentSizesKB[t],delete this._metadata.documentModificationTime[t],delete this._metadata.documentPermanent[t],this._metadata.totalSizeKB-=a,--this._metadata.totalLength,this._saveMetadata(),0))}getAllKeys(){return Object.keys(this._metadata.documentSizesKB)}getDocumentSync(t,e=null){t=this._documentKeyPrefix+t;return(t=localStorage.getItem(t))?(t=oe.serialize(t),new ke(t,e).unpackSync()):null}toString(){return`[QuickStore: ${this._dbName} | Size: ${this._metadata.totalSizeKB.toFixed(2)}KB | Documents: ${this._metadata.totalLength}]`}}class ve{constructor(){this.queue=[],this.processing=!1}async execute(t){return new Promise((e,a)=>{this.queue.push({operation:t,resolve:e,reject:a}),this.process()})}async process(){if(!this.processing&&0!==this.queue.length){for(this.processing=!0;0<this.queue.length;){var{operation:t,resolve:e,reject:a}=this.queue.shift();try{e(await t())}catch(t){a(t)}}this.processing=!1}}toString(){return`[TransactionManager processing:${this.processing} queue:${this.queue.length}]`}}class Se{constructor(){this._listeners={beforeAdd:[],afterAdd:[],beforeDelete:[],afterDelete:[],beforeGet:[],afterGet:[]}}on(t,e){if(!this._listeners[t])throw new Error(`Event "${t}" is not supported.`);this._listeners[t].push(e)}off(t,e){this._listeners[t]&&-1<(e=this._listeners[t].indexOf(e))&&this._listeners[t].splice(e,1)}_emit(t,...e){if(this._listeners[t])for(var a of this._listeners[t])a(...e)}_cleanup(){for(var t in this._listeners)this._listeners[t]=[]}toString(){return`[Observer listeners:{${Object.entries(this._listeners).map(([t,e])=>t+":"+e.length).join(" ")}}]`}}class Ae{constructor(t,e={}){this._dbName=t,this._db=null,this._collections=new Map,this._metadata=new fe(t),this._settings=new De(t,e),this._quickStore=new _e(this._dbName),this._settings.init()}get quickStore(){return this._quickStore}async init(){var t;for(t of(this.db=await de.openDatabase(this.name,void 0,(t,e,a)=>{this._upgradeDatabase(t,e,a)}),this.data.getCollectionNames())){var e=new Be(this,t,this.settings);await e.init(),this.collections.set(t,e)}}_createDataStores(t){for(var e of this.collections.keys())this._createDataStore(t,e)}_createDataStore(t,e){t.objectStoreNames.contains(e)||t.createObjectStore(e,{keyPath:"_id"})}_upgradeDatabase(t,e,a){console.log(`Upgrading database "${this.name}" from version ${e} to `+a),t.objectStoreNames.contains("_metadata")||t.createObjectStore("_metadata",{keyPath:"_id"})}async createCollection(t){var e;return this.collections.has(t)?(console.log(`Collection "${t}" already exists.`),new be(!1,this.collections.get(t),new pe(`Collection "${t}" already exists`,we))):(this.db.objectStoreNames.contains(t)||(e=this.db.version+1,this.db.close(),this.db=await de.openDatabase(this.name,e,(e,a,r)=>{this._createDataStore(e,t)})),await(e=new Be(this,t,this.settings)).init(),this.collections.set(t,e),this.data.getCollectionMetadata(t),await this.data.saveMetadata(),new be(!0,e))}async deleteCollection(t){var e;return this.collections.has(t)?(await(e=this.collections.get(t)).close(),e.observer._cleanup(),await de.performTransaction(this.db,t,"readwrite",t=>de.clear(t)),this.collections.delete(t),this.data.removeCollectionMetadata(t),await this.data.saveMetadata(),new be(!0,null)):new be(!1,null,new pe(`Collection "${t}" does not exist`,ge))}async getCollection(t){var e;return this.collections.has(t)?new be(!0,this.collections.get(t)):this.db.objectStoreNames.contains(t)?(await(e=new Be(this,t,this.settings)).init(),this.collections.set(t,e),new be(!0,e)):new be(!1,null,new pe(`Collection "${t}" does not exist`,ge))}async close(){var t;for(t of this.collectionsArray)await t.close();this.db&&(this.db.close(),this.db=null)}async deleteDatabase(){await this.close(),await de.deleteDatabase(this.name),ue.removeItem(this.data.metadataKey),this.settings.clear(),this.data=null}get name(){return this._dbName}get db(){return this._db}set db(t){this._db=t}get data(){return this.metadata}set data(t){this.metadata=t}get collectionsArray(){return Array.from(this.collections.values())}get collections(){return this._collections}get metadata(){return this._metadata}set metadata(t){this._metadata=t}get totalSizeKB(){return this.data.totalSizeKB}get totalLength(){return this.data.totalLength}get modifiedAt(){return this.data.modifiedAt}get settings(){return this._settings}get settingsData(){return this.settings.data}toString(){return`[Database: ${this.name} | Collections: ${this.collections.size} | Size: ${this.totalSizeKB.toFixed(2)}KB | Documents: ${this.totalLength}]`}}class ke{constructor(t,e=null){this._id=t._id||this._generateId(),this._created=t._created||Date.now(),this._permanent=!!t._permanent,this._encrypted=t._encrypted||!!e,this._compressed=t._compressed||!1,this._attachments=t._attachments||t.attachments||[],t.packedData?(this._packedData=t.packedData,this._modified=t._modified||Date.now(),this._data=null):(this._data=t.data||{},this._modified=Date.now(),this._packedData=new Uint8Array(0)),this._encryptionKey=e||""}get attachments(){return this._attachments}set attachments(t){this._attachments=t}get data(){return this._data}get packedData(){return this._packedData}get encryptionKey(){return this._encryptionKey}set data(t){this._data=t}set packedData(t){this._packedData=t}set encryptionKey(t){this._encryptionKey=t}static hasAttachments(t){return t._attachments&&0<t._attachments.length||t.attachments&&0<t.attachments.length}static async getAttachments(t,e,a){var r;return ke.hasAttachments(t)?(r=t._attachments||t.attachments,t.attachments=await he.getAttachments(r),Promise.resolve(t)):[]}static isEncrypted(t){return t._encrypted&&t.packedData}static async decryptDocument(t,e){if(ke.isEncrypted(t))return e=await le.decrypt(t.packedData,e),e=oe.deserialize(e),{_id:t._id,_created:t._created,_modified:t._modified,_encrypted:!0,_compressed:t._compressed,_permanent:!!t._permanent,attachments:t.attachments,data:e};throw new Error("Document is not encrypted.")}async pack(){if(!this.data)throw new Error("No data to pack");let t=oe.serialize(this.data);return this._compressed&&(t=await this._compressData(t)),this._encrypted&&(t=await this._encryptData(t)),this.packedData=t}packSync(){if(!this.data)throw new Error("No data to pack");if(this._encrypted)throw new Error("Packing synchronously a document being encrypted is impossible.");if(this._compressed)throw new Error("Packing synchronously a document being compressed is impossible.");var t=oe.serialize(this.data);return this.packedData=t}async unpack(){if(!this.data&&0<this.packedData.length){let t=this.packedData;this._encrypted&&(t=await this._decryptData(t)),this._compressed&&(t=await this._decompressData(t)),this.data=oe.deserialize(t)}return this.data}unpackSync(){if(!this.data&&0<this.packedData.length){if(this._encrypted)throw new Error("Unpacking synchronously a document being encrypted is impossible.");if(this._compressed)throw new Error("Unpacking synchronously a document being compressed is impossible.");this.data=oe.deserialize(this.packedData)}return this.data}async _encryptData(t){var e=this.encryptionKey;return le.encrypt(t,e)}async _decryptData(t){var e=this.encryptionKey;return le.decrypt(t,e)}async _compressData(t){return ce.compress(t)}async _decompressData(t){return ce.decompress(t)}_generateId(){return"xxxx-xxxx-xxxx".replace(/[x]/g,()=>(16*Math.random()|0).toString(16))}async objectOutput(t=!1){this.data||await this.unpack();var e={_id:this._id,_created:this._created,_modified:this._modified,_permanent:this._permanent,_encrypted:this._encrypted,_compressed:this._compressed,attachments:this.attachments,data:this.data};return t&&0<this.attachments.length&&(t=await he.getAttachments(this.attachments),e.attachments=t),e}async databaseOutput(){return this.packedData&&0!==this.packedData.length||await this.pack(),{_id:this._id,_created:this._created,_modified:this._modified,_permanent:!!this._permanent,_compressed:this._compressed,_encrypted:this._encrypted,attachments:this.attachments,packedData:this.packedData}}toString(){return`[Document: ${this._id} | Created: ${new Date(this._created).toISOString()} | Encrypted: ${this._encrypted} | Compressed: ${this._compressed} | Permanent: ${this._permanent}]`}}class De{constructor(t,e={}){this._dbName=t,this._settingsKey=`lacertadb_${this._dbName}_settings`,this._data=this._loadSettings(),this._mergeSettings(e)}init(){if(this.set("sizeLimitKB",this.get("sizeLimitKB")||1/0),this.set("bufferLimitKB",this.get("bufferLimitKB")||-.2*this.get("sizeLimitKB")),this.get("bufferLimitKB")<-.8*this.get("sizeLimitKB"))throw new Error("Buffer limit cannot be below -80% of the size limit.");this.set("freeSpaceEvery",this._validateFreeSpaceSetting(this.get("freeSpaceEvery")))}_validateFreeSpaceSetting(t=1e4){if(void 0===t||!1===t||0===t)return 1/0;if(t<1e3&&0!==t)throw new Error("Invalid freeSpaceEvery value. It must be 0, Infinity, or above 1000.");return 1e3<=t&&t<1e4&&console.warn("Warning: freeSpaceEvery value is between 1000 and 10000, which may lead to frequent freeing."),t}_loadSettings(){return ue.getItem(this.settingsKey)||{}}_saveSettings(){ue.setItem(this.settingsKey,this.data)}_mergeSettings(t){this.data=Object.assign(this.data,t),this._saveSettings()}get(t){return this.data[t]}set(t,e){this.data[t]=e,this._saveSettings()}remove(t){delete this.data[t],this._saveSettings()}clear(){this.data={},this._saveSettings()}get dbName(){return this._dbName}get data(){return this._data}set data(t){this._data=t}get settingsKey(){return this._settingsKey}toString(){return`[Settings: ${this.dbName} | SizeLimit: ${this.get("sizeLimitKB")}KB | BufferLimit: ${this.get("bufferLimitKB")}KB]`}}class Be{constructor(t,e,a){this._database=t,this._collectionName=e,this._settings=a,this._metadata=null,this._lastFreeSpaceTime=0,this._observer=new Se,this._transactionManager=new ve,this._freeSpaceInterval=null,this._freeSpaceHandler=null}get observer(){return this._observer}async createIndex(t,e={}){let a=e.name||t.replace(/\./g,"_");var r=this.database.db.version+1;this.database.db.close(),this.database.db=await de.openDatabase(this.database.name,r,r=>{r.objectStoreNames.contains(this.name)&&!(r=r.transaction([this.name]).objectStore(this.name)).indexNames.contains(a)&&r.createIndex(a,t,{unique:e.unique||!1,multiEntry:e.multiEntry||!1})})}async init(){this.metadata=this.database.metadata.getCollectionMetadata(this.name),this.settingsData.freeSpaceEvery!==1/0&&(this._freeSpaceHandler=()=>this._maybeFreeSpace(),this._freeSpaceInterval=setInterval(this._freeSpaceHandler,this.settingsData.freeSpaceEvery))}get name(){return this._collectionName}get sizes(){return this.metadataData.documentSizes||{}}get modifications(){return this.metadataData.documentModifiedAt||{}}get attachments(){return this.metadataData.documentAttachments||{}}get permanents(){return this.metadataData.documentPermanent||{}}get keys(){return Object.keys(this.sizes)}get documentsMetadata(){var t,e=this.keys,a=this.sizes,r=this.modifications,i=this.permanents,s=this.attachments,n=new Array(e.length),o=0;for(t of e)n[o++]={id:t,size:a[t],modified:r[t],permanent:i[t],attachment:s[t]};return n}get settings(){return this._settings}get settingsData(){return this.settings.data}set settings(t){this._settings=t}get lastFreeSpaceTime(){return this._lastFreeSpaceTime}set lastFreeSpaceTime(t){this._lastFreeSpaceTime=t}get database(){return this._database}get metadata(){return this.database.metadata.getCollectionMetadata(this.name)}get metadataData(){return this.metadata.getRawMetadata()}set metadata(t){this._metadata=t}get sizeKB(){return this.metadataData.sizeKB}get length(){return this.metadataData.length}get totalSizeKB(){return this.sizeKB}get totalLength(){return this.length}get modifiedAt(){return this.metadataData.modifiedAt}get isFreeSpaceEnabled(){return this.settingsData.freeSpaceEvery!==1/0}get shouldRunFreeSpaceSize(){return this.totalSizeKB>this.settingsData.sizeLimitKB+this.settingsData.bufferLimitKB}get shouldRunFreeSpaceTime(){return this.isFreeSpaceEnabled&&Date.now()-this.lastFreeSpaceTime>=this.settingsData.freeSpaceEvery}async _maybeFreeSpace(){if(this.shouldRunFreeSpaceSize||this.shouldRunFreeSpaceTime)return this.freeSpace(this.settingsData.sizeLimitKB)}async addDocument(t,e=null){return this._transactionManager.execute(async()=>{this.observer._emit("beforeAdd",t);var a=new ke(t,e),r=[];if(ke.hasAttachments(t)){var i=t._attachments||t.attachments;for(let t=0;t<i.length;t++)r.push(`${this.database.name}/${this.name}/${a._id}/`+t);a._attachments=r}let s=await a.databaseOutput();var n,o=s._id,h=s._permanent||!1,c=s.packedData.byteLength/1024;let l=!(o in this.metadataData.documentSizes);try{await de.performTransaction(this.database.db,this.name,"readwrite",t=>l?de.add(t,s):de.put(t,s)),0<r.length&&(n=t._attachments||t.attachments,await he.saveAttachments(this.database.name,this.name,a._id,n)),this.metadata.updateDocument(o,c,h,r.length),await this.database.metadata.saveMetadata()}catch(n){if(0<r.length)try{await he.deleteAttachments(this.database.name,this.name,a._id)}catch(n){}throw n}return await this._maybeFreeSpace(),this.observer._emit("afterAdd",t),l})}async getDocument(t,e=null,a=!1){if(this.observer._emit("beforeGet",t),t in this.metadataData.documentSizes){var r=await de.performTransaction(this.database.db,this.name,"readonly",e=>de.get(e,t));if(r){let t;if(ke.isEncrypted(r)){if(!e)return!1;t=new ke(r,e)}else t=new ke(r);return e=await t.objectOutput(a),this.observer._emit("afterGet",e),e}}return!1}async getDocuments(t,e=null,a=!1){let r=[],i=t.filter(t=>t in this.metadataData.documentSizes);return 0!==i.length&&await de.performTransaction(this.database.db,this.name,"readonly",async t=>{var s,n=i.map(e=>de.get(t,e));for(s of await Promise.all(n))if(s){let t;if(ke.isEncrypted(s)){if(!e)continue;t=new ke(s,e)}else t=new ke(s);var o=await t.objectOutput(a);r.push(o)}}),r}async deleteDocument(t,e=!1){return this.observer._emit("beforeDelete",t),!(this.permanents[t]&&!e)&&t in this.sizes&&(0<(this.metadata.documentAttachments[t]||0)&&await he.deleteAttachments(this.database.name,this.name,t),await de.performTransaction(this.database.db,this.name,"readwrite",e=>de.delete(e,t)),this.metadata.deleteDocument(t),await this.database.metadata.saveMetadata(),this.observer._emit("afterDelete",t),!0)}async freeSpace(t){let e;this.lastFreeSpaceTime=Date.now();var a,r=this.sizeKB;if(0<=t){if(r<=t)return 0;e=r-t}else t=r-(e=-t);let i=0;for([a]of Object.entries(this.metadataData.documentModifiedAt).filter(([t])=>!this.metadataData.documentPermanent[t]).sort((t,e)=>t[1]-e[1]))if(this.sizeKB>t){if(i+=this.metadataData.documentSizes[a],await this.deleteDocument(a,!0),i>=e)break}return i}async query(t={},e={}){let{encryptionKey:a=null,limit:r=1/0,offset:i=0,orderBy:s=null,index:n=null}=e,o=[];await de.performTransaction(this.database.db,this.name,"readonly",async t=>{let e=t,a=(n&&t.indexNames.contains(n)&&(e=t.index(n)),s?e.openCursor(null,"asc"===s?"next":"prev"):e.openCursor());return new Promise((t,e)=>{let s=0,n=0;a.onsuccess=e=>{var a;!(e=e.target.result)||s>=r?t():(n<i?n++:(a=e.value,o.push(a),s++),e.continue())},a.onerror=()=>e(a.error)})});var h,c,l=[];for(h of o){let e;if(ke.isEncrypted(h)){if(!a)continue;e=new ke(h,a)}else e=new ke(h);if(0<Object.keys(t).length){var d,u=await e.objectOutput();let a=!0;for(d in t)if((d.includes(".")?(c=u.data,d.split(".").reduce((t,e)=>(t||{})[e],c)):u.data[d])!==t[d]){a=!1;break}if(!a)continue}l.push(await e.objectOutput())}return l}async close(){this._freeSpaceInterval&&(clearInterval(this._freeSpaceInterval),this._freeSpaceInterval=null,this._freeSpaceHandler=null)}toString(){return`[Collection: ${this.name} | Database: ${this.database.name} | Size: ${this.sizeKB.toFixed(2)}KB | Documents: ${this.length}]`}}},function(t,e,a){a.r(e),e=a(0),"undefined"!=typeof window?(window.Database=e.Database,window.Document=e.Document,window.Collection=e.Collection):(self.Database=e.Database,self.Document=e.Document,self.Collection=e.Collection)}]);
|
package/dist/index.min.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(t=>{var e={};function a(r){var s;return(e[r]||(s=e[r]={i:r,l:!1,exports:{}},t[r].call(s.exports,s,s.exports,a),s.l=!0,s)).exports}a.m=t,a.c=e,a.d=function(t,e,r){a.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:r})},a.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},a.t=function(t,e){if(1&e&&(t=a(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var r=Object.create(null);if(a.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var s in t)a.d(r,s,function(e){return t[e]}.bind(null,s));return r},a.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return a.d(e,"a",e),e},a.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},a.p="",a(a.s=0)})([function(t,e,a){a.r(e);var r=a(1);class s{constructor(t){this.arrayType=t,this.bitMask=this.calculateBitMask()}calculateBitMask(){var t={Uint8Array:255,Uint16Array:65535,Uint32Array:4294967295};if(this.arrayType.name in t)return t[this.arrayType.name];throw new Error("Unsupported array type: "+this.arrayType.name)}performDeltaEncoding(t){this.validateInputType(t,"performDeltaEncoding");var e,a=new this.arrayType(t.length),r=0|t.length,s=0;for(a[0]=0|t[0],s=1;(0|s)<(0|r);s=s+1|0)e=t[s]-t[s-1]&this.bitMask,a[s]=0|e;return a}performDeltaDecoding(t){this.validateInputType(t,"performDeltaDecoding");var e,a=new this.arrayType(t.length),r=0|t.length,s=0;for(a[0]=0|t[0],s=1;(0|s)<(0|r);s=s+1|0)e=a[s-1]+t[s]&this.bitMask,a[s]=0|e;return a}validateInputType(t,e){if(!(t instanceof this.arrayType))throw new Error(`Input data type does not match for method ${e}. Expected: `+this.arrayType.name)}}class i{constructor(t){this.bitArray=new Uint8Array(t+7>>3)}setBit(t,e){var a=1<<(t|=0)%8;this.bitArray[t=t/8|0]=(e|=0)?this.bitArray[t]|a:this.bitArray[t]&~a}getBit(t){return this.bitArray[(t|=0)/8|0]&1<<t%8?1:0}}var n=new class{constructor(){this.deltaEncoder8Bit=new s(Uint8Array),this.deltaEncoder16Bit=new s(Uint16Array),this.deltaEncoder32Bit=new s(Uint32Array)}getDeltaEncoder(t){switch(t){case"Uint8Array":case"Int8Array":case"Uint8ClampedArray":return this.deltaEncoder8Bit;case"Uint16Array":case"Int16Array":return this.deltaEncoder16Bit;case"Uint32Array":case"Int32Array":case"Float32Array":case"Float64Array":return this.deltaEncoder32Bit;default:throw new Error("Unknown TypedArray type.")}}compress(t){var e=t.constructor,a=e.name,r=t.length,s=this.getDeltaEncoder(a).performDeltaEncoding(new e(t.buffer)),n=new i(t.length),o=[];let c=s[0];o.push(c);for(let t=1;t<s.length;t++)s[t]===c?n.setBit(t,!0):(o.push(s[t]),c=s[t]);return this.packData(o,n,r,e.BYTES_PER_ELEMENT)}packData(t,e,a,r){r=t.length*r;var s=(e=e.bitArray).length;return(s=new Uint8Array(9+r+s))[0]=this.getDataTypeId(t),s.set(this.convertLengthToBytes(r),1),s.set(this.convertLengthToBytes(a),5),s.set(t,9),s.set(e,9+r),s}convertLengthToBytes(t){return Uint8Array.of(t>>0&255,t>>8&255,t>>16&255,t>>24&255)}getDataTypeId(t){return{Uint8Array:1,Int8Array:2,Uint8ClampedArray:3,Uint16Array:4,Int16Array:5,Uint32Array:6,Int32Array:7,Float32Array:8,Float64Array:9}[t.constructor.name]||0}decompress(t){var e=t[0],a=this.extractLengthFromBytes(t,1),r=this.extractLengthFromBytes(t,5),s=new Uint8Array(t.subarray(9,9+a)),n=(t=new Uint8Array(t.subarray(9+a)),new(a=this.getArrayConstructorByTypeId(e))(s.buffer)),o=new i(8*t.length),c=(o.bitArray=t,new a(r));let h=0;for(let t=0;(0|t)<(0|r);t=t+1|0)o.getBit(t)?c[t]=c[t-1|0]:c[t]=n[h++];return this.getDeltaEncoder(a.name).performDeltaDecoding(c)}extractLengthFromBytes(t,e){return t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24}getArrayConstructorByTypeId(t){return{1:Uint8Array,2:Int8Array,3:Uint8ClampedArray,4:Uint16Array,5:Int16Array,6:Uint32Array,7:Int32Array,8:Float32Array,9:Float64Array}[t]||Uint8Array}},o=class{constructor(t){this._buffers=new WeakMap,this._store={},this._nextId=0,this._compress=t?n.compress.bind(n):function(t){return t},this._decompress=t?n.decompress.bind(n):function(t){return t}}_generateId(){var t=this._nextId;return this._nextId++,t}clear(){this._buffers=new WeakMap,this._store={},this._nextId=0}insert(t,e){if(void 0===e){if(this._buffers.has(t))return this._buffers.get(t);e=this._generateId()}else if(this._store.hasOwnProperty(e))throw new Error(`ID ${e} is already in use.`);return e=parseInt(e),this._buffers.set(t,e),this._store[e]=t,e}retrieve(t){return this._store[parseInt(t)]}retrieveAll(){var t={},e=Object.entries(this._store);for(let s=0;s<e.length;s++){var[a,r]=e[s],r=this._compress(new Uint8Array(r)).buffer;t[parseInt(a)]=r}return t}insertAll(t){var e=Object.entries(t);for(let t=0;t<e.length;t++){var[a,r]=e[t],r=this._decompress(new Uint8Array(r)).buffer;this.insert(r,parseInt(a))}}},c=new class{constructor(){this._packBufferTemp8=new Uint8Array(15e3),this._headerByteLength=0,this._offset=0,this._b64=new r.B64chromium,this._b64Base64ToBytes=this._b64.base64ToBytes.bind(this._b64),this._b64BytesToBase64=this._b64.bytesToBase64.bind(this._b64),this._textDecoder=new TextDecoder,this._textDecoderFunction=this._textDecoder.decode.bind(this._textDecoder),this._textEncoder=new TextEncoder,this._textEncoderFunction=this._textEncoder.encode.bind(this._textEncoder),this._textEncoderIntoFunction=this._textEncoder.encodeInto.bind(this._textEncoder),this.encodeOtherBound=this.encodeOther.bind(this),this.decodeOtherBound=this.decodeOther.bind(this),this.stringifyBound=this._innerStringify.bind(this),this.parseBound=this._innerParse.bind(this),this.use_compressor=!1,this._setEngine()}_setEngine(){this.engine=new class{constructor(t,e,a,r,s,i,n,c,h){this._hasher=new class{constructor(t){this._chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",this._charLookup={};for(let t=0;t<this._chars.length;t++)this._charLookup[this._chars[t]]=t;this._bitPerChar=6,this._accumulatorBitNumber=32,this._outputLength=Math.max(1,Math.min(0|t,this._accumulatorBitNumber/this._bitPerChar|0)),this._primes=Uint32Array.of(2654435761,2246822519,3266489917,668265263),this._values=new Uint32Array(this._primes.length+2),this.imul=Math.imul,this.rotl=function(t,e){return(t>>>=0)<<(e&=31)|t>>>32-e}}get outputLength(){return this._outputLength}get chars(){return this._chars}get finalValue(){return this._values[4]}set finalValue(t){return this._values[4]=(0|t)>>>0}get primes(){return this._primes}get values(){return this._values}get accumulator(){return this._values}get charLookup(){return this._charLookup}getCharValue(t){return 63&this.charLookup[t]}aggregateCharValue(t,e,a,r){return t<<18|e<<12|a<<6|r}getCharByOffset(t){return this.chars[63&t]}hash(t){this.values.fill(0);for(var e=0,a=0,r=t.length,s=r>>2>>2;e<s;a=++e<<4)this.accumulator[0]=this.accumulator[0]+this.imul(this.aggregateCharValue(this.getCharValue(t[a]),this.getCharValue(t[a+1|0]),this.getCharValue(t[a+2|0]),this.getCharValue(t[a+3|0])),this.primes[0]),this.accumulator[1]=this.accumulator[1]+this.imul(this.aggregateCharValue(this.getCharValue(t[a+4|0]),this.getCharValue(t[a+5|0]),this.getCharValue(t[a+6|0]),this.getCharValue(t[a+7|0])),this.primes[1]),this.accumulator[2]=this.accumulator[2]+this.imul(this.aggregateCharValue(this.getCharValue(t[a+8|0]),this.getCharValue(t[a+9|0]),this.getCharValue(t[a+10|0]),this.getCharValue(t[a+11|0])),this.primes[2]),this.accumulator[3]=this.accumulator[3]+this.imul(this.aggregateCharValue(this.getCharValue(t[a+12|0]),this.getCharValue(t[a+13|0]),this.getCharValue(t[a+14|0]),this.getCharValue(t[a+15|0])),this.primes[3]);for(e<<=2;(0|e)<(0|r);a=(e=(e+1|0)>>>0)<<2)this.accumulator[3&e]=this.accumulator[3&e]+this.imul(this.aggregateCharValue(this.getCharValue(t[a])||0,this.getCharValue(t[a+1|0])||0,this.getCharValue(t[a+2|0])||0,this.getCharValue(t[a+3|0]))||0,this.primes[3&e]);this.finalValue=this.rotl(this.accumulator[0],1)+this.rotl(this.accumulator[1],7)+this.rotl(this.accumulator[2],12)+this.rotl(this.accumulator[3],18)>>>0;for(var i,n=0,o=new Array(this.outputLength);n<this.outputLength;n++)i=63&this.finalValue,o[n]=this.getCharByOffset(i),this.finalValue=(this.finalValue-i)/64>>>0;return o.join("")}}(1),this.hashThis=r||this._hasher.hash.bind(this._hasher),this.base=t||"data:joyson/",this.shortBase=e||"d:j/",this.baseLength=this.base.length,this.shortBaseLength=this.shortBase.length,this.encapsulate=a||function(t){return JSON.stringify(t)},this.encodeObjectOut=s||function(t){return t},this.decodeObjectOut=i||function(t){return t},this.stringifyOut=n||JSON.stringify,this.parseOut=c||JSON.parse,this._initializeErrorConstructors(),this.arrayBufferIDManager=new o(h),this._initializeBufferConstructors(),this._initializeDynamicTypes(["object","number","bigint","map","set","date","string","error","regexp","buffer","boolean","static"])}_initializeDynamicTypes(t){this.dynamicValues={},this.dynamicValuesIdKey={};for(var e=0;e<t.length;e++){var a=t[e];this.dynamicValues[a]={},this.dynamicValues[a].name=a,this.dynamicValues[a].str=this.base+this.dynamicValues[a].name+";",this.dynamicValues[a].id=this.hashThis(this.dynamicValues[a].name),this.dynamicValues[a].shortStr=this.shortBase+this.dynamicValues[a].id+";",this.dynamicValues[a].strCode=new Uint8Array(this.dynamicValues[a].str.split("").map((function(t){return t.charCodeAt(0)}))),this.dynamicValues[a].shortStrCode=new Uint8Array(this.dynamicValues[a].shortStr.split("").map((function(t){return t.charCodeAt(0)}))),this.dynamicValues[a].strLen=this.dynamicValues[a].str.length,this.dynamicValues[a].shortStrLen=this.dynamicValues[a].shortStr.length,this.dynamicValuesIdKey[this.dynamicValues[a].id]=this.dynamicValues[a].name}}_initializeErrorConstructors(){this.errorConstructors={Error:Error,TypeError:TypeError,SyntaxError:SyntaxError,ReferenceError:ReferenceError,RangeError:RangeError,EvalError:EvalError,URIError:URIError,DOMException:DOMException}}_initializeBufferConstructors(){this.bufferConstructors={ArrayBuffer:ArrayBuffer,Uint8Array:Uint8Array,Uint8ClampedArray:Uint8ClampedArray,Int8Array:Int8Array,Uint16Array:Uint16Array,Int16Array:Int16Array,Uint32Array:Uint32Array,Int32Array:Int32Array,Float32Array:Float32Array,Float64Array:Float64Array}}clear(){this.arrayBufferIDManager.clear()}getAllArrayBuffer(){var t=this.arrayBufferIDManager.retrieveAll();return this.clear(),t}setAllArrayBuffer(t){this.clear(),this.arrayBufferIDManager.insertAll(t)}_isNotNumber(t){return isNaN(t)}_isNotFiniteNumber(t){return!isFinite(t)}_isNotObject(t){return null===t}_isNotString(t){return t.includes("\0")}_isError(t){return void 0!==t.name&&t.name in this.errorConstructors}_isBuffer(t){return(t instanceof ArrayBuffer||"object"==typeof t.buffer)&&(t.constructor||{}).name in this.bufferConstructors}_mustDecodeOfType(t){if("string"==typeof t){if(t.startsWith(this.shortBase))return 2;if(t.startsWith(this.base))return 1}return 0}_dataTypeNameFromKey(t){return this.dynamicValuesIdKey[t]}_decode(t,e){var a=t.slice(e?this.shortBaseLength:this.baseLength).split(";"),r=a[0],s=a[1];switch(e?this._dataTypeNameFromKey(r):r){case"static":return this.decodeStatic(s);case"number":return this.decodeSpecialNumber(s);case"bigint":return this.decodeBigNumber(s);case"string":return this.decodeSpecialString(s);case"boolean":return this.decodeBoolean(s);case"map":return this.decodeMap(s);case"set":return this.decodeSet(s);case"date":return this.decodeDate(s);case"regexp":return this.decodeRegexp(s);case"error":return this.decodeError(s);case"buffer":return this.decodeBuffer(s);case"object":return this.decodeSpecialObject(s);default:return this.decodeObjectOut(t,e)}}decode(t,e){switch(this._mustDecodeOfType(t)){case 0:return"object"==typeof t?this.decodeObjectOut(t,e):t;case 1:return this._decode(t,!1);case 2:return this._decode(t,!0)}}decodeStatic(t){switch(t){case"nan":return NaN;case"null":return null;case"undefined":return}}decodeSpecialNumber(t){switch(t){case"nan":return NaN;case"infinity":return 1/0;case"-infinity":return-1/0;case"epsilon":return Number.EPSILON;case"-epsilon":return-Number.EPSILON;case"-0":return parseInt("-0");default:return Number(t)}}decodeBigNumber(t){return BigInt(t)}decodeSpecialString(t){return atob(t)}decodeBoolean(t){return"true"===t}decodeMap(t){return t=atob(t),t=this.parseOut(t),new Map(t)}decodeSet(t){return t=atob(t),t=this.parseOut(t),new Set(t)}decodeDate(t){return new Date(t)||new Date(NaN)}decodeRegexp(t){t=t.split(":");var e=atob(t[0]);t=atob(t[1]);return new RegExp(e,t)}decodeError(t){t=t.split(":");var e=atob(t[0]);t=atob(t[1]);return new this.errorConstructors[e](t)}decodeBuffer(t){var e="ArrayBuffer"===(a=(t=t.split(":"))[0]),a=this.bufferConstructors[a],r=parseInt(t[1],16),s=parseInt(t[2],16);t=parseInt(t[3],16),t=this.arrayBufferIDManager.retrieve(t);return e?t:new a(t,r,s)}decodeSpecialObject(t){return t=atob(t),t=this.parseOut(t),Object(t)}_encodeFinal(t,e,a){return a?this.dynamicValues[t].shortStr+e:this.encapsulate(this.dynamicValues[t].str+e)}encode(t,e){switch(typeof t){case"undefined":return this.encodeStatic(t,e);case"number":return this._isNotNumber(t)?this.encodeStatic(t,e):this.encodeNumber(t,e);case"bigint":return this.encodeBigNumber(t,e);case"string":return this._isNotString(t)?this.encodeSpecialString(t,e):this.encodeString(t,e);case"boolean":return this.encodeBoolean(t,e);case"object":return this._isNotObject(t)?this.encodeStatic(t,e):"function"==typeof t.get?this.encodeMap(t,e):"function"==typeof t.delete?this.encodeSet(t,e):"function"==typeof t.toISOString?this.encodeDate(t,e):"function"==typeof t.exec?this.encodeRegexp(t,e):t!==t.valueOf()?this.encodeSpecialObject(t,e):this._isError(t)?this.encodeError(t,e):this._isBuffer(t)?this.encodeBuffer(t,e):this.encodeObject(t,e)}}encodeStatic(t,e){var a;switch(typeof t){case"number":a="nan";break;case"object":a="null";break;case"undefined":a="undefined"}return this._encodeFinal("static",a,e)}encodeNumber(t,e){var a;switch(t){case NaN:a="nan";break;case 1/0:a="infinity";break;case-1/0:a="-infinity";break;case Number.EPSILON:a="epsilon";break;case-Number.EPSILON:a="-epsilon";break;default:if("-0"===Number(t).toLocaleString())a="-0";else{if(!this._isNotFiniteNumber(t))return e?t:""+t;a=t}}return this._encodeFinal("number",a,e)}encodeBigNumber(t,e){return t=t.toString(),this._encodeFinal("bigint",t,e)}encodeSpecialString(t,e){return t=btoa(t),this._encodeFinal("string",t,e)}encodeString(t,e){return e?""+t:this.encapsulate(t)}encodeBoolean(t,e){return this._encodeFinal("boolean",t?"true":"false",e)}encodeMap(t,e){return t=Object.entries(Object.fromEntries(t)),t=this.stringifyOut(t),t=btoa(t),this._encodeFinal("map",t,e)}encodeSet(t,e){return t=Array.from(t),t=this.stringifyOut(t),t=btoa(t),this._encodeFinal("set",t,e)}encodeDate(t,e){return t=t.toISOString(),this._encodeFinal("date",t,e)}encodeRegexp(t,e){return t=[btoa(t.source),btoa(t.flags)],this._encodeFinal("regexp",t.join(":"),e)}encodeSpecialObject(t,e){return t=this.stringifyOut(t.valueOf()),t=btoa(t),this._encodeFinal("object",t,e)}encodeError(t,e){return t=[btoa(t.name),btoa(t.message)],this._encodeFinal("error",t.join(":"),e)}encodeBuffer(t,e){var a=(i=void 0===t.buffer)?"ArrayBuffer":t.constructor.name,r=t.byteOffset,s=i?t.byteLength:t.length,i=i?t:t.buffer;t=this.arrayBufferIDManager.insert(i),i=[a,parseInt(r).toString(16),parseInt(s).toString(16),parseInt(t).toString(16)];return this._encodeFinal("buffer",i.join(":"),e)}encodeObject(t,e){return this.encodeObjectOut(t,e)}}(void 0,void 0,void 0,void 0,this.encodeOtherBound,this.decodeOtherBound,this.stringifyBound,this.parseBound,this.use_compressor)}get compress(){return this.use_compressor}set compress(t){this.use_compressor=Boolean(t),this._setEngine()}_getComparator(){return function(t){return function(e){return function(a,r){return a={key:a,value:e[a]},t(a,{key:r,value:e[r]})}}}}_stringifyObject(t){if(Array.isArray(t)){for(var e=0,a=t.length,r=((s=Object.keys(t)).length,new Array(a));(0|e)<(0|a);e=(e+1|0)>>>0)r[e]=this.engine.encode(t[e],!1);return"["+r.join(",")+"]"}for(var s,i,n=this._getComparator(),o="",c=(e=0,a=0|(s=Object.keys(t).sort(n&&n(t))).length,"");(0|e)<(0|a);e=(e+1|0)>>>0)if(o=s[e]+"",i=this.engine.encode(t[o],!1))switch(0<(0|c.length)&&(c+=","),0|(0===o.length||o.includes("\0")||o.startsWith("$"))){case 0:c+=this.engine.encode(o,!1)+":"+i;break;case 1:c+='"$'+btoa("$"+o)+'":'+i}return"{"+c+"}"}encodeOther(t,e){return e?this._packObject(t):this._stringifyObject(t)}decodeOther(t,e){return e?this._unpackObject(t):this._parseObject(t)}_stringify(t,e){var a={};if(a.header=this.engine.encode(t,!1),!e){var r,s=this.engine.getAllArrayBuffer();for(r in a.buffers={},s)a.buffers[r]=this._b64BytesToBase64(new Uint8Array(s[r]))}return JSON.stringify(a)}stringify(t){return this._stringify(t,!1)}_innerStringify(t){return this._stringify(t,!0)}_parseObject(t){if(Array.isArray(t)){for(var e=[],a=0,r=t.length;(0|a)<(0|r);a=(a+1|0)>>>0)e.push(this.engine.decode(t[a]));return e}var s,i,n={},o=Object.keys(t),c="";for(a=0,r=0|o.length;(0|a)<(0|r);a=(a+1|0)>>>0)switch(c=o[a],s=this._keyMustDecode(c),i=this.engine.decode(t[c]),0|s){case 0:n[c]=i;break;case 1:n[atob(c.slice(1)).slice(1)]=i}return n}_parse(t,e){var a,r;t=JSON.parse(t);return e||(a=this._b64Base64ToBytes,r={},Object.entries(t.buffers).forEach((function(t){var e=t[0];r[e]=a(t[1]).buffer})),this.engine.setAllArrayBuffer(r)),this.engine.decode(JSON.parse(t.header))}parse(t){return this._parse(t,!1)}_innerParse(t){return this._parse(t,!0)}_packObject(t){if(Array.isArray(t)){for(var e=[],a=0,r=t.length;(0|a)<(0|r);a=(a+1|0)>>>0)e.push(this.engine.encode(t[a],!0));return e}var s,i={},n=Object.keys(t),o="";for(a=0,r=0|n.length;(0|a)<(0|r);a=(a+1|0)>>>0)if(o=n[a]+"",s=this.engine.encode(t[o],!0))switch(0|(""===o||o.includes("\0")||o.startsWith("$"))){case 0:i[this.engine.encode(o,!0)]=s;break;case 1:i["$"+btoa("$"+o)]=s}return i}pack(t){t=JSON.stringify(this.engine.encode(t,!0));var e=this.engine.getAllArrayBuffer(),a=0,r=Object.keys(e).length;for(n in e)a+=e[n].byteLength;var s=2*t.length+5,i=s+a+4;if((i=(this._packBufferTemp8.length<i&&(this._packBufferTemp8=new Uint8Array(i)),this._textEncoderIntoFunction(t,this._packBufferTemp8.subarray(4,4+s)))).written>s)throw new Error("Header in json is too fat!");t=i.written;var n,o=(this._packBufferTemp8[0]=t>>0&255,this._packBufferTemp8[1]=t>>8&255,this._packBufferTemp8[2]=t>>16&255,this._packBufferTemp8[3]=t>>24&255,t);a=4;for(n in this._packBufferTemp8[o+a]=r>>0&255,this._packBufferTemp8[o+a+1]=r>>8&255,this._packBufferTemp8[o+a+2]=r>>16&255,this._packBufferTemp8[o+a+3]=r>>24&255,a+=4,e){var c=e[n],h=c.byteLength;this._packBufferTemp8[o+a]=h>>0&255,this._packBufferTemp8[o+a+1]=h>>8&255,this._packBufferTemp8[o+a+2]=h>>16&255,this._packBufferTemp8[o+a+3]=h>>24&255,a+=4,this._packBufferTemp8.set(new Uint8Array(c),o+a),a+=h}return this._packBufferTemp8.slice(0,o+a)}_keyMustDecode(t){return t.startsWith("$")}_unpackObject(t){if(Array.isArray(t)){for(var e=[],a=0,r=t.length;(0|a)<(0|r);a=(a+1|0)>>>0)e.push(this.engine.decode(t[a],!0));return e}var s,i,n={},o=Object.keys(t),c="";for(a=0,r=0|o.length;(0|a)<(0|r);a=(a+1|0)>>>0)switch(c=o[a],s=this._keyMustDecode(c),i=this.engine.decode(t[c],!0),0|s){case 0:n[c]=i;break;case 1:n[atob(c.slice(1)).slice(1)]=i}return n}unpack(t){for(var e=4+(t[0]<<0|t[1]<<8|t[2]<<16|t[3]<<24),a=4+e,r=JSON.parse(this._textDecoderFunction(t.subarray(4,e))),s=t[e]<<0|t[1+e]<<8|t[2+e]<<16|t[3+e]<<24,i={},n=a,o=0;o<s;o++){var c=t[n]<<0|t[n+1]<<8|t[n+2]<<16|t[n+3]<<24;n+=4,i[o]=t.buffer.slice(n,n+c),n+=c}return this.engine.setAllArrayBuffer(i),this.engine.decode(r,!0)}};a.d(e,"Database",(function(){return D})),a.d(e,"Document",(function(){return B})),a.d(e,"Collection",(function(){return T}));class h{static async saveAttachments(t,e,a,r){var s,i=[];let n=await navigator.storage.getDirectory();for(s of[t,e,a])n=await n.getDirectoryHandle(s,{create:!0});for(let s=0;s<r.length;s++){var o=s.toString(),c=await(await n.getFileHandle(o,{create:!0})).createWritable();c=(await c.write(r[s].data),await c.close(),t+`/${e}/${a}/`+o);i.push(c)}return i}static async getAttachments(t){var e,a=[],r=await navigator.storage.getDirectory();for(e of t)try{var s=e.split("/");let t=r;for(let e=0;e<s.length-1;e++)t=await t.getDirectoryHandle(s[e]);var i=await(await t.getFileHandle(s[s.length-1])).getFile();a.push({path:e,data:i})}catch(t){console.error(`Error retrieving attachment at "${e}": `+t.message)}return a}static async deleteAttachments(t,e,a){var r=[t,e,a];let s=await navigator.storage.getDirectory();for(let t=0;t<r.length-1;t++)s=await s.getDirectoryHandle(r[t]);try{await s.removeEntry(r[r.length-1],{recursive:!0})}catch(t){console.error(`Error deleting attachments for document "${a}": `+t.message)}}toString(){return"[OPFSUtility]"}}class d{static async compress(t){t="string"==typeof t?(new TextEncoder).encode(t):t;var e=new CompressionStream("deflate"),a=e.writable.getWriter();return a.write(t),a.close(),this._streamToUint8Array(e.readable)}static async decompress(t){var e=new DecompressionStream("deflate"),a=e.writable.getWriter();return a.write(t),a.close(),this._streamToUint8Array(e.readable)}static async _streamToUint8Array(t){var e=t.getReader(),a=[];let r=0;for(;;){var{value:s,done:i}=await e.read();if(i)break;a.push(s),r+=s.length}var n,o=new Uint8Array(r);let c=0;for(n of a)o.set(n,c),c+=n.length;return o}toString(){return"[BrowserCompressionUtility]"}}class u{static async encrypt(t,e){var a=crypto.getRandomValues(new Uint8Array(16)),r=(e=await this._deriveKey(e,a),crypto.getRandomValues(new Uint8Array(12))),s=await this._generateChecksum(t);t=this._combineDataAndChecksum(t,s),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},e,t);return this._wrapIntoUint8Array(a,r,new Uint8Array(s))}static async decrypt(t,e){var{salt:t,iv:a,encryptedData:r}=this._unwrapUint8Array(t),a=(e=await this._deriveKey(e,t),t=await crypto.subtle.decrypt({name:"AES-GCM",iv:a},e,r),new Uint8Array(t)),{data:e,checksum:r}=this._separateDataAndChecksum(a);t=await this._generateChecksum(e);if(this._verifyChecksum(t,r))return e;throw new Error("Data integrity check failed. The data has been tampered with.")}static async _deriveKey(t,e){var a=new TextEncoder;a=await crypto.subtle.importKey("raw",a.encode(t),{name:"PBKDF2"},!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"PBKDF2",salt:e,iterations:6e5,hash:"SHA-512"},a,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}static async _generateChecksum(t){return new Uint8Array(await crypto.subtle.digest("SHA-256",t))}static _verifyChecksum(t,e){if(t.length!==e.length)return!1;for(let a=0;a<t.length;a++)if(t[a]!==e[a])return!1;return!0}static _combineDataAndChecksum(t,e){var a=new Uint8Array(t.length+e.length);return a.set(t),a.set(e,t.length),a}static _separateDataAndChecksum(t){var e=t.length-32;return{data:t.slice(0,e),checksum:t.slice(e)}}static _wrapIntoUint8Array(t,e,a){var r=new Uint8Array(t.length+e.length+a.length);return r.set(t,0),r.set(e,t.length),r.set(a,t.length+e.length),r}static _unwrapUint8Array(t){return{salt:t.slice(0,16),iv:t.slice(16,28),encryptedData:t.slice(28)}}toString(){return"[BrowserEncryptionUtility]"}}class l{static openDatabase(t,e=null,a=null){return new Promise((r,s)=>{let i;(i=e?indexedDB.open(t,e):indexedDB.open(t)).onupgradeneeded=e=>{var r=e.target.result,s=e.oldVersion;e=e.newVersion;console.log(`Upgrading database "${t}" from version ${s} to `+e),a&&a(r,s,e)},i.onsuccess=e=>{(e=e.target.result).onclose=()=>{console.log(`Database "${t}" connection is closing.`)},r(e)},i.onerror=e=>{s(new Error(`Failed to open database "${t}": `+e.target.error.message))}})}static async performTransaction(t,e,a,r,s=3,i=null){let n=null;for(let h=0;h<=s;h++)try{if(!t)throw new Error("Database connection is not available.");let s=t.transaction(Array.isArray(e)?e:[e],a);var o=Array.isArray(e)?e.map(t=>s.objectStore(t)):[s.objectStore(e)],c=i||Date.now()+"_"+Math.random();let h=await r(...o,c);return new Promise((t,e)=>{s.oncomplete=()=>t(h),s.onerror=()=>{n=new Error("Transaction failed: "+(s.error?s.error.message:"unknown error")),e(n)},s.onabort=()=>{n=new Error("Transaction aborted: "+(s.error?s.error.message:"unknown reason")),e(n)}})}catch(t){n=t,h<s&&(console.warn(`Transaction failed, retrying... (${s-h} attempts left): `+t.message),await new Promise(t=>setTimeout(t,100*Math.pow(2,h))))}throw new Error(`Transaction ultimately failed after ${s+1} attempts: `+n.message)}static add(t,e){return new Promise((a,r)=>{var s=t.add(e);s.onsuccess=()=>a(),s.onerror=t=>r("Failed to insert record: "+t.target.error.message)})}static put(t,e){return new Promise((a,r)=>{var s=t.put(e);s.onsuccess=()=>a(),s.onerror=t=>r("Failed to put record: "+t.target.error.message)})}static delete(t,e){return new Promise((a,r)=>{var s=t.delete(e);s.onsuccess=()=>a(),s.onerror=t=>r("Failed to delete record: "+t.target.error.message)})}static get(t,e){return new Promise((a,r)=>{var s=t.get(e);s.onsuccess=t=>a(t.target.result),s.onerror=t=>r(`Failed to retrieve record with key ${e}: `+t.target.error.message)})}static getAll(t){return new Promise((e,a)=>{var r=t.getAll();r.onsuccess=t=>e(t.target.result),r.onerror=t=>a("Failed to retrieve records: "+t.target.error.message)})}static count(t){return new Promise((e,a)=>{var r=t.count();r.onsuccess=t=>e(t.target.result),r.onerror=t=>a("Failed to count records: "+t.target.error.message)})}static clear(t){return new Promise((e,a)=>{var r=t.clear();r.onsuccess=()=>e(),r.onerror=t=>a("Failed to clear store: "+t.target.error.message)})}static deleteDatabase(t){return new Promise((e,a)=>{var r=indexedDB.deleteDatabase(t);r.onsuccess=()=>e(),r.onerror=t=>a("Failed to delete database: "+t.target.error.message)})}static iterateCursor(t,e){return new Promise((a,r)=>{var s=t.openCursor();s.onsuccess=t=>{(t=t.target.result)?(e(t.value,t.key),t.continue()):a()},s.onerror=t=>r("Cursor iteration failed: "+t.target.error.message)})}toString(){return"[IndexedDBUtility]"}}class m{static getItem(t){return(t=localStorage.getItem(t))?c.parse(t):null}static setItem(t,e){localStorage.setItem(t,c.stringify(e))}static removeItem(t){localStorage.removeItem(t)}static clear(){localStorage.clear()}toString(){return"[LocalStorageUtility]"}}class _{constructor(){this.queue=[],this.locked=!1}async acquire(){return new Promise(t=>{this.locked?this.queue.push(t):(this.locked=!0,t())})}release(){0<this.queue.length?this.queue.shift()():this.locked=!1}async runExclusive(t){await this.acquire();try{return await t()}finally{this.release()}}toString(){return`[AsyncMutex locked:${this.locked} queue:${this.queue.length}]`}}class g{constructor(t){this._dbName=t,this._metadataKey=`lacertadb_${this._dbName}_metadata`,this._collections=new Map,this._metadata=this._loadMetadata(),this._mutex=new _}async saveMetadata(){return this._mutex.runExclusive(()=>{m.setItem(this.metadataKey,this.getRawMetadata())})}async adjustTotals(t,e){return this._mutex.runExclusive(()=>{this.data.totalSizeKB+=t,this.data.totalLength+=e,this.data.modifiedAt=Date.now()})}_loadMetadata(){var t=m.getItem(this.metadataKey);if(t){for(var e in t.collections){var a=t.collections[e];a=new b(e,this,a);this.collections.set(e,a)}return t}return{name:this._dbName,collections:{},totalSizeKB:0,totalLength:0,modifiedAt:Date.now()}}get data(){return this._metadata}set data(t){this._metadata=t}get name(){return this.data.name}get metadataKey(){return this._metadataKey}get collections(){return this._collections}set collections(t){this._collections=t}get totalSizeKB(){return this.data.totalSizeKB}get totalLength(){return this.data.totalLength}get modifiedAt(){return this.data.modifiedAt}getCollectionMetadata(t){var e;return this.collections.has(t)||(e=new b(t,this),this.collections.set(t,e),this.data.collections[t]=e.getRawMetadata(),this.data.modifiedAt=Date.now()),this.collections.get(t)}getCollectionMetadataData(t){return(t=this.getCollectionMetadata(t))?t.getRawMetadata():{}}removeCollectionMetadata(t){var e=this.collections.get(t);e&&(this.data.totalSizeKB-=e.sizeKB,this.data.totalLength-=e.length,this.collections.delete(t),delete this.data.collections[t],this.data.modifiedAt=Date.now())}getCollectionNames(){return Array.from(this.collections.keys())}getRawMetadata(){for(var[t,e]of this._collections.entries())this.data.collections[t]=e.getRawMetadata();return this.data}setRawMetadata(t){for(var e in this._metadata=t,this._collections.clear(),t.collections){var a=t.collections[e];a=new b(e,this,a);this._collections.set(e,a)}}get dbName(){return this._dbName}get key(){return this._metadataKey}toString(){return`[DatabaseMetadata: ${this.name} | Collections: ${this.collections.size} | Size: ${this.totalSizeKB.toFixed(2)}KB | Documents: ${this.totalLength}]`}}class f extends Error{constructor(t,e,a=null){super(t),this.name="LacertaDBError",this.code=e,this.originalError=a,this.timestamp=Date.now()}toString(){return`[LacertaDBError ${this.code}: ${this.message} at ${new Date(this.timestamp).toISOString()}]`}}let y="COLLECTION_NOT_FOUND",p="COLLECTION_EXISTS";class b{constructor(t,e,a=null){this._collectionName=t,this._databaseMetadata=e,a?this._metadata=a:(this._metadata={name:t,sizeKB:0,length:0,createdAt:Date.now(),modifiedAt:Date.now(),documentSizes:{},documentModifiedAt:{},documentPermanent:{},documentAttachments:{}},this._databaseMetadata.data.collections[t]=this._metadata,this._databaseMetadata.data.modifiedAt=Date.now())}get name(){return this._collectionName}get keys(){return Object.keys(this.documentSizes)}get collectionName(){return this.name}get sizeKB(){return this._metadata.sizeKB}get length(){return this._metadata.length}get modifiedAt(){return this._metadata.modifiedAt}get metadata(){return this._metadata}set metadata(t){return this._metadata=t}get data(){return this.metadata}set data(t){this.metadata=t}get databaseMetadata(){return this._databaseMetadata}set databaseMetadata(t){this._databaseMetadata=t}get documentSizes(){return this.metadata.documentSizes}get documentModifiedAt(){return this.metadata.documentModifiedAt}get documentPermanent(){return this.metadata.documentPermanent}get documentAttachments(){return this.metadata.documentAttachments}set documentSizes(t){this.metadata.documentSizes=t}set documentModifiedAt(t){this.metadata.documentModifiedAt=t}set documentPermanent(t){this.metadata.documentPermanent=t}set documentAttachments(t){this.metadata.documentAttachments=t}updateDocument(t,e,a=!1,r=0){var s=!this.keys.includes(t),i=e-(this.documentSizes[t]||0);s=s?1:0;this.documentSizes[t]=e,this.documentModifiedAt[t]=Date.now(),this.documentPermanent[t]=a?1:0,this.documentAttachments[t]=r,this.metadata.sizeKB+=i,this.metadata.length+=s,this.metadata.modifiedAt=Date.now(),this.databaseMetadata.adjustTotals(i,s)}deleteDocument(t){var e;return t in this.documentSizes&&(e=this.documentSizes[t],delete this.documentSizes[t],delete this.documentModifiedAt[t],delete this.documentPermanent[t],delete this.documentAttachments[t],this.metadata.sizeKB-=e,--this.metadata.length,this.metadata.modifiedAt=Date.now(),this.databaseMetadata.adjustTotals(-e,-1),!0)}updateDocuments(t){for(var{docId:e,docSizeKB:a,isPermanent:r,attachmentCount:s}of t)this.updateDocument(e,a,r,s||0)}getRawMetadata(){return this.metadata}setRawMetadata(t){this.metadata=t}toString(){return`[CollectionMetadata: ${this.name} | Size: ${this.sizeKB.toFixed(2)}KB | Documents: ${this.length}]`}}class w{constructor(t,e=null,a=null){this.success=t,this.data=e,this.error=a}toString(){return`[LacertaDBResult success:${this.success} ${this.error?"error:"+this.error:""}]`}}class A{constructor(t){this._dbName=t,this._metadataKey=`lacertadb_${this._dbName}_quickstore_metadata`,this._documentKeyPrefix=`lacertadb_${this._dbName}_quickstore_data_`,this._metadata=this._loadMetadata()}_loadMetadata(){return m.getItem(this._metadataKey)||{totalSizeKB:0,totalLength:0,documentSizesKB:{},documentModificationTime:{},documentPermanent:{}}}_saveMetadata(){m.setItem(this._metadataKey,this._metadata)}setDocumentSync(t,e=null){e=(t=new B(t,e)).packSync();var a=t._id,r=t._permanent||!1,s=(e=c.stringify({_id:t._id,_created:t._created,_modified:t._modified,_permanent:r,_encrypted:t._encrypted,_compressed:t._compressed,packedData:e}),this._documentKeyPrefix+a);localStorage.setItem(s,e),s=e.length/1024;return(e=!(a in this._metadata.documentSizesKB))?this._metadata.totalLength+=1:this._metadata.totalSizeKB-=this._metadata.documentSizesKB[a],this._metadata.documentSizesKB[a]=s,this._metadata.documentModificationTime[a]=t._modified,this._metadata.documentPermanent[a]=r,this._metadata.totalSizeKB+=s,this._saveMetadata(),e}deleteDocumentSync(t,e=!1){var a;return!(this._metadata.documentPermanent[t]&&!e||(e=this._documentKeyPrefix+t,a=this._metadata.documentSizesKB[t]||0,!localStorage.getItem(e))||(localStorage.removeItem(e),delete this._metadata.documentSizesKB[t],delete this._metadata.documentModificationTime[t],delete this._metadata.documentPermanent[t],this._metadata.totalSizeKB-=a,--this._metadata.totalLength,this._saveMetadata(),0))}getAllKeys(){return Object.keys(this._metadata.documentSizesKB)}getDocumentSync(t,e=null){t=this._documentKeyPrefix+t;return(t=localStorage.getItem(t))?(t=c.parse(t),new B(t,e).unpackSync()):null}toString(){return`[QuickStore: ${this._dbName} | Size: ${this._metadata.totalSizeKB.toFixed(2)}KB | Documents: ${this._metadata.totalLength}]`}}class v{constructor(){this.queue=[],this.processing=!1}async execute(t){return new Promise((e,a)=>{this.queue.push({operation:t,resolve:e,reject:a}),this.process()})}async process(){if(!this.processing&&0!==this.queue.length){for(this.processing=!0;0<this.queue.length;){var{operation:t,resolve:e,reject:a}=this.queue.shift();try{e(await t())}catch(t){a(t)}}this.processing=!1}}toString(){return`[TransactionManager processing:${this.processing} queue:${this.queue.length}]`}}class S{constructor(){this._listeners={beforeAdd:[],afterAdd:[],beforeDelete:[],afterDelete:[],beforeGet:[],afterGet:[]}}on(t,e){if(!this._listeners[t])throw new Error(`Event "${t}" is not supported.`);this._listeners[t].push(e)}off(t,e){this._listeners[t]&&-1<(e=this._listeners[t].indexOf(e))&&this._listeners[t].splice(e,1)}_emit(t,...e){if(this._listeners[t])for(var a of this._listeners[t])a(...e)}_cleanup(){for(var t in this._listeners)this._listeners[t]=[]}toString(){return`[Observer listeners:{${Object.entries(this._listeners).map(([t,e])=>t+":"+e.length).join(" ")}}]`}}class D{constructor(t,e={}){this._dbName=t,this._db=null,this._collections=new Map,this._metadata=new g(t),this._settings=new C(t,e),this._quickStore=new A(this._dbName),this._settings.init()}get quickStore(){return this._quickStore}async init(){var t;for(t of(this.db=await l.openDatabase(this.name,void 0,(t,e,a)=>{this._upgradeDatabase(t,e,a)}),this.data.getCollectionNames())){var e=new T(this,t,this.settings);await e.init(),this.collections.set(t,e)}}_createDataStores(t){for(var e of this.collections.keys())this._createDataStore(t,e)}_createDataStore(t,e){t.objectStoreNames.contains(e)||t.createObjectStore(e,{keyPath:"_id"})}_upgradeDatabase(t,e,a){console.log(`Upgrading database "${this.name}" from version ${e} to `+a),t.objectStoreNames.contains("_metadata")||t.createObjectStore("_metadata",{keyPath:"_id"})}async createCollection(t){var e;return this.collections.has(t)?(console.log(`Collection "${t}" already exists.`),new w(!1,this.collections.get(t),new f(`Collection "${t}" already exists`,p))):(this.db.objectStoreNames.contains(t)||(e=this.db.version+1,this.db.close(),this.db=await l.openDatabase(this.name,e,(e,a,r)=>{this._createDataStore(e,t)})),await(e=new T(this,t,this.settings)).init(),this.collections.set(t,e),this.data.getCollectionMetadata(t),await this.data.saveMetadata(),new w(!0,e))}async deleteCollection(t){var e;return this.collections.has(t)?(await(e=this.collections.get(t)).close(),e.observer._cleanup(),await l.performTransaction(this.db,t,"readwrite",t=>l.clear(t)),this.collections.delete(t),this.data.removeCollectionMetadata(t),await this.data.saveMetadata(),new w(!0,null)):new w(!1,null,new f(`Collection "${t}" does not exist`,y))}async getCollection(t){var e;return this.collections.has(t)?new w(!0,this.collections.get(t)):this.db.objectStoreNames.contains(t)?(await(e=new T(this,t,this.settings)).init(),this.collections.set(t,e),new w(!0,e)):new w(!1,null,new f(`Collection "${t}" does not exist`,y))}async close(){var t;for(t of this.collectionsArray)await t.close();this.db&&(this.db.close(),this.db=null)}async deleteDatabase(){await this.close(),await l.deleteDatabase(this.name),m.removeItem(this.data.metadataKey),this.settings.clear(),this.data=null}get name(){return this._dbName}get db(){return this._db}set db(t){this._db=t}get data(){return this.metadata}set data(t){this.metadata=t}get collectionsArray(){return Array.from(this.collections.values())}get collections(){return this._collections}get metadata(){return this._metadata}set metadata(t){this._metadata=t}get totalSizeKB(){return this.data.totalSizeKB}get totalLength(){return this.data.totalLength}get modifiedAt(){return this.data.modifiedAt}get settings(){return this._settings}get settingsData(){return this.settings.data}toString(){return`[Database: ${this.name} | Collections: ${this.collections.size} | Size: ${this.totalSizeKB.toFixed(2)}KB | Documents: ${this.totalLength}]`}}class B{constructor(t,e=null){this._id=t._id||this._generateId(),this._created=t._created||Date.now(),this._permanent=!!t._permanent,this._encrypted=t._encrypted||!!e,this._compressed=t._compressed||!1,this._attachments=t._attachments||t.attachments||[],t.packedData?(this._packedData=t.packedData,this._modified=t._modified||Date.now(),this._data=null):(this._data=t.data||{},this._modified=Date.now(),this._packedData=new Uint8Array(0)),this._encryptionKey=e||""}get attachments(){return this._attachments}set attachments(t){this._attachments=t}get data(){return this._data}get packedData(){return this._packedData}get encryptionKey(){return this._encryptionKey}set data(t){this._data=t}set packedData(t){this._packedData=t}set encryptionKey(t){this._encryptionKey=t}static hasAttachments(t){return t._attachments&&0<t._attachments.length||t.attachments&&0<t.attachments.length}static async getAttachments(t,e,a){var r;return B.hasAttachments(t)?(r=t._attachments||t.attachments,t.attachments=await h.getAttachments(r),Promise.resolve(t)):[]}static isEncrypted(t){return t._encrypted&&t.packedData}static async decryptDocument(t,e){if(B.isEncrypted(t))return e=await u.decrypt(t.packedData,e),e=c.unpack(e),{_id:t._id,_created:t._created,_modified:t._modified,_encrypted:!0,_compressed:t._compressed,_permanent:!!t._permanent,attachments:t.attachments,data:e};throw new Error("Document is not encrypted.")}async pack(){if(!this.data)throw new Error("No data to pack");let t=c.pack(this.data);return this._compressed&&(t=await this._compressData(t)),this._encrypted&&(t=await this._encryptData(t)),this.packedData=t}packSync(){if(!this.data)throw new Error("No data to pack");if(this._encrypted)throw new Error("Packing synchronously a document being encrypted is impossible.");if(this._compressed)throw new Error("Packing synchronously a document being compressed is impossible.");var t=c.pack(this.data);return this.packedData=t}async unpack(){if(!this.data&&0<this.packedData.length){let t=this.packedData;this._encrypted&&(t=await this._decryptData(t)),this._compressed&&(t=await this._decompressData(t)),this.data=c.unpack(t)}return this.data}unpackSync(){if(!this.data&&0<this.packedData.length){if(this._encrypted)throw new Error("Unpacking synchronously a document being encrypted is impossible.");if(this._compressed)throw new Error("Unpacking synchronously a document being compressed is impossible.");this.data=c.unpack(this.packedData)}return this.data}async _encryptData(t){var e=this.encryptionKey;return u.encrypt(t,e)}async _decryptData(t){var e=this.encryptionKey;return u.decrypt(t,e)}async _compressData(t){return d.compress(t)}async _decompressData(t){return d.decompress(t)}_generateId(){return"xxxx-xxxx-xxxx".replace(/[x]/g,()=>(16*Math.random()|0).toString(16))}async objectOutput(t=!1){this.data||await this.unpack();var e={_id:this._id,_created:this._created,_modified:this._modified,_permanent:this._permanent,_encrypted:this._encrypted,_compressed:this._compressed,attachments:this.attachments,data:this.data};return t&&0<this.attachments.length&&(t=await h.getAttachments(this.attachments),e.attachments=t),e}async databaseOutput(){return this.packedData&&0!==this.packedData.length||await this.pack(),{_id:this._id,_created:this._created,_modified:this._modified,_permanent:!!this._permanent,_compressed:this._compressed,_encrypted:this._encrypted,attachments:this.attachments,packedData:this.packedData}}toString(){return`[Document: ${this._id} | Created: ${new Date(this._created).toISOString()} | Encrypted: ${this._encrypted} | Compressed: ${this._compressed} | Permanent: ${this._permanent}]`}}class C{constructor(t,e={}){this._dbName=t,this._settingsKey=`lacertadb_${this._dbName}_settings`,this._data=this._loadSettings(),this._mergeSettings(e)}init(){if(this.set("sizeLimitKB",this.get("sizeLimitKB")||1/0),this.set("bufferLimitKB",this.get("bufferLimitKB")||-.2*this.get("sizeLimitKB")),this.get("bufferLimitKB")<-.8*this.get("sizeLimitKB"))throw new Error("Buffer limit cannot be below -80% of the size limit.");this.set("freeSpaceEvery",this._validateFreeSpaceSetting(this.get("freeSpaceEvery")))}_validateFreeSpaceSetting(t=1e4){if(void 0===t||!1===t||0===t)return 1/0;if(t<1e3&&0!==t)throw new Error("Invalid freeSpaceEvery value. It must be 0, Infinity, or above 1000.");return 1e3<=t&&t<1e4&&console.warn("Warning: freeSpaceEvery value is between 1000 and 10000, which may lead to frequent freeing."),t}_loadSettings(){return m.getItem(this.settingsKey)||{}}_saveSettings(){m.setItem(this.settingsKey,this.data)}_mergeSettings(t){this.data=Object.assign(this.data,t),this._saveSettings()}get(t){return this.data[t]}set(t,e){this.data[t]=e,this._saveSettings()}remove(t){delete this.data[t],this._saveSettings()}clear(){this.data={},this._saveSettings()}get dbName(){return this._dbName}get data(){return this._data}set data(t){this._data=t}get settingsKey(){return this._settingsKey}toString(){return`[Settings: ${this.dbName} | SizeLimit: ${this.get("sizeLimitKB")}KB | BufferLimit: ${this.get("bufferLimitKB")}KB]`}}class T{constructor(t,e,a){this._database=t,this._collectionName=e,this._settings=a,this._metadata=null,this._lastFreeSpaceTime=0,this._observer=new S,this._transactionManager=new v,this._freeSpaceInterval=null,this._freeSpaceHandler=null}get observer(){return this._observer}async createIndex(t,e={}){let a=e.name||t.replace(/\./g,"_");var r=this.database.db.version+1;this.database.db.close(),this.database.db=await l.openDatabase(this.database.name,r,r=>{r.objectStoreNames.contains(this.name)&&!(r=r.transaction([this.name]).objectStore(this.name)).indexNames.contains(a)&&r.createIndex(a,t,{unique:e.unique||!1,multiEntry:e.multiEntry||!1})})}async init(){this.metadata=this.database.metadata.getCollectionMetadata(this.name),this.settingsData.freeSpaceEvery!==1/0&&(this._freeSpaceHandler=()=>this._maybeFreeSpace(),this._freeSpaceInterval=setInterval(this._freeSpaceHandler,this.settingsData.freeSpaceEvery))}get name(){return this._collectionName}get sizes(){return this.metadataData.documentSizes||{}}get modifications(){return this.metadataData.documentModifiedAt||{}}get attachments(){return this.metadataData.documentAttachments||{}}get permanents(){return this.metadataData.documentPermanent||{}}get keys(){return Object.keys(this.sizes)}get documentsMetadata(){var t,e=this.keys,a=this.sizes,r=this.modifications,s=this.permanents,i=this.attachments,n=new Array(e.length),o=0;for(t of e)n[o++]={id:t,size:a[t],modified:r[t],permanent:s[t],attachment:i[t]};return n}get settings(){return this._settings}get settingsData(){return this.settings.data}set settings(t){this._settings=t}get lastFreeSpaceTime(){return this._lastFreeSpaceTime}set lastFreeSpaceTime(t){this._lastFreeSpaceTime=t}get database(){return this._database}get metadata(){return this.database.metadata.getCollectionMetadata(this.name)}get metadataData(){return this.metadata.getRawMetadata()}set metadata(t){this._metadata=t}get sizeKB(){return this.metadataData.sizeKB}get length(){return this.metadataData.length}get totalSizeKB(){return this.sizeKB}get totalLength(){return this.length}get modifiedAt(){return this.metadataData.modifiedAt}get isFreeSpaceEnabled(){return this.settingsData.freeSpaceEvery!==1/0}get shouldRunFreeSpaceSize(){return this.totalSizeKB>this.settingsData.sizeLimitKB+this.settingsData.bufferLimitKB}get shouldRunFreeSpaceTime(){return this.isFreeSpaceEnabled&&Date.now()-this.lastFreeSpaceTime>=this.settingsData.freeSpaceEvery}async _maybeFreeSpace(){if(this.shouldRunFreeSpaceSize||this.shouldRunFreeSpaceTime)return this.freeSpace(this.settingsData.sizeLimitKB)}async addDocument(t,e=null){return this._transactionManager.execute(async()=>{this.observer._emit("beforeAdd",t);var a=new B(t,e),r=[];if(B.hasAttachments(t)){var s=t._attachments||t.attachments;for(let t=0;t<s.length;t++)r.push(`${this.database.name}/${this.name}/${a._id}/`+t);a._attachments=r}let i=await a.databaseOutput();var n,o=i._id,c=i._permanent||!1,d=i.packedData.byteLength/1024;let u=!(o in this.metadataData.documentSizes);try{await l.performTransaction(this.database.db,this.name,"readwrite",t=>u?l.add(t,i):l.put(t,i)),0<r.length&&(n=t._attachments||t.attachments,await h.saveAttachments(this.database.name,this.name,a._id,n)),this.metadata.updateDocument(o,d,c,r.length),await this.database.metadata.saveMetadata()}catch(n){if(0<r.length)try{await h.deleteAttachments(this.database.name,this.name,a._id)}catch(n){}throw n}return await this._maybeFreeSpace(),this.observer._emit("afterAdd",t),u})}async getDocument(t,e=null,a=!1){if(this.observer._emit("beforeGet",t),t in this.metadataData.documentSizes){var r=await l.performTransaction(this.database.db,this.name,"readonly",e=>l.get(e,t));if(r){let t;if(B.isEncrypted(r)){if(!e)return!1;t=new B(r,e)}else t=new B(r);return e=await t.objectOutput(a),this.observer._emit("afterGet",e),e}}return!1}async getDocuments(t,e=null,a=!1){let r=[],s=t.filter(t=>t in this.metadataData.documentSizes);return 0!==s.length&&await l.performTransaction(this.database.db,this.name,"readonly",async t=>{var i,n=s.map(e=>l.get(t,e));for(i of await Promise.all(n))if(i){let t;if(B.isEncrypted(i)){if(!e)continue;t=new B(i,e)}else t=new B(i);var o=await t.objectOutput(a);r.push(o)}}),r}async deleteDocument(t,e=!1){return this.observer._emit("beforeDelete",t),!(this.permanents[t]&&!e)&&t in this.sizes&&(0<(this.metadata.documentAttachments[t]||0)&&await h.deleteAttachments(this.database.name,this.name,t),await l.performTransaction(this.database.db,this.name,"readwrite",e=>l.delete(e,t)),this.metadata.deleteDocument(t),await this.database.metadata.saveMetadata(),this.observer._emit("afterDelete",t),!0)}async freeSpace(t){let e;this.lastFreeSpaceTime=Date.now();var a,r=this.sizeKB;if(0<=t){if(r<=t)return 0;e=r-t}else t=r-(e=-t);let s=0;for([a]of Object.entries(this.metadataData.documentModifiedAt).filter(([t])=>!this.metadataData.documentPermanent[t]).sort((t,e)=>t[1]-e[1]))if(this.sizeKB>t){if(s+=this.metadataData.documentSizes[a],await this.deleteDocument(a,!0),s>=e)break}return s}async query(t={},e={}){let{encryptionKey:a=null,limit:r=1/0,offset:s=0,orderBy:i=null,index:n=null}=e,o=[],c=0,h=0;return await l.performTransaction(this.database.db,this.name,"readonly",async e=>{let d=e,u=(n&&e.indexNames.contains(n)&&(d=e.index(n)),i?d.openCursor(null,"asc"===i?"next":"prev"):d.openCursor());return new Promise((e,i)=>{u.onsuccess=async i=>{if(!(i=i.target.result)||c>=r)e(o);else{var n,d=i.value;if(h<s)h++;else{let e;if(B.isEncrypted(d)){if(!a)return void i.continue();e=new B(d,a)}else e=new B(d);if(0<Object.keys(t).length){var u,l=await e.objectOutput();let a=!0;for(u in t)if((u.includes(".")?(n=l.data,u.split(".").reduce((t,e)=>(t||{})[e],n)):l.data[u])!==t[u]){a=!1;break}if(!a)return void i.continue()}o.push(await e.objectOutput()),c++}i.continue()}},u.onerror=()=>i(u.error)})}),o}async close(){this._freeSpaceInterval&&(clearInterval(this._freeSpaceInterval),this._freeSpaceInterval=null,this._freeSpaceHandler=null)}toString(){return`[Collection: ${this.name} | Database: ${this.database.name} | Size: ${this.sizeKB.toFixed(2)}KB | Documents: ${this.length}]`}}},function(t,e,a){var r=(()=>{var t=new ArrayBuffer(2560),e=new Uint8Array(t,0,256),a=new Uint8Array(t,256,256),r=new Uint32Array(t,512,128),s=new Uint32Array(t,1024,128),i=new Uint32Array(t,1536,128),n=new Uint32Array(t,2048,128);e.set(Uint8Array.from("AAAABBBBCCCCDDDDEEEEFFFFGGGGHHHHIIIIJJJJKKKKLLLLMMMMNNNNOOOOPPPPQQQQRRRRSSSSTTTTUUUUVVVVWWWWXXXXYYYYZZZZaaaabbbbccccddddeeeeffffgggghhhhiiiijjjjkkkkllllmmmmnnnnooooppppqqqqrrrrssssttttuuuuvvvvwwwwxxxxyyyyzzzz0000111122223333444455556666777788889999++++////".split("").map((function(t){return 255&t.charCodeAt(0)})))),a.set(Uint8Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("").map((function(t){return 255&t.charCodeAt(0)})))),r.set(new Uint32Array(128).fill(33554431)),s.set(new Uint32Array(128).fill(33554431)),i.set(new Uint32Array(128).fill(33554431)),n.set(new Uint32Array(128).fill(33554431)),Object.entries({43:[248,57347,8392448,4063232],47:[252,61443,12586752,4128768],48:[208,16387,3328,3407872],49:[212,20483,4197632,3473408],50:[216,24579,8391936,3538944],51:[220,28675,12586240,3604480],52:[224,32771,3584,3670016],53:[228,36867,4197888,3735552],54:[232,40963,8392192,3801088],55:[236,45059,12586496,3866624],56:[240,49155,3840,3932160],57:[244,53251,4198144,3997696],65:[0,0,0,0],66:[4,4096,4194304,65536],67:[8,8192,8388608,131072],68:[12,12288,12582912,196608],69:[16,16384,256,262144],70:[20,20480,4194560,327680],71:[24,24576,8388864,393216],72:[28,28672,12583168,458752],73:[32,32768,512,524288],74:[36,36864,4194816,589824],75:[40,40960,8389120,655360],76:[44,45056,12583424,720896],77:[48,49152,768,786432],78:[52,53248,4195072,851968],79:[56,57344,8389376,917504],80:[60,61440,12583680,983040],81:[64,1,1024,1048576],82:[68,4097,4195328,1114112],83:[72,8193,8389632,1179648],84:[76,12289,12583936,1245184],85:[80,16385,1280,1310720],86:[84,20481,4195584,1376256],87:[88,24577,8389888,1441792],88:[92,28673,12584192,1507328],89:[96,32769,1536,1572864],90:[100,36865,4195840,1638400],97:[104,40961,8390144,1703936],98:[108,45057,12584448,1769472],99:[112,49153,1792,1835008],100:[116,53249,4196096,1900544],101:[120,57345,8390400,1966080],102:[124,61441,12584704,2031616],103:[128,2,2048,2097152],104:[132,4098,4196352,2162688],105:[136,8194,8390656,2228224],106:[140,12290,12584960,2293760],107:[144,16386,2304,2359296],108:[148,20482,4196608,2424832],109:[152,24578,8390912,2490368],110:[156,28674,12585216,2555904],111:[160,32770,2560,2621440],112:[164,36866,4196864,2686976],113:[168,40962,8391168,2752512],114:[172,45058,12585472,2818048],115:[176,49154,2816,2883584],116:[180,53250,4197120,2949120],117:[184,57346,8391424,3014656],118:[188,61442,12585728,3080192],119:[192,3,3072,3145728],120:[196,4099,4197376,3211264],121:[200,8195,8391680,3276800],122:[204,12291,12585984,3342336]}).forEach((function(t){r[parseInt(t[0])]=4294967295&t[1][0],s[parseInt(t[0])]=4294967295&t[1][1],i[parseInt(t[0])]=4294967295&t[1][2],n[parseInt(t[0])]=4294967295&t[1][3]}));class o{constructor(){this._CHNK_L_=Math.pow(108,2)/2|0,this._CHNK_L_STR_=3*this._CHNK_L_|0,this._CHNK_L_BUFF_=4*this._CHNK_L_|0,this._PAD_C_=255&"=".charCodeAt(0),this._E0_=e.slice(0,e.length),this._E1_=a.slice(0,a.length),this._D0_=r.slice(0,r.length),this._D1_=s.slice(0,s.length),this._D2_=i.slice(0,i.length),this._D3_=n.slice(0,n.length),this._AB_=new ArrayBuffer(this._CHNK_L_BUFF_+4|0),this._u32aT_=new Uint32Array(this._AB_,0,1),this._u8aT_=new Uint8Array(this._AB_,0,3),this._T_=new Uint8Array(this._AB_,4,0|this._CHNK_L_BUFF_)}get PAD_C(){return 255&this._PAD_C_}get CHNK_L_STR(){return 0|this._CHNK_L_STR_}get u32aT0(){return this._u32aT_[0]}set u32aT0(t){this._u32aT_[0]=(0|t)>>>0}get u8aTa(){return this._u8aT_[0]}get u8aTb(){return this._u8aT_[1]}get u8aTc(){return this._u8aT_[2]}_base64_decode_u32ax1(t,e){this.u32aT0=this._D0_[255&t.charCodeAt(e=(0|e)>>>0)]|this._D1_[255&t.charCodeAt(e+1|0)]|this._D2_[255&t.charCodeAt(e+2|0)]|this._D3_[255&t.charCodeAt(e+3|0)]}_base64_encode_u8ax4(t,e,a){this._T_[0|(e=(0|e)>>>0)]=this._E0_[t[(0|(a=(0|a)>>>0))>>>0]],this._T_[e+1|0]=this._E1_[(3&t[(0|a)>>>0])<<4|t[(a+1|0)>>>0]>>4&15],this._T_[e+2|0]=this._E1_[(15&t[(a+1|0)>>>0])<<2|t[(a+2|0)>>>0]>>6&3],this._T_[e+3|0]=this._E1_[t[(a+2|0)>>>0]]}_base64_encode_final(t,e,a,r){switch(r=(0|r)>>>0,((a=(0|a)>>>0)-(e=(0|e)>>>0)|0)>>>0){case 1:return this._T_[0|r]=this._E0_[t[(0|e)>>>0]],this._T_[r+1|0]=this._E1_[(3&t[(0|e)>>>0])<<4|t[(e+1|0)>>>0]>>4&15],this._T_[r+2|0]=this._PAD_C_,this._T_[r+3|0]=this._PAD_C_,this._T_.subarray(0,0|(r=r+4|0));case 2:return this._T_[0|r]=this._E0_[t[(0|e)>>>0]],this._T_[r+1|0]=this._E1_[(3&t[(0|e)>>>0])<<4|t[(e+1|0)>>>0]>>4&15],this._T_[r+2|0]=this._E1_[(15&t[(e+1|0)>>>0])<<2|t[(e+2|0)>>>0]>>6&3],this._T_[r+3|0]=this._PAD_C_,this._T_.subarray(0,0|(r=r+4|0));case 0:return this._T_.subarray(0,0|r);default:return this._T_}}_base64_decode_final(t,e,a,r,s){switch(a=(0|a)>>>0,r=(0|r)>>>0,0|(s=(0|s)>>>0)){case 0:return this.u32aT0=(this._D0_[e.charCodeAt(0|a)]|this._D1_[e.charCodeAt(a+1|0)]|this._D2_[e.charCodeAt(a+2|0)]|this._D3_[e.charCodeAt(a+3|0)]|0)>>>0,t[0|r]=255&this.u32aT0,t[r+1|0]=this.u32aT0>>8&255,t[r+2|0]=this.u32aT0>>16&255,r+3|0;case 1:return this.u32aT0=(0|this._D0_[e.charCodeAt(0|a)])>>>0,t[0|r]=255&this.u32aT0,r+1|0;case 2:return this.u32aT0=(this._D0_[e.charCodeAt(0|a)]|this._D1_[e.charCodeAt(a+1|0)]|0)>>>0,t[0|r]=255&this.u32aT0,r+1|0;default:return this.u32aT0=(this._D0_[e.charCodeAt(0|a)]|this._D1_[e.charCodeAt(a+1|0)]|this._D2_[e.charCodeAt(a+2|0)]|0)>>>0,t[0|r]=255&this.u32aT0,t[r+1|0]=this.u32aT0>>8&255,r+2|0}}_base64_store_u8ax3(t,e){t[e=(0|e)>>>0]=this.u8aTa,t[e+1|0]=this.u8aTb,t[e+2|0]=this.u8aTc}get_max_round_str(t){return 0|Math.ceil(t/this.CHNK_L_STR)}base64_encode(t,e){var a=0|t.length,r=(e|=0)*this.CHNK_L_STR|0,s=0,i=Math.min(r+this.CHNK_L_STR|0,0|a)-2|0;if(0<(0|i))for(;(0|r)<(0|i);r=(r+3|0)>>>0,s=s+4|0)this._base64_encode_u8ax4(t,s,r);return o.encodeChars_(this._base64_encode_final(t,r,a,s))}bytesToBase64(t){for(var e="",a=0,r=this.get_max_round_str(t.length);(0|a)<(0|r);a=(a+1|0)>>>0)e+=this.base64_encode(t,0|a);return e}base64ToBytes(t){var e,a,r=0|t.length,s=0,i=0,n=0;if(0==(0|r))return new Uint8Array(0);for(t.charCodeAt(r-1|0)===this.PAD_C&&(n=n+1|0,t.charCodeAt((r=r-1|0)-1|0)===this.PAD_C)&&(r=r-1|0,n=n+1|0),e=new Uint8Array(t.length/4*3-n),a=0==(0|(n=3&r))?(r>>>2)-1|0:r>>>2;(0|s)<(0|a);s=(s+1|0)>>>0)this._base64_decode_u32ax1(t,s<<2),this._base64_store_u8ax3(e,i),i=i+3|0;return this._base64_decode_final(e,t,s<<=2,i,n),e}}return o.charCode_=function(t){return 255&t.charCodeAt(0)},o.charCodeAt_=function(t,e){return 255&t.charCodeAt(0|e)},o.encodeChars_=function(t){return 0<(0|t.length)?String.fromCharCode.apply(null,t):""},o})();t.exports={B64chromium:r}}]);
|
|
1
|
+
(t=>{var e={};function r(a){var i;return(e[a]||(i=e[a]={i:a,l:!1,exports:{}},t[a].call(i.exports,i,i.exports,r),i.l=!0,i)).exports}r.m=t,r.c=e,r.d=function(t,e,a){r.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:a})},r.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r.t=function(t,e){if(1&e&&(t=r(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var a=Object.create(null);if(r.r(a),Object.defineProperty(a,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var i in t)r.d(a,i,function(e){return t[e]}.bind(null,i));return a},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="",r(r.s=0)})([function(t,e,r){r.r(e);let a=240,i=0,s=16,n=32,o=48,h=64,c=80,l=96,d=112,u=128,m=144,f=160,p=176,g=192,w=224,y=0,b=1,_=2,v=3,S=16,A=17,k=18,B=19,D=20,z=21,I=22,E=23,U=24,M=25,V=26,K=32,P=33,C=34,x=35,T=48,F=49,O=50,$=51,j=52,N=53,R=54,L=55,q=64,H=65,G=66,W=67,Y=68,X=69,J=70,Q=71,Z=72,tt=80,et=81,rt=82,at=83,it=96,st=97,nt=98,ot=99,ht=100,ct=101,lt=102,dt=103,ut=104,mt=105,ft=106,pt=107,gt=112,wt=113,yt=114,bt=128,_t=129,vt=130,St=131,At=144,kt=145,Bt=160,Dt=161,zt=162,It=163,Et=164,Ut=165,Mt=166,Vt=167,Kt=168,Pt=176,Ct=192,xt=193,Tt=208,Ft=209,Ot=224,$t=225,jt=16;var Nt=16-(15&(Rt=new ArrayBuffer(128)).byteLength)&15,Rt=Rt.slice(Nt);let Lt=new Float32Array(Rt,0,32),qt=new Float64Array(Rt,0,16);new Int32Array(Rt,0,32),new Int16Array(Rt,0,64),new Int8Array(Rt,0,128),new Uint32Array(Rt,0,32),new Uint16Array(Rt,0,64),new Uint8Array(Rt,0,128);let Ht=new Array(256),Gt=new Array(256),Wt=new Array(256);var Yt=[[A,2],[k,4],[B,4],[D,4],[z,8],[K,8],[P,8]];for(let t=0;t<Yt.length;t++){var[Xt,Jt]=Yt[t];Gt[Xt]=Jt}var Qt,Zt,te=[[it,1],[st,1],[nt,1],[ot,2],[ht,2],[ct,4],[lt,4],[dt,4],[ut,8],[mt,8],[ft,8],[W,1],[Y,2],[X,4],[J,4],[Q,8]];for(let t=0;t<te.length;t++){var[ee,re]=te[t];Wt[ee]=re}for([Qt,Zt]of[[it,"Uint8Array"],[st,"Int8Array"],[nt,"Uint8ClampedArray"],[ot,"Uint16Array"],[ht,"Int16Array"],[ct,"Uint32Array"],[lt,"Int32Array"],[dt,"Float32Array"],[ut,"Float64Array"],[mt,"BigInt64Array"],[ft,"BigUint64Array"],[pt,"DataView"]]){var ae=globalThis[Zt];ae&&(Ht[Qt]=ae)}class ie{constructor(){this.blockSize=16,this.tempBuffer=new ArrayBuffer(1040),this.tempOffset=jt-(15&this.tempBuffer.byteLength)&15,this.alignedTempBuffer=this.tempBuffer.slice(this.tempOffset),this.tempF32=new Float32Array(this.alignedTempBuffer),this.tempF64=new Float64Array(this.alignedTempBuffer),this.tempI32=new Int32Array(this.alignedTempBuffer)}canOptimize(t){var e=t.length;if(!(8<=e&(0==(e&e-1)||16<=e)))return!1;var r=typeof t[0];if(!("number"==r|0))return!1;var a=1+(e>>>5);for(let i=0;i<a;i++)if(typeof t[i<<5&e-1]!=r)return!1;return!0}analyzeNumericArray(t){let e=1,r=1/0,a=-1/0,i=1;var s,n=t.length,o=n>>>4;for(let s=0;s<o;s++){var h=s<<4;for(let s=0;s<4;s++){var c=h+s;c<n&&(e&=(c=t[c])===(0|(Lt[s]=c))|0,r=r<c?r:c,a=a>c?a:c,i)&&Lt[s]!==c&&(i=0)}}for(let s=o<<4;s<n;s++){var l=t[s];e&=l===(0|l)|0,r=r<l?r:l,a=a>l?a:l,i&&(Lt[0]=l,Lt[0]!==l)&&(i=0)}return e?(s=Math.max(Math.abs(r),Math.abs(a)))<=127?{type:W,elementSize:1}:s<=32767?{type:Y,elementSize:2}:{type:X,elementSize:4}:i?{type:J,elementSize:4}:{type:Q,elementSize:8}}processInBlocks(t,e){var r=[],a=t.length,i=a+16-1>>>4;for(let o=0;o<i;o++){var s=o<<4,n=Math.min(16+s,a);s=this.process128BitBlock(t,s,n,e);r.push(...s)}return r}process128BitBlock(t,e,r,a){var i=r-e;if(i<=4){let r=new Array(i);for(let s=0;s<i;s++)r[s]=a(t[e+s]);return r}let s=new Array(i);var n=i>>>2;for(let r=0;r<n;r++){var o=r<<2;for(let r=0;r<4;r++)this.tempF32[r]=t[e+o+r];for(let t=0;t<4;t++)s[o+t]=a(this.tempF32[t])}for(let r=n<<2;r<i;r++)s[r]=a(t[e+r]);return s}}class se{constructor(t=65536){this.size=(t+15&-16)>>>0,this.buffer=new ArrayBuffer(this.size+jt),this.offset=jt-(15&this.buffer.byteLength)&15,this.alignedBuffer=this.buffer.slice(this.offset),this.u8=new Uint8Array(this.alignedBuffer),this.view=new DataView(this.alignedBuffer),this.pos=0,this.alignedViews={u16:null,u32:null,f32:null,f64:null,i64:null}}ensure(t){if(this.pos+(t|=0)>this.size){t=(Math.max(this.size<<1,this.size+t)+15&-16)>>>0;var e,r=new ArrayBuffer(t+jt),a=jt-(15&r.byteLength)&15,i=(a=r.slice(a),new Uint8Array(a)),s=(n=this.pos)>>>4,n=15&n;for(let t=0;t<s;t++){var o=t<<4,h=this.u8.subarray(o,16+o);i.set(h,o)}0<n&&(n=this.u8.subarray(e=s<<4,e+n),i.set(n,e)),this.buffer=r,this.alignedBuffer=a,this.u8=i,this.view=new DataView(a),this.size=t,this.alignedViews={u16:null,u32:null,f32:null,f64:null,i64:null}}}alignPos(t){t=t-1|0,this.pos=(this.pos+t&~t)>>>0}writeU8(t){this.ensure(1),this.u8[this.pos++]=255&t}writeU16(t){if(this.alignPos(2),this.ensure(2),!(0==(1&this.pos)|0))throw new Error("Alignment error: position not 2-byte aligned");this.view.setUint16(this.pos,65535&t,!0),this.pos=this.pos+2|0}writeI16(t){if(this.alignPos(2),this.ensure(2),!(0==(1&this.pos)|0))throw new Error("Alignment error: position not 2-byte aligned");this.view.setInt16(this.pos,t,!0),this.pos=this.pos+2|0}writeU32(t){if(this.alignPos(4),this.ensure(4),!(0==(3&this.pos)|0))throw new Error("Alignment error: position not 4-byte aligned");this.view.setUint32(this.pos,t>>>0,!0),this.pos=this.pos+4|0}writeI32(t){if(this.alignPos(4),this.ensure(4),!(0==(3&this.pos)|0))throw new Error("Alignment error: position not 4-byte aligned");this.view.setInt32(this.pos,t,!0),this.pos=this.pos+4|0}writeF32(t){if(this.alignPos(4),this.ensure(4),!(0==(3&this.pos)|0))throw new Error("Alignment error: position not 4-byte aligned");this.view.setFloat32(this.pos,+t,!0),this.pos=this.pos+4|0}writeF64(t){if(this.alignPos(8),this.ensure(8),!(0==(7&this.pos)|0))throw new Error("Alignment error: position not 8-byte aligned");this.view.setFloat64(this.pos,+t,!0),this.pos=this.pos+8|0}writeBigInt64(t){if(this.alignPos(8),this.ensure(8),!(0==(7&this.pos)|0))throw new Error("Alignment error: position not 8-byte aligned");this.view.setBigInt64(this.pos,t,!0),this.pos=this.pos+8|0}writeVarint(t){if(t>>>=0,this.ensure(5),t<128|0)this.u8[this.pos++]=t;else if(t<16384|0)this.u8[this.pos]=127&t|128,this.u8[this.pos+1]=t>>>7,this.pos+=2;else{let e=this.pos;for(;128<=t;)this.u8[e++]=127&t|128,t>>>=7;this.u8[e++]=t,this.pos=e}}writeBulkAligned(t,e){e=Math.min(e,jt);var r,a=(this.alignPos(e),t.byteLength||t.length);this.ensure(a),t.buffer?(r=t.byteOffset||0)%e==0|0?(e=new Uint8Array(t.buffer,r,a),this.copy128BitAligned(e,a)):((e=new Uint8Array(a)).set(new Uint8Array(t.buffer,r,a)),this.copy128BitAligned(e,a)):this.u8.set(t,this.pos),this.pos=this.pos+a|0}copy128BitAligned(t,e){var r,a=e>>>4;e&=15;for(let e=0;e<a;e++){var i=e<<4,s=this.pos+i;i=t.subarray(i,16+i);this.u8.set(i,s)}0<e&&(e=t.subarray(r=a<<4,r+e),this.u8.set(e,this.pos+r))}writePackedArray(t,e){var r=0|t.length,a=(this.writeVarint(r),Wt[e]);if(!a)throw new Error("Unknown element size for type: 0x"+e.toString(16));switch(this.alignPos(Math.min(a,8)),this.ensure(r*a),e){case W:for(let e=0;e<r;e++)this.view.setInt8(this.pos,t[e]),this.pos+=1;break;case Y:for(let e=0;e<r;e++)this.view.setInt16(this.pos,t[e],!0),this.pos+=2;break;case X:for(let e=0;e<r;e++)this.view.setInt32(this.pos,t[e],!0),this.pos+=4;break;case J:for(let e=0;e<r;e++)this.view.setFloat32(this.pos,t[e],!0),this.pos+=4;break;case Q:for(let e=0;e<r;e++)this.view.setFloat64(this.pos,t[e],!0),this.pos+=8;break;default:throw new Error("Unknown packed array type: 0x"+e.toString(16))}}reset(){this.pos=0}getResult(){return this.u8.subarray(0,this.pos)}}class ne{constructor(){this.simdProcessor=new ie,this.constructorMap=new Map,this.initConstructorMap(),this.TYPE_FLAGS={IS_ARRAY:1,IS_TYPED_ARRAY:2,IS_OBJECT:4,IS_COLLECTION:8,IS_ERROR:16,IS_DATE:32,IS_REGEXP:64,IS_BINARY:128}}initConstructorMap(){var t,e,r,a,i=[[Date,At],[RegExp,Pt],[Map,bt],[Set,_t],[WeakMap,vt],[WeakSet,St],[ArrayBuffer,gt],[DataView,pt]];for([t,e]of[["Uint8Array",it],["Int8Array",st],["Uint8ClampedArray",nt],["Uint16Array",ot],["Int16Array",ht],["Uint32Array",ct],["Int32Array",lt],["Float32Array",dt],["Float64Array",ut],["BigInt64Array",mt],["BigUint64Array",ft],["SharedArrayBuffer",yt]]){var s=globalThis[t];s&&i.push([s,e])}for([r,a]of i)this.constructorMap.set(r,a)}detect(t){if(null===t)return y;if(void 0===t)return b;var e=typeof t;switch(e){case"boolean":return t?v:_;case"number":return this.detectNumber(t);case"bigint":return this.detectBigInt(t);case"string":return this.detectString(t);case"symbol":return this.detectSymbol(t);case"object":return null===t?y:this.detectObject(t);case"function":return b;default:throw new Error("Unknown type: "+e)}}detectNumber(t){if(t!=t|0)return I;qt[0]=t;var e,r=(e=new Uint32Array(qt.buffer,qt.byteOffset))[0],a=2146435072;return((e=e[1])&a)==a&0===r&0==(1048575&e)?(2147483648&e)>>>31?U:E:0===t&(2147483648&e)>>>31?M:t===(0|t)|0?(a=Math.abs(t))<=127?S:a<=32767?A:a<=2147483647?k:V:(Lt[0]=t,Lt[0]===t|0?D:z)}detectBigInt(t){var e=t<0n|0;return((t=(e?-t:t)<=0x7fffffffffffffffn|0)?[K,P]:[C,x])[e]}detectString(t){if("string"!=typeof t)throw new Error("detectString called with non-string value: "+typeof t);var e=t.length;if(0===e)return T;let r=1;var a,i=e>>>4;for(let e=0;e<i&&r;e++){var s=e<<4;for(let e=0;e<16;e++){r&=t.charCodeAt(s+e)<=127|0}}for(let a=i<<4;a<e&&r;a++){r&=t.charCodeAt(a)<=127|0}return r?[$,O,F,F][a=e<16|(e<256)<<1]:(a=(a=(new TextEncoder).encode(t).length)<16|(a<256)<<1,[R,N,j,j][a])}detectSymbol(t){if("symbol"!=typeof t)throw new Error("detectSymbol called with non-symbol value: "+typeof t);return void 0!==Symbol.keyFor(t)|0?$t:Ot}detectObject(t){if(null===t)return y;var e,r=t.constructor,a=this.constructorMap.get(r);return void 0!==a?a===At?(e=t.getTime())==e|0?At:kt:a:0|Array.isArray(t)?this.detectArray(t):0|ArrayBuffer.isView(t)?this.detectTypedArrayType(t):t instanceof Error|0?this.detectErrorType(t):"undefined"!=typeof Blob&&t instanceof Blob|0?t instanceof File|0?xt:Ct:r===Object|void 0===r|null===r?0===Object.keys(t).length|0?tt:et:(e=Object.getPrototypeOf(t))===Object.prototype|null===e?0===Object.keys(t).length|0?tt:rt:at}detectArray(t){var e=t.length;if(0===e)return q;let r=0,a=!1;for(let i=0;i<e;i++)i in t?r++:a=!0;return a||r<3*e>>>2?G:this.simdProcessor.canOptimize(t)?this.simdProcessor.analyzeNumericArray(t).type:H}detectTypedArrayType(t){var e=t.constructor.name;t=e.length;switch(e.charCodeAt(0)<<8|e.charCodeAt(t-1)){case 21881:return"Uint8Array"===e?it:this.fallbackTypedArrayDetection(e);case 18809:return"Int8Array"===e?st:this.fallbackTypedArrayDetection(e);case 21860:return nt;case 18041:return e.includes("32")?dt:ut;case 17017:return e.startsWith("BigU")?ft:mt;default:return this.fallbackTypedArrayDetection(e)}}fallbackTypedArrayDetection(t){return{DataView:pt,Uint8Array:it,Int8Array:st,Uint8ClampedArray:nt,Uint16Array:ot,Int16Array:ht,Uint32Array:ct,Int32Array:lt,Float32Array:dt,Float64Array:ut,BigInt64Array:mt,BigUint64Array:ft}[t]||it}detectErrorType(t){var e=t.constructor.name;switch(e.charCodeAt(0)){case 69:return 114===e.charCodeAt(1)?Bt:Dt;case 82:return 110===e.charCodeAt(2)?zt:It;case 83:return Et;case 84:return Ut;case 85:return Mt;case 65:return Vt;default:return Kt}}}Nt=class{constructor(t={}){this.options={compression:t.compression||!1,deduplication:!1!==t.deduplication,shareArrayBuffers:!1!==t.shareArrayBuffers,simdOptimization:!1!==t.simdOptimization,detectCircular:!1!==t.detectCircular,memoryPoolSize:t.memoryPoolSize||65536,...t},this.pool=new se(this.options.memoryPoolSize),this.detector=new ne,this.simdProcessor=new ie,this.refs=new Map,this.circularRefs=new Set,this.strings=new Map,this.buffers=new Map,this.encoder=new TextEncoder,this.decoder=new TextDecoder}serialize(t){return this.resetState(),this.pool.writeU32(1413632565),this.pool.writeU8(5),this.options.detectCircular&&this.detectCircularReferences(t,new WeakSet),this.writeValue(t),this.pool.getResult()}resetState(){this.pool.reset(),this.refs.clear(),this.circularRefs.clear(),this.strings.clear(),this.buffers.clear()}detectCircularReferences(t,e){if("object"==typeof t&&null!==t)if(e.has(t))this.circularRefs.add(t);else{e.add(t);try{if(Array.isArray(t))for(let r=0;r<t.length;r++)r in t&&this.detectCircularReferences(t[r],e);else if(t instanceof Map)for(var[r,a]of t)this.detectCircularReferences(r,e),this.detectCircularReferences(a,e);else if(t instanceof Set)for(var i of t)this.detectCircularReferences(i,e);else for(var s in t)if(t.hasOwnProperty(s))try{this.detectCircularReferences(t[s],e)}catch(r){}}finally{e.delete(t)}}}writeValue(t){if(this.options.detectCircular&&"object"==typeof t&&null!==t&&this.circularRefs.has(t)){var e=this.refs.get(t);if(void 0!==e)return this.pool.writeU8(Ft),void this.pool.writeVarint(e);this.refs.set(t,this.refs.size)}if(this.options.deduplication&&"object"==typeof t&&null!==t&&!this.circularRefs.has(t)){if(void 0!==(e=this.refs.get(t)))return this.pool.writeU8(Tt),void this.pool.writeVarint(e);this.refs.set(t,this.refs.size)}if(this.options.deduplication&&"string"==typeof t&&3<t.length){if(void 0!==(e=this.strings.get(t)))return this.pool.writeU8(L),void this.pool.writeVarint(e);this.strings.set(t,this.strings.size)}if(this.options.shareArrayBuffers&&t instanceof ArrayBuffer){if(void 0!==(e=this.buffers.get(t)))return this.pool.writeU8(wt),void this.pool.writeVarint(e);this.buffers.set(t,this.buffers.size)}var r=this.detector.detect(t),y=(this.pool.writeU8(r),r&a);switch(y){case i:break;case s:this.writeNumber(t,r);break;case n:this.writeBigInt(t,r);break;case o:this.writeString(t,r);break;case h:this.writeArray(t,r);break;case c:this.writeObject(t,r);break;case l:this.writeTypedArray(t,r);break;case d:this.writeArrayBuffer(t,r);break;case u:this.writeCollection(t,r);break;case m:this.writeDate(t,r);break;case f:this.writeError(t,r);break;case p:this.writeRegExp(t);break;case g:this.writeBinary(t,r);break;case w:this.writeSpecial(t,r);break;default:throw new Error(`Unsupported type group: 0x${y.toString(16)} for type 0x`+r.toString(16))}}writeNumber(t,e){switch(e){case S:this.pool.writeU8(t);break;case A:this.pool.writeI16(t);break;case k:this.pool.writeI32(t);break;case B:this.pool.writeU32(t);break;case D:this.pool.writeF32(t);break;case z:this.pool.writeF64(t);break;case V:var r=t<0;this.pool.writeVarint(Math.abs(t)),this.pool.writeU8(r?1:0)}}writeBigInt(t,e){switch(e){case K:case P:this.pool.writeBigInt64(BigInt(t));break;case C:case x:this.writeLargeBigInt(t)}}writeLargeBigInt(t){var e,r=BigInt(t).toString(16).replace("-",""),a=[];for(let t=r.length-2;0<=t;t-=2)a.push(parseInt(r.substr(t,2),16));for(e of(r.length%2&&a.push(parseInt(r[0],16)),this.pool.writeVarint(a.length),a))this.pool.writeU8(e)}writeString(t,e){var r=t.length;switch(e){case T:break;case F:this.pool.writeU8(r);for(let e=0;e<r;e++)this.pool.writeU8(t.charCodeAt(e));break;case O:this.pool.writeU8(r);for(let e=0;e<r;e++)this.pool.writeU8(t.charCodeAt(e));break;case $:this.pool.writeVarint(r);for(let e=0;e<r;e++)this.pool.writeU8(t.charCodeAt(e));break;case j:case N:case R:var a=this.encoder.encode(t);e===j||e===N?this.pool.writeU8(a.length):this.pool.writeVarint(a.length),this.pool.writeBulkAligned(a,1)}}writeArray(t,e){var r=t.length;switch(e){case q:break;case H:this.pool.writeVarint(r);for(let e=0;e<r;e++)this.writeValue(t[e]);break;case G:this.writeSparseArray(t);break;case W:case Y:case X:case J:case Q:this.pool.writePackedArray(t,e);break;case Z:this.writeSIMDOptimizedArray(t)}}writeSparseArray(t){var e,r,a=t.length,i=[];for(let e=0;e<a;e++)e in t&&i.push([e,t[e]]);for([e,r]of(this.pool.writeVarint(a),this.pool.writeVarint(i.length),i))this.pool.writeVarint(e),this.writeValue(r)}writeSIMDOptimizedArray(t){var e=this.simdProcessor.analyzeNumericArray(t);this.pool.writeU8(e.type),this.pool.writePackedArray(t,e.type)}writeObject(t,e){var r=Object.keys(t);if(e!==tt){var a;e=r.filter(e=>{try{return"function"!=typeof t[e]}catch(e){return!1}});for(a of(e.sort(),this.pool.writeVarint(e.length),e))this.writeValue(a),this.writeValue(t[a])}}writeTypedArray(t,e){var r=t.buffer,a=t.byteOffset,i=t.length;if(this.options.shareArrayBuffers){if(void 0!==(s=this.buffers.get(r)))return this.pool.writeU8(1),this.pool.writeVarint(s),this.pool.writeVarint(a),void this.pool.writeVarint(i);this.buffers.set(r,this.buffers.size)}this.pool.writeU8(0),this.pool.writeVarint(a),this.pool.writeVarint(i);var s,n=i*(s=Wt[e]||1);if(e===mt||e===ft)for(let e=0;e<i;e++)this.pool.writeBigInt64(t[e]);else e=new Uint8Array(r,a,n),this.pool.writeBulkAligned(e,s)}writeArrayBuffer(t,e){t=new Uint8Array(t),this.pool.writeVarint(t.length),this.pool.writeBulkAligned(t,1)}writeCollection(t,e){switch(e){case bt:for(var[r,a]of(this.pool.writeVarint(t.size),t))this.writeValue(r),this.writeValue(a);break;case _t:for(var i of(this.pool.writeVarint(t.size),t))this.writeValue(i)}}writeDate(t,e){e===At&&this.pool.writeF64(t.getTime())}writeError(t,e){if(this.writeValue(t.message||""),this.writeValue(t.stack||""),e===Vt&&t.errors)for(var r of(this.pool.writeVarint(t.errors.length),t.errors))this.writeValue(r)}writeRegExp(t){this.writeValue(t.source),this.writeValue(t.flags)}writeBinary(t,e){this.pool.writeVarint(0),this.pool.writeVarint(0)}writeSpecial(t,e){switch(e){case Ot:var r=t.description;this.writeValue(void 0!==r?String(r):"");break;case $t:r=Symbol.keyFor(t),this.writeValue(void 0!==r?String(r):"")}}deserialize(t){if(this.buffer=new Uint8Array(t),this.view=new DataView(this.buffer.buffer,this.buffer.byteOffset),this.pos=0,this.deserializeRefs=[],this.deserializeStrings=[],this.deserializeBuffers=[],1413632565!==this.readU32())throw new Error("Invalid TurboSerial data: wrong magic number");if(5!==(t=this.readU8()))throw new Error("Unsupported TurboSerial version: "+t);return this.readValue()}readValue(){if(this.pos>=this.buffer.length)throw new Error("Unexpected end of buffer");var t=this.readU8();if(null==t)throw new Error("Invalid type byte read from buffer");if(t===Tt||t===Ft){var e=this.readVarint();if(e>=this.deserializeRefs.length)throw new Error("Invalid reference ID: "+e);return this.deserializeRefs[e]}if(t===L){if((e=this.readVarint())>=this.deserializeStrings.length)throw new Error("Invalid string reference: "+e);return this.deserializeStrings[e]}if(t===wt){if((e=this.readVarint())>=this.deserializeBuffers.length)throw new Error("Invalid buffer reference: "+e);return this.deserializeBuffers[e]}let r,y=!1;switch(e=t&a){case c:case h:case u:y=!0}if(y){switch(e){case h:r=[];break;case u:t===bt?r=new Map:t===_t&&(r=new Set);break;case c:r={}}switch(r&&this.deserializeRefs.push(r),e){case h:this.fillArray(r,t);break;case c:this.fillObject(r,t);break;case u:this.fillCollection(r,t)}}else{try{switch(e){case i:r=this.readPrimitive(t);break;case s:r=this.readNumber(t);break;case n:r=this.readBigInt(t);break;case o:r=this.readString(t);break;case l:r=this.readTypedArray(t);break;case d:r=this.readArrayBuffer(t);break;case m:r=this.readDate(t);break;case f:r=this.readError(t);break;case p:r=this.readRegExp();break;case g:r=this.readBinary(t);break;case w:r=this.readSpecial(t);break;default:throw new Error("Unknown type: 0x"+t.toString(16))}}catch(e){throw new Error(`Failed to deserialize type 0x${t.toString(16)}: `+e.message)}"object"!=typeof r||null===r||y||this.deserializeRefs.push(r)}return r}fillArray(t,e){switch(e){case q:break;case H:var r=this.readVarint();for(let e=0;e<r;e++)t[e]=this.readValue();break;case G:var a=this.readVarint(),i=this.readVarint();t.length=a;for(let e=0;e<i;e++){var s=this.readVarint(),n=this.readValue();t[s]=n}break;case W:case Y:case X:case J:case Q:a=this.readPackedArrayData(e),t.push(...a);break;case Z:a=this.readU8(),a=this.readPackedArrayData(a),t.push(...a)}}fillObject(t,e){if(e!==tt){var r=this.readVarint();for(let e=0;e<r;e++){var a=this.readValue(),i=this.readValue();t[a]=i}}}fillCollection(t,e){var r=this.readVarint();switch(e){case bt:for(let e=0;e<r;e++){var a=this.readValue(),i=this.readValue();t.set(a,i)}break;case _t:for(let e=0;e<r;e++)t.add(this.readValue())}}readPrimitive(t){switch(t){case y:return null;case b:return;case _:return!1;case v:return!0;default:throw new Error("Unknown primitive type: 0x"+(t?t.toString(16):"undefined"))}}readNumber(t){switch(t){case S:return this.view.getInt8(this.pos++);case A:return this.readI16();case k:return this.readI32();case B:return this.readU32();case D:return this.readF32();case z:return this.readF64();case I:return NaN;case E:return 1/0;case U:return-1/0;case M:return-0;case V:var e=this.readVarint();return this.readU8()?-e:e;default:throw new Error("Unknown number type: 0x"+t.toString(16))}}readBigInt(t){switch(t){case K:case P:return this.readBigInt64();case C:case x:return this.readLargeBigInt(t===x);default:throw new Error("Unknown BigInt type: 0x"+t.toString(16))}}readLargeBigInt(t){var e=this.readVarint(),r=(this.ensureBytes(e),this.buffer.subarray(this.pos,this.pos+e));this.pos+=e;let a="";for(let t=r.length-1;0<=t;t--)a+=r[t].toString(16).padStart(2,"0");return e=BigInt("0x"+a),t?-e:e}readString(t){if(t===T)return"";let e,r;switch(t){case F:case O:case j:case N:e=this.readU8();break;default:e=this.readVarint()}if(this.ensureBytes(e),t===F||t===O||t===$){r="";for(let t=0;t<e;t++)r+=String.fromCharCode(this.readU8())}else t=this.buffer.subarray(this.pos,this.pos+e),this.pos+=e,r=this.decoder.decode(t);return this.deserializeStrings.push(r),r}readArray(t){var e=[];return this.fillArray(e,t),e}readPackedArrayData(t){var e=this.readVarint(),r=new Array(e),a=Wt[t];if(!a)throw new Error("Unknown element size for packed array type: 0x"+t.toString(16));switch(this.alignPos(Math.min(a,8)),this.ensureBytes(e*a),t){case W:for(let t=0;t<e;t++)r[t]=this.view.getInt8(this.pos++);break;case Y:for(let t=0;t<e;t++)r[t]=this.view.getInt16(this.pos,!0),this.pos+=2;break;case X:for(let t=0;t<e;t++)r[t]=this.view.getInt32(this.pos,!0),this.pos+=4;break;case J:for(let t=0;t<e;t++)r[t]=this.view.getFloat32(this.pos,!0),this.pos+=4;break;case Q:for(let t=0;t<e;t++)r[t]=this.view.getFloat64(this.pos,!0),this.pos+=8;break;default:throw new Error("Unknown packed array type: 0x"+t.toString(16))}return r}readObject(t){var e={};return this.fillObject(e,t),e}readTypedArray(t){if(this.readU8()){var e=this.readVarint(),r=this.readVarint(),a=this.readVarint();if(e>=this.deserializeBuffers.length)throw new Error("Invalid buffer reference: "+e);return e=this.deserializeBuffers[e],this.createTypedArray(t,e,r,a)}this.readVarint();var i=this.readVarint();e=Wt[t]||1;if(t!==mt&&t!==ft)return r=i*e,this.alignPos(e),this.ensureBytes(r),a=this.buffer.subarray(this.pos,this.pos+r),this.pos+=r,e=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength),this.deserializeBuffers.push(e),this.createTypedArray(t,e,0,i);this.alignPos(8);var s=[];for(let t=0;t<i;t++)s.push(this.readBigInt64());return new Ht[t](s)}createTypedArray(t,e,r,a){var i=Ht[t];if(!i)throw new Error("Unknown typed array type: 0x"+t.toString(16));try{return new i(e,r,a)}catch(t){throw new Error("Failed to create typed array: "+t.message)}}readArrayBuffer(t){var e=this.readVarint(),r=(this.ensureBytes(e),this.buffer.subarray(this.pos,this.pos+e));this.pos+=e,e=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);return this.deserializeBuffers.push(e),e}readCollection(t){var e=new(t===bt?Map:Set);return this.fillCollection(e,t),e}readDate(t){switch(t){case At:var e=this.readF64();return new Date(e);case kt:return new Date(NaN);default:throw new Error("Unknown date type: 0x"+t.toString(16))}}readError(t){var e=this.readValue(),r=this.readValue();let a;switch(t){case Bt:a=new Error(e);break;case Dt:a=new EvalError(e);break;case zt:a=new RangeError(e);break;case It:a=new ReferenceError(e);break;case Et:a=new SyntaxError(e);break;case Ut:a=new TypeError(e);break;case Mt:a=new URIError(e);break;case Vt:var i=this.readVarint(),s=[];for(let t=0;t<i;t++)s.push(this.readValue());a=new AggregateError(s,e);break;default:a=new Error(e)}return r&&(a.stack=r),a}readRegExp(){var t=this.readValue(),e=this.readValue();return new RegExp(t,e)}readBinary(t){return{_type:"Binary",size:this.readVarint(),typeStr:this.readVarint()}}readSpecial(t){switch(t){case Ot:var e=this.readValue();return Symbol(e);case $t:return e=this.readValue(),Symbol.for(e);default:throw new Error("Unknown special type: 0x"+t.toString(16))}}readU8(){return this.ensureBytes(1),this.buffer[this.pos++]}readI16(){this.alignPos(2),this.ensureBytes(2);var t=this.view.getInt16(this.pos,!0);return this.pos+=2,t}readU16(){this.alignPos(2),this.ensureBytes(2);var t=this.view.getUint16(this.pos,!0);return this.pos+=2,t}readI32(){this.alignPos(4),this.ensureBytes(4);var t=this.view.getInt32(this.pos,!0);return this.pos+=4,t}readU32(){this.alignPos(4),this.ensureBytes(4);var t=this.view.getUint32(this.pos,!0);return this.pos+=4,t}readF32(){this.alignPos(4),this.ensureBytes(4);var t=this.view.getFloat32(this.pos,!0);return this.pos+=4,t}readF64(){this.alignPos(8),this.ensureBytes(8);var t=this.view.getFloat64(this.pos,!0);return this.pos+=8,t}readBigInt64(){this.alignPos(8),this.ensureBytes(8);var t=this.view.getBigInt64(this.pos,!0);return this.pos+=8,t}readVarint(){let t=0,e=0;for(var r;this.ensureBytes(1),t|=(127&(r=this.buffer[this.pos++]))<<e,e+=7,128&r;);return t>>>0}alignPos(t){t=t-1|0,this.pos=(this.pos+t&~t)>>>0}ensureBytes(t){if(this.pos+t>this.buffer.length)throw new Error(`Not enough bytes in buffer: need ${t}, available `+(this.buffer.length-this.pos))}},r.d(e,"Database",(function(){return Ae})),r.d(e,"Document",(function(){return ke})),r.d(e,"Collection",(function(){return De}));let oe=new Nt({compression:!1,deduplication:!0,shareArrayBuffers:!0,simdOptimization:!0,detectCircular:!0,memoryPoolSize:65536});class he{static async saveAttachments(t,e,r,a){var i,s=[];let n=await navigator.storage.getDirectory();for(i of[t,e,r])n=await n.getDirectoryHandle(i,{create:!0});for(let i=0;i<a.length;i++){var o=i.toString(),h=await(await n.getFileHandle(o,{create:!0})).createWritable();h=(await h.write(a[i].data),await h.close(),t+`/${e}/${r}/`+o);s.push(h)}return s}static async getAttachments(t){var e,r=[],a=await navigator.storage.getDirectory();for(e of t)try{var i=e.split("/");let t=a;for(let e=0;e<i.length-1;e++)t=await t.getDirectoryHandle(i[e]);var s=await(await t.getFileHandle(i[i.length-1])).getFile();r.push({path:e,data:s})}catch(t){console.error(`Error retrieving attachment at "${e}": `+t.message)}return r}static async deleteAttachments(t,e,r){var a=[t,e,r];let i=await navigator.storage.getDirectory();for(let t=0;t<a.length-1;t++)i=await i.getDirectoryHandle(a[t]);try{await i.removeEntry(a[a.length-1],{recursive:!0})}catch(t){console.error(`Error deleting attachments for document "${r}": `+t.message)}}toString(){return"[OPFSUtility]"}}class ce{static async compress(t){t="string"==typeof t?(new TextEncoder).encode(t):t;var e=new CompressionStream("deflate"),r=e.writable.getWriter();return r.write(t),r.close(),this._streamToUint8Array(e.readable)}static async decompress(t){var e=new DecompressionStream("deflate"),r=e.writable.getWriter();return r.write(t),r.close(),this._streamToUint8Array(e.readable)}static async _streamToUint8Array(t){var e=t.getReader(),r=[];let a=0;for(;;){var{value:i,done:s}=await e.read();if(s)break;r.push(i),a+=i.length}var n,o=new Uint8Array(a);let h=0;for(n of r)o.set(n,h),h+=n.length;return o}toString(){return"[BrowserCompressionUtility]"}}class le{static async encrypt(t,e){var r=crypto.getRandomValues(new Uint8Array(16)),a=(e=await this._deriveKey(e,r),crypto.getRandomValues(new Uint8Array(12))),i=await this._generateChecksum(t);t=this._combineDataAndChecksum(t,i),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:a},e,t);return this._wrapIntoUint8Array(r,a,new Uint8Array(i))}static async decrypt(t,e){var{salt:t,iv:r,encryptedData:a}=this._unwrapUint8Array(t),r=(e=await this._deriveKey(e,t),t=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},e,a),new Uint8Array(t)),{data:e,checksum:a}=this._separateDataAndChecksum(r);t=await this._generateChecksum(e);if(this._verifyChecksum(t,a))return e;throw new Error("Data integrity check failed. The data has been tampered with.")}static async _deriveKey(t,e){var r=new TextEncoder;r=await crypto.subtle.importKey("raw",r.encode(t),{name:"PBKDF2"},!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"PBKDF2",salt:e,iterations:6e5,hash:"SHA-512"},r,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}static async _generateChecksum(t){return new Uint8Array(await crypto.subtle.digest("SHA-256",t))}static _verifyChecksum(t,e){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(t[r]!==e[r])return!1;return!0}static _combineDataAndChecksum(t,e){var r=new Uint8Array(t.length+e.length);return r.set(t),r.set(e,t.length),r}static _separateDataAndChecksum(t){var e=t.length-32;return{data:t.slice(0,e),checksum:t.slice(e)}}static _wrapIntoUint8Array(t,e,r){var a=new Uint8Array(t.length+e.length+r.length);return a.set(t,0),a.set(e,t.length),a.set(r,t.length+e.length),a}static _unwrapUint8Array(t){return{salt:t.slice(0,16),iv:t.slice(16,28),encryptedData:t.slice(28)}}toString(){return"[BrowserEncryptionUtility]"}}class de{static openDatabase(t,e=null,r=null){return new Promise((a,i)=>{let s;(s=e?indexedDB.open(t,e):indexedDB.open(t)).onupgradeneeded=e=>{var a=e.target.result,i=e.oldVersion;e=e.newVersion;console.log(`Upgrading database "${t}" from version ${i} to `+e),r&&r(a,i,e)},s.onsuccess=e=>{(e=e.target.result).onclose=()=>{console.log(`Database "${t}" connection is closing.`)},a(e)},s.onerror=e=>{i(new Error(`Failed to open database "${t}": `+e.target.error.message))}})}static async performTransaction(t,e,r,a,i=3,s=null){let n=null;for(let h=0;h<=i;h++)try{if(!t||"done"!==t.readyState)throw new Error("Database connection is not available or ready.");let i=t.transaction(Array.isArray(e)?e:[e],r);var o=Array.isArray(e)?e.map(t=>i.objectStore(t)):[i.objectStore(e)];let h=setTimeout(()=>{i.abort()},3e4),c=await a(...o,s);return new Promise((t,e)=>{i.oncomplete=()=>{clearTimeout(h),t(c)},i.onerror=()=>{clearTimeout(h),n=new Error("Transaction failed: "+(i.error?i.error.message:"unknown error")),e(n)},i.onabort=()=>{clearTimeout(h),n=new Error("Transaction aborted: "+(i.error?i.error.message:"timeout or abort")),e(n)}})}catch(t){if(n=t,h<i){console.warn(`Transaction failed, retrying... (${i-h} attempts left): `+t.message);let e=100*Math.pow(2,h)+100*Math.random();await new Promise(t=>setTimeout(t,e))}}throw new Error(`Transaction ultimately failed after ${i+1} attempts: `+n.message)}static add(t,e){return new Promise((r,a)=>{var i=t.add(e);i.onsuccess=()=>r(),i.onerror=t=>a("Failed to insert record: "+t.target.error.message)})}static put(t,e){return new Promise((r,a)=>{var i=t.put(e);i.onsuccess=()=>r(),i.onerror=t=>a("Failed to put record: "+t.target.error.message)})}static delete(t,e){return new Promise((r,a)=>{var i=t.delete(e);i.onsuccess=()=>r(),i.onerror=t=>a("Failed to delete record: "+t.target.error.message)})}static get(t,e){return new Promise((r,a)=>{var i=t.get(e);i.onsuccess=t=>r(t.target.result),i.onerror=t=>a(`Failed to retrieve record with key ${e}: `+t.target.error.message)})}static getAll(t){return new Promise((e,r)=>{var a=t.getAll();a.onsuccess=t=>e(t.target.result),a.onerror=t=>r("Failed to retrieve records: "+t.target.error.message)})}static count(t){return new Promise((e,r)=>{var a=t.count();a.onsuccess=t=>e(t.target.result),a.onerror=t=>r("Failed to count records: "+t.target.error.message)})}static clear(t){return new Promise((e,r)=>{var a=t.clear();a.onsuccess=()=>e(),a.onerror=t=>r("Failed to clear store: "+t.target.error.message)})}static deleteDatabase(t){return new Promise((e,r)=>{var a=indexedDB.deleteDatabase(t);a.onsuccess=()=>e(),a.onerror=t=>r("Failed to delete database: "+t.target.error.message)})}static iterateCursor(t,e){return new Promise((r,a)=>{var i=t.openCursor();i.onsuccess=t=>{(t=t.target.result)?(e(t.value,t.key),t.continue()):r()},i.onerror=t=>a("Cursor iteration failed: "+t.target.error.message)})}static iterateCursorSafe(t,e,r={}){return new Promise((a,i)=>{var{index:s=null,direction:n="next",range:o=null}=r;let h=t,c=(h=s&&t.indexNames.contains(s)?t.index(s):h).openCursor(o,n),l=[];c.onsuccess=t=>{(t=t.target.result)&&!1!==e(t.value,t.key,l)?t.continue():a(l)},c.onerror=()=>i(c.error)})}toString(){return"[IndexedDBUtility]"}}class ue{static getItem(t){return(t=localStorage.getItem(t))?oe.serialize(t):null}static setItem(t,e){localStorage.setItem(t,oe.serialize(e))}static removeItem(t){localStorage.removeItem(t)}static clear(){localStorage.clear()}toString(){return"[LocalStorageUtility]"}}class me{constructor(){this.queue=[],this.locked=!1}async acquire(){return new Promise(t=>{this.locked?this.queue.push(t):(this.locked=!0,t())})}release(){0<this.queue.length?this.queue.shift()():this.locked=!1}async runExclusive(t){await this.acquire();try{return await t()}finally{this.release()}}toString(){return`[AsyncMutex locked:${this.locked} queue:${this.queue.length}]`}}class fe{constructor(t){this._dbName=t,this._metadataKey=`lacertadb_${this._dbName}_metadata`,this._collections=new Map,this._metadata=this._loadMetadata(),this._mutex=new me}async saveMetadata(){return this._mutex.runExclusive(()=>{ue.setItem(this.metadataKey,this.getRawMetadata())})}async adjustTotals(t,e){return this._mutex.runExclusive(()=>{this.data.totalSizeKB+=t,this.data.totalLength+=e,this.data.modifiedAt=Date.now()})}_loadMetadata(){var t=ue.getItem(this.metadataKey);if(t){for(var e in t.collections){var r=t.collections[e];r=new ye(e,this,r);this.collections.set(e,r)}return t}return{name:this._dbName,collections:{},totalSizeKB:0,totalLength:0,modifiedAt:Date.now()}}get data(){return this._metadata}set data(t){this._metadata=t}get name(){return this.data.name}get metadataKey(){return this._metadataKey}get collections(){return this._collections}set collections(t){this._collections=t}get totalSizeKB(){return this.data.totalSizeKB}get totalLength(){return this.data.totalLength}get modifiedAt(){return this.data.modifiedAt}getCollectionMetadata(t){var e;return this.collections.has(t)||(e=new ye(t,this),this.collections.set(t,e),this.data.collections[t]=e.getRawMetadata(),this.data.modifiedAt=Date.now()),this.collections.get(t)}getCollectionMetadataData(t){return(t=this.getCollectionMetadata(t))?t.getRawMetadata():{}}removeCollectionMetadata(t){var e=this.collections.get(t);e&&(this.data.totalSizeKB-=e.sizeKB,this.data.totalLength-=e.length,this.collections.delete(t),delete this.data.collections[t],this.data.modifiedAt=Date.now())}getCollectionNames(){return Array.from(this.collections.keys())}getRawMetadata(){for(var[t,e]of this._collections.entries())this.data.collections[t]=e.getRawMetadata();return this.data}setRawMetadata(t){for(var e in this._metadata=t,this._collections.clear(),t.collections){var r=t.collections[e];r=new ye(e,this,r);this._collections.set(e,r)}}get dbName(){return this._dbName}get key(){return this._metadataKey}toString(){return`[DatabaseMetadata: ${this.name} | Collections: ${this.collections.size} | Size: ${this.totalSizeKB.toFixed(2)}KB | Documents: ${this.totalLength}]`}}class pe extends Error{constructor(t,e,r=null){super(t),this.name="LacertaDBError",this.code=e,this.originalError=r,this.timestamp=Date.now()}toString(){return`[LacertaDBError ${this.code}: ${this.message} at ${new Date(this.timestamp).toISOString()}]`}}let ge="COLLECTION_NOT_FOUND",we="COLLECTION_EXISTS";class ye{constructor(t,e,r=null){this._collectionName=t,this._databaseMetadata=e,r?this._metadata=r:(this._metadata={name:t,sizeKB:0,length:0,createdAt:Date.now(),modifiedAt:Date.now(),documentSizes:{},documentModifiedAt:{},documentPermanent:{},documentAttachments:{}},this._databaseMetadata.data.collections[t]=this._metadata,this._databaseMetadata.data.modifiedAt=Date.now())}get name(){return this._collectionName}get keys(){return Object.keys(this.documentSizes)}get collectionName(){return this.name}get sizeKB(){return this._metadata.sizeKB}get length(){return this._metadata.length}get modifiedAt(){return this._metadata.modifiedAt}get metadata(){return this._metadata}set metadata(t){return this._metadata=t}get data(){return this.metadata}set data(t){this.metadata=t}get databaseMetadata(){return this._databaseMetadata}set databaseMetadata(t){this._databaseMetadata=t}get documentSizes(){return this.metadata.documentSizes}get documentModifiedAt(){return this.metadata.documentModifiedAt}get documentPermanent(){return this.metadata.documentPermanent}get documentAttachments(){return this.metadata.documentAttachments}set documentSizes(t){this.metadata.documentSizes=t}set documentModifiedAt(t){this.metadata.documentModifiedAt=t}set documentPermanent(t){this.metadata.documentPermanent=t}set documentAttachments(t){this.metadata.documentAttachments=t}updateDocument(t,e,r=!1,a=0){var i=!this.keys.includes(t),s=e-(this.documentSizes[t]||0);i=i?1:0;this.documentSizes[t]=e,this.documentModifiedAt[t]=Date.now(),this.documentPermanent[t]=r?1:0,this.documentAttachments[t]=a,this.metadata.sizeKB+=s,this.metadata.length+=i,this.metadata.modifiedAt=Date.now(),this.databaseMetadata.adjustTotals(s,i)}deleteDocument(t){var e;return t in this.documentSizes&&(e=this.documentSizes[t],delete this.documentSizes[t],delete this.documentModifiedAt[t],delete this.documentPermanent[t],delete this.documentAttachments[t],this.metadata.sizeKB-=e,--this.metadata.length,this.metadata.modifiedAt=Date.now(),this.databaseMetadata.adjustTotals(-e,-1),!0)}updateDocuments(t){for(var{docId:e,docSizeKB:r,isPermanent:a,attachmentCount:i}of t)this.updateDocument(e,r,a,i||0)}getRawMetadata(){return this.metadata}setRawMetadata(t){this.metadata=t}toString(){return`[CollectionMetadata: ${this.name} | Size: ${this.sizeKB.toFixed(2)}KB | Documents: ${this.length}]`}}class be{constructor(t,e=null,r=null){this.success=t,this.data=e,this.error=r}toString(){return`[LacertaDBResult success:${this.success} ${this.error?"error:"+this.error:""}]`}}class _e{constructor(t){this._dbName=t,this._metadataKey=`lacertadb_${this._dbName}_quickstore_metadata`,this._documentKeyPrefix=`lacertadb_${this._dbName}_quickstore_data_`,this._metadata=this._loadMetadata()}_loadMetadata(){return ue.getItem(this._metadataKey)||{totalSizeKB:0,totalLength:0,documentSizesKB:{},documentModificationTime:{},documentPermanent:{}}}_saveMetadata(){ue.setItem(this._metadataKey,this._metadata)}setDocumentSync(t,e=null){e=(t=new ke(t,e)).packSync();var r=t._id,a=t._permanent||!1,i=(e=oe.serialize({_id:t._id,_created:t._created,_modified:t._modified,_permanent:a,_encrypted:t._encrypted,_compressed:t._compressed,packedData:e}),this._documentKeyPrefix+r);localStorage.setItem(i,e),i=e.length/1024;return(e=!(r in this._metadata.documentSizesKB))?this._metadata.totalLength+=1:this._metadata.totalSizeKB-=this._metadata.documentSizesKB[r],this._metadata.documentSizesKB[r]=i,this._metadata.documentModificationTime[r]=t._modified,this._metadata.documentPermanent[r]=a,this._metadata.totalSizeKB+=i,this._saveMetadata(),e}deleteDocumentSync(t,e=!1){var r;return!(this._metadata.documentPermanent[t]&&!e||(e=this._documentKeyPrefix+t,r=this._metadata.documentSizesKB[t]||0,!localStorage.getItem(e))||(localStorage.removeItem(e),delete this._metadata.documentSizesKB[t],delete this._metadata.documentModificationTime[t],delete this._metadata.documentPermanent[t],this._metadata.totalSizeKB-=r,--this._metadata.totalLength,this._saveMetadata(),0))}getAllKeys(){return Object.keys(this._metadata.documentSizesKB)}getDocumentSync(t,e=null){t=this._documentKeyPrefix+t;return(t=localStorage.getItem(t))?(t=oe.serialize(t),new ke(t,e).unpackSync()):null}toString(){return`[QuickStore: ${this._dbName} | Size: ${this._metadata.totalSizeKB.toFixed(2)}KB | Documents: ${this._metadata.totalLength}]`}}class ve{constructor(){this.queue=[],this.processing=!1}async execute(t){return new Promise((e,r)=>{this.queue.push({operation:t,resolve:e,reject:r}),this.process()})}async process(){if(!this.processing&&0!==this.queue.length){for(this.processing=!0;0<this.queue.length;){var{operation:t,resolve:e,reject:r}=this.queue.shift();try{e(await t())}catch(t){r(t)}}this.processing=!1}}toString(){return`[TransactionManager processing:${this.processing} queue:${this.queue.length}]`}}class Se{constructor(){this._listeners={beforeAdd:[],afterAdd:[],beforeDelete:[],afterDelete:[],beforeGet:[],afterGet:[]}}on(t,e){if(!this._listeners[t])throw new Error(`Event "${t}" is not supported.`);this._listeners[t].push(e)}off(t,e){this._listeners[t]&&-1<(e=this._listeners[t].indexOf(e))&&this._listeners[t].splice(e,1)}_emit(t,...e){if(this._listeners[t])for(var r of this._listeners[t])r(...e)}_cleanup(){for(var t in this._listeners)this._listeners[t]=[]}toString(){return`[Observer listeners:{${Object.entries(this._listeners).map(([t,e])=>t+":"+e.length).join(" ")}}]`}}class Ae{constructor(t,e={}){this._dbName=t,this._db=null,this._collections=new Map,this._metadata=new fe(t),this._settings=new Be(t,e),this._quickStore=new _e(this._dbName),this._settings.init()}get quickStore(){return this._quickStore}async init(){var t;for(t of(this.db=await de.openDatabase(this.name,void 0,(t,e,r)=>{this._upgradeDatabase(t,e,r)}),this.data.getCollectionNames())){var e=new De(this,t,this.settings);await e.init(),this.collections.set(t,e)}}_createDataStores(t){for(var e of this.collections.keys())this._createDataStore(t,e)}_createDataStore(t,e){t.objectStoreNames.contains(e)||t.createObjectStore(e,{keyPath:"_id"})}_upgradeDatabase(t,e,r){console.log(`Upgrading database "${this.name}" from version ${e} to `+r),t.objectStoreNames.contains("_metadata")||t.createObjectStore("_metadata",{keyPath:"_id"})}async createCollection(t){var e;return this.collections.has(t)?(console.log(`Collection "${t}" already exists.`),new be(!1,this.collections.get(t),new pe(`Collection "${t}" already exists`,we))):(this.db.objectStoreNames.contains(t)||(e=this.db.version+1,this.db.close(),this.db=await de.openDatabase(this.name,e,(e,r,a)=>{this._createDataStore(e,t)})),await(e=new De(this,t,this.settings)).init(),this.collections.set(t,e),this.data.getCollectionMetadata(t),await this.data.saveMetadata(),new be(!0,e))}async deleteCollection(t){var e;return this.collections.has(t)?(await(e=this.collections.get(t)).close(),e.observer._cleanup(),await de.performTransaction(this.db,t,"readwrite",t=>de.clear(t)),this.collections.delete(t),this.data.removeCollectionMetadata(t),await this.data.saveMetadata(),new be(!0,null)):new be(!1,null,new pe(`Collection "${t}" does not exist`,ge))}async getCollection(t){var e;return this.collections.has(t)?new be(!0,this.collections.get(t)):this.db.objectStoreNames.contains(t)?(await(e=new De(this,t,this.settings)).init(),this.collections.set(t,e),new be(!0,e)):new be(!1,null,new pe(`Collection "${t}" does not exist`,ge))}async close(){var t;for(t of this.collectionsArray)await t.close();this.db&&(this.db.close(),this.db=null)}async deleteDatabase(){await this.close(),await de.deleteDatabase(this.name),ue.removeItem(this.data.metadataKey),this.settings.clear(),this.data=null}get name(){return this._dbName}get db(){return this._db}set db(t){this._db=t}get data(){return this.metadata}set data(t){this.metadata=t}get collectionsArray(){return Array.from(this.collections.values())}get collections(){return this._collections}get metadata(){return this._metadata}set metadata(t){this._metadata=t}get totalSizeKB(){return this.data.totalSizeKB}get totalLength(){return this.data.totalLength}get modifiedAt(){return this.data.modifiedAt}get settings(){return this._settings}get settingsData(){return this.settings.data}toString(){return`[Database: ${this.name} | Collections: ${this.collections.size} | Size: ${this.totalSizeKB.toFixed(2)}KB | Documents: ${this.totalLength}]`}}class ke{constructor(t,e=null){this._id=t._id||this._generateId(),this._created=t._created||Date.now(),this._permanent=!!t._permanent,this._encrypted=t._encrypted||!!e,this._compressed=t._compressed||!1,this._attachments=t._attachments||t.attachments||[],t.packedData?(this._packedData=t.packedData,this._modified=t._modified||Date.now(),this._data=null):(this._data=t.data||{},this._modified=Date.now(),this._packedData=new Uint8Array(0)),this._encryptionKey=e||""}get attachments(){return this._attachments}set attachments(t){this._attachments=t}get data(){return this._data}get packedData(){return this._packedData}get encryptionKey(){return this._encryptionKey}set data(t){this._data=t}set packedData(t){this._packedData=t}set encryptionKey(t){this._encryptionKey=t}static hasAttachments(t){return t._attachments&&0<t._attachments.length||t.attachments&&0<t.attachments.length}static async getAttachments(t,e,r){var a;return ke.hasAttachments(t)?(a=t._attachments||t.attachments,t.attachments=await he.getAttachments(a),Promise.resolve(t)):[]}static isEncrypted(t){return t._encrypted&&t.packedData}static async decryptDocument(t,e){if(ke.isEncrypted(t))return e=await le.decrypt(t.packedData,e),e=oe.deserialize(e),{_id:t._id,_created:t._created,_modified:t._modified,_encrypted:!0,_compressed:t._compressed,_permanent:!!t._permanent,attachments:t.attachments,data:e};throw new Error("Document is not encrypted.")}async pack(){if(!this.data)throw new Error("No data to pack");let t=oe.serialize(this.data);return this._compressed&&(t=await this._compressData(t)),this._encrypted&&(t=await this._encryptData(t)),this.packedData=t}packSync(){if(!this.data)throw new Error("No data to pack");if(this._encrypted)throw new Error("Packing synchronously a document being encrypted is impossible.");if(this._compressed)throw new Error("Packing synchronously a document being compressed is impossible.");var t=oe.serialize(this.data);return this.packedData=t}async unpack(){if(!this.data&&0<this.packedData.length){let t=this.packedData;this._encrypted&&(t=await this._decryptData(t)),this._compressed&&(t=await this._decompressData(t)),this.data=oe.deserialize(t)}return this.data}unpackSync(){if(!this.data&&0<this.packedData.length){if(this._encrypted)throw new Error("Unpacking synchronously a document being encrypted is impossible.");if(this._compressed)throw new Error("Unpacking synchronously a document being compressed is impossible.");this.data=oe.deserialize(this.packedData)}return this.data}async _encryptData(t){var e=this.encryptionKey;return le.encrypt(t,e)}async _decryptData(t){var e=this.encryptionKey;return le.decrypt(t,e)}async _compressData(t){return ce.compress(t)}async _decompressData(t){return ce.decompress(t)}_generateId(){return"xxxx-xxxx-xxxx".replace(/[x]/g,()=>(16*Math.random()|0).toString(16))}async objectOutput(t=!1){this.data||await this.unpack();var e={_id:this._id,_created:this._created,_modified:this._modified,_permanent:this._permanent,_encrypted:this._encrypted,_compressed:this._compressed,attachments:this.attachments,data:this.data};return t&&0<this.attachments.length&&(t=await he.getAttachments(this.attachments),e.attachments=t),e}async databaseOutput(){return this.packedData&&0!==this.packedData.length||await this.pack(),{_id:this._id,_created:this._created,_modified:this._modified,_permanent:!!this._permanent,_compressed:this._compressed,_encrypted:this._encrypted,attachments:this.attachments,packedData:this.packedData}}toString(){return`[Document: ${this._id} | Created: ${new Date(this._created).toISOString()} | Encrypted: ${this._encrypted} | Compressed: ${this._compressed} | Permanent: ${this._permanent}]`}}class Be{constructor(t,e={}){this._dbName=t,this._settingsKey=`lacertadb_${this._dbName}_settings`,this._data=this._loadSettings(),this._mergeSettings(e)}init(){if(this.set("sizeLimitKB",this.get("sizeLimitKB")||1/0),this.set("bufferLimitKB",this.get("bufferLimitKB")||-.2*this.get("sizeLimitKB")),this.get("bufferLimitKB")<-.8*this.get("sizeLimitKB"))throw new Error("Buffer limit cannot be below -80% of the size limit.");this.set("freeSpaceEvery",this._validateFreeSpaceSetting(this.get("freeSpaceEvery")))}_validateFreeSpaceSetting(t=1e4){if(void 0===t||!1===t||0===t)return 1/0;if(t<1e3&&0!==t)throw new Error("Invalid freeSpaceEvery value. It must be 0, Infinity, or above 1000.");return 1e3<=t&&t<1e4&&console.warn("Warning: freeSpaceEvery value is between 1000 and 10000, which may lead to frequent freeing."),t}_loadSettings(){return ue.getItem(this.settingsKey)||{}}_saveSettings(){ue.setItem(this.settingsKey,this.data)}_mergeSettings(t){this.data=Object.assign(this.data,t),this._saveSettings()}get(t){return this.data[t]}set(t,e){this.data[t]=e,this._saveSettings()}remove(t){delete this.data[t],this._saveSettings()}clear(){this.data={},this._saveSettings()}get dbName(){return this._dbName}get data(){return this._data}set data(t){this._data=t}get settingsKey(){return this._settingsKey}toString(){return`[Settings: ${this.dbName} | SizeLimit: ${this.get("sizeLimitKB")}KB | BufferLimit: ${this.get("bufferLimitKB")}KB]`}}class De{constructor(t,e,r){this._database=t,this._collectionName=e,this._settings=r,this._metadata=null,this._lastFreeSpaceTime=0,this._observer=new Se,this._transactionManager=new ve,this._freeSpaceInterval=null,this._freeSpaceHandler=null}get observer(){return this._observer}async createIndex(t,e={}){let r=e.name||t.replace(/\./g,"_");var a=this.database.db.version+1;this.database.db.close(),this.database.db=await de.openDatabase(this.database.name,a,a=>{a.objectStoreNames.contains(this.name)&&!(a=a.transaction([this.name]).objectStore(this.name)).indexNames.contains(r)&&a.createIndex(r,t,{unique:e.unique||!1,multiEntry:e.multiEntry||!1})})}async init(){this.metadata=this.database.metadata.getCollectionMetadata(this.name),this.settingsData.freeSpaceEvery!==1/0&&(this._freeSpaceHandler=()=>this._maybeFreeSpace(),this._freeSpaceInterval=setInterval(this._freeSpaceHandler,this.settingsData.freeSpaceEvery))}get name(){return this._collectionName}get sizes(){return this.metadataData.documentSizes||{}}get modifications(){return this.metadataData.documentModifiedAt||{}}get attachments(){return this.metadataData.documentAttachments||{}}get permanents(){return this.metadataData.documentPermanent||{}}get keys(){return Object.keys(this.sizes)}get documentsMetadata(){var t,e=this.keys,r=this.sizes,a=this.modifications,i=this.permanents,s=this.attachments,n=new Array(e.length),o=0;for(t of e)n[o++]={id:t,size:r[t],modified:a[t],permanent:i[t],attachment:s[t]};return n}get settings(){return this._settings}get settingsData(){return this.settings.data}set settings(t){this._settings=t}get lastFreeSpaceTime(){return this._lastFreeSpaceTime}set lastFreeSpaceTime(t){this._lastFreeSpaceTime=t}get database(){return this._database}get metadata(){return this.database.metadata.getCollectionMetadata(this.name)}get metadataData(){return this.metadata.getRawMetadata()}set metadata(t){this._metadata=t}get sizeKB(){return this.metadataData.sizeKB}get length(){return this.metadataData.length}get totalSizeKB(){return this.sizeKB}get totalLength(){return this.length}get modifiedAt(){return this.metadataData.modifiedAt}get isFreeSpaceEnabled(){return this.settingsData.freeSpaceEvery!==1/0}get shouldRunFreeSpaceSize(){return this.totalSizeKB>this.settingsData.sizeLimitKB+this.settingsData.bufferLimitKB}get shouldRunFreeSpaceTime(){return this.isFreeSpaceEnabled&&Date.now()-this.lastFreeSpaceTime>=this.settingsData.freeSpaceEvery}async _maybeFreeSpace(){if(this.shouldRunFreeSpaceSize||this.shouldRunFreeSpaceTime)return this.freeSpace(this.settingsData.sizeLimitKB)}async addDocument(t,e=null){return this._transactionManager.execute(async()=>{this.observer._emit("beforeAdd",t);var r=new ke(t,e),a=[];if(ke.hasAttachments(t)){var i=t._attachments||t.attachments;for(let t=0;t<i.length;t++)a.push(`${this.database.name}/${this.name}/${r._id}/`+t);r._attachments=a}let s=await r.databaseOutput();var n,o=s._id,h=s._permanent||!1,c=s.packedData.byteLength/1024;let l=!(o in this.metadataData.documentSizes);try{await de.performTransaction(this.database.db,this.name,"readwrite",t=>l?de.add(t,s):de.put(t,s)),0<a.length&&(n=t._attachments||t.attachments,await he.saveAttachments(this.database.name,this.name,r._id,n)),this.metadata.updateDocument(o,c,h,a.length),await this.database.metadata.saveMetadata()}catch(n){if(0<a.length)try{await he.deleteAttachments(this.database.name,this.name,r._id)}catch(n){}throw n}return await this._maybeFreeSpace(),this.observer._emit("afterAdd",t),l})}async getDocument(t,e=null,r=!1){if(this.observer._emit("beforeGet",t),t in this.metadataData.documentSizes){var a=await de.performTransaction(this.database.db,this.name,"readonly",e=>de.get(e,t));if(a){let t;if(ke.isEncrypted(a)){if(!e)return!1;t=new ke(a,e)}else t=new ke(a);return e=await t.objectOutput(r),this.observer._emit("afterGet",e),e}}return!1}async getDocuments(t,e=null,r=!1){let a=[],i=t.filter(t=>t in this.metadataData.documentSizes);return 0!==i.length&&await de.performTransaction(this.database.db,this.name,"readonly",async t=>{var s,n=i.map(e=>de.get(t,e));for(s of await Promise.all(n))if(s){let t;if(ke.isEncrypted(s)){if(!e)continue;t=new ke(s,e)}else t=new ke(s);var o=await t.objectOutput(r);a.push(o)}}),a}async deleteDocument(t,e=!1){return this.observer._emit("beforeDelete",t),!(this.permanents[t]&&!e)&&t in this.sizes&&(0<(this.metadata.documentAttachments[t]||0)&&await he.deleteAttachments(this.database.name,this.name,t),await de.performTransaction(this.database.db,this.name,"readwrite",e=>de.delete(e,t)),this.metadata.deleteDocument(t),await this.database.metadata.saveMetadata(),this.observer._emit("afterDelete",t),!0)}async freeSpace(t){let e;this.lastFreeSpaceTime=Date.now();var r,a=this.sizeKB;if(0<=t){if(a<=t)return 0;e=a-t}else t=a-(e=-t);let i=0;for([r]of Object.entries(this.metadataData.documentModifiedAt).filter(([t])=>!this.metadataData.documentPermanent[t]).sort((t,e)=>t[1]-e[1]))if(this.sizeKB>t){if(i+=this.metadataData.documentSizes[r],await this.deleteDocument(r,!0),i>=e)break}return i}async query(t={},e={}){let{encryptionKey:r=null,limit:a=1/0,offset:i=0,orderBy:s=null,index:n=null}=e,o=[];await de.performTransaction(this.database.db,this.name,"readonly",async t=>{let e=t,r=(n&&t.indexNames.contains(n)&&(e=t.index(n)),s?e.openCursor(null,"asc"===s?"next":"prev"):e.openCursor());return new Promise((t,e)=>{let s=0,n=0;r.onsuccess=e=>{var r;!(e=e.target.result)||s>=a?t():(n<i?n++:(r=e.value,o.push(r),s++),e.continue())},r.onerror=()=>e(r.error)})});var h,c,l=[];for(h of o){let e;if(ke.isEncrypted(h)){if(!r)continue;e=new ke(h,r)}else e=new ke(h);if(0<Object.keys(t).length){var d,u=await e.objectOutput();let r=!0;for(d in t)if((d.includes(".")?(c=u.data,d.split(".").reduce((t,e)=>(t||{})[e],c)):u.data[d])!==t[d]){r=!1;break}if(!r)continue}l.push(await e.objectOutput())}return l}async close(){this._freeSpaceInterval&&(clearInterval(this._freeSpaceInterval),this._freeSpaceInterval=null,this._freeSpaceHandler=null)}toString(){return`[Collection: ${this.name} | Database: ${this.database.name} | Size: ${this.sizeKB.toFixed(2)}KB | Documents: ${this.length}]`}}}]);
|
package/index.js
CHANGED
|
@@ -1,13 +1,18 @@
|
|
|
1
1
|
/*
|
|
2
2
|
The MIT License (MIT)
|
|
3
3
|
Copyright (c) 2024 Matias Affolter
|
|
4
|
-
|
|
5
|
-
CRITICAL DEPENDENCY: This module requires JOYSON library for serialization.
|
|
6
|
-
Install via: npm install joyson or include via CDN
|
|
7
4
|
*/
|
|
8
5
|
"use strict";
|
|
9
|
-
import
|
|
10
|
-
|
|
6
|
+
import TurboSerial from "@pixagram/turboserial";
|
|
7
|
+
const TURBO = new TurboSerial({
|
|
8
|
+
compression: false, // Enable compression
|
|
9
|
+
deduplication: true, // Enable reference deduplication
|
|
10
|
+
shareArrayBuffers: true, // Share ArrayBuffer references
|
|
11
|
+
simdOptimization: true, // Enable SIMD optimizations
|
|
12
|
+
detectCircular: true, // Detect circular references
|
|
13
|
+
memoryPoolSize: 65536 // Initial memory pool size
|
|
14
|
+
});
|
|
15
|
+
|
|
11
16
|
// Utility function for nested object access
|
|
12
17
|
function getNestedValue(obj, path) {
|
|
13
18
|
return path.split('.').reduce((curr, prop) => (curr || {})[prop], obj);
|
|
@@ -287,34 +292,41 @@ class IndexedDBUtility {
|
|
|
287
292
|
});
|
|
288
293
|
}
|
|
289
294
|
|
|
290
|
-
//
|
|
295
|
+
// Improved transaction handling with better retry logic
|
|
291
296
|
static async performTransaction(db, storeNames, mode, callback, retries = 3, operationId = null) {
|
|
292
297
|
let lastError = null;
|
|
293
|
-
|
|
298
|
+
|
|
294
299
|
for (let attempt = 0; attempt <= retries; attempt++) {
|
|
295
300
|
try {
|
|
296
|
-
if (!db) {
|
|
297
|
-
throw new Error('Database connection is not available.');
|
|
301
|
+
if (!db || db.readyState !== 'done') {
|
|
302
|
+
throw new Error('Database connection is not available or ready.');
|
|
298
303
|
}
|
|
299
|
-
|
|
304
|
+
|
|
300
305
|
const tx = db.transaction(Array.isArray(storeNames) ? storeNames : [storeNames], mode);
|
|
301
|
-
const stores = Array.isArray(storeNames)
|
|
302
|
-
? storeNames.map(name => tx.objectStore(name))
|
|
306
|
+
const stores = Array.isArray(storeNames)
|
|
307
|
+
? storeNames.map(name => tx.objectStore(name))
|
|
303
308
|
: [tx.objectStore(storeNames)];
|
|
304
|
-
|
|
305
|
-
//
|
|
306
|
-
const
|
|
307
|
-
|
|
308
|
-
|
|
309
|
+
|
|
310
|
+
// Add transaction timeout
|
|
311
|
+
const timeoutId = setTimeout(() => {
|
|
312
|
+
tx.abort();
|
|
313
|
+
}, 30000); // 30 second timeout
|
|
314
|
+
|
|
315
|
+
const result = await callback(...stores, operationId);
|
|
309
316
|
|
|
310
317
|
return new Promise((resolve, reject) => {
|
|
311
|
-
tx.oncomplete = () =>
|
|
318
|
+
tx.oncomplete = () => {
|
|
319
|
+
clearTimeout(timeoutId);
|
|
320
|
+
resolve(result);
|
|
321
|
+
};
|
|
312
322
|
tx.onerror = () => {
|
|
323
|
+
clearTimeout(timeoutId);
|
|
313
324
|
lastError = new Error(`Transaction failed: ${tx.error ? tx.error.message : 'unknown error'}`);
|
|
314
325
|
reject(lastError);
|
|
315
326
|
};
|
|
316
327
|
tx.onabort = () => {
|
|
317
|
-
|
|
328
|
+
clearTimeout(timeoutId);
|
|
329
|
+
lastError = new Error(`Transaction aborted: ${tx.error ? tx.error.message : 'timeout or abort'}`);
|
|
318
330
|
reject(lastError);
|
|
319
331
|
};
|
|
320
332
|
});
|
|
@@ -322,12 +334,13 @@ class IndexedDBUtility {
|
|
|
322
334
|
lastError = error;
|
|
323
335
|
if (attempt < retries) {
|
|
324
336
|
console.warn(`Transaction failed, retrying... (${retries - attempt} attempts left): ${error.message}`);
|
|
325
|
-
// Exponential backoff
|
|
326
|
-
|
|
337
|
+
// Exponential backoff with jitter
|
|
338
|
+
const delay = Math.pow(2, attempt) * 100 + Math.random() * 100;
|
|
339
|
+
await new Promise(resolve => setTimeout(resolve, delay));
|
|
327
340
|
}
|
|
328
341
|
}
|
|
329
342
|
}
|
|
330
|
-
|
|
343
|
+
|
|
331
344
|
throw new Error(`Transaction ultimately failed after ${retries + 1} attempts: ${lastError.message}`);
|
|
332
345
|
}
|
|
333
346
|
|
|
@@ -456,11 +469,11 @@ class IndexedDBUtility {
|
|
|
456
469
|
class LocalStorageUtility {
|
|
457
470
|
static getItem(key) {
|
|
458
471
|
const value = localStorage.getItem(key);
|
|
459
|
-
return value ?
|
|
472
|
+
return value ? TURBO.serialize(value) : null;
|
|
460
473
|
}
|
|
461
474
|
|
|
462
475
|
static setItem(key, value) {
|
|
463
|
-
localStorage.setItem(key,
|
|
476
|
+
localStorage.setItem(key, TURBO.serialize(value));
|
|
464
477
|
}
|
|
465
478
|
|
|
466
479
|
static removeItem(key) {
|
|
@@ -867,7 +880,7 @@ class QuickStore {
|
|
|
867
880
|
const docId = document._id;
|
|
868
881
|
const isPermanent = document._permanent || false;
|
|
869
882
|
|
|
870
|
-
const dataToStore =
|
|
883
|
+
const dataToStore = TURBO.serialize({
|
|
871
884
|
_id: document._id,
|
|
872
885
|
_created: document._created,
|
|
873
886
|
_modified: document._modified,
|
|
@@ -937,7 +950,7 @@ class QuickStore {
|
|
|
937
950
|
const dataString = localStorage.getItem(key);
|
|
938
951
|
|
|
939
952
|
if (dataString) {
|
|
940
|
-
const docData =
|
|
953
|
+
const docData = TURBO.serialize(dataString);
|
|
941
954
|
const document = new Document(docData, encryptionKey);
|
|
942
955
|
return document.unpackSync();
|
|
943
956
|
} else {
|
|
@@ -1330,7 +1343,7 @@ export class Document {
|
|
|
1330
1343
|
throw new Error('Document is not encrypted.');
|
|
1331
1344
|
}
|
|
1332
1345
|
const decryptedData = await BrowserEncryptionUtility.decrypt(documentData.packedData, encryptionKey);
|
|
1333
|
-
const unpackedData =
|
|
1346
|
+
const unpackedData = TURBO.deserialize(decryptedData);
|
|
1334
1347
|
|
|
1335
1348
|
return {
|
|
1336
1349
|
_id: documentData._id,
|
|
@@ -1349,7 +1362,7 @@ export class Document {
|
|
|
1349
1362
|
throw new Error('No data to pack');
|
|
1350
1363
|
}
|
|
1351
1364
|
|
|
1352
|
-
let packedData =
|
|
1365
|
+
let packedData = TURBO.serialize(this.data);
|
|
1353
1366
|
if (this._compressed) {
|
|
1354
1367
|
packedData = await this._compressData(packedData);
|
|
1355
1368
|
}
|
|
@@ -1372,7 +1385,7 @@ export class Document {
|
|
|
1372
1385
|
throw new Error("Packing synchronously a document being compressed is impossible.")
|
|
1373
1386
|
}
|
|
1374
1387
|
|
|
1375
|
-
let packedData =
|
|
1388
|
+
let packedData = TURBO.serialize(this.data);
|
|
1376
1389
|
this.packedData = packedData;
|
|
1377
1390
|
return packedData;
|
|
1378
1391
|
}
|
|
@@ -1386,7 +1399,7 @@ export class Document {
|
|
|
1386
1399
|
if (this._compressed) {
|
|
1387
1400
|
unpackedData = await this._decompressData(unpackedData);
|
|
1388
1401
|
}
|
|
1389
|
-
this.data =
|
|
1402
|
+
this.data = TURBO.deserialize(unpackedData);
|
|
1390
1403
|
}
|
|
1391
1404
|
return this.data;
|
|
1392
1405
|
}
|
|
@@ -1399,7 +1412,7 @@ export class Document {
|
|
|
1399
1412
|
if (this._compressed) {
|
|
1400
1413
|
throw new Error("Unpacking synchronously a document being compressed is impossible.")
|
|
1401
1414
|
}
|
|
1402
|
-
this.data =
|
|
1415
|
+
this.data = TURBO.deserialize(this.packedData);
|
|
1403
1416
|
}
|
|
1404
1417
|
return this.data;
|
|
1405
1418
|
}
|
|
@@ -2075,3 +2088,4 @@ export class Collection {
|
|
|
2075
2088
|
return `[Collection: ${this.name} | Database: ${this.database.name} | Size: ${this.sizeKB.toFixed(2)}KB | Documents: ${this.length}]`;
|
|
2076
2089
|
}
|
|
2077
2090
|
}
|
|
2091
|
+
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pixagram/lacerta-db",
|
|
3
|
-
"version": "0.0
|
|
3
|
+
"version": "0.1.0",
|
|
4
4
|
"description": "Lacerta-DB is a Javascript IndexedDB Database for Web Browsers. Simple, Fast, Secure.",
|
|
5
5
|
"devDependencies": {
|
|
6
6
|
"@babel/core": "^7.23.6",
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
"webpack-cli": "~4.10.0"
|
|
13
13
|
},
|
|
14
14
|
"dependencies": {
|
|
15
|
-
"
|
|
15
|
+
"@pixagram/turboserial": "~0.0.1"
|
|
16
16
|
},
|
|
17
17
|
"build": {},
|
|
18
18
|
"author": "Affolter Matias",
|