@sv443-network/coreutils 3.0.2 → 3.0.4

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,35 +631,59 @@ 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;
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)
617
661
  this.migrateIds = Array.isArray(opts.migrateIds) ? opts.migrateIds : [opts.migrateIds];
618
- this.encodeData = opts.encodeData;
619
- this.decodeData = opts.decodeData;
620
662
  this.engine = typeof opts.engine === "function" ? opts.engine() : opts.engine;
621
663
  this.options = opts;
622
- if (typeof opts.compressionFormat === "undefined")
623
- this.compressionFormat = opts.compressionFormat = ((_a = opts.encodeData) == null ? void 0 : _a[0]) ?? "deflate-raw";
624
- 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")];
627
- } else if ("encodeData" in opts && "decodeData" in opts && Array.isArray(opts.encodeData) && Array.isArray(opts.decodeData)) {
664
+ if ("encodeData" in opts && "decodeData" in opts && Array.isArray(opts.encodeData) && Array.isArray(opts.decodeData)) {
628
665
  this.encodeData = [opts.encodeData[0], opts.encodeData[1]];
629
666
  this.decodeData = [opts.decodeData[0], opts.decodeData[1]];
630
- this.compressionFormat = opts.encodeData[0] ?? null;
667
+ this.compressionFormat = (_b = opts.encodeData[0]) != null ? _b : null;
631
668
  } else if (opts.compressionFormat === null) {
632
669
  this.encodeData = void 0;
633
670
  this.decodeData = void 0;
634
671
  this.compressionFormat = null;
635
- } else
636
- throw new TypeError("Either `compressionFormat` or `encodeData` and `decodeData` have to be set and valid, but not all three at a time. Please refer to the documentation for more info.");
637
- this.engine.setDataStoreOptions(opts);
672
+ } else {
673
+ const fmt = typeof opts.compressionFormat === "string" ? opts.compressionFormat : "deflate-raw";
674
+ 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
+ })];
681
+ }
682
+ this.engine.setDataStoreOptions({
683
+ id: this.id,
684
+ encodeData: this.encodeData,
685
+ decodeData: this.decodeData
686
+ });
638
687
  }
639
688
  //#region loadData
640
689
  /**
@@ -642,66 +691,69 @@ var DataStore = class {
642
691
  * Automatically populates persistent storage with default data if it doesn't contain any data yet.
643
692
  * Also runs all necessary migration functions if the data format has changed since the last time the data was saved.
644
693
  */
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}`));
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);
667
720
  }
668
- await Promise.allSettled(promises);
721
+ if (isNaN(dsVer) || dsVer < dsFmtVer)
722
+ yield this.engine.setValue("__ds_fmt_ver", dsFmtVer);
669
723
  }
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;
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") {
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;
690
755
  }
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
- }
756
+ });
705
757
  }
706
758
  //#region getData
707
759
  /**
@@ -719,25 +771,27 @@ var DataStore = class {
719
771
  setData(data) {
720
772
  if (this.memoryCache)
721
773
  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())),
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())),
725
777
  this.engine.setValue(`__ds-${this.id}-ver`, this.formatVersion),
726
778
  this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat)
727
779
  ]);
728
780
  resolve();
729
- });
781
+ }));
730
782
  }
731
783
  //#region saveDefaultData
732
784
  /** 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
- ]);
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
+ });
741
795
  }
742
796
  //#region deleteData
743
797
  /**
@@ -745,14 +799,16 @@ var DataStore = class {
745
799
  * The in-memory cache will be left untouched, so you may still access the data with {@linkcode getData()}
746
800
  * Calling {@linkcode loadData()} or {@linkcode setData()} after this method was called will recreate persistent storage with the cached or default data.
747
801
  */
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));
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
+ });
756
812
  }
757
813
  //#region encodingEnabled
758
814
  /** Returns whether encoding and decoding are enabled for this DataStore instance */
@@ -767,73 +823,77 @@ var DataStore = class {
767
823
  *
768
824
  * 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
825
  */
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();
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.getData();
845
+ }
788
846
  }
789
847
  }
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);
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
+ });
800
858
  }
801
859
  //#region migrateId
802
860
  /**
803
861
  * Tries to migrate the currently saved persistent data from one or more old IDs to the ID set in the constructor.
804
862
  * 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
863
  */
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)
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`)
814
886
  ]);
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
- }));
887
+ })));
888
+ });
829
889
  }
