-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
2101 lines (1784 loc) · 67.8 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
The MIT License (MIT)
Copyright (c) 2024 Matias Affolter
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
"use strict";
import JOYSON from "joyson";
class OPFSUtility {
/**
* Save attachments to the file system.
* @param {string} dbName - The database name.
* @param {string} collectionName - The collection name.
* @param {string} documentId - The ID of the document.
* @param {Array} attachments - Array of attachment objects with `data` property (Blob or File).
* @returns {Promise<Array>} - Array of file paths where attachments are stored.
*/
static async saveAttachments(dbName, collectionName, documentId, attachments) {
const attachmentPaths = [];
// Ensure OPFS is available
const rootHandle = await navigator.storage.getDirectory();
// Build the directory path
const pathParts = [dbName, collectionName, documentId];
// Navigate to the document directory
let dirHandle = rootHandle;
for (const part of pathParts) {
dirHandle = await dirHandle.getDirectoryHandle(part, { create: true });
}
// Save each attachment
for (let i = 0; i < attachments.length; i++) {
const fileId = i.toString(); // Use index as file ID
const fileHandle = await dirHandle.getFileHandle(fileId, { create: true });
const writable = await fileHandle.createWritable();
await writable.write(attachments[i].data);
await writable.close();
// Store the path
const filePath = `${dbName}/${collectionName}/${documentId}/${fileId}`;
attachmentPaths.push(filePath);
}
return attachmentPaths;
}
/**
* Retrieve attachments from the file system.
* @param {Array} attachmentPaths - Array of file paths to retrieve attachments from.
* @returns {Promise<Array>} - Array of attachment objects with `data` property (Blob).
*/
static async getAttachments(attachmentPaths) {
const attachments = [];
// Ensure OPFS is available
const rootHandle = await navigator.storage.getDirectory();
for (const path of attachmentPaths) {
try {
// Split the path to navigate
const pathParts = path.split('/');
let dirHandle = rootHandle;
for (let i = 0; i < pathParts.length - 1; i++) {
dirHandle = await dirHandle.getDirectoryHandle(pathParts[i]);
}
const fileHandle = await dirHandle.getFileHandle(pathParts[pathParts.length - 1]);
const file = await fileHandle.getFile();
attachments.push({
path: path,
data: file,
});
} catch (error) {
console.error(`Error retrieving attachment at "${path}": ${error.message}`);
}
}
return attachments;
}
/**
* Delete attachments from the file system.
* @param {string} dbName - The database name.
* @param {string} collectionName - The collection name.
* @param {string} documentId - The ID of the document.
* @returns {Promise<void>}
*/
static async deleteAttachments(dbName, collectionName, documentId) {
// Ensure OPFS is available
const rootHandle = await navigator.storage.getDirectory();
// Build the directory path
const pathParts = [dbName, collectionName, documentId];
// Navigate to the parent directory
let dirHandle = rootHandle;
for (let i = 0; i < pathParts.length - 1; i++) {
dirHandle = await dirHandle.getDirectoryHandle(pathParts[i]);
}
try {
await dirHandle.removeEntry(pathParts[pathParts.length - 1], { recursive: true });
} catch (error) {
console.error(`Error deleting attachments for document "${documentId}": ${error.message}`);
}
}
}
class BrowserCompressionUtility {
/**
* Compress a string or Uint8Array using Gzip.
* @param {Uint8Array|string} input - The input data to compress.
* @returns {Promise<Uint8Array>} - A promise that resolves to the compressed data as a Uint8Array.
*/
static async compress(input) {
const data = typeof input === "string" ? new TextEncoder().encode(input) : input;
const stream = new CompressionStream('deflate');
const writer = stream.writable.getWriter();
writer.write(data);
writer.close();
return await this._streamToUint8Array(stream.readable);
}
/**
* Decompress a Gzip-compressed Uint8Array.
* @param {Uint8Array} compressedData - The compressed data to decompress.
* @returns {Promise<Uint8Array>} - A promise that resolves to the decompressed data as a Uint8Array.
*/
static async decompress(compressedData) {
const stream = new DecompressionStream('deflate');
const writer = stream.writable.getWriter();
writer.write(compressedData);
writer.close();
return await this._streamToUint8Array(stream.readable);
}
/**
* Helper function to convert a ReadableStream to a Uint8Array.
* @param {ReadableStream} readableStream - The readable stream to convert.
* @returns {Promise<Uint8Array>} - A promise that resolves to a Uint8Array.
*/
static async _streamToUint8Array(readableStream) {
const reader = readableStream.getReader();
const chunks = [];
let totalLength = 0;
// Read all chunks from the stream
while (true) {
const { value, done } = await reader.read();
if (done) break;
chunks.push(value);
totalLength += value.length;
}
// Merge all chunks into a single Uint8Array
const result = new Uint8Array(totalLength);
let offset = 0;
for (const chunk of chunks) {
result.set(chunk, offset);
offset += chunk.length;
}
return result;
}
}
class BrowserEncryptionUtility {
/**
* Encrypt data using multiple layers of encryption, returning everything as a single Uint8Array.
* @param {Uint8Array} data - The data to be encrypted.
* @param {string} password - The password to derive the encryption key.
* @returns {Promise<Uint8Array>} - A Uint8Array containing IV, salt, and encrypted data.
*/
static async encrypt(data, password) {
// Generate salt and derive key from the password
const salt = crypto.getRandomValues(new Uint8Array(16)); // Random salt
const key = await this._deriveKey(password, salt);
// Generate IV for AES-GCM
const iv = crypto.getRandomValues(new Uint8Array(12)); // Random IV
// Add a checksum to the data for integrity
const checksum = await this._generateChecksum(data);
const combinedData = this._combineDataAndChecksum(data, checksum);
// First layer of AES-GCM encryption
const encryptedData = await crypto.subtle.encrypt(
{ name: "AES-GCM", iv: iv },
key,
combinedData // Data + checksum
);
// Wrap everything into a Uint8Array: [salt, iv, encryptedData]
return this._wrapIntoUint8Array(salt, iv, new Uint8Array(encryptedData));
}
/**
* Decrypt data, verifying integrity with a checksum, and return the original Uint8Array.
* @param {Uint8Array} wrappedData - The Uint8Array that contains the salt, IV, and encrypted data.
* @param {string} password - The password to derive the decryption key.
* @returns {Promise<Uint8Array>} - The original decrypted data.
*/
static async decrypt(wrappedData, password) {
// Extract the salt, IV, and encrypted data from the Uint8Array
const { salt, iv, encryptedData } = this._unwrapUint8Array(wrappedData);
// Derive the key using the same salt
const key = await this._deriveKey(password, salt);
// Decrypt the data
const decryptedData = await crypto.subtle.decrypt(
{ name: "AES-GCM", iv: iv },
key,
encryptedData
);
// Separate the checksum and the original data
const decryptedUint8Array = new Uint8Array(decryptedData);
const { data, checksum } = this._separateDataAndChecksum(decryptedUint8Array);
// Verify the checksum to ensure data integrity
const validChecksum = await this._generateChecksum(data);
if (!this._verifyChecksum(validChecksum, checksum)) {
throw new Error("Data integrity check failed. The data has been tampered with.");
}
// Return the original data
return data;
}
// Private method to derive a cryptographic key from the password and salt
static async _deriveKey(password, salt) {
const encoder = new TextEncoder();
const keyMaterial = await crypto.subtle.importKey(
"raw",
encoder.encode(password), // Password converted to Uint8Array
{ name: "PBKDF2" },
false,
["deriveKey"]
);
// Derive a key using PBKDF2
return await crypto.subtle.deriveKey(
{
name: "PBKDF2",
salt: salt, // Salt
iterations: 150000, // Increased iterations for stronger security
hash: "SHA-512" // Using SHA-512 for key derivation
},
keyMaterial,
{
name: "AES-GCM",
length: 256 // AES-GCM with a 256-bit key
},
false,
["encrypt", "decrypt"]
);
}
// Private method to generate a checksum using SHA-256
static async _generateChecksum(data) {
return new Uint8Array(
await crypto.subtle.digest("SHA-256", data) // Generate SHA-256 hash
);
}
// Verify the checksum
static _verifyChecksum(generatedChecksum, originalChecksum) {
if (generatedChecksum.length !== originalChecksum.length) return false;
for (let i = 0; i < generatedChecksum.length; i++) {
if (generatedChecksum[i] !== originalChecksum[i]) {
return false;
}
}
return true;
}
// Combine the checksum and data
static _combineDataAndChecksum(data, checksum) {
const combined = new Uint8Array(data.length + checksum.length);
combined.set(data); // Set original data first
combined.set(checksum, data.length); // Append checksum
return combined;
}
// Separate the checksum and data after decryption
static _separateDataAndChecksum(combinedData) {
const dataLength = combinedData.length - 32; // SHA-256 checksum is 32 bytes
const data = combinedData.slice(0, dataLength);
const checksum = combinedData.slice(dataLength);
return { data, checksum };
}
// Wrap salt, IV, and encrypted data into a single Uint8Array
static _wrapIntoUint8Array(salt, iv, encryptedData) {
const result = new Uint8Array(salt.length + iv.length + encryptedData.length);
result.set(salt, 0); // Add salt at the beginning
result.set(iv, salt.length); // Add IV after salt
result.set(encryptedData, salt.length + iv.length); // Add encrypted data
return result;
}
// Unwrap salt, IV, and encrypted data from a Uint8Array
static _unwrapUint8Array(wrappedData) {
const salt = wrappedData.slice(0, 16); // First 16 bytes are salt
const iv = wrappedData.slice(16, 28); // Next 12 bytes are IV (16+12=28)
const encryptedData = wrappedData.slice(28); // Remaining bytes are the encrypted data
return { salt, iv, encryptedData };
}
}
class IndexedDBUtility {
/**
* Open or create a new IndexedDB database.
* @param {string} dbName - The name of the database.
* @param {number} version - The version of the database.
* @param {function} upgradeCallback - Callback function for handling upgrades.
* @returns {Promise<IDBDatabase>} - Resolves with the opened database.
*/
static openDatabase(dbName, version = null, upgradeCallback = null) {
return new Promise((resolve, reject) => {
let request;
if (version) {
request = indexedDB.open(dbName, version);
} else {
request = indexedDB.open(dbName);
}
request.onupgradeneeded = (event) => {
const db = event.target.result;
const oldVersion = event.oldVersion;
const newVersion = event.newVersion;
console.log(`Upgrading database "${dbName}" from version ${oldVersion} to ${newVersion}`);
// Execute the upgrade callback, allowing creation or modification of object stores
if (upgradeCallback) {
upgradeCallback(db, oldVersion, newVersion);
}
};
request.onsuccess = (event) => {
const db = event.target.result;
// Handle the database close event
db.onclose = () => {
console.log(`Database "${dbName}" connection is closing.`);
};
// Resolve with the opened database instance
resolve(db);
};
request.onerror = (event) => {
// Reject if an error occurs while opening the database
reject(new Error(`Failed to open database "${dbName}": ${event.target.error.message}`));
};
});
}
/**
* Perform a transaction on the specified object store with retries.
* @param {IDBDatabase} db - The IndexedDB instance.
* @param {string|string[]} storeNames - List of store names or a single store name.
* @param {string} mode - Transaction mode ("readonly", "readwrite").
* @param {function} callback - Callback function to perform the transaction.
* @param {number} retries - Number of retry attempts in case of failure.
* @returns {Promise<any>} - Resolves with the result of the transaction.
*/
static async performTransaction(db, storeNames, mode, callback, retries = 3) {
try {
if (!db) {
throw new Error('Database connection is not available.');
}
const tx = db.transaction(Array.isArray(storeNames) ? storeNames : [storeNames], mode);
const stores = Array.isArray(storeNames) ? storeNames.map(name => tx.objectStore(name)) : [tx.objectStore(storeNames)];
const result = await callback(...stores);
return new Promise((resolve, reject) => {
tx.oncomplete = () => resolve(result);
tx.onerror = () => reject(new Error(`Transaction failed: ${tx.error ? tx.error.message : 'unknown error'}`));
});
} catch (error) {
if (retries > 0) {
console.warn(`Transaction failed, retrying... (${retries} attempts left): ${error.message}`);
return this.performTransaction(db, storeNames, mode, callback, retries - 1);
} else {
throw new Error(`Transaction ultimately failed after retries: ${error.message}`);
}
}
}
/**
* Add (insert) a new record into the store. Fails if the record already exists.
* @param {IDBObjectStore} store - The object store to insert the record into.
* @param {any} record - The record to be inserted.
* @returns {Promise<void>} - Resolves when the record is inserted.
*/
static add(store, record) {
return new Promise((resolve, reject) => {
const request = store.add(record);
request.onsuccess = () => resolve();
request.onerror = event => reject(`Failed to insert record: ${event.target.error.message}`);
});
}
/**
* Put (insert or update) a record into the store.
* @param {IDBObjectStore} store - The object store to put the record into.
* @param {any} record - The record to be put.
* @returns {Promise<void>} - Resolves when the record is put.
*/
static put(store, record) {
return new Promise((resolve, reject) => {
const request = store.put(record);
request.onsuccess = () => resolve();
request.onerror = event => reject(`Failed to put record: ${event.target.error.message}`);
});
}
/**
* Delete a record by its key from a store.
* @param {IDBObjectStore} store - The object store to delete the record from.
* @param {any} key - The key of the record to delete.
* @returns {Promise<void>} - Resolves when the record is deleted.
*/
static delete(store, key) {
return new Promise((resolve, reject) => {
const request = store.delete(key);
request.onsuccess = () => resolve();
request.onerror = event => reject(`Failed to delete record: ${event.target.error.message}`);
});
}
/**
* Get a record by its key from a store.
* @param {IDBObjectStore} store - The object store to get the record from.
* @param {any} key - The key of the record to retrieve.
* @returns {Promise<any>} - Resolves with the record if found.
*/
static get(store, key) {
return new Promise((resolve, reject) => {
const request = store.get(key);
request.onsuccess = event => resolve(event.target.result);
request.onerror = event => reject(`Failed to retrieve record with key ${key}: ${event.target.error.message}`);
});
}
/**
* Get all records from a store.
* @param {IDBObjectStore} store - The object store to query.
* @returns {Promise<any[]>} - Resolves with an array of all records.
*/
static getAll(store) {
return new Promise((resolve, reject) => {
const request = store.getAll();
request.onsuccess = event => resolve(event.target.result);
request.onerror = event => reject(`Failed to retrieve records: ${event.target.error.message}`);
});
}
/**
* Count the number of records in a store.
* @param {IDBObjectStore} store - The object store to count records.
* @returns {Promise<number>} - Resolves with the number of records.
*/
static count(store) {
return new Promise((resolve, reject) => {
const request = store.count();
request.onsuccess = event => resolve(event.target.result);
request.onerror = event => reject(`Failed to count records: ${event.target.error.message}`);
});
}
/**
* Clear all records from a store.
* @param {IDBObjectStore} store - The object store to clear.
* @returns {Promise<void>} - Resolves when the store is cleared.
*/
static clear(store) {
return new Promise((resolve, reject) => {
const request = store.clear();
request.onsuccess = () => resolve();
request.onerror = event => reject(`Failed to clear store: ${event.target.error.message}`);
});
}
/**
* Delete an IndexedDB database.
* @param {string} dbName - The name of the database to delete.
* @returns {Promise<void>} - Resolves when the database is deleted.
*/
static deleteDatabase(dbName) {
return new Promise((resolve, reject) => {
const request = indexedDB.deleteDatabase(dbName);
request.onsuccess = () => resolve();
request.onerror = event => reject(`Failed to delete database: ${event.target.error.message}`);
});
}
/**
* Open a cursor to iterate over records in a store.
* @param {IDBObjectStore} store - The object store to open a cursor on.
* @param {function} processCallback - Callback to process each record.
* @returns {Promise<void>} - Resolves when the iteration is complete.
*/
static iterateCursor(store, processCallback) {
return new Promise((resolve, reject) => {
const request = store.openCursor();
request.onsuccess = event => {
const cursor = event.target.result;
if (cursor) {
processCallback(cursor.value, cursor.key);
cursor.continue();
} else {
resolve();
}
};
request.onerror = event => reject(`Cursor iteration failed: ${event.target.error.message}`);
});
}
}
class LocalStorageUtility {
/**
* Get an item from localStorage.
* @param {string} key - The key to retrieve.
* @returns {any} - The parsed value from localStorage.
*/
static getItem(key) {
const value = localStorage.getItem(key);
return value ? JOYSON.parse(value) : null;
}
/**
* Set an item in localStorage.
* @param {string} key - The key to set.
* @param {any} value - The value to store.
*/
static setItem(key, value) {
localStorage.setItem(key, JOYSON.stringify(value));
}
/**
* Remove an item from localStorage.
* @param {string} key - The key to remove.
*/
static removeItem(key) {
localStorage.removeItem(key);
}
/**
* Clear all items from localStorage.
*/
static clear() {
localStorage.clear();
}
}
class DatabaseMetadata {
constructor(dbName) {
this._dbName = dbName;
this._metadataKey = `lacertadb_${this._dbName}_metadata`;
this._collections = new Map();
this._metadata = this._loadMetadata();
}
_loadMetadata() {
const metadata = LocalStorageUtility.getItem(this.metadataKey);
if (metadata) {
// Recreate CollectionMetadata instances
for (const collectionName in metadata.collections) {
const collectionData = metadata.collections[collectionName];
const collectionMetadata = new CollectionMetadata(collectionName, this, collectionData);
this.collections.set(collectionName, collectionMetadata);
}
this.data = metadata;
} else {
this.data = {
name: this._dbName,
collections: {}, // collectionName -> collection metadata data
totalSizeKB: 0,
totalLength: 0,
modifiedAt: Date.now(),
};
}
return this._metadata;
}
// Getter and Setter for data
get data() {
return this._metadata;
}
set data(d) {
this._metadata = d;
}
// Getter for name
get name() {
return this.data.name;
}
// Getter for key
get metadataKey() {
return this._metadataKey;
}
// Getter and Setter for collections
get collections() {
return this._collections;
}
set collections(c) {
this._collections = c;
}
// Getter for totalSizeKB
get totalSizeKB() {
return this.data.totalSizeKB;
}
// Getter for totalLength
get totalLength() {
return this.data.totalLength;
}
// Getter for modifiedAt
get modifiedAt() {
return this.data.modifiedAt;
}
// Get or create CollectionMetadata
getCollectionMetadata(collectionName) {
if (!this.collections.has(collectionName)) {
// Create new CollectionMetadata
const collectionMetadata = new CollectionMetadata(collectionName, this);
this.collections.set(collectionName, collectionMetadata);
this.data.collections[collectionName] = collectionMetadata.getRawMetadata();
this.data.modifiedAt = Date.now();
}
return this.collections.get(collectionName);
}
getCollectionMetadataData(collectionName) {
const metadata = this.getCollectionMetadata(collectionName);
return metadata ? metadata.getRawMetadata(): {}
}
// Remove a collection's metadata
removeCollectionMetadata(collectionName) {
const collectionMetadata = this.collections.get(collectionName);
if (collectionMetadata) {
// Subtract collection's size and length from totals
this.data.totalSizeKB -= collectionMetadata.sizeKB;
this.data.totalLength -= collectionMetadata.length;
// Remove the collection's metadata
this.collections.delete(collectionName);
delete this.data.collections[collectionName];
// Update modifiedAt internally
this.data.modifiedAt = Date.now();
}
}
// Adjust totalSizeKB and totalLength (used by CollectionMetadata)
adjustTotals(sizeKBChange, lengthChange) {
this.data.totalSizeKB += sizeKBChange;
this.data.totalLength += lengthChange;
this.data.modifiedAt = Date.now();
}
// Get all collection names
getCollectionNames() {
return Array.from(this.collections.keys());
}
// Get raw metadata (for saving)
getRawMetadata() {
// Before returning, ensure that collections in _metadata are updated
for (const [collectionName, collectionMetadata] of this._collections.entries()) {
this.data.collections[collectionName] = collectionMetadata.getRawMetadata();
}
return this.data;
}
// Set raw metadata (e.g., after loading)
setRawMetadata(metadata) {
this._metadata = metadata;
// Recreate CollectionMetadata instances
this._collections.clear();
for (const collectionName in metadata.collections) {
const collectionData = metadata.collections[collectionName];
const collectionMetadata = new CollectionMetadata(collectionName, this, collectionData);
this._collections.set(collectionName, collectionMetadata);
}
}
// Accessor methods for private properties (if needed)
get dbName() {
return this._dbName;
}
get key() {
return this._metadataKey;
}
// Method to save metadata
saveMetadata() {
LocalStorageUtility.setItem(this.key, this.getRawMetadata());
}
}
class CollectionMetadata {
constructor(collectionName, databaseMetadata, existingMetadata = null) {
this._collectionName = collectionName;
this._databaseMetadata = databaseMetadata;
if (existingMetadata) {
this._metadata = existingMetadata;
} else {
this._metadata = {
name: collectionName,
sizeKB: 0,
length: 0,
createdAt: Date.now(),
modifiedAt: Date.now(),
documentSizes: {}, // Stores document sizes in KB
documentModifiedAt: {}, // Stores document modification timestamps
documentPermanent: {}, // Stores document permanent flags
documentAttachments: {}, // Stores document attachments
};
// Update databaseMetadata
this._databaseMetadata.data.collections[collectionName] = this._metadata;
this._databaseMetadata.data.modifiedAt = Date.now();
}
}
// Getter for name
get name() {
return this._collectionName;
}
get keys() {
return Object.keys(this.documentSizes);
}
// Getter for collection name
get collectionName() {
return this.name;
}
// Getter for sizeKB
get sizeKB() {
return this._metadata.sizeKB;
}
// Getter for length
get length() {
return this._metadata.length;
}
// Getter for modifiedAt
get modifiedAt() {
return this._metadata.modifiedAt;
}
get metadata() {
return this._metadata;
}
set metadata(m) {
return this._metadata = m;
}
get data() {
return this.metadata;
}
set data(m) {
this.metadata = m;
}
get databaseMetadata() {
return this._databaseMetadata;
}
set databaseMetadata(m) {
this._databaseMetadata = m;
}
// Methods to add, update, delete documents
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(v){ this.metadata.documentSizes = v;}
set documentModifiedAt(v){ this.metadata.documentModifiedAt = v;}
set documentPermanent(v){ this.metadata.documentPermanent = v;}
set documentAttachments(v){ this.metadata.documentAttachments = v;}
// Add or update a document
updateDocument(docId, docSizeKB, isPermanent = false, attachmentCount = 0) {
const isNewDocument = !this.keys.includes(docId);
const previousDocSizeKB = this.documentSizes[docId] || 0;
const sizeKBChange = docSizeKB - previousDocSizeKB;
const lengthChange = isNewDocument ? 1 : 0;
// Update document metadata
this.documentSizes[docId] = docSizeKB;
this.documentModifiedAt[docId] = Date.now();
this.documentPermanent[docId] = isPermanent ? 1 : 0;
this.documentAttachments[docId] = attachmentCount; // Number of attachments
// Update collection metadata
this.metadata.sizeKB += sizeKBChange;
this.metadata.length += lengthChange;
this.metadata.modifiedAt = Date.now();
// Update database totals
this.databaseMetadata.adjustTotals(sizeKBChange, lengthChange);
}
// Delete a document
deleteDocument(docId) {
if (!this.keys.includes(docId)) {
return false;
}
const docSizeKB = this.documentSizes[docId];
const sizeKBChange = -docSizeKB;
const lengthChange = -1;
// Remove document metadata
delete this.documentSizes[docId];
delete this.documentModifiedAt[docId];
delete this.documentPermanent[docId];
delete this.documentAttachments[docId];
// Update collection metadata
this.metadata.sizeKB += sizeKBChange;
this.metadata.length += lengthChange;
this.metadata.modifiedAt = Date.now();
// Update database totals
this.databaseMetadata.adjustTotals(sizeKBChange, lengthChange);
return true;
}
// Batch update documents
updateDocuments(updates) {
// updates is an array of { docId, docSizeKB, isPermanent }
for (const { docId, docSizeKB, isPermanent } of updates) {
this.updateDocument(docId, docSizeKB, isPermanent);
}
}
// Batch delete documents
deleteDocuments(docIds) {
for (const docId of docIds) {
this.deleteDocument(docId);
}
}
// Get raw metadata (for saving)
getRawMetadata() {
return this.metadata;
}
// Set raw metadata (e.g., after loading)
setRawMetadata(metadata) {
this.metadata = metadata;
}
}
class QuickStore {
constructor(dbName) {
this._dbName = dbName;
this._metadataKey = `lacertadb_${this._dbName}_quickstore_`;
this._documentKeyPrefix = 'lacertadb_quickstore_';
this._metadata = this._loadMetadata();
}
_loadMetadata() {
const metadata = LocalStorageUtility.getItem(this._metadataKey);
if (metadata) {
return metadata;
} else {
// Initialize metadata
return {
totalSizeKB: 0,
totalLength: 0,
documentSizesKB: {}, // docId -> sizeKB
documentModificationTime: {}, // docId -> timestamp
documentPermanent: {}, // docId -> boolean
};
}
}
_saveMetadata() {
LocalStorageUtility.setItem(this._metadataKey, this._metadata);
}
async setDocument(documentData, encryptionKey = null) {
const document = new Document(documentData, encryptionKey);
await document.pack(); // Packs the data
const docId = document._id;
const isPermanent = document._permanent || false;
const dataToStore = JOYSON.stringify({
_id: document._id,
_created: document._created,
_modified: document._modified,
_permanent: document._permanent,
_encrypted: document._encrypted,
_compressed: document._compressed,
packedData: document.packedData, // Convert Uint8Array to Array for JSON
});
const key = this._documentKeyPrefix + docId;
localStorage.setItem(key, dataToStore);
const dataSizeKB = dataToStore.length / 1024;
const isNewDocument = !(docId in this._metadata.documentSizesKB);
if (isNewDocument) {
this._metadata.totalLength += 1;
} else {
// Adjust totalSizeKB
this._metadata.totalSizeKB -= this._metadata.documentSizesKB[docId];
}
this._metadata.documentSizesKB[docId] = dataSizeKB;
this._metadata.documentModificationTime[docId] = document._modified;
this._metadata.documentPermanent[docId] = isPermanent;
this._metadata.totalSizeKB += dataSizeKB;
this._saveMetadata();
return isNewDocument;
}
async deleteDocument(docId, force = false) {
const isPermanent = this._metadata.documentPermanent[docId] || false;
if (isPermanent && !force) {
return false;
}
const key = this._documentKeyPrefix + docId;
const docSizeKB = this._metadata.documentSizesKB[docId] || 0;
if (localStorage.getItem(key)) {
localStorage.removeItem(key);
delete this._metadata.documentSizesKB[docId];
delete this._metadata.documentModificationTime[docId];
delete this._metadata.documentPermanent[docId];
this._metadata.totalSizeKB -= docSizeKB;
this._metadata.totalLength -= 1;
this._saveMetadata();
return true;
} else {
return false;
}
}
getAllKeys() {
return Object.keys(this._metadata.documentSizesKB);
}
async getDocument(docId, encryptionKey = null) {
const key = this._documentKeyPrefix + docId;
const dataString = localStorage.getItem(key);