@sv443-network/coreutils 3.0.4 → 3.0.6
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 +13 -0
- package/dist/CoreUtils.cjs +31 -7
- package/dist/CoreUtils.min.cjs +3 -3
- package/dist/CoreUtils.min.mjs +3 -3
- package/dist/CoreUtils.min.umd.js +3 -3
- package/dist/CoreUtils.mjs +31 -7
- package/dist/CoreUtils.umd.js +31 -7
- package/dist/lib/DataStore.d.ts +9 -9
- package/dist/lib/DataStoreEngine.d.ts +1 -1
- package/dist/lib/DataStoreSerializer.d.ts +3 -3
- package/dist/lib/TieredCache.d.ts +1 -1
- package/dist/lib/test/DirectAccessDataStore.d.ts +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
1
1
|
# @sv443-network/coreutils
|
|
2
2
|
|
|
3
|
+
## 3.0.6
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- d17ec25: The `FileStorageEngine` for `DataStore`s now saves unencoded data as a plain object for easier editing.
|
|
8
|
+
Previously saved stringified data will be loaded fine, but will be saved in the new format on the next save.
|
|
9
|
+
|
|
10
|
+
## 3.0.5
|
|
11
|
+
|
|
12
|
+
### Patch Changes
|
|
13
|
+
|
|
14
|
+
- bb69014: Made `DataStore.getData()` unavailable at the type level when `memoryCache` is set to `false`.
|
|
15
|
+
|
|
3
16
|
## 3.0.4
|
|
4
17
|
|
|
5
18
|
### Patch Changes
|
package/dist/CoreUtils.cjs
CHANGED
|
@@ -564,7 +564,7 @@ var DataStore = class {
|
|
|
564
564
|
encodeData;
|
|
565
565
|
decodeData;
|
|
566
566
|
compressionFormat = "deflate-raw";
|
|
567
|
-
memoryCache
|
|
567
|
+
memoryCache;
|
|
568
568
|
engine;
|
|
569
569
|
options;
|
|
570
570
|
/**
|
|
@@ -591,7 +591,7 @@ var DataStore = class {
|
|
|
591
591
|
this.id = opts.id;
|
|
592
592
|
this.formatVersion = opts.formatVersion;
|
|
593
593
|
this.defaultData = opts.defaultData;
|
|
594
|
-
this.memoryCache =
|
|
594
|
+
this.memoryCache = opts.memoryCache ?? true;
|
|
595
595
|
this.cachedData = this.memoryCache ? opts.defaultData : {};
|
|
596
596
|
this.migrations = opts.migrations;
|
|
597
597
|
if (opts.migrateIds)
|
|
@@ -689,7 +689,7 @@ var DataStore = class {
|
|
|
689
689
|
/**
|
|
690
690
|
* Returns a copy of the data from the in-memory cache.
|
|
691
691
|
* Use {@linkcode loadData()} to get fresh data from persistent storage (usually not necessary since the cache should always exactly reflect persistent storage).
|
|
692
|
-
* ⚠️
|
|
692
|
+
* ⚠️ Only available when `memoryCache` is `true` (default). When set to `false`, this produces a type and runtime error - use {@linkcode loadData()} instead.
|
|
693
693
|
*/
|
|
694
694
|
getData() {
|
|
695
695
|
if (!this.memoryCache)
|
|
@@ -766,7 +766,7 @@ var DataStore = class {
|
|
|
766
766
|
if (!resetOnError)
|
|
767
767
|
throw new MigrationError(`Error while running migration function for format version '${fmtVer}'`, { cause: err });
|
|
768
768
|
await this.saveDefaultData();
|
|
769
|
-
return this.
|
|
769
|
+
return this.engine.deepCopy(this.defaultData);
|
|
770
770
|
}
|
|
771
771
|
}
|
|
772
772
|
}
|
|
@@ -961,8 +961,21 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
961
961
|
const value = data == null ? void 0 : data[name];
|
|
962
962
|
if (typeof value === "undefined")
|
|
963
963
|
return defaultValue;
|
|
964
|
-
if (typeof
|
|
965
|
-
|
|
964
|
+
if (typeof defaultValue === "string") {
|
|
965
|
+
if (typeof value === "object" && value !== null)
|
|
966
|
+
return JSON.stringify(value);
|
|
967
|
+
if (typeof value === "string")
|
|
968
|
+
return value;
|
|
969
|
+
return String(value);
|
|
970
|
+
}
|
|
971
|
+
if (typeof value === "string") {
|
|
972
|
+
try {
|
|
973
|
+
const parsed = JSON.parse(value);
|
|
974
|
+
return parsed;
|
|
975
|
+
} catch {
|
|
976
|
+
return defaultValue;
|
|
977
|
+
}
|
|
978
|
+
}
|
|
966
979
|
return value;
|
|
967
980
|
}
|
|
968
981
|
/** Sets a value in persistent storage */
|
|
@@ -971,7 +984,18 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
971
984
|
let data = await this.readFile();
|
|
972
985
|
if (!data)
|
|
973
986
|
data = {};
|
|
974
|
-
|
|
987
|
+
let storeVal = value;
|
|
988
|
+
if (typeof value === "string") {
|
|
989
|
+
try {
|
|
990
|
+
if (value.startsWith("{") || value.startsWith("[")) {
|
|
991
|
+
const parsed = JSON.parse(value);
|
|
992
|
+
if (typeof parsed === "object" && parsed !== null)
|
|
993
|
+
storeVal = parsed;
|
|
994
|
+
}
|
|
995
|
+
} catch {
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
data[name] = storeVal;
|
|
975
999
|
await this.writeFile(data);
|
|
976
1000
|
}).catch((err) => {
|
|
977
1001
|
console.error("Error in setValue:", err);
|
package/dist/CoreUtils.min.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
"use strict";var Y=Object.create;var V=Object.defineProperty;var ee=Object.getOwnPropertyDescriptor;var te=Object.getOwnPropertyNames;var re=Object.getPrototypeOf,ie=Object.prototype.hasOwnProperty;var ne=(r,e)=>{for(var t in e)V(r,t,{get:e[t],enumerable:!0})},K=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of te(e))!ie.call(r,n)&&n!==t&&V(r,n,{get:()=>e[n],enumerable:!(i=ee(e,n))||i.enumerable});return r};var M=(r,e,t)=>(t=r!=null?Y(re(r)):{},K(e||!r||!r.__esModule?V(t,"default",{value:r,enumerable:!0}):t,r)),ae=r=>K(V({},"__esModule",{value:!0}),r);var
|
|
1
|
+
"use strict";var Y=Object.create;var V=Object.defineProperty;var ee=Object.getOwnPropertyDescriptor;var te=Object.getOwnPropertyNames;var re=Object.getPrototypeOf,ie=Object.prototype.hasOwnProperty;var ne=(r,e)=>{for(var t in e)V(r,t,{get:e[t],enumerable:!0})},K=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of te(e))!ie.call(r,n)&&n!==t&&V(r,n,{get:()=>e[n],enumerable:!(i=ee(e,n))||i.enumerable});return r};var M=(r,e,t)=>(t=r!=null?Y(re(r)):{},K(e||!r||!r.__esModule?V(t,"default",{value:r,enumerable:!0}):t,r)),ae=r=>K(V({},"__esModule",{value:!0}),r);var Ce={};ne(Ce,{BrowserStorageEngine:()=>R,ChecksumMismatchError:()=>S,CustomError:()=>v,DataStore:()=>U,DataStoreEngine:()=>E,DataStoreSerializer:()=>B,DatedError:()=>m,Debouncer:()=>F,FileStorageEngine:()=>j,MigrationError:()=>w,NanoEmitter:()=>P,NetworkError:()=>x,ScriptContextError:()=>g,ValidationError:()=>z,abtoa:()=>W,atoab:()=>Q,autoPlural:()=>Pe,bitSetHas:()=>oe,capitalize:()=>Oe,clamp:()=>D,compress:()=>_,computeHash:()=>$,consumeGen:()=>ge,consumeStringGen:()=>be,createProgressBar:()=>Ve,darkenColor:()=>J,debounce:()=>Ie,decompress:()=>k,defaultPbChars:()=>G,digitCount:()=>se,fetchAdvanced:()=>ye,formatNumber:()=>ue,getCallStack:()=>Ee,getListLength:()=>De,hexToRgb:()=>q,insertValues:()=>Ne,joinArrayReadable:()=>Fe,lightenColor:()=>fe,mapRange:()=>N,overflowVal:()=>ce,pauseFor:()=>Te,pureObj:()=>Se,randRange:()=>T,randomId:()=>he,randomItem:()=>de,randomItemIndex:()=>C,randomizeArray:()=>me,rgbToHex:()=>H,roundFixed:()=>I,scheduleExit:()=>xe,secsToTimeStr:()=>Ae,setImmediateInterval:()=>ve,setImmediateTimeoutLoop:()=>we,takeRandomItem:()=>pe,takeRandomItemIndex:()=>L,truncStr:()=>Me,valsWithin:()=>le});module.exports=ae(Ce);function oe(r,e){return(r&e)===e}function D(r,e,t){return typeof t!="number"&&(t=e,e=0),Math.max(Math.min(r,t),e)}function se(r,e=!0){if(r=Number(["string","number"].includes(typeof r)?r:String(r)),typeof r=="number"&&isNaN(r))return NaN;let[t,i]=r.toString().split("."),n=t==="0"?1:Math.floor(Math.log10(Math.abs(Number(t)))+1),o=e&&i?i.length:0;return n+o}function ue(r,e,t){return r.toLocaleString(e,t==="short"?{notation:"compact",compactDisplay:"short",maximumFractionDigits:1}:{style:"decimal",maximumFractionDigits:0})}function N(r,e,t,i,n){return(typeof i>"u"||typeof n>"u")&&(n=t,t=e,i=e=0),Number(e)===0&&Number(i)===0?r*(n/t):(r-e)*((n-i)/(t-e))+i}function ce(r,e,t){let i=typeof t=="number"?e:0;if(t=typeof t=="number"?t:e,i>t)throw new RangeError(`Parameter "min" can't be bigger than "max"`);if(isNaN(r)||isNaN(i)||isNaN(t)||!isFinite(r)||!isFinite(i)||!isFinite(t))return NaN;if(r>=i&&r<=t)return r;let n=t-i+1;return((r-i)%n+n)%n+i}function T(...r){let e,t,i=!1;if(typeof r[0]=="number"&&typeof r[1]=="number")[e,t]=r;else if(typeof r[0]=="number"&&typeof r[1]!="number")e=0,[t]=r;else throw new TypeError(`Wrong parameter(s) provided - expected (number, boolean|undefined) or (number, number, boolean|undefined) but got (${r.map(n=>typeof n).join(", ")}) instead`);if(typeof r[2]=="boolean"?i=r[2]:typeof r[1]=="boolean"&&(i=r[1]),e=Number(e),t=Number(t),isNaN(e)||isNaN(t))return NaN;if(e>t)throw new TypeError(`Parameter "min" can't be bigger than "max"`);if(i){let n=new Uint8Array(1);return crypto.getRandomValues(n),Number(Array.from(n,o=>Math.round(N(o,0,255,e,t)).toString(10)).join(""))}else return Math.floor(Math.random()*(t-e+1))+e}function I(r,e){let t=10**e;return Math.round(r*t)/t}function le(r,e,t=1,i=.5){return Math.abs(I(r,t)-I(e,t))<=i}function de(r){return C(r)[0]}function C(r){if(r.length===0)return[void 0,void 0];let e=T(r.length-1);return[r[e],e]}function me(r){let e=[...r];if(r.length===0)return e;for(let t=e.length-1;t>0;t--){let i=Math.floor(Math.random()*(t+1));[e[t],e[i]]=[e[i],e[t]]}return e}function pe(r){var e;return(e=L(r))==null?void 0:e[0]}function L(r){let[e,t]=C(r);return t===void 0?[void 0,void 0]:(r.splice(t,1),[e,t])}function J(r,e,t=!1){var l;r=r.trim();let i=(c,d,p,b)=>(c=Math.max(0,Math.min(255,c-c*b/100)),d=Math.max(0,Math.min(255,d-d*b/100)),p=Math.max(0,Math.min(255,p-p*b/100)),[c,d,p]),n,o,a,s,u=r.match(/^#?([0-9A-Fa-f]{3}|[0-9A-Fa-f]{4}|[0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})$/);if(u)[n,o,a,s]=q(r);else if(r.startsWith("rgb")){let c=(l=r.match(/\d+(\.\d+)?/g))==null?void 0:l.map(Number);if(!c)throw new TypeError("Invalid RGB/RGBA color format");[n,o,a,s]=c}else throw new TypeError("Unsupported color format");return[n,o,a]=i(n,o,a,e),u?H(n,o,a,s,r.startsWith("#"),t):r.startsWith("rgba")?`rgba(${n}, ${o}, ${a}, ${s??NaN})`:`rgb(${n}, ${o}, ${a})`}function q(r){r=(r.startsWith("#")?r.slice(1):r).trim();let e=r.length===8||r.length===4?parseInt(r.slice(-(r.length/4)),16)/(r.length===8?255:15):void 0;isNaN(Number(e))||(r=r.slice(0,-(r.length/4))),(r.length===3||r.length===4)&&(r=r.split("").map(a=>a+a).join(""));let t=parseInt(r,16),i=t>>16&255,n=t>>8&255,o=t&255;return[D(i,0,255),D(n,0,255),D(o,0,255),typeof e=="number"?D(e,0,1):void 0]}function fe(r,e,t=!1){return J(r,e*-1,t)}function H(r,e,t,i,n=!0,o=!1){let a=s=>D(Math.round(s),0,255).toString(16).padStart(2,"0")[o?"toUpperCase":"toLowerCase"]();return`${n?"#":""}${a(r)}${a(e)}${a(t)}${i?a(i*255):""}`}function W(r){return btoa(new Uint8Array(r).reduce((e,t)=>e+String.fromCharCode(t),""))}function Q(r){return Uint8Array.from(atob(r),e=>e.charCodeAt(0))}async function _(r,e,t="string"){let i=r instanceof Uint8Array?r:new TextEncoder().encode((r==null?void 0:r.toString())??String(r)),n=new CompressionStream(e),o=n.writable.getWriter();o.write(i),o.close();let a=new Uint8Array(await new Response(n.readable).arrayBuffer());return t==="arrayBuffer"?a:W(a)}async function k(r,e,t="string"){let i=r instanceof Uint8Array?r:Q((r==null?void 0:r.toString())??String(r)),n=new DecompressionStream(e),o=n.writable.getWriter();o.write(i),o.close();let a=new Uint8Array(await new Response(n.readable).arrayBuffer());return t==="arrayBuffer"?a:new TextDecoder().decode(a)}async function $(r,e="SHA-256"){let t;typeof r=="string"?t=new TextEncoder().encode(r):t=r;let i=await crypto.subtle.digest(e,t);return Array.from(new Uint8Array(i)).map(a=>a.toString(16).padStart(2,"0")).join("")}function he(r=16,e=16,t=!1,i=!0){if(r<1)throw new RangeError("The length argument must be at least 1");if(e<2||e>36)throw new RangeError("The radix argument must be between 2 and 36");let n=[],o=i?[0,1]:[0];if(t){let a=new Uint8Array(r);crypto.getRandomValues(a),n=Array.from(a,s=>N(s,0,255,0,e).toString(e).substring(0,1))}else n=Array.from({length:r},()=>Math.floor(Math.random()*e).toString(e));return n.some(a=>/[a-zA-Z]/.test(a))?n.map(a=>o[T(0,o.length-1,t)]===1?a.toUpperCase():a).join(""):n.join("")}var m=class extends Error{date;constructor(e,t){super(e,t),this.name=this.constructor.name,this.date=new Date}},S=class extends m{constructor(e,t){super(e,t),this.name="ChecksumMismatchError"}},v=class extends m{constructor(e,t,i){super(t,i),this.name=e}},w=class extends m{constructor(e,t){super(e,t),this.name="MigrationError"}},z=class extends m{constructor(e,t){super(e,t),this.name="ValidationError"}},g=class extends m{constructor(e,t){super(e,t),this.name="ScriptContextError"}},x=class extends m{constructor(e,t){super(e,t),this.name="NetworkError"}};async function ge(r){return await(typeof r=="function"?r():r)}async function be(r){return typeof r=="string"?r:String(typeof r=="function"?await r():r)}async function ye(r,e={}){let{timeout:t=1e4,signal:i,...n}=e,o=new AbortController;i==null||i.addEventListener("abort",()=>o.abort());let a={},s;t>=0&&(s=setTimeout(()=>o.abort(),t),a={signal:o.signal});try{let u=await fetch(r,{...n,...a});return typeof s<"u"&&clearTimeout(s),u}catch(u){throw typeof s<"u"&&clearTimeout(s),new x("Error while calling fetch",{cause:u})}}function De(r,e=!0){return"length"in r?r.length:"size"in r?r.size:"count"in r?r.count:e?0:NaN}function Te(r,e,t=!1){return new Promise((i,n)=>{let o=setTimeout(()=>i(),r);e==null||e.addEventListener("abort",()=>{clearTimeout(o),t?n(new v("AbortError","The pause was aborted")):i()})})}function Se(r){return Object.assign(Object.create(null),r??{})}function ve(r,e,t){let i,n=()=>clearInterval(i),o=()=>{if(t!=null&&t.aborted)return n();r()};t==null||t.addEventListener("abort",n),o(),i=setInterval(o,e)}function we(r,e,t){let i,n=()=>clearTimeout(i),o=async()=>{if(t!=null&&t.aborted)return n();await r(),i=setTimeout(o,e)};t==null||t.addEventListener("abort",n),o()}function xe(r=0,e=0){if(e<0)throw new TypeError("Timeout must be a non-negative number");let t;if(typeof process<"u"&&"exit"in process&&typeof process.exit=="function")t=()=>process.exit(r);else if(typeof Deno<"u"&&"exit"in Deno&&typeof Deno.exit=="function")t=()=>Deno.exit(r);else throw new g("Cannot exit the process, no exit method available");setTimeout(t,e)}function Ee(r,e=1/0){if(typeof e!="number"||isNaN(e)||e<0)throw new TypeError("lines parameter must be a non-negative number");try{throw new Error("This is to capture a stack trace with CoreUtils.getCallStack(). (If you see this somewhere, you can safely ignore it.)")}catch(t){let i=(t.stack??"").split(`
|
|
2
2
|
`).map(n=>n.trim()).slice(2,e+2);return r!==!1?i:i.join(`
|
|
3
|
-
`)}}function Pe(r,e,t="auto"){switch(typeof e!="number"&&("length"in e?e=e.length:"size"in e?e=e.size:"count"in e&&(e=e.count)),["-s","-ies"].includes(t)||(t="auto"),isNaN(e)&&(e=2),t==="auto"?String(r).endsWith("y")?"-ies":"-s":t){case"-s":return`${r}${e===1?"":"s"}`;case"-ies":return`${String(r).slice(0,-1)}${e===1?"y":"ies"}`}}function Oe(r){return r.charAt(0).toUpperCase()+r.slice(1)}var G={100:"\u2588",75:"\u2593",50:"\u2592",25:"\u2591",0:"\u2500"};function Ve(r,e,t=G){if(r===100)return t[100].repeat(e);let i=Math.floor(r/100*e),n=r/10*e-i,o="";n>=.75?o=t[75]:n>=.5?o=t[50]:n>=.25&&(o=t[25]);let a=t[100].repeat(i),s=t[0].repeat(e-i-(o?1:0));return`${a}${o}${s}`}function Fe(r,...e){return r.replace(/%\d/gm,t=>{var n;let i=Number(t.substring(1))-1;return(n=e[i]??t)==null?void 0:n.toString()})}function Ne(r,e=", ",t=" and "){let i=[...r];if(i.length===0)return"";if(i.length===1)return String(i[0]);if(i.length===2)return i.join(t);let n=t+i[i.length-1];return i.pop(),i.join(e)+n}function Ae(r){let e=r<0,t=Math.abs(r);if(isNaN(t)||!isFinite(t))throw new TypeError("The seconds argument must be a valid number");let i=Math.floor(t/3600),n=Math.floor(t%3600/60),o=Math.floor(t%60);return(e?"-":"")+[i?i+":":"",String(n).padStart(n>0||i>0?2:1,"0"),":",String(o).padStart(o>0||n>0||i>0||r===0?2:1,"0")].join("")}function Me(r,e,t="..."){let i=(r==null?void 0:r.toString())??String(r),n=i.length>e?i.substring(0,e-t.length)+t:i;return n.length>e?n.substring(0,e):n}var Z=1,U=class{id;formatVersion;defaultData;encodeData;decodeData;compressionFormat="deflate-raw";memoryCache=!0;engine;options;firstInit=!0;cachedData;migrations;migrateIds=[];constructor(e){if(this.id=e.id,this.formatVersion=e.formatVersion,this.defaultData=e.defaultData,this.memoryCache=!!(e.memoryCache??!0),this.cachedData=this.memoryCache?e.defaultData:{},this.migrations=e.migrations,e.migrateIds&&(this.migrateIds=Array.isArray(e.migrateIds)?e.migrateIds:[e.migrateIds]),this.engine=typeof e.engine=="function"?e.engine():e.engine,this.options=e,"encodeData"in e&&"decodeData"in e&&Array.isArray(e.encodeData)&&Array.isArray(e.decodeData))this.encodeData=[e.encodeData[0],e.encodeData[1]],this.decodeData=[e.decodeData[0],e.decodeData[1]],this.compressionFormat=e.encodeData[0]??null;else if(e.compressionFormat===null)this.encodeData=void 0,this.decodeData=void 0,this.compressionFormat=null;else{let t=typeof e.compressionFormat=="string"?e.compressionFormat:"deflate-raw";this.compressionFormat=t,this.encodeData=[t,async i=>await C(i,t,"string")],this.decodeData=[t,async i=>await k(i,t,"string")]}this.engine.setDataStoreOptions({id:this.id,encodeData:this.encodeData,decodeData:this.decodeData})}async loadData(){try{if(this.firstInit){this.firstInit=!1;let u=Number(await this.engine.getValue("__ds_fmt_ver",0)),l=await this.engine.getValue(`_uucfg-${this.id}`,null);if(l){let c=Number(await this.engine.getValue(`_uucfgver-${this.id}`,NaN)),d=await this.engine.getValue(`_uucfgenc-${this.id}`,null),p=[],b=(O,h,y)=>{p.push(this.engine.setValue(h,y)),p.push(this.engine.deleteValue(O))};b(`_uucfg-${this.id}`,`__ds-${this.id}-dat`,l),isNaN(c)||b(`_uucfgver-${this.id}`,`__ds-${this.id}-ver`,c),typeof d=="boolean"||d==="true"||d==="false"||typeof d=="number"||d==="0"||d==="1"?b(`_uucfgenc-${this.id}`,`__ds-${this.id}-enf`,[0,"0",!0,"true"].includes(d)?this.compressionFormat??null:null):(p.push(this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)),p.push(this.engine.deleteValue(`_uucfgenc-${this.id}`))),await Promise.allSettled(p)}(isNaN(u)||u<Z)&&await this.engine.setValue("__ds_fmt_ver",Z)}this.migrateIds.length>0&&(await this.migrateId(this.migrateIds),this.migrateIds=[]);let e=await this.engine.getValue(`__ds-${this.id}-dat`,null),t=Number(await this.engine.getValue(`__ds-${this.id}-ver`,NaN));if(typeof e!="string")return await this.saveDefaultData(),this.engine.deepCopy(this.defaultData);let i=e??JSON.stringify(this.defaultData),n=String(await this.engine.getValue(`__ds-${this.id}-enf`,null)),o=n!=="null"&&n!=="false"&&n!=="0"&&n!==""&&n!==null,a=!1;isNaN(t)&&(await this.engine.setValue(`__ds-${this.id}-ver`,t=this.formatVersion),a=!0);let s=await this.engine.deserializeData(i,o);return t<this.formatVersion&&this.migrations&&(s=await this.runMigrations(s,t)),a&&await this.setData(s),this.memoryCache?this.cachedData=this.engine.deepCopy(s):this.engine.deepCopy(s)}catch(e){return console.warn("Error while parsing JSON data, resetting it to the default value.",e),await this.saveDefaultData(),this.defaultData}}getData(){if(!this.memoryCache)throw new m("In-memory cache is disabled for this DataStore instance, so getData() can't be used. Please use loadData() instead.");return this.engine.deepCopy(this.cachedData)}setData(e){return this.memoryCache&&(this.cachedData=e),new Promise(async t=>{await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(e,this.encodingEnabled())),this.engine.setValue(`__ds-${this.id}-ver`,this.formatVersion),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)]),t()})}async saveDefaultData(){this.memoryCache&&(this.cachedData=this.defaultData),await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(this.defaultData,this.encodingEnabled())),this.engine.setValue(`__ds-${this.id}-ver`,this.formatVersion),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)])}async deleteData(){var e,t;await Promise.allSettled([this.engine.deleteValue(`__ds-${this.id}-dat`),this.engine.deleteValue(`__ds-${this.id}-ver`),this.engine.deleteValue(`__ds-${this.id}-enf`)]),await((t=(e=this.engine).deleteStorage)==null?void 0:t.call(e))}encodingEnabled(){return!!(this.encodeData&&this.decodeData)&&this.compressionFormat!==null||!!this.compressionFormat}async runMigrations(e,t,i=!0){if(!this.migrations)return e;let n=e,o=Object.entries(this.migrations).sort(([s],[u])=>Number(s)-Number(u)),a=t;for(let[s,u]of o){let l=Number(s);if(t<this.formatVersion&&t<l)try{let c=u(n);n=c instanceof Promise?await c:c,a=t=l}catch(c){if(!i)throw new w(`Error while running migration function for format version '${s}'`,{cause:c});return await this.saveDefaultData(),this.getData()}}return await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(n,this.encodingEnabled())),this.engine.setValue(`__ds-${this.id}-ver`,a),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)]),this.memoryCache?this.cachedData=this.engine.deepCopy(n):this.engine.deepCopy(n)}async migrateId(e){let t=Array.isArray(e)?e:[e];await Promise.all(t.map(async i=>{let[n,o,a]=await(async()=>{let[u,l,c]=await Promise.all([this.engine.getValue(`__ds-${i}-dat`,JSON.stringify(this.defaultData)),this.engine.getValue(`__ds-${i}-ver`,NaN),this.engine.getValue(`__ds-${i}-enf`,null)]);return[u,Number(l),!!c&&String(c)!=="null"]})();if(n===void 0||isNaN(o))return;let s=await this.engine.deserializeData(n,a);await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(s,this.encodingEnabled())),this.engine.setValue(`__ds-${this.id}-ver`,o),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat),this.engine.deleteValue(`__ds-${i}-dat`),this.engine.deleteValue(`__ds-${i}-ver`),this.engine.deleteValue(`__ds-${i}-enf`)])}))}};var E=class{dataStoreOptions;constructor(e){e&&(this.dataStoreOptions=e)}setDataStoreOptions(e){this.dataStoreOptions=e}async serializeData(e,t){var o,a,s,u,l;this.ensureDataStoreOptions();let i=JSON.stringify(e);if(!t||!((o=this.dataStoreOptions)!=null&&o.encodeData)||!((a=this.dataStoreOptions)!=null&&a.decodeData))return i;let n=(l=(u=(s=this.dataStoreOptions)==null?void 0:s.encodeData)==null?void 0:u[1])==null?void 0:l.call(u,i);return n instanceof Promise?await n:n}async deserializeData(e,t){var n,o,a;this.ensureDataStoreOptions();let i=(n=this.dataStoreOptions)!=null&&n.decodeData&&t?(a=(o=this.dataStoreOptions.decodeData)==null?void 0:o[1])==null?void 0:a.call(o,e):void 0;return i instanceof Promise&&(i=await i),JSON.parse(i??e)}ensureDataStoreOptions(){if(!this.dataStoreOptions)throw new m("DataStoreEngine must be initialized with DataStore options before use. If you are using this instance standalone, set them in the constructor or call `setDataStoreOptions()` with the DataStore options.");if(!this.dataStoreOptions.id)throw new m("DataStoreEngine must be initialized with a valid DataStore ID")}deepCopy(e){try{if("structuredClone"in globalThis)return structuredClone(e)}catch{}return JSON.parse(JSON.stringify(e))}},R=class extends E{options;constructor(e){super(e==null?void 0:e.dataStoreOptions),this.options={type:"localStorage",...e}}async getValue(e,t){let i=this.options.type==="localStorage"?globalThis.localStorage.getItem(e):globalThis.sessionStorage.getItem(e);return typeof i>"u"?t:i}async setValue(e,t){this.options.type==="localStorage"?globalThis.localStorage.setItem(e,String(t)):globalThis.sessionStorage.setItem(e,String(t))}async deleteValue(e){this.options.type==="localStorage"?globalThis.localStorage.removeItem(e):globalThis.sessionStorage.removeItem(e)}},f,j=class extends E{options;fileAccessQueue=Promise.resolve();constructor(e){super(e==null?void 0:e.dataStoreOptions),this.options={filePath:t=>`.ds-${t}`,...e}}async readFile(){var e,t,i,n;this.ensureDataStoreOptions();try{if(f||(f=(e=await import("fs/promises"))==null?void 0:e.default),!f)throw new g("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new m("'node:fs/promises' module not available")});let o=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id),a=await f.readFile(o,"utf-8");return a?JSON.parse(await((n=(i=(t=this.dataStoreOptions)==null?void 0:t.decodeData)==null?void 0:i[1])==null?void 0:n.call(i,a))??a):void 0}catch{return}}async writeFile(e){var t,i,n,o;this.ensureDataStoreOptions();try{if(f||(f=(t=await import("fs/promises"))==null?void 0:t.default),!f)throw new g("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new m("'node:fs/promises' module not available")});let a=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id);await f.mkdir(a.slice(0,a.lastIndexOf(a.includes("/")?"/":"\\")),{recursive:!0}),await f.writeFile(a,await((o=(n=(i=this.dataStoreOptions)==null?void 0:i.encodeData)==null?void 0:n[1])==null?void 0:o.call(n,JSON.stringify(e)))??JSON.stringify(e,void 0,2),"utf-8")}catch(a){console.error("Error writing file:",a)}}async getValue(e,t){let i=await this.readFile();if(!i)return t;let n=i==null?void 0:i[e];return typeof n>"u"?t:n}async setValue(e,t){this.fileAccessQueue=this.fileAccessQueue.then(async()=>{let i=await this.readFile();i||(i={}),i[e]=t,await this.writeFile(i)}).catch(i=>{throw console.error("Error in setValue:",i),i}),await this.fileAccessQueue.catch(()=>{})}async deleteValue(e){this.fileAccessQueue=this.fileAccessQueue.then(async()=>{let t=await this.readFile();t&&(delete t[e],await this.writeFile(t))}).catch(t=>{throw console.error("Error in deleteValue:",t),t}),await this.fileAccessQueue.catch(()=>{})}async deleteStorage(){var e;this.ensureDataStoreOptions();try{if(f||(f=(e=await import("fs/promises"))==null?void 0:e.default),!f)throw new g("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new m("'node:fs/promises' module not available")});let t=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id);return await f.unlink(t)}catch(t){console.error("Error deleting file:",t)}}};var B=class r{stores;options;constructor(e,t={}){if(!crypto||!crypto.subtle)throw new g("DataStoreSerializer has to run in a secure context (HTTPS) or in another environment that implements the subtleCrypto API!");this.stores=e,this.options={addChecksum:!0,ensureIntegrity:!0,remapIds:{},...t}}async calcChecksum(e){return $(e,"SHA-256")}async serializePartial(e,t=!0,i=!0){var a;let n=[],o=this.stores.filter(s=>typeof e=="function"?e(s.id):e.includes(s.id));for(let s of o){let u=!!(t&&s.encodingEnabled()&&((a=s.encodeData)!=null&&a[1])),l=s.memoryCache?s.getData():await s.loadData(),c=u?await s.encodeData[1](JSON.stringify(l)):JSON.stringify(l);n.push({id:s.id,data:c,formatVersion:s.formatVersion,encoded:u,checksum:this.options.addChecksum?await this.calcChecksum(c):void 0})}return i?JSON.stringify(n):n}async serialize(e=!0,t=!0){return this.serializePartial(this.stores.map(i=>i.id),e,t)}async deserializePartial(e,t){let i=typeof t=="string"?JSON.parse(t):t;if(!Array.isArray(i)||!i.every(r.isSerializedDataStoreObj))throw new TypeError("Invalid serialized data format! Expected an array of SerializedDataStore objects.");let n=a=>{var s;return((s=Object.entries(this.options.remapIds).find(([,u])=>u.includes(a)))==null?void 0:s[0])??a},o=a=>typeof e=="function"?e(a):e.includes(a);for(let a of i){let s=n(a.id);if(!o(s))continue;let u=this.stores.find(c=>c.id===s);if(!u)throw new m(`Can't deserialize data because no DataStore instance with the ID "${s}" was found! Make sure to provide it in the DataStoreSerializer constructor.`);if(this.options.ensureIntegrity&&typeof a.checksum=="string"){let c=await this.calcChecksum(a.data);if(c!==a.checksum)throw new S(`Checksum mismatch for DataStore with ID "${a.id}"!
|
|
3
|
+
`)}}function Pe(r,e,t="auto"){switch(typeof e!="number"&&("length"in e?e=e.length:"size"in e?e=e.size:"count"in e&&(e=e.count)),["-s","-ies"].includes(t)||(t="auto"),isNaN(e)&&(e=2),t==="auto"?String(r).endsWith("y")?"-ies":"-s":t){case"-s":return`${r}${e===1?"":"s"}`;case"-ies":return`${String(r).slice(0,-1)}${e===1?"y":"ies"}`}}function Oe(r){return r.charAt(0).toUpperCase()+r.slice(1)}var G={100:"\u2588",75:"\u2593",50:"\u2592",25:"\u2591",0:"\u2500"};function Ve(r,e,t=G){if(r===100)return t[100].repeat(e);let i=Math.floor(r/100*e),n=r/10*e-i,o="";n>=.75?o=t[75]:n>=.5?o=t[50]:n>=.25&&(o=t[25]);let a=t[100].repeat(i),s=t[0].repeat(e-i-(o?1:0));return`${a}${o}${s}`}function Ne(r,...e){return r.replace(/%\d/gm,t=>{var n;let i=Number(t.substring(1))-1;return(n=e[i]??t)==null?void 0:n.toString()})}function Fe(r,e=", ",t=" and "){let i=[...r];if(i.length===0)return"";if(i.length===1)return String(i[0]);if(i.length===2)return i.join(t);let n=t+i[i.length-1];return i.pop(),i.join(e)+n}function Ae(r){let e=r<0,t=Math.abs(r);if(isNaN(t)||!isFinite(t))throw new TypeError("The seconds argument must be a valid number");let i=Math.floor(t/3600),n=Math.floor(t%3600/60),o=Math.floor(t%60);return(e?"-":"")+[i?i+":":"",String(n).padStart(n>0||i>0?2:1,"0"),":",String(o).padStart(o>0||n>0||i>0||r===0?2:1,"0")].join("")}function Me(r,e,t="..."){let i=(r==null?void 0:r.toString())??String(r),n=i.length>e?i.substring(0,e-t.length)+t:i;return n.length>e?n.substring(0,e):n}var Z=1,U=class{id;formatVersion;defaultData;encodeData;decodeData;compressionFormat="deflate-raw";memoryCache;engine;options;firstInit=!0;cachedData;migrations;migrateIds=[];constructor(e){if(this.id=e.id,this.formatVersion=e.formatVersion,this.defaultData=e.defaultData,this.memoryCache=e.memoryCache??!0,this.cachedData=this.memoryCache?e.defaultData:{},this.migrations=e.migrations,e.migrateIds&&(this.migrateIds=Array.isArray(e.migrateIds)?e.migrateIds:[e.migrateIds]),this.engine=typeof e.engine=="function"?e.engine():e.engine,this.options=e,"encodeData"in e&&"decodeData"in e&&Array.isArray(e.encodeData)&&Array.isArray(e.decodeData))this.encodeData=[e.encodeData[0],e.encodeData[1]],this.decodeData=[e.decodeData[0],e.decodeData[1]],this.compressionFormat=e.encodeData[0]??null;else if(e.compressionFormat===null)this.encodeData=void 0,this.decodeData=void 0,this.compressionFormat=null;else{let t=typeof e.compressionFormat=="string"?e.compressionFormat:"deflate-raw";this.compressionFormat=t,this.encodeData=[t,async i=>await _(i,t,"string")],this.decodeData=[t,async i=>await k(i,t,"string")]}this.engine.setDataStoreOptions({id:this.id,encodeData:this.encodeData,decodeData:this.decodeData})}async loadData(){try{if(this.firstInit){this.firstInit=!1;let u=Number(await this.engine.getValue("__ds_fmt_ver",0)),l=await this.engine.getValue(`_uucfg-${this.id}`,null);if(l){let c=Number(await this.engine.getValue(`_uucfgver-${this.id}`,NaN)),d=await this.engine.getValue(`_uucfgenc-${this.id}`,null),p=[],b=(O,h,y)=>{p.push(this.engine.setValue(h,y)),p.push(this.engine.deleteValue(O))};b(`_uucfg-${this.id}`,`__ds-${this.id}-dat`,l),isNaN(c)||b(`_uucfgver-${this.id}`,`__ds-${this.id}-ver`,c),typeof d=="boolean"||d==="true"||d==="false"||typeof d=="number"||d==="0"||d==="1"?b(`_uucfgenc-${this.id}`,`__ds-${this.id}-enf`,[0,"0",!0,"true"].includes(d)?this.compressionFormat??null:null):(p.push(this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)),p.push(this.engine.deleteValue(`_uucfgenc-${this.id}`))),await Promise.allSettled(p)}(isNaN(u)||u<Z)&&await this.engine.setValue("__ds_fmt_ver",Z)}this.migrateIds.length>0&&(await this.migrateId(this.migrateIds),this.migrateIds=[]);let e=await this.engine.getValue(`__ds-${this.id}-dat`,null),t=Number(await this.engine.getValue(`__ds-${this.id}-ver`,NaN));if(typeof e!="string")return await this.saveDefaultData(),this.engine.deepCopy(this.defaultData);let i=e??JSON.stringify(this.defaultData),n=String(await this.engine.getValue(`__ds-${this.id}-enf`,null)),o=n!=="null"&&n!=="false"&&n!=="0"&&n!==""&&n!==null,a=!1;isNaN(t)&&(await this.engine.setValue(`__ds-${this.id}-ver`,t=this.formatVersion),a=!0);let s=await this.engine.deserializeData(i,o);return t<this.formatVersion&&this.migrations&&(s=await this.runMigrations(s,t)),a&&await this.setData(s),this.memoryCache?this.cachedData=this.engine.deepCopy(s):this.engine.deepCopy(s)}catch(e){return console.warn("Error while parsing JSON data, resetting it to the default value.",e),await this.saveDefaultData(),this.defaultData}}getData(){if(!this.memoryCache)throw new m("In-memory cache is disabled for this DataStore instance, so getData() can't be used. Please use loadData() instead.");return this.engine.deepCopy(this.cachedData)}setData(e){return this.memoryCache&&(this.cachedData=e),new Promise(async t=>{await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(e,this.encodingEnabled())),this.engine.setValue(`__ds-${this.id}-ver`,this.formatVersion),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)]),t()})}async saveDefaultData(){this.memoryCache&&(this.cachedData=this.defaultData),await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(this.defaultData,this.encodingEnabled())),this.engine.setValue(`__ds-${this.id}-ver`,this.formatVersion),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)])}async deleteData(){var e,t;await Promise.allSettled([this.engine.deleteValue(`__ds-${this.id}-dat`),this.engine.deleteValue(`__ds-${this.id}-ver`),this.engine.deleteValue(`__ds-${this.id}-enf`)]),await((t=(e=this.engine).deleteStorage)==null?void 0:t.call(e))}encodingEnabled(){return!!(this.encodeData&&this.decodeData)&&this.compressionFormat!==null||!!this.compressionFormat}async runMigrations(e,t,i=!0){if(!this.migrations)return e;let n=e,o=Object.entries(this.migrations).sort(([s],[u])=>Number(s)-Number(u)),a=t;for(let[s,u]of o){let l=Number(s);if(t<this.formatVersion&&t<l)try{let c=u(n);n=c instanceof Promise?await c:c,a=t=l}catch(c){if(!i)throw new w(`Error while running migration function for format version '${s}'`,{cause:c});return await this.saveDefaultData(),this.engine.deepCopy(this.defaultData)}}return await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(n,this.encodingEnabled())),this.engine.setValue(`__ds-${this.id}-ver`,a),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)]),this.memoryCache?this.cachedData=this.engine.deepCopy(n):this.engine.deepCopy(n)}async migrateId(e){let t=Array.isArray(e)?e:[e];await Promise.all(t.map(async i=>{let[n,o,a]=await(async()=>{let[u,l,c]=await Promise.all([this.engine.getValue(`__ds-${i}-dat`,JSON.stringify(this.defaultData)),this.engine.getValue(`__ds-${i}-ver`,NaN),this.engine.getValue(`__ds-${i}-enf`,null)]);return[u,Number(l),!!c&&String(c)!=="null"]})();if(n===void 0||isNaN(o))return;let s=await this.engine.deserializeData(n,a);await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(s,this.encodingEnabled())),this.engine.setValue(`__ds-${this.id}-ver`,o),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat),this.engine.deleteValue(`__ds-${i}-dat`),this.engine.deleteValue(`__ds-${i}-ver`),this.engine.deleteValue(`__ds-${i}-enf`)])}))}};var E=class{dataStoreOptions;constructor(e){e&&(this.dataStoreOptions=e)}setDataStoreOptions(e){this.dataStoreOptions=e}async serializeData(e,t){var o,a,s,u,l;this.ensureDataStoreOptions();let i=JSON.stringify(e);if(!t||!((o=this.dataStoreOptions)!=null&&o.encodeData)||!((a=this.dataStoreOptions)!=null&&a.decodeData))return i;let n=(l=(u=(s=this.dataStoreOptions)==null?void 0:s.encodeData)==null?void 0:u[1])==null?void 0:l.call(u,i);return n instanceof Promise?await n:n}async deserializeData(e,t){var n,o,a;this.ensureDataStoreOptions();let i=(n=this.dataStoreOptions)!=null&&n.decodeData&&t?(a=(o=this.dataStoreOptions.decodeData)==null?void 0:o[1])==null?void 0:a.call(o,e):void 0;return i instanceof Promise&&(i=await i),JSON.parse(i??e)}ensureDataStoreOptions(){if(!this.dataStoreOptions)throw new m("DataStoreEngine must be initialized with DataStore options before use. If you are using this instance standalone, set them in the constructor or call `setDataStoreOptions()` with the DataStore options.");if(!this.dataStoreOptions.id)throw new m("DataStoreEngine must be initialized with a valid DataStore ID")}deepCopy(e){try{if("structuredClone"in globalThis)return structuredClone(e)}catch{}return JSON.parse(JSON.stringify(e))}},R=class extends E{options;constructor(e){super(e==null?void 0:e.dataStoreOptions),this.options={type:"localStorage",...e}}async getValue(e,t){let i=this.options.type==="localStorage"?globalThis.localStorage.getItem(e):globalThis.sessionStorage.getItem(e);return typeof i>"u"?t:i}async setValue(e,t){this.options.type==="localStorage"?globalThis.localStorage.setItem(e,String(t)):globalThis.sessionStorage.setItem(e,String(t))}async deleteValue(e){this.options.type==="localStorage"?globalThis.localStorage.removeItem(e):globalThis.sessionStorage.removeItem(e)}},f,j=class extends E{options;fileAccessQueue=Promise.resolve();constructor(e){super(e==null?void 0:e.dataStoreOptions),this.options={filePath:t=>`.ds-${t}`,...e}}async readFile(){var e,t,i,n;this.ensureDataStoreOptions();try{if(f||(f=(e=await import("fs/promises"))==null?void 0:e.default),!f)throw new g("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new m("'node:fs/promises' module not available")});let o=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id),a=await f.readFile(o,"utf-8");return a?JSON.parse(await((n=(i=(t=this.dataStoreOptions)==null?void 0:t.decodeData)==null?void 0:i[1])==null?void 0:n.call(i,a))??a):void 0}catch{return}}async writeFile(e){var t,i,n,o;this.ensureDataStoreOptions();try{if(f||(f=(t=await import("fs/promises"))==null?void 0:t.default),!f)throw new g("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new m("'node:fs/promises' module not available")});let a=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id);await f.mkdir(a.slice(0,a.lastIndexOf(a.includes("/")?"/":"\\")),{recursive:!0}),await f.writeFile(a,await((o=(n=(i=this.dataStoreOptions)==null?void 0:i.encodeData)==null?void 0:n[1])==null?void 0:o.call(n,JSON.stringify(e)))??JSON.stringify(e,void 0,2),"utf-8")}catch(a){console.error("Error writing file:",a)}}async getValue(e,t){let i=await this.readFile();if(!i)return t;let n=i==null?void 0:i[e];if(typeof n>"u")return t;if(typeof t=="string")return typeof n=="object"&&n!==null?JSON.stringify(n):typeof n=="string"?n:String(n);if(typeof n=="string")try{return JSON.parse(n)}catch{return t}return n}async setValue(e,t){this.fileAccessQueue=this.fileAccessQueue.then(async()=>{let i=await this.readFile();i||(i={});let n=t;if(typeof t=="string")try{if(t.startsWith("{")||t.startsWith("[")){let o=JSON.parse(t);typeof o=="object"&&o!==null&&(n=o)}}catch{}i[e]=n,await this.writeFile(i)}).catch(i=>{throw console.error("Error in setValue:",i),i}),await this.fileAccessQueue.catch(()=>{})}async deleteValue(e){this.fileAccessQueue=this.fileAccessQueue.then(async()=>{let t=await this.readFile();t&&(delete t[e],await this.writeFile(t))}).catch(t=>{throw console.error("Error in deleteValue:",t),t}),await this.fileAccessQueue.catch(()=>{})}async deleteStorage(){var e;this.ensureDataStoreOptions();try{if(f||(f=(e=await import("fs/promises"))==null?void 0:e.default),!f)throw new g("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new m("'node:fs/promises' module not available")});let t=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id);return await f.unlink(t)}catch(t){console.error("Error deleting file:",t)}}};var B=class r{stores;options;constructor(e,t={}){if(!crypto||!crypto.subtle)throw new g("DataStoreSerializer has to run in a secure context (HTTPS) or in another environment that implements the subtleCrypto API!");this.stores=e,this.options={addChecksum:!0,ensureIntegrity:!0,remapIds:{},...t}}async calcChecksum(e){return $(e,"SHA-256")}async serializePartial(e,t=!0,i=!0){var a;let n=[],o=this.stores.filter(s=>typeof e=="function"?e(s.id):e.includes(s.id));for(let s of o){let u=!!(t&&s.encodingEnabled()&&((a=s.encodeData)!=null&&a[1])),l=s.memoryCache?s.getData():await s.loadData(),c=u?await s.encodeData[1](JSON.stringify(l)):JSON.stringify(l);n.push({id:s.id,data:c,formatVersion:s.formatVersion,encoded:u,checksum:this.options.addChecksum?await this.calcChecksum(c):void 0})}return i?JSON.stringify(n):n}async serialize(e=!0,t=!0){return this.serializePartial(this.stores.map(i=>i.id),e,t)}async deserializePartial(e,t){let i=typeof t=="string"?JSON.parse(t):t;if(!Array.isArray(i)||!i.every(r.isSerializedDataStoreObj))throw new TypeError("Invalid serialized data format! Expected an array of SerializedDataStore objects.");let n=a=>{var s;return((s=Object.entries(this.options.remapIds).find(([,u])=>u.includes(a)))==null?void 0:s[0])??a},o=a=>typeof e=="function"?e(a):e.includes(a);for(let a of i){let s=n(a.id);if(!o(s))continue;let u=this.stores.find(c=>c.id===s);if(!u)throw new m(`Can't deserialize data because no DataStore instance with the ID "${s}" was found! Make sure to provide it in the DataStoreSerializer constructor.`);if(this.options.ensureIntegrity&&typeof a.checksum=="string"){let c=await this.calcChecksum(a.data);if(c!==a.checksum)throw new S(`Checksum mismatch for DataStore with ID "${a.id}"!
|
|
4
4
|
Expected: ${a.checksum}
|
|
5
|
-
Has: ${c}`)}let l=a.encoded&&u.encodingEnabled()?await u.decodeData[1](a.data):a.data;a.formatVersion&&!isNaN(Number(a.formatVersion))&&Number(a.formatVersion)<u.formatVersion?await u.runMigrations(JSON.parse(l),Number(a.formatVersion),!1):await u.setData(JSON.parse(l))}}async deserialize(e){return this.deserializePartial(this.stores.map(t=>t.id),e)}async loadStoresData(e){return Promise.allSettled(this.getStoresFiltered(e).map(async t=>({id:t.id,data:await t.loadData()})))}async resetStoresData(e){return Promise.allSettled(this.getStoresFiltered(e).map(t=>t.saveDefaultData()))}async deleteStoresData(e){return Promise.allSettled(this.getStoresFiltered(e).map(t=>t.deleteData()))}static isSerializedDataStoreObjArray(e){return Array.isArray(e)&&e.every(t=>typeof t=="object"&&t!==null&&"id"in t&&"data"in t&&"formatVersion"in t&&"encoded"in t)}static isSerializedDataStoreObj(e){return typeof e=="object"&&e!==null&&"id"in e&&"data"in e&&"formatVersion"in e&&"encoded"in e}getStoresFiltered(e){return this.stores.filter(t=>typeof e>"u"?!0:Array.isArray(e)?e.includes(t.id):e(t.id))}};var X=()=>({emit(r,...e){for(let t=this.events[r]||[],i=0,n=t.length;i<n;i++)t[i](...e)},events:{},on(r,e){return(this.events[r]||=[]).push(e),()=>{var t;this.events[r]=(t=this.events[r])==null?void 0:t.filter(i=>e!==i)}}});var P=class{events=X();eventUnsubscribes=[];emitterOptions;constructor(e={}){this.emitterOptions={publicEmit:!1,...e}}on(e,t){let i,n=()=>{i&&(i(),this.eventUnsubscribes=this.eventUnsubscribes.filter(o=>o!==i))};return i=this.events.on(e,t),this.eventUnsubscribes.push(i),n}once(e,t){return new Promise(i=>{let n,o=((...a)=>{t==null||t(...a),n==null||n(),i(a)});n=this.events.on(e,o),this.eventUnsubscribes.push(n)})}onMulti(e){let t=[],i=()=>{for(let n of t)n();t.splice(0,t.length),this.eventUnsubscribes=this.eventUnsubscribes.filter(n=>!t.includes(n))};for(let n of Array.isArray(e)?e:[e]){let o={allOf:[],oneOf:[],once:!1,...n},{oneOf:a,allOf:s,once:u,signal:l,callback:c}=o;if(l!=null&&l.aborted)return i;if(a.length===0&&s.length===0)throw new TypeError("NanoEmitter.onMulti(): Either `oneOf` or `allOf` or both must be provided in the options");let d=[],p=(h=!1)=>{if(!(!(l!=null&&l.aborted)&&!h)){for(let y of d)y();d.splice(0,d.length),this.eventUnsubscribes=this.eventUnsubscribes.filter(y=>!d.includes(y))}},b=new Set,O=()=>s.length===0||b.size===s.length;for(let h of a){let y=this.events.on(h,((...A)=>{p(),O()&&(c(h,...A),u&&p(!0))}));d.push(y)}for(let h of s){let y=this.events.on(h,((...A)=>{p(),b.add(h),O()&&(a.length===0||a.includes(h))&&(c(h,...A),u&&p(!0))}));d.push(y)}t.push(()=>p(!0))}return i}emit(e,...t){return this.emitterOptions.publicEmit?(this.events.emit(e,...t),!0):!1}unsubscribeAll(){for(let e of this.eventUnsubscribes)e();this.eventUnsubscribes=[]}};var
|
|
5
|
+
Has: ${c}`)}let l=a.encoded&&u.encodingEnabled()?await u.decodeData[1](a.data):a.data;a.formatVersion&&!isNaN(Number(a.formatVersion))&&Number(a.formatVersion)<u.formatVersion?await u.runMigrations(JSON.parse(l),Number(a.formatVersion),!1):await u.setData(JSON.parse(l))}}async deserialize(e){return this.deserializePartial(this.stores.map(t=>t.id),e)}async loadStoresData(e){return Promise.allSettled(this.getStoresFiltered(e).map(async t=>({id:t.id,data:await t.loadData()})))}async resetStoresData(e){return Promise.allSettled(this.getStoresFiltered(e).map(t=>t.saveDefaultData()))}async deleteStoresData(e){return Promise.allSettled(this.getStoresFiltered(e).map(t=>t.deleteData()))}static isSerializedDataStoreObjArray(e){return Array.isArray(e)&&e.every(t=>typeof t=="object"&&t!==null&&"id"in t&&"data"in t&&"formatVersion"in t&&"encoded"in t)}static isSerializedDataStoreObj(e){return typeof e=="object"&&e!==null&&"id"in e&&"data"in e&&"formatVersion"in e&&"encoded"in e}getStoresFiltered(e){return this.stores.filter(t=>typeof e>"u"?!0:Array.isArray(e)?e.includes(t.id):e(t.id))}};var X=()=>({emit(r,...e){for(let t=this.events[r]||[],i=0,n=t.length;i<n;i++)t[i](...e)},events:{},on(r,e){return(this.events[r]||=[]).push(e),()=>{var t;this.events[r]=(t=this.events[r])==null?void 0:t.filter(i=>e!==i)}}});var P=class{events=X();eventUnsubscribes=[];emitterOptions;constructor(e={}){this.emitterOptions={publicEmit:!1,...e}}on(e,t){let i,n=()=>{i&&(i(),this.eventUnsubscribes=this.eventUnsubscribes.filter(o=>o!==i))};return i=this.events.on(e,t),this.eventUnsubscribes.push(i),n}once(e,t){return new Promise(i=>{let n,o=((...a)=>{t==null||t(...a),n==null||n(),i(a)});n=this.events.on(e,o),this.eventUnsubscribes.push(n)})}onMulti(e){let t=[],i=()=>{for(let n of t)n();t.splice(0,t.length),this.eventUnsubscribes=this.eventUnsubscribes.filter(n=>!t.includes(n))};for(let n of Array.isArray(e)?e:[e]){let o={allOf:[],oneOf:[],once:!1,...n},{oneOf:a,allOf:s,once:u,signal:l,callback:c}=o;if(l!=null&&l.aborted)return i;if(a.length===0&&s.length===0)throw new TypeError("NanoEmitter.onMulti(): Either `oneOf` or `allOf` or both must be provided in the options");let d=[],p=(h=!1)=>{if(!(!(l!=null&&l.aborted)&&!h)){for(let y of d)y();d.splice(0,d.length),this.eventUnsubscribes=this.eventUnsubscribes.filter(y=>!d.includes(y))}},b=new Set,O=()=>s.length===0||b.size===s.length;for(let h of a){let y=this.events.on(h,((...A)=>{p(),O()&&(c(h,...A),u&&p(!0))}));d.push(y)}for(let h of s){let y=this.events.on(h,((...A)=>{p(),b.add(h),O()&&(a.length===0||a.includes(h))&&(c(h,...A),u&&p(!0))}));d.push(y)}t.push(()=>p(!0))}return i}emit(e,...t){return this.emitterOptions.publicEmit?(this.events.emit(e,...t),!0):!1}unsubscribeAll(){for(let e of this.eventUnsubscribes)e();this.eventUnsubscribes=[]}};var F=class extends P{constructor(t=200,i="immediate"){super();this.timeout=t;this.type=i}listeners=[];activeTimeout;queuedCall;addListener(t){this.listeners.push(t)}removeListener(t){let i=this.listeners.findIndex(n=>n===t);i!==-1&&this.listeners.splice(i,1)}removeAllListeners(){this.listeners=[]}getListeners(){return this.listeners}setTimeout(t){this.emit("change",this.timeout=t,this.type)}getTimeout(){return this.timeout}isTimeoutActive(){return typeof this.activeTimeout<"u"}setType(t){this.emit("change",this.timeout,this.type=t)}getType(){return this.type}call(...t){let i=(...o)=>{this.queuedCall=void 0,this.emit("call",...o),this.listeners.forEach(a=>a.call(this,...o))},n=()=>{this.activeTimeout=setTimeout(()=>{this.queuedCall?(this.queuedCall(),n()):this.activeTimeout=void 0},this.timeout)};switch(this.type){case"immediate":typeof this.activeTimeout>"u"?(i(...t),n()):this.queuedCall=()=>i(...t);break;case"idle":this.activeTimeout&&clearTimeout(this.activeTimeout),this.activeTimeout=setTimeout(()=>{i(...t),this.activeTimeout=void 0},this.timeout);break;default:throw new TypeError(`Invalid debouncer type: ${this.type}`)}}};function Ie(r,e=200,t="immediate"){let i=new F(e,t);i.addListener(r);let n=((...o)=>i.call(...o));return n.debouncer=i,n}
|
|
6
6
|
//# sourceMappingURL=CoreUtils.min.cjs.map
|
package/dist/CoreUtils.min.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
function G(r,e){return(r&e)===e}function D(r,e,t){return typeof t!="number"&&(t=e,e=0),Math.max(Math.min(r,t),e)}function Z(r,e=!0){if(r=Number(["string","number"].includes(typeof r)?r:String(r)),typeof r=="number"&&isNaN(r))return NaN;let[t,i]=r.toString().split("."),n=t==="0"?1:Math.floor(Math.log10(Math.abs(Number(t)))+1),o=e&&i?i.length:0;return n+o}function X(r,e,t){return r.toLocaleString(e,t==="short"?{notation:"compact",compactDisplay:"short",maximumFractionDigits:1}:{style:"decimal",maximumFractionDigits:0})}function
|
|
1
|
+
function G(r,e){return(r&e)===e}function D(r,e,t){return typeof t!="number"&&(t=e,e=0),Math.max(Math.min(r,t),e)}function Z(r,e=!0){if(r=Number(["string","number"].includes(typeof r)?r:String(r)),typeof r=="number"&&isNaN(r))return NaN;let[t,i]=r.toString().split("."),n=t==="0"?1:Math.floor(Math.log10(Math.abs(Number(t)))+1),o=e&&i?i.length:0;return n+o}function X(r,e,t){return r.toLocaleString(e,t==="short"?{notation:"compact",compactDisplay:"short",maximumFractionDigits:1}:{style:"decimal",maximumFractionDigits:0})}function N(r,e,t,i,n){return(typeof i>"u"||typeof n>"u")&&(n=t,t=e,i=e=0),Number(e)===0&&Number(i)===0?r*(n/t):(r-e)*((n-i)/(t-e))+i}function Y(r,e,t){let i=typeof t=="number"?e:0;if(t=typeof t=="number"?t:e,i>t)throw new RangeError(`Parameter "min" can't be bigger than "max"`);if(isNaN(r)||isNaN(i)||isNaN(t)||!isFinite(r)||!isFinite(i)||!isFinite(t))return NaN;if(r>=i&&r<=t)return r;let n=t-i+1;return((r-i)%n+n)%n+i}function S(...r){let e,t,i=!1;if(typeof r[0]=="number"&&typeof r[1]=="number")[e,t]=r;else if(typeof r[0]=="number"&&typeof r[1]!="number")e=0,[t]=r;else throw new TypeError(`Wrong parameter(s) provided - expected (number, boolean|undefined) or (number, number, boolean|undefined) but got (${r.map(n=>typeof n).join(", ")}) instead`);if(typeof r[2]=="boolean"?i=r[2]:typeof r[1]=="boolean"&&(i=r[1]),e=Number(e),t=Number(t),isNaN(e)||isNaN(t))return NaN;if(e>t)throw new TypeError(`Parameter "min" can't be bigger than "max"`);if(i){let n=new Uint8Array(1);return crypto.getRandomValues(n),Number(Array.from(n,o=>Math.round(N(o,0,255,e,t)).toString(10)).join(""))}else return Math.floor(Math.random()*(t-e+1))+e}function A(r,e){let t=10**e;return Math.round(r*t)/t}function ee(r,e,t=1,i=.5){return Math.abs(A(r,t)-A(e,t))<=i}function ie(r){return M(r)[0]}function M(r){if(r.length===0)return[void 0,void 0];let e=S(r.length-1);return[r[e],e]}function ne(r){let e=[...r];if(r.length===0)return e;for(let t=e.length-1;t>0;t--){let i=Math.floor(Math.random()*(t+1));[e[t],e[i]]=[e[i],e[t]]}return e}function ae(r){var e;return(e=K(r))==null?void 0:e[0]}function K(r){let[e,t]=M(r);return t===void 0?[void 0,void 0]:(r.splice(t,1),[e,t])}function L(r,e,t=!1){var l;r=r.trim();let i=(c,d,p,g)=>(c=Math.max(0,Math.min(255,c-c*g/100)),d=Math.max(0,Math.min(255,d-d*g/100)),p=Math.max(0,Math.min(255,p-p*g/100)),[c,d,p]),n,o,a,s,u=r.match(/^#?([0-9A-Fa-f]{3}|[0-9A-Fa-f]{4}|[0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})$/);if(u)[n,o,a,s]=J(r);else if(r.startsWith("rgb")){let c=(l=r.match(/\d+(\.\d+)?/g))==null?void 0:l.map(Number);if(!c)throw new TypeError("Invalid RGB/RGBA color format");[n,o,a,s]=c}else throw new TypeError("Unsupported color format");return[n,o,a]=i(n,o,a,e),u?q(n,o,a,s,r.startsWith("#"),t):r.startsWith("rgba")?`rgba(${n}, ${o}, ${a}, ${s??NaN})`:`rgb(${n}, ${o}, ${a})`}function J(r){r=(r.startsWith("#")?r.slice(1):r).trim();let e=r.length===8||r.length===4?parseInt(r.slice(-(r.length/4)),16)/(r.length===8?255:15):void 0;isNaN(Number(e))||(r=r.slice(0,-(r.length/4))),(r.length===3||r.length===4)&&(r=r.split("").map(a=>a+a).join(""));let t=parseInt(r,16),i=t>>16&255,n=t>>8&255,o=t&255;return[D(i,0,255),D(n,0,255),D(o,0,255),typeof e=="number"?D(e,0,1):void 0]}function ue(r,e,t=!1){return L(r,e*-1,t)}function q(r,e,t,i,n=!0,o=!1){let a=s=>D(Math.round(s),0,255).toString(16).padStart(2,"0")[o?"toUpperCase":"toLowerCase"]();return`${n?"#":""}${a(r)}${a(e)}${a(t)}${i?a(i*255):""}`}function H(r){return btoa(new Uint8Array(r).reduce((e,t)=>e+String.fromCharCode(t),""))}function W(r){return Uint8Array.from(atob(r),e=>e.charCodeAt(0))}async function I(r,e,t="string"){let i=r instanceof Uint8Array?r:new TextEncoder().encode((r==null?void 0:r.toString())??String(r)),n=new CompressionStream(e),o=n.writable.getWriter();o.write(i),o.close();let a=new Uint8Array(await new Response(n.readable).arrayBuffer());return t==="arrayBuffer"?a:H(a)}async function C(r,e,t="string"){let i=r instanceof Uint8Array?r:W((r==null?void 0:r.toString())??String(r)),n=new DecompressionStream(e),o=n.writable.getWriter();o.write(i),o.close();let a=new Uint8Array(await new Response(n.readable).arrayBuffer());return t==="arrayBuffer"?a:new TextDecoder().decode(a)}async function _(r,e="SHA-256"){let t;typeof r=="string"?t=new TextEncoder().encode(r):t=r;let i=await crypto.subtle.digest(e,t);return Array.from(new Uint8Array(i)).map(a=>a.toString(16).padStart(2,"0")).join("")}function de(r=16,e=16,t=!1,i=!0){if(r<1)throw new RangeError("The length argument must be at least 1");if(e<2||e>36)throw new RangeError("The radix argument must be between 2 and 36");let n=[],o=i?[0,1]:[0];if(t){let a=new Uint8Array(r);crypto.getRandomValues(a),n=Array.from(a,s=>N(s,0,255,0,e).toString(e).substring(0,1))}else n=Array.from({length:r},()=>Math.floor(Math.random()*e).toString(e));return n.some(a=>/[a-zA-Z]/.test(a))?n.map(a=>o[S(0,o.length-1,t)]===1?a.toUpperCase():a).join(""):n.join("")}var m=class extends Error{date;constructor(e,t){super(e,t),this.name=this.constructor.name,this.date=new Date}},v=class extends m{constructor(e,t){super(e,t),this.name="ChecksumMismatchError"}},w=class extends m{constructor(e,t,i){super(t,i),this.name=e}},x=class extends m{constructor(e,t){super(e,t),this.name="MigrationError"}},k=class extends m{constructor(e,t){super(e,t),this.name="ValidationError"}},b=class extends m{constructor(e,t){super(e,t),this.name="ScriptContextError"}},E=class extends m{constructor(e,t){super(e,t),this.name="NetworkError"}};async function he(r){return await(typeof r=="function"?r():r)}async function ge(r){return typeof r=="string"?r:String(typeof r=="function"?await r():r)}async function be(r,e={}){let{timeout:t=1e4,signal:i,...n}=e,o=new AbortController;i==null||i.addEventListener("abort",()=>o.abort());let a={},s;t>=0&&(s=setTimeout(()=>o.abort(),t),a={signal:o.signal});try{let u=await fetch(r,{...n,...a});return typeof s<"u"&&clearTimeout(s),u}catch(u){throw typeof s<"u"&&clearTimeout(s),new E("Error while calling fetch",{cause:u})}}function ye(r,e=!0){return"length"in r?r.length:"size"in r?r.size:"count"in r?r.count:e?0:NaN}function De(r,e,t=!1){return new Promise((i,n)=>{let o=setTimeout(()=>i(),r);e==null||e.addEventListener("abort",()=>{clearTimeout(o),t?n(new w("AbortError","The pause was aborted")):i()})})}function Te(r){return Object.assign(Object.create(null),r??{})}function Se(r,e,t){let i,n=()=>clearInterval(i),o=()=>{if(t!=null&&t.aborted)return n();r()};t==null||t.addEventListener("abort",n),o(),i=setInterval(o,e)}function ve(r,e,t){let i,n=()=>clearTimeout(i),o=async()=>{if(t!=null&&t.aborted)return n();await r(),i=setTimeout(o,e)};t==null||t.addEventListener("abort",n),o()}function we(r=0,e=0){if(e<0)throw new TypeError("Timeout must be a non-negative number");let t;if(typeof process<"u"&&"exit"in process&&typeof process.exit=="function")t=()=>process.exit(r);else if(typeof Deno<"u"&&"exit"in Deno&&typeof Deno.exit=="function")t=()=>Deno.exit(r);else throw new b("Cannot exit the process, no exit method available");setTimeout(t,e)}function xe(r,e=1/0){if(typeof e!="number"||isNaN(e)||e<0)throw new TypeError("lines parameter must be a non-negative number");try{throw new Error("This is to capture a stack trace with CoreUtils.getCallStack(). (If you see this somewhere, you can safely ignore it.)")}catch(t){let i=(t.stack??"").split(`
|
|
2
2
|
`).map(n=>n.trim()).slice(2,e+2);return r!==!1?i:i.join(`
|
|
3
|
-
`)}}function Pe(r,e,t="auto"){switch(typeof e!="number"&&("length"in e?e=e.length:"size"in e?e=e.size:"count"in e&&(e=e.count)),["-s","-ies"].includes(t)||(t="auto"),isNaN(e)&&(e=2),t==="auto"?String(r).endsWith("y")?"-ies":"-s":t){case"-s":return`${r}${e===1?"":"s"}`;case"-ies":return`${String(r).slice(0,-1)}${e===1?"y":"ies"}`}}function Oe(r){return r.charAt(0).toUpperCase()+r.slice(1)}var Q={100:"\u2588",75:"\u2593",50:"\u2592",25:"\u2591",0:"\u2500"};function Ve(r,e,t=Q){if(r===100)return t[100].repeat(e);let i=Math.floor(r/100*e),n=r/10*e-i,o="";n>=.75?o=t[75]:n>=.5?o=t[50]:n>=.25&&(o=t[25]);let a=t[100].repeat(i),s=t[0].repeat(e-i-(o?1:0));return`${a}${o}${s}`}function Fe(r,...e){return r.replace(/%\d/gm,t=>{var n;let i=Number(t.substring(1))-1;return(n=e[i]??t)==null?void 0:n.toString()})}function Ne(r,e=", ",t=" and "){let i=[...r];if(i.length===0)return"";if(i.length===1)return String(i[0]);if(i.length===2)return i.join(t);let n=t+i[i.length-1];return i.pop(),i.join(e)+n}function Ae(r){let e=r<0,t=Math.abs(r);if(isNaN(t)||!isFinite(t))throw new TypeError("The seconds argument must be a valid number");let i=Math.floor(t/3600),n=Math.floor(t%3600/60),o=Math.floor(t%60);return(e?"-":"")+[i?i+":":"",String(n).padStart(n>0||i>0?2:1,"0"),":",String(o).padStart(o>0||n>0||i>0||r===0?2:1,"0")].join("")}function Me(r,e,t="..."){let i=(r==null?void 0:r.toString())??String(r),n=i.length>e?i.substring(0,e-t.length)+t:i;return n.length>e?n.substring(0,e):n}var $=1,z=class{id;formatVersion;defaultData;encodeData;decodeData;compressionFormat="deflate-raw";memoryCache=!0;engine;options;firstInit=!0;cachedData;migrations;migrateIds=[];constructor(e){if(this.id=e.id,this.formatVersion=e.formatVersion,this.defaultData=e.defaultData,this.memoryCache=!!(e.memoryCache??!0),this.cachedData=this.memoryCache?e.defaultData:{},this.migrations=e.migrations,e.migrateIds&&(this.migrateIds=Array.isArray(e.migrateIds)?e.migrateIds:[e.migrateIds]),this.engine=typeof e.engine=="function"?e.engine():e.engine,this.options=e,"encodeData"in e&&"decodeData"in e&&Array.isArray(e.encodeData)&&Array.isArray(e.decodeData))this.encodeData=[e.encodeData[0],e.encodeData[1]],this.decodeData=[e.decodeData[0],e.decodeData[1]],this.compressionFormat=e.encodeData[0]??null;else if(e.compressionFormat===null)this.encodeData=void 0,this.decodeData=void 0,this.compressionFormat=null;else{let t=typeof e.compressionFormat=="string"?e.compressionFormat:"deflate-raw";this.compressionFormat=t,this.encodeData=[t,async i=>await I(i,t,"string")],this.decodeData=[t,async i=>await _(i,t,"string")]}this.engine.setDataStoreOptions({id:this.id,encodeData:this.encodeData,decodeData:this.decodeData})}async loadData(){try{if(this.firstInit){this.firstInit=!1;let u=Number(await this.engine.getValue("__ds_fmt_ver",0)),l=await this.engine.getValue(`_uucfg-${this.id}`,null);if(l){let c=Number(await this.engine.getValue(`_uucfgver-${this.id}`,NaN)),d=await this.engine.getValue(`_uucfgenc-${this.id}`,null),p=[],g=(T,h,y)=>{p.push(this.engine.setValue(h,y)),p.push(this.engine.deleteValue(T))};g(`_uucfg-${this.id}`,`__ds-${this.id}-dat`,l),isNaN(c)||g(`_uucfgver-${this.id}`,`__ds-${this.id}-ver`,c),typeof d=="boolean"||d==="true"||d==="false"||typeof d=="number"||d==="0"||d==="1"?g(`_uucfgenc-${this.id}`,`__ds-${this.id}-enf`,[0,"0",!0,"true"].includes(d)?this.compressionFormat??null:null):(p.push(this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)),p.push(this.engine.deleteValue(`_uucfgenc-${this.id}`))),await Promise.allSettled(p)}(isNaN(u)||u<$)&&await this.engine.setValue("__ds_fmt_ver",$)}this.migrateIds.length>0&&(await this.migrateId(this.migrateIds),this.migrateIds=[]);let e=await this.engine.getValue(`__ds-${this.id}-dat`,null),t=Number(await this.engine.getValue(`__ds-${this.id}-ver`,NaN));if(typeof e!="string")return await this.saveDefaultData(),this.engine.deepCopy(this.defaultData);let i=e??JSON.stringify(this.defaultData),n=String(await this.engine.getValue(`__ds-${this.id}-enf`,null)),o=n!=="null"&&n!=="false"&&n!=="0"&&n!==""&&n!==null,a=!1;isNaN(t)&&(await this.engine.setValue(`__ds-${this.id}-ver`,t=this.formatVersion),a=!0);let s=await this.engine.deserializeData(i,o);return t<this.formatVersion&&this.migrations&&(s=await this.runMigrations(s,t)),a&&await this.setData(s),this.memoryCache?this.cachedData=this.engine.deepCopy(s):this.engine.deepCopy(s)}catch(e){return console.warn("Error while parsing JSON data, resetting it to the default value.",e),await this.saveDefaultData(),this.defaultData}}getData(){if(!this.memoryCache)throw new m("In-memory cache is disabled for this DataStore instance, so getData() can't be used. Please use loadData() instead.");return this.engine.deepCopy(this.cachedData)}setData(e){return this.memoryCache&&(this.cachedData=e),new Promise(async t=>{await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(e,this.encodingEnabled())),this.engine.setValue(`__ds-${this.id}-ver`,this.formatVersion),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)]),t()})}async saveDefaultData(){this.memoryCache&&(this.cachedData=this.defaultData),await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(this.defaultData,this.encodingEnabled())),this.engine.setValue(`__ds-${this.id}-ver`,this.formatVersion),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)])}async deleteData(){var e,t;await Promise.allSettled([this.engine.deleteValue(`__ds-${this.id}-dat`),this.engine.deleteValue(`__ds-${this.id}-ver`),this.engine.deleteValue(`__ds-${this.id}-enf`)]),await((t=(e=this.engine).deleteStorage)==null?void 0:t.call(e))}encodingEnabled(){return!!(this.encodeData&&this.decodeData)&&this.compressionFormat!==null||!!this.compressionFormat}async runMigrations(e,t,i=!0){if(!this.migrations)return e;let n=e,o=Object.entries(this.migrations).sort(([s],[u])=>Number(s)-Number(u)),a=t;for(let[s,u]of o){let l=Number(s);if(t<this.formatVersion&&t<l)try{let c=u(n);n=c instanceof Promise?await c:c,a=t=l}catch(c){if(!i)throw new x(`Error while running migration function for format version '${s}'`,{cause:c});return await this.saveDefaultData(),this.getData()}}return await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(n,this.encodingEnabled())),this.engine.setValue(`__ds-${this.id}-ver`,a),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)]),this.memoryCache?this.cachedData=this.engine.deepCopy(n):this.engine.deepCopy(n)}async migrateId(e){let t=Array.isArray(e)?e:[e];await Promise.all(t.map(async i=>{let[n,o,a]=await(async()=>{let[u,l,c]=await Promise.all([this.engine.getValue(`__ds-${i}-dat`,JSON.stringify(this.defaultData)),this.engine.getValue(`__ds-${i}-ver`,NaN),this.engine.getValue(`__ds-${i}-enf`,null)]);return[u,Number(l),!!c&&String(c)!=="null"]})();if(n===void 0||isNaN(o))return;let s=await this.engine.deserializeData(n,a);await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(s,this.encodingEnabled())),this.engine.setValue(`__ds-${this.id}-ver`,o),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat),this.engine.deleteValue(`__ds-${i}-dat`),this.engine.deleteValue(`__ds-${i}-ver`),this.engine.deleteValue(`__ds-${i}-enf`)])}))}};var P=class{dataStoreOptions;constructor(e){e&&(this.dataStoreOptions=e)}setDataStoreOptions(e){this.dataStoreOptions=e}async serializeData(e,t){var o,a,s,u,l;this.ensureDataStoreOptions();let i=JSON.stringify(e);if(!t||!((o=this.dataStoreOptions)!=null&&o.encodeData)||!((a=this.dataStoreOptions)!=null&&a.decodeData))return i;let n=(l=(u=(s=this.dataStoreOptions)==null?void 0:s.encodeData)==null?void 0:u[1])==null?void 0:l.call(u,i);return n instanceof Promise?await n:n}async deserializeData(e,t){var n,o,a;this.ensureDataStoreOptions();let i=(n=this.dataStoreOptions)!=null&&n.decodeData&&t?(a=(o=this.dataStoreOptions.decodeData)==null?void 0:o[1])==null?void 0:a.call(o,e):void 0;return i instanceof Promise&&(i=await i),JSON.parse(i??e)}ensureDataStoreOptions(){if(!this.dataStoreOptions)throw new m("DataStoreEngine must be initialized with DataStore options before use. If you are using this instance standalone, set them in the constructor or call `setDataStoreOptions()` with the DataStore options.");if(!this.dataStoreOptions.id)throw new m("DataStoreEngine must be initialized with a valid DataStore ID")}deepCopy(e){try{if("structuredClone"in globalThis)return structuredClone(e)}catch{}return JSON.parse(JSON.stringify(e))}},U=class extends P{options;constructor(e){super(e==null?void 0:e.dataStoreOptions),this.options={type:"localStorage",...e}}async getValue(e,t){let i=this.options.type==="localStorage"?globalThis.localStorage.getItem(e):globalThis.sessionStorage.getItem(e);return typeof i>"u"?t:i}async setValue(e,t){this.options.type==="localStorage"?globalThis.localStorage.setItem(e,String(t)):globalThis.sessionStorage.setItem(e,String(t))}async deleteValue(e){this.options.type==="localStorage"?globalThis.localStorage.removeItem(e):globalThis.sessionStorage.removeItem(e)}},f,R=class extends P{options;fileAccessQueue=Promise.resolve();constructor(e){super(e==null?void 0:e.dataStoreOptions),this.options={filePath:t=>`.ds-${t}`,...e}}async readFile(){var e,t,i,n;this.ensureDataStoreOptions();try{if(f||(f=(e=await import("fs/promises"))==null?void 0:e.default),!f)throw new b("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new m("'node:fs/promises' module not available")});let o=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id),a=await f.readFile(o,"utf-8");return a?JSON.parse(await((n=(i=(t=this.dataStoreOptions)==null?void 0:t.decodeData)==null?void 0:i[1])==null?void 0:n.call(i,a))??a):void 0}catch{return}}async writeFile(e){var t,i,n,o;this.ensureDataStoreOptions();try{if(f||(f=(t=await import("fs/promises"))==null?void 0:t.default),!f)throw new b("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new m("'node:fs/promises' module not available")});let a=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id);await f.mkdir(a.slice(0,a.lastIndexOf(a.includes("/")?"/":"\\")),{recursive:!0}),await f.writeFile(a,await((o=(n=(i=this.dataStoreOptions)==null?void 0:i.encodeData)==null?void 0:n[1])==null?void 0:o.call(n,JSON.stringify(e)))??JSON.stringify(e,void 0,2),"utf-8")}catch(a){console.error("Error writing file:",a)}}async getValue(e,t){let i=await this.readFile();if(!i)return t;let n=i==null?void 0:i[e];return typeof n>"u"?t:n}async setValue(e,t){this.fileAccessQueue=this.fileAccessQueue.then(async()=>{let i=await this.readFile();i||(i={}),i[e]=t,await this.writeFile(i)}).catch(i=>{throw console.error("Error in setValue:",i),i}),await this.fileAccessQueue.catch(()=>{})}async deleteValue(e){this.fileAccessQueue=this.fileAccessQueue.then(async()=>{let t=await this.readFile();t&&(delete t[e],await this.writeFile(t))}).catch(t=>{throw console.error("Error in deleteValue:",t),t}),await this.fileAccessQueue.catch(()=>{})}async deleteStorage(){var e;this.ensureDataStoreOptions();try{if(f||(f=(e=await import("fs/promises"))==null?void 0:e.default),!f)throw new b("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new m("'node:fs/promises' module not available")});let t=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id);return await f.unlink(t)}catch(t){console.error("Error deleting file:",t)}}};var j=class r{stores;options;constructor(e,t={}){if(!crypto||!crypto.subtle)throw new b("DataStoreSerializer has to run in a secure context (HTTPS) or in another environment that implements the subtleCrypto API!");this.stores=e,this.options={addChecksum:!0,ensureIntegrity:!0,remapIds:{},...t}}async calcChecksum(e){return C(e,"SHA-256")}async serializePartial(e,t=!0,i=!0){var a;let n=[],o=this.stores.filter(s=>typeof e=="function"?e(s.id):e.includes(s.id));for(let s of o){let u=!!(t&&s.encodingEnabled()&&((a=s.encodeData)!=null&&a[1])),l=s.memoryCache?s.getData():await s.loadData(),c=u?await s.encodeData[1](JSON.stringify(l)):JSON.stringify(l);n.push({id:s.id,data:c,formatVersion:s.formatVersion,encoded:u,checksum:this.options.addChecksum?await this.calcChecksum(c):void 0})}return i?JSON.stringify(n):n}async serialize(e=!0,t=!0){return this.serializePartial(this.stores.map(i=>i.id),e,t)}async deserializePartial(e,t){let i=typeof t=="string"?JSON.parse(t):t;if(!Array.isArray(i)||!i.every(r.isSerializedDataStoreObj))throw new TypeError("Invalid serialized data format! Expected an array of SerializedDataStore objects.");let n=a=>{var s;return((s=Object.entries(this.options.remapIds).find(([,u])=>u.includes(a)))==null?void 0:s[0])??a},o=a=>typeof e=="function"?e(a):e.includes(a);for(let a of i){let s=n(a.id);if(!o(s))continue;let u=this.stores.find(c=>c.id===s);if(!u)throw new m(`Can't deserialize data because no DataStore instance with the ID "${s}" was found! Make sure to provide it in the DataStoreSerializer constructor.`);if(this.options.ensureIntegrity&&typeof a.checksum=="string"){let c=await this.calcChecksum(a.data);if(c!==a.checksum)throw new v(`Checksum mismatch for DataStore with ID "${a.id}"!
|
|
3
|
+
`)}}function Pe(r,e,t="auto"){switch(typeof e!="number"&&("length"in e?e=e.length:"size"in e?e=e.size:"count"in e&&(e=e.count)),["-s","-ies"].includes(t)||(t="auto"),isNaN(e)&&(e=2),t==="auto"?String(r).endsWith("y")?"-ies":"-s":t){case"-s":return`${r}${e===1?"":"s"}`;case"-ies":return`${String(r).slice(0,-1)}${e===1?"y":"ies"}`}}function Oe(r){return r.charAt(0).toUpperCase()+r.slice(1)}var Q={100:"\u2588",75:"\u2593",50:"\u2592",25:"\u2591",0:"\u2500"};function Ve(r,e,t=Q){if(r===100)return t[100].repeat(e);let i=Math.floor(r/100*e),n=r/10*e-i,o="";n>=.75?o=t[75]:n>=.5?o=t[50]:n>=.25&&(o=t[25]);let a=t[100].repeat(i),s=t[0].repeat(e-i-(o?1:0));return`${a}${o}${s}`}function Ne(r,...e){return r.replace(/%\d/gm,t=>{var n;let i=Number(t.substring(1))-1;return(n=e[i]??t)==null?void 0:n.toString()})}function Fe(r,e=", ",t=" and "){let i=[...r];if(i.length===0)return"";if(i.length===1)return String(i[0]);if(i.length===2)return i.join(t);let n=t+i[i.length-1];return i.pop(),i.join(e)+n}function Ae(r){let e=r<0,t=Math.abs(r);if(isNaN(t)||!isFinite(t))throw new TypeError("The seconds argument must be a valid number");let i=Math.floor(t/3600),n=Math.floor(t%3600/60),o=Math.floor(t%60);return(e?"-":"")+[i?i+":":"",String(n).padStart(n>0||i>0?2:1,"0"),":",String(o).padStart(o>0||n>0||i>0||r===0?2:1,"0")].join("")}function Me(r,e,t="..."){let i=(r==null?void 0:r.toString())??String(r),n=i.length>e?i.substring(0,e-t.length)+t:i;return n.length>e?n.substring(0,e):n}var $=1,z=class{id;formatVersion;defaultData;encodeData;decodeData;compressionFormat="deflate-raw";memoryCache;engine;options;firstInit=!0;cachedData;migrations;migrateIds=[];constructor(e){if(this.id=e.id,this.formatVersion=e.formatVersion,this.defaultData=e.defaultData,this.memoryCache=e.memoryCache??!0,this.cachedData=this.memoryCache?e.defaultData:{},this.migrations=e.migrations,e.migrateIds&&(this.migrateIds=Array.isArray(e.migrateIds)?e.migrateIds:[e.migrateIds]),this.engine=typeof e.engine=="function"?e.engine():e.engine,this.options=e,"encodeData"in e&&"decodeData"in e&&Array.isArray(e.encodeData)&&Array.isArray(e.decodeData))this.encodeData=[e.encodeData[0],e.encodeData[1]],this.decodeData=[e.decodeData[0],e.decodeData[1]],this.compressionFormat=e.encodeData[0]??null;else if(e.compressionFormat===null)this.encodeData=void 0,this.decodeData=void 0,this.compressionFormat=null;else{let t=typeof e.compressionFormat=="string"?e.compressionFormat:"deflate-raw";this.compressionFormat=t,this.encodeData=[t,async i=>await I(i,t,"string")],this.decodeData=[t,async i=>await C(i,t,"string")]}this.engine.setDataStoreOptions({id:this.id,encodeData:this.encodeData,decodeData:this.decodeData})}async loadData(){try{if(this.firstInit){this.firstInit=!1;let u=Number(await this.engine.getValue("__ds_fmt_ver",0)),l=await this.engine.getValue(`_uucfg-${this.id}`,null);if(l){let c=Number(await this.engine.getValue(`_uucfgver-${this.id}`,NaN)),d=await this.engine.getValue(`_uucfgenc-${this.id}`,null),p=[],g=(T,h,y)=>{p.push(this.engine.setValue(h,y)),p.push(this.engine.deleteValue(T))};g(`_uucfg-${this.id}`,`__ds-${this.id}-dat`,l),isNaN(c)||g(`_uucfgver-${this.id}`,`__ds-${this.id}-ver`,c),typeof d=="boolean"||d==="true"||d==="false"||typeof d=="number"||d==="0"||d==="1"?g(`_uucfgenc-${this.id}`,`__ds-${this.id}-enf`,[0,"0",!0,"true"].includes(d)?this.compressionFormat??null:null):(p.push(this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)),p.push(this.engine.deleteValue(`_uucfgenc-${this.id}`))),await Promise.allSettled(p)}(isNaN(u)||u<$)&&await this.engine.setValue("__ds_fmt_ver",$)}this.migrateIds.length>0&&(await this.migrateId(this.migrateIds),this.migrateIds=[]);let e=await this.engine.getValue(`__ds-${this.id}-dat`,null),t=Number(await this.engine.getValue(`__ds-${this.id}-ver`,NaN));if(typeof e!="string")return await this.saveDefaultData(),this.engine.deepCopy(this.defaultData);let i=e??JSON.stringify(this.defaultData),n=String(await this.engine.getValue(`__ds-${this.id}-enf`,null)),o=n!=="null"&&n!=="false"&&n!=="0"&&n!==""&&n!==null,a=!1;isNaN(t)&&(await this.engine.setValue(`__ds-${this.id}-ver`,t=this.formatVersion),a=!0);let s=await this.engine.deserializeData(i,o);return t<this.formatVersion&&this.migrations&&(s=await this.runMigrations(s,t)),a&&await this.setData(s),this.memoryCache?this.cachedData=this.engine.deepCopy(s):this.engine.deepCopy(s)}catch(e){return console.warn("Error while parsing JSON data, resetting it to the default value.",e),await this.saveDefaultData(),this.defaultData}}getData(){if(!this.memoryCache)throw new m("In-memory cache is disabled for this DataStore instance, so getData() can't be used. Please use loadData() instead.");return this.engine.deepCopy(this.cachedData)}setData(e){return this.memoryCache&&(this.cachedData=e),new Promise(async t=>{await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(e,this.encodingEnabled())),this.engine.setValue(`__ds-${this.id}-ver`,this.formatVersion),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)]),t()})}async saveDefaultData(){this.memoryCache&&(this.cachedData=this.defaultData),await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(this.defaultData,this.encodingEnabled())),this.engine.setValue(`__ds-${this.id}-ver`,this.formatVersion),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)])}async deleteData(){var e,t;await Promise.allSettled([this.engine.deleteValue(`__ds-${this.id}-dat`),this.engine.deleteValue(`__ds-${this.id}-ver`),this.engine.deleteValue(`__ds-${this.id}-enf`)]),await((t=(e=this.engine).deleteStorage)==null?void 0:t.call(e))}encodingEnabled(){return!!(this.encodeData&&this.decodeData)&&this.compressionFormat!==null||!!this.compressionFormat}async runMigrations(e,t,i=!0){if(!this.migrations)return e;let n=e,o=Object.entries(this.migrations).sort(([s],[u])=>Number(s)-Number(u)),a=t;for(let[s,u]of o){let l=Number(s);if(t<this.formatVersion&&t<l)try{let c=u(n);n=c instanceof Promise?await c:c,a=t=l}catch(c){if(!i)throw new x(`Error while running migration function for format version '${s}'`,{cause:c});return await this.saveDefaultData(),this.engine.deepCopy(this.defaultData)}}return await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(n,this.encodingEnabled())),this.engine.setValue(`__ds-${this.id}-ver`,a),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)]),this.memoryCache?this.cachedData=this.engine.deepCopy(n):this.engine.deepCopy(n)}async migrateId(e){let t=Array.isArray(e)?e:[e];await Promise.all(t.map(async i=>{let[n,o,a]=await(async()=>{let[u,l,c]=await Promise.all([this.engine.getValue(`__ds-${i}-dat`,JSON.stringify(this.defaultData)),this.engine.getValue(`__ds-${i}-ver`,NaN),this.engine.getValue(`__ds-${i}-enf`,null)]);return[u,Number(l),!!c&&String(c)!=="null"]})();if(n===void 0||isNaN(o))return;let s=await this.engine.deserializeData(n,a);await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(s,this.encodingEnabled())),this.engine.setValue(`__ds-${this.id}-ver`,o),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat),this.engine.deleteValue(`__ds-${i}-dat`),this.engine.deleteValue(`__ds-${i}-ver`),this.engine.deleteValue(`__ds-${i}-enf`)])}))}};var P=class{dataStoreOptions;constructor(e){e&&(this.dataStoreOptions=e)}setDataStoreOptions(e){this.dataStoreOptions=e}async serializeData(e,t){var o,a,s,u,l;this.ensureDataStoreOptions();let i=JSON.stringify(e);if(!t||!((o=this.dataStoreOptions)!=null&&o.encodeData)||!((a=this.dataStoreOptions)!=null&&a.decodeData))return i;let n=(l=(u=(s=this.dataStoreOptions)==null?void 0:s.encodeData)==null?void 0:u[1])==null?void 0:l.call(u,i);return n instanceof Promise?await n:n}async deserializeData(e,t){var n,o,a;this.ensureDataStoreOptions();let i=(n=this.dataStoreOptions)!=null&&n.decodeData&&t?(a=(o=this.dataStoreOptions.decodeData)==null?void 0:o[1])==null?void 0:a.call(o,e):void 0;return i instanceof Promise&&(i=await i),JSON.parse(i??e)}ensureDataStoreOptions(){if(!this.dataStoreOptions)throw new m("DataStoreEngine must be initialized with DataStore options before use. If you are using this instance standalone, set them in the constructor or call `setDataStoreOptions()` with the DataStore options.");if(!this.dataStoreOptions.id)throw new m("DataStoreEngine must be initialized with a valid DataStore ID")}deepCopy(e){try{if("structuredClone"in globalThis)return structuredClone(e)}catch{}return JSON.parse(JSON.stringify(e))}},U=class extends P{options;constructor(e){super(e==null?void 0:e.dataStoreOptions),this.options={type:"localStorage",...e}}async getValue(e,t){let i=this.options.type==="localStorage"?globalThis.localStorage.getItem(e):globalThis.sessionStorage.getItem(e);return typeof i>"u"?t:i}async setValue(e,t){this.options.type==="localStorage"?globalThis.localStorage.setItem(e,String(t)):globalThis.sessionStorage.setItem(e,String(t))}async deleteValue(e){this.options.type==="localStorage"?globalThis.localStorage.removeItem(e):globalThis.sessionStorage.removeItem(e)}},f,R=class extends P{options;fileAccessQueue=Promise.resolve();constructor(e){super(e==null?void 0:e.dataStoreOptions),this.options={filePath:t=>`.ds-${t}`,...e}}async readFile(){var e,t,i,n;this.ensureDataStoreOptions();try{if(f||(f=(e=await import("fs/promises"))==null?void 0:e.default),!f)throw new b("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new m("'node:fs/promises' module not available")});let o=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id),a=await f.readFile(o,"utf-8");return a?JSON.parse(await((n=(i=(t=this.dataStoreOptions)==null?void 0:t.decodeData)==null?void 0:i[1])==null?void 0:n.call(i,a))??a):void 0}catch{return}}async writeFile(e){var t,i,n,o;this.ensureDataStoreOptions();try{if(f||(f=(t=await import("fs/promises"))==null?void 0:t.default),!f)throw new b("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new m("'node:fs/promises' module not available")});let a=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id);await f.mkdir(a.slice(0,a.lastIndexOf(a.includes("/")?"/":"\\")),{recursive:!0}),await f.writeFile(a,await((o=(n=(i=this.dataStoreOptions)==null?void 0:i.encodeData)==null?void 0:n[1])==null?void 0:o.call(n,JSON.stringify(e)))??JSON.stringify(e,void 0,2),"utf-8")}catch(a){console.error("Error writing file:",a)}}async getValue(e,t){let i=await this.readFile();if(!i)return t;let n=i==null?void 0:i[e];if(typeof n>"u")return t;if(typeof t=="string")return typeof n=="object"&&n!==null?JSON.stringify(n):typeof n=="string"?n:String(n);if(typeof n=="string")try{return JSON.parse(n)}catch{return t}return n}async setValue(e,t){this.fileAccessQueue=this.fileAccessQueue.then(async()=>{let i=await this.readFile();i||(i={});let n=t;if(typeof t=="string")try{if(t.startsWith("{")||t.startsWith("[")){let o=JSON.parse(t);typeof o=="object"&&o!==null&&(n=o)}}catch{}i[e]=n,await this.writeFile(i)}).catch(i=>{throw console.error("Error in setValue:",i),i}),await this.fileAccessQueue.catch(()=>{})}async deleteValue(e){this.fileAccessQueue=this.fileAccessQueue.then(async()=>{let t=await this.readFile();t&&(delete t[e],await this.writeFile(t))}).catch(t=>{throw console.error("Error in deleteValue:",t),t}),await this.fileAccessQueue.catch(()=>{})}async deleteStorage(){var e;this.ensureDataStoreOptions();try{if(f||(f=(e=await import("fs/promises"))==null?void 0:e.default),!f)throw new b("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new m("'node:fs/promises' module not available")});let t=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id);return await f.unlink(t)}catch(t){console.error("Error deleting file:",t)}}};var j=class r{stores;options;constructor(e,t={}){if(!crypto||!crypto.subtle)throw new b("DataStoreSerializer has to run in a secure context (HTTPS) or in another environment that implements the subtleCrypto API!");this.stores=e,this.options={addChecksum:!0,ensureIntegrity:!0,remapIds:{},...t}}async calcChecksum(e){return _(e,"SHA-256")}async serializePartial(e,t=!0,i=!0){var a;let n=[],o=this.stores.filter(s=>typeof e=="function"?e(s.id):e.includes(s.id));for(let s of o){let u=!!(t&&s.encodingEnabled()&&((a=s.encodeData)!=null&&a[1])),l=s.memoryCache?s.getData():await s.loadData(),c=u?await s.encodeData[1](JSON.stringify(l)):JSON.stringify(l);n.push({id:s.id,data:c,formatVersion:s.formatVersion,encoded:u,checksum:this.options.addChecksum?await this.calcChecksum(c):void 0})}return i?JSON.stringify(n):n}async serialize(e=!0,t=!0){return this.serializePartial(this.stores.map(i=>i.id),e,t)}async deserializePartial(e,t){let i=typeof t=="string"?JSON.parse(t):t;if(!Array.isArray(i)||!i.every(r.isSerializedDataStoreObj))throw new TypeError("Invalid serialized data format! Expected an array of SerializedDataStore objects.");let n=a=>{var s;return((s=Object.entries(this.options.remapIds).find(([,u])=>u.includes(a)))==null?void 0:s[0])??a},o=a=>typeof e=="function"?e(a):e.includes(a);for(let a of i){let s=n(a.id);if(!o(s))continue;let u=this.stores.find(c=>c.id===s);if(!u)throw new m(`Can't deserialize data because no DataStore instance with the ID "${s}" was found! Make sure to provide it in the DataStoreSerializer constructor.`);if(this.options.ensureIntegrity&&typeof a.checksum=="string"){let c=await this.calcChecksum(a.data);if(c!==a.checksum)throw new v(`Checksum mismatch for DataStore with ID "${a.id}"!
|
|
4
4
|
Expected: ${a.checksum}
|
|
5
|
-
Has: ${c}`)}let l=a.encoded&&u.encodingEnabled()?await u.decodeData[1](a.data):a.data;a.formatVersion&&!isNaN(Number(a.formatVersion))&&Number(a.formatVersion)<u.formatVersion?await u.runMigrations(JSON.parse(l),Number(a.formatVersion),!1):await u.setData(JSON.parse(l))}}async deserialize(e){return this.deserializePartial(this.stores.map(t=>t.id),e)}async loadStoresData(e){return Promise.allSettled(this.getStoresFiltered(e).map(async t=>({id:t.id,data:await t.loadData()})))}async resetStoresData(e){return Promise.allSettled(this.getStoresFiltered(e).map(t=>t.saveDefaultData()))}async deleteStoresData(e){return Promise.allSettled(this.getStoresFiltered(e).map(t=>t.deleteData()))}static isSerializedDataStoreObjArray(e){return Array.isArray(e)&&e.every(t=>typeof t=="object"&&t!==null&&"id"in t&&"data"in t&&"formatVersion"in t&&"encoded"in t)}static isSerializedDataStoreObj(e){return typeof e=="object"&&e!==null&&"id"in e&&"data"in e&&"formatVersion"in e&&"encoded"in e}getStoresFiltered(e){return this.stores.filter(t=>typeof e>"u"?!0:Array.isArray(e)?e.includes(t.id):e(t.id))}};var B=()=>({emit(r,...e){for(let t=this.events[r]||[],i=0,n=t.length;i<n;i++)t[i](...e)},events:{},on(r,e){return(this.events[r]||=[]).push(e),()=>{var t;this.events[r]=(t=this.events[r])==null?void 0:t.filter(i=>e!==i)}}});var O=class{events=B();eventUnsubscribes=[];emitterOptions;constructor(e={}){this.emitterOptions={publicEmit:!1,...e}}on(e,t){let i,n=()=>{i&&(i(),this.eventUnsubscribes=this.eventUnsubscribes.filter(o=>o!==i))};return i=this.events.on(e,t),this.eventUnsubscribes.push(i),n}once(e,t){return new Promise(i=>{let n,o=((...a)=>{t==null||t(...a),n==null||n(),i(a)});n=this.events.on(e,o),this.eventUnsubscribes.push(n)})}onMulti(e){let t=[],i=()=>{for(let n of t)n();t.splice(0,t.length),this.eventUnsubscribes=this.eventUnsubscribes.filter(n=>!t.includes(n))};for(let n of Array.isArray(e)?e:[e]){let o={allOf:[],oneOf:[],once:!1,...n},{oneOf:a,allOf:s,once:u,signal:l,callback:c}=o;if(l!=null&&l.aborted)return i;if(a.length===0&&s.length===0)throw new TypeError("NanoEmitter.onMulti(): Either `oneOf` or `allOf` or both must be provided in the options");let d=[],p=(h=!1)=>{if(!(!(l!=null&&l.aborted)&&!h)){for(let y of d)y();d.splice(0,d.length),this.eventUnsubscribes=this.eventUnsubscribes.filter(y=>!d.includes(y))}},g=new Set,T=()=>s.length===0||g.size===s.length;for(let h of a){let y=this.events.on(h,((...V)=>{p(),T()&&(c(h,...V),u&&p(!0))}));d.push(y)}for(let h of s){let y=this.events.on(h,((...V)=>{p(),g.add(h),T()&&(a.length===0||a.includes(h))&&(c(h,...V),u&&p(!0))}));d.push(y)}t.push(()=>p(!0))}return i}emit(e,...t){return this.emitterOptions.publicEmit?(this.events.emit(e,...t),!0):!1}unsubscribeAll(){for(let e of this.eventUnsubscribes)e();this.eventUnsubscribes=[]}};var
|
|
5
|
+
Has: ${c}`)}let l=a.encoded&&u.encodingEnabled()?await u.decodeData[1](a.data):a.data;a.formatVersion&&!isNaN(Number(a.formatVersion))&&Number(a.formatVersion)<u.formatVersion?await u.runMigrations(JSON.parse(l),Number(a.formatVersion),!1):await u.setData(JSON.parse(l))}}async deserialize(e){return this.deserializePartial(this.stores.map(t=>t.id),e)}async loadStoresData(e){return Promise.allSettled(this.getStoresFiltered(e).map(async t=>({id:t.id,data:await t.loadData()})))}async resetStoresData(e){return Promise.allSettled(this.getStoresFiltered(e).map(t=>t.saveDefaultData()))}async deleteStoresData(e){return Promise.allSettled(this.getStoresFiltered(e).map(t=>t.deleteData()))}static isSerializedDataStoreObjArray(e){return Array.isArray(e)&&e.every(t=>typeof t=="object"&&t!==null&&"id"in t&&"data"in t&&"formatVersion"in t&&"encoded"in t)}static isSerializedDataStoreObj(e){return typeof e=="object"&&e!==null&&"id"in e&&"data"in e&&"formatVersion"in e&&"encoded"in e}getStoresFiltered(e){return this.stores.filter(t=>typeof e>"u"?!0:Array.isArray(e)?e.includes(t.id):e(t.id))}};var B=()=>({emit(r,...e){for(let t=this.events[r]||[],i=0,n=t.length;i<n;i++)t[i](...e)},events:{},on(r,e){return(this.events[r]||=[]).push(e),()=>{var t;this.events[r]=(t=this.events[r])==null?void 0:t.filter(i=>e!==i)}}});var O=class{events=B();eventUnsubscribes=[];emitterOptions;constructor(e={}){this.emitterOptions={publicEmit:!1,...e}}on(e,t){let i,n=()=>{i&&(i(),this.eventUnsubscribes=this.eventUnsubscribes.filter(o=>o!==i))};return i=this.events.on(e,t),this.eventUnsubscribes.push(i),n}once(e,t){return new Promise(i=>{let n,o=((...a)=>{t==null||t(...a),n==null||n(),i(a)});n=this.events.on(e,o),this.eventUnsubscribes.push(n)})}onMulti(e){let t=[],i=()=>{for(let n of t)n();t.splice(0,t.length),this.eventUnsubscribes=this.eventUnsubscribes.filter(n=>!t.includes(n))};for(let n of Array.isArray(e)?e:[e]){let o={allOf:[],oneOf:[],once:!1,...n},{oneOf:a,allOf:s,once:u,signal:l,callback:c}=o;if(l!=null&&l.aborted)return i;if(a.length===0&&s.length===0)throw new TypeError("NanoEmitter.onMulti(): Either `oneOf` or `allOf` or both must be provided in the options");let d=[],p=(h=!1)=>{if(!(!(l!=null&&l.aborted)&&!h)){for(let y of d)y();d.splice(0,d.length),this.eventUnsubscribes=this.eventUnsubscribes.filter(y=>!d.includes(y))}},g=new Set,T=()=>s.length===0||g.size===s.length;for(let h of a){let y=this.events.on(h,((...V)=>{p(),T()&&(c(h,...V),u&&p(!0))}));d.push(y)}for(let h of s){let y=this.events.on(h,((...V)=>{p(),g.add(h),T()&&(a.length===0||a.includes(h))&&(c(h,...V),u&&p(!0))}));d.push(y)}t.push(()=>p(!0))}return i}emit(e,...t){return this.emitterOptions.publicEmit?(this.events.emit(e,...t),!0):!1}unsubscribeAll(){for(let e of this.eventUnsubscribes)e();this.eventUnsubscribes=[]}};var F=class extends O{constructor(t=200,i="immediate"){super();this.timeout=t;this.type=i}listeners=[];activeTimeout;queuedCall;addListener(t){this.listeners.push(t)}removeListener(t){let i=this.listeners.findIndex(n=>n===t);i!==-1&&this.listeners.splice(i,1)}removeAllListeners(){this.listeners=[]}getListeners(){return this.listeners}setTimeout(t){this.emit("change",this.timeout=t,this.type)}getTimeout(){return this.timeout}isTimeoutActive(){return typeof this.activeTimeout<"u"}setType(t){this.emit("change",this.timeout,this.type=t)}getType(){return this.type}call(...t){let i=(...o)=>{this.queuedCall=void 0,this.emit("call",...o),this.listeners.forEach(a=>a.call(this,...o))},n=()=>{this.activeTimeout=setTimeout(()=>{this.queuedCall?(this.queuedCall(),n()):this.activeTimeout=void 0},this.timeout)};switch(this.type){case"immediate":typeof this.activeTimeout>"u"?(i(...t),n()):this.queuedCall=()=>i(...t);break;case"idle":this.activeTimeout&&clearTimeout(this.activeTimeout),this.activeTimeout=setTimeout(()=>{i(...t),this.activeTimeout=void 0},this.timeout);break;default:throw new TypeError(`Invalid debouncer type: ${this.type}`)}}};function qe(r,e=200,t="immediate"){let i=new F(e,t);i.addListener(r);let n=((...o)=>i.call(...o));return n.debouncer=i,n}export{U as BrowserStorageEngine,v as ChecksumMismatchError,w as CustomError,z as DataStore,P as DataStoreEngine,j as DataStoreSerializer,m as DatedError,F as Debouncer,R as FileStorageEngine,x as MigrationError,O as NanoEmitter,E as NetworkError,b as ScriptContextError,k as ValidationError,H as abtoa,W as atoab,Pe as autoPlural,G as bitSetHas,Oe as capitalize,D as clamp,I as compress,_ as computeHash,he as consumeGen,ge as consumeStringGen,Ve as createProgressBar,L as darkenColor,qe as debounce,C as decompress,Q as defaultPbChars,Z as digitCount,be as fetchAdvanced,X as formatNumber,xe as getCallStack,ye as getListLength,J as hexToRgb,Ne as insertValues,Fe as joinArrayReadable,ue as lightenColor,N as mapRange,Y as overflowVal,De as pauseFor,Te as pureObj,S as randRange,de as randomId,ie as randomItem,M as randomItemIndex,ne as randomizeArray,q as rgbToHex,A as roundFixed,we as scheduleExit,Ae as secsToTimeStr,Se as setImmediateInterval,ve as setImmediateTimeoutLoop,ae as takeRandomItem,K as takeRandomItemIndex,Me as truncStr,ee as valsWithin};
|
|
6
6
|
//# sourceMappingURL=CoreUtils.min.mjs.map
|
|
@@ -16,11 +16,11 @@
|
|
|
16
16
|
|
|
17
17
|
|
|
18
18
|
|
|
19
|
-
"use strict";var Y=Object.create;var V=Object.defineProperty;var ee=Object.getOwnPropertyDescriptor;var te=Object.getOwnPropertyNames;var re=Object.getPrototypeOf,ie=Object.prototype.hasOwnProperty;var ne=(r,e)=>{for(var t in e)V(r,t,{get:e[t],enumerable:!0})},K=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of te(e))!ie.call(r,n)&&n!==t&&V(r,n,{get:()=>e[n],enumerable:!(i=ee(e,n))||i.enumerable});return r};var M=(r,e,t)=>(t=r!=null?Y(re(r)):{},K(e||!r||!r.__esModule?V(t,"default",{value:r,enumerable:!0}):t,r)),ae=r=>K(V({},"__esModule",{value:!0}),r);var
|
|
19
|
+
"use strict";var Y=Object.create;var V=Object.defineProperty;var ee=Object.getOwnPropertyDescriptor;var te=Object.getOwnPropertyNames;var re=Object.getPrototypeOf,ie=Object.prototype.hasOwnProperty;var ne=(r,e)=>{for(var t in e)V(r,t,{get:e[t],enumerable:!0})},K=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of te(e))!ie.call(r,n)&&n!==t&&V(r,n,{get:()=>e[n],enumerable:!(i=ee(e,n))||i.enumerable});return r};var M=(r,e,t)=>(t=r!=null?Y(re(r)):{},K(e||!r||!r.__esModule?V(t,"default",{value:r,enumerable:!0}):t,r)),ae=r=>K(V({},"__esModule",{value:!0}),r);var Ce={};ne(Ce,{BrowserStorageEngine:()=>R,ChecksumMismatchError:()=>S,CustomError:()=>v,DataStore:()=>U,DataStoreEngine:()=>E,DataStoreSerializer:()=>B,DatedError:()=>m,Debouncer:()=>F,FileStorageEngine:()=>j,MigrationError:()=>w,NanoEmitter:()=>P,NetworkError:()=>x,ScriptContextError:()=>g,ValidationError:()=>z,abtoa:()=>W,atoab:()=>Q,autoPlural:()=>Pe,bitSetHas:()=>oe,capitalize:()=>Oe,clamp:()=>D,compress:()=>_,computeHash:()=>$,consumeGen:()=>ge,consumeStringGen:()=>be,createProgressBar:()=>Ve,darkenColor:()=>J,debounce:()=>Ie,decompress:()=>k,defaultPbChars:()=>G,digitCount:()=>se,fetchAdvanced:()=>ye,formatNumber:()=>ue,getCallStack:()=>Ee,getListLength:()=>De,hexToRgb:()=>q,insertValues:()=>Ne,joinArrayReadable:()=>Fe,lightenColor:()=>fe,mapRange:()=>N,overflowVal:()=>ce,pauseFor:()=>Te,pureObj:()=>Se,randRange:()=>T,randomId:()=>he,randomItem:()=>de,randomItemIndex:()=>C,randomizeArray:()=>me,rgbToHex:()=>H,roundFixed:()=>I,scheduleExit:()=>xe,secsToTimeStr:()=>Ae,setImmediateInterval:()=>ve,setImmediateTimeoutLoop:()=>we,takeRandomItem:()=>pe,takeRandomItemIndex:()=>L,truncStr:()=>Me,valsWithin:()=>le});module.exports=ae(Ce);function oe(r,e){return(r&e)===e}function D(r,e,t){return typeof t!="number"&&(t=e,e=0),Math.max(Math.min(r,t),e)}function se(r,e=!0){if(r=Number(["string","number"].includes(typeof r)?r:String(r)),typeof r=="number"&&isNaN(r))return NaN;let[t,i]=r.toString().split("."),n=t==="0"?1:Math.floor(Math.log10(Math.abs(Number(t)))+1),o=e&&i?i.length:0;return n+o}function ue(r,e,t){return r.toLocaleString(e,t==="short"?{notation:"compact",compactDisplay:"short",maximumFractionDigits:1}:{style:"decimal",maximumFractionDigits:0})}function N(r,e,t,i,n){return(typeof i>"u"||typeof n>"u")&&(n=t,t=e,i=e=0),Number(e)===0&&Number(i)===0?r*(n/t):(r-e)*((n-i)/(t-e))+i}function ce(r,e,t){let i=typeof t=="number"?e:0;if(t=typeof t=="number"?t:e,i>t)throw new RangeError(`Parameter "min" can't be bigger than "max"`);if(isNaN(r)||isNaN(i)||isNaN(t)||!isFinite(r)||!isFinite(i)||!isFinite(t))return NaN;if(r>=i&&r<=t)return r;let n=t-i+1;return((r-i)%n+n)%n+i}function T(...r){let e,t,i=!1;if(typeof r[0]=="number"&&typeof r[1]=="number")[e,t]=r;else if(typeof r[0]=="number"&&typeof r[1]!="number")e=0,[t]=r;else throw new TypeError(`Wrong parameter(s) provided - expected (number, boolean|undefined) or (number, number, boolean|undefined) but got (${r.map(n=>typeof n).join(", ")}) instead`);if(typeof r[2]=="boolean"?i=r[2]:typeof r[1]=="boolean"&&(i=r[1]),e=Number(e),t=Number(t),isNaN(e)||isNaN(t))return NaN;if(e>t)throw new TypeError(`Parameter "min" can't be bigger than "max"`);if(i){let n=new Uint8Array(1);return crypto.getRandomValues(n),Number(Array.from(n,o=>Math.round(N(o,0,255,e,t)).toString(10)).join(""))}else return Math.floor(Math.random()*(t-e+1))+e}function I(r,e){let t=10**e;return Math.round(r*t)/t}function le(r,e,t=1,i=.5){return Math.abs(I(r,t)-I(e,t))<=i}function de(r){return C(r)[0]}function C(r){if(r.length===0)return[void 0,void 0];let e=T(r.length-1);return[r[e],e]}function me(r){let e=[...r];if(r.length===0)return e;for(let t=e.length-1;t>0;t--){let i=Math.floor(Math.random()*(t+1));[e[t],e[i]]=[e[i],e[t]]}return e}function pe(r){var e;return(e=L(r))==null?void 0:e[0]}function L(r){let[e,t]=C(r);return t===void 0?[void 0,void 0]:(r.splice(t,1),[e,t])}function J(r,e,t=!1){var l;r=r.trim();let i=(c,d,p,b)=>(c=Math.max(0,Math.min(255,c-c*b/100)),d=Math.max(0,Math.min(255,d-d*b/100)),p=Math.max(0,Math.min(255,p-p*b/100)),[c,d,p]),n,o,a,s,u=r.match(/^#?([0-9A-Fa-f]{3}|[0-9A-Fa-f]{4}|[0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})$/);if(u)[n,o,a,s]=q(r);else if(r.startsWith("rgb")){let c=(l=r.match(/\d+(\.\d+)?/g))==null?void 0:l.map(Number);if(!c)throw new TypeError("Invalid RGB/RGBA color format");[n,o,a,s]=c}else throw new TypeError("Unsupported color format");return[n,o,a]=i(n,o,a,e),u?H(n,o,a,s,r.startsWith("#"),t):r.startsWith("rgba")?`rgba(${n}, ${o}, ${a}, ${s??NaN})`:`rgb(${n}, ${o}, ${a})`}function q(r){r=(r.startsWith("#")?r.slice(1):r).trim();let e=r.length===8||r.length===4?parseInt(r.slice(-(r.length/4)),16)/(r.length===8?255:15):void 0;isNaN(Number(e))||(r=r.slice(0,-(r.length/4))),(r.length===3||r.length===4)&&(r=r.split("").map(a=>a+a).join(""));let t=parseInt(r,16),i=t>>16&255,n=t>>8&255,o=t&255;return[D(i,0,255),D(n,0,255),D(o,0,255),typeof e=="number"?D(e,0,1):void 0]}function fe(r,e,t=!1){return J(r,e*-1,t)}function H(r,e,t,i,n=!0,o=!1){let a=s=>D(Math.round(s),0,255).toString(16).padStart(2,"0")[o?"toUpperCase":"toLowerCase"]();return`${n?"#":""}${a(r)}${a(e)}${a(t)}${i?a(i*255):""}`}function W(r){return btoa(new Uint8Array(r).reduce((e,t)=>e+String.fromCharCode(t),""))}function Q(r){return Uint8Array.from(atob(r),e=>e.charCodeAt(0))}async function _(r,e,t="string"){let i=r instanceof Uint8Array?r:new TextEncoder().encode((r==null?void 0:r.toString())??String(r)),n=new CompressionStream(e),o=n.writable.getWriter();o.write(i),o.close();let a=new Uint8Array(await new Response(n.readable).arrayBuffer());return t==="arrayBuffer"?a:W(a)}async function k(r,e,t="string"){let i=r instanceof Uint8Array?r:Q((r==null?void 0:r.toString())??String(r)),n=new DecompressionStream(e),o=n.writable.getWriter();o.write(i),o.close();let a=new Uint8Array(await new Response(n.readable).arrayBuffer());return t==="arrayBuffer"?a:new TextDecoder().decode(a)}async function $(r,e="SHA-256"){let t;typeof r=="string"?t=new TextEncoder().encode(r):t=r;let i=await crypto.subtle.digest(e,t);return Array.from(new Uint8Array(i)).map(a=>a.toString(16).padStart(2,"0")).join("")}function he(r=16,e=16,t=!1,i=!0){if(r<1)throw new RangeError("The length argument must be at least 1");if(e<2||e>36)throw new RangeError("The radix argument must be between 2 and 36");let n=[],o=i?[0,1]:[0];if(t){let a=new Uint8Array(r);crypto.getRandomValues(a),n=Array.from(a,s=>N(s,0,255,0,e).toString(e).substring(0,1))}else n=Array.from({length:r},()=>Math.floor(Math.random()*e).toString(e));return n.some(a=>/[a-zA-Z]/.test(a))?n.map(a=>o[T(0,o.length-1,t)]===1?a.toUpperCase():a).join(""):n.join("")}var m=class extends Error{date;constructor(e,t){super(e,t),this.name=this.constructor.name,this.date=new Date}},S=class extends m{constructor(e,t){super(e,t),this.name="ChecksumMismatchError"}},v=class extends m{constructor(e,t,i){super(t,i),this.name=e}},w=class extends m{constructor(e,t){super(e,t),this.name="MigrationError"}},z=class extends m{constructor(e,t){super(e,t),this.name="ValidationError"}},g=class extends m{constructor(e,t){super(e,t),this.name="ScriptContextError"}},x=class extends m{constructor(e,t){super(e,t),this.name="NetworkError"}};async function ge(r){return await(typeof r=="function"?r():r)}async function be(r){return typeof r=="string"?r:String(typeof r=="function"?await r():r)}async function ye(r,e={}){let{timeout:t=1e4,signal:i,...n}=e,o=new AbortController;i==null||i.addEventListener("abort",()=>o.abort());let a={},s;t>=0&&(s=setTimeout(()=>o.abort(),t),a={signal:o.signal});try{let u=await fetch(r,{...n,...a});return typeof s<"u"&&clearTimeout(s),u}catch(u){throw typeof s<"u"&&clearTimeout(s),new x("Error while calling fetch",{cause:u})}}function De(r,e=!0){return"length"in r?r.length:"size"in r?r.size:"count"in r?r.count:e?0:NaN}function Te(r,e,t=!1){return new Promise((i,n)=>{let o=setTimeout(()=>i(),r);e==null||e.addEventListener("abort",()=>{clearTimeout(o),t?n(new v("AbortError","The pause was aborted")):i()})})}function Se(r){return Object.assign(Object.create(null),r??{})}function ve(r,e,t){let i,n=()=>clearInterval(i),o=()=>{if(t!=null&&t.aborted)return n();r()};t==null||t.addEventListener("abort",n),o(),i=setInterval(o,e)}function we(r,e,t){let i,n=()=>clearTimeout(i),o=async()=>{if(t!=null&&t.aborted)return n();await r(),i=setTimeout(o,e)};t==null||t.addEventListener("abort",n),o()}function xe(r=0,e=0){if(e<0)throw new TypeError("Timeout must be a non-negative number");let t;if(typeof process<"u"&&"exit"in process&&typeof process.exit=="function")t=()=>process.exit(r);else if(typeof Deno<"u"&&"exit"in Deno&&typeof Deno.exit=="function")t=()=>Deno.exit(r);else throw new g("Cannot exit the process, no exit method available");setTimeout(t,e)}function Ee(r,e=1/0){if(typeof e!="number"||isNaN(e)||e<0)throw new TypeError("lines parameter must be a non-negative number");try{throw new Error("This is to capture a stack trace with CoreUtils.getCallStack(). (If you see this somewhere, you can safely ignore it.)")}catch(t){let i=(t.stack??"").split(`
|
|
20
20
|
`).map(n=>n.trim()).slice(2,e+2);return r!==!1?i:i.join(`
|
|
21
|
-
`)}}function Pe(r,e,t="auto"){switch(typeof e!="number"&&("length"in e?e=e.length:"size"in e?e=e.size:"count"in e&&(e=e.count)),["-s","-ies"].includes(t)||(t="auto"),isNaN(e)&&(e=2),t==="auto"?String(r).endsWith("y")?"-ies":"-s":t){case"-s":return`${r}${e===1?"":"s"}`;case"-ies":return`${String(r).slice(0,-1)}${e===1?"y":"ies"}`}}function Oe(r){return r.charAt(0).toUpperCase()+r.slice(1)}var G={100:"\u2588",75:"\u2593",50:"\u2592",25:"\u2591",0:"\u2500"};function Ve(r,e,t=G){if(r===100)return t[100].repeat(e);let i=Math.floor(r/100*e),n=r/10*e-i,o="";n>=.75?o=t[75]:n>=.5?o=t[50]:n>=.25&&(o=t[25]);let a=t[100].repeat(i),s=t[0].repeat(e-i-(o?1:0));return`${a}${o}${s}`}function Fe(r,...e){return r.replace(/%\d/gm,t=>{var n;let i=Number(t.substring(1))-1;return(n=e[i]??t)==null?void 0:n.toString()})}function Ne(r,e=", ",t=" and "){let i=[...r];if(i.length===0)return"";if(i.length===1)return String(i[0]);if(i.length===2)return i.join(t);let n=t+i[i.length-1];return i.pop(),i.join(e)+n}function Ae(r){let e=r<0,t=Math.abs(r);if(isNaN(t)||!isFinite(t))throw new TypeError("The seconds argument must be a valid number");let i=Math.floor(t/3600),n=Math.floor(t%3600/60),o=Math.floor(t%60);return(e?"-":"")+[i?i+":":"",String(n).padStart(n>0||i>0?2:1,"0"),":",String(o).padStart(o>0||n>0||i>0||r===0?2:1,"0")].join("")}function Me(r,e,t="..."){let i=(r==null?void 0:r.toString())??String(r),n=i.length>e?i.substring(0,e-t.length)+t:i;return n.length>e?n.substring(0,e):n}var Z=1,U=class{id;formatVersion;defaultData;encodeData;decodeData;compressionFormat="deflate-raw";memoryCache=!0;engine;options;firstInit=!0;cachedData;migrations;migrateIds=[];constructor(e){if(this.id=e.id,this.formatVersion=e.formatVersion,this.defaultData=e.defaultData,this.memoryCache=!!(e.memoryCache??!0),this.cachedData=this.memoryCache?e.defaultData:{},this.migrations=e.migrations,e.migrateIds&&(this.migrateIds=Array.isArray(e.migrateIds)?e.migrateIds:[e.migrateIds]),this.engine=typeof e.engine=="function"?e.engine():e.engine,this.options=e,"encodeData"in e&&"decodeData"in e&&Array.isArray(e.encodeData)&&Array.isArray(e.decodeData))this.encodeData=[e.encodeData[0],e.encodeData[1]],this.decodeData=[e.decodeData[0],e.decodeData[1]],this.compressionFormat=e.encodeData[0]??null;else if(e.compressionFormat===null)this.encodeData=void 0,this.decodeData=void 0,this.compressionFormat=null;else{let t=typeof e.compressionFormat=="string"?e.compressionFormat:"deflate-raw";this.compressionFormat=t,this.encodeData=[t,async i=>await C(i,t,"string")],this.decodeData=[t,async i=>await k(i,t,"string")]}this.engine.setDataStoreOptions({id:this.id,encodeData:this.encodeData,decodeData:this.decodeData})}async loadData(){try{if(this.firstInit){this.firstInit=!1;let u=Number(await this.engine.getValue("__ds_fmt_ver",0)),l=await this.engine.getValue(`_uucfg-${this.id}`,null);if(l){let c=Number(await this.engine.getValue(`_uucfgver-${this.id}`,NaN)),d=await this.engine.getValue(`_uucfgenc-${this.id}`,null),p=[],b=(O,h,y)=>{p.push(this.engine.setValue(h,y)),p.push(this.engine.deleteValue(O))};b(`_uucfg-${this.id}`,`__ds-${this.id}-dat`,l),isNaN(c)||b(`_uucfgver-${this.id}`,`__ds-${this.id}-ver`,c),typeof d=="boolean"||d==="true"||d==="false"||typeof d=="number"||d==="0"||d==="1"?b(`_uucfgenc-${this.id}`,`__ds-${this.id}-enf`,[0,"0",!0,"true"].includes(d)?this.compressionFormat??null:null):(p.push(this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)),p.push(this.engine.deleteValue(`_uucfgenc-${this.id}`))),await Promise.allSettled(p)}(isNaN(u)||u<Z)&&await this.engine.setValue("__ds_fmt_ver",Z)}this.migrateIds.length>0&&(await this.migrateId(this.migrateIds),this.migrateIds=[]);let e=await this.engine.getValue(`__ds-${this.id}-dat`,null),t=Number(await this.engine.getValue(`__ds-${this.id}-ver`,NaN));if(typeof e!="string")return await this.saveDefaultData(),this.engine.deepCopy(this.defaultData);let i=e??JSON.stringify(this.defaultData),n=String(await this.engine.getValue(`__ds-${this.id}-enf`,null)),o=n!=="null"&&n!=="false"&&n!=="0"&&n!==""&&n!==null,a=!1;isNaN(t)&&(await this.engine.setValue(`__ds-${this.id}-ver`,t=this.formatVersion),a=!0);let s=await this.engine.deserializeData(i,o);return t<this.formatVersion&&this.migrations&&(s=await this.runMigrations(s,t)),a&&await this.setData(s),this.memoryCache?this.cachedData=this.engine.deepCopy(s):this.engine.deepCopy(s)}catch(e){return console.warn("Error while parsing JSON data, resetting it to the default value.",e),await this.saveDefaultData(),this.defaultData}}getData(){if(!this.memoryCache)throw new m("In-memory cache is disabled for this DataStore instance, so getData() can't be used. Please use loadData() instead.");return this.engine.deepCopy(this.cachedData)}setData(e){return this.memoryCache&&(this.cachedData=e),new Promise(async t=>{await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(e,this.encodingEnabled())),this.engine.setValue(`__ds-${this.id}-ver`,this.formatVersion),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)]),t()})}async saveDefaultData(){this.memoryCache&&(this.cachedData=this.defaultData),await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(this.defaultData,this.encodingEnabled())),this.engine.setValue(`__ds-${this.id}-ver`,this.formatVersion),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)])}async deleteData(){var e,t;await Promise.allSettled([this.engine.deleteValue(`__ds-${this.id}-dat`),this.engine.deleteValue(`__ds-${this.id}-ver`),this.engine.deleteValue(`__ds-${this.id}-enf`)]),await((t=(e=this.engine).deleteStorage)==null?void 0:t.call(e))}encodingEnabled(){return!!(this.encodeData&&this.decodeData)&&this.compressionFormat!==null||!!this.compressionFormat}async runMigrations(e,t,i=!0){if(!this.migrations)return e;let n=e,o=Object.entries(this.migrations).sort(([s],[u])=>Number(s)-Number(u)),a=t;for(let[s,u]of o){let l=Number(s);if(t<this.formatVersion&&t<l)try{let c=u(n);n=c instanceof Promise?await c:c,a=t=l}catch(c){if(!i)throw new w(`Error while running migration function for format version '${s}'`,{cause:c});return await this.saveDefaultData(),this.getData()}}return await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(n,this.encodingEnabled())),this.engine.setValue(`__ds-${this.id}-ver`,a),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)]),this.memoryCache?this.cachedData=this.engine.deepCopy(n):this.engine.deepCopy(n)}async migrateId(e){let t=Array.isArray(e)?e:[e];await Promise.all(t.map(async i=>{let[n,o,a]=await(async()=>{let[u,l,c]=await Promise.all([this.engine.getValue(`__ds-${i}-dat`,JSON.stringify(this.defaultData)),this.engine.getValue(`__ds-${i}-ver`,NaN),this.engine.getValue(`__ds-${i}-enf`,null)]);return[u,Number(l),!!c&&String(c)!=="null"]})();if(n===void 0||isNaN(o))return;let s=await this.engine.deserializeData(n,a);await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(s,this.encodingEnabled())),this.engine.setValue(`__ds-${this.id}-ver`,o),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat),this.engine.deleteValue(`__ds-${i}-dat`),this.engine.deleteValue(`__ds-${i}-ver`),this.engine.deleteValue(`__ds-${i}-enf`)])}))}};var E=class{dataStoreOptions;constructor(e){e&&(this.dataStoreOptions=e)}setDataStoreOptions(e){this.dataStoreOptions=e}async serializeData(e,t){var o,a,s,u,l;this.ensureDataStoreOptions();let i=JSON.stringify(e);if(!t||!((o=this.dataStoreOptions)!=null&&o.encodeData)||!((a=this.dataStoreOptions)!=null&&a.decodeData))return i;let n=(l=(u=(s=this.dataStoreOptions)==null?void 0:s.encodeData)==null?void 0:u[1])==null?void 0:l.call(u,i);return n instanceof Promise?await n:n}async deserializeData(e,t){var n,o,a;this.ensureDataStoreOptions();let i=(n=this.dataStoreOptions)!=null&&n.decodeData&&t?(a=(o=this.dataStoreOptions.decodeData)==null?void 0:o[1])==null?void 0:a.call(o,e):void 0;return i instanceof Promise&&(i=await i),JSON.parse(i??e)}ensureDataStoreOptions(){if(!this.dataStoreOptions)throw new m("DataStoreEngine must be initialized with DataStore options before use. If you are using this instance standalone, set them in the constructor or call `setDataStoreOptions()` with the DataStore options.");if(!this.dataStoreOptions.id)throw new m("DataStoreEngine must be initialized with a valid DataStore ID")}deepCopy(e){try{if("structuredClone"in globalThis)return structuredClone(e)}catch{}return JSON.parse(JSON.stringify(e))}},R=class extends E{options;constructor(e){super(e==null?void 0:e.dataStoreOptions),this.options={type:"localStorage",...e}}async getValue(e,t){let i=this.options.type==="localStorage"?globalThis.localStorage.getItem(e):globalThis.sessionStorage.getItem(e);return typeof i>"u"?t:i}async setValue(e,t){this.options.type==="localStorage"?globalThis.localStorage.setItem(e,String(t)):globalThis.sessionStorage.setItem(e,String(t))}async deleteValue(e){this.options.type==="localStorage"?globalThis.localStorage.removeItem(e):globalThis.sessionStorage.removeItem(e)}},f,j=class extends E{options;fileAccessQueue=Promise.resolve();constructor(e){super(e==null?void 0:e.dataStoreOptions),this.options={filePath:t=>`.ds-${t}`,...e}}async readFile(){var e,t,i,n;this.ensureDataStoreOptions();try{if(f||(f=(e=await import("fs/promises"))==null?void 0:e.default),!f)throw new g("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new m("'node:fs/promises' module not available")});let o=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id),a=await f.readFile(o,"utf-8");return a?JSON.parse(await((n=(i=(t=this.dataStoreOptions)==null?void 0:t.decodeData)==null?void 0:i[1])==null?void 0:n.call(i,a))??a):void 0}catch{return}}async writeFile(e){var t,i,n,o;this.ensureDataStoreOptions();try{if(f||(f=(t=await import("fs/promises"))==null?void 0:t.default),!f)throw new g("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new m("'node:fs/promises' module not available")});let a=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id);await f.mkdir(a.slice(0,a.lastIndexOf(a.includes("/")?"/":"\\")),{recursive:!0}),await f.writeFile(a,await((o=(n=(i=this.dataStoreOptions)==null?void 0:i.encodeData)==null?void 0:n[1])==null?void 0:o.call(n,JSON.stringify(e)))??JSON.stringify(e,void 0,2),"utf-8")}catch(a){console.error("Error writing file:",a)}}async getValue(e,t){let i=await this.readFile();if(!i)return t;let n=i==null?void 0:i[e];return typeof n>"u"?t:n}async setValue(e,t){this.fileAccessQueue=this.fileAccessQueue.then(async()=>{let i=await this.readFile();i||(i={}),i[e]=t,await this.writeFile(i)}).catch(i=>{throw console.error("Error in setValue:",i),i}),await this.fileAccessQueue.catch(()=>{})}async deleteValue(e){this.fileAccessQueue=this.fileAccessQueue.then(async()=>{let t=await this.readFile();t&&(delete t[e],await this.writeFile(t))}).catch(t=>{throw console.error("Error in deleteValue:",t),t}),await this.fileAccessQueue.catch(()=>{})}async deleteStorage(){var e;this.ensureDataStoreOptions();try{if(f||(f=(e=await import("fs/promises"))==null?void 0:e.default),!f)throw new g("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new m("'node:fs/promises' module not available")});let t=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id);return await f.unlink(t)}catch(t){console.error("Error deleting file:",t)}}};var B=class r{stores;options;constructor(e,t={}){if(!crypto||!crypto.subtle)throw new g("DataStoreSerializer has to run in a secure context (HTTPS) or in another environment that implements the subtleCrypto API!");this.stores=e,this.options={addChecksum:!0,ensureIntegrity:!0,remapIds:{},...t}}async calcChecksum(e){return $(e,"SHA-256")}async serializePartial(e,t=!0,i=!0){var a;let n=[],o=this.stores.filter(s=>typeof e=="function"?e(s.id):e.includes(s.id));for(let s of o){let u=!!(t&&s.encodingEnabled()&&((a=s.encodeData)!=null&&a[1])),l=s.memoryCache?s.getData():await s.loadData(),c=u?await s.encodeData[1](JSON.stringify(l)):JSON.stringify(l);n.push({id:s.id,data:c,formatVersion:s.formatVersion,encoded:u,checksum:this.options.addChecksum?await this.calcChecksum(c):void 0})}return i?JSON.stringify(n):n}async serialize(e=!0,t=!0){return this.serializePartial(this.stores.map(i=>i.id),e,t)}async deserializePartial(e,t){let i=typeof t=="string"?JSON.parse(t):t;if(!Array.isArray(i)||!i.every(r.isSerializedDataStoreObj))throw new TypeError("Invalid serialized data format! Expected an array of SerializedDataStore objects.");let n=a=>{var s;return((s=Object.entries(this.options.remapIds).find(([,u])=>u.includes(a)))==null?void 0:s[0])??a},o=a=>typeof e=="function"?e(a):e.includes(a);for(let a of i){let s=n(a.id);if(!o(s))continue;let u=this.stores.find(c=>c.id===s);if(!u)throw new m(`Can't deserialize data because no DataStore instance with the ID "${s}" was found! Make sure to provide it in the DataStoreSerializer constructor.`);if(this.options.ensureIntegrity&&typeof a.checksum=="string"){let c=await this.calcChecksum(a.data);if(c!==a.checksum)throw new S(`Checksum mismatch for DataStore with ID "${a.id}"!
|
|
21
|
+
`)}}function Pe(r,e,t="auto"){switch(typeof e!="number"&&("length"in e?e=e.length:"size"in e?e=e.size:"count"in e&&(e=e.count)),["-s","-ies"].includes(t)||(t="auto"),isNaN(e)&&(e=2),t==="auto"?String(r).endsWith("y")?"-ies":"-s":t){case"-s":return`${r}${e===1?"":"s"}`;case"-ies":return`${String(r).slice(0,-1)}${e===1?"y":"ies"}`}}function Oe(r){return r.charAt(0).toUpperCase()+r.slice(1)}var G={100:"\u2588",75:"\u2593",50:"\u2592",25:"\u2591",0:"\u2500"};function Ve(r,e,t=G){if(r===100)return t[100].repeat(e);let i=Math.floor(r/100*e),n=r/10*e-i,o="";n>=.75?o=t[75]:n>=.5?o=t[50]:n>=.25&&(o=t[25]);let a=t[100].repeat(i),s=t[0].repeat(e-i-(o?1:0));return`${a}${o}${s}`}function Ne(r,...e){return r.replace(/%\d/gm,t=>{var n;let i=Number(t.substring(1))-1;return(n=e[i]??t)==null?void 0:n.toString()})}function Fe(r,e=", ",t=" and "){let i=[...r];if(i.length===0)return"";if(i.length===1)return String(i[0]);if(i.length===2)return i.join(t);let n=t+i[i.length-1];return i.pop(),i.join(e)+n}function Ae(r){let e=r<0,t=Math.abs(r);if(isNaN(t)||!isFinite(t))throw new TypeError("The seconds argument must be a valid number");let i=Math.floor(t/3600),n=Math.floor(t%3600/60),o=Math.floor(t%60);return(e?"-":"")+[i?i+":":"",String(n).padStart(n>0||i>0?2:1,"0"),":",String(o).padStart(o>0||n>0||i>0||r===0?2:1,"0")].join("")}function Me(r,e,t="..."){let i=(r==null?void 0:r.toString())??String(r),n=i.length>e?i.substring(0,e-t.length)+t:i;return n.length>e?n.substring(0,e):n}var Z=1,U=class{id;formatVersion;defaultData;encodeData;decodeData;compressionFormat="deflate-raw";memoryCache;engine;options;firstInit=!0;cachedData;migrations;migrateIds=[];constructor(e){if(this.id=e.id,this.formatVersion=e.formatVersion,this.defaultData=e.defaultData,this.memoryCache=e.memoryCache??!0,this.cachedData=this.memoryCache?e.defaultData:{},this.migrations=e.migrations,e.migrateIds&&(this.migrateIds=Array.isArray(e.migrateIds)?e.migrateIds:[e.migrateIds]),this.engine=typeof e.engine=="function"?e.engine():e.engine,this.options=e,"encodeData"in e&&"decodeData"in e&&Array.isArray(e.encodeData)&&Array.isArray(e.decodeData))this.encodeData=[e.encodeData[0],e.encodeData[1]],this.decodeData=[e.decodeData[0],e.decodeData[1]],this.compressionFormat=e.encodeData[0]??null;else if(e.compressionFormat===null)this.encodeData=void 0,this.decodeData=void 0,this.compressionFormat=null;else{let t=typeof e.compressionFormat=="string"?e.compressionFormat:"deflate-raw";this.compressionFormat=t,this.encodeData=[t,async i=>await _(i,t,"string")],this.decodeData=[t,async i=>await k(i,t,"string")]}this.engine.setDataStoreOptions({id:this.id,encodeData:this.encodeData,decodeData:this.decodeData})}async loadData(){try{if(this.firstInit){this.firstInit=!1;let u=Number(await this.engine.getValue("__ds_fmt_ver",0)),l=await this.engine.getValue(`_uucfg-${this.id}`,null);if(l){let c=Number(await this.engine.getValue(`_uucfgver-${this.id}`,NaN)),d=await this.engine.getValue(`_uucfgenc-${this.id}`,null),p=[],b=(O,h,y)=>{p.push(this.engine.setValue(h,y)),p.push(this.engine.deleteValue(O))};b(`_uucfg-${this.id}`,`__ds-${this.id}-dat`,l),isNaN(c)||b(`_uucfgver-${this.id}`,`__ds-${this.id}-ver`,c),typeof d=="boolean"||d==="true"||d==="false"||typeof d=="number"||d==="0"||d==="1"?b(`_uucfgenc-${this.id}`,`__ds-${this.id}-enf`,[0,"0",!0,"true"].includes(d)?this.compressionFormat??null:null):(p.push(this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)),p.push(this.engine.deleteValue(`_uucfgenc-${this.id}`))),await Promise.allSettled(p)}(isNaN(u)||u<Z)&&await this.engine.setValue("__ds_fmt_ver",Z)}this.migrateIds.length>0&&(await this.migrateId(this.migrateIds),this.migrateIds=[]);let e=await this.engine.getValue(`__ds-${this.id}-dat`,null),t=Number(await this.engine.getValue(`__ds-${this.id}-ver`,NaN));if(typeof e!="string")return await this.saveDefaultData(),this.engine.deepCopy(this.defaultData);let i=e??JSON.stringify(this.defaultData),n=String(await this.engine.getValue(`__ds-${this.id}-enf`,null)),o=n!=="null"&&n!=="false"&&n!=="0"&&n!==""&&n!==null,a=!1;isNaN(t)&&(await this.engine.setValue(`__ds-${this.id}-ver`,t=this.formatVersion),a=!0);let s=await this.engine.deserializeData(i,o);return t<this.formatVersion&&this.migrations&&(s=await this.runMigrations(s,t)),a&&await this.setData(s),this.memoryCache?this.cachedData=this.engine.deepCopy(s):this.engine.deepCopy(s)}catch(e){return console.warn("Error while parsing JSON data, resetting it to the default value.",e),await this.saveDefaultData(),this.defaultData}}getData(){if(!this.memoryCache)throw new m("In-memory cache is disabled for this DataStore instance, so getData() can't be used. Please use loadData() instead.");return this.engine.deepCopy(this.cachedData)}setData(e){return this.memoryCache&&(this.cachedData=e),new Promise(async t=>{await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(e,this.encodingEnabled())),this.engine.setValue(`__ds-${this.id}-ver`,this.formatVersion),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)]),t()})}async saveDefaultData(){this.memoryCache&&(this.cachedData=this.defaultData),await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(this.defaultData,this.encodingEnabled())),this.engine.setValue(`__ds-${this.id}-ver`,this.formatVersion),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)])}async deleteData(){var e,t;await Promise.allSettled([this.engine.deleteValue(`__ds-${this.id}-dat`),this.engine.deleteValue(`__ds-${this.id}-ver`),this.engine.deleteValue(`__ds-${this.id}-enf`)]),await((t=(e=this.engine).deleteStorage)==null?void 0:t.call(e))}encodingEnabled(){return!!(this.encodeData&&this.decodeData)&&this.compressionFormat!==null||!!this.compressionFormat}async runMigrations(e,t,i=!0){if(!this.migrations)return e;let n=e,o=Object.entries(this.migrations).sort(([s],[u])=>Number(s)-Number(u)),a=t;for(let[s,u]of o){let l=Number(s);if(t<this.formatVersion&&t<l)try{let c=u(n);n=c instanceof Promise?await c:c,a=t=l}catch(c){if(!i)throw new w(`Error while running migration function for format version '${s}'`,{cause:c});return await this.saveDefaultData(),this.engine.deepCopy(this.defaultData)}}return await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(n,this.encodingEnabled())),this.engine.setValue(`__ds-${this.id}-ver`,a),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)]),this.memoryCache?this.cachedData=this.engine.deepCopy(n):this.engine.deepCopy(n)}async migrateId(e){let t=Array.isArray(e)?e:[e];await Promise.all(t.map(async i=>{let[n,o,a]=await(async()=>{let[u,l,c]=await Promise.all([this.engine.getValue(`__ds-${i}-dat`,JSON.stringify(this.defaultData)),this.engine.getValue(`__ds-${i}-ver`,NaN),this.engine.getValue(`__ds-${i}-enf`,null)]);return[u,Number(l),!!c&&String(c)!=="null"]})();if(n===void 0||isNaN(o))return;let s=await this.engine.deserializeData(n,a);await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(s,this.encodingEnabled())),this.engine.setValue(`__ds-${this.id}-ver`,o),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat),this.engine.deleteValue(`__ds-${i}-dat`),this.engine.deleteValue(`__ds-${i}-ver`),this.engine.deleteValue(`__ds-${i}-enf`)])}))}};var E=class{dataStoreOptions;constructor(e){e&&(this.dataStoreOptions=e)}setDataStoreOptions(e){this.dataStoreOptions=e}async serializeData(e,t){var o,a,s,u,l;this.ensureDataStoreOptions();let i=JSON.stringify(e);if(!t||!((o=this.dataStoreOptions)!=null&&o.encodeData)||!((a=this.dataStoreOptions)!=null&&a.decodeData))return i;let n=(l=(u=(s=this.dataStoreOptions)==null?void 0:s.encodeData)==null?void 0:u[1])==null?void 0:l.call(u,i);return n instanceof Promise?await n:n}async deserializeData(e,t){var n,o,a;this.ensureDataStoreOptions();let i=(n=this.dataStoreOptions)!=null&&n.decodeData&&t?(a=(o=this.dataStoreOptions.decodeData)==null?void 0:o[1])==null?void 0:a.call(o,e):void 0;return i instanceof Promise&&(i=await i),JSON.parse(i??e)}ensureDataStoreOptions(){if(!this.dataStoreOptions)throw new m("DataStoreEngine must be initialized with DataStore options before use. If you are using this instance standalone, set them in the constructor or call `setDataStoreOptions()` with the DataStore options.");if(!this.dataStoreOptions.id)throw new m("DataStoreEngine must be initialized with a valid DataStore ID")}deepCopy(e){try{if("structuredClone"in globalThis)return structuredClone(e)}catch{}return JSON.parse(JSON.stringify(e))}},R=class extends E{options;constructor(e){super(e==null?void 0:e.dataStoreOptions),this.options={type:"localStorage",...e}}async getValue(e,t){let i=this.options.type==="localStorage"?globalThis.localStorage.getItem(e):globalThis.sessionStorage.getItem(e);return typeof i>"u"?t:i}async setValue(e,t){this.options.type==="localStorage"?globalThis.localStorage.setItem(e,String(t)):globalThis.sessionStorage.setItem(e,String(t))}async deleteValue(e){this.options.type==="localStorage"?globalThis.localStorage.removeItem(e):globalThis.sessionStorage.removeItem(e)}},f,j=class extends E{options;fileAccessQueue=Promise.resolve();constructor(e){super(e==null?void 0:e.dataStoreOptions),this.options={filePath:t=>`.ds-${t}`,...e}}async readFile(){var e,t,i,n;this.ensureDataStoreOptions();try{if(f||(f=(e=await import("fs/promises"))==null?void 0:e.default),!f)throw new g("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new m("'node:fs/promises' module not available")});let o=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id),a=await f.readFile(o,"utf-8");return a?JSON.parse(await((n=(i=(t=this.dataStoreOptions)==null?void 0:t.decodeData)==null?void 0:i[1])==null?void 0:n.call(i,a))??a):void 0}catch{return}}async writeFile(e){var t,i,n,o;this.ensureDataStoreOptions();try{if(f||(f=(t=await import("fs/promises"))==null?void 0:t.default),!f)throw new g("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new m("'node:fs/promises' module not available")});let a=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id);await f.mkdir(a.slice(0,a.lastIndexOf(a.includes("/")?"/":"\\")),{recursive:!0}),await f.writeFile(a,await((o=(n=(i=this.dataStoreOptions)==null?void 0:i.encodeData)==null?void 0:n[1])==null?void 0:o.call(n,JSON.stringify(e)))??JSON.stringify(e,void 0,2),"utf-8")}catch(a){console.error("Error writing file:",a)}}async getValue(e,t){let i=await this.readFile();if(!i)return t;let n=i==null?void 0:i[e];if(typeof n>"u")return t;if(typeof t=="string")return typeof n=="object"&&n!==null?JSON.stringify(n):typeof n=="string"?n:String(n);if(typeof n=="string")try{return JSON.parse(n)}catch{return t}return n}async setValue(e,t){this.fileAccessQueue=this.fileAccessQueue.then(async()=>{let i=await this.readFile();i||(i={});let n=t;if(typeof t=="string")try{if(t.startsWith("{")||t.startsWith("[")){let o=JSON.parse(t);typeof o=="object"&&o!==null&&(n=o)}}catch{}i[e]=n,await this.writeFile(i)}).catch(i=>{throw console.error("Error in setValue:",i),i}),await this.fileAccessQueue.catch(()=>{})}async deleteValue(e){this.fileAccessQueue=this.fileAccessQueue.then(async()=>{let t=await this.readFile();t&&(delete t[e],await this.writeFile(t))}).catch(t=>{throw console.error("Error in deleteValue:",t),t}),await this.fileAccessQueue.catch(()=>{})}async deleteStorage(){var e;this.ensureDataStoreOptions();try{if(f||(f=(e=await import("fs/promises"))==null?void 0:e.default),!f)throw new g("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new m("'node:fs/promises' module not available")});let t=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id);return await f.unlink(t)}catch(t){console.error("Error deleting file:",t)}}};var B=class r{stores;options;constructor(e,t={}){if(!crypto||!crypto.subtle)throw new g("DataStoreSerializer has to run in a secure context (HTTPS) or in another environment that implements the subtleCrypto API!");this.stores=e,this.options={addChecksum:!0,ensureIntegrity:!0,remapIds:{},...t}}async calcChecksum(e){return $(e,"SHA-256")}async serializePartial(e,t=!0,i=!0){var a;let n=[],o=this.stores.filter(s=>typeof e=="function"?e(s.id):e.includes(s.id));for(let s of o){let u=!!(t&&s.encodingEnabled()&&((a=s.encodeData)!=null&&a[1])),l=s.memoryCache?s.getData():await s.loadData(),c=u?await s.encodeData[1](JSON.stringify(l)):JSON.stringify(l);n.push({id:s.id,data:c,formatVersion:s.formatVersion,encoded:u,checksum:this.options.addChecksum?await this.calcChecksum(c):void 0})}return i?JSON.stringify(n):n}async serialize(e=!0,t=!0){return this.serializePartial(this.stores.map(i=>i.id),e,t)}async deserializePartial(e,t){let i=typeof t=="string"?JSON.parse(t):t;if(!Array.isArray(i)||!i.every(r.isSerializedDataStoreObj))throw new TypeError("Invalid serialized data format! Expected an array of SerializedDataStore objects.");let n=a=>{var s;return((s=Object.entries(this.options.remapIds).find(([,u])=>u.includes(a)))==null?void 0:s[0])??a},o=a=>typeof e=="function"?e(a):e.includes(a);for(let a of i){let s=n(a.id);if(!o(s))continue;let u=this.stores.find(c=>c.id===s);if(!u)throw new m(`Can't deserialize data because no DataStore instance with the ID "${s}" was found! Make sure to provide it in the DataStoreSerializer constructor.`);if(this.options.ensureIntegrity&&typeof a.checksum=="string"){let c=await this.calcChecksum(a.data);if(c!==a.checksum)throw new S(`Checksum mismatch for DataStore with ID "${a.id}"!
|
|
22
22
|
Expected: ${a.checksum}
|
|
23
|
-
Has: ${c}`)}let l=a.encoded&&u.encodingEnabled()?await u.decodeData[1](a.data):a.data;a.formatVersion&&!isNaN(Number(a.formatVersion))&&Number(a.formatVersion)<u.formatVersion?await u.runMigrations(JSON.parse(l),Number(a.formatVersion),!1):await u.setData(JSON.parse(l))}}async deserialize(e){return this.deserializePartial(this.stores.map(t=>t.id),e)}async loadStoresData(e){return Promise.allSettled(this.getStoresFiltered(e).map(async t=>({id:t.id,data:await t.loadData()})))}async resetStoresData(e){return Promise.allSettled(this.getStoresFiltered(e).map(t=>t.saveDefaultData()))}async deleteStoresData(e){return Promise.allSettled(this.getStoresFiltered(e).map(t=>t.deleteData()))}static isSerializedDataStoreObjArray(e){return Array.isArray(e)&&e.every(t=>typeof t=="object"&&t!==null&&"id"in t&&"data"in t&&"formatVersion"in t&&"encoded"in t)}static isSerializedDataStoreObj(e){return typeof e=="object"&&e!==null&&"id"in e&&"data"in e&&"formatVersion"in e&&"encoded"in e}getStoresFiltered(e){return this.stores.filter(t=>typeof e>"u"?!0:Array.isArray(e)?e.includes(t.id):e(t.id))}};var X=()=>({emit(r,...e){for(let t=this.events[r]||[],i=0,n=t.length;i<n;i++)t[i](...e)},events:{},on(r,e){return(this.events[r]||=[]).push(e),()=>{var t;this.events[r]=(t=this.events[r])==null?void 0:t.filter(i=>e!==i)}}});var P=class{events=X();eventUnsubscribes=[];emitterOptions;constructor(e={}){this.emitterOptions={publicEmit:!1,...e}}on(e,t){let i,n=()=>{i&&(i(),this.eventUnsubscribes=this.eventUnsubscribes.filter(o=>o!==i))};return i=this.events.on(e,t),this.eventUnsubscribes.push(i),n}once(e,t){return new Promise(i=>{let n,o=((...a)=>{t==null||t(...a),n==null||n(),i(a)});n=this.events.on(e,o),this.eventUnsubscribes.push(n)})}onMulti(e){let t=[],i=()=>{for(let n of t)n();t.splice(0,t.length),this.eventUnsubscribes=this.eventUnsubscribes.filter(n=>!t.includes(n))};for(let n of Array.isArray(e)?e:[e]){let o={allOf:[],oneOf:[],once:!1,...n},{oneOf:a,allOf:s,once:u,signal:l,callback:c}=o;if(l!=null&&l.aborted)return i;if(a.length===0&&s.length===0)throw new TypeError("NanoEmitter.onMulti(): Either `oneOf` or `allOf` or both must be provided in the options");let d=[],p=(h=!1)=>{if(!(!(l!=null&&l.aborted)&&!h)){for(let y of d)y();d.splice(0,d.length),this.eventUnsubscribes=this.eventUnsubscribes.filter(y=>!d.includes(y))}},b=new Set,O=()=>s.length===0||b.size===s.length;for(let h of a){let y=this.events.on(h,((...A)=>{p(),O()&&(c(h,...A),u&&p(!0))}));d.push(y)}for(let h of s){let y=this.events.on(h,((...A)=>{p(),b.add(h),O()&&(a.length===0||a.includes(h))&&(c(h,...A),u&&p(!0))}));d.push(y)}t.push(()=>p(!0))}return i}emit(e,...t){return this.emitterOptions.publicEmit?(this.events.emit(e,...t),!0):!1}unsubscribeAll(){for(let e of this.eventUnsubscribes)e();this.eventUnsubscribes=[]}};var
|
|
23
|
+
Has: ${c}`)}let l=a.encoded&&u.encodingEnabled()?await u.decodeData[1](a.data):a.data;a.formatVersion&&!isNaN(Number(a.formatVersion))&&Number(a.formatVersion)<u.formatVersion?await u.runMigrations(JSON.parse(l),Number(a.formatVersion),!1):await u.setData(JSON.parse(l))}}async deserialize(e){return this.deserializePartial(this.stores.map(t=>t.id),e)}async loadStoresData(e){return Promise.allSettled(this.getStoresFiltered(e).map(async t=>({id:t.id,data:await t.loadData()})))}async resetStoresData(e){return Promise.allSettled(this.getStoresFiltered(e).map(t=>t.saveDefaultData()))}async deleteStoresData(e){return Promise.allSettled(this.getStoresFiltered(e).map(t=>t.deleteData()))}static isSerializedDataStoreObjArray(e){return Array.isArray(e)&&e.every(t=>typeof t=="object"&&t!==null&&"id"in t&&"data"in t&&"formatVersion"in t&&"encoded"in t)}static isSerializedDataStoreObj(e){return typeof e=="object"&&e!==null&&"id"in e&&"data"in e&&"formatVersion"in e&&"encoded"in e}getStoresFiltered(e){return this.stores.filter(t=>typeof e>"u"?!0:Array.isArray(e)?e.includes(t.id):e(t.id))}};var X=()=>({emit(r,...e){for(let t=this.events[r]||[],i=0,n=t.length;i<n;i++)t[i](...e)},events:{},on(r,e){return(this.events[r]||=[]).push(e),()=>{var t;this.events[r]=(t=this.events[r])==null?void 0:t.filter(i=>e!==i)}}});var P=class{events=X();eventUnsubscribes=[];emitterOptions;constructor(e={}){this.emitterOptions={publicEmit:!1,...e}}on(e,t){let i,n=()=>{i&&(i(),this.eventUnsubscribes=this.eventUnsubscribes.filter(o=>o!==i))};return i=this.events.on(e,t),this.eventUnsubscribes.push(i),n}once(e,t){return new Promise(i=>{let n,o=((...a)=>{t==null||t(...a),n==null||n(),i(a)});n=this.events.on(e,o),this.eventUnsubscribes.push(n)})}onMulti(e){let t=[],i=()=>{for(let n of t)n();t.splice(0,t.length),this.eventUnsubscribes=this.eventUnsubscribes.filter(n=>!t.includes(n))};for(let n of Array.isArray(e)?e:[e]){let o={allOf:[],oneOf:[],once:!1,...n},{oneOf:a,allOf:s,once:u,signal:l,callback:c}=o;if(l!=null&&l.aborted)return i;if(a.length===0&&s.length===0)throw new TypeError("NanoEmitter.onMulti(): Either `oneOf` or `allOf` or both must be provided in the options");let d=[],p=(h=!1)=>{if(!(!(l!=null&&l.aborted)&&!h)){for(let y of d)y();d.splice(0,d.length),this.eventUnsubscribes=this.eventUnsubscribes.filter(y=>!d.includes(y))}},b=new Set,O=()=>s.length===0||b.size===s.length;for(let h of a){let y=this.events.on(h,((...A)=>{p(),O()&&(c(h,...A),u&&p(!0))}));d.push(y)}for(let h of s){let y=this.events.on(h,((...A)=>{p(),b.add(h),O()&&(a.length===0||a.includes(h))&&(c(h,...A),u&&p(!0))}));d.push(y)}t.push(()=>p(!0))}return i}emit(e,...t){return this.emitterOptions.publicEmit?(this.events.emit(e,...t),!0):!1}unsubscribeAll(){for(let e of this.eventUnsubscribes)e();this.eventUnsubscribes=[]}};var F=class extends P{constructor(t=200,i="immediate"){super();this.timeout=t;this.type=i}listeners=[];activeTimeout;queuedCall;addListener(t){this.listeners.push(t)}removeListener(t){let i=this.listeners.findIndex(n=>n===t);i!==-1&&this.listeners.splice(i,1)}removeAllListeners(){this.listeners=[]}getListeners(){return this.listeners}setTimeout(t){this.emit("change",this.timeout=t,this.type)}getTimeout(){return this.timeout}isTimeoutActive(){return typeof this.activeTimeout<"u"}setType(t){this.emit("change",this.timeout,this.type=t)}getType(){return this.type}call(...t){let i=(...o)=>{this.queuedCall=void 0,this.emit("call",...o),this.listeners.forEach(a=>a.call(this,...o))},n=()=>{this.activeTimeout=setTimeout(()=>{this.queuedCall?(this.queuedCall(),n()):this.activeTimeout=void 0},this.timeout)};switch(this.type){case"immediate":typeof this.activeTimeout>"u"?(i(...t),n()):this.queuedCall=()=>i(...t);break;case"idle":this.activeTimeout&&clearTimeout(this.activeTimeout),this.activeTimeout=setTimeout(()=>{i(...t),this.activeTimeout=void 0},this.timeout);break;default:throw new TypeError(`Invalid debouncer type: ${this.type}`)}}};function Ie(r,e=200,t="immediate"){let i=new F(e,t);i.addListener(r);let n=((...o)=>i.call(...o));return n.debouncer=i,n}
|
|
24
24
|
|
|
25
25
|
|
|
26
26
|
|
package/dist/CoreUtils.mjs
CHANGED
|
@@ -472,7 +472,7 @@ var DataStore = class {
|
|
|
472
472
|
encodeData;
|
|
473
473
|
decodeData;
|
|
474
474
|
compressionFormat = "deflate-raw";
|
|
475
|
-
memoryCache
|
|
475
|
+
memoryCache;
|
|
476
476
|
engine;
|
|
477
477
|
options;
|
|
478
478
|
/**
|
|
@@ -499,7 +499,7 @@ var DataStore = class {
|
|
|
499
499
|
this.id = opts.id;
|
|
500
500
|
this.formatVersion = opts.formatVersion;
|
|
501
501
|
this.defaultData = opts.defaultData;
|
|
502
|
-
this.memoryCache =
|
|
502
|
+
this.memoryCache = opts.memoryCache ?? true;
|
|
503
503
|
this.cachedData = this.memoryCache ? opts.defaultData : {};
|
|
504
504
|
this.migrations = opts.migrations;
|
|
505
505
|
if (opts.migrateIds)
|
|
@@ -597,7 +597,7 @@ var DataStore = class {
|
|
|
597
597
|
/**
|
|
598
598
|
* Returns a copy of the data from the in-memory cache.
|
|
599
599
|
* Use {@linkcode loadData()} to get fresh data from persistent storage (usually not necessary since the cache should always exactly reflect persistent storage).
|
|
600
|
-
* ⚠️
|
|
600
|
+
* ⚠️ Only available when `memoryCache` is `true` (default). When set to `false`, this produces a type and runtime error - use {@linkcode loadData()} instead.
|
|
601
601
|
*/
|
|
602
602
|
getData() {
|
|
603
603
|
if (!this.memoryCache)
|
|
@@ -674,7 +674,7 @@ var DataStore = class {
|
|
|
674
674
|
if (!resetOnError)
|
|
675
675
|
throw new MigrationError(`Error while running migration function for format version '${fmtVer}'`, { cause: err });
|
|
676
676
|
await this.saveDefaultData();
|
|
677
|
-
return this.
|
|
677
|
+
return this.engine.deepCopy(this.defaultData);
|
|
678
678
|
}
|
|
679
679
|
}
|
|
680
680
|
}
|
|
@@ -869,8 +869,21 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
869
869
|
const value = data == null ? void 0 : data[name];
|
|
870
870
|
if (typeof value === "undefined")
|
|
871
871
|
return defaultValue;
|
|
872
|
-
if (typeof
|
|
873
|
-
|
|
872
|
+
if (typeof defaultValue === "string") {
|
|
873
|
+
if (typeof value === "object" && value !== null)
|
|
874
|
+
return JSON.stringify(value);
|
|
875
|
+
if (typeof value === "string")
|
|
876
|
+
return value;
|
|
877
|
+
return String(value);
|
|
878
|
+
}
|
|
879
|
+
if (typeof value === "string") {
|
|
880
|
+
try {
|
|
881
|
+
const parsed = JSON.parse(value);
|
|
882
|
+
return parsed;
|
|
883
|
+
} catch {
|
|
884
|
+
return defaultValue;
|
|
885
|
+
}
|
|
886
|
+
}
|
|
874
887
|
return value;
|
|
875
888
|
}
|
|
876
889
|
/** Sets a value in persistent storage */
|
|
@@ -879,7 +892,18 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
879
892
|
let data = await this.readFile();
|
|
880
893
|
if (!data)
|
|
881
894
|
data = {};
|
|
882
|
-
|
|
895
|
+
let storeVal = value;
|
|
896
|
+
if (typeof value === "string") {
|
|
897
|
+
try {
|
|
898
|
+
if (value.startsWith("{") || value.startsWith("[")) {
|
|
899
|
+
const parsed = JSON.parse(value);
|
|
900
|
+
if (typeof parsed === "object" && parsed !== null)
|
|
901
|
+
storeVal = parsed;
|
|
902
|
+
}
|
|
903
|
+
} catch {
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
data[name] = storeVal;
|
|
883
907
|
await this.writeFile(data);
|
|
884
908
|
}).catch((err) => {
|
|
885
909
|
console.error("Error in setValue:", err);
|
package/dist/CoreUtils.umd.js
CHANGED
|
@@ -637,7 +637,7 @@ var DataStore = class {
|
|
|
637
637
|
__publicField(this, "encodeData");
|
|
638
638
|
__publicField(this, "decodeData");
|
|
639
639
|
__publicField(this, "compressionFormat", "deflate-raw");
|
|
640
|
-
__publicField(this, "memoryCache"
|
|
640
|
+
__publicField(this, "memoryCache");
|
|
641
641
|
__publicField(this, "engine");
|
|
642
642
|
__publicField(this, "options");
|
|
643
643
|
/**
|
|
@@ -654,7 +654,7 @@ var DataStore = class {
|
|
|
654
654
|
this.id = opts.id;
|
|
655
655
|
this.formatVersion = opts.formatVersion;
|
|
656
656
|
this.defaultData = opts.defaultData;
|
|
657
|
-
this.memoryCache =
|
|
657
|
+
this.memoryCache = (_a = opts.memoryCache) != null ? _a : true;
|
|
658
658
|
this.cachedData = this.memoryCache ? opts.defaultData : {};
|
|
659
659
|
this.migrations = opts.migrations;
|
|
660
660
|
if (opts.migrateIds)
|
|
@@ -759,7 +759,7 @@ var DataStore = class {
|
|
|
759
759
|
/**
|
|
760
760
|
* Returns a copy of the data from the in-memory cache.
|
|
761
761
|
* Use {@linkcode loadData()} to get fresh data from persistent storage (usually not necessary since the cache should always exactly reflect persistent storage).
|
|
762
|
-
* ⚠️
|
|
762
|
+
* ⚠️ Only available when `memoryCache` is `true` (default). When set to `false`, this produces a type and runtime error - use {@linkcode loadData()} instead.
|
|
763
763
|
*/
|
|
764
764
|
getData() {
|
|
765
765
|
if (!this.memoryCache)
|
|
@@ -841,7 +841,7 @@ var DataStore = class {
|
|
|
841
841
|
if (!resetOnError)
|
|
842
842
|
throw new MigrationError(`Error while running migration function for format version '${fmtVer}'`, { cause: err });
|
|
843
843
|
yield this.saveDefaultData();
|
|
844
|
-
return this.
|
|
844
|
+
return this.engine.deepCopy(this.defaultData);
|
|
845
845
|
}
|
|
846
846
|
}
|
|
847
847
|
}
|
|
@@ -1052,8 +1052,21 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
1052
1052
|
const value = data == null ? void 0 : data[name];
|
|
1053
1053
|
if (typeof value === "undefined")
|
|
1054
1054
|
return defaultValue;
|
|
1055
|
-
if (typeof
|
|
1056
|
-
|
|
1055
|
+
if (typeof defaultValue === "string") {
|
|
1056
|
+
if (typeof value === "object" && value !== null)
|
|
1057
|
+
return JSON.stringify(value);
|
|
1058
|
+
if (typeof value === "string")
|
|
1059
|
+
return value;
|
|
1060
|
+
return String(value);
|
|
1061
|
+
}
|
|
1062
|
+
if (typeof value === "string") {
|
|
1063
|
+
try {
|
|
1064
|
+
const parsed = JSON.parse(value);
|
|
1065
|
+
return parsed;
|
|
1066
|
+
} catch (e) {
|
|
1067
|
+
return defaultValue;
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1057
1070
|
return value;
|
|
1058
1071
|
});
|
|
1059
1072
|
}
|
|
@@ -1064,7 +1077,18 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
1064
1077
|
let data = yield this.readFile();
|
|
1065
1078
|
if (!data)
|
|
1066
1079
|
data = {};
|
|
1067
|
-
|
|
1080
|
+
let storeVal = value;
|
|
1081
|
+
if (typeof value === "string") {
|
|
1082
|
+
try {
|
|
1083
|
+
if (value.startsWith("{") || value.startsWith("[")) {
|
|
1084
|
+
const parsed = JSON.parse(value);
|
|
1085
|
+
if (typeof parsed === "object" && parsed !== null)
|
|
1086
|
+
storeVal = parsed;
|
|
1087
|
+
}
|
|
1088
|
+
} catch (e) {
|
|
1089
|
+
}
|
|
1090
|
+
}
|
|
1091
|
+
data[name] = storeVal;
|
|
1068
1092
|
yield this.writeFile(data);
|
|
1069
1093
|
})).catch((err) => {
|
|
1070
1094
|
console.error("Error in setValue:", err);
|
package/dist/lib/DataStore.d.ts
CHANGED
|
@@ -13,7 +13,7 @@ export type EncodeTuple = [format: LooseUnion<CompressionFormat> | null, encode:
|
|
|
13
13
|
/** Tuple of a compression format identifier and a function to use to decode the data */
|
|
14
14
|
export type DecodeTuple = [format: LooseUnion<CompressionFormat> | null, decode: (data: string) => string | Promise<string>];
|
|
15
15
|
/** Options for the DataStore instance */
|
|
16
|
-
export type DataStoreOptions<TData extends DataStoreData> = Prettify<{
|
|
16
|
+
export type DataStoreOptions<TData extends DataStoreData, TMemCache extends boolean = true> = Prettify<{
|
|
17
17
|
/**
|
|
18
18
|
* A unique internal ID for this data store.
|
|
19
19
|
* To avoid conflicts with other scripts, it is recommended to use a prefix that is unique to your script.
|
|
@@ -59,10 +59,10 @@ export type DataStoreOptions<TData extends DataStoreData> = Prettify<{
|
|
|
59
59
|
/**
|
|
60
60
|
* Whether to keep a copy of the data in memory for synchronous read access. Defaults to `true`.
|
|
61
61
|
*
|
|
62
|
-
* - ⚠️ If turned off, {@linkcode DataStore.getData()} will
|
|
62
|
+
* - ⚠️ If turned off, {@linkcode DataStore.getData()} will be unavailable at the type level and only {@linkcode DataStore.loadData()} can be used to access the data.
|
|
63
63
|
* This may be useful if multiple sources are modifying the data, or the data is very large and you want to save memory, but it will make accessing the data slower, especially when combined with compression.
|
|
64
64
|
*/
|
|
65
|
-
memoryCache?:
|
|
65
|
+
memoryCache?: TMemCache;
|
|
66
66
|
} & ({
|
|
67
67
|
encodeData?: never;
|
|
68
68
|
decodeData?: never;
|
|
@@ -114,16 +114,16 @@ export type DataStoreData = object;
|
|
|
114
114
|
* @template TData The type of the data that is saved in persistent storage for the currently set format version
|
|
115
115
|
* (TODO:FIXME: will be automatically inferred from `defaultData` if not provided)
|
|
116
116
|
*/
|
|
117
|
-
export declare class DataStore<TData extends DataStoreData> {
|
|
117
|
+
export declare class DataStore<TData extends DataStoreData, TMemCache extends boolean = true> {
|
|
118
118
|
readonly id: string;
|
|
119
119
|
readonly formatVersion: number;
|
|
120
120
|
readonly defaultData: TData;
|
|
121
121
|
readonly encodeData: DataStoreOptions<TData>["encodeData"];
|
|
122
122
|
readonly decodeData: DataStoreOptions<TData>["decodeData"];
|
|
123
123
|
readonly compressionFormat: Exclude<DataStoreOptions<TData>["compressionFormat"], undefined>;
|
|
124
|
-
readonly memoryCache:
|
|
124
|
+
readonly memoryCache: TMemCache;
|
|
125
125
|
readonly engine: DataStoreEngine;
|
|
126
|
-
options: DataStoreOptions<TData>;
|
|
126
|
+
options: DataStoreOptions<TData, TMemCache>;
|
|
127
127
|
/**
|
|
128
128
|
* Whether all first-init checks should be done.
|
|
129
129
|
* This includes migrating the internal DataStore format, migrating data from the UserUtils format, and anything similar.
|
|
@@ -143,7 +143,7 @@ export declare class DataStore<TData extends DataStoreData> {
|
|
|
143
143
|
* @template TData The type of the data that is saved in persistent storage for the currently set format version (will be automatically inferred from `defaultData` if not provided) - **This has to be a JSON-compatible object!** (no undefined, circular references, etc.)
|
|
144
144
|
* @param opts The options for this DataStore instance
|
|
145
145
|
*/
|
|
146
|
-
constructor(opts: DataStoreOptions<TData>);
|
|
146
|
+
constructor(opts: DataStoreOptions<TData, TMemCache>);
|
|
147
147
|
/**
|
|
148
148
|
* Loads the data saved in persistent storage into the in-memory cache and also returns a copy of it.
|
|
149
149
|
* Automatically populates persistent storage with default data if it doesn't contain any data yet.
|
|
@@ -153,9 +153,9 @@ export declare class DataStore<TData extends DataStoreData> {
|
|
|
153
153
|
/**
|
|
154
154
|
* Returns a copy of the data from the in-memory cache.
|
|
155
155
|
* Use {@linkcode loadData()} to get fresh data from persistent storage (usually not necessary since the cache should always exactly reflect persistent storage).
|
|
156
|
-
* ⚠️
|
|
156
|
+
* ⚠️ Only available when `memoryCache` is `true` (default). When set to `false`, this produces a type and runtime error - use {@linkcode loadData()} instead.
|
|
157
157
|
*/
|
|
158
|
-
getData(): TData;
|
|
158
|
+
getData(this: DataStore<TData, true>): TData;
|
|
159
159
|
/** Saves the data synchronously to the in-memory cache and asynchronously to the persistent storage */
|
|
160
160
|
setData(data: TData): Promise<void>;
|
|
161
161
|
/** Saves the default data passed in the constructor synchronously to the in-memory cache and asynchronously to persistent storage */
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
import type { DataStoreData, DataStoreOptions } from "./DataStore.ts";
|
|
7
7
|
import type { Prettify, SerializableVal } from "./types.ts";
|
|
8
8
|
/** Contains the only properties of {@linkcode DataStoreOptions} that are relevant to the {@linkcode DataStoreEngine} class. */
|
|
9
|
-
export type DataStoreEngineDSOptions<TData extends DataStoreData = DataStoreData> = Prettify<Pick<DataStoreOptions<TData>, "decodeData" | "encodeData" | "id">>;
|
|
9
|
+
export type DataStoreEngineDSOptions<TData extends DataStoreData = DataStoreData> = Prettify<Pick<DataStoreOptions<TData, boolean>, "decodeData" | "encodeData" | "id">>;
|
|
10
10
|
export interface DataStoreEngine<TData extends DataStoreData = DataStoreData> {
|
|
11
11
|
/** Deletes all data in persistent storage, including the data container itself (e.g. a file or a database) */
|
|
12
12
|
deleteStorage?(): Promise<void>;
|
|
@@ -43,9 +43,9 @@ export type StoreFilter = string[] | ((id: string) => boolean);
|
|
|
43
43
|
* - ⚠️ Needs to run in a secure context (HTTPS) due to the use of the SubtleCrypto API if checksumming is enabled.
|
|
44
44
|
*/
|
|
45
45
|
export declare class DataStoreSerializer {
|
|
46
|
-
protected stores: DataStore<DataStoreData>[];
|
|
46
|
+
protected stores: DataStore<DataStoreData, boolean>[];
|
|
47
47
|
protected options: Required<DataStoreSerializerOptions>;
|
|
48
|
-
constructor(stores: DataStore<DataStoreData>[], options?: DataStoreSerializerOptions);
|
|
48
|
+
constructor(stores: DataStore<DataStoreData, boolean>[], options?: DataStoreSerializerOptions);
|
|
49
49
|
/** Calculates the checksum of a string */
|
|
50
50
|
protected calcChecksum(input: string): Promise<string>;
|
|
51
51
|
/**
|
|
@@ -114,5 +114,5 @@ export declare class DataStoreSerializer {
|
|
|
114
114
|
/** Checks if a given value is a SerializedDataStore object */
|
|
115
115
|
static isSerializedDataStoreObj(obj: unknown): obj is SerializedDataStore;
|
|
116
116
|
/** Returns the DataStore instances whose IDs match the provided array or function */
|
|
117
|
-
protected getStoresFiltered(stores?: StoreFilter): DataStore<DataStoreData>[];
|
|
117
|
+
protected getStoresFiltered(stores?: StoreFilter): DataStore<DataStoreData, boolean>[];
|
|
118
118
|
}
|
|
@@ -65,7 +65,7 @@ export type TieredCacheEventMap = {};
|
|
|
65
65
|
*/
|
|
66
66
|
export declare class TieredCache<TData extends DataStoreData> extends NanoEmitter<TieredCacheEventMap> {
|
|
67
67
|
protected options: TieredCacheOptions<TData>;
|
|
68
|
-
protected stores: Map<number, DataStore<TData>>;
|
|
68
|
+
protected stores: Map<number, DataStore<TData, true>>;
|
|
69
69
|
/**
|
|
70
70
|
* Creates a new TieredCache instance.
|
|
71
71
|
* It is a cache that can have multiple tiers with different max TTLs, with data being moved between tiers based on what is fetched the most.
|
|
@@ -3,7 +3,7 @@ import type { SerializableVal } from "../types.ts";
|
|
|
3
3
|
/**
|
|
4
4
|
* A DataStore wrapper subclass that exposes internal methods for testing via the `direct_` prefixed methods.
|
|
5
5
|
*/
|
|
6
|
-
export declare class DirectAccessDataStore<TData extends DataStoreData> extends DataStore<TData> {
|
|
6
|
+
export declare class DirectAccessDataStore<TData extends DataStoreData, TMemCache extends boolean = true> extends DataStore<TData, TMemCache> {
|
|
7
7
|
direct_getValue<TValue extends SerializableVal = string>(name: string, defaultValue: TValue): Promise<string | TValue>;
|
|
8
8
|
direct_setValue(name: string, value: SerializableVal): Promise<void>;
|
|
9
9
|
direct_renameKey(oldName: string, newName: string): Promise<void>;
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sv443-network/coreutils",
|
|
3
3
|
"libName": "@sv443-network/coreutils",
|
|
4
|
-
"version": "3.0.
|
|
4
|
+
"version": "3.0.6",
|
|
5
5
|
"description": "Cross-platform, general-purpose, JavaScript core library for Node, Deno and the browser. Intended to be used in conjunction with `@sv443-network/userutils` and `@sv443-network/djsutils`, but can be used independently as well.",
|
|
6
6
|
"main": "dist/CoreUtils.cjs",
|
|
7
7
|
"module": "dist/CoreUtils.mjs",
|