830
890
  };
831
891
 
832
892
  // lib/DataStoreEngine.ts
833
893
  var DataStoreEngine = class {
834
- dataStoreOptions;
835
894
  // setDataStoreOptions() is called from inside the DataStore constructor to set this value
836
895
  constructor(options) {
896
+ __publicField(this, "dataStoreOptions");
837
897
  if (options)
838
898
  this.dataStoreOptions = options;
839
899
  }
@@ -843,25 +903,29 @@ var DataStoreEngine = class {
843
903
  }
844
904
  //#region serialization api
845
905
  /** 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;
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
+ });
856
918
  }
857
919
  /** 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);
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
+ });
865
929
  }
866
930
  //#region misc api
867
931
  /** Throws an error if the DataStoreOptions are not set or invalid */
@@ -879,13 +943,12 @@ var DataStoreEngine = class {
879
943
  try {
880
944
  if ("structuredClone" in globalThis)
881
945
  return structuredClone(obj);
882
- } catch {
946
+ } catch (e) {
883
947
  }
884
948
  return JSON.parse(JSON.stringify(obj));
885
949
  }
886
950
  };
887
951
  var BrowserStorageEngine = class extends DataStoreEngine {
888
- options;
889
952
  /**
890
953
  * Creates an instance of `BrowserStorageEngine`.
891
954
  *
@@ -894,36 +957,40 @@ var BrowserStorageEngine = class extends DataStoreEngine {
894
957
  */
895
958
  constructor(options) {
896
959
  super(options == null ? void 0 : options.dataStoreOptions);
897
- this.options = {
898
- type: "localStorage",
899
- ...options
900
- };
960
+ __publicField(this, "options");
961
+ this.options = __spreadValues({
962
+ type: "localStorage"
963
+ }, options);
901
964
  }
902
965
  //#region storage api
903
966
  /** 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;
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
+ });
907
972
  }
908
973
  /** 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));
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
+ });
914
981
  }
915
982
  /** 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);
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
+ });
921
990
  }
922
991
  };
923
992
  var fs;
924
993
  var FileStorageEngine = class extends DataStoreEngine {
925
- options;
926
- fileAccessQueue = Promise.resolve();
927
994
  /**
928
995
  * Creates an instance of `FileStorageEngine`.
929
996
  *
@@ -932,122 +999,136 @@ var FileStorageEngine = class extends DataStoreEngine {
932
999
  */
933
1000
  constructor(options) {
934
1001
  super(options == null ? void 0 : options.dataStoreOptions);
935
- this.options = {
936
- filePath: (id) => `.ds-${id}`,
937
- ...options
938
- };
1002
+ __publicField(this, "options");
1003
+ __publicField(this, "fileAccessQueue", Promise.resolve());
1004
+ this.options = __spreadValues({
1005
+ filePath: (id) => `.ds-${id}`
1006
+ }, options);
939
1007
  }
940
1008
  //#region json file
941
1009
  /** 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
- }
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
+ });
956
1026
  }
957
1027
  /** 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
- }
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
+ });
972
1044
  }
973
1045
  //#region storage api
974
1046
  /** 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")
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")
1054
+ return defaultValue;
1055
+ if (typeof value === "string")
1056
+ return value;
983
1057
  return value;
984
- return value;
1058
+ });
985
1059
  }
986
1060
  /** 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(() => {
1061
+ setValue(name, value) {
1062
+ return __async(this, null, function* () {
1063
+ this.fileAccessQueue = this.fileAccessQueue.then(() => __async(this, null, function* () {
1064
+ let data = yield this.readFile();
1065
+ if (!data)
1066
+ data = {};
1067
+ data[name] = value;
1068
+ yield this.writeFile(data);
1069
+ })).catch((err) => {
1070
+ console.error("Error in setValue:", err);
1071
+ throw err;
1072
+ });
1073
+ yield this.fileAccessQueue.catch(() => {
1074
+ });
999
1075
  });
1000
1076
  }
1001
1077
  /** 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(() => {
1078
+ deleteValue(name) {
1079
+ return __async(this, null, function* () {
1080
+ this.fileAccessQueue = this.fileAccessQueue.then(() => __async(this, null, function* () {
1081
+ const data = yield this.readFile();
1082
+ if (!data)
1083
+ return;
1084
+ delete data[name];
1085
+ yield this.writeFile(data);
1086
+ })).catch((err) => {
1087
+ console.error("Error in deleteValue:", err);
1088
+ throw err;
1089
+ });
1090
+ yield this.fileAccessQueue.catch(() => {
1091
+ });
1014
1092
  });
1015
1093
  }
1016
1094
  /** 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
- }
1095
+ deleteStorage() {
1096
+ return __async(this, null, function* () {
1097
+ var _a;
1098
+ this.ensureDataStoreOptions();
1099
+ try {
1100
+ if (!fs)
1101
+ fs = (_a = yield import("fs/promises")) == null ? void 0 : _a.default;
1102
+ if (!fs)
1103
+ throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
1104
+ const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
1105
+ return yield fs.unlink(path);
1106
+ } catch (err) {
1107
+ console.error("Error deleting file:", err);
1108
+ }
1109
+ });
1030
1110
  }
1031
1111
  };
1032
1112
 
1033
1113
  // lib/DataStoreSerializer.ts
1034
1114
  var DataStoreSerializer = class _DataStoreSerializer {
1035
- stores;
1036
- options;
1037
1115
  constructor(stores, options = {}) {
1116
+ __publicField(this, "stores");
1117
+ __publicField(this, "options");
1038
1118
  if (!crypto || !crypto.subtle)
1039
1119
  throw new ScriptContextError("DataStoreSerializer has to run in a secure context (HTTPS) or in another environment that implements the subtleCrypto API!");
1040
1120
  this.stores = stores;
1041
- this.options = {
1121
+ this.options = __spreadValues({
1042
1122
  addChecksum: true,
1043
1123
  ensureIntegrity: true,
1044
- remapIds: {},
1045
- ...options
1046
- };
1124
+ remapIds: {}
1125
+ }, options);
1047
1126
  }
1048
1127
  /** Calculates the checksum of a string */
1049
- async calcChecksum(input) {
1050
- return computeHash(input, "SHA-256");
1128
+ calcChecksum(input) {
1129
+ return __async(this, null, function* () {
1130
+ return computeHash(input, "SHA-256");
1131
+ });
1051
1132
  }
1052
1133
  /**
1053
1134
  * Serializes only a subset of the data stores into a string.
@@ -1055,72 +1136,80 @@ var DataStoreSerializer = class _DataStoreSerializer {
1055
1136
  * @param useEncoding Whether to encode the data using each DataStore's `encodeData()` method
1056
1137
  * @param stringified Whether to return the result as a string or as an array of `SerializedDataStore` objects
1057
1138
  */
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;
1139
+ serializePartial(stores, useEncoding = true, stringified = true) {
1140
+ return __async(this, null, function* () {
1141
+ var _a;
1142
+ const serData = [];
1143
+ const filteredStores = this.stores.filter((s) => typeof stores === "function" ? stores(s.id) : stores.includes(s.id));
1144
+ for (const storeInst of filteredStores) {
1145
+ const encoded = Boolean(useEncoding && storeInst.encodingEnabled() && ((_a = storeInst.encodeData) == null ? void 0 : _a[1]));
1146
+ const rawData = storeInst.memoryCache ? storeInst.getData() : yield storeInst.loadData();
1147
+ const data = encoded ? yield storeInst.encodeData[1](JSON.stringify(rawData)) : JSON.stringify(rawData);
1148
+ serData.push({
1149
+ id: storeInst.id,
1150
+ data,
1151
+ formatVersion: storeInst.formatVersion,
1152
+ encoded,
1153
+ checksum: this.options.addChecksum ? yield this.calcChecksum(data) : void 0
1154
+ });
1155
+ }
1156
+ return stringified ? JSON.stringify(serData) : serData;
1157
+ });
1075
1158
  }
1076
1159
  /**
1077
1160
  * Serializes the data stores into a string.
1078
1161
  * @param useEncoding Whether to encode the data using each DataStore's `encodeData()` method
1079
1162
  * @param stringified Whether to return the result as a string or as an array of `SerializedDataStore` objects
1080
1163
  */
1081
- async serialize(useEncoding = true, stringified = true) {
1082
- return this.serializePartial(this.stores.map((s) => s.id), useEncoding, stringified);
1164
+ serialize(useEncoding = true, stringified = true) {
1165
+ return __async(this, null, function* () {
1166
+ return this.serializePartial(this.stores.map((s) => s.id), useEncoding, stringified);
1167
+ });
1083
1168
  }
1084
1169
  /**
1085
1170
  * Deserializes the data exported via {@linkcode serialize()} and imports only a subset into the DataStore instances.
1086
1171
  * Also triggers the migration process if the data format has changed.
1087
1172
  */
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}"!
1173
+ deserializePartial(stores, data) {
1174
+ return __async(this, null, function* () {
1175
+ const deserStores = typeof data === "string" ? JSON.parse(data) : data;
1176
+ if (!Array.isArray(deserStores) || !deserStores.every(_DataStoreSerializer.isSerializedDataStoreObj))
1177
+ throw new TypeError("Invalid serialized data format! Expected an array of SerializedDataStore objects.");
1178
+ const resolveStoreId = (id) => {
1179
+ var _a, _b;
1180
+ return (_b = (_a = Object.entries(this.options.remapIds).find(([, v]) => v.includes(id))) == null ? void 0 : _a[0]) != null ? _b : id;
1181
+ };
1182
+ const matchesFilter = (id) => typeof stores === "function" ? stores(id) : stores.includes(id);
1183
+ for (const storeData of deserStores) {
1184
+ const effectiveId = resolveStoreId(storeData.id);
1185
+ if (!matchesFilter(effectiveId))
1186
+ continue;
1187
+ const storeInst = this.stores.find((s) => s.id === effectiveId);
1188
+ if (!storeInst)
1189
+ 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.`);
1190
+ if (this.options.ensureIntegrity && typeof storeData.checksum === "string") {
1191
+ const checksum = yield this.calcChecksum(storeData.data);
1192
+ if (checksum !== storeData.checksum)
1193
+ throw new ChecksumMismatchError(`Checksum mismatch for DataStore with ID "${storeData.id}"!
1108
1194
  Expected: ${storeData.checksum}
1109
1195
  Has: ${checksum}`);
1196
+ }
1197
+ const decodedData = storeData.encoded && storeInst.encodingEnabled() ? yield storeInst.decodeData[1](storeData.data) : storeData.data;
1198
+ if (storeData.formatVersion && !isNaN(Number(storeData.formatVersion)) && Number(storeData.formatVersion) < storeInst.formatVersion)
1199
+ yield storeInst.runMigrations(JSON.parse(decodedData), Number(storeData.formatVersion), false);
1200
+ else
1201
+ yield storeInst.setData(JSON.parse(decodedData));
1110
1202
  }
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
- }
1203
+ });
1117
1204
  }
1118
1205
  /**
1119
1206
  * Deserializes the data exported via {@linkcode serialize()} and imports the data into all matching DataStore instances.
1120
1207
  * Also triggers the migration process if the data format has changed.
1121
1208
  */
1122
- async deserialize(data) {
1123
- return this.deserializePartial(this.stores.map((s) => s.id), data);
1209
+ deserialize(data) {
1210
+ return __async(this, null, function* () {
1211
+ return this.deserializePartial(this.stores.map((s) => s.id), data);
1212
+ });
1124
1213
  }
1125
1214
  /**
1126
1215
  * Loads the persistent data of the DataStore instances into the in-memory cache.
@@ -1128,32 +1217,40 @@ Has: ${checksum}`);
1128
1217
  * @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
1218
  * @returns Returns a PromiseSettledResult array with the results of each DataStore instance in the format `{ id: string, data: object }`
1130
1219
  */
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
- );
1220
+ loadStoresData(stores) {
1221
+ return __async(this, null, function* () {
1222
+ return Promise.allSettled(
1223
+ this.getStoresFiltered(stores).map((store) => __async(this, null, function* () {
1224
+ return {
1225
+ id: store.id,
1226
+ data: yield store.loadData()
1227
+ };
1228
+ }))
1229
+ );
1230
+ });
1138
1231
  }
1139
1232
  /**
1140
1233
  * Resets the persistent and in-memory data of the DataStore instances to their default values.
1141
1234
  * @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
1235
  */
1143
- async resetStoresData(stores) {
1144
- return Promise.allSettled(
1145
- this.getStoresFiltered(stores).map((store) => store.saveDefaultData())
1146
- );
1236
+ resetStoresData(stores) {
1237
+ return __async(this, null, function* () {
1238
+ return Promise.allSettled(
1239
+ this.getStoresFiltered(stores).map((store) => store.saveDefaultData())
1240
+ );
1241
+ });
1147
1242
  }
1148
1243
  /**
1149
1244
  * Deletes the persistent data of the DataStore instances.
1150
1245
  * Leaves the in-memory data untouched.
1151
1246
  * @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
1247
  */
1153
- async deleteStoresData(stores) {
1154
- return Promise.allSettled(
1155
- this.getStoresFiltered(stores).map((store) => store.deleteData())
1156
- );
1248
+ deleteStoresData(stores) {
1249
+ return __async(this, null, function* () {
1250
+ return Promise.allSettled(
1251
+ this.getStoresFiltered(stores).map((store) => store.deleteData())
1252
+ );
1253
+ });
1157
1254
  }
1158
1255
  /** Checks if a given value is an array of SerializedDataStore objects */
1159
1256
  static isSerializedDataStoreObjArray(obj) {
@@ -1178,26 +1275,26 @@ var createNanoEvents = () => ({
1178
1275
  },
1179
1276
  events: {},
1180
1277
  on(event, cb) {
1278
+ var _a;
1181
1279
  ;
1182
- (this.events[event] ||= []).push(cb);
1280
+ ((_a = this.events)[event] || (_a[event] = [])).push(cb);
1183
1281
  return () => {
1184
- var _a;
1185
- this.events[event] = (_a = this.events[event]) == null ? void 0 : _a.filter((i) => cb !== i);
1282
+ var _a2;
1283
+ this.events[event] = (_a2 = this.events[event]) == null ? void 0 : _a2.filter((i) => cb !== i);
1186
1284
  };
1187
1285
  }
1188
1286
  });
1189
1287
 
1190
1288
  // lib/NanoEmitter.ts
1191
1289
  var NanoEmitter = class {
1192
- events = createNanoEvents();
1193
- eventUnsubscribes = [];
1194
- emitterOptions;
1195
1290
  /** Creates a new instance of NanoEmitter - a lightweight event emitter with helper methods and a strongly typed event map */
1196
1291
  constructor(options = {}) {
1197
- this.emitterOptions = {
1198
- publicEmit: false,
1199
- ...options
1200
- };
1292
+ __publicField(this, "events", createNanoEvents());
1293
+ __publicField(this, "eventUnsubscribes", []);
1294
+ __publicField(this, "emitterOptions");
1295
+ this.emitterOptions = __spreadValues({
1296
+ publicEmit: false
1297
+ }, options);
1201
1298
  }
1202
1299
  //#region on
1203
1300
  /**
@@ -1289,12 +1386,11 @@ var NanoEmitter = class {
1289
1386
  this.eventUnsubscribes = this.eventUnsubscribes.filter((u) => !allUnsubs.includes(u));
1290
1387
  };
1291
1388
  for (const opts of Array.isArray(options) ? options : [options]) {
1292
- const optsWithDefaults = {
1389
+ const optsWithDefaults = __spreadValues({
1293
1390
  allOf: [],
1294
1391
  oneOf: [],
1295
- once: false,
1296
- ...opts
1297
- };
1392
+ once: false
1393
+ }, opts);
1298
1394
  const {
1299
1395
  oneOf,
1300
1396
  allOf,
@@ -1379,13 +1475,13 @@ var Debouncer = class extends NanoEmitter {
1379
1475
  super();
1380
1476
  this.timeout = timeout;
1381
1477
  this.type = type;
1478
+ /** All registered listener functions and the time they were attached */
1479
+ __publicField(this, "listeners", []);
1480
+ /** The currently active timeout */
1481
+ __publicField(this, "activeTimeout");
1482
+ /** The latest queued call */
1483
+ __publicField(this, "queuedCall");
1382
1484
  }
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
1485
  //#region listeners
1390
1486
  /** Adds a listener function that will be called on timeout */
1391
1487
  addListener(fn) {
@@ -1472,27 +1568,5 @@ function debounce(fn, timeout = 200, type = "immediate") {
1472
1568
  return func;
1473
1569
  }
1474
1570
 
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
1571
+ if(__exports != exports)module.exports = exports;return module.exports}));
1572
+ //# sourceMappingURL=CoreUtils.umd.js.map