@sv443-network/coreutils 2.0.0 → 2.0.2
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 +12 -0
- package/dist/CoreUtils.cjs +25 -15
- package/dist/CoreUtils.min.cjs +2 -2
- package/dist/CoreUtils.min.mjs +2 -2
- package/dist/CoreUtils.min.umd.js +2 -2
- package/dist/CoreUtils.mjs +25 -15
- package/dist/CoreUtils.umd.js +511 -388
- package/dist/lib/DataStoreEngine.d.ts +2 -1
- package/dist/lib/TestDataStore.d.ts +12 -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 = {};
|
|
@@ -190,7 +239,7 @@ function randRange(...args) {
|
|
|
190
239
|
return Math.floor(Math.random() * (max - min + 1)) + min;
|
|
191
240
|
}
|
|
192
241
|
function roundFixed(num, fractionDigits) {
|
|
193
|
-
const scale = 10
|
|
242
|
+
const scale = __pow(10, fractionDigits);
|
|
194
243
|
return Math.round(num * scale) / scale;
|
|
195
244
|
}
|
|
196
245
|
function valsWithin(a, b, dec = 10, withinRange = 0.5) {
|
|
@@ -254,7 +303,7 @@ function darkenColor(color, percent, upperCase = false) {
|
|
|
254
303
|
if (isHexCol)
|
|
255
304
|
return rgbToHex(r, g, b, a, color.startsWith("#"), upperCase);
|
|
256
305
|
else if (color.startsWith("rgba"))
|
|
257
|
-
return `rgba(${r}, ${g}, ${b}, ${a
|
|
306
|
+
return `rgba(${r}, ${g}, ${b}, ${a != null ? a : NaN})`;
|
|
258
307
|
else
|
|
259
308
|
return `rgb(${r}, ${g}, ${b})`;
|
|
260
309
|
}
|
|
@@ -288,35 +337,43 @@ function abtoa(buf) {
|
|
|
288
337
|
function atoab(str) {
|
|
289
338
|
return Uint8Array.from(atob(str), (c) => c.charCodeAt(0));
|
|
290
339
|
}
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
340
|
+
function compress(input, compressionFormat, outputType = "string") {
|
|
341
|
+
return __async(this, null, function* () {
|
|
342
|
+
var _a;
|
|
343
|
+
const byteArray = input instanceof Uint8Array ? input : new TextEncoder().encode((_a = input == null ? void 0 : input.toString()) != null ? _a : String(input));
|
|
344
|
+
const comp = new CompressionStream(compressionFormat);
|
|
345
|
+
const writer = comp.writable.getWriter();
|
|
346
|
+
writer.write(byteArray);
|
|
347
|
+
writer.close();
|
|
348
|
+
const uintArr = new Uint8Array(yield new Response(comp.readable).arrayBuffer());
|
|
349
|
+
return outputType === "arrayBuffer" ? uintArr : abtoa(uintArr);
|
|
350
|
+
});
|
|
299
351
|
}
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
352
|
+
function decompress(input, compressionFormat, outputType = "string") {
|
|
353
|
+
return __async(this, null, function* () {
|
|
354
|
+
var _a;
|
|
355
|
+
const byteArray = input instanceof Uint8Array ? input : atoab((_a = input == null ? void 0 : input.toString()) != null ? _a : String(input));
|
|
356
|
+
const decomp = new DecompressionStream(compressionFormat);
|
|
357
|
+
const writer = decomp.writable.getWriter();
|
|
358
|
+
writer.write(byteArray);
|
|
359
|
+
writer.close();
|
|
360
|
+
const uintArr = new Uint8Array(yield new Response(decomp.readable).arrayBuffer());
|
|
361
|
+
return outputType === "arrayBuffer" ? uintArr : new TextDecoder().decode(uintArr);
|
|
362
|
+
});
|
|
308
363
|
}
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
364
|
+
function computeHash(input, algorithm = "SHA-256") {
|
|
365
|
+
return __async(this, null, function* () {
|
|
366
|
+
let data;
|
|
367
|
+
if (typeof input === "string") {
|
|
368
|
+
const encoder = new TextEncoder();
|
|
369
|
+
data = encoder.encode(input);
|
|
370
|
+
} else
|
|
371
|
+
data = input;
|
|
372
|
+
const hashBuffer = yield crypto.subtle.digest(algorithm, data);
|
|
373
|
+
const hashArray = Array.from(new Uint8Array(hashBuffer));
|
|
374
|
+
const hashHex = hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
375
|
+
return hashHex;
|
|
376
|
+
});
|
|
320
377
|
}
|
|
321
378
|
function randomId(length = 16, radix = 16, enhancedEntropy = false, randomCase = true) {
|
|
322
379
|
if (length < 1)
|
|
@@ -344,35 +401,38 @@ function randomId(length = 16, radix = 16, enhancedEntropy = false, randomCase =
|
|
|
344
401
|
}
|
|
345
402
|
|
|
346
403
|
// lib/misc.ts
|
|
347
|
-
|
|
348
|
-
return
|
|
404
|
+
function consumeGen(valGen) {
|
|
405
|
+
return __async(this, null, function* () {
|
|
406
|
+
return yield typeof valGen === "function" ? valGen() : valGen;
|
|
407
|
+
});
|
|
349
408
|
}
|
|
350
|
-
|
|
351
|
-
return
|
|
352
|
-
typeof strGen === "
|
|
353
|
-
|
|
409
|
+
function consumeStringGen(strGen) {
|
|
410
|
+
return __async(this, null, function* () {
|
|
411
|
+
return typeof strGen === "string" ? strGen : String(
|
|
412
|
+
typeof strGen === "function" ? yield strGen() : strGen
|
|
413
|
+
);
|
|
414
|
+
});
|
|
354
415
|
}
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
}
|
|
416
|
+
function fetchAdvanced(_0) {
|
|
417
|
+
return __async(this, arguments, function* (input, options = {}) {
|
|
418
|
+
const { timeout = 1e4 } = options;
|
|
419
|
+
const ctl = new AbortController();
|
|
420
|
+
const _a = options, { signal } = _a, restOpts = __objRest(_a, ["signal"]);
|
|
421
|
+
signal == null ? void 0 : signal.addEventListener("abort", () => ctl.abort());
|
|
422
|
+
let sigOpts = {}, id = void 0;
|
|
423
|
+
if (timeout >= 0) {
|
|
424
|
+
id = setTimeout(() => ctl.abort(), timeout);
|
|
425
|
+
sigOpts = { signal: ctl.signal };
|
|
426
|
+
}
|
|
427
|
+
try {
|
|
428
|
+
const res = yield fetch(input, __spreadValues(__spreadValues({}, restOpts), sigOpts));
|
|
429
|
+
typeof id !== "undefined" && clearTimeout(id);
|
|
430
|
+
return res;
|
|
431
|
+
} catch (err) {
|
|
432
|
+
typeof id !== "undefined" && clearTimeout(id);
|
|
433
|
+
throw new Error("Error while calling fetch", { cause: err });
|
|
434
|
+
}
|
|
435
|
+
});
|
|
376
436
|
}
|
|
377
437
|
function getListLength(listLike, zeroOnInvalid = true) {
|
|
378
438
|
return "length" in listLike ? listLike.length : "size" in listLike ? listLike.size : "count" in listLike ? listLike.count : zeroOnInvalid ? 0 : NaN;
|
|
@@ -387,7 +447,7 @@ function pauseFor(time, signal, rejectOnAbort = false) {
|
|
|
387
447
|
});
|
|
388
448
|
}
|
|
389
449
|
function pureObj(obj) {
|
|
390
|
-
return Object.assign(/* @__PURE__ */ Object.create(null), obj
|
|
450
|
+
return Object.assign(/* @__PURE__ */ Object.create(null), obj != null ? obj : {});
|
|
391
451
|
}
|
|
392
452
|
function setImmediateInterval(callback, interval, signal) {
|
|
393
453
|
let intervalId;
|
|
@@ -404,12 +464,12 @@ function setImmediateInterval(callback, interval, signal) {
|
|
|
404
464
|
function setImmediateTimeoutLoop(callback, interval, signal) {
|
|
405
465
|
let timeout;
|
|
406
466
|
const cleanup = () => clearTimeout(timeout);
|
|
407
|
-
const loop =
|
|
467
|
+
const loop = () => __async(null, null, function* () {
|
|
408
468
|
if (signal == null ? void 0 : signal.aborted)
|
|
409
469
|
return cleanup();
|
|
410
|
-
|
|
470
|
+
yield callback();
|
|
411
471
|
timeout = setTimeout(loop, interval);
|
|
412
|
-
};
|
|
472
|
+
});
|
|
413
473
|
signal == null ? void 0 : signal.addEventListener("abort", cleanup);
|
|
414
474
|
loop();
|
|
415
475
|
}
|
|
@@ -476,9 +536,9 @@ function createProgressBar(percentage, barLength, chars = defaultPbChars) {
|
|
|
476
536
|
}
|
|
477
537
|
function insertValues(input, ...values) {
|
|
478
538
|
return input.replace(/%\d/gm, (match) => {
|
|
479
|
-
var _a;
|
|
539
|
+
var _a, _b;
|
|
480
540
|
const argIndex = Number(match.substring(1)) - 1;
|
|
481
|
-
return (_a = values[argIndex]
|
|
541
|
+
return (_b = (_a = values[argIndex]) != null ? _a : match) == null ? void 0 : _b.toString();
|
|
482
542
|
});
|
|
483
543
|
}
|
|
484
544
|
function joinArrayReadable(array, separators = ", ", lastSeparator = " and ") {
|
|
@@ -507,16 +567,17 @@ function secsToTimeStr(seconds) {
|
|
|
507
567
|
].join("");
|
|
508
568
|
}
|
|
509
569
|
function truncStr(input, length, endStr = "...") {
|
|
510
|
-
|
|
570
|
+
var _a;
|
|
571
|
+
const str = (_a = input == null ? void 0 : input.toString()) != null ? _a : String(input);
|
|
511
572
|
const finalStr = str.length > length ? str.substring(0, length - endStr.length) + endStr : str;
|
|
512
573
|
return finalStr.length > length ? finalStr.substring(0, length) : finalStr;
|
|
513
574
|
}
|
|
514
575
|
|
|
515
576
|
// lib/Errors.ts
|
|
516
577
|
var DatedError = class extends Error {
|
|
517
|
-
date;
|
|
518
578
|
constructor(message, options) {
|
|
519
579
|
super(message, options);
|
|
580
|
+
__publicField(this, "date");
|
|
520
581
|
this.name = this.constructor.name;
|
|
521
582
|
this.date = /* @__PURE__ */ new Date();
|
|
522
583
|
}
|
|
@@ -543,24 +604,6 @@ var ValidationError = class extends DatedError {
|
|
|
543
604
|
// lib/DataStore.ts
|
|
544
605
|
var dsFmtVer = 1;
|
|
545
606
|
var DataStore = class {
|
|
546
|
-
id;
|
|
547
|
-
formatVersion;
|
|
548
|
-
defaultData;
|
|
549
|
-
encodeData;
|
|
550
|
-
decodeData;
|
|
551
|
-
compressionFormat = "deflate-raw";
|
|
552
|
-
engine;
|
|
553
|
-
options;
|
|
554
|
-
/**
|
|
555
|
-
* Whether all first-init checks should be done.
|
|
556
|
-
* This includes migrating the internal DataStore format, migrating data from the UserUtils format, and anything similar.
|
|
557
|
-
* 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.
|
|
558
|
-
*/
|
|
559
|
-
firstInit = true;
|
|
560
|
-
/** In-memory cached copy of the data that is saved in persistent storage used for synchronous read access. */
|
|
561
|
-
cachedData;
|
|
562
|
-
migrations;
|
|
563
|
-
migrateIds = [];
|
|
564
607
|
/**
|
|
565
608
|
* Creates an instance of DataStore to manage a sync & async database that is cached in memory and persistently saved across sessions.
|
|
566
609
|
* Supports migrating data from older versions to newer ones and populating the cache with default data if no persistent data is found.
|
|
@@ -571,7 +614,25 @@ var DataStore = class {
|
|
|
571
614
|
* @param opts The options for this DataStore instance
|
|
572
615
|
*/
|
|
573
616
|
constructor(opts) {
|
|
574
|
-
|
|
617
|
+
__publicField(this, "id");
|
|
618
|
+
__publicField(this, "formatVersion");
|
|
619
|
+
__publicField(this, "defaultData");
|
|
620
|
+
__publicField(this, "encodeData");
|
|
621
|
+
__publicField(this, "decodeData");
|
|
622
|
+
__publicField(this, "compressionFormat", "deflate-raw");
|
|
623
|
+
__publicField(this, "engine");
|
|
624
|
+
__publicField(this, "options");
|
|
625
|
+
/**
|
|
626
|
+
* Whether all first-init checks should be done.
|
|
627
|
+
* This includes migrating the internal DataStore format, migrating data from the UserUtils format, and anything similar.
|
|
628
|
+
* 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.
|
|
629
|
+
*/
|
|
630
|
+
__publicField(this, "firstInit", true);
|
|
631
|
+
/** In-memory cached copy of the data that is saved in persistent storage used for synchronous read access. */
|
|
632
|
+
__publicField(this, "cachedData");
|
|
633
|
+
__publicField(this, "migrations");
|
|
634
|
+
__publicField(this, "migrateIds", []);
|
|
635
|
+
var _a, _b, _c;
|
|
575
636
|
this.id = opts.id;
|
|
576
637
|
this.formatVersion = opts.formatVersion;
|
|
577
638
|
this.defaultData = opts.defaultData;
|
|
@@ -584,16 +645,22 @@ var DataStore = class {
|
|
|
584
645
|
this.engine = typeof opts.engine === "function" ? opts.engine() : opts.engine;
|
|
585
646
|
this.options = opts;
|
|
586
647
|
if (typeof opts.compressionFormat === "undefined")
|
|
587
|
-
opts.compressionFormat = ((_a = opts.encodeData) == null ? void 0 : _a[0])
|
|
648
|
+
this.compressionFormat = opts.compressionFormat = (_b = (_a = opts.encodeData) == null ? void 0 : _a[0]) != null ? _b : "deflate-raw";
|
|
588
649
|
if (typeof opts.compressionFormat === "string") {
|
|
589
|
-
this.encodeData = [opts.compressionFormat,
|
|
590
|
-
|
|
650
|
+
this.encodeData = [opts.compressionFormat, (data) => __async(this, null, function* () {
|
|
651
|
+
return yield compress(data, opts.compressionFormat, "string");
|
|
652
|
+
})];
|
|
653
|
+
this.decodeData = [opts.compressionFormat, (data) => __async(this, null, function* () {
|
|
654
|
+
return yield compress(data, opts.compressionFormat, "string");
|
|
655
|
+
})];
|
|
591
656
|
} else if ("encodeData" in opts && "decodeData" in opts && Array.isArray(opts.encodeData) && Array.isArray(opts.decodeData)) {
|
|
592
657
|
this.encodeData = [opts.encodeData[0], opts.encodeData[1]];
|
|
593
658
|
this.decodeData = [opts.decodeData[0], opts.decodeData[1]];
|
|
659
|
+
this.compressionFormat = (_c = opts.encodeData[0]) != null ? _c : null;
|
|
594
660
|
} else if (opts.compressionFormat === null) {
|
|
595
661
|
this.encodeData = void 0;
|
|
596
662
|
this.decodeData = void 0;
|
|
663
|
+
this.compressionFormat = null;
|
|
597
664
|
} else
|
|
598
665
|
throw new TypeError("Either `compressionFormat` or `encodeData` and `decodeData` have to be set and valid, but not all three at a time. Please refer to the documentation for more info.");
|
|
599
666
|
this.engine.setDataStoreOptions(opts);
|
|
@@ -604,62 +671,64 @@ var DataStore = class {
|
|
|
604
671
|
* Automatically populates persistent storage with default data if it doesn't contain any data yet.
|
|
605
672
|
* Also runs all necessary migration functions if the data format has changed since the last time the data was saved.
|
|
606
673
|
*/
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
this.firstInit
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
674
|
+
loadData() {
|
|
675
|
+
return __async(this, null, function* () {
|
|
676
|
+
try {
|
|
677
|
+
if (this.firstInit) {
|
|
678
|
+
this.firstInit = false;
|
|
679
|
+
const dsVer = Number(yield this.engine.getValue("__ds_fmt_ver", 0));
|
|
680
|
+
if (isNaN(dsVer) || dsVer < 1) {
|
|
681
|
+
const oldData = yield this.engine.getValue(`_uucfg-${this.id}`, null);
|
|
682
|
+
if (oldData) {
|
|
683
|
+
const oldVer = Number(yield this.engine.getValue(`_uucfgver-${this.id}`, NaN));
|
|
684
|
+
const oldEnc = yield this.engine.getValue(`_uucfgenc-${this.id}`, null);
|
|
685
|
+
const promises = [];
|
|
686
|
+
const migrateFmt = (oldKey, newKey, value) => {
|
|
687
|
+
promises.push(this.engine.setValue(newKey, value));
|
|
688
|
+
promises.push(this.engine.deleteValue(oldKey));
|
|
689
|
+
};
|
|
690
|
+
if (oldData)
|
|
691
|
+
migrateFmt(`_uucfg-${this.id}`, `__ds-${this.id}-dat`, oldData);
|
|
692
|
+
if (!isNaN(oldVer))
|
|
693
|
+
migrateFmt(`_uucfgver-${this.id}`, `__ds-${this.id}-ver`, oldVer);
|
|
694
|
+
if (typeof oldEnc === "boolean")
|
|
695
|
+
migrateFmt(`_uucfgenc-${this.id}`, `__ds-${this.id}-enf`, oldEnc === true ? Boolean(this.compressionFormat) || null : null);
|
|
696
|
+
else
|
|
697
|
+
promises.push(this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat));
|
|
698
|
+
yield Promise.allSettled(promises);
|
|
699
|
+
}
|
|
700
|
+
yield this.engine.setValue("__ds_fmt_ver", dsFmtVer);
|
|
631
701
|
}
|
|
632
|
-
await this.engine.setValue("__ds_fmt_ver", dsFmtVer);
|
|
633
702
|
}
|
|
703
|
+
if (this.migrateIds.length > 0) {
|
|
704
|
+
yield this.migrateId(this.migrateIds);
|
|
705
|
+
this.migrateIds = [];
|
|
706
|
+
}
|
|
707
|
+
const storedData = yield this.engine.getValue(`__ds-${this.id}-dat`, JSON.stringify(this.defaultData));
|
|
708
|
+
let storedFmtVer = Number(yield this.engine.getValue(`__ds-${this.id}-ver`, NaN));
|
|
709
|
+
if (typeof storedData !== "string") {
|
|
710
|
+
yield this.saveDefaultData();
|
|
711
|
+
return __spreadValues({}, this.defaultData);
|
|
712
|
+
}
|
|
713
|
+
const encodingFmt = String(yield this.engine.getValue(`__ds-${this.id}-enf`, null));
|
|
714
|
+
const isEncoded = encodingFmt !== "null" && encodingFmt !== "false";
|
|
715
|
+
let saveData = false;
|
|
716
|
+
if (isNaN(storedFmtVer)) {
|
|
717
|
+
yield this.engine.setValue(`__ds-${this.id}-ver`, storedFmtVer = this.formatVersion);
|
|
718
|
+
saveData = true;
|
|
719
|
+
}
|
|
720
|
+
let parsed = yield this.engine.deserializeData(storedData, isEncoded);
|
|
721
|
+
if (storedFmtVer < this.formatVersion && this.migrations)
|
|
722
|
+
parsed = yield this.runMigrations(parsed, storedFmtVer);
|
|
723
|
+
if (saveData)
|
|
724
|
+
yield this.setData(parsed);
|
|
725
|
+
return this.cachedData = this.engine.deepCopy(parsed);
|
|
726
|
+
} catch (err) {
|
|
727
|
+
console.warn("Error while parsing JSON data, resetting it to the default value.", err);
|
|
728
|
+
yield this.saveDefaultData();
|
|
729
|
+
return this.defaultData;
|
|
634
730
|
}
|
|
635
|
-
|
|
636
|
-
await this.migrateId(this.migrateIds);
|
|
637
|
-
this.migrateIds = [];
|
|
638
|
-
}
|
|
639
|
-
const storedData = await this.engine.getValue(`__ds-${this.id}-dat`, JSON.stringify(this.defaultData));
|
|
640
|
-
let storedFmtVer = Number(await this.engine.getValue(`__ds-${this.id}-ver`, NaN));
|
|
641
|
-
if (typeof storedData !== "string") {
|
|
642
|
-
await this.saveDefaultData();
|
|
643
|
-
return { ...this.defaultData };
|
|
644
|
-
}
|
|
645
|
-
const encodingFmt = String(await this.engine.getValue(`__ds-${this.id}-enf`, null));
|
|
646
|
-
const isEncoded = encodingFmt !== "null" && encodingFmt !== "false";
|
|
647
|
-
let saveData = false;
|
|
648
|
-
if (isNaN(storedFmtVer)) {
|
|
649
|
-
await this.engine.setValue(`__ds-${this.id}-ver`, storedFmtVer = this.formatVersion);
|
|
650
|
-
saveData = true;
|
|
651
|
-
}
|
|
652
|
-
let parsed = await this.engine.deserializeData(storedData, isEncoded);
|
|
653
|
-
if (storedFmtVer < this.formatVersion && this.migrations)
|
|
654
|
-
parsed = await this.runMigrations(parsed, storedFmtVer);
|
|
655
|
-
if (saveData)
|
|
656
|
-
await this.setData(parsed);
|
|
657
|
-
return this.cachedData = this.engine.deepCopy(parsed);
|
|
658
|
-
} catch (err) {
|
|
659
|
-
console.warn("Error while parsing JSON data, resetting it to the default value.", err);
|
|
660
|
-
await this.saveDefaultData();
|
|
661
|
-
return this.defaultData;
|
|
662
|
-
}
|
|
731
|
+
});
|
|
663
732
|
}
|
|
664
733
|
/**
|
|
665
734
|
* Returns a copy of the data from the in-memory cache.
|
|
@@ -671,37 +740,41 @@ var DataStore = class {
|
|
|
671
740
|
/** Saves the data synchronously to the in-memory cache and asynchronously to the persistent storage */
|
|
672
741
|
setData(data) {
|
|
673
742
|
this.cachedData = data;
|
|
674
|
-
return new Promise(
|
|
675
|
-
|
|
676
|
-
this.engine.setValue(`__ds-${this.id}-dat`,
|
|
743
|
+
return new Promise((resolve) => __async(this, null, function* () {
|
|
744
|
+
yield Promise.allSettled([
|
|
745
|
+
this.engine.setValue(`__ds-${this.id}-dat`, yield this.engine.serializeData(data, this.encodingEnabled())),
|
|
677
746
|
this.engine.setValue(`__ds-${this.id}-ver`, this.formatVersion),
|
|
678
747
|
this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat)
|
|
679
748
|
]);
|
|
680
749
|
resolve();
|
|
681
|
-
});
|
|
750
|
+
}));
|
|
682
751
|
}
|
|
683
752
|
/** Saves the default data passed in the constructor synchronously to the in-memory cache and asynchronously to persistent storage */
|
|
684
|
-
|
|
685
|
-
this
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
753
|
+
saveDefaultData() {
|
|
754
|
+
return __async(this, null, function* () {
|
|
755
|
+
this.cachedData = this.defaultData;
|
|
756
|
+
yield Promise.allSettled([
|
|
757
|
+
this.engine.setValue(`__ds-${this.id}-dat`, yield this.engine.serializeData(this.defaultData, this.encodingEnabled())),
|
|
758
|
+
this.engine.setValue(`__ds-${this.id}-ver`, this.formatVersion),
|
|
759
|
+
this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat)
|
|
760
|
+
]);
|
|
761
|
+
});
|
|
691
762
|
}
|
|
692
763
|
/**
|
|
693
764
|
* Call this method to clear all persistently stored data associated with this DataStore instance, including the storage container (if supported by the DataStoreEngine).
|
|
694
765
|
* The in-memory cache will be left untouched, so you may still access the data with {@linkcode getData()}
|
|
695
766
|
* Calling {@linkcode loadData()} or {@linkcode setData()} after this method was called will recreate persistent storage with the cached or default data.
|
|
696
767
|
*/
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
768
|
+
deleteData() {
|
|
769
|
+
return __async(this, null, function* () {
|
|
770
|
+
var _a, _b;
|
|
771
|
+
yield Promise.allSettled([
|
|
772
|
+
this.engine.deleteValue(`__ds-${this.id}-dat`),
|
|
773
|
+
this.engine.deleteValue(`__ds-${this.id}-ver`),
|
|
774
|
+
this.engine.deleteValue(`__ds-${this.id}-enf`)
|
|
775
|
+
]);
|
|
776
|
+
yield (_b = (_a = this.engine).deleteStorage) == null ? void 0 : _b.call(_a);
|
|
777
|
+
});
|
|
705
778
|
}
|
|
706
779
|
/** Returns whether encoding and decoding are enabled for this DataStore instance */
|
|
707
780
|
encodingEnabled() {
|
|
@@ -715,69 +788,73 @@ var DataStore = class {
|
|
|
715
788
|
*
|
|
716
789
|
* 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.
|
|
717
790
|
*/
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
const
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
791
|
+
runMigrations(oldData, oldFmtVer, resetOnError = true) {
|
|
792
|
+
return __async(this, null, function* () {
|
|
793
|
+
if (!this.migrations)
|
|
794
|
+
return oldData;
|
|
795
|
+
let newData = oldData;
|
|
796
|
+
const sortedMigrations = Object.entries(this.migrations).sort(([a], [b]) => Number(a) - Number(b));
|
|
797
|
+
let lastFmtVer = oldFmtVer;
|
|
798
|
+
for (const [fmtVer, migrationFunc] of sortedMigrations) {
|
|
799
|
+
const ver = Number(fmtVer);
|
|
800
|
+
if (oldFmtVer < this.formatVersion && oldFmtVer < ver) {
|
|
801
|
+
try {
|
|
802
|
+
const migRes = migrationFunc(newData);
|
|
803
|
+
newData = migRes instanceof Promise ? yield migRes : migRes;
|
|
804
|
+
lastFmtVer = oldFmtVer = ver;
|
|
805
|
+
} catch (err) {
|
|
806
|
+
if (!resetOnError)
|
|
807
|
+
throw new MigrationError(`Error while running migration function for format version '${fmtVer}'`, { cause: err });
|
|
808
|
+
yield this.saveDefaultData();
|
|
809
|
+
return this.getData();
|
|
810
|
+
}
|
|
736
811
|
}
|
|
737
812
|
}
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
813
|
+
yield Promise.allSettled([
|
|
814
|
+
this.engine.setValue(`__ds-${this.id}-dat`, yield this.engine.serializeData(newData)),
|
|
815
|
+
this.engine.setValue(`__ds-${this.id}-ver`, lastFmtVer),
|
|
816
|
+
this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat)
|
|
817
|
+
]);
|
|
818
|
+
return this.cachedData = __spreadValues({}, newData);
|
|
819
|
+
});
|
|
745
820
|
}
|
|
746
821
|
/**
|
|
747
822
|
* Tries to migrate the currently saved persistent data from one or more old IDs to the ID set in the constructor.
|
|
748
823
|
* 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.
|
|
749
824
|
*/
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
const [
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
825
|
+
migrateId(oldIds) {
|
|
826
|
+
return __async(this, null, function* () {
|
|
827
|
+
const ids = Array.isArray(oldIds) ? oldIds : [oldIds];
|
|
828
|
+
yield Promise.all(ids.map((id) => __async(this, null, function* () {
|
|
829
|
+
const [data, fmtVer, isEncoded] = yield (() => __async(this, null, function* () {
|
|
830
|
+
const [d, f, e] = yield Promise.all([
|
|
831
|
+
this.engine.getValue(`__ds-${id}-dat`, JSON.stringify(this.defaultData)),
|
|
832
|
+
this.engine.getValue(`__ds-${id}-ver`, NaN),
|
|
833
|
+
this.engine.getValue(`__ds-${id}-enf`, null)
|
|
834
|
+
]);
|
|
835
|
+
return [d, Number(f), Boolean(e) && String(e) !== "null"];
|
|
836
|
+
}))();
|
|
837
|
+
if (data === void 0 || isNaN(fmtVer))
|
|
838
|
+
return;
|
|
839
|
+
const parsed = yield this.engine.deserializeData(data, isEncoded);
|
|
840
|
+
yield Promise.allSettled([
|
|
841
|
+
this.engine.setValue(`__ds-${this.id}-dat`, yield this.engine.serializeData(parsed)),
|
|
842
|
+
this.engine.setValue(`__ds-${this.id}-ver`, fmtVer),
|
|
843
|
+
this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat),
|
|
844
|
+
this.engine.deleteValue(`__ds-${id}-dat`),
|
|
845
|
+
this.engine.deleteValue(`__ds-${id}-ver`),
|
|
846
|
+
this.engine.deleteValue(`__ds-${id}-enf`)
|
|
758
847
|
]);
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
if (data === void 0 || isNaN(fmtVer))
|
|
762
|
-
return;
|
|
763
|
-
const parsed = await this.engine.deserializeData(data, isEncoded);
|
|
764
|
-
await Promise.allSettled([
|
|
765
|
-
this.engine.setValue(`__ds-${this.id}-dat`, await this.engine.serializeData(parsed)),
|
|
766
|
-
this.engine.setValue(`__ds-${this.id}-ver`, fmtVer),
|
|
767
|
-
this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat),
|
|
768
|
-
this.engine.deleteValue(`__ds-${id}-dat`),
|
|
769
|
-
this.engine.deleteValue(`__ds-${id}-ver`),
|
|
770
|
-
this.engine.deleteValue(`__ds-${id}-enf`)
|
|
771
|
-
]);
|
|
772
|
-
}));
|
|
848
|
+
})));
|
|
849
|
+
});
|
|
773
850
|
}
|
|
774
851
|
};
|
|
775
852
|
|
|
776
853
|
// lib/DataStoreEngine.ts
|
|
777
854
|
var DataStoreEngine = class {
|
|
778
|
-
dataStoreOptions;
|
|
779
855
|
// setDataStoreOptions() is called from inside the DataStore constructor to set this value
|
|
780
856
|
constructor(options) {
|
|
857
|
+
__publicField(this, "dataStoreOptions");
|
|
781
858
|
if (options)
|
|
782
859
|
this.dataStoreOptions = options;
|
|
783
860
|
}
|
|
@@ -787,25 +864,29 @@ var DataStoreEngine = class {
|
|
|
787
864
|
}
|
|
788
865
|
//#region serialization api
|
|
789
866
|
/** Serializes the given object to a string, optionally encoded with `options.encodeData` if {@linkcode useEncoding} is set to true */
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
867
|
+
serializeData(data, useEncoding) {
|
|
868
|
+
return __async(this, null, function* () {
|
|
869
|
+
var _a, _b, _c, _d, _e;
|
|
870
|
+
this.ensureDataStoreOptions();
|
|
871
|
+
const stringData = JSON.stringify(data);
|
|
872
|
+
if (!useEncoding || !((_a = this.dataStoreOptions) == null ? void 0 : _a.encodeData) || !((_b = this.dataStoreOptions) == null ? void 0 : _b.decodeData))
|
|
873
|
+
return stringData;
|
|
874
|
+
const encRes = (_e = (_d = (_c = this.dataStoreOptions) == null ? void 0 : _c.encodeData) == null ? void 0 : _d[1]) == null ? void 0 : _e.call(_d, stringData);
|
|
875
|
+
if (encRes instanceof Promise)
|
|
876
|
+
return yield encRes;
|
|
877
|
+
return encRes;
|
|
878
|
+
});
|
|
800
879
|
}
|
|
801
880
|
/** Deserializes the given string to a JSON object, optionally decoded with `options.decodeData` if {@linkcode useEncoding} is set to true */
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
decRes
|
|
808
|
-
|
|
881
|
+
deserializeData(data, useEncoding) {
|
|
882
|
+
return __async(this, null, function* () {
|
|
883
|
+
var _a, _b, _c;
|
|
884
|
+
this.ensureDataStoreOptions();
|
|
885
|
+
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;
|
|
886
|
+
if (decRes instanceof Promise)
|
|
887
|
+
decRes = yield decRes;
|
|
888
|
+
return JSON.parse(decRes != null ? decRes : data);
|
|
889
|
+
});
|
|
809
890
|
}
|
|
810
891
|
//#region misc api
|
|
811
892
|
/** Throws an error if the DataStoreOptions are not set or invalid */
|
|
@@ -823,13 +904,12 @@ var DataStoreEngine = class {
|
|
|
823
904
|
try {
|
|
824
905
|
if ("structuredClone" in globalThis)
|
|
825
906
|
return structuredClone(obj);
|
|
826
|
-
} catch {
|
|
907
|
+
} catch (e) {
|
|
827
908
|
}
|
|
828
909
|
return JSON.parse(JSON.stringify(obj));
|
|
829
910
|
}
|
|
830
911
|
};
|
|
831
912
|
var BrowserStorageEngine = class extends DataStoreEngine {
|
|
832
|
-
options;
|
|
833
913
|
/**
|
|
834
914
|
* Creates an instance of `BrowserStorageEngine`.
|
|
835
915
|
*
|
|
@@ -838,34 +918,40 @@ var BrowserStorageEngine = class extends DataStoreEngine {
|
|
|
838
918
|
*/
|
|
839
919
|
constructor(options) {
|
|
840
920
|
super(options == null ? void 0 : options.dataStoreOptions);
|
|
841
|
-
this
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
};
|
|
921
|
+
__publicField(this, "options");
|
|
922
|
+
this.options = __spreadValues({
|
|
923
|
+
type: "localStorage"
|
|
924
|
+
}, options);
|
|
845
925
|
}
|
|
846
926
|
//#region storage api
|
|
847
927
|
/** Fetches a value from persistent storage */
|
|
848
|
-
|
|
849
|
-
return (this
|
|
928
|
+
getValue(name, defaultValue) {
|
|
929
|
+
return __async(this, null, function* () {
|
|
930
|
+
const val = this.options.type === "localStorage" ? globalThis.localStorage.getItem(name) : globalThis.sessionStorage.getItem(name);
|
|
931
|
+
return typeof val === "undefined" ? defaultValue : val;
|
|
932
|
+
});
|
|
850
933
|
}
|
|
851
934
|
/** Sets a value in persistent storage */
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
935
|
+
setValue(name, value) {
|
|
936
|
+
return __async(this, null, function* () {
|
|
937
|
+
if (this.options.type === "localStorage")
|
|
938
|
+
globalThis.localStorage.setItem(name, String(value));
|
|
939
|
+
else
|
|
940
|
+
globalThis.sessionStorage.setItem(name, String(value));
|
|
941
|
+
});
|
|
857
942
|
}
|
|
858
943
|
/** Deletes a value from persistent storage */
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
944
|
+
deleteValue(name) {
|
|
945
|
+
return __async(this, null, function* () {
|
|
946
|
+
if (this.options.type === "localStorage")
|
|
947
|
+
globalThis.localStorage.removeItem(name);
|
|
948
|
+
else
|
|
949
|
+
globalThis.sessionStorage.removeItem(name);
|
|
950
|
+
});
|
|
864
951
|
}
|
|
865
952
|
};
|
|
866
953
|
var fs;
|
|
867
954
|
var FileStorageEngine = class extends DataStoreEngine {
|
|
868
|
-
options;
|
|
869
955
|
/**
|
|
870
956
|
* Creates an instance of `FileStorageEngine`.
|
|
871
957
|
*
|
|
@@ -874,107 +960,127 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
874
960
|
*/
|
|
875
961
|
constructor(options) {
|
|
876
962
|
super(options == null ? void 0 : options.dataStoreOptions);
|
|
877
|
-
this
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
963
|
+
__publicField(this, "options");
|
|
964
|
+
__publicField(this, "fileAccessQueue", Promise.resolve());
|
|
965
|
+
this.options = __spreadValues({
|
|
966
|
+
filePath: (id) => `.ds-${id}`
|
|
967
|
+
}, options);
|
|
881
968
|
}
|
|
882
969
|
//#region json file
|
|
883
970
|
/** Reads the file contents */
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
971
|
+
readFile() {
|
|
972
|
+
return __async(this, null, function* () {
|
|
973
|
+
var _a, _b, _c, _d, _e;
|
|
974
|
+
this.ensureDataStoreOptions();
|
|
975
|
+
try {
|
|
976
|
+
if (!fs)
|
|
977
|
+
fs = (_a = yield import("fs/promises")) == null ? void 0 : _a.default;
|
|
978
|
+
if (!fs)
|
|
979
|
+
throw new DatedError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new Error("'node:fs/promises' module not available") });
|
|
980
|
+
const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
|
|
981
|
+
const data = yield fs.readFile(path, "utf-8");
|
|
982
|
+
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;
|
|
983
|
+
} catch (e) {
|
|
984
|
+
return void 0;
|
|
985
|
+
}
|
|
986
|
+
});
|
|
898
987
|
}
|
|
899
988
|
/** Overwrites the file contents */
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
989
|
+
writeFile(data) {
|
|
990
|
+
return __async(this, null, function* () {
|
|
991
|
+
var _a, _b, _c, _d, _e;
|
|
992
|
+
this.ensureDataStoreOptions();
|
|
993
|
+
try {
|
|
994
|
+
if (!fs)
|
|
995
|
+
fs = (_a = yield import("fs/promises")) == null ? void 0 : _a.default;
|
|
996
|
+
if (!fs)
|
|
997
|
+
throw new DatedError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new Error("'node:fs/promises' module not available") });
|
|
998
|
+
const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
|
|
999
|
+
yield fs.mkdir(path.slice(0, path.lastIndexOf(path.includes("/") ? "/" : "\\")), { recursive: true });
|
|
1000
|
+
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");
|
|
1001
|
+
} catch (err) {
|
|
1002
|
+
console.error("Error writing file:", err);
|
|
1003
|
+
}
|
|
1004
|
+
});
|
|
914
1005
|
}
|
|
915
1006
|
//#region storage api
|
|
916
1007
|
/** Fetches a value from persistent storage */
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
1008
|
+
getValue(name, defaultValue) {
|
|
1009
|
+
return __async(this, null, function* () {
|
|
1010
|
+
const data = yield this.readFile();
|
|
1011
|
+
if (!data)
|
|
1012
|
+
return defaultValue;
|
|
1013
|
+
const value = data == null ? void 0 : data[name];
|
|
1014
|
+
if (typeof value === "undefined")
|
|
1015
|
+
return defaultValue;
|
|
1016
|
+
if (typeof value === "string")
|
|
1017
|
+
return value;
|
|
925
1018
|
return value;
|
|
926
|
-
|
|
1019
|
+
});
|
|
927
1020
|
}
|
|
928
1021
|
/** Sets a value in persistent storage */
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
1022
|
+
setValue(name, value) {
|
|
1023
|
+
return __async(this, null, function* () {
|
|
1024
|
+
this.fileAccessQueue = this.fileAccessQueue.then(() => __async(this, null, function* () {
|
|
1025
|
+
let data = yield this.readFile();
|
|
1026
|
+
if (!data)
|
|
1027
|
+
data = {};
|
|
1028
|
+
data[name] = value;
|
|
1029
|
+
yield this.writeFile(data);
|
|
1030
|
+
}));
|
|
1031
|
+
yield this.fileAccessQueue;
|
|
1032
|
+
});
|
|
935
1033
|
}
|
|
936
1034
|
/** Deletes a value from persistent storage */
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
1035
|
+
deleteValue(name) {
|
|
1036
|
+
return __async(this, null, function* () {
|
|
1037
|
+
this.fileAccessQueue = this.fileAccessQueue.then(() => __async(this, null, function* () {
|
|
1038
|
+
const data = yield this.readFile();
|
|
1039
|
+
if (!data)
|
|
1040
|
+
return;
|
|
1041
|
+
delete data[name];
|
|
1042
|
+
yield this.writeFile(data);
|
|
1043
|
+
}));
|
|
1044
|
+
yield this.fileAccessQueue;
|
|
1045
|
+
});
|
|
943
1046
|
}
|
|
944
1047
|
/** Deletes the file that contains the data of this DataStore. */
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
1048
|
+
deleteStorage() {
|
|
1049
|
+
return __async(this, null, function* () {
|
|
1050
|
+
var _a;
|
|
1051
|
+
this.ensureDataStoreOptions();
|
|
1052
|
+
try {
|
|
1053
|
+
if (!fs)
|
|
1054
|
+
fs = (_a = yield import("fs/promises")) == null ? void 0 : _a.default;
|
|
1055
|
+
if (!fs)
|
|
1056
|
+
throw new DatedError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new Error("'node:fs/promises' module not available") });
|
|
1057
|
+
const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
|
|
1058
|
+
yield fs.unlink(path);
|
|
1059
|
+
} catch (err) {
|
|
1060
|
+
console.error("Error deleting file:", err);
|
|
1061
|
+
}
|
|
1062
|
+
});
|
|
958
1063
|
}
|
|
959
1064
|
};
|
|
960
1065
|
|
|
961
1066
|
// lib/DataStoreSerializer.ts
|
|
962
1067
|
var DataStoreSerializer = class _DataStoreSerializer {
|
|
963
|
-
stores;
|
|
964
|
-
options;
|
|
965
1068
|
constructor(stores, options = {}) {
|
|
1069
|
+
__publicField(this, "stores");
|
|
1070
|
+
__publicField(this, "options");
|
|
966
1071
|
if (!crypto || !crypto.subtle)
|
|
967
1072
|
throw new Error("DataStoreSerializer has to run in a secure context (HTTPS) or in another environment that implements the subtleCrypto API!");
|
|
968
1073
|
this.stores = stores;
|
|
969
|
-
this.options = {
|
|
1074
|
+
this.options = __spreadValues({
|
|
970
1075
|
addChecksum: true,
|
|
971
|
-
ensureIntegrity: true
|
|
972
|
-
|
|
973
|
-
};
|
|
1076
|
+
ensureIntegrity: true
|
|
1077
|
+
}, options);
|
|
974
1078
|
}
|
|
975
1079
|
/** Calculates the checksum of a string */
|
|
976
|
-
|
|
977
|
-
return
|
|
1080
|
+
calcChecksum(input) {
|
|
1081
|
+
return __async(this, null, function* () {
|
|
1082
|
+
return computeHash(input, "SHA-256");
|
|
1083
|
+
});
|
|
978
1084
|
}
|
|
979
1085
|
/**
|
|
980
1086
|
* Serializes only a subset of the data stores into a string.
|
|
@@ -982,62 +1088,70 @@ var DataStoreSerializer = class _DataStoreSerializer {
|
|
|
982
1088
|
* @param useEncoding Whether to encode the data using each DataStore's `encodeData()` method
|
|
983
1089
|
* @param stringified Whether to return the result as a string or as an array of `SerializedDataStore` objects
|
|
984
1090
|
*/
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
const
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1091
|
+
serializePartial(stores, useEncoding = true, stringified = true) {
|
|
1092
|
+
return __async(this, null, function* () {
|
|
1093
|
+
var _a;
|
|
1094
|
+
const serData = [];
|
|
1095
|
+
for (const storeInst of this.stores.filter((s) => typeof stores === "function" ? stores(s.id) : stores.includes(s.id))) {
|
|
1096
|
+
const encoded = Boolean(useEncoding && storeInst.encodingEnabled() && ((_a = storeInst.encodeData) == null ? void 0 : _a[1]));
|
|
1097
|
+
const data = encoded ? yield storeInst.encodeData[1](JSON.stringify(storeInst.getData())) : JSON.stringify(storeInst.getData());
|
|
1098
|
+
serData.push({
|
|
1099
|
+
id: storeInst.id,
|
|
1100
|
+
data,
|
|
1101
|
+
formatVersion: storeInst.formatVersion,
|
|
1102
|
+
encoded,
|
|
1103
|
+
checksum: this.options.addChecksum ? yield this.calcChecksum(data) : void 0
|
|
1104
|
+
});
|
|
1105
|
+
}
|
|
1106
|
+
return stringified ? JSON.stringify(serData) : serData;
|
|
1107
|
+
});
|
|
1000
1108
|
}
|
|
1001
1109
|
/**
|
|
1002
1110
|
* Serializes the data stores into a string.
|
|
1003
1111
|
* @param useEncoding Whether to encode the data using each DataStore's `encodeData()` method
|
|
1004
1112
|
* @param stringified Whether to return the result as a string or as an array of `SerializedDataStore` objects
|
|
1005
1113
|
*/
|
|
1006
|
-
|
|
1007
|
-
return
|
|
1114
|
+
serialize(useEncoding = true, stringified = true) {
|
|
1115
|
+
return __async(this, null, function* () {
|
|
1116
|
+
return this.serializePartial(this.stores.map((s) => s.id), useEncoding, stringified);
|
|
1117
|
+
});
|
|
1008
1118
|
}
|
|
1009
1119
|
/**
|
|
1010
1120
|
* Deserializes the data exported via {@linkcode serialize()} and imports only a subset into the DataStore instances.
|
|
1011
1121
|
* Also triggers the migration process if the data format has changed.
|
|
1012
1122
|
*/
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
const
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1123
|
+
deserializePartial(stores, data) {
|
|
1124
|
+
return __async(this, null, function* () {
|
|
1125
|
+
const deserStores = typeof data === "string" ? JSON.parse(data) : data;
|
|
1126
|
+
if (!Array.isArray(deserStores) || !deserStores.every(_DataStoreSerializer.isSerializedDataStoreObj))
|
|
1127
|
+
throw new TypeError("Invalid serialized data format! Expected an array of SerializedDataStore objects.");
|
|
1128
|
+
for (const storeData of deserStores.filter((s) => typeof stores === "function" ? stores(s.id) : stores.includes(s.id))) {
|
|
1129
|
+
const storeInst = this.stores.find((s) => s.id === storeData.id);
|
|
1130
|
+
if (!storeInst)
|
|
1131
|
+
throw new Error(`DataStore instance with ID "${storeData.id}" not found! Make sure to provide it in the DataStoreSerializer constructor.`);
|
|
1132
|
+
if (this.options.ensureIntegrity && typeof storeData.checksum === "string") {
|
|
1133
|
+
const checksum = yield this.calcChecksum(storeData.data);
|
|
1134
|
+
if (checksum !== storeData.checksum)
|
|
1135
|
+
throw new ChecksumMismatchError(`Checksum mismatch for DataStore with ID "${storeData.id}"!
|
|
1025
1136
|
Expected: ${storeData.checksum}
|
|
1026
1137
|
Has: ${checksum}`);
|
|
1138
|
+
}
|
|
1139
|
+
const decodedData = storeData.encoded && storeInst.encodingEnabled() ? yield storeInst.decodeData[1](storeData.data) : storeData.data;
|
|
1140
|
+
if (storeData.formatVersion && !isNaN(Number(storeData.formatVersion)) && Number(storeData.formatVersion) < storeInst.formatVersion)
|
|
1141
|
+
yield storeInst.runMigrations(JSON.parse(decodedData), Number(storeData.formatVersion), false);
|
|
1142
|
+
else
|
|
1143
|
+
yield storeInst.setData(JSON.parse(decodedData));
|
|
1027
1144
|
}
|
|
1028
|
-
|
|
1029
|
-
if (storeData.formatVersion && !isNaN(Number(storeData.formatVersion)) && Number(storeData.formatVersion) < storeInst.formatVersion)
|
|
1030
|
-
await storeInst.runMigrations(JSON.parse(decodedData), Number(storeData.formatVersion), false);
|
|
1031
|
-
else
|
|
1032
|
-
await storeInst.setData(JSON.parse(decodedData));
|
|
1033
|
-
}
|
|
1145
|
+
});
|
|
1034
1146
|
}
|
|
1035
1147
|
/**
|
|
1036
1148
|
* Deserializes the data exported via {@linkcode serialize()} and imports the data into all matching DataStore instances.
|
|
1037
1149
|
* Also triggers the migration process if the data format has changed.
|
|
1038
1150
|
*/
|
|
1039
|
-
|
|
1040
|
-
return
|
|
1151
|
+
deserialize(data) {
|
|
1152
|
+
return __async(this, null, function* () {
|
|
1153
|
+
return this.deserializePartial(this.stores.map((s) => s.id), data);
|
|
1154
|
+
});
|
|
1041
1155
|
}
|
|
1042
1156
|
/**
|
|
1043
1157
|
* Loads the persistent data of the DataStore instances into the in-memory cache.
|
|
@@ -1045,32 +1159,40 @@ Has: ${checksum}`);
|
|
|
1045
1159
|
* @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
|
|
1046
1160
|
* @returns Returns a PromiseSettledResult array with the results of each DataStore instance in the format `{ id: string, data: object }`
|
|
1047
1161
|
*/
|
|
1048
|
-
|
|
1049
|
-
return
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1162
|
+
loadStoresData(stores) {
|
|
1163
|
+
return __async(this, null, function* () {
|
|
1164
|
+
return Promise.allSettled(
|
|
1165
|
+
this.getStoresFiltered(stores).map((store) => __async(this, null, function* () {
|
|
1166
|
+
return {
|
|
1167
|
+
id: store.id,
|
|
1168
|
+
data: yield store.loadData()
|
|
1169
|
+
};
|
|
1170
|
+
}))
|
|
1171
|
+
);
|
|
1172
|
+
});
|
|
1055
1173
|
}
|
|
1056
1174
|
/**
|
|
1057
1175
|
* Resets the persistent and in-memory data of the DataStore instances to their default values.
|
|
1058
1176
|
* @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
|
|
1059
1177
|
*/
|
|
1060
|
-
|
|
1061
|
-
return
|
|
1062
|
-
|
|
1063
|
-
|
|
1178
|
+
resetStoresData(stores) {
|
|
1179
|
+
return __async(this, null, function* () {
|
|
1180
|
+
return Promise.allSettled(
|
|
1181
|
+
this.getStoresFiltered(stores).map((store) => store.saveDefaultData())
|
|
1182
|
+
);
|
|
1183
|
+
});
|
|
1064
1184
|
}
|
|
1065
1185
|
/**
|
|
1066
1186
|
* Deletes the persistent data of the DataStore instances.
|
|
1067
1187
|
* Leaves the in-memory data untouched.
|
|
1068
1188
|
* @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
|
|
1069
1189
|
*/
|
|
1070
|
-
|
|
1071
|
-
return
|
|
1072
|
-
|
|
1073
|
-
|
|
1190
|
+
deleteStoresData(stores) {
|
|
1191
|
+
return __async(this, null, function* () {
|
|
1192
|
+
return Promise.allSettled(
|
|
1193
|
+
this.getStoresFiltered(stores).map((store) => store.deleteData())
|
|
1194
|
+
);
|
|
1195
|
+
});
|
|
1074
1196
|
}
|
|
1075
1197
|
/** Checks if a given value is an array of SerializedDataStore objects */
|
|
1076
1198
|
static isSerializedDataStoreObjArray(obj) {
|
|
@@ -1095,26 +1217,26 @@ var createNanoEvents = () => ({
|
|
|
1095
1217
|
},
|
|
1096
1218
|
events: {},
|
|
1097
1219
|
on(event, cb) {
|
|
1220
|
+
var _a;
|
|
1098
1221
|
;
|
|
1099
|
-
(this.events[event]
|
|
1222
|
+
((_a = this.events)[event] || (_a[event] = [])).push(cb);
|
|
1100
1223
|
return () => {
|
|
1101
|
-
var
|
|
1102
|
-
this.events[event] = (
|
|
1224
|
+
var _a2;
|
|
1225
|
+
this.events[event] = (_a2 = this.events[event]) == null ? void 0 : _a2.filter((i) => cb !== i);
|
|
1103
1226
|
};
|
|
1104
1227
|
}
|
|
1105
1228
|
});
|
|
1106
1229
|
|
|
1107
1230
|
// lib/NanoEmitter.ts
|
|
1108
1231
|
var NanoEmitter = class {
|
|
1109
|
-
events = createNanoEvents();
|
|
1110
|
-
eventUnsubscribes = [];
|
|
1111
|
-
emitterOptions;
|
|
1112
1232
|
/** Creates a new instance of NanoEmitter - a lightweight event emitter with helper methods and a strongly typed event map */
|
|
1113
1233
|
constructor(options = {}) {
|
|
1114
|
-
this
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1234
|
+
__publicField(this, "events", createNanoEvents());
|
|
1235
|
+
__publicField(this, "eventUnsubscribes", []);
|
|
1236
|
+
__publicField(this, "emitterOptions");
|
|
1237
|
+
this.emitterOptions = __spreadValues({
|
|
1238
|
+
publicEmit: false
|
|
1239
|
+
}, options);
|
|
1118
1240
|
}
|
|
1119
1241
|
//#region on
|
|
1120
1242
|
/**
|
|
@@ -1205,12 +1327,11 @@ var NanoEmitter = class {
|
|
|
1205
1327
|
this.eventUnsubscribes = this.eventUnsubscribes.filter((u) => !allUnsubs.includes(u));
|
|
1206
1328
|
};
|
|
1207
1329
|
for (const opts of Array.isArray(options) ? options : [options]) {
|
|
1208
|
-
const optsWithDefaults = {
|
|
1330
|
+
const optsWithDefaults = __spreadValues({
|
|
1209
1331
|
allOf: [],
|
|
1210
1332
|
oneOf: [],
|
|
1211
|
-
once: false
|
|
1212
|
-
|
|
1213
|
-
};
|
|
1333
|
+
once: false
|
|
1334
|
+
}, opts);
|
|
1214
1335
|
const {
|
|
1215
1336
|
oneOf,
|
|
1216
1337
|
allOf,
|
|
@@ -1296,13 +1417,13 @@ var Debouncer = class extends NanoEmitter {
|
|
|
1296
1417
|
super();
|
|
1297
1418
|
this.timeout = timeout;
|
|
1298
1419
|
this.type = type;
|
|
1420
|
+
/** All registered listener functions and the time they were attached */
|
|
1421
|
+
__publicField(this, "listeners", []);
|
|
1422
|
+
/** The currently active timeout */
|
|
1423
|
+
__publicField(this, "activeTimeout");
|
|
1424
|
+
/** The latest queued call */
|
|
1425
|
+
__publicField(this, "queuedCall");
|
|
1299
1426
|
}
|
|
1300
|
-
/** All registered listener functions and the time they were attached */
|
|
1301
|
-
listeners = [];
|
|
1302
|
-
/** The currently active timeout */
|
|
1303
|
-
activeTimeout;
|
|
1304
|
-
/** The latest queued call */
|
|
1305
|
-
queuedCall;
|
|
1306
1427
|
//#region listeners
|
|
1307
1428
|
/** Adds a listener function that will be called on timeout */
|
|
1308
1429
|
addListener(fn) {
|
|
@@ -1389,6 +1510,8 @@ function debounce(fn, timeout = 200, type = "immediate") {
|
|
|
1389
1510
|
return func;
|
|
1390
1511
|
}
|
|
1391
1512
|
|
|
1513
|
+
if(__exports != exports)module.exports = exports;return module.exports}));
|
|
1514
|
+
|
|
1392
1515
|
|
|
1393
1516
|
|
|
1394
1517
|
if (typeof module.exports == "object" && typeof exports == "object") {
|