@sv443-network/coreutils 0.0.1 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -10
- package/README.md +34 -7
- package/dist/CoreUtils.cjs +19 -4
- 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 +21 -6
- package/dist/CoreUtils.umd.js +474 -344
- package/dist/lib/DataStoreEngine.d.ts +2 -2
- package/dist/lib/misc.d.ts +8 -0
- package/package.json +34 -28
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 = {};
|
|
@@ -92,6 +141,7 @@ __export(lib_exports, {
|
|
|
92
141
|
randomizeArray: () => randomizeArray,
|
|
93
142
|
rgbToHex: () => rgbToHex,
|
|
94
143
|
roundFixed: () => roundFixed,
|
|
144
|
+
scheduleExit: () => scheduleExit,
|
|
95
145
|
secsToTimeStr: () => secsToTimeStr,
|
|
96
146
|
setImmediateInterval: () => setImmediateInterval,
|
|
97
147
|
setImmediateTimeoutLoop: () => setImmediateTimeoutLoop,
|
|
@@ -175,7 +225,7 @@ function randRange(...args) {
|
|
|
175
225
|
return Math.floor(Math.random() * (max - min + 1)) + min;
|
|
176
226
|
}
|
|
177
227
|
function roundFixed(num, fractionDigits) {
|
|
178
|
-
const scale = 10
|
|
228
|
+
const scale = __pow(10, fractionDigits);
|
|
179
229
|
return Math.round(num * scale) / scale;
|
|
180
230
|
}
|
|
181
231
|
function valsWithin(a, b, dec = 10, withinRange = 0.5) {
|
|
@@ -239,7 +289,7 @@ function darkenColor(color, percent, upperCase = false) {
|
|
|
239
289
|
if (isHexCol)
|
|
240
290
|
return rgbToHex(r, g, b, a, color.startsWith("#"), upperCase);
|
|
241
291
|
else if (color.startsWith("rgba"))
|
|
242
|
-
return `rgba(${r}, ${g}, ${b}, ${a
|
|
292
|
+
return `rgba(${r}, ${g}, ${b}, ${a != null ? a : NaN})`;
|
|
243
293
|
else if (color.startsWith("rgb"))
|
|
244
294
|
return `rgb(${r}, ${g}, ${b})`;
|
|
245
295
|
else
|
|
@@ -275,35 +325,43 @@ function abtoa(buf) {
|
|
|
275
325
|
function atoab(str) {
|
|
276
326
|
return Uint8Array.from(atob(str), (c) => c.charCodeAt(0));
|
|
277
327
|
}
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
328
|
+
function compress(input, compressionFormat, outputType = "string") {
|
|
329
|
+
return __async(this, null, function* () {
|
|
330
|
+
var _a;
|
|
331
|
+
const byteArray = input instanceof ArrayBuffer ? input : new TextEncoder().encode((_a = input == null ? void 0 : input.toString()) != null ? _a : String(input));
|
|
332
|
+
const comp = new CompressionStream(compressionFormat);
|
|
333
|
+
const writer = comp.writable.getWriter();
|
|
334
|
+
writer.write(byteArray);
|
|
335
|
+
writer.close();
|
|
336
|
+
const buf = yield new Response(comp.readable).arrayBuffer();
|
|
337
|
+
return outputType === "arrayBuffer" ? buf : abtoa(buf);
|
|
338
|
+
});
|
|
286
339
|
}
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
340
|
+
function decompress(input, compressionFormat, outputType = "string") {
|
|
341
|
+
return __async(this, null, function* () {
|
|
342
|
+
var _a;
|
|
343
|
+
const byteArray = input instanceof ArrayBuffer ? input : atoab((_a = input == null ? void 0 : input.toString()) != null ? _a : String(input));
|
|
344
|
+
const decomp = new DecompressionStream(compressionFormat);
|
|
345
|
+
const writer = decomp.writable.getWriter();
|
|
346
|
+
writer.write(byteArray);
|
|
347
|
+
writer.close();
|
|
348
|
+
const buf = yield new Response(decomp.readable).arrayBuffer();
|
|
349
|
+
return outputType === "arrayBuffer" ? buf : new TextDecoder().decode(buf);
|
|
350
|
+
});
|
|
295
351
|
}
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
352
|
+
function computeHash(input, algorithm = "SHA-256") {
|
|
353
|
+
return __async(this, null, function* () {
|
|
354
|
+
let data;
|
|
355
|
+
if (typeof input === "string") {
|
|
356
|
+
const encoder = new TextEncoder();
|
|
357
|
+
data = encoder.encode(input);
|
|
358
|
+
} else
|
|
359
|
+
data = input;
|
|
360
|
+
const hashBuffer = yield crypto.subtle.digest(algorithm, data);
|
|
361
|
+
const hashArray = Array.from(new Uint8Array(hashBuffer));
|
|
362
|
+
const hashHex = hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
363
|
+
return hashHex;
|
|
364
|
+
});
|
|
307
365
|
}
|
|
308
366
|
function randomId(length = 16, radix = 16, enhancedEntropy = false, randomCase = true) {
|
|
309
367
|
if (length < 1)
|
|
@@ -331,35 +389,38 @@ function randomId(length = 16, radix = 16, enhancedEntropy = false, randomCase =
|
|
|
331
389
|
}
|
|
332
390
|
|
|
333
391
|
// lib/misc.ts
|
|
334
|
-
|
|
335
|
-
return
|
|
392
|
+
function consumeGen(valGen) {
|
|
393
|
+
return __async(this, null, function* () {
|
|
394
|
+
return yield typeof valGen === "function" ? valGen() : valGen;
|
|
395
|
+
});
|
|
336
396
|
}
|
|
337
|
-
|
|
338
|
-
return
|
|
339
|
-
typeof strGen === "
|
|
340
|
-
|
|
397
|
+
function consumeStringGen(strGen) {
|
|
398
|
+
return __async(this, null, function* () {
|
|
399
|
+
return typeof strGen === "string" ? strGen : String(
|
|
400
|
+
typeof strGen === "function" ? yield strGen() : strGen
|
|
401
|
+
);
|
|
402
|
+
});
|
|
341
403
|
}
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
}
|
|
404
|
+
function fetchAdvanced(_0) {
|
|
405
|
+
return __async(this, arguments, function* (input, options = {}) {
|
|
406
|
+
const { timeout = 1e4 } = options;
|
|
407
|
+
const ctl = new AbortController();
|
|
408
|
+
const _a = options, { signal } = _a, restOpts = __objRest(_a, ["signal"]);
|
|
409
|
+
signal == null ? void 0 : signal.addEventListener("abort", () => ctl.abort());
|
|
410
|
+
let sigOpts = {}, id = void 0;
|
|
411
|
+
if (timeout >= 0) {
|
|
412
|
+
id = setTimeout(() => ctl.abort(), timeout);
|
|
413
|
+
sigOpts = { signal: ctl.signal };
|
|
414
|
+
}
|
|
415
|
+
try {
|
|
416
|
+
const res = yield fetch(input, __spreadValues(__spreadValues({}, restOpts), sigOpts));
|
|
417
|
+
typeof id !== "undefined" && clearTimeout(id);
|
|
418
|
+
return res;
|
|
419
|
+
} catch (err) {
|
|
420
|
+
typeof id !== "undefined" && clearTimeout(id);
|
|
421
|
+
throw new Error("Error while calling fetch", { cause: err });
|
|
422
|
+
}
|
|
423
|
+
});
|
|
363
424
|
}
|
|
364
425
|
function getListLength(listLike, zeroOnInvalid = true) {
|
|
365
426
|
return "length" in listLike ? listLike.length : "size" in listLike ? listLike.size : "count" in listLike ? listLike.count : zeroOnInvalid ? 0 : NaN;
|
|
@@ -374,7 +435,7 @@ function pauseFor(time, signal, rejectOnAbort = false) {
|
|
|
374
435
|
});
|
|
375
436
|
}
|
|
376
437
|
function pureObj(obj) {
|
|
377
|
-
return Object.assign(/* @__PURE__ */ Object.create(null), obj
|
|
438
|
+
return Object.assign(/* @__PURE__ */ Object.create(null), obj != null ? obj : {});
|
|
378
439
|
}
|
|
379
440
|
function setImmediateInterval(callback, interval, signal) {
|
|
380
441
|
let intervalId;
|
|
@@ -391,15 +452,27 @@ function setImmediateInterval(callback, interval, signal) {
|
|
|
391
452
|
function setImmediateTimeoutLoop(callback, interval, signal) {
|
|
392
453
|
let timeout;
|
|
393
454
|
const cleanup = () => clearTimeout(timeout);
|
|
394
|
-
const loop =
|
|
455
|
+
const loop = () => __async(null, null, function* () {
|
|
395
456
|
if (signal == null ? void 0 : signal.aborted)
|
|
396
457
|
return cleanup();
|
|
397
|
-
|
|
458
|
+
yield callback();
|
|
398
459
|
timeout = setTimeout(loop, interval);
|
|
399
|
-
};
|
|
460
|
+
});
|
|
400
461
|
signal == null ? void 0 : signal.addEventListener("abort", cleanup);
|
|
401
462
|
loop();
|
|
402
463
|
}
|
|
464
|
+
function scheduleExit(code = 0, timeout = 0) {
|
|
465
|
+
if (timeout < 0)
|
|
466
|
+
throw new TypeError("Timeout must be a non-negative number");
|
|
467
|
+
let exit;
|
|
468
|
+
if (typeof process !== "undefined" && "exit" in process)
|
|
469
|
+
exit = () => process.exit(code);
|
|
470
|
+
else if (typeof Deno !== "undefined" && "exit" in Deno)
|
|
471
|
+
exit = () => Deno.exit(code);
|
|
472
|
+
else
|
|
473
|
+
throw new Error("Cannot exit the process, no exit method available");
|
|
474
|
+
setTimeout(exit, timeout);
|
|
475
|
+
}
|
|
403
476
|
|
|
404
477
|
// lib/text.ts
|
|
405
478
|
function autoPlural(term, num, pluralType = "auto") {
|
|
@@ -451,9 +524,9 @@ function createProgressBar(percentage, barLength, chars = defaultPbChars) {
|
|
|
451
524
|
}
|
|
452
525
|
function insertValues(input, ...values) {
|
|
453
526
|
return input.replace(/%\d/gm, (match) => {
|
|
454
|
-
var _a;
|
|
527
|
+
var _a, _b;
|
|
455
528
|
const argIndex = Number(match.substring(1)) - 1;
|
|
456
|
-
return (_a = values[argIndex]
|
|
529
|
+
return (_b = (_a = values[argIndex]) != null ? _a : match) == null ? void 0 : _b.toString();
|
|
457
530
|
});
|
|
458
531
|
}
|
|
459
532
|
function joinArrayReadable(array, separators = ", ", lastSeparator = " and ") {
|
|
@@ -482,16 +555,17 @@ function secsToTimeStr(seconds) {
|
|
|
482
555
|
].join("");
|
|
483
556
|
}
|
|
484
557
|
function truncStr(input, length, endStr = "...") {
|
|
485
|
-
|
|
558
|
+
var _a;
|
|
559
|
+
const str = (_a = input == null ? void 0 : input.toString()) != null ? _a : String(input);
|
|
486
560
|
const finalStr = str.length > length ? str.substring(0, length - endStr.length) + endStr : str;
|
|
487
561
|
return finalStr.length > length ? finalStr.substring(0, length) : finalStr;
|
|
488
562
|
}
|
|
489
563
|
|
|
490
564
|
// lib/Errors.ts
|
|
491
565
|
var DatedError = class extends Error {
|
|
492
|
-
date;
|
|
493
566
|
constructor(message, options) {
|
|
494
567
|
super(message, options);
|
|
568
|
+
__publicField(this, "date");
|
|
495
569
|
this.name = this.constructor.name;
|
|
496
570
|
this.date = /* @__PURE__ */ new Date();
|
|
497
571
|
}
|
|
@@ -518,17 +592,6 @@ var ValidationError = class extends DatedError {
|
|
|
518
592
|
// lib/DataStore.ts
|
|
519
593
|
var dsFmtVer = 1;
|
|
520
594
|
var DataStore = class {
|
|
521
|
-
id;
|
|
522
|
-
formatVersion;
|
|
523
|
-
defaultData;
|
|
524
|
-
encodeData;
|
|
525
|
-
decodeData;
|
|
526
|
-
compressionFormat = "deflate-raw";
|
|
527
|
-
engine;
|
|
528
|
-
firstInit = true;
|
|
529
|
-
cachedData;
|
|
530
|
-
migrations;
|
|
531
|
-
migrateIds = [];
|
|
532
595
|
/**
|
|
533
596
|
* Creates an instance of DataStore to manage a sync & async database that is cached in memory and persistently saved across sessions.
|
|
534
597
|
* Supports migrating data from older versions to newer ones and populating the cache with default data if no persistent data is found.
|
|
@@ -540,6 +603,17 @@ var DataStore = class {
|
|
|
540
603
|
* @param opts The options for this DataStore instance
|
|
541
604
|
*/
|
|
542
605
|
constructor(opts) {
|
|
606
|
+
__publicField(this, "id");
|
|
607
|
+
__publicField(this, "formatVersion");
|
|
608
|
+
__publicField(this, "defaultData");
|
|
609
|
+
__publicField(this, "encodeData");
|
|
610
|
+
__publicField(this, "decodeData");
|
|
611
|
+
__publicField(this, "compressionFormat", "deflate-raw");
|
|
612
|
+
__publicField(this, "engine");
|
|
613
|
+
__publicField(this, "firstInit", true);
|
|
614
|
+
__publicField(this, "cachedData");
|
|
615
|
+
__publicField(this, "migrations");
|
|
616
|
+
__publicField(this, "migrateIds", []);
|
|
543
617
|
this.id = opts.id;
|
|
544
618
|
this.formatVersion = opts.formatVersion;
|
|
545
619
|
this.defaultData = opts.defaultData;
|
|
@@ -553,8 +627,12 @@ var DataStore = class {
|
|
|
553
627
|
if (typeof opts.compressionFormat === "undefined")
|
|
554
628
|
opts.compressionFormat = "deflate-raw";
|
|
555
629
|
if (typeof opts.compressionFormat === "string") {
|
|
556
|
-
this.encodeData = [opts.compressionFormat,
|
|
557
|
-
|
|
630
|
+
this.encodeData = [opts.compressionFormat, (data) => __async(this, null, function* () {
|
|
631
|
+
return yield compress(data, opts.compressionFormat, "string");
|
|
632
|
+
})];
|
|
633
|
+
this.decodeData = [opts.compressionFormat, (data) => __async(this, null, function* () {
|
|
634
|
+
return yield compress(data, opts.compressionFormat, "string");
|
|
635
|
+
})];
|
|
558
636
|
} else if ("encodeData" in opts && "decodeData" in opts && Array.isArray(opts.encodeData) && Array.isArray(opts.decodeData)) {
|
|
559
637
|
this.encodeData = [opts.encodeData[0], opts.encodeData[1]];
|
|
560
638
|
this.decodeData = [opts.decodeData[0], opts.decodeData[1]];
|
|
@@ -571,56 +649,58 @@ var DataStore = class {
|
|
|
571
649
|
* Automatically populates persistent storage with default data if it doesn't contain any data yet.
|
|
572
650
|
* Also runs all necessary migration functions if the data format has changed since the last time the data was saved.
|
|
573
651
|
*/
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
this.firstInit
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
652
|
+
loadData() {
|
|
653
|
+
return __async(this, null, function* () {
|
|
654
|
+
try {
|
|
655
|
+
if (this.firstInit) {
|
|
656
|
+
this.firstInit = false;
|
|
657
|
+
const dsVer = Number(yield this.engine.getValue("__ds_fmt_ver", 0));
|
|
658
|
+
if (isNaN(dsVer) || dsVer < 1) {
|
|
659
|
+
const oldData = yield this.engine.getValue(`_uucfg-${this.id}`, null);
|
|
660
|
+
if (oldData) {
|
|
661
|
+
const oldVer = Number(yield this.engine.getValue(`_uucfgver-${this.id}`, NaN));
|
|
662
|
+
const oldEnc = yield this.engine.getValue(`_uucfgenc-${this.id}`, null);
|
|
663
|
+
const promises = [];
|
|
664
|
+
const migrateFmt = (oldKey, newKey, value) => {
|
|
665
|
+
promises.push(this.engine.setValue(newKey, value));
|
|
666
|
+
promises.push(this.engine.deleteValue(oldKey));
|
|
667
|
+
};
|
|
668
|
+
oldData && migrateFmt(`_uucfg-${this.id}`, `__ds-${this.id}-dat`, oldData);
|
|
669
|
+
!isNaN(oldVer) && migrateFmt(`_uucfgver-${this.id}`, `__ds-${this.id}-ver`, oldVer);
|
|
670
|
+
typeof oldEnc === "boolean" && migrateFmt(`_uucfgenc-${this.id}`, `__ds-${this.id}-enc`, oldEnc === true ? this.compressionFormat : null);
|
|
671
|
+
yield Promise.allSettled(promises);
|
|
672
|
+
}
|
|
673
|
+
yield this.engine.setValue("__ds_fmt_ver", dsFmtVer);
|
|
593
674
|
}
|
|
594
|
-
await this.engine.setValue("__ds_fmt_ver", dsFmtVer);
|
|
595
675
|
}
|
|
676
|
+
if (this.migrateIds.length > 0) {
|
|
677
|
+
yield this.migrateId(this.migrateIds);
|
|
678
|
+
this.migrateIds = [];
|
|
679
|
+
}
|
|
680
|
+
const gmData = yield this.engine.getValue(`__ds-${this.id}-dat`, JSON.stringify(this.defaultData));
|
|
681
|
+
let gmFmtVer = Number(yield this.engine.getValue(`__ds-${this.id}-ver`, NaN));
|
|
682
|
+
if (typeof gmData !== "string") {
|
|
683
|
+
yield this.saveDefaultData();
|
|
684
|
+
return __spreadValues({}, this.defaultData);
|
|
685
|
+
}
|
|
686
|
+
const isEncoded = Boolean(yield this.engine.getValue(`__ds-${this.id}-enc`, false));
|
|
687
|
+
let saveData = false;
|
|
688
|
+
if (isNaN(gmFmtVer)) {
|
|
689
|
+
yield this.engine.setValue(`__ds-${this.id}-ver`, gmFmtVer = this.formatVersion);
|
|
690
|
+
saveData = true;
|
|
691
|
+
}
|
|
692
|
+
let parsed = yield this.engine.deserializeData(gmData, isEncoded);
|
|
693
|
+
if (gmFmtVer < this.formatVersion && this.migrations)
|
|
694
|
+
parsed = yield this.runMigrations(parsed, gmFmtVer);
|
|
695
|
+
if (saveData)
|
|
696
|
+
yield this.setData(parsed);
|
|
697
|
+
return this.cachedData = this.engine.deepCopy(parsed);
|
|
698
|
+
} catch (err) {
|
|
699
|
+
console.warn("Error while parsing JSON data, resetting it to the default value.", err);
|
|
700
|
+
yield this.saveDefaultData();
|
|
701
|
+
return this.defaultData;
|
|
596
702
|
}
|
|
597
|
-
|
|
598
|
-
await this.migrateId(this.migrateIds);
|
|
599
|
-
this.migrateIds = [];
|
|
600
|
-
}
|
|
601
|
-
const gmData = await this.engine.getValue(`__ds-${this.id}-dat`, JSON.stringify(this.defaultData));
|
|
602
|
-
let gmFmtVer = Number(await this.engine.getValue(`__ds-${this.id}-ver`, NaN));
|
|
603
|
-
if (typeof gmData !== "string") {
|
|
604
|
-
await this.saveDefaultData();
|
|
605
|
-
return { ...this.defaultData };
|
|
606
|
-
}
|
|
607
|
-
const isEncoded = Boolean(await this.engine.getValue(`__ds-${this.id}-enc`, false));
|
|
608
|
-
let saveData = false;
|
|
609
|
-
if (isNaN(gmFmtVer)) {
|
|
610
|
-
await this.engine.setValue(`__ds-${this.id}-ver`, gmFmtVer = this.formatVersion);
|
|
611
|
-
saveData = true;
|
|
612
|
-
}
|
|
613
|
-
let parsed = await this.engine.deserializeData(gmData, isEncoded);
|
|
614
|
-
if (gmFmtVer < this.formatVersion && this.migrations)
|
|
615
|
-
parsed = await this.runMigrations(parsed, gmFmtVer);
|
|
616
|
-
if (saveData)
|
|
617
|
-
await this.setData(parsed);
|
|
618
|
-
return this.cachedData = this.engine.deepCopy(parsed);
|
|
619
|
-
} catch (err) {
|
|
620
|
-
console.warn("Error while parsing JSON data, resetting it to the default value.", err);
|
|
621
|
-
await this.saveDefaultData();
|
|
622
|
-
return this.defaultData;
|
|
623
|
-
}
|
|
703
|
+
});
|
|
624
704
|
}
|
|
625
705
|
/**
|
|
626
706
|
* Returns a copy of the data from the in-memory cache.
|
|
@@ -633,24 +713,26 @@ var DataStore = class {
|
|
|
633
713
|
setData(data) {
|
|
634
714
|
this.cachedData = data;
|
|
635
715
|
const useEncoding = this.encodingEnabled();
|
|
636
|
-
return new Promise(
|
|
637
|
-
|
|
638
|
-
this.engine.setValue(`__ds-${this.id}-dat`,
|
|
716
|
+
return new Promise((resolve) => __async(this, null, function* () {
|
|
717
|
+
yield Promise.allSettled([
|
|
718
|
+
this.engine.setValue(`__ds-${this.id}-dat`, yield this.engine.serializeData(data, useEncoding)),
|
|
639
719
|
this.engine.setValue(`__ds-${this.id}-ver`, this.formatVersion),
|
|
640
720
|
this.engine.setValue(`__ds-${this.id}-enc`, useEncoding)
|
|
641
721
|
]);
|
|
642
722
|
resolve();
|
|
643
|
-
});
|
|
723
|
+
}));
|
|
644
724
|
}
|
|
645
725
|
/** Saves the default data passed in the constructor synchronously to the in-memory cache and asynchronously to persistent storage */
|
|
646
|
-
|
|
647
|
-
this
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
726
|
+
saveDefaultData() {
|
|
727
|
+
return __async(this, null, function* () {
|
|
728
|
+
this.cachedData = this.defaultData;
|
|
729
|
+
const useEncoding = this.encodingEnabled();
|
|
730
|
+
yield Promise.allSettled([
|
|
731
|
+
this.engine.setValue(`__ds-${this.id}-dat`, yield this.engine.serializeData(this.defaultData, useEncoding)),
|
|
732
|
+
this.engine.setValue(`__ds-${this.id}-ver`, this.formatVersion),
|
|
733
|
+
this.engine.setValue(`__ds-${this.id}-enc`, useEncoding)
|
|
734
|
+
]);
|
|
735
|
+
});
|
|
654
736
|
}
|
|
655
737
|
/**
|
|
656
738
|
* Call this method to clear all persistently stored data associated with this DataStore instance.
|
|
@@ -659,12 +741,14 @@ var DataStore = class {
|
|
|
659
741
|
*
|
|
660
742
|
* - ⚠️ This requires the additional directive `@grant GM.deleteValue` if the storageMethod is left as the default of `"GM"`
|
|
661
743
|
*/
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
744
|
+
deleteData() {
|
|
745
|
+
return __async(this, null, function* () {
|
|
746
|
+
yield Promise.allSettled([
|
|
747
|
+
this.engine.deleteValue(`__ds-${this.id}-dat`),
|
|
748
|
+
this.engine.deleteValue(`__ds-${this.id}-ver`),
|
|
749
|
+
this.engine.deleteValue(`__ds-${this.id}-enc`)
|
|
750
|
+
]);
|
|
751
|
+
});
|
|
668
752
|
}
|
|
669
753
|
/** Returns whether encoding and decoding are enabled for this DataStore instance */
|
|
670
754
|
encodingEnabled() {
|
|
@@ -678,62 +762,68 @@ var DataStore = class {
|
|
|
678
762
|
*
|
|
679
763
|
* 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.
|
|
680
764
|
*/
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
const
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
765
|
+
runMigrations(oldData, oldFmtVer, resetOnError = true) {
|
|
766
|
+
return __async(this, null, function* () {
|
|
767
|
+
if (!this.migrations)
|
|
768
|
+
return oldData;
|
|
769
|
+
let newData = oldData;
|
|
770
|
+
const sortedMigrations = Object.entries(this.migrations).sort(([a], [b]) => Number(a) - Number(b));
|
|
771
|
+
let lastFmtVer = oldFmtVer;
|
|
772
|
+
for (const [fmtVer, migrationFunc] of sortedMigrations) {
|
|
773
|
+
const ver = Number(fmtVer);
|
|
774
|
+
if (oldFmtVer < this.formatVersion && oldFmtVer < ver) {
|
|
775
|
+
try {
|
|
776
|
+
const migRes = migrationFunc(newData);
|
|
777
|
+
newData = migRes instanceof Promise ? yield migRes : migRes;
|
|
778
|
+
lastFmtVer = oldFmtVer = ver;
|
|
779
|
+
} catch (err) {
|
|
780
|
+
if (!resetOnError)
|
|
781
|
+
throw new MigrationError(`Error while running migration function for format version '${fmtVer}'`, { cause: err });
|
|
782
|
+
yield this.saveDefaultData();
|
|
783
|
+
return this.getData();
|
|
784
|
+
}
|
|
699
785
|
}
|
|
700
786
|
}
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
787
|
+
yield Promise.allSettled([
|
|
788
|
+
this.engine.setValue(`__ds-${this.id}-dat`, yield this.engine.serializeData(newData)),
|
|
789
|
+
this.engine.setValue(`__ds-${this.id}-ver`, lastFmtVer),
|
|
790
|
+
this.engine.setValue(`__ds-${this.id}-enc`, this.encodingEnabled())
|
|
791
|
+
]);
|
|
792
|
+
return this.cachedData = __spreadValues({}, newData);
|
|
793
|
+
});
|
|
708
794
|
}
|
|
709
795
|
/**
|
|
710
796
|
* Tries to migrate the currently saved persistent data from one or more old IDs to the ID set in the constructor.
|
|
711
797
|
* 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.
|
|
712
798
|
*/
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
799
|
+
migrateId(oldIds) {
|
|
800
|
+
return __async(this, null, function* () {
|
|
801
|
+
const ids = Array.isArray(oldIds) ? oldIds : [oldIds];
|
|
802
|
+
yield Promise.all(ids.map((id) => __async(this, null, function* () {
|
|
803
|
+
const data = yield this.engine.getValue(`__ds-${id}-dat`, JSON.stringify(this.defaultData));
|
|
804
|
+
const fmtVer = Number(yield this.engine.getValue(`__ds-${id}-ver`, NaN));
|
|
805
|
+
const isEncoded = Boolean(yield this.engine.getValue(`__ds-${id}-enc`, false));
|
|
806
|
+
if (data === void 0 || isNaN(fmtVer))
|
|
807
|
+
return;
|
|
808
|
+
const parsed = yield this.engine.deserializeData(data, isEncoded);
|
|
809
|
+
yield Promise.allSettled([
|
|
810
|
+
this.engine.setValue(`__ds-${this.id}-dat`, yield this.engine.serializeData(parsed)),
|
|
811
|
+
this.engine.setValue(`__ds-${this.id}-ver`, fmtVer),
|
|
812
|
+
this.engine.setValue(`__ds-${this.id}-enc`, isEncoded),
|
|
813
|
+
this.engine.deleteValue(`__ds-${id}-dat`),
|
|
814
|
+
this.engine.deleteValue(`__ds-${id}-ver`),
|
|
815
|
+
this.engine.deleteValue(`__ds-${id}-enc`)
|
|
816
|
+
]);
|
|
817
|
+
})));
|
|
818
|
+
});
|
|
731
819
|
}
|
|
732
820
|
};
|
|
733
821
|
|
|
734
822
|
// lib/DataStoreEngine.ts
|
|
735
823
|
var DataStoreEngine = class {
|
|
736
|
-
|
|
824
|
+
constructor() {
|
|
825
|
+
__publicField(this, "dataStoreOptions");
|
|
826
|
+
}
|
|
737
827
|
// setDataStoreOptions() is called from inside the DataStore constructor to set this value
|
|
738
828
|
/** Called by DataStore on creation, to pass its options */
|
|
739
829
|
setDataStoreOptions(dataStoreOptions) {
|
|
@@ -741,23 +831,27 @@ var DataStoreEngine = class {
|
|
|
741
831
|
}
|
|
742
832
|
//#region serialization api
|
|
743
833
|
/** Serializes the given object to a string, optionally encoded with `options.encodeData` if {@linkcode useEncoding} is set to true */
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
834
|
+
serializeData(data, useEncoding) {
|
|
835
|
+
return __async(this, null, function* () {
|
|
836
|
+
var _a, _b, _c, _d, _e;
|
|
837
|
+
const stringData = JSON.stringify(data);
|
|
838
|
+
if (!useEncoding || !((_a = this.dataStoreOptions) == null ? void 0 : _a.encodeData) || !((_b = this.dataStoreOptions) == null ? void 0 : _b.decodeData))
|
|
839
|
+
return stringData;
|
|
840
|
+
const encRes = (_e = (_d = (_c = this.dataStoreOptions) == null ? void 0 : _c.encodeData) == null ? void 0 : _d[1]) == null ? void 0 : _e.call(_d, stringData);
|
|
841
|
+
if (encRes instanceof Promise)
|
|
842
|
+
return yield encRes;
|
|
843
|
+
return encRes;
|
|
844
|
+
});
|
|
753
845
|
}
|
|
754
846
|
/** Deserializes the given string to a JSON object, optionally decoded with `options.decodeData` if {@linkcode useEncoding} is set to true */
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
decRes
|
|
760
|
-
|
|
847
|
+
deserializeData(data, useEncoding) {
|
|
848
|
+
return __async(this, null, function* () {
|
|
849
|
+
var _a, _b, _c;
|
|
850
|
+
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;
|
|
851
|
+
if (decRes instanceof Promise)
|
|
852
|
+
decRes = yield decRes;
|
|
853
|
+
return JSON.parse(decRes != null ? decRes : data);
|
|
854
|
+
});
|
|
761
855
|
}
|
|
762
856
|
//#region misc api
|
|
763
857
|
/**
|
|
@@ -768,13 +862,12 @@ var DataStoreEngine = class {
|
|
|
768
862
|
try {
|
|
769
863
|
if ("structuredClone" in globalThis)
|
|
770
864
|
return structuredClone(obj);
|
|
771
|
-
} catch {
|
|
865
|
+
} catch (e) {
|
|
772
866
|
}
|
|
773
867
|
return JSON.parse(JSON.stringify(obj));
|
|
774
868
|
}
|
|
775
869
|
};
|
|
776
870
|
var BrowserStorageEngine = class extends DataStoreEngine {
|
|
777
|
-
options;
|
|
778
871
|
/**
|
|
779
872
|
* Creates an instance of `BrowserStorageEngine`.
|
|
780
873
|
*
|
|
@@ -783,124 +876,143 @@ var BrowserStorageEngine = class extends DataStoreEngine {
|
|
|
783
876
|
*/
|
|
784
877
|
constructor(options) {
|
|
785
878
|
super();
|
|
786
|
-
this
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
};
|
|
879
|
+
__publicField(this, "options");
|
|
880
|
+
this.options = __spreadValues({
|
|
881
|
+
type: "localStorage"
|
|
882
|
+
}, options);
|
|
790
883
|
}
|
|
791
884
|
//#region storage api
|
|
792
885
|
/** Fetches a value from persistent storage */
|
|
793
|
-
|
|
794
|
-
return (this
|
|
886
|
+
getValue(name, defaultValue) {
|
|
887
|
+
return __async(this, null, function* () {
|
|
888
|
+
var _a;
|
|
889
|
+
return (_a = this.options.type === "localStorage" ? globalThis.localStorage.getItem(name) : globalThis.sessionStorage.getItem(name)) != null ? _a : defaultValue;
|
|
890
|
+
});
|
|
795
891
|
}
|
|
796
892
|
/** Sets a value in persistent storage */
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
893
|
+
setValue(name, value) {
|
|
894
|
+
return __async(this, null, function* () {
|
|
895
|
+
if (this.options.type === "localStorage")
|
|
896
|
+
globalThis.localStorage.setItem(name, String(value));
|
|
897
|
+
else
|
|
898
|
+
globalThis.sessionStorage.setItem(name, String(value));
|
|
899
|
+
});
|
|
802
900
|
}
|
|
803
901
|
/** Deletes a value from persistent storage */
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
902
|
+
deleteValue(name) {
|
|
903
|
+
return __async(this, null, function* () {
|
|
904
|
+
if (this.options.type === "localStorage")
|
|
905
|
+
globalThis.localStorage.removeItem(name);
|
|
906
|
+
else
|
|
907
|
+
globalThis.sessionStorage.removeItem(name);
|
|
908
|
+
});
|
|
809
909
|
}
|
|
810
910
|
};
|
|
811
911
|
var fs;
|
|
812
912
|
var FileStorageEngine = class extends DataStoreEngine {
|
|
813
|
-
options;
|
|
814
913
|
/**
|
|
815
914
|
* Creates an instance of `FileStorageEngine`.
|
|
816
915
|
*
|
|
817
|
-
* ⚠️ Requires Node.js or Deno with Node compatibility
|
|
916
|
+
* ⚠️ Requires Node.js or Deno with Node compatibility (v1.31+)
|
|
818
917
|
* ⚠️ Don't reuse this engine across multiple {@linkcode DataStore} instances
|
|
819
918
|
*/
|
|
820
919
|
constructor(options) {
|
|
821
920
|
super();
|
|
822
|
-
this
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
};
|
|
921
|
+
__publicField(this, "options");
|
|
922
|
+
this.options = __spreadValues({
|
|
923
|
+
filePath: (id) => `.ds-${id}`
|
|
924
|
+
}, options);
|
|
826
925
|
}
|
|
827
926
|
//#region json file
|
|
828
927
|
/** Reads the file contents */
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
928
|
+
readFile() {
|
|
929
|
+
return __async(this, null, function* () {
|
|
930
|
+
var _a, _b, _c, _d;
|
|
931
|
+
try {
|
|
932
|
+
if (!fs)
|
|
933
|
+
fs = (yield import("fs/promises")).default;
|
|
934
|
+
if (!fs)
|
|
935
|
+
throw new DatedError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new Error("'node:fs/promises' module not available") });
|
|
936
|
+
const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
|
|
937
|
+
const data = yield fs.readFile(path, "utf-8");
|
|
938
|
+
return data ? JSON.parse((_d = yield (_c = (_b = (_a = this.dataStoreOptions) == null ? void 0 : _a.decodeData) == null ? void 0 : _b[1]) == null ? void 0 : _c.call(_b, data)) != null ? _d : data) : void 0;
|
|
939
|
+
} catch (e) {
|
|
837
940
|
return void 0;
|
|
838
|
-
|
|
839
|
-
}
|
|
840
|
-
return void 0;
|
|
841
|
-
}
|
|
941
|
+
}
|
|
942
|
+
});
|
|
842
943
|
}
|
|
843
944
|
/** Overwrites the file contents */
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
945
|
+
writeFile(data) {
|
|
946
|
+
return __async(this, null, function* () {
|
|
947
|
+
var _a, _b, _c, _d;
|
|
948
|
+
try {
|
|
949
|
+
if (!fs)
|
|
950
|
+
fs = (yield import("fs/promises")).default;
|
|
951
|
+
if (!fs)
|
|
952
|
+
throw new DatedError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new Error("'node:fs/promises' module not available") });
|
|
953
|
+
const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
|
|
954
|
+
yield fs.mkdir(path.slice(0, path.lastIndexOf("/")), { recursive: true });
|
|
955
|
+
yield fs.writeFile(path, (_d = yield (_c = (_b = (_a = this.dataStoreOptions) == null ? void 0 : _a.encodeData) == null ? void 0 : _b[1]) == null ? void 0 : _c.call(_b, JSON.stringify(data))) != null ? _d : JSON.stringify(data, void 0, 2), "utf-8");
|
|
956
|
+
} catch (err) {
|
|
957
|
+
console.error("Error writing file:", err);
|
|
958
|
+
}
|
|
959
|
+
});
|
|
855
960
|
}
|
|
856
961
|
//#region storage api
|
|
857
962
|
/** Fetches a value from persistent storage */
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
963
|
+
getValue(name, defaultValue) {
|
|
964
|
+
return __async(this, null, function* () {
|
|
965
|
+
const data = yield this.readFile();
|
|
966
|
+
if (!data)
|
|
967
|
+
return defaultValue;
|
|
968
|
+
const value = data == null ? void 0 : data[name];
|
|
969
|
+
if (value === void 0)
|
|
970
|
+
return defaultValue;
|
|
971
|
+
if (typeof value === "string")
|
|
972
|
+
return value;
|
|
973
|
+
return String(value != null ? value : defaultValue);
|
|
974
|
+
});
|
|
868
975
|
}
|
|
869
976
|
/** Sets a value in persistent storage */
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
data
|
|
874
|
-
|
|
875
|
-
|
|
977
|
+
setValue(name, value) {
|
|
978
|
+
return __async(this, null, function* () {
|
|
979
|
+
let data = yield this.readFile();
|
|
980
|
+
if (!data)
|
|
981
|
+
data = {};
|
|
982
|
+
data[name] = value;
|
|
983
|
+
yield this.writeFile(data);
|
|
984
|
+
});
|
|
876
985
|
}
|
|
877
986
|
/** Deletes a value from persistent storage */
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
987
|
+
deleteValue(name) {
|
|
988
|
+
return __async(this, null, function* () {
|
|
989
|
+
const data = yield this.readFile();
|
|
990
|
+
if (!data)
|
|
991
|
+
return;
|
|
992
|
+
delete data[name];
|
|
993
|
+
yield this.writeFile(data);
|
|
994
|
+
});
|
|
884
995
|
}
|
|
885
996
|
};
|
|
886
997
|
|
|
887
998
|
// lib/DataStoreSerializer.ts
|
|
888
999
|
var DataStoreSerializer = class _DataStoreSerializer {
|
|
889
|
-
stores;
|
|
890
|
-
options;
|
|
891
1000
|
constructor(stores, options = {}) {
|
|
1001
|
+
__publicField(this, "stores");
|
|
1002
|
+
__publicField(this, "options");
|
|
892
1003
|
if (!crypto || !crypto.subtle)
|
|
893
1004
|
throw new Error("DataStoreSerializer has to run in a secure context (HTTPS) or in another environment that implements the subtleCrypto API!");
|
|
894
1005
|
this.stores = stores;
|
|
895
|
-
this.options = {
|
|
1006
|
+
this.options = __spreadValues({
|
|
896
1007
|
addChecksum: true,
|
|
897
|
-
ensureIntegrity: true
|
|
898
|
-
|
|
899
|
-
};
|
|
1008
|
+
ensureIntegrity: true
|
|
1009
|
+
}, options);
|
|
900
1010
|
}
|
|
901
1011
|
/** Calculates the checksum of a string */
|
|
902
|
-
|
|
903
|
-
return
|
|
1012
|
+
calcChecksum(input) {
|
|
1013
|
+
return __async(this, null, function* () {
|
|
1014
|
+
return computeHash(input, "SHA-256");
|
|
1015
|
+
});
|
|
904
1016
|
}
|
|
905
1017
|
/**
|
|
906
1018
|
* Serializes only a subset of the data stores into a string.
|
|
@@ -908,60 +1020,68 @@ var DataStoreSerializer = class _DataStoreSerializer {
|
|
|
908
1020
|
* @param useEncoding Whether to encode the data using each DataStore's `encodeData()` method
|
|
909
1021
|
* @param stringified Whether to return the result as a string or as an array of `SerializedDataStore` objects
|
|
910
1022
|
*/
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
const
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
1023
|
+
serializePartial(stores, useEncoding = true, stringified = true) {
|
|
1024
|
+
return __async(this, null, function* () {
|
|
1025
|
+
const serData = [];
|
|
1026
|
+
for (const storeInst of this.stores.filter((s) => typeof stores === "function" ? stores(s.id) : stores.includes(s.id))) {
|
|
1027
|
+
const data = useEncoding && storeInst.encodingEnabled() ? yield storeInst.encodeData[1](JSON.stringify(storeInst.getData())) : JSON.stringify(storeInst.getData());
|
|
1028
|
+
serData.push({
|
|
1029
|
+
id: storeInst.id,
|
|
1030
|
+
data,
|
|
1031
|
+
formatVersion: storeInst.formatVersion,
|
|
1032
|
+
encoded: useEncoding && storeInst.encodingEnabled(),
|
|
1033
|
+
checksum: this.options.addChecksum ? yield this.calcChecksum(data) : void 0
|
|
1034
|
+
});
|
|
1035
|
+
}
|
|
1036
|
+
return stringified ? JSON.stringify(serData) : serData;
|
|
1037
|
+
});
|
|
924
1038
|
}
|
|
925
1039
|
/**
|
|
926
1040
|
* Serializes the data stores into a string.
|
|
927
1041
|
* @param useEncoding Whether to encode the data using each DataStore's `encodeData()` method
|
|
928
1042
|
* @param stringified Whether to return the result as a string or as an array of `SerializedDataStore` objects
|
|
929
1043
|
*/
|
|
930
|
-
|
|
931
|
-
return
|
|
1044
|
+
serialize(useEncoding = true, stringified = true) {
|
|
1045
|
+
return __async(this, null, function* () {
|
|
1046
|
+
return this.serializePartial(this.stores.map((s) => s.id), useEncoding, stringified);
|
|
1047
|
+
});
|
|
932
1048
|
}
|
|
933
1049
|
/**
|
|
934
1050
|
* Deserializes the data exported via {@linkcode serialize()} and imports only a subset into the DataStore instances.
|
|
935
1051
|
* Also triggers the migration process if the data format has changed.
|
|
936
1052
|
*/
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
const
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
1053
|
+
deserializePartial(stores, data) {
|
|
1054
|
+
return __async(this, null, function* () {
|
|
1055
|
+
const deserStores = typeof data === "string" ? JSON.parse(data) : data;
|
|
1056
|
+
if (!Array.isArray(deserStores) || !deserStores.every(_DataStoreSerializer.isSerializedDataStoreObj))
|
|
1057
|
+
throw new TypeError("Invalid serialized data format! Expected an array of SerializedDataStore objects.");
|
|
1058
|
+
for (const storeData of deserStores.filter((s) => typeof stores === "function" ? stores(s.id) : stores.includes(s.id))) {
|
|
1059
|
+
const storeInst = this.stores.find((s) => s.id === storeData.id);
|
|
1060
|
+
if (!storeInst)
|
|
1061
|
+
throw new Error(`DataStore instance with ID "${storeData.id}" not found! Make sure to provide it in the DataStoreSerializer constructor.`);
|
|
1062
|
+
if (this.options.ensureIntegrity && typeof storeData.checksum === "string") {
|
|
1063
|
+
const checksum = yield this.calcChecksum(storeData.data);
|
|
1064
|
+
if (checksum !== storeData.checksum)
|
|
1065
|
+
throw new ChecksumMismatchError(`Checksum mismatch for DataStore with ID "${storeData.id}"!
|
|
949
1066
|
Expected: ${storeData.checksum}
|
|
950
1067
|
Has: ${checksum}`);
|
|
1068
|
+
}
|
|
1069
|
+
const decodedData = storeData.encoded && storeInst.encodingEnabled() ? yield storeInst.decodeData[1](storeData.data) : storeData.data;
|
|
1070
|
+
if (storeData.formatVersion && !isNaN(Number(storeData.formatVersion)) && Number(storeData.formatVersion) < storeInst.formatVersion)
|
|
1071
|
+
yield storeInst.runMigrations(JSON.parse(decodedData), Number(storeData.formatVersion), false);
|
|
1072
|
+
else
|
|
1073
|
+
yield storeInst.setData(JSON.parse(decodedData));
|
|
951
1074
|
}
|
|
952
|
-
|
|
953
|
-
if (storeData.formatVersion && !isNaN(Number(storeData.formatVersion)) && Number(storeData.formatVersion) < storeInst.formatVersion)
|
|
954
|
-
await storeInst.runMigrations(JSON.parse(decodedData), Number(storeData.formatVersion), false);
|
|
955
|
-
else
|
|
956
|
-
await storeInst.setData(JSON.parse(decodedData));
|
|
957
|
-
}
|
|
1075
|
+
});
|
|
958
1076
|
}
|
|
959
1077
|
/**
|
|
960
1078
|
* Deserializes the data exported via {@linkcode serialize()} and imports the data into all matching DataStore instances.
|
|
961
1079
|
* Also triggers the migration process if the data format has changed.
|
|
962
1080
|
*/
|
|
963
|
-
|
|
964
|
-
return
|
|
1081
|
+
deserialize(data) {
|
|
1082
|
+
return __async(this, null, function* () {
|
|
1083
|
+
return this.deserializePartial(this.stores.map((s) => s.id), data);
|
|
1084
|
+
});
|
|
965
1085
|
}
|
|
966
1086
|
/**
|
|
967
1087
|
* Loads the persistent data of the DataStore instances into the in-memory cache.
|
|
@@ -969,32 +1089,40 @@ Has: ${checksum}`);
|
|
|
969
1089
|
* @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
|
|
970
1090
|
* @returns Returns a PromiseSettledResult array with the results of each DataStore instance in the format `{ id: string, data: object }`
|
|
971
1091
|
*/
|
|
972
|
-
|
|
973
|
-
return
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
1092
|
+
loadStoresData(stores) {
|
|
1093
|
+
return __async(this, null, function* () {
|
|
1094
|
+
return Promise.allSettled(
|
|
1095
|
+
this.getStoresFiltered(stores).map((store) => __async(this, null, function* () {
|
|
1096
|
+
return {
|
|
1097
|
+
id: store.id,
|
|
1098
|
+
data: yield store.loadData()
|
|
1099
|
+
};
|
|
1100
|
+
}))
|
|
1101
|
+
);
|
|
1102
|
+
});
|
|
979
1103
|
}
|
|
980
1104
|
/**
|
|
981
1105
|
* Resets the persistent and in-memory data of the DataStore instances to their default values.
|
|
982
1106
|
* @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
|
|
983
1107
|
*/
|
|
984
|
-
|
|
985
|
-
return
|
|
986
|
-
|
|
987
|
-
|
|
1108
|
+
resetStoresData(stores) {
|
|
1109
|
+
return __async(this, null, function* () {
|
|
1110
|
+
return Promise.allSettled(
|
|
1111
|
+
this.getStoresFiltered(stores).map((store) => store.saveDefaultData())
|
|
1112
|
+
);
|
|
1113
|
+
});
|
|
988
1114
|
}
|
|
989
1115
|
/**
|
|
990
1116
|
* Deletes the persistent data of the DataStore instances.
|
|
991
1117
|
* Leaves the in-memory data untouched.
|
|
992
1118
|
* @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
|
|
993
1119
|
*/
|
|
994
|
-
|
|
995
|
-
return
|
|
996
|
-
|
|
997
|
-
|
|
1120
|
+
deleteStoresData(stores) {
|
|
1121
|
+
return __async(this, null, function* () {
|
|
1122
|
+
return Promise.allSettled(
|
|
1123
|
+
this.getStoresFiltered(stores).map((store) => store.deleteData())
|
|
1124
|
+
);
|
|
1125
|
+
});
|
|
998
1126
|
}
|
|
999
1127
|
/** Checks if a given value is an array of SerializedDataStore objects */
|
|
1000
1128
|
static isSerializedDataStoreObjArray(obj) {
|
|
@@ -1019,26 +1147,26 @@ var createNanoEvents = () => ({
|
|
|
1019
1147
|
},
|
|
1020
1148
|
events: {},
|
|
1021
1149
|
on(event, cb) {
|
|
1150
|
+
var _a;
|
|
1022
1151
|
;
|
|
1023
|
-
(this.events[event]
|
|
1152
|
+
((_a = this.events)[event] || (_a[event] = [])).push(cb);
|
|
1024
1153
|
return () => {
|
|
1025
|
-
var
|
|
1026
|
-
this.events[event] = (
|
|
1154
|
+
var _a2;
|
|
1155
|
+
this.events[event] = (_a2 = this.events[event]) == null ? void 0 : _a2.filter((i) => cb !== i);
|
|
1027
1156
|
};
|
|
1028
1157
|
}
|
|
1029
1158
|
});
|
|
1030
1159
|
|
|
1031
1160
|
// lib/NanoEmitter.ts
|
|
1032
1161
|
var NanoEmitter = class {
|
|
1033
|
-
events = createNanoEvents();
|
|
1034
|
-
eventUnsubscribes = [];
|
|
1035
|
-
emitterOptions;
|
|
1036
1162
|
/** Creates a new instance of NanoEmitter - a lightweight event emitter with helper methods and a strongly typed event map */
|
|
1037
1163
|
constructor(options = {}) {
|
|
1038
|
-
this
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1164
|
+
__publicField(this, "events", createNanoEvents());
|
|
1165
|
+
__publicField(this, "eventUnsubscribes", []);
|
|
1166
|
+
__publicField(this, "emitterOptions");
|
|
1167
|
+
this.emitterOptions = __spreadValues({
|
|
1168
|
+
publicEmit: false
|
|
1169
|
+
}, options);
|
|
1042
1170
|
}
|
|
1043
1171
|
/**
|
|
1044
1172
|
* Subscribes to an event and calls the callback when it's emitted.
|
|
@@ -1136,13 +1264,13 @@ var Debouncer = class extends NanoEmitter {
|
|
|
1136
1264
|
super();
|
|
1137
1265
|
this.timeout = timeout;
|
|
1138
1266
|
this.type = type;
|
|
1267
|
+
/** All registered listener functions and the time they were attached */
|
|
1268
|
+
__publicField(this, "listeners", []);
|
|
1269
|
+
/** The currently active timeout */
|
|
1270
|
+
__publicField(this, "activeTimeout");
|
|
1271
|
+
/** The latest queued call */
|
|
1272
|
+
__publicField(this, "queuedCall");
|
|
1139
1273
|
}
|
|
1140
|
-
/** All registered listener functions and the time they were attached */
|
|
1141
|
-
listeners = [];
|
|
1142
|
-
/** The currently active timeout */
|
|
1143
|
-
activeTimeout;
|
|
1144
|
-
/** The latest queued call */
|
|
1145
|
-
queuedCall;
|
|
1146
1274
|
//#region listeners
|
|
1147
1275
|
/** Adds a listener function that will be called on timeout */
|
|
1148
1276
|
addListener(fn) {
|
|
@@ -1229,6 +1357,8 @@ function debounce(fn, timeout = 200, type = "immediate") {
|
|
|
1229
1357
|
return func;
|
|
1230
1358
|
}
|
|
1231
1359
|
|
|
1360
|
+
if(__exports != exports)module.exports = exports;return module.exports}));
|
|
1361
|
+
|
|
1232
1362
|
|
|
1233
1363
|
|
|
1234
1364
|
if (typeof module.exports == "object" && typeof exports == "object") {
|