@sv443-network/coreutils 3.0.0 → 3.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 +14 -0
- package/dist/CoreUtils.cjs +1 -2
- package/dist/CoreUtils.min.cjs +1 -1
- package/dist/CoreUtils.min.mjs +1 -1
- package/dist/CoreUtils.min.umd.js +1 -1
- package/dist/CoreUtils.mjs +1 -2
- package/dist/CoreUtils.umd.js +423 -539
- package/dist/lib/DataStore.d.ts +9 -5
- package/dist/lib/DataStoreEngine.d.ts +5 -5
- package/dist/lib/DataStoreSerializer.d.ts +4 -4
- package/package.json +5 -2
package/dist/CoreUtils.umd.js
CHANGED
|
@@ -16,41 +16,13 @@
|
|
|
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};
|
|
20
19
|
"use strict";
|
|
21
20
|
var __create = Object.create;
|
|
22
21
|
var __defProp = Object.defineProperty;
|
|
23
22
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
24
23
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
25
|
-
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
26
24
|
var __getProtoOf = Object.getPrototypeOf;
|
|
27
25
|
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
|
-
};
|
|
54
26
|
var __export = (target, all) => {
|
|
55
27
|
for (var name in all)
|
|
56
28
|
__defProp(target, name, { get: all[name], enumerable: true });
|
|
@@ -72,27 +44,6 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
72
44
|
mod
|
|
73
45
|
));
|
|
74
46
|
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
|
-
};
|
|
96
47
|
|
|
97
48
|
// lib/index.ts
|
|
98
49
|
var lib_exports = {};
|
|
@@ -243,7 +194,7 @@ function randRange(...args) {
|
|
|
243
194
|
return Math.floor(Math.random() * (max - min + 1)) + min;
|
|
244
195
|
}
|
|
245
196
|
function roundFixed(num, fractionDigits) {
|
|
246
|
-
const scale =
|
|
197
|
+
const scale = 10 ** fractionDigits;
|
|
247
198
|
return Math.round(num * scale) / scale;
|
|
248
199
|
}
|
|
249
200
|
function valsWithin(a, b, dec = 1, withinRange = 0.5) {
|
|
@@ -307,7 +258,7 @@ function darkenColor(color, percent, upperCase = false) {
|
|
|
307
258
|
if (isHexCol)
|
|
308
259
|
return rgbToHex(r, g, b, a, color.startsWith("#"), upperCase);
|
|
309
260
|
else if (color.startsWith("rgba"))
|
|
310
|
-
return `rgba(${r}, ${g}, ${b}, ${a
|
|
261
|
+
return `rgba(${r}, ${g}, ${b}, ${a ?? NaN})`;
|
|
311
262
|
else
|
|
312
263
|
return `rgb(${r}, ${g}, ${b})`;
|
|
313
264
|
}
|
|
@@ -341,43 +292,35 @@ function abtoa(buf) {
|
|
|
341
292
|
function atoab(str) {
|
|
342
293
|
return Uint8Array.from(atob(str), (c) => c.charCodeAt(0));
|
|
343
294
|
}
|
|
344
|
-
function compress(input, compressionFormat, outputType = "string") {
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
const uintArr = new Uint8Array(yield new Response(comp.readable).arrayBuffer());
|
|
353
|
-
return outputType === "arrayBuffer" ? uintArr : abtoa(uintArr);
|
|
354
|
-
});
|
|
295
|
+
async function compress(input, compressionFormat, outputType = "string") {
|
|
296
|
+
const byteArray = input instanceof Uint8Array ? input : new TextEncoder().encode((input == null ? void 0 : input.toString()) ?? String(input));
|
|
297
|
+
const comp = new CompressionStream(compressionFormat);
|
|
298
|
+
const writer = comp.writable.getWriter();
|
|
299
|
+
writer.write(byteArray);
|
|
300
|
+
writer.close();
|
|
301
|
+
const uintArr = new Uint8Array(await new Response(comp.readable).arrayBuffer());
|
|
302
|
+
return outputType === "arrayBuffer" ? uintArr : abtoa(uintArr);
|
|
355
303
|
}
|
|
356
|
-
function decompress(input, compressionFormat, outputType = "string") {
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
const uintArr = new Uint8Array(yield new Response(decomp.readable).arrayBuffer());
|
|
365
|
-
return outputType === "arrayBuffer" ? uintArr : new TextDecoder().decode(uintArr);
|
|
366
|
-
});
|
|
304
|
+
async function decompress(input, compressionFormat, outputType = "string") {
|
|
305
|
+
const byteArray = input instanceof Uint8Array ? input : atoab((input == null ? void 0 : input.toString()) ?? String(input));
|
|
306
|
+
const decomp = new DecompressionStream(compressionFormat);
|
|
307
|
+
const writer = decomp.writable.getWriter();
|
|
308
|
+
writer.write(byteArray);
|
|
309
|
+
writer.close();
|
|
310
|
+
const uintArr = new Uint8Array(await new Response(decomp.readable).arrayBuffer());
|
|
311
|
+
return outputType === "arrayBuffer" ? uintArr : new TextDecoder().decode(uintArr);
|
|
367
312
|
}
|
|
368
|
-
function computeHash(input, algorithm = "SHA-256") {
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
return hashHex;
|
|
380
|
-
});
|
|
313
|
+
async function computeHash(input, algorithm = "SHA-256") {
|
|
314
|
+
let data;
|
|
315
|
+
if (typeof input === "string") {
|
|
316
|
+
const encoder = new TextEncoder();
|
|
317
|
+
data = encoder.encode(input);
|
|
318
|
+
} else
|
|
319
|
+
data = input;
|
|
320
|
+
const hashBuffer = await crypto.subtle.digest(algorithm, data);
|
|
321
|
+
const hashArray = Array.from(new Uint8Array(hashBuffer));
|
|
322
|
+
const hashHex = hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
323
|
+
return hashHex;
|
|
381
324
|
}
|
|
382
325
|
function randomId(length = 16, radix = 16, enhancedEntropy = false, randomCase = true) {
|
|
383
326
|
if (length < 1)
|
|
@@ -406,9 +349,9 @@ function randomId(length = 16, radix = 16, enhancedEntropy = false, randomCase =
|
|
|
406
349
|
|
|
407
350
|
// lib/Errors.ts
|
|
408
351
|
var DatedError = class extends Error {
|
|
352
|
+
date;
|
|
409
353
|
constructor(message, options) {
|
|
410
354
|
super(message, options);
|
|
411
|
-
__publicField(this, "date");
|
|
412
355
|
this.name = this.constructor.name;
|
|
413
356
|
this.date = /* @__PURE__ */ new Date();
|
|
414
357
|
}
|
|
@@ -451,38 +394,34 @@ var NetworkError = class extends DatedError {
|
|
|
451
394
|
};
|
|
452
395
|
|
|
453
396
|
// lib/misc.ts
|
|
454
|
-
function consumeGen(valGen) {
|
|
455
|
-
return
|
|
456
|
-
return yield typeof valGen === "function" ? valGen() : valGen;
|
|
457
|
-
});
|
|
397
|
+
async function consumeGen(valGen) {
|
|
398
|
+
return await (typeof valGen === "function" ? valGen() : valGen);
|
|
458
399
|
}
|
|
459
|
-
function consumeStringGen(strGen) {
|
|
460
|
-
return
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
);
|
|
464
|
-
});
|
|
400
|
+
async function consumeStringGen(strGen) {
|
|
401
|
+
return typeof strGen === "string" ? strGen : String(
|
|
402
|
+
typeof strGen === "function" ? await strGen() : strGen
|
|
403
|
+
);
|
|
465
404
|
}
|
|
466
|
-
function fetchAdvanced(
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
}
|
|
485
|
-
}
|
|
405
|
+
async function fetchAdvanced(input, options = {}) {
|
|
406
|
+
const { timeout = 1e4, signal, ...restOpts } = options;
|
|
407
|
+
const ctl = new AbortController();
|
|
408
|
+
signal == null ? void 0 : signal.addEventListener("abort", () => ctl.abort());
|
|
409
|
+
let sigOpts = {}, id = void 0;
|
|
410
|
+
if (timeout >= 0) {
|
|
411
|
+
id = setTimeout(() => ctl.abort(), timeout);
|
|
412
|
+
sigOpts = { signal: ctl.signal };
|
|
413
|
+
}
|
|
414
|
+
try {
|
|
415
|
+
const res = await fetch(input, {
|
|
416
|
+
...restOpts,
|
|
417
|
+
...sigOpts
|
|
418
|
+
});
|
|
419
|
+
typeof id !== "undefined" && clearTimeout(id);
|
|
420
|
+
return res;
|
|
421
|
+
} catch (err) {
|
|
422
|
+
typeof id !== "undefined" && clearTimeout(id);
|
|
423
|
+
throw new NetworkError("Error while calling fetch", { cause: err });
|
|
424
|
+
}
|
|
486
425
|
}
|
|
487
426
|
function getListLength(listLike, zeroOnInvalid = true) {
|
|
488
427
|
return "length" in listLike ? listLike.length : "size" in listLike ? listLike.size : "count" in listLike ? listLike.count : zeroOnInvalid ? 0 : NaN;
|
|
@@ -497,7 +436,7 @@ function pauseFor(time, signal, rejectOnAbort = false) {
|
|
|
497
436
|
});
|
|
498
437
|
}
|
|
499
438
|
function pureObj(obj) {
|
|
500
|
-
return Object.assign(/* @__PURE__ */ Object.create(null), obj
|
|
439
|
+
return Object.assign(/* @__PURE__ */ Object.create(null), obj ?? {});
|
|
501
440
|
}
|
|
502
441
|
function setImmediateInterval(callback, interval, signal) {
|
|
503
442
|
let intervalId;
|
|
@@ -514,12 +453,12 @@ function setImmediateInterval(callback, interval, signal) {
|
|
|
514
453
|
function setImmediateTimeoutLoop(callback, interval, signal) {
|
|
515
454
|
let timeout;
|
|
516
455
|
const cleanup = () => clearTimeout(timeout);
|
|
517
|
-
const loop = () =>
|
|
456
|
+
const loop = async () => {
|
|
518
457
|
if (signal == null ? void 0 : signal.aborted)
|
|
519
458
|
return cleanup();
|
|
520
|
-
|
|
459
|
+
await callback();
|
|
521
460
|
timeout = setTimeout(loop, interval);
|
|
522
|
-
}
|
|
461
|
+
};
|
|
523
462
|
signal == null ? void 0 : signal.addEventListener("abort", cleanup);
|
|
524
463
|
loop();
|
|
525
464
|
}
|
|
@@ -536,13 +475,12 @@ function scheduleExit(code = 0, timeout = 0) {
|
|
|
536
475
|
setTimeout(exit, timeout);
|
|
537
476
|
}
|
|
538
477
|
function getCallStack(asArray, lines = Infinity) {
|
|
539
|
-
var _a;
|
|
540
478
|
if (typeof lines !== "number" || isNaN(lines) || lines < 0)
|
|
541
479
|
throw new TypeError("lines parameter must be a non-negative number");
|
|
542
480
|
try {
|
|
543
481
|
throw new Error("This is to capture a stack trace with CoreUtils.getCallStack(). (If you see this somewhere, you can safely ignore it.)");
|
|
544
482
|
} catch (err) {
|
|
545
|
-
const stack = (
|
|
483
|
+
const stack = (err.stack ?? "").split("\n").map((line) => line.trim()).slice(2, lines + 2);
|
|
546
484
|
return asArray !== false ? stack : stack.join("\n");
|
|
547
485
|
}
|
|
548
486
|
}
|
|
@@ -597,9 +535,9 @@ function createProgressBar(percentage, barLength, chars = defaultPbChars) {
|
|
|
597
535
|
}
|
|
598
536
|
function insertValues(input, ...values) {
|
|
599
537
|
return input.replace(/%\d/gm, (match) => {
|
|
600
|
-
var _a
|
|
538
|
+
var _a;
|
|
601
539
|
const argIndex = Number(match.substring(1)) - 1;
|
|
602
|
-
return (
|
|
540
|
+
return (_a = values[argIndex] ?? match) == null ? void 0 : _a.toString();
|
|
603
541
|
});
|
|
604
542
|
}
|
|
605
543
|
function joinArrayReadable(array, separators = ", ", lastSeparator = " and ") {
|
|
@@ -630,8 +568,7 @@ function secsToTimeStr(seconds) {
|
|
|
630
568
|
].join("");
|
|
631
569
|
}
|
|
632
570
|
function truncStr(input, length, endStr = "...") {
|
|
633
|
-
|
|
634
|
-
const str = (_a = input == null ? void 0 : input.toString()) != null ? _a : String(input);
|
|
571
|
+
const str = (input == null ? void 0 : input.toString()) ?? String(input);
|
|
635
572
|
const finalStr = str.length > length ? str.substring(0, length - endStr.length) + endStr : str;
|
|
636
573
|
return finalStr.length > length ? finalStr.substring(0, length) : finalStr;
|
|
637
574
|
}
|
|
@@ -639,6 +576,25 @@ function truncStr(input, length, endStr = "...") {
|
|
|
639
576
|
// lib/DataStore.ts
|
|
640
577
|
var dsFmtVer = 1;
|
|
641
578
|
var DataStore = class {
|
|
579
|
+
id;
|
|
580
|
+
formatVersion;
|
|
581
|
+
defaultData;
|
|
582
|
+
encodeData;
|
|
583
|
+
decodeData;
|
|
584
|
+
compressionFormat = "deflate-raw";
|
|
585
|
+
memoryCache = true;
|
|
586
|
+
engine;
|
|
587
|
+
options;
|
|
588
|
+
/**
|
|
589
|
+
* Whether all first-init checks should be done.
|
|
590
|
+
* This includes migrating the internal DataStore format, migrating data from the UserUtils format, and anything similar.
|
|
591
|
+
* 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.
|
|
592
|
+
*/
|
|
593
|
+
firstInit = true;
|
|
594
|
+
/** In-memory cached copy of the data that is saved in persistent storage used for synchronous read access. */
|
|
595
|
+
cachedData;
|
|
596
|
+
migrations;
|
|
597
|
+
migrateIds = [];
|
|
642
598
|
//#region constructor
|
|
643
599
|
/**
|
|
644
600
|
* Creates an instance of DataStore to manage a sync & async database that is cached in memory and persistently saved across sessions.
|
|
@@ -650,30 +606,11 @@ var DataStore = class {
|
|
|
650
606
|
* @param opts The options for this DataStore instance
|
|
651
607
|
*/
|
|
652
608
|
constructor(opts) {
|
|
653
|
-
|
|
654
|
-
__publicField(this, "formatVersion");
|
|
655
|
-
__publicField(this, "defaultData");
|
|
656
|
-
__publicField(this, "encodeData");
|
|
657
|
-
__publicField(this, "decodeData");
|
|
658
|
-
__publicField(this, "compressionFormat", "deflate-raw");
|
|
659
|
-
__publicField(this, "memoryCache", true);
|
|
660
|
-
__publicField(this, "engine");
|
|
661
|
-
__publicField(this, "options");
|
|
662
|
-
/**
|
|
663
|
-
* Whether all first-init checks should be done.
|
|
664
|
-
* This includes migrating the internal DataStore format, migrating data from the UserUtils format, and anything similar.
|
|
665
|
-
* 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.
|
|
666
|
-
*/
|
|
667
|
-
__publicField(this, "firstInit", true);
|
|
668
|
-
/** In-memory cached copy of the data that is saved in persistent storage used for synchronous read access. */
|
|
669
|
-
__publicField(this, "cachedData");
|
|
670
|
-
__publicField(this, "migrations");
|
|
671
|
-
__publicField(this, "migrateIds", []);
|
|
672
|
-
var _a, _b, _c, _d;
|
|
609
|
+
var _a;
|
|
673
610
|
this.id = opts.id;
|
|
674
611
|
this.formatVersion = opts.formatVersion;
|
|
675
612
|
this.defaultData = opts.defaultData;
|
|
676
|
-
this.memoryCache = Boolean(
|
|
613
|
+
this.memoryCache = Boolean(opts.memoryCache ?? true);
|
|
677
614
|
this.cachedData = this.memoryCache ? opts.defaultData : {};
|
|
678
615
|
this.migrations = opts.migrations;
|
|
679
616
|
if (opts.migrateIds)
|
|
@@ -683,18 +620,14 @@ var DataStore = class {
|
|
|
683
620
|
this.engine = typeof opts.engine === "function" ? opts.engine() : opts.engine;
|
|
684
621
|
this.options = opts;
|
|
685
622
|
if (typeof opts.compressionFormat === "undefined")
|
|
686
|
-
this.compressionFormat = opts.compressionFormat = (
|
|
623
|
+
this.compressionFormat = opts.compressionFormat = ((_a = opts.encodeData) == null ? void 0 : _a[0]) ?? "deflate-raw";
|
|
687
624
|
if (typeof opts.compressionFormat === "string") {
|
|
688
|
-
this.encodeData = [opts.compressionFormat, (data) =>
|
|
689
|
-
|
|
690
|
-
})];
|
|
691
|
-
this.decodeData = [opts.compressionFormat, (data) => __async(this, null, function* () {
|
|
692
|
-
return yield compress(data, opts.compressionFormat, "string");
|
|
693
|
-
})];
|
|
625
|
+
this.encodeData = [opts.compressionFormat, async (data) => await compress(data, opts.compressionFormat, "string")];
|
|
626
|
+
this.decodeData = [opts.compressionFormat, async (data) => await compress(data, opts.compressionFormat, "string")];
|
|
694
627
|
} else if ("encodeData" in opts && "decodeData" in opts && Array.isArray(opts.encodeData) && Array.isArray(opts.decodeData)) {
|
|
695
628
|
this.encodeData = [opts.encodeData[0], opts.encodeData[1]];
|
|
696
629
|
this.decodeData = [opts.decodeData[0], opts.decodeData[1]];
|
|
697
|
-
this.compressionFormat =
|
|
630
|
+
this.compressionFormat = opts.encodeData[0] ?? null;
|
|
698
631
|
} else if (opts.compressionFormat === null) {
|
|
699
632
|
this.encodeData = void 0;
|
|
700
633
|
this.decodeData = void 0;
|
|
@@ -709,69 +642,66 @@ var DataStore = class {
|
|
|
709
642
|
* Automatically populates persistent storage with default data if it doesn't contain any data yet.
|
|
710
643
|
* Also runs all necessary migration functions if the data format has changed since the last time the data was saved.
|
|
711
644
|
*/
|
|
712
|
-
loadData() {
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
const
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
migrateFmt(`
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
promises.push(this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat));
|
|
735
|
-
promises.push(this.engine.deleteValue(`_uucfgenc-${this.id}`));
|
|
736
|
-
}
|
|
737
|
-
yield Promise.allSettled(promises);
|
|
645
|
+
async loadData() {
|
|
646
|
+
try {
|
|
647
|
+
if (this.firstInit) {
|
|
648
|
+
this.firstInit = false;
|
|
649
|
+
const dsVer = Number(await this.engine.getValue("__ds_fmt_ver", 0));
|
|
650
|
+
const oldData = await this.engine.getValue(`_uucfg-${this.id}`, null);
|
|
651
|
+
if (oldData) {
|
|
652
|
+
const oldVer = Number(await this.engine.getValue(`_uucfgver-${this.id}`, NaN));
|
|
653
|
+
const oldEnc = await this.engine.getValue(`_uucfgenc-${this.id}`, null);
|
|
654
|
+
const promises = [];
|
|
655
|
+
const migrateFmt = (oldKey, newKey, value) => {
|
|
656
|
+
promises.push(this.engine.setValue(newKey, value));
|
|
657
|
+
promises.push(this.engine.deleteValue(oldKey));
|
|
658
|
+
};
|
|
659
|
+
migrateFmt(`_uucfg-${this.id}`, `__ds-${this.id}-dat`, oldData);
|
|
660
|
+
if (!isNaN(oldVer))
|
|
661
|
+
migrateFmt(`_uucfgver-${this.id}`, `__ds-${this.id}-ver`, oldVer);
|
|
662
|
+
if (typeof oldEnc === "boolean")
|
|
663
|
+
migrateFmt(`_uucfgenc-${this.id}`, `__ds-${this.id}-enf`, oldEnc === true ? this.compressionFormat ?? null : null);
|
|
664
|
+
else {
|
|
665
|
+
promises.push(this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat));
|
|
666
|
+
promises.push(this.engine.deleteValue(`_uucfgenc-${this.id}`));
|
|
738
667
|
}
|
|
739
|
-
|
|
740
|
-
yield this.engine.setValue("__ds_fmt_ver", dsFmtVer);
|
|
741
|
-
}
|
|
742
|
-
if (this.migrateIds.length > 0) {
|
|
743
|
-
yield this.migrateId(this.migrateIds);
|
|
744
|
-
this.migrateIds = [];
|
|
745
|
-
}
|
|
746
|
-
const storedDataRaw = yield this.engine.getValue(`__ds-${this.id}-dat`, null);
|
|
747
|
-
let storedFmtVer = Number(yield this.engine.getValue(`__ds-${this.id}-ver`, NaN));
|
|
748
|
-
if (typeof storedDataRaw !== "string") {
|
|
749
|
-
yield this.saveDefaultData();
|
|
750
|
-
return this.engine.deepCopy(this.defaultData);
|
|
751
|
-
}
|
|
752
|
-
const storedData = storedDataRaw != null ? storedDataRaw : JSON.stringify(this.defaultData);
|
|
753
|
-
const encodingFmt = String(yield this.engine.getValue(`__ds-${this.id}-enf`, null));
|
|
754
|
-
const isEncoded = encodingFmt !== "null" && encodingFmt !== "false";
|
|
755
|
-
let saveData = false;
|
|
756
|
-
if (isNaN(storedFmtVer)) {
|
|
757
|
-
yield this.engine.setValue(`__ds-${this.id}-ver`, storedFmtVer = this.formatVersion);
|
|
758
|
-
saveData = true;
|
|
668
|
+
await Promise.allSettled(promises);
|
|
759
669
|
}
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
parsed = yield this.runMigrations(parsed, storedFmtVer);
|
|
763
|
-
if (saveData)
|
|
764
|
-
yield this.setData(parsed);
|
|
765
|
-
if (this.memoryCache)
|
|
766
|
-
return this.cachedData = this.engine.deepCopy(parsed);
|
|
767
|
-
else
|
|
768
|
-
return this.engine.deepCopy(parsed);
|
|
769
|
-
} catch (err) {
|
|
770
|
-
console.warn("Error while parsing JSON data, resetting it to the default value.", err);
|
|
771
|
-
yield this.saveDefaultData();
|
|
772
|
-
return this.defaultData;
|
|
670
|
+
if (isNaN(dsVer) || dsVer < dsFmtVer)
|
|
671
|
+
await this.engine.setValue("__ds_fmt_ver", dsFmtVer);
|
|
773
672
|
}
|
|
774
|
-
|
|
673
|
+
if (this.migrateIds.length > 0) {
|
|
674
|
+
await this.migrateId(this.migrateIds);
|
|
675
|
+
this.migrateIds = [];
|
|
676
|
+
}
|
|
677
|
+
const storedDataRaw = await this.engine.getValue(`__ds-${this.id}-dat`, null);
|
|
678
|
+
let storedFmtVer = Number(await this.engine.getValue(`__ds-${this.id}-ver`, NaN));
|
|
679
|
+
if (typeof storedDataRaw !== "string") {
|
|
680
|
+
await this.saveDefaultData();
|
|
681
|
+
return this.engine.deepCopy(this.defaultData);
|
|
682
|
+
}
|
|
683
|
+
const storedData = storedDataRaw ?? JSON.stringify(this.defaultData);
|
|
684
|
+
const encodingFmt = String(await this.engine.getValue(`__ds-${this.id}-enf`, null));
|
|
685
|
+
const isEncoded = encodingFmt !== "null" && encodingFmt !== "false";
|
|
686
|
+
let saveData = false;
|
|
687
|
+
if (isNaN(storedFmtVer)) {
|
|
688
|
+
await this.engine.setValue(`__ds-${this.id}-ver`, storedFmtVer = this.formatVersion);
|
|
689
|
+
saveData = true;
|
|
690
|
+
}
|
|
691
|
+
let parsed = await this.engine.deserializeData(storedData, isEncoded);
|
|
692
|
+
if (storedFmtVer < this.formatVersion && this.migrations)
|
|
693
|
+
parsed = await this.runMigrations(parsed, storedFmtVer);
|
|
694
|
+
if (saveData)
|
|
695
|
+
await this.setData(parsed);
|
|
696
|
+
if (this.memoryCache)
|
|
697
|
+
return this.cachedData = this.engine.deepCopy(parsed);
|
|
698
|
+
else
|
|
699
|
+
return this.engine.deepCopy(parsed);
|
|
700
|
+
} catch (err) {
|
|
701
|
+
console.warn("Error while parsing JSON data, resetting it to the default value.", err);
|
|
702
|
+
await this.saveDefaultData();
|
|
703
|
+
return this.defaultData;
|
|
704
|
+
}
|
|
775
705
|
}
|
|
776
706
|
//#region getData
|
|
777
707
|
/**
|
|
@@ -789,27 +719,25 @@ var DataStore = class {
|
|
|
789
719
|
setData(data) {
|
|
790
720
|
if (this.memoryCache)
|
|
791
721
|
this.cachedData = data;
|
|
792
|
-
return new Promise((resolve) =>
|
|
793
|
-
|
|
794
|
-
this.engine.setValue(`__ds-${this.id}-dat`,
|
|
722
|
+
return new Promise(async (resolve) => {
|
|
723
|
+
await Promise.allSettled([
|
|
724
|
+
this.engine.setValue(`__ds-${this.id}-dat`, await this.engine.serializeData(data, this.encodingEnabled())),
|
|
795
725
|
this.engine.setValue(`__ds-${this.id}-ver`, this.formatVersion),
|
|
796
726
|
this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat)
|
|
797
727
|
]);
|
|
798
728
|
resolve();
|
|
799
|
-
})
|
|
729
|
+
});
|
|
800
730
|
}
|
|
801
731
|
//#region saveDefaultData
|
|
802
732
|
/** Saves the default data passed in the constructor synchronously to the in-memory cache and asynchronously to persistent storage */
|
|
803
|
-
saveDefaultData() {
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
]);
|
|
812
|
-
});
|
|
733
|
+
async saveDefaultData() {
|
|
734
|
+
if (this.memoryCache)
|
|
735
|
+
this.cachedData = this.defaultData;
|
|
736
|
+
await Promise.allSettled([
|
|
737
|
+
this.engine.setValue(`__ds-${this.id}-dat`, await this.engine.serializeData(this.defaultData, this.encodingEnabled())),
|
|
738
|
+
this.engine.setValue(`__ds-${this.id}-ver`, this.formatVersion),
|
|
739
|
+
this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat)
|
|
740
|
+
]);
|
|
813
741
|
}
|
|
814
742
|
//#region deleteData
|
|
815
743
|
/**
|
|
@@ -817,16 +745,14 @@ var DataStore = class {
|
|
|
817
745
|
* The in-memory cache will be left untouched, so you may still access the data with {@linkcode getData()}
|
|
818
746
|
* Calling {@linkcode loadData()} or {@linkcode setData()} after this method was called will recreate persistent storage with the cached or default data.
|
|
819
747
|
*/
|
|
820
|
-
deleteData() {
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
yield (_b = (_a = this.engine).deleteStorage) == null ? void 0 : _b.call(_a);
|
|
829
|
-
});
|
|
748
|
+
async deleteData() {
|
|
749
|
+
var _a, _b;
|
|
750
|
+
await Promise.allSettled([
|
|
751
|
+
this.engine.deleteValue(`__ds-${this.id}-dat`),
|
|
752
|
+
this.engine.deleteValue(`__ds-${this.id}-ver`),
|
|
753
|
+
this.engine.deleteValue(`__ds-${this.id}-enf`)
|
|
754
|
+
]);
|
|
755
|
+
await ((_b = (_a = this.engine).deleteStorage) == null ? void 0 : _b.call(_a));
|
|
830
756
|
}
|
|
831
757
|
//#region encodingEnabled
|
|
832
758
|
/** Returns whether encoding and decoding are enabled for this DataStore instance */
|
|
@@ -841,77 +767,73 @@ var DataStore = class {
|
|
|
841
767
|
*
|
|
842
768
|
* 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.
|
|
843
769
|
*/
|
|
844
|
-
runMigrations(oldData, oldFmtVer, resetOnError = true) {
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
return this.getData();
|
|
863
|
-
}
|
|
770
|
+
async runMigrations(oldData, oldFmtVer, resetOnError = true) {
|
|
771
|
+
if (!this.migrations)
|
|
772
|
+
return oldData;
|
|
773
|
+
let newData = oldData;
|
|
774
|
+
const sortedMigrations = Object.entries(this.migrations).sort(([a], [b]) => Number(a) - Number(b));
|
|
775
|
+
let lastFmtVer = oldFmtVer;
|
|
776
|
+
for (const [fmtVer, migrationFunc] of sortedMigrations) {
|
|
777
|
+
const ver = Number(fmtVer);
|
|
778
|
+
if (oldFmtVer < this.formatVersion && oldFmtVer < ver) {
|
|
779
|
+
try {
|
|
780
|
+
const migRes = migrationFunc(newData);
|
|
781
|
+
newData = migRes instanceof Promise ? await migRes : migRes;
|
|
782
|
+
lastFmtVer = oldFmtVer = ver;
|
|
783
|
+
} catch (err) {
|
|
784
|
+
if (!resetOnError)
|
|
785
|
+
throw new MigrationError(`Error while running migration function for format version '${fmtVer}'`, { cause: err });
|
|
786
|
+
await this.saveDefaultData();
|
|
787
|
+
return this.getData();
|
|
864
788
|
}
|
|
865
789
|
}
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
790
|
+
}
|
|
791
|
+
await Promise.allSettled([
|
|
792
|
+
this.engine.setValue(`__ds-${this.id}-dat`, await this.engine.serializeData(newData)),
|
|
793
|
+
this.engine.setValue(`__ds-${this.id}-ver`, lastFmtVer),
|
|
794
|
+
this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat)
|
|
795
|
+
]);
|
|
796
|
+
if (this.memoryCache)
|
|
797
|
+
return this.cachedData = this.engine.deepCopy(newData);
|
|
798
|
+
else
|
|
799
|
+
return this.engine.deepCopy(newData);
|
|
876
800
|
}
|
|
877
801
|
//#region migrateId
|
|
878
802
|
/**
|
|
879
803
|
* Tries to migrate the currently saved persistent data from one or more old IDs to the ID set in the constructor.
|
|
880
804
|
* 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.
|
|
881
805
|
*/
|
|
882
|
-
migrateId(oldIds) {
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
const [
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
this.engine.getValue(`__ds-${id}-enf`, null)
|
|
891
|
-
]);
|
|
892
|
-
return [d, Number(f), Boolean(e) && String(e) !== "null"];
|
|
893
|
-
}))();
|
|
894
|
-
if (data === void 0 || isNaN(fmtVer))
|
|
895
|
-
return;
|
|
896
|
-
const parsed = yield this.engine.deserializeData(data, isEncoded);
|
|
897
|
-
yield Promise.allSettled([
|
|
898
|
-
this.engine.setValue(`__ds-${this.id}-dat`, yield this.engine.serializeData(parsed)),
|
|
899
|
-
this.engine.setValue(`__ds-${this.id}-ver`, fmtVer),
|
|
900
|
-
this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat),
|
|
901
|
-
this.engine.deleteValue(`__ds-${id}-dat`),
|
|
902
|
-
this.engine.deleteValue(`__ds-${id}-ver`),
|
|
903
|
-
this.engine.deleteValue(`__ds-${id}-enf`)
|
|
806
|
+
async migrateId(oldIds) {
|
|
807
|
+
const ids = Array.isArray(oldIds) ? oldIds : [oldIds];
|
|
808
|
+
await Promise.all(ids.map(async (id) => {
|
|
809
|
+
const [data, fmtVer, isEncoded] = await (async () => {
|
|
810
|
+
const [d, f, e] = await Promise.all([
|
|
811
|
+
this.engine.getValue(`__ds-${id}-dat`, JSON.stringify(this.defaultData)),
|
|
812
|
+
this.engine.getValue(`__ds-${id}-ver`, NaN),
|
|
813
|
+
this.engine.getValue(`__ds-${id}-enf`, null)
|
|
904
814
|
]);
|
|
905
|
-
|
|
906
|
-
|
|
815
|
+
return [d, Number(f), Boolean(e) && String(e) !== "null"];
|
|
816
|
+
})();
|
|
817
|
+
if (data === void 0 || isNaN(fmtVer))
|
|
818
|
+
return;
|
|
819
|
+
const parsed = await this.engine.deserializeData(data, isEncoded);
|
|
820
|
+
await Promise.allSettled([
|
|
821
|
+
this.engine.setValue(`__ds-${this.id}-dat`, await this.engine.serializeData(parsed)),
|
|
822
|
+
this.engine.setValue(`__ds-${this.id}-ver`, fmtVer),
|
|
823
|
+
this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat),
|
|
824
|
+
this.engine.deleteValue(`__ds-${id}-dat`),
|
|
825
|
+
this.engine.deleteValue(`__ds-${id}-ver`),
|
|
826
|
+
this.engine.deleteValue(`__ds-${id}-enf`)
|
|
827
|
+
]);
|
|
828
|
+
}));
|
|
907
829
|
}
|
|
908
830
|
};
|
|
909
831
|
|
|
910
832
|
// lib/DataStoreEngine.ts
|
|
911
833
|
var DataStoreEngine = class {
|
|
834
|
+
dataStoreOptions;
|
|
912
835
|
// setDataStoreOptions() is called from inside the DataStore constructor to set this value
|
|
913
836
|
constructor(options) {
|
|
914
|
-
__publicField(this, "dataStoreOptions");
|
|
915
837
|
if (options)
|
|
916
838
|
this.dataStoreOptions = options;
|
|
917
839
|
}
|
|
@@ -921,29 +843,25 @@ var DataStoreEngine = class {
|
|
|
921
843
|
}
|
|
922
844
|
//#region serialization api
|
|
923
845
|
/** 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 */
|
|
924
|
-
serializeData(data, useEncoding) {
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
return encRes;
|
|
935
|
-
});
|
|
846
|
+
async serializeData(data, useEncoding) {
|
|
847
|
+
var _a, _b, _c, _d, _e;
|
|
848
|
+
this.ensureDataStoreOptions();
|
|
849
|
+
const stringData = JSON.stringify(data);
|
|
850
|
+
if (!useEncoding || !((_a = this.dataStoreOptions) == null ? void 0 : _a.encodeData) || !((_b = this.dataStoreOptions) == null ? void 0 : _b.decodeData))
|
|
851
|
+
return stringData;
|
|
852
|
+
const encRes = (_e = (_d = (_c = this.dataStoreOptions) == null ? void 0 : _c.encodeData) == null ? void 0 : _d[1]) == null ? void 0 : _e.call(_d, stringData);
|
|
853
|
+
if (encRes instanceof Promise)
|
|
854
|
+
return await encRes;
|
|
855
|
+
return encRes;
|
|
936
856
|
}
|
|
937
857
|
/** Deserializes the given string to a JSON object, optionally decoded with `options.decodeData` if {@linkcode useEncoding} is set to true */
|
|
938
|
-
deserializeData(data, useEncoding) {
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
return JSON.parse(decRes != null ? decRes : data);
|
|
946
|
-
});
|
|
858
|
+
async deserializeData(data, useEncoding) {
|
|
859
|
+
var _a, _b, _c;
|
|
860
|
+
this.ensureDataStoreOptions();
|
|
861
|
+
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;
|
|
862
|
+
if (decRes instanceof Promise)
|
|
863
|
+
decRes = await decRes;
|
|
864
|
+
return JSON.parse(decRes ?? data);
|
|
947
865
|
}
|
|
948
866
|
//#region misc api
|
|
949
867
|
/** Throws an error if the DataStoreOptions are not set or invalid */
|
|
@@ -961,12 +879,13 @@ var DataStoreEngine = class {
|
|
|
961
879
|
try {
|
|
962
880
|
if ("structuredClone" in globalThis)
|
|
963
881
|
return structuredClone(obj);
|
|
964
|
-
} catch
|
|
882
|
+
} catch {
|
|
965
883
|
}
|
|
966
884
|
return JSON.parse(JSON.stringify(obj));
|
|
967
885
|
}
|
|
968
886
|
};
|
|
969
887
|
var BrowserStorageEngine = class extends DataStoreEngine {
|
|
888
|
+
options;
|
|
970
889
|
/**
|
|
971
890
|
* Creates an instance of `BrowserStorageEngine`.
|
|
972
891
|
*
|
|
@@ -975,40 +894,36 @@ var BrowserStorageEngine = class extends DataStoreEngine {
|
|
|
975
894
|
*/
|
|
976
895
|
constructor(options) {
|
|
977
896
|
super(options == null ? void 0 : options.dataStoreOptions);
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
}
|
|
897
|
+
this.options = {
|
|
898
|
+
type: "localStorage",
|
|
899
|
+
...options
|
|
900
|
+
};
|
|
982
901
|
}
|
|
983
902
|
//#region storage api
|
|
984
903
|
/** Fetches a value from persistent storage */
|
|
985
|
-
getValue(name, defaultValue) {
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
return typeof val === "undefined" ? defaultValue : val;
|
|
989
|
-
});
|
|
904
|
+
async getValue(name, defaultValue) {
|
|
905
|
+
const val = this.options.type === "localStorage" ? globalThis.localStorage.getItem(name) : globalThis.sessionStorage.getItem(name);
|
|
906
|
+
return typeof val === "undefined" ? defaultValue : val;
|
|
990
907
|
}
|
|
991
908
|
/** Sets a value in persistent storage */
|
|
992
|
-
setValue(name, value) {
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
globalThis.sessionStorage.setItem(name, String(value));
|
|
998
|
-
});
|
|
909
|
+
async setValue(name, value) {
|
|
910
|
+
if (this.options.type === "localStorage")
|
|
911
|
+
globalThis.localStorage.setItem(name, String(value));
|
|
912
|
+
else
|
|
913
|
+
globalThis.sessionStorage.setItem(name, String(value));
|
|
999
914
|
}
|
|
1000
915
|
/** Deletes a value from persistent storage */
|
|
1001
|
-
deleteValue(name) {
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
globalThis.sessionStorage.removeItem(name);
|
|
1007
|
-
});
|
|
916
|
+
async deleteValue(name) {
|
|
917
|
+
if (this.options.type === "localStorage")
|
|
918
|
+
globalThis.localStorage.removeItem(name);
|
|
919
|
+
else
|
|
920
|
+
globalThis.sessionStorage.removeItem(name);
|
|
1008
921
|
}
|
|
1009
922
|
};
|
|
1010
923
|
var fs;
|
|
1011
924
|
var FileStorageEngine = class extends DataStoreEngine {
|
|
925
|
+
options;
|
|
926
|
+
fileAccessQueue = Promise.resolve();
|
|
1012
927
|
/**
|
|
1013
928
|
* Creates an instance of `FileStorageEngine`.
|
|
1014
929
|
*
|
|
@@ -1017,136 +932,122 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
1017
932
|
*/
|
|
1018
933
|
constructor(options) {
|
|
1019
934
|
super(options == null ? void 0 : options.dataStoreOptions);
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
}, options);
|
|
935
|
+
this.options = {
|
|
936
|
+
filePath: (id) => `.ds-${id}`,
|
|
937
|
+
...options
|
|
938
|
+
};
|
|
1025
939
|
}
|
|
1026
940
|
//#region json file
|
|
1027
941
|
/** Reads the file contents */
|
|
1028
|
-
readFile() {
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
}
|
|
1043
|
-
});
|
|
942
|
+
async readFile() {
|
|
943
|
+
var _a, _b, _c, _d;
|
|
944
|
+
this.ensureDataStoreOptions();
|
|
945
|
+
try {
|
|
946
|
+
if (!fs)
|
|
947
|
+
fs = (_a = await import("fs/promises")) == null ? void 0 : _a.default;
|
|
948
|
+
if (!fs)
|
|
949
|
+
throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
|
|
950
|
+
const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
|
|
951
|
+
const data = await fs.readFile(path, "utf-8");
|
|
952
|
+
return data ? JSON.parse(await ((_d = (_c = (_b = this.dataStoreOptions) == null ? void 0 : _b.decodeData) == null ? void 0 : _c[1]) == null ? void 0 : _d.call(_c, data)) ?? data) : void 0;
|
|
953
|
+
} catch {
|
|
954
|
+
return void 0;
|
|
955
|
+
}
|
|
1044
956
|
}
|
|
1045
957
|
/** Overwrites the file contents */
|
|
1046
|
-
writeFile(data) {
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
}
|
|
1061
|
-
});
|
|
958
|
+
async writeFile(data) {
|
|
959
|
+
var _a, _b, _c, _d;
|
|
960
|
+
this.ensureDataStoreOptions();
|
|
961
|
+
try {
|
|
962
|
+
if (!fs)
|
|
963
|
+
fs = (_a = await import("fs/promises")) == null ? void 0 : _a.default;
|
|
964
|
+
if (!fs)
|
|
965
|
+
throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
|
|
966
|
+
const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
|
|
967
|
+
await fs.mkdir(path.slice(0, path.lastIndexOf(path.includes("/") ? "/" : "\\")), { recursive: true });
|
|
968
|
+
await fs.writeFile(path, await ((_d = (_c = (_b = this.dataStoreOptions) == null ? void 0 : _b.encodeData) == null ? void 0 : _c[1]) == null ? void 0 : _d.call(_c, JSON.stringify(data))) ?? JSON.stringify(data, void 0, 2), "utf-8");
|
|
969
|
+
} catch (err) {
|
|
970
|
+
console.error("Error writing file:", err);
|
|
971
|
+
}
|
|
1062
972
|
}
|
|
1063
973
|
//#region storage api
|
|
1064
974
|
/** Fetches a value from persistent storage */
|
|
1065
|
-
getValue(name, defaultValue) {
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
if (typeof value === "string")
|
|
1074
|
-
return value;
|
|
975
|
+
async getValue(name, defaultValue) {
|
|
976
|
+
const data = await this.readFile();
|
|
977
|
+
if (!data)
|
|
978
|
+
return defaultValue;
|
|
979
|
+
const value = data == null ? void 0 : data[name];
|
|
980
|
+
if (typeof value === "undefined")
|
|
981
|
+
return defaultValue;
|
|
982
|
+
if (typeof value === "string")
|
|
1075
983
|
return value;
|
|
1076
|
-
|
|
984
|
+
return value;
|
|
1077
985
|
}
|
|
1078
986
|
/** Sets a value in persistent storage */
|
|
1079
|
-
setValue(name, value) {
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
yield this.fileAccessQueue.catch(() => {
|
|
1092
|
-
});
|
|
987
|
+
async setValue(name, value) {
|
|
988
|
+
this.fileAccessQueue = this.fileAccessQueue.then(async () => {
|
|
989
|
+
let data = await this.readFile();
|
|
990
|
+
if (!data)
|
|
991
|
+
data = {};
|
|
992
|
+
data[name] = value;
|
|
993
|
+
await this.writeFile(data);
|
|
994
|
+
}).catch((err) => {
|
|
995
|
+
console.error("Error in setValue:", err);
|
|
996
|
+
throw err;
|
|
997
|
+
});
|
|
998
|
+
await this.fileAccessQueue.catch(() => {
|
|
1093
999
|
});
|
|
1094
1000
|
}
|
|
1095
1001
|
/** Deletes a value from persistent storage */
|
|
1096
|
-
deleteValue(name) {
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
yield this.fileAccessQueue.catch(() => {
|
|
1109
|
-
});
|
|
1002
|
+
async deleteValue(name) {
|
|
1003
|
+
this.fileAccessQueue = this.fileAccessQueue.then(async () => {
|
|
1004
|
+
const data = await this.readFile();
|
|
1005
|
+
if (!data)
|
|
1006
|
+
return;
|
|
1007
|
+
delete data[name];
|
|
1008
|
+
await this.writeFile(data);
|
|
1009
|
+
}).catch((err) => {
|
|
1010
|
+
console.error("Error in deleteValue:", err);
|
|
1011
|
+
throw err;
|
|
1012
|
+
});
|
|
1013
|
+
await this.fileAccessQueue.catch(() => {
|
|
1110
1014
|
});
|
|
1111
1015
|
}
|
|
1112
1016
|
/** Deletes the file that contains the data of this DataStore. */
|
|
1113
|
-
deleteStorage() {
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
}
|
|
1127
|
-
});
|
|
1017
|
+
async deleteStorage() {
|
|
1018
|
+
var _a;
|
|
1019
|
+
this.ensureDataStoreOptions();
|
|
1020
|
+
try {
|
|
1021
|
+
if (!fs)
|
|
1022
|
+
fs = (_a = await import("fs/promises")) == null ? void 0 : _a.default;
|
|
1023
|
+
if (!fs)
|
|
1024
|
+
throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
|
|
1025
|
+
const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
|
|
1026
|
+
return await fs.unlink(path);
|
|
1027
|
+
} catch (err) {
|
|
1028
|
+
console.error("Error deleting file:", err);
|
|
1029
|
+
}
|
|
1128
1030
|
}
|
|
1129
1031
|
};
|
|
1130
1032
|
|
|
1131
1033
|
// lib/DataStoreSerializer.ts
|
|
1132
1034
|
var DataStoreSerializer = class _DataStoreSerializer {
|
|
1035
|
+
stores;
|
|
1036
|
+
options;
|
|
1133
1037
|
constructor(stores, options = {}) {
|
|
1134
|
-
__publicField(this, "stores");
|
|
1135
|
-
__publicField(this, "options");
|
|
1136
1038
|
if (!crypto || !crypto.subtle)
|
|
1137
1039
|
throw new ScriptContextError("DataStoreSerializer has to run in a secure context (HTTPS) or in another environment that implements the subtleCrypto API!");
|
|
1138
1040
|
this.stores = stores;
|
|
1139
|
-
this.options =
|
|
1041
|
+
this.options = {
|
|
1140
1042
|
addChecksum: true,
|
|
1141
1043
|
ensureIntegrity: true,
|
|
1142
|
-
remapIds: {}
|
|
1143
|
-
|
|
1044
|
+
remapIds: {},
|
|
1045
|
+
...options
|
|
1046
|
+
};
|
|
1144
1047
|
}
|
|
1145
1048
|
/** Calculates the checksum of a string */
|
|
1146
|
-
calcChecksum(input) {
|
|
1147
|
-
return
|
|
1148
|
-
return computeHash(input, "SHA-256");
|
|
1149
|
-
});
|
|
1049
|
+
async calcChecksum(input) {
|
|
1050
|
+
return computeHash(input, "SHA-256");
|
|
1150
1051
|
}
|
|
1151
1052
|
/**
|
|
1152
1053
|
* Serializes only a subset of the data stores into a string.
|
|
@@ -1154,80 +1055,72 @@ var DataStoreSerializer = class _DataStoreSerializer {
|
|
|
1154
1055
|
* @param useEncoding Whether to encode the data using each DataStore's `encodeData()` method
|
|
1155
1056
|
* @param stringified Whether to return the result as a string or as an array of `SerializedDataStore` objects
|
|
1156
1057
|
*/
|
|
1157
|
-
serializePartial(stores, useEncoding = true, stringified = true) {
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
return stringified ? JSON.stringify(serData) : serData;
|
|
1175
|
-
});
|
|
1058
|
+
async serializePartial(stores, useEncoding = true, stringified = true) {
|
|
1059
|
+
var _a;
|
|
1060
|
+
const serData = [];
|
|
1061
|
+
const filteredStores = this.stores.filter((s) => typeof stores === "function" ? stores(s.id) : stores.includes(s.id));
|
|
1062
|
+
for (const storeInst of filteredStores) {
|
|
1063
|
+
const encoded = Boolean(useEncoding && storeInst.encodingEnabled() && ((_a = storeInst.encodeData) == null ? void 0 : _a[1]));
|
|
1064
|
+
const rawData = storeInst.memoryCache ? storeInst.getData() : await storeInst.loadData();
|
|
1065
|
+
const data = encoded ? await storeInst.encodeData[1](JSON.stringify(rawData)) : JSON.stringify(rawData);
|
|
1066
|
+
serData.push({
|
|
1067
|
+
id: storeInst.id,
|
|
1068
|
+
data,
|
|
1069
|
+
formatVersion: storeInst.formatVersion,
|
|
1070
|
+
encoded,
|
|
1071
|
+
checksum: this.options.addChecksum ? await this.calcChecksum(data) : void 0
|
|
1072
|
+
});
|
|
1073
|
+
}
|
|
1074
|
+
return stringified ? JSON.stringify(serData) : serData;
|
|
1176
1075
|
}
|
|
1177
1076
|
/**
|
|
1178
1077
|
* Serializes the data stores into a string.
|
|
1179
1078
|
* @param useEncoding Whether to encode the data using each DataStore's `encodeData()` method
|
|
1180
1079
|
* @param stringified Whether to return the result as a string or as an array of `SerializedDataStore` objects
|
|
1181
1080
|
*/
|
|
1182
|
-
serialize(useEncoding = true, stringified = true) {
|
|
1183
|
-
return
|
|
1184
|
-
return this.serializePartial(this.stores.map((s) => s.id), useEncoding, stringified);
|
|
1185
|
-
});
|
|
1081
|
+
async serialize(useEncoding = true, stringified = true) {
|
|
1082
|
+
return this.serializePartial(this.stores.map((s) => s.id), useEncoding, stringified);
|
|
1186
1083
|
}
|
|
1187
1084
|
/**
|
|
1188
1085
|
* Deserializes the data exported via {@linkcode serialize()} and imports only a subset into the DataStore instances.
|
|
1189
1086
|
* Also triggers the migration process if the data format has changed.
|
|
1190
1087
|
*/
|
|
1191
|
-
deserializePartial(stores, data) {
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
throw new ChecksumMismatchError(`Checksum mismatch for DataStore with ID "${storeData.id}"!
|
|
1088
|
+
async deserializePartial(stores, data) {
|
|
1089
|
+
const deserStores = typeof data === "string" ? JSON.parse(data) : data;
|
|
1090
|
+
if (!Array.isArray(deserStores) || !deserStores.every(_DataStoreSerializer.isSerializedDataStoreObj))
|
|
1091
|
+
throw new TypeError("Invalid serialized data format! Expected an array of SerializedDataStore objects.");
|
|
1092
|
+
const resolveStoreId = (id) => {
|
|
1093
|
+
var _a;
|
|
1094
|
+
return ((_a = Object.entries(this.options.remapIds).find(([, v]) => v.includes(id))) == null ? void 0 : _a[0]) ?? id;
|
|
1095
|
+
};
|
|
1096
|
+
const matchesFilter = (id) => typeof stores === "function" ? stores(id) : stores.includes(id);
|
|
1097
|
+
for (const storeData of deserStores) {
|
|
1098
|
+
const effectiveId = resolveStoreId(storeData.id);
|
|
1099
|
+
if (!matchesFilter(effectiveId))
|
|
1100
|
+
continue;
|
|
1101
|
+
const storeInst = this.stores.find((s) => s.id === effectiveId);
|
|
1102
|
+
if (!storeInst)
|
|
1103
|
+
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.`);
|
|
1104
|
+
if (this.options.ensureIntegrity && typeof storeData.checksum === "string") {
|
|
1105
|
+
const checksum = await this.calcChecksum(storeData.data);
|
|
1106
|
+
if (checksum !== storeData.checksum)
|
|
1107
|
+
throw new ChecksumMismatchError(`Checksum mismatch for DataStore with ID "${storeData.id}"!
|
|
1212
1108
|
Expected: ${storeData.checksum}
|
|
1213
1109
|
Has: ${checksum}`);
|
|
1214
|
-
}
|
|
1215
|
-
const decodedData = storeData.encoded && storeInst.encodingEnabled() ? yield storeInst.decodeData[1](storeData.data) : storeData.data;
|
|
1216
|
-
if (storeData.formatVersion && !isNaN(Number(storeData.formatVersion)) && Number(storeData.formatVersion) < storeInst.formatVersion)
|
|
1217
|
-
yield storeInst.runMigrations(JSON.parse(decodedData), Number(storeData.formatVersion), false);
|
|
1218
|
-
else
|
|
1219
|
-
yield storeInst.setData(JSON.parse(decodedData));
|
|
1220
1110
|
}
|
|
1221
|
-
|
|
1111
|
+
const decodedData = storeData.encoded && storeInst.encodingEnabled() ? await storeInst.decodeData[1](storeData.data) : storeData.data;
|
|
1112
|
+
if (storeData.formatVersion && !isNaN(Number(storeData.formatVersion)) && Number(storeData.formatVersion) < storeInst.formatVersion)
|
|
1113
|
+
await storeInst.runMigrations(JSON.parse(decodedData), Number(storeData.formatVersion), false);
|
|
1114
|
+
else
|
|
1115
|
+
await storeInst.setData(JSON.parse(decodedData));
|
|
1116
|
+
}
|
|
1222
1117
|
}
|
|
1223
1118
|
/**
|
|
1224
1119
|
* Deserializes the data exported via {@linkcode serialize()} and imports the data into all matching DataStore instances.
|
|
1225
1120
|
* Also triggers the migration process if the data format has changed.
|
|
1226
1121
|
*/
|
|
1227
|
-
deserialize(data) {
|
|
1228
|
-
return
|
|
1229
|
-
return this.deserializePartial(this.stores.map((s) => s.id), data);
|
|
1230
|
-
});
|
|
1122
|
+
async deserialize(data) {
|
|
1123
|
+
return this.deserializePartial(this.stores.map((s) => s.id), data);
|
|
1231
1124
|
}
|
|
1232
1125
|
/**
|
|
1233
1126
|
* Loads the persistent data of the DataStore instances into the in-memory cache.
|
|
@@ -1235,40 +1128,32 @@ Has: ${checksum}`);
|
|
|
1235
1128
|
* @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
|
|
1236
1129
|
* @returns Returns a PromiseSettledResult array with the results of each DataStore instance in the format `{ id: string, data: object }`
|
|
1237
1130
|
*/
|
|
1238
|
-
loadStoresData(stores) {
|
|
1239
|
-
return
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
};
|
|
1246
|
-
}))
|
|
1247
|
-
);
|
|
1248
|
-
});
|
|
1131
|
+
async loadStoresData(stores) {
|
|
1132
|
+
return Promise.allSettled(
|
|
1133
|
+
this.getStoresFiltered(stores).map(async (store) => ({
|
|
1134
|
+
id: store.id,
|
|
1135
|
+
data: await store.loadData()
|
|
1136
|
+
}))
|
|
1137
|
+
);
|
|
1249
1138
|
}
|
|
1250
1139
|
/**
|
|
1251
1140
|
* Resets the persistent and in-memory data of the DataStore instances to their default values.
|
|
1252
1141
|
* @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
|
|
1253
1142
|
*/
|
|
1254
|
-
resetStoresData(stores) {
|
|
1255
|
-
return
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
);
|
|
1259
|
-
});
|
|
1143
|
+
async resetStoresData(stores) {
|
|
1144
|
+
return Promise.allSettled(
|
|
1145
|
+
this.getStoresFiltered(stores).map((store) => store.saveDefaultData())
|
|
1146
|
+
);
|
|
1260
1147
|
}
|
|
1261
1148
|
/**
|
|
1262
1149
|
* Deletes the persistent data of the DataStore instances.
|
|
1263
1150
|
* Leaves the in-memory data untouched.
|
|
1264
1151
|
* @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
|
|
1265
1152
|
*/
|
|
1266
|
-
deleteStoresData(stores) {
|
|
1267
|
-
return
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
);
|
|
1271
|
-
});
|
|
1153
|
+
async deleteStoresData(stores) {
|
|
1154
|
+
return Promise.allSettled(
|
|
1155
|
+
this.getStoresFiltered(stores).map((store) => store.deleteData())
|
|
1156
|
+
);
|
|
1272
1157
|
}
|
|
1273
1158
|
/** Checks if a given value is an array of SerializedDataStore objects */
|
|
1274
1159
|
static isSerializedDataStoreObjArray(obj) {
|
|
@@ -1293,26 +1178,26 @@ var createNanoEvents = () => ({
|
|
|
1293
1178
|
},
|
|
1294
1179
|
events: {},
|
|
1295
1180
|
on(event, cb) {
|
|
1296
|
-
var _a;
|
|
1297
1181
|
;
|
|
1298
|
-
(
|
|
1182
|
+
(this.events[event] ||= []).push(cb);
|
|
1299
1183
|
return () => {
|
|
1300
|
-
var
|
|
1301
|
-
this.events[event] = (
|
|
1184
|
+
var _a;
|
|
1185
|
+
this.events[event] = (_a = this.events[event]) == null ? void 0 : _a.filter((i) => cb !== i);
|
|
1302
1186
|
};
|
|
1303
1187
|
}
|
|
1304
1188
|
});
|
|
1305
1189
|
|
|
1306
1190
|
// lib/NanoEmitter.ts
|
|
1307
1191
|
var NanoEmitter = class {
|
|
1192
|
+
events = createNanoEvents();
|
|
1193
|
+
eventUnsubscribes = [];
|
|
1194
|
+
emitterOptions;
|
|
1308
1195
|
/** Creates a new instance of NanoEmitter - a lightweight event emitter with helper methods and a strongly typed event map */
|
|
1309
1196
|
constructor(options = {}) {
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
publicEmit: false
|
|
1315
|
-
}, options);
|
|
1197
|
+
this.emitterOptions = {
|
|
1198
|
+
publicEmit: false,
|
|
1199
|
+
...options
|
|
1200
|
+
};
|
|
1316
1201
|
}
|
|
1317
1202
|
//#region on
|
|
1318
1203
|
/**
|
|
@@ -1404,11 +1289,12 @@ var NanoEmitter = class {
|
|
|
1404
1289
|
this.eventUnsubscribes = this.eventUnsubscribes.filter((u) => !allUnsubs.includes(u));
|
|
1405
1290
|
};
|
|
1406
1291
|
for (const opts of Array.isArray(options) ? options : [options]) {
|
|
1407
|
-
const optsWithDefaults =
|
|
1292
|
+
const optsWithDefaults = {
|
|
1408
1293
|
allOf: [],
|
|
1409
1294
|
oneOf: [],
|
|
1410
|
-
once: false
|
|
1411
|
-
|
|
1295
|
+
once: false,
|
|
1296
|
+
...opts
|
|
1297
|
+
};
|
|
1412
1298
|
const {
|
|
1413
1299
|
oneOf,
|
|
1414
1300
|
allOf,
|
|
@@ -1493,13 +1379,13 @@ var Debouncer = class extends NanoEmitter {
|
|
|
1493
1379
|
super();
|
|
1494
1380
|
this.timeout = timeout;
|
|
1495
1381
|
this.type = type;
|
|
1496
|
-
/** All registered listener functions and the time they were attached */
|
|
1497
|
-
__publicField(this, "listeners", []);
|
|
1498
|
-
/** The currently active timeout */
|
|
1499
|
-
__publicField(this, "activeTimeout");
|
|
1500
|
-
/** The latest queued call */
|
|
1501
|
-
__publicField(this, "queuedCall");
|
|
1502
1382
|
}
|
|
1383
|
+
/** All registered listener functions and the time they were attached */
|
|
1384
|
+
listeners = [];
|
|
1385
|
+
/** The currently active timeout */
|
|
1386
|
+
activeTimeout;
|
|
1387
|
+
/** The latest queued call */
|
|
1388
|
+
queuedCall;
|
|
1503
1389
|
//#region listeners
|
|
1504
1390
|
/** Adds a listener function that will be called on timeout */
|
|
1505
1391
|
addListener(fn) {
|
|
@@ -1586,8 +1472,6 @@ function debounce(fn, timeout = 200, type = "immediate") {
|
|
|
1586
1472
|
return func;
|
|
1587
1473
|
}
|
|
1588
1474
|
|
|
1589
|
-
if(__exports != exports)module.exports = exports;return module.exports}));
|
|
1590
|
-
|
|
1591
1475
|
|
|
1592
1476
|
|
|
1593
1477
|
if (typeof module.exports == "object" && typeof exports == "object") {
|