@sv443-network/coreutils 3.5.0 → 3.5.1

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,13 +16,41 @@
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};
19
20
  "use strict";
20
21
  var __create = Object.create;
21
22
  var __defProp = Object.defineProperty;
22
23
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
23
24
  var __getOwnPropNames = Object.getOwnPropertyNames;
25
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
24
26
  var __getProtoOf = Object.getPrototypeOf;
25
27
  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
+ };
26
54
  var __export = (target, all) => {
27
55
  for (var name in all)
28
56
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -44,6 +72,27 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
44
72
  mod
45
73
  ));
46
74
  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
+ };
47
96
 
48
97
  // lib/index.ts
49
98
  var lib_exports = {};
@@ -197,7 +246,7 @@ function randRange(...args) {
197
246
  return Math.floor(Math.random() * (max - min + 1)) + min;
198
247
  }
199
248
  function roundFixed(num, fractionDigits) {
200
- const scale = 10 ** fractionDigits;
249
+ const scale = __pow(10, fractionDigits);
201
250
  return Math.round(num * scale) / scale;
202
251
  }
203
252
  function valsWithin(a, b, dec = 1, withinRange = 0.5) {
@@ -261,7 +310,7 @@ function darkenColor(color, percent, upperCase = false) {
261
310
  if (isHexCol)
262
311
  return rgbToHex(r, g, b, a, color.startsWith("#"), upperCase);
263
312
  else if (color.startsWith("rgba"))
264
- return `rgba(${r}, ${g}, ${b}, ${a ?? NaN})`;
313
+ return `rgba(${r}, ${g}, ${b}, ${a != null ? a : NaN})`;
265
314
  else
266
315
  return `rgb(${r}, ${g}, ${b})`;
267
316
  }
@@ -295,35 +344,43 @@ function abtoa(buf) {
295
344
  function atoab(str) {
296
345
  return Uint8Array.from(atob(str), (c) => c.charCodeAt(0));
297
346
  }
298
- async function compress(input, compressionFormat, outputType = "string") {
299
- const byteArray = input instanceof Uint8Array ? input : new TextEncoder().encode((input == null ? void 0 : input.toString()) ?? String(input));
300
- const comp = new CompressionStream(compressionFormat);
301
- const writer = comp.writable.getWriter();
302
- writer.write(byteArray);
303
- writer.close();
304
- const uintArr = new Uint8Array(await new Response(comp.readable).arrayBuffer());
305
- return outputType === "arrayBuffer" ? uintArr : abtoa(uintArr);
347
+ function compress(input, compressionFormat, outputType = "string") {
348
+ return __async(this, null, function* () {
349
+ var _a;
350
+ const byteArray = input instanceof Uint8Array ? input : new TextEncoder().encode((_a = input == null ? void 0 : input.toString()) != null ? _a : String(input));
351
+ const comp = new CompressionStream(compressionFormat);
352
+ const writer = comp.writable.getWriter();
353
+ writer.write(byteArray);
354
+ writer.close();
355
+ const uintArr = new Uint8Array(yield new Response(comp.readable).arrayBuffer());
356
+ return outputType === "arrayBuffer" ? uintArr : abtoa(uintArr);
357
+ });
306
358
  }
307
- async function decompress(input, compressionFormat, outputType = "string") {
308
- const byteArray = input instanceof Uint8Array ? input : atoab((input == null ? void 0 : input.toString()) ?? String(input));
309
- const decomp = new DecompressionStream(compressionFormat);
310
- const writer = decomp.writable.getWriter();
311
- writer.write(byteArray);
312
- writer.close();
313
- const uintArr = new Uint8Array(await new Response(decomp.readable).arrayBuffer());
314
- return outputType === "arrayBuffer" ? uintArr : new TextDecoder().decode(uintArr);
359
+ function decompress(input, compressionFormat, outputType = "string") {
360
+ return __async(this, null, function* () {
361
+ var _a;
362
+ const byteArray = input instanceof Uint8Array ? input : atoab((_a = input == null ? void 0 : input.toString()) != null ? _a : String(input));
363
+ const decomp = new DecompressionStream(compressionFormat);
364
+ const writer = decomp.writable.getWriter();
365
+ writer.write(byteArray);
366
+ writer.close();
367
+ const uintArr = new Uint8Array(yield new Response(decomp.readable).arrayBuffer());
368
+ return outputType === "arrayBuffer" ? uintArr : new TextDecoder().decode(uintArr);
369
+ });
315
370
  }
316
- async function computeHash(input, algorithm = "SHA-256") {
317
- let data;
318
- if (typeof input === "string") {
319
- const encoder = new TextEncoder();
320
- data = encoder.encode(input);
321
- } else
322
- data = input;
323
- const hashBuffer = await crypto.subtle.digest(algorithm, data);
324
- const hashArray = Array.from(new Uint8Array(hashBuffer));
325
- const hashHex = hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
326
- return hashHex;
371
+ function computeHash(input, algorithm = "SHA-256") {
372
+ return __async(this, null, function* () {
373
+ let data;
374
+ if (typeof input === "string") {
375
+ const encoder = new TextEncoder();
376
+ data = encoder.encode(input);
377
+ } else
378
+ data = input;
379
+ const hashBuffer = yield crypto.subtle.digest(algorithm, data);
380
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
381
+ const hashHex = hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
382
+ return hashHex;
383
+ });
327
384
  }
328
385
  function randomId(length = 16, radix = 16, enhancedEntropy = false, randomCase = true) {
329
386
  if (length < 1)
@@ -352,9 +409,9 @@ function randomId(length = 16, radix = 16, enhancedEntropy = false, randomCase =
352
409
 
353
410
  // lib/Errors.ts
354
411
  var DatedError = class extends Error {
355
- date;
356
412
  constructor(message, options) {
357
413
  super(message, options);
414
+ __publicField(this, "date");
358
415
  this.name = this.constructor.name;
359
416
  this.date = /* @__PURE__ */ new Date();
360
417
  }
@@ -397,34 +454,37 @@ var NetworkError = class extends DatedError {
397
454
  };
398
455
 
399
456
  // lib/misc.ts
400
- async function consumeGen(valGen) {
401
- return await (typeof valGen === "function" ? valGen() : valGen);
457
+ function consumeGen(valGen) {
458
+ return __async(this, null, function* () {
459
+ return yield typeof valGen === "function" ? valGen() : valGen;
460
+ });
402
461
  }
403
- async function consumeStringGen(strGen) {
404
- return typeof strGen === "string" ? strGen : String(
405
- typeof strGen === "function" ? await strGen() : strGen
406
- );
462
+ function consumeStringGen(strGen) {
463
+ return __async(this, null, function* () {
464
+ return typeof strGen === "string" ? strGen : String(
465
+ typeof strGen === "function" ? yield strGen() : strGen
466
+ );
467
+ });
407
468
  }
408
- async function fetchAdvanced(input, options = {}) {
409
- const { timeout = 1e4, signal, ...restOpts } = options;
410
- const ctl = new AbortController();
411
- signal == null ? void 0 : signal.addEventListener("abort", () => ctl.abort());
412
- let sigOpts = {}, id = void 0;
413
- if (timeout >= 0) {
414
- id = setTimeout(() => ctl.abort(), timeout);
415
- sigOpts = { signal: ctl.signal };
416
- }
417
- try {
418
- const res = await fetch(input, {
419
- ...restOpts,
420
- ...sigOpts
421
- });
422
- typeof id !== "undefined" && clearTimeout(id);
423
- return res;
424
- } catch (err) {
425
- typeof id !== "undefined" && clearTimeout(id);
426
- throw new NetworkError("Error while calling fetch", { cause: err });
427
- }
469
+ function fetchAdvanced(_0) {
470
+ return __async(this, arguments, function* (input, options = {}) {
471
+ const _a = options, { timeout = 1e4, signal } = _a, restOpts = __objRest(_a, ["timeout", "signal"]);
472
+ const ctl = new AbortController();
473
+ signal == null ? void 0 : signal.addEventListener("abort", () => ctl.abort());
474
+ let sigOpts = {}, id = void 0;
475
+ if (timeout >= 0) {
476
+ id = setTimeout(() => ctl.abort(), timeout);
477
+ sigOpts = { signal: ctl.signal };
478
+ }
479
+ try {
480
+ const res = yield fetch(input, __spreadValues(__spreadValues({}, restOpts), sigOpts));
481
+ typeof id !== "undefined" && clearTimeout(id);
482
+ return res;
483
+ } catch (err) {
484
+ typeof id !== "undefined" && clearTimeout(id);
485
+ throw new NetworkError("Error while calling fetch", { cause: err });
486
+ }
487
+ });
428
488
  }
429
489
  function getListLength(listLike, zeroOnInvalid = true) {
430
490
  return "length" in listLike ? listLike.length : "size" in listLike ? listLike.size : "count" in listLike ? listLike.count : zeroOnInvalid ? 0 : NaN;
@@ -439,7 +499,7 @@ function pauseFor(time, signal, rejectOnAbort = false) {
439
499
  });
440
500
  }
441
501
  function pureObj(obj) {
442
- return Object.assign(/* @__PURE__ */ Object.create(null), obj ?? {});
502
+ return Object.assign(/* @__PURE__ */ Object.create(null), obj != null ? obj : {});
443
503
  }
444
504
  function setImmediateInterval(callback, interval, signal) {
445
505
  let intervalId;
@@ -456,12 +516,12 @@ function setImmediateInterval(callback, interval, signal) {
456
516
  function setImmediateTimeoutLoop(callback, interval, signal) {
457
517
  let timeout;
458
518
  const cleanup = () => clearTimeout(timeout);
459
- const loop = async () => {
519
+ const loop = () => __async(null, null, function* () {
460
520
  if (signal == null ? void 0 : signal.aborted)
461
521
  return cleanup();
462
- await callback();
522
+ yield callback();
463
523
  timeout = setTimeout(loop, interval);
464
- };
524
+ });
465
525
  signal == null ? void 0 : signal.addEventListener("abort", cleanup);
466
526
  loop();
467
527
  }
@@ -478,12 +538,13 @@ function scheduleExit(code = 0, timeout = 0) {
478
538
  setTimeout(exit, timeout);
479
539
  }
480
540
  function getCallStack(asArray, lines = Infinity) {
541
+ var _a;
481
542
  if (typeof lines !== "number" || isNaN(lines) || lines < 0)
482
543
  throw new TypeError("lines parameter must be a non-negative number");
483
544
  try {
484
545
  throw new CustomError("GetCallStack", "Capturing a stack trace with CoreUtils.getCallStack(). If you see this anywhere, you can safely ignore it.");
485
546
  } catch (err) {
486
- const stack = (err.stack ?? "").split("\n").map((line) => line.trim()).slice(2, lines + 2);
547
+ const stack = ((_a = err.stack) != null ? _a : "").split("\n").map((line) => line.trim()).slice(2, lines + 2);
487
548
  return asArray !== false ? stack : stack.join("\n");
488
549
  }
489
550
  }
@@ -494,22 +555,22 @@ function createRecurringTask(options) {
494
555
  (_a = options.signal) == null ? void 0 : _a.addEventListener("abort", () => {
495
556
  aborted = true;
496
557
  }, { once: true });
497
- const runRecurringTask = async (initial = false) => {
498
- var _a2;
558
+ const runRecurringTask = (initial = false) => __async(null, null, function* () {
559
+ var _a2, _b, _c;
499
560
  if (aborted)
500
561
  return;
501
562
  try {
502
- if ((options.immediate ?? true) || !initial) {
563
+ if (((_a2 = options.immediate) != null ? _a2 : true) || !initial) {
503
564
  iterations++;
504
- if (await ((_a2 = options.condition) == null ? void 0 : _a2.call(options, iterations - 1)) ?? true) {
505
- const val = await options.task(iterations - 1);
565
+ if ((_c = yield (_b = options.condition) == null ? void 0 : _b.call(options, iterations - 1)) != null ? _c : true) {
566
+ const val = yield options.task(iterations - 1);
506
567
  if (options.onSuccess)
507
- await options.onSuccess(val, iterations - 1);
568
+ yield options.onSuccess(val, iterations - 1);
508
569
  }
509
570
  }
510
571
  } catch (err) {
511
572
  if (options.onError)
512
- await options.onError(err, iterations - 1);
573
+ yield options.onError(err, iterations - 1);
513
574
  if (options.abortOnError)
514
575
  aborted = true;
515
576
  if (!options.onError && !options.abortOnError)
@@ -517,7 +578,7 @@ function createRecurringTask(options) {
517
578
  }
518
579
  if (!aborted && (typeof options.maxIterations !== "number" || iterations < options.maxIterations))
519
580
  setTimeout(runRecurringTask, options.timeout);
520
- };
581
+ });
521
582
  return runRecurringTask(true);
522
583
  }
523
584
 
@@ -571,9 +632,9 @@ function createProgressBar(percentage, barLength, chars = defaultPbChars) {
571
632
  }
572
633
  function insertValues(input, ...values) {
573
634
  return input.replace(/%\d/gm, (match) => {
574
- var _a;
635
+ var _a, _b;
575
636
  const argIndex = Number(match.substring(1)) - 1;
576
- return (_a = values[argIndex] ?? match) == null ? void 0 : _a.toString();
637
+ return (_b = (_a = values[argIndex]) != null ? _a : match) == null ? void 0 : _b.toString();
577
638
  });
578
639
  }
579
640
  function joinArrayReadable(array, separators = ", ", lastSeparator = " and ") {
@@ -604,7 +665,8 @@ function secsToTimeStr(seconds) {
604
665
  ].join("");
605
666
  }
606
667
  function truncStr(input, length, endStr = "...") {
607
- const str = (input == null ? void 0 : input.toString()) ?? String(input);
668
+ var _a;
669
+ const str = (_a = input == null ? void 0 : input.toString()) != null ? _a : String(input);
608
670
  const finalStr = str.length > length ? str.substring(0, length - endStr.length) + endStr : str;
609
671
  return finalStr.length > length ? finalStr.substring(0, length) : finalStr;
610
672
  }
@@ -650,8 +712,8 @@ var defaultTableLineCharset = {
650
712
  }
651
713
  };
652
714
  function createTable(rows, options) {
653
- var _a;
654
- const opts = {
715
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
716
+ const opts = __spreadValues({
655
717
  columnAlign: "left",
656
718
  truncateAbove: Infinity,
657
719
  truncEndStr: "\u2026",
@@ -659,16 +721,15 @@ function createTable(rows, options) {
659
721
  lineStyle: "single",
660
722
  applyCellStyle: () => void 0,
661
723
  applyLineStyle: () => void 0,
662
- lineCharset: defaultTableLineCharset,
663
- ...options ?? {}
664
- };
724
+ lineCharset: defaultTableLineCharset
725
+ }, options != null ? options : {});
665
726
  const defRange = (val, min, max) => clamp(typeof val !== "number" || isNaN(Number(val)) ? min : val, min, max);
666
727
  opts.truncateAbove = defRange(opts.truncateAbove, 0, Infinity);
667
728
  opts.minPadding = defRange(opts.minPadding, 0, Infinity);
668
729
  const lnCh = opts.lineCharset[opts.lineStyle];
669
730
  const stripAnsi = (str) => str.replace(/\u001b\[[0-9;]*m/g, "");
670
731
  const stringRows = rows.map((row) => row.map((cell) => String(cell)));
671
- const colCount = ((_a = rows[0]) == null ? void 0 : _a.length) ?? 0;
732
+ const colCount = (_b = (_a = rows[0]) == null ? void 0 : _a.length) != null ? _b : 0;
672
733
  if (colCount === 0 || stringRows.length === 0)
673
734
  return "";
674
735
  if (isFinite(opts.truncateAbove)) {
@@ -704,23 +765,28 @@ function createTable(rows, options) {
704
765
  };
705
766
  for (const row of stringRows)
706
767
  for (let j = 0; j < row.length; j++)
707
- if (stripAnsi(row[j] ?? "").length > opts.truncateAbove)
708
- row[j] = truncAnsi(row[j] ?? "", opts.truncateAbove, opts.truncEndStr);
768
+ if (stripAnsi((_c = row[j]) != null ? _c : "").length > opts.truncateAbove)
769
+ row[j] = truncAnsi((_d = row[j]) != null ? _d : "", opts.truncateAbove, opts.truncEndStr);
709
770
  }
710
771
  const colWidths = Array.from(
711
772
  { length: colCount },
712
- (_, j) => Math.max(0, ...stringRows.map((row) => stripAnsi(row[j] ?? "").length))
773
+ (_, j) => Math.max(0, ...stringRows.map((row) => {
774
+ var _a2;
775
+ return stripAnsi((_a2 = row[j]) != null ? _a2 : "").length;
776
+ }))
713
777
  );
714
778
  const applyLn = (i, j, ch) => {
715
- const [before = "", after = ""] = opts.applyLineStyle(i, j) ?? [];
779
+ var _a2;
780
+ const [before = "", after = ""] = (_a2 = opts.applyLineStyle(i, j)) != null ? _a2 : [];
716
781
  return `${before}${ch}${after}`;
717
782
  };
718
783
  const buildBorderRow = (lineIdx, leftCh, midCh, rightCh) => {
784
+ var _a2;
719
785
  let result = "";
720
786
  let j = 0;
721
787
  result += applyLn(lineIdx, j++, leftCh);
722
788
  for (let col = 0; col < colCount; col++) {
723
- const cellWidth = (colWidths[col] ?? 0) + opts.minPadding * 2;
789
+ const cellWidth = ((_a2 = colWidths[col]) != null ? _a2 : 0) + opts.minPadding * 2;
724
790
  for (let ci = 0; ci < cellWidth; ci++)
725
791
  result += applyLn(lineIdx, j++, lnCh.horizontal);
726
792
  if (col < colCount - 1)
@@ -731,7 +797,7 @@ function createTable(rows, options) {
731
797
  };
732
798
  const lines = [];
733
799
  for (let rowIdx = 0; rowIdx < stringRows.length; rowIdx++) {
734
- const row = stringRows[rowIdx] ?? [];
800
+ const row = (_e = stringRows[rowIdx]) != null ? _e : [];
735
801
  const lineIdxBase = rowIdx * 3;
736
802
  if (opts.lineStyle !== "none") {
737
803
  lines.push(
@@ -742,10 +808,10 @@ function createTable(rows, options) {
742
808
  let j = 0;
743
809
  contentLine += applyLn(lineIdxBase + 1, j++, lnCh.vertical);
744
810
  for (let colIdx = 0; colIdx < colCount; colIdx++) {
745
- const cell = row[colIdx] ?? "";
811
+ const cell = (_f = row[colIdx]) != null ? _f : "";
746
812
  const visLen = stripAnsi(cell).length;
747
- const extra = (colWidths[colIdx] ?? 0) - visLen;
748
- const align = (Array.isArray(opts.columnAlign) ? opts.columnAlign[colIdx] : opts.columnAlign) ?? "left";
813
+ const extra = ((_g = colWidths[colIdx]) != null ? _g : 0) - visLen;
814
+ const align = (_h = Array.isArray(opts.columnAlign) ? opts.columnAlign[colIdx] : opts.columnAlign) != null ? _h : "left";
749
815
  let leftPad;
750
816
  let rightPad;
751
817
  switch (align) {
@@ -765,7 +831,7 @@ function createTable(rows, options) {
765
831
  leftPad = opts.minPadding;
766
832
  rightPad = opts.minPadding + extra;
767
833
  }
768
- const [cellBefore = "", cellAfter = ""] = opts.applyCellStyle(rowIdx, colIdx) ?? [];
834
+ const [cellBefore = "", cellAfter = ""] = (_i = opts.applyCellStyle(rowIdx, colIdx)) != null ? _i : [];
769
835
  contentLine += " ".repeat(leftPad) + cellBefore + cell + cellAfter + " ".repeat(rightPad);
770
836
  contentLine += applyLn(lineIdxBase + 1, j++, lnCh.vertical);
771
837
  }
@@ -785,26 +851,26 @@ var createNanoEvents = () => ({
785
851
  },
786
852
  events: {},
787
853
  on(event, cb) {
854
+ var _a;
788
855
  ;
789
- (this.events[event] ||= []).push(cb);
856
+ ((_a = this.events)[event] || (_a[event] = [])).push(cb);
790
857
  return () => {
791
- var _a;
792
- this.events[event] = (_a = this.events[event]) == null ? void 0 : _a.filter((i) => cb !== i);
858
+ var _a2;
859
+ this.events[event] = (_a2 = this.events[event]) == null ? void 0 : _a2.filter((i) => cb !== i);
793
860
  };
794
861
  }
795
862
  });
796
863
 
797
864
  // lib/NanoEmitter.ts
798
865
  var NanoEmitter = class {
799
- events = createNanoEvents();
800
- eventUnsubscribes = [];
801
- emitterOptions;
802
866
  /** Creates a new instance of NanoEmitter - a lightweight event emitter with helper methods and a strongly typed event map */
803
867
  constructor(options = {}) {
804
- this.emitterOptions = {
805
- publicEmit: false,
806
- ...options
807
- };
868
+ __publicField(this, "events", createNanoEvents());
869
+ __publicField(this, "eventUnsubscribes", []);
870
+ __publicField(this, "emitterOptions");
871
+ this.emitterOptions = __spreadValues({
872
+ publicEmit: false
873
+ }, options);
808
874
  }
809
875
  //#region on
810
876
  /**
@@ -896,12 +962,11 @@ var NanoEmitter = class {
896
962
  this.eventUnsubscribes = this.eventUnsubscribes.filter((u) => !allUnsubs.includes(u));
897
963
  };
898
964
  for (const opts of Array.isArray(options) ? options : [options]) {
899
- const optsWithDefaults = {
965
+ const optsWithDefaults = __spreadValues({
900
966
  allOf: [],
901
967
  oneOf: [],
902
- once: false,
903
- ...opts
904
- };
968
+ once: false
969
+ }, opts);
905
970
  const {
906
971
  oneOf,
907
972
  allOf,
@@ -978,26 +1043,6 @@ var NanoEmitter = class {
978
1043
  // lib/DataStore.ts
979
1044
  var dsFmtVer = 1;
980
1045
  var DataStore = class extends NanoEmitter {
981
- id;
982
- formatVersion;
983
- defaultData;
984
- encodeData;
985
- decodeData;
986
- compressionFormat = "deflate-raw";
987
- memoryCache;
988
- engine;
989
- keyPrefix;
990
- options;
991
- /**
992
- * Whether all first-init checks should be done.
993
- * This includes migrating the internal DataStore format, migrating data from the UserUtils format, and anything similar.
994
- * 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.
995
- */
996
- firstInit = true;
997
- /** In-memory cached copy of the data that is saved in persistent storage used for synchronous read access. */
998
- cachedData;
999
- migrations;
1000
- migrateIds = [];
1001
1046
  //#region constructor
1002
1047
  /**
1003
1048
  * Creates an instance of DataStore to manage a sync & async database that is cached in memory and persistently saved across sessions.
@@ -1009,22 +1054,43 @@ var DataStore = class extends NanoEmitter {
1009
1054
  * @param opts The options for this DataStore instance
1010
1055
  */
1011
1056
  constructor(opts) {
1057
+ var _a, _b, _c;
1012
1058
  super(opts.nanoEmitterOptions);
1059
+ __publicField(this, "id");
1060
+ __publicField(this, "formatVersion");
1061
+ __publicField(this, "defaultData");
1062
+ __publicField(this, "encodeData");
1063
+ __publicField(this, "decodeData");
1064
+ __publicField(this, "compressionFormat", "deflate-raw");
1065
+ __publicField(this, "memoryCache");
1066
+ __publicField(this, "engine");
1067
+ __publicField(this, "keyPrefix");
1068
+ __publicField(this, "options");
1069
+ /**
1070
+ * Whether all first-init checks should be done.
1071
+ * This includes migrating the internal DataStore format, migrating data from the UserUtils format, and anything similar.
1072
+ * 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.
1073
+ */
1074
+ __publicField(this, "firstInit", true);
1075
+ /** In-memory cached copy of the data that is saved in persistent storage used for synchronous read access. */
1076
+ __publicField(this, "cachedData");
1077
+ __publicField(this, "migrations");
1078
+ __publicField(this, "migrateIds", []);
1013
1079
  this.id = opts.id;
1014
1080
  this.formatVersion = opts.formatVersion;
1015
1081
  this.defaultData = opts.defaultData;
1016
- this.memoryCache = opts.memoryCache ?? true;
1082
+ this.memoryCache = (_a = opts.memoryCache) != null ? _a : true;
1017
1083
  this.cachedData = this.memoryCache ? opts.defaultData : {};
1018
1084
  this.migrations = opts.migrations;
1019
1085
  if (opts.migrateIds)
1020
1086
  this.migrateIds = Array.isArray(opts.migrateIds) ? opts.migrateIds : [opts.migrateIds];
1021
1087
  this.engine = typeof opts.engine === "function" ? opts.engine() : opts.engine;
1022
- this.keyPrefix = opts.keyPrefix ?? "__ds-";
1088
+ this.keyPrefix = (_b = opts.keyPrefix) != null ? _b : "__ds-";
1023
1089
  this.options = opts;
1024
1090
  if ("encodeData" in opts && "decodeData" in opts && Array.isArray(opts.encodeData) && Array.isArray(opts.decodeData)) {
1025
1091
  this.encodeData = [opts.encodeData[0], opts.encodeData[1]];
1026
1092
  this.decodeData = [opts.decodeData[0], opts.decodeData[1]];
1027
- this.compressionFormat = opts.encodeData[0] ?? null;
1093
+ this.compressionFormat = (_c = opts.encodeData[0]) != null ? _c : null;
1028
1094
  } else if (opts.compressionFormat === null) {
1029
1095
  this.encodeData = void 0;
1030
1096
  this.decodeData = void 0;
@@ -1032,8 +1098,12 @@ var DataStore = class extends NanoEmitter {
1032
1098
  } else {
1033
1099
  const fmt = typeof opts.compressionFormat === "string" ? opts.compressionFormat : "deflate-raw";
1034
1100
  this.compressionFormat = fmt;
1035
- this.encodeData = [fmt, async (data) => await compress(data, fmt, "string")];
1036
- this.decodeData = [fmt, async (data) => await decompress(data, fmt, "string")];
1101
+ this.encodeData = [fmt, (data) => __async(this, null, function* () {
1102
+ return yield compress(data, fmt, "string");
1103
+ })];
1104
+ this.decodeData = [fmt, (data) => __async(this, null, function* () {
1105
+ return yield decompress(data, fmt, "string");
1106
+ })];
1037
1107
  }
1038
1108
  this.engine.setDataStoreOptions({
1039
1109
  id: this.id,
@@ -1047,62 +1117,65 @@ var DataStore = class extends NanoEmitter {
1047
1117
  * Automatically populates persistent storage with default data if it doesn't contain any data yet.
1048
1118
  * Also runs all necessary migration functions if the data format has changed since the last time the data was saved.
1049
1119
  */
1050
- async loadData() {
1051
- try {
1052
- if (this.firstInit) {
1053
- this.firstInit = false;
1054
- const dsVer = Number(await this.engine.getValue("__ds_fmt_ver", 0));
1055
- const oldData = await this.engine.getValue(`_uucfg-${this.id}`, null);
1056
- if (oldData) {
1057
- const oldVer = Number(await this.engine.getValue(`_uucfgver-${this.id}`, NaN));
1058
- const oldEnc = await this.engine.getValue(`_uucfgenc-${this.id}`, null);
1059
- const promises = [];
1060
- const migrateFmt = (oldKey, newKey, value) => {
1061
- promises.push(this.engine.setValue(newKey, value));
1062
- promises.push(this.engine.deleteValue(oldKey));
1063
- };
1064
- migrateFmt(`_uucfg-${this.id}`, `${this.keyPrefix}${this.id}-dat`, oldData);
1065
- if (!isNaN(oldVer))
1066
- migrateFmt(`_uucfgver-${this.id}`, `${this.keyPrefix}${this.id}-ver`, oldVer);
1067
- if (typeof oldEnc === "boolean" || oldEnc === "true" || oldEnc === "false" || typeof oldEnc === "number" || oldEnc === "0" || oldEnc === "1")
1068
- migrateFmt(`_uucfgenc-${this.id}`, `${this.keyPrefix}${this.id}-enf`, [0, "0", true, "true"].includes(oldEnc) ? this.compressionFormat ?? null : null);
1069
- else {
1070
- promises.push(this.engine.setValue(`${this.keyPrefix}${this.id}-enf`, this.compressionFormat));
1071
- promises.push(this.engine.deleteValue(`_uucfgenc-${this.id}`));
1120
+ loadData() {
1121
+ return __async(this, null, function* () {
1122
+ var _a;
1123
+ try {
1124
+ if (this.firstInit) {
1125
+ this.firstInit = false;
1126
+ const dsVer = Number(yield this.engine.getValue("__ds_fmt_ver", 0));
1127
+ const oldData = yield this.engine.getValue(`_uucfg-${this.id}`, null);
1128
+ if (oldData) {
1129
+ const oldVer = Number(yield this.engine.getValue(`_uucfgver-${this.id}`, NaN));
1130
+ const oldEnc = yield this.engine.getValue(`_uucfgenc-${this.id}`, null);
1131
+ const promises = [];
1132
+ const migrateFmt = (oldKey, newKey, value) => {
1133
+ promises.push(this.engine.setValue(newKey, value));
1134
+ promises.push(this.engine.deleteValue(oldKey));
1135
+ };
1136
+ migrateFmt(`_uucfg-${this.id}`, `${this.keyPrefix}${this.id}-dat`, oldData);
1137
+ if (!isNaN(oldVer))
1138
+ migrateFmt(`_uucfgver-${this.id}`, `${this.keyPrefix}${this.id}-ver`, oldVer);
1139
+ if (typeof oldEnc === "boolean" || oldEnc === "true" || oldEnc === "false" || typeof oldEnc === "number" || oldEnc === "0" || oldEnc === "1")
1140
+ migrateFmt(`_uucfgenc-${this.id}`, `${this.keyPrefix}${this.id}-enf`, [0, "0", true, "true"].includes(oldEnc) ? (_a = this.compressionFormat) != null ? _a : null : null);
1141
+ else {
1142
+ promises.push(this.engine.setValue(`${this.keyPrefix}${this.id}-enf`, this.compressionFormat));
1143
+ promises.push(this.engine.deleteValue(`_uucfgenc-${this.id}`));
1144
+ }
1145
+ yield Promise.allSettled(promises);
1072
1146
  }
1073
- await Promise.allSettled(promises);
1147
+ if (isNaN(dsVer) || dsVer < dsFmtVer)
1148
+ yield this.engine.setValue("__ds_fmt_ver", dsFmtVer);
1074
1149
  }
1075
- if (isNaN(dsVer) || dsVer < dsFmtVer)
1076
- await this.engine.setValue("__ds_fmt_ver", dsFmtVer);
1077
- }
1078
- if (this.migrateIds.length > 0) {
1079
- await this.migrateId(this.migrateIds);
1080
- this.migrateIds = [];
1081
- }
1082
- const storedDataRaw = await this.engine.getValue(`${this.keyPrefix}${this.id}-dat`, null);
1083
- const storedFmtVer = Number(await this.engine.getValue(`${this.keyPrefix}${this.id}-ver`, NaN));
1084
- if (typeof storedDataRaw !== "string" && typeof storedDataRaw !== "object" || storedDataRaw === null || isNaN(storedFmtVer)) {
1085
- await this.saveDefaultData(false);
1086
- const data = this.engine.deepCopy(this.defaultData);
1087
- this.events.emit("loadData", data);
1088
- return data;
1150
+ if (this.migrateIds.length > 0) {
1151
+ yield this.migrateId(this.migrateIds);
1152
+ this.migrateIds = [];
1153
+ }
1154
+ const storedDataRaw = yield this.engine.getValue(`${this.keyPrefix}${this.id}-dat`, null);
1155
+ const storedFmtVer = Number(yield this.engine.getValue(`${this.keyPrefix}${this.id}-ver`, NaN));
1156
+ if (typeof storedDataRaw !== "string" && typeof storedDataRaw !== "object" || storedDataRaw === null || isNaN(storedFmtVer)) {
1157
+ yield this.saveDefaultData(false);
1158
+ const data = this.engine.deepCopy(this.defaultData);
1159
+ this.events.emit("loadData", data);
1160
+ return data;
1161
+ }
1162
+ const storedData = storedDataRaw != null ? storedDataRaw : JSON.stringify(this.defaultData);
1163
+ const encodingFmt = String(yield this.engine.getValue(`${this.keyPrefix}${this.id}-enf`, null));
1164
+ const isEncoded = encodingFmt !== "null" && encodingFmt !== "false" && encodingFmt !== "0" && encodingFmt !== "" && encodingFmt !== null;
1165
+ let parsed = typeof storedData === "string" ? yield this.engine.deserializeData(storedData, isEncoded) : storedData;
1166
+ if (storedFmtVer < this.formatVersion && this.migrations)
1167
+ parsed = yield this.runMigrations(parsed, storedFmtVer);
1168
+ const result = this.memoryCache ? this.cachedData = this.engine.deepCopy(parsed) : this.engine.deepCopy(parsed);
1169
+ this.events.emit("loadData", result);
1170
+ return result;
1171
+ } catch (err) {
1172
+ const error = err instanceof Error ? err : new Error(String(err));
1173
+ console.warn("Error while parsing JSON data, resetting it to the default value.", err);
1174
+ this.events.emit("error", error);
1175
+ yield this.saveDefaultData();
1176
+ return this.defaultData;
1089
1177
  }
1090
- const storedData = storedDataRaw ?? JSON.stringify(this.defaultData);
1091
- const encodingFmt = String(await this.engine.getValue(`${this.keyPrefix}${this.id}-enf`, null));
1092
- const isEncoded = encodingFmt !== "null" && encodingFmt !== "false" && encodingFmt !== "0" && encodingFmt !== "" && encodingFmt !== null;
1093
- let parsed = typeof storedData === "string" ? await this.engine.deserializeData(storedData, isEncoded) : storedData;
1094
- if (storedFmtVer < this.formatVersion && this.migrations)
1095
- parsed = await this.runMigrations(parsed, storedFmtVer);
1096
- const result = this.memoryCache ? this.cachedData = this.engine.deepCopy(parsed) : this.engine.deepCopy(parsed);
1097
- this.events.emit("loadData", result);
1098
- return result;
1099
- } catch (err) {
1100
- const error = err instanceof Error ? err : new Error(String(err));
1101
- console.warn("Error while parsing JSON data, resetting it to the default value.", err);
1102
- this.events.emit("error", error);
1103
- await this.saveDefaultData();
1104
- return this.defaultData;
1105
- }
1178
+ });
1106
1179
  }
1107
1180
  //#region getData
1108
1181
  /**
@@ -1123,9 +1196,9 @@ var DataStore = class extends NanoEmitter {
1123
1196
  this.cachedData = data;
1124
1197
  this.events.emit("updateDataSync", dataCopy);
1125
1198
  }
1126
- return new Promise(async (resolve) => {
1127
- const results = await Promise.allSettled([
1128
- this.engine.setValue(`${this.keyPrefix}${this.id}-dat`, await this.engine.serializeData(data, this.encodingEnabled())),
1199
+ return new Promise((resolve) => __async(this, null, function* () {
1200
+ const results = yield Promise.allSettled([
1201
+ this.engine.setValue(`${this.keyPrefix}${this.id}-dat`, yield this.engine.serializeData(data, this.encodingEnabled())),
1129
1202
  this.engine.setValue(`${this.keyPrefix}${this.id}-ver`, this.formatVersion),
1130
1203
  this.engine.setValue(`${this.keyPrefix}${this.id}-enf`, this.compressionFormat)
1131
1204
  ]);
@@ -1137,28 +1210,30 @@ var DataStore = class extends NanoEmitter {
1137
1210
  this.events.emit("error", error);
1138
1211
  }
1139
1212
  resolve();
1140
- });
1213
+ }));
1141
1214
  }
1142
1215
  //#region saveDefaultData
1143
1216
  /**
1144
1217
  * Saves the default data passed in the constructor synchronously to the in-memory cache and asynchronously to persistent storage.
1145
1218
  * @param emitEvent Whether to emit the `setDefaultData` event - set to `false` to prevent event emission (used internally during initial population in {@linkcode loadData()})
1146
1219
  */
1147
- async saveDefaultData(emitEvent = true) {
1148
- if (this.memoryCache)
1149
- this.cachedData = this.defaultData;
1150
- const results = await Promise.allSettled([
1151
- this.engine.setValue(`${this.keyPrefix}${this.id}-dat`, await this.engine.serializeData(this.defaultData, this.encodingEnabled())),
1152
- this.engine.setValue(`${this.keyPrefix}${this.id}-ver`, this.formatVersion),
1153
- this.engine.setValue(`${this.keyPrefix}${this.id}-enf`, this.compressionFormat)
1154
- ]);
1155
- if (results.every((r) => r.status === "fulfilled"))
1156
- emitEvent && this.events.emit("setDefaultData", this.defaultData);
1157
- else {
1158
- const error = new Error("Error while saving default data to persistent storage: " + results.map((r) => r.status === "rejected" ? r.reason : null).filter(Boolean).join("; "));
1159
- console.error(error);
1160
- this.events.emit("error", error);
1161
- }
1220
+ saveDefaultData(emitEvent = true) {
1221
+ return __async(this, null, function* () {
1222
+ if (this.memoryCache)
1223
+ this.cachedData = this.defaultData;
1224
+ const results = yield Promise.allSettled([
1225
+ this.engine.setValue(`${this.keyPrefix}${this.id}-dat`, yield this.engine.serializeData(this.defaultData, this.encodingEnabled())),
1226
+ this.engine.setValue(`${this.keyPrefix}${this.id}-ver`, this.formatVersion),
1227
+ this.engine.setValue(`${this.keyPrefix}${this.id}-enf`, this.compressionFormat)
1228
+ ]);
1229
+ if (results.every((r) => r.status === "fulfilled"))
1230
+ emitEvent && this.events.emit("setDefaultData", this.defaultData);
1231
+ else {
1232
+ const error = new Error("Error while saving default data to persistent storage: " + results.map((r) => r.status === "rejected" ? r.reason : null).filter(Boolean).join("; "));
1233
+ console.error(error);
1234
+ this.events.emit("error", error);
1235
+ }
1236
+ });
1162
1237
  }
1163
1238
  //#region deleteData
1164
1239
  /**
@@ -1166,15 +1241,17 @@ var DataStore = class extends NanoEmitter {
1166
1241
  * The in-memory cache will be left untouched, so you may still access the data with {@linkcode getData()}
1167
1242
  * Calling {@linkcode loadData()} or {@linkcode setData()} after this method was called will recreate persistent storage with the cached or default data.
1168
1243
  */
1169
- async deleteData() {
1170
- var _a, _b;
1171
- await Promise.allSettled([
1172
- this.engine.deleteValue(`${this.keyPrefix}${this.id}-dat`),
1173
- this.engine.deleteValue(`${this.keyPrefix}${this.id}-ver`),
1174
- this.engine.deleteValue(`${this.keyPrefix}${this.id}-enf`)
1175
- ]);
1176
- await ((_b = (_a = this.engine).deleteStorage) == null ? void 0 : _b.call(_a));
1177
- this.events.emit("deleteData");
1244
+ deleteData() {
1245
+ return __async(this, null, function* () {
1246
+ var _a, _b;
1247
+ yield Promise.allSettled([
1248
+ this.engine.deleteValue(`${this.keyPrefix}${this.id}-dat`),
1249
+ this.engine.deleteValue(`${this.keyPrefix}${this.id}-ver`),
1250
+ this.engine.deleteValue(`${this.keyPrefix}${this.id}-enf`)
1251
+ ]);
1252
+ yield (_b = (_a = this.engine).deleteStorage) == null ? void 0 : _b.call(_a);
1253
+ this.events.emit("deleteData");
1254
+ });
1178
1255
  }
1179
1256
  //#region encodingEnabled
1180
1257
  /** Returns whether encoding and decoding are enabled for this DataStore instance */
@@ -1189,79 +1266,83 @@ var DataStore = class extends NanoEmitter {
1189
1266
  *
1190
1267
  * 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.
1191
1268
  */
1192
- async runMigrations(oldData, oldFmtVer, resetOnError = true) {
1193
- if (!this.migrations)
1194
- return oldData;
1195
- let newData = oldData;
1196
- const sortedMigrations = Object.entries(this.migrations).sort(([a], [b]) => Number(a) - Number(b));
1197
- let lastFmtVer = oldFmtVer;
1198
- for (let i = 0; i < sortedMigrations.length; i++) {
1199
- const [fmtVer, migrationFunc] = sortedMigrations[i];
1200
- const ver = Number(fmtVer);
1201
- if (oldFmtVer < this.formatVersion && oldFmtVer < ver) {
1202
- try {
1203
- const migRes = migrationFunc(newData);
1204
- newData = migRes instanceof Promise ? await migRes : migRes;
1205
- lastFmtVer = oldFmtVer = ver;
1206
- const isFinal = ver >= this.formatVersion || i === sortedMigrations.length - 1;
1207
- this.events.emit("migrateData", ver, newData, isFinal);
1208
- } catch (err) {
1209
- const migError = new MigrationError(`Error while running migration function for format version '${fmtVer}'`, { cause: err });
1210
- this.events.emit("migrationError", ver, migError);
1211
- this.events.emit("error", migError);
1212
- if (!resetOnError)
1213
- throw migError;
1214
- await this.saveDefaultData();
1215
- return this.engine.deepCopy(this.defaultData);
1269
+ runMigrations(oldData, oldFmtVer, resetOnError = true) {
1270
+ return __async(this, null, function* () {
1271
+ if (!this.migrations)
1272
+ return oldData;
1273
+ let newData = oldData;
1274
+ const sortedMigrations = Object.entries(this.migrations).sort(([a], [b]) => Number(a) - Number(b));
1275
+ let lastFmtVer = oldFmtVer;
1276
+ for (let i = 0; i < sortedMigrations.length; i++) {
1277
+ const [fmtVer, migrationFunc] = sortedMigrations[i];
1278
+ const ver = Number(fmtVer);
1279
+ if (oldFmtVer < this.formatVersion && oldFmtVer < ver) {
1280
+ try {
1281
+ const migRes = migrationFunc(newData);
1282
+ newData = migRes instanceof Promise ? yield migRes : migRes;
1283
+ lastFmtVer = oldFmtVer = ver;
1284
+ const isFinal = ver >= this.formatVersion || i === sortedMigrations.length - 1;
1285
+ this.events.emit("migrateData", ver, newData, isFinal);
1286
+ } catch (err) {
1287
+ const migError = new MigrationError(`Error while running migration function for format version '${fmtVer}'`, { cause: err });
1288
+ this.events.emit("migrationError", ver, migError);
1289
+ this.events.emit("error", migError);
1290
+ if (!resetOnError)
1291
+ throw migError;
1292
+ yield this.saveDefaultData();
1293
+ return this.engine.deepCopy(this.defaultData);
1294
+ }
1216
1295
  }
1217
1296
  }
1218
- }
1219
- await Promise.allSettled([
1220
- this.engine.setValue(`${this.keyPrefix}${this.id}-dat`, await this.engine.serializeData(newData, this.encodingEnabled())),
1221
- this.engine.setValue(`${this.keyPrefix}${this.id}-ver`, lastFmtVer),
1222
- this.engine.setValue(`${this.keyPrefix}${this.id}-enf`, this.compressionFormat)
1223
- ]);
1224
- const result = this.memoryCache ? this.cachedData = this.engine.deepCopy(newData) : this.engine.deepCopy(newData);
1225
- this.events.emit("updateData", result);
1226
- return result;
1297
+ yield Promise.allSettled([
1298
+ this.engine.setValue(`${this.keyPrefix}${this.id}-dat`, yield this.engine.serializeData(newData, this.encodingEnabled())),
1299
+ this.engine.setValue(`${this.keyPrefix}${this.id}-ver`, lastFmtVer),
1300
+ this.engine.setValue(`${this.keyPrefix}${this.id}-enf`, this.compressionFormat)
1301
+ ]);
1302
+ const result = this.memoryCache ? this.cachedData = this.engine.deepCopy(newData) : this.engine.deepCopy(newData);
1303
+ this.events.emit("updateData", result);
1304
+ return result;
1305
+ });
1227
1306
  }
1228
1307
  //#region migrateId
1229
1308
  /**
1230
1309
  * Tries to migrate the currently saved persistent data from one or more old IDs to the ID set in the constructor.
1231
1310
  * 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.
1232
1311
  */
1233
- async migrateId(oldIds) {
1234
- const ids = Array.isArray(oldIds) ? oldIds : [oldIds];
1235
- await Promise.all(ids.map(async (id) => {
1236
- const [data, fmtVer, isEncoded] = await (async () => {
1237
- const [d, f, e] = await Promise.all([
1238
- this.engine.getValue(`${this.keyPrefix}${id}-dat`, JSON.stringify(this.defaultData)),
1239
- this.engine.getValue(`${this.keyPrefix}${id}-ver`, NaN),
1240
- this.engine.getValue(`${this.keyPrefix}${id}-enf`, null)
1312
+ migrateId(oldIds) {
1313
+ return __async(this, null, function* () {
1314
+ const ids = Array.isArray(oldIds) ? oldIds : [oldIds];
1315
+ yield Promise.all(ids.map((id) => __async(this, null, function* () {
1316
+ const [data, fmtVer, isEncoded] = yield (() => __async(this, null, function* () {
1317
+ const [d, f, e] = yield Promise.all([
1318
+ this.engine.getValue(`${this.keyPrefix}${id}-dat`, JSON.stringify(this.defaultData)),
1319
+ this.engine.getValue(`${this.keyPrefix}${id}-ver`, NaN),
1320
+ this.engine.getValue(`${this.keyPrefix}${id}-enf`, null)
1321
+ ]);
1322
+ return [d, Number(f), Boolean(e) && String(e) !== "null"];
1323
+ }))();
1324
+ if (data === void 0 || isNaN(fmtVer))
1325
+ return;
1326
+ const parsed = yield this.engine.deserializeData(data, isEncoded);
1327
+ yield Promise.allSettled([
1328
+ this.engine.setValue(`${this.keyPrefix}${this.id}-dat`, yield this.engine.serializeData(parsed, this.encodingEnabled())),
1329
+ this.engine.setValue(`${this.keyPrefix}${this.id}-ver`, fmtVer),
1330
+ this.engine.setValue(`${this.keyPrefix}${this.id}-enf`, this.compressionFormat),
1331
+ this.engine.deleteValue(`${this.keyPrefix}${id}-dat`),
1332
+ this.engine.deleteValue(`${this.keyPrefix}${id}-ver`),
1333
+ this.engine.deleteValue(`${this.keyPrefix}${id}-enf`)
1241
1334
  ]);
1242
- return [d, Number(f), Boolean(e) && String(e) !== "null"];
1243
- })();
1244
- if (data === void 0 || isNaN(fmtVer))
1245
- return;
1246
- const parsed = await this.engine.deserializeData(data, isEncoded);
1247
- await Promise.allSettled([
1248
- this.engine.setValue(`${this.keyPrefix}${this.id}-dat`, await this.engine.serializeData(parsed, this.encodingEnabled())),
1249
- this.engine.setValue(`${this.keyPrefix}${this.id}-ver`, fmtVer),
1250
- this.engine.setValue(`${this.keyPrefix}${this.id}-enf`, this.compressionFormat),
1251
- this.engine.deleteValue(`${this.keyPrefix}${id}-dat`),
1252
- this.engine.deleteValue(`${this.keyPrefix}${id}-ver`),
1253
- this.engine.deleteValue(`${this.keyPrefix}${id}-enf`)
1254
- ]);
1255
- this.events.emit("migrateId", id, this.id);
1256
- }));
1335
+ this.events.emit("migrateId", id, this.id);
1336
+ })));
1337
+ });
1257
1338
  }
1258
1339
  };
1259
1340
 
1260
1341
  // lib/DataStoreEngine.ts
1261
1342
  var DataStoreEngine = class {
1262
- dataStoreOptions;
1263
1343
  // setDataStoreOptions() is called from inside the DataStore constructor to set this value
1264
1344
  constructor(options) {
1345
+ __publicField(this, "dataStoreOptions");
1265
1346
  if (options)
1266
1347
  this.dataStoreOptions = options;
1267
1348
  }
@@ -1271,25 +1352,29 @@ var DataStoreEngine = class {
1271
1352
  }
1272
1353
  //#region serialization api
1273
1354
  /** 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 */
1274
- async serializeData(data, useEncoding) {
1275
- var _a, _b, _c, _d, _e;
1276
- this.ensureDataStoreOptions();
1277
- const stringData = JSON.stringify(data);
1278
- if (!useEncoding || !((_a = this.dataStoreOptions) == null ? void 0 : _a.encodeData) || !((_b = this.dataStoreOptions) == null ? void 0 : _b.decodeData))
1279
- return stringData;
1280
- const encRes = (_e = (_d = (_c = this.dataStoreOptions) == null ? void 0 : _c.encodeData) == null ? void 0 : _d[1]) == null ? void 0 : _e.call(_d, stringData);
1281
- if (encRes instanceof Promise)
1282
- return await encRes;
1283
- return encRes;
1355
+ serializeData(data, useEncoding) {
1356
+ return __async(this, null, function* () {
1357
+ var _a, _b, _c, _d, _e;
1358
+ this.ensureDataStoreOptions();
1359
+ const stringData = JSON.stringify(data);
1360
+ if (!useEncoding || !((_a = this.dataStoreOptions) == null ? void 0 : _a.encodeData) || !((_b = this.dataStoreOptions) == null ? void 0 : _b.decodeData))
1361
+ return stringData;
1362
+ const encRes = (_e = (_d = (_c = this.dataStoreOptions) == null ? void 0 : _c.encodeData) == null ? void 0 : _d[1]) == null ? void 0 : _e.call(_d, stringData);
1363
+ if (encRes instanceof Promise)
1364
+ return yield encRes;
1365
+ return encRes;
1366
+ });
1284
1367
  }
1285
1368
  /** Deserializes the given string to a JSON object, optionally decoded with `options.decodeData` if {@linkcode useEncoding} is set to true */
1286
- async deserializeData(data, useEncoding) {
1287
- var _a, _b, _c;
1288
- this.ensureDataStoreOptions();
1289
- 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;
1290
- if (decRes instanceof Promise)
1291
- decRes = await decRes;
1292
- return JSON.parse(decRes ?? data);
1369
+ deserializeData(data, useEncoding) {
1370
+ return __async(this, null, function* () {
1371
+ var _a, _b, _c;
1372
+ this.ensureDataStoreOptions();
1373
+ 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;
1374
+ if (decRes instanceof Promise)
1375
+ decRes = yield decRes;
1376
+ return JSON.parse(decRes != null ? decRes : data);
1377
+ });
1293
1378
  }
1294
1379
  //#region misc api
1295
1380
  /** Throws an error if the DataStoreOptions are not set or invalid */
@@ -1307,13 +1392,12 @@ var DataStoreEngine = class {
1307
1392
  try {
1308
1393
  if ("structuredClone" in globalThis)
1309
1394
  return structuredClone(obj);
1310
- } catch {
1395
+ } catch (e) {
1311
1396
  }
1312
1397
  return JSON.parse(JSON.stringify(obj));
1313
1398
  }
1314
1399
  };
1315
1400
  var BrowserStorageEngine = class extends DataStoreEngine {
1316
- options;
1317
1401
  /**
1318
1402
  * Creates an instance of `BrowserStorageEngine`.
1319
1403
  *
@@ -1322,36 +1406,40 @@ var BrowserStorageEngine = class extends DataStoreEngine {
1322
1406
  */
1323
1407
  constructor(options) {
1324
1408
  super(options == null ? void 0 : options.dataStoreOptions);
1325
- this.options = {
1326
- type: "localStorage",
1327
- ...options
1328
- };
1409
+ __publicField(this, "options");
1410
+ this.options = __spreadValues({
1411
+ type: "localStorage"
1412
+ }, options);
1329
1413
  }
1330
1414
  //#region storage api
1331
1415
  /** Fetches a value from persistent storage */
1332
- async getValue(name, defaultValue) {
1333
- const val = this.options.type === "localStorage" ? globalThis.localStorage.getItem(name) : globalThis.sessionStorage.getItem(name);
1334
- return typeof val === "undefined" ? defaultValue : val;
1416
+ getValue(name, defaultValue) {
1417
+ return __async(this, null, function* () {
1418
+ const val = this.options.type === "localStorage" ? globalThis.localStorage.getItem(name) : globalThis.sessionStorage.getItem(name);
1419
+ return typeof val === "undefined" ? defaultValue : val;
1420
+ });
1335
1421
  }
1336
1422
  /** Sets a value in persistent storage */
1337
- async setValue(name, value) {
1338
- if (this.options.type === "localStorage")
1339
- globalThis.localStorage.setItem(name, String(value));
1340
- else
1341
- globalThis.sessionStorage.setItem(name, String(value));
1423
+ setValue(name, value) {
1424
+ return __async(this, null, function* () {
1425
+ if (this.options.type === "localStorage")
1426
+ globalThis.localStorage.setItem(name, String(value));
1427
+ else
1428
+ globalThis.sessionStorage.setItem(name, String(value));
1429
+ });
1342
1430
  }
1343
1431
  /** Deletes a value from persistent storage */
1344
- async deleteValue(name) {
1345
- if (this.options.type === "localStorage")
1346
- globalThis.localStorage.removeItem(name);
1347
- else
1348
- globalThis.sessionStorage.removeItem(name);
1432
+ deleteValue(name) {
1433
+ return __async(this, null, function* () {
1434
+ if (this.options.type === "localStorage")
1435
+ globalThis.localStorage.removeItem(name);
1436
+ else
1437
+ globalThis.sessionStorage.removeItem(name);
1438
+ });
1349
1439
  }
1350
1440
  };
1351
1441
  var fs;
1352
1442
  var FileStorageEngine = class extends DataStoreEngine {
1353
- options;
1354
- fileAccessQueue = Promise.resolve();
1355
1443
  /**
1356
1444
  * Creates an instance of `FileStorageEngine`.
1357
1445
  *
@@ -1360,150 +1448,164 @@ var FileStorageEngine = class extends DataStoreEngine {
1360
1448
  */
1361
1449
  constructor(options) {
1362
1450
  super(options == null ? void 0 : options.dataStoreOptions);
1363
- this.options = {
1364
- filePath: (id) => `.ds-${id}`,
1365
- ...options
1366
- };
1451
+ __publicField(this, "options");
1452
+ __publicField(this, "fileAccessQueue", Promise.resolve());
1453
+ this.options = __spreadValues({
1454
+ filePath: (id) => `.ds-${id}`
1455
+ }, options);
1367
1456
  }
1368
1457
  //#region json file
1369
1458
  /** Reads the file contents */
1370
- async readFile() {
1371
- var _a, _b, _c, _d;
1372
- this.ensureDataStoreOptions();
1373
- try {
1374
- if (!fs)
1375
- fs = (_a = await import("fs/promises")) == null ? void 0 : _a.default;
1376
- if (!fs)
1377
- throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
1378
- const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id, this.dataStoreOptions);
1379
- const data = await fs.readFile(path, "utf-8");
1380
- 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;
1381
- } catch {
1382
- return void 0;
1383
- }
1459
+ readFile() {
1460
+ return __async(this, null, function* () {
1461
+ var _a, _b, _c, _d, _e;
1462
+ this.ensureDataStoreOptions();
1463
+ try {
1464
+ if (!fs)
1465
+ fs = (_a = yield import("fs/promises")) == null ? void 0 : _a.default;
1466
+ if (!fs)
1467
+ throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
1468
+ const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id, this.dataStoreOptions);
1469
+ const data = yield fs.readFile(path, "utf-8");
1470
+ 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;
1471
+ } catch (e) {
1472
+ return void 0;
1473
+ }
1474
+ });
1384
1475
  }
1385
1476
  /** Overwrites the file contents */
1386
- async writeFile(data) {
1387
- var _a, _b, _c, _d;
1388
- this.ensureDataStoreOptions();
1389
- try {
1390
- if (!fs)
1391
- fs = (_a = await import("fs/promises")) == null ? void 0 : _a.default;
1392
- if (!fs)
1393
- throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
1394
- const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id, this.dataStoreOptions);
1395
- await fs.mkdir(path.slice(0, path.lastIndexOf(path.includes("/") ? "/" : "\\")), { recursive: true });
1396
- 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");
1397
- } catch (err) {
1398
- console.error("Error writing file:", err);
1399
- }
1477
+ writeFile(data) {
1478
+ return __async(this, null, function* () {
1479
+ var _a, _b, _c, _d, _e;
1480
+ this.ensureDataStoreOptions();
1481
+ try {
1482
+ if (!fs)
1483
+ fs = (_a = yield import("fs/promises")) == null ? void 0 : _a.default;
1484
+ if (!fs)
1485
+ throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
1486
+ const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id, this.dataStoreOptions);
1487
+ yield fs.mkdir(path.slice(0, path.lastIndexOf(path.includes("/") ? "/" : "\\")), { recursive: true });
1488
+ 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");
1489
+ } catch (err) {
1490
+ console.error("Error writing file:", err);
1491
+ }
1492
+ });
1400
1493
  }
1401
1494
  //#region storage api
1402
1495
  /** Fetches a value from persistent storage */
1403
- async getValue(name, defaultValue) {
1404
- const data = await this.readFile();
1405
- if (!data)
1406
- return defaultValue;
1407
- const value = data == null ? void 0 : data[name];
1408
- if (typeof value === "undefined")
1409
- return defaultValue;
1410
- if (typeof defaultValue === "string") {
1411
- if (typeof value === "object" && value !== null)
1412
- return JSON.stringify(value);
1413
- if (typeof value === "string")
1414
- return value;
1415
- return String(value);
1416
- }
1417
- if (typeof value === "string") {
1418
- try {
1419
- const parsed = JSON.parse(value);
1420
- return parsed;
1421
- } catch {
1496
+ getValue(name, defaultValue) {
1497
+ return __async(this, null, function* () {
1498
+ const data = yield this.readFile();
1499
+ if (!data)
1500
+ return defaultValue;
1501
+ const value = data == null ? void 0 : data[name];
1502
+ if (typeof value === "undefined")
1422
1503
  return defaultValue;
1504
+ if (typeof defaultValue === "string") {
1505
+ if (typeof value === "object" && value !== null)
1506
+ return JSON.stringify(value);
1507
+ if (typeof value === "string")
1508
+ return value;
1509
+ return String(value);
1423
1510
  }
1424
- }
1425
- return value;
1426
- }
1427
- /** Sets a value in persistent storage */
1428
- async setValue(name, value) {
1429
- this.fileAccessQueue = this.fileAccessQueue.then(async () => {
1430
- let data = await this.readFile();
1431
- if (!data)
1432
- data = {};
1433
- let storeVal = value;
1434
1511
  if (typeof value === "string") {
1435
1512
  try {
1436
- if (value.startsWith("{") || value.startsWith("[")) {
1437
- const parsed = JSON.parse(value);
1438
- if (typeof parsed === "object" && parsed !== null)
1439
- storeVal = parsed;
1440
- }
1441
- } catch {
1513
+ const parsed = JSON.parse(value);
1514
+ return parsed;
1515
+ } catch (e) {
1516
+ return defaultValue;
1442
1517
  }
1443
1518
  }
1444
- data[name] = storeVal;
1445
- await this.writeFile(data);
1446
- }).catch((err) => {
1447
- console.error("Error in setValue:", err);
1448
- throw err;
1519
+ return value;
1449
1520
  });
1450
- await this.fileAccessQueue.catch(() => {
1521
+ }
1522
+ /** Sets a value in persistent storage */
1523
+ setValue(name, value) {
1524
+ return __async(this, null, function* () {
1525
+ this.fileAccessQueue = this.fileAccessQueue.then(() => __async(this, null, function* () {
1526
+ let data = yield this.readFile();
1527
+ if (!data)
1528
+ data = {};
1529
+ let storeVal = value;
1530
+ if (typeof value === "string") {
1531
+ try {
1532
+ if (value.startsWith("{") || value.startsWith("[")) {
1533
+ const parsed = JSON.parse(value);
1534
+ if (typeof parsed === "object" && parsed !== null)
1535
+ storeVal = parsed;
1536
+ }
1537
+ } catch (e) {
1538
+ }
1539
+ }
1540
+ data[name] = storeVal;
1541
+ yield this.writeFile(data);
1542
+ })).catch((err) => {
1543
+ console.error("Error in setValue:", err);
1544
+ throw err;
1545
+ });
1546
+ yield this.fileAccessQueue.catch(() => {
1547
+ });
1451
1548
  });
1452
1549
  }
1453
1550
  /** Deletes a value from persistent storage */
1454
- async deleteValue(name) {
1455
- this.fileAccessQueue = this.fileAccessQueue.then(async () => {
1456
- const data = await this.readFile();
1457
- if (!data)
1458
- return;
1459
- delete data[name];
1460
- await this.writeFile(data);
1461
- }).catch((err) => {
1462
- console.error("Error in deleteValue:", err);
1463
- throw err;
1464
- });
1465
- await this.fileAccessQueue.catch(() => {
1551
+ deleteValue(name) {
1552
+ return __async(this, null, function* () {
1553
+ this.fileAccessQueue = this.fileAccessQueue.then(() => __async(this, null, function* () {
1554
+ const data = yield this.readFile();
1555
+ if (!data)
1556
+ return;
1557
+ delete data[name];
1558
+ yield this.writeFile(data);
1559
+ })).catch((err) => {
1560
+ console.error("Error in deleteValue:", err);
1561
+ throw err;
1562
+ });
1563
+ yield this.fileAccessQueue.catch(() => {
1564
+ });
1466
1565
  });
1467
1566
  }
1468
1567
  /** Deletes the file that contains the data of this DataStore. */
1469
- async deleteStorage() {
1470
- var _a;
1471
- this.ensureDataStoreOptions();
1472
- try {
1473
- if (!fs)
1474
- fs = (_a = await import("fs/promises")) == null ? void 0 : _a.default;
1475
- if (!fs)
1476
- throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
1477
- const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id, this.dataStoreOptions);
1478
- return await fs.unlink(path);
1479
- } catch (err) {
1480
- console.error("Error deleting file:", err);
1481
- }
1568
+ deleteStorage() {
1569
+ return __async(this, null, function* () {
1570
+ var _a;
1571
+ this.ensureDataStoreOptions();
1572
+ try {
1573
+ if (!fs)
1574
+ fs = (_a = yield import("fs/promises")) == null ? void 0 : _a.default;
1575
+ if (!fs)
1576
+ throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
1577
+ const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id, this.dataStoreOptions);
1578
+ return yield fs.unlink(path);
1579
+ } catch (err) {
1580
+ console.error("Error deleting file:", err);
1581
+ }
1582
+ });
1482
1583
  }
1483
1584
  };
1484
1585
 
1485
1586
  // lib/DataStoreSerializer.ts
1486
1587
  var DataStoreSerializer = class _DataStoreSerializer {
1487
- stores;
1488
- // eslint-disable-line @typescript-eslint/no-explicit-any
1489
- options;
1490
1588
  constructor(stores, options = {}) {
1589
+ __publicField(this, "stores");
1590
+ // eslint-disable-line @typescript-eslint/no-explicit-any
1591
+ __publicField(this, "options");
1491
1592
  if (!crypto || !crypto.subtle)
1492
1593
  throw new ScriptContextError("DataStoreSerializer has to run in a secure context (HTTPS) or in another environment that implements the subtleCrypto API!");
1493
1594
  this.stores = stores;
1494
- this.options = {
1595
+ this.options = __spreadValues({
1495
1596
  addChecksum: true,
1496
1597
  ensureIntegrity: true,
1497
- remapIds: {},
1498
- ...options
1499
- };
1598
+ remapIds: {}
1599
+ }, options);
1500
1600
  }
1501
1601
  /**
1502
1602
  * Calculates the checksum of a string. Uses {@linkcode computeHash()} with SHA-256 and digests as a hex string by default.
1503
1603
  * Override this in a subclass if a custom checksum method is needed.
1504
1604
  */
1505
- async calcChecksum(input) {
1506
- return computeHash(input, "SHA-256");
1605
+ calcChecksum(input) {
1606
+ return __async(this, null, function* () {
1607
+ return computeHash(input, "SHA-256");
1608
+ });
1507
1609
  }
1508
1610
  /**
1509
1611
  * Serializes only a subset of the data stores into a string.
@@ -1511,72 +1613,80 @@ var DataStoreSerializer = class _DataStoreSerializer {
1511
1613
  * @param useEncoding Whether to encode the data using each DataStore's `encodeData()` method
1512
1614
  * @param stringified Whether to return the result as a string or as an array of `SerializedDataStore` objects
1513
1615
  */
1514
- async serializePartial(stores, useEncoding = true, stringified = true) {
1515
- var _a;
1516
- const serData = [];
1517
- const filteredStores = this.stores.filter((s) => typeof stores === "function" ? stores(s.id) : stores.includes(s.id));
1518
- for (const storeInst of filteredStores) {
1519
- const encoded = Boolean(useEncoding && storeInst.encodingEnabled() && ((_a = storeInst.encodeData) == null ? void 0 : _a[1]));
1520
- const rawData = storeInst.memoryCache ? storeInst.getData() : await storeInst.loadData();
1521
- const data = encoded ? await storeInst.encodeData[1](JSON.stringify(rawData)) : JSON.stringify(rawData);
1522
- serData.push({
1523
- id: storeInst.id,
1524
- data,
1525
- formatVersion: storeInst.formatVersion,
1526
- encoded,
1527
- checksum: this.options.addChecksum ? await this.calcChecksum(data) : void 0
1528
- });
1529
- }
1530
- return stringified ? JSON.stringify(serData) : serData;
1616
+ serializePartial(stores, useEncoding = true, stringified = true) {
1617
+ return __async(this, null, function* () {
1618
+ var _a;
1619
+ const serData = [];
1620
+ const filteredStores = this.stores.filter((s) => typeof stores === "function" ? stores(s.id) : stores.includes(s.id));
1621
+ for (const storeInst of filteredStores) {
1622
+ const encoded = Boolean(useEncoding && storeInst.encodingEnabled() && ((_a = storeInst.encodeData) == null ? void 0 : _a[1]));
1623
+ const rawData = storeInst.memoryCache ? storeInst.getData() : yield storeInst.loadData();
1624
+ const data = encoded ? yield storeInst.encodeData[1](JSON.stringify(rawData)) : JSON.stringify(rawData);
1625
+ serData.push({
1626
+ id: storeInst.id,
1627
+ data,
1628
+ formatVersion: storeInst.formatVersion,
1629
+ encoded,
1630
+ checksum: this.options.addChecksum ? yield this.calcChecksum(data) : void 0
1631
+ });
1632
+ }
1633
+ return stringified ? JSON.stringify(serData) : serData;
1634
+ });
1531
1635
  }
1532
1636
  /**
1533
1637
  * Serializes the data stores into a string.
1534
1638
  * @param useEncoding Whether to encode the data using each DataStore's `encodeData()` method
1535
1639
  * @param stringified Whether to return the result as a string or as an array of `SerializedDataStore` objects
1536
1640
  */
1537
- async serialize(useEncoding = true, stringified = true) {
1538
- return this.serializePartial(this.stores.map((s) => s.id), useEncoding, stringified);
1641
+ serialize(useEncoding = true, stringified = true) {
1642
+ return __async(this, null, function* () {
1643
+ return this.serializePartial(this.stores.map((s) => s.id), useEncoding, stringified);
1644
+ });
1539
1645
  }
1540
1646
  /**
1541
1647
  * Deserializes the data exported via {@linkcode serialize()} and imports only a subset into the DataStore instances.
1542
1648
  * Also triggers the migration process if the data format has changed.
1543
1649
  */
1544
- async deserializePartial(stores, data) {
1545
- const deserStores = typeof data === "string" ? JSON.parse(data) : data;
1546
- if (!Array.isArray(deserStores) || !deserStores.every(_DataStoreSerializer.isSerializedDataStoreObj))
1547
- throw new TypeError("Invalid serialized data format! Expected an array of SerializedDataStore objects.");
1548
- const resolveStoreId = (id) => {
1549
- var _a;
1550
- return ((_a = Object.entries(this.options.remapIds).find(([, v]) => v.includes(id))) == null ? void 0 : _a[0]) ?? id;
1551
- };
1552
- const matchesFilter = (id) => typeof stores === "function" ? stores(id) : stores.includes(id);
1553
- for (const storeData of deserStores) {
1554
- const effectiveId = resolveStoreId(storeData.id);
1555
- if (!matchesFilter(effectiveId))
1556
- continue;
1557
- const storeInst = this.stores.find((s) => s.id === effectiveId);
1558
- if (!storeInst)
1559
- 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.`);
1560
- if (this.options.ensureIntegrity && typeof storeData.checksum === "string") {
1561
- const checksum = await this.calcChecksum(storeData.data);
1562
- if (checksum !== storeData.checksum)
1563
- throw new ChecksumMismatchError(`Checksum mismatch for DataStore with ID "${storeData.id}"!
1650
+ deserializePartial(stores, data) {
1651
+ return __async(this, null, function* () {
1652
+ const deserStores = typeof data === "string" ? JSON.parse(data) : data;
1653
+ if (!Array.isArray(deserStores) || !deserStores.every(_DataStoreSerializer.isSerializedDataStoreObj))
1654
+ throw new TypeError("Invalid serialized data format! Expected an array of SerializedDataStore objects.");
1655
+ const resolveStoreId = (id) => {
1656
+ var _a, _b;
1657
+ return (_b = (_a = Object.entries(this.options.remapIds).find(([, v]) => v.includes(id))) == null ? void 0 : _a[0]) != null ? _b : id;
1658
+ };
1659
+ const matchesFilter = (id) => typeof stores === "function" ? stores(id) : stores.includes(id);
1660
+ for (const storeData of deserStores) {
1661
+ const effectiveId = resolveStoreId(storeData.id);
1662
+ if (!matchesFilter(effectiveId))
1663
+ continue;
1664
+ const storeInst = this.stores.find((s) => s.id === effectiveId);
1665
+ if (!storeInst)
1666
+ 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.`);
1667
+ if (this.options.ensureIntegrity && typeof storeData.checksum === "string") {
1668
+ const checksum = yield this.calcChecksum(storeData.data);
1669
+ if (checksum !== storeData.checksum)
1670
+ throw new ChecksumMismatchError(`Checksum mismatch for DataStore with ID "${storeData.id}"!
1564
1671
  Expected: ${storeData.checksum}
1565
1672
  Has: ${checksum}`);
1673
+ }
1674
+ const decodedData = storeData.encoded && storeInst.encodingEnabled() ? yield storeInst.decodeData[1](storeData.data) : storeData.data;
1675
+ if (storeData.formatVersion && !isNaN(Number(storeData.formatVersion)) && Number(storeData.formatVersion) < storeInst.formatVersion)
1676
+ yield storeInst.runMigrations(JSON.parse(decodedData), Number(storeData.formatVersion), false);
1677
+ else
1678
+ yield storeInst.setData(JSON.parse(decodedData));
1566
1679
  }
1567
- const decodedData = storeData.encoded && storeInst.encodingEnabled() ? await storeInst.decodeData[1](storeData.data) : storeData.data;
1568
- if (storeData.formatVersion && !isNaN(Number(storeData.formatVersion)) && Number(storeData.formatVersion) < storeInst.formatVersion)
1569
- await storeInst.runMigrations(JSON.parse(decodedData), Number(storeData.formatVersion), false);
1570
- else
1571
- await storeInst.setData(JSON.parse(decodedData));
1572
- }
1680
+ });
1573
1681
  }
1574
1682
  /**
1575
1683
  * Deserializes the data exported via {@linkcode serialize()} and imports the data into all matching DataStore instances.
1576
1684
  * Also triggers the migration process if the data format has changed.
1577
1685
  */
1578
- async deserialize(data) {
1579
- return this.deserializePartial(this.stores.map((s) => s.id), data);
1686
+ deserialize(data) {
1687
+ return __async(this, null, function* () {
1688
+ return this.deserializePartial(this.stores.map((s) => s.id), data);
1689
+ });
1580
1690
  }
1581
1691
  /**
1582
1692
  * Loads the persistent data of the DataStore instances into the in-memory cache.
@@ -1584,155 +1694,6 @@ Has: ${checksum}`);
1584
1694
  * @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
1585
1695
  * @returns Returns a PromiseSettledResult array with the results of each DataStore instance in the format `{ id: string, data: object }`
1586
1696
  */
1587
- async loadStoresData(stores) {
1588
- return Promise.allSettled(
1589
- this.getStoresFiltered(stores).map(async (store) => ({
1590
- id: store.id,
1591
- data: await store.loadData()
1592
- }))
1593
- );
1594
- }
1595
- /**
1596
- * Resets the persistent and in-memory data of the DataStore instances to their default values.
1597
- * @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
1598
- */
1599
- async resetStoresData(stores) {
1600
- return Promise.allSettled(
1601
- this.getStoresFiltered(stores).map((store) => store.saveDefaultData())
1602
- );
1603
- }
1604
- /**
1605
- * Deletes the persistent data of the DataStore instances.
1606
- * Leaves the in-memory data untouched.
1607
- * @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
1608
- */
1609
- async deleteStoresData(stores) {
1610
- return Promise.allSettled(
1611
- this.getStoresFiltered(stores).map((store) => store.deleteData())
1612
- );
1613
- }
1614
- /** Checks if a given value is an array of SerializedDataStore objects */
1615
- static isSerializedDataStoreObjArray(obj) {
1616
- return Array.isArray(obj) && obj.every((o) => typeof o === "object" && o !== null && "id" in o && "data" in o && "formatVersion" in o && "encoded" in o);
1617
- }
1618
- /** Checks if a given value is a SerializedDataStore object */
1619
- static isSerializedDataStoreObj(obj) {
1620
- return typeof obj === "object" && obj !== null && "id" in obj && "data" in obj && "formatVersion" in obj && "encoded" in obj;
1621
- }
1622
- /** Returns the DataStore instances whose IDs match the provided array or function */
1623
- getStoresFiltered(stores) {
1624
- return this.stores.filter((s) => typeof stores === "undefined" ? true : Array.isArray(stores) ? stores.includes(s.id) : stores(s.id));
1625
- }
1626
- };
1627
-
1628
- // lib/Debouncer.ts
1629
- var Debouncer = class extends NanoEmitter {
1630
- /**
1631
- * Creates a new debouncer with the specified timeout and edge type.
1632
- * @param timeout Timeout in milliseconds between letting through calls - defaults to 200
1633
- * @param type The edge type to use for the debouncer - see {@linkcode DebouncerType} for details or [the documentation for an explanation and diagram](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#debouncer) - defaults to "immediate"
1634
- */
1635
- constructor(timeout = 200, type = "immediate", nanoEmitterOptions) {
1636
- super(nanoEmitterOptions);
1637
- this.timeout = timeout;
1638
- this.type = type;
1639
- }
1640
- /** All registered listener functions and the time they were attached */
1641
- listeners = [];
1642
- /** The currently active timeout */
1643
- activeTimeout;
1644
- /** The latest queued call */
1645
- queuedCall;
1646
- //#region listeners
1647
- /** Adds a listener function that will be called on timeout */
1648
- addListener(fn) {
1649
- this.listeners.push(fn);
1650
- }
1651
- /** Removes the listener with the specified function reference */
1652
- removeListener(fn) {
1653
- const idx = this.listeners.findIndex((l) => l === fn);
1654
- idx !== -1 && this.listeners.splice(idx, 1);
1655
- }
1656
- /** Removes all listeners */
1657
- removeAllListeners() {
1658
- this.listeners = [];
1659
- }
1660
- /** Returns all registered listeners */
1661
- getListeners() {
1662
- return this.listeners;
1663
- }
1664
- //#region timeout
1665
- /** Sets the timeout for the debouncer */
1666
- setTimeout(timeout) {
1667
- this.events.emit("change", this.timeout = timeout, this.type);
1668
- }
1669
- /** Returns the current timeout */
1670
- getTimeout() {
1671
- return this.timeout;
1672
- }
1673
- /** Whether the timeout is currently active, meaning any latest call to the {@linkcode call()} method will be queued */
1674
- isTimeoutActive() {
1675
- return typeof this.activeTimeout !== "undefined";
1676
- }
1677
- //#region type
1678
- /** Sets the edge type for the debouncer */
1679
- setType(type) {
1680
- this.events.emit("change", this.timeout, this.type = type);
1681
- }
1682
- /** Returns the current edge type */
1683
- getType() {
1684
- return this.type;
1685
- }
1686
- //#region call
1687
- /** Use this to call the debouncer with the specified arguments that will be passed to all listener functions registered with {@linkcode addListener()} */
1688
- call(...args) {
1689
- const cl = (...a) => {
1690
- this.queuedCall = void 0;
1691
- this.events.emit("call", ...a);
1692
- this.listeners.forEach((l) => l.call(this, ...a));
1693
- };
1694
- const setRepeatTimeout = () => {
1695
- this.activeTimeout = setTimeout(() => {
1696
- if (this.queuedCall) {
1697
- this.queuedCall();
1698
- setRepeatTimeout();
1699
- } else
1700
- this.activeTimeout = void 0;
1701
- }, this.timeout);
1702
- };
1703
- switch (this.type) {
1704
- case "immediate":
1705
- if (typeof this.activeTimeout === "undefined") {
1706
- cl(...args);
1707
- setRepeatTimeout();
1708
- } else
1709
- this.queuedCall = () => cl(...args);
1710
- break;
1711
- case "idle":
1712
- if (this.activeTimeout)
1713
- clearTimeout(this.activeTimeout);
1714
- this.activeTimeout = setTimeout(() => {
1715
- cl(...args);
1716
- this.activeTimeout = void 0;
1717
- }, this.timeout);
1718
- break;
1719
- default:
1720
- throw new TypeError(`Invalid debouncer type: ${this.type}`);
1721
- }
1722
- }
1723
- };
1724
- function debounce(fn, timeout = 200, type = "immediate", nanoEmitterOptions) {
1725
- const debouncer = new Debouncer(timeout, type, nanoEmitterOptions);
1726
- debouncer.addListener(fn);
1727
- const func = ((...args) => debouncer.call(...args));
1728
- func.debouncer = debouncer;
1729
- return func;
1730
- }
1731
- sistent data of the DataStore instances into the in-memory cache.
1732
- * Also triggers the migration process if the data format has changed.
1733
- * @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
1734
- * @returns Returns a PromiseSettledResult array with the results of each DataStore instance in the format `{ id: string, data: object }`
1735
- */
1736
1697
  loadStoresData(stores) {
1737
1698
  return __async(this, null, function* () {
1738
1699
  return Promise.allSettled(
@@ -1887,7 +1848,7 @@ function debounce(fn, timeout = 200, type = "immediate", nanoEmitterOptions) {
1887
1848
  }
1888
1849
 
1889
1850
  if(__exports != exports)module.exports = exports;return module.exports}));
1890
- //# sourceMappingURL=CoreUtils.umd.js.map
1851
+
1891
1852
 
1892
1853
 
1893
1854
  if (typeof module.exports == "object" && typeof exports == "object") {