@sv443-network/coreutils 3.4.0 → 3.5.1
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 +16 -0
- package/README.md +11 -4
- package/dist/CoreUtils.cjs +170 -0
- 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 +170 -0
- package/dist/CoreUtils.umd.js +751 -461
- package/dist/lib/DataStoreSerializer.d.ts +4 -4
- package/dist/lib/text.d.ts +65 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,21 @@
|
|
|
1
1
|
# @sv443-network/coreutils
|
|
2
2
|
|
|
3
|
+
## 3.5.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- bea712a: Fixed build error that led to a SyntaxError.
|
|
8
|
+
|
|
9
|
+
## 3.5.0
|
|
10
|
+
|
|
11
|
+
### Minor Changes
|
|
12
|
+
|
|
13
|
+
- 9a2f561: Added function `createTable()` to create a very flexible ASCII table, including ANSI color and `%c` styling support.
|
|
14
|
+
|
|
15
|
+
### Patch Changes
|
|
16
|
+
|
|
17
|
+
- 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>`.
|
|
18
|
+
|
|
3
19
|
## 3.4.0
|
|
4
20
|
|
|
5
21
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -30,7 +30,7 @@ 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
|
|
@@ -41,7 +41,7 @@ Intended to be used in conjunction with [`@sv443-network/userutils`](https://git
|
|
|
41
41
|
- 🔷 [`type LoadStoresDataResult`](./docs.md#type-loadstoresdataresult) - Result of calling [`loadStoresData()`](./docs.md#datastoreserializer-loadstoresdata)
|
|
42
42
|
- 🔷 [`type SerializedDataStore`](./docs.md#type-serializeddatastore) - Meta object and serialized data of a DataStore instance
|
|
43
43
|
- 🔷 [`type StoreFilter`](./docs.md#type-storefilter) - Filter for selecting data stores
|
|
44
|
-
- 🟧 [`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
|
|
45
45
|
- 🔷 [`type DataStoreEngineDSOptions`](./docs.md#type-datastoreenginedsoptions) - Reduced version of [`DataStoreOptions`](./docs.md#type-datastoreoptions)
|
|
46
46
|
- [Storage Engines:](./docs.md#storage-engines)
|
|
47
47
|
- 🟧 [`class BrowserStorageEngine`](./docs.md#class-browserstorageengine) - Storage engine for browser environments (localStorage, sessionStorage)
|
|
@@ -94,10 +94,17 @@ Intended to be used in conjunction with [`@sv443-network/userutils`](https://git
|
|
|
94
94
|
- 🟣 [`function autoPlural()`](./docs.md#function-autoplural) - Turns the given term into its plural form, depending on the given number or list length
|
|
95
95
|
- 🟣 [`function capitalize()`](./docs.md#function-capitalize) - Capitalizes the first letter of the given string
|
|
96
96
|
- 🟣 [`function createProgressBar()`](./docs.md#function-createprogressbar) - Creates a progress bar string with the given percentage and length
|
|
97
|
-
-
|
|
97
|
+
- 🟩 [`const defaultPbChars`](./docs.md#const-defaultpbchars) - Default characters for the progress bar
|
|
98
98
|
- 🔷 [`type ProgressBarChars`](./docs.md#type-progressbarchars) - Type for the progress bar characters object
|
|
99
99
|
- 🟣 [`function joinArrayReadable()`](./docs.md#function-joinarrayreadable) - Joins the given array into a string, using the given separators and last separator
|
|
100
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
|
|
101
108
|
- 🟣 [`function truncStr()`](./docs.md#function-truncstr) - Truncates the given string to the given length
|
|
102
109
|
<!-- - *[**TieredCache:**](./docs.md#tieredcache)
|
|
103
110
|
- 🟧 *[`class TieredCache`](./docs.md#class-tieredcache) - A multi-tier cache that uses multiple storage engines with different expiration times
|
|
@@ -129,7 +136,7 @@ Intended to be used in conjunction with [`@sv443-network/userutils`](https://git
|
|
|
129
136
|
> 🟣 = function
|
|
130
137
|
> 🟧 = class
|
|
131
138
|
> 🔷 = type
|
|
132
|
-
>
|
|
139
|
+
> 🟩 = const
|
|
133
140
|
|
|
134
141
|
<br>
|
|
135
142
|
|
package/dist/CoreUtils.cjs
CHANGED
|
@@ -56,10 +56,12 @@ __export(lib_exports, {
|
|
|
56
56
|
consumeStringGen: () => consumeStringGen,
|
|
57
57
|
createProgressBar: () => createProgressBar,
|
|
58
58
|
createRecurringTask: () => createRecurringTask,
|
|
59
|
+
createTable: () => createTable,
|
|
59
60
|
darkenColor: () => darkenColor,
|
|
60
61
|
debounce: () => debounce,
|
|
61
62
|
decompress: () => decompress,
|
|
62
63
|
defaultPbChars: () => defaultPbChars,
|
|
64
|
+
defaultTableLineCharset: () => defaultTableLineCharset,
|
|
63
65
|
digitCount: () => digitCount,
|
|
64
66
|
fetchAdvanced: () => fetchAdvanced,
|
|
65
67
|
formatNumber: () => formatNumber,
|
|
@@ -588,6 +590,173 @@ function truncStr(input, length, endStr = "...") {
|
|
|
588
590
|
const finalStr = str.length > length ? str.substring(0, length - endStr.length) + endStr : str;
|
|
589
591
|
return finalStr.length > length ? finalStr.substring(0, length) : finalStr;
|
|
590
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
|
+
}
|
|
591
760
|
|
|
592
761
|
// node_modules/.pnpm/nanoevents@9.1.0/node_modules/nanoevents/index.js
|
|
593
762
|
var createNanoEvents = () => ({
|
|
@@ -1298,6 +1467,7 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
1298
1467
|
// lib/DataStoreSerializer.ts
|
|
1299
1468
|
var DataStoreSerializer = class _DataStoreSerializer {
|
|
1300
1469
|
stores;
|
|
1470
|
+
// eslint-disable-line @typescript-eslint/no-explicit-any
|
|
1301
1471
|
options;
|
|
1302
1472
|
constructor(stores, options = {}) {
|
|
1303
1473
|
if (!crypto || !crypto.subtle)
|
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){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 Oe(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 Ne(r){return r.charAt(0).toUpperCase()+r.slice(1)}var G={100:"\u2588",75:"\u2593",50:"\u2592",25:"\u2591",0:"\u2500"};function Ve(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 ke(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 Me(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 T=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 y of d)y();d.splice(0,d.length),this.eventUnsubscribes=this.eventUnsubscribes.filter(y=>!d.includes(y))}},f=new Set,O=()=>s.length===0||f.size===s.length;for(let g of a){let y=this.events.on(g,((...k)=>{m(),O()&&(l(g,...k),u&&m(!0))}));d.push(y)}for(let g of s){let y=this.events.on(g,((...k)=>{m(),f.add(g),O()&&(a.length===0||a.includes(g))&&(l(g,...k),u&&m(!0))}));d.push(y)}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,U=class extends T{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,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,y)=>{m.push(this.engine.setValue(g,y)),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 b("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 b("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 b("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 L=class r{stores;options;constructor(e,t={}){if(!crypto||!crypto.subtle)throw new b("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 w(`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
|
package/dist/CoreUtils.min.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
function
|
|
1
|
+
function oe(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 se(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 ue(r,e,t){return r.toLocaleString(e,t==="short"?{notation:"compact",compactDisplay:"short",maximumFractionDigits:1}:{style:"decimal",maximumFractionDigits:0})}function I(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 le(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(I(o,0,255,e,t)).toString(10)).join(""))}else return Math.floor(Math.random()*(t-e+1))+e}function z(r,e){let t=10**e;return Math.round(r*t)/t}function ce(r,e,t=1,i=.5){return Math.abs(z(r,t)-z(e,t))<=i}function pe(r){return U(r)[0]}function U(r){if(r.length===0)return[void 0,void 0];let e=k(r.length-1);return[r[e],e]}function fe(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 he(r){var e;return(e=X(r))==null?void 0:e[0]}function X(r){let[e,t]=U(r);return t===void 0?[void 0,void 0]:(r.splice(t,1),[e,t])}function Y(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]=ee(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?te(n,o,a,s,r.startsWith("#"),t):r.startsWith("rgba")?`rgba(${n}, ${o}, ${a}, ${s??NaN})`:`rgb(${n}, ${o}, ${a})`}function ee(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 ye(r,e,t=!1){return Y(r,e*-1,t)}function te(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 re(r){return btoa(new Uint8Array(r).reduce((e,t)=>e+String.fromCharCode(t),""))}function ie(r){return Uint8Array.from(atob(r),e=>e.charCodeAt(0))}async function L(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:re(a)}async function j(r,e,t="string"){let i=r instanceof Uint8Array?r:ie((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 B(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 Se(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=>I(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"}},V=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"}},K=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 Pe(r){return await(typeof r=="function"?r():r)}async function Ee(r){return typeof r=="string"?r:String(typeof r=="function"?await r():r)}async function Oe(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 Ae(r,e=!0){return"length"in r?r.length:"size"in r?r.size:"count"in r?r.count:e?0:NaN}function Ne(r,e,t=!1){return new Promise((i,n)=>{let o=setTimeout(()=>i(),r);e==null||e.addEventListener("abort",()=>{clearTimeout(o),t?n(new V("AbortError","The pause was aborted")):i()})})}function Ve(r){return Object.assign(Object.create(null),r??{})}function ke(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 Fe(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 Me(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 Ce(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 V("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 Ee(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 Oe(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 Ne(r){return r.charAt(0).toUpperCase()+r.slice(1)}var Q={100:"\u2588",75:"\u2593",50:"\u2592",25:"\u2591",0:"\u2500"};function Ve(r,e,t=Q){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 ke(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 Me(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 T=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 y of d)y();d.splice(0,d.length),this.eventUnsubscribes=this.eventUnsubscribes.filter(y=>!d.includes(y))}},f=new Set,v=()=>s.length===0||f.size===s.length;for(let g of a){let y=this.events.on(g,((...N)=>{m(),v()&&(l(g,...N),u&&m(!0))}));d.push(y)}for(let g of s){let y=this.events.on(g,((...N)=>{m(),f.add(g),v()&&(a.length===0||a.includes(g))&&(l(g,...N),u&&m(!0))}));d.push(y)}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 R=1,U=class extends T{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 M(i,t,"string")],this.decodeData=[t,async i=>await I(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=(v,g,y)=>{m.push(this.engine.setValue(g,y)),m.push(this.engine.deleteValue(v))};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<R)&&await this.engine.setValue("__ds_fmt_ver",R)}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 E(`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 O=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 O{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 O{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 b("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 b("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 b("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 L=class r{stores;options;constructor(e,t={}){if(!crypto||!crypto.subtle)throw new b("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 $(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 x(`Checksum mismatch for DataStore with ID "${a.id}"!
|
|
3
|
+
`)}}function $e(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 ze(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 Ue(r){return r.charAt(0).toUpperCase()+r.slice(1)}var ne={100:"\u2588",75:"\u2593",50:"\u2592",25:"\u2591",0:"\u2500"};function Le(r,e,t=ne){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 je(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 Be(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 Ke(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 qe(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 ae={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 Je(r,e){var h;let t={columnAlign:"left",truncateAbove:1/0,truncEndStr:"\u2026",minPadding:1,lineStyle:"single",applyCellStyle:()=>{},applyLineStyle:()=>{},lineCharset:ae,...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 O=f.indexOf("m",v+2);if(O!==-1){D+=f.slice(v,O+1),w=!0,v=O+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,O=(Array.isArray(t.columnAlign)?t.columnAlign[T]:t.columnAlign)??"left",A,N;switch(O){case"right":A=t.minPadding+w,N=t.minPadding;break;case"centerLeft":A=t.minPadding+Math.floor(w/2),N=t.minPadding+Math.ceil(w/2);break;case"centerRight":A=t.minPadding+Math.ceil(w/2),N=t.minPadding+Math.floor(w/2);break;default:A=t.minPadding,N=t.minPadding+w}let[G="",Z=""]=t.applyCellStyle(l,T)??[];g+=" ".repeat(A)+G+D+Z+" ".repeat(N),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 q=()=>({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=q();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 J=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 L(i,t,"string")],this.decodeData=[t,async i=>await j(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<J)&&await this.engine.setValue("__ds_fmt_ver",J)}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 B(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 R=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 ot(r,e=200,t="immediate",i){let n=new R(e,t,i);n.addListener(r);let o=((...a)=>n.call(...a));return o.debouncer=n,o}export{W as BrowserStorageEngine,F as ChecksumMismatchError,V as CustomError,_ as DataStore,$ as DataStoreEngine,Q as DataStoreSerializer,b as DatedError,R as Debouncer,H as FileStorageEngine,M as MigrationError,E as NanoEmitter,C as NetworkError,x as ScriptContextError,K as ValidationError,re as abtoa,ie as atoab,ze as autoPlural,oe as bitSetHas,Ue as capitalize,P as clamp,L as compress,B as computeHash,Pe as consumeGen,Ee as consumeStringGen,Le as createProgressBar,$e as createRecurringTask,Je as createTable,Y as darkenColor,ot as debounce,j as decompress,ne as defaultPbChars,ae as defaultTableLineCharset,se as digitCount,Oe as fetchAdvanced,ue as formatNumber,Ce as getCallStack,Ae as getListLength,ee as hexToRgb,je as insertValues,Be as joinArrayReadable,ye as lightenColor,I as mapRange,le as overflowVal,Ne as pauseFor,Ve as pureObj,k as randRange,Se as randomId,pe as randomItem,U as randomItemIndex,fe as randomizeArray,te as rgbToHex,z as roundFixed,Me as scheduleExit,Ke as secsToTimeStr,ke as setImmediateInterval,Fe as setImmediateTimeoutLoop,he as takeRandomItem,X as takeRandomItemIndex,qe as truncStr,ce as valsWithin};
|
|
6
7
|
//# sourceMappingURL=CoreUtils.min.mjs.map
|