@sv443-network/coreutils 3.0.8 → 3.2.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 +12 -0
- package/dist/CoreUtils.cjs +34 -32
- package/dist/CoreUtils.min.cjs +3 -3
- package/dist/CoreUtils.min.mjs +3 -3
- package/dist/CoreUtils.min.umd.js +3 -3
- package/dist/CoreUtils.mjs +34 -32
- package/dist/CoreUtils.umd.js +606 -552
- package/dist/lib/DataStore.d.ts +6 -0
- package/dist/lib/DataStoreEngine.d.ts +1 -1
- package/package.json +5 -5
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,37 +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
|
-
|
|
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
|
+
}
|
|
485
425
|
}
|
|
486
426
|
function getListLength(listLike, zeroOnInvalid = true) {
|
|
487
427
|
return "length" in listLike ? listLike.length : "size" in listLike ? listLike.size : "count" in listLike ? listLike.count : zeroOnInvalid ? 0 : NaN;
|
|
@@ -496,7 +436,7 @@ function pauseFor(time, signal, rejectOnAbort = false) {
|
|
|
496
436
|
});
|
|
497
437
|
}
|
|
498
438
|
function pureObj(obj) {
|
|
499
|
-
return Object.assign(/* @__PURE__ */ Object.create(null), obj
|
|
439
|
+
return Object.assign(/* @__PURE__ */ Object.create(null), obj ?? {});
|
|
500
440
|
}
|
|
501
441
|
function setImmediateInterval(callback, interval, signal) {
|
|
502
442
|
let intervalId;
|
|
@@ -513,12 +453,12 @@ function setImmediateInterval(callback, interval, signal) {
|
|
|
513
453
|
function setImmediateTimeoutLoop(callback, interval, signal) {
|
|
514
454
|
let timeout;
|
|
515
455
|
const cleanup = () => clearTimeout(timeout);
|
|
516
|
-
const loop = () =>
|
|
456
|
+
const loop = async () => {
|
|
517
457
|
if (signal == null ? void 0 : signal.aborted)
|
|
518
458
|
return cleanup();
|
|
519
|
-
|
|
459
|
+
await callback();
|
|
520
460
|
timeout = setTimeout(loop, interval);
|
|
521
|
-
}
|
|
461
|
+
};
|
|
522
462
|
signal == null ? void 0 : signal.addEventListener("abort", cleanup);
|
|
523
463
|
loop();
|
|
524
464
|
}
|
|
@@ -535,13 +475,12 @@ function scheduleExit(code = 0, timeout = 0) {
|
|
|
535
475
|
setTimeout(exit, timeout);
|
|
536
476
|
}
|
|
537
477
|
function getCallStack(asArray, lines = Infinity) {
|
|
538
|
-
var _a;
|
|
539
478
|
if (typeof lines !== "number" || isNaN(lines) || lines < 0)
|
|
540
479
|
throw new TypeError("lines parameter must be a non-negative number");
|
|
541
480
|
try {
|
|
542
481
|
throw new Error("This is to capture a stack trace with CoreUtils.getCallStack(). (If you see this somewhere, you can safely ignore it.)");
|
|
543
482
|
} catch (err) {
|
|
544
|
-
const stack = (
|
|
483
|
+
const stack = (err.stack ?? "").split("\n").map((line) => line.trim()).slice(2, lines + 2);
|
|
545
484
|
return asArray !== false ? stack : stack.join("\n");
|
|
546
485
|
}
|
|
547
486
|
}
|
|
@@ -596,9 +535,9 @@ function createProgressBar(percentage, barLength, chars = defaultPbChars) {
|
|
|
596
535
|
}
|
|
597
536
|
function insertValues(input, ...values) {
|
|
598
537
|
return input.replace(/%\d/gm, (match) => {
|
|
599
|
-
var _a
|
|
538
|
+
var _a;
|
|
600
539
|
const argIndex = Number(match.substring(1)) - 1;
|
|
601
|
-
return (
|
|
540
|
+
return (_a = values[argIndex] ?? match) == null ? void 0 : _a.toString();
|
|
602
541
|
});
|
|
603
542
|
}
|
|
604
543
|
function joinArrayReadable(array, separators = ", ", lastSeparator = " and ") {
|
|
@@ -629,8 +568,7 @@ function secsToTimeStr(seconds) {
|
|
|
629
568
|
].join("");
|
|
630
569
|
}
|
|
631
570
|
function truncStr(input, length, endStr = "...") {
|
|
632
|
-
|
|
633
|
-
const str = (_a = input == null ? void 0 : input.toString()) != null ? _a : String(input);
|
|
571
|
+
const str = (input == null ? void 0 : input.toString()) ?? String(input);
|
|
634
572
|
const finalStr = str.length > length ? str.substring(0, length - endStr.length) + endStr : str;
|
|
635
573
|
return finalStr.length > length ? finalStr.substring(0, length) : finalStr;
|
|
636
574
|
}
|
|
@@ -638,6 +576,26 @@ function truncStr(input, length, endStr = "...") {
|
|
|
638
576
|
// lib/DataStore.ts
|
|
639
577
|
var dsFmtVer = 1;
|
|
640
578
|
var DataStore = class {
|
|
579
|
+
id;
|
|
580
|
+
formatVersion;
|
|
581
|
+
defaultData;
|
|
582
|
+
encodeData;
|
|
583
|
+
decodeData;
|
|
584
|
+
compressionFormat = "deflate-raw";
|
|
585
|
+
memoryCache;
|
|
586
|
+
engine;
|
|
587
|
+
keyPrefix;
|
|
588
|
+
options;
|
|
589
|
+
/**
|
|
590
|
+
* Whether all first-init checks should be done.
|
|
591
|
+
* This includes migrating the internal DataStore format, migrating data from the UserUtils format, and anything similar.
|
|
592
|
+
* 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.
|
|
593
|
+
*/
|
|
594
|
+
firstInit = true;
|
|
595
|
+
/** In-memory cached copy of the data that is saved in persistent storage used for synchronous read access. */
|
|
596
|
+
cachedData;
|
|
597
|
+
migrations;
|
|
598
|
+
migrateIds = [];
|
|
641
599
|
//#region constructor
|
|
642
600
|
/**
|
|
643
601
|
* Creates an instance of DataStore to manage a sync & async database that is cached in memory and persistently saved across sessions.
|
|
@@ -649,40 +607,21 @@ var DataStore = class {
|
|
|
649
607
|
* @param opts The options for this DataStore instance
|
|
650
608
|
*/
|
|
651
609
|
constructor(opts) {
|
|
652
|
-
__publicField(this, "id");
|
|
653
|
-
__publicField(this, "formatVersion");
|
|
654
|
-
__publicField(this, "defaultData");
|
|
655
|
-
__publicField(this, "encodeData");
|
|
656
|
-
__publicField(this, "decodeData");
|
|
657
|
-
__publicField(this, "compressionFormat", "deflate-raw");
|
|
658
|
-
__publicField(this, "memoryCache");
|
|
659
|
-
__publicField(this, "engine");
|
|
660
|
-
__publicField(this, "options");
|
|
661
|
-
/**
|
|
662
|
-
* Whether all first-init checks should be done.
|
|
663
|
-
* This includes migrating the internal DataStore format, migrating data from the UserUtils format, and anything similar.
|
|
664
|
-
* 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.
|
|
665
|
-
*/
|
|
666
|
-
__publicField(this, "firstInit", true);
|
|
667
|
-
/** In-memory cached copy of the data that is saved in persistent storage used for synchronous read access. */
|
|
668
|
-
__publicField(this, "cachedData");
|
|
669
|
-
__publicField(this, "migrations");
|
|
670
|
-
__publicField(this, "migrateIds", []);
|
|
671
|
-
var _a, _b;
|
|
672
610
|
this.id = opts.id;
|
|
673
611
|
this.formatVersion = opts.formatVersion;
|
|
674
612
|
this.defaultData = opts.defaultData;
|
|
675
|
-
this.memoryCache =
|
|
613
|
+
this.memoryCache = opts.memoryCache ?? true;
|
|
676
614
|
this.cachedData = this.memoryCache ? opts.defaultData : {};
|
|
677
615
|
this.migrations = opts.migrations;
|
|
678
616
|
if (opts.migrateIds)
|
|
679
617
|
this.migrateIds = Array.isArray(opts.migrateIds) ? opts.migrateIds : [opts.migrateIds];
|
|
680
618
|
this.engine = typeof opts.engine === "function" ? opts.engine() : opts.engine;
|
|
619
|
+
this.keyPrefix = opts.keyPrefix ?? "__ds-";
|
|
681
620
|
this.options = opts;
|
|
682
621
|
if ("encodeData" in opts && "decodeData" in opts && Array.isArray(opts.encodeData) && Array.isArray(opts.decodeData)) {
|
|
683
622
|
this.encodeData = [opts.encodeData[0], opts.encodeData[1]];
|
|
684
623
|
this.decodeData = [opts.decodeData[0], opts.decodeData[1]];
|
|
685
|
-
this.compressionFormat =
|
|
624
|
+
this.compressionFormat = opts.encodeData[0] ?? null;
|
|
686
625
|
} else if (opts.compressionFormat === null) {
|
|
687
626
|
this.encodeData = void 0;
|
|
688
627
|
this.decodeData = void 0;
|
|
@@ -690,12 +629,8 @@ var DataStore = class {
|
|
|
690
629
|
} else {
|
|
691
630
|
const fmt = typeof opts.compressionFormat === "string" ? opts.compressionFormat : "deflate-raw";
|
|
692
631
|
this.compressionFormat = fmt;
|
|
693
|
-
this.encodeData = [fmt, (data) =>
|
|
694
|
-
|
|
695
|
-
})];
|
|
696
|
-
this.decodeData = [fmt, (data) => __async(this, null, function* () {
|
|
697
|
-
return yield decompress(data, fmt, "string");
|
|
698
|
-
})];
|
|
632
|
+
this.encodeData = [fmt, async (data) => await compress(data, fmt, "string")];
|
|
633
|
+
this.decodeData = [fmt, async (data) => await decompress(data, fmt, "string")];
|
|
699
634
|
}
|
|
700
635
|
this.engine.setDataStoreOptions({
|
|
701
636
|
id: this.id,
|
|
@@ -709,69 +644,66 @@ var DataStore = class {
|
|
|
709
644
|
* Automatically populates persistent storage with default data if it doesn't contain any data yet.
|
|
710
645
|
* Also runs all necessary migration functions if the data format has changed since the last time the data was saved.
|
|
711
646
|
*/
|
|
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);
|
|
647
|
+
async loadData() {
|
|
648
|
+
try {
|
|
649
|
+
if (this.firstInit) {
|
|
650
|
+
this.firstInit = false;
|
|
651
|
+
const dsVer = Number(await this.engine.getValue("__ds_fmt_ver", 0));
|
|
652
|
+
const oldData = await this.engine.getValue(`_uucfg-${this.id}`, null);
|
|
653
|
+
if (oldData) {
|
|
654
|
+
const oldVer = Number(await this.engine.getValue(`_uucfgver-${this.id}`, NaN));
|
|
655
|
+
const oldEnc = await this.engine.getValue(`_uucfgenc-${this.id}`, null);
|
|
656
|
+
const promises = [];
|
|
657
|
+
const migrateFmt = (oldKey, newKey, value) => {
|
|
658
|
+
promises.push(this.engine.setValue(newKey, value));
|
|
659
|
+
promises.push(this.engine.deleteValue(oldKey));
|
|
660
|
+
};
|
|
661
|
+
migrateFmt(`_uucfg-${this.id}`, `${this.keyPrefix}${this.id}-dat`, oldData);
|
|
662
|
+
if (!isNaN(oldVer))
|
|
663
|
+
migrateFmt(`_uucfgver-${this.id}`, `${this.keyPrefix}${this.id}-ver`, oldVer);
|
|
664
|
+
if (typeof oldEnc === "boolean" || oldEnc === "true" || oldEnc === "false" || typeof oldEnc === "number" || oldEnc === "0" || oldEnc === "1")
|
|
665
|
+
migrateFmt(`_uucfgenc-${this.id}`, `${this.keyPrefix}${this.id}-enf`, [0, "0", true, "true"].includes(oldEnc) ? this.compressionFormat ?? null : null);
|
|
666
|
+
else {
|
|
667
|
+
promises.push(this.engine.setValue(`${this.keyPrefix}${this.id}-enf`, this.compressionFormat));
|
|
668
|
+
promises.push(this.engine.deleteValue(`_uucfgenc-${this.id}`));
|
|
738
669
|
}
|
|
739
|
-
|
|
740
|
-
yield this.engine.setValue("__ds_fmt_ver", dsFmtVer);
|
|
670
|
+
await Promise.allSettled(promises);
|
|
741
671
|
}
|
|
742
|
-
if (
|
|
743
|
-
|
|
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" && typeof storedDataRaw !== "object" || storedDataRaw === null || isNaN(storedFmtVer)) {
|
|
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" && encodingFmt !== "0" && encodingFmt !== "" && encodingFmt !== null;
|
|
755
|
-
let saveData = false;
|
|
756
|
-
if (isNaN(storedFmtVer)) {
|
|
757
|
-
yield this.engine.setValue(`__ds-${this.id}-ver`, storedFmtVer = this.formatVersion);
|
|
758
|
-
saveData = true;
|
|
759
|
-
}
|
|
760
|
-
let parsed = typeof storedData === "string" ? yield this.engine.deserializeData(storedData, isEncoded) : storedData;
|
|
761
|
-
if (storedFmtVer < this.formatVersion && this.migrations)
|
|
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;
|
|
672
|
+
if (isNaN(dsVer) || dsVer < dsFmtVer)
|
|
673
|
+
await this.engine.setValue("__ds_fmt_ver", dsFmtVer);
|
|
773
674
|
}
|
|
774
|
-
|
|
675
|
+
if (this.migrateIds.length > 0) {
|
|
676
|
+
await this.migrateId(this.migrateIds);
|
|
677
|
+
this.migrateIds = [];
|
|
678
|
+
}
|
|
679
|
+
const storedDataRaw = await this.engine.getValue(`${this.keyPrefix}${this.id}-dat`, null);
|
|
680
|
+
let storedFmtVer = Number(await this.engine.getValue(`${this.keyPrefix}${this.id}-ver`, NaN));
|
|
681
|
+
if (typeof storedDataRaw !== "string" && typeof storedDataRaw !== "object" || storedDataRaw === null || isNaN(storedFmtVer)) {
|
|
682
|
+
await this.saveDefaultData();
|
|
683
|
+
return this.engine.deepCopy(this.defaultData);
|
|
684
|
+
}
|
|
685
|
+
const storedData = storedDataRaw ?? JSON.stringify(this.defaultData);
|
|
686
|
+
const encodingFmt = String(await this.engine.getValue(`${this.keyPrefix}${this.id}-enf`, null));
|
|
687
|
+
const isEncoded = encodingFmt !== "null" && encodingFmt !== "false" && encodingFmt !== "0" && encodingFmt !== "" && encodingFmt !== null;
|
|
688
|
+
let saveData = false;
|
|
689
|
+
if (isNaN(storedFmtVer)) {
|
|
690
|
+
await this.engine.setValue(`${this.keyPrefix}${this.id}-ver`, storedFmtVer = this.formatVersion);
|
|
691
|
+
saveData = true;
|
|
692
|
+
}
|
|
693
|
+
let parsed = typeof storedData === "string" ? await this.engine.deserializeData(storedData, isEncoded) : storedData;
|
|
694
|
+
if (storedFmtVer < this.formatVersion && this.migrations)
|
|
695
|
+
parsed = await this.runMigrations(parsed, storedFmtVer);
|
|
696
|
+
if (saveData)
|
|
697
|
+
await this.setData(parsed);
|
|
698
|
+
if (this.memoryCache)
|
|
699
|
+
return this.cachedData = this.engine.deepCopy(parsed);
|
|
700
|
+
else
|
|
701
|
+
return this.engine.deepCopy(parsed);
|
|
702
|
+
} catch (err) {
|
|
703
|
+
console.warn("Error while parsing JSON data, resetting it to the default value.", err);
|
|
704
|
+
await this.saveDefaultData();
|
|
705
|
+
return this.defaultData;
|
|
706
|
+
}
|
|
775
707
|
}
|
|
776
708
|
//#region getData
|
|
777
709
|
/**
|
|
@@ -789,27 +721,25 @@ var DataStore = class {
|
|
|
789
721
|
setData(data) {
|
|
790
722
|
if (this.memoryCache)
|
|
791
723
|
this.cachedData = data;
|
|
792
|
-
return new Promise((resolve) =>
|
|
793
|
-
|
|
794
|
-
this.engine.setValue(
|
|
795
|
-
this.engine.setValue(
|
|
796
|
-
this.engine.setValue(
|
|
724
|
+
return new Promise(async (resolve) => {
|
|
725
|
+
await Promise.allSettled([
|
|
726
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-dat`, await this.engine.serializeData(data, this.encodingEnabled())),
|
|
727
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-ver`, this.formatVersion),
|
|
728
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-enf`, this.compressionFormat)
|
|
797
729
|
]);
|
|
798
730
|
resolve();
|
|
799
|
-
})
|
|
731
|
+
});
|
|
800
732
|
}
|
|
801
733
|
//#region saveDefaultData
|
|
802
734
|
/** 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
|
-
});
|
|
735
|
+
async saveDefaultData() {
|
|
736
|
+
if (this.memoryCache)
|
|
737
|
+
this.cachedData = this.defaultData;
|
|
738
|
+
await Promise.allSettled([
|
|
739
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-dat`, await this.engine.serializeData(this.defaultData, this.encodingEnabled())),
|
|
740
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-ver`, this.formatVersion),
|
|
741
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-enf`, this.compressionFormat)
|
|
742
|
+
]);
|
|
813
743
|
}
|
|
814
744
|
//#region deleteData
|
|
815
745
|
/**
|
|
@@ -817,16 +747,14 @@ var DataStore = class {
|
|
|
817
747
|
* The in-memory cache will be left untouched, so you may still access the data with {@linkcode getData()}
|
|
818
748
|
* Calling {@linkcode loadData()} or {@linkcode setData()} after this method was called will recreate persistent storage with the cached or default data.
|
|
819
749
|
*/
|
|
820
|
-
deleteData() {
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
yield (_b = (_a = this.engine).deleteStorage) == null ? void 0 : _b.call(_a);
|
|
829
|
-
});
|
|
750
|
+
async deleteData() {
|
|
751
|
+
var _a, _b;
|
|
752
|
+
await Promise.allSettled([
|
|
753
|
+
this.engine.deleteValue(`${this.keyPrefix}${this.id}-dat`),
|
|
754
|
+
this.engine.deleteValue(`${this.keyPrefix}${this.id}-ver`),
|
|
755
|
+
this.engine.deleteValue(`${this.keyPrefix}${this.id}-enf`)
|
|
756
|
+
]);
|
|
757
|
+
await ((_b = (_a = this.engine).deleteStorage) == null ? void 0 : _b.call(_a));
|
|
830
758
|
}
|
|
831
759
|
//#region encodingEnabled
|
|
832
760
|
/** Returns whether encoding and decoding are enabled for this DataStore instance */
|
|
@@ -841,77 +769,73 @@ var DataStore = class {
|
|
|
841
769
|
*
|
|
842
770
|
* 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
771
|
*/
|
|
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.engine.deepCopy(this.defaultData);
|
|
863
|
-
}
|
|
772
|
+
async runMigrations(oldData, oldFmtVer, resetOnError = true) {
|
|
773
|
+
if (!this.migrations)
|
|
774
|
+
return oldData;
|
|
775
|
+
let newData = oldData;
|
|
776
|
+
const sortedMigrations = Object.entries(this.migrations).sort(([a], [b]) => Number(a) - Number(b));
|
|
777
|
+
let lastFmtVer = oldFmtVer;
|
|
778
|
+
for (const [fmtVer, migrationFunc] of sortedMigrations) {
|
|
779
|
+
const ver = Number(fmtVer);
|
|
780
|
+
if (oldFmtVer < this.formatVersion && oldFmtVer < ver) {
|
|
781
|
+
try {
|
|
782
|
+
const migRes = migrationFunc(newData);
|
|
783
|
+
newData = migRes instanceof Promise ? await migRes : migRes;
|
|
784
|
+
lastFmtVer = oldFmtVer = ver;
|
|
785
|
+
} catch (err) {
|
|
786
|
+
if (!resetOnError)
|
|
787
|
+
throw new MigrationError(`Error while running migration function for format version '${fmtVer}'`, { cause: err });
|
|
788
|
+
await this.saveDefaultData();
|
|
789
|
+
return this.engine.deepCopy(this.defaultData);
|
|
864
790
|
}
|
|
865
791
|
}
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
792
|
+
}
|
|
793
|
+
await Promise.allSettled([
|
|
794
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-dat`, await this.engine.serializeData(newData, this.encodingEnabled())),
|
|
795
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-ver`, lastFmtVer),
|
|
796
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-enf`, this.compressionFormat)
|
|
797
|
+
]);
|
|
798
|
+
if (this.memoryCache)
|
|
799
|
+
return this.cachedData = this.engine.deepCopy(newData);
|
|
800
|
+
else
|
|
801
|
+
return this.engine.deepCopy(newData);
|
|
876
802
|
}
|
|
877
803
|
//#region migrateId
|
|
878
804
|
/**
|
|
879
805
|
* Tries to migrate the currently saved persistent data from one or more old IDs to the ID set in the constructor.
|
|
880
806
|
* 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
807
|
*/
|
|
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, this.encodingEnabled())),
|
|
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`)
|
|
808
|
+
async migrateId(oldIds) {
|
|
809
|
+
const ids = Array.isArray(oldIds) ? oldIds : [oldIds];
|
|
810
|
+
await Promise.all(ids.map(async (id) => {
|
|
811
|
+
const [data, fmtVer, isEncoded] = await (async () => {
|
|
812
|
+
const [d, f, e] = await Promise.all([
|
|
813
|
+
this.engine.getValue(`${this.keyPrefix}${id}-dat`, JSON.stringify(this.defaultData)),
|
|
814
|
+
this.engine.getValue(`${this.keyPrefix}${id}-ver`, NaN),
|
|
815
|
+
this.engine.getValue(`${this.keyPrefix}${id}-enf`, null)
|
|
904
816
|
]);
|
|
905
|
-
|
|
906
|
-
|
|
817
|
+
return [d, Number(f), Boolean(e) && String(e) !== "null"];
|
|
818
|
+
})();
|
|
819
|
+
if (data === void 0 || isNaN(fmtVer))
|
|
820
|
+
return;
|
|
821
|
+
const parsed = await this.engine.deserializeData(data, isEncoded);
|
|
822
|
+
await Promise.allSettled([
|
|
823
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-dat`, await this.engine.serializeData(parsed, this.encodingEnabled())),
|
|
824
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-ver`, fmtVer),
|
|
825
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-enf`, this.compressionFormat),
|
|
826
|
+
this.engine.deleteValue(`${this.keyPrefix}${id}-dat`),
|
|
827
|
+
this.engine.deleteValue(`${this.keyPrefix}${id}-ver`),
|
|
828
|
+
this.engine.deleteValue(`${this.keyPrefix}${id}-enf`)
|
|
829
|
+
]);
|
|
830
|
+
}));
|
|
907
831
|
}
|
|
908
832
|
};
|
|
909
833
|
|
|
910
834
|
// lib/DataStoreEngine.ts
|
|
911
835
|
var DataStoreEngine = class {
|
|
836
|
+
dataStoreOptions;
|
|
912
837
|
// setDataStoreOptions() is called from inside the DataStore constructor to set this value
|
|
913
838
|
constructor(options) {
|
|
914
|
-
__publicField(this, "dataStoreOptions");
|
|
915
839
|
if (options)
|
|
916
840
|
this.dataStoreOptions = options;
|
|
917
841
|
}
|
|
@@ -921,29 +845,25 @@ var DataStoreEngine = class {
|
|
|
921
845
|
}
|
|
922
846
|
//#region serialization api
|
|
923
847
|
/** 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
|
-
});
|
|
848
|
+
async serializeData(data, useEncoding) {
|
|
849
|
+
var _a, _b, _c, _d, _e;
|
|
850
|
+
this.ensureDataStoreOptions();
|
|
851
|
+
const stringData = JSON.stringify(data);
|
|
852
|
+
if (!useEncoding || !((_a = this.dataStoreOptions) == null ? void 0 : _a.encodeData) || !((_b = this.dataStoreOptions) == null ? void 0 : _b.decodeData))
|
|
853
|
+
return stringData;
|
|
854
|
+
const encRes = (_e = (_d = (_c = this.dataStoreOptions) == null ? void 0 : _c.encodeData) == null ? void 0 : _d[1]) == null ? void 0 : _e.call(_d, stringData);
|
|
855
|
+
if (encRes instanceof Promise)
|
|
856
|
+
return await encRes;
|
|
857
|
+
return encRes;
|
|
936
858
|
}
|
|
937
859
|
/** 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
|
-
});
|
|
860
|
+
async deserializeData(data, useEncoding) {
|
|
861
|
+
var _a, _b, _c;
|
|
862
|
+
this.ensureDataStoreOptions();
|
|
863
|
+
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;
|
|
864
|
+
if (decRes instanceof Promise)
|
|
865
|
+
decRes = await decRes;
|
|
866
|
+
return JSON.parse(decRes ?? data);
|
|
947
867
|
}
|
|
948
868
|
//#region misc api
|
|
949
869
|
/** Throws an error if the DataStoreOptions are not set or invalid */
|
|
@@ -961,12 +881,13 @@ var DataStoreEngine = class {
|
|
|
961
881
|
try {
|
|
962
882
|
if ("structuredClone" in globalThis)
|
|
963
883
|
return structuredClone(obj);
|
|
964
|
-
} catch
|
|
884
|
+
} catch {
|
|
965
885
|
}
|
|
966
886
|
return JSON.parse(JSON.stringify(obj));
|
|
967
887
|
}
|
|
968
888
|
};
|
|
969
889
|
var BrowserStorageEngine = class extends DataStoreEngine {
|
|
890
|
+
options;
|
|
970
891
|
/**
|
|
971
892
|
* Creates an instance of `BrowserStorageEngine`.
|
|
972
893
|
*
|
|
@@ -975,40 +896,36 @@ var BrowserStorageEngine = class extends DataStoreEngine {
|
|
|
975
896
|
*/
|
|
976
897
|
constructor(options) {
|
|
977
898
|
super(options == null ? void 0 : options.dataStoreOptions);
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
}
|
|
899
|
+
this.options = {
|
|
900
|
+
type: "localStorage",
|
|
901
|
+
...options
|
|
902
|
+
};
|
|
982
903
|
}
|
|
983
904
|
//#region storage api
|
|
984
905
|
/** Fetches a value from persistent storage */
|
|
985
|
-
getValue(name, defaultValue) {
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
return typeof val === "undefined" ? defaultValue : val;
|
|
989
|
-
});
|
|
906
|
+
async getValue(name, defaultValue) {
|
|
907
|
+
const val = this.options.type === "localStorage" ? globalThis.localStorage.getItem(name) : globalThis.sessionStorage.getItem(name);
|
|
908
|
+
return typeof val === "undefined" ? defaultValue : val;
|
|
990
909
|
}
|
|
991
910
|
/** Sets a value in persistent storage */
|
|
992
|
-
setValue(name, value) {
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
globalThis.sessionStorage.setItem(name, String(value));
|
|
998
|
-
});
|
|
911
|
+
async setValue(name, value) {
|
|
912
|
+
if (this.options.type === "localStorage")
|
|
913
|
+
globalThis.localStorage.setItem(name, String(value));
|
|
914
|
+
else
|
|
915
|
+
globalThis.sessionStorage.setItem(name, String(value));
|
|
999
916
|
}
|
|
1000
917
|
/** Deletes a value from persistent storage */
|
|
1001
|
-
deleteValue(name) {
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
globalThis.sessionStorage.removeItem(name);
|
|
1007
|
-
});
|
|
918
|
+
async deleteValue(name) {
|
|
919
|
+
if (this.options.type === "localStorage")
|
|
920
|
+
globalThis.localStorage.removeItem(name);
|
|
921
|
+
else
|
|
922
|
+
globalThis.sessionStorage.removeItem(name);
|
|
1008
923
|
}
|
|
1009
924
|
};
|
|
1010
925
|
var fs;
|
|
1011
926
|
var FileStorageEngine = class extends DataStoreEngine {
|
|
927
|
+
options;
|
|
928
|
+
fileAccessQueue = Promise.resolve();
|
|
1012
929
|
/**
|
|
1013
930
|
* Creates an instance of `FileStorageEngine`.
|
|
1014
931
|
*
|
|
@@ -1017,160 +934,146 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
1017
934
|
*/
|
|
1018
935
|
constructor(options) {
|
|
1019
936
|
super(options == null ? void 0 : options.dataStoreOptions);
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
}, options);
|
|
937
|
+
this.options = {
|
|
938
|
+
filePath: (id) => `.ds-${id}`,
|
|
939
|
+
...options
|
|
940
|
+
};
|
|
1025
941
|
}
|
|
1026
942
|
//#region json file
|
|
1027
943
|
/** Reads the file contents */
|
|
1028
|
-
readFile() {
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
}
|
|
1043
|
-
});
|
|
944
|
+
async readFile() {
|
|
945
|
+
var _a, _b, _c, _d;
|
|
946
|
+
this.ensureDataStoreOptions();
|
|
947
|
+
try {
|
|
948
|
+
if (!fs)
|
|
949
|
+
fs = (_a = await import("fs/promises")) == null ? void 0 : _a.default;
|
|
950
|
+
if (!fs)
|
|
951
|
+
throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
|
|
952
|
+
const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id, this.dataStoreOptions);
|
|
953
|
+
const data = await fs.readFile(path, "utf-8");
|
|
954
|
+
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;
|
|
955
|
+
} catch {
|
|
956
|
+
return void 0;
|
|
957
|
+
}
|
|
1044
958
|
}
|
|
1045
959
|
/** Overwrites the file contents */
|
|
1046
|
-
writeFile(data) {
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
}
|
|
1061
|
-
});
|
|
960
|
+
async writeFile(data) {
|
|
961
|
+
var _a, _b, _c, _d;
|
|
962
|
+
this.ensureDataStoreOptions();
|
|
963
|
+
try {
|
|
964
|
+
if (!fs)
|
|
965
|
+
fs = (_a = await import("fs/promises")) == null ? void 0 : _a.default;
|
|
966
|
+
if (!fs)
|
|
967
|
+
throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
|
|
968
|
+
const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id, this.dataStoreOptions);
|
|
969
|
+
await fs.mkdir(path.slice(0, path.lastIndexOf(path.includes("/") ? "/" : "\\")), { recursive: true });
|
|
970
|
+
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");
|
|
971
|
+
} catch (err) {
|
|
972
|
+
console.error("Error writing file:", err);
|
|
973
|
+
}
|
|
1062
974
|
}
|
|
1063
975
|
//#region storage api
|
|
1064
976
|
/** Fetches a value from persistent storage */
|
|
1065
|
-
getValue(name, defaultValue) {
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
977
|
+
async getValue(name, defaultValue) {
|
|
978
|
+
const data = await this.readFile();
|
|
979
|
+
if (!data)
|
|
980
|
+
return defaultValue;
|
|
981
|
+
const value = data == null ? void 0 : data[name];
|
|
982
|
+
if (typeof value === "undefined")
|
|
983
|
+
return defaultValue;
|
|
984
|
+
if (typeof defaultValue === "string") {
|
|
985
|
+
if (typeof value === "object" && value !== null)
|
|
986
|
+
return JSON.stringify(value);
|
|
987
|
+
if (typeof value === "string")
|
|
988
|
+
return value;
|
|
989
|
+
return String(value);
|
|
990
|
+
}
|
|
991
|
+
if (typeof value === "string") {
|
|
992
|
+
try {
|
|
993
|
+
const parsed = JSON.parse(value);
|
|
994
|
+
return parsed;
|
|
995
|
+
} catch {
|
|
1072
996
|
return defaultValue;
|
|
1073
|
-
if (typeof defaultValue === "string") {
|
|
1074
|
-
if (typeof value === "object" && value !== null)
|
|
1075
|
-
return JSON.stringify(value);
|
|
1076
|
-
if (typeof value === "string")
|
|
1077
|
-
return value;
|
|
1078
|
-
return String(value);
|
|
1079
997
|
}
|
|
998
|
+
}
|
|
999
|
+
return value;
|
|
1000
|
+
}
|
|
1001
|
+
/** Sets a value in persistent storage */
|
|
1002
|
+
async setValue(name, value) {
|
|
1003
|
+
this.fileAccessQueue = this.fileAccessQueue.then(async () => {
|
|
1004
|
+
let data = await this.readFile();
|
|
1005
|
+
if (!data)
|
|
1006
|
+
data = {};
|
|
1007
|
+
let storeVal = value;
|
|
1080
1008
|
if (typeof value === "string") {
|
|
1081
1009
|
try {
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1010
|
+
if (value.startsWith("{") || value.startsWith("[")) {
|
|
1011
|
+
const parsed = JSON.parse(value);
|
|
1012
|
+
if (typeof parsed === "object" && parsed !== null)
|
|
1013
|
+
storeVal = parsed;
|
|
1014
|
+
}
|
|
1015
|
+
} catch {
|
|
1086
1016
|
}
|
|
1087
1017
|
}
|
|
1088
|
-
|
|
1018
|
+
data[name] = storeVal;
|
|
1019
|
+
await this.writeFile(data);
|
|
1020
|
+
}).catch((err) => {
|
|
1021
|
+
console.error("Error in setValue:", err);
|
|
1022
|
+
throw err;
|
|
1089
1023
|
});
|
|
1090
|
-
|
|
1091
|
-
/** Sets a value in persistent storage */
|
|
1092
|
-
setValue(name, value) {
|
|
1093
|
-
return __async(this, null, function* () {
|
|
1094
|
-
this.fileAccessQueue = this.fileAccessQueue.then(() => __async(this, null, function* () {
|
|
1095
|
-
let data = yield this.readFile();
|
|
1096
|
-
if (!data)
|
|
1097
|
-
data = {};
|
|
1098
|
-
let storeVal = value;
|
|
1099
|
-
if (typeof value === "string") {
|
|
1100
|
-
try {
|
|
1101
|
-
if (value.startsWith("{") || value.startsWith("[")) {
|
|
1102
|
-
const parsed = JSON.parse(value);
|
|
1103
|
-
if (typeof parsed === "object" && parsed !== null)
|
|
1104
|
-
storeVal = parsed;
|
|
1105
|
-
}
|
|
1106
|
-
} catch (e) {
|
|
1107
|
-
}
|
|
1108
|
-
}
|
|
1109
|
-
data[name] = storeVal;
|
|
1110
|
-
yield this.writeFile(data);
|
|
1111
|
-
})).catch((err) => {
|
|
1112
|
-
console.error("Error in setValue:", err);
|
|
1113
|
-
throw err;
|
|
1114
|
-
});
|
|
1115
|
-
yield this.fileAccessQueue.catch(() => {
|
|
1116
|
-
});
|
|
1024
|
+
await this.fileAccessQueue.catch(() => {
|
|
1117
1025
|
});
|
|
1118
1026
|
}
|
|
1119
1027
|
/** Deletes a value from persistent storage */
|
|
1120
|
-
deleteValue(name) {
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
yield this.fileAccessQueue.catch(() => {
|
|
1133
|
-
});
|
|
1028
|
+
async deleteValue(name) {
|
|
1029
|
+
this.fileAccessQueue = this.fileAccessQueue.then(async () => {
|
|
1030
|
+
const data = await this.readFile();
|
|
1031
|
+
if (!data)
|
|
1032
|
+
return;
|
|
1033
|
+
delete data[name];
|
|
1034
|
+
await this.writeFile(data);
|
|
1035
|
+
}).catch((err) => {
|
|
1036
|
+
console.error("Error in deleteValue:", err);
|
|
1037
|
+
throw err;
|
|
1038
|
+
});
|
|
1039
|
+
await this.fileAccessQueue.catch(() => {
|
|
1134
1040
|
});
|
|
1135
1041
|
}
|
|
1136
1042
|
/** Deletes the file that contains the data of this DataStore. */
|
|
1137
|
-
deleteStorage() {
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
}
|
|
1151
|
-
});
|
|
1043
|
+
async deleteStorage() {
|
|
1044
|
+
var _a;
|
|
1045
|
+
this.ensureDataStoreOptions();
|
|
1046
|
+
try {
|
|
1047
|
+
if (!fs)
|
|
1048
|
+
fs = (_a = await import("fs/promises")) == null ? void 0 : _a.default;
|
|
1049
|
+
if (!fs)
|
|
1050
|
+
throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
|
|
1051
|
+
const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id, this.dataStoreOptions);
|
|
1052
|
+
return await fs.unlink(path);
|
|
1053
|
+
} catch (err) {
|
|
1054
|
+
console.error("Error deleting file:", err);
|
|
1055
|
+
}
|
|
1152
1056
|
}
|
|
1153
1057
|
};
|
|
1154
1058
|
|
|
1155
1059
|
// lib/DataStoreSerializer.ts
|
|
1156
1060
|
var DataStoreSerializer = class _DataStoreSerializer {
|
|
1061
|
+
stores;
|
|
1062
|
+
options;
|
|
1157
1063
|
constructor(stores, options = {}) {
|
|
1158
|
-
__publicField(this, "stores");
|
|
1159
|
-
__publicField(this, "options");
|
|
1160
1064
|
if (!crypto || !crypto.subtle)
|
|
1161
1065
|
throw new ScriptContextError("DataStoreSerializer has to run in a secure context (HTTPS) or in another environment that implements the subtleCrypto API!");
|
|
1162
1066
|
this.stores = stores;
|
|
1163
|
-
this.options =
|
|
1067
|
+
this.options = {
|
|
1164
1068
|
addChecksum: true,
|
|
1165
1069
|
ensureIntegrity: true,
|
|
1166
|
-
remapIds: {}
|
|
1167
|
-
|
|
1070
|
+
remapIds: {},
|
|
1071
|
+
...options
|
|
1072
|
+
};
|
|
1168
1073
|
}
|
|
1169
1074
|
/** Calculates the checksum of a string */
|
|
1170
|
-
calcChecksum(input) {
|
|
1171
|
-
return
|
|
1172
|
-
return computeHash(input, "SHA-256");
|
|
1173
|
-
});
|
|
1075
|
+
async calcChecksum(input) {
|
|
1076
|
+
return computeHash(input, "SHA-256");
|
|
1174
1077
|
}
|
|
1175
1078
|
/**
|
|
1176
1079
|
* Serializes only a subset of the data stores into a string.
|
|
@@ -1178,80 +1081,72 @@ var DataStoreSerializer = class _DataStoreSerializer {
|
|
|
1178
1081
|
* @param useEncoding Whether to encode the data using each DataStore's `encodeData()` method
|
|
1179
1082
|
* @param stringified Whether to return the result as a string or as an array of `SerializedDataStore` objects
|
|
1180
1083
|
*/
|
|
1181
|
-
serializePartial(stores, useEncoding = true, stringified = true) {
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
return stringified ? JSON.stringify(serData) : serData;
|
|
1199
|
-
});
|
|
1084
|
+
async serializePartial(stores, useEncoding = true, stringified = true) {
|
|
1085
|
+
var _a;
|
|
1086
|
+
const serData = [];
|
|
1087
|
+
const filteredStores = this.stores.filter((s) => typeof stores === "function" ? stores(s.id) : stores.includes(s.id));
|
|
1088
|
+
for (const storeInst of filteredStores) {
|
|
1089
|
+
const encoded = Boolean(useEncoding && storeInst.encodingEnabled() && ((_a = storeInst.encodeData) == null ? void 0 : _a[1]));
|
|
1090
|
+
const rawData = storeInst.memoryCache ? storeInst.getData() : await storeInst.loadData();
|
|
1091
|
+
const data = encoded ? await storeInst.encodeData[1](JSON.stringify(rawData)) : JSON.stringify(rawData);
|
|
1092
|
+
serData.push({
|
|
1093
|
+
id: storeInst.id,
|
|
1094
|
+
data,
|
|
1095
|
+
formatVersion: storeInst.formatVersion,
|
|
1096
|
+
encoded,
|
|
1097
|
+
checksum: this.options.addChecksum ? await this.calcChecksum(data) : void 0
|
|
1098
|
+
});
|
|
1099
|
+
}
|
|
1100
|
+
return stringified ? JSON.stringify(serData) : serData;
|
|
1200
1101
|
}
|
|
1201
1102
|
/**
|
|
1202
1103
|
* Serializes the data stores into a string.
|
|
1203
1104
|
* @param useEncoding Whether to encode the data using each DataStore's `encodeData()` method
|
|
1204
1105
|
* @param stringified Whether to return the result as a string or as an array of `SerializedDataStore` objects
|
|
1205
1106
|
*/
|
|
1206
|
-
serialize(useEncoding = true, stringified = true) {
|
|
1207
|
-
return
|
|
1208
|
-
return this.serializePartial(this.stores.map((s) => s.id), useEncoding, stringified);
|
|
1209
|
-
});
|
|
1107
|
+
async serialize(useEncoding = true, stringified = true) {
|
|
1108
|
+
return this.serializePartial(this.stores.map((s) => s.id), useEncoding, stringified);
|
|
1210
1109
|
}
|
|
1211
1110
|
/**
|
|
1212
1111
|
* Deserializes the data exported via {@linkcode serialize()} and imports only a subset into the DataStore instances.
|
|
1213
1112
|
* Also triggers the migration process if the data format has changed.
|
|
1214
1113
|
*/
|
|
1215
|
-
deserializePartial(stores, data) {
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
throw new ChecksumMismatchError(`Checksum mismatch for DataStore with ID "${storeData.id}"!
|
|
1114
|
+
async deserializePartial(stores, data) {
|
|
1115
|
+
const deserStores = typeof data === "string" ? JSON.parse(data) : data;
|
|
1116
|
+
if (!Array.isArray(deserStores) || !deserStores.every(_DataStoreSerializer.isSerializedDataStoreObj))
|
|
1117
|
+
throw new TypeError("Invalid serialized data format! Expected an array of SerializedDataStore objects.");
|
|
1118
|
+
const resolveStoreId = (id) => {
|
|
1119
|
+
var _a;
|
|
1120
|
+
return ((_a = Object.entries(this.options.remapIds).find(([, v]) => v.includes(id))) == null ? void 0 : _a[0]) ?? id;
|
|
1121
|
+
};
|
|
1122
|
+
const matchesFilter = (id) => typeof stores === "function" ? stores(id) : stores.includes(id);
|
|
1123
|
+
for (const storeData of deserStores) {
|
|
1124
|
+
const effectiveId = resolveStoreId(storeData.id);
|
|
1125
|
+
if (!matchesFilter(effectiveId))
|
|
1126
|
+
continue;
|
|
1127
|
+
const storeInst = this.stores.find((s) => s.id === effectiveId);
|
|
1128
|
+
if (!storeInst)
|
|
1129
|
+
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.`);
|
|
1130
|
+
if (this.options.ensureIntegrity && typeof storeData.checksum === "string") {
|
|
1131
|
+
const checksum = await this.calcChecksum(storeData.data);
|
|
1132
|
+
if (checksum !== storeData.checksum)
|
|
1133
|
+
throw new ChecksumMismatchError(`Checksum mismatch for DataStore with ID "${storeData.id}"!
|
|
1236
1134
|
Expected: ${storeData.checksum}
|
|
1237
1135
|
Has: ${checksum}`);
|
|
1238
|
-
}
|
|
1239
|
-
const decodedData = storeData.encoded && storeInst.encodingEnabled() ? yield storeInst.decodeData[1](storeData.data) : storeData.data;
|
|
1240
|
-
if (storeData.formatVersion && !isNaN(Number(storeData.formatVersion)) && Number(storeData.formatVersion) < storeInst.formatVersion)
|
|
1241
|
-
yield storeInst.runMigrations(JSON.parse(decodedData), Number(storeData.formatVersion), false);
|
|
1242
|
-
else
|
|
1243
|
-
yield storeInst.setData(JSON.parse(decodedData));
|
|
1244
1136
|
}
|
|
1245
|
-
|
|
1137
|
+
const decodedData = storeData.encoded && storeInst.encodingEnabled() ? await storeInst.decodeData[1](storeData.data) : storeData.data;
|
|
1138
|
+
if (storeData.formatVersion && !isNaN(Number(storeData.formatVersion)) && Number(storeData.formatVersion) < storeInst.formatVersion)
|
|
1139
|
+
await storeInst.runMigrations(JSON.parse(decodedData), Number(storeData.formatVersion), false);
|
|
1140
|
+
else
|
|
1141
|
+
await storeInst.setData(JSON.parse(decodedData));
|
|
1142
|
+
}
|
|
1246
1143
|
}
|
|
1247
1144
|
/**
|
|
1248
1145
|
* Deserializes the data exported via {@linkcode serialize()} and imports the data into all matching DataStore instances.
|
|
1249
1146
|
* Also triggers the migration process if the data format has changed.
|
|
1250
1147
|
*/
|
|
1251
|
-
deserialize(data) {
|
|
1252
|
-
return
|
|
1253
|
-
return this.deserializePartial(this.stores.map((s) => s.id), data);
|
|
1254
|
-
});
|
|
1148
|
+
async deserialize(data) {
|
|
1149
|
+
return this.deserializePartial(this.stores.map((s) => s.id), data);
|
|
1255
1150
|
}
|
|
1256
1151
|
/**
|
|
1257
1152
|
* Loads the persistent data of the DataStore instances into the in-memory cache.
|
|
@@ -1259,40 +1154,32 @@ Has: ${checksum}`);
|
|
|
1259
1154
|
* @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
|
|
1260
1155
|
* @returns Returns a PromiseSettledResult array with the results of each DataStore instance in the format `{ id: string, data: object }`
|
|
1261
1156
|
*/
|
|
1262
|
-
loadStoresData(stores) {
|
|
1263
|
-
return
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
};
|
|
1270
|
-
}))
|
|
1271
|
-
);
|
|
1272
|
-
});
|
|
1157
|
+
async loadStoresData(stores) {
|
|
1158
|
+
return Promise.allSettled(
|
|
1159
|
+
this.getStoresFiltered(stores).map(async (store) => ({
|
|
1160
|
+
id: store.id,
|
|
1161
|
+
data: await store.loadData()
|
|
1162
|
+
}))
|
|
1163
|
+
);
|
|
1273
1164
|
}
|
|
1274
1165
|
/**
|
|
1275
1166
|
* Resets the persistent and in-memory data of the DataStore instances to their default values.
|
|
1276
1167
|
* @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
|
|
1277
1168
|
*/
|
|
1278
|
-
resetStoresData(stores) {
|
|
1279
|
-
return
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
);
|
|
1283
|
-
});
|
|
1169
|
+
async resetStoresData(stores) {
|
|
1170
|
+
return Promise.allSettled(
|
|
1171
|
+
this.getStoresFiltered(stores).map((store) => store.saveDefaultData())
|
|
1172
|
+
);
|
|
1284
1173
|
}
|
|
1285
1174
|
/**
|
|
1286
1175
|
* Deletes the persistent data of the DataStore instances.
|
|
1287
1176
|
* Leaves the in-memory data untouched.
|
|
1288
1177
|
* @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
|
|
1289
1178
|
*/
|
|
1290
|
-
deleteStoresData(stores) {
|
|
1291
|
-
return
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
);
|
|
1295
|
-
});
|
|
1179
|
+
async deleteStoresData(stores) {
|
|
1180
|
+
return Promise.allSettled(
|
|
1181
|
+
this.getStoresFiltered(stores).map((store) => store.deleteData())
|
|
1182
|
+
);
|
|
1296
1183
|
}
|
|
1297
1184
|
/** Checks if a given value is an array of SerializedDataStore objects */
|
|
1298
1185
|
static isSerializedDataStoreObjArray(obj) {
|
|
@@ -1317,26 +1204,26 @@ var createNanoEvents = () => ({
|
|
|
1317
1204
|
},
|
|
1318
1205
|
events: {},
|
|
1319
1206
|
on(event, cb) {
|
|
1320
|
-
var _a;
|
|
1321
1207
|
;
|
|
1322
|
-
(
|
|
1208
|
+
(this.events[event] ||= []).push(cb);
|
|
1323
1209
|
return () => {
|
|
1324
|
-
var
|
|
1325
|
-
this.events[event] = (
|
|
1210
|
+
var _a;
|
|
1211
|
+
this.events[event] = (_a = this.events[event]) == null ? void 0 : _a.filter((i) => cb !== i);
|
|
1326
1212
|
};
|
|
1327
1213
|
}
|
|
1328
1214
|
});
|
|
1329
1215
|
|
|
1330
1216
|
// lib/NanoEmitter.ts
|
|
1331
1217
|
var NanoEmitter = class {
|
|
1218
|
+
events = createNanoEvents();
|
|
1219
|
+
eventUnsubscribes = [];
|
|
1220
|
+
emitterOptions;
|
|
1332
1221
|
/** Creates a new instance of NanoEmitter - a lightweight event emitter with helper methods and a strongly typed event map */
|
|
1333
1222
|
constructor(options = {}) {
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
publicEmit: false
|
|
1339
|
-
}, options);
|
|
1223
|
+
this.emitterOptions = {
|
|
1224
|
+
publicEmit: false,
|
|
1225
|
+
...options
|
|
1226
|
+
};
|
|
1340
1227
|
}
|
|
1341
1228
|
//#region on
|
|
1342
1229
|
/**
|
|
@@ -1428,11 +1315,12 @@ var NanoEmitter = class {
|
|
|
1428
1315
|
this.eventUnsubscribes = this.eventUnsubscribes.filter((u) => !allUnsubs.includes(u));
|
|
1429
1316
|
};
|
|
1430
1317
|
for (const opts of Array.isArray(options) ? options : [options]) {
|
|
1431
|
-
const optsWithDefaults =
|
|
1318
|
+
const optsWithDefaults = {
|
|
1432
1319
|
allOf: [],
|
|
1433
1320
|
oneOf: [],
|
|
1434
|
-
once: false
|
|
1435
|
-
|
|
1321
|
+
once: false,
|
|
1322
|
+
...opts
|
|
1323
|
+
};
|
|
1436
1324
|
const {
|
|
1437
1325
|
oneOf,
|
|
1438
1326
|
allOf,
|
|
@@ -1506,6 +1394,172 @@ var NanoEmitter = class {
|
|
|
1506
1394
|
}
|
|
1507
1395
|
};
|
|
1508
1396
|
|
|
1397
|
+
// lib/Debouncer.ts
|
|
1398
|
+
var Debouncer = class extends NanoEmitter {
|
|
1399
|
+
/**
|
|
1400
|
+
* Creates a new debouncer with the specified timeout and edge type.
|
|
1401
|
+
* @param timeout Timeout in milliseconds between letting through calls - defaults to 200
|
|
1402
|
+
* @param type The edge type to use for the debouncer - see {@linkcode DebouncerType} for details or [the documentation for an explanation and diagram](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#debouncer) - defaults to "immediate"
|
|
1403
|
+
*/
|
|
1404
|
+
constructor(timeout = 200, type = "immediate") {
|
|
1405
|
+
super();
|
|
1406
|
+
this.timeout = timeout;
|
|
1407
|
+
this.type = type;
|
|
1408
|
+
}
|
|
1409
|
+
/** All registered listener functions and the time they were attached */
|
|
1410
|
+
listeners = [];
|
|
1411
|
+
/** The currently active timeout */
|
|
1412
|
+
activeTimeout;
|
|
1413
|
+
/** The latest queued call */
|
|
1414
|
+
queuedCall;
|
|
1415
|
+
//#region listeners
|
|
1416
|
+
/** Adds a listener function that will be called on timeout */
|
|
1417
|
+
addListener(fn) {
|
|
1418
|
+
this.listeners.push(fn);
|
|
1419
|
+
}
|
|
1420
|
+
/** Removes the listener with the specified function reference */
|
|
1421
|
+
removeListener(fn) {
|
|
1422
|
+
const idx = this.listeners.findIndex((l) => l === fn);
|
|
1423
|
+
idx !== -1 && this.listeners.splice(idx, 1);
|
|
1424
|
+
}
|
|
1425
|
+
/** Removes all listeners */
|
|
1426
|
+
removeAllListeners() {
|
|
1427
|
+
this.listeners = [];
|
|
1428
|
+
}
|
|
1429
|
+
/** Returns all registered listeners */
|
|
1430
|
+
getListeners() {
|
|
1431
|
+
return this.listeners;
|
|
1432
|
+
}
|
|
1433
|
+
//#region timeout
|
|
1434
|
+
/** Sets the timeout for the debouncer */
|
|
1435
|
+
setTimeout(timeout) {
|
|
1436
|
+
this.emit("change", this.timeout = timeout, this.type);
|
|
1437
|
+
}
|
|
1438
|
+
/** Returns the current timeout */
|
|
1439
|
+
getTimeout() {
|
|
1440
|
+
return this.timeout;
|
|
1441
|
+
}
|
|
1442
|
+
/** Whether the timeout is currently active, meaning any latest call to the {@linkcode call()} method will be queued */
|
|
1443
|
+
isTimeoutActive() {
|
|
1444
|
+
return typeof this.activeTimeout !== "undefined";
|
|
1445
|
+
}
|
|
1446
|
+
//#region type
|
|
1447
|
+
/** Sets the edge type for the debouncer */
|
|
1448
|
+
setType(type) {
|
|
1449
|
+
this.emit("change", this.timeout, this.type = type);
|
|
1450
|
+
}
|
|
1451
|
+
/** Returns the current edge type */
|
|
1452
|
+
getType() {
|
|
1453
|
+
return this.type;
|
|
1454
|
+
}
|
|
1455
|
+
//#region call
|
|
1456
|
+
/** Use this to call the debouncer with the specified arguments that will be passed to all listener functions registered with {@linkcode addListener()} */
|
|
1457
|
+
call(...args) {
|
|
1458
|
+
const cl = (...a) => {
|
|
1459
|
+
this.queuedCall = void 0;
|
|
1460
|
+
this.emit("call", ...a);
|
|
1461
|
+
this.listeners.forEach((l) => l.call(this, ...a));
|
|
1462
|
+
};
|
|
1463
|
+
const setRepeatTimeout = () => {
|
|
1464
|
+
this.activeTimeout = setTimeout(() => {
|
|
1465
|
+
if (this.queuedCall) {
|
|
1466
|
+
this.queuedCall();
|
|
1467
|
+
setRepeatTimeout();
|
|
1468
|
+
} else
|
|
1469
|
+
this.activeTimeout = void 0;
|
|
1470
|
+
}, this.timeout);
|
|
1471
|
+
};
|
|
1472
|
+
switch (this.type) {
|
|
1473
|
+
case "immediate":
|
|
1474
|
+
if (typeof this.activeTimeout === "undefined") {
|
|
1475
|
+
cl(...args);
|
|
1476
|
+
setRepeatTimeout();
|
|
1477
|
+
} else
|
|
1478
|
+
this.queuedCall = () => cl(...args);
|
|
1479
|
+
break;
|
|
1480
|
+
case "idle":
|
|
1481
|
+
if (this.activeTimeout)
|
|
1482
|
+
clearTimeout(this.activeTimeout);
|
|
1483
|
+
this.activeTimeout = setTimeout(() => {
|
|
1484
|
+
cl(...args);
|
|
1485
|
+
this.activeTimeout = void 0;
|
|
1486
|
+
}, this.timeout);
|
|
1487
|
+
break;
|
|
1488
|
+
default:
|
|
1489
|
+
throw new TypeError(`Invalid debouncer type: ${this.type}`);
|
|
1490
|
+
}
|
|
1491
|
+
}
|
|
1492
|
+
};
|
|
1493
|
+
function debounce(fn, timeout = 200, type = "immediate") {
|
|
1494
|
+
const debouncer = new Debouncer(timeout, type);
|
|
1495
|
+
debouncer.addListener(fn);
|
|
1496
|
+
const func = ((...args) => debouncer.call(...args));
|
|
1497
|
+
func.debouncer = debouncer;
|
|
1498
|
+
return func;
|
|
1499
|
+
}
|
|
1500
|
+
`oneOf` or `allOf` or both must be provided in the options");
|
|
1501
|
+
const curEvtUnsubs = [];
|
|
1502
|
+
const checkUnsubAllEvt = (force = false) => {
|
|
1503
|
+
if (!(signal == null ? void 0 : signal.aborted) && !force)
|
|
1504
|
+
return;
|
|
1505
|
+
for (const unsub of curEvtUnsubs)
|
|
1506
|
+
unsub();
|
|
1507
|
+
curEvtUnsubs.splice(0, curEvtUnsubs.length);
|
|
1508
|
+
this.eventUnsubscribes = this.eventUnsubscribes.filter((u) => !curEvtUnsubs.includes(u));
|
|
1509
|
+
};
|
|
1510
|
+
const allOfEmitted = /* @__PURE__ */ new Set();
|
|
1511
|
+
const allOfConditionMet = () => allOf.length === 0 || allOfEmitted.size === allOf.length;
|
|
1512
|
+
for (const event of oneOf) {
|
|
1513
|
+
const unsub = this.events.on(event, ((...args) => {
|
|
1514
|
+
checkUnsubAllEvt();
|
|
1515
|
+
if (allOfConditionMet()) {
|
|
1516
|
+
callback(event, ...args);
|
|
1517
|
+
if (once)
|
|
1518
|
+
checkUnsubAllEvt(true);
|
|
1519
|
+
}
|
|
1520
|
+
}));
|
|
1521
|
+
curEvtUnsubs.push(unsub);
|
|
1522
|
+
}
|
|
1523
|
+
for (const event of allOf) {
|
|
1524
|
+
const unsub = this.events.on(event, ((...args) => {
|
|
1525
|
+
checkUnsubAllEvt();
|
|
1526
|
+
allOfEmitted.add(event);
|
|
1527
|
+
if (allOfConditionMet() && (oneOf.length === 0 || oneOf.includes(event))) {
|
|
1528
|
+
callback(event, ...args);
|
|
1529
|
+
if (once)
|
|
1530
|
+
checkUnsubAllEvt(true);
|
|
1531
|
+
}
|
|
1532
|
+
}));
|
|
1533
|
+
curEvtUnsubs.push(unsub);
|
|
1534
|
+
}
|
|
1535
|
+
allUnsubs.push(() => checkUnsubAllEvt(true));
|
|
1536
|
+
}
|
|
1537
|
+
return unsubAll;
|
|
1538
|
+
}
|
|
1539
|
+
//#region emit
|
|
1540
|
+
/**
|
|
1541
|
+
* Emits an event on this instance.
|
|
1542
|
+
* - ⚠️ Needs `publicEmit` to be set to true in the NanoEmitter constructor or super() call!
|
|
1543
|
+
* @param event The event to emit
|
|
1544
|
+
* @param args The arguments to pass to the event listeners
|
|
1545
|
+
* @returns Returns true if `publicEmit` is true and the event was emitted successfully
|
|
1546
|
+
*/
|
|
1547
|
+
emit(event, ...args) {
|
|
1548
|
+
if (this.emitterOptions.publicEmit) {
|
|
1549
|
+
this.events.emit(event, ...args);
|
|
1550
|
+
return true;
|
|
1551
|
+
}
|
|
1552
|
+
return false;
|
|
1553
|
+
}
|
|
1554
|
+
//#region unsubscribeAll
|
|
1555
|
+
/** Unsubscribes all event listeners from this instance */
|
|
1556
|
+
unsubscribeAll() {
|
|
1557
|
+
for (const unsub of this.eventUnsubscribes)
|
|
1558
|
+
unsub();
|
|
1559
|
+
this.eventUnsubscribes = [];
|
|
1560
|
+
}
|
|
1561
|
+
};
|
|
1562
|
+
|
|
1509
1563
|
// lib/Debouncer.ts
|
|
1510
1564
|
var Debouncer = class extends NanoEmitter {
|
|
1511
1565
|
/**
|
|
@@ -1611,7 +1665,7 @@ function debounce(fn, timeout = 200, type = "immediate") {
|
|
|
1611
1665
|
}
|
|
1612
1666
|
|
|
1613
1667
|
if(__exports != exports)module.exports = exports;return module.exports}));
|
|
1614
|
-
|
|
1668
|
+
//# sourceMappingURL=CoreUtils.umd.js.map
|
|
1615
1669
|
|
|
1616
1670
|
|
|
1617
1671
|
if (typeof module.exports == "object" && typeof exports == "object") {
|