@sv443-network/coreutils 3.3.0 → 3.5.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 +21 -0
- package/README.md +14 -4
- package/dist/CoreUtils.cjs +216 -9
- package/dist/CoreUtils.min.cjs +4 -3
- package/dist/CoreUtils.min.mjs +4 -3
- package/dist/CoreUtils.min.umd.js +4 -3
- package/dist/CoreUtils.mjs +216 -9
- package/dist/CoreUtils.umd.js +798 -548
- package/dist/lib/DataStore.d.ts +2 -2
- package/dist/lib/DataStoreSerializer.d.ts +10 -6
- package/dist/lib/Debouncer.d.ts +3 -3
- package/dist/lib/misc.d.ts +36 -0
- package/dist/lib/text.d.ts +65 -0
- package/package.json +23 -23
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,26 @@
|
|
|
1
1
|
# @sv443-network/coreutils
|
|
2
2
|
|
|
3
|
+
## 3.5.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 9a2f561: Added function `createTable()` to create a very flexible ASCII table, including ANSI color and `%c` styling support.
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- b620a8a: Fixed type variance issue in `DataStoreSerializer` where `DataStore` instances with specific data types (e.g. `DataStore<MyType>`) couldn't be passed to the constructor without being asserted `as DataStore<DataStoreData, boolean>`.
|
|
12
|
+
|
|
13
|
+
## 3.4.0
|
|
14
|
+
|
|
15
|
+
### Minor Changes
|
|
16
|
+
|
|
17
|
+
- 7e5c0b6: `Debouncer` and `debounce` now have an extra parameter of type `NanoEmitterOptions` to customize the underlying `NanoEmitter` instance.
|
|
18
|
+
- 2a04a7d: Added function `createRecurringTask()` as a "batteries included" alternative to `setImmediateTimeoutLoop()` and `setImmediateInterval()`, with more ways to control task execution and aborting.
|
|
19
|
+
|
|
20
|
+
### Patch Changes
|
|
21
|
+
|
|
22
|
+
- 328c460: Fix internal event emission problems in `Debouncer`
|
|
23
|
+
|
|
3
24
|
## 3.3.0
|
|
4
25
|
|
|
5
26
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -30,17 +30,18 @@ Intended to be used in conjunction with [`@sv443-network/userutils`](https://git
|
|
|
30
30
|
- 🟣 [`function decompress()`](./docs.md#function-decompress) - Decompresses the given string using the given algorithm and encoding
|
|
31
31
|
- 🟣 [`function computeHash()`](./docs.md#function-computehash) - Computes a string's hash using the given algorithm
|
|
32
32
|
- 🟣 [`function randomId()`](./docs.md#function-randomid) - Generates a random ID of the given length
|
|
33
|
-
- [**DataStore:**](./docs.md#datastore) - Cross-platform, general-purpose, sync/async hybrid, JSON-serializable database
|
|
33
|
+
- [**DataStore:**](./docs.md#datastore) - Cross-platform, general-purpose, sync/async hybrid, JSON-serializable database:
|
|
34
34
|
- 🟧 [`class DataStore`](./docs.md#class-datastore) - The main class for the data store
|
|
35
35
|
- 🔷 [`type DataStoreOptions`](./docs.md#type-datastoreoptions) - Options for the data store
|
|
36
36
|
- 🔷 [`type DataMigrationsDict`](./docs.md#type-datamigrationsdict) - Dictionary of data migration functions
|
|
37
37
|
- 🔷 [`type DataStoreData`](./docs.md#type-datastoredata) - The type of the serializable data
|
|
38
|
+
- 🔷 [`type DataStoreEventMap`](./docs.md#type-datastoreeventmap) - Map of DataStore events
|
|
38
39
|
- 🟧 [`class DataStoreSerializer`](./docs.md#class-datastoreserializer) - Serializes and deserializes data for multiple DataStore instances
|
|
39
40
|
- 🔷 [`type DataStoreSerializerOptions`](./docs.md#type-datastoreserializeroptions) - Options for the DataStoreSerializer
|
|
40
41
|
- 🔷 [`type LoadStoresDataResult`](./docs.md#type-loadstoresdataresult) - Result of calling [`loadStoresData()`](./docs.md#datastoreserializer-loadstoresdata)
|
|
41
42
|
- 🔷 [`type SerializedDataStore`](./docs.md#type-serializeddatastore) - Meta object and serialized data of a DataStore instance
|
|
42
43
|
- 🔷 [`type StoreFilter`](./docs.md#type-storefilter) - Filter for selecting data stores
|
|
43
|
-
- 🟧 [`class DataStoreEngine`](./docs.md#class-datastoreengine) - Base class for
|
|
44
|
+
- 🟧 [`class DataStoreEngine`](./docs.md#class-datastoreengine) - Base class for abstracting data storage into multiple instances
|
|
44
45
|
- 🔷 [`type DataStoreEngineDSOptions`](./docs.md#type-datastoreenginedsoptions) - Reduced version of [`DataStoreOptions`](./docs.md#type-datastoreoptions)
|
|
45
46
|
- [Storage Engines:](./docs.md#storage-engines)
|
|
46
47
|
- 🟧 [`class BrowserStorageEngine`](./docs.md#class-browserstorageengine) - Storage engine for browser environments (localStorage, sessionStorage)
|
|
@@ -83,6 +84,8 @@ Intended to be used in conjunction with [`@sv443-network/userutils`](https://git
|
|
|
83
84
|
- 🟣 [`function pureObj()`](./docs.md#function-pureobj) - Applies an object's props to a null object (object without prototype chain) or just returns a new null object
|
|
84
85
|
- 🟣 [`function setImmediateInterval()`](./docs.md#function-setimmediateinterval) - Like `setInterval()`, but instantly calls the callback and supports passing an [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal)
|
|
85
86
|
- 🟣 [`function setImmediateTimeoutLoop()`](./docs.md#function-setimmediatetimeoutloop) - Like a recursive `setTimeout()` loop, but instantly calls the callback and supports passing an [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal)
|
|
87
|
+
- 🟣 [`function createRecurringTask()`](./docs.md#function-createrecurringtask) - Similar to `setImmediateTimeoutLoop()`, but with many more ways of controlling execution.
|
|
88
|
+
- 🔷 [`type RecurringTaskOptions`](./docs.md#type-recurringtaskoptions) - Options for the `createRecurringTask()` function.
|
|
86
89
|
- 🟣 [`function scheduleExit()`](./docs.md#function-scheduleexit) - Schedules a process exit after the next event loop tick, to allow operations like IO writes to finish.
|
|
87
90
|
- [**NanoEmitter:**](./docs.md#nanoemitter)
|
|
88
91
|
- 🟧 [`class NanoEmitter`](./docs.md#class-nanoemitter) - Simple, lightweight event emitter class that can be used in both FP and OOP, inspired by [`EventEmitter` from `node:events`](https://nodejs.org/api/events.html#class-eventemitter), based on [`nanoevents`](https://npmjs.com/package/nanoevents)
|
|
@@ -91,10 +94,17 @@ Intended to be used in conjunction with [`@sv443-network/userutils`](https://git
|
|
|
91
94
|
- 🟣 [`function autoPlural()`](./docs.md#function-autoplural) - Turns the given term into its plural form, depending on the given number or list length
|
|
92
95
|
- 🟣 [`function capitalize()`](./docs.md#function-capitalize) - Capitalizes the first letter of the given string
|
|
93
96
|
- 🟣 [`function createProgressBar()`](./docs.md#function-createprogressbar) - Creates a progress bar string with the given percentage and length
|
|
94
|
-
-
|
|
97
|
+
- 🟩 [`const defaultPbChars`](./docs.md#const-defaultpbchars) - Default characters for the progress bar
|
|
95
98
|
- 🔷 [`type ProgressBarChars`](./docs.md#type-progressbarchars) - Type for the progress bar characters object
|
|
96
99
|
- 🟣 [`function joinArrayReadable()`](./docs.md#function-joinarrayreadable) - Joins the given array into a string, using the given separators and last separator
|
|
97
100
|
- 🟣 [`function secsToTimeStr()`](./docs.md#function-secstotimestr) - Turns the given number of seconds into a string in the format `(hh:)mm:ss` with intelligent zero-padding
|
|
101
|
+
- 🟣 [`function createTable()`](./docs.md#function-createtable) - Creates an ASCII table string from the given rows
|
|
102
|
+
- 🟩 [`const defaultTableLineCharset`](./docs.md#const-defaulttablelinecharset) - Default line characters for the table
|
|
103
|
+
- 🔷 [`type TableOptions`](./docs.md#type-tableoptions) - Options for the [`createTable()`](./docs.md#function-createtable) function
|
|
104
|
+
- 🔷 [`type TableLineStyle`](./docs.md#type-tablelinestyle) - The line style to use for the table border
|
|
105
|
+
- 🔷 [`type TableColumnAlign`](./docs.md#type-tablecolumnalign) - The alignment mode for a column
|
|
106
|
+
- 🔷 [`type TableLineCharset`](./docs.md#type-tablelinecharset) - The full charset used for table line characters
|
|
107
|
+
- 🔷 [`type TableLineStyleChars`](./docs.md#type-tablelinestylechars) - The characters for one line style variant
|
|
98
108
|
- 🟣 [`function truncStr()`](./docs.md#function-truncstr) - Truncates the given string to the given length
|
|
99
109
|
<!-- - *[**TieredCache:**](./docs.md#tieredcache)
|
|
100
110
|
- 🟧 *[`class TieredCache`](./docs.md#class-tieredcache) - A multi-tier cache that uses multiple storage engines with different expiration times
|
|
@@ -126,7 +136,7 @@ Intended to be used in conjunction with [`@sv443-network/userutils`](https://git
|
|
|
126
136
|
> 🟣 = function
|
|
127
137
|
> 🟧 = class
|
|
128
138
|
> 🔷 = type
|
|
129
|
-
>
|
|
139
|
+
> 🟩 = const
|
|
130
140
|
|
|
131
141
|
<br>
|
|
132
142
|
|
package/dist/CoreUtils.cjs
CHANGED
|
@@ -55,10 +55,13 @@ __export(lib_exports, {
|
|
|
55
55
|
consumeGen: () => consumeGen,
|
|
56
56
|
consumeStringGen: () => consumeStringGen,
|
|
57
57
|
createProgressBar: () => createProgressBar,
|
|
58
|
+
createRecurringTask: () => createRecurringTask,
|
|
59
|
+
createTable: () => createTable,
|
|
58
60
|
darkenColor: () => darkenColor,
|
|
59
61
|
debounce: () => debounce,
|
|
60
62
|
decompress: () => decompress,
|
|
61
63
|
defaultPbChars: () => defaultPbChars,
|
|
64
|
+
defaultTableLineCharset: () => defaultTableLineCharset,
|
|
62
65
|
digitCount: () => digitCount,
|
|
63
66
|
fetchAdvanced: () => fetchAdvanced,
|
|
64
67
|
formatNumber: () => formatNumber,
|
|
@@ -460,12 +463,45 @@ function getCallStack(asArray, lines = Infinity) {
|
|
|
460
463
|
if (typeof lines !== "number" || isNaN(lines) || lines < 0)
|
|
461
464
|
throw new TypeError("lines parameter must be a non-negative number");
|
|
462
465
|
try {
|
|
463
|
-
throw new
|
|
466
|
+
throw new CustomError("GetCallStack", "Capturing a stack trace with CoreUtils.getCallStack(). If you see this anywhere, you can safely ignore it.");
|
|
464
467
|
} catch (err) {
|
|
465
468
|
const stack = (err.stack ?? "").split("\n").map((line) => line.trim()).slice(2, lines + 2);
|
|
466
469
|
return asArray !== false ? stack : stack.join("\n");
|
|
467
470
|
}
|
|
468
471
|
}
|
|
472
|
+
function createRecurringTask(options) {
|
|
473
|
+
var _a;
|
|
474
|
+
let iterations = 0;
|
|
475
|
+
let aborted = false;
|
|
476
|
+
(_a = options.signal) == null ? void 0 : _a.addEventListener("abort", () => {
|
|
477
|
+
aborted = true;
|
|
478
|
+
}, { once: true });
|
|
479
|
+
const runRecurringTask = async (initial = false) => {
|
|
480
|
+
var _a2;
|
|
481
|
+
if (aborted)
|
|
482
|
+
return;
|
|
483
|
+
try {
|
|
484
|
+
if ((options.immediate ?? true) || !initial) {
|
|
485
|
+
iterations++;
|
|
486
|
+
if (await ((_a2 = options.condition) == null ? void 0 : _a2.call(options, iterations - 1)) ?? true) {
|
|
487
|
+
const val = await options.task(iterations - 1);
|
|
488
|
+
if (options.onSuccess)
|
|
489
|
+
await options.onSuccess(val, iterations - 1);
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
} catch (err) {
|
|
493
|
+
if (options.onError)
|
|
494
|
+
await options.onError(err, iterations - 1);
|
|
495
|
+
if (options.abortOnError)
|
|
496
|
+
aborted = true;
|
|
497
|
+
if (!options.onError && !options.abortOnError)
|
|
498
|
+
throw err;
|
|
499
|
+
}
|
|
500
|
+
if (!aborted && (typeof options.maxIterations !== "number" || iterations < options.maxIterations))
|
|
501
|
+
setTimeout(runRecurringTask, options.timeout);
|
|
502
|
+
};
|
|
503
|
+
return runRecurringTask(true);
|
|
504
|
+
}
|
|
469
505
|
|
|
470
506
|
// lib/text.ts
|
|
471
507
|
function autoPlural(term, num, pluralType = "auto") {
|
|
@@ -554,6 +590,173 @@ function truncStr(input, length, endStr = "...") {
|
|
|
554
590
|
const finalStr = str.length > length ? str.substring(0, length - endStr.length) + endStr : str;
|
|
555
591
|
return finalStr.length > length ? finalStr.substring(0, length) : finalStr;
|
|
556
592
|
}
|
|
593
|
+
var defaultTableLineCharset = {
|
|
594
|
+
single: {
|
|
595
|
+
horizontal: "\u2500",
|
|
596
|
+
vertical: "\u2502",
|
|
597
|
+
topLeft: "\u250C",
|
|
598
|
+
topRight: "\u2510",
|
|
599
|
+
bottomLeft: "\u2514",
|
|
600
|
+
bottomRight: "\u2518",
|
|
601
|
+
leftT: "\u251C",
|
|
602
|
+
rightT: "\u2524",
|
|
603
|
+
topT: "\u252C",
|
|
604
|
+
bottomT: "\u2534",
|
|
605
|
+
cross: "\u253C"
|
|
606
|
+
},
|
|
607
|
+
double: {
|
|
608
|
+
horizontal: "\u2550",
|
|
609
|
+
vertical: "\u2551",
|
|
610
|
+
topLeft: "\u2554",
|
|
611
|
+
topRight: "\u2557",
|
|
612
|
+
bottomLeft: "\u255A",
|
|
613
|
+
bottomRight: "\u255D",
|
|
614
|
+
leftT: "\u2560",
|
|
615
|
+
rightT: "\u2563",
|
|
616
|
+
topT: "\u2566",
|
|
617
|
+
bottomT: "\u2569",
|
|
618
|
+
cross: "\u256C"
|
|
619
|
+
},
|
|
620
|
+
none: {
|
|
621
|
+
horizontal: " ",
|
|
622
|
+
vertical: " ",
|
|
623
|
+
topLeft: " ",
|
|
624
|
+
topRight: " ",
|
|
625
|
+
bottomLeft: " ",
|
|
626
|
+
bottomRight: " ",
|
|
627
|
+
leftT: " ",
|
|
628
|
+
rightT: " ",
|
|
629
|
+
topT: " ",
|
|
630
|
+
bottomT: " ",
|
|
631
|
+
cross: " "
|
|
632
|
+
}
|
|
633
|
+
};
|
|
634
|
+
function createTable(rows, options) {
|
|
635
|
+
var _a;
|
|
636
|
+
const opts = {
|
|
637
|
+
columnAlign: "left",
|
|
638
|
+
truncateAbove: Infinity,
|
|
639
|
+
truncEndStr: "\u2026",
|
|
640
|
+
minPadding: 1,
|
|
641
|
+
lineStyle: "single",
|
|
642
|
+
applyCellStyle: () => void 0,
|
|
643
|
+
applyLineStyle: () => void 0,
|
|
644
|
+
lineCharset: defaultTableLineCharset,
|
|
645
|
+
...options ?? {}
|
|
646
|
+
};
|
|
647
|
+
const defRange = (val, min, max) => clamp(typeof val !== "number" || isNaN(Number(val)) ? min : val, min, max);
|
|
648
|
+
opts.truncateAbove = defRange(opts.truncateAbove, 0, Infinity);
|
|
649
|
+
opts.minPadding = defRange(opts.minPadding, 0, Infinity);
|
|
650
|
+
const lnCh = opts.lineCharset[opts.lineStyle];
|
|
651
|
+
const stripAnsi = (str) => str.replace(/\u001b\[[0-9;]*m/g, "");
|
|
652
|
+
const stringRows = rows.map((row) => row.map((cell) => String(cell)));
|
|
653
|
+
const colCount = ((_a = rows[0]) == null ? void 0 : _a.length) ?? 0;
|
|
654
|
+
if (colCount === 0 || stringRows.length === 0)
|
|
655
|
+
return "";
|
|
656
|
+
if (isFinite(opts.truncateAbove)) {
|
|
657
|
+
const truncAnsi = (str, maxVisible, endStr) => {
|
|
658
|
+
const limit = maxVisible - endStr.length;
|
|
659
|
+
if (limit <= 0)
|
|
660
|
+
return endStr.slice(0, maxVisible);
|
|
661
|
+
let visible = 0;
|
|
662
|
+
let result = "";
|
|
663
|
+
let i = 0;
|
|
664
|
+
let hasAnsi = false;
|
|
665
|
+
while (i < str.length) {
|
|
666
|
+
if (str[i] === "\x1B" && str[i + 1] === "[") {
|
|
667
|
+
const seqEnd = str.indexOf("m", i + 2);
|
|
668
|
+
if (seqEnd !== -1) {
|
|
669
|
+
result += str.slice(i, seqEnd + 1);
|
|
670
|
+
hasAnsi = true;
|
|
671
|
+
i = seqEnd + 1;
|
|
672
|
+
continue;
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
if (visible === limit) {
|
|
676
|
+
result += endStr;
|
|
677
|
+
if (hasAnsi)
|
|
678
|
+
result += "\x1B[0m";
|
|
679
|
+
return result;
|
|
680
|
+
}
|
|
681
|
+
result += str[i];
|
|
682
|
+
visible++;
|
|
683
|
+
i++;
|
|
684
|
+
}
|
|
685
|
+
return result;
|
|
686
|
+
};
|
|
687
|
+
for (const row of stringRows)
|
|
688
|
+
for (let j = 0; j < row.length; j++)
|
|
689
|
+
if (stripAnsi(row[j] ?? "").length > opts.truncateAbove)
|
|
690
|
+
row[j] = truncAnsi(row[j] ?? "", opts.truncateAbove, opts.truncEndStr);
|
|
691
|
+
}
|
|
692
|
+
const colWidths = Array.from(
|
|
693
|
+
{ length: colCount },
|
|
694
|
+
(_, j) => Math.max(0, ...stringRows.map((row) => stripAnsi(row[j] ?? "").length))
|
|
695
|
+
);
|
|
696
|
+
const applyLn = (i, j, ch) => {
|
|
697
|
+
const [before = "", after = ""] = opts.applyLineStyle(i, j) ?? [];
|
|
698
|
+
return `${before}${ch}${after}`;
|
|
699
|
+
};
|
|
700
|
+
const buildBorderRow = (lineIdx, leftCh, midCh, rightCh) => {
|
|
701
|
+
let result = "";
|
|
702
|
+
let j = 0;
|
|
703
|
+
result += applyLn(lineIdx, j++, leftCh);
|
|
704
|
+
for (let col = 0; col < colCount; col++) {
|
|
705
|
+
const cellWidth = (colWidths[col] ?? 0) + opts.minPadding * 2;
|
|
706
|
+
for (let ci = 0; ci < cellWidth; ci++)
|
|
707
|
+
result += applyLn(lineIdx, j++, lnCh.horizontal);
|
|
708
|
+
if (col < colCount - 1)
|
|
709
|
+
result += applyLn(lineIdx, j++, midCh);
|
|
710
|
+
}
|
|
711
|
+
result += applyLn(lineIdx, j++, rightCh);
|
|
712
|
+
return result;
|
|
713
|
+
};
|
|
714
|
+
const lines = [];
|
|
715
|
+
for (let rowIdx = 0; rowIdx < stringRows.length; rowIdx++) {
|
|
716
|
+
const row = stringRows[rowIdx] ?? [];
|
|
717
|
+
const lineIdxBase = rowIdx * 3;
|
|
718
|
+
if (opts.lineStyle !== "none") {
|
|
719
|
+
lines.push(
|
|
720
|
+
rowIdx === 0 ? buildBorderRow(lineIdxBase, lnCh.topLeft, lnCh.topT, lnCh.topRight) : buildBorderRow(lineIdxBase, lnCh.leftT, lnCh.cross, lnCh.rightT)
|
|
721
|
+
);
|
|
722
|
+
}
|
|
723
|
+
let contentLine = "";
|
|
724
|
+
let j = 0;
|
|
725
|
+
contentLine += applyLn(lineIdxBase + 1, j++, lnCh.vertical);
|
|
726
|
+
for (let colIdx = 0; colIdx < colCount; colIdx++) {
|
|
727
|
+
const cell = row[colIdx] ?? "";
|
|
728
|
+
const visLen = stripAnsi(cell).length;
|
|
729
|
+
const extra = (colWidths[colIdx] ?? 0) - visLen;
|
|
730
|
+
const align = (Array.isArray(opts.columnAlign) ? opts.columnAlign[colIdx] : opts.columnAlign) ?? "left";
|
|
731
|
+
let leftPad;
|
|
732
|
+
let rightPad;
|
|
733
|
+
switch (align) {
|
|
734
|
+
case "right":
|
|
735
|
+
leftPad = opts.minPadding + extra;
|
|
736
|
+
rightPad = opts.minPadding;
|
|
737
|
+
break;
|
|
738
|
+
case "centerLeft":
|
|
739
|
+
leftPad = opts.minPadding + Math.floor(extra / 2);
|
|
740
|
+
rightPad = opts.minPadding + Math.ceil(extra / 2);
|
|
741
|
+
break;
|
|
742
|
+
case "centerRight":
|
|
743
|
+
leftPad = opts.minPadding + Math.ceil(extra / 2);
|
|
744
|
+
rightPad = opts.minPadding + Math.floor(extra / 2);
|
|
745
|
+
break;
|
|
746
|
+
default:
|
|
747
|
+
leftPad = opts.minPadding;
|
|
748
|
+
rightPad = opts.minPadding + extra;
|
|
749
|
+
}
|
|
750
|
+
const [cellBefore = "", cellAfter = ""] = opts.applyCellStyle(rowIdx, colIdx) ?? [];
|
|
751
|
+
contentLine += " ".repeat(leftPad) + cellBefore + cell + cellAfter + " ".repeat(rightPad);
|
|
752
|
+
contentLine += applyLn(lineIdxBase + 1, j++, lnCh.vertical);
|
|
753
|
+
}
|
|
754
|
+
lines.push(contentLine);
|
|
755
|
+
if (opts.lineStyle !== "none" && rowIdx === stringRows.length - 1)
|
|
756
|
+
lines.push(buildBorderRow(lineIdxBase + 2, lnCh.bottomLeft, lnCh.bottomT, lnCh.bottomRight));
|
|
757
|
+
}
|
|
758
|
+
return lines.join("\n");
|
|
759
|
+
}
|
|
557
760
|
|
|
558
761
|
// node_modules/.pnpm/nanoevents@9.1.0/node_modules/nanoevents/index.js
|
|
559
762
|
var createNanoEvents = () => ({
|
|
@@ -1264,6 +1467,7 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
1264
1467
|
// lib/DataStoreSerializer.ts
|
|
1265
1468
|
var DataStoreSerializer = class _DataStoreSerializer {
|
|
1266
1469
|
stores;
|
|
1470
|
+
// eslint-disable-line @typescript-eslint/no-explicit-any
|
|
1267
1471
|
options;
|
|
1268
1472
|
constructor(stores, options = {}) {
|
|
1269
1473
|
if (!crypto || !crypto.subtle)
|
|
@@ -1276,7 +1480,10 @@ var DataStoreSerializer = class _DataStoreSerializer {
|
|
|
1276
1480
|
...options
|
|
1277
1481
|
};
|
|
1278
1482
|
}
|
|
1279
|
-
/**
|
|
1483
|
+
/**
|
|
1484
|
+
* Calculates the checksum of a string. Uses {@linkcode computeHash()} with SHA-256 and digests as a hex string by default.
|
|
1485
|
+
* Override this in a subclass if a custom checksum method is needed.
|
|
1486
|
+
*/
|
|
1280
1487
|
async calcChecksum(input) {
|
|
1281
1488
|
return computeHash(input, "SHA-256");
|
|
1282
1489
|
}
|
|
@@ -1407,8 +1614,8 @@ var Debouncer = class extends NanoEmitter {
|
|
|
1407
1614
|
* @param timeout Timeout in milliseconds between letting through calls - defaults to 200
|
|
1408
1615
|
* @param type The edge type to use for the debouncer - see {@linkcode DebouncerType} for details or [the documentation for an explanation and diagram](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#debouncer) - defaults to "immediate"
|
|
1409
1616
|
*/
|
|
1410
|
-
constructor(timeout = 200, type = "immediate") {
|
|
1411
|
-
super();
|
|
1617
|
+
constructor(timeout = 200, type = "immediate", nanoEmitterOptions) {
|
|
1618
|
+
super(nanoEmitterOptions);
|
|
1412
1619
|
this.timeout = timeout;
|
|
1413
1620
|
this.type = type;
|
|
1414
1621
|
}
|
|
@@ -1439,7 +1646,7 @@ var Debouncer = class extends NanoEmitter {
|
|
|
1439
1646
|
//#region timeout
|
|
1440
1647
|
/** Sets the timeout for the debouncer */
|
|
1441
1648
|
setTimeout(timeout) {
|
|
1442
|
-
this.emit("change", this.timeout = timeout, this.type);
|
|
1649
|
+
this.events.emit("change", this.timeout = timeout, this.type);
|
|
1443
1650
|
}
|
|
1444
1651
|
/** Returns the current timeout */
|
|
1445
1652
|
getTimeout() {
|
|
@@ -1452,7 +1659,7 @@ var Debouncer = class extends NanoEmitter {
|
|
|
1452
1659
|
//#region type
|
|
1453
1660
|
/** Sets the edge type for the debouncer */
|
|
1454
1661
|
setType(type) {
|
|
1455
|
-
this.emit("change", this.timeout, this.type = type);
|
|
1662
|
+
this.events.emit("change", this.timeout, this.type = type);
|
|
1456
1663
|
}
|
|
1457
1664
|
/** Returns the current edge type */
|
|
1458
1665
|
getType() {
|
|
@@ -1463,7 +1670,7 @@ var Debouncer = class extends NanoEmitter {
|
|
|
1463
1670
|
call(...args) {
|
|
1464
1671
|
const cl = (...a) => {
|
|
1465
1672
|
this.queuedCall = void 0;
|
|
1466
|
-
this.emit("call", ...a);
|
|
1673
|
+
this.events.emit("call", ...a);
|
|
1467
1674
|
this.listeners.forEach((l) => l.call(this, ...a));
|
|
1468
1675
|
};
|
|
1469
1676
|
const setRepeatTimeout = () => {
|
|
@@ -1496,8 +1703,8 @@ var Debouncer = class extends NanoEmitter {
|
|
|
1496
1703
|
}
|
|
1497
1704
|
}
|
|
1498
1705
|
};
|
|
1499
|
-
function debounce(fn, timeout = 200, type = "immediate") {
|
|
1500
|
-
const debouncer = new Debouncer(timeout, type);
|
|
1706
|
+
function debounce(fn, timeout = 200, type = "immediate", nanoEmitterOptions) {
|
|
1707
|
+
const debouncer = new Debouncer(timeout, type, nanoEmitterOptions);
|
|
1501
1708
|
debouncer.addListener(fn);
|
|
1502
1709
|
const func = ((...args) => debouncer.call(...args));
|
|
1503
1710
|
func.debouncer = debouncer;
|
package/dist/CoreUtils.min.cjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var le=Object.create;var I=Object.defineProperty;var ce=Object.getOwnPropertyDescriptor;var de=Object.getOwnPropertyNames;var me=Object.getPrototypeOf,pe=Object.prototype.hasOwnProperty;var fe=(r,e)=>{for(var t in e)I(r,t,{get:e[t],enumerable:!0})},G=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of de(e))!pe.call(r,n)&&n!==t&&I(r,n,{get:()=>e[n],enumerable:!(i=ce(e,n))||i.enumerable});return r};var U=(r,e,t)=>(t=r!=null?le(me(r)):{},G(e||!r||!r.__esModule?I(t,"default",{value:r,enumerable:!0}):t,r)),he=r=>G(I({},"__esModule",{value:!0}),r);var _e={};fe(_e,{BrowserStorageEngine:()=>W,ChecksumMismatchError:()=>F,CustomError:()=>O,DataStore:()=>_,DataStoreEngine:()=>$,DataStoreSerializer:()=>Q,DatedError:()=>b,Debouncer:()=>z,FileStorageEngine:()=>H,MigrationError:()=>M,NanoEmitter:()=>E,NetworkError:()=>C,ScriptContextError:()=>x,ValidationError:()=>J,abtoa:()=>te,atoab:()=>re,autoPlural:()=>Re,bitSetHas:()=>ge,capitalize:()=>ze,clamp:()=>P,compress:()=>B,computeHash:()=>q,consumeGen:()=>Ee,consumeStringGen:()=>Oe,createProgressBar:()=>Ue,createRecurringTask:()=>Ie,createTable:()=>qe,darkenColor:()=>X,debounce:()=>Je,decompress:()=>K,defaultPbChars:()=>ie,defaultTableLineCharset:()=>ne,digitCount:()=>be,fetchAdvanced:()=>Ae,formatNumber:()=>ye,getCallStack:()=>$e,getListLength:()=>Ne,hexToRgb:()=>Y,insertValues:()=>Le,joinArrayReadable:()=>je,lightenColor:()=>xe,mapRange:()=>R,overflowVal:()=>Te,pauseFor:()=>Ve,pureObj:()=>ke,randRange:()=>k,randomId:()=>Pe,randomItem:()=>Se,randomItemIndex:()=>j,randomizeArray:()=>ve,rgbToHex:()=>ee,roundFixed:()=>L,scheduleExit:()=>Ce,secsToTimeStr:()=>Be,setImmediateInterval:()=>Fe,setImmediateTimeoutLoop:()=>Me,takeRandomItem:()=>we,takeRandomItemIndex:()=>Z,truncStr:()=>Ke,valsWithin:()=>De});module.exports=he(_e);function ge(r,e){return(r&e)===e}function P(r,e,t){return typeof t!="number"&&(t=e,e=0),Math.max(Math.min(r,t),e)}function be(r,e=!0){if(r=Number(["string","number"].includes(typeof r)?r:String(r)),typeof r=="number"&&isNaN(r))return NaN;let[t,i]=r.toString().split("."),n=t==="0"?1:Math.floor(Math.log10(Math.abs(Number(t)))+1),o=e&&i?i.length:0;return n+o}function ye(r,e,t){return r.toLocaleString(e,t==="short"?{notation:"compact",compactDisplay:"short",maximumFractionDigits:1}:{style:"decimal",maximumFractionDigits:0})}function R(r,e,t,i,n){return(typeof i>"u"||typeof n>"u")&&(n=t,t=e,i=e=0),Number(e)===0&&Number(i)===0?r*(n/t):(r-e)*((n-i)/(t-e))+i}function Te(r,e,t){let i=typeof t=="number"?e:0;if(t=typeof t=="number"?t:e,i>t)throw new RangeError(`Parameter "min" can't be bigger than "max"`);if(isNaN(r)||isNaN(i)||isNaN(t)||!isFinite(r)||!isFinite(i)||!isFinite(t))return NaN;if(r>=i&&r<=t)return r;let n=t-i+1;return((r-i)%n+n)%n+i}function k(...r){let e,t,i=!1;if(typeof r[0]=="number"&&typeof r[1]=="number")[e,t]=r;else if(typeof r[0]=="number"&&typeof r[1]!="number")e=0,[t]=r;else throw new TypeError(`Wrong parameter(s) provided - expected (number, boolean|undefined) or (number, number, boolean|undefined) but got (${r.map(n=>typeof n).join(", ")}) instead`);if(typeof r[2]=="boolean"?i=r[2]:typeof r[1]=="boolean"&&(i=r[1]),e=Number(e),t=Number(t),isNaN(e)||isNaN(t))return NaN;if(e>t)throw new TypeError(`Parameter "min" can't be bigger than "max"`);if(i){let n=new Uint8Array(1);return crypto.getRandomValues(n),Number(Array.from(n,o=>Math.round(R(o,0,255,e,t)).toString(10)).join(""))}else return Math.floor(Math.random()*(t-e+1))+e}function L(r,e){let t=10**e;return Math.round(r*t)/t}function De(r,e,t=1,i=.5){return Math.abs(L(r,t)-L(e,t))<=i}function Se(r){return j(r)[0]}function j(r){if(r.length===0)return[void 0,void 0];let e=k(r.length-1);return[r[e],e]}function ve(r){let e=[...r];if(r.length===0)return e;for(let t=e.length-1;t>0;t--){let i=Math.floor(Math.random()*(t+1));[e[t],e[i]]=[e[i],e[t]]}return e}function we(r){var e;return(e=Z(r))==null?void 0:e[0]}function Z(r){let[e,t]=j(r);return t===void 0?[void 0,void 0]:(r.splice(t,1),[e,t])}function X(r,e,t=!1){var c;r=r.trim();let i=(m,p,h,l)=>(m=Math.max(0,Math.min(255,m-m*l/100)),p=Math.max(0,Math.min(255,p-p*l/100)),h=Math.max(0,Math.min(255,h-h*l/100)),[m,p,h]),n,o,a,s,u=r.match(/^#?([0-9A-Fa-f]{3}|[0-9A-Fa-f]{4}|[0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})$/);if(u)[n,o,a,s]=Y(r);else if(r.startsWith("rgb")){let m=(c=r.match(/\d+(\.\d+)?/g))==null?void 0:c.map(Number);if(!m)throw new TypeError("Invalid RGB/RGBA color format");[n,o,a,s]=m}else throw new TypeError("Unsupported color format");return[n,o,a]=i(n,o,a,e),u?ee(n,o,a,s,r.startsWith("#"),t):r.startsWith("rgba")?`rgba(${n}, ${o}, ${a}, ${s??NaN})`:`rgb(${n}, ${o}, ${a})`}function Y(r){r=(r.startsWith("#")?r.slice(1):r).trim();let e=r.length===8||r.length===4?parseInt(r.slice(-(r.length/4)),16)/(r.length===8?255:15):void 0;isNaN(Number(e))||(r=r.slice(0,-(r.length/4))),(r.length===3||r.length===4)&&(r=r.split("").map(a=>a+a).join(""));let t=parseInt(r,16),i=t>>16&255,n=t>>8&255,o=t&255;return[P(i,0,255),P(n,0,255),P(o,0,255),typeof e=="number"?P(e,0,1):void 0]}function xe(r,e,t=!1){return X(r,e*-1,t)}function ee(r,e,t,i,n=!0,o=!1){let a=s=>P(Math.round(s),0,255).toString(16).padStart(2,"0")[o?"toUpperCase":"toLowerCase"]();return`${n?"#":""}${a(r)}${a(e)}${a(t)}${i?a(i*255):""}`}function te(r){return btoa(new Uint8Array(r).reduce((e,t)=>e+String.fromCharCode(t),""))}function re(r){return Uint8Array.from(atob(r),e=>e.charCodeAt(0))}async function B(r,e,t="string"){let i=r instanceof Uint8Array?r:new TextEncoder().encode((r==null?void 0:r.toString())??String(r)),n=new CompressionStream(e),o=n.writable.getWriter();o.write(i),o.close();let a=new Uint8Array(await new Response(n.readable).arrayBuffer());return t==="arrayBuffer"?a:te(a)}async function K(r,e,t="string"){let i=r instanceof Uint8Array?r:re((r==null?void 0:r.toString())??String(r)),n=new DecompressionStream(e),o=n.writable.getWriter();o.write(i),o.close();let a=new Uint8Array(await new Response(n.readable).arrayBuffer());return t==="arrayBuffer"?a:new TextDecoder().decode(a)}async function q(r,e="SHA-256"){let t;typeof r=="string"?t=new TextEncoder().encode(r):t=r;let i=await crypto.subtle.digest(e,t);return Array.from(new Uint8Array(i)).map(a=>a.toString(16).padStart(2,"0")).join("")}function Pe(r=16,e=16,t=!1,i=!0){if(r<1)throw new RangeError("The length argument must be at least 1");if(e<2||e>36)throw new RangeError("The radix argument must be between 2 and 36");let n=[],o=i?[0,1]:[0];if(t){let a=new Uint8Array(r);crypto.getRandomValues(a),n=Array.from(a,s=>R(s,0,255,0,e).toString(e).substring(0,1))}else n=Array.from({length:r},()=>Math.floor(Math.random()*e).toString(e));return n.some(a=>/[a-zA-Z]/.test(a))?n.map(a=>o[k(0,o.length-1,t)]===1?a.toUpperCase():a).join(""):n.join("")}var b=class extends Error{date;constructor(e,t){super(e,t),this.name=this.constructor.name,this.date=new Date}},F=class extends b{constructor(e,t){super(e,t),this.name="ChecksumMismatchError"}},O=class extends b{constructor(e,t,i){super(t,i),this.name=e}},M=class extends b{constructor(e,t){super(e,t),this.name="MigrationError"}},J=class extends b{constructor(e,t){super(e,t),this.name="ValidationError"}},x=class extends b{constructor(e,t){super(e,t),this.name="ScriptContextError"}},C=class extends b{constructor(e,t){super(e,t),this.name="NetworkError"}};async function Ee(r){return await(typeof r=="function"?r():r)}async function Oe(r){return typeof r=="string"?r:String(typeof r=="function"?await r():r)}async function Ae(r,e={}){let{timeout:t=1e4,signal:i,...n}=e,o=new AbortController;i==null||i.addEventListener("abort",()=>o.abort());let a={},s;t>=0&&(s=setTimeout(()=>o.abort(),t),a={signal:o.signal});try{let u=await fetch(r,{...n,...a});return typeof s<"u"&&clearTimeout(s),u}catch(u){throw typeof s<"u"&&clearTimeout(s),new C("Error while calling fetch",{cause:u})}}function Ne(r,e=!0){return"length"in r?r.length:"size"in r?r.size:"count"in r?r.count:e?0:NaN}function Ve(r,e,t=!1){return new Promise((i,n)=>{let o=setTimeout(()=>i(),r);e==null||e.addEventListener("abort",()=>{clearTimeout(o),t?n(new O("AbortError","The pause was aborted")):i()})})}function ke(r){return Object.assign(Object.create(null),r??{})}function Fe(r,e,t){let i,n=()=>clearInterval(i),o=()=>{if(t!=null&&t.aborted)return n();r()};t==null||t.addEventListener("abort",n),o(),i=setInterval(o,e)}function Me(r,e,t){let i,n=()=>clearTimeout(i),o=async()=>{if(t!=null&&t.aborted)return n();await r(),i=setTimeout(o,e)};t==null||t.addEventListener("abort",n),o()}function Ce(r=0,e=0){if(e<0)throw new TypeError("Timeout must be a non-negative number");let t;if(typeof process<"u"&&"exit"in process&&typeof process.exit=="function")t=()=>process.exit(r);else if(typeof Deno<"u"&&"exit"in Deno&&typeof Deno.exit=="function")t=()=>Deno.exit(r);else throw new x("Cannot exit the process, no exit method available");setTimeout(t,e)}function $e(r,e=1/0){if(typeof e!="number"||isNaN(e)||e<0)throw new TypeError("lines parameter must be a non-negative number");try{throw new O("GetCallStack","Capturing a stack trace with CoreUtils.getCallStack(). If you see this anywhere, you can safely ignore it.")}catch(t){let i=(t.stack??"").split(`
|
|
2
2
|
`).map(n=>n.trim()).slice(2,e+2);return r!==!1?i:i.join(`
|
|
3
|
-
`)}}function Pe(r,e,t="auto"){switch(typeof e!="number"&&("length"in e?e=e.length:"size"in e?e=e.size:"count"in e&&(e=e.count)),["-s","-ies"].includes(t)||(t="auto"),isNaN(e)&&(e=2),t==="auto"?String(r).endsWith("y")?"-ies":"-s":t){case"-s":return`${r}${e===1?"":"s"}`;case"-ies":return`${String(r).slice(0,-1)}${e===1?"y":"ies"}`}}function Oe(r){return r.charAt(0).toUpperCase()+r.slice(1)}var G={100:"\u2588",75:"\u2593",50:"\u2592",25:"\u2591",0:"\u2500"};function Ne(r,e,t=G){if(r===100)return t[100].repeat(e);let i=Math.floor(r/100*e),n=r/10*e-i,o="";n>=.75?o=t[75]:n>=.5?o=t[50]:n>=.25&&(o=t[25]);let a=t[100].repeat(i),s=t[0].repeat(e-i-(o?1:0));return`${a}${o}${s}`}function Fe(r,...e){return r.replace(/%\d/gm,t=>{var n;let i=Number(t.substring(1))-1;return(n=e[i]??t)==null?void 0:n.toString()})}function Ve(r,e=", ",t=" and "){let i=[...r];if(i.length===0)return"";if(i.length===1)return String(i[0]);if(i.length===2)return i.join(t);let n=t+i[i.length-1];return i.pop(),i.join(e)+n}function Ae(r){let e=r<0,t=Math.abs(r);if(isNaN(t)||!isFinite(t))throw new TypeError("The seconds argument must be a valid number");let i=Math.floor(t/3600),n=Math.floor(t%3600/60),o=Math.floor(t%60);return(e?"-":"")+[i?i+":":"",String(n).padStart(n>0||i>0?2:1,"0"),":",String(o).padStart(o>0||n>0||i>0||r===0?2:1,"0")].join("")}function ke(r,e,t="..."){let i=(r==null?void 0:r.toString())??String(r),n=i.length>e?i.substring(0,e-t.length)+t:i;return n.length>e?n.substring(0,e):n}var Z=()=>({emit(r,...e){for(let t=this.events[r]||[],i=0,n=t.length;i<n;i++)t[i](...e)},events:{},on(r,e){return(this.events[r]||=[]).push(e),()=>{var t;this.events[r]=(t=this.events[r])==null?void 0:t.filter(i=>e!==i)}}});var S=class{events=Z();eventUnsubscribes=[];emitterOptions;constructor(e={}){this.emitterOptions={publicEmit:!1,...e}}on(e,t){let i,n=()=>{i&&(i(),this.eventUnsubscribes=this.eventUnsubscribes.filter(o=>o!==i))};return i=this.events.on(e,t),this.eventUnsubscribes.push(i),n}once(e,t){return new Promise(i=>{let n,o=((...a)=>{t==null||t(...a),n==null||n(),i(a)});n=this.events.on(e,o),this.eventUnsubscribes.push(n)})}onMulti(e){let t=[],i=()=>{for(let n of t)n();t.splice(0,t.length),this.eventUnsubscribes=this.eventUnsubscribes.filter(n=>!t.includes(n))};for(let n of Array.isArray(e)?e:[e]){let o={allOf:[],oneOf:[],once:!1,...n},{oneOf:a,allOf:s,once:u,signal:c,callback:l}=o;if(c!=null&&c.aborted)return i;if(a.length===0&&s.length===0)throw new TypeError("NanoEmitter.onMulti(): Either `oneOf` or `allOf` or both must be provided in the options");let d=[],m=(g=!1)=>{if(!(!(c!=null&&c.aborted)&&!g)){for(let b of d)b();d.splice(0,d.length),this.eventUnsubscribes=this.eventUnsubscribes.filter(b=>!d.includes(b))}},f=new Set,O=()=>s.length===0||f.size===s.length;for(let g of a){let b=this.events.on(g,((...A)=>{m(),O()&&(l(g,...A),u&&m(!0))}));d.push(b)}for(let g of s){let b=this.events.on(g,((...A)=>{m(),f.add(g),O()&&(a.length===0||a.includes(g))&&(l(g,...A),u&&m(!0))}));d.push(b)}t.push(()=>m(!0))}return i}emit(e,...t){return this.emitterOptions.publicEmit?(this.events.emit(e,...t),!0):!1}unsubscribeAll(){for(let e of this.eventUnsubscribes)e();this.eventUnsubscribes=[]}};var X=1,R=class extends S{id;formatVersion;defaultData;encodeData;decodeData;compressionFormat="deflate-raw";memoryCache;engine;keyPrefix;options;firstInit=!0;cachedData;migrations;migrateIds=[];constructor(e){if(super(e.nanoEmitterOptions),this.id=e.id,this.formatVersion=e.formatVersion,this.defaultData=e.defaultData,this.memoryCache=e.memoryCache??!0,this.cachedData=this.memoryCache?e.defaultData:{},this.migrations=e.migrations,e.migrateIds&&(this.migrateIds=Array.isArray(e.migrateIds)?e.migrateIds:[e.migrateIds]),this.engine=typeof e.engine=="function"?e.engine():e.engine,this.keyPrefix=e.keyPrefix??"__ds-",this.options=e,"encodeData"in e&&"decodeData"in e&&Array.isArray(e.encodeData)&&Array.isArray(e.decodeData))this.encodeData=[e.encodeData[0],e.encodeData[1]],this.decodeData=[e.decodeData[0],e.decodeData[1]],this.compressionFormat=e.encodeData[0]??null;else if(e.compressionFormat===null)this.encodeData=void 0,this.decodeData=void 0,this.compressionFormat=null;else{let t=typeof e.compressionFormat=="string"?e.compressionFormat:"deflate-raw";this.compressionFormat=t,this.encodeData=[t,async i=>await I(i,t,"string")],this.decodeData=[t,async i=>await C(i,t,"string")]}this.engine.setDataStoreOptions({id:this.id,encodeData:this.encodeData,decodeData:this.decodeData})}async loadData(){try{if(this.firstInit){this.firstInit=!1;let u=Number(await this.engine.getValue("__ds_fmt_ver",0)),c=await this.engine.getValue(`_uucfg-${this.id}`,null);if(c){let l=Number(await this.engine.getValue(`_uucfgver-${this.id}`,NaN)),d=await this.engine.getValue(`_uucfgenc-${this.id}`,null),m=[],f=(O,g,b)=>{m.push(this.engine.setValue(g,b)),m.push(this.engine.deleteValue(O))};f(`_uucfg-${this.id}`,`${this.keyPrefix}${this.id}-dat`,c),isNaN(l)||f(`_uucfgver-${this.id}`,`${this.keyPrefix}${this.id}-ver`,l),typeof d=="boolean"||d==="true"||d==="false"||typeof d=="number"||d==="0"||d==="1"?f(`_uucfgenc-${this.id}`,`${this.keyPrefix}${this.id}-enf`,[0,"0",!0,"true"].includes(d)?this.compressionFormat??null:null):(m.push(this.engine.setValue(`${this.keyPrefix}${this.id}-enf`,this.compressionFormat)),m.push(this.engine.deleteValue(`_uucfgenc-${this.id}`))),await Promise.allSettled(m)}(isNaN(u)||u<X)&&await this.engine.setValue("__ds_fmt_ver",X)}this.migrateIds.length>0&&(await this.migrateId(this.migrateIds),this.migrateIds=[]);let e=await this.engine.getValue(`${this.keyPrefix}${this.id}-dat`,null),t=Number(await this.engine.getValue(`${this.keyPrefix}${this.id}-ver`,NaN));if(typeof e!="string"&&typeof e!="object"||e===null||isNaN(t)){await this.saveDefaultData(!1);let u=this.engine.deepCopy(this.defaultData);return this.events.emit("loadData",u),u}let i=e??JSON.stringify(this.defaultData),n=String(await this.engine.getValue(`${this.keyPrefix}${this.id}-enf`,null)),o=n!=="null"&&n!=="false"&&n!=="0"&&n!==""&&n!==null,a=typeof i=="string"?await this.engine.deserializeData(i,o):i;t<this.formatVersion&&this.migrations&&(a=await this.runMigrations(a,t));let s=this.memoryCache?this.cachedData=this.engine.deepCopy(a):this.engine.deepCopy(a);return this.events.emit("loadData",s),s}catch(e){let t=e instanceof Error?e:new Error(String(e));return console.warn("Error while parsing JSON data, resetting it to the default value.",e),this.events.emit("error",t),await this.saveDefaultData(),this.defaultData}}getData(){if(!this.memoryCache)throw new p("In-memory cache is disabled for this DataStore instance, so getData() can't be used. Please use loadData() instead.");return this.engine.deepCopy(this.cachedData)}setData(e){let t=this.engine.deepCopy(e);return this.memoryCache&&(this.cachedData=e,this.events.emit("updateDataSync",t)),new Promise(async i=>{let n=await Promise.allSettled([this.engine.setValue(`${this.keyPrefix}${this.id}-dat`,await this.engine.serializeData(e,this.encodingEnabled())),this.engine.setValue(`${this.keyPrefix}${this.id}-ver`,this.formatVersion),this.engine.setValue(`${this.keyPrefix}${this.id}-enf`,this.compressionFormat)]);if(n.every(o=>o.status==="fulfilled"))this.events.emit("updateData",t);else{let o=new Error("Error while saving data to persistent storage: "+n.map(a=>a.status==="rejected"?a.reason:null).filter(Boolean).join("; "));console.error(o),this.events.emit("error",o)}i()})}async saveDefaultData(e=!0){this.memoryCache&&(this.cachedData=this.defaultData);let t=await Promise.allSettled([this.engine.setValue(`${this.keyPrefix}${this.id}-dat`,await this.engine.serializeData(this.defaultData,this.encodingEnabled())),this.engine.setValue(`${this.keyPrefix}${this.id}-ver`,this.formatVersion),this.engine.setValue(`${this.keyPrefix}${this.id}-enf`,this.compressionFormat)]);if(t.every(i=>i.status==="fulfilled"))e&&this.events.emit("setDefaultData",this.defaultData);else{let i=new Error("Error while saving default data to persistent storage: "+t.map(n=>n.status==="rejected"?n.reason:null).filter(Boolean).join("; "));console.error(i),this.events.emit("error",i)}}async deleteData(){var e,t;await Promise.allSettled([this.engine.deleteValue(`${this.keyPrefix}${this.id}-dat`),this.engine.deleteValue(`${this.keyPrefix}${this.id}-ver`),this.engine.deleteValue(`${this.keyPrefix}${this.id}-enf`)]),await((t=(e=this.engine).deleteStorage)==null?void 0:t.call(e)),this.events.emit("deleteData")}encodingEnabled(){return!!(this.encodeData&&this.decodeData)&&this.compressionFormat!==null||!!this.compressionFormat}async runMigrations(e,t,i=!0){if(!this.migrations)return e;let n=e,o=Object.entries(this.migrations).sort(([u],[c])=>Number(u)-Number(c)),a=t;for(let u=0;u<o.length;u++){let[c,l]=o[u],d=Number(c);if(t<this.formatVersion&&t<d)try{let m=l(n);n=m instanceof Promise?await m:m,a=t=d;let f=d>=this.formatVersion||u===o.length-1;this.events.emit("migrateData",d,n,f)}catch(m){let f=new x(`Error while running migration function for format version '${c}'`,{cause:m});if(this.events.emit("migrationError",d,f),this.events.emit("error",f),!i)throw f;return await this.saveDefaultData(),this.engine.deepCopy(this.defaultData)}}await Promise.allSettled([this.engine.setValue(`${this.keyPrefix}${this.id}-dat`,await this.engine.serializeData(n,this.encodingEnabled())),this.engine.setValue(`${this.keyPrefix}${this.id}-ver`,a),this.engine.setValue(`${this.keyPrefix}${this.id}-enf`,this.compressionFormat)]);let s=this.memoryCache?this.cachedData=this.engine.deepCopy(n):this.engine.deepCopy(n);return this.events.emit("updateData",s),s}async migrateId(e){let t=Array.isArray(e)?e:[e];await Promise.all(t.map(async i=>{let[n,o,a]=await(async()=>{let[u,c,l]=await Promise.all([this.engine.getValue(`${this.keyPrefix}${i}-dat`,JSON.stringify(this.defaultData)),this.engine.getValue(`${this.keyPrefix}${i}-ver`,NaN),this.engine.getValue(`${this.keyPrefix}${i}-enf`,null)]);return[u,Number(c),!!l&&String(l)!=="null"]})();if(n===void 0||isNaN(o))return;let s=await this.engine.deserializeData(n,a);await Promise.allSettled([this.engine.setValue(`${this.keyPrefix}${this.id}-dat`,await this.engine.serializeData(s,this.encodingEnabled())),this.engine.setValue(`${this.keyPrefix}${this.id}-ver`,o),this.engine.setValue(`${this.keyPrefix}${this.id}-enf`,this.compressionFormat),this.engine.deleteValue(`${this.keyPrefix}${i}-dat`),this.engine.deleteValue(`${this.keyPrefix}${i}-ver`),this.engine.deleteValue(`${this.keyPrefix}${i}-enf`)]),this.events.emit("migrateId",i,this.id)}))}};var P=class{dataStoreOptions;constructor(e){e&&(this.dataStoreOptions=e)}setDataStoreOptions(e){this.dataStoreOptions=e}async serializeData(e,t){var o,a,s,u,c;this.ensureDataStoreOptions();let i=JSON.stringify(e);if(!t||!((o=this.dataStoreOptions)!=null&&o.encodeData)||!((a=this.dataStoreOptions)!=null&&a.decodeData))return i;let n=(c=(u=(s=this.dataStoreOptions)==null?void 0:s.encodeData)==null?void 0:u[1])==null?void 0:c.call(u,i);return n instanceof Promise?await n:n}async deserializeData(e,t){var n,o,a;this.ensureDataStoreOptions();let i=(n=this.dataStoreOptions)!=null&&n.decodeData&&t?(a=(o=this.dataStoreOptions.decodeData)==null?void 0:o[1])==null?void 0:a.call(o,e):void 0;return i instanceof Promise&&(i=await i),JSON.parse(i??e)}ensureDataStoreOptions(){if(!this.dataStoreOptions)throw new p("DataStoreEngine must be initialized with DataStore options before use. If you are using this instance standalone, set them in the constructor or call `setDataStoreOptions()` with the DataStore options.");if(!this.dataStoreOptions.id)throw new p("DataStoreEngine must be initialized with a valid DataStore ID")}deepCopy(e){try{if("structuredClone"in globalThis)return structuredClone(e)}catch{}return JSON.parse(JSON.stringify(e))}},j=class extends P{options;constructor(e){super(e==null?void 0:e.dataStoreOptions),this.options={type:"localStorage",...e}}async getValue(e,t){let i=this.options.type==="localStorage"?globalThis.localStorage.getItem(e):globalThis.sessionStorage.getItem(e);return typeof i>"u"?t:i}async setValue(e,t){this.options.type==="localStorage"?globalThis.localStorage.setItem(e,String(t)):globalThis.sessionStorage.setItem(e,String(t))}async deleteValue(e){this.options.type==="localStorage"?globalThis.localStorage.removeItem(e):globalThis.sessionStorage.removeItem(e)}},h,B=class extends P{options;fileAccessQueue=Promise.resolve();constructor(e){super(e==null?void 0:e.dataStoreOptions),this.options={filePath:t=>`.ds-${t}`,...e}}async readFile(){var e,t,i,n;this.ensureDataStoreOptions();try{if(h||(h=(e=await import("fs/promises"))==null?void 0:e.default),!h)throw new y("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new p("'node:fs/promises' module not available")});let o=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id,this.dataStoreOptions),a=await h.readFile(o,"utf-8");return a?JSON.parse(await((n=(i=(t=this.dataStoreOptions)==null?void 0:t.decodeData)==null?void 0:i[1])==null?void 0:n.call(i,a))??a):void 0}catch{return}}async writeFile(e){var t,i,n,o;this.ensureDataStoreOptions();try{if(h||(h=(t=await import("fs/promises"))==null?void 0:t.default),!h)throw new y("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new p("'node:fs/promises' module not available")});let a=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id,this.dataStoreOptions);await h.mkdir(a.slice(0,a.lastIndexOf(a.includes("/")?"/":"\\")),{recursive:!0}),await h.writeFile(a,await((o=(n=(i=this.dataStoreOptions)==null?void 0:i.encodeData)==null?void 0:n[1])==null?void 0:o.call(n,JSON.stringify(e)))??JSON.stringify(e,void 0,2),"utf-8")}catch(a){console.error("Error writing file:",a)}}async getValue(e,t){let i=await this.readFile();if(!i)return t;let n=i==null?void 0:i[e];if(typeof n>"u")return t;if(typeof t=="string")return typeof n=="object"&&n!==null?JSON.stringify(n):typeof n=="string"?n:String(n);if(typeof n=="string")try{return JSON.parse(n)}catch{return t}return n}async setValue(e,t){this.fileAccessQueue=this.fileAccessQueue.then(async()=>{let i=await this.readFile();i||(i={});let n=t;if(typeof t=="string")try{if(t.startsWith("{")||t.startsWith("[")){let o=JSON.parse(t);typeof o=="object"&&o!==null&&(n=o)}}catch{}i[e]=n,await this.writeFile(i)}).catch(i=>{throw console.error("Error in setValue:",i),i}),await this.fileAccessQueue.catch(()=>{})}async deleteValue(e){this.fileAccessQueue=this.fileAccessQueue.then(async()=>{let t=await this.readFile();t&&(delete t[e],await this.writeFile(t))}).catch(t=>{throw console.error("Error in deleteValue:",t),t}),await this.fileAccessQueue.catch(()=>{})}async deleteStorage(){var e;this.ensureDataStoreOptions();try{if(h||(h=(e=await import("fs/promises"))==null?void 0:e.default),!h)throw new y("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new p("'node:fs/promises' module not available")});let t=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id,this.dataStoreOptions);return await h.unlink(t)}catch(t){console.error("Error deleting file:",t)}}};var K=class r{stores;options;constructor(e,t={}){if(!crypto||!crypto.subtle)throw new y("DataStoreSerializer has to run in a secure context (HTTPS) or in another environment that implements the subtleCrypto API!");this.stores=e,this.options={addChecksum:!0,ensureIntegrity:!0,remapIds:{},...t}}async calcChecksum(e){return z(e,"SHA-256")}async serializePartial(e,t=!0,i=!0){var a;let n=[],o=this.stores.filter(s=>typeof e=="function"?e(s.id):e.includes(s.id));for(let s of o){let u=!!(t&&s.encodingEnabled()&&((a=s.encodeData)!=null&&a[1])),c=s.memoryCache?s.getData():await s.loadData(),l=u?await s.encodeData[1](JSON.stringify(c)):JSON.stringify(c);n.push({id:s.id,data:l,formatVersion:s.formatVersion,encoded:u,checksum:this.options.addChecksum?await this.calcChecksum(l):void 0})}return i?JSON.stringify(n):n}async serialize(e=!0,t=!0){return this.serializePartial(this.stores.map(i=>i.id),e,t)}async deserializePartial(e,t){let i=typeof t=="string"?JSON.parse(t):t;if(!Array.isArray(i)||!i.every(r.isSerializedDataStoreObj))throw new TypeError("Invalid serialized data format! Expected an array of SerializedDataStore objects.");let n=a=>{var s;return((s=Object.entries(this.options.remapIds).find(([,u])=>u.includes(a)))==null?void 0:s[0])??a},o=a=>typeof e=="function"?e(a):e.includes(a);for(let a of i){let s=n(a.id);if(!o(s))continue;let u=this.stores.find(l=>l.id===s);if(!u)throw new p(`Can't deserialize data because no DataStore instance with the ID "${s}" was found! Make sure to provide it in the DataStoreSerializer constructor.`);if(this.options.ensureIntegrity&&typeof a.checksum=="string"){let l=await this.calcChecksum(a.data);if(l!==a.checksum)throw new v(`Checksum mismatch for DataStore with ID "${a.id}"!
|
|
3
|
+
`)}}function Ie(r){var n;let e=0,t=!1;(n=r.signal)==null||n.addEventListener("abort",()=>{t=!0},{once:!0});let i=async(o=!1)=>{var a;if(!t){try{if(((r.immediate??!0)||!o)&&(e++,await((a=r.condition)==null?void 0:a.call(r,e-1))??!0)){let s=await r.task(e-1);r.onSuccess&&await r.onSuccess(s,e-1)}}catch(s){if(r.onError&&await r.onError(s,e-1),r.abortOnError&&(t=!0),!r.onError&&!r.abortOnError)throw s}!t&&(typeof r.maxIterations!="number"||e<r.maxIterations)&&setTimeout(i,r.timeout)}};return i(!0)}function Re(r,e,t="auto"){switch(typeof e!="number"&&("length"in e?e=e.length:"size"in e?e=e.size:"count"in e&&(e=e.count)),["-s","-ies"].includes(t)||(t="auto"),isNaN(e)&&(e=2),t==="auto"?String(r).endsWith("y")?"-ies":"-s":t){case"-s":return`${r}${e===1?"":"s"}`;case"-ies":return`${String(r).slice(0,-1)}${e===1?"y":"ies"}`}}function ze(r){return r.charAt(0).toUpperCase()+r.slice(1)}var ie={100:"\u2588",75:"\u2593",50:"\u2592",25:"\u2591",0:"\u2500"};function Ue(r,e,t=ie){if(r===100)return t[100].repeat(e);let i=Math.floor(r/100*e),n=r/10*e-i,o="";n>=.75?o=t[75]:n>=.5?o=t[50]:n>=.25&&(o=t[25]);let a=t[100].repeat(i),s=t[0].repeat(e-i-(o?1:0));return`${a}${o}${s}`}function Le(r,...e){return r.replace(/%\d/gm,t=>{var n;let i=Number(t.substring(1))-1;return(n=e[i]??t)==null?void 0:n.toString()})}function je(r,e=", ",t=" and "){let i=[...r];if(i.length===0)return"";if(i.length===1)return String(i[0]);if(i.length===2)return i.join(t);let n=t+i[i.length-1];return i.pop(),i.join(e)+n}function Be(r){let e=r<0,t=Math.abs(r);if(isNaN(t)||!isFinite(t))throw new TypeError("The seconds argument must be a valid number");let i=Math.floor(t/3600),n=Math.floor(t%3600/60),o=Math.floor(t%60);return(e?"-":"")+[i?i+":":"",String(n).padStart(n>0||i>0?2:1,"0"),":",String(o).padStart(o>0||n>0||i>0||r===0?2:1,"0")].join("")}function Ke(r,e,t="..."){let i=(r==null?void 0:r.toString())??String(r),n=i.length>e?i.substring(0,e-t.length)+t:i;return n.length>e?n.substring(0,e):n}var ne={single:{horizontal:"\u2500",vertical:"\u2502",topLeft:"\u250C",topRight:"\u2510",bottomLeft:"\u2514",bottomRight:"\u2518",leftT:"\u251C",rightT:"\u2524",topT:"\u252C",bottomT:"\u2534",cross:"\u253C"},double:{horizontal:"\u2550",vertical:"\u2551",topLeft:"\u2554",topRight:"\u2557",bottomLeft:"\u255A",bottomRight:"\u255D",leftT:"\u2560",rightT:"\u2563",topT:"\u2566",bottomT:"\u2569",cross:"\u256C"},none:{horizontal:" ",vertical:" ",topLeft:" ",topRight:" ",bottomLeft:" ",bottomRight:" ",leftT:" ",rightT:" ",topT:" ",bottomT:" ",cross:" "}};function qe(r,e){var h;let t={columnAlign:"left",truncateAbove:1/0,truncEndStr:"\u2026",minPadding:1,lineStyle:"single",applyCellStyle:()=>{},applyLineStyle:()=>{},lineCharset:ne,...e??{}},i=(l,f,d)=>P(typeof l!="number"||isNaN(Number(l))?f:l,f,d);t.truncateAbove=i(t.truncateAbove,0,1/0),t.minPadding=i(t.minPadding,0,1/0);let n=t.lineCharset[t.lineStyle],o=l=>l.replace(/\u001b\[[0-9;]*m/g,""),a=r.map(l=>l.map(f=>String(f))),s=((h=r[0])==null?void 0:h.length)??0;if(s===0||a.length===0)return"";if(isFinite(t.truncateAbove)){let l=(f,d,g)=>{let y=d-g.length;if(y<=0)return g.slice(0,d);let T=0,D="",v=0,w=!1;for(;v<f.length;){if(f[v]==="\x1B"&&f[v+1]==="["){let A=f.indexOf("m",v+2);if(A!==-1){D+=f.slice(v,A+1),w=!0,v=A+1;continue}}if(T===y)return D+=g,w&&(D+="\x1B[0m"),D;D+=f[v],T++,v++}return D};for(let f of a)for(let d=0;d<f.length;d++)o(f[d]??"").length>t.truncateAbove&&(f[d]=l(f[d]??"",t.truncateAbove,t.truncEndStr))}let u=Array.from({length:s},(l,f)=>Math.max(0,...a.map(d=>o(d[f]??"").length))),c=(l,f,d)=>{let[g="",y=""]=t.applyLineStyle(l,f)??[];return`${g}${d}${y}`},m=(l,f,d,g)=>{let y="",T=0;y+=c(l,T++,f);for(let D=0;D<s;D++){let v=(u[D]??0)+t.minPadding*2;for(let w=0;w<v;w++)y+=c(l,T++,n.horizontal);D<s-1&&(y+=c(l,T++,d))}return y+=c(l,T++,g),y},p=[];for(let l=0;l<a.length;l++){let f=a[l]??[],d=l*3;t.lineStyle!=="none"&&p.push(l===0?m(d,n.topLeft,n.topT,n.topRight):m(d,n.leftT,n.cross,n.rightT));let g="",y=0;g+=c(d+1,y++,n.vertical);for(let T=0;T<s;T++){let D=f[T]??"",v=o(D).length,w=(u[T]??0)-v,A=(Array.isArray(t.columnAlign)?t.columnAlign[T]:t.columnAlign)??"left",N,V;switch(A){case"right":N=t.minPadding+w,V=t.minPadding;break;case"centerLeft":N=t.minPadding+Math.floor(w/2),V=t.minPadding+Math.ceil(w/2);break;case"centerRight":N=t.minPadding+Math.ceil(w/2),V=t.minPadding+Math.floor(w/2);break;default:N=t.minPadding,V=t.minPadding+w}let[se="",ue=""]=t.applyCellStyle(l,T)??[];g+=" ".repeat(N)+se+D+ue+" ".repeat(V),g+=c(d+1,y++,n.vertical)}p.push(g),t.lineStyle!=="none"&&l===a.length-1&&p.push(m(d+2,n.bottomLeft,n.bottomT,n.bottomRight))}return p.join(`
|
|
4
|
+
`)}var ae=()=>({emit(r,...e){for(let t=this.events[r]||[],i=0,n=t.length;i<n;i++)t[i](...e)},events:{},on(r,e){return(this.events[r]||=[]).push(e),()=>{var t;this.events[r]=(t=this.events[r])==null?void 0:t.filter(i=>e!==i)}}});var E=class{events=ae();eventUnsubscribes=[];emitterOptions;constructor(e={}){this.emitterOptions={publicEmit:!1,...e}}on(e,t){let i,n=()=>{i&&(i(),this.eventUnsubscribes=this.eventUnsubscribes.filter(o=>o!==i))};return i=this.events.on(e,t),this.eventUnsubscribes.push(i),n}once(e,t){return new Promise(i=>{let n,o=((...a)=>{t==null||t(...a),n==null||n(),i(a)});n=this.events.on(e,o),this.eventUnsubscribes.push(n)})}onMulti(e){let t=[],i=()=>{for(let n of t)n();t.splice(0,t.length),this.eventUnsubscribes=this.eventUnsubscribes.filter(n=>!t.includes(n))};for(let n of Array.isArray(e)?e:[e]){let o={allOf:[],oneOf:[],once:!1,...n},{oneOf:a,allOf:s,once:u,signal:c,callback:m}=o;if(c!=null&&c.aborted)return i;if(a.length===0&&s.length===0)throw new TypeError("NanoEmitter.onMulti(): Either `oneOf` or `allOf` or both must be provided in the options");let p=[],h=(d=!1)=>{if(!(!(c!=null&&c.aborted)&&!d)){for(let g of p)g();p.splice(0,p.length),this.eventUnsubscribes=this.eventUnsubscribes.filter(g=>!p.includes(g))}},l=new Set,f=()=>s.length===0||l.size===s.length;for(let d of a){let g=this.events.on(d,((...y)=>{h(),f()&&(m(d,...y),u&&h(!0))}));p.push(g)}for(let d of s){let g=this.events.on(d,((...y)=>{h(),l.add(d),f()&&(a.length===0||a.includes(d))&&(m(d,...y),u&&h(!0))}));p.push(g)}t.push(()=>h(!0))}return i}emit(e,...t){return this.emitterOptions.publicEmit?(this.events.emit(e,...t),!0):!1}unsubscribeAll(){for(let e of this.eventUnsubscribes)e();this.eventUnsubscribes=[]}};var oe=1,_=class extends E{id;formatVersion;defaultData;encodeData;decodeData;compressionFormat="deflate-raw";memoryCache;engine;keyPrefix;options;firstInit=!0;cachedData;migrations;migrateIds=[];constructor(e){if(super(e.nanoEmitterOptions),this.id=e.id,this.formatVersion=e.formatVersion,this.defaultData=e.defaultData,this.memoryCache=e.memoryCache??!0,this.cachedData=this.memoryCache?e.defaultData:{},this.migrations=e.migrations,e.migrateIds&&(this.migrateIds=Array.isArray(e.migrateIds)?e.migrateIds:[e.migrateIds]),this.engine=typeof e.engine=="function"?e.engine():e.engine,this.keyPrefix=e.keyPrefix??"__ds-",this.options=e,"encodeData"in e&&"decodeData"in e&&Array.isArray(e.encodeData)&&Array.isArray(e.decodeData))this.encodeData=[e.encodeData[0],e.encodeData[1]],this.decodeData=[e.decodeData[0],e.decodeData[1]],this.compressionFormat=e.encodeData[0]??null;else if(e.compressionFormat===null)this.encodeData=void 0,this.decodeData=void 0,this.compressionFormat=null;else{let t=typeof e.compressionFormat=="string"?e.compressionFormat:"deflate-raw";this.compressionFormat=t,this.encodeData=[t,async i=>await B(i,t,"string")],this.decodeData=[t,async i=>await K(i,t,"string")]}this.engine.setDataStoreOptions({id:this.id,encodeData:this.encodeData,decodeData:this.decodeData})}async loadData(){try{if(this.firstInit){this.firstInit=!1;let u=Number(await this.engine.getValue("__ds_fmt_ver",0)),c=await this.engine.getValue(`_uucfg-${this.id}`,null);if(c){let m=Number(await this.engine.getValue(`_uucfgver-${this.id}`,NaN)),p=await this.engine.getValue(`_uucfgenc-${this.id}`,null),h=[],l=(f,d,g)=>{h.push(this.engine.setValue(d,g)),h.push(this.engine.deleteValue(f))};l(`_uucfg-${this.id}`,`${this.keyPrefix}${this.id}-dat`,c),isNaN(m)||l(`_uucfgver-${this.id}`,`${this.keyPrefix}${this.id}-ver`,m),typeof p=="boolean"||p==="true"||p==="false"||typeof p=="number"||p==="0"||p==="1"?l(`_uucfgenc-${this.id}`,`${this.keyPrefix}${this.id}-enf`,[0,"0",!0,"true"].includes(p)?this.compressionFormat??null:null):(h.push(this.engine.setValue(`${this.keyPrefix}${this.id}-enf`,this.compressionFormat)),h.push(this.engine.deleteValue(`_uucfgenc-${this.id}`))),await Promise.allSettled(h)}(isNaN(u)||u<oe)&&await this.engine.setValue("__ds_fmt_ver",oe)}this.migrateIds.length>0&&(await this.migrateId(this.migrateIds),this.migrateIds=[]);let e=await this.engine.getValue(`${this.keyPrefix}${this.id}-dat`,null),t=Number(await this.engine.getValue(`${this.keyPrefix}${this.id}-ver`,NaN));if(typeof e!="string"&&typeof e!="object"||e===null||isNaN(t)){await this.saveDefaultData(!1);let u=this.engine.deepCopy(this.defaultData);return this.events.emit("loadData",u),u}let i=e??JSON.stringify(this.defaultData),n=String(await this.engine.getValue(`${this.keyPrefix}${this.id}-enf`,null)),o=n!=="null"&&n!=="false"&&n!=="0"&&n!==""&&n!==null,a=typeof i=="string"?await this.engine.deserializeData(i,o):i;t<this.formatVersion&&this.migrations&&(a=await this.runMigrations(a,t));let s=this.memoryCache?this.cachedData=this.engine.deepCopy(a):this.engine.deepCopy(a);return this.events.emit("loadData",s),s}catch(e){let t=e instanceof Error?e:new Error(String(e));return console.warn("Error while parsing JSON data, resetting it to the default value.",e),this.events.emit("error",t),await this.saveDefaultData(),this.defaultData}}getData(){if(!this.memoryCache)throw new b("In-memory cache is disabled for this DataStore instance, so getData() can't be used. Please use loadData() instead.");return this.engine.deepCopy(this.cachedData)}setData(e){let t=this.engine.deepCopy(e);return this.memoryCache&&(this.cachedData=e,this.events.emit("updateDataSync",t)),new Promise(async i=>{let n=await Promise.allSettled([this.engine.setValue(`${this.keyPrefix}${this.id}-dat`,await this.engine.serializeData(e,this.encodingEnabled())),this.engine.setValue(`${this.keyPrefix}${this.id}-ver`,this.formatVersion),this.engine.setValue(`${this.keyPrefix}${this.id}-enf`,this.compressionFormat)]);if(n.every(o=>o.status==="fulfilled"))this.events.emit("updateData",t);else{let o=new Error("Error while saving data to persistent storage: "+n.map(a=>a.status==="rejected"?a.reason:null).filter(Boolean).join("; "));console.error(o),this.events.emit("error",o)}i()})}async saveDefaultData(e=!0){this.memoryCache&&(this.cachedData=this.defaultData);let t=await Promise.allSettled([this.engine.setValue(`${this.keyPrefix}${this.id}-dat`,await this.engine.serializeData(this.defaultData,this.encodingEnabled())),this.engine.setValue(`${this.keyPrefix}${this.id}-ver`,this.formatVersion),this.engine.setValue(`${this.keyPrefix}${this.id}-enf`,this.compressionFormat)]);if(t.every(i=>i.status==="fulfilled"))e&&this.events.emit("setDefaultData",this.defaultData);else{let i=new Error("Error while saving default data to persistent storage: "+t.map(n=>n.status==="rejected"?n.reason:null).filter(Boolean).join("; "));console.error(i),this.events.emit("error",i)}}async deleteData(){var e,t;await Promise.allSettled([this.engine.deleteValue(`${this.keyPrefix}${this.id}-dat`),this.engine.deleteValue(`${this.keyPrefix}${this.id}-ver`),this.engine.deleteValue(`${this.keyPrefix}${this.id}-enf`)]),await((t=(e=this.engine).deleteStorage)==null?void 0:t.call(e)),this.events.emit("deleteData")}encodingEnabled(){return!!(this.encodeData&&this.decodeData)&&this.compressionFormat!==null||!!this.compressionFormat}async runMigrations(e,t,i=!0){if(!this.migrations)return e;let n=e,o=Object.entries(this.migrations).sort(([u],[c])=>Number(u)-Number(c)),a=t;for(let u=0;u<o.length;u++){let[c,m]=o[u],p=Number(c);if(t<this.formatVersion&&t<p)try{let h=m(n);n=h instanceof Promise?await h:h,a=t=p;let l=p>=this.formatVersion||u===o.length-1;this.events.emit("migrateData",p,n,l)}catch(h){let l=new M(`Error while running migration function for format version '${c}'`,{cause:h});if(this.events.emit("migrationError",p,l),this.events.emit("error",l),!i)throw l;return await this.saveDefaultData(),this.engine.deepCopy(this.defaultData)}}await Promise.allSettled([this.engine.setValue(`${this.keyPrefix}${this.id}-dat`,await this.engine.serializeData(n,this.encodingEnabled())),this.engine.setValue(`${this.keyPrefix}${this.id}-ver`,a),this.engine.setValue(`${this.keyPrefix}${this.id}-enf`,this.compressionFormat)]);let s=this.memoryCache?this.cachedData=this.engine.deepCopy(n):this.engine.deepCopy(n);return this.events.emit("updateData",s),s}async migrateId(e){let t=Array.isArray(e)?e:[e];await Promise.all(t.map(async i=>{let[n,o,a]=await(async()=>{let[u,c,m]=await Promise.all([this.engine.getValue(`${this.keyPrefix}${i}-dat`,JSON.stringify(this.defaultData)),this.engine.getValue(`${this.keyPrefix}${i}-ver`,NaN),this.engine.getValue(`${this.keyPrefix}${i}-enf`,null)]);return[u,Number(c),!!m&&String(m)!=="null"]})();if(n===void 0||isNaN(o))return;let s=await this.engine.deserializeData(n,a);await Promise.allSettled([this.engine.setValue(`${this.keyPrefix}${this.id}-dat`,await this.engine.serializeData(s,this.encodingEnabled())),this.engine.setValue(`${this.keyPrefix}${this.id}-ver`,o),this.engine.setValue(`${this.keyPrefix}${this.id}-enf`,this.compressionFormat),this.engine.deleteValue(`${this.keyPrefix}${i}-dat`),this.engine.deleteValue(`${this.keyPrefix}${i}-ver`),this.engine.deleteValue(`${this.keyPrefix}${i}-enf`)]),this.events.emit("migrateId",i,this.id)}))}};var $=class{dataStoreOptions;constructor(e){e&&(this.dataStoreOptions=e)}setDataStoreOptions(e){this.dataStoreOptions=e}async serializeData(e,t){var o,a,s,u,c;this.ensureDataStoreOptions();let i=JSON.stringify(e);if(!t||!((o=this.dataStoreOptions)!=null&&o.encodeData)||!((a=this.dataStoreOptions)!=null&&a.decodeData))return i;let n=(c=(u=(s=this.dataStoreOptions)==null?void 0:s.encodeData)==null?void 0:u[1])==null?void 0:c.call(u,i);return n instanceof Promise?await n:n}async deserializeData(e,t){var n,o,a;this.ensureDataStoreOptions();let i=(n=this.dataStoreOptions)!=null&&n.decodeData&&t?(a=(o=this.dataStoreOptions.decodeData)==null?void 0:o[1])==null?void 0:a.call(o,e):void 0;return i instanceof Promise&&(i=await i),JSON.parse(i??e)}ensureDataStoreOptions(){if(!this.dataStoreOptions)throw new b("DataStoreEngine must be initialized with DataStore options before use. If you are using this instance standalone, set them in the constructor or call `setDataStoreOptions()` with the DataStore options.");if(!this.dataStoreOptions.id)throw new b("DataStoreEngine must be initialized with a valid DataStore ID")}deepCopy(e){try{if("structuredClone"in globalThis)return structuredClone(e)}catch{}return JSON.parse(JSON.stringify(e))}},W=class extends ${options;constructor(e){super(e==null?void 0:e.dataStoreOptions),this.options={type:"localStorage",...e}}async getValue(e,t){let i=this.options.type==="localStorage"?globalThis.localStorage.getItem(e):globalThis.sessionStorage.getItem(e);return typeof i>"u"?t:i}async setValue(e,t){this.options.type==="localStorage"?globalThis.localStorage.setItem(e,String(t)):globalThis.sessionStorage.setItem(e,String(t))}async deleteValue(e){this.options.type==="localStorage"?globalThis.localStorage.removeItem(e):globalThis.sessionStorage.removeItem(e)}},S,H=class extends ${options;fileAccessQueue=Promise.resolve();constructor(e){super(e==null?void 0:e.dataStoreOptions),this.options={filePath:t=>`.ds-${t}`,...e}}async readFile(){var e,t,i,n;this.ensureDataStoreOptions();try{if(S||(S=(e=await import("fs/promises"))==null?void 0:e.default),!S)throw new x("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new b("'node:fs/promises' module not available")});let o=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id,this.dataStoreOptions),a=await S.readFile(o,"utf-8");return a?JSON.parse(await((n=(i=(t=this.dataStoreOptions)==null?void 0:t.decodeData)==null?void 0:i[1])==null?void 0:n.call(i,a))??a):void 0}catch{return}}async writeFile(e){var t,i,n,o;this.ensureDataStoreOptions();try{if(S||(S=(t=await import("fs/promises"))==null?void 0:t.default),!S)throw new x("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new b("'node:fs/promises' module not available")});let a=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id,this.dataStoreOptions);await S.mkdir(a.slice(0,a.lastIndexOf(a.includes("/")?"/":"\\")),{recursive:!0}),await S.writeFile(a,await((o=(n=(i=this.dataStoreOptions)==null?void 0:i.encodeData)==null?void 0:n[1])==null?void 0:o.call(n,JSON.stringify(e)))??JSON.stringify(e,void 0,2),"utf-8")}catch(a){console.error("Error writing file:",a)}}async getValue(e,t){let i=await this.readFile();if(!i)return t;let n=i==null?void 0:i[e];if(typeof n>"u")return t;if(typeof t=="string")return typeof n=="object"&&n!==null?JSON.stringify(n):typeof n=="string"?n:String(n);if(typeof n=="string")try{return JSON.parse(n)}catch{return t}return n}async setValue(e,t){this.fileAccessQueue=this.fileAccessQueue.then(async()=>{let i=await this.readFile();i||(i={});let n=t;if(typeof t=="string")try{if(t.startsWith("{")||t.startsWith("[")){let o=JSON.parse(t);typeof o=="object"&&o!==null&&(n=o)}}catch{}i[e]=n,await this.writeFile(i)}).catch(i=>{throw console.error("Error in setValue:",i),i}),await this.fileAccessQueue.catch(()=>{})}async deleteValue(e){this.fileAccessQueue=this.fileAccessQueue.then(async()=>{let t=await this.readFile();t&&(delete t[e],await this.writeFile(t))}).catch(t=>{throw console.error("Error in deleteValue:",t),t}),await this.fileAccessQueue.catch(()=>{})}async deleteStorage(){var e;this.ensureDataStoreOptions();try{if(S||(S=(e=await import("fs/promises"))==null?void 0:e.default),!S)throw new x("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new b("'node:fs/promises' module not available")});let t=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id,this.dataStoreOptions);return await S.unlink(t)}catch(t){console.error("Error deleting file:",t)}}};var Q=class r{stores;options;constructor(e,t={}){if(!crypto||!crypto.subtle)throw new x("DataStoreSerializer has to run in a secure context (HTTPS) or in another environment that implements the subtleCrypto API!");this.stores=e,this.options={addChecksum:!0,ensureIntegrity:!0,remapIds:{},...t}}async calcChecksum(e){return q(e,"SHA-256")}async serializePartial(e,t=!0,i=!0){var a;let n=[],o=this.stores.filter(s=>typeof e=="function"?e(s.id):e.includes(s.id));for(let s of o){let u=!!(t&&s.encodingEnabled()&&((a=s.encodeData)!=null&&a[1])),c=s.memoryCache?s.getData():await s.loadData(),m=u?await s.encodeData[1](JSON.stringify(c)):JSON.stringify(c);n.push({id:s.id,data:m,formatVersion:s.formatVersion,encoded:u,checksum:this.options.addChecksum?await this.calcChecksum(m):void 0})}return i?JSON.stringify(n):n}async serialize(e=!0,t=!0){return this.serializePartial(this.stores.map(i=>i.id),e,t)}async deserializePartial(e,t){let i=typeof t=="string"?JSON.parse(t):t;if(!Array.isArray(i)||!i.every(r.isSerializedDataStoreObj))throw new TypeError("Invalid serialized data format! Expected an array of SerializedDataStore objects.");let n=a=>{var s;return((s=Object.entries(this.options.remapIds).find(([,u])=>u.includes(a)))==null?void 0:s[0])??a},o=a=>typeof e=="function"?e(a):e.includes(a);for(let a of i){let s=n(a.id);if(!o(s))continue;let u=this.stores.find(m=>m.id===s);if(!u)throw new b(`Can't deserialize data because no DataStore instance with the ID "${s}" was found! Make sure to provide it in the DataStoreSerializer constructor.`);if(this.options.ensureIntegrity&&typeof a.checksum=="string"){let m=await this.calcChecksum(a.data);if(m!==a.checksum)throw new F(`Checksum mismatch for DataStore with ID "${a.id}"!
|
|
4
5
|
Expected: ${a.checksum}
|
|
5
|
-
Has: ${
|
|
6
|
+
Has: ${m}`)}let c=a.encoded&&u.encodingEnabled()?await u.decodeData[1](a.data):a.data;a.formatVersion&&!isNaN(Number(a.formatVersion))&&Number(a.formatVersion)<u.formatVersion?await u.runMigrations(JSON.parse(c),Number(a.formatVersion),!1):await u.setData(JSON.parse(c))}}async deserialize(e){return this.deserializePartial(this.stores.map(t=>t.id),e)}async loadStoresData(e){return Promise.allSettled(this.getStoresFiltered(e).map(async t=>({id:t.id,data:await t.loadData()})))}async resetStoresData(e){return Promise.allSettled(this.getStoresFiltered(e).map(t=>t.saveDefaultData()))}async deleteStoresData(e){return Promise.allSettled(this.getStoresFiltered(e).map(t=>t.deleteData()))}static isSerializedDataStoreObjArray(e){return Array.isArray(e)&&e.every(t=>typeof t=="object"&&t!==null&&"id"in t&&"data"in t&&"formatVersion"in t&&"encoded"in t)}static isSerializedDataStoreObj(e){return typeof e=="object"&&e!==null&&"id"in e&&"data"in e&&"formatVersion"in e&&"encoded"in e}getStoresFiltered(e){return this.stores.filter(t=>typeof e>"u"?!0:Array.isArray(e)?e.includes(t.id):e(t.id))}};var z=class extends E{constructor(t=200,i="immediate",n){super(n);this.timeout=t;this.type=i}listeners=[];activeTimeout;queuedCall;addListener(t){this.listeners.push(t)}removeListener(t){let i=this.listeners.findIndex(n=>n===t);i!==-1&&this.listeners.splice(i,1)}removeAllListeners(){this.listeners=[]}getListeners(){return this.listeners}setTimeout(t){this.events.emit("change",this.timeout=t,this.type)}getTimeout(){return this.timeout}isTimeoutActive(){return typeof this.activeTimeout<"u"}setType(t){this.events.emit("change",this.timeout,this.type=t)}getType(){return this.type}call(...t){let i=(...o)=>{this.queuedCall=void 0,this.events.emit("call",...o),this.listeners.forEach(a=>a.call(this,...o))},n=()=>{this.activeTimeout=setTimeout(()=>{this.queuedCall?(this.queuedCall(),n()):this.activeTimeout=void 0},this.timeout)};switch(this.type){case"immediate":typeof this.activeTimeout>"u"?(i(...t),n()):this.queuedCall=()=>i(...t);break;case"idle":this.activeTimeout&&clearTimeout(this.activeTimeout),this.activeTimeout=setTimeout(()=>{i(...t),this.activeTimeout=void 0},this.timeout);break;default:throw new TypeError(`Invalid debouncer type: ${this.type}`)}}};function Je(r,e=200,t="immediate",i){let n=new z(e,t,i);n.addListener(r);let o=((...a)=>n.call(...a));return o.debouncer=n,o}
|
|
6
7
|
//# sourceMappingURL=CoreUtils.min.cjs.map
|