@sv443-network/coreutils
Version:
Cross-platform, general-purpose, JavaScript core library for Node, Deno and the browser. Intended to be used in conjunction with `@sv443-network/userutils` and `@sv443-network/djsutils`, but can be used independently as well.
4 lines • 24.3 kB
JavaScript
function J(r,e){return(r&e)===e}function y(r,e,t){return typeof t!="number"&&(t=e,e=0),Math.max(Math.min(r,t),e)}function H(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 W(r,e,t){return r.toLocaleString(e,t==="short"?{notation:"compact",compactDisplay:"short",maximumFractionDigits:1}:{style:"decimal",maximumFractionDigits:0})}function P(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 G(r,e,t){let i=typeof t=="number"?e:0;if(t=typeof t=="number"?t:e,i>t)throw new RangeError(`Parameter "min" can't be bigger than "max"`);if(isNaN(r)||isNaN(i)||isNaN(t)||!isFinite(r)||!isFinite(i)||!isFinite(t))return NaN;if(r>=i&&r<=t)return r;let n=t-i+1;return((r-i)%n+n)%n+i}function D(...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(P(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 Z(r,e,t=10,i=.5){return Math.abs(V(r,t)-V(e,t))<=i}function Y(r){return N(r)[0]}function N(r){if(r.length===0)return[void 0,void 0];let e=D(r.length-1);return[r[e],e]}function ee(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 te(r){var e;return(e=U(r))==null?void 0:e[0]}function U(r){let[e,t]=N(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=(l,d,m,g)=>(l=Math.max(0,Math.min(255,l-l*g/100)),d=Math.max(0,Math.min(255,d-d*g/100)),m=Math.max(0,Math.min(255,m-m*g/100)),[l,d,m]),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 l=(c=r.match(/\d+(\.\d+)?/g))==null?void 0:c.map(Number);if(!l)throw new TypeError("Invalid RGB/RGBA color format");[n,a,o,s]=l}else throw new TypeError("Unsupported color format");return[n,a,o]=i(n,a,o,e),u?j(n,a,o,s,r.startsWith("#"),t):r.startsWith("rgba")?`rgba(${n}, ${a}, ${o}, ${s??NaN})`:`rgb(${n}, ${a}, ${o})`}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[y(i,0,255),y(n,0,255),y(a,0,255),typeof e=="number"?y(e,0,1):void 0]}function ne(r,e,t=!1){return R(r,e*-1,t)}function j(r,e,t,i,n=!0,a=!1){let o=s=>y(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 K(r){return Uint8Array.from(atob(r),e=>e.charCodeAt(0))}async function O(r,e,t="string"){let i=r instanceof Uint8Array?r:new TextEncoder().encode((r==null?void 0:r.toString())??String(r)),n=new CompressionStream(e),a=n.writable.getWriter();a.write(i),a.close();let o=new Uint8Array(await new Response(n.readable).arrayBuffer());return t==="arrayBuffer"?o:B(o)}async function se(r,e,t="string"){let i=r instanceof Uint8Array?r:K((r==null?void 0:r.toString())??String(r)),n=new DecompressionStream(e),a=n.writable.getWriter();a.write(i),a.close();let o=new Uint8Array(await new Response(n.readable).arrayBuffer());return t==="arrayBuffer"?o:new TextDecoder().decode(o)}async function A(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 ue(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=>P(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[D(0,a.length-1,t)]===1?o.toUpperCase():o).join(""):n.join("")}async function ce(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 me(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 pe(r,e=!0){return"length"in r?r.length:"size"in r?r.size:"count"in r?r.count:e?0:NaN}function fe(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 he(r){return Object.assign(Object.create(null),r??{})}function be(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 ge(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 ye(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 Te(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 Se(r){return r.charAt(0).toUpperCase()+r.slice(1)}var L={100:"\u2588",75:"\u2593",50:"\u2592",25:"\u2591",0:"\u2500"};function ve(r,e,t=L){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 we(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 xe(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 Ee(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 Pe(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}},T=class extends h{constructor(e,t){super(e,t),this.name="ChecksumMismatchError"}},S=class extends h{constructor(e,t){super(e,t),this.name="MigrationError"}},M=class extends h{constructor(e,t){super(e,t),this.name="ValidationError"}};var q=1,I=class{id;formatVersion;defaultData;encodeData;decodeData;compressionFormat="deflate-raw";engine;options;firstInit=!0;cachedData;migrations;migrateIds=[];constructor(e){var t;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,this.options=e,typeof e.compressionFormat>"u"&&(e.compressionFormat=((t=e.encodeData)==null?void 0:t[0])??"deflate-raw"),typeof e.compressionFormat=="string")this.encodeData=[e.compressionFormat,async i=>await O(i,e.compressionFormat,"string")],this.decodeData=[e.compressionFormat,async i=>await O(i,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 s=Number(await this.engine.getValue("__ds_fmt_ver",0));if(isNaN(s)||s<1){let u=await this.engine.getValue(`_uucfg-${this.id}`,null);if(u){let c=Number(await this.engine.getValue(`_uucfgver-${this.id}`,NaN)),l=await this.engine.getValue(`_uucfgenc-${this.id}`,null),d=[],m=(g,x,f)=>{d.push(this.engine.setValue(x,f)),d.push(this.engine.deleteValue(g))};u&&m(`_uucfg-${this.id}`,`__ds-${this.id}-dat`,u),isNaN(c)||m(`_uucfgver-${this.id}`,`__ds-${this.id}-ver`,c),typeof l=="boolean"?m(`_uucfgenc-${this.id}`,`__ds-${this.id}-enf`,l===!0&&!!this.compressionFormat||null):d.push(this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)),await Promise.allSettled(d)}await this.engine.setValue("__ds_fmt_ver",q)}}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=String(await this.engine.getValue(`__ds-${this.id}-enf`,null)),n=i!=="null"&&i!=="false",a=!1;isNaN(t)&&(await this.engine.setValue(`__ds-${this.id}-ver`,t=this.formatVersion),a=!0);let o=await this.engine.deserializeData(e,n);return t<this.formatVersion&&this.migrations&&(o=await this.runMigrations(o,t)),a&&await this.setData(o),this.cachedData=this.engine.deepCopy(o)}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){return this.cachedData=e,new Promise(async t=>{await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(e,this.encodingEnabled())),this.engine.setValue(`__ds-${this.id}-ver`,this.formatVersion),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)]),t()})}async saveDefaultData(){this.cachedData=this.defaultData,await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(this.defaultData,this.encodingEnabled())),this.engine.setValue(`__ds-${this.id}-ver`,this.formatVersion),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)])}async deleteData(){var e,t;await Promise.allSettled([this.engine.deleteValue(`__ds-${this.id}-dat`),this.engine.deleteValue(`__ds-${this.id}-ver`),this.engine.deleteValue(`__ds-${this.id}-enf`)]),await((t=(e=this.engine).deleteStorage)==null?void 0:t.call(e))}encodingEnabled(){return!!(this.encodeData&&this.decodeData)&&this.compressionFormat!==null||!!this.compressionFormat}async runMigrations(e,t,i=!0){if(!this.migrations)return e;let n=e,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 l=u(n);n=l instanceof Promise?await l:l,o=t=c}catch(l){if(!i)throw new S(`Error while running migration function for format version '${s}'`,{cause:l});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}-enf`,this.compressionFormat)]),this.cachedData={...n}}async migrateId(e){let t=Array.isArray(e)?e:[e];await Promise.all(t.map(async i=>{let[n,a,o]=await(async()=>{let[u,c,l]=await Promise.all([this.engine.getValue(`__ds-${i}-dat`,JSON.stringify(this.defaultData)),this.engine.getValue(`__ds-${i}-ver`,NaN),this.engine.getValue(`__ds-${i}-enf`,null)]);return[u,Number(c),!!l&&String(l)!=="null"]})();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}-enf`,this.compressionFormat),this.engine.deleteValue(`__ds-${i}-dat`),this.engine.deleteValue(`__ds-${i}-ver`),this.engine.deleteValue(`__ds-${i}-enf`)])}))}};var v=class{dataStoreOptions;constructor(e){e&&(this.dataStoreOptions=e)}setDataStoreOptions(e){this.dataStoreOptions=e}async serializeData(e,t){var a,o,s,u,c;this.ensureDataStoreOptions();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;this.ensureDataStoreOptions();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)}ensureDataStoreOptions(){if(!this.dataStoreOptions)throw new h("DataStoreEngine must be initialized with DataStore options before use. If you are using this instance standalone, set them in the constructor or call `setDataStoreOptions()` with the DataStore options.");if(!this.dataStoreOptions.id)throw new h("DataStoreEngine must be initialized with a valid DataStore ID")}deepCopy(e){try{if("structuredClone"in globalThis)return structuredClone(e)}catch{}return JSON.parse(JSON.stringify(e))}},_=class extends v{options;constructor(e){super(e==null?void 0:e.dataStoreOptions),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,$=class extends v{options;constructor(e){super(e==null?void 0:e.dataStoreOptions),this.options={filePath:t=>`.ds-${t}`,...e}}async readFile(){var e,t,i,n;this.ensureDataStoreOptions();try{if(p||(p=(e=await import("fs/promises"))==null?void 0:e.default),!p)throw new h("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),o=await p.readFile(a,"utf-8");return o?JSON.parse(await((n=(i=(t=this.dataStoreOptions)==null?void 0:t.decodeData)==null?void 0:i[1])==null?void 0:n.call(i,o))??o):void 0}catch{return}}async writeFile(e){var t,i,n,a;this.ensureDataStoreOptions();try{if(p||(p=(t=await import("fs/promises"))==null?void 0:t.default),!p)throw new h("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new Error("'node:fs/promises' module not available")});let o=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id);await p.mkdir(o.slice(0,o.lastIndexOf("/")),{recursive:!0}),await p.writeFile(o,await((a=(n=(i=this.dataStoreOptions)==null?void 0:i.encodeData)==null?void 0:n[1])==null?void 0:a.call(n,JSON.stringify(e)))??JSON.stringify(e,void 0,2),"utf-8")}catch(o){console.error("Error writing file:",o)}}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))}async deleteStorage(){var e;this.ensureDataStoreOptions();try{if(p||(p=(e=await import("fs/promises"))==null?void 0:e.default),!p)throw new h("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new Error("'node:fs/promises' module not available")});let t=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id);await p.unlink(t)}catch(t){console.error("Error deleting file:",t)}}};var z=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 A(e,"SHA-256")}async serializePartial(e,t=!0,i=!0){var a;let n=[];for(let o of this.stores.filter(s=>typeof e=="function"?e(s.id):e.includes(s.id))){let s=!!(t&&o.encodingEnabled()&&((a=o.encodeData)!=null&&a[1])),u=s?await o.encodeData[1](JSON.stringify(o.getData())):JSON.stringify(o.getData());n.push({id:o.id,data:u,formatVersion:o.formatVersion,encoded:s,checksum:this.options.addChecksum?await this.calcChecksum(u):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 T(`Checksum mismatch for DataStore with ID "${n.id}"!
Expected: ${n.checksum}
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 k=()=>({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 w=class{events=k();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)})}onMulti(e){let t=[],i=()=>{for(let n of t)n();t.splice(0,t.length),this.eventUnsubscribes=this.eventUnsubscribes.filter(n=>!t.includes(n))};for(let n of Array.isArray(e)?e:[e]){let a={allOf:[],oneOf:[],once:!1,...n},{oneOf:o,allOf:s,once:u,signal:c,callback:l}=a;if(c!=null&&c.aborted)return i;let d=[],m=(f=!1)=>{if(!(!(c!=null&&c.aborted)&&!f)){for(let b of d)b();d.splice(0,d.length),this.eventUnsubscribes=this.eventUnsubscribes.filter(b=>!d.includes(b))}};for(let f of o){let b=this.events.on(f,(...E)=>{m(),l(f,...E),u&&m(!0)});d.push(b)}let g=new Set,x=(f,...b)=>{m(),g.add(f),g.size===s.length&&(l(f,...b),u&&m(!0))};for(let f of s){let b=this.events.on(f,(...E)=>{m(),x(f,...E)});d.push(b)}if(o.length===0&&s.length===0)throw new TypeError("NanoEmitter.onMulti(): Either `oneOf` or `allOf` or both must be provided in the options");t.push(()=>m(!0))}return i}emit(e,...t){return this.emitterOptions.publicEmit?(this.events.emit(e,...t),!0):!1}unsubscribeAll(){for(let e of this.eventUnsubscribes)e();this.eventUnsubscribes=[]}};var F=class extends w{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 je(r,e=200,t="immediate"){let i=new F(e,t);i.addListener(r);let n=(...a)=>i.call(...a);return n.debouncer=i,n}export{_ as BrowserStorageEngine,T as ChecksumMismatchError,I as DataStore,v as DataStoreEngine,z as DataStoreSerializer,h as DatedError,F as Debouncer,$ as FileStorageEngine,S as MigrationError,w as NanoEmitter,M as ValidationError,B as abtoa,K as atoab,Te as autoPlural,J as bitSetHas,Se as capitalize,y as clamp,O as compress,A as computeHash,ce as consumeGen,de as consumeStringGen,ve as createProgressBar,R as darkenColor,je as debounce,se as decompress,L as defaultPbChars,H as digitCount,me as fetchAdvanced,W as formatNumber,pe as getListLength,C as hexToRgb,we as insertValues,xe as joinArrayReadable,ne as lightenColor,P as mapRange,G as overflowVal,fe as pauseFor,he as pureObj,D as randRange,ue as randomId,Y as randomItem,N as randomItemIndex,ee as randomizeArray,j as rgbToHex,V as roundFixed,ye as scheduleExit,Ee as secsToTimeStr,be as setImmediateInterval,ge as setImmediateTimeoutLoop,te as takeRandomItem,U as takeRandomItemIndex,Pe as truncStr,Z as valsWithin};
//# sourceMappingURL=CoreUtils.min.mjs.map