@sv443-network/coreutils 3.0.8 → 3.1.0

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