@pixagram/lacerta-db 0.0.3 → 0.2.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/browser.js +24 -3
- package/dist/browser.min.js +8 -1
- package/dist/index.min.js +8 -1
- package/index.js +2087 -1711
- package/package.json +3 -2
- package/readme.md +132 -923
package/browser.js
CHANGED
|
@@ -1,10 +1,31 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {LacertaDB,
|
|
2
|
+
Database,
|
|
3
|
+
Collection,
|
|
4
|
+
Document,
|
|
5
|
+
QueryOperators,
|
|
6
|
+
AggregationPipeline,
|
|
7
|
+
MigrationManager,
|
|
8
|
+
PerformanceMonitor,
|
|
9
|
+
LacertaDBError} from "./index.js";
|
|
10
|
+
|
|
2
11
|
if(typeof window != "undefined"){
|
|
3
12
|
window.Database = Database;
|
|
4
|
-
window.Document = Document;
|
|
5
13
|
window.Collection = Collection;
|
|
14
|
+
window.Document = Document;
|
|
15
|
+
window.QueryOperators = QueryOperators;
|
|
16
|
+
window.AggregationPipeline = AggregationPipeline;
|
|
17
|
+
window.MigrationManager = MigrationManager;
|
|
18
|
+
window.PerformanceMonitor = PerformanceMonitor;
|
|
19
|
+
window.LacertaDBError = LacertaDBError;
|
|
20
|
+
window.lacertaDBInstance = lacertaDBInstance;
|
|
6
21
|
}else {
|
|
7
22
|
self.Database = Database;
|
|
8
|
-
self.Document = Document;
|
|
9
23
|
self.Collection = Collection;
|
|
24
|
+
self.Document = Document;
|
|
25
|
+
self.QueryOperators = QueryOperators;
|
|
26
|
+
self.AggregationPipeline = AggregationPipeline;
|
|
27
|
+
self.MigrationManager = MigrationManager;
|
|
28
|
+
self.PerformanceMonitor = PerformanceMonitor;
|
|
29
|
+
self.LacertaDBError = LacertaDBError;
|
|
30
|
+
self.lacertaDBInstance = lacertaDBInstance;
|
|
10
31
|
}
|
package/dist/browser.min.js
CHANGED
|
@@ -1 +1,8 @@
|
|
|
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
|
+
(e=>{var t={};function r(i){var a;return(t[i]||(a=t[i]={i:i,l:!1,exports:{}},e[i].call(a.exports,a,a.exports,r),a.l=!0,a)).exports}r.m=e,r.c=t,r.d=function(e,t,i){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:i})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var i=Object.create(null);if(r.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var a in e)r.d(i,a,function(t){return e[t]}.bind(null,a));return i},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=3)})([function(e,t,r){
|
|
2
|
+
/**
|
|
3
|
+
* LacertaDB V4 - Complete Core Library (Refactored)
|
|
4
|
+
* A powerful browser-based document database with encryption, compression, and OPFS support
|
|
5
|
+
* @version 4.0.0
|
|
6
|
+
* @license MIT
|
|
7
|
+
*/
|
|
8
|
+
{var i=("undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:this)||{},a=r(1),s=(r=r(2),new a({compression:!0,deduplication:!0,shareArrayBuffers:!0,simdOptimization:!0,detectCircular:!0})),n=new r;class t{constructor(){this._queue=[],this._locked=!1}acquire(){var e=this;return new Promise((function(t){e._queue.push(t),e._dispatch()}))}release(){this._locked=!1,this._dispatch()}async runExclusive(e){var t=await this.acquire();try{return await e()}finally{t()}}_dispatch(){var e,t;this._locked||0===this._queue.length||(this._locked=!0,e=this._queue.shift(),t=this,e((function(){t.release()})))}}class o extends Error{constructor(e,t,r){super(e),this.name="LacertaDBError",this.code=t,this.originalError=r||null,this.timestamp=(new Date).toISOString()}}class c{async compress(e){try{var t=new Response(e).body.pipeThrough(new CompressionStream("deflate")),r=await new Response(t).arrayBuffer();return new Uint8Array(r)}catch(e){throw new o("Compression failed","COMPRESSION_FAILED",e)}}async decompress(e){try{var t=new Response(e).body.pipeThrough(new DecompressionStream("deflate")),r=await new Response(t).arrayBuffer();return new Uint8Array(r)}catch(e){throw new o("Decompression failed","DECOMPRESSION_FAILED",e)}}compressSync(e){return(new TextEncoder).encode(n.encode(e))}decompressSync(e){return n.decode((new TextDecoder).decode(e))}}class h{async encrypt(e,t){try{var r=crypto.getRandomValues(new Uint8Array(16)),i=crypto.getRandomValues(new Uint8Array(12)),a=await crypto.subtle.importKey("raw",(new TextEncoder).encode(t),"PBKDF2",!1,["deriveKey"]),s=await crypto.subtle.deriveKey({name:"PBKDF2",salt:r,iterations:6e5,hash:"SHA-512"},a,{name:"AES-GCM",length:256},!1,["encrypt"]),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:i},s,e),c=await crypto.subtle.digest("SHA-256",e),h=new Uint8Array(c),l=new Uint8Array(r.length+i.length+h.length+n.byteLength);return l.set(r,0),l.set(i,r.length),l.set(h,r.length+i.length),l.set(new Uint8Array(n),r.length+i.length+h.length),l}catch(e){throw new o("Encryption failed","ENCRYPTION_FAILED",e)}}async decrypt(e,t){try{for(var r=e.slice(0,16),i=e.slice(16,28),a=e.slice(28,60),s=e.slice(60),n=await crypto.subtle.importKey("raw",(new TextEncoder).encode(t),"PBKDF2",!1,["deriveKey"]),c=await crypto.subtle.deriveKey({name:"PBKDF2",salt:r,iterations:6e5,hash:"SHA-512"},n,{name:"AES-GCM",length:256},!1,["decrypt"]),h=await crypto.subtle.decrypt({name:"AES-GCM",iv:i},c,s),l=await crypto.subtle.digest("SHA-256",h),u=new Uint8Array(l),d=!0,f=0;f<a.length;f++)if(a[f]!==u[f]){d=!1;break}if(d)return new Uint8Array(h);throw new Error("Checksum verification failed")}catch(e){throw new o("Decryption failed","DECRYPTION_FAILED",e)}}}class l{async saveAttachments(e,t,r,i){var a=[],s=await navigator.storage.getDirectory();try{for(var n=await(await(await s.getDirectoryHandle(e,{create:!0})).getDirectoryHandle(t,{create:!0})).getDirectoryHandle(r,{create:!0}),c=0;c<i.length;c++){var h=i[c],l=await(await n.getFileHandle(String(c),{create:!0})).createWritable(),u=new Blob([h.data],{type:h.type});await l.write(u),await l.close(),a.push({path:"/"+e+"/"+t+"/"+r+"/"+c,name:h.name,type:h.type,size:h.data.byteLength})}return a}catch(e){throw new o("Failed to save attachments","ATTACHMENT_SAVE_FAILED",e)}}async getAttachments(e){for(var t=[],r=await navigator.storage.getDirectory(),i=0;i<e.length;i++){var a=e[i];try{for(var s=a.path.split("/").filter((function(e){return e})),n=r,o=0;o<s.length-1;o++)n=await n.getDirectoryHandle(s[o]);var c=await(await(await n.getFileHandle(s[s.length-1])).getFile()).arrayBuffer();t.push({name:a.name,type:a.type,data:new Uint8Array(c),size:a.size})}catch(e){console.error("Failed to get attachment:",a.path,e)}}return t}async deleteAttachments(e,t,r){try{await(await(await(await navigator.storage.getDirectory()).getDirectoryHandle(e)).getDirectoryHandle(t)).removeEntry(r,{recursive:!0})}catch(e){console.error("Failed to delete attachments:",e)}}}class u{constructor(){this.transactionQueue=[],this.isProcessing=!1,this.mutex=new t}openDatabase(e,t,r){return t=t||1,new Promise((function(i,a){var s=indexedDB.open(e,t);s.onerror=function(){a(new o("Failed to open database","DATABASE_OPEN_FAILED",s.error))},s.onsuccess=function(){i(s.result)},s.onupgradeneeded=function(e){var t=e.target.result;r&&r(t,e.oldVersion,e.newVersion)}}))}async performTransaction(e,t,r,i,a,s){return a=a||3,this.mutex.runExclusive((async function(){for(var s,n=0;n<a;n++)try{return await new Promise((function(a,s){var n,o=e.transaction(t,r);o.oncomplete=function(){a(n)},o.onerror=function(){s(o.error)},o.onabort=function(){s(new Error("Transaction aborted"))};try{(n=i(o))instanceof Promise&&n.then((function(e){n=e})).catch(s)}catch(a){s(a)}}))}catch(e){s=e,n<a-1&&await new Promise((function(e){setTimeout(e,100*Math.pow(2,n))}))}throw new o("Transaction failed after retries","TRANSACTION_FAILED",s)}))}add(e,t,r,i){return i=void 0===i?void 0:i,this.performTransaction(e,[t],"readwrite",(function(e){return new Promise((function(a,s){var n=i?e.objectStore(t).add(r,i):e.objectStore(t).add(r);n.onsuccess=function(){a(n.result)},n.onerror=function(){s(n.error)}}))}))}put(e,t,r,i){return i=void 0===i?void 0:i,this.performTransaction(e,[t],"readwrite",(function(e){return new Promise((function(a,s){var n=i?e.objectStore(t).put(r,i):e.objectStore(t).put(r);n.onsuccess=function(){a(n.result)},n.onerror=function(){s(n.error)}}))}))}get(e,t,r){return this.performTransaction(e,[t],"readonly",(function(e){return new Promise((function(i,a){var s=e.objectStore(t).get(r);s.onsuccess=function(){i(s.result)},s.onerror=function(){a(s.error)}}))}))}getAll(e,t,r,i){return r=void 0===r?void 0:r,i=void 0===i?void 0:i,this.performTransaction(e,[t],"readonly",(function(e){return new Promise((function(a,s){var n=e.objectStore(t).getAll(r,i);n.onsuccess=function(){a(n.result)},n.onerror=function(){s(n.error)}}))}))}delete(e,t,r){return this.performTransaction(e,[t],"readwrite",(function(e){return new Promise((function(i,a){var s=e.objectStore(t).delete(r);s.onsuccess=function(){i()},s.onerror=function(){a(s.error)}}))}))}clear(e,t){return this.performTransaction(e,[t],"readwrite",(function(e){return new Promise((function(r,i){var a=e.objectStore(t).clear();a.onsuccess=function(){r()},a.onerror=function(){i(a.error)}}))}))}count(e,t,r){return r=void 0===r?void 0:r,this.performTransaction(e,[t],"readonly",(function(e){return new Promise((function(i,a){var s=e.objectStore(t).count(r);s.onsuccess=function(){i(s.result)},s.onerror=function(){a(s.error)}}))}))}iterateCursorSafe(e,t,r,i,a){return i=i||"next",a=void 0===a?void 0:a,this.performTransaction(e,[t],"readonly",(function(e){return new Promise((function(s,n){var o=[],c=e.objectStore(t).openCursor(a,i);c.onsuccess=function(e){if(e=e.target.result)try{var t=r(e.value,e.key);!1!==t?(o.push(t),e.continue()):s(o)}catch(e){n(e)}else s(o)},c.onerror=function(){n(c.error)}}))}))}}class d{constructor(e,t){t=t||{},this._id=(e=e||{})._id||this.generateId(),this._created=e._created||Date.now(),this._modified=e._modified||Date.now(),this._permanent=e._permanent||t.permanent||!1,this._encrypted=e._encrypted||t.encrypted||!1,this._compressed=e._compressed||t.compressed||!1,this._attachments=e._attachments||[],this.data=e.data||{},this.packedData=e.packedData||null,this.serializer=new a({compression:!0,deduplication:!0,shareArrayBuffers:!0,simdOptimization:!0,detectCircular:!0}),this.compression=new c,this.encryption=new h,this.password=t.password||null}generateId(){return"doc_"+Date.now()+"_"+Math.random().toString(36).substr(2,9)}async pack(){try{var e=this.serializer.serialize(this.data);return this._compressed&&(e=await this.compression.compress(e)),this._encrypted&&this.password&&(e=await this.encryption.encrypt(e,this.password)),this.packedData=e}catch(e){throw new o("Failed to pack document","PACK_FAILED",e)}}async unpack(){try{var e=this.packedData;return this._encrypted&&this.password&&(e=await this.encryption.decrypt(e,this.password)),this._compressed&&(e=await this.compression.decompress(e)),this.data=this.serializer.deserialize(e),this.data}catch(e){throw new o("Failed to unpack document","UNPACK_FAILED",e)}}packSync(){var e=this.serializer.serialize(this.data);if(this._compressed&&(e=this.compression.compressSync(e)),this._encrypted&&this.password)throw new o("Synchronous encryption not supported","SYNC_ENCRYPT_NOT_SUPPORTED");return this.packedData=e}unpackSync(){var e=this.packedData;if(this._encrypted&&this.password)throw new o("Synchronous decryption not supported","SYNC_DECRYPT_NOT_SUPPORTED");return this._compressed&&(e=this.compression.decompressSync(e)),this.data=this.serializer.deserialize(e),this.data}objectOutput(e){e=e||!1;var t,r={_id:this._id,_created:this._created,_modified:this._modified,_permanent:this._permanent};for(t in this.data)Object.prototype.hasOwnProperty.call(this.data,t)&&(r[t]=this.data[t]);return e&&0<this._attachments.length&&(r._attachments=this._attachments),r}databaseOutput(){return{_id:this._id,_created:this._created,_modified:this._modified,_permanent:this._permanent,_encrypted:this._encrypted,_compressed:this._compressed,_attachments:this._attachments,packedData:this.packedData}}}class f{constructor(e,t){t=t||{},this.name=e,this.sizeKB=t.sizeKB||0,this.length=t.length||0,this.createdAt=t.createdAt||Date.now(),this.modifiedAt=t.modifiedAt||Date.now(),this.documentSizes=t.documentSizes||{},this.documentModifiedAt=t.documentModifiedAt||{},this.documentPermanent=t.documentPermanent||{},this.documentAttachments=t.documentAttachments||{}}addDocument(e,t,r,i){this.documentSizes[e]=t,this.documentModifiedAt[e]=Date.now(),r&&(this.documentPermanent[e]=!0),0<i&&(this.documentAttachments[e]=i),this.sizeKB+=t,this.length++,this.modifiedAt=Date.now()}updateDocument(e,t,r,i){var a=this.documentSizes[e]||0;this.sizeKB=this.sizeKB-a+t,this.documentSizes[e]=t,this.documentModifiedAt[e]=Date.now(),r?this.documentPermanent[e]=!0:delete this.documentPermanent[e],0<i?this.documentAttachments[e]=i:delete this.documentAttachments[e],this.modifiedAt=Date.now()}removeDocument(e){var t=this.documentSizes[e]||0;delete this.documentSizes[e],delete this.documentModifiedAt[e],delete this.documentPermanent[e],delete this.documentAttachments[e],this.sizeKB-=t,this.length--,this.modifiedAt=Date.now()}getOldestNonPermanentDocuments(e){var t=this;return Object.entries(this.documentModifiedAt).filter((function(e){return e=e[0],!t.documentPermanent[e]})).sort((function(e,t){return e[1]-t[1]})).slice(0,e).map((function(e){return e[0]}))}}class p{constructor(e,t){t=t||{},this.name=e,this.collections=t.collections||{},this.totalSizeKB=t.totalSizeKB||0,this.totalLength=t.totalLength||0,this.modifiedAt=t.modifiedAt||Date.now()}static load(e){var t=localStorage.getItem("lacertadb_"+e+"_metadata");if(t)try{var r=n.decode(t),i=s.deserialize(r);return new p(e,i)}catch(e){console.error("Failed to load metadata:",e)}return new p(e)}save(){var e="lacertadb_"+this.name+"_metadata";try{var t={collections:this.collections,totalSizeKB:this.totalSizeKB,totalLength:this.totalLength,modifiedAt:this.modifiedAt},r=s.serialize(t),i=n.encode(r);localStorage.setItem(e,i)}catch(e){if("QuotaExceededError"===e.name)throw new o("Storage quota exceeded","QUOTA_EXCEEDED",e);throw new o("Failed to save metadata","METADATA_SAVE_FAILED",e)}}addCollection(e){this.collections[e.name]={sizeKB:e.sizeKB,length:e.length,createdAt:e.createdAt,modifiedAt:e.modifiedAt,documentSizes:e.documentSizes,documentModifiedAt:e.documentModifiedAt,documentPermanent:e.documentPermanent,documentAttachments:e.documentAttachments},this.recalculate(),this.save()}updateCollection(e){this.collections[e.name]={sizeKB:e.sizeKB,length:e.length,createdAt:e.createdAt,modifiedAt:e.modifiedAt,documentSizes:e.documentSizes,documentModifiedAt:e.documentModifiedAt,documentPermanent:e.documentPermanent,documentAttachments:e.documentAttachments},this.recalculate(),this.save()}removeCollection(e){delete this.collections[e],this.recalculate(),this.save()}recalculate(){for(var e in this.totalSizeKB=0,this.totalLength=0,this.collections)Object.prototype.hasOwnProperty.call(this.collections,e)&&(e=this.collections[e],this.totalSizeKB+=e.sizeKB,this.totalLength+=e.length);this.modifiedAt=Date.now()}}class w{constructor(e,t){t=t||{},this.dbName=e,this.sizeLimitKB=t.sizeLimitKB||1/0,this.bufferLimitKB=t.bufferLimitKB||(this.sizeLimitKB===1/0?0:.8*this.sizeLimitKB),this.freeSpaceEvery=t.freeSpaceEvery||1e4}static load(e){var t=localStorage.getItem("lacertadb_"+e+"_settings");if(t)try{var r=n.decode(t),i=s.deserialize(r);return new w(e,i)}catch(e){console.error("Failed to load settings:",e)}return new w(e)}save(){var e="lacertadb_"+this.dbName+"_settings",t={sizeLimitKB:this.sizeLimitKB,bufferLimitKB:this.bufferLimitKB,freeSpaceEvery:this.freeSpaceEvery};t=s.serialize(t),t=n.encode(t);localStorage.setItem(e,t)}updateSettings(e){Object.assign(this,e),this.save()}}class m{constructor(e){this.dbName=e,this.keyPrefix="lacertadb_"+e+"_quickstore_"}add(e,t){var r=this.keyPrefix+"data_"+e;try{var i=s.serialize(t),a=n.encode(i);return localStorage.setItem(r,a),this.updateIndex(e,"add"),!0}catch(e){if("QuotaExceededError"===e.name)throw new o("QuickStore quota exceeded","QUOTA_EXCEEDED",e);return!1}}get(e){if(e=this.keyPrefix+"data_"+e,e=localStorage.getItem(e))try{var t=n.decode(e);return s.deserialize(t)}catch(e){console.error("Failed to parse QuickStore data:",e)}return null}update(e,t){return this.add(e,t)}delete(e){var t=this.keyPrefix+"data_"+e;localStorage.removeItem(t),this.updateIndex(e,"delete")}getAll(){var e=this.keyPrefix+"index",t=[];if(e=localStorage.getItem(e))try{var r=n.decode(e);t=s.deserialize(r)}catch(e){t=[]}for(var i=[],a=0;a<t.length;a++){var o=t[a],c=this.get(o);if(c){var h,l={_id:o};for(h in c)Object.prototype.hasOwnProperty.call(c,h)&&(l[h]=c[h]);i.push(l)}}return i}clear(){var e=this.keyPrefix+"index",t=localStorage.getItem(e),r=[];if(t)try{var i=n.decode(t);r=s.deserialize(i)}catch(e){r=[]}for(var a=0;a<r.length;a++)this.delete(r[a]);localStorage.removeItem(e)}updateIndex(e,t){var r=this.keyPrefix+"index",i=localStorage.getItem(r),a=[];if(i)try{var o=n.decode(i);a=s.deserialize(o)}catch(t){a=[]}"add"!==t||a.includes(e)?"delete"===t&&(a=a.filter((function(t){return t!==e}))):a.push(e),i=s.serialize(a),o=n.encode(i),localStorage.setItem(r,o)}}class y{}y.operators={$eq:function(e,t){return e===t},$ne:function(e,t){return e!==t},$gt:function(e,t){return t<e},$gte:function(e,t){return t<=e},$lt:function(e,t){return e<t},$lte:function(e,t){return e<=t},$in:function(e,t){return Array.isArray(t)&&t.includes(e)},$nin:function(e,t){return Array.isArray(t)&&!t.includes(e)},$and:function(e,t){return t.every((function(t){return y.evaluate(e,t)}))},$or:function(e,t){return t.some((function(t){return y.evaluate(e,t)}))},$not:function(e,t){return!y.evaluate(e,t)},$nor:function(e,t){return!t.some((function(t){return y.evaluate(e,t)}))},$exists:function(e,t){return void 0!==e===t},$type:function(e,t){return typeof e===t},$all:function(e,t){return Array.isArray(e)&&t.every((function(t){return e.includes(t)}))},$elemMatch:function(e,t){return Array.isArray(e)&&e.some((function(e){return y.evaluate({value:e},{value:t})}))},$size:function(e,t){return Array.isArray(e)&&e.length===t},$regex:function(e,t){return"string"==typeof e&&new RegExp(t).test(e)},$text:function(e,t){return"string"==typeof e&&e.toLowerCase().includes(t.toLowerCase())}},y.evaluate=function(e,t){for(var r in t)if(Object.prototype.hasOwnProperty.call(t,r)){var i=t[r];if(r.startsWith("$")){var a=this.operators[r];if(!a)return!1;if(!a(e,i))return!1}else{var s=this.getFieldValue(e,r);if("object"!=typeof i||null===i||Array.isArray(i)){if(s!==i)return!1}else for(var n in i)if(Object.prototype.hasOwnProperty.call(i,n)){var o=i[n];if(n.startsWith("$")){if(!(n=this.operators[n])||!n(s,o))return!1}else if(s!==i)return!1}}}return!0}.bind(y),y.getFieldValue=function(e,t){for(var r=t.split("."),i=e,a=0;a<r.length;a++){var s=r[a];if(null==i)return;i=i[s]}return i};class g{}g.stages={$match:function(e,t){return e.filter((function(e){return y.evaluate(e,t)}))},$project:function(e,t){var r=this;return e.map((function(e){var i,a,s={};for(i in t)Object.prototype.hasOwnProperty.call(t,i)&&(1===(a=t[i])||!0===a?s[i]=y.getFieldValue(e,i):"object"==typeof a&&(s[i]=r.computeField(e,a)));return s}))},$sort:function(e,t){return(e=e.slice()).sort((function(e,r){for(var i in t)if(Object.prototype.hasOwnProperty.call(t,i)){var a=t[i],s=y.getFieldValue(e,i);if(s<(i=y.getFieldValue(r,i)))return 1===a?-1:1;if(i<s)return 1===a?1:-1}return 0})),e},$limit:function(e,t){return e.slice(0,t)},$skip:function(e,t){return e.slice(t)},$group:function(e,t){for(var r={},i=t._id,a=0;a<e.length;a++){var s=e[a],n="string"==typeof i?y.getFieldValue(s,i.replace("$","")):JSON.stringify(i);r[n]||(r[n]={_id:n,docs:[]}),r[n].docs.push(s)}var o,c=[];for(o in r)if(Object.prototype.hasOwnProperty.call(r,o)){var h,l,u,d=r[o],f={_id:d._id};for(h in t)Object.prototype.hasOwnProperty.call(t,h)&&"_id"!==h&&((l=t[h]).$sum?f[h]=d.docs.reduce((function(e,t){return e+(("string"==typeof l.$sum?y.getFieldValue(t,l.$sum.replace("$","")):l.$sum)||0)}),0):l.$avg?(u=d.docs.reduce((function(e,t){return e+(y.getFieldValue(t,l.$avg.replace("$",""))||0)}),0),f[h]=u/d.docs.length):l.$count?f[h]=d.docs.length:l.$max?f[h]=Math.max.apply(null,d.docs.map((function(e){return y.getFieldValue(e,l.$max.replace("$",""))}))):l.$min&&(f[h]=Math.min.apply(null,d.docs.map((function(e){return y.getFieldValue(e,l.$min.replace("$",""))})))));c.push(f)}return c},$lookup:async function(e,t,r){for(var i=[],a=await r.getCollection(t.from),s=0;s<e.length;s++){var n,o=e[s],c=y.getFieldValue(o,t.localField),h={},l=(c=(h[t.foreignField]=c,await a.query(h)),{});for(n in o)Object.prototype.hasOwnProperty.call(o,n)&&(l[n]=o[n]);l[t.as]=c,i.push(l)}return i}},g.computeField=function(e,t){return"string"==typeof t&&t.startsWith("$")?y.getFieldValue(e,t.replace("$","")):t},g.execute=async function(e,t,r){for(var i=e,a=0;a<t.length;a++){var s=t[a],n=Object.keys(s)[0],o=(s=s[n],this.stages[n]);if(!o)throw new Error("Unknown aggregation stage: "+n);i="$lookup"===n?await o(i,s,r):o.call(this,i,s)}return i}.bind(g);class v{constructor(){this.metrics={operations:[],latencies:[],cacheHits:0,cacheMisses:0,memoryUsage:[]},this.monitoring=!1,this.monitoringInterval=null}startMonitoring(){this.monitoring=!0,this.monitoringInterval=setInterval(this.collectMetrics.bind(this),1e3)}stopMonitoring(){this.monitoring=!1,this.monitoringInterval&&(clearInterval(this.monitoringInterval),this.monitoringInterval=null)}recordOperation(e,t){this.monitoring&&(this.metrics.operations.push({type:e,duration:t,timestamp:Date.now()}),this.metrics.latencies.push(t),100<this.metrics.operations.length&&this.metrics.operations.shift(),100<this.metrics.latencies.length)&&this.metrics.latencies.shift()}recordCacheHit(){this.metrics.cacheHits++}recordCacheMiss(){this.metrics.cacheMisses++}collectMetrics(){"undefined"!=typeof performance&&performance.memory&&(this.metrics.memoryUsage.push({used:performance.memory.usedJSHeapSize,total:performance.memory.totalJSHeapSize,limit:performance.memory.jsHeapSizeLimit,timestamp:Date.now()}),60<this.metrics.memoryUsage.length)&&this.metrics.memoryUsage.shift()}getStats(){var e=this.metrics.operations.filter((function(e){return Date.now()-e.timestamp<1e3})).length,t=0<this.metrics.latencies.length?this.metrics.latencies.reduce((function(e,t){return e+t}),0)/this.metrics.latencies.length:0,r=0<this.metrics.cacheHits+this.metrics.cacheMisses?this.metrics.cacheHits/(this.metrics.cacheHits+this.metrics.cacheMisses)*100:0,i=0<this.metrics.memoryUsage.length?this.metrics.memoryUsage[this.metrics.memoryUsage.length-1].used/1048576:0;return{opsPerSec:e,avgLatency:t.toFixed(2),cacheHitRate:r.toFixed(1),memoryUsage:i.toFixed(2)}}getOptimizationTips(){var e,t=[];return 0<this.metrics.latencies.length&&100<this.metrics.latencies.reduce((function(e,t){return e+t}),0)/this.metrics.latencies.length&&t.push("High average latency detected. Consider enabling compression and indexing frequently queried fields."),(0<this.metrics.cacheHits+this.metrics.cacheMisses?this.metrics.cacheHits/(this.metrics.cacheHits+this.metrics.cacheMisses)*100:0)<50&&t.push("Low cache hit rate. Consider increasing cache size or optimizing query patterns."),10<this.metrics.memoryUsage.length&&10485760<(e=this.metrics.memoryUsage.slice(-10))[e.length-1].used-e[0].used&&t.push("Memory usage is increasing rapidly. Check for memory leaks or consider batch processing."),0===t.length&&t.push("Performance is optimal. No issues detected."),t}}class b{constructor(e,t){this.name=e,this.database=t,this.db=null,this.metadata=null,this.settings=t.settings,this.indexedDB=new u,this.opfs=new l,this.cleanupInterval=null,this.events={beforeAdd:[],afterAdd:[],beforeGet:[],afterGet:[],beforeUpdate:[],afterUpdate:[],beforeDelete:[],afterDelete:[]},this.queryCache=new Map,this.cacheTimeout=6e4}async init(){var e=this.database.name+"_"+this.name;this.db=await this.indexedDB.openDatabase(e,1,(function(e){e.objectStoreNames.contains("documents")||((e=e.createObjectStore("documents",{keyPath:"_id"})).createIndex("created","_created",{unique:!1}),e.createIndex("modified","_modified",{unique:!1}),e.createIndex("permanent","_permanent",{unique:!1}))})),e=this.database.metadata.collections[this.name];return this.metadata=new f(this.name,e),0<this.settings.freeSpaceEvery&&(this.cleanupInterval=setInterval(this.freeSpace.bind(this),this.settings.freeSpaceEvery)),this}async add(e,t){return t=t||{},await this.trigger("beforeAdd",e),e=new d({data:e,_id:t.id},{encrypted:t.encrypted||!1,compressed:!1!==t.compressed,permanent:t.permanent||!1,password:t.password}),t.attachments&&0<t.attachments.length&&(t=await this.opfs.saveAttachments(this.database.name,this.name,e._id,t.attachments),e._attachments=t),await e.pack(),t=e.databaseOutput(),await this.indexedDB.add(this.db,"documents",t),t=new Blob([t.packedData]).size/1024,this.metadata.addDocument(e._id,t,e._permanent,e._attachments.length),this.database.metadata.updateCollection(this.metadata),await this.checkSpaceLimit(),await this.trigger("afterAdd",e),this.queryCache.clear(),e._id}async get(e,t){var r;if(t=t||{},await this.trigger("beforeGet",e),e=await this.indexedDB.get(this.db,"documents",e))return r=new d(e,{password:t.password,encrypted:e._encrypted,compressed:e._compressed}),e.packedData&&await r.unpack(),t.includeAttachments&&0<r._attachments.length&&(e=await this.opfs.getAttachments(r._attachments),r.data._attachments=e),await this.trigger("afterGet",r),r.objectOutput(t.includeAttachments);throw new o("Document not found","DOCUMENT_NOT_FOUND")}async getAll(e){for(var t=await this.indexedDB.getAll(this.db,"documents",void 0,(e=e||{}).limit),r=[],i=0;i<t.length;i++){var a=t[i];try{var s=new d(a,{password:e.password,encrypted:a._encrypted,compressed:a._compressed});a.packedData&&await s.unpack(),r.push(s.objectOutput())}catch(e){console.error("Failed to unpack document:",e)}}return r}async update(e,t,r){r=r||{},await this.trigger("beforeUpdate",{docId:e,updates:t});var i,a,s=await this.get(e,{password:r.password}),n={};for(i in s)Object.prototype.hasOwnProperty.call(s,i)&&(n[i]=s[i]);for(a in t)Object.prototype.hasOwnProperty.call(t,a)&&(n[a]=t[a]);delete n._id,delete n._created,delete n._modified,delete n._permanent;var o=new d({_id:e,_created:s._created,data:n},{encrypted:r.encrypted||!1,compressed:!1!==r.compressed,permanent:r.permanent||s._permanent,password:r.password});r.attachments&&0<r.attachments.length&&(await this.opfs.deleteAttachments(this.database.name,this.name,e),e=await this.opfs.saveAttachments(this.database.name,this.name,o._id,r.attachments),o._attachments=e),await o.pack(),r=o.databaseOutput(),await this.indexedDB.put(this.db,"documents",r),e=new Blob([r.packedData]).size/1024;return this.metadata.updateDocument(o._id,e,o._permanent,o._attachments.length),this.database.metadata.updateCollection(this.metadata),await this.trigger("afterUpdate",o),this.queryCache.clear(),o._id}async delete(e){await this.trigger("beforeDelete",e);var t=await this.indexedDB.get(this.db,"documents",e);if(!t)throw new o("Document not found","DOCUMENT_NOT_FOUND");if(t._permanent)throw new o("Cannot delete permanent document","INVALID_OPERATION");await this.indexedDB.delete(this.db,"documents",e),t._attachments&&0<t._attachments.length&&await this.opfs.deleteAttachments(this.database.name,this.name,e),this.metadata.removeDocument(e),this.database.metadata.updateCollection(this.metadata),await this.trigger("afterDelete",e),this.queryCache.clear()}async query(e,t){var r={filter:e=e||{},options:t=t||{}};r=s.serialize(r),r=n.encode(r);if((a=this.queryCache.get(r))&&Date.now()-a.timestamp<this.cacheTimeout)return i.performanceMonitor&&i.performanceMonitor.recordCacheHit(),a.data;i.performanceMonitor&&i.performanceMonitor.recordCacheMiss();var a=performance.now(),o=c=(await this.getAll(t)).filter((function(t){return y.evaluate(t,e)})),c=(t.projection&&(o=g.stages.$project(c,t.projection)),t.sort&&(o=g.stages.$sort(o,t.sort)),t.skip&&(o=g.stages.$skip(o,t.skip)),t.limit&&(o=g.stages.$limit(o,t.limit)),performance.now()-a);return i.performanceMonitor&&i.performanceMonitor.recordOperation("query",c),this.queryCache.set(r,{data:o,timestamp:Date.now()}),100<this.queryCache.size&&(t=this.queryCache.keys().next().value,this.queryCache.delete(t)),o}async aggregate(e){var t=performance.now(),r=await this.getAll();r=await g.execute(r,e,this.database),e=performance.now()-t;return i.performanceMonitor&&i.performanceMonitor.recordOperation("aggregate",e),r}async batchAdd(e,t){t=t||{};for(var r=[],a=performance.now(),s=0;s<e.length;s++){var n=e[s];try{var o=await this.add(n,t);r.push({success:!0,id:o})}catch(e){r.push({success:!1,error:e.message})}}return a=performance.now()-a,i.performanceMonitor&&i.performanceMonitor.recordOperation("batchAdd",a),r}async batchUpdate(e,t){t=t||{};for(var r=[],i=0;i<e.length;i++){var a=e[i];try{await this.update(a.id,a.data,t),r.push({success:!0,id:a.id})}catch(e){r.push({success:!1,id:a.id,error:e.message})}}return r}async batchDelete(e){for(var t=[],r=0;r<e.length;r++){var i=e[r];try{await this.delete(i),t.push({success:!0,id:i})}catch(e){t.push({success:!1,id:i,error:e.message})}}return t}async clear(){await this.indexedDB.clear(this.db,"documents"),this.metadata=new f(this.name),this.database.metadata.updateCollection(this.metadata),this.queryCache.clear()}async checkSpaceLimit(){this.settings.sizeLimitKB!==1/0&&this.metadata.sizeKB>this.settings.bufferLimitKB&&await this.freeSpace()}async freeSpace(){for(var e=.8*this.settings.bufferLimitKB;this.metadata.sizeKB>e;){var t=this.metadata.getOldestNonPermanentDocuments(10);if(0===t.length)break;for(var r=0;r<t.length;r++){var i=t[r];try{await this.delete(i)}catch(e){console.error("Failed to delete document during cleanup:",e)}}}}createIndex(e,t){console.log("Index for "+e+" would be created on next database upgrade")}on(e,t){this.events[e]&&this.events[e].push(t)}off(e,t){this.events[e]&&(this.events[e]=this.events[e].filter((function(e){return e!==t})))}async trigger(e,t){if(this.events[e])for(var r=this.events[e],i=0;i<r.length;i++)await r[i](t)}clearCache(){this.queryCache.clear()}destroy(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null),this.db&&(this.db.close(),this.db=null)}}class A{constructor(e){this.name=e,this.collections=new Map,this.metadata=null,this.settings=null,this.quickStore=null}async init(){return this.metadata=p.load(this.name),this.settings=w.load(this.name),this.quickStore=new m(this.name),this}async createCollection(e,t){if(this.collections.has(e))throw new o("Collection already exists","COLLECTION_EXISTS");var r=new b(e,this);return await r.init(),this.collections.set(e,r),this.metadata.collections[e]||(e=new f(e),this.metadata.addCollection(e)),r}async getCollection(e){if(!this.collections.has(e)){if(!this.metadata.collections[e])throw new o("Collection not found","COLLECTION_NOT_FOUND");var t=new b(e,this);await t.init(),this.collections.set(e,t)}return this.collections.get(e)}async dropCollection(e){var t=await this.getCollection(e),r=(await t.clear(),t.destroy(),this.collections.delete(e),this.metadata.removeCollection(e),this.name+"_"+e);await new Promise((function(e,t){var i=indexedDB.deleteDatabase(r);i.onsuccess=e,i.onerror=t}))}async listCollections(){return Object.keys(this.metadata.collections)}getStats(){var e,t,r=[],i=this.metadata.collections;for(e in i)Object.prototype.hasOwnProperty.call(i,e)&&(t=i[e],r.push({name:e,sizeKB:t.sizeKB,documents:t.length,createdAt:new Date(t.createdAt).toISOString(),modifiedAt:new Date(t.modifiedAt).toISOString()}));return{name:this.name,totalSizeKB:this.metadata.totalSizeKB,totalDocuments:this.metadata.totalLength,collections:r}}updateSettings(e){this.settings.updateSettings(e)}async export(e,t){e=e||"json",t=t||null;for(var r,i,a={version:"4.0.0",database:this.name,timestamp:Date.now(),collections:{}},o=await this.listCollections(),c=0;c<o.length;c++){var l=o[c],u=await(await this.getCollection(l)).getAll({password:t});a.collections[l]=u}if("json"===e)return i=s.serialize(a),n.encode(i);if("encrypted"===e&&t)return i=new h,r=s.serialize(a),i=await i.encrypt(r,t),n.encode(i);if("csv"!==e)return a;var d="";for(l in a.collections)if(Object.prototype.hasOwnProperty.call(a.collections,l)&&0<(u=a.collections[l]).length){for(var f=Object.keys(u[0]),p=(d=(d+="Collection: "+l+"\n")+f.join(",")+"\n",0);p<u.length;p++){var w=u[p];d+=f.map((function(e){return JSON.stringify(w[e]||"")})).join(",")+"\n"}d+="\n"}return d}async import(e,t,r){var i,a,c,l,u;t=t||"json",r=r||null;try{l="encrypted"===t&&r?(i=new h,a=n.decode(e),c=await i.decrypt(a,r),s.deserialize(c)):(u=n.decode(e),s.deserialize(u))}catch(e){throw new o("Failed to parse import data","IMPORT_PARSE_FAILED",e)}var d,f=this;for(d in l.collections)if(Object.prototype.hasOwnProperty.call(l.collections,d))for(var p=l.collections[d],w=await this.createCollection(d).catch((function(){return f.getCollection(d)})),m=0;m<p.length;m++)await w.add(p[m]);var y,g=0;for(y in l.collections)Object.prototype.hasOwnProperty.call(l.collections,y)&&(g+=l.collections[y].length);return{collections:Object.keys(l.collections).length,documents:g}}async clearAll(){this.collections.forEach((async function(e,t){await e.clear(),e.destroy()})),this.collections.clear(),this.metadata=new p(this.name),this.metadata.save(),this.quickStore.clear()}destroy(){this.collections.forEach((function(e){e.destroy()})),this.collections.clear()}}r={LacertaDB:class{constructor(){this.databases=new Map,this.performanceMonitor=new v,void 0!==i&&(i.performanceMonitor=this.performanceMonitor)}async getDatabase(e){var t;return this.databases.has(e)||(await(t=new A(e)).init(),this.databases.set(e,t)),this.databases.get(e)}async dropDatabase(e){var t;this.databases.has(e)&&(await(t=this.databases.get(e)).clearAll(),t.destroy(),this.databases.delete(e),localStorage.removeItem("lacertadb_"+e+"_metadata"),localStorage.removeItem("lacertadb_"+e+"_settings"),localStorage.removeItem("lacertadb_"+e+"_version"),new m(e).clear())}listDatabases(){for(var e=[],t=0;t<localStorage.length;t++){var r=localStorage.key(t);r&&r.startsWith("lacertadb_")&&r.endsWith("_metadata")&&(r=r.replace("lacertadb_","").replace("_metadata",""),e.push(r))}return e}async createBackup(e){e=e||null;for(var t={version:"4.0.0",timestamp:Date.now(),databases:{}},r=this.listDatabases(),i=0;i<r.length;i++){var a=r[i],o=await(await this.getDatabase(a)).export("json");o=n.decode(o);t.databases[a]=s.deserialize(o)}var c=s.serialize(t);return e?(e=await(new h).encrypt(c,e),n.encode(e)):n.encode(c)}async restoreBackup(e,t){t=t||null;try{var r,i,a=n.decode(e);i=t?(r=await(new h).decrypt(a,t),s.deserialize(r)):s.deserialize(a)}catch(e){throw new o("Failed to parse backup data","BACKUP_PARSE_FAILED",e)}var c,l,u,d={databases:0,collections:0,documents:0};for(c in i.databases)Object.prototype.hasOwnProperty.call(i.databases,c)&&(l=i.databases[c],u=await this.getDatabase(c),l=s.serialize(l),l=n.encode(l),u=await u.import(l),d.databases++,d.collections+=u.collections,d.documents+=u.documents);return d}},Database:A,Collection:b,Document:d,QueryOperators:y,AggregationPipeline:g,MigrationManager:class{constructor(e){this.database=e,this.migrations=[],this.currentVersion=this.loadVersion()}loadVersion(){return localStorage.getItem("lacertadb_"+this.database.name+"_version")||"1.0.0"}saveVersion(e){localStorage.setItem("lacertadb_"+this.database.name+"_version",e),this.currentVersion=e}addMigration(e){this.migrations.push(e)}async runMigrations(e){var t=this,r=this.migrations.filter((function(r){return 0<t.compareVersions(r.version,t.currentVersion)&&t.compareVersions(r.version,e)<=0}));r.sort((function(e,r){return t.compareVersions(e.version,r.version)}));for(var i=0;i<r.length;i++){var a=r[i];await this.runMigration(a),this.saveVersion(a.version)}}async runMigration(e){console.log("Running migration: "+e.name+" (v"+e.version+")");for(var t=await this.database.listCollections(),r=0;r<t.length;r++)for(var i=t[r],a=await this.database.getCollection(i),s=await a.getAll(),n=0;n<s.length;n++){var o=s[n],c=await e.up(o);c&&await a.update(o._id,c)}}async rollback(e){var t=this,r=this.migrations.filter((function(r){return 0<t.compareVersions(r.version,e)&&t.compareVersions(r.version,t.currentVersion)<=0}));r.sort((function(e,r){return t.compareVersions(r.version,e.version)}));for(var i=0;i<r.length;i++){var a=r[i];a.down&&await this.runRollback(a)}this.saveVersion(e)}async runRollback(e){console.log("Rolling back migration: "+e.name+" (v"+e.version+")");for(var t=await this.database.listCollections(),r=0;r<t.length;r++)for(var i=t[r],a=await this.database.getCollection(i),s=await a.getAll(),n=0;n<s.length;n++){var o=s[n],c=await e.down(o);c&&await a.update(o._id,c)}}compareVersions(e,t){for(var r=e.split(".").map(Number),i=t.split(".").map(Number),a=0;a<Math.max(r.length,i.length);a++){var s=r[a]||0,n=i[a]||0;if(n<s)return 1;if(s<n)return-1}return 0}},PerformanceMonitor:v,LacertaDBError:o},e.exports=r}},function(e,t,r){r.r(t);let i=240,a=0,s=16,n=32,o=48,c=64,h=80,l=96,u=112,d=128,f=144,p=160,w=176,m=192,y=224,g=240,v=0,b=1,A=2,_=3,S=16,E=17,U=18,D=19,k=20,x=21,I=22,O=23,V=24,B=25,C=26,z=32,P=33,M=34,T=35,L=48,j=49,F=50,R=51,N=52,$=53,K=54,q=55,H=64,W=65,Q=66,G=67,Y=68,J=69,X=70,Z=71,ee=80,te=81,re=82,ie=83,ae=84,se=85,ne=96,oe=97,ce=98,he=99,le=100,ue=101,de=102,fe=103,pe=104,we=105,me=106,ye=107,ge=112,ve=113,be=114,Ae=128,_e=129,Se=144,Ee=145,Ue=160,De=161,ke=162,xe=163,Ie=164,Oe=165,Ve=166,Be=167,Ce=168,ze=176,Pe=192,Me=193,Te=208,Le=209,je=224,Fe=225,Re=226,Ne=227,$e=240,Ke=new Uint8Array(256),qe=new Uint8Array(256);new Map;let He=new Map,We=new Map;var Qe=[[E,2],[U,4],[D,4],[k,4],[x,8],[z,8],[P,8]];for(let e=0;e<Qe.length;e++)Ke[Qe[e][0]]=Qe[e][1];var Ge,Ye=[[ne,1],[oe,1],[ce,1],[he,2],[le,2],[ue,4],[de,4],[fe,4],[pe,8],[we,8],[me,8],[G,1],[Y,2],[J,4],[X,4],[Z,8]];for(let e=0;e<Ye.length;e++)qe[Ye[e][0]]=Ye[e][1];for(Ge of["asyncIterator","hasInstance","isConcatSpreadable","iterator","match","matchAll","replace","search","species","split","toPrimitive","toStringTag","unscopables"]){var Je=Symbol[Ge];Je&&(He.set(Je,Ge),We.set(Ge,Je))}class Xe{constructor(e=65536){this.size=(e+128-1&-128)>>>0,this.buffer=new ArrayBuffer(this.size),this.offset=0,this.u8=new Uint8Array(this.buffer),this.view=new DataView(this.buffer),this.pos=0,this.f32View=null,this.f64View=null,this.i32View=null}ensure(e){var t,r;(e=this.pos+(e|=0)|0)>this.size&&(e=(128+(0|Math.max(this.size<<1,128+e))-1&-128)>>>0,t=new ArrayBuffer(e),(r=new Uint8Array(t)).set(this.u8.subarray(0,this.pos)),this.buffer=t,this.u8=r,this.view=new DataView(t),this.size=e,this.f32View=null,this.f64View=null,this.i32View=null)}alignPos(e){e=e-1|0,this.pos=(this.pos+e&~e)>>>0}writeU8(e){this.ensure(1),this.u8[this.pos++]=255&e}writeU16(e){this.alignPos(2),this.ensure(2),this.view.setUint16(this.pos,65535&e,!0),this.pos=this.pos+2|0}writeI16(e){this.alignPos(2),this.ensure(2),this.view.setInt16(this.pos,e,!0),this.pos=this.pos+2|0}writeU32(e){this.alignPos(4),this.ensure(4),this.view.setUint32(this.pos,e>>>0,!0),this.pos=this.pos+4|0}writeI32(e){this.alignPos(4),this.ensure(4),this.view.setInt32(this.pos,0|e,!0),this.pos=this.pos+4|0}writeF32(e){this.alignPos(4),this.ensure(4),this.view.setFloat32(this.pos,+e,!0),this.pos=this.pos+4|0}writeF64(e){this.alignPos(8),this.ensure(8),this.view.setFloat64(this.pos,+e,!0),this.pos=this.pos+8|0}writeBigInt64(e){this.alignPos(8),this.ensure(8),this.view.setBigInt64(this.pos,BigInt(e),!0),this.pos=this.pos+8|0}writeVarint(e){if(e>>>=0,this.ensure(5),e<128)this.u8[this.pos++]=e;else if(e<16384)this.u8[this.pos]=127&e|128,this.u8[this.pos+1]=e>>>7,this.pos=this.pos+2|0;else{let t=this.pos;for(;this.u8[t++]=127&e|128,128<=(e>>>=7););this.u8[t++]=e,this.pos=t}}writePackedArray(e,t){var r=0|e.length,i=(this.writeVarint(r),0|qe[t]);if(!i)throw new Error("Unknown element type: 0x"+t.toString(16));switch(this.alignPos(Math.min(i,8)),this.ensure(r*i),t){case G:new Int8Array(this.buffer,this.pos,r).set(e),this.pos=this.pos+r|0;break;case Y:var a=new Int16Array(this.buffer,this.pos,r);for(let t=0;t<r;t++)a[t]=0|e[t];this.pos=this.pos+(r<<1)|0;break;case J:var s=new Int32Array(this.buffer,this.pos,r);for(let t=0;t<r;t++)s[t]=0|e[t];this.pos=this.pos+(r<<2)|0;break;case X:var n=new Float32Array(this.buffer,this.pos,r);for(let t=0;t<r;t++)n[t]=+e[t];this.pos=this.pos+(r<<2)|0;break;case Z:var o=new Float64Array(this.buffer,this.pos,r);for(let t=0;t<r;t++)o[t]=+e[t];this.pos=this.pos+(r<<3)|0;break;default:throw new Error("Unsupported packed array type: 0x"+t.toString(16))}}writeBulkAligned(e,t){var r;t=Math.min(t,8),this.alignPos(t),t=e.byteLength||e.length;this.ensure(t),e.buffer&&void 0!==e.byteOffset?(r=new Uint8Array(e.buffer,e.byteOffset,t),this.u8.set(r,this.pos)):this.u8.set(e,this.pos),this.pos=this.pos+t|0}reset(){this.pos=0}getResult(){return this.u8.subarray(0,this.pos)}}class Ze{constructor(){this.blockSize=16}canOptimize(e){var t=e.length;if(!(8<=t&(0==(t&t-1)||16<=t)))return!1;var r=typeof e[0];if("number"!=r)return!1;var i=Math.max(1,t>>>5|0);for(let a=i;a<t;a+=i)if(typeof e[a]!=r)return!1;return!0}analyzeNumericArray(e){let t=1,r=1/0,i=-1/0,a=1;var s,n=e.length;for(let s=0;s<n;s++){var o=e[s];t&=+(o==(0|o)),r=Math.min(r,o),i=Math.max(i,o),a&&(a&=+(Math.fround(o)==o))}return t?(s=+((s=Math.max(Math.abs(r),Math.abs(i)))<=127)<<0|+(s<=32767)<<1|+(s<=2147483647)<<2,[{type:J,elementSize:4},{type:G,elementSize:1},{type:Y,elementSize:2},{type:J,elementSize:4}][3&s]):a?{type:X,elementSize:4}:{type:Z,elementSize:8}}}class et{constructor(){this.simdProcessor=new Ze,this.constructorMap=new Map,this.typeNameMap=new Map,this.errorTypeMap=new Map,this.initMaps()}initMaps(){var e,t,r,i,a=[[Date,Se],[RegExp,ze],[Map,Ae],[Set,_e],[ArrayBuffer,ge],[DataView,ye]],s=[["Uint8Array",ne],["Int8Array",oe],["Uint8ClampedArray",ce],["Uint16Array",he],["Int16Array",le],["Uint32Array",ue],["Int32Array",de],["Float32Array",fe],["Float64Array",pe],["BigInt64Array",we],["BigUint64Array",me],["SharedArrayBuffer",be]];for([e,t]of a)this.constructorMap.set(e,t);for([r,i]of s){var n=globalThis[r];n&&(this.constructorMap.set(n,i),this.typeNameMap.set(r,i))}this.errorTypeMap.set("Error",Ue),this.errorTypeMap.set("EvalError",De),this.errorTypeMap.set("RangeError",ke),this.errorTypeMap.set("ReferenceError",xe),this.errorTypeMap.set("SyntaxError",Ie),this.errorTypeMap.set("TypeError",Oe),this.errorTypeMap.set("URIError",Ve),this.errorTypeMap.set("AggregateError",Be)}detect(e){if(null==e)return null===e?v:b;switch(typeof e){case"boolean":return e?_:A;case"number":return this.detectNumber(e);case"bigint":return this.detectBigInt(e);case"string":return this.detectString(e);case"symbol":return this.detectSymbol(e);case"object":return this.detectObject(e);default:return b}}detectNumber(e){var t,r,i;return e!=e?I:(i=new Float64Array([e]),((t=(i=new Uint32Array(i.buffer))[1])&(r=2146435072))==r&0==i[0]&0==(1048575&t)?t>>>31?V:O:0==e&&t>>>31?B:e==(0|e)?(i=+((r=Math.abs(e))<=127)<<0|+(r<=32767)<<1|+(r<=2147483647)<<2,[C,S,E,U][Math.min(i,3)]):Math.fround(e)==e?k:x)}detectBigInt(e){var t=e<0n;return(t?-e:e)<=0x7fffffffffffffffn?t?P:z:t?T:M}detectString(e){var t,r=e.length;if(0==r)return L;let i=1;for(let t=0;t<r&&i;t++)i&=+(e.charCodeAt(t)<=127);return i?r<16?j:r<256?F:R:(t=(new TextEncoder).encode(e).length)<16?N:t<256?$:K}detectSymbol(e){return void 0!==Symbol.keyFor(e)?Fe:He.has(e)?Re:void 0===e.description?Ne:je}detectObject(e){var t,r;return null==e?v:(t=e.constructor,void 0!==(t=this.constructorMap.get(t))?t==Se?(r=e.getTime())==r?Se:Ee:t:Array.isArray(e)?this.detectArray(e):ArrayBuffer.isView(e)?this.detectTypedArrayType(e):e instanceof Error?this.detectErrorType(e):"undefined"!=typeof Blob&&e instanceof Blob?e instanceof File?Me:Pe:this.classifyObject(e))}classifyObject(e){var t=Object.getPrototypeOf(e);if(e.constructor!=Object&&t!=Object.prototype&&null!=t)return ie;t=Object.getOwnPropertyNames(e);var r,i=Object.getOwnPropertySymbols(e);if(0===(t=[...t,...i]).length)return ee;let a=!1,s=!1;for(r of t){var n=Object.getOwnPropertyDescriptor(e,r);if(n.get||n.set){a=!0;break}"function"==typeof n.value&&(s=!0),n.enumerable&&n.writable&&n.configurable||(a=!0)}return a?ae:s?se:re}detectArray(e){var t=e.length;if(0==t)return H;let r=0,i=!1;for(let a=0;a<t;a++)a in e?r++:i=!0;return i||r<3*t>>>2?Q:this.simdProcessor.canOptimize(e)?this.simdProcessor.analyzeNumericArray(e).type:W}detectTypedArrayType(e){return e=e.constructor.name,this.typeNameMap.get(e)||ne}detectErrorType(e){return e=e.constructor.name,this.errorTypeMap.get(e)||Ce}}t.default=class{constructor(e={}){this.options={compression:e.compression||!1,deduplication:!1!==e.deduplication,shareArrayBuffers:!1!==e.shareArrayBuffers,simdOptimization:!1!==e.simdOptimization,detectCircular:!1!==e.detectCircular,serializeFunctions:e.serializeFunctions||!1,preservePropertyDescriptors:!1!==e.preservePropertyDescriptors,memoryPoolSize:e.memoryPoolSize||65536,...e},this.pool=new Xe(this.options.memoryPoolSize),this.detector=new et,this.simdProcessor=new Ze,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(e){return this.resetState(),this.pool.writeU32(1413632565),this.pool.writeU8(5),this.options.detectCircular&&this.detectCircularReferences(e,new WeakSet),this.writeValue(e),this.pool.getResult()}resetState(){this.pool.reset(),this.refs.clear(),this.circularRefs.clear(),this.strings.clear(),this.buffers.clear()}detectCircularReferences(e,t){if("object"==typeof e&&null!=e)if(t.has(e))this.circularRefs.add(e);else{t.add(e);try{if(Array.isArray(e))for(let r=0;r<e.length;r++)r in e&&this.detectCircularReferences(e[r],t);else if(e instanceof Map)for(var[r,i]of e)this.detectCircularReferences(r,t),this.detectCircularReferences(i,t);else if(e instanceof Set)for(var a of e)this.detectCircularReferences(a,t);else for(var s in e)if(e.hasOwnProperty(s))try{this.detectCircularReferences(e[s],t)}catch(r){}}finally{t.delete(e)}}}writeValue(e){if(this.options.detectCircular&&"object"==typeof e&&null!=e&&this.circularRefs.has(e)){if(void 0!==(t=this.refs.get(e)))return this.pool.writeU8(Le),void this.pool.writeVarint(t);this.refs.set(e,this.refs.size)}if(this.options.deduplication&&"object"==typeof e&&null!=e&&!this.circularRefs.has(e)){if(void 0!==(t=this.refs.get(e)))return this.pool.writeU8(Te),void this.pool.writeVarint(t);this.refs.set(e,this.refs.size)}if(this.options.deduplication&&"string"==typeof e&&3<e.length){if(void 0!==(t=this.strings.get(e)))return this.pool.writeU8(q),void this.pool.writeVarint(t);this.strings.set(e,this.strings.size)}if(this.options.shareArrayBuffers&&e instanceof ArrayBuffer){if(void 0!==(t=this.buffers.get(e)))return this.pool.writeU8(ve),void this.pool.writeVarint(t);this.buffers.set(e,this.buffers.size)}var t,r=this.detector.detect(e);switch(t=(this.pool.writeU8(r),r&i)){case a:break;case s:this.writeNumber(e,r);break;case n:this.writeBigInt(e,r);break;case o:this.writeString(e,r);break;case c:this.writeArray(e,r);break;case h:this.writeObject(e,r);break;case l:this.writeTypedArray(e,r);break;case u:this.writeArrayBuffer(e,r);break;case d:this.writeCollection(e,r);break;case f:this.writeDate(e,r);break;case p:this.writeError(e,r);break;case w:this.writeRegExp(e);break;case m:this.writeBinary(e,r);break;case y:this.writeSpecial(e,r);break;case g:this.writeExtension(e,r)}}writeNumber(e,t){switch(t){case S:this.pool.writeU8(e);break;case E:this.pool.writeI16(e);break;case U:this.pool.writeI32(e);break;case D:this.pool.writeU32(e);break;case k:this.pool.writeF32(e);break;case x:this.pool.writeF64(e);break;case C:var r=e<0;this.pool.writeVarint(Math.abs(e)),this.pool.writeU8(r?1:0)}}writeBigInt(e,t){switch(t){case z:case P:this.pool.writeBigInt64(e);break;case M:case T:this.writeLargeBigInt(e)}}writeLargeBigInt(e){var t,r=BigInt(e).toString(16).replace("-",""),i=[];for(let e=r.length-2;0<=e;e-=2)i.push(parseInt(r.substr(e,2),16));for(t of(r.length%2&&i.push(parseInt(r[0],16)),this.pool.writeVarint(i.length),i))this.pool.writeU8(t)}writeString(e,t){var r=e.length;switch(t){case L:break;case j:case F:this.pool.writeU8(r);for(let t=0;t<r;t++)this.pool.writeU8(e.charCodeAt(t));break;case R:this.pool.writeVarint(r);for(let t=0;t<r;t++)this.pool.writeU8(e.charCodeAt(t));break;case N:case $:case K:var i=this.encoder.encode(e);t==N||t==$?this.pool.writeU8(i.length):this.pool.writeVarint(i.length),this.pool.writeBulkAligned(i,1)}}writeArray(e,t){var r=e.length;switch(t){case H:break;case W:this.pool.writeVarint(r);for(let t=0;t<r;t++)this.writeValue(e[t]);break;case Q:this.writeSparseArray(e);break;case G:case Y:case J:case X:case Z:this.pool.writePackedArray(e,t)}}writeSparseArray(e){var t=e.length,r=new Uint32Array(t),i=[];let a=0;for(let s=0;s<t;s++)s in e&&(r[a]=s,i[a]=e[s],a++);this.pool.writeVarint(t),this.pool.writeVarint(a);for(let e=0;e<a;e++)this.pool.writeVarint(r[e]),this.writeValue(i[e])}writeObject(e,t){if(t!=ee)switch(t){case re:case te:this.writeSimpleObject(e);break;case ae:this.writeObjectWithDescriptors(e);break;case se:this.writeObjectWithMethods(e);break;case ie:this.writeConstructorObject(e)}}writeSimpleObject(e){var t,r=Object.keys(e).filter(t=>{try{return"function"!=typeof e[t]||this.options.serializeFunctions}catch(t){return!1}});for(t of(r.sort(),this.pool.writeVarint(r.length),r))this.writeValue(t),this.writeValue(e[t])}writeObjectWithDescriptors(e){var t,r=Object.getOwnPropertyNames(e),i=Object.getOwnPropertySymbols(e);r=[...r,...i].filter(t=>{try{var r=Object.getOwnPropertyDescriptor(e,t);return r&&(this.options.serializeFunctions||!r.get&&!r.set&&"function"!=typeof r.value)}catch(t){return!1}});for(t of(this.pool.writeVarint(r.length),r)){this.writeValue(t);var a=Object.getOwnPropertyDescriptor(e,t);let r=0;a.enumerable&&(r|=1),a.writable&&(r|=2),a.configurable&&(r|=4),a.get&&(r|=8),a.set&&(r|=16),this.pool.writeU8(r),a.get||a.set?(a.get&&this.writeValue(a.get),a.set&&this.writeValue(a.set)):this.writeValue(a.value)}}writeObjectWithMethods(e){var t,r,i,a,s=[];for(t of Object.keys(e))try{var n=e[t];"function"==typeof n?this.options.serializeFunctions?s.push([t,n,!0]):s.push([t,null,!1]):s.push([t,n,!1])}catch(e){}for([r,i,a]of(this.pool.writeVarint(s.length),s))this.writeValue(r),this.pool.writeU8(a?1:0),a&&this.options.serializeFunctions?(this.writeValue(i.toString()),this.writeValue(i.name||"")):a?this.pool.writeU8($e):this.writeValue(i)}writeConstructorObject(e){this.writeValue(e.constructor.name||"");var t,r=Object.keys(e).filter(t=>{try{return"function"!=typeof e[t]||this.options.serializeFunctions}catch(t){return!1}});for(t of(this.pool.writeVarint(r.length),r))this.writeValue(t),this.writeValue(e[t])}writeTypedArray(e,t){var r=e.buffer,i=e.byteOffset,a=e.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(i),void this.pool.writeVarint(a);this.buffers.set(r,this.buffers.size)}this.pool.writeU8(0),this.pool.writeVarint(i),this.pool.writeVarint(a);var s,n=a*(s=qe[t]||1);if(t==we||t==me)for(let t=0;t<a;t++)this.pool.writeBigInt64(e[t]);else t=new Uint8Array(r,i,n),this.pool.writeBulkAligned(t,s)}writeArrayBuffer(e,t){e=new Uint8Array(e),this.pool.writeVarint(e.length),this.pool.writeBulkAligned(e,1)}writeCollection(e,t){switch(t){case Ae:for(var[r,i]of(this.pool.writeVarint(e.size),e))this.writeValue(r),this.writeValue(i);break;case _e:for(var a of(this.pool.writeVarint(e.size),e))this.writeValue(a)}}writeDate(e,t){t==Se&&this.pool.writeF64(e.getTime())}writeError(e,t){if(this.writeValue(e.message||""),this.writeValue(e.stack||""),t==Be&&e.errors)for(var r of(this.pool.writeVarint(e.errors.length),e.errors))this.writeValue(r)}writeRegExp(e){this.writeValue(e.source),this.writeValue(e.flags)}writeBinary(e,t){this.pool.writeVarint(0),this.pool.writeVarint(0)}writeSpecial(e,t){switch(t){case je:var r=e.description;this.writeValue(r);break;case Ne:break;case Fe:r=Symbol.keyFor(e),this.writeValue(r||"");break;case Re:r=He.get(e),this.writeValue(r||"")}}writeExtension(e,t){}deserialize(e){if(this.buffer=new Uint8Array(e),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");if(5!==(e=this.readU8()))throw new Error("Unsupported version: "+e);return this.readValue()}readValue(){if(this.pos>=this.buffer.length)throw new Error("Unexpected end of buffer");var e=this.readU8();if(e==Te||e==Le){var t=this.readVarint();if(t>=this.deserializeRefs.length)throw new Error("Invalid reference: "+t);return this.deserializeRefs[t]}if(e==q){if((t=this.readVarint())>=this.deserializeStrings.length)throw new Error("Invalid string reference: "+t);return this.deserializeStrings[t]}if(e==ve){if((t=this.readVarint())>=this.deserializeBuffers.length)throw new Error("Invalid buffer reference: "+t);return this.deserializeBuffers[t]}let r,v=!1;switch(t=e&i){case h:case c:case d:v=!0}if(v){switch(t){case c:r=[];break;case d:e==Ae?r=new Map:e==_e&&(r=new Set);break;case h:r={}}switch(r&&this.deserializeRefs.push(r),t){case c:this.fillArray(r,e);break;case h:this.fillObject(r,e);break;case d:this.fillCollection(r,e)}}else{switch(t){case a:r=this.readPrimitive(e);break;case s:r=this.readNumber(e);break;case n:r=this.readBigInt(e);break;case o:r=this.readString(e);break;case l:r=this.readTypedArray(e);break;case u:r=this.readArrayBuffer(e);break;case f:r=this.readDate(e);break;case p:r=this.readError(e);break;case w:r=this.readRegExp();break;case m:r=this.readBinary(e);break;case y:r=this.readSpecial(e);break;case g:r=this.readExtension(e);break;default:throw new Error("Unknown type: 0x"+e.toString(16))}"object"!=typeof r||null==r||v||this.deserializeRefs.push(r)}return r}fillArray(e,t){switch(t){case H:break;case W:var r=this.readVarint();for(let t=0;t<r;t++)e[t]=this.readValue();break;case Q:var i=this.readVarint(),a=this.readVarint();e.length=i;for(let t=0;t<a;t++)e[this.readVarint()]=this.readValue();break;case G:case Y:case J:case X:case Z:i=this.readPackedArrayData(t),e.push(...i)}}fillObject(e,t){if(t!=ee)switch(t){case re:case te:this.fillSimpleObject(e);break;case ae:this.fillObjectWithDescriptors(e);break;case se:this.fillObjectWithMethods(e);break;case ie:this.fillConstructorObject(e)}}fillSimpleObject(e){var t=this.readVarint();for(let r=0;r<t;r++)e[this.readValue()]=this.readValue()}fillObjectWithDescriptors(e){var t=this.readVarint();for(let n=0;n<t;n++){var r=this.readValue(),i={enumerable:!!(1&(s=this.readU8())),writable:!!(2&s),configurable:!!(4&s)},a=!!(8&s),s=!!(16&s);a||s?(a&&(i.get=this.readValue()),s&&(i.set=this.readValue())):i.value=this.readValue(),Object.defineProperty(e,r,i)}}fillObjectWithMethods(e){var t=this.readVarint();for(let a=0;a<t;a++){var r=this.readValue();if(this.readU8())if(this.options.serializeFunctions){var i=this.readValue();this.readValue();try{e[r]=new Function("return "+i)()}catch(t){e[r]=function(){throw new Error("Function deserialization failed")}}}else this.readU8()===$e&&(e[r]=function(){throw new Error("Function not serialized")});else e[r]=this.readValue()}}fillConstructorObject(e){var t=this.readValue(),r=this.readVarint();for(let t=0;t<r;t++)e[this.readValue()]=this.readValue();Object.defineProperty(e,"__constructorName",{value:t,enumerable:!1,writable:!1,configurable:!0})}fillCollection(e,t){var r=this.readVarint();switch(t){case Ae:for(let t=0;t<r;t++){var i=this.readValue(),a=this.readValue();e.set(i,a)}break;case _e:for(let t=0;t<r;t++)e.add(this.readValue())}}readPrimitive(e){switch(e){case v:return null;case b:return;case A:return!1;case _:return!0;default:throw new Error("Unknown primitive: 0x"+e.toString(16))}}readNumber(e){switch(e){case S:return this.view.getInt8(this.pos++);case E:return this.readI16();case U:return this.readI32();case D:return this.readU32();case k:return this.readF32();case x:return this.readF64();case I:return NaN;case O:return 1/0;case V:return-1/0;case B:return-0;case C:var t=this.readVarint();return this.readU8()?-t:t;default:throw new Error("Unknown number type: 0x"+e.toString(16))}}readBigInt(e){switch(e){case z:case P:return this.readBigInt64();case M:case T:return this.readLargeBigInt(e==T);default:throw new Error("Unknown BigInt type: 0x"+e.toString(16))}}readLargeBigInt(e){var t=this.readVarint(),r=(this.ensureBytes(t),this.buffer.subarray(this.pos,this.pos+t));this.pos+=t;let i="";for(let e=r.length-1;0<=e;e--)i+=r[e].toString(16).padStart(2,"0");return t=BigInt("0x"+i),e?-t:t}readString(e){if(e==L)return"";let t,r;switch(e){case j:case F:case N:case $:t=this.readU8();break;default:t=this.readVarint()}if(this.ensureBytes(t),e==j||e==F||e==R){r="";for(let e=0;e<t;e++)r+=String.fromCharCode(this.readU8())}else e=this.buffer.subarray(this.pos,this.pos+t),this.pos+=t,r=this.decoder.decode(e);return this.deserializeStrings.push(r),r}readPackedArrayData(e){var t=this.readVarint(),r=new Array(t),i=qe[e];if(!i)throw new Error("Unknown packed array type: 0x"+e.toString(16));switch(this.alignPos(Math.min(i,8)),this.ensureBytes(t*i),e){case G:for(let e=0;e<t;e++)r[e]=this.view.getInt8(this.pos++);break;case Y:for(let e=0;e<t;e++)r[e]=this.view.getInt16(this.pos,!0),this.pos+=2;break;case J:for(let e=0;e<t;e++)r[e]=this.view.getInt32(this.pos,!0),this.pos+=4;break;case X:for(let e=0;e<t;e++)r[e]=this.view.getFloat32(this.pos,!0),this.pos+=4;break;case Z:for(let e=0;e<t;e++)r[e]=this.view.getFloat64(this.pos,!0),this.pos+=8}return r}readTypedArray(e){if(this.readU8()){var t=this.readVarint(),r=this.readVarint(),i=this.readVarint();if(t>=this.deserializeBuffers.length)throw new Error("Invalid buffer reference: "+t);return t=this.deserializeBuffers[t],this.createTypedArray(e,t,r,i)}this.readVarint();var a=this.readVarint();t=qe[e]||1;if(e!=we&&e!=me)return r=a*t,this.alignPos(t),this.ensureBytes(r),i=this.buffer.subarray(this.pos,this.pos+r),this.pos+=r,t=new ArrayBuffer(r),new Uint8Array(t).set(i),this.deserializeBuffers.push(t),this.createTypedArray(e,t,0,a);this.alignPos(8);var s=[];for(let e=0;e<a;e++)s.push(this.readBigInt64());return new(e==we?BigInt64Array:BigUint64Array)(s)}createTypedArray(e,t,r,i){var a={[ne]:Uint8Array,[oe]:Int8Array,[ce]:Uint8ClampedArray,[he]:Uint16Array,[le]:Int16Array,[ue]:Uint32Array,[de]:Int32Array,[fe]:Float32Array,[pe]:Float64Array,[we]:BigInt64Array,[me]:BigUint64Array,[ye]:DataView}[e];if(a)return new a(t,r,i);throw new Error("Unknown typed array type: 0x"+e.toString(16))}readArrayBuffer(e){var t=this.readVarint(),r=(this.ensureBytes(t),this.buffer.subarray(this.pos,this.pos+t));this.pos+=t,t=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);return this.deserializeBuffers.push(t),t}readDate(e){switch(e){case Se:return new Date(this.readF64());case Ee:return new Date(NaN);default:throw new Error("Unknown date type: 0x"+e.toString(16))}}readError(e){var t=this.readValue(),r=this.readValue();let i;var a={[Ue]:Error,[De]:EvalError,[ke]:RangeError,[xe]:ReferenceError,[Ie]:SyntaxError,[Oe]:TypeError,[Ve]:URIError}[e]||Error;if(e==Be){var s=this.readVarint(),n=[];for(let e=0;e<s;e++)n.push(this.readValue());i=new AggregateError(n,t)}else i=new a(t);return r&&(i.stack=r),i}readRegExp(){var e=this.readValue(),t=this.readValue();return new RegExp(e,t)}readBinary(e){return{_type:"Binary",size:this.readVarint(),typeStr:this.readVarint()}}readSpecial(e){switch(e){case je:var t=this.readValue();return Symbol(t);case Ne:return Symbol();case Fe:return t=this.readValue(),Symbol.for(t);case Re:return t=this.readValue(),We.get(t)||Symbol(t);default:throw new Error("Unknown special type: 0x"+e.toString(16))}}readExtension(e){if(e!==$e)throw new Error("Unknown extension type: 0x"+e.toString(16));return function(){throw new Error("Function not serialized")}}readU8(){return this.ensureBytes(1),this.buffer[this.pos++]}readI16(){this.alignPos(2),this.ensureBytes(2);var e=this.view.getInt16(this.pos,!0);return this.pos+=2,e}readU16(){this.alignPos(2),this.ensureBytes(2);var e=this.view.getUint16(this.pos,!0);return this.pos+=2,e}readI32(){this.alignPos(4),this.ensureBytes(4);var e=this.view.getInt32(this.pos,!0);return this.pos+=4,e}readU32(){this.alignPos(4),this.ensureBytes(4);var e=this.view.getUint32(this.pos,!0);return this.pos+=4,e}readF32(){this.alignPos(4),this.ensureBytes(4);var e=this.view.getFloat32(this.pos,!0);return this.pos+=4,e}readF64(){this.alignPos(8),this.ensureBytes(8);var e=this.view.getFloat64(this.pos,!0);return this.pos+=8,e}readBigInt64(){this.alignPos(8),this.ensureBytes(8);var e=this.view.getBigInt64(this.pos,!0);return this.pos+=8,e}readVarint(){let e=0,t=0;for(var r;this.ensureBytes(1),e|=(127&(r=this.buffer[this.pos++]))<<t,t+=7,128&r;);return e>>>0}alignPos(e){e=e-1|0,this.pos=(this.pos+e&~e)>>>0}ensureBytes(e){if(this.pos+e>this.buffer.length)throw new Error(`Buffer underflow: need ${e}, available `+(this.buffer.length-this.pos))}}},function(e,t){var r={},i=new Float32Array(4);function a(e,t){if((0|e)!==e)throw new TypeError("Lane index must be an int32");if(e<0||t<=e)throw new RangeError("Lane index must be in bounds")}new Int32Array(i.buffer),new Int16Array(i.buffer),new Int8Array(i.buffer),new Uint32Array(i.buffer),new Uint16Array(i.buffer),new Uint8Array(i.buffer),void 0!==r.Int8x16&&void 0!==r.Int8x16.extractLane||(r.Int8x16=function(e,t,i,a,s,n,o,c,h,l,u,d,f,p,w,m){if(!(this instanceof r.Int8x16))return new r.Int8x16(e,t,i,a,s,n,o,c,h,l,u,d,f,p,w,m);this.s_=new Int8Array([e,t,i,a,s,n,o,c,h,l,u,d,f,p,w,m])},r.Int8x16.check=function(e){if(e instanceof r.Int8x16)return e;throw new TypeError("Argument is not a Int8x16.")},r.Int8x16.splat=function(e){return new r.Int8x16(e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e)},r.Int8x16.extractLane=function(e,t){return e=r.Int8x16.check(e),a(t,16),e.s_[t]},r.Int8x16.replaceLane=function(e,t,i){return e=r.Int8x16.check(e),a(t,16),(e=Array.from(e.s_))[t]=i,new r.Int8x16(...e)},r.Int8x16.shuffle=function(e,t,i,s,n,o,c,h,l,u,d,f,p,w,m,y,g,v){var b=[i,s,n,o,c,h,l,u,d,f,p,w,m,y,g,v],A=[];e=r.Int8x16.check(e),t=r.Int8x16.check(t);for(var _=0;_<16;_++){var S=b[_];a(S,32),A[_]=S<16?e.s_[S]:t.s_[S-16]}return new r.Int8x16(...A)}),void 0!==r.Uint8x16&&void 0!==r.Uint8x16.extractLane||(r.Uint8x16=function(e,t,i,a,s,n,o,c,h,l,u,d,f,p,w,m){if(!(this instanceof r.Uint8x16))return new r.Uint8x16(e,t,i,a,s,n,o,c,h,l,u,d,f,p,w,m);this.s_=new Uint8Array([e,t,i,a,s,n,o,c,h,l,u,d,f,p,w,m])},r.Uint8x16.check=function(e){if(e instanceof r.Uint8x16)return e;throw new TypeError("Argument is not a Uint8x16.")},r.Uint8x16.splat=function(e){return new r.Uint8x16(e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e)},r.Uint8x16.extractLane=function(e,t){return e=r.Uint8x16.check(e),a(t,16),e.s_[t]},r.Uint8x16.load=function(e,t){if(t<0||t*e.BYTES_PER_ELEMENT+16>e.byteLength)throw new RangeError("The value of index is invalid.");return new r.Uint8x16(...e.subarray(t,t+16))},r.Uint8x16.store=function(e,t,r){if(t<0||t*e.BYTES_PER_ELEMENT+16>e.byteLength)throw new RangeError("The value of index is invalid.");return e.set(r.s_,t),r},r.Uint8x16.shuffle=function(e,t,i,s,n,o,c,h,l,u,d,f,p,w,m,y,g,v){var b=[i,s,n,o,c,h,l,u,d,f,p,w,m,y,g,v],A=[];e=r.Uint8x16.check(e),t=r.Uint8x16.check(t);for(var _=0;_<16;_++){var S=b[_];a(S,32),A[_]=S<16?e.s_[S]:t.s_[S-16]}return new r.Uint8x16(...A)},r.Uint8x16.and=function(e,t){for(var i=[],a=0;a<16;++a)i[a]=e.s_[a]&t.s_[a];return new r.Uint8x16(...i)},r.Uint8x16.or=function(e,t){for(var i=[],a=0;a<16;++a)i[a]=e.s_[a]|t.s_[a];return new r.Uint8x16(...i)},r.Uint8x16.shiftLeftByScalar=function(e,t){for(var i=[],a=0;a<16;++a)i[a]=e.s_[a]<<t;return new r.Uint8x16(...i)},r.Uint8x16.shiftRightByScalar=function(e,t){for(var i=[],a=0;a<16;++a)i[a]=e.s_[a]>>>t;return new r.Uint8x16(...i)}),e.exports=class{constructor(){this.ENC_SHUFFLE=r.Int8x16(10,11,9,10,7,8,6,7,4,5,3,4,1,2,0,1),this.ENC_LUT="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",this.ENC_LUT_SIMD=[r.Uint8x16.splat(0),r.Uint8x16.splat(0),r.Uint8x16.splat(0),r.Uint8x16.splat(0)];for(let t=0;t<4;t++){var e=this.ENC_LUT.substring(16*t,16*(t+1));this.ENC_LUT_SIMD[t]=r.Uint8x16(...Array.from(e).map(e=>e.charCodeAt(0)))}this.DEC_DELTA_ASSO=r.Uint8x16(1,1,1,1,1,1,1,1,0,0,0,0,0,15,0,15),this.DEC_DELTA_VALUES=r.Int8x16(0,0,0,19,4,191,191,185,185,0,16,195,191,191,185,185),this.DEC_SHUFFLE=r.Int8x16(-1,-1,-1,-1,12,13,14,8,9,10,4,5,6,0,1,2),this.SCALAR_ENC_LUT="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",this.SCALAR_DEC_LUT={};for(let e=0;e<this.SCALAR_ENC_LUT.length;e++)this.SCALAR_DEC_LUT[this.SCALAR_ENC_LUT.charAt(e)]=e;this.SCALAR_DEC_LUT["="]=0}_scalar_encode(e){let t="";for(let s=0;s<e.length;s+=3){var r=e[s],i=s+1<e.length?e[s+1]:0,a=s+2<e.length?e[s+2]:0;t+=this.SCALAR_ENC_LUT[r>>2]+this.SCALAR_ENC_LUT[(3&r)<<4|i>>4],s+1<e.length?t+=this.SCALAR_ENC_LUT[(15&i)<<2|a>>6]:t+="=",s+2<e.length?t+=this.SCALAR_ENC_LUT[63&a]:t+="="}return t}encode(e){var t=e.length,r=4*Math.ceil(t/3),i=new Uint8Array(r);let a=0,s=0;for(;a+12<=t;){var n=e.subarray(a,a+12),o=new Uint8Array(16);o[0]=n[0]>>2,o[1]=(3&n[0])<<4|n[1]>>4,o[2]=(15&n[1])<<2|n[2]>>6,o[3]=63&n[2],o[4]=n[3]>>2,o[5]=(3&n[3])<<4|n[4]>>4,o[6]=(15&n[4])<<2|n[5]>>6,o[7]=63&n[5],o[8]=n[6]>>2,o[9]=(3&n[6])<<4|n[7]>>4,o[10]=(15&n[7])<<2|n[8]>>6,o[11]=63&n[8],o[12]=n[9]>>2,o[13]=(3&n[9])<<4|n[10]>>4,o[14]=(15&n[10])<<2|n[11]>>6,o[15]=63&n[11];for(let e=0;e<16;e++)i[s+e]=this.SCALAR_ENC_LUT.charCodeAt(o[e]);a+=12,s+=16}let c=(new TextDecoder).decode(i.subarray(0,s));return a<t&&(c+=this._scalar_encode(e.subarray(a))),c}_scalar_decode(e){e=e.replace(/=+$/,"");var t=Math.floor(3*e.length/4),r=new Uint8Array(t);let i=0;for(let c=0;c<e.length;c+=4){var a=this.SCALAR_DEC_LUT[e[c]],s=this.SCALAR_DEC_LUT[e[c+1]],n=c+2<e.length?this.SCALAR_DEC_LUT[e[c+2]]:0,o=c+3<e.length?this.SCALAR_DEC_LUT[e[c+3]]:0;r[i++]=a<<2|s>>4,i<t&&(r[i++]=(15&s)<<4|n>>2),i<t&&(r[i++]=(3&n)<<6|o)}return r}decode(e){var t=e.length;if(t%4!=0)throw new Error("Invalid Base64 string length.");var r=(e.match(/=/g)||[]).length,i=new Uint8Array(3*t/4-r);let a=0,s=0;for(var n;a+16<=t-r;){var o=Array.from(e.substring(a,a+16)).map(e=>this.SCALAR_DEC_LUT[e]),c=new Uint8Array(12);c[0]=o[0]<<2|o[1]>>4,c[1]=(15&o[1])<<4|o[2]>>2,c[2]=(3&o[2])<<6|o[3],c[3]=o[4]<<2|o[5]>>4,c[4]=(15&o[5])<<4|o[6]>>2,c[5]=(3&o[6])<<6|o[7],c[6]=o[8]<<2|o[9]>>4,c[7]=(15&o[9])<<4|o[10]>>2,c[8]=(3&o[10])<<6|o[11],c[9]=o[12]<<2|o[13]>>4,c[10]=(15&o[13])<<4|o[14]>>2,c[11]=(3&o[14])<<6|o[15],i.set(c,s),a+=16,s+=12}return a<t&&(n=this._scalar_decode(e.substring(a)),i.set(n,s)),i}}},function(e,t,r){r.r(t),t=r(0),"undefined"!=typeof window?(window.Database=t.Database,window.Collection=t.Collection,window.Document=t.Document,window.QueryOperators=t.QueryOperators,window.AggregationPipeline=t.AggregationPipeline,window.MigrationManager=t.MigrationManager,window.PerformanceMonitor=t.PerformanceMonitor,window.LacertaDBError=t.LacertaDBError,window.lacertaDBInstance=lacertaDBInstance):(self.Database=t.Database,self.Collection=t.Collection,self.Document=t.Document,self.QueryOperators=t.QueryOperators,self.AggregationPipeline=t.AggregationPipeline,self.MigrationManager=t.MigrationManager,self.PerformanceMonitor=t.PerformanceMonitor,self.LacertaDBError=t.LacertaDBError,self.lacertaDBInstance=lacertaDBInstance)}]);
|