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