@sv443-network/coreutils 0.0.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,11 +1,23 @@
1
+ # @sv443-network/coreutils
2
+
3
+ ## 1.0.0
4
+
5
+ This is the initial release of CoreUtils. Most features have been originally ported from [version 9.4.1 of `@sv443-network/userutils`](https://github.com/Sv443-Network/UserUtils/tree/v9.4.1)
6
+ Parts of the code have been overhauled, and some features have been added:
1
7
  - Additions:
2
- - array:
3
- - Added `takeRandomItemIndex()`
4
- - BREAKING CHANGES:
5
- - Reworked DataStore
6
- - Encoding with `deflate-raw` will now be enabled by default. Set `compressionFormat: null` to disable it.
7
- - Added `DataStoreEngine` base class to create a persistent storage engine
8
- - Added `FileStorageEngine` for file-based storage in the backend and `BrowserStorageEngine` for browser API based storage
9
- - The global key `__ds_fmt_ver` will now contain a global version number for DataStore-internal format integrity
10
- - crypto:
11
- - renamed `ab2str()` to `abtoa()` and `str2ab()` to `atoab()` to match `btoa()` and `atob()`
8
+ - Added [`capitalize()`](https://github.com/Sv443-Network/CoreUtils/blob/main/docs.md#function-capitalize) to capitalize the first letter of a string.
9
+ - Added [`setImmediateInterval()`](https://github.com/Sv443-Network/CoreUtils/blob/main/docs.md#function-setimmediateinterval) to set an interval that runs immediately, then again on a fixed *interval.*
10
+ - Added [`setImmediateTimeoutLoop()`](https://github.com/Sv443-Network/CoreUtils/blob/main/docs.md#function-setimmediatetimeoutloop) to set a recursive `setTimeout()` loop with a fixed *delay.*
11
+ - Added [`takeRandomItemIndex()`](https://github.com/Sv443-Network/CoreUtils/blob/main/docs.md#function-takerandomitemindex), as a mutating counterpart to [`randomItemIndex()`](https://github.com/Sv443-Network/CoreUtils/blob/main/docs.md#function-randomitemindex)
12
+ - Added [`truncStr()`](https://github.com/Sv443-Network/CoreUtils/blob/main/docs.md#function-truncstr) to truncate a string to a given length, optionally adding an ellipsis.
13
+ - Added [`valsWithin()`](https://github.com/Sv443-Network/CoreUtils/blob/main/docs.md#function-valswithin) to check if two values, rounded at the given decimal, are within a certain range of each other.
14
+ - Added [`scheduleExit()`](https://github.com/Sv443-Network/CoreUtils/blob/main/docs.md#function-scheduleexit) to schedule a Node/Deno process to exit with the given code, after the microtask queue is empty or after the given timeout.
15
+ - **BREAKING CHANGES:**
16
+ - Reworked `DataStore`
17
+ - The constructor now needs an `engine` property that is an instance of a [`DataStoreEngine`](https://github.com/Sv443-Network/CoreUtils/blob/main/docs.md#class-datastoreengine.)
18
+ - Encoding with `deflate-raw` will now be enabled by default. Set `compressionFormat: null` to disable it and restore the previous behavior.
19
+ - Added [`DataStoreEngine` class](https://github.com/Sv443-Network/CoreUtils/blob/main/docs.md#class-datastoreengine) with two implementations available out-of-the-box; [`FileStorageEngine`](https://github.com/Sv443-Network/CoreUtils/blob/main/docs.md#class-filestorageengine) and [`BrowserStorageEngine`](https://github.com/Sv443-Network/CoreUtils/blob/main/docs.md#class-browserstorageengine), for Node/Deno and browser environments respectively. Userscripts need to use [`BrowserStorageEngine`.](https://github.com/Sv443-Network/CoreUtils/blob/main/docs.md#class-browserstorageengine)
20
+ - Added shorthand property `compressionFormat` as an alternative to the properties `encodeData` and `decodeData`
21
+ - The global key `__ds_fmt_ver` will now contain a global version number for DataStore-internal format integrity.
22
+ - Renamed `ab2str()` to `abtoa()` and `str2ab()` to `atoab()` to match the naming of `atob()` and `btoa()`
23
+ - Renamed `purifyObj()` to `pureObj()`
package/README.md CHANGED
@@ -1,15 +1,10 @@
1
- > [!IMPORTANT]
2
- > This library is not ready to be used yet. Please check back in a couple weeks.
3
-
4
- <br><br>
5
-
6
1
  <div align="center" style="text-align: center;">
7
2
 
8
3
  # CoreUtils
9
4
  Cross-platform, general-purpose, JavaScript core library for Node, Deno and the browser.
10
5
  Intended to be used in conjunction with [`@sv443-network/userutils`](https://github.com/Sv443-Network/UserUtils) and [`@sv443-network/djsutils`](https://github.com/Sv443-Network/DJSUtils), but can be used independently as well.
11
6
 
12
- ### [Documentation](./docs.md#readme) &bull; [Features](#features) &bull; [Installation](#installation) &bull; [License](#license)
7
+ ### [Documentation](./docs.md#readme) &bull; [Features](#features) &bull; [Installation](#installation) &bull; [License](#license) &bull; [Changelog](./CHANGELOG.md)
13
8
 
14
9
  </div>
15
10
  <br>
@@ -84,6 +79,7 @@ Intended to be used in conjunction with [`@sv443-network/userutils`](https://git
84
79
  - 🟣 [`function pureObj()`](./docs.md#function-pureobj) - Applies an object's props to a null object (object without prototype chain) or just returns a new null object
85
80
  - 🟣 [`function setImmediateInterval()`](./docs.md#function-setimmediateinterval) - Like `setInterval()`, but instantly calls the callback and supports passing an [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal)
86
81
  - 🟣 [`function setImmediateTimeoutLoop()`](./docs.md#function-setimmediatetimeoutloop) - Like a recursive `setTimeout()` loop, but instantly calls the callback and supports passing an [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal)
82
+ - 🟣 [`function scheduleExit()`](./docs.md#function-scheduleexit) - Schedules a process exit after the next event loop tick, to allow operations like IO writes to finish.
87
83
  - [**NanoEmitter:**](./docs.md#nanoemitter)
88
84
  - 🟧 [`class NanoEmitter`](./docs.md#class-nanoemitter) - Simple, lightweight event emitter class that can be used in both FP and OOP, inspired by [`EventEmitter` from `node:events`](https://nodejs.org/api/events.html#class-eventemitter), based on [`nanoevents`](https://npmjs.com/package/nanoevents)
89
85
  - 🔷 [`type NanoEmitterOptions`](./docs.md#type-nanoemitteroptions) - Options for the [`NanoEmitter` class](./docs.md#class-nanoemitter)
@@ -138,4 +134,35 @@ pnpm i @sv443-network/coreutils
138
134
  yarn add @sv443-network/coreutils
139
135
  npx jsr install @sv443-network/coreutils
140
136
  deno add jsr:@sv443-network/coreutils
141
- ```
137
+ ```
138
+ - If you are in a DOM environment, you can include the UMD bundle using your favorite CDN:
139
+ ```html
140
+ <script src="https://cdn.jsdelivr.net/npm/@sv443-network/coreutils@latest/dist/CoreUtils.min.umd.js"></script>
141
+ <script src="https://unpkg.com/@sv443-network/coreutils@latest/dist/CoreUtils.min.umd.js"></script>
142
+ <script src="https://esm.sh/@sv443-network/coreutils@latest/dist/CoreUtils.min.umd.js"></script>
143
+ ```
144
+ - Then, import parts of the library as needed:
145
+ ```ts
146
+ // >> EcmaScript Modules (ESM):
147
+
148
+ // - import parts of the library:
149
+ import { randomItem } from "@sv443-network/coreutils";
150
+ // - or import the full library:
151
+ import * as CoreUtils from "@sv443-network/coreutils";
152
+ // - or import raw TS files, after installing via JSR:
153
+ import { DataStore } from "jsr:@sv443-network/coreutils/lib/DataStore.ts";
154
+
155
+ // >> CommonJS (CJS):
156
+
157
+ // - import parts of the library:
158
+ const { debounce } = require("@sv443-network/coreutils");
159
+ // - or import the full library:
160
+ const CoreUtils = require("@sv443-network/coreutils");
161
+
162
+ // >> Universal Module Definition (UMD):
163
+
164
+ // - to make the global variable `CoreUtils` available, import this file:
165
+ // "@sv443-network/coreutils/dist/CoreUtils.min.umd.js"
166
+ // - or import the library on your HTML page:
167
+ // <script src="https://cdn.jsdelivr.net/npm/@sv443-network/coreutils@latest/dist/CoreUtils.min.umd.js"></script>
168
+ ```
@@ -74,6 +74,7 @@ __export(lib_exports, {
74
74
  randomizeArray: () => randomizeArray,
75
75
  rgbToHex: () => rgbToHex,
76
76
  roundFixed: () => roundFixed,
77
+ scheduleExit: () => scheduleExit,
77
78
  secsToTimeStr: () => secsToTimeStr,
78
79
  setImmediateInterval: () => setImmediateInterval,
79
80
  setImmediateTimeoutLoop: () => setImmediateTimeoutLoop,
@@ -382,6 +383,18 @@ function setImmediateTimeoutLoop(callback, interval, signal) {
382
383
  signal == null ? void 0 : signal.addEventListener("abort", cleanup);
383
384
  loop();
384
385
  }
386
+ function scheduleExit(code = 0, timeout = 0) {
387
+ if (timeout < 0)
388
+ throw new TypeError("Timeout must be a non-negative number");
389
+ let exit;
390
+ if (typeof process !== "undefined" && "exit" in process)
391
+ exit = () => process.exit(code);
392
+ else if (typeof Deno !== "undefined" && "exit" in Deno)
393
+ exit = () => Deno.exit(code);
394
+ else
395
+ throw new Error("Cannot exit the process, no exit method available");
396
+ setTimeout(exit, timeout);
397
+ }
385
398
 
386
399
  // lib/text.ts
387
400
  function autoPlural(term, num, pluralType = "auto") {
@@ -796,7 +809,7 @@ var FileStorageEngine = class extends DataStoreEngine {
796
809
  /**
797
810
  * Creates an instance of `FileStorageEngine`.
798
811
  *
799
- * ⚠️ Requires Node.js or Deno with Node compatibility
812
+ * ⚠️ Requires Node.js or Deno with Node compatibility (v1.31+)
800
813
  * ⚠️ Don't reuse this engine across multiple {@linkcode DataStore} instances
801
814
  */
802
815
  constructor(options) {
@@ -813,11 +826,11 @@ var FileStorageEngine = class extends DataStoreEngine {
813
826
  try {
814
827
  if (!fs)
815
828
  fs = (await import("fs/promises")).default;
829
+ if (!fs)
830
+ throw new DatedError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new Error("'node:fs/promises' module not available") });
816
831
  const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
817
832
  const data = await fs.readFile(path, "utf-8");
818
- if (!data)
819
- return void 0;
820
- return JSON.parse(await ((_c = (_b = (_a = this.dataStoreOptions) == null ? void 0 : _a.decodeData) == null ? void 0 : _b[1]) == null ? void 0 : _c.call(_b, data)) ?? data);
833
+ return data ? JSON.parse(await ((_c = (_b = (_a = this.dataStoreOptions) == null ? void 0 : _a.decodeData) == null ? void 0 : _b[1]) == null ? void 0 : _c.call(_b, data)) ?? data) : void 0;
821
834
  } catch {
822
835
  return void 0;
823
836
  }
@@ -828,6 +841,8 @@ var FileStorageEngine = class extends DataStoreEngine {
828
841
  try {
829
842
  if (!fs)
830
843
  fs = (await import("fs/promises")).default;
844
+ if (!fs)
845
+ throw new DatedError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new Error("'node:fs/promises' module not available") });
831
846
  const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
832
847
  await fs.mkdir(path.slice(0, path.lastIndexOf("/")), { recursive: true });
833
848
  await fs.writeFile(path, await ((_c = (_b = (_a = this.dataStoreOptions) == null ? void 0 : _a.encodeData) == null ? void 0 : _b[1]) == null ? void 0 : _c.call(_b, JSON.stringify(data))) ?? JSON.stringify(data, void 0, 2), "utf-8");
@@ -1,4 +1,4 @@
1
- "use strict";var q=Object.create;var w=Object.defineProperty;var H=Object.getOwnPropertyDescriptor;var K=Object.getOwnPropertyNames;var W=Object.getPrototypeOf,G=Object.prototype.hasOwnProperty;var Z=(r,e)=>{for(var t in e)w(r,t,{get:e[t],enumerable:!0})},$=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of K(e))!G.call(r,n)&&n!==t&&w(r,n,{get:()=>e[n],enumerable:!(i=H(e,n))||i.enumerable});return r};var z=(r,e,t)=>(t=r!=null?q(W(r)):{},$(e||!r||!r.__esModule?w(t,"default",{value:r,enumerable:!0}):t,r)),Q=r=>$(w({},"__esModule",{value:!0}),r);var Pe={};Z(Pe,{BrowserStorageEngine:()=>I,ChecksumMismatchError:()=>y,DataStore:()=>N,DataStoreEngine:()=>T,DataStoreSerializer:()=>_,DatedError:()=>h,Debouncer:()=>P,FileStorageEngine:()=>O,MigrationError:()=>D,NanoEmitter:()=>S,ValidationError:()=>A,abtoa:()=>B,atoab:()=>j,autoPlural:()=>ge,bitSetHas:()=>X,capitalize:()=>be,clamp:()=>m,compress:()=>x,computeHash:()=>E,consumeGen:()=>ue,consumeStringGen:()=>ce,createProgressBar:()=>ye,darkenColor:()=>R,debounce:()=>xe,decompress:()=>oe,defaultPbChars:()=>U,digitCount:()=>Y,fetchAdvanced:()=>de,formatNumber:()=>ee,getListLength:()=>le,hexToRgb:()=>k,insertValues:()=>De,joinArrayReadable:()=>Te,lightenColor:()=>ae,mapRange:()=>v,pauseFor:()=>me,pureObj:()=>pe,randRange:()=>b,randomId:()=>se,randomItem:()=>re,randomItemIndex:()=>F,randomizeArray:()=>ie,rgbToHex:()=>C,roundFixed:()=>V,secsToTimeStr:()=>Se,setImmediateInterval:()=>fe,setImmediateTimeoutLoop:()=>he,takeRandomItem:()=>ne,takeRandomItemIndex:()=>M,truncStr:()=>we,valsWithin:()=>te});module.exports=Q(Pe);function X(r,e){return(r&e)===e}function m(r,e,t){return typeof t!="number"&&(t=e,e=0),Math.max(Math.min(r,t),e)}function Y(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),a=e&&i?i.length:0;return n+a}function ee(r,e,t){return r.toLocaleString(e,t==="short"?{notation:"compact",compactDisplay:"short",maximumFractionDigits:1}:{style:"decimal",maximumFractionDigits:0})}function v(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 b(...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,a=>Math.round(v(a,0,255,e,t)).toString(10)).join(""))}else return Math.floor(Math.random()*(t-e+1))+e}function V(r,e){let t=10**e;return Math.round(r*t)/t}function te(r,e,t=10,i=.5){return Math.abs(V(r,t)-V(e,t))<=i}function re(r){return F(r)[0]}function F(r){if(r.length===0)return[void 0,void 0];let e=b(r.length-1);return[r[e],e]}function ie(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 ne(r){var e;return(e=M(r))==null?void 0:e[0]}function M(r){let[e,t]=F(r);return t===void 0?[void 0,void 0]:(r.splice(t,1),[e,t])}function R(r,e,t=!1){var d;r=r.trim();let i=(c,l,f,g)=>(c=Math.max(0,Math.min(255,c-c*g/100)),l=Math.max(0,Math.min(255,l-l*g/100)),f=Math.max(0,Math.min(255,f-f*g/100)),[c,l,f]),n,a,o,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,a,o,s]=k(r);else if(r.startsWith("rgb")){let c=(d=r.match(/\d+(\.\d+)?/g))==null?void 0:d.map(Number);if(!c)throw new TypeError("Invalid RGB/RGBA color format");[n,a,o,s]=c}else throw new TypeError("Unsupported color format");if([n,a,o]=i(n,a,o,e),u)return C(n,a,o,s,r.startsWith("#"),t);if(r.startsWith("rgba"))return`rgba(${n}, ${a}, ${o}, ${s??NaN})`;if(r.startsWith("rgb"))return`rgb(${n}, ${a}, ${o})`;throw new TypeError("Unsupported color format")}function k(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(o=>o+o).join(""));let t=parseInt(r,16),i=t>>16&255,n=t>>8&255,a=t&255;return[m(i,0,255),m(n,0,255),m(a,0,255),typeof e=="number"?m(e,0,1):void 0]}function ae(r,e,t=!1){return R(r,e*-1,t)}function C(r,e,t,i,n=!0,a=!1){let o=s=>m(Math.round(s),0,255).toString(16).padStart(2,"0")[a?"toUpperCase":"toLowerCase"]();return`${n?"#":""}${o(r)}${o(e)}${o(t)}${i?o(i*255):""}`}function B(r){return btoa(new Uint8Array(r).reduce((e,t)=>e+String.fromCharCode(t),""))}function j(r){return Uint8Array.from(atob(r),e=>e.charCodeAt(0))}async function x(r,e,t="string"){let i=r instanceof ArrayBuffer?r:new TextEncoder().encode((r==null?void 0:r.toString())??String(r)),n=new CompressionStream(e),a=n.writable.getWriter();a.write(i),a.close();let o=await new Response(n.readable).arrayBuffer();return t==="arrayBuffer"?o:B(o)}async function oe(r,e,t="string"){let i=r instanceof ArrayBuffer?r:j((r==null?void 0:r.toString())??String(r)),n=new DecompressionStream(e),a=n.writable.getWriter();a.write(i),a.close();let o=await new Response(n.readable).arrayBuffer();return t==="arrayBuffer"?o:new TextDecoder().decode(o)}async function E(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(o=>o.toString(16).padStart(2,"0")).join("")}function se(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=[],a=i?[0,1]:[0];if(t){let o=new Uint8Array(r);crypto.getRandomValues(o),n=Array.from(o,s=>v(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(o=>/[a-zA-Z]/.test(o))?n.map(o=>a[b(0,a.length-1,t)]===1?o.toUpperCase():o).join(""):n.join("")}async function ue(r){return await(typeof r=="function"?r():r)}async function ce(r){return typeof r=="string"?r:String(typeof r=="function"?await r():r)}async function de(r,e={}){let{timeout:t=1e4}=e,i=new AbortController,{signal:n,...a}=e;n==null||n.addEventListener("abort",()=>i.abort());let o={},s;t>=0&&(s=setTimeout(()=>i.abort(),t),o={signal:i.signal});try{let u=await fetch(r,{...a,...o});return typeof s<"u"&&clearTimeout(s),u}catch(u){throw typeof s<"u"&&clearTimeout(s),new Error("Error while calling fetch",{cause:u})}}function le(r,e=!0){return"length"in r?r.length:"size"in r?r.size:"count"in r?r.count:e?0:NaN}function me(r,e,t=!1){return new Promise((i,n)=>{let a=setTimeout(()=>i(),r);e==null||e.addEventListener("abort",()=>{clearTimeout(a),t?n(new Error("The pause was aborted")):i()})})}function pe(r){return Object.assign(Object.create(null),r??{})}function fe(r,e,t){let i,n=()=>clearInterval(i),a=()=>{if(t!=null&&t.aborted)return n();r()};t==null||t.addEventListener("abort",n),a(),i=setInterval(a,e)}function he(r,e,t){let i,n=()=>clearTimeout(i),a=async()=>{if(t!=null&&t.aborted)return n();await r(),i=setTimeout(a,e)};t==null||t.addEventListener("abort",n),a()}function ge(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 be(r){return r.charAt(0).toUpperCase()+r.slice(1)}var U={100:"\u2588",75:"\u2593",50:"\u2592",25:"\u2591",0:"\u2500"};function ye(r,e,t=U){if(r===100)return t[100].repeat(e);let i=Math.floor(r/100*e),n=r/10*e-i,a="";n>=.75?a=t[75]:n>=.5?a=t[50]:n>=.25&&(a=t[25]);let o=t[100].repeat(i),s=t[0].repeat(e-i-(a?1:0));return`${o}${a}${s}`}function De(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 Te(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 Se(r){if(r<0)throw new TypeError("Seconds must be a positive number");let e=Math.floor(r/3600),t=Math.floor(r%3600/60),i=Math.floor(r%60);return[e?e+":":"",String(t).padStart(t>0||e>0?2:1,"0"),":",String(i).padStart(i>0||t>0||e>0?2:1,"0")].join("")}function we(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 h=class extends Error{date;constructor(e,t){super(e,t),this.name=this.constructor.name,this.date=new Date}},y=class extends h{constructor(e,t){super(e,t),this.name="ChecksumMismatchError"}},D=class extends h{constructor(e,t){super(e,t),this.name="MigrationError"}},A=class extends h{constructor(e,t){super(e,t),this.name="ValidationError"}};var ve=1,N=class{id;formatVersion;defaultData;encodeData;decodeData;compressionFormat="deflate-raw";engine;firstInit=!0;cachedData;migrations;migrateIds=[];constructor(e){if(this.id=e.id,this.formatVersion=e.formatVersion,this.defaultData=e.defaultData,this.cachedData=e.defaultData,this.migrations=e.migrations,e.migrateIds&&(this.migrateIds=Array.isArray(e.migrateIds)?e.migrateIds:[e.migrateIds]),this.encodeData=e.encodeData,this.decodeData=e.decodeData,this.engine=typeof e.engine=="function"?e.engine():e.engine,typeof e.compressionFormat>"u"&&(e.compressionFormat="deflate-raw"),typeof e.compressionFormat=="string")this.encodeData=[e.compressionFormat,async t=>await x(t,e.compressionFormat,"string")],this.decodeData=[e.compressionFormat,async t=>await x(t,e.compressionFormat,"string")];else if("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]];else if(e.compressionFormat===null)this.encodeData=void 0,this.decodeData=void 0;else throw new TypeError("Either `compressionFormat` or `encodeData` and `decodeData` have to be set and valid, but not all three at a time. Please refer to the documentation for more info.");this.engine.setDataStoreOptions(e)}async loadData(){try{if(this.firstInit){this.firstInit=!1;let o=Number(await this.engine.getValue("__ds_fmt_ver",0));if(isNaN(o)||o<1){let s=await this.engine.getValue(`_uucfg-${this.id}`,null);if(s){let u=Number(await this.engine.getValue(`_uucfgver-${this.id}`,NaN)),d=await this.engine.getValue(`_uucfgenc-${this.id}`,null),c=[],l=(f,g,J)=>{c.push(this.engine.setValue(g,J)),c.push(this.engine.deleteValue(f))};s&&l(`_uucfg-${this.id}`,`__ds-${this.id}-dat`,s),!isNaN(u)&&l(`_uucfgver-${this.id}`,`__ds-${this.id}-ver`,u),typeof d=="boolean"&&l(`_uucfgenc-${this.id}`,`__ds-${this.id}-enc`,d===!0?this.compressionFormat:null),await Promise.allSettled(c)}await this.engine.setValue("__ds_fmt_ver",ve)}}this.migrateIds.length>0&&(await this.migrateId(this.migrateIds),this.migrateIds=[]);let e=await this.engine.getValue(`__ds-${this.id}-dat`,JSON.stringify(this.defaultData)),t=Number(await this.engine.getValue(`__ds-${this.id}-ver`,NaN));if(typeof e!="string")return await this.saveDefaultData(),{...this.defaultData};let i=!!await this.engine.getValue(`__ds-${this.id}-enc`,!1),n=!1;isNaN(t)&&(await this.engine.setValue(`__ds-${this.id}-ver`,t=this.formatVersion),n=!0);let a=await this.engine.deserializeData(e,i);return t<this.formatVersion&&this.migrations&&(a=await this.runMigrations(a,t)),n&&await this.setData(a),this.cachedData=this.engine.deepCopy(a)}catch(e){return console.warn("Error while parsing JSON data, resetting it to the default value.",e),await this.saveDefaultData(),this.defaultData}}getData(){return this.engine.deepCopy(this.cachedData)}setData(e){this.cachedData=e;let t=this.encodingEnabled();return new Promise(async i=>{await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(e,t)),this.engine.setValue(`__ds-${this.id}-ver`,this.formatVersion),this.engine.setValue(`__ds-${this.id}-enc`,t)]),i()})}async saveDefaultData(){this.cachedData=this.defaultData;let e=this.encodingEnabled();await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(this.defaultData,e)),this.engine.setValue(`__ds-${this.id}-ver`,this.formatVersion),this.engine.setValue(`__ds-${this.id}-enc`,e)])}async deleteData(){await Promise.allSettled([this.engine.deleteValue(`__ds-${this.id}-dat`),this.engine.deleteValue(`__ds-${this.id}-ver`),this.engine.deleteValue(`__ds-${this.id}-enc`)])}encodingEnabled(){return!!(this.encodeData&&this.decodeData)}async runMigrations(e,t,i=!0){if(!this.migrations)return e;let n=e,a=Object.entries(this.migrations).sort(([s],[u])=>Number(s)-Number(u)),o=t;for(let[s,u]of a){let d=Number(s);if(t<this.formatVersion&&t<d)try{let c=u(n);n=c instanceof Promise?await c:c,o=t=d}catch(c){if(!i)throw new D(`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.engine.setValue(`__ds-${this.id}-ver`,o),this.engine.setValue(`__ds-${this.id}-enc`,this.encodingEnabled())]),this.cachedData={...n}}async migrateId(e){let t=Array.isArray(e)?e:[e];await Promise.all(t.map(async i=>{let n=await this.engine.getValue(`__ds-${i}-dat`,JSON.stringify(this.defaultData)),a=Number(await this.engine.getValue(`__ds-${i}-ver`,NaN)),o=!!await this.engine.getValue(`__ds-${i}-enc`,!1);if(n===void 0||isNaN(a))return;let s=await this.engine.deserializeData(n,o);await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(s)),this.engine.setValue(`__ds-${this.id}-ver`,a),this.engine.setValue(`__ds-${this.id}-enc`,o),this.engine.deleteValue(`__ds-${i}-dat`),this.engine.deleteValue(`__ds-${i}-ver`),this.engine.deleteValue(`__ds-${i}-enc`)])}))}};var T=class{dataStoreOptions;setDataStoreOptions(e){this.dataStoreOptions=e}async serializeData(e,t){var a,o,s,u,d;let i=JSON.stringify(e);if(!t||!((a=this.dataStoreOptions)!=null&&a.encodeData)||!((o=this.dataStoreOptions)!=null&&o.decodeData))return i;let n=(d=(u=(s=this.dataStoreOptions)==null?void 0:s.encodeData)==null?void 0:u[1])==null?void 0:d.call(u,i);return n instanceof Promise?await n:n}async deserializeData(e,t){var n,a,o;let i=(n=this.dataStoreOptions)!=null&&n.decodeData&&t?(o=(a=this.dataStoreOptions.decodeData)==null?void 0:a[1])==null?void 0:o.call(a,e):void 0;return i instanceof Promise&&(i=await i),JSON.parse(i??e)}deepCopy(e){try{if("structuredClone"in globalThis)return structuredClone(e)}catch{}return JSON.parse(JSON.stringify(e))}},I=class extends T{options;constructor(e){super(),this.options={type:"localStorage",...e}}async getValue(e,t){return(this.options.type==="localStorage"?globalThis.localStorage.getItem(e):globalThis.sessionStorage.getItem(e))??t}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)}},p,O=class extends T{options;constructor(e){super(),this.options={filePath:t=>`.ds-${t}`,...e}}async readFile(){var e,t,i;try{p||(p=(await import("fs/promises")).default);let n=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id),a=await p.readFile(n,"utf-8");return a?JSON.parse(await((i=(t=(e=this.dataStoreOptions)==null?void 0:e.decodeData)==null?void 0:t[1])==null?void 0:i.call(t,a))??a):void 0}catch{return}}async writeFile(e){var t,i,n;try{p||(p=(await import("fs/promises")).default);let a=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id);await p.mkdir(a.slice(0,a.lastIndexOf("/")),{recursive:!0}),await p.writeFile(a,await((n=(i=(t=this.dataStoreOptions)==null?void 0:t.encodeData)==null?void 0:i[1])==null?void 0:n.call(i,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 n===void 0?t:typeof n=="string"?n:String(n??t)}async setValue(e,t){let i=await this.readFile();i||(i={}),i[e]=t,await this.writeFile(i)}async deleteValue(e){let t=await this.readFile();t&&(delete t[e],await this.writeFile(t))}};var _=class r{stores;options;constructor(e,t={}){if(!crypto||!crypto.subtle)throw new Error("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,...t}}async calcChecksum(e){return E(e,"SHA-256")}async serializePartial(e,t=!0,i=!0){let n=[];for(let a of this.stores.filter(o=>typeof e=="function"?e(o.id):e.includes(o.id))){let o=t&&a.encodingEnabled()?await a.encodeData[1](JSON.stringify(a.getData())):JSON.stringify(a.getData());n.push({id:a.id,data:o,formatVersion:a.formatVersion,encoded:t&&a.encodingEnabled(),checksum:this.options.addChecksum?await this.calcChecksum(o):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.");for(let n of i.filter(a=>typeof e=="function"?e(a.id):e.includes(a.id))){let a=this.stores.find(s=>s.id===n.id);if(!a)throw new Error(`DataStore instance with ID "${n.id}" not found! Make sure to provide it in the DataStoreSerializer constructor.`);if(this.options.ensureIntegrity&&typeof n.checksum=="string"){let s=await this.calcChecksum(n.data);if(s!==n.checksum)throw new y(`Checksum mismatch for DataStore with ID "${n.id}"!
1
+ "use strict";var q=Object.create;var w=Object.defineProperty;var H=Object.getOwnPropertyDescriptor;var K=Object.getOwnPropertyNames;var W=Object.getPrototypeOf,G=Object.prototype.hasOwnProperty;var Z=(r,e)=>{for(var t in e)w(r,t,{get:e[t],enumerable:!0})},$=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of K(e))!G.call(r,n)&&n!==t&&w(r,n,{get:()=>e[n],enumerable:!(i=H(e,n))||i.enumerable});return r};var z=(r,e,t)=>(t=r!=null?q(W(r)):{},$(e||!r||!r.__esModule?w(t,"default",{value:r,enumerable:!0}):t,r)),Q=r=>$(w({},"__esModule",{value:!0}),r);var Ve={};Z(Ve,{BrowserStorageEngine:()=>I,ChecksumMismatchError:()=>y,DataStore:()=>A,DataStoreEngine:()=>T,DataStoreSerializer:()=>_,DatedError:()=>l,Debouncer:()=>P,FileStorageEngine:()=>O,MigrationError:()=>D,NanoEmitter:()=>S,ValidationError:()=>N,abtoa:()=>B,atoab:()=>j,autoPlural:()=>be,bitSetHas:()=>X,capitalize:()=>ye,clamp:()=>f,compress:()=>x,computeHash:()=>F,consumeGen:()=>ue,consumeStringGen:()=>de,createProgressBar:()=>De,darkenColor:()=>R,debounce:()=>Pe,decompress:()=>oe,defaultPbChars:()=>U,digitCount:()=>Y,fetchAdvanced:()=>ce,formatNumber:()=>ee,getListLength:()=>le,hexToRgb:()=>C,insertValues:()=>Te,joinArrayReadable:()=>Se,lightenColor:()=>ae,mapRange:()=>v,pauseFor:()=>me,pureObj:()=>pe,randRange:()=>b,randomId:()=>se,randomItem:()=>re,randomItemIndex:()=>E,randomizeArray:()=>ie,rgbToHex:()=>k,roundFixed:()=>V,scheduleExit:()=>ge,secsToTimeStr:()=>we,setImmediateInterval:()=>fe,setImmediateTimeoutLoop:()=>he,takeRandomItem:()=>ne,takeRandomItemIndex:()=>M,truncStr:()=>ve,valsWithin:()=>te});module.exports=Q(Ve);function X(r,e){return(r&e)===e}function f(r,e,t){return typeof t!="number"&&(t=e,e=0),Math.max(Math.min(r,t),e)}function Y(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),a=e&&i?i.length:0;return n+a}function ee(r,e,t){return r.toLocaleString(e,t==="short"?{notation:"compact",compactDisplay:"short",maximumFractionDigits:1}:{style:"decimal",maximumFractionDigits:0})}function v(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 b(...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,a=>Math.round(v(a,0,255,e,t)).toString(10)).join(""))}else return Math.floor(Math.random()*(t-e+1))+e}function V(r,e){let t=10**e;return Math.round(r*t)/t}function te(r,e,t=10,i=.5){return Math.abs(V(r,t)-V(e,t))<=i}function re(r){return E(r)[0]}function E(r){if(r.length===0)return[void 0,void 0];let e=b(r.length-1);return[r[e],e]}function ie(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 ne(r){var e;return(e=M(r))==null?void 0:e[0]}function M(r){let[e,t]=E(r);return t===void 0?[void 0,void 0]:(r.splice(t,1),[e,t])}function R(r,e,t=!1){var c;r=r.trim();let i=(d,p,h,g)=>(d=Math.max(0,Math.min(255,d-d*g/100)),p=Math.max(0,Math.min(255,p-p*g/100)),h=Math.max(0,Math.min(255,h-h*g/100)),[d,p,h]),n,a,o,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,a,o,s]=C(r);else if(r.startsWith("rgb")){let d=(c=r.match(/\d+(\.\d+)?/g))==null?void 0:c.map(Number);if(!d)throw new TypeError("Invalid RGB/RGBA color format");[n,a,o,s]=d}else throw new TypeError("Unsupported color format");if([n,a,o]=i(n,a,o,e),u)return k(n,a,o,s,r.startsWith("#"),t);if(r.startsWith("rgba"))return`rgba(${n}, ${a}, ${o}, ${s??NaN})`;if(r.startsWith("rgb"))return`rgb(${n}, ${a}, ${o})`;throw new TypeError("Unsupported color format")}function C(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(o=>o+o).join(""));let t=parseInt(r,16),i=t>>16&255,n=t>>8&255,a=t&255;return[f(i,0,255),f(n,0,255),f(a,0,255),typeof e=="number"?f(e,0,1):void 0]}function ae(r,e,t=!1){return R(r,e*-1,t)}function k(r,e,t,i,n=!0,a=!1){let o=s=>f(Math.round(s),0,255).toString(16).padStart(2,"0")[a?"toUpperCase":"toLowerCase"]();return`${n?"#":""}${o(r)}${o(e)}${o(t)}${i?o(i*255):""}`}function B(r){return btoa(new Uint8Array(r).reduce((e,t)=>e+String.fromCharCode(t),""))}function j(r){return Uint8Array.from(atob(r),e=>e.charCodeAt(0))}async function x(r,e,t="string"){let i=r instanceof ArrayBuffer?r:new TextEncoder().encode((r==null?void 0:r.toString())??String(r)),n=new CompressionStream(e),a=n.writable.getWriter();a.write(i),a.close();let o=await new Response(n.readable).arrayBuffer();return t==="arrayBuffer"?o:B(o)}async function oe(r,e,t="string"){let i=r instanceof ArrayBuffer?r:j((r==null?void 0:r.toString())??String(r)),n=new DecompressionStream(e),a=n.writable.getWriter();a.write(i),a.close();let o=await new Response(n.readable).arrayBuffer();return t==="arrayBuffer"?o:new TextDecoder().decode(o)}async function F(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(o=>o.toString(16).padStart(2,"0")).join("")}function se(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=[],a=i?[0,1]:[0];if(t){let o=new Uint8Array(r);crypto.getRandomValues(o),n=Array.from(o,s=>v(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(o=>/[a-zA-Z]/.test(o))?n.map(o=>a[b(0,a.length-1,t)]===1?o.toUpperCase():o).join(""):n.join("")}async function ue(r){return await(typeof r=="function"?r():r)}async function de(r){return typeof r=="string"?r:String(typeof r=="function"?await r():r)}async function ce(r,e={}){let{timeout:t=1e4}=e,i=new AbortController,{signal:n,...a}=e;n==null||n.addEventListener("abort",()=>i.abort());let o={},s;t>=0&&(s=setTimeout(()=>i.abort(),t),o={signal:i.signal});try{let u=await fetch(r,{...a,...o});return typeof s<"u"&&clearTimeout(s),u}catch(u){throw typeof s<"u"&&clearTimeout(s),new Error("Error while calling fetch",{cause:u})}}function le(r,e=!0){return"length"in r?r.length:"size"in r?r.size:"count"in r?r.count:e?0:NaN}function me(r,e,t=!1){return new Promise((i,n)=>{let a=setTimeout(()=>i(),r);e==null||e.addEventListener("abort",()=>{clearTimeout(a),t?n(new Error("The pause was aborted")):i()})})}function pe(r){return Object.assign(Object.create(null),r??{})}function fe(r,e,t){let i,n=()=>clearInterval(i),a=()=>{if(t!=null&&t.aborted)return n();r()};t==null||t.addEventListener("abort",n),a(),i=setInterval(a,e)}function he(r,e,t){let i,n=()=>clearTimeout(i),a=async()=>{if(t!=null&&t.aborted)return n();await r(),i=setTimeout(a,e)};t==null||t.addEventListener("abort",n),a()}function ge(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)t=()=>process.exit(r);else if(typeof Deno<"u"&&"exit"in Deno)t=()=>Deno.exit(r);else throw new Error("Cannot exit the process, no exit method available");setTimeout(t,e)}function be(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 ye(r){return r.charAt(0).toUpperCase()+r.slice(1)}var U={100:"\u2588",75:"\u2593",50:"\u2592",25:"\u2591",0:"\u2500"};function De(r,e,t=U){if(r===100)return t[100].repeat(e);let i=Math.floor(r/100*e),n=r/10*e-i,a="";n>=.75?a=t[75]:n>=.5?a=t[50]:n>=.25&&(a=t[25]);let o=t[100].repeat(i),s=t[0].repeat(e-i-(a?1:0));return`${o}${a}${s}`}function Te(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 Se(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 we(r){if(r<0)throw new TypeError("Seconds must be a positive number");let e=Math.floor(r/3600),t=Math.floor(r%3600/60),i=Math.floor(r%60);return[e?e+":":"",String(t).padStart(t>0||e>0?2:1,"0"),":",String(i).padStart(i>0||t>0||e>0?2:1,"0")].join("")}function ve(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 l=class extends Error{date;constructor(e,t){super(e,t),this.name=this.constructor.name,this.date=new Date}},y=class extends l{constructor(e,t){super(e,t),this.name="ChecksumMismatchError"}},D=class extends l{constructor(e,t){super(e,t),this.name="MigrationError"}},N=class extends l{constructor(e,t){super(e,t),this.name="ValidationError"}};var xe=1,A=class{id;formatVersion;defaultData;encodeData;decodeData;compressionFormat="deflate-raw";engine;firstInit=!0;cachedData;migrations;migrateIds=[];constructor(e){if(this.id=e.id,this.formatVersion=e.formatVersion,this.defaultData=e.defaultData,this.cachedData=e.defaultData,this.migrations=e.migrations,e.migrateIds&&(this.migrateIds=Array.isArray(e.migrateIds)?e.migrateIds:[e.migrateIds]),this.encodeData=e.encodeData,this.decodeData=e.decodeData,this.engine=typeof e.engine=="function"?e.engine():e.engine,typeof e.compressionFormat>"u"&&(e.compressionFormat="deflate-raw"),typeof e.compressionFormat=="string")this.encodeData=[e.compressionFormat,async t=>await x(t,e.compressionFormat,"string")],this.decodeData=[e.compressionFormat,async t=>await x(t,e.compressionFormat,"string")];else if("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]];else if(e.compressionFormat===null)this.encodeData=void 0,this.decodeData=void 0;else throw new TypeError("Either `compressionFormat` or `encodeData` and `decodeData` have to be set and valid, but not all three at a time. Please refer to the documentation for more info.");this.engine.setDataStoreOptions(e)}async loadData(){try{if(this.firstInit){this.firstInit=!1;let o=Number(await this.engine.getValue("__ds_fmt_ver",0));if(isNaN(o)||o<1){let s=await this.engine.getValue(`_uucfg-${this.id}`,null);if(s){let u=Number(await this.engine.getValue(`_uucfgver-${this.id}`,NaN)),c=await this.engine.getValue(`_uucfgenc-${this.id}`,null),d=[],p=(h,g,J)=>{d.push(this.engine.setValue(g,J)),d.push(this.engine.deleteValue(h))};s&&p(`_uucfg-${this.id}`,`__ds-${this.id}-dat`,s),!isNaN(u)&&p(`_uucfgver-${this.id}`,`__ds-${this.id}-ver`,u),typeof c=="boolean"&&p(`_uucfgenc-${this.id}`,`__ds-${this.id}-enc`,c===!0?this.compressionFormat:null),await Promise.allSettled(d)}await this.engine.setValue("__ds_fmt_ver",xe)}}this.migrateIds.length>0&&(await this.migrateId(this.migrateIds),this.migrateIds=[]);let e=await this.engine.getValue(`__ds-${this.id}-dat`,JSON.stringify(this.defaultData)),t=Number(await this.engine.getValue(`__ds-${this.id}-ver`,NaN));if(typeof e!="string")return await this.saveDefaultData(),{...this.defaultData};let i=!!await this.engine.getValue(`__ds-${this.id}-enc`,!1),n=!1;isNaN(t)&&(await this.engine.setValue(`__ds-${this.id}-ver`,t=this.formatVersion),n=!0);let a=await this.engine.deserializeData(e,i);return t<this.formatVersion&&this.migrations&&(a=await this.runMigrations(a,t)),n&&await this.setData(a),this.cachedData=this.engine.deepCopy(a)}catch(e){return console.warn("Error while parsing JSON data, resetting it to the default value.",e),await this.saveDefaultData(),this.defaultData}}getData(){return this.engine.deepCopy(this.cachedData)}setData(e){this.cachedData=e;let t=this.encodingEnabled();return new Promise(async i=>{await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(e,t)),this.engine.setValue(`__ds-${this.id}-ver`,this.formatVersion),this.engine.setValue(`__ds-${this.id}-enc`,t)]),i()})}async saveDefaultData(){this.cachedData=this.defaultData;let e=this.encodingEnabled();await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(this.defaultData,e)),this.engine.setValue(`__ds-${this.id}-ver`,this.formatVersion),this.engine.setValue(`__ds-${this.id}-enc`,e)])}async deleteData(){await Promise.allSettled([this.engine.deleteValue(`__ds-${this.id}-dat`),this.engine.deleteValue(`__ds-${this.id}-ver`),this.engine.deleteValue(`__ds-${this.id}-enc`)])}encodingEnabled(){return!!(this.encodeData&&this.decodeData)}async runMigrations(e,t,i=!0){if(!this.migrations)return e;let n=e,a=Object.entries(this.migrations).sort(([s],[u])=>Number(s)-Number(u)),o=t;for(let[s,u]of a){let c=Number(s);if(t<this.formatVersion&&t<c)try{let d=u(n);n=d instanceof Promise?await d:d,o=t=c}catch(d){if(!i)throw new D(`Error while running migration function for format version '${s}'`,{cause:d});return await this.saveDefaultData(),this.getData()}}return await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(n)),this.engine.setValue(`__ds-${this.id}-ver`,o),this.engine.setValue(`__ds-${this.id}-enc`,this.encodingEnabled())]),this.cachedData={...n}}async migrateId(e){let t=Array.isArray(e)?e:[e];await Promise.all(t.map(async i=>{let n=await this.engine.getValue(`__ds-${i}-dat`,JSON.stringify(this.defaultData)),a=Number(await this.engine.getValue(`__ds-${i}-ver`,NaN)),o=!!await this.engine.getValue(`__ds-${i}-enc`,!1);if(n===void 0||isNaN(a))return;let s=await this.engine.deserializeData(n,o);await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(s)),this.engine.setValue(`__ds-${this.id}-ver`,a),this.engine.setValue(`__ds-${this.id}-enc`,o),this.engine.deleteValue(`__ds-${i}-dat`),this.engine.deleteValue(`__ds-${i}-ver`),this.engine.deleteValue(`__ds-${i}-enc`)])}))}};var T=class{dataStoreOptions;setDataStoreOptions(e){this.dataStoreOptions=e}async serializeData(e,t){var a,o,s,u,c;let i=JSON.stringify(e);if(!t||!((a=this.dataStoreOptions)!=null&&a.encodeData)||!((o=this.dataStoreOptions)!=null&&o.decodeData))return i;let n=(c=(u=(s=this.dataStoreOptions)==null?void 0:s.encodeData)==null?void 0:u[1])==null?void 0:c.call(u,i);return n instanceof Promise?await n:n}async deserializeData(e,t){var n,a,o;let i=(n=this.dataStoreOptions)!=null&&n.decodeData&&t?(o=(a=this.dataStoreOptions.decodeData)==null?void 0:a[1])==null?void 0:o.call(a,e):void 0;return i instanceof Promise&&(i=await i),JSON.parse(i??e)}deepCopy(e){try{if("structuredClone"in globalThis)return structuredClone(e)}catch{}return JSON.parse(JSON.stringify(e))}},I=class extends T{options;constructor(e){super(),this.options={type:"localStorage",...e}}async getValue(e,t){return(this.options.type==="localStorage"?globalThis.localStorage.getItem(e):globalThis.sessionStorage.getItem(e))??t}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)}},m,O=class extends T{options;constructor(e){super(),this.options={filePath:t=>`.ds-${t}`,...e}}async readFile(){var e,t,i;try{if(m||(m=(await import("fs/promises")).default),!m)throw new l("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new Error("'node:fs/promises' module not available")});let n=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id),a=await m.readFile(n,"utf-8");return a?JSON.parse(await((i=(t=(e=this.dataStoreOptions)==null?void 0:e.decodeData)==null?void 0:t[1])==null?void 0:i.call(t,a))??a):void 0}catch{return}}async writeFile(e){var t,i,n;try{if(m||(m=(await import("fs/promises")).default),!m)throw new l("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new Error("'node:fs/promises' module not available")});let a=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id);await m.mkdir(a.slice(0,a.lastIndexOf("/")),{recursive:!0}),await m.writeFile(a,await((n=(i=(t=this.dataStoreOptions)==null?void 0:t.encodeData)==null?void 0:i[1])==null?void 0:n.call(i,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 n===void 0?t:typeof n=="string"?n:String(n??t)}async setValue(e,t){let i=await this.readFile();i||(i={}),i[e]=t,await this.writeFile(i)}async deleteValue(e){let t=await this.readFile();t&&(delete t[e],await this.writeFile(t))}};var _=class r{stores;options;constructor(e,t={}){if(!crypto||!crypto.subtle)throw new Error("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,...t}}async calcChecksum(e){return F(e,"SHA-256")}async serializePartial(e,t=!0,i=!0){let n=[];for(let a of this.stores.filter(o=>typeof e=="function"?e(o.id):e.includes(o.id))){let o=t&&a.encodingEnabled()?await a.encodeData[1](JSON.stringify(a.getData())):JSON.stringify(a.getData());n.push({id:a.id,data:o,formatVersion:a.formatVersion,encoded:t&&a.encodingEnabled(),checksum:this.options.addChecksum?await this.calcChecksum(o):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.");for(let n of i.filter(a=>typeof e=="function"?e(a.id):e.includes(a.id))){let a=this.stores.find(s=>s.id===n.id);if(!a)throw new Error(`DataStore instance with ID "${n.id}" not found! Make sure to provide it in the DataStoreSerializer constructor.`);if(this.options.ensureIntegrity&&typeof n.checksum=="string"){let s=await this.calcChecksum(n.data);if(s!==n.checksum)throw new y(`Checksum mismatch for DataStore with ID "${n.id}"!
2
2
  Expected: ${n.checksum}
3
- Has: ${s}`)}let o=n.encoded&&a.encodingEnabled()?await a.decodeData[1](n.data):n.data;n.formatVersion&&!isNaN(Number(n.formatVersion))&&Number(n.formatVersion)<a.formatVersion?await a.runMigrations(JSON.parse(o),Number(n.formatVersion),!1):await a.setData(JSON.parse(o))}}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 L=()=>({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 S=class{events=L();eventUnsubscribes=[];emitterOptions;constructor(e={}){this.emitterOptions={publicEmit:!1,...e}}on(e,t){let i,n=()=>{i&&(i(),this.eventUnsubscribes=this.eventUnsubscribes.filter(a=>a!==i))};return i=this.events.on(e,t),this.eventUnsubscribes.push(i),n}once(e,t){return new Promise(i=>{let n,a=(...o)=>{t==null||t(...o),n==null||n(),i(o)};n=this.events.on(e,a),this.eventUnsubscribes.push(n)})}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 P=class extends S{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=(...a)=>{this.queuedCall=void 0,this.emit("call",...a),this.listeners.forEach(o=>o.call(this,...a))},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 xe(r,e=200,t="immediate"){let i=new P(e,t);i.addListener(r);let n=(...a)=>i.call(...a);return n.debouncer=i,n}
3
+ Has: ${s}`)}let o=n.encoded&&a.encodingEnabled()?await a.decodeData[1](n.data):n.data;n.formatVersion&&!isNaN(Number(n.formatVersion))&&Number(n.formatVersion)<a.formatVersion?await a.runMigrations(JSON.parse(o),Number(n.formatVersion),!1):await a.setData(JSON.parse(o))}}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 L=()=>({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 S=class{events=L();eventUnsubscribes=[];emitterOptions;constructor(e={}){this.emitterOptions={publicEmit:!1,...e}}on(e,t){let i,n=()=>{i&&(i(),this.eventUnsubscribes=this.eventUnsubscribes.filter(a=>a!==i))};return i=this.events.on(e,t),this.eventUnsubscribes.push(i),n}once(e,t){return new Promise(i=>{let n,a=(...o)=>{t==null||t(...o),n==null||n(),i(o)};n=this.events.on(e,a),this.eventUnsubscribes.push(n)})}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 P=class extends S{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=(...a)=>{this.queuedCall=void 0,this.emit("call",...a),this.listeners.forEach(o=>o.call(this,...a))},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 Pe(r,e=200,t="immediate"){let i=new P(e,t);i.addListener(r);let n=(...a)=>i.call(...a);return n.debouncer=i,n}
4
4
  //# sourceMappingURL=CoreUtils.min.cjs.map
@@ -1,4 +1,4 @@
1
- function L(r,e){return(r&e)===e}function f(r,e,t){return typeof t!="number"&&(t=e,e=0),Math.max(Math.min(r,t),e)}function J(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),a=e&&i?i.length:0;return n+a}function q(r,e,t){return r.toLocaleString(e,t==="short"?{notation:"compact",compactDisplay:"short",maximumFractionDigits:1}:{style:"decimal",maximumFractionDigits:0})}function w(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 b(...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,a=>Math.round(w(a,0,255,e,t)).toString(10)).join(""))}else return Math.floor(Math.random()*(t-e+1))+e}function P(r,e){let t=10**e;return Math.round(r*t)/t}function H(r,e,t=10,i=.5){return Math.abs(P(r,t)-P(e,t))<=i}function G(r){return V(r)[0]}function V(r){if(r.length===0)return[void 0,void 0];let e=b(r.length-1);return[r[e],e]}function Z(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 Q(r){var e;return(e=z(r))==null?void 0:e[0]}function z(r){let[e,t]=V(r);return t===void 0?[void 0,void 0]:(r.splice(t,1),[e,t])}function M(r,e,t=!1){var d;r=r.trim();let i=(c,l,p,h)=>(c=Math.max(0,Math.min(255,c-c*h/100)),l=Math.max(0,Math.min(255,l-l*h/100)),p=Math.max(0,Math.min(255,p-p*h/100)),[c,l,p]),n,a,o,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,a,o,s]=R(r);else if(r.startsWith("rgb")){let c=(d=r.match(/\d+(\.\d+)?/g))==null?void 0:d.map(Number);if(!c)throw new TypeError("Invalid RGB/RGBA color format");[n,a,o,s]=c}else throw new TypeError("Unsupported color format");if([n,a,o]=i(n,a,o,e),u)return k(n,a,o,s,r.startsWith("#"),t);if(r.startsWith("rgba"))return`rgba(${n}, ${a}, ${o}, ${s??NaN})`;if(r.startsWith("rgb"))return`rgb(${n}, ${a}, ${o})`;throw new TypeError("Unsupported color format")}function R(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(o=>o+o).join(""));let t=parseInt(r,16),i=t>>16&255,n=t>>8&255,a=t&255;return[f(i,0,255),f(n,0,255),f(a,0,255),typeof e=="number"?f(e,0,1):void 0]}function ee(r,e,t=!1){return M(r,e*-1,t)}function k(r,e,t,i,n=!0,a=!1){let o=s=>f(Math.round(s),0,255).toString(16).padStart(2,"0")[a?"toUpperCase":"toLowerCase"]();return`${n?"#":""}${o(r)}${o(e)}${o(t)}${i?o(i*255):""}`}function C(r){return btoa(new Uint8Array(r).reduce((e,t)=>e+String.fromCharCode(t),""))}function B(r){return Uint8Array.from(atob(r),e=>e.charCodeAt(0))}async function v(r,e,t="string"){let i=r instanceof ArrayBuffer?r:new TextEncoder().encode((r==null?void 0:r.toString())??String(r)),n=new CompressionStream(e),a=n.writable.getWriter();a.write(i),a.close();let o=await new Response(n.readable).arrayBuffer();return t==="arrayBuffer"?o:C(o)}async function ie(r,e,t="string"){let i=r instanceof ArrayBuffer?r:B((r==null?void 0:r.toString())??String(r)),n=new DecompressionStream(e),a=n.writable.getWriter();a.write(i),a.close();let o=await new Response(n.readable).arrayBuffer();return t==="arrayBuffer"?o:new TextDecoder().decode(o)}async function F(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(o=>o.toString(16).padStart(2,"0")).join("")}function ne(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=[],a=i?[0,1]:[0];if(t){let o=new Uint8Array(r);crypto.getRandomValues(o),n=Array.from(o,s=>w(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(o=>/[a-zA-Z]/.test(o))?n.map(o=>a[b(0,a.length-1,t)]===1?o.toUpperCase():o).join(""):n.join("")}async function oe(r){return await(typeof r=="function"?r():r)}async function se(r){return typeof r=="string"?r:String(typeof r=="function"?await r():r)}async function ue(r,e={}){let{timeout:t=1e4}=e,i=new AbortController,{signal:n,...a}=e;n==null||n.addEventListener("abort",()=>i.abort());let o={},s;t>=0&&(s=setTimeout(()=>i.abort(),t),o={signal:i.signal});try{let u=await fetch(r,{...a,...o});return typeof s<"u"&&clearTimeout(s),u}catch(u){throw typeof s<"u"&&clearTimeout(s),new Error("Error while calling fetch",{cause:u})}}function ce(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 a=setTimeout(()=>i(),r);e==null||e.addEventListener("abort",()=>{clearTimeout(a),t?n(new Error("The pause was aborted")):i()})})}function le(r){return Object.assign(Object.create(null),r??{})}function me(r,e,t){let i,n=()=>clearInterval(i),a=()=>{if(t!=null&&t.aborted)return n();r()};t==null||t.addEventListener("abort",n),a(),i=setInterval(a,e)}function pe(r,e,t){let i,n=()=>clearTimeout(i),a=async()=>{if(t!=null&&t.aborted)return n();await r(),i=setTimeout(a,e)};t==null||t.addEventListener("abort",n),a()}function he(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 ge(r){return r.charAt(0).toUpperCase()+r.slice(1)}var j={100:"\u2588",75:"\u2593",50:"\u2592",25:"\u2591",0:"\u2500"};function be(r,e,t=j){if(r===100)return t[100].repeat(e);let i=Math.floor(r/100*e),n=r/10*e-i,a="";n>=.75?a=t[75]:n>=.5?a=t[50]:n>=.25&&(a=t[25]);let o=t[100].repeat(i),s=t[0].repeat(e-i-(a?1:0));return`${o}${a}${s}`}function ye(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 De(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 Te(r){if(r<0)throw new TypeError("Seconds must be a positive number");let e=Math.floor(r/3600),t=Math.floor(r%3600/60),i=Math.floor(r%60);return[e?e+":":"",String(t).padStart(t>0||e>0?2:1,"0"),":",String(i).padStart(i>0||t>0||e>0?2:1,"0")].join("")}function Se(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 g=class extends Error{date;constructor(e,t){super(e,t),this.name=this.constructor.name,this.date=new Date}},y=class extends g{constructor(e,t){super(e,t),this.name="ChecksumMismatchError"}},D=class extends g{constructor(e,t){super(e,t),this.name="MigrationError"}},E=class extends g{constructor(e,t){super(e,t),this.name="ValidationError"}};var U=1,A=class{id;formatVersion;defaultData;encodeData;decodeData;compressionFormat="deflate-raw";engine;firstInit=!0;cachedData;migrations;migrateIds=[];constructor(e){if(this.id=e.id,this.formatVersion=e.formatVersion,this.defaultData=e.defaultData,this.cachedData=e.defaultData,this.migrations=e.migrations,e.migrateIds&&(this.migrateIds=Array.isArray(e.migrateIds)?e.migrateIds:[e.migrateIds]),this.encodeData=e.encodeData,this.decodeData=e.decodeData,this.engine=typeof e.engine=="function"?e.engine():e.engine,typeof e.compressionFormat>"u"&&(e.compressionFormat="deflate-raw"),typeof e.compressionFormat=="string")this.encodeData=[e.compressionFormat,async t=>await v(t,e.compressionFormat,"string")],this.decodeData=[e.compressionFormat,async t=>await v(t,e.compressionFormat,"string")];else if("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]];else if(e.compressionFormat===null)this.encodeData=void 0,this.decodeData=void 0;else throw new TypeError("Either `compressionFormat` or `encodeData` and `decodeData` have to be set and valid, but not all three at a time. Please refer to the documentation for more info.");this.engine.setDataStoreOptions(e)}async loadData(){try{if(this.firstInit){this.firstInit=!1;let o=Number(await this.engine.getValue("__ds_fmt_ver",0));if(isNaN(o)||o<1){let s=await this.engine.getValue(`_uucfg-${this.id}`,null);if(s){let u=Number(await this.engine.getValue(`_uucfgver-${this.id}`,NaN)),d=await this.engine.getValue(`_uucfgenc-${this.id}`,null),c=[],l=(p,h,$)=>{c.push(this.engine.setValue(h,$)),c.push(this.engine.deleteValue(p))};s&&l(`_uucfg-${this.id}`,`__ds-${this.id}-dat`,s),!isNaN(u)&&l(`_uucfgver-${this.id}`,`__ds-${this.id}-ver`,u),typeof d=="boolean"&&l(`_uucfgenc-${this.id}`,`__ds-${this.id}-enc`,d===!0?this.compressionFormat:null),await Promise.allSettled(c)}await this.engine.setValue("__ds_fmt_ver",U)}}this.migrateIds.length>0&&(await this.migrateId(this.migrateIds),this.migrateIds=[]);let e=await this.engine.getValue(`__ds-${this.id}-dat`,JSON.stringify(this.defaultData)),t=Number(await this.engine.getValue(`__ds-${this.id}-ver`,NaN));if(typeof e!="string")return await this.saveDefaultData(),{...this.defaultData};let i=!!await this.engine.getValue(`__ds-${this.id}-enc`,!1),n=!1;isNaN(t)&&(await this.engine.setValue(`__ds-${this.id}-ver`,t=this.formatVersion),n=!0);let a=await this.engine.deserializeData(e,i);return t<this.formatVersion&&this.migrations&&(a=await this.runMigrations(a,t)),n&&await this.setData(a),this.cachedData=this.engine.deepCopy(a)}catch(e){return console.warn("Error while parsing JSON data, resetting it to the default value.",e),await this.saveDefaultData(),this.defaultData}}getData(){return this.engine.deepCopy(this.cachedData)}setData(e){this.cachedData=e;let t=this.encodingEnabled();return new Promise(async i=>{await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(e,t)),this.engine.setValue(`__ds-${this.id}-ver`,this.formatVersion),this.engine.setValue(`__ds-${this.id}-enc`,t)]),i()})}async saveDefaultData(){this.cachedData=this.defaultData;let e=this.encodingEnabled();await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(this.defaultData,e)),this.engine.setValue(`__ds-${this.id}-ver`,this.formatVersion),this.engine.setValue(`__ds-${this.id}-enc`,e)])}async deleteData(){await Promise.allSettled([this.engine.deleteValue(`__ds-${this.id}-dat`),this.engine.deleteValue(`__ds-${this.id}-ver`),this.engine.deleteValue(`__ds-${this.id}-enc`)])}encodingEnabled(){return!!(this.encodeData&&this.decodeData)}async runMigrations(e,t,i=!0){if(!this.migrations)return e;let n=e,a=Object.entries(this.migrations).sort(([s],[u])=>Number(s)-Number(u)),o=t;for(let[s,u]of a){let d=Number(s);if(t<this.formatVersion&&t<d)try{let c=u(n);n=c instanceof Promise?await c:c,o=t=d}catch(c){if(!i)throw new D(`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.engine.setValue(`__ds-${this.id}-ver`,o),this.engine.setValue(`__ds-${this.id}-enc`,this.encodingEnabled())]),this.cachedData={...n}}async migrateId(e){let t=Array.isArray(e)?e:[e];await Promise.all(t.map(async i=>{let n=await this.engine.getValue(`__ds-${i}-dat`,JSON.stringify(this.defaultData)),a=Number(await this.engine.getValue(`__ds-${i}-ver`,NaN)),o=!!await this.engine.getValue(`__ds-${i}-enc`,!1);if(n===void 0||isNaN(a))return;let s=await this.engine.deserializeData(n,o);await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(s)),this.engine.setValue(`__ds-${this.id}-ver`,a),this.engine.setValue(`__ds-${this.id}-enc`,o),this.engine.deleteValue(`__ds-${i}-dat`),this.engine.deleteValue(`__ds-${i}-ver`),this.engine.deleteValue(`__ds-${i}-enc`)])}))}};var T=class{dataStoreOptions;setDataStoreOptions(e){this.dataStoreOptions=e}async serializeData(e,t){var a,o,s,u,d;let i=JSON.stringify(e);if(!t||!((a=this.dataStoreOptions)!=null&&a.encodeData)||!((o=this.dataStoreOptions)!=null&&o.decodeData))return i;let n=(d=(u=(s=this.dataStoreOptions)==null?void 0:s.encodeData)==null?void 0:u[1])==null?void 0:d.call(u,i);return n instanceof Promise?await n:n}async deserializeData(e,t){var n,a,o;let i=(n=this.dataStoreOptions)!=null&&n.decodeData&&t?(o=(a=this.dataStoreOptions.decodeData)==null?void 0:a[1])==null?void 0:o.call(a,e):void 0;return i instanceof Promise&&(i=await i),JSON.parse(i??e)}deepCopy(e){try{if("structuredClone"in globalThis)return structuredClone(e)}catch{}return JSON.parse(JSON.stringify(e))}},N=class extends T{options;constructor(e){super(),this.options={type:"localStorage",...e}}async getValue(e,t){return(this.options.type==="localStorage"?globalThis.localStorage.getItem(e):globalThis.sessionStorage.getItem(e))??t}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)}},m,I=class extends T{options;constructor(e){super(),this.options={filePath:t=>`.ds-${t}`,...e}}async readFile(){var e,t,i;try{m||(m=(await import("node:fs/promises")).default);let n=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id),a=await m.readFile(n,"utf-8");return a?JSON.parse(await((i=(t=(e=this.dataStoreOptions)==null?void 0:e.decodeData)==null?void 0:t[1])==null?void 0:i.call(t,a))??a):void 0}catch{return}}async writeFile(e){var t,i,n;try{m||(m=(await import("node:fs/promises")).default);let a=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id);await m.mkdir(a.slice(0,a.lastIndexOf("/")),{recursive:!0}),await m.writeFile(a,await((n=(i=(t=this.dataStoreOptions)==null?void 0:t.encodeData)==null?void 0:i[1])==null?void 0:n.call(i,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 n===void 0?t:typeof n=="string"?n:String(n??t)}async setValue(e,t){let i=await this.readFile();i||(i={}),i[e]=t,await this.writeFile(i)}async deleteValue(e){let t=await this.readFile();t&&(delete t[e],await this.writeFile(t))}};var O=class r{stores;options;constructor(e,t={}){if(!crypto||!crypto.subtle)throw new Error("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,...t}}async calcChecksum(e){return F(e,"SHA-256")}async serializePartial(e,t=!0,i=!0){let n=[];for(let a of this.stores.filter(o=>typeof e=="function"?e(o.id):e.includes(o.id))){let o=t&&a.encodingEnabled()?await a.encodeData[1](JSON.stringify(a.getData())):JSON.stringify(a.getData());n.push({id:a.id,data:o,formatVersion:a.formatVersion,encoded:t&&a.encodingEnabled(),checksum:this.options.addChecksum?await this.calcChecksum(o):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.");for(let n of i.filter(a=>typeof e=="function"?e(a.id):e.includes(a.id))){let a=this.stores.find(s=>s.id===n.id);if(!a)throw new Error(`DataStore instance with ID "${n.id}" not found! Make sure to provide it in the DataStoreSerializer constructor.`);if(this.options.ensureIntegrity&&typeof n.checksum=="string"){let s=await this.calcChecksum(n.data);if(s!==n.checksum)throw new y(`Checksum mismatch for DataStore with ID "${n.id}"!
1
+ function L(r,e){return(r&e)===e}function h(r,e,t){return typeof t!="number"&&(t=e,e=0),Math.max(Math.min(r,t),e)}function J(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),a=e&&i?i.length:0;return n+a}function q(r,e,t){return r.toLocaleString(e,t==="short"?{notation:"compact",compactDisplay:"short",maximumFractionDigits:1}:{style:"decimal",maximumFractionDigits:0})}function w(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 b(...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,a=>Math.round(w(a,0,255,e,t)).toString(10)).join(""))}else return Math.floor(Math.random()*(t-e+1))+e}function P(r,e){let t=10**e;return Math.round(r*t)/t}function H(r,e,t=10,i=.5){return Math.abs(P(r,t)-P(e,t))<=i}function G(r){return V(r)[0]}function V(r){if(r.length===0)return[void 0,void 0];let e=b(r.length-1);return[r[e],e]}function Z(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 Q(r){var e;return(e=z(r))==null?void 0:e[0]}function z(r){let[e,t]=V(r);return t===void 0?[void 0,void 0]:(r.splice(t,1),[e,t])}function M(r,e,t=!1){var c;r=r.trim();let i=(d,m,f,g)=>(d=Math.max(0,Math.min(255,d-d*g/100)),m=Math.max(0,Math.min(255,m-m*g/100)),f=Math.max(0,Math.min(255,f-f*g/100)),[d,m,f]),n,a,o,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,a,o,s]=R(r);else if(r.startsWith("rgb")){let d=(c=r.match(/\d+(\.\d+)?/g))==null?void 0:c.map(Number);if(!d)throw new TypeError("Invalid RGB/RGBA color format");[n,a,o,s]=d}else throw new TypeError("Unsupported color format");if([n,a,o]=i(n,a,o,e),u)return C(n,a,o,s,r.startsWith("#"),t);if(r.startsWith("rgba"))return`rgba(${n}, ${a}, ${o}, ${s??NaN})`;if(r.startsWith("rgb"))return`rgb(${n}, ${a}, ${o})`;throw new TypeError("Unsupported color format")}function R(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(o=>o+o).join(""));let t=parseInt(r,16),i=t>>16&255,n=t>>8&255,a=t&255;return[h(i,0,255),h(n,0,255),h(a,0,255),typeof e=="number"?h(e,0,1):void 0]}function ee(r,e,t=!1){return M(r,e*-1,t)}function C(r,e,t,i,n=!0,a=!1){let o=s=>h(Math.round(s),0,255).toString(16).padStart(2,"0")[a?"toUpperCase":"toLowerCase"]();return`${n?"#":""}${o(r)}${o(e)}${o(t)}${i?o(i*255):""}`}function k(r){return btoa(new Uint8Array(r).reduce((e,t)=>e+String.fromCharCode(t),""))}function B(r){return Uint8Array.from(atob(r),e=>e.charCodeAt(0))}async function v(r,e,t="string"){let i=r instanceof ArrayBuffer?r:new TextEncoder().encode((r==null?void 0:r.toString())??String(r)),n=new CompressionStream(e),a=n.writable.getWriter();a.write(i),a.close();let o=await new Response(n.readable).arrayBuffer();return t==="arrayBuffer"?o:k(o)}async function ie(r,e,t="string"){let i=r instanceof ArrayBuffer?r:B((r==null?void 0:r.toString())??String(r)),n=new DecompressionStream(e),a=n.writable.getWriter();a.write(i),a.close();let o=await new Response(n.readable).arrayBuffer();return t==="arrayBuffer"?o:new TextDecoder().decode(o)}async function E(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(o=>o.toString(16).padStart(2,"0")).join("")}function ne(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=[],a=i?[0,1]:[0];if(t){let o=new Uint8Array(r);crypto.getRandomValues(o),n=Array.from(o,s=>w(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(o=>/[a-zA-Z]/.test(o))?n.map(o=>a[b(0,a.length-1,t)]===1?o.toUpperCase():o).join(""):n.join("")}async function oe(r){return await(typeof r=="function"?r():r)}async function se(r){return typeof r=="string"?r:String(typeof r=="function"?await r():r)}async function ue(r,e={}){let{timeout:t=1e4}=e,i=new AbortController,{signal:n,...a}=e;n==null||n.addEventListener("abort",()=>i.abort());let o={},s;t>=0&&(s=setTimeout(()=>i.abort(),t),o={signal:i.signal});try{let u=await fetch(r,{...a,...o});return typeof s<"u"&&clearTimeout(s),u}catch(u){throw typeof s<"u"&&clearTimeout(s),new Error("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 ce(r,e,t=!1){return new Promise((i,n)=>{let a=setTimeout(()=>i(),r);e==null||e.addEventListener("abort",()=>{clearTimeout(a),t?n(new Error("The pause was aborted")):i()})})}function le(r){return Object.assign(Object.create(null),r??{})}function me(r,e,t){let i,n=()=>clearInterval(i),a=()=>{if(t!=null&&t.aborted)return n();r()};t==null||t.addEventListener("abort",n),a(),i=setInterval(a,e)}function pe(r,e,t){let i,n=()=>clearTimeout(i),a=async()=>{if(t!=null&&t.aborted)return n();await r(),i=setTimeout(a,e)};t==null||t.addEventListener("abort",n),a()}function fe(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)t=()=>process.exit(r);else if(typeof Deno<"u"&&"exit"in Deno)t=()=>Deno.exit(r);else throw new Error("Cannot exit the process, no exit method available");setTimeout(t,e)}function ge(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 be(r){return r.charAt(0).toUpperCase()+r.slice(1)}var j={100:"\u2588",75:"\u2593",50:"\u2592",25:"\u2591",0:"\u2500"};function ye(r,e,t=j){if(r===100)return t[100].repeat(e);let i=Math.floor(r/100*e),n=r/10*e-i,a="";n>=.75?a=t[75]:n>=.5?a=t[50]:n>=.25&&(a=t[25]);let o=t[100].repeat(i),s=t[0].repeat(e-i-(a?1:0));return`${o}${a}${s}`}function De(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 Te(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 Se(r){if(r<0)throw new TypeError("Seconds must be a positive number");let e=Math.floor(r/3600),t=Math.floor(r%3600/60),i=Math.floor(r%60);return[e?e+":":"",String(t).padStart(t>0||e>0?2:1,"0"),":",String(i).padStart(i>0||t>0||e>0?2:1,"0")].join("")}function we(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 p=class extends Error{date;constructor(e,t){super(e,t),this.name=this.constructor.name,this.date=new Date}},y=class extends p{constructor(e,t){super(e,t),this.name="ChecksumMismatchError"}},D=class extends p{constructor(e,t){super(e,t),this.name="MigrationError"}},F=class extends p{constructor(e,t){super(e,t),this.name="ValidationError"}};var U=1,N=class{id;formatVersion;defaultData;encodeData;decodeData;compressionFormat="deflate-raw";engine;firstInit=!0;cachedData;migrations;migrateIds=[];constructor(e){if(this.id=e.id,this.formatVersion=e.formatVersion,this.defaultData=e.defaultData,this.cachedData=e.defaultData,this.migrations=e.migrations,e.migrateIds&&(this.migrateIds=Array.isArray(e.migrateIds)?e.migrateIds:[e.migrateIds]),this.encodeData=e.encodeData,this.decodeData=e.decodeData,this.engine=typeof e.engine=="function"?e.engine():e.engine,typeof e.compressionFormat>"u"&&(e.compressionFormat="deflate-raw"),typeof e.compressionFormat=="string")this.encodeData=[e.compressionFormat,async t=>await v(t,e.compressionFormat,"string")],this.decodeData=[e.compressionFormat,async t=>await v(t,e.compressionFormat,"string")];else if("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]];else if(e.compressionFormat===null)this.encodeData=void 0,this.decodeData=void 0;else throw new TypeError("Either `compressionFormat` or `encodeData` and `decodeData` have to be set and valid, but not all three at a time. Please refer to the documentation for more info.");this.engine.setDataStoreOptions(e)}async loadData(){try{if(this.firstInit){this.firstInit=!1;let o=Number(await this.engine.getValue("__ds_fmt_ver",0));if(isNaN(o)||o<1){let s=await this.engine.getValue(`_uucfg-${this.id}`,null);if(s){let u=Number(await this.engine.getValue(`_uucfgver-${this.id}`,NaN)),c=await this.engine.getValue(`_uucfgenc-${this.id}`,null),d=[],m=(f,g,$)=>{d.push(this.engine.setValue(g,$)),d.push(this.engine.deleteValue(f))};s&&m(`_uucfg-${this.id}`,`__ds-${this.id}-dat`,s),!isNaN(u)&&m(`_uucfgver-${this.id}`,`__ds-${this.id}-ver`,u),typeof c=="boolean"&&m(`_uucfgenc-${this.id}`,`__ds-${this.id}-enc`,c===!0?this.compressionFormat:null),await Promise.allSettled(d)}await this.engine.setValue("__ds_fmt_ver",U)}}this.migrateIds.length>0&&(await this.migrateId(this.migrateIds),this.migrateIds=[]);let e=await this.engine.getValue(`__ds-${this.id}-dat`,JSON.stringify(this.defaultData)),t=Number(await this.engine.getValue(`__ds-${this.id}-ver`,NaN));if(typeof e!="string")return await this.saveDefaultData(),{...this.defaultData};let i=!!await this.engine.getValue(`__ds-${this.id}-enc`,!1),n=!1;isNaN(t)&&(await this.engine.setValue(`__ds-${this.id}-ver`,t=this.formatVersion),n=!0);let a=await this.engine.deserializeData(e,i);return t<this.formatVersion&&this.migrations&&(a=await this.runMigrations(a,t)),n&&await this.setData(a),this.cachedData=this.engine.deepCopy(a)}catch(e){return console.warn("Error while parsing JSON data, resetting it to the default value.",e),await this.saveDefaultData(),this.defaultData}}getData(){return this.engine.deepCopy(this.cachedData)}setData(e){this.cachedData=e;let t=this.encodingEnabled();return new Promise(async i=>{await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(e,t)),this.engine.setValue(`__ds-${this.id}-ver`,this.formatVersion),this.engine.setValue(`__ds-${this.id}-enc`,t)]),i()})}async saveDefaultData(){this.cachedData=this.defaultData;let e=this.encodingEnabled();await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(this.defaultData,e)),this.engine.setValue(`__ds-${this.id}-ver`,this.formatVersion),this.engine.setValue(`__ds-${this.id}-enc`,e)])}async deleteData(){await Promise.allSettled([this.engine.deleteValue(`__ds-${this.id}-dat`),this.engine.deleteValue(`__ds-${this.id}-ver`),this.engine.deleteValue(`__ds-${this.id}-enc`)])}encodingEnabled(){return!!(this.encodeData&&this.decodeData)}async runMigrations(e,t,i=!0){if(!this.migrations)return e;let n=e,a=Object.entries(this.migrations).sort(([s],[u])=>Number(s)-Number(u)),o=t;for(let[s,u]of a){let c=Number(s);if(t<this.formatVersion&&t<c)try{let d=u(n);n=d instanceof Promise?await d:d,o=t=c}catch(d){if(!i)throw new D(`Error while running migration function for format version '${s}'`,{cause:d});return await this.saveDefaultData(),this.getData()}}return await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(n)),this.engine.setValue(`__ds-${this.id}-ver`,o),this.engine.setValue(`__ds-${this.id}-enc`,this.encodingEnabled())]),this.cachedData={...n}}async migrateId(e){let t=Array.isArray(e)?e:[e];await Promise.all(t.map(async i=>{let n=await this.engine.getValue(`__ds-${i}-dat`,JSON.stringify(this.defaultData)),a=Number(await this.engine.getValue(`__ds-${i}-ver`,NaN)),o=!!await this.engine.getValue(`__ds-${i}-enc`,!1);if(n===void 0||isNaN(a))return;let s=await this.engine.deserializeData(n,o);await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(s)),this.engine.setValue(`__ds-${this.id}-ver`,a),this.engine.setValue(`__ds-${this.id}-enc`,o),this.engine.deleteValue(`__ds-${i}-dat`),this.engine.deleteValue(`__ds-${i}-ver`),this.engine.deleteValue(`__ds-${i}-enc`)])}))}};var T=class{dataStoreOptions;setDataStoreOptions(e){this.dataStoreOptions=e}async serializeData(e,t){var a,o,s,u,c;let i=JSON.stringify(e);if(!t||!((a=this.dataStoreOptions)!=null&&a.encodeData)||!((o=this.dataStoreOptions)!=null&&o.decodeData))return i;let n=(c=(u=(s=this.dataStoreOptions)==null?void 0:s.encodeData)==null?void 0:u[1])==null?void 0:c.call(u,i);return n instanceof Promise?await n:n}async deserializeData(e,t){var n,a,o;let i=(n=this.dataStoreOptions)!=null&&n.decodeData&&t?(o=(a=this.dataStoreOptions.decodeData)==null?void 0:a[1])==null?void 0:o.call(a,e):void 0;return i instanceof Promise&&(i=await i),JSON.parse(i??e)}deepCopy(e){try{if("structuredClone"in globalThis)return structuredClone(e)}catch{}return JSON.parse(JSON.stringify(e))}},A=class extends T{options;constructor(e){super(),this.options={type:"localStorage",...e}}async getValue(e,t){return(this.options.type==="localStorage"?globalThis.localStorage.getItem(e):globalThis.sessionStorage.getItem(e))??t}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)}},l,I=class extends T{options;constructor(e){super(),this.options={filePath:t=>`.ds-${t}`,...e}}async readFile(){var e,t,i;try{if(l||(l=(await import("fs/promises")).default),!l)throw new p("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new Error("'node:fs/promises' module not available")});let n=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id),a=await l.readFile(n,"utf-8");return a?JSON.parse(await((i=(t=(e=this.dataStoreOptions)==null?void 0:e.decodeData)==null?void 0:t[1])==null?void 0:i.call(t,a))??a):void 0}catch{return}}async writeFile(e){var t,i,n;try{if(l||(l=(await import("fs/promises")).default),!l)throw new p("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new Error("'node:fs/promises' module not available")});let a=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id);await l.mkdir(a.slice(0,a.lastIndexOf("/")),{recursive:!0}),await l.writeFile(a,await((n=(i=(t=this.dataStoreOptions)==null?void 0:t.encodeData)==null?void 0:i[1])==null?void 0:n.call(i,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 n===void 0?t:typeof n=="string"?n:String(n??t)}async setValue(e,t){let i=await this.readFile();i||(i={}),i[e]=t,await this.writeFile(i)}async deleteValue(e){let t=await this.readFile();t&&(delete t[e],await this.writeFile(t))}};var O=class r{stores;options;constructor(e,t={}){if(!crypto||!crypto.subtle)throw new Error("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,...t}}async calcChecksum(e){return E(e,"SHA-256")}async serializePartial(e,t=!0,i=!0){let n=[];for(let a of this.stores.filter(o=>typeof e=="function"?e(o.id):e.includes(o.id))){let o=t&&a.encodingEnabled()?await a.encodeData[1](JSON.stringify(a.getData())):JSON.stringify(a.getData());n.push({id:a.id,data:o,formatVersion:a.formatVersion,encoded:t&&a.encodingEnabled(),checksum:this.options.addChecksum?await this.calcChecksum(o):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.");for(let n of i.filter(a=>typeof e=="function"?e(a.id):e.includes(a.id))){let a=this.stores.find(s=>s.id===n.id);if(!a)throw new Error(`DataStore instance with ID "${n.id}" not found! Make sure to provide it in the DataStoreSerializer constructor.`);if(this.options.ensureIntegrity&&typeof n.checksum=="string"){let s=await this.calcChecksum(n.data);if(s!==n.checksum)throw new y(`Checksum mismatch for DataStore with ID "${n.id}"!
2
2
  Expected: ${n.checksum}
3
- Has: ${s}`)}let o=n.encoded&&a.encodingEnabled()?await a.decodeData[1](n.data):n.data;n.formatVersion&&!isNaN(Number(n.formatVersion))&&Number(n.formatVersion)<a.formatVersion?await a.runMigrations(JSON.parse(o),Number(n.formatVersion),!1):await a.setData(JSON.parse(o))}}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 _=()=>({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 S=class{events=_();eventUnsubscribes=[];emitterOptions;constructor(e={}){this.emitterOptions={publicEmit:!1,...e}}on(e,t){let i,n=()=>{i&&(i(),this.eventUnsubscribes=this.eventUnsubscribes.filter(a=>a!==i))};return i=this.events.on(e,t),this.eventUnsubscribes.push(i),n}once(e,t){return new Promise(i=>{let n,a=(...o)=>{t==null||t(...o),n==null||n(),i(o)};n=this.events.on(e,a),this.eventUnsubscribes.push(n)})}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 x=class extends S{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=(...a)=>{this.queuedCall=void 0,this.emit("call",...a),this.listeners.forEach(o=>o.call(this,...a))},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 ze(r,e=200,t="immediate"){let i=new x(e,t);i.addListener(r);let n=(...a)=>i.call(...a);return n.debouncer=i,n}export{N as BrowserStorageEngine,y as ChecksumMismatchError,A as DataStore,T as DataStoreEngine,O as DataStoreSerializer,g as DatedError,x as Debouncer,I as FileStorageEngine,D as MigrationError,S as NanoEmitter,E as ValidationError,C as abtoa,B as atoab,he as autoPlural,L as bitSetHas,ge as capitalize,f as clamp,v as compress,F as computeHash,oe as consumeGen,se as consumeStringGen,be as createProgressBar,M as darkenColor,ze as debounce,ie as decompress,j as defaultPbChars,J as digitCount,ue as fetchAdvanced,q as formatNumber,ce as getListLength,R as hexToRgb,ye as insertValues,De as joinArrayReadable,ee as lightenColor,w as mapRange,de as pauseFor,le as pureObj,b as randRange,ne as randomId,G as randomItem,V as randomItemIndex,Z as randomizeArray,k as rgbToHex,P as roundFixed,Te as secsToTimeStr,me as setImmediateInterval,pe as setImmediateTimeoutLoop,Q as takeRandomItem,z as takeRandomItemIndex,Se as truncStr,H as valsWithin};
3
+ Has: ${s}`)}let o=n.encoded&&a.encodingEnabled()?await a.decodeData[1](n.data):n.data;n.formatVersion&&!isNaN(Number(n.formatVersion))&&Number(n.formatVersion)<a.formatVersion?await a.runMigrations(JSON.parse(o),Number(n.formatVersion),!1):await a.setData(JSON.parse(o))}}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 _=()=>({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 S=class{events=_();eventUnsubscribes=[];emitterOptions;constructor(e={}){this.emitterOptions={publicEmit:!1,...e}}on(e,t){let i,n=()=>{i&&(i(),this.eventUnsubscribes=this.eventUnsubscribes.filter(a=>a!==i))};return i=this.events.on(e,t),this.eventUnsubscribes.push(i),n}once(e,t){return new Promise(i=>{let n,a=(...o)=>{t==null||t(...o),n==null||n(),i(o)};n=this.events.on(e,a),this.eventUnsubscribes.push(n)})}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 x=class extends S{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=(...a)=>{this.queuedCall=void 0,this.emit("call",...a),this.listeners.forEach(o=>o.call(this,...a))},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 Re(r,e=200,t="immediate"){let i=new x(e,t);i.addListener(r);let n=(...a)=>i.call(...a);return n.debouncer=i,n}export{A as BrowserStorageEngine,y as ChecksumMismatchError,N as DataStore,T as DataStoreEngine,O as DataStoreSerializer,p as DatedError,x as Debouncer,I as FileStorageEngine,D as MigrationError,S as NanoEmitter,F as ValidationError,k as abtoa,B as atoab,ge as autoPlural,L as bitSetHas,be as capitalize,h as clamp,v as compress,E as computeHash,oe as consumeGen,se as consumeStringGen,ye as createProgressBar,M as darkenColor,Re as debounce,ie as decompress,j as defaultPbChars,J as digitCount,ue as fetchAdvanced,q as formatNumber,de as getListLength,R as hexToRgb,De as insertValues,Te as joinArrayReadable,ee as lightenColor,w as mapRange,ce as pauseFor,le as pureObj,b as randRange,ne as randomId,G as randomItem,V as randomItemIndex,Z as randomizeArray,C as rgbToHex,P as roundFixed,fe as scheduleExit,Se as secsToTimeStr,me as setImmediateInterval,pe as setImmediateTimeoutLoop,Q as takeRandomItem,z as takeRandomItemIndex,we as truncStr,H as valsWithin};
4
4
  //# sourceMappingURL=CoreUtils.min.mjs.map
@@ -16,9 +16,9 @@
16
16
 
17
17
 
18
18
 
19
- "use strict";var q=Object.create;var w=Object.defineProperty;var H=Object.getOwnPropertyDescriptor;var K=Object.getOwnPropertyNames;var W=Object.getPrototypeOf,G=Object.prototype.hasOwnProperty;var Z=(r,e)=>{for(var t in e)w(r,t,{get:e[t],enumerable:!0})},$=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of K(e))!G.call(r,n)&&n!==t&&w(r,n,{get:()=>e[n],enumerable:!(i=H(e,n))||i.enumerable});return r};var z=(r,e,t)=>(t=r!=null?q(W(r)):{},$(e||!r||!r.__esModule?w(t,"default",{value:r,enumerable:!0}):t,r)),Q=r=>$(w({},"__esModule",{value:!0}),r);var Pe={};Z(Pe,{BrowserStorageEngine:()=>I,ChecksumMismatchError:()=>y,DataStore:()=>N,DataStoreEngine:()=>T,DataStoreSerializer:()=>_,DatedError:()=>h,Debouncer:()=>P,FileStorageEngine:()=>O,MigrationError:()=>D,NanoEmitter:()=>S,ValidationError:()=>A,abtoa:()=>B,atoab:()=>j,autoPlural:()=>ge,bitSetHas:()=>X,capitalize:()=>be,clamp:()=>m,compress:()=>x,computeHash:()=>E,consumeGen:()=>ue,consumeStringGen:()=>ce,createProgressBar:()=>ye,darkenColor:()=>R,debounce:()=>xe,decompress:()=>oe,defaultPbChars:()=>U,digitCount:()=>Y,fetchAdvanced:()=>de,formatNumber:()=>ee,getListLength:()=>le,hexToRgb:()=>k,insertValues:()=>De,joinArrayReadable:()=>Te,lightenColor:()=>ae,mapRange:()=>v,pauseFor:()=>me,pureObj:()=>pe,randRange:()=>b,randomId:()=>se,randomItem:()=>re,randomItemIndex:()=>F,randomizeArray:()=>ie,rgbToHex:()=>C,roundFixed:()=>V,secsToTimeStr:()=>Se,setImmediateInterval:()=>fe,setImmediateTimeoutLoop:()=>he,takeRandomItem:()=>ne,takeRandomItemIndex:()=>M,truncStr:()=>we,valsWithin:()=>te});module.exports=Q(Pe);function X(r,e){return(r&e)===e}function m(r,e,t){return typeof t!="number"&&(t=e,e=0),Math.max(Math.min(r,t),e)}function Y(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),a=e&&i?i.length:0;return n+a}function ee(r,e,t){return r.toLocaleString(e,t==="short"?{notation:"compact",compactDisplay:"short",maximumFractionDigits:1}:{style:"decimal",maximumFractionDigits:0})}function v(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 b(...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,a=>Math.round(v(a,0,255,e,t)).toString(10)).join(""))}else return Math.floor(Math.random()*(t-e+1))+e}function V(r,e){let t=10**e;return Math.round(r*t)/t}function te(r,e,t=10,i=.5){return Math.abs(V(r,t)-V(e,t))<=i}function re(r){return F(r)[0]}function F(r){if(r.length===0)return[void 0,void 0];let e=b(r.length-1);return[r[e],e]}function ie(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 ne(r){var e;return(e=M(r))==null?void 0:e[0]}function M(r){let[e,t]=F(r);return t===void 0?[void 0,void 0]:(r.splice(t,1),[e,t])}function R(r,e,t=!1){var d;r=r.trim();let i=(c,l,f,g)=>(c=Math.max(0,Math.min(255,c-c*g/100)),l=Math.max(0,Math.min(255,l-l*g/100)),f=Math.max(0,Math.min(255,f-f*g/100)),[c,l,f]),n,a,o,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,a,o,s]=k(r);else if(r.startsWith("rgb")){let c=(d=r.match(/\d+(\.\d+)?/g))==null?void 0:d.map(Number);if(!c)throw new TypeError("Invalid RGB/RGBA color format");[n,a,o,s]=c}else throw new TypeError("Unsupported color format");if([n,a,o]=i(n,a,o,e),u)return C(n,a,o,s,r.startsWith("#"),t);if(r.startsWith("rgba"))return`rgba(${n}, ${a}, ${o}, ${s??NaN})`;if(r.startsWith("rgb"))return`rgb(${n}, ${a}, ${o})`;throw new TypeError("Unsupported color format")}function k(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(o=>o+o).join(""));let t=parseInt(r,16),i=t>>16&255,n=t>>8&255,a=t&255;return[m(i,0,255),m(n,0,255),m(a,0,255),typeof e=="number"?m(e,0,1):void 0]}function ae(r,e,t=!1){return R(r,e*-1,t)}function C(r,e,t,i,n=!0,a=!1){let o=s=>m(Math.round(s),0,255).toString(16).padStart(2,"0")[a?"toUpperCase":"toLowerCase"]();return`${n?"#":""}${o(r)}${o(e)}${o(t)}${i?o(i*255):""}`}function B(r){return btoa(new Uint8Array(r).reduce((e,t)=>e+String.fromCharCode(t),""))}function j(r){return Uint8Array.from(atob(r),e=>e.charCodeAt(0))}async function x(r,e,t="string"){let i=r instanceof ArrayBuffer?r:new TextEncoder().encode((r==null?void 0:r.toString())??String(r)),n=new CompressionStream(e),a=n.writable.getWriter();a.write(i),a.close();let o=await new Response(n.readable).arrayBuffer();return t==="arrayBuffer"?o:B(o)}async function oe(r,e,t="string"){let i=r instanceof ArrayBuffer?r:j((r==null?void 0:r.toString())??String(r)),n=new DecompressionStream(e),a=n.writable.getWriter();a.write(i),a.close();let o=await new Response(n.readable).arrayBuffer();return t==="arrayBuffer"?o:new TextDecoder().decode(o)}async function E(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(o=>o.toString(16).padStart(2,"0")).join("")}function se(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=[],a=i?[0,1]:[0];if(t){let o=new Uint8Array(r);crypto.getRandomValues(o),n=Array.from(o,s=>v(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(o=>/[a-zA-Z]/.test(o))?n.map(o=>a[b(0,a.length-1,t)]===1?o.toUpperCase():o).join(""):n.join("")}async function ue(r){return await(typeof r=="function"?r():r)}async function ce(r){return typeof r=="string"?r:String(typeof r=="function"?await r():r)}async function de(r,e={}){let{timeout:t=1e4}=e,i=new AbortController,{signal:n,...a}=e;n==null||n.addEventListener("abort",()=>i.abort());let o={},s;t>=0&&(s=setTimeout(()=>i.abort(),t),o={signal:i.signal});try{let u=await fetch(r,{...a,...o});return typeof s<"u"&&clearTimeout(s),u}catch(u){throw typeof s<"u"&&clearTimeout(s),new Error("Error while calling fetch",{cause:u})}}function le(r,e=!0){return"length"in r?r.length:"size"in r?r.size:"count"in r?r.count:e?0:NaN}function me(r,e,t=!1){return new Promise((i,n)=>{let a=setTimeout(()=>i(),r);e==null||e.addEventListener("abort",()=>{clearTimeout(a),t?n(new Error("The pause was aborted")):i()})})}function pe(r){return Object.assign(Object.create(null),r??{})}function fe(r,e,t){let i,n=()=>clearInterval(i),a=()=>{if(t!=null&&t.aborted)return n();r()};t==null||t.addEventListener("abort",n),a(),i=setInterval(a,e)}function he(r,e,t){let i,n=()=>clearTimeout(i),a=async()=>{if(t!=null&&t.aborted)return n();await r(),i=setTimeout(a,e)};t==null||t.addEventListener("abort",n),a()}function ge(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 be(r){return r.charAt(0).toUpperCase()+r.slice(1)}var U={100:"\u2588",75:"\u2593",50:"\u2592",25:"\u2591",0:"\u2500"};function ye(r,e,t=U){if(r===100)return t[100].repeat(e);let i=Math.floor(r/100*e),n=r/10*e-i,a="";n>=.75?a=t[75]:n>=.5?a=t[50]:n>=.25&&(a=t[25]);let o=t[100].repeat(i),s=t[0].repeat(e-i-(a?1:0));return`${o}${a}${s}`}function De(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 Te(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 Se(r){if(r<0)throw new TypeError("Seconds must be a positive number");let e=Math.floor(r/3600),t=Math.floor(r%3600/60),i=Math.floor(r%60);return[e?e+":":"",String(t).padStart(t>0||e>0?2:1,"0"),":",String(i).padStart(i>0||t>0||e>0?2:1,"0")].join("")}function we(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 h=class extends Error{date;constructor(e,t){super(e,t),this.name=this.constructor.name,this.date=new Date}},y=class extends h{constructor(e,t){super(e,t),this.name="ChecksumMismatchError"}},D=class extends h{constructor(e,t){super(e,t),this.name="MigrationError"}},A=class extends h{constructor(e,t){super(e,t),this.name="ValidationError"}};var ve=1,N=class{id;formatVersion;defaultData;encodeData;decodeData;compressionFormat="deflate-raw";engine;firstInit=!0;cachedData;migrations;migrateIds=[];constructor(e){if(this.id=e.id,this.formatVersion=e.formatVersion,this.defaultData=e.defaultData,this.cachedData=e.defaultData,this.migrations=e.migrations,e.migrateIds&&(this.migrateIds=Array.isArray(e.migrateIds)?e.migrateIds:[e.migrateIds]),this.encodeData=e.encodeData,this.decodeData=e.decodeData,this.engine=typeof e.engine=="function"?e.engine():e.engine,typeof e.compressionFormat>"u"&&(e.compressionFormat="deflate-raw"),typeof e.compressionFormat=="string")this.encodeData=[e.compressionFormat,async t=>await x(t,e.compressionFormat,"string")],this.decodeData=[e.compressionFormat,async t=>await x(t,e.compressionFormat,"string")];else if("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]];else if(e.compressionFormat===null)this.encodeData=void 0,this.decodeData=void 0;else throw new TypeError("Either `compressionFormat` or `encodeData` and `decodeData` have to be set and valid, but not all three at a time. Please refer to the documentation for more info.");this.engine.setDataStoreOptions(e)}async loadData(){try{if(this.firstInit){this.firstInit=!1;let o=Number(await this.engine.getValue("__ds_fmt_ver",0));if(isNaN(o)||o<1){let s=await this.engine.getValue(`_uucfg-${this.id}`,null);if(s){let u=Number(await this.engine.getValue(`_uucfgver-${this.id}`,NaN)),d=await this.engine.getValue(`_uucfgenc-${this.id}`,null),c=[],l=(f,g,J)=>{c.push(this.engine.setValue(g,J)),c.push(this.engine.deleteValue(f))};s&&l(`_uucfg-${this.id}`,`__ds-${this.id}-dat`,s),!isNaN(u)&&l(`_uucfgver-${this.id}`,`__ds-${this.id}-ver`,u),typeof d=="boolean"&&l(`_uucfgenc-${this.id}`,`__ds-${this.id}-enc`,d===!0?this.compressionFormat:null),await Promise.allSettled(c)}await this.engine.setValue("__ds_fmt_ver",ve)}}this.migrateIds.length>0&&(await this.migrateId(this.migrateIds),this.migrateIds=[]);let e=await this.engine.getValue(`__ds-${this.id}-dat`,JSON.stringify(this.defaultData)),t=Number(await this.engine.getValue(`__ds-${this.id}-ver`,NaN));if(typeof e!="string")return await this.saveDefaultData(),{...this.defaultData};let i=!!await this.engine.getValue(`__ds-${this.id}-enc`,!1),n=!1;isNaN(t)&&(await this.engine.setValue(`__ds-${this.id}-ver`,t=this.formatVersion),n=!0);let a=await this.engine.deserializeData(e,i);return t<this.formatVersion&&this.migrations&&(a=await this.runMigrations(a,t)),n&&await this.setData(a),this.cachedData=this.engine.deepCopy(a)}catch(e){return console.warn("Error while parsing JSON data, resetting it to the default value.",e),await this.saveDefaultData(),this.defaultData}}getData(){return this.engine.deepCopy(this.cachedData)}setData(e){this.cachedData=e;let t=this.encodingEnabled();return new Promise(async i=>{await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(e,t)),this.engine.setValue(`__ds-${this.id}-ver`,this.formatVersion),this.engine.setValue(`__ds-${this.id}-enc`,t)]),i()})}async saveDefaultData(){this.cachedData=this.defaultData;let e=this.encodingEnabled();await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(this.defaultData,e)),this.engine.setValue(`__ds-${this.id}-ver`,this.formatVersion),this.engine.setValue(`__ds-${this.id}-enc`,e)])}async deleteData(){await Promise.allSettled([this.engine.deleteValue(`__ds-${this.id}-dat`),this.engine.deleteValue(`__ds-${this.id}-ver`),this.engine.deleteValue(`__ds-${this.id}-enc`)])}encodingEnabled(){return!!(this.encodeData&&this.decodeData)}async runMigrations(e,t,i=!0){if(!this.migrations)return e;let n=e,a=Object.entries(this.migrations).sort(([s],[u])=>Number(s)-Number(u)),o=t;for(let[s,u]of a){let d=Number(s);if(t<this.formatVersion&&t<d)try{let c=u(n);n=c instanceof Promise?await c:c,o=t=d}catch(c){if(!i)throw new D(`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.engine.setValue(`__ds-${this.id}-ver`,o),this.engine.setValue(`__ds-${this.id}-enc`,this.encodingEnabled())]),this.cachedData={...n}}async migrateId(e){let t=Array.isArray(e)?e:[e];await Promise.all(t.map(async i=>{let n=await this.engine.getValue(`__ds-${i}-dat`,JSON.stringify(this.defaultData)),a=Number(await this.engine.getValue(`__ds-${i}-ver`,NaN)),o=!!await this.engine.getValue(`__ds-${i}-enc`,!1);if(n===void 0||isNaN(a))return;let s=await this.engine.deserializeData(n,o);await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(s)),this.engine.setValue(`__ds-${this.id}-ver`,a),this.engine.setValue(`__ds-${this.id}-enc`,o),this.engine.deleteValue(`__ds-${i}-dat`),this.engine.deleteValue(`__ds-${i}-ver`),this.engine.deleteValue(`__ds-${i}-enc`)])}))}};var T=class{dataStoreOptions;setDataStoreOptions(e){this.dataStoreOptions=e}async serializeData(e,t){var a,o,s,u,d;let i=JSON.stringify(e);if(!t||!((a=this.dataStoreOptions)!=null&&a.encodeData)||!((o=this.dataStoreOptions)!=null&&o.decodeData))return i;let n=(d=(u=(s=this.dataStoreOptions)==null?void 0:s.encodeData)==null?void 0:u[1])==null?void 0:d.call(u,i);return n instanceof Promise?await n:n}async deserializeData(e,t){var n,a,o;let i=(n=this.dataStoreOptions)!=null&&n.decodeData&&t?(o=(a=this.dataStoreOptions.decodeData)==null?void 0:a[1])==null?void 0:o.call(a,e):void 0;return i instanceof Promise&&(i=await i),JSON.parse(i??e)}deepCopy(e){try{if("structuredClone"in globalThis)return structuredClone(e)}catch{}return JSON.parse(JSON.stringify(e))}},I=class extends T{options;constructor(e){super(),this.options={type:"localStorage",...e}}async getValue(e,t){return(this.options.type==="localStorage"?globalThis.localStorage.getItem(e):globalThis.sessionStorage.getItem(e))??t}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)}},p,O=class extends T{options;constructor(e){super(),this.options={filePath:t=>`.ds-${t}`,...e}}async readFile(){var e,t,i;try{p||(p=(await import("node:fs/promises")).default);let n=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id),a=await p.readFile(n,"utf-8");return a?JSON.parse(await((i=(t=(e=this.dataStoreOptions)==null?void 0:e.decodeData)==null?void 0:t[1])==null?void 0:i.call(t,a))??a):void 0}catch{return}}async writeFile(e){var t,i,n;try{p||(p=(await import("node:fs/promises")).default);let a=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id);await p.mkdir(a.slice(0,a.lastIndexOf("/")),{recursive:!0}),await p.writeFile(a,await((n=(i=(t=this.dataStoreOptions)==null?void 0:t.encodeData)==null?void 0:i[1])==null?void 0:n.call(i,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 n===void 0?t:typeof n=="string"?n:String(n??t)}async setValue(e,t){let i=await this.readFile();i||(i={}),i[e]=t,await this.writeFile(i)}async deleteValue(e){let t=await this.readFile();t&&(delete t[e],await this.writeFile(t))}};var _=class r{stores;options;constructor(e,t={}){if(!crypto||!crypto.subtle)throw new Error("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,...t}}async calcChecksum(e){return E(e,"SHA-256")}async serializePartial(e,t=!0,i=!0){let n=[];for(let a of this.stores.filter(o=>typeof e=="function"?e(o.id):e.includes(o.id))){let o=t&&a.encodingEnabled()?await a.encodeData[1](JSON.stringify(a.getData())):JSON.stringify(a.getData());n.push({id:a.id,data:o,formatVersion:a.formatVersion,encoded:t&&a.encodingEnabled(),checksum:this.options.addChecksum?await this.calcChecksum(o):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.");for(let n of i.filter(a=>typeof e=="function"?e(a.id):e.includes(a.id))){let a=this.stores.find(s=>s.id===n.id);if(!a)throw new Error(`DataStore instance with ID "${n.id}" not found! Make sure to provide it in the DataStoreSerializer constructor.`);if(this.options.ensureIntegrity&&typeof n.checksum=="string"){let s=await this.calcChecksum(n.data);if(s!==n.checksum)throw new y(`Checksum mismatch for DataStore with ID "${n.id}"!
19
+ "use strict";var q=Object.create;var w=Object.defineProperty;var H=Object.getOwnPropertyDescriptor;var K=Object.getOwnPropertyNames;var W=Object.getPrototypeOf,G=Object.prototype.hasOwnProperty;var Z=(r,e)=>{for(var t in e)w(r,t,{get:e[t],enumerable:!0})},$=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of K(e))!G.call(r,n)&&n!==t&&w(r,n,{get:()=>e[n],enumerable:!(i=H(e,n))||i.enumerable});return r};var z=(r,e,t)=>(t=r!=null?q(W(r)):{},$(e||!r||!r.__esModule?w(t,"default",{value:r,enumerable:!0}):t,r)),Q=r=>$(w({},"__esModule",{value:!0}),r);var Ve={};Z(Ve,{BrowserStorageEngine:()=>I,ChecksumMismatchError:()=>y,DataStore:()=>A,DataStoreEngine:()=>T,DataStoreSerializer:()=>_,DatedError:()=>l,Debouncer:()=>P,FileStorageEngine:()=>O,MigrationError:()=>D,NanoEmitter:()=>S,ValidationError:()=>N,abtoa:()=>B,atoab:()=>j,autoPlural:()=>be,bitSetHas:()=>X,capitalize:()=>ye,clamp:()=>f,compress:()=>x,computeHash:()=>F,consumeGen:()=>ue,consumeStringGen:()=>de,createProgressBar:()=>De,darkenColor:()=>R,debounce:()=>Pe,decompress:()=>oe,defaultPbChars:()=>U,digitCount:()=>Y,fetchAdvanced:()=>ce,formatNumber:()=>ee,getListLength:()=>le,hexToRgb:()=>C,insertValues:()=>Te,joinArrayReadable:()=>Se,lightenColor:()=>ae,mapRange:()=>v,pauseFor:()=>me,pureObj:()=>pe,randRange:()=>b,randomId:()=>se,randomItem:()=>re,randomItemIndex:()=>E,randomizeArray:()=>ie,rgbToHex:()=>k,roundFixed:()=>V,scheduleExit:()=>ge,secsToTimeStr:()=>we,setImmediateInterval:()=>fe,setImmediateTimeoutLoop:()=>he,takeRandomItem:()=>ne,takeRandomItemIndex:()=>M,truncStr:()=>ve,valsWithin:()=>te});module.exports=Q(Ve);function X(r,e){return(r&e)===e}function f(r,e,t){return typeof t!="number"&&(t=e,e=0),Math.max(Math.min(r,t),e)}function Y(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),a=e&&i?i.length:0;return n+a}function ee(r,e,t){return r.toLocaleString(e,t==="short"?{notation:"compact",compactDisplay:"short",maximumFractionDigits:1}:{style:"decimal",maximumFractionDigits:0})}function v(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 b(...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,a=>Math.round(v(a,0,255,e,t)).toString(10)).join(""))}else return Math.floor(Math.random()*(t-e+1))+e}function V(r,e){let t=10**e;return Math.round(r*t)/t}function te(r,e,t=10,i=.5){return Math.abs(V(r,t)-V(e,t))<=i}function re(r){return E(r)[0]}function E(r){if(r.length===0)return[void 0,void 0];let e=b(r.length-1);return[r[e],e]}function ie(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 ne(r){var e;return(e=M(r))==null?void 0:e[0]}function M(r){let[e,t]=E(r);return t===void 0?[void 0,void 0]:(r.splice(t,1),[e,t])}function R(r,e,t=!1){var c;r=r.trim();let i=(d,p,h,g)=>(d=Math.max(0,Math.min(255,d-d*g/100)),p=Math.max(0,Math.min(255,p-p*g/100)),h=Math.max(0,Math.min(255,h-h*g/100)),[d,p,h]),n,a,o,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,a,o,s]=C(r);else if(r.startsWith("rgb")){let d=(c=r.match(/\d+(\.\d+)?/g))==null?void 0:c.map(Number);if(!d)throw new TypeError("Invalid RGB/RGBA color format");[n,a,o,s]=d}else throw new TypeError("Unsupported color format");if([n,a,o]=i(n,a,o,e),u)return k(n,a,o,s,r.startsWith("#"),t);if(r.startsWith("rgba"))return`rgba(${n}, ${a}, ${o}, ${s??NaN})`;if(r.startsWith("rgb"))return`rgb(${n}, ${a}, ${o})`;throw new TypeError("Unsupported color format")}function C(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(o=>o+o).join(""));let t=parseInt(r,16),i=t>>16&255,n=t>>8&255,a=t&255;return[f(i,0,255),f(n,0,255),f(a,0,255),typeof e=="number"?f(e,0,1):void 0]}function ae(r,e,t=!1){return R(r,e*-1,t)}function k(r,e,t,i,n=!0,a=!1){let o=s=>f(Math.round(s),0,255).toString(16).padStart(2,"0")[a?"toUpperCase":"toLowerCase"]();return`${n?"#":""}${o(r)}${o(e)}${o(t)}${i?o(i*255):""}`}function B(r){return btoa(new Uint8Array(r).reduce((e,t)=>e+String.fromCharCode(t),""))}function j(r){return Uint8Array.from(atob(r),e=>e.charCodeAt(0))}async function x(r,e,t="string"){let i=r instanceof ArrayBuffer?r:new TextEncoder().encode((r==null?void 0:r.toString())??String(r)),n=new CompressionStream(e),a=n.writable.getWriter();a.write(i),a.close();let o=await new Response(n.readable).arrayBuffer();return t==="arrayBuffer"?o:B(o)}async function oe(r,e,t="string"){let i=r instanceof ArrayBuffer?r:j((r==null?void 0:r.toString())??String(r)),n=new DecompressionStream(e),a=n.writable.getWriter();a.write(i),a.close();let o=await new Response(n.readable).arrayBuffer();return t==="arrayBuffer"?o:new TextDecoder().decode(o)}async function F(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(o=>o.toString(16).padStart(2,"0")).join("")}function se(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=[],a=i?[0,1]:[0];if(t){let o=new Uint8Array(r);crypto.getRandomValues(o),n=Array.from(o,s=>v(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(o=>/[a-zA-Z]/.test(o))?n.map(o=>a[b(0,a.length-1,t)]===1?o.toUpperCase():o).join(""):n.join("")}async function ue(r){return await(typeof r=="function"?r():r)}async function de(r){return typeof r=="string"?r:String(typeof r=="function"?await r():r)}async function ce(r,e={}){let{timeout:t=1e4}=e,i=new AbortController,{signal:n,...a}=e;n==null||n.addEventListener("abort",()=>i.abort());let o={},s;t>=0&&(s=setTimeout(()=>i.abort(),t),o={signal:i.signal});try{let u=await fetch(r,{...a,...o});return typeof s<"u"&&clearTimeout(s),u}catch(u){throw typeof s<"u"&&clearTimeout(s),new Error("Error while calling fetch",{cause:u})}}function le(r,e=!0){return"length"in r?r.length:"size"in r?r.size:"count"in r?r.count:e?0:NaN}function me(r,e,t=!1){return new Promise((i,n)=>{let a=setTimeout(()=>i(),r);e==null||e.addEventListener("abort",()=>{clearTimeout(a),t?n(new Error("The pause was aborted")):i()})})}function pe(r){return Object.assign(Object.create(null),r??{})}function fe(r,e,t){let i,n=()=>clearInterval(i),a=()=>{if(t!=null&&t.aborted)return n();r()};t==null||t.addEventListener("abort",n),a(),i=setInterval(a,e)}function he(r,e,t){let i,n=()=>clearTimeout(i),a=async()=>{if(t!=null&&t.aborted)return n();await r(),i=setTimeout(a,e)};t==null||t.addEventListener("abort",n),a()}function ge(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)t=()=>process.exit(r);else if(typeof Deno<"u"&&"exit"in Deno)t=()=>Deno.exit(r);else throw new Error("Cannot exit the process, no exit method available");setTimeout(t,e)}function be(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 ye(r){return r.charAt(0).toUpperCase()+r.slice(1)}var U={100:"\u2588",75:"\u2593",50:"\u2592",25:"\u2591",0:"\u2500"};function De(r,e,t=U){if(r===100)return t[100].repeat(e);let i=Math.floor(r/100*e),n=r/10*e-i,a="";n>=.75?a=t[75]:n>=.5?a=t[50]:n>=.25&&(a=t[25]);let o=t[100].repeat(i),s=t[0].repeat(e-i-(a?1:0));return`${o}${a}${s}`}function Te(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 Se(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 we(r){if(r<0)throw new TypeError("Seconds must be a positive number");let e=Math.floor(r/3600),t=Math.floor(r%3600/60),i=Math.floor(r%60);return[e?e+":":"",String(t).padStart(t>0||e>0?2:1,"0"),":",String(i).padStart(i>0||t>0||e>0?2:1,"0")].join("")}function ve(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 l=class extends Error{date;constructor(e,t){super(e,t),this.name=this.constructor.name,this.date=new Date}},y=class extends l{constructor(e,t){super(e,t),this.name="ChecksumMismatchError"}},D=class extends l{constructor(e,t){super(e,t),this.name="MigrationError"}},N=class extends l{constructor(e,t){super(e,t),this.name="ValidationError"}};var xe=1,A=class{id;formatVersion;defaultData;encodeData;decodeData;compressionFormat="deflate-raw";engine;firstInit=!0;cachedData;migrations;migrateIds=[];constructor(e){if(this.id=e.id,this.formatVersion=e.formatVersion,this.defaultData=e.defaultData,this.cachedData=e.defaultData,this.migrations=e.migrations,e.migrateIds&&(this.migrateIds=Array.isArray(e.migrateIds)?e.migrateIds:[e.migrateIds]),this.encodeData=e.encodeData,this.decodeData=e.decodeData,this.engine=typeof e.engine=="function"?e.engine():e.engine,typeof e.compressionFormat>"u"&&(e.compressionFormat="deflate-raw"),typeof e.compressionFormat=="string")this.encodeData=[e.compressionFormat,async t=>await x(t,e.compressionFormat,"string")],this.decodeData=[e.compressionFormat,async t=>await x(t,e.compressionFormat,"string")];else if("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]];else if(e.compressionFormat===null)this.encodeData=void 0,this.decodeData=void 0;else throw new TypeError("Either `compressionFormat` or `encodeData` and `decodeData` have to be set and valid, but not all three at a time. Please refer to the documentation for more info.");this.engine.setDataStoreOptions(e)}async loadData(){try{if(this.firstInit){this.firstInit=!1;let o=Number(await this.engine.getValue("__ds_fmt_ver",0));if(isNaN(o)||o<1){let s=await this.engine.getValue(`_uucfg-${this.id}`,null);if(s){let u=Number(await this.engine.getValue(`_uucfgver-${this.id}`,NaN)),c=await this.engine.getValue(`_uucfgenc-${this.id}`,null),d=[],p=(h,g,J)=>{d.push(this.engine.setValue(g,J)),d.push(this.engine.deleteValue(h))};s&&p(`_uucfg-${this.id}`,`__ds-${this.id}-dat`,s),!isNaN(u)&&p(`_uucfgver-${this.id}`,`__ds-${this.id}-ver`,u),typeof c=="boolean"&&p(`_uucfgenc-${this.id}`,`__ds-${this.id}-enc`,c===!0?this.compressionFormat:null),await Promise.allSettled(d)}await this.engine.setValue("__ds_fmt_ver",xe)}}this.migrateIds.length>0&&(await this.migrateId(this.migrateIds),this.migrateIds=[]);let e=await this.engine.getValue(`__ds-${this.id}-dat`,JSON.stringify(this.defaultData)),t=Number(await this.engine.getValue(`__ds-${this.id}-ver`,NaN));if(typeof e!="string")return await this.saveDefaultData(),{...this.defaultData};let i=!!await this.engine.getValue(`__ds-${this.id}-enc`,!1),n=!1;isNaN(t)&&(await this.engine.setValue(`__ds-${this.id}-ver`,t=this.formatVersion),n=!0);let a=await this.engine.deserializeData(e,i);return t<this.formatVersion&&this.migrations&&(a=await this.runMigrations(a,t)),n&&await this.setData(a),this.cachedData=this.engine.deepCopy(a)}catch(e){return console.warn("Error while parsing JSON data, resetting it to the default value.",e),await this.saveDefaultData(),this.defaultData}}getData(){return this.engine.deepCopy(this.cachedData)}setData(e){this.cachedData=e;let t=this.encodingEnabled();return new Promise(async i=>{await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(e,t)),this.engine.setValue(`__ds-${this.id}-ver`,this.formatVersion),this.engine.setValue(`__ds-${this.id}-enc`,t)]),i()})}async saveDefaultData(){this.cachedData=this.defaultData;let e=this.encodingEnabled();await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(this.defaultData,e)),this.engine.setValue(`__ds-${this.id}-ver`,this.formatVersion),this.engine.setValue(`__ds-${this.id}-enc`,e)])}async deleteData(){await Promise.allSettled([this.engine.deleteValue(`__ds-${this.id}-dat`),this.engine.deleteValue(`__ds-${this.id}-ver`),this.engine.deleteValue(`__ds-${this.id}-enc`)])}encodingEnabled(){return!!(this.encodeData&&this.decodeData)}async runMigrations(e,t,i=!0){if(!this.migrations)return e;let n=e,a=Object.entries(this.migrations).sort(([s],[u])=>Number(s)-Number(u)),o=t;for(let[s,u]of a){let c=Number(s);if(t<this.formatVersion&&t<c)try{let d=u(n);n=d instanceof Promise?await d:d,o=t=c}catch(d){if(!i)throw new D(`Error while running migration function for format version '${s}'`,{cause:d});return await this.saveDefaultData(),this.getData()}}return await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(n)),this.engine.setValue(`__ds-${this.id}-ver`,o),this.engine.setValue(`__ds-${this.id}-enc`,this.encodingEnabled())]),this.cachedData={...n}}async migrateId(e){let t=Array.isArray(e)?e:[e];await Promise.all(t.map(async i=>{let n=await this.engine.getValue(`__ds-${i}-dat`,JSON.stringify(this.defaultData)),a=Number(await this.engine.getValue(`__ds-${i}-ver`,NaN)),o=!!await this.engine.getValue(`__ds-${i}-enc`,!1);if(n===void 0||isNaN(a))return;let s=await this.engine.deserializeData(n,o);await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(s)),this.engine.setValue(`__ds-${this.id}-ver`,a),this.engine.setValue(`__ds-${this.id}-enc`,o),this.engine.deleteValue(`__ds-${i}-dat`),this.engine.deleteValue(`__ds-${i}-ver`),this.engine.deleteValue(`__ds-${i}-enc`)])}))}};var T=class{dataStoreOptions;setDataStoreOptions(e){this.dataStoreOptions=e}async serializeData(e,t){var a,o,s,u,c;let i=JSON.stringify(e);if(!t||!((a=this.dataStoreOptions)!=null&&a.encodeData)||!((o=this.dataStoreOptions)!=null&&o.decodeData))return i;let n=(c=(u=(s=this.dataStoreOptions)==null?void 0:s.encodeData)==null?void 0:u[1])==null?void 0:c.call(u,i);return n instanceof Promise?await n:n}async deserializeData(e,t){var n,a,o;let i=(n=this.dataStoreOptions)!=null&&n.decodeData&&t?(o=(a=this.dataStoreOptions.decodeData)==null?void 0:a[1])==null?void 0:o.call(a,e):void 0;return i instanceof Promise&&(i=await i),JSON.parse(i??e)}deepCopy(e){try{if("structuredClone"in globalThis)return structuredClone(e)}catch{}return JSON.parse(JSON.stringify(e))}},I=class extends T{options;constructor(e){super(),this.options={type:"localStorage",...e}}async getValue(e,t){return(this.options.type==="localStorage"?globalThis.localStorage.getItem(e):globalThis.sessionStorage.getItem(e))??t}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)}},m,O=class extends T{options;constructor(e){super(),this.options={filePath:t=>`.ds-${t}`,...e}}async readFile(){var e,t,i;try{if(m||(m=(await import("fs/promises")).default),!m)throw new l("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new Error("'node:fs/promises' module not available")});let n=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id),a=await m.readFile(n,"utf-8");return a?JSON.parse(await((i=(t=(e=this.dataStoreOptions)==null?void 0:e.decodeData)==null?void 0:t[1])==null?void 0:i.call(t,a))??a):void 0}catch{return}}async writeFile(e){var t,i,n;try{if(m||(m=(await import("fs/promises")).default),!m)throw new l("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new Error("'node:fs/promises' module not available")});let a=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id);await m.mkdir(a.slice(0,a.lastIndexOf("/")),{recursive:!0}),await m.writeFile(a,await((n=(i=(t=this.dataStoreOptions)==null?void 0:t.encodeData)==null?void 0:i[1])==null?void 0:n.call(i,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 n===void 0?t:typeof n=="string"?n:String(n??t)}async setValue(e,t){let i=await this.readFile();i||(i={}),i[e]=t,await this.writeFile(i)}async deleteValue(e){let t=await this.readFile();t&&(delete t[e],await this.writeFile(t))}};var _=class r{stores;options;constructor(e,t={}){if(!crypto||!crypto.subtle)throw new Error("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,...t}}async calcChecksum(e){return F(e,"SHA-256")}async serializePartial(e,t=!0,i=!0){let n=[];for(let a of this.stores.filter(o=>typeof e=="function"?e(o.id):e.includes(o.id))){let o=t&&a.encodingEnabled()?await a.encodeData[1](JSON.stringify(a.getData())):JSON.stringify(a.getData());n.push({id:a.id,data:o,formatVersion:a.formatVersion,encoded:t&&a.encodingEnabled(),checksum:this.options.addChecksum?await this.calcChecksum(o):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.");for(let n of i.filter(a=>typeof e=="function"?e(a.id):e.includes(a.id))){let a=this.stores.find(s=>s.id===n.id);if(!a)throw new Error(`DataStore instance with ID "${n.id}" not found! Make sure to provide it in the DataStoreSerializer constructor.`);if(this.options.ensureIntegrity&&typeof n.checksum=="string"){let s=await this.calcChecksum(n.data);if(s!==n.checksum)throw new y(`Checksum mismatch for DataStore with ID "${n.id}"!
20
20
  Expected: ${n.checksum}
21
- Has: ${s}`)}let o=n.encoded&&a.encodingEnabled()?await a.decodeData[1](n.data):n.data;n.formatVersion&&!isNaN(Number(n.formatVersion))&&Number(n.formatVersion)<a.formatVersion?await a.runMigrations(JSON.parse(o),Number(n.formatVersion),!1):await a.setData(JSON.parse(o))}}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 L=()=>({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 S=class{events=L();eventUnsubscribes=[];emitterOptions;constructor(e={}){this.emitterOptions={publicEmit:!1,...e}}on(e,t){let i,n=()=>{i&&(i(),this.eventUnsubscribes=this.eventUnsubscribes.filter(a=>a!==i))};return i=this.events.on(e,t),this.eventUnsubscribes.push(i),n}once(e,t){return new Promise(i=>{let n,a=(...o)=>{t==null||t(...o),n==null||n(),i(o)};n=this.events.on(e,a),this.eventUnsubscribes.push(n)})}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 P=class extends S{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=(...a)=>{this.queuedCall=void 0,this.emit("call",...a),this.listeners.forEach(o=>o.call(this,...a))},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 xe(r,e=200,t="immediate"){let i=new P(e,t);i.addListener(r);let n=(...a)=>i.call(...a);return n.debouncer=i,n}
21
+ Has: ${s}`)}let o=n.encoded&&a.encodingEnabled()?await a.decodeData[1](n.data):n.data;n.formatVersion&&!isNaN(Number(n.formatVersion))&&Number(n.formatVersion)<a.formatVersion?await a.runMigrations(JSON.parse(o),Number(n.formatVersion),!1):await a.setData(JSON.parse(o))}}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 L=()=>({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 S=class{events=L();eventUnsubscribes=[];emitterOptions;constructor(e={}){this.emitterOptions={publicEmit:!1,...e}}on(e,t){let i,n=()=>{i&&(i(),this.eventUnsubscribes=this.eventUnsubscribes.filter(a=>a!==i))};return i=this.events.on(e,t),this.eventUnsubscribes.push(i),n}once(e,t){return new Promise(i=>{let n,a=(...o)=>{t==null||t(...o),n==null||n(),i(o)};n=this.events.on(e,a),this.eventUnsubscribes.push(n)})}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 P=class extends S{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=(...a)=>{this.queuedCall=void 0,this.emit("call",...a),this.listeners.forEach(o=>o.call(this,...a))},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 Pe(r,e=200,t="immediate"){let i=new P(e,t);i.addListener(r);let n=(...a)=>i.call(...a);return n.debouncer=i,n}
22
22
 
23
23
 
24
24
 
@@ -296,6 +296,18 @@ function setImmediateTimeoutLoop(callback, interval, signal) {
296
296
  signal == null ? void 0 : signal.addEventListener("abort", cleanup);
297
297
  loop();
298
298
  }
299
+ function scheduleExit(code = 0, timeout = 0) {
300
+ if (timeout < 0)
301
+ throw new TypeError("Timeout must be a non-negative number");
302
+ let exit;
303
+ if (typeof process !== "undefined" && "exit" in process)
304
+ exit = () => process.exit(code);
305
+ else if (typeof Deno !== "undefined" && "exit" in Deno)
306
+ exit = () => Deno.exit(code);
307
+ else
308
+ throw new Error("Cannot exit the process, no exit method available");
309
+ setTimeout(exit, timeout);
310
+ }
299
311
 
300
312
  // lib/text.ts
301
313
  function autoPlural(term, num, pluralType = "auto") {
@@ -710,7 +722,7 @@ var FileStorageEngine = class extends DataStoreEngine {
710
722
  /**
711
723
  * Creates an instance of `FileStorageEngine`.
712
724
  *
713
- * ⚠️ Requires Node.js or Deno with Node compatibility
725
+ * ⚠️ Requires Node.js or Deno with Node compatibility (v1.31+)
714
726
  * ⚠️ Don't reuse this engine across multiple {@linkcode DataStore} instances
715
727
  */
716
728
  constructor(options) {
@@ -726,12 +738,12 @@ var FileStorageEngine = class extends DataStoreEngine {
726
738
  var _a, _b, _c;
727
739
  try {
728
740
  if (!fs)
729
- fs = (await import("node:fs/promises")).default;
741
+ fs = (await import("fs/promises")).default;
742
+ if (!fs)
743
+ throw new DatedError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new Error("'node:fs/promises' module not available") });
730
744
  const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
731
745
  const data = await fs.readFile(path, "utf-8");
732
- if (!data)
733
- return void 0;
734
- return JSON.parse(await ((_c = (_b = (_a = this.dataStoreOptions) == null ? void 0 : _a.decodeData) == null ? void 0 : _b[1]) == null ? void 0 : _c.call(_b, data)) ?? data);
746
+ return data ? JSON.parse(await ((_c = (_b = (_a = this.dataStoreOptions) == null ? void 0 : _a.decodeData) == null ? void 0 : _b[1]) == null ? void 0 : _c.call(_b, data)) ?? data) : void 0;
735
747
  } catch {
736
748
  return void 0;
737
749
  }
@@ -741,7 +753,9 @@ var FileStorageEngine = class extends DataStoreEngine {
741
753
  var _a, _b, _c;
742
754
  try {
743
755
  if (!fs)
744
- fs = (await import("node:fs/promises")).default;
756
+ fs = (await import("fs/promises")).default;
757
+ if (!fs)
758
+ throw new DatedError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new Error("'node:fs/promises' module not available") });
745
759
  const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
746
760
  await fs.mkdir(path.slice(0, path.lastIndexOf("/")), { recursive: true });
747
761
  await fs.writeFile(path, await ((_c = (_b = (_a = this.dataStoreOptions) == null ? void 0 : _a.encodeData) == null ? void 0 : _b[1]) == null ? void 0 : _c.call(_b, JSON.stringify(data))) ?? JSON.stringify(data, void 0, 2), "utf-8");
@@ -1169,6 +1183,7 @@ export {
1169
1183
  randomizeArray,
1170
1184
  rgbToHex,
1171
1185
  roundFixed,
1186
+ scheduleExit,
1172
1187
  secsToTimeStr,
1173
1188
  setImmediateInterval,
1174
1189
  setImmediateTimeoutLoop,