@sv443-network/coreutils 2.0.2 → 3.0.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/CHANGELOG.md +38 -0
- package/README.md +4 -3
- package/dist/CoreUtils.cjs +188 -114
- package/dist/CoreUtils.min.cjs +5 -3
- package/dist/CoreUtils.min.mjs +5 -3
- package/dist/CoreUtils.min.umd.js +5 -3
- package/dist/CoreUtils.mjs +188 -114
- package/dist/CoreUtils.umd.js +196 -120
- package/dist/lib/DataStore.d.ts +23 -9
- package/dist/lib/DataStoreEngine.d.ts +10 -10
- package/dist/lib/DataStoreSerializer.d.ts +3 -1
- package/dist/lib/Debouncer.d.ts +1 -1
- package/dist/lib/Errors.d.ts +15 -3
- package/dist/lib/NanoEmitter.d.ts +7 -6
- package/dist/lib/TieredCache.d.ts +4 -4
- package/dist/lib/Translate.d.ts +1 -1
- package/dist/lib/crypto.d.ts +1 -1
- package/dist/lib/index.d.ts +13 -13
- package/dist/lib/math.d.ts +2 -2
- package/dist/lib/misc.d.ts +7 -1
- package/dist/lib/{TestDataStore.d.ts → test/DirectAccessDataStore.d.ts} +4 -3
- package/dist/lib/test/softExpect.d.ts +11 -0
- package/dist/lib/text.d.ts +1 -1
- package/dist/lib/types.d.ts +7 -0
- package/package.json +18 -18
package/dist/CoreUtils.umd.js
CHANGED
|
@@ -99,6 +99,7 @@ var lib_exports = {};
|
|
|
99
99
|
__export(lib_exports, {
|
|
100
100
|
BrowserStorageEngine: () => BrowserStorageEngine,
|
|
101
101
|
ChecksumMismatchError: () => ChecksumMismatchError,
|
|
102
|
+
CustomError: () => CustomError,
|
|
102
103
|
DataStore: () => DataStore,
|
|
103
104
|
DataStoreEngine: () => DataStoreEngine,
|
|
104
105
|
DataStoreSerializer: () => DataStoreSerializer,
|
|
@@ -107,6 +108,8 @@ __export(lib_exports, {
|
|
|
107
108
|
FileStorageEngine: () => FileStorageEngine,
|
|
108
109
|
MigrationError: () => MigrationError,
|
|
109
110
|
NanoEmitter: () => NanoEmitter,
|
|
111
|
+
NetworkError: () => NetworkError,
|
|
112
|
+
ScriptContextError: () => ScriptContextError,
|
|
110
113
|
ValidationError: () => ValidationError,
|
|
111
114
|
abtoa: () => abtoa,
|
|
112
115
|
atoab: () => atoab,
|
|
@@ -126,6 +129,7 @@ __export(lib_exports, {
|
|
|
126
129
|
digitCount: () => digitCount,
|
|
127
130
|
fetchAdvanced: () => fetchAdvanced,
|
|
128
131
|
formatNumber: () => formatNumber,
|
|
132
|
+
getCallStack: () => getCallStack,
|
|
129
133
|
getListLength: () => getListLength,
|
|
130
134
|
hexToRgb: () => hexToRgb,
|
|
131
135
|
insertValues: () => insertValues,
|
|
@@ -242,7 +246,7 @@ function roundFixed(num, fractionDigits) {
|
|
|
242
246
|
const scale = __pow(10, fractionDigits);
|
|
243
247
|
return Math.round(num * scale) / scale;
|
|
244
248
|
}
|
|
245
|
-
function valsWithin(a, b, dec =
|
|
249
|
+
function valsWithin(a, b, dec = 1, withinRange = 0.5) {
|
|
246
250
|
return Math.abs(roundFixed(a, dec) - roundFixed(b, dec)) <= withinRange;
|
|
247
251
|
}
|
|
248
252
|
|
|
@@ -400,6 +404,52 @@ function randomId(length = 16, radix = 16, enhancedEntropy = false, randomCase =
|
|
|
400
404
|
return arr.map((v) => caseArr[randRange(0, caseArr.length - 1, enhancedEntropy)] === 1 ? v.toUpperCase() : v).join("");
|
|
401
405
|
}
|
|
402
406
|
|
|
407
|
+
// lib/Errors.ts
|
|
408
|
+
var DatedError = class extends Error {
|
|
409
|
+
constructor(message, options) {
|
|
410
|
+
super(message, options);
|
|
411
|
+
__publicField(this, "date");
|
|
412
|
+
this.name = this.constructor.name;
|
|
413
|
+
this.date = /* @__PURE__ */ new Date();
|
|
414
|
+
}
|
|
415
|
+
};
|
|
416
|
+
var ChecksumMismatchError = class extends DatedError {
|
|
417
|
+
constructor(message, options) {
|
|
418
|
+
super(message, options);
|
|
419
|
+
this.name = "ChecksumMismatchError";
|
|
420
|
+
}
|
|
421
|
+
};
|
|
422
|
+
var CustomError = class extends DatedError {
|
|
423
|
+
constructor(name, message, options) {
|
|
424
|
+
super(message, options);
|
|
425
|
+
this.name = name;
|
|
426
|
+
}
|
|
427
|
+
};
|
|
428
|
+
var MigrationError = class extends DatedError {
|
|
429
|
+
constructor(message, options) {
|
|
430
|
+
super(message, options);
|
|
431
|
+
this.name = "MigrationError";
|
|
432
|
+
}
|
|
433
|
+
};
|
|
434
|
+
var ValidationError = class extends DatedError {
|
|
435
|
+
constructor(message, options) {
|
|
436
|
+
super(message, options);
|
|
437
|
+
this.name = "ValidationError";
|
|
438
|
+
}
|
|
439
|
+
};
|
|
440
|
+
var ScriptContextError = class extends DatedError {
|
|
441
|
+
constructor(message, options) {
|
|
442
|
+
super(message, options);
|
|
443
|
+
this.name = "ScriptContextError";
|
|
444
|
+
}
|
|
445
|
+
};
|
|
446
|
+
var NetworkError = class extends DatedError {
|
|
447
|
+
constructor(message, options) {
|
|
448
|
+
super(message, options);
|
|
449
|
+
this.name = "NetworkError";
|
|
450
|
+
}
|
|
451
|
+
};
|
|
452
|
+
|
|
403
453
|
// lib/misc.ts
|
|
404
454
|
function consumeGen(valGen) {
|
|
405
455
|
return __async(this, null, function* () {
|
|
@@ -430,7 +480,7 @@ function fetchAdvanced(_0) {
|
|
|
430
480
|
return res;
|
|
431
481
|
} catch (err) {
|
|
432
482
|
typeof id !== "undefined" && clearTimeout(id);
|
|
433
|
-
throw new
|
|
483
|
+
throw new NetworkError("Error while calling fetch", { cause: err });
|
|
434
484
|
}
|
|
435
485
|
});
|
|
436
486
|
}
|
|
@@ -442,7 +492,7 @@ function pauseFor(time, signal, rejectOnAbort = false) {
|
|
|
442
492
|
const timeout = setTimeout(() => res(), time);
|
|
443
493
|
signal == null ? void 0 : signal.addEventListener("abort", () => {
|
|
444
494
|
clearTimeout(timeout);
|
|
445
|
-
rejectOnAbort ? rej(new
|
|
495
|
+
rejectOnAbort ? rej(new CustomError("AbortError", "The pause was aborted")) : res();
|
|
446
496
|
});
|
|
447
497
|
});
|
|
448
498
|
}
|
|
@@ -477,14 +527,25 @@ function scheduleExit(code = 0, timeout = 0) {
|
|
|
477
527
|
if (timeout < 0)
|
|
478
528
|
throw new TypeError("Timeout must be a non-negative number");
|
|
479
529
|
let exit;
|
|
480
|
-
if (typeof process !== "undefined" && "exit" in process)
|
|
530
|
+
if (typeof process !== "undefined" && "exit" in process && typeof process.exit === "function")
|
|
481
531
|
exit = () => process.exit(code);
|
|
482
|
-
else if (typeof Deno !== "undefined" && "exit" in Deno)
|
|
532
|
+
else if (typeof Deno !== "undefined" && "exit" in Deno && typeof Deno.exit === "function")
|
|
483
533
|
exit = () => Deno.exit(code);
|
|
484
534
|
else
|
|
485
|
-
throw new
|
|
535
|
+
throw new ScriptContextError("Cannot exit the process, no exit method available");
|
|
486
536
|
setTimeout(exit, timeout);
|
|
487
537
|
}
|
|
538
|
+
function getCallStack(asArray, lines = Infinity) {
|
|
539
|
+
var _a;
|
|
540
|
+
if (typeof lines !== "number" || isNaN(lines) || lines < 0)
|
|
541
|
+
throw new TypeError("lines parameter must be a non-negative number");
|
|
542
|
+
try {
|
|
543
|
+
throw new Error("This is to capture a stack trace with CoreUtils.getCallStack(). (If you see this somewhere, you can safely ignore it.)");
|
|
544
|
+
} catch (err) {
|
|
545
|
+
const stack = ((_a = err.stack) != null ? _a : "").split("\n").map((line) => line.trim()).slice(2, lines + 2);
|
|
546
|
+
return asArray !== false ? stack : stack.join("\n");
|
|
547
|
+
}
|
|
548
|
+
}
|
|
488
549
|
|
|
489
550
|
// lib/text.ts
|
|
490
551
|
function autoPlural(term, num, pluralType = "auto") {
|
|
@@ -554,16 +615,18 @@ function joinArrayReadable(array, separators = ", ", lastSeparator = " and ") {
|
|
|
554
615
|
return arr.join(separators) + lastItm;
|
|
555
616
|
}
|
|
556
617
|
function secsToTimeStr(seconds) {
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
const
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
618
|
+
const isNegative = seconds < 0;
|
|
619
|
+
const s = Math.abs(seconds);
|
|
620
|
+
if (isNaN(s) || !isFinite(s))
|
|
621
|
+
throw new TypeError("The seconds argument must be a valid number");
|
|
622
|
+
const hrs = Math.floor(s / 3600);
|
|
623
|
+
const mins = Math.floor(s % 3600 / 60);
|
|
624
|
+
const secs = Math.floor(s % 60);
|
|
625
|
+
return (isNegative ? "-" : "") + [
|
|
626
|
+
hrs ? hrs + ":" : "",
|
|
627
|
+
String(mins).padStart(mins > 0 || hrs > 0 ? 2 : 1, "0"),
|
|
565
628
|
":",
|
|
566
|
-
String(secs).padStart(secs > 0 ||
|
|
629
|
+
String(secs).padStart(secs > 0 || mins > 0 || hrs > 0 || seconds === 0 ? 2 : 1, "0")
|
|
567
630
|
].join("");
|
|
568
631
|
}
|
|
569
632
|
function truncStr(input, length, endStr = "...") {
|
|
@@ -573,37 +636,10 @@ function truncStr(input, length, endStr = "...") {
|
|
|
573
636
|
return finalStr.length > length ? finalStr.substring(0, length) : finalStr;
|
|
574
637
|
}
|
|
575
638
|
|
|
576
|
-
// lib/Errors.ts
|
|
577
|
-
var DatedError = class extends Error {
|
|
578
|
-
constructor(message, options) {
|
|
579
|
-
super(message, options);
|
|
580
|
-
__publicField(this, "date");
|
|
581
|
-
this.name = this.constructor.name;
|
|
582
|
-
this.date = /* @__PURE__ */ new Date();
|
|
583
|
-
}
|
|
584
|
-
};
|
|
585
|
-
var ChecksumMismatchError = class extends DatedError {
|
|
586
|
-
constructor(message, options) {
|
|
587
|
-
super(message, options);
|
|
588
|
-
this.name = "ChecksumMismatchError";
|
|
589
|
-
}
|
|
590
|
-
};
|
|
591
|
-
var MigrationError = class extends DatedError {
|
|
592
|
-
constructor(message, options) {
|
|
593
|
-
super(message, options);
|
|
594
|
-
this.name = "MigrationError";
|
|
595
|
-
}
|
|
596
|
-
};
|
|
597
|
-
var ValidationError = class extends DatedError {
|
|
598
|
-
constructor(message, options) {
|
|
599
|
-
super(message, options);
|
|
600
|
-
this.name = "ValidationError";
|
|
601
|
-
}
|
|
602
|
-
};
|
|
603
|
-
|
|
604
639
|
// lib/DataStore.ts
|
|
605
640
|
var dsFmtVer = 1;
|
|
606
641
|
var DataStore = class {
|
|
642
|
+
//#region constructor
|
|
607
643
|
/**
|
|
608
644
|
* Creates an instance of DataStore to manage a sync & async database that is cached in memory and persistently saved across sessions.
|
|
609
645
|
* Supports migrating data from older versions to newer ones and populating the cache with default data if no persistent data is found.
|
|
@@ -620,6 +656,7 @@ var DataStore = class {
|
|
|
620
656
|
__publicField(this, "encodeData");
|
|
621
657
|
__publicField(this, "decodeData");
|
|
622
658
|
__publicField(this, "compressionFormat", "deflate-raw");
|
|
659
|
+
__publicField(this, "memoryCache", true);
|
|
623
660
|
__publicField(this, "engine");
|
|
624
661
|
__publicField(this, "options");
|
|
625
662
|
/**
|
|
@@ -632,11 +669,12 @@ var DataStore = class {
|
|
|
632
669
|
__publicField(this, "cachedData");
|
|
633
670
|
__publicField(this, "migrations");
|
|
634
671
|
__publicField(this, "migrateIds", []);
|
|
635
|
-
var _a, _b, _c;
|
|
672
|
+
var _a, _b, _c, _d;
|
|
636
673
|
this.id = opts.id;
|
|
637
674
|
this.formatVersion = opts.formatVersion;
|
|
638
675
|
this.defaultData = opts.defaultData;
|
|
639
|
-
this.
|
|
676
|
+
this.memoryCache = Boolean((_a = opts.memoryCache) != null ? _a : true);
|
|
677
|
+
this.cachedData = this.memoryCache ? opts.defaultData : {};
|
|
640
678
|
this.migrations = opts.migrations;
|
|
641
679
|
if (opts.migrateIds)
|
|
642
680
|
this.migrateIds = Array.isArray(opts.migrateIds) ? opts.migrateIds : [opts.migrateIds];
|
|
@@ -645,7 +683,7 @@ var DataStore = class {
|
|
|
645
683
|
this.engine = typeof opts.engine === "function" ? opts.engine() : opts.engine;
|
|
646
684
|
this.options = opts;
|
|
647
685
|
if (typeof opts.compressionFormat === "undefined")
|
|
648
|
-
this.compressionFormat = opts.compressionFormat = (
|
|
686
|
+
this.compressionFormat = opts.compressionFormat = (_c = (_b = opts.encodeData) == null ? void 0 : _b[0]) != null ? _c : "deflate-raw";
|
|
649
687
|
if (typeof opts.compressionFormat === "string") {
|
|
650
688
|
this.encodeData = [opts.compressionFormat, (data) => __async(this, null, function* () {
|
|
651
689
|
return yield compress(data, opts.compressionFormat, "string");
|
|
@@ -656,7 +694,7 @@ var DataStore = class {
|
|
|
656
694
|
} else if ("encodeData" in opts && "decodeData" in opts && Array.isArray(opts.encodeData) && Array.isArray(opts.decodeData)) {
|
|
657
695
|
this.encodeData = [opts.encodeData[0], opts.encodeData[1]];
|
|
658
696
|
this.decodeData = [opts.decodeData[0], opts.decodeData[1]];
|
|
659
|
-
this.compressionFormat = (
|
|
697
|
+
this.compressionFormat = (_d = opts.encodeData[0]) != null ? _d : null;
|
|
660
698
|
} else if (opts.compressionFormat === null) {
|
|
661
699
|
this.encodeData = void 0;
|
|
662
700
|
this.decodeData = void 0;
|
|
@@ -665,7 +703,7 @@ var DataStore = class {
|
|
|
665
703
|
throw new TypeError("Either `compressionFormat` or `encodeData` and `decodeData` have to be set and valid, but not all three at a time. Please refer to the documentation for more info.");
|
|
666
704
|
this.engine.setDataStoreOptions(opts);
|
|
667
705
|
}
|
|
668
|
-
//#region
|
|
706
|
+
//#region loadData
|
|
669
707
|
/**
|
|
670
708
|
* Loads the data saved in persistent storage into the in-memory cache and also returns a copy of it.
|
|
671
709
|
* Automatically populates persistent storage with default data if it doesn't contain any data yet.
|
|
@@ -673,43 +711,45 @@ var DataStore = class {
|
|
|
673
711
|
*/
|
|
674
712
|
loadData() {
|
|
675
713
|
return __async(this, null, function* () {
|
|
714
|
+
var _a;
|
|
676
715
|
try {
|
|
677
716
|
if (this.firstInit) {
|
|
678
717
|
this.firstInit = false;
|
|
679
718
|
const dsVer = Number(yield this.engine.getValue("__ds_fmt_ver", 0));
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
promises.push(this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat));
|
|
698
|
-
yield Promise.allSettled(promises);
|
|
719
|
+
const oldData = yield this.engine.getValue(`_uucfg-${this.id}`, null);
|
|
720
|
+
if (oldData) {
|
|
721
|
+
const oldVer = Number(yield this.engine.getValue(`_uucfgver-${this.id}`, NaN));
|
|
722
|
+
const oldEnc = yield this.engine.getValue(`_uucfgenc-${this.id}`, null);
|
|
723
|
+
const promises = [];
|
|
724
|
+
const migrateFmt = (oldKey, newKey, value) => {
|
|
725
|
+
promises.push(this.engine.setValue(newKey, value));
|
|
726
|
+
promises.push(this.engine.deleteValue(oldKey));
|
|
727
|
+
};
|
|
728
|
+
migrateFmt(`_uucfg-${this.id}`, `__ds-${this.id}-dat`, oldData);
|
|
729
|
+
if (!isNaN(oldVer))
|
|
730
|
+
migrateFmt(`_uucfgver-${this.id}`, `__ds-${this.id}-ver`, oldVer);
|
|
731
|
+
if (typeof oldEnc === "boolean")
|
|
732
|
+
migrateFmt(`_uucfgenc-${this.id}`, `__ds-${this.id}-enf`, oldEnc === true ? (_a = this.compressionFormat) != null ? _a : null : null);
|
|
733
|
+
else {
|
|
734
|
+
promises.push(this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat));
|
|
735
|
+
promises.push(this.engine.deleteValue(`_uucfgenc-${this.id}`));
|
|
699
736
|
}
|
|
700
|
-
yield
|
|
737
|
+
yield Promise.allSettled(promises);
|
|
701
738
|
}
|
|
739
|
+
if (isNaN(dsVer) || dsVer < dsFmtVer)
|
|
740
|
+
yield this.engine.setValue("__ds_fmt_ver", dsFmtVer);
|
|
702
741
|
}
|
|
703
742
|
if (this.migrateIds.length > 0) {
|
|
704
743
|
yield this.migrateId(this.migrateIds);
|
|
705
744
|
this.migrateIds = [];
|
|
706
745
|
}
|
|
707
|
-
const
|
|
746
|
+
const storedDataRaw = yield this.engine.getValue(`__ds-${this.id}-dat`, null);
|
|
708
747
|
let storedFmtVer = Number(yield this.engine.getValue(`__ds-${this.id}-ver`, NaN));
|
|
709
|
-
if (typeof
|
|
748
|
+
if (typeof storedDataRaw !== "string") {
|
|
710
749
|
yield this.saveDefaultData();
|
|
711
|
-
return
|
|
750
|
+
return this.engine.deepCopy(this.defaultData);
|
|
712
751
|
}
|
|
752
|
+
const storedData = storedDataRaw != null ? storedDataRaw : JSON.stringify(this.defaultData);
|
|
713
753
|
const encodingFmt = String(yield this.engine.getValue(`__ds-${this.id}-enf`, null));
|
|
714
754
|
const isEncoded = encodingFmt !== "null" && encodingFmt !== "false";
|
|
715
755
|
let saveData = false;
|
|
@@ -722,7 +762,10 @@ var DataStore = class {
|
|
|
722
762
|
parsed = yield this.runMigrations(parsed, storedFmtVer);
|
|
723
763
|
if (saveData)
|
|
724
764
|
yield this.setData(parsed);
|
|
725
|
-
|
|
765
|
+
if (this.memoryCache)
|
|
766
|
+
return this.cachedData = this.engine.deepCopy(parsed);
|
|
767
|
+
else
|
|
768
|
+
return this.engine.deepCopy(parsed);
|
|
726
769
|
} catch (err) {
|
|
727
770
|
console.warn("Error while parsing JSON data, resetting it to the default value.", err);
|
|
728
771
|
yield this.saveDefaultData();
|
|
@@ -730,16 +773,22 @@ var DataStore = class {
|
|
|
730
773
|
}
|
|
731
774
|
});
|
|
732
775
|
}
|
|
776
|
+
//#region getData
|
|
733
777
|
/**
|
|
734
778
|
* Returns a copy of the data from the in-memory cache.
|
|
735
|
-
* Use {@linkcode loadData()} to get fresh data from persistent storage (usually not necessary since the cache should always exactly reflect persistent storage).
|
|
779
|
+
* Use {@linkcode loadData()} to get fresh data from persistent storage (usually not necessary since the cache should always exactly reflect persistent storage).
|
|
780
|
+
* ⚠️ If `memoryCache` was set to `false` in the constructor options, this method will throw an error.
|
|
736
781
|
*/
|
|
737
782
|
getData() {
|
|
783
|
+
if (!this.memoryCache)
|
|
784
|
+
throw new DatedError("In-memory cache is disabled for this DataStore instance, so getData() can't be used. Please use loadData() instead.");
|
|
738
785
|
return this.engine.deepCopy(this.cachedData);
|
|
739
786
|
}
|
|
787
|
+
//#region setData
|
|
740
788
|
/** Saves the data synchronously to the in-memory cache and asynchronously to the persistent storage */
|
|
741
789
|
setData(data) {
|
|
742
|
-
this.
|
|
790
|
+
if (this.memoryCache)
|
|
791
|
+
this.cachedData = data;
|
|
743
792
|
return new Promise((resolve) => __async(this, null, function* () {
|
|
744
793
|
yield Promise.allSettled([
|
|
745
794
|
this.engine.setValue(`__ds-${this.id}-dat`, yield this.engine.serializeData(data, this.encodingEnabled())),
|
|
@@ -749,10 +798,12 @@ var DataStore = class {
|
|
|
749
798
|
resolve();
|
|
750
799
|
}));
|
|
751
800
|
}
|
|
801
|
+
//#region saveDefaultData
|
|
752
802
|
/** Saves the default data passed in the constructor synchronously to the in-memory cache and asynchronously to persistent storage */
|
|
753
803
|
saveDefaultData() {
|
|
754
804
|
return __async(this, null, function* () {
|
|
755
|
-
|
|
805
|
+
if (this.memoryCache)
|
|
806
|
+
this.cachedData = this.defaultData;
|
|
756
807
|
yield Promise.allSettled([
|
|
757
808
|
this.engine.setValue(`__ds-${this.id}-dat`, yield this.engine.serializeData(this.defaultData, this.encodingEnabled())),
|
|
758
809
|
this.engine.setValue(`__ds-${this.id}-ver`, this.formatVersion),
|
|
@@ -760,6 +811,7 @@ var DataStore = class {
|
|
|
760
811
|
]);
|
|
761
812
|
});
|
|
762
813
|
}
|
|
814
|
+
//#region deleteData
|
|
763
815
|
/**
|
|
764
816
|
* Call this method to clear all persistently stored data associated with this DataStore instance, including the storage container (if supported by the DataStoreEngine).
|
|
765
817
|
* The in-memory cache will be left untouched, so you may still access the data with {@linkcode getData()}
|
|
@@ -776,11 +828,12 @@ var DataStore = class {
|
|
|
776
828
|
yield (_b = (_a = this.engine).deleteStorage) == null ? void 0 : _b.call(_a);
|
|
777
829
|
});
|
|
778
830
|
}
|
|
831
|
+
//#region encodingEnabled
|
|
779
832
|
/** Returns whether encoding and decoding are enabled for this DataStore instance */
|
|
780
833
|
encodingEnabled() {
|
|
781
834
|
return Boolean(this.encodeData && this.decodeData) && this.compressionFormat !== null || Boolean(this.compressionFormat);
|
|
782
835
|
}
|
|
783
|
-
//#region
|
|
836
|
+
//#region runMigrations
|
|
784
837
|
/**
|
|
785
838
|
* Runs all necessary migration functions consecutively and saves the result to the in-memory cache and persistent storage and also returns it.
|
|
786
839
|
* This method is automatically called by {@linkcode loadData()} if the data format has changed since the last time the data was saved.
|
|
@@ -815,9 +868,13 @@ var DataStore = class {
|
|
|
815
868
|
this.engine.setValue(`__ds-${this.id}-ver`, lastFmtVer),
|
|
816
869
|
this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat)
|
|
817
870
|
]);
|
|
818
|
-
|
|
871
|
+
if (this.memoryCache)
|
|
872
|
+
return this.cachedData = this.engine.deepCopy(newData);
|
|
873
|
+
else
|
|
874
|
+
return this.engine.deepCopy(newData);
|
|
819
875
|
});
|
|
820
876
|
}
|
|
877
|
+
//#region migrateId
|
|
821
878
|
/**
|
|
822
879
|
* Tries to migrate the currently saved persistent data from one or more old IDs to the ID set in the constructor.
|
|
823
880
|
* If no data exist for the old ID(s), nothing will be done, but some time may still pass trying to fetch the non-existent data.
|
|
@@ -863,7 +920,7 @@ var DataStoreEngine = class {
|
|
|
863
920
|
this.dataStoreOptions = dataStoreOptions;
|
|
864
921
|
}
|
|
865
922
|
//#region serialization api
|
|
866
|
-
/** Serializes the given object to a string, optionally encoded with `options.encodeData` if {@linkcode useEncoding} is set to
|
|
923
|
+
/** Serializes the given object to a string, optionally encoded with `options.encodeData` if {@linkcode useEncoding} is not set to false and the `encodeData` and `decodeData` options are set */
|
|
867
924
|
serializeData(data, useEncoding) {
|
|
868
925
|
return __async(this, null, function* () {
|
|
869
926
|
var _a, _b, _c, _d, _e;
|
|
@@ -914,7 +971,7 @@ var BrowserStorageEngine = class extends DataStoreEngine {
|
|
|
914
971
|
* Creates an instance of `BrowserStorageEngine`.
|
|
915
972
|
*
|
|
916
973
|
* - ⚠️ Requires a DOM environment
|
|
917
|
-
* - ⚠️ Don't reuse
|
|
974
|
+
* - ⚠️ Don't reuse engine instances, always create a new one for each {@linkcode DataStore} instance
|
|
918
975
|
*/
|
|
919
976
|
constructor(options) {
|
|
920
977
|
super(options == null ? void 0 : options.dataStoreOptions);
|
|
@@ -956,7 +1013,7 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
956
1013
|
* Creates an instance of `FileStorageEngine`.
|
|
957
1014
|
*
|
|
958
1015
|
* - ⚠️ Requires Node.js or Deno with Node compatibility (v1.31+)
|
|
959
|
-
* - ⚠️ Don't reuse
|
|
1016
|
+
* - ⚠️ Don't reuse engine instances, always create a new one for each {@linkcode DataStore} instance
|
|
960
1017
|
*/
|
|
961
1018
|
constructor(options) {
|
|
962
1019
|
super(options == null ? void 0 : options.dataStoreOptions);
|
|
@@ -976,7 +1033,7 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
976
1033
|
if (!fs)
|
|
977
1034
|
fs = (_a = yield import("fs/promises")) == null ? void 0 : _a.default;
|
|
978
1035
|
if (!fs)
|
|
979
|
-
throw new
|
|
1036
|
+
throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
|
|
980
1037
|
const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
|
|
981
1038
|
const data = yield fs.readFile(path, "utf-8");
|
|
982
1039
|
return data ? JSON.parse((_e = yield (_d = (_c = (_b = this.dataStoreOptions) == null ? void 0 : _b.decodeData) == null ? void 0 : _c[1]) == null ? void 0 : _d.call(_c, data)) != null ? _e : data) : void 0;
|
|
@@ -994,7 +1051,7 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
994
1051
|
if (!fs)
|
|
995
1052
|
fs = (_a = yield import("fs/promises")) == null ? void 0 : _a.default;
|
|
996
1053
|
if (!fs)
|
|
997
|
-
throw new
|
|
1054
|
+
throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
|
|
998
1055
|
const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
|
|
999
1056
|
yield fs.mkdir(path.slice(0, path.lastIndexOf(path.includes("/") ? "/" : "\\")), { recursive: true });
|
|
1000
1057
|
yield fs.writeFile(path, (_e = yield (_d = (_c = (_b = this.dataStoreOptions) == null ? void 0 : _b.encodeData) == null ? void 0 : _c[1]) == null ? void 0 : _d.call(_c, JSON.stringify(data))) != null ? _e : JSON.stringify(data, void 0, 2), "utf-8");
|
|
@@ -1027,8 +1084,12 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
1027
1084
|
data = {};
|
|
1028
1085
|
data[name] = value;
|
|
1029
1086
|
yield this.writeFile(data);
|
|
1030
|
-
}))
|
|
1031
|
-
|
|
1087
|
+
})).catch((err) => {
|
|
1088
|
+
console.error("Error in setValue:", err);
|
|
1089
|
+
throw err;
|
|
1090
|
+
});
|
|
1091
|
+
yield this.fileAccessQueue.catch(() => {
|
|
1092
|
+
});
|
|
1032
1093
|
});
|
|
1033
1094
|
}
|
|
1034
1095
|
/** Deletes a value from persistent storage */
|
|
@@ -1040,8 +1101,12 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
1040
1101
|
return;
|
|
1041
1102
|
delete data[name];
|
|
1042
1103
|
yield this.writeFile(data);
|
|
1043
|
-
}))
|
|
1044
|
-
|
|
1104
|
+
})).catch((err) => {
|
|
1105
|
+
console.error("Error in deleteValue:", err);
|
|
1106
|
+
throw err;
|
|
1107
|
+
});
|
|
1108
|
+
yield this.fileAccessQueue.catch(() => {
|
|
1109
|
+
});
|
|
1045
1110
|
});
|
|
1046
1111
|
}
|
|
1047
1112
|
/** Deletes the file that contains the data of this DataStore. */
|
|
@@ -1053,9 +1118,9 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
1053
1118
|
if (!fs)
|
|
1054
1119
|
fs = (_a = yield import("fs/promises")) == null ? void 0 : _a.default;
|
|
1055
1120
|
if (!fs)
|
|
1056
|
-
throw new
|
|
1121
|
+
throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
|
|
1057
1122
|
const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
|
|
1058
|
-
yield fs.unlink(path);
|
|
1123
|
+
return yield fs.unlink(path);
|
|
1059
1124
|
} catch (err) {
|
|
1060
1125
|
console.error("Error deleting file:", err);
|
|
1061
1126
|
}
|
|
@@ -1069,11 +1134,12 @@ var DataStoreSerializer = class _DataStoreSerializer {
|
|
|
1069
1134
|
__publicField(this, "stores");
|
|
1070
1135
|
__publicField(this, "options");
|
|
1071
1136
|
if (!crypto || !crypto.subtle)
|
|
1072
|
-
throw new
|
|
1137
|
+
throw new ScriptContextError("DataStoreSerializer has to run in a secure context (HTTPS) or in another environment that implements the subtleCrypto API!");
|
|
1073
1138
|
this.stores = stores;
|
|
1074
1139
|
this.options = __spreadValues({
|
|
1075
1140
|
addChecksum: true,
|
|
1076
|
-
ensureIntegrity: true
|
|
1141
|
+
ensureIntegrity: true,
|
|
1142
|
+
remapIds: {}
|
|
1077
1143
|
}, options);
|
|
1078
1144
|
}
|
|
1079
1145
|
/** Calculates the checksum of a string */
|
|
@@ -1092,9 +1158,11 @@ var DataStoreSerializer = class _DataStoreSerializer {
|
|
|
1092
1158
|
return __async(this, null, function* () {
|
|
1093
1159
|
var _a;
|
|
1094
1160
|
const serData = [];
|
|
1095
|
-
|
|
1161
|
+
const filteredStores = this.stores.filter((s) => typeof stores === "function" ? stores(s.id) : stores.includes(s.id));
|
|
1162
|
+
for (const storeInst of filteredStores) {
|
|
1096
1163
|
const encoded = Boolean(useEncoding && storeInst.encodingEnabled() && ((_a = storeInst.encodeData) == null ? void 0 : _a[1]));
|
|
1097
|
-
const
|
|
1164
|
+
const rawData = storeInst.memoryCache ? storeInst.getData() : yield storeInst.loadData();
|
|
1165
|
+
const data = encoded ? yield storeInst.encodeData[1](JSON.stringify(rawData)) : JSON.stringify(rawData);
|
|
1098
1166
|
serData.push({
|
|
1099
1167
|
id: storeInst.id,
|
|
1100
1168
|
data,
|
|
@@ -1125,10 +1193,18 @@ var DataStoreSerializer = class _DataStoreSerializer {
|
|
|
1125
1193
|
const deserStores = typeof data === "string" ? JSON.parse(data) : data;
|
|
1126
1194
|
if (!Array.isArray(deserStores) || !deserStores.every(_DataStoreSerializer.isSerializedDataStoreObj))
|
|
1127
1195
|
throw new TypeError("Invalid serialized data format! Expected an array of SerializedDataStore objects.");
|
|
1128
|
-
|
|
1129
|
-
|
|
1196
|
+
const resolveStoreId = (id) => {
|
|
1197
|
+
var _a, _b;
|
|
1198
|
+
return (_b = (_a = Object.entries(this.options.remapIds).find(([, v]) => v.includes(id))) == null ? void 0 : _a[0]) != null ? _b : id;
|
|
1199
|
+
};
|
|
1200
|
+
const matchesFilter = (id) => typeof stores === "function" ? stores(id) : stores.includes(id);
|
|
1201
|
+
for (const storeData of deserStores) {
|
|
1202
|
+
const effectiveId = resolveStoreId(storeData.id);
|
|
1203
|
+
if (!matchesFilter(effectiveId))
|
|
1204
|
+
continue;
|
|
1205
|
+
const storeInst = this.stores.find((s) => s.id === effectiveId);
|
|
1130
1206
|
if (!storeInst)
|
|
1131
|
-
throw new
|
|
1207
|
+
throw new DatedError(`Can't deserialize data because no DataStore instance with the ID "${effectiveId}" was found! Make sure to provide it in the DataStoreSerializer constructor.`);
|
|
1132
1208
|
if (this.options.ensureIntegrity && typeof storeData.checksum === "string") {
|
|
1133
1209
|
const checksum = yield this.calcChecksum(storeData.data);
|
|
1134
1210
|
if (checksum !== storeData.checksum)
|
|
@@ -1294,11 +1370,11 @@ var NanoEmitter = class {
|
|
|
1294
1370
|
once(event, cb) {
|
|
1295
1371
|
return new Promise((resolve) => {
|
|
1296
1372
|
let unsub;
|
|
1297
|
-
const onceProxy = (...args) => {
|
|
1373
|
+
const onceProxy = ((...args) => {
|
|
1298
1374
|
cb == null ? void 0 : cb(...args);
|
|
1299
1375
|
unsub == null ? void 0 : unsub();
|
|
1300
1376
|
resolve(args);
|
|
1301
|
-
};
|
|
1377
|
+
});
|
|
1302
1378
|
unsub = this.events.on(event, onceProxy);
|
|
1303
1379
|
this.eventUnsubscribes.push(unsub);
|
|
1304
1380
|
});
|
|
@@ -1310,11 +1386,12 @@ var NanoEmitter = class {
|
|
|
1310
1386
|
* `callback` (required) is the function that will be called when the conditions are met.
|
|
1311
1387
|
*
|
|
1312
1388
|
* Set `once` to true to call the callback only once for the first event (or set of events) that match the criteria, then stop listening.
|
|
1313
|
-
* If `signal` is provided, the subscription will be
|
|
1389
|
+
* If `signal` is provided, the subscription will be canceled when the given signal is aborted.
|
|
1314
1390
|
*
|
|
1315
1391
|
* If `oneOf` is used, the callback will be called when any of the matching events are emitted.
|
|
1316
1392
|
* If `allOf` is used, the callback will be called after all of the matching events are emitted at least once, then any time any of them are emitted.
|
|
1317
|
-
*
|
|
1393
|
+
* If both `oneOf` and `allOf` are used together, the callback will be called when any of the `oneOf` events are emitted AND all of the `allOf` events have been emitted at least once.
|
|
1394
|
+
* At least one of `oneOf` or `allOf` must be provided.
|
|
1318
1395
|
*
|
|
1319
1396
|
* @returns Returns a function that can be called to unsubscribe all listeners created by this call. Alternatively, pass an `AbortSignal` to all options objects to achieve the same effect or for finer control.
|
|
1320
1397
|
*/
|
|
@@ -1341,6 +1418,8 @@ var NanoEmitter = class {
|
|
|
1341
1418
|
} = optsWithDefaults;
|
|
1342
1419
|
if (signal == null ? void 0 : signal.aborted)
|
|
1343
1420
|
return unsubAll;
|
|
1421
|
+
if (oneOf.length === 0 && allOf.length === 0)
|
|
1422
|
+
throw new TypeError("NanoEmitter.onMulti(): Either `oneOf` or `allOf` or both must be provided in the options");
|
|
1344
1423
|
const curEvtUnsubs = [];
|
|
1345
1424
|
const checkUnsubAllEvt = (force = false) => {
|
|
1346
1425
|
if (!(signal == null ? void 0 : signal.aborted) && !force)
|
|
@@ -1350,34 +1429,31 @@ var NanoEmitter = class {
|
|
|
1350
1429
|
curEvtUnsubs.splice(0, curEvtUnsubs.length);
|
|
1351
1430
|
this.eventUnsubscribes = this.eventUnsubscribes.filter((u) => !curEvtUnsubs.includes(u));
|
|
1352
1431
|
};
|
|
1432
|
+
const allOfEmitted = /* @__PURE__ */ new Set();
|
|
1433
|
+
const allOfConditionMet = () => allOf.length === 0 || allOfEmitted.size === allOf.length;
|
|
1353
1434
|
for (const event of oneOf) {
|
|
1354
|
-
const unsub = this.events.on(event, (...args) => {
|
|
1435
|
+
const unsub = this.events.on(event, ((...args) => {
|
|
1355
1436
|
checkUnsubAllEvt();
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1437
|
+
if (allOfConditionMet()) {
|
|
1438
|
+
callback(event, ...args);
|
|
1439
|
+
if (once)
|
|
1440
|
+
checkUnsubAllEvt(true);
|
|
1441
|
+
}
|
|
1442
|
+
}));
|
|
1360
1443
|
curEvtUnsubs.push(unsub);
|
|
1361
1444
|
}
|
|
1362
|
-
const allOfEmitted = /* @__PURE__ */ new Set();
|
|
1363
|
-
const checkAllOf = (event, ...args) => {
|
|
1364
|
-
checkUnsubAllEvt();
|
|
1365
|
-
allOfEmitted.add(event);
|
|
1366
|
-
if (allOfEmitted.size === allOf.length) {
|
|
1367
|
-
callback(event, ...args);
|
|
1368
|
-
if (once)
|
|
1369
|
-
checkUnsubAllEvt(true);
|
|
1370
|
-
}
|
|
1371
|
-
};
|
|
1372
1445
|
for (const event of allOf) {
|
|
1373
|
-
const unsub = this.events.on(event, (...args) => {
|
|
1446
|
+
const unsub = this.events.on(event, ((...args) => {
|
|
1374
1447
|
checkUnsubAllEvt();
|
|
1375
|
-
|
|
1376
|
-
|
|
1448
|
+
allOfEmitted.add(event);
|
|
1449
|
+
if (allOfConditionMet() && (oneOf.length === 0 || oneOf.includes(event))) {
|
|
1450
|
+
callback(event, ...args);
|
|
1451
|
+
if (once)
|
|
1452
|
+
checkUnsubAllEvt(true);
|
|
1453
|
+
}
|
|
1454
|
+
}));
|
|
1377
1455
|
curEvtUnsubs.push(unsub);
|
|
1378
1456
|
}
|
|
1379
|
-
if (oneOf.length === 0 && allOf.length === 0)
|
|
1380
|
-
throw new TypeError("NanoEmitter.onMulti(): Either `oneOf` or `allOf` or both must be provided in the options");
|
|
1381
1457
|
allUnsubs.push(() => checkUnsubAllEvt(true));
|
|
1382
1458
|
}
|
|
1383
1459
|
return unsubAll;
|
|
@@ -1505,7 +1581,7 @@ var Debouncer = class extends NanoEmitter {
|
|
|
1505
1581
|
function debounce(fn, timeout = 200, type = "immediate") {
|
|
1506
1582
|
const debouncer = new Debouncer(timeout, type);
|
|
1507
1583
|
debouncer.addListener(fn);
|
|
1508
|
-
const func = (...args) => debouncer.call(...args);
|
|
1584
|
+
const func = ((...args) => debouncer.call(...args));
|
|
1509
1585
|
func.debouncer = debouncer;
|
|
1510
1586
|
return func;
|
|
1511
1587
|
}
|