@sv443-network/coreutils 2.0.3 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +32 -0
- package/README.md +4 -3
- package/dist/CoreUtils.cjs +168 -103
- package/dist/CoreUtils.min.cjs +5 -3
- package/dist/CoreUtils.min.mjs +5 -3
- package/dist/CoreUtils.min.umd.js +5 -3
- package/dist/CoreUtils.mjs +168 -103
- package/dist/CoreUtils.umd.js +174 -107
- package/dist/lib/DataStore.d.ts +21 -7
- package/dist/lib/DataStoreEngine.d.ts +8 -8
- package/dist/lib/DataStoreSerializer.d.ts +2 -0
- package/dist/lib/Errors.d.ts +15 -3
- package/dist/lib/NanoEmitter.d.ts +6 -5
- package/dist/lib/math.d.ts +1 -1
- package/dist/lib/misc.d.ts +6 -0
- package/dist/lib/{TestDataStore.d.ts → test/DirectAccessDataStore.d.ts} +4 -3
- package/dist/lib/test/softExpect.d.ts +11 -0
- package/dist/lib/types.d.ts +7 -0
- package/package.json +1 -1
package/dist/CoreUtils.mjs
CHANGED
|
@@ -87,7 +87,7 @@ function roundFixed(num, fractionDigits) {
|
|
|
87
87
|
const scale = 10 ** fractionDigits;
|
|
88
88
|
return Math.round(num * scale) / scale;
|
|
89
89
|
}
|
|
90
|
-
function valsWithin(a, b, dec =
|
|
90
|
+
function valsWithin(a, b, dec = 1, withinRange = 0.5) {
|
|
91
91
|
return Math.abs(roundFixed(a, dec) - roundFixed(b, dec)) <= withinRange;
|
|
92
92
|
}
|
|
93
93
|
|
|
@@ -237,6 +237,52 @@ function randomId(length = 16, radix = 16, enhancedEntropy = false, randomCase =
|
|
|
237
237
|
return arr.map((v) => caseArr[randRange(0, caseArr.length - 1, enhancedEntropy)] === 1 ? v.toUpperCase() : v).join("");
|
|
238
238
|
}
|
|
239
239
|
|
|
240
|
+
// lib/Errors.ts
|
|
241
|
+
var DatedError = class extends Error {
|
|
242
|
+
date;
|
|
243
|
+
constructor(message, options) {
|
|
244
|
+
super(message, options);
|
|
245
|
+
this.name = this.constructor.name;
|
|
246
|
+
this.date = /* @__PURE__ */ new Date();
|
|
247
|
+
}
|
|
248
|
+
};
|
|
249
|
+
var ChecksumMismatchError = class extends DatedError {
|
|
250
|
+
constructor(message, options) {
|
|
251
|
+
super(message, options);
|
|
252
|
+
this.name = "ChecksumMismatchError";
|
|
253
|
+
}
|
|
254
|
+
};
|
|
255
|
+
var CustomError = class extends DatedError {
|
|
256
|
+
constructor(name, message, options) {
|
|
257
|
+
super(message, options);
|
|
258
|
+
this.name = name;
|
|
259
|
+
}
|
|
260
|
+
};
|
|
261
|
+
var MigrationError = class extends DatedError {
|
|
262
|
+
constructor(message, options) {
|
|
263
|
+
super(message, options);
|
|
264
|
+
this.name = "MigrationError";
|
|
265
|
+
}
|
|
266
|
+
};
|
|
267
|
+
var ValidationError = class extends DatedError {
|
|
268
|
+
constructor(message, options) {
|
|
269
|
+
super(message, options);
|
|
270
|
+
this.name = "ValidationError";
|
|
271
|
+
}
|
|
272
|
+
};
|
|
273
|
+
var ScriptContextError = class extends DatedError {
|
|
274
|
+
constructor(message, options) {
|
|
275
|
+
super(message, options);
|
|
276
|
+
this.name = "ScriptContextError";
|
|
277
|
+
}
|
|
278
|
+
};
|
|
279
|
+
var NetworkError = class extends DatedError {
|
|
280
|
+
constructor(message, options) {
|
|
281
|
+
super(message, options);
|
|
282
|
+
this.name = "NetworkError";
|
|
283
|
+
}
|
|
284
|
+
};
|
|
285
|
+
|
|
240
286
|
// lib/misc.ts
|
|
241
287
|
async function consumeGen(valGen) {
|
|
242
288
|
return await (typeof valGen === "function" ? valGen() : valGen);
|
|
@@ -265,7 +311,7 @@ async function fetchAdvanced(input, options = {}) {
|
|
|
265
311
|
return res;
|
|
266
312
|
} catch (err) {
|
|
267
313
|
typeof id !== "undefined" && clearTimeout(id);
|
|
268
|
-
throw new
|
|
314
|
+
throw new NetworkError("Error while calling fetch", { cause: err });
|
|
269
315
|
}
|
|
270
316
|
}
|
|
271
317
|
function getListLength(listLike, zeroOnInvalid = true) {
|
|
@@ -276,7 +322,7 @@ function pauseFor(time, signal, rejectOnAbort = false) {
|
|
|
276
322
|
const timeout = setTimeout(() => res(), time);
|
|
277
323
|
signal == null ? void 0 : signal.addEventListener("abort", () => {
|
|
278
324
|
clearTimeout(timeout);
|
|
279
|
-
rejectOnAbort ? rej(new
|
|
325
|
+
rejectOnAbort ? rej(new CustomError("AbortError", "The pause was aborted")) : res();
|
|
280
326
|
});
|
|
281
327
|
});
|
|
282
328
|
}
|
|
@@ -311,14 +357,24 @@ function scheduleExit(code = 0, timeout = 0) {
|
|
|
311
357
|
if (timeout < 0)
|
|
312
358
|
throw new TypeError("Timeout must be a non-negative number");
|
|
313
359
|
let exit;
|
|
314
|
-
if (typeof process !== "undefined" && "exit" in process)
|
|
360
|
+
if (typeof process !== "undefined" && "exit" in process && typeof process.exit === "function")
|
|
315
361
|
exit = () => process.exit(code);
|
|
316
|
-
else if (typeof Deno !== "undefined" && "exit" in Deno)
|
|
362
|
+
else if (typeof Deno !== "undefined" && "exit" in Deno && typeof Deno.exit === "function")
|
|
317
363
|
exit = () => Deno.exit(code);
|
|
318
364
|
else
|
|
319
|
-
throw new
|
|
365
|
+
throw new ScriptContextError("Cannot exit the process, no exit method available");
|
|
320
366
|
setTimeout(exit, timeout);
|
|
321
367
|
}
|
|
368
|
+
function getCallStack(asArray, lines = Infinity) {
|
|
369
|
+
if (typeof lines !== "number" || isNaN(lines) || lines < 0)
|
|
370
|
+
throw new TypeError("lines parameter must be a non-negative number");
|
|
371
|
+
try {
|
|
372
|
+
throw new Error("This is to capture a stack trace with CoreUtils.getCallStack(). (If you see this somewhere, you can safely ignore it.)");
|
|
373
|
+
} catch (err) {
|
|
374
|
+
const stack = (err.stack ?? "").split("\n").map((line) => line.trim()).slice(2, lines + 2);
|
|
375
|
+
return asArray !== false ? stack : stack.join("\n");
|
|
376
|
+
}
|
|
377
|
+
}
|
|
322
378
|
|
|
323
379
|
// lib/text.ts
|
|
324
380
|
function autoPlural(term, num, pluralType = "auto") {
|
|
@@ -388,16 +444,18 @@ function joinArrayReadable(array, separators = ", ", lastSeparator = " and ") {
|
|
|
388
444
|
return arr.join(separators) + lastItm;
|
|
389
445
|
}
|
|
390
446
|
function secsToTimeStr(seconds) {
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
const
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
447
|
+
const isNegative = seconds < 0;
|
|
448
|
+
const s = Math.abs(seconds);
|
|
449
|
+
if (isNaN(s) || !isFinite(s))
|
|
450
|
+
throw new TypeError("The seconds argument must be a valid number");
|
|
451
|
+
const hrs = Math.floor(s / 3600);
|
|
452
|
+
const mins = Math.floor(s % 3600 / 60);
|
|
453
|
+
const secs = Math.floor(s % 60);
|
|
454
|
+
return (isNegative ? "-" : "") + [
|
|
455
|
+
hrs ? hrs + ":" : "",
|
|
456
|
+
String(mins).padStart(mins > 0 || hrs > 0 ? 2 : 1, "0"),
|
|
399
457
|
":",
|
|
400
|
-
String(secs).padStart(secs > 0 ||
|
|
458
|
+
String(secs).padStart(secs > 0 || mins > 0 || hrs > 0 || seconds === 0 ? 2 : 1, "0")
|
|
401
459
|
].join("");
|
|
402
460
|
}
|
|
403
461
|
function truncStr(input, length, endStr = "...") {
|
|
@@ -406,34 +464,6 @@ function truncStr(input, length, endStr = "...") {
|
|
|
406
464
|
return finalStr.length > length ? finalStr.substring(0, length) : finalStr;
|
|
407
465
|
}
|
|
408
466
|
|
|
409
|
-
// lib/Errors.ts
|
|
410
|
-
var DatedError = class extends Error {
|
|
411
|
-
date;
|
|
412
|
-
constructor(message, options) {
|
|
413
|
-
super(message, options);
|
|
414
|
-
this.name = this.constructor.name;
|
|
415
|
-
this.date = /* @__PURE__ */ new Date();
|
|
416
|
-
}
|
|
417
|
-
};
|
|
418
|
-
var ChecksumMismatchError = class extends DatedError {
|
|
419
|
-
constructor(message, options) {
|
|
420
|
-
super(message, options);
|
|
421
|
-
this.name = "ChecksumMismatchError";
|
|
422
|
-
}
|
|
423
|
-
};
|
|
424
|
-
var MigrationError = class extends DatedError {
|
|
425
|
-
constructor(message, options) {
|
|
426
|
-
super(message, options);
|
|
427
|
-
this.name = "MigrationError";
|
|
428
|
-
}
|
|
429
|
-
};
|
|
430
|
-
var ValidationError = class extends DatedError {
|
|
431
|
-
constructor(message, options) {
|
|
432
|
-
super(message, options);
|
|
433
|
-
this.name = "ValidationError";
|
|
434
|
-
}
|
|
435
|
-
};
|
|
436
|
-
|
|
437
467
|
// lib/DataStore.ts
|
|
438
468
|
var dsFmtVer = 1;
|
|
439
469
|
var DataStore = class {
|
|
@@ -443,6 +473,7 @@ var DataStore = class {
|
|
|
443
473
|
encodeData;
|
|
444
474
|
decodeData;
|
|
445
475
|
compressionFormat = "deflate-raw";
|
|
476
|
+
memoryCache = true;
|
|
446
477
|
engine;
|
|
447
478
|
options;
|
|
448
479
|
/**
|
|
@@ -455,6 +486,7 @@ var DataStore = class {
|
|
|
455
486
|
cachedData;
|
|
456
487
|
migrations;
|
|
457
488
|
migrateIds = [];
|
|
489
|
+
//#region constructor
|
|
458
490
|
/**
|
|
459
491
|
* Creates an instance of DataStore to manage a sync & async database that is cached in memory and persistently saved across sessions.
|
|
460
492
|
* Supports migrating data from older versions to newer ones and populating the cache with default data if no persistent data is found.
|
|
@@ -469,7 +501,8 @@ var DataStore = class {
|
|
|
469
501
|
this.id = opts.id;
|
|
470
502
|
this.formatVersion = opts.formatVersion;
|
|
471
503
|
this.defaultData = opts.defaultData;
|
|
472
|
-
this.
|
|
504
|
+
this.memoryCache = Boolean(opts.memoryCache ?? true);
|
|
505
|
+
this.cachedData = this.memoryCache ? opts.defaultData : {};
|
|
473
506
|
this.migrations = opts.migrations;
|
|
474
507
|
if (opts.migrateIds)
|
|
475
508
|
this.migrateIds = Array.isArray(opts.migrateIds) ? opts.migrateIds : [opts.migrateIds];
|
|
@@ -494,7 +527,7 @@ var DataStore = class {
|
|
|
494
527
|
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.");
|
|
495
528
|
this.engine.setDataStoreOptions(opts);
|
|
496
529
|
}
|
|
497
|
-
//#region
|
|
530
|
+
//#region loadData
|
|
498
531
|
/**
|
|
499
532
|
* Loads the data saved in persistent storage into the in-memory cache and also returns a copy of it.
|
|
500
533
|
* Automatically populates persistent storage with default data if it doesn't contain any data yet.
|
|
@@ -505,28 +538,28 @@ var DataStore = class {
|
|
|
505
538
|
if (this.firstInit) {
|
|
506
539
|
this.firstInit = false;
|
|
507
540
|
const dsVer = Number(await this.engine.getValue("__ds_fmt_ver", 0));
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
promises.push(this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat));
|
|
526
|
-
await Promise.allSettled(promises);
|
|
541
|
+
const oldData = await this.engine.getValue(`_uucfg-${this.id}`, null);
|
|
542
|
+
if (oldData) {
|
|
543
|
+
const oldVer = Number(await this.engine.getValue(`_uucfgver-${this.id}`, NaN));
|
|
544
|
+
const oldEnc = await this.engine.getValue(`_uucfgenc-${this.id}`, null);
|
|
545
|
+
const promises = [];
|
|
546
|
+
const migrateFmt = (oldKey, newKey, value) => {
|
|
547
|
+
promises.push(this.engine.setValue(newKey, value));
|
|
548
|
+
promises.push(this.engine.deleteValue(oldKey));
|
|
549
|
+
};
|
|
550
|
+
migrateFmt(`_uucfg-${this.id}`, `__ds-${this.id}-dat`, oldData);
|
|
551
|
+
if (!isNaN(oldVer))
|
|
552
|
+
migrateFmt(`_uucfgver-${this.id}`, `__ds-${this.id}-ver`, oldVer);
|
|
553
|
+
if (typeof oldEnc === "boolean")
|
|
554
|
+
migrateFmt(`_uucfgenc-${this.id}`, `__ds-${this.id}-enf`, oldEnc === true ? this.compressionFormat ?? null : null);
|
|
555
|
+
else {
|
|
556
|
+
promises.push(this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat));
|
|
557
|
+
promises.push(this.engine.deleteValue(`_uucfgenc-${this.id}`));
|
|
527
558
|
}
|
|
528
|
-
await
|
|
559
|
+
await Promise.allSettled(promises);
|
|
529
560
|
}
|
|
561
|
+
if (isNaN(dsVer) || dsVer < dsFmtVer)
|
|
562
|
+
await this.engine.setValue("__ds_fmt_ver", dsFmtVer);
|
|
530
563
|
}
|
|
531
564
|
if (this.migrateIds.length > 0) {
|
|
532
565
|
await this.migrateId(this.migrateIds);
|
|
@@ -536,7 +569,7 @@ var DataStore = class {
|
|
|
536
569
|
let storedFmtVer = Number(await this.engine.getValue(`__ds-${this.id}-ver`, NaN));
|
|
537
570
|
if (typeof storedDataRaw !== "string") {
|
|
538
571
|
await this.saveDefaultData();
|
|
539
|
-
return
|
|
572
|
+
return this.engine.deepCopy(this.defaultData);
|
|
540
573
|
}
|
|
541
574
|
const storedData = storedDataRaw ?? JSON.stringify(this.defaultData);
|
|
542
575
|
const encodingFmt = String(await this.engine.getValue(`__ds-${this.id}-enf`, null));
|
|
@@ -551,23 +584,32 @@ var DataStore = class {
|
|
|
551
584
|
parsed = await this.runMigrations(parsed, storedFmtVer);
|
|
552
585
|
if (saveData)
|
|
553
586
|
await this.setData(parsed);
|
|
554
|
-
|
|
587
|
+
if (this.memoryCache)
|
|
588
|
+
return this.cachedData = this.engine.deepCopy(parsed);
|
|
589
|
+
else
|
|
590
|
+
return this.engine.deepCopy(parsed);
|
|
555
591
|
} catch (err) {
|
|
556
592
|
console.warn("Error while parsing JSON data, resetting it to the default value.", err);
|
|
557
593
|
await this.saveDefaultData();
|
|
558
594
|
return this.defaultData;
|
|
559
595
|
}
|
|
560
596
|
}
|
|
597
|
+
//#region getData
|
|
561
598
|
/**
|
|
562
599
|
* Returns a copy of the data from the in-memory cache.
|
|
563
|
-
* Use {@linkcode loadData()} to get fresh data from persistent storage (usually not necessary since the cache should always exactly reflect persistent storage).
|
|
600
|
+
* Use {@linkcode loadData()} to get fresh data from persistent storage (usually not necessary since the cache should always exactly reflect persistent storage).
|
|
601
|
+
* ⚠️ If `memoryCache` was set to `false` in the constructor options, this method will throw an error.
|
|
564
602
|
*/
|
|
565
603
|
getData() {
|
|
604
|
+
if (!this.memoryCache)
|
|
605
|
+
throw new DatedError("In-memory cache is disabled for this DataStore instance, so getData() can't be used. Please use loadData() instead.");
|
|
566
606
|
return this.engine.deepCopy(this.cachedData);
|
|
567
607
|
}
|
|
608
|
+
//#region setData
|
|
568
609
|
/** Saves the data synchronously to the in-memory cache and asynchronously to the persistent storage */
|
|
569
610
|
setData(data) {
|
|
570
|
-
this.
|
|
611
|
+
if (this.memoryCache)
|
|
612
|
+
this.cachedData = data;
|
|
571
613
|
return new Promise(async (resolve) => {
|
|
572
614
|
await Promise.allSettled([
|
|
573
615
|
this.engine.setValue(`__ds-${this.id}-dat`, await this.engine.serializeData(data, this.encodingEnabled())),
|
|
@@ -577,15 +619,18 @@ var DataStore = class {
|
|
|
577
619
|
resolve();
|
|
578
620
|
});
|
|
579
621
|
}
|
|
622
|
+
//#region saveDefaultData
|
|
580
623
|
/** Saves the default data passed in the constructor synchronously to the in-memory cache and asynchronously to persistent storage */
|
|
581
624
|
async saveDefaultData() {
|
|
582
|
-
|
|
625
|
+
if (this.memoryCache)
|
|
626
|
+
this.cachedData = this.defaultData;
|
|
583
627
|
await Promise.allSettled([
|
|
584
628
|
this.engine.setValue(`__ds-${this.id}-dat`, await this.engine.serializeData(this.defaultData, this.encodingEnabled())),
|
|
585
629
|
this.engine.setValue(`__ds-${this.id}-ver`, this.formatVersion),
|
|
586
630
|
this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat)
|
|
587
631
|
]);
|
|
588
632
|
}
|
|
633
|
+
//#region deleteData
|
|
589
634
|
/**
|
|
590
635
|
* Call this method to clear all persistently stored data associated with this DataStore instance, including the storage container (if supported by the DataStoreEngine).
|
|
591
636
|
* The in-memory cache will be left untouched, so you may still access the data with {@linkcode getData()}
|
|
@@ -600,11 +645,12 @@ var DataStore = class {
|
|
|
600
645
|
]);
|
|
601
646
|
await ((_b = (_a = this.engine).deleteStorage) == null ? void 0 : _b.call(_a));
|
|
602
647
|
}
|
|
648
|
+
//#region encodingEnabled
|
|
603
649
|
/** Returns whether encoding and decoding are enabled for this DataStore instance */
|
|
604
650
|
encodingEnabled() {
|
|
605
651
|
return Boolean(this.encodeData && this.decodeData) && this.compressionFormat !== null || Boolean(this.compressionFormat);
|
|
606
652
|
}
|
|
607
|
-
//#region
|
|
653
|
+
//#region runMigrations
|
|
608
654
|
/**
|
|
609
655
|
* Runs all necessary migration functions consecutively and saves the result to the in-memory cache and persistent storage and also returns it.
|
|
610
656
|
* This method is automatically called by {@linkcode loadData()} if the data format has changed since the last time the data was saved.
|
|
@@ -638,8 +684,12 @@ var DataStore = class {
|
|
|
638
684
|
this.engine.setValue(`__ds-${this.id}-ver`, lastFmtVer),
|
|
639
685
|
this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat)
|
|
640
686
|
]);
|
|
641
|
-
|
|
687
|
+
if (this.memoryCache)
|
|
688
|
+
return this.cachedData = this.engine.deepCopy(newData);
|
|
689
|
+
else
|
|
690
|
+
return this.engine.deepCopy(newData);
|
|
642
691
|
}
|
|
692
|
+
//#region migrateId
|
|
643
693
|
/**
|
|
644
694
|
* Tries to migrate the currently saved persistent data from one or more old IDs to the ID set in the constructor.
|
|
645
695
|
* 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.
|
|
@@ -683,7 +733,7 @@ var DataStoreEngine = class {
|
|
|
683
733
|
this.dataStoreOptions = dataStoreOptions;
|
|
684
734
|
}
|
|
685
735
|
//#region serialization api
|
|
686
|
-
/** Serializes the given object to a string, optionally encoded with `options.encodeData` if {@linkcode useEncoding} is set to
|
|
736
|
+
/** 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 */
|
|
687
737
|
async serializeData(data, useEncoding) {
|
|
688
738
|
var _a, _b, _c, _d, _e;
|
|
689
739
|
this.ensureDataStoreOptions();
|
|
@@ -731,7 +781,7 @@ var BrowserStorageEngine = class extends DataStoreEngine {
|
|
|
731
781
|
* Creates an instance of `BrowserStorageEngine`.
|
|
732
782
|
*
|
|
733
783
|
* - ⚠️ Requires a DOM environment
|
|
734
|
-
* - ⚠️ Don't reuse
|
|
784
|
+
* - ⚠️ Don't reuse engine instances, always create a new one for each {@linkcode DataStore} instance
|
|
735
785
|
*/
|
|
736
786
|
constructor(options) {
|
|
737
787
|
super(options == null ? void 0 : options.dataStoreOptions);
|
|
@@ -769,7 +819,7 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
769
819
|
* Creates an instance of `FileStorageEngine`.
|
|
770
820
|
*
|
|
771
821
|
* - ⚠️ Requires Node.js or Deno with Node compatibility (v1.31+)
|
|
772
|
-
* - ⚠️ Don't reuse
|
|
822
|
+
* - ⚠️ Don't reuse engine instances, always create a new one for each {@linkcode DataStore} instance
|
|
773
823
|
*/
|
|
774
824
|
constructor(options) {
|
|
775
825
|
super(options == null ? void 0 : options.dataStoreOptions);
|
|
@@ -787,7 +837,7 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
787
837
|
if (!fs)
|
|
788
838
|
fs = (_a = await import("fs/promises")) == null ? void 0 : _a.default;
|
|
789
839
|
if (!fs)
|
|
790
|
-
throw new
|
|
840
|
+
throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
|
|
791
841
|
const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
|
|
792
842
|
const data = await fs.readFile(path, "utf-8");
|
|
793
843
|
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;
|
|
@@ -803,7 +853,7 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
803
853
|
if (!fs)
|
|
804
854
|
fs = (_a = await import("fs/promises")) == null ? void 0 : _a.default;
|
|
805
855
|
if (!fs)
|
|
806
|
-
throw new
|
|
856
|
+
throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
|
|
807
857
|
const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
|
|
808
858
|
await fs.mkdir(path.slice(0, path.lastIndexOf(path.includes("/") ? "/" : "\\")), { recursive: true });
|
|
809
859
|
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");
|
|
@@ -862,9 +912,9 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
862
912
|
if (!fs)
|
|
863
913
|
fs = (_a = await import("fs/promises")) == null ? void 0 : _a.default;
|
|
864
914
|
if (!fs)
|
|
865
|
-
throw new
|
|
915
|
+
throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
|
|
866
916
|
const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
|
|
867
|
-
await fs.unlink(path);
|
|
917
|
+
return await fs.unlink(path);
|
|
868
918
|
} catch (err) {
|
|
869
919
|
console.error("Error deleting file:", err);
|
|
870
920
|
}
|
|
@@ -877,11 +927,12 @@ var DataStoreSerializer = class _DataStoreSerializer {
|
|
|
877
927
|
options;
|
|
878
928
|
constructor(stores, options = {}) {
|
|
879
929
|
if (!crypto || !crypto.subtle)
|
|
880
|
-
throw new
|
|
930
|
+
throw new ScriptContextError("DataStoreSerializer has to run in a secure context (HTTPS) or in another environment that implements the subtleCrypto API!");
|
|
881
931
|
this.stores = stores;
|
|
882
932
|
this.options = {
|
|
883
933
|
addChecksum: true,
|
|
884
934
|
ensureIntegrity: true,
|
|
935
|
+
remapIds: {},
|
|
885
936
|
...options
|
|
886
937
|
};
|
|
887
938
|
}
|
|
@@ -898,9 +949,11 @@ var DataStoreSerializer = class _DataStoreSerializer {
|
|
|
898
949
|
async serializePartial(stores, useEncoding = true, stringified = true) {
|
|
899
950
|
var _a;
|
|
900
951
|
const serData = [];
|
|
901
|
-
|
|
952
|
+
const filteredStores = this.stores.filter((s) => typeof stores === "function" ? stores(s.id) : stores.includes(s.id));
|
|
953
|
+
for (const storeInst of filteredStores) {
|
|
902
954
|
const encoded = Boolean(useEncoding && storeInst.encodingEnabled() && ((_a = storeInst.encodeData) == null ? void 0 : _a[1]));
|
|
903
|
-
const
|
|
955
|
+
const rawData = storeInst.memoryCache ? storeInst.getData() : await storeInst.loadData();
|
|
956
|
+
const data = encoded ? await storeInst.encodeData[1](JSON.stringify(rawData)) : JSON.stringify(rawData);
|
|
904
957
|
serData.push({
|
|
905
958
|
id: storeInst.id,
|
|
906
959
|
data,
|
|
@@ -927,10 +980,18 @@ var DataStoreSerializer = class _DataStoreSerializer {
|
|
|
927
980
|
const deserStores = typeof data === "string" ? JSON.parse(data) : data;
|
|
928
981
|
if (!Array.isArray(deserStores) || !deserStores.every(_DataStoreSerializer.isSerializedDataStoreObj))
|
|
929
982
|
throw new TypeError("Invalid serialized data format! Expected an array of SerializedDataStore objects.");
|
|
930
|
-
|
|
931
|
-
|
|
983
|
+
const resolveStoreId = (id) => {
|
|
984
|
+
var _a;
|
|
985
|
+
return ((_a = Object.entries(this.options.remapIds).find(([, v]) => v.includes(id))) == null ? void 0 : _a[0]) ?? id;
|
|
986
|
+
};
|
|
987
|
+
const matchesFilter = (id) => typeof stores === "function" ? stores(id) : stores.includes(id);
|
|
988
|
+
for (const storeData of deserStores) {
|
|
989
|
+
const effectiveId = resolveStoreId(storeData.id);
|
|
990
|
+
if (!matchesFilter(effectiveId))
|
|
991
|
+
continue;
|
|
992
|
+
const storeInst = this.stores.find((s) => s.id === effectiveId);
|
|
932
993
|
if (!storeInst)
|
|
933
|
-
throw new
|
|
994
|
+
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.`);
|
|
934
995
|
if (this.options.ensureIntegrity && typeof storeData.checksum === "string") {
|
|
935
996
|
const checksum = await this.calcChecksum(storeData.data);
|
|
936
997
|
if (checksum !== storeData.checksum)
|
|
@@ -1101,11 +1162,12 @@ var NanoEmitter = class {
|
|
|
1101
1162
|
* `callback` (required) is the function that will be called when the conditions are met.
|
|
1102
1163
|
*
|
|
1103
1164
|
* Set `once` to true to call the callback only once for the first event (or set of events) that match the criteria, then stop listening.
|
|
1104
|
-
* If `signal` is provided, the subscription will be
|
|
1165
|
+
* If `signal` is provided, the subscription will be canceled when the given signal is aborted.
|
|
1105
1166
|
*
|
|
1106
1167
|
* If `oneOf` is used, the callback will be called when any of the matching events are emitted.
|
|
1107
1168
|
* If `allOf` is used, the callback will be called after all of the matching events are emitted at least once, then any time any of them are emitted.
|
|
1108
|
-
*
|
|
1169
|
+
* If both `oneOf` and `allOf` are used together, the callback will be called when any of the `oneOf` events are emitted AND all of the `allOf` events have been emitted at least once.
|
|
1170
|
+
* At least one of `oneOf` or `allOf` must be provided.
|
|
1109
1171
|
*
|
|
1110
1172
|
* @returns Returns a function that can be called to unsubscribe all listeners created by this call. Alternatively, pass an `AbortSignal` to all options objects to achieve the same effect or for finer control.
|
|
1111
1173
|
*/
|
|
@@ -1133,6 +1195,8 @@ var NanoEmitter = class {
|
|
|
1133
1195
|
} = optsWithDefaults;
|
|
1134
1196
|
if (signal == null ? void 0 : signal.aborted)
|
|
1135
1197
|
return unsubAll;
|
|
1198
|
+
if (oneOf.length === 0 && allOf.length === 0)
|
|
1199
|
+
throw new TypeError("NanoEmitter.onMulti(): Either `oneOf` or `allOf` or both must be provided in the options");
|
|
1136
1200
|
const curEvtUnsubs = [];
|
|
1137
1201
|
const checkUnsubAllEvt = (force = false) => {
|
|
1138
1202
|
if (!(signal == null ? void 0 : signal.aborted) && !force)
|
|
@@ -1142,34 +1206,31 @@ var NanoEmitter = class {
|
|
|
1142
1206
|
curEvtUnsubs.splice(0, curEvtUnsubs.length);
|
|
1143
1207
|
this.eventUnsubscribes = this.eventUnsubscribes.filter((u) => !curEvtUnsubs.includes(u));
|
|
1144
1208
|
};
|
|
1209
|
+
const allOfEmitted = /* @__PURE__ */ new Set();
|
|
1210
|
+
const allOfConditionMet = () => allOf.length === 0 || allOfEmitted.size === allOf.length;
|
|
1145
1211
|
for (const event of oneOf) {
|
|
1146
1212
|
const unsub = this.events.on(event, ((...args) => {
|
|
1147
1213
|
checkUnsubAllEvt();
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1214
|
+
if (allOfConditionMet()) {
|
|
1215
|
+
callback(event, ...args);
|
|
1216
|
+
if (once)
|
|
1217
|
+
checkUnsubAllEvt(true);
|
|
1218
|
+
}
|
|
1151
1219
|
}));
|
|
1152
1220
|
curEvtUnsubs.push(unsub);
|
|
1153
1221
|
}
|
|
1154
|
-
const allOfEmitted = /* @__PURE__ */ new Set();
|
|
1155
|
-
const checkAllOf = (event, ...args) => {
|
|
1156
|
-
checkUnsubAllEvt();
|
|
1157
|
-
allOfEmitted.add(event);
|
|
1158
|
-
if (allOfEmitted.size === allOf.length) {
|
|
1159
|
-
callback(event, ...args);
|
|
1160
|
-
if (once)
|
|
1161
|
-
checkUnsubAllEvt(true);
|
|
1162
|
-
}
|
|
1163
|
-
};
|
|
1164
1222
|
for (const event of allOf) {
|
|
1165
1223
|
const unsub = this.events.on(event, ((...args) => {
|
|
1166
1224
|
checkUnsubAllEvt();
|
|
1167
|
-
|
|
1225
|
+
allOfEmitted.add(event);
|
|
1226
|
+
if (allOfConditionMet() && (oneOf.length === 0 || oneOf.includes(event))) {
|
|
1227
|
+
callback(event, ...args);
|
|
1228
|
+
if (once)
|
|
1229
|
+
checkUnsubAllEvt(true);
|
|
1230
|
+
}
|
|
1168
1231
|
}));
|
|
1169
1232
|
curEvtUnsubs.push(unsub);
|
|
1170
1233
|
}
|
|
1171
|
-
if (oneOf.length === 0 && allOf.length === 0)
|
|
1172
|
-
throw new TypeError("NanoEmitter.onMulti(): Either `oneOf` or `allOf` or both must be provided in the options");
|
|
1173
1234
|
allUnsubs.push(() => checkUnsubAllEvt(true));
|
|
1174
1235
|
}
|
|
1175
1236
|
return unsubAll;
|
|
@@ -1304,6 +1365,7 @@ function debounce(fn, timeout = 200, type = "immediate") {
|
|
|
1304
1365
|
export {
|
|
1305
1366
|
BrowserStorageEngine,
|
|
1306
1367
|
ChecksumMismatchError,
|
|
1368
|
+
CustomError,
|
|
1307
1369
|
DataStore,
|
|
1308
1370
|
DataStoreEngine,
|
|
1309
1371
|
DataStoreSerializer,
|
|
@@ -1312,6 +1374,8 @@ export {
|
|
|
1312
1374
|
FileStorageEngine,
|
|
1313
1375
|
MigrationError,
|
|
1314
1376
|
NanoEmitter,
|
|
1377
|
+
NetworkError,
|
|
1378
|
+
ScriptContextError,
|
|
1315
1379
|
ValidationError,
|
|
1316
1380
|
abtoa,
|
|
1317
1381
|
atoab,
|
|
@@ -1331,6 +1395,7 @@ export {
|
|
|
1331
1395
|
digitCount,
|
|
1332
1396
|
fetchAdvanced,
|
|
1333
1397
|
formatNumber,
|
|
1398
|
+
getCallStack,
|
|
1334
1399
|
getListLength,
|
|
1335
1400
|
hexToRgb,
|
|
1336
1401
|
insertValues,
|