@sv443-network/coreutils 2.0.1 → 2.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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 = {};
@@ -190,7 +239,7 @@ function randRange(...args) {
190
239
  return Math.floor(Math.random() * (max - min + 1)) + min;
191
240
  }
192
241
  function roundFixed(num, fractionDigits) {
193
- const scale = 10 ** fractionDigits;
242
+ const scale = __pow(10, fractionDigits);
194
243
  return Math.round(num * scale) / scale;
195
244
  }
196
245
  function valsWithin(a, b, dec = 10, withinRange = 0.5) {
@@ -254,7 +303,7 @@ function darkenColor(color, percent, upperCase = false) {
254
303
  if (isHexCol)
255
304
  return rgbToHex(r, g, b, a, color.startsWith("#"), upperCase);
256
305
  else if (color.startsWith("rgba"))
257
- return `rgba(${r}, ${g}, ${b}, ${a ?? NaN})`;
306
+ return `rgba(${r}, ${g}, ${b}, ${a != null ? a : NaN})`;
258
307
  else
259
308
  return `rgb(${r}, ${g}, ${b})`;
260
309
  }
@@ -288,35 +337,43 @@ function abtoa(buf) {
288
337
  function atoab(str) {
289
338
  return Uint8Array.from(atob(str), (c) => c.charCodeAt(0));
290
339
  }
291
- async function compress(input, compressionFormat, outputType = "string") {
292
- const byteArray = input instanceof Uint8Array ? input : new TextEncoder().encode((input == null ? void 0 : input.toString()) ?? String(input));
293
- const comp = new CompressionStream(compressionFormat);
294
- const writer = comp.writable.getWriter();
295
- writer.write(byteArray);
296
- writer.close();
297
- const uintArr = new Uint8Array(await new Response(comp.readable).arrayBuffer());
298
- return outputType === "arrayBuffer" ? uintArr : abtoa(uintArr);
340
+ function compress(input, compressionFormat, outputType = "string") {
341
+ return __async(this, null, function* () {
342
+ var _a;
343
+ const byteArray = input instanceof Uint8Array ? input : new TextEncoder().encode((_a = input == null ? void 0 : input.toString()) != null ? _a : String(input));
344
+ const comp = new CompressionStream(compressionFormat);
345
+ const writer = comp.writable.getWriter();
346
+ writer.write(byteArray);
347
+ writer.close();
348
+ const uintArr = new Uint8Array(yield new Response(comp.readable).arrayBuffer());
349
+ return outputType === "arrayBuffer" ? uintArr : abtoa(uintArr);
350
+ });
299
351
  }
300
- async function decompress(input, compressionFormat, outputType = "string") {
301
- const byteArray = input instanceof Uint8Array ? input : atoab((input == null ? void 0 : input.toString()) ?? String(input));
302
- const decomp = new DecompressionStream(compressionFormat);
303
- const writer = decomp.writable.getWriter();
304
- writer.write(byteArray);
305
- writer.close();
306
- const uintArr = new Uint8Array(await new Response(decomp.readable).arrayBuffer());
307
- return outputType === "arrayBuffer" ? uintArr : new TextDecoder().decode(uintArr);
352
+ function decompress(input, compressionFormat, outputType = "string") {
353
+ return __async(this, null, function* () {
354
+ var _a;
355
+ const byteArray = input instanceof Uint8Array ? input : atoab((_a = input == null ? void 0 : input.toString()) != null ? _a : String(input));
356
+ const decomp = new DecompressionStream(compressionFormat);
357
+ const writer = decomp.writable.getWriter();
358
+ writer.write(byteArray);
359
+ writer.close();
360
+ const uintArr = new Uint8Array(yield new Response(decomp.readable).arrayBuffer());
361
+ return outputType === "arrayBuffer" ? uintArr : new TextDecoder().decode(uintArr);
362
+ });
308
363
  }
309
- async function computeHash(input, algorithm = "SHA-256") {
310
- let data;
311
- if (typeof input === "string") {
312
- const encoder = new TextEncoder();
313
- data = encoder.encode(input);
314
- } else
315
- data = input;
316
- const hashBuffer = await crypto.subtle.digest(algorithm, data);
317
- const hashArray = Array.from(new Uint8Array(hashBuffer));
318
- const hashHex = hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
319
- return hashHex;
364
+ function computeHash(input, algorithm = "SHA-256") {
365
+ return __async(this, null, function* () {
366
+ let data;
367
+ if (typeof input === "string") {
368
+ const encoder = new TextEncoder();
369
+ data = encoder.encode(input);
370
+ } else
371
+ data = input;
372
+ const hashBuffer = yield crypto.subtle.digest(algorithm, data);
373
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
374
+ const hashHex = hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
375
+ return hashHex;
376
+ });
320
377
  }
321
378
  function randomId(length = 16, radix = 16, enhancedEntropy = false, randomCase = true) {
322
379
  if (length < 1)
@@ -344,35 +401,38 @@ function randomId(length = 16, radix = 16, enhancedEntropy = false, randomCase =
344
401
  }
345
402
 
346
403
  // lib/misc.ts
347
- async function consumeGen(valGen) {
348
- return await (typeof valGen === "function" ? valGen() : valGen);
404
+ function consumeGen(valGen) {
405
+ return __async(this, null, function* () {
406
+ return yield typeof valGen === "function" ? valGen() : valGen;
407
+ });
349
408
  }
350
- async function consumeStringGen(strGen) {
351
- return typeof strGen === "string" ? strGen : String(
352
- typeof strGen === "function" ? await strGen() : strGen
353
- );
409
+ function consumeStringGen(strGen) {
410
+ return __async(this, null, function* () {
411
+ return typeof strGen === "string" ? strGen : String(
412
+ typeof strGen === "function" ? yield strGen() : strGen
413
+ );
414
+ });
354
415
  }
355
- async function fetchAdvanced(input, options = {}) {
356
- const { timeout = 1e4 } = options;
357
- const ctl = new AbortController();
358
- const { signal, ...restOpts } = options;
359
- signal == null ? void 0 : signal.addEventListener("abort", () => ctl.abort());
360
- let sigOpts = {}, id = void 0;
361
- if (timeout >= 0) {
362
- id = setTimeout(() => ctl.abort(), timeout);
363
- sigOpts = { signal: ctl.signal };
364
- }
365
- try {
366
- const res = await fetch(input, {
367
- ...restOpts,
368
- ...sigOpts
369
- });
370
- typeof id !== "undefined" && clearTimeout(id);
371
- return res;
372
- } catch (err) {
373
- typeof id !== "undefined" && clearTimeout(id);
374
- throw new Error("Error while calling fetch", { cause: err });
375
- }
416
+ function fetchAdvanced(_0) {
417
+ return __async(this, arguments, function* (input, options = {}) {
418
+ const { timeout = 1e4 } = options;
419
+ const ctl = new AbortController();
420
+ const _a = options, { signal } = _a, restOpts = __objRest(_a, ["signal"]);
421
+ signal == null ? void 0 : signal.addEventListener("abort", () => ctl.abort());
422
+ let sigOpts = {}, id = void 0;
423
+ if (timeout >= 0) {
424
+ id = setTimeout(() => ctl.abort(), timeout);
425
+ sigOpts = { signal: ctl.signal };
426
+ }
427
+ try {
428
+ const res = yield fetch(input, __spreadValues(__spreadValues({}, restOpts), sigOpts));
429
+ typeof id !== "undefined" && clearTimeout(id);
430
+ return res;
431
+ } catch (err) {
432
+ typeof id !== "undefined" && clearTimeout(id);
433
+ throw new Error("Error while calling fetch", { cause: err });
434
+ }
435
+ });
376
436
  }
377
437
  function getListLength(listLike, zeroOnInvalid = true) {
378
438
  return "length" in listLike ? listLike.length : "size" in listLike ? listLike.size : "count" in listLike ? listLike.count : zeroOnInvalid ? 0 : NaN;
@@ -387,7 +447,7 @@ function pauseFor(time, signal, rejectOnAbort = false) {
387
447
  });
388
448
  }
389
449
  function pureObj(obj) {
390
- return Object.assign(/* @__PURE__ */ Object.create(null), obj ?? {});
450
+ return Object.assign(/* @__PURE__ */ Object.create(null), obj != null ? obj : {});
391
451
  }
392
452
  function setImmediateInterval(callback, interval, signal) {
393
453
  let intervalId;
@@ -404,12 +464,12 @@ function setImmediateInterval(callback, interval, signal) {
404
464
  function setImmediateTimeoutLoop(callback, interval, signal) {
405
465
  let timeout;
406
466
  const cleanup = () => clearTimeout(timeout);
407
- const loop = async () => {
467
+ const loop = () => __async(null, null, function* () {
408
468
  if (signal == null ? void 0 : signal.aborted)
409
469
  return cleanup();
410
- await callback();
470
+ yield callback();
411
471
  timeout = setTimeout(loop, interval);
412
- };
472
+ });
413
473
  signal == null ? void 0 : signal.addEventListener("abort", cleanup);
414
474
  loop();
415
475
  }
@@ -476,9 +536,9 @@ function createProgressBar(percentage, barLength, chars = defaultPbChars) {
476
536
  }
477
537
  function insertValues(input, ...values) {
478
538
  return input.replace(/%\d/gm, (match) => {
479
- var _a;
539
+ var _a, _b;
480
540
  const argIndex = Number(match.substring(1)) - 1;
481
- return (_a = values[argIndex] ?? match) == null ? void 0 : _a.toString();
541
+ return (_b = (_a = values[argIndex]) != null ? _a : match) == null ? void 0 : _b.toString();
482
542
  });
483
543
  }
484
544
  function joinArrayReadable(array, separators = ", ", lastSeparator = " and ") {
@@ -507,16 +567,17 @@ function secsToTimeStr(seconds) {
507
567
  ].join("");
508
568
  }
509
569
  function truncStr(input, length, endStr = "...") {
510
- const str = (input == null ? void 0 : input.toString()) ?? String(input);
570
+ var _a;
571
+ const str = (_a = input == null ? void 0 : input.toString()) != null ? _a : String(input);
511
572
  const finalStr = str.length > length ? str.substring(0, length - endStr.length) + endStr : str;
512
573
  return finalStr.length > length ? finalStr.substring(0, length) : finalStr;
513
574
  }
514
575
 
515
576
  // lib/Errors.ts
516
577
  var DatedError = class extends Error {
517
- date;
518
578
  constructor(message, options) {
519
579
  super(message, options);
580
+ __publicField(this, "date");
520
581
  this.name = this.constructor.name;
521
582
  this.date = /* @__PURE__ */ new Date();
522
583
  }
@@ -543,24 +604,6 @@ var ValidationError = class extends DatedError {
543
604
  // lib/DataStore.ts
544
605
  var dsFmtVer = 1;
545
606
  var DataStore = class {
546
- id;
547
- formatVersion;
548
- defaultData;
549
- encodeData;
550
- decodeData;
551
- compressionFormat = "deflate-raw";
552
- engine;
553
- options;
554
- /**
555
- * Whether all first-init checks should be done.
556
- * This includes migrating the internal DataStore format, migrating data from the UserUtils format, and anything similar.
557
- * 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.
558
- */
559
- firstInit = true;
560
- /** In-memory cached copy of the data that is saved in persistent storage used for synchronous read access. */
561
- cachedData;
562
- migrations;
563
- migrateIds = [];
564
607
  /**
565
608
  * Creates an instance of DataStore to manage a sync & async database that is cached in memory and persistently saved across sessions.
566
609
  * Supports migrating data from older versions to newer ones and populating the cache with default data if no persistent data is found.
@@ -571,7 +614,25 @@ var DataStore = class {
571
614
  * @param opts The options for this DataStore instance
572
615
  */
573
616
  constructor(opts) {
574
- var _a;
617
+ __publicField(this, "id");
618
+ __publicField(this, "formatVersion");
619
+ __publicField(this, "defaultData");
620
+ __publicField(this, "encodeData");
621
+ __publicField(this, "decodeData");
622
+ __publicField(this, "compressionFormat", "deflate-raw");
623
+ __publicField(this, "engine");
624
+ __publicField(this, "options");
625
+ /**
626
+ * Whether all first-init checks should be done.
627
+ * This includes migrating the internal DataStore format, migrating data from the UserUtils format, and anything similar.
628
+ * 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.
629
+ */
630
+ __publicField(this, "firstInit", true);
631
+ /** In-memory cached copy of the data that is saved in persistent storage used for synchronous read access. */
632
+ __publicField(this, "cachedData");
633
+ __publicField(this, "migrations");
634
+ __publicField(this, "migrateIds", []);
635
+ var _a, _b, _c;
575
636
  this.id = opts.id;
576
637
  this.formatVersion = opts.formatVersion;
577
638
  this.defaultData = opts.defaultData;
@@ -584,16 +645,22 @@ var DataStore = class {
584
645
  this.engine = typeof opts.engine === "function" ? opts.engine() : opts.engine;
585
646
  this.options = opts;
586
647
  if (typeof opts.compressionFormat === "undefined")
587
- opts.compressionFormat = ((_a = opts.encodeData) == null ? void 0 : _a[0]) ?? "deflate-raw";
648
+ this.compressionFormat = opts.compressionFormat = (_b = (_a = opts.encodeData) == null ? void 0 : _a[0]) != null ? _b : "deflate-raw";
588
649
  if (typeof opts.compressionFormat === "string") {
589
- this.encodeData = [opts.compressionFormat, async (data) => await compress(data, opts.compressionFormat, "string")];
590
- this.decodeData = [opts.compressionFormat, async (data) => await compress(data, opts.compressionFormat, "string")];
650
+ this.encodeData = [opts.compressionFormat, (data) => __async(this, null, function* () {
651
+ return yield compress(data, opts.compressionFormat, "string");
652
+ })];
653
+ this.decodeData = [opts.compressionFormat, (data) => __async(this, null, function* () {
654
+ return yield compress(data, opts.compressionFormat, "string");
655
+ })];
591
656
  } else if ("encodeData" in opts && "decodeData" in opts && Array.isArray(opts.encodeData) && Array.isArray(opts.decodeData)) {
592
657
  this.encodeData = [opts.encodeData[0], opts.encodeData[1]];
593
658
  this.decodeData = [opts.decodeData[0], opts.decodeData[1]];
659
+ this.compressionFormat = (_c = opts.encodeData[0]) != null ? _c : null;
594
660
  } else if (opts.compressionFormat === null) {
595
661
  this.encodeData = void 0;
596
662
  this.decodeData = void 0;
663
+ this.compressionFormat = null;
597
664
  } else
598
665
  throw new TypeError("Either `compressionFormat` or `encodeData` and `decodeData` have to be set and valid, but not all three at a time. Please refer to the documentation for more info.");
599
666
  this.engine.setDataStoreOptions(opts);
@@ -604,62 +671,65 @@ var DataStore = class {
604
671
  * Automatically populates persistent storage with default data if it doesn't contain any data yet.
605
672
  * Also runs all necessary migration functions if the data format has changed since the last time the data was saved.
606
673
  */
607
- async loadData() {
608
- try {
609
- if (this.firstInit) {
610
- this.firstInit = false;
611
- const dsVer = Number(await this.engine.getValue("__ds_fmt_ver", 0));
612
- if (isNaN(dsVer) || dsVer < 1) {
613
- const oldData = await this.engine.getValue(`_uucfg-${this.id}`, null);
614
- if (oldData) {
615
- const oldVer = Number(await this.engine.getValue(`_uucfgver-${this.id}`, NaN));
616
- const oldEnc = await this.engine.getValue(`_uucfgenc-${this.id}`, null);
617
- const promises = [];
618
- const migrateFmt = (oldKey, newKey, value) => {
619
- promises.push(this.engine.setValue(newKey, value));
620
- promises.push(this.engine.deleteValue(oldKey));
621
- };
622
- if (oldData)
623
- migrateFmt(`_uucfg-${this.id}`, `__ds-${this.id}-dat`, oldData);
624
- if (!isNaN(oldVer))
625
- migrateFmt(`_uucfgver-${this.id}`, `__ds-${this.id}-ver`, oldVer);
626
- if (typeof oldEnc === "boolean")
627
- migrateFmt(`_uucfgenc-${this.id}`, `__ds-${this.id}-enf`, oldEnc === true ? Boolean(this.compressionFormat) || null : null);
628
- else
629
- promises.push(this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat));
630
- await Promise.allSettled(promises);
674
+ loadData() {
675
+ return __async(this, null, function* () {
676
+ try {
677
+ if (this.firstInit) {
678
+ this.firstInit = false;
679
+ const dsVer = Number(yield this.engine.getValue("__ds_fmt_ver", 0));
680
+ if (isNaN(dsVer) || dsVer < 1) {
681
+ const oldData = yield this.engine.getValue(`_uucfg-${this.id}`, null);
682
+ if (oldData) {
683
+ const oldVer = Number(yield this.engine.getValue(`_uucfgver-${this.id}`, NaN));
684
+ const oldEnc = yield this.engine.getValue(`_uucfgenc-${this.id}`, null);
685
+ const promises = [];
686
+ const migrateFmt = (oldKey, newKey, value) => {
687
+ promises.push(this.engine.setValue(newKey, value));
688
+ promises.push(this.engine.deleteValue(oldKey));
689
+ };
690
+ if (oldData)
691
+ migrateFmt(`_uucfg-${this.id}`, `__ds-${this.id}-dat`, oldData);
692
+ if (!isNaN(oldVer))
693
+ migrateFmt(`_uucfgver-${this.id}`, `__ds-${this.id}-ver`, oldVer);
694
+ if (typeof oldEnc === "boolean")
695
+ migrateFmt(`_uucfgenc-${this.id}`, `__ds-${this.id}-enf`, oldEnc === true ? Boolean(this.compressionFormat) || null : null);
696
+ else
697
+ promises.push(this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat));
698
+ yield Promise.allSettled(promises);
699
+ }
700
+ yield this.engine.setValue("__ds_fmt_ver", dsFmtVer);
631
701
  }
632
- await this.engine.setValue("__ds_fmt_ver", dsFmtVer);
633
702
  }
703
+ if (this.migrateIds.length > 0) {
704
+ yield this.migrateId(this.migrateIds);
705
+ this.migrateIds = [];
706
+ }
707
+ const storedDataRaw = yield this.engine.getValue(`__ds-${this.id}-dat`, null);
708
+ let storedFmtVer = Number(yield this.engine.getValue(`__ds-${this.id}-ver`, NaN));
709
+ if (typeof storedDataRaw !== "string") {
710
+ yield this.saveDefaultData();
711
+ return __spreadValues({}, this.defaultData);
712
+ }
713
+ const storedData = storedDataRaw != null ? storedDataRaw : JSON.stringify(this.defaultData);
714
+ const encodingFmt = String(yield this.engine.getValue(`__ds-${this.id}-enf`, null));
715
+ const isEncoded = encodingFmt !== "null" && encodingFmt !== "false";
716
+ let saveData = false;
717
+ if (isNaN(storedFmtVer)) {
718
+ yield this.engine.setValue(`__ds-${this.id}-ver`, storedFmtVer = this.formatVersion);
719
+ saveData = true;
720
+ }
721
+ let parsed = yield this.engine.deserializeData(storedData, isEncoded);
722
+ if (storedFmtVer < this.formatVersion && this.migrations)
723
+ parsed = yield this.runMigrations(parsed, storedFmtVer);
724
+ if (saveData)
725
+ yield this.setData(parsed);
726
+ return this.cachedData = this.engine.deepCopy(parsed);
727
+ } catch (err) {
728
+ console.warn("Error while parsing JSON data, resetting it to the default value.", err);
729
+ yield this.saveDefaultData();
730
+ return this.defaultData;
634
731
  }
635
- if (this.migrateIds.length > 0) {
636
- await this.migrateId(this.migrateIds);
637
- this.migrateIds = [];
638
- }
639
- const storedData = await this.engine.getValue(`__ds-${this.id}-dat`, JSON.stringify(this.defaultData));
640
- let storedFmtVer = Number(await this.engine.getValue(`__ds-${this.id}-ver`, NaN));
641
- if (typeof storedData !== "string") {
642
- await this.saveDefaultData();
643
- return { ...this.defaultData };
644
- }
645
- const encodingFmt = String(await this.engine.getValue(`__ds-${this.id}-enf`, null));
646
- const isEncoded = encodingFmt !== "null" && encodingFmt !== "false";
647
- let saveData = false;
648
- if (isNaN(storedFmtVer)) {
649
- await this.engine.setValue(`__ds-${this.id}-ver`, storedFmtVer = this.formatVersion);
650
- saveData = true;
651
- }
652
- let parsed = await this.engine.deserializeData(storedData, isEncoded);
653
- if (storedFmtVer < this.formatVersion && this.migrations)
654
- parsed = await this.runMigrations(parsed, storedFmtVer);
655
- if (saveData)
656
- await this.setData(parsed);
657
- return this.cachedData = this.engine.deepCopy(parsed);
658
- } catch (err) {
659
- console.warn("Error while parsing JSON data, resetting it to the default value.", err);
660
- await this.saveDefaultData();
661
- return this.defaultData;
662
- }
732
+ });
663
733
  }
664
734
  /**
665
735
  * Returns a copy of the data from the in-memory cache.
@@ -671,37 +741,41 @@ var DataStore = class {
671
741
  /** Saves the data synchronously to the in-memory cache and asynchronously to the persistent storage */
672
742
  setData(data) {
673
743
  this.cachedData = data;
674
- return new Promise(async (resolve) => {
675
- await Promise.allSettled([
676
- this.engine.setValue(`__ds-${this.id}-dat`, await this.engine.serializeData(data, this.encodingEnabled())),
744
+ return new Promise((resolve) => __async(this, null, function* () {
745
+ yield Promise.allSettled([
746
+ this.engine.setValue(`__ds-${this.id}-dat`, yield this.engine.serializeData(data, this.encodingEnabled())),
677
747
  this.engine.setValue(`__ds-${this.id}-ver`, this.formatVersion),
678
748
  this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat)
679
749
  ]);
680
750
  resolve();
681
- });
751
+ }));
682
752
  }
683
753
  /** Saves the default data passed in the constructor synchronously to the in-memory cache and asynchronously to persistent storage */
684
- async saveDefaultData() {
685
- this.cachedData = this.defaultData;
686
- await Promise.allSettled([
687
- this.engine.setValue(`__ds-${this.id}-dat`, await this.engine.serializeData(this.defaultData, this.encodingEnabled())),
688
- this.engine.setValue(`__ds-${this.id}-ver`, this.formatVersion),
689
- this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat)
690
- ]);
754
+ saveDefaultData() {
755
+ return __async(this, null, function* () {
756
+ this.cachedData = this.defaultData;
757
+ yield Promise.allSettled([
758
+ this.engine.setValue(`__ds-${this.id}-dat`, yield this.engine.serializeData(this.defaultData, this.encodingEnabled())),
759
+ this.engine.setValue(`__ds-${this.id}-ver`, this.formatVersion),
760
+ this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat)
761
+ ]);
762
+ });
691
763
  }
692
764
  /**
693
765
  * Call this method to clear all persistently stored data associated with this DataStore instance, including the storage container (if supported by the DataStoreEngine).
694
766
  * The in-memory cache will be left untouched, so you may still access the data with {@linkcode getData()}
695
767
  * Calling {@linkcode loadData()} or {@linkcode setData()} after this method was called will recreate persistent storage with the cached or default data.
696
768
  */
697
- async deleteData() {
698
- var _a, _b;
699
- await Promise.allSettled([
700
- this.engine.deleteValue(`__ds-${this.id}-dat`),
701
- this.engine.deleteValue(`__ds-${this.id}-ver`),
702
- this.engine.deleteValue(`__ds-${this.id}-enf`)
703
- ]);
704
- await ((_b = (_a = this.engine).deleteStorage) == null ? void 0 : _b.call(_a));
769
+ deleteData() {
770
+ return __async(this, null, function* () {
771
+ var _a, _b;
772
+ yield Promise.allSettled([
773
+ this.engine.deleteValue(`__ds-${this.id}-dat`),
774
+ this.engine.deleteValue(`__ds-${this.id}-ver`),
775
+ this.engine.deleteValue(`__ds-${this.id}-enf`)
776
+ ]);
777
+ yield (_b = (_a = this.engine).deleteStorage) == null ? void 0 : _b.call(_a);
778
+ });
705
779
  }
706
780
  /** Returns whether encoding and decoding are enabled for this DataStore instance */
707
781
  encodingEnabled() {
@@ -715,69 +789,73 @@ var DataStore = class {
715
789
  *
716
790
  * 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.
717
791
  */
718
- async runMigrations(oldData, oldFmtVer, resetOnError = true) {
719
- if (!this.migrations)
720
- return oldData;
721
- let newData = oldData;
722
- const sortedMigrations = Object.entries(this.migrations).sort(([a], [b]) => Number(a) - Number(b));
723
- let lastFmtVer = oldFmtVer;
724
- for (const [fmtVer, migrationFunc] of sortedMigrations) {
725
- const ver = Number(fmtVer);
726
- if (oldFmtVer < this.formatVersion && oldFmtVer < ver) {
727
- try {
728
- const migRes = migrationFunc(newData);
729
- newData = migRes instanceof Promise ? await migRes : migRes;
730
- lastFmtVer = oldFmtVer = ver;
731
- } catch (err) {
732
- if (!resetOnError)
733
- throw new MigrationError(`Error while running migration function for format version '${fmtVer}'`, { cause: err });
734
- await this.saveDefaultData();
735
- return this.getData();
792
+ runMigrations(oldData, oldFmtVer, resetOnError = true) {
793
+ return __async(this, null, function* () {
794
+ if (!this.migrations)
795
+ return oldData;
796
+ let newData = oldData;
797
+ const sortedMigrations = Object.entries(this.migrations).sort(([a], [b]) => Number(a) - Number(b));
798
+ let lastFmtVer = oldFmtVer;
799
+ for (const [fmtVer, migrationFunc] of sortedMigrations) {
800
+ const ver = Number(fmtVer);
801
+ if (oldFmtVer < this.formatVersion && oldFmtVer < ver) {
802
+ try {
803
+ const migRes = migrationFunc(newData);
804
+ newData = migRes instanceof Promise ? yield migRes : migRes;
805
+ lastFmtVer = oldFmtVer = ver;
806
+ } catch (err) {
807
+ if (!resetOnError)
808
+ throw new MigrationError(`Error while running migration function for format version '${fmtVer}'`, { cause: err });
809
+ yield this.saveDefaultData();
810
+ return this.getData();
811
+ }
736
812
  }
737
813
  }
738
- }
739
- await Promise.allSettled([
740
- this.engine.setValue(`__ds-${this.id}-dat`, await this.engine.serializeData(newData)),
741
- this.engine.setValue(`__ds-${this.id}-ver`, lastFmtVer),
742
- this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat)
743
- ]);
744
- return this.cachedData = { ...newData };
814
+ yield Promise.allSettled([
815
+ this.engine.setValue(`__ds-${this.id}-dat`, yield this.engine.serializeData(newData)),
816
+ this.engine.setValue(`__ds-${this.id}-ver`, lastFmtVer),
817
+ this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat)
818
+ ]);
819
+ return this.cachedData = __spreadValues({}, newData);
820
+ });
745
821
  }
746
822
  /**
747
823
  * Tries to migrate the currently saved persistent data from one or more old IDs to the ID set in the constructor.
748
824
  * 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.
749
825
  */
750
- async migrateId(oldIds) {
751
- const ids = Array.isArray(oldIds) ? oldIds : [oldIds];
752
- await Promise.all(ids.map(async (id) => {
753
- const [data, fmtVer, isEncoded] = await (async () => {
754
- const [d, f, e] = await Promise.all([
755
- this.engine.getValue(`__ds-${id}-dat`, JSON.stringify(this.defaultData)),
756
- this.engine.getValue(`__ds-${id}-ver`, NaN),
757
- this.engine.getValue(`__ds-${id}-enf`, null)
826
+ migrateId(oldIds) {
827
+ return __async(this, null, function* () {
828
+ const ids = Array.isArray(oldIds) ? oldIds : [oldIds];
829
+ yield Promise.all(ids.map((id) => __async(this, null, function* () {
830
+ const [data, fmtVer, isEncoded] = yield (() => __async(this, null, function* () {
831
+ const [d, f, e] = yield Promise.all([
832
+ this.engine.getValue(`__ds-${id}-dat`, JSON.stringify(this.defaultData)),
833
+ this.engine.getValue(`__ds-${id}-ver`, NaN),
834
+ this.engine.getValue(`__ds-${id}-enf`, null)
835
+ ]);
836
+ return [d, Number(f), Boolean(e) && String(e) !== "null"];
837
+ }))();
838
+ if (data === void 0 || isNaN(fmtVer))
839
+ return;
840
+ const parsed = yield this.engine.deserializeData(data, isEncoded);
841
+ yield Promise.allSettled([
842
+ this.engine.setValue(`__ds-${this.id}-dat`, yield this.engine.serializeData(parsed)),
843
+ this.engine.setValue(`__ds-${this.id}-ver`, fmtVer),
844
+ this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat),
845
+ this.engine.deleteValue(`__ds-${id}-dat`),
846
+ this.engine.deleteValue(`__ds-${id}-ver`),
847
+ this.engine.deleteValue(`__ds-${id}-enf`)
758
848
  ]);
759
- return [d, Number(f), Boolean(e) && String(e) !== "null"];
760
- })();
761
- if (data === void 0 || isNaN(fmtVer))
762
- return;
763
- const parsed = await this.engine.deserializeData(data, isEncoded);
764
- await Promise.allSettled([
765
- this.engine.setValue(`__ds-${this.id}-dat`, await this.engine.serializeData(parsed)),
766
- this.engine.setValue(`__ds-${this.id}-ver`, fmtVer),
767
- this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat),
768
- this.engine.deleteValue(`__ds-${id}-dat`),
769
- this.engine.deleteValue(`__ds-${id}-ver`),
770
- this.engine.deleteValue(`__ds-${id}-enf`)
771
- ]);
772
- }));
849
+ })));
850
+ });
773
851
  }
774
852
  };
775
853
 
776
854
  // lib/DataStoreEngine.ts
777
855
  var DataStoreEngine = class {
778
- dataStoreOptions;
779
856
  // setDataStoreOptions() is called from inside the DataStore constructor to set this value
780
857
  constructor(options) {
858
+ __publicField(this, "dataStoreOptions");
781
859
  if (options)
782
860
  this.dataStoreOptions = options;
783
861
  }
@@ -787,25 +865,29 @@ var DataStoreEngine = class {
787
865
  }
788
866
  //#region serialization api
789
867
  /** Serializes the given object to a string, optionally encoded with `options.encodeData` if {@linkcode useEncoding} is set to true */
790
- async serializeData(data, useEncoding) {
791
- var _a, _b, _c, _d, _e;
792
- this.ensureDataStoreOptions();
793
- const stringData = JSON.stringify(data);
794
- if (!useEncoding || !((_a = this.dataStoreOptions) == null ? void 0 : _a.encodeData) || !((_b = this.dataStoreOptions) == null ? void 0 : _b.decodeData))
795
- return stringData;
796
- const encRes = (_e = (_d = (_c = this.dataStoreOptions) == null ? void 0 : _c.encodeData) == null ? void 0 : _d[1]) == null ? void 0 : _e.call(_d, stringData);
797
- if (encRes instanceof Promise)
798
- return await encRes;
799
- return encRes;
868
+ serializeData(data, useEncoding) {
869
+ return __async(this, null, function* () {
870
+ var _a, _b, _c, _d, _e;
871
+ this.ensureDataStoreOptions();
872
+ const stringData = JSON.stringify(data);
873
+ if (!useEncoding || !((_a = this.dataStoreOptions) == null ? void 0 : _a.encodeData) || !((_b = this.dataStoreOptions) == null ? void 0 : _b.decodeData))
874
+ return stringData;
875
+ const encRes = (_e = (_d = (_c = this.dataStoreOptions) == null ? void 0 : _c.encodeData) == null ? void 0 : _d[1]) == null ? void 0 : _e.call(_d, stringData);
876
+ if (encRes instanceof Promise)
877
+ return yield encRes;
878
+ return encRes;
879
+ });
800
880
  }
801
881
  /** Deserializes the given string to a JSON object, optionally decoded with `options.decodeData` if {@linkcode useEncoding} is set to true */
802
- async deserializeData(data, useEncoding) {
803
- var _a, _b, _c;
804
- this.ensureDataStoreOptions();
805
- 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;
806
- if (decRes instanceof Promise)
807
- decRes = await decRes;
808
- return JSON.parse(decRes ?? data);
882
+ deserializeData(data, useEncoding) {
883
+ return __async(this, null, function* () {
884
+ var _a, _b, _c;
885
+ this.ensureDataStoreOptions();
886
+ 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;
887
+ if (decRes instanceof Promise)
888
+ decRes = yield decRes;
889
+ return JSON.parse(decRes != null ? decRes : data);
890
+ });
809
891
  }
810
892
  //#region misc api
811
893
  /** Throws an error if the DataStoreOptions are not set or invalid */
@@ -823,13 +905,12 @@ var DataStoreEngine = class {
823
905
  try {
824
906
  if ("structuredClone" in globalThis)
825
907
  return structuredClone(obj);
826
- } catch {
908
+ } catch (e) {
827
909
  }
828
910
  return JSON.parse(JSON.stringify(obj));
829
911
  }
830
912
  };
831
913
  var BrowserStorageEngine = class extends DataStoreEngine {
832
- options;
833
914
  /**
834
915
  * Creates an instance of `BrowserStorageEngine`.
835
916
  *
@@ -838,34 +919,40 @@ var BrowserStorageEngine = class extends DataStoreEngine {
838
919
  */
839
920
  constructor(options) {
840
921
  super(options == null ? void 0 : options.dataStoreOptions);
841
- this.options = {
842
- type: "localStorage",
843
- ...options
844
- };
922
+ __publicField(this, "options");
923
+ this.options = __spreadValues({
924
+ type: "localStorage"
925
+ }, options);
845
926
  }
846
927
  //#region storage api
847
928
  /** Fetches a value from persistent storage */
848
- async getValue(name, defaultValue) {
849
- return (this.options.type === "localStorage" ? globalThis.localStorage.getItem(name) : globalThis.sessionStorage.getItem(name)) ?? defaultValue;
929
+ getValue(name, defaultValue) {
930
+ return __async(this, null, function* () {
931
+ const val = this.options.type === "localStorage" ? globalThis.localStorage.getItem(name) : globalThis.sessionStorage.getItem(name);
932
+ return typeof val === "undefined" ? defaultValue : val;
933
+ });
850
934
  }
851
935
  /** Sets a value in persistent storage */
852
- async setValue(name, value) {
853
- if (this.options.type === "localStorage")
854
- globalThis.localStorage.setItem(name, String(value));
855
- else
856
- globalThis.sessionStorage.setItem(name, String(value));
936
+ setValue(name, value) {
937
+ return __async(this, null, function* () {
938
+ if (this.options.type === "localStorage")
939
+ globalThis.localStorage.setItem(name, String(value));
940
+ else
941
+ globalThis.sessionStorage.setItem(name, String(value));
942
+ });
857
943
  }
858
944
  /** Deletes a value from persistent storage */
859
- async deleteValue(name) {
860
- if (this.options.type === "localStorage")
861
- globalThis.localStorage.removeItem(name);
862
- else
863
- globalThis.sessionStorage.removeItem(name);
945
+ deleteValue(name) {
946
+ return __async(this, null, function* () {
947
+ if (this.options.type === "localStorage")
948
+ globalThis.localStorage.removeItem(name);
949
+ else
950
+ globalThis.sessionStorage.removeItem(name);
951
+ });
864
952
  }
865
953
  };
866
954
  var fs;
867
955
  var FileStorageEngine = class extends DataStoreEngine {
868
- options;
869
956
  /**
870
957
  * Creates an instance of `FileStorageEngine`.
871
958
  *
@@ -874,107 +961,135 @@ var FileStorageEngine = class extends DataStoreEngine {
874
961
  */
875
962
  constructor(options) {
876
963
  super(options == null ? void 0 : options.dataStoreOptions);
877
- this.options = {
878
- filePath: (id) => `.ds-${id}`,
879
- ...options
880
- };
964
+ __publicField(this, "options");
965
+ __publicField(this, "fileAccessQueue", Promise.resolve());
966
+ this.options = __spreadValues({
967
+ filePath: (id) => `.ds-${id}`
968
+ }, options);
881
969
  }
882
970
  //#region json file
883
971
  /** Reads the file contents */
884
- async readFile() {
885
- var _a, _b, _c, _d;
886
- this.ensureDataStoreOptions();
887
- try {
888
- if (!fs)
889
- fs = (_a = await import("fs/promises")) == null ? void 0 : _a.default;
890
- if (!fs)
891
- throw new DatedError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new Error("'node:fs/promises' module not available") });
892
- const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
893
- const data = await fs.readFile(path, "utf-8");
894
- 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;
895
- } catch {
896
- return void 0;
897
- }
972
+ readFile() {
973
+ return __async(this, null, function* () {
974
+ var _a, _b, _c, _d, _e;
975
+ this.ensureDataStoreOptions();
976
+ try {
977
+ if (!fs)
978
+ fs = (_a = yield import("fs/promises")) == null ? void 0 : _a.default;
979
+ if (!fs)
980
+ throw new DatedError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new Error("'node:fs/promises' module not available") });
981
+ const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
982
+ const data = yield fs.readFile(path, "utf-8");
983
+ 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;
984
+ } catch (e) {
985
+ return void 0;
986
+ }
987
+ });
898
988
  }
899
989
  /** Overwrites the file contents */
900
- async writeFile(data) {
901
- var _a, _b, _c, _d;
902
- this.ensureDataStoreOptions();
903
- try {
904
- if (!fs)
905
- fs = (_a = await import("fs/promises")) == null ? void 0 : _a.default;
906
- if (!fs)
907
- throw new DatedError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new Error("'node:fs/promises' module not available") });
908
- const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
909
- await fs.mkdir(path.slice(0, path.lastIndexOf(path.includes("/") ? "/" : "\\")), { recursive: true });
910
- 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");
911
- } catch (err) {
912
- console.error("Error writing file:", err);
913
- }
990
+ writeFile(data) {
991
+ return __async(this, null, function* () {
992
+ var _a, _b, _c, _d, _e;
993
+ this.ensureDataStoreOptions();
994
+ try {
995
+ if (!fs)
996
+ fs = (_a = yield import("fs/promises")) == null ? void 0 : _a.default;
997
+ if (!fs)
998
+ throw new DatedError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new Error("'node:fs/promises' module not available") });
999
+ const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
1000
+ yield fs.mkdir(path.slice(0, path.lastIndexOf(path.includes("/") ? "/" : "\\")), { recursive: true });
1001
+ 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");
1002
+ } catch (err) {
1003
+ console.error("Error writing file:", err);
1004
+ }
1005
+ });
914
1006
  }
915
1007
  //#region storage api
916
1008
  /** Fetches a value from persistent storage */
917
- async getValue(name, defaultValue) {
918
- const data = await this.readFile();
919
- if (!data)
920
- return defaultValue;
921
- const value = data == null ? void 0 : data[name];
922
- if (value === void 0)
923
- return defaultValue;
924
- if (typeof value === "string")
1009
+ getValue(name, defaultValue) {
1010
+ return __async(this, null, function* () {
1011
+ const data = yield this.readFile();
1012
+ if (!data)
1013
+ return defaultValue;
1014
+ const value = data == null ? void 0 : data[name];
1015
+ if (typeof value === "undefined")
1016
+ return defaultValue;
1017
+ if (typeof value === "string")
1018
+ return value;
925
1019
  return value;
926
- return String(value ?? defaultValue);
1020
+ });
927
1021
  }
928
1022
  /** Sets a value in persistent storage */
929
- async setValue(name, value) {
930
- let data = await this.readFile();
931
- if (!data)
932
- data = {};
933
- data[name] = value;
934
- await this.writeFile(data);
1023
+ setValue(name, value) {
1024
+ return __async(this, null, function* () {
1025
+ this.fileAccessQueue = this.fileAccessQueue.then(() => __async(this, null, function* () {
1026
+ let data = yield this.readFile();
1027
+ if (!data)
1028
+ data = {};
1029
+ data[name] = value;
1030
+ yield this.writeFile(data);
1031
+ })).catch((err) => {
1032
+ console.error("Error in setValue:", err);
1033
+ throw err;
1034
+ });
1035
+ yield this.fileAccessQueue.catch(() => {
1036
+ });
1037
+ });
935
1038
  }
936
1039
  /** Deletes a value from persistent storage */
937
- async deleteValue(name) {
938
- const data = await this.readFile();
939
- if (!data)
940
- return;
941
- delete data[name];
942
- await this.writeFile(data);
1040
+ deleteValue(name) {
1041
+ return __async(this, null, function* () {
1042
+ this.fileAccessQueue = this.fileAccessQueue.then(() => __async(this, null, function* () {
1043
+ const data = yield this.readFile();
1044
+ if (!data)
1045
+ return;
1046
+ delete data[name];
1047
+ yield this.writeFile(data);
1048
+ })).catch((err) => {
1049
+ console.error("Error in deleteValue:", err);
1050
+ throw err;
1051
+ });
1052
+ yield this.fileAccessQueue.catch(() => {
1053
+ });
1054
+ });
943
1055
  }
944
1056
  /** Deletes the file that contains the data of this DataStore. */
945
- async deleteStorage() {
946
- var _a;
947
- this.ensureDataStoreOptions();
948
- try {
949
- if (!fs)
950
- fs = (_a = await import("fs/promises")) == null ? void 0 : _a.default;
951
- if (!fs)
952
- throw new DatedError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new Error("'node:fs/promises' module not available") });
953
- const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
954
- await fs.unlink(path);
955
- } catch (err) {
956
- console.error("Error deleting file:", err);
957
- }
1057
+ deleteStorage() {
1058
+ return __async(this, null, function* () {
1059
+ var _a;
1060
+ this.ensureDataStoreOptions();
1061
+ try {
1062
+ if (!fs)
1063
+ fs = (_a = yield import("fs/promises")) == null ? void 0 : _a.default;
1064
+ if (!fs)
1065
+ throw new DatedError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new Error("'node:fs/promises' module not available") });
1066
+ const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
1067
+ yield fs.unlink(path);
1068
+ } catch (err) {
1069
+ console.error("Error deleting file:", err);
1070
+ }
1071
+ });
958
1072
  }
959
1073
  };
960
1074
 
961
1075
  // lib/DataStoreSerializer.ts
962
1076
  var DataStoreSerializer = class _DataStoreSerializer {
963
- stores;
964
- options;
965
1077
  constructor(stores, options = {}) {
1078
+ __publicField(this, "stores");
1079
+ __publicField(this, "options");
966
1080
  if (!crypto || !crypto.subtle)
967
1081
  throw new Error("DataStoreSerializer has to run in a secure context (HTTPS) or in another environment that implements the subtleCrypto API!");
968
1082
  this.stores = stores;
969
- this.options = {
1083
+ this.options = __spreadValues({
970
1084
  addChecksum: true,
971
- ensureIntegrity: true,
972
- ...options
973
- };
1085
+ ensureIntegrity: true
1086
+ }, options);
974
1087
  }
975
1088
  /** Calculates the checksum of a string */
976
- async calcChecksum(input) {
977
- return computeHash(input, "SHA-256");
1089
+ calcChecksum(input) {
1090
+ return __async(this, null, function* () {
1091
+ return computeHash(input, "SHA-256");
1092
+ });
978
1093
  }
979
1094
  /**
980
1095
  * Serializes only a subset of the data stores into a string.
@@ -982,62 +1097,70 @@ var DataStoreSerializer = class _DataStoreSerializer {
982
1097
  * @param useEncoding Whether to encode the data using each DataStore's `encodeData()` method
983
1098
  * @param stringified Whether to return the result as a string or as an array of `SerializedDataStore` objects
984
1099
  */
985
- async serializePartial(stores, useEncoding = true, stringified = true) {
986
- var _a;
987
- const serData = [];
988
- for (const storeInst of this.stores.filter((s) => typeof stores === "function" ? stores(s.id) : stores.includes(s.id))) {
989
- const encoded = Boolean(useEncoding && storeInst.encodingEnabled() && ((_a = storeInst.encodeData) == null ? void 0 : _a[1]));
990
- const data = encoded ? await storeInst.encodeData[1](JSON.stringify(storeInst.getData())) : JSON.stringify(storeInst.getData());
991
- serData.push({
992
- id: storeInst.id,
993
- data,
994
- formatVersion: storeInst.formatVersion,
995
- encoded,
996
- checksum: this.options.addChecksum ? await this.calcChecksum(data) : void 0
997
- });
998
- }
999
- return stringified ? JSON.stringify(serData) : serData;
1100
+ serializePartial(stores, useEncoding = true, stringified = true) {
1101
+ return __async(this, null, function* () {
1102
+ var _a;
1103
+ const serData = [];
1104
+ for (const storeInst of this.stores.filter((s) => typeof stores === "function" ? stores(s.id) : stores.includes(s.id))) {
1105
+ const encoded = Boolean(useEncoding && storeInst.encodingEnabled() && ((_a = storeInst.encodeData) == null ? void 0 : _a[1]));
1106
+ const data = encoded ? yield storeInst.encodeData[1](JSON.stringify(storeInst.getData())) : JSON.stringify(storeInst.getData());
1107
+ serData.push({
1108
+ id: storeInst.id,
1109
+ data,
1110
+ formatVersion: storeInst.formatVersion,
1111
+ encoded,
1112
+ checksum: this.options.addChecksum ? yield this.calcChecksum(data) : void 0
1113
+ });
1114
+ }
1115
+ return stringified ? JSON.stringify(serData) : serData;
1116
+ });
1000
1117
  }
1001
1118
  /**
1002
1119
  * Serializes the data stores into a string.
1003
1120
  * @param useEncoding Whether to encode the data using each DataStore's `encodeData()` method
1004
1121
  * @param stringified Whether to return the result as a string or as an array of `SerializedDataStore` objects
1005
1122
  */
1006
- async serialize(useEncoding = true, stringified = true) {
1007
- return this.serializePartial(this.stores.map((s) => s.id), useEncoding, stringified);
1123
+ serialize(useEncoding = true, stringified = true) {
1124
+ return __async(this, null, function* () {
1125
+ return this.serializePartial(this.stores.map((s) => s.id), useEncoding, stringified);
1126
+ });
1008
1127
  }
1009
1128
  /**
1010
1129
  * Deserializes the data exported via {@linkcode serialize()} and imports only a subset into the DataStore instances.
1011
1130
  * Also triggers the migration process if the data format has changed.
1012
1131
  */
1013
- async deserializePartial(stores, data) {
1014
- const deserStores = typeof data === "string" ? JSON.parse(data) : data;
1015
- if (!Array.isArray(deserStores) || !deserStores.every(_DataStoreSerializer.isSerializedDataStoreObj))
1016
- throw new TypeError("Invalid serialized data format! Expected an array of SerializedDataStore objects.");
1017
- for (const storeData of deserStores.filter((s) => typeof stores === "function" ? stores(s.id) : stores.includes(s.id))) {
1018
- const storeInst = this.stores.find((s) => s.id === storeData.id);
1019
- if (!storeInst)
1020
- throw new Error(`DataStore instance with ID "${storeData.id}" not found! Make sure to provide it in the DataStoreSerializer constructor.`);
1021
- if (this.options.ensureIntegrity && typeof storeData.checksum === "string") {
1022
- const checksum = await this.calcChecksum(storeData.data);
1023
- if (checksum !== storeData.checksum)
1024
- throw new ChecksumMismatchError(`Checksum mismatch for DataStore with ID "${storeData.id}"!
1132
+ deserializePartial(stores, data) {
1133
+ return __async(this, null, function* () {
1134
+ const deserStores = typeof data === "string" ? JSON.parse(data) : data;
1135
+ if (!Array.isArray(deserStores) || !deserStores.every(_DataStoreSerializer.isSerializedDataStoreObj))
1136
+ throw new TypeError("Invalid serialized data format! Expected an array of SerializedDataStore objects.");
1137
+ for (const storeData of deserStores.filter((s) => typeof stores === "function" ? stores(s.id) : stores.includes(s.id))) {
1138
+ const storeInst = this.stores.find((s) => s.id === storeData.id);
1139
+ if (!storeInst)
1140
+ throw new Error(`DataStore instance with ID "${storeData.id}" not found! Make sure to provide it in the DataStoreSerializer constructor.`);
1141
+ if (this.options.ensureIntegrity && typeof storeData.checksum === "string") {
1142
+ const checksum = yield this.calcChecksum(storeData.data);
1143
+ if (checksum !== storeData.checksum)
1144
+ throw new ChecksumMismatchError(`Checksum mismatch for DataStore with ID "${storeData.id}"!
1025
1145
  Expected: ${storeData.checksum}
1026
1146
  Has: ${checksum}`);
1147
+ }
1148
+ const decodedData = storeData.encoded && storeInst.encodingEnabled() ? yield storeInst.decodeData[1](storeData.data) : storeData.data;
1149
+ if (storeData.formatVersion && !isNaN(Number(storeData.formatVersion)) && Number(storeData.formatVersion) < storeInst.formatVersion)
1150
+ yield storeInst.runMigrations(JSON.parse(decodedData), Number(storeData.formatVersion), false);
1151
+ else
1152
+ yield storeInst.setData(JSON.parse(decodedData));
1027
1153
  }
1028
- const decodedData = storeData.encoded && storeInst.encodingEnabled() ? await storeInst.decodeData[1](storeData.data) : storeData.data;
1029
- if (storeData.formatVersion && !isNaN(Number(storeData.formatVersion)) && Number(storeData.formatVersion) < storeInst.formatVersion)
1030
- await storeInst.runMigrations(JSON.parse(decodedData), Number(storeData.formatVersion), false);
1031
- else
1032
- await storeInst.setData(JSON.parse(decodedData));
1033
- }
1154
+ });
1034
1155
  }
1035
1156
  /**
1036
1157
  * Deserializes the data exported via {@linkcode serialize()} and imports the data into all matching DataStore instances.
1037
1158
  * Also triggers the migration process if the data format has changed.
1038
1159
  */
1039
- async deserialize(data) {
1040
- return this.deserializePartial(this.stores.map((s) => s.id), data);
1160
+ deserialize(data) {
1161
+ return __async(this, null, function* () {
1162
+ return this.deserializePartial(this.stores.map((s) => s.id), data);
1163
+ });
1041
1164
  }
1042
1165
  /**
1043
1166
  * Loads the persistent data of the DataStore instances into the in-memory cache.
@@ -1045,32 +1168,40 @@ Has: ${checksum}`);
1045
1168
  * @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
1046
1169
  * @returns Returns a PromiseSettledResult array with the results of each DataStore instance in the format `{ id: string, data: object }`
1047
1170
  */
1048
- async loadStoresData(stores) {
1049
- return Promise.allSettled(
1050
- this.getStoresFiltered(stores).map(async (store) => ({
1051
- id: store.id,
1052
- data: await store.loadData()
1053
- }))
1054
- );
1171
+ loadStoresData(stores) {
1172
+ return __async(this, null, function* () {
1173
+ return Promise.allSettled(
1174
+ this.getStoresFiltered(stores).map((store) => __async(this, null, function* () {
1175
+ return {
1176
+ id: store.id,
1177
+ data: yield store.loadData()
1178
+ };
1179
+ }))
1180
+ );
1181
+ });
1055
1182
  }
1056
1183
  /**
1057
1184
  * Resets the persistent and in-memory data of the DataStore instances to their default values.
1058
1185
  * @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
1059
1186
  */
1060
- async resetStoresData(stores) {
1061
- return Promise.allSettled(
1062
- this.getStoresFiltered(stores).map((store) => store.saveDefaultData())
1063
- );
1187
+ resetStoresData(stores) {
1188
+ return __async(this, null, function* () {
1189
+ return Promise.allSettled(
1190
+ this.getStoresFiltered(stores).map((store) => store.saveDefaultData())
1191
+ );
1192
+ });
1064
1193
  }
1065
1194
  /**
1066
1195
  * Deletes the persistent data of the DataStore instances.
1067
1196
  * Leaves the in-memory data untouched.
1068
1197
  * @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
1069
1198
  */
1070
- async deleteStoresData(stores) {
1071
- return Promise.allSettled(
1072
- this.getStoresFiltered(stores).map((store) => store.deleteData())
1073
- );
1199
+ deleteStoresData(stores) {
1200
+ return __async(this, null, function* () {
1201
+ return Promise.allSettled(
1202
+ this.getStoresFiltered(stores).map((store) => store.deleteData())
1203
+ );
1204
+ });
1074
1205
  }
1075
1206
  /** Checks if a given value is an array of SerializedDataStore objects */
1076
1207
  static isSerializedDataStoreObjArray(obj) {
@@ -1095,26 +1226,26 @@ var createNanoEvents = () => ({
1095
1226
  },
1096
1227
  events: {},
1097
1228
  on(event, cb) {
1229
+ var _a;
1098
1230
  ;
1099
- (this.events[event] ||= []).push(cb);
1231
+ ((_a = this.events)[event] || (_a[event] = [])).push(cb);
1100
1232
  return () => {
1101
- var _a;
1102
- this.events[event] = (_a = this.events[event]) == null ? void 0 : _a.filter((i) => cb !== i);
1233
+ var _a2;
1234
+ this.events[event] = (_a2 = this.events[event]) == null ? void 0 : _a2.filter((i) => cb !== i);
1103
1235
  };
1104
1236
  }
1105
1237
  });
1106
1238
 
1107
1239
  // lib/NanoEmitter.ts
1108
1240
  var NanoEmitter = class {
1109
- events = createNanoEvents();
1110
- eventUnsubscribes = [];
1111
- emitterOptions;
1112
1241
  /** Creates a new instance of NanoEmitter - a lightweight event emitter with helper methods and a strongly typed event map */
1113
1242
  constructor(options = {}) {
1114
- this.emitterOptions = {
1115
- publicEmit: false,
1116
- ...options
1117
- };
1243
+ __publicField(this, "events", createNanoEvents());
1244
+ __publicField(this, "eventUnsubscribes", []);
1245
+ __publicField(this, "emitterOptions");
1246
+ this.emitterOptions = __spreadValues({
1247
+ publicEmit: false
1248
+ }, options);
1118
1249
  }
1119
1250
  //#region on
1120
1251
  /**
@@ -1172,11 +1303,11 @@ var NanoEmitter = class {
1172
1303
  once(event, cb) {
1173
1304
  return new Promise((resolve) => {
1174
1305
  let unsub;
1175
- const onceProxy = (...args) => {
1306
+ const onceProxy = ((...args) => {
1176
1307
  cb == null ? void 0 : cb(...args);
1177
1308
  unsub == null ? void 0 : unsub();
1178
1309
  resolve(args);
1179
- };
1310
+ });
1180
1311
  unsub = this.events.on(event, onceProxy);
1181
1312
  this.eventUnsubscribes.push(unsub);
1182
1313
  });
@@ -1205,12 +1336,11 @@ var NanoEmitter = class {
1205
1336
  this.eventUnsubscribes = this.eventUnsubscribes.filter((u) => !allUnsubs.includes(u));
1206
1337
  };
1207
1338
  for (const opts of Array.isArray(options) ? options : [options]) {
1208
- const optsWithDefaults = {
1339
+ const optsWithDefaults = __spreadValues({
1209
1340
  allOf: [],
1210
1341
  oneOf: [],
1211
- once: false,
1212
- ...opts
1213
- };
1342
+ once: false
1343
+ }, opts);
1214
1344
  const {
1215
1345
  oneOf,
1216
1346
  allOf,
@@ -1230,12 +1360,12 @@ var NanoEmitter = class {
1230
1360
  this.eventUnsubscribes = this.eventUnsubscribes.filter((u) => !curEvtUnsubs.includes(u));
1231
1361
  };
1232
1362
  for (const event of oneOf) {
1233
- const unsub = this.events.on(event, (...args) => {
1363
+ const unsub = this.events.on(event, ((...args) => {
1234
1364
  checkUnsubAllEvt();
1235
1365
  callback(event, ...args);
1236
1366
  if (once)
1237
1367
  checkUnsubAllEvt(true);
1238
- });
1368
+ }));
1239
1369
  curEvtUnsubs.push(unsub);
1240
1370
  }
1241
1371
  const allOfEmitted = /* @__PURE__ */ new Set();
@@ -1249,10 +1379,10 @@ var NanoEmitter = class {
1249
1379
  }
1250
1380
  };
1251
1381
  for (const event of allOf) {
1252
- const unsub = this.events.on(event, (...args) => {
1382
+ const unsub = this.events.on(event, ((...args) => {
1253
1383
  checkUnsubAllEvt();
1254
1384
  checkAllOf(event, ...args);
1255
- });
1385
+ }));
1256
1386
  curEvtUnsubs.push(unsub);
1257
1387
  }
1258
1388
  if (oneOf.length === 0 && allOf.length === 0)
@@ -1296,13 +1426,13 @@ var Debouncer = class extends NanoEmitter {
1296
1426
  super();
1297
1427
  this.timeout = timeout;
1298
1428
  this.type = type;
1429
+ /** All registered listener functions and the time they were attached */
1430
+ __publicField(this, "listeners", []);
1431
+ /** The currently active timeout */
1432
+ __publicField(this, "activeTimeout");
1433
+ /** The latest queued call */
1434
+ __publicField(this, "queuedCall");
1299
1435
  }
1300
- /** All registered listener functions and the time they were attached */
1301
- listeners = [];
1302
- /** The currently active timeout */
1303
- activeTimeout;
1304
- /** The latest queued call */
1305
- queuedCall;
1306
1436
  //#region listeners
1307
1437
  /** Adds a listener function that will be called on timeout */
1308
1438
  addListener(fn) {
@@ -1384,11 +1514,13 @@ var Debouncer = class extends NanoEmitter {
1384
1514
  function debounce(fn, timeout = 200, type = "immediate") {
1385
1515
  const debouncer = new Debouncer(timeout, type);
1386
1516
  debouncer.addListener(fn);
1387
- const func = (...args) => debouncer.call(...args);
1517
+ const func = ((...args) => debouncer.call(...args));
1388
1518
  func.debouncer = debouncer;
1389
1519
  return func;
1390
1520
  }
1391
1521
 
1522
+ if(__exports != exports)module.exports = exports;return module.exports}));
1523
+
1392
1524
 
1393
1525
 
1394
1526
  if (typeof module.exports == "object" && typeof exports == "object") {