@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/dist/CoreUtils.umd.js
CHANGED
|
@@ -16,13 +16,41 @@
|
|
|
16
16
|
|
|
17
17
|
|
|
18
18
|
|
|
19
|
+
(function(g,f){if(typeof exports=="object"&&typeof module<"u"){module.exports=f()}else if("function"==typeof define && define.amd){define("CoreUtils",f)}else {g["CoreUtils"]=f()}}(typeof globalThis < "u" ? globalThis : typeof self < "u" ? self : this,function(){var exports={};var __exports=exports;var module={exports};
|
|
19
20
|
"use strict";
|
|
20
21
|
var __create = Object.create;
|
|
21
22
|
var __defProp = Object.defineProperty;
|
|
22
23
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
23
24
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
25
|
+
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
24
26
|
var __getProtoOf = Object.getPrototypeOf;
|
|
25
27
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
28
|
+
var __propIsEnum = Object.prototype.propertyIsEnumerable;
|
|
29
|
+
var __pow = Math.pow;
|
|
30
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
31
|
+
var __spreadValues = (a, b) => {
|
|
32
|
+
for (var prop in b || (b = {}))
|
|
33
|
+
if (__hasOwnProp.call(b, prop))
|
|
34
|
+
__defNormalProp(a, prop, b[prop]);
|
|
35
|
+
if (__getOwnPropSymbols)
|
|
36
|
+
for (var prop of __getOwnPropSymbols(b)) {
|
|
37
|
+
if (__propIsEnum.call(b, prop))
|
|
38
|
+
__defNormalProp(a, prop, b[prop]);
|
|
39
|
+
}
|
|
40
|
+
return a;
|
|
41
|
+
};
|
|
42
|
+
var __objRest = (source, exclude) => {
|
|
43
|
+
var target = {};
|
|
44
|
+
for (var prop in source)
|
|
45
|
+
if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
|
|
46
|
+
target[prop] = source[prop];
|
|
47
|
+
if (source != null && __getOwnPropSymbols)
|
|
48
|
+
for (var prop of __getOwnPropSymbols(source)) {
|
|
49
|
+
if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
|
|
50
|
+
target[prop] = source[prop];
|
|
51
|
+
}
|
|
52
|
+
return target;
|
|
53
|
+
};
|
|
26
54
|
var __export = (target, all) => {
|
|
27
55
|
for (var name in all)
|
|
28
56
|
__defProp(target, name, { get: all[name], enumerable: true });
|
|
@@ -44,6 +72,27 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
44
72
|
mod
|
|
45
73
|
));
|
|
46
74
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
75
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
76
|
+
var __async = (__this, __arguments, generator) => {
|
|
77
|
+
return new Promise((resolve, reject) => {
|
|
78
|
+
var fulfilled = (value) => {
|
|
79
|
+
try {
|
|
80
|
+
step(generator.next(value));
|
|
81
|
+
} catch (e) {
|
|
82
|
+
reject(e);
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
var rejected = (value) => {
|
|
86
|
+
try {
|
|
87
|
+
step(generator.throw(value));
|
|
88
|
+
} catch (e) {
|
|
89
|
+
reject(e);
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
|
|
93
|
+
step((generator = generator.apply(__this, __arguments)).next());
|
|
94
|
+
});
|
|
95
|
+
};
|
|
47
96
|
|
|
48
97
|
// lib/index.ts
|
|
49
98
|
var lib_exports = {};
|
|
@@ -74,10 +123,12 @@ __export(lib_exports, {
|
|
|
74
123
|
consumeStringGen: () => consumeStringGen,
|
|
75
124
|
createProgressBar: () => createProgressBar,
|
|
76
125
|
createRecurringTask: () => createRecurringTask,
|
|
126
|
+
createTable: () => createTable,
|
|
77
127
|
darkenColor: () => darkenColor,
|
|
78
128
|
debounce: () => debounce,
|
|
79
129
|
decompress: () => decompress,
|
|
80
130
|
defaultPbChars: () => defaultPbChars,
|
|
131
|
+
defaultTableLineCharset: () => defaultTableLineCharset,
|
|
81
132
|
digitCount: () => digitCount,
|
|
82
133
|
fetchAdvanced: () => fetchAdvanced,
|
|
83
134
|
formatNumber: () => formatNumber,
|
|
@@ -195,7 +246,7 @@ function randRange(...args) {
|
|
|
195
246
|
return Math.floor(Math.random() * (max - min + 1)) + min;
|
|
196
247
|
}
|
|
197
248
|
function roundFixed(num, fractionDigits) {
|
|
198
|
-
const scale = 10
|
|
249
|
+
const scale = __pow(10, fractionDigits);
|
|
199
250
|
return Math.round(num * scale) / scale;
|
|
200
251
|
}
|
|
201
252
|
function valsWithin(a, b, dec = 1, withinRange = 0.5) {
|
|
@@ -259,7 +310,7 @@ function darkenColor(color, percent, upperCase = false) {
|
|
|
259
310
|
if (isHexCol)
|
|
260
311
|
return rgbToHex(r, g, b, a, color.startsWith("#"), upperCase);
|
|
261
312
|
else if (color.startsWith("rgba"))
|
|
262
|
-
return `rgba(${r}, ${g}, ${b}, ${a
|
|
313
|
+
return `rgba(${r}, ${g}, ${b}, ${a != null ? a : NaN})`;
|
|
263
314
|
else
|
|
264
315
|
return `rgb(${r}, ${g}, ${b})`;
|
|
265
316
|
}
|
|
@@ -293,35 +344,43 @@ function abtoa(buf) {
|
|
|
293
344
|
function atoab(str) {
|
|
294
345
|
return Uint8Array.from(atob(str), (c) => c.charCodeAt(0));
|
|
295
346
|
}
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
347
|
+
function compress(input, compressionFormat, outputType = "string") {
|
|
348
|
+
return __async(this, null, function* () {
|
|
349
|
+
var _a;
|
|
350
|
+
const byteArray = input instanceof Uint8Array ? input : new TextEncoder().encode((_a = input == null ? void 0 : input.toString()) != null ? _a : String(input));
|
|
351
|
+
const comp = new CompressionStream(compressionFormat);
|
|
352
|
+
const writer = comp.writable.getWriter();
|
|
353
|
+
writer.write(byteArray);
|
|
354
|
+
writer.close();
|
|
355
|
+
const uintArr = new Uint8Array(yield new Response(comp.readable).arrayBuffer());
|
|
356
|
+
return outputType === "arrayBuffer" ? uintArr : abtoa(uintArr);
|
|
357
|
+
});
|
|
304
358
|
}
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
359
|
+
function decompress(input, compressionFormat, outputType = "string") {
|
|
360
|
+
return __async(this, null, function* () {
|
|
361
|
+
var _a;
|
|
362
|
+
const byteArray = input instanceof Uint8Array ? input : atoab((_a = input == null ? void 0 : input.toString()) != null ? _a : String(input));
|
|
363
|
+
const decomp = new DecompressionStream(compressionFormat);
|
|
364
|
+
const writer = decomp.writable.getWriter();
|
|
365
|
+
writer.write(byteArray);
|
|
366
|
+
writer.close();
|
|
367
|
+
const uintArr = new Uint8Array(yield new Response(decomp.readable).arrayBuffer());
|
|
368
|
+
return outputType === "arrayBuffer" ? uintArr : new TextDecoder().decode(uintArr);
|
|
369
|
+
});
|
|
313
370
|
}
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
371
|
+
function computeHash(input, algorithm = "SHA-256") {
|
|
372
|
+
return __async(this, null, function* () {
|
|
373
|
+
let data;
|
|
374
|
+
if (typeof input === "string") {
|
|
375
|
+
const encoder = new TextEncoder();
|
|
376
|
+
data = encoder.encode(input);
|
|
377
|
+
} else
|
|
378
|
+
data = input;
|
|
379
|
+
const hashBuffer = yield crypto.subtle.digest(algorithm, data);
|
|
380
|
+
const hashArray = Array.from(new Uint8Array(hashBuffer));
|
|
381
|
+
const hashHex = hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
382
|
+
return hashHex;
|
|
383
|
+
});
|
|
325
384
|
}
|
|
326
385
|
function randomId(length = 16, radix = 16, enhancedEntropy = false, randomCase = true) {
|
|
327
386
|
if (length < 1)
|
|
@@ -350,9 +409,9 @@ function randomId(length = 16, radix = 16, enhancedEntropy = false, randomCase =
|
|
|
350
409
|
|
|
351
410
|
// lib/Errors.ts
|
|
352
411
|
var DatedError = class extends Error {
|
|
353
|
-
date;
|
|
354
412
|
constructor(message, options) {
|
|
355
413
|
super(message, options);
|
|
414
|
+
__publicField(this, "date");
|
|
356
415
|
this.name = this.constructor.name;
|
|
357
416
|
this.date = /* @__PURE__ */ new Date();
|
|
358
417
|
}
|
|
@@ -395,34 +454,37 @@ var NetworkError = class extends DatedError {
|
|
|
395
454
|
};
|
|
396
455
|
|
|
397
456
|
// lib/misc.ts
|
|
398
|
-
|
|
399
|
-
return
|
|
457
|
+
function consumeGen(valGen) {
|
|
458
|
+
return __async(this, null, function* () {
|
|
459
|
+
return yield typeof valGen === "function" ? valGen() : valGen;
|
|
460
|
+
});
|
|
400
461
|
}
|
|
401
|
-
|
|
402
|
-
return
|
|
403
|
-
typeof strGen === "
|
|
404
|
-
|
|
462
|
+
function consumeStringGen(strGen) {
|
|
463
|
+
return __async(this, null, function* () {
|
|
464
|
+
return typeof strGen === "string" ? strGen : String(
|
|
465
|
+
typeof strGen === "function" ? yield strGen() : strGen
|
|
466
|
+
);
|
|
467
|
+
});
|
|
405
468
|
}
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
}
|
|
469
|
+
function fetchAdvanced(_0) {
|
|
470
|
+
return __async(this, arguments, function* (input, options = {}) {
|
|
471
|
+
const _a = options, { timeout = 1e4, signal } = _a, restOpts = __objRest(_a, ["timeout", "signal"]);
|
|
472
|
+
const ctl = new AbortController();
|
|
473
|
+
signal == null ? void 0 : signal.addEventListener("abort", () => ctl.abort());
|
|
474
|
+
let sigOpts = {}, id = void 0;
|
|
475
|
+
if (timeout >= 0) {
|
|
476
|
+
id = setTimeout(() => ctl.abort(), timeout);
|
|
477
|
+
sigOpts = { signal: ctl.signal };
|
|
478
|
+
}
|
|
479
|
+
try {
|
|
480
|
+
const res = yield fetch(input, __spreadValues(__spreadValues({}, restOpts), sigOpts));
|
|
481
|
+
typeof id !== "undefined" && clearTimeout(id);
|
|
482
|
+
return res;
|
|
483
|
+
} catch (err) {
|
|
484
|
+
typeof id !== "undefined" && clearTimeout(id);
|
|
485
|
+
throw new NetworkError("Error while calling fetch", { cause: err });
|
|
486
|
+
}
|
|
487
|
+
});
|
|
426
488
|
}
|
|
427
489
|
function getListLength(listLike, zeroOnInvalid = true) {
|
|
428
490
|
return "length" in listLike ? listLike.length : "size" in listLike ? listLike.size : "count" in listLike ? listLike.count : zeroOnInvalid ? 0 : NaN;
|
|
@@ -437,7 +499,7 @@ function pauseFor(time, signal, rejectOnAbort = false) {
|
|
|
437
499
|
});
|
|
438
500
|
}
|
|
439
501
|
function pureObj(obj) {
|
|
440
|
-
return Object.assign(/* @__PURE__ */ Object.create(null), obj
|
|
502
|
+
return Object.assign(/* @__PURE__ */ Object.create(null), obj != null ? obj : {});
|
|
441
503
|
}
|
|
442
504
|
function setImmediateInterval(callback, interval, signal) {
|
|
443
505
|
let intervalId;
|
|
@@ -454,12 +516,12 @@ function setImmediateInterval(callback, interval, signal) {
|
|
|
454
516
|
function setImmediateTimeoutLoop(callback, interval, signal) {
|
|
455
517
|
let timeout;
|
|
456
518
|
const cleanup = () => clearTimeout(timeout);
|
|
457
|
-
const loop =
|
|
519
|
+
const loop = () => __async(null, null, function* () {
|
|
458
520
|
if (signal == null ? void 0 : signal.aborted)
|
|
459
521
|
return cleanup();
|
|
460
|
-
|
|
522
|
+
yield callback();
|
|
461
523
|
timeout = setTimeout(loop, interval);
|
|
462
|
-
};
|
|
524
|
+
});
|
|
463
525
|
signal == null ? void 0 : signal.addEventListener("abort", cleanup);
|
|
464
526
|
loop();
|
|
465
527
|
}
|
|
@@ -476,12 +538,13 @@ function scheduleExit(code = 0, timeout = 0) {
|
|
|
476
538
|
setTimeout(exit, timeout);
|
|
477
539
|
}
|
|
478
540
|
function getCallStack(asArray, lines = Infinity) {
|
|
541
|
+
var _a;
|
|
479
542
|
if (typeof lines !== "number" || isNaN(lines) || lines < 0)
|
|
480
543
|
throw new TypeError("lines parameter must be a non-negative number");
|
|
481
544
|
try {
|
|
482
545
|
throw new CustomError("GetCallStack", "Capturing a stack trace with CoreUtils.getCallStack(). If you see this anywhere, you can safely ignore it.");
|
|
483
546
|
} catch (err) {
|
|
484
|
-
const stack = (err.stack
|
|
547
|
+
const stack = ((_a = err.stack) != null ? _a : "").split("\n").map((line) => line.trim()).slice(2, lines + 2);
|
|
485
548
|
return asArray !== false ? stack : stack.join("\n");
|
|
486
549
|
}
|
|
487
550
|
}
|
|
@@ -492,22 +555,22 @@ function createRecurringTask(options) {
|
|
|
492
555
|
(_a = options.signal) == null ? void 0 : _a.addEventListener("abort", () => {
|
|
493
556
|
aborted = true;
|
|
494
557
|
}, { once: true });
|
|
495
|
-
const runRecurringTask =
|
|
496
|
-
var _a2;
|
|
558
|
+
const runRecurringTask = (initial = false) => __async(null, null, function* () {
|
|
559
|
+
var _a2, _b, _c;
|
|
497
560
|
if (aborted)
|
|
498
561
|
return;
|
|
499
562
|
try {
|
|
500
|
-
if ((options.immediate
|
|
563
|
+
if (((_a2 = options.immediate) != null ? _a2 : true) || !initial) {
|
|
501
564
|
iterations++;
|
|
502
|
-
if (
|
|
503
|
-
const val =
|
|
565
|
+
if ((_c = yield (_b = options.condition) == null ? void 0 : _b.call(options, iterations - 1)) != null ? _c : true) {
|
|
566
|
+
const val = yield options.task(iterations - 1);
|
|
504
567
|
if (options.onSuccess)
|
|
505
|
-
|
|
568
|
+
yield options.onSuccess(val, iterations - 1);
|
|
506
569
|
}
|
|
507
570
|
}
|
|
508
571
|
} catch (err) {
|
|
509
572
|
if (options.onError)
|
|
510
|
-
|
|
573
|
+
yield options.onError(err, iterations - 1);
|
|
511
574
|
if (options.abortOnError)
|
|
512
575
|
aborted = true;
|
|
513
576
|
if (!options.onError && !options.abortOnError)
|
|
@@ -515,7 +578,7 @@ function createRecurringTask(options) {
|
|
|
515
578
|
}
|
|
516
579
|
if (!aborted && (typeof options.maxIterations !== "number" || iterations < options.maxIterations))
|
|
517
580
|
setTimeout(runRecurringTask, options.timeout);
|
|
518
|
-
};
|
|
581
|
+
});
|
|
519
582
|
return runRecurringTask(true);
|
|
520
583
|
}
|
|
521
584
|
|
|
@@ -569,9 +632,9 @@ function createProgressBar(percentage, barLength, chars = defaultPbChars) {
|
|
|
569
632
|
}
|
|
570
633
|
function insertValues(input, ...values) {
|
|
571
634
|
return input.replace(/%\d/gm, (match) => {
|
|
572
|
-
var _a;
|
|
635
|
+
var _a, _b;
|
|
573
636
|
const argIndex = Number(match.substring(1)) - 1;
|
|
574
|
-
return (_a = values[argIndex]
|
|
637
|
+
return (_b = (_a = values[argIndex]) != null ? _a : match) == null ? void 0 : _b.toString();
|
|
575
638
|
});
|
|
576
639
|
}
|
|
577
640
|
function joinArrayReadable(array, separators = ", ", lastSeparator = " and ") {
|
|
@@ -602,10 +665,182 @@ function secsToTimeStr(seconds) {
|
|
|
602
665
|
].join("");
|
|
603
666
|
}
|
|
604
667
|
function truncStr(input, length, endStr = "...") {
|
|
605
|
-
|
|
668
|
+
var _a;
|
|
669
|
+
const str = (_a = input == null ? void 0 : input.toString()) != null ? _a : String(input);
|
|
606
670
|
const finalStr = str.length > length ? str.substring(0, length - endStr.length) + endStr : str;
|
|
607
671
|
return finalStr.length > length ? finalStr.substring(0, length) : finalStr;
|
|
608
672
|
}
|
|
673
|
+
var defaultTableLineCharset = {
|
|
674
|
+
single: {
|
|
675
|
+
horizontal: "\u2500",
|
|
676
|
+
vertical: "\u2502",
|
|
677
|
+
topLeft: "\u250C",
|
|
678
|
+
topRight: "\u2510",
|
|
679
|
+
bottomLeft: "\u2514",
|
|
680
|
+
bottomRight: "\u2518",
|
|
681
|
+
leftT: "\u251C",
|
|
682
|
+
rightT: "\u2524",
|
|
683
|
+
topT: "\u252C",
|
|
684
|
+
bottomT: "\u2534",
|
|
685
|
+
cross: "\u253C"
|
|
686
|
+
},
|
|
687
|
+
double: {
|
|
688
|
+
horizontal: "\u2550",
|
|
689
|
+
vertical: "\u2551",
|
|
690
|
+
topLeft: "\u2554",
|
|
691
|
+
topRight: "\u2557",
|
|
692
|
+
bottomLeft: "\u255A",
|
|
693
|
+
bottomRight: "\u255D",
|
|
694
|
+
leftT: "\u2560",
|
|
695
|
+
rightT: "\u2563",
|
|
696
|
+
topT: "\u2566",
|
|
697
|
+
bottomT: "\u2569",
|
|
698
|
+
cross: "\u256C"
|
|
699
|
+
},
|
|
700
|
+
none: {
|
|
701
|
+
horizontal: " ",
|
|
702
|
+
vertical: " ",
|
|
703
|
+
topLeft: " ",
|
|
704
|
+
topRight: " ",
|
|
705
|
+
bottomLeft: " ",
|
|
706
|
+
bottomRight: " ",
|
|
707
|
+
leftT: " ",
|
|
708
|
+
rightT: " ",
|
|
709
|
+
topT: " ",
|
|
710
|
+
bottomT: " ",
|
|
711
|
+
cross: " "
|
|
712
|
+
}
|
|
713
|
+
};
|
|
714
|
+
function createTable(rows, options) {
|
|
715
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _i;
|
|
716
|
+
const opts = __spreadValues({
|
|
717
|
+
columnAlign: "left",
|
|
718
|
+
truncateAbove: Infinity,
|
|
719
|
+
truncEndStr: "\u2026",
|
|
720
|
+
minPadding: 1,
|
|
721
|
+
lineStyle: "single",
|
|
722
|
+
applyCellStyle: () => void 0,
|
|
723
|
+
applyLineStyle: () => void 0,
|
|
724
|
+
lineCharset: defaultTableLineCharset
|
|
725
|
+
}, options != null ? options : {});
|
|
726
|
+
const defRange = (val, min, max) => clamp(typeof val !== "number" || isNaN(Number(val)) ? min : val, min, max);
|
|
727
|
+
opts.truncateAbove = defRange(opts.truncateAbove, 0, Infinity);
|
|
728
|
+
opts.minPadding = defRange(opts.minPadding, 0, Infinity);
|
|
729
|
+
const lnCh = opts.lineCharset[opts.lineStyle];
|
|
730
|
+
const stripAnsi = (str) => str.replace(/\u001b\[[0-9;]*m/g, "");
|
|
731
|
+
const stringRows = rows.map((row) => row.map((cell) => String(cell)));
|
|
732
|
+
const colCount = (_b = (_a = rows[0]) == null ? void 0 : _a.length) != null ? _b : 0;
|
|
733
|
+
if (colCount === 0 || stringRows.length === 0)
|
|
734
|
+
return "";
|
|
735
|
+
if (isFinite(opts.truncateAbove)) {
|
|
736
|
+
const truncAnsi = (str, maxVisible, endStr) => {
|
|
737
|
+
const limit = maxVisible - endStr.length;
|
|
738
|
+
if (limit <= 0)
|
|
739
|
+
return endStr.slice(0, maxVisible);
|
|
740
|
+
let visible = 0;
|
|
741
|
+
let result = "";
|
|
742
|
+
let i = 0;
|
|
743
|
+
let hasAnsi = false;
|
|
744
|
+
while (i < str.length) {
|
|
745
|
+
if (str[i] === "\x1B" && str[i + 1] === "[") {
|
|
746
|
+
const seqEnd = str.indexOf("m", i + 2);
|
|
747
|
+
if (seqEnd !== -1) {
|
|
748
|
+
result += str.slice(i, seqEnd + 1);
|
|
749
|
+
hasAnsi = true;
|
|
750
|
+
i = seqEnd + 1;
|
|
751
|
+
continue;
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
if (visible === limit) {
|
|
755
|
+
result += endStr;
|
|
756
|
+
if (hasAnsi)
|
|
757
|
+
result += "\x1B[0m";
|
|
758
|
+
return result;
|
|
759
|
+
}
|
|
760
|
+
result += str[i];
|
|
761
|
+
visible++;
|
|
762
|
+
i++;
|
|
763
|
+
}
|
|
764
|
+
return result;
|
|
765
|
+
};
|
|
766
|
+
for (const row of stringRows)
|
|
767
|
+
for (let j = 0; j < row.length; j++)
|
|
768
|
+
if (stripAnsi((_c = row[j]) != null ? _c : "").length > opts.truncateAbove)
|
|
769
|
+
row[j] = truncAnsi((_d = row[j]) != null ? _d : "", opts.truncateAbove, opts.truncEndStr);
|
|
770
|
+
}
|
|
771
|
+
const colWidths = Array.from(
|
|
772
|
+
{ length: colCount },
|
|
773
|
+
(_, j) => Math.max(0, ...stringRows.map((row) => {
|
|
774
|
+
var _a2;
|
|
775
|
+
return stripAnsi((_a2 = row[j]) != null ? _a2 : "").length;
|
|
776
|
+
}))
|
|
777
|
+
);
|
|
778
|
+
const applyLn = (i, j, ch) => {
|
|
779
|
+
var _a2;
|
|
780
|
+
const [before = "", after = ""] = (_a2 = opts.applyLineStyle(i, j)) != null ? _a2 : [];
|
|
781
|
+
return `${before}${ch}${after}`;
|
|
782
|
+
};
|
|
783
|
+
const buildBorderRow = (lineIdx, leftCh, midCh, rightCh) => {
|
|
784
|
+
var _a2;
|
|
785
|
+
let result = "";
|
|
786
|
+
let j = 0;
|
|
787
|
+
result += applyLn(lineIdx, j++, leftCh);
|
|
788
|
+
for (let col = 0; col < colCount; col++) {
|
|
789
|
+
const cellWidth = ((_a2 = colWidths[col]) != null ? _a2 : 0) + opts.minPadding * 2;
|
|
790
|
+
for (let ci = 0; ci < cellWidth; ci++)
|
|
791
|
+
result += applyLn(lineIdx, j++, lnCh.horizontal);
|
|
792
|
+
if (col < colCount - 1)
|
|
793
|
+
result += applyLn(lineIdx, j++, midCh);
|
|
794
|
+
}
|
|
795
|
+
result += applyLn(lineIdx, j++, rightCh);
|
|
796
|
+
return result;
|
|
797
|
+
};
|
|
798
|
+
const lines = [];
|
|
799
|
+
for (let rowIdx = 0; rowIdx < stringRows.length; rowIdx++) {
|
|
800
|
+
const row = (_e = stringRows[rowIdx]) != null ? _e : [];
|
|
801
|
+
const lineIdxBase = rowIdx * 3;
|
|
802
|
+
if (opts.lineStyle !== "none") {
|
|
803
|
+
lines.push(
|
|
804
|
+
rowIdx === 0 ? buildBorderRow(lineIdxBase, lnCh.topLeft, lnCh.topT, lnCh.topRight) : buildBorderRow(lineIdxBase, lnCh.leftT, lnCh.cross, lnCh.rightT)
|
|
805
|
+
);
|
|
806
|
+
}
|
|
807
|
+
let contentLine = "";
|
|
808
|
+
let j = 0;
|
|
809
|
+
contentLine += applyLn(lineIdxBase + 1, j++, lnCh.vertical);
|
|
810
|
+
for (let colIdx = 0; colIdx < colCount; colIdx++) {
|
|
811
|
+
const cell = (_f = row[colIdx]) != null ? _f : "";
|
|
812
|
+
const visLen = stripAnsi(cell).length;
|
|
813
|
+
const extra = ((_g = colWidths[colIdx]) != null ? _g : 0) - visLen;
|
|
814
|
+
const align = (_h = Array.isArray(opts.columnAlign) ? opts.columnAlign[colIdx] : opts.columnAlign) != null ? _h : "left";
|
|
815
|
+
let leftPad;
|
|
816
|
+
let rightPad;
|
|
817
|
+
switch (align) {
|
|
818
|
+
case "right":
|
|
819
|
+
leftPad = opts.minPadding + extra;
|
|
820
|
+
rightPad = opts.minPadding;
|
|
821
|
+
break;
|
|
822
|
+
case "centerLeft":
|
|
823
|
+
leftPad = opts.minPadding + Math.floor(extra / 2);
|
|
824
|
+
rightPad = opts.minPadding + Math.ceil(extra / 2);
|
|
825
|
+
break;
|
|
826
|
+
case "centerRight":
|
|
827
|
+
leftPad = opts.minPadding + Math.ceil(extra / 2);
|
|
828
|
+
rightPad = opts.minPadding + Math.floor(extra / 2);
|
|
829
|
+
break;
|
|
830
|
+
default:
|
|
831
|
+
leftPad = opts.minPadding;
|
|
832
|
+
rightPad = opts.minPadding + extra;
|
|
833
|
+
}
|
|
834
|
+
const [cellBefore = "", cellAfter = ""] = (_i = opts.applyCellStyle(rowIdx, colIdx)) != null ? _i : [];
|
|
835
|
+
contentLine += " ".repeat(leftPad) + cellBefore + cell + cellAfter + " ".repeat(rightPad);
|
|
836
|
+
contentLine += applyLn(lineIdxBase + 1, j++, lnCh.vertical);
|
|
837
|
+
}
|
|
838
|
+
lines.push(contentLine);
|
|
839
|
+
if (opts.lineStyle !== "none" && rowIdx === stringRows.length - 1)
|
|
840
|
+
lines.push(buildBorderRow(lineIdxBase + 2, lnCh.bottomLeft, lnCh.bottomT, lnCh.bottomRight));
|
|
841
|
+
}
|
|
842
|
+
return lines.join("\n");
|
|
843
|
+
}
|
|
609
844
|
|
|
610
845
|
// node_modules/.pnpm/nanoevents@9.1.0/node_modules/nanoevents/index.js
|
|
611
846
|
var createNanoEvents = () => ({
|
|
@@ -616,26 +851,26 @@ var createNanoEvents = () => ({
|
|
|
616
851
|
},
|
|
617
852
|
events: {},
|
|
618
853
|
on(event, cb) {
|
|
854
|
+
var _a;
|
|
619
855
|
;
|
|
620
|
-
(this.events[event]
|
|
856
|
+
((_a = this.events)[event] || (_a[event] = [])).push(cb);
|
|
621
857
|
return () => {
|
|
622
|
-
var
|
|
623
|
-
this.events[event] = (
|
|
858
|
+
var _a2;
|
|
859
|
+
this.events[event] = (_a2 = this.events[event]) == null ? void 0 : _a2.filter((i) => cb !== i);
|
|
624
860
|
};
|
|
625
861
|
}
|
|
626
862
|
});
|
|
627
863
|
|
|
628
864
|
// lib/NanoEmitter.ts
|
|
629
865
|
var NanoEmitter = class {
|
|
630
|
-
events = createNanoEvents();
|
|
631
|
-
eventUnsubscribes = [];
|
|
632
|
-
emitterOptions;
|
|
633
866
|
/** Creates a new instance of NanoEmitter - a lightweight event emitter with helper methods and a strongly typed event map */
|
|
634
867
|
constructor(options = {}) {
|
|
635
|
-
this
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
868
|
+
__publicField(this, "events", createNanoEvents());
|
|
869
|
+
__publicField(this, "eventUnsubscribes", []);
|
|
870
|
+
__publicField(this, "emitterOptions");
|
|
871
|
+
this.emitterOptions = __spreadValues({
|
|
872
|
+
publicEmit: false
|
|
873
|
+
}, options);
|
|
639
874
|
}
|
|
640
875
|
//#region on
|
|
641
876
|
/**
|
|
@@ -727,12 +962,11 @@ var NanoEmitter = class {
|
|
|
727
962
|
this.eventUnsubscribes = this.eventUnsubscribes.filter((u) => !allUnsubs.includes(u));
|
|
728
963
|
};
|
|
729
964
|
for (const opts of Array.isArray(options) ? options : [options]) {
|
|
730
|
-
const optsWithDefaults = {
|
|
965
|
+
const optsWithDefaults = __spreadValues({
|
|
731
966
|
allOf: [],
|
|
732
967
|
oneOf: [],
|
|
733
|
-
once: false
|
|
734
|
-
|
|
735
|
-
};
|
|
968
|
+
once: false
|
|
969
|
+
}, opts);
|
|
736
970
|
const {
|
|
737
971
|
oneOf,
|
|
738
972
|
allOf,
|
|
@@ -809,26 +1043,6 @@ var NanoEmitter = class {
|
|
|
809
1043
|
// lib/DataStore.ts
|
|
810
1044
|
var dsFmtVer = 1;
|
|
811
1045
|
var DataStore = class extends NanoEmitter {
|
|
812
|
-
id;
|
|
813
|
-
formatVersion;
|
|
814
|
-
defaultData;
|
|
815
|
-
encodeData;
|
|
816
|
-
decodeData;
|
|
817
|
-
compressionFormat = "deflate-raw";
|
|
818
|
-
memoryCache;
|
|
819
|
-
engine;
|
|
820
|
-
keyPrefix;
|
|
821
|
-
options;
|
|
822
|
-
/**
|
|
823
|
-
* Whether all first-init checks should be done.
|
|
824
|
-
* This includes migrating the internal DataStore format, migrating data from the UserUtils format, and anything similar.
|
|
825
|
-
* This is set to `true` by default. Create a subclass and set it to `false` before calling {@linkcode loadData()} if you want to explicitly skip these checks.
|
|
826
|
-
*/
|
|
827
|
-
firstInit = true;
|
|
828
|
-
/** In-memory cached copy of the data that is saved in persistent storage used for synchronous read access. */
|
|
829
|
-
cachedData;
|
|
830
|
-
migrations;
|
|
831
|
-
migrateIds = [];
|
|
832
1046
|
//#region constructor
|
|
833
1047
|
/**
|
|
834
1048
|
* Creates an instance of DataStore to manage a sync & async database that is cached in memory and persistently saved across sessions.
|
|
@@ -840,22 +1054,43 @@ var DataStore = class extends NanoEmitter {
|
|
|
840
1054
|
* @param opts The options for this DataStore instance
|
|
841
1055
|
*/
|
|
842
1056
|
constructor(opts) {
|
|
1057
|
+
var _a, _b, _c;
|
|
843
1058
|
super(opts.nanoEmitterOptions);
|
|
1059
|
+
__publicField(this, "id");
|
|
1060
|
+
__publicField(this, "formatVersion");
|
|
1061
|
+
__publicField(this, "defaultData");
|
|
1062
|
+
__publicField(this, "encodeData");
|
|
1063
|
+
__publicField(this, "decodeData");
|
|
1064
|
+
__publicField(this, "compressionFormat", "deflate-raw");
|
|
1065
|
+
__publicField(this, "memoryCache");
|
|
1066
|
+
__publicField(this, "engine");
|
|
1067
|
+
__publicField(this, "keyPrefix");
|
|
1068
|
+
__publicField(this, "options");
|
|
1069
|
+
/**
|
|
1070
|
+
* Whether all first-init checks should be done.
|
|
1071
|
+
* This includes migrating the internal DataStore format, migrating data from the UserUtils format, and anything similar.
|
|
1072
|
+
* This is set to `true` by default. Create a subclass and set it to `false` before calling {@linkcode loadData()} if you want to explicitly skip these checks.
|
|
1073
|
+
*/
|
|
1074
|
+
__publicField(this, "firstInit", true);
|
|
1075
|
+
/** In-memory cached copy of the data that is saved in persistent storage used for synchronous read access. */
|
|
1076
|
+
__publicField(this, "cachedData");
|
|
1077
|
+
__publicField(this, "migrations");
|
|
1078
|
+
__publicField(this, "migrateIds", []);
|
|
844
1079
|
this.id = opts.id;
|
|
845
1080
|
this.formatVersion = opts.formatVersion;
|
|
846
1081
|
this.defaultData = opts.defaultData;
|
|
847
|
-
this.memoryCache = opts.memoryCache
|
|
1082
|
+
this.memoryCache = (_a = opts.memoryCache) != null ? _a : true;
|
|
848
1083
|
this.cachedData = this.memoryCache ? opts.defaultData : {};
|
|
849
1084
|
this.migrations = opts.migrations;
|
|
850
1085
|
if (opts.migrateIds)
|
|
851
1086
|
this.migrateIds = Array.isArray(opts.migrateIds) ? opts.migrateIds : [opts.migrateIds];
|
|
852
1087
|
this.engine = typeof opts.engine === "function" ? opts.engine() : opts.engine;
|
|
853
|
-
this.keyPrefix = opts.keyPrefix
|
|
1088
|
+
this.keyPrefix = (_b = opts.keyPrefix) != null ? _b : "__ds-";
|
|
854
1089
|
this.options = opts;
|
|
855
1090
|
if ("encodeData" in opts && "decodeData" in opts && Array.isArray(opts.encodeData) && Array.isArray(opts.decodeData)) {
|
|
856
1091
|
this.encodeData = [opts.encodeData[0], opts.encodeData[1]];
|
|
857
1092
|
this.decodeData = [opts.decodeData[0], opts.decodeData[1]];
|
|
858
|
-
this.compressionFormat = opts.encodeData[0]
|
|
1093
|
+
this.compressionFormat = (_c = opts.encodeData[0]) != null ? _c : null;
|
|
859
1094
|
} else if (opts.compressionFormat === null) {
|
|
860
1095
|
this.encodeData = void 0;
|
|
861
1096
|
this.decodeData = void 0;
|
|
@@ -863,8 +1098,12 @@ var DataStore = class extends NanoEmitter {
|
|
|
863
1098
|
} else {
|
|
864
1099
|
const fmt = typeof opts.compressionFormat === "string" ? opts.compressionFormat : "deflate-raw";
|
|
865
1100
|
this.compressionFormat = fmt;
|
|
866
|
-
this.encodeData = [fmt,
|
|
867
|
-
|
|
1101
|
+
this.encodeData = [fmt, (data) => __async(this, null, function* () {
|
|
1102
|
+
return yield compress(data, fmt, "string");
|
|
1103
|
+
})];
|
|
1104
|
+
this.decodeData = [fmt, (data) => __async(this, null, function* () {
|
|
1105
|
+
return yield decompress(data, fmt, "string");
|
|
1106
|
+
})];
|
|
868
1107
|
}
|
|
869
1108
|
this.engine.setDataStoreOptions({
|
|
870
1109
|
id: this.id,
|
|
@@ -878,62 +1117,65 @@ var DataStore = class extends NanoEmitter {
|
|
|
878
1117
|
* Automatically populates persistent storage with default data if it doesn't contain any data yet.
|
|
879
1118
|
* Also runs all necessary migration functions if the data format has changed since the last time the data was saved.
|
|
880
1119
|
*/
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
const
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
promises
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
migrateFmt(`
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
1120
|
+
loadData() {
|
|
1121
|
+
return __async(this, null, function* () {
|
|
1122
|
+
var _a;
|
|
1123
|
+
try {
|
|
1124
|
+
if (this.firstInit) {
|
|
1125
|
+
this.firstInit = false;
|
|
1126
|
+
const dsVer = Number(yield this.engine.getValue("__ds_fmt_ver", 0));
|
|
1127
|
+
const oldData = yield this.engine.getValue(`_uucfg-${this.id}`, null);
|
|
1128
|
+
if (oldData) {
|
|
1129
|
+
const oldVer = Number(yield this.engine.getValue(`_uucfgver-${this.id}`, NaN));
|
|
1130
|
+
const oldEnc = yield this.engine.getValue(`_uucfgenc-${this.id}`, null);
|
|
1131
|
+
const promises = [];
|
|
1132
|
+
const migrateFmt = (oldKey, newKey, value) => {
|
|
1133
|
+
promises.push(this.engine.setValue(newKey, value));
|
|
1134
|
+
promises.push(this.engine.deleteValue(oldKey));
|
|
1135
|
+
};
|
|
1136
|
+
migrateFmt(`_uucfg-${this.id}`, `${this.keyPrefix}${this.id}-dat`, oldData);
|
|
1137
|
+
if (!isNaN(oldVer))
|
|
1138
|
+
migrateFmt(`_uucfgver-${this.id}`, `${this.keyPrefix}${this.id}-ver`, oldVer);
|
|
1139
|
+
if (typeof oldEnc === "boolean" || oldEnc === "true" || oldEnc === "false" || typeof oldEnc === "number" || oldEnc === "0" || oldEnc === "1")
|
|
1140
|
+
migrateFmt(`_uucfgenc-${this.id}`, `${this.keyPrefix}${this.id}-enf`, [0, "0", true, "true"].includes(oldEnc) ? (_a = this.compressionFormat) != null ? _a : null : null);
|
|
1141
|
+
else {
|
|
1142
|
+
promises.push(this.engine.setValue(`${this.keyPrefix}${this.id}-enf`, this.compressionFormat));
|
|
1143
|
+
promises.push(this.engine.deleteValue(`_uucfgenc-${this.id}`));
|
|
1144
|
+
}
|
|
1145
|
+
yield Promise.allSettled(promises);
|
|
903
1146
|
}
|
|
904
|
-
|
|
1147
|
+
if (isNaN(dsVer) || dsVer < dsFmtVer)
|
|
1148
|
+
yield this.engine.setValue("__ds_fmt_ver", dsFmtVer);
|
|
905
1149
|
}
|
|
906
|
-
if (
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
this.
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
this.
|
|
919
|
-
|
|
1150
|
+
if (this.migrateIds.length > 0) {
|
|
1151
|
+
yield this.migrateId(this.migrateIds);
|
|
1152
|
+
this.migrateIds = [];
|
|
1153
|
+
}
|
|
1154
|
+
const storedDataRaw = yield this.engine.getValue(`${this.keyPrefix}${this.id}-dat`, null);
|
|
1155
|
+
const storedFmtVer = Number(yield this.engine.getValue(`${this.keyPrefix}${this.id}-ver`, NaN));
|
|
1156
|
+
if (typeof storedDataRaw !== "string" && typeof storedDataRaw !== "object" || storedDataRaw === null || isNaN(storedFmtVer)) {
|
|
1157
|
+
yield this.saveDefaultData(false);
|
|
1158
|
+
const data = this.engine.deepCopy(this.defaultData);
|
|
1159
|
+
this.events.emit("loadData", data);
|
|
1160
|
+
return data;
|
|
1161
|
+
}
|
|
1162
|
+
const storedData = storedDataRaw != null ? storedDataRaw : JSON.stringify(this.defaultData);
|
|
1163
|
+
const encodingFmt = String(yield this.engine.getValue(`${this.keyPrefix}${this.id}-enf`, null));
|
|
1164
|
+
const isEncoded = encodingFmt !== "null" && encodingFmt !== "false" && encodingFmt !== "0" && encodingFmt !== "" && encodingFmt !== null;
|
|
1165
|
+
let parsed = typeof storedData === "string" ? yield this.engine.deserializeData(storedData, isEncoded) : storedData;
|
|
1166
|
+
if (storedFmtVer < this.formatVersion && this.migrations)
|
|
1167
|
+
parsed = yield this.runMigrations(parsed, storedFmtVer);
|
|
1168
|
+
const result = this.memoryCache ? this.cachedData = this.engine.deepCopy(parsed) : this.engine.deepCopy(parsed);
|
|
1169
|
+
this.events.emit("loadData", result);
|
|
1170
|
+
return result;
|
|
1171
|
+
} catch (err) {
|
|
1172
|
+
const error = err instanceof Error ? err : new Error(String(err));
|
|
1173
|
+
console.warn("Error while parsing JSON data, resetting it to the default value.", err);
|
|
1174
|
+
this.events.emit("error", error);
|
|
1175
|
+
yield this.saveDefaultData();
|
|
1176
|
+
return this.defaultData;
|
|
920
1177
|
}
|
|
921
|
-
|
|
922
|
-
const encodingFmt = String(await this.engine.getValue(`${this.keyPrefix}${this.id}-enf`, null));
|
|
923
|
-
const isEncoded = encodingFmt !== "null" && encodingFmt !== "false" && encodingFmt !== "0" && encodingFmt !== "" && encodingFmt !== null;
|
|
924
|
-
let parsed = typeof storedData === "string" ? await this.engine.deserializeData(storedData, isEncoded) : storedData;
|
|
925
|
-
if (storedFmtVer < this.formatVersion && this.migrations)
|
|
926
|
-
parsed = await this.runMigrations(parsed, storedFmtVer);
|
|
927
|
-
const result = this.memoryCache ? this.cachedData = this.engine.deepCopy(parsed) : this.engine.deepCopy(parsed);
|
|
928
|
-
this.events.emit("loadData", result);
|
|
929
|
-
return result;
|
|
930
|
-
} catch (err) {
|
|
931
|
-
const error = err instanceof Error ? err : new Error(String(err));
|
|
932
|
-
console.warn("Error while parsing JSON data, resetting it to the default value.", err);
|
|
933
|
-
this.events.emit("error", error);
|
|
934
|
-
await this.saveDefaultData();
|
|
935
|
-
return this.defaultData;
|
|
936
|
-
}
|
|
1178
|
+
});
|
|
937
1179
|
}
|
|
938
1180
|
//#region getData
|
|
939
1181
|
/**
|
|
@@ -954,9 +1196,9 @@ var DataStore = class extends NanoEmitter {
|
|
|
954
1196
|
this.cachedData = data;
|
|
955
1197
|
this.events.emit("updateDataSync", dataCopy);
|
|
956
1198
|
}
|
|
957
|
-
return new Promise(
|
|
958
|
-
const results =
|
|
959
|
-
this.engine.setValue(`${this.keyPrefix}${this.id}-dat`,
|
|
1199
|
+
return new Promise((resolve) => __async(this, null, function* () {
|
|
1200
|
+
const results = yield Promise.allSettled([
|
|
1201
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-dat`, yield this.engine.serializeData(data, this.encodingEnabled())),
|
|
960
1202
|
this.engine.setValue(`${this.keyPrefix}${this.id}-ver`, this.formatVersion),
|
|
961
1203
|
this.engine.setValue(`${this.keyPrefix}${this.id}-enf`, this.compressionFormat)
|
|
962
1204
|
]);
|
|
@@ -968,28 +1210,30 @@ var DataStore = class extends NanoEmitter {
|
|
|
968
1210
|
this.events.emit("error", error);
|
|
969
1211
|
}
|
|
970
1212
|
resolve();
|
|
971
|
-
});
|
|
1213
|
+
}));
|
|
972
1214
|
}
|
|
973
1215
|
//#region saveDefaultData
|
|
974
1216
|
/**
|
|
975
1217
|
* Saves the default data passed in the constructor synchronously to the in-memory cache and asynchronously to persistent storage.
|
|
976
1218
|
* @param emitEvent Whether to emit the `setDefaultData` event - set to `false` to prevent event emission (used internally during initial population in {@linkcode loadData()})
|
|
977
1219
|
*/
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
1220
|
+
saveDefaultData(emitEvent = true) {
|
|
1221
|
+
return __async(this, null, function* () {
|
|
1222
|
+
if (this.memoryCache)
|
|
1223
|
+
this.cachedData = this.defaultData;
|
|
1224
|
+
const results = yield Promise.allSettled([
|
|
1225
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-dat`, yield this.engine.serializeData(this.defaultData, this.encodingEnabled())),
|
|
1226
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-ver`, this.formatVersion),
|
|
1227
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-enf`, this.compressionFormat)
|
|
1228
|
+
]);
|
|
1229
|
+
if (results.every((r) => r.status === "fulfilled"))
|
|
1230
|
+
emitEvent && this.events.emit("setDefaultData", this.defaultData);
|
|
1231
|
+
else {
|
|
1232
|
+
const error = new Error("Error while saving default data to persistent storage: " + results.map((r) => r.status === "rejected" ? r.reason : null).filter(Boolean).join("; "));
|
|
1233
|
+
console.error(error);
|
|
1234
|
+
this.events.emit("error", error);
|
|
1235
|
+
}
|
|
1236
|
+
});
|
|
993
1237
|
}
|
|
994
1238
|
//#region deleteData
|
|
995
1239
|
/**
|
|
@@ -997,15 +1241,17 @@ var DataStore = class extends NanoEmitter {
|
|
|
997
1241
|
* The in-memory cache will be left untouched, so you may still access the data with {@linkcode getData()}
|
|
998
1242
|
* Calling {@linkcode loadData()} or {@linkcode setData()} after this method was called will recreate persistent storage with the cached or default data.
|
|
999
1243
|
*/
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1244
|
+
deleteData() {
|
|
1245
|
+
return __async(this, null, function* () {
|
|
1246
|
+
var _a, _b;
|
|
1247
|
+
yield Promise.allSettled([
|
|
1248
|
+
this.engine.deleteValue(`${this.keyPrefix}${this.id}-dat`),
|
|
1249
|
+
this.engine.deleteValue(`${this.keyPrefix}${this.id}-ver`),
|
|
1250
|
+
this.engine.deleteValue(`${this.keyPrefix}${this.id}-enf`)
|
|
1251
|
+
]);
|
|
1252
|
+
yield (_b = (_a = this.engine).deleteStorage) == null ? void 0 : _b.call(_a);
|
|
1253
|
+
this.events.emit("deleteData");
|
|
1254
|
+
});
|
|
1009
1255
|
}
|
|
1010
1256
|
//#region encodingEnabled
|
|
1011
1257
|
/** Returns whether encoding and decoding are enabled for this DataStore instance */
|
|
@@ -1020,79 +1266,83 @@ var DataStore = class extends NanoEmitter {
|
|
|
1020
1266
|
*
|
|
1021
1267
|
* If one of the migrations fails, the data will be reset to the default value if `resetOnError` is set to `true` (default). Otherwise, an error will be thrown and no data will be saved.
|
|
1022
1268
|
*/
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1269
|
+
runMigrations(oldData, oldFmtVer, resetOnError = true) {
|
|
1270
|
+
return __async(this, null, function* () {
|
|
1271
|
+
if (!this.migrations)
|
|
1272
|
+
return oldData;
|
|
1273
|
+
let newData = oldData;
|
|
1274
|
+
const sortedMigrations = Object.entries(this.migrations).sort(([a], [b]) => Number(a) - Number(b));
|
|
1275
|
+
let lastFmtVer = oldFmtVer;
|
|
1276
|
+
for (let i = 0; i < sortedMigrations.length; i++) {
|
|
1277
|
+
const [fmtVer, migrationFunc] = sortedMigrations[i];
|
|
1278
|
+
const ver = Number(fmtVer);
|
|
1279
|
+
if (oldFmtVer < this.formatVersion && oldFmtVer < ver) {
|
|
1280
|
+
try {
|
|
1281
|
+
const migRes = migrationFunc(newData);
|
|
1282
|
+
newData = migRes instanceof Promise ? yield migRes : migRes;
|
|
1283
|
+
lastFmtVer = oldFmtVer = ver;
|
|
1284
|
+
const isFinal = ver >= this.formatVersion || i === sortedMigrations.length - 1;
|
|
1285
|
+
this.events.emit("migrateData", ver, newData, isFinal);
|
|
1286
|
+
} catch (err) {
|
|
1287
|
+
const migError = new MigrationError(`Error while running migration function for format version '${fmtVer}'`, { cause: err });
|
|
1288
|
+
this.events.emit("migrationError", ver, migError);
|
|
1289
|
+
this.events.emit("error", migError);
|
|
1290
|
+
if (!resetOnError)
|
|
1291
|
+
throw migError;
|
|
1292
|
+
yield this.saveDefaultData();
|
|
1293
|
+
return this.engine.deepCopy(this.defaultData);
|
|
1294
|
+
}
|
|
1047
1295
|
}
|
|
1048
1296
|
}
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1297
|
+
yield Promise.allSettled([
|
|
1298
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-dat`, yield this.engine.serializeData(newData, this.encodingEnabled())),
|
|
1299
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-ver`, lastFmtVer),
|
|
1300
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-enf`, this.compressionFormat)
|
|
1301
|
+
]);
|
|
1302
|
+
const result = this.memoryCache ? this.cachedData = this.engine.deepCopy(newData) : this.engine.deepCopy(newData);
|
|
1303
|
+
this.events.emit("updateData", result);
|
|
1304
|
+
return result;
|
|
1305
|
+
});
|
|
1058
1306
|
}
|
|
1059
1307
|
//#region migrateId
|
|
1060
1308
|
/**
|
|
1061
1309
|
* Tries to migrate the currently saved persistent data from one or more old IDs to the ID set in the constructor.
|
|
1062
1310
|
* If no data exist for the old ID(s), nothing will be done, but some time may still pass trying to fetch the non-existent data.
|
|
1063
1311
|
*/
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
const [
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1312
|
+
migrateId(oldIds) {
|
|
1313
|
+
return __async(this, null, function* () {
|
|
1314
|
+
const ids = Array.isArray(oldIds) ? oldIds : [oldIds];
|
|
1315
|
+
yield Promise.all(ids.map((id) => __async(this, null, function* () {
|
|
1316
|
+
const [data, fmtVer, isEncoded] = yield (() => __async(this, null, function* () {
|
|
1317
|
+
const [d, f, e] = yield Promise.all([
|
|
1318
|
+
this.engine.getValue(`${this.keyPrefix}${id}-dat`, JSON.stringify(this.defaultData)),
|
|
1319
|
+
this.engine.getValue(`${this.keyPrefix}${id}-ver`, NaN),
|
|
1320
|
+
this.engine.getValue(`${this.keyPrefix}${id}-enf`, null)
|
|
1321
|
+
]);
|
|
1322
|
+
return [d, Number(f), Boolean(e) && String(e) !== "null"];
|
|
1323
|
+
}))();
|
|
1324
|
+
if (data === void 0 || isNaN(fmtVer))
|
|
1325
|
+
return;
|
|
1326
|
+
const parsed = yield this.engine.deserializeData(data, isEncoded);
|
|
1327
|
+
yield Promise.allSettled([
|
|
1328
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-dat`, yield this.engine.serializeData(parsed, this.encodingEnabled())),
|
|
1329
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-ver`, fmtVer),
|
|
1330
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-enf`, this.compressionFormat),
|
|
1331
|
+
this.engine.deleteValue(`${this.keyPrefix}${id}-dat`),
|
|
1332
|
+
this.engine.deleteValue(`${this.keyPrefix}${id}-ver`),
|
|
1333
|
+
this.engine.deleteValue(`${this.keyPrefix}${id}-enf`)
|
|
1072
1334
|
]);
|
|
1073
|
-
|
|
1074
|
-
})
|
|
1075
|
-
|
|
1076
|
-
return;
|
|
1077
|
-
const parsed = await this.engine.deserializeData(data, isEncoded);
|
|
1078
|
-
await Promise.allSettled([
|
|
1079
|
-
this.engine.setValue(`${this.keyPrefix}${this.id}-dat`, await this.engine.serializeData(parsed, this.encodingEnabled())),
|
|
1080
|
-
this.engine.setValue(`${this.keyPrefix}${this.id}-ver`, fmtVer),
|
|
1081
|
-
this.engine.setValue(`${this.keyPrefix}${this.id}-enf`, this.compressionFormat),
|
|
1082
|
-
this.engine.deleteValue(`${this.keyPrefix}${id}-dat`),
|
|
1083
|
-
this.engine.deleteValue(`${this.keyPrefix}${id}-ver`),
|
|
1084
|
-
this.engine.deleteValue(`${this.keyPrefix}${id}-enf`)
|
|
1085
|
-
]);
|
|
1086
|
-
this.events.emit("migrateId", id, this.id);
|
|
1087
|
-
}));
|
|
1335
|
+
this.events.emit("migrateId", id, this.id);
|
|
1336
|
+
})));
|
|
1337
|
+
});
|
|
1088
1338
|
}
|
|
1089
1339
|
};
|
|
1090
1340
|
|
|
1091
1341
|
// lib/DataStoreEngine.ts
|
|
1092
1342
|
var DataStoreEngine = class {
|
|
1093
|
-
dataStoreOptions;
|
|
1094
1343
|
// setDataStoreOptions() is called from inside the DataStore constructor to set this value
|
|
1095
1344
|
constructor(options) {
|
|
1345
|
+
__publicField(this, "dataStoreOptions");
|
|
1096
1346
|
if (options)
|
|
1097
1347
|
this.dataStoreOptions = options;
|
|
1098
1348
|
}
|
|
@@ -1102,25 +1352,29 @@ var DataStoreEngine = class {
|
|
|
1102
1352
|
}
|
|
1103
1353
|
//#region serialization api
|
|
1104
1354
|
/** Serializes the given object to a string, optionally encoded with `options.encodeData` if {@linkcode useEncoding} is not set to false and the `encodeData` and `decodeData` options are set */
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1355
|
+
serializeData(data, useEncoding) {
|
|
1356
|
+
return __async(this, null, function* () {
|
|
1357
|
+
var _a, _b, _c, _d, _e;
|
|
1358
|
+
this.ensureDataStoreOptions();
|
|
1359
|
+
const stringData = JSON.stringify(data);
|
|
1360
|
+
if (!useEncoding || !((_a = this.dataStoreOptions) == null ? void 0 : _a.encodeData) || !((_b = this.dataStoreOptions) == null ? void 0 : _b.decodeData))
|
|
1361
|
+
return stringData;
|
|
1362
|
+
const encRes = (_e = (_d = (_c = this.dataStoreOptions) == null ? void 0 : _c.encodeData) == null ? void 0 : _d[1]) == null ? void 0 : _e.call(_d, stringData);
|
|
1363
|
+
if (encRes instanceof Promise)
|
|
1364
|
+
return yield encRes;
|
|
1365
|
+
return encRes;
|
|
1366
|
+
});
|
|
1115
1367
|
}
|
|
1116
1368
|
/** Deserializes the given string to a JSON object, optionally decoded with `options.decodeData` if {@linkcode useEncoding} is set to true */
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
decRes
|
|
1123
|
-
|
|
1369
|
+
deserializeData(data, useEncoding) {
|
|
1370
|
+
return __async(this, null, function* () {
|
|
1371
|
+
var _a, _b, _c;
|
|
1372
|
+
this.ensureDataStoreOptions();
|
|
1373
|
+
let decRes = ((_a = this.dataStoreOptions) == null ? void 0 : _a.decodeData) && useEncoding ? (_c = (_b = this.dataStoreOptions.decodeData) == null ? void 0 : _b[1]) == null ? void 0 : _c.call(_b, data) : void 0;
|
|
1374
|
+
if (decRes instanceof Promise)
|
|
1375
|
+
decRes = yield decRes;
|
|
1376
|
+
return JSON.parse(decRes != null ? decRes : data);
|
|
1377
|
+
});
|
|
1124
1378
|
}
|
|
1125
1379
|
//#region misc api
|
|
1126
1380
|
/** Throws an error if the DataStoreOptions are not set or invalid */
|
|
@@ -1138,13 +1392,12 @@ var DataStoreEngine = class {
|
|
|
1138
1392
|
try {
|
|
1139
1393
|
if ("structuredClone" in globalThis)
|
|
1140
1394
|
return structuredClone(obj);
|
|
1141
|
-
} catch {
|
|
1395
|
+
} catch (e) {
|
|
1142
1396
|
}
|
|
1143
1397
|
return JSON.parse(JSON.stringify(obj));
|
|
1144
1398
|
}
|
|
1145
1399
|
};
|
|
1146
1400
|
var BrowserStorageEngine = class extends DataStoreEngine {
|
|
1147
|
-
options;
|
|
1148
1401
|
/**
|
|
1149
1402
|
* Creates an instance of `BrowserStorageEngine`.
|
|
1150
1403
|
*
|
|
@@ -1153,36 +1406,40 @@ var BrowserStorageEngine = class extends DataStoreEngine {
|
|
|
1153
1406
|
*/
|
|
1154
1407
|
constructor(options) {
|
|
1155
1408
|
super(options == null ? void 0 : options.dataStoreOptions);
|
|
1156
|
-
this
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
};
|
|
1409
|
+
__publicField(this, "options");
|
|
1410
|
+
this.options = __spreadValues({
|
|
1411
|
+
type: "localStorage"
|
|
1412
|
+
}, options);
|
|
1160
1413
|
}
|
|
1161
1414
|
//#region storage api
|
|
1162
1415
|
/** Fetches a value from persistent storage */
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1416
|
+
getValue(name, defaultValue) {
|
|
1417
|
+
return __async(this, null, function* () {
|
|
1418
|
+
const val = this.options.type === "localStorage" ? globalThis.localStorage.getItem(name) : globalThis.sessionStorage.getItem(name);
|
|
1419
|
+
return typeof val === "undefined" ? defaultValue : val;
|
|
1420
|
+
});
|
|
1166
1421
|
}
|
|
1167
1422
|
/** Sets a value in persistent storage */
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1423
|
+
setValue(name, value) {
|
|
1424
|
+
return __async(this, null, function* () {
|
|
1425
|
+
if (this.options.type === "localStorage")
|
|
1426
|
+
globalThis.localStorage.setItem(name, String(value));
|
|
1427
|
+
else
|
|
1428
|
+
globalThis.sessionStorage.setItem(name, String(value));
|
|
1429
|
+
});
|
|
1173
1430
|
}
|
|
1174
1431
|
/** Deletes a value from persistent storage */
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1432
|
+
deleteValue(name) {
|
|
1433
|
+
return __async(this, null, function* () {
|
|
1434
|
+
if (this.options.type === "localStorage")
|
|
1435
|
+
globalThis.localStorage.removeItem(name);
|
|
1436
|
+
else
|
|
1437
|
+
globalThis.sessionStorage.removeItem(name);
|
|
1438
|
+
});
|
|
1180
1439
|
}
|
|
1181
1440
|
};
|
|
1182
1441
|
var fs;
|
|
1183
1442
|
var FileStorageEngine = class extends DataStoreEngine {
|
|
1184
|
-
options;
|
|
1185
|
-
fileAccessQueue = Promise.resolve();
|
|
1186
1443
|
/**
|
|
1187
1444
|
* Creates an instance of `FileStorageEngine`.
|
|
1188
1445
|
*
|
|
@@ -1191,149 +1448,164 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
1191
1448
|
*/
|
|
1192
1449
|
constructor(options) {
|
|
1193
1450
|
super(options == null ? void 0 : options.dataStoreOptions);
|
|
1194
|
-
this
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1451
|
+
__publicField(this, "options");
|
|
1452
|
+
__publicField(this, "fileAccessQueue", Promise.resolve());
|
|
1453
|
+
this.options = __spreadValues({
|
|
1454
|
+
filePath: (id) => `.ds-${id}`
|
|
1455
|
+
}, options);
|
|
1198
1456
|
}
|
|
1199
1457
|
//#region json file
|
|
1200
1458
|
/** Reads the file contents */
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1459
|
+
readFile() {
|
|
1460
|
+
return __async(this, null, function* () {
|
|
1461
|
+
var _a, _b, _c, _d, _e;
|
|
1462
|
+
this.ensureDataStoreOptions();
|
|
1463
|
+
try {
|
|
1464
|
+
if (!fs)
|
|
1465
|
+
fs = (_a = yield import("fs/promises")) == null ? void 0 : _a.default;
|
|
1466
|
+
if (!fs)
|
|
1467
|
+
throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
|
|
1468
|
+
const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id, this.dataStoreOptions);
|
|
1469
|
+
const data = yield fs.readFile(path, "utf-8");
|
|
1470
|
+
return data ? JSON.parse((_e = yield (_d = (_c = (_b = this.dataStoreOptions) == null ? void 0 : _b.decodeData) == null ? void 0 : _c[1]) == null ? void 0 : _d.call(_c, data)) != null ? _e : data) : void 0;
|
|
1471
|
+
} catch (e) {
|
|
1472
|
+
return void 0;
|
|
1473
|
+
}
|
|
1474
|
+
});
|
|
1215
1475
|
}
|
|
1216
1476
|
/** Overwrites the file contents */
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1477
|
+
writeFile(data) {
|
|
1478
|
+
return __async(this, null, function* () {
|
|
1479
|
+
var _a, _b, _c, _d, _e;
|
|
1480
|
+
this.ensureDataStoreOptions();
|
|
1481
|
+
try {
|
|
1482
|
+
if (!fs)
|
|
1483
|
+
fs = (_a = yield import("fs/promises")) == null ? void 0 : _a.default;
|
|
1484
|
+
if (!fs)
|
|
1485
|
+
throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
|
|
1486
|
+
const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id, this.dataStoreOptions);
|
|
1487
|
+
yield fs.mkdir(path.slice(0, path.lastIndexOf(path.includes("/") ? "/" : "\\")), { recursive: true });
|
|
1488
|
+
yield fs.writeFile(path, (_e = yield (_d = (_c = (_b = this.dataStoreOptions) == null ? void 0 : _b.encodeData) == null ? void 0 : _c[1]) == null ? void 0 : _d.call(_c, JSON.stringify(data))) != null ? _e : JSON.stringify(data, void 0, 2), "utf-8");
|
|
1489
|
+
} catch (err) {
|
|
1490
|
+
console.error("Error writing file:", err);
|
|
1491
|
+
}
|
|
1492
|
+
});
|
|
1231
1493
|
}
|
|
1232
1494
|
//#region storage api
|
|
1233
1495
|
/** Fetches a value from persistent storage */
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
if (typeof defaultValue === "string") {
|
|
1242
|
-
if (typeof value === "object" && value !== null)
|
|
1243
|
-
return JSON.stringify(value);
|
|
1244
|
-
if (typeof value === "string")
|
|
1245
|
-
return value;
|
|
1246
|
-
return String(value);
|
|
1247
|
-
}
|
|
1248
|
-
if (typeof value === "string") {
|
|
1249
|
-
try {
|
|
1250
|
-
const parsed = JSON.parse(value);
|
|
1251
|
-
return parsed;
|
|
1252
|
-
} catch {
|
|
1496
|
+
getValue(name, defaultValue) {
|
|
1497
|
+
return __async(this, null, function* () {
|
|
1498
|
+
const data = yield this.readFile();
|
|
1499
|
+
if (!data)
|
|
1500
|
+
return defaultValue;
|
|
1501
|
+
const value = data == null ? void 0 : data[name];
|
|
1502
|
+
if (typeof value === "undefined")
|
|
1253
1503
|
return defaultValue;
|
|
1504
|
+
if (typeof defaultValue === "string") {
|
|
1505
|
+
if (typeof value === "object" && value !== null)
|
|
1506
|
+
return JSON.stringify(value);
|
|
1507
|
+
if (typeof value === "string")
|
|
1508
|
+
return value;
|
|
1509
|
+
return String(value);
|
|
1254
1510
|
}
|
|
1255
|
-
}
|
|
1256
|
-
return value;
|
|
1257
|
-
}
|
|
1258
|
-
/** Sets a value in persistent storage */
|
|
1259
|
-
async setValue(name, value) {
|
|
1260
|
-
this.fileAccessQueue = this.fileAccessQueue.then(async () => {
|
|
1261
|
-
let data = await this.readFile();
|
|
1262
|
-
if (!data)
|
|
1263
|
-
data = {};
|
|
1264
|
-
let storeVal = value;
|
|
1265
1511
|
if (typeof value === "string") {
|
|
1266
1512
|
try {
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
}
|
|
1272
|
-
} catch {
|
|
1513
|
+
const parsed = JSON.parse(value);
|
|
1514
|
+
return parsed;
|
|
1515
|
+
} catch (e) {
|
|
1516
|
+
return defaultValue;
|
|
1273
1517
|
}
|
|
1274
1518
|
}
|
|
1275
|
-
|
|
1276
|
-
await this.writeFile(data);
|
|
1277
|
-
}).catch((err) => {
|
|
1278
|
-
console.error("Error in setValue:", err);
|
|
1279
|
-
throw err;
|
|
1519
|
+
return value;
|
|
1280
1520
|
});
|
|
1281
|
-
|
|
1521
|
+
}
|
|
1522
|
+
/** Sets a value in persistent storage */
|
|
1523
|
+
setValue(name, value) {
|
|
1524
|
+
return __async(this, null, function* () {
|
|
1525
|
+
this.fileAccessQueue = this.fileAccessQueue.then(() => __async(this, null, function* () {
|
|
1526
|
+
let data = yield this.readFile();
|
|
1527
|
+
if (!data)
|
|
1528
|
+
data = {};
|
|
1529
|
+
let storeVal = value;
|
|
1530
|
+
if (typeof value === "string") {
|
|
1531
|
+
try {
|
|
1532
|
+
if (value.startsWith("{") || value.startsWith("[")) {
|
|
1533
|
+
const parsed = JSON.parse(value);
|
|
1534
|
+
if (typeof parsed === "object" && parsed !== null)
|
|
1535
|
+
storeVal = parsed;
|
|
1536
|
+
}
|
|
1537
|
+
} catch (e) {
|
|
1538
|
+
}
|
|
1539
|
+
}
|
|
1540
|
+
data[name] = storeVal;
|
|
1541
|
+
yield this.writeFile(data);
|
|
1542
|
+
})).catch((err) => {
|
|
1543
|
+
console.error("Error in setValue:", err);
|
|
1544
|
+
throw err;
|
|
1545
|
+
});
|
|
1546
|
+
yield this.fileAccessQueue.catch(() => {
|
|
1547
|
+
});
|
|
1282
1548
|
});
|
|
1283
1549
|
}
|
|
1284
1550
|
/** Deletes a value from persistent storage */
|
|
1285
|
-
|
|
1286
|
-
this
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1551
|
+
deleteValue(name) {
|
|
1552
|
+
return __async(this, null, function* () {
|
|
1553
|
+
this.fileAccessQueue = this.fileAccessQueue.then(() => __async(this, null, function* () {
|
|
1554
|
+
const data = yield this.readFile();
|
|
1555
|
+
if (!data)
|
|
1556
|
+
return;
|
|
1557
|
+
delete data[name];
|
|
1558
|
+
yield this.writeFile(data);
|
|
1559
|
+
})).catch((err) => {
|
|
1560
|
+
console.error("Error in deleteValue:", err);
|
|
1561
|
+
throw err;
|
|
1562
|
+
});
|
|
1563
|
+
yield this.fileAccessQueue.catch(() => {
|
|
1564
|
+
});
|
|
1297
1565
|
});
|
|
1298
1566
|
}
|
|
1299
1567
|
/** Deletes the file that contains the data of this DataStore. */
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1568
|
+
deleteStorage() {
|
|
1569
|
+
return __async(this, null, function* () {
|
|
1570
|
+
var _a;
|
|
1571
|
+
this.ensureDataStoreOptions();
|
|
1572
|
+
try {
|
|
1573
|
+
if (!fs)
|
|
1574
|
+
fs = (_a = yield import("fs/promises")) == null ? void 0 : _a.default;
|
|
1575
|
+
if (!fs)
|
|
1576
|
+
throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
|
|
1577
|
+
const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id, this.dataStoreOptions);
|
|
1578
|
+
return yield fs.unlink(path);
|
|
1579
|
+
} catch (err) {
|
|
1580
|
+
console.error("Error deleting file:", err);
|
|
1581
|
+
}
|
|
1582
|
+
});
|
|
1313
1583
|
}
|
|
1314
1584
|
};
|
|
1315
1585
|
|
|
1316
1586
|
// lib/DataStoreSerializer.ts
|
|
1317
1587
|
var DataStoreSerializer = class _DataStoreSerializer {
|
|
1318
|
-
stores;
|
|
1319
|
-
options;
|
|
1320
1588
|
constructor(stores, options = {}) {
|
|
1589
|
+
__publicField(this, "stores");
|
|
1590
|
+
// eslint-disable-line @typescript-eslint/no-explicit-any
|
|
1591
|
+
__publicField(this, "options");
|
|
1321
1592
|
if (!crypto || !crypto.subtle)
|
|
1322
1593
|
throw new ScriptContextError("DataStoreSerializer has to run in a secure context (HTTPS) or in another environment that implements the subtleCrypto API!");
|
|
1323
1594
|
this.stores = stores;
|
|
1324
|
-
this.options = {
|
|
1595
|
+
this.options = __spreadValues({
|
|
1325
1596
|
addChecksum: true,
|
|
1326
1597
|
ensureIntegrity: true,
|
|
1327
|
-
remapIds: {}
|
|
1328
|
-
|
|
1329
|
-
};
|
|
1598
|
+
remapIds: {}
|
|
1599
|
+
}, options);
|
|
1330
1600
|
}
|
|
1331
1601
|
/**
|
|
1332
1602
|
* Calculates the checksum of a string. Uses {@linkcode computeHash()} with SHA-256 and digests as a hex string by default.
|
|
1333
1603
|
* Override this in a subclass if a custom checksum method is needed.
|
|
1334
1604
|
*/
|
|
1335
|
-
|
|
1336
|
-
return
|
|
1605
|
+
calcChecksum(input) {
|
|
1606
|
+
return __async(this, null, function* () {
|
|
1607
|
+
return computeHash(input, "SHA-256");
|
|
1608
|
+
});
|
|
1337
1609
|
}
|
|
1338
1610
|
/**
|
|
1339
1611
|
* Serializes only a subset of the data stores into a string.
|
|
@@ -1341,72 +1613,80 @@ var DataStoreSerializer = class _DataStoreSerializer {
|
|
|
1341
1613
|
* @param useEncoding Whether to encode the data using each DataStore's `encodeData()` method
|
|
1342
1614
|
* @param stringified Whether to return the result as a string or as an array of `SerializedDataStore` objects
|
|
1343
1615
|
*/
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1616
|
+
serializePartial(stores, useEncoding = true, stringified = true) {
|
|
1617
|
+
return __async(this, null, function* () {
|
|
1618
|
+
var _a;
|
|
1619
|
+
const serData = [];
|
|
1620
|
+
const filteredStores = this.stores.filter((s) => typeof stores === "function" ? stores(s.id) : stores.includes(s.id));
|
|
1621
|
+
for (const storeInst of filteredStores) {
|
|
1622
|
+
const encoded = Boolean(useEncoding && storeInst.encodingEnabled() && ((_a = storeInst.encodeData) == null ? void 0 : _a[1]));
|
|
1623
|
+
const rawData = storeInst.memoryCache ? storeInst.getData() : yield storeInst.loadData();
|
|
1624
|
+
const data = encoded ? yield storeInst.encodeData[1](JSON.stringify(rawData)) : JSON.stringify(rawData);
|
|
1625
|
+
serData.push({
|
|
1626
|
+
id: storeInst.id,
|
|
1627
|
+
data,
|
|
1628
|
+
formatVersion: storeInst.formatVersion,
|
|
1629
|
+
encoded,
|
|
1630
|
+
checksum: this.options.addChecksum ? yield this.calcChecksum(data) : void 0
|
|
1631
|
+
});
|
|
1632
|
+
}
|
|
1633
|
+
return stringified ? JSON.stringify(serData) : serData;
|
|
1634
|
+
});
|
|
1361
1635
|
}
|
|
1362
1636
|
/**
|
|
1363
1637
|
* Serializes the data stores into a string.
|
|
1364
1638
|
* @param useEncoding Whether to encode the data using each DataStore's `encodeData()` method
|
|
1365
1639
|
* @param stringified Whether to return the result as a string or as an array of `SerializedDataStore` objects
|
|
1366
1640
|
*/
|
|
1367
|
-
|
|
1368
|
-
return
|
|
1641
|
+
serialize(useEncoding = true, stringified = true) {
|
|
1642
|
+
return __async(this, null, function* () {
|
|
1643
|
+
return this.serializePartial(this.stores.map((s) => s.id), useEncoding, stringified);
|
|
1644
|
+
});
|
|
1369
1645
|
}
|
|
1370
1646
|
/**
|
|
1371
1647
|
* Deserializes the data exported via {@linkcode serialize()} and imports only a subset into the DataStore instances.
|
|
1372
1648
|
* Also triggers the migration process if the data format has changed.
|
|
1373
1649
|
*/
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
const
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1650
|
+
deserializePartial(stores, data) {
|
|
1651
|
+
return __async(this, null, function* () {
|
|
1652
|
+
const deserStores = typeof data === "string" ? JSON.parse(data) : data;
|
|
1653
|
+
if (!Array.isArray(deserStores) || !deserStores.every(_DataStoreSerializer.isSerializedDataStoreObj))
|
|
1654
|
+
throw new TypeError("Invalid serialized data format! Expected an array of SerializedDataStore objects.");
|
|
1655
|
+
const resolveStoreId = (id) => {
|
|
1656
|
+
var _a, _b;
|
|
1657
|
+
return (_b = (_a = Object.entries(this.options.remapIds).find(([, v]) => v.includes(id))) == null ? void 0 : _a[0]) != null ? _b : id;
|
|
1658
|
+
};
|
|
1659
|
+
const matchesFilter = (id) => typeof stores === "function" ? stores(id) : stores.includes(id);
|
|
1660
|
+
for (const storeData of deserStores) {
|
|
1661
|
+
const effectiveId = resolveStoreId(storeData.id);
|
|
1662
|
+
if (!matchesFilter(effectiveId))
|
|
1663
|
+
continue;
|
|
1664
|
+
const storeInst = this.stores.find((s) => s.id === effectiveId);
|
|
1665
|
+
if (!storeInst)
|
|
1666
|
+
throw new DatedError(`Can't deserialize data because no DataStore instance with the ID "${effectiveId}" was found! Make sure to provide it in the DataStoreSerializer constructor.`);
|
|
1667
|
+
if (this.options.ensureIntegrity && typeof storeData.checksum === "string") {
|
|
1668
|
+
const checksum = yield this.calcChecksum(storeData.data);
|
|
1669
|
+
if (checksum !== storeData.checksum)
|
|
1670
|
+
throw new ChecksumMismatchError(`Checksum mismatch for DataStore with ID "${storeData.id}"!
|
|
1394
1671
|
Expected: ${storeData.checksum}
|
|
1395
1672
|
Has: ${checksum}`);
|
|
1673
|
+
}
|
|
1674
|
+
const decodedData = storeData.encoded && storeInst.encodingEnabled() ? yield storeInst.decodeData[1](storeData.data) : storeData.data;
|
|
1675
|
+
if (storeData.formatVersion && !isNaN(Number(storeData.formatVersion)) && Number(storeData.formatVersion) < storeInst.formatVersion)
|
|
1676
|
+
yield storeInst.runMigrations(JSON.parse(decodedData), Number(storeData.formatVersion), false);
|
|
1677
|
+
else
|
|
1678
|
+
yield storeInst.setData(JSON.parse(decodedData));
|
|
1396
1679
|
}
|
|
1397
|
-
|
|
1398
|
-
if (storeData.formatVersion && !isNaN(Number(storeData.formatVersion)) && Number(storeData.formatVersion) < storeInst.formatVersion)
|
|
1399
|
-
await storeInst.runMigrations(JSON.parse(decodedData), Number(storeData.formatVersion), false);
|
|
1400
|
-
else
|
|
1401
|
-
await storeInst.setData(JSON.parse(decodedData));
|
|
1402
|
-
}
|
|
1680
|
+
});
|
|
1403
1681
|
}
|
|
1404
1682
|
/**
|
|
1405
1683
|
* Deserializes the data exported via {@linkcode serialize()} and imports the data into all matching DataStore instances.
|
|
1406
1684
|
* Also triggers the migration process if the data format has changed.
|
|
1407
1685
|
*/
|
|
1408
|
-
|
|
1409
|
-
return
|
|
1686
|
+
deserialize(data) {
|
|
1687
|
+
return __async(this, null, function* () {
|
|
1688
|
+
return this.deserializePartial(this.stores.map((s) => s.id), data);
|
|
1689
|
+
});
|
|
1410
1690
|
}
|
|
1411
1691
|
/**
|
|
1412
1692
|
* Loads the persistent data of the DataStore instances into the in-memory cache.
|
|
@@ -1414,32 +1694,40 @@ Has: ${checksum}`);
|
|
|
1414
1694
|
* @param stores An array of store IDs or a function that takes the store IDs and returns a boolean - if omitted, all stores will be loaded
|
|
1415
1695
|
* @returns Returns a PromiseSettledResult array with the results of each DataStore instance in the format `{ id: string, data: object }`
|
|
1416
1696
|
*/
|
|
1417
|
-
|
|
1418
|
-
return
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1697
|
+
loadStoresData(stores) {
|
|
1698
|
+
return __async(this, null, function* () {
|
|
1699
|
+
return Promise.allSettled(
|
|
1700
|
+
this.getStoresFiltered(stores).map((store) => __async(this, null, function* () {
|
|
1701
|
+
return {
|
|
1702
|
+
id: store.id,
|
|
1703
|
+
data: yield store.loadData()
|
|
1704
|
+
};
|
|
1705
|
+
}))
|
|
1706
|
+
);
|
|
1707
|
+
});
|
|
1424
1708
|
}
|
|
1425
1709
|
/**
|
|
1426
1710
|
* Resets the persistent and in-memory data of the DataStore instances to their default values.
|
|
1427
1711
|
* @param stores An array of store IDs or a function that takes the store IDs and returns a boolean - if omitted, all stores will be affected
|
|
1428
1712
|
*/
|
|
1429
|
-
|
|
1430
|
-
return
|
|
1431
|
-
|
|
1432
|
-
|
|
1713
|
+
resetStoresData(stores) {
|
|
1714
|
+
return __async(this, null, function* () {
|
|
1715
|
+
return Promise.allSettled(
|
|
1716
|
+
this.getStoresFiltered(stores).map((store) => store.saveDefaultData())
|
|
1717
|
+
);
|
|
1718
|
+
});
|
|
1433
1719
|
}
|
|
1434
1720
|
/**
|
|
1435
1721
|
* Deletes the persistent data of the DataStore instances.
|
|
1436
1722
|
* Leaves the in-memory data untouched.
|
|
1437
1723
|
* @param stores An array of store IDs or a function that takes the store IDs and returns a boolean - if omitted, all stores will be affected
|
|
1438
1724
|
*/
|
|
1439
|
-
|
|
1440
|
-
return
|
|
1441
|
-
|
|
1442
|
-
|
|
1725
|
+
deleteStoresData(stores) {
|
|
1726
|
+
return __async(this, null, function* () {
|
|
1727
|
+
return Promise.allSettled(
|
|
1728
|
+
this.getStoresFiltered(stores).map((store) => store.deleteData())
|
|
1729
|
+
);
|
|
1730
|
+
});
|
|
1443
1731
|
}
|
|
1444
1732
|
/** Checks if a given value is an array of SerializedDataStore objects */
|
|
1445
1733
|
static isSerializedDataStoreObjArray(obj) {
|
|
@@ -1466,13 +1754,13 @@ var Debouncer = class extends NanoEmitter {
|
|
|
1466
1754
|
super(nanoEmitterOptions);
|
|
1467
1755
|
this.timeout = timeout;
|
|
1468
1756
|
this.type = type;
|
|
1757
|
+
/** All registered listener functions and the time they were attached */
|
|
1758
|
+
__publicField(this, "listeners", []);
|
|
1759
|
+
/** The currently active timeout */
|
|
1760
|
+
__publicField(this, "activeTimeout");
|
|
1761
|
+
/** The latest queued call */
|
|
1762
|
+
__publicField(this, "queuedCall");
|
|
1469
1763
|
}
|
|
1470
|
-
/** All registered listener functions and the time they were attached */
|
|
1471
|
-
listeners = [];
|
|
1472
|
-
/** The currently active timeout */
|
|
1473
|
-
activeTimeout;
|
|
1474
|
-
/** The latest queued call */
|
|
1475
|
-
queuedCall;
|
|
1476
1764
|
//#region listeners
|
|
1477
1765
|
/** Adds a listener function that will be called on timeout */
|
|
1478
1766
|
addListener(fn) {
|
|
@@ -1559,6 +1847,8 @@ function debounce(fn, timeout = 200, type = "immediate", nanoEmitterOptions) {
|
|
|
1559
1847
|
return func;
|
|
1560
1848
|
}
|
|
1561
1849
|
|
|
1850
|
+
if(__exports != exports)module.exports = exports;return module.exports}));
|
|
1851
|
+
|
|
1562
1852
|
|
|
1563
1853
|
|
|
1564
1854
|
if (typeof module.exports == "object" && typeof exports == "object") {
|