@sv443-network/coreutils 3.0.2 → 3.0.3

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