| # Code of Conduct - memorio | ||
| ## Our Pledge | ||
| In the interest of fostering an open and welcoming environment, we as | ||
| contributors and maintainers pledge to make participation in our project and | ||
| our community a harassment-free experience for everyone, regardless of age, body | ||
| size, disability, ethnicity, sex characteristics, gender identity and expression, | ||
| level of experience, education, socio-economic status, nationality, personal | ||
| appearance, race, religion, or sexual identity and orientation. | ||
| ## Our Standards | ||
| Examples of behavior that contributes to a positive environment for our | ||
| community include: | ||
| * Demonstrating empathy and kindness toward other people | ||
| * Being respectful of differing opinions, viewpoints, and experiences | ||
| * Giving and gracefully accepting constructive feedback | ||
| * Accepting responsibility and apologizing to those affected by our mistakes, | ||
| and learning from the experience | ||
| * Focusing on what is best not just for us as individuals, but for the | ||
| overall community | ||
| Examples of unacceptable behavior include: | ||
| * The use of sexualized language or imagery, and sexual attention or advances | ||
| * Trolling, insulting or derogatory comments, and personal or political attacks | ||
| * Public or private harassment | ||
| * Publishing others' private information, such as a physical or email | ||
| address, without their explicit permission | ||
| * Other conduct which could reasonably be considered inappropriate in a | ||
| professional setting | ||
| ## Our Responsibilities | ||
| Project maintainers are responsible for clarifying and enforcing our standards of | ||
| acceptable behavior and will take appropriate and fair corrective action in | ||
| response to any behavior that they deem inappropriate, | ||
| threatening, offensive, or harmful. | ||
| Project maintainers have the right and responsibility to remove, edit, or reject | ||
| comments, commits, code, wiki edits, issues, and other contributions that are | ||
| not aligned to this Code of Conduct, and will | ||
| communicate reasons for moderation decisions when appropriate. | ||
| ## Scope | ||
| This Code of Conduct applies within all community spaces, and also applies when | ||
| an individual is officially representing the community in public spaces. | ||
| Examples of representing our community include using an official e-mail address, | ||
| posting via an official social media account, or acting as an appointed | ||
| representative at an online or offline event. | ||
| ## Enforcement | ||
| Instances of abusive, harassing, or otherwise unacceptable behavior may be | ||
| reported to the community leaders responsible for enforcement at <dariopassariello@gmail.com>. | ||
| All complaints will be reviewed and investigated promptly and fairly. | ||
| All community leaders are obligated to respect the privacy and security of the | ||
| reporter of any incident. | ||
| ## Enforcement Guidelines | ||
| Community leaders will follow these Community Impact Guidelines in determining | ||
| the consequences for any action they deem in violation of this Code of Conduct: | ||
| ### 1. Correction | ||
| **Community Impact**: Use of inappropriate language or other behavior deemed | ||
| unprofessional or unwelcome in the community. | ||
| **Consequence**: A private, written warning from community leaders, providing | ||
| clarity around the nature of the violation and an explanation of why the | ||
| behavior was inappropriate. A public apology may be requested. | ||
| ### 2. Warning | ||
| **Community Impact**: A violation through a single incident or series | ||
| of actions. | ||
| **Consequence**: A warning with consequences for continued behavior. No | ||
| interaction with the people involved, including unsolicited interaction with | ||
| those enforcing the Code of Conduct, for a specified period of time. This | ||
| includes avoiding interactions in community spaces as well as external channels | ||
| like social media. Violating these terms may lead to a temporary or | ||
| permanent ban. | ||
| ### 3. Temporary Ban | ||
| **Community Impact**: A serious violation of community standards, including | ||
| sustained inappropriate behavior. | ||
| **Consequence**: A temporary ban from any sort of interaction or public | ||
| communication with the community for a specified period of time. No public or | ||
| private interaction with the people involved, including unsolicited interaction | ||
| with those enforcing the Code of Conduct, is allowed during this period. | ||
| Violating these terms may lead to a permanent ban. | ||
| ### 4. Permanent Ban | ||
| **Community Impact**: Demonstrating a pattern of violation of community | ||
| standards, including sustained inappropriate behavior, harassment of an | ||
| individual, or aggression toward or disparagement of classes of individuals. | ||
| **Consequence**: A permanent ban from any sort of public interaction within | ||
| the community. |
+108
| # Contributing | ||
| First off, thanks for taking the time to contribute! | ||
| All types of contributions are encouraged and valued. See the [Table of Contents](contributing.md#table-of-contents) for different ways to help and details about how this project handles them. Please make sure to read the relevant section before making your contribution. It will make it a lot easier for us maintainers and smooth out the experience for all involved. The community looks forward to your contributions. | ||
| > And if you like the project, but just don't have time to contribute, that's fine. There are other easy ways to support the project and show your appreciation, which we would also be very happy about: | ||
| > | ||
| > * Star the project | ||
| > * Tweet about it | ||
| > * Refer this project in your project's readme | ||
| > * Mention the project at local meetups and tell your friends/colleagues | ||
| ## Table of Contents | ||
| * [Code of Conduct](contributing.md#code-of-conduct) | ||
| * [I Have a Question](contributing.md#i-have-a-question) | ||
| * [I Want To Contribute](contributing.md#i-want-to-contribute) | ||
| * [Reporting Bugs](contributing.md#reporting-bugs) | ||
| * [Suggesting Enhancements](contributing.md#suggesting-enhancements) | ||
| * [Your First Code Contribution](contributing.md#your-first-code-contribution) | ||
| * [Improving The Documentation](contributing.md#improving-the-documentation) | ||
| * [Style guides](contributing.md#styleguides) | ||
| * [Commit Messages](contributing.md#commit-messages) | ||
| * [Join The Project Team](contributing.md#join-the-project-team) | ||
| ## Code of Conduct | ||
| This project and everyone participating in it is governed by the [memorio Code of Conduct](https://github.com/a51-dev/a51.memorio/blob/CODE_OF_CONDUCT.md). By participating, you are expected to uphold this code. Please report unacceptable behavior to [dariopassariello@gmail.com](mailto:dariopassariello@gmail.com). | ||
| ## I Have a Question | ||
| > If you want to ask a question, we assume that you have read the available [Documentation](https://a51.gitbook.io/memorio/). | ||
| Before you ask a question, it is best to search for existing [Issues](https://github.com/a51-dev/a51.memorio/issues) that might help you. In case you have found a suitable issue and still need clarification, you can write your question in this issue. It is also advisable to search the internet for answers first. | ||
| If you then still feel the need to ask a question and need clarification, we recommend the following: | ||
| * Open an [Issue](https://github.com/a51-dev/a51.memorio/issues/new). | ||
| * Provide as much context as you can about what you're running into. | ||
| * Provide project and platform versions (nodejs, npm, etc), depending on what seems relevant. | ||
| We will then take care of the issue as soon as possible. | ||
| ## I Want To Contribute | ||
| > ### Legal Notice | ||
| > | ||
| > When contributing to this project, you must agree that you have authored 100% of the content, that you have the necessary rights to the content and that the content you contribute may be provided under the project license. | ||
| ### Reporting Bugs | ||
| #### Before Submitting a Bug Report | ||
| A good bug report shouldn't leave others needing to chase you up for more information. Therefore, we ask you to investigate carefully, collect information and describe the issue in detail in your report. Please complete the following steps in advance to help us fix any potential bug as fast as possible. | ||
| * Make sure that you are using the latest version. | ||
| * Determine if your bug is really a bug and not an error on your side e.g. using incompatible environment components/versions (Make sure that you have read the [documentation](https://a51.gitbook.io/memorio/). If you are looking for support, you might want to check [this section](contributing.md#i-have-a-question)). | ||
| * To see if other users have experienced (and potentially already solved) the same issue you are having, check if there is not already a bug report existing for your bug or error in the [bug tracker](https://github.com/a51-dev/a51.memorio/issues?q=label%3Abug). | ||
| * Also make sure to search the internet (including Stack Overflow) to see if users outside of the GitHub community have discussed the issue. | ||
| * Collect information about the bug: | ||
| * Stack trace (Traceback) | ||
| * OS, Platform and Version (Windows, Linux, macOS, x86, ARM) | ||
| * Version of the interpreter, compiler, SDK, runtime environment, package manager, depending on what seems relevant. | ||
| * Possibly your input and the output | ||
| * Can you reliably reproduce the issue? And can you also reproduce it with older versions? | ||
| #### How Do I Submit a Good Bug Report? | ||
| > You must never report security related issues, vulnerabilities or bugs including sensitive information to the issue tracker, or elsewhere in public. Instead sensitive bugs must be sent by email to [dariopassariello@gmail.com](mailto:dariopassariello@gmail.com). | ||
| We use GitHub issues to track bugs and errors. If you run into an issue with the project: | ||
| * Open an [Issue](https://github.com/a51-dev/a51.memorio/issues/new). (Since we can't be sure at this point whether it is a bug or not, we ask you not to talk about a bug yet and not to label the issue.) | ||
| * Explain the behavior you would expect and the actual behavior. | ||
| * Please provide as much context as possible and describe the _reproduction steps_ that someone else can follow to recreate the issue on their own. This usually includes your code. For good bug reports you should isolate the problem and create a reduced test case. | ||
| * Provide the information you collected in the previous section. | ||
| Once it's filed: | ||
| * The project team will label the issue accordingly. | ||
| * A team member will try to reproduce the issue with your provided steps. If there are no reproduction steps or no obvious way to reproduce the issue, the team will ask you for those steps and mark the issue as `needs-repro`. Bugs with the `needs-repro` tag will not be addressed until they are reproduced. | ||
| * If the team is able to reproduce the issue, it will be marked `needs-fix`, as well as possibly other tags (such as `critical`), and the issue will be left to be [implemented by someone](contributing.md#your-first-code-contribution). | ||
| ### Suggesting Enhancements | ||
| This section guides you through submitting an enhancement suggestion for memorio, **including completely new features and minor improvements to existing functionality**. Following these guidelines will help maintainers and the community to understand your suggestion and find related suggestions. | ||
| #### Before Submitting an Enhancement | ||
| * Make sure that you are using the latest version. | ||
| * Read the [documentation](https://a51.gitbook.io/memorio/) carefully and find out if the functionality is already covered, maybe by an individual configuration. | ||
| * Perform a [search](https://github.com/a51-dev/a51.memorio/issues) to see if the enhancement has already been suggested. If it has, add a comment to the existing issue instead of opening a new one. | ||
| * Find out whether your idea fits with the scope and aims of the project. It's up to you to make a strong case to convince the project's developers of the merits of this feature. Keep in mind that we want features that will be useful to the majority of our users and not just a small subset. If you're just targeting a minority of users, consider writing an add-on/plugin library. | ||
| #### How Do I Submit a Good Enhancement Suggestion? | ||
| Enhancement suggestions are tracked as [GitHub issues](https://github.com/a51-dev/a51.memorio/issues). | ||
| * Use a **clear and descriptive title** for the issue to identify the suggestion. | ||
| * Provide a **step-by-step description of the suggested enhancement** in as many details as possible. | ||
| * **Describe the current behavior** and **explain which behavior you expected to see instead** and why. At this point you can also tell which alternatives do not work for you. | ||
| * You may want to **include screenshots or screen recordings** which help you demonstrate the steps or point out the part which the suggestion is related to. You can use [screentogif](https://www.screentogif.com/) to record GIFs on macOS and Windows, and the built-in [screen recorder in GNOME](https://help.gnome.org/users/gnome-help/stable/screen-shot-record.html.en) or [SimpleScreenRecorder](https://github.com/MaartenBaert/ssr) on Linux. | ||
| * **Explain why this enhancement would be useful** to most boilerplate users. You may also want to point out the other projects that solved it better and which could serve as inspiration. | ||
| ## Join The Project Team | ||
| Please send email to <dariopassariello@gmail.com> |
| # Copyright | ||
| Copyright (c) 2025, Dario Passariello. All rights reserved. | ||
| <https://dario.passariello.ca> | ||
| This software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the software. |
| 'use strict'; | ||
| var __getOwnPropNames=Object.getOwnPropertyNames;var __esm=(fn,res)=>function __init(){return fn&&(res=(0, fn[__getOwnPropNames(fn)[0]])(fn=0)),res};var db_create_exports={};var init_db_create=__esm({"functions/idb/tools/db.create.ts"(){idb.db.create=(dbName,ver=1)=>{return new Promise((resolve,reject)=>{if(!idb.db.support()){return reject(new Error("IndexedDB not supported"))}const request=globalThis.indexedDB.open(dbName,ver);request.onerror=()=>{console.debug(`IndexedDB error: ${request.error?.message}`);reject(request.error);};request.onsuccess=()=>{console.debug(`Database ${dbName} connected successfully`);idb.db.list();resolve(request.result);};request.onupgradeneeded=()=>{console.debug(`Database ${dbName} upgrade/creation initiated`);};})};}});var db_list_exports={};var init_db_list=__esm({"functions/idb/tools/db.list.ts"(){idb.db.list=async()=>{if(!("indexedDB"in globalThis)||!indexedDB.databases)return [];try{const result=await indexedDB.databases();globalThis.idbases=result||[];await idb.db.size();return globalThis.idbases}catch(err){console.error("Error listing databases:",err);return []}};idb.db.list();}});var db_exist_exports={};var init_db_exist=__esm({"functions/idb/tools/db.exist.ts"(){idb.db.exist=storeName=>{return idbases?.some(db=>db.name===storeName)};}});var db_quota_exports={};var init_db_quota=__esm({"functions/idb/tools/db.quota.ts"(){idb.db.quota=()=>{return navigator.storage.estimate()};}});var db_delete_exports={};var init_db_delete=__esm({"functions/idb/tools/db.delete.ts"(){idb.db.delete=storeName=>{return new Promise((resolve,reject)=>{console.debug(`Removing database ${storeName}...`);const performDelete=()=>{const request=indexedDB.deleteDatabase(storeName);request.onsuccess=()=>{console.debug(`${storeName} database removed successfully`);idb.db.list();resolve();};request.onerror=()=>{console.error(`Error removing ${storeName}:`,request.error);reject(request.error);};request.onblocked=()=>{console.warn(`Deletion of ${storeName} is blocked. Please close other tabs.`);};};if(confirm(`Are you sure you want to remove the "${storeName}" database?`)){performDelete();}else {console.debug("Database deletion cancelled by user.");resolve();}})};}});var db_size_exports={};var init_db_size=__esm({"functions/idb/tools/db.size.ts"(){idb.db.size=async()=>{if(!idbases||idbases.length===0)return;for(let i=0;i<idbases.length;i++){const dbInfo=idbases[i];try{const db=await idb.db.create(dbInfo.name,dbInfo.version);const tableNames=Array.from(db.objectStoreNames);let totalDbSize=0;for(const tableName of tableNames){const tableSize=await idb.table.size(db,tableName);totalDbSize+=tableSize;}dbInfo.size=totalDbSize;db.close();}catch(err){console.debug(`Could not calculate size for ${dbInfo.name}:`,err);}}};}});var db_version_exports={};var init_db_version=__esm({"functions/idb/tools/db.version.ts"(){idb.db.version=storeName=>{let idbVer=0;for(const v of idbases){if(v.name===storeName)idbVer=v.version;break}return idbVer};}});var db_support_exports={};var init_db_support=__esm({"functions/idb/tools/db.support.ts"(){idb.db.support=()=>{const isSupported="indexedDB"in globalThis;if(!isSupported){console.debug("Your environment doesn't support IndexedDB");}return isSupported};}});var table_create_exports={};var init_table_create=__esm({"functions/idb/tools/table.create.ts"(){idb.table.create=(dbName,dbTable)=>{return new Promise(async(resolve,reject)=>{try{const currentVersion=Number(idb.db.version(dbName))||0;const nextVersion=currentVersion+1;const request=indexedDB.open(dbName,nextVersion);request.onupgradeneeded=e=>{const db=e.target.result;if(!db.objectStoreNames.contains(dbTable)){const store2=db.createObjectStore(dbTable,{keyPath:"id",autoIncrement:true});store2.createIndex("id","id",{unique:true});store2.createIndex("data","data",{unique:false});console.debug(`Table ${dbTable} created in ${dbName}`);}};request.onsuccess=()=>{request.result.close();idb.db.list();resolve();};request.onerror=()=>{console.error(`Error creating table ${dbTable}:`,request.error);reject(request.error);};}catch(err){console.error("Critical error in table.create:",err);reject(err);}})};}});var table_size_exports={};var init_table_size=__esm({"functions/idb/tools/table.size.ts"(){idb.table.size=(db,table)=>{return new Promise((resolve,reject)=>{if(!db)return reject(new Error("Database instance is required"));if(!db.objectStoreNames.contains(table))return resolve(0);let size=0;let count=0;const transaction=db.transaction([table],"readonly");const store2=transaction.objectStore(table);const request=store2.openCursor();request.onsuccess=async event=>{const cursor=event.target.result;if(cursor){try{const value=cursor.value;size+=JSON.stringify(value).length;}catch(e){console.debug("Error stringifying IDB value tracking size:",e);}count++;if(count%200===0){await new Promise(resolve2=>setTimeout(resolve2,0));}cursor.continue();}else {resolve(size);}};request.onerror=()=>{reject(request.error);};})};}});var data_delete_exports={};var init_data_delete=__esm({"functions/idb/crud/data.delete.ts"(){idb.data.delete=(storeName,table,key)=>{return new Promise((resolve,reject)=>{const request=indexedDB.open(storeName);request.onsuccess=()=>{const db=request.result;if(!db.objectStoreNames.contains(table)){db.close();return reject(new Error(`Table ${table} not found`))}const transaction=db.transaction(table,"readwrite");const objectStore=transaction.objectStore(table);const deleteRequest=objectStore.delete(key);deleteRequest.onsuccess=()=>{db.close();console.debug(`Record ${key} deleted from ${table}`);resolve();};deleteRequest.onerror=()=>{db.close();reject(deleteRequest.error);};};request.onerror=()=>reject(request.error);})};idb.data.delete.all=(storeName,table)=>{return new Promise((resolve,reject)=>{const request=indexedDB.open(storeName);request.onsuccess=event=>{const db=event.target.result;if(!db.objectStoreNames.contains(table)){db.close();return reject(new Error(`Table ${table} not found`))}const transaction=db.transaction(table,"readwrite");const store2=transaction.objectStore(table);const clearRequest=store2.clear();clearRequest.onsuccess=()=>{db.close();console.debug(`All data cleared from ${table}`);resolve();};clearRequest.onerror=()=>{db.close();reject(clearRequest.error);};};request.onerror=()=>reject(request.error);})};}});var data_set_exports={};var init_data_set=__esm({"functions/idb/crud/data.set.ts"(){idb.data.set=(storeName,table,value)=>{return new Promise((resolve,reject)=>{const request=indexedDB.open(storeName);request.onsuccess=()=>{const db=request.result;if(!db.objectStoreNames.contains(table)){db.close();return reject(new Error(`Table ${table} does not exist in ${storeName}`))}const transaction=db.transaction(table,"readwrite");const objectStore=transaction.objectStore(table);const putRequest=objectStore.put(value);putRequest.onsuccess=()=>{db.close();console.debug(`Data saved in ${storeName}.${table}`);resolve(putRequest.result);};putRequest.onerror=e=>{db.close();console.debug(`Database insert error: ${putRequest.error?.message}`);reject(putRequest.error);};};request.onerror=()=>{reject(request.error);};})};}});var data_get_exports={};var init_data_get=__esm({"functions/idb/crud/data.get.ts"(){idb.data.get=(storeName,table,key)=>{return new Promise((resolve,reject)=>{const request=indexedDB.open(storeName);request.onsuccess=event=>{const db=event.target.result;if(!db.objectStoreNames.contains(table)){db.close();return reject(new Error(`Table ${table} not found in ${storeName}`))}const transaction=db.transaction(table,"readonly");const store2=transaction.objectStore(table);const getRequest=store2.get(key);getRequest.onsuccess=()=>{db.close();resolve(getRequest.result);};getRequest.onerror=()=>{db.close();reject(getRequest.error);};};request.onerror=()=>{reject(request.error);};})};}});var package_default={version:"2.6.0"};Object.defineProperty(globalThis,"memorio",{value:{},writable:false,configurable:true,enumerable:false});Object.defineProperty(globalThis,"events",{value:{},writable:true,enumerable:false});Object.defineProperty(memorio,"version",{writable:false,enumerable:false,value:package_default.version});var protect=["list","state","store","idb","observer","useObserver","remove","removeAll"];Object.defineProperty(memorio,"dispatch",{writable:false,enumerable:false,value:{set:(name,value={})=>{globalThis.dispatchEvent(new CustomEvent(String(name),value));},listen:(name,cb=null,flag=false)=>{if(globalThis.observer?.list?.[name]?.length>0)globalThis.observer?.remove?.(name);const exec=cb?e=>setTimeout(()=>cb(e),1):void 0;if(exec)globalThis.addEventListener(name,exec);if(exec)globalThis.events[name]=exec;},remove:name=>{const listener=globalThis.events?.[name];if(listener){globalThis.removeEventListener(name,listener);delete globalThis.events[name];}}}});memorio.propertyName=(container,object)=>{const t=String(object).replace("() => ","");return t};Object.defineProperty(memorio,"objPath",{writable:false,enumerable:false,value:(prop,object,separator=".")=>{const path=object.concat(prop).join(separator);if(globalThis.memorio._tracking){globalThis.memorio._trackedPaths?.add("state."+path);}return path}});globalThis.memorio._tracking=false;globalThis.memorio._trackedPaths=new Set;globalThis.memorio._locked=false;var buildProxy=(obj,callback,tree=[])=>{const event=name=>{try{globalThis.memorio?.dispatch?.set?.(name,{detail:{name}});}catch(e){}return};return new Proxy(obj,{get(target,prop){if(prop==="__path"){return tree.length>0?"state."+tree.join("."):"state"}if(prop==="list"){console.debug('Some state could be hidden when you use "state.list". Use "state" to see the complete list ');return JSON.parse(JSON.stringify(globalThis.state))}if(globalThis.memorio._tracking&&typeof prop==="string"){const path=tree.length>0?"state."+tree.concat(prop).join("."):"state."+prop;globalThis.memorio._trackedPaths?.add(path);}if(prop==="remove"){return key=>{delete target[key];return true}}if(prop==="removeAll"){return ()=>{try{for(const key in target){if(typeof target[key]!=="function"&&!["list","remove","removeAll"].includes(key)){if(!Object.isFrozen(target[key]))delete target[key];delete target[key];}}}catch(error){console.debug(error);}return}}if(Object.isFrozen(target[prop]))return target[prop];if(prop==="lock"||prop==="unlock"){const value=Reflect.get(target,prop);if(value)return value}try{const value=Reflect.get(target,prop);if(value&&typeof value==="object"&&["Array","Object"].includes(value.constructor.name)){return buildProxy(value,callback,tree.concat(prop))}return value}catch(error){console.error("Error: ",error);return void 0}},set(target,key,value){if(globalThis.memorio._locked){console.error("Error: state is locked. Use state.unlock() to enable modifications.");return false}if(protect.includes(key)){console.error("key "+key+" is protected");return false}if(target[key]&&typeof target[key]==="object"&&Object.isFrozen(target[key])){console.error(`Error: state '${key}' is locked`);return false}if(target[key]&&typeof target[key]==="object"&&target[key].__locked){console.error(`Error: state '${key}' is locked. Use state.${key}.unlock() to enable modifications.`);return false}try{const path=globalThis.memorio.objPath?.(key,tree)??key;callback({action:"set",path,target,newValue:value,previousValue:Reflect.get(target,key)});event("state."+path);Reflect.set(target,key,value);if(target[key]&&typeof target[key]==="object"){const rawValue=target[key];if(rawValue&&typeof rawValue==="object"){try{Object.defineProperty(rawValue,"__locked",{writable:true,enumerable:false,configurable:false,value:false});Object.defineProperty(rawValue,"lock",{writable:false,enumerable:false,configurable:false,value:()=>{Object.defineProperty(rawValue,"__locked",{writable:true,enumerable:false,configurable:false,value:true});console.info(`State '${key}' is now locked.`);}});Object.defineProperty(rawValue,"unlock",{writable:false,enumerable:false,configurable:false,value:()=>{Object.defineProperty(rawValue,"__locked",{writable:true,enumerable:false,configurable:false,value:false});console.info(`State '${key}' is now unlocked.`);}});}catch(defineError){}}}return true}catch(error){console.error("Error in set trap:",error);return false}},deleteProperty(target,prop){try{const path=globalThis.memorio.objPath?.(prop,tree);callback({action:"delete",path,target});return Reflect.deleteProperty(target,prop)}catch(error){console.error("Error in deleteProperty trap:",error);return false}},ownKeys(target){return Reflect.ownKeys(target)},getOwnPropertyDescriptor(target,prop){return Reflect.getOwnPropertyDescriptor(target,prop)}})};!globalThis?.state?globalThis.state=buildProxy({},()=>{}):globalThis.state=state;globalThis.state.lock=()=>{globalThis.memorio._locked=true;console.info("State is now locked. All modifications are blocked.");};globalThis.state.unlock=()=>{globalThis.memorio._locked=false;console.info("State is now unlocked. Modifications are allowed.");};Object.defineProperty(globalThis,"state",{enumerable:false,configurable:true});if(!globalThis.observer){globalThis.observer=null;}Object.defineProperty(globalThis,"observer",{enumerable:false,configurable:true});var observerFunction=(s,cb=null,option=true)=>{console.warn('DEPRECATED: "observer" is deprecated and will be removed in future versions. Please use "useObserver" instead.');try{const checkStateOrStore=s2=>{const t=s2.split(".");if(t[0]!=="state"){console.error(`Observer Error: You need to declare 'state.' or 'store.'. The '${s2}' string is incorrect!`);return false}return true};if(!checkStateOrStore(s))return}catch(error){console.error(error);return}if(!s&&!cb){console.error("Observer Error: You need to setup observer correctly, Some parameters are missed!");return}if(!s&&cb){console.error(`Observer Error: You need to declare what state need to be monitored as string like 'state.test'.`);return}if(s&&!cb){const f=({detail:{name:String(s)}});const obs=globalThis.observer;if(obs?.list?.[s])globalThis.memorio.dispatch.remove(f);if(!obs?.list?.[s])globalThis.memorio.dispatch.listen(f);console.debug("called: ",s);return}if(s&&cb){if(typeof s!=="string"||typeof cb!=="function"){console.error(`Observer Error: name of state need to be a 'string' like 'state.test' and the callback need to be a 'function'`);return}const obs=globalThis.observer;if(obs?.list?.[s])globalThis.memorio.dispatch.remove(s,cb,option);if(!obs?.list?.[s])globalThis.memorio.dispatch.listen(s,cb,option);return}};globalThis.observer=observerFunction;Object.defineProperties(globalThis.observer,{list:{get:()=>globalThis.events},remove:{value:name=>{if(!name)return;globalThis.memorio.dispatch.remove(name);delete globalThis.events[name];return}},removeAll:{get:()=>{const obs=globalThis.observer;const list=obs?.list;if(list){Object.keys(list).forEach(key=>{obs?.remove?.(key);});}return true}}});Object.freeze(observer);if(!globalThis.useObserver)globalThis.useObserver=null;Object.defineProperty(globalThis,"useObserver",{value:null,writable:true,enumerable:false,configurable:true});globalThis.useObserver=((func,deps)=>{if(!deps||typeof func!=="function"){return ()=>{}}const handlers=[];const depList=Array.isArray(deps)&&!deps.__path?deps:[deps];try{depList.forEach(dep=>{let t="";if(typeof dep==="function"){const propName=globalThis.memorio.propertyName;if(typeof propName==="function"){const result=propName(globalThis.state,dep);if(result)t=result;}}else if(typeof dep==="object"&&dep!==null){t=dep.__path||(typeof dep.toString==="function"&&dep.toString()!=="[object Object]"?dep.toString():"");}else if(typeof dep==="string"&&(dep.startsWith("state.")||dep.startsWith("store."))){t=dep;}if(t){t=t.replace(/^(\(\)\s*=>\s*)/,"").replace(/^globalThis\./,"").replace(/^state\./,"");const path=t.startsWith("store.")||t.startsWith("state.")?t:"state."+t;globalThis.memorio.dispatch.listen(path,()=>func());handlers.push(path);}else {globalThis.memorio._trackedPaths?.clear();globalThis.memorio._tracking=true;try{func();}catch(e){}globalThis.memorio._tracking=false;globalThis.memorio._trackedPaths?.forEach(path=>{if(!handlers.includes(path)){console.info(`useObserver: [Auto-Discovery] -> "${path}"`);globalThis.memorio.dispatch.listen(path,()=>func());handlers.push(path);}});}});if(handlers.length>0){console.info(`useObserver: Monitoring ${handlers.length} paths.`);}else {console.warn(`useObserver: No paths resolved for monitoring. Check your dependencies!`);}return ()=>{handlers.forEach(path=>{if(globalThis.memorio.dispatch&&typeof globalThis.memorio.dispatch.remove==="function"){globalThis.memorio.dispatch.remove(path);console.debug(`useObserver: Stopped monitoring "${path}"`);}});}}catch(err){console.debug("useObserver Error:",err);return ()=>{}}});Object.freeze(globalThis.useObserver);Object.defineProperty(globalThis,"store",{value:new Proxy({},{}),enumerable:false,configurable:true});Object.defineProperties(store,{get:{value:name=>{if(!name)return;try{const item=globalThis.localStorage.getItem(name);if(item)return JSON.parse(item);return item}catch(err){console.debug(`Error parsing store item '${name}':`,err);}return null}},set:{value:(name,value)=>{if(!name)return;try{if(value===null||value===void 0)globalThis.localStorage.setItem(name,JSON.stringify(null));else if(typeof value==="object"||typeof value==="number"||typeof value==="boolean"||typeof value==="string")globalThis.localStorage.setItem(name,JSON.stringify(value));else if(typeof value==="function")console.debug("It's not secure to store functions.");}catch(err){console.debug(`Error setting store item '${name}':`,err);}return null}},remove:{value:name=>{if(!name)return;if(globalThis.localStorage.getItem(name)){globalThis.localStorage.removeItem(name);return true}return false}},delete:{value:name=>{store.remove(name);return true}},removeAll:{value:()=>{globalThis.localStorage.clear();return true}},clearAll:{value:()=>{store.removeAll();return true}},quota:{value:async()=>{if(globalThis.navigator&&"storage"in globalThis.navigator&&"estimate"in globalThis.navigator.storage){return globalThis.navigator.storage.estimate().then(({usage,quota})=>{const u=usage??0;const q=quota??0;if(u&&q)console.debug(`Using ${u/1024} out of ${q/1024} Mb.`);return [u/1024,q/1024]}).catch(err=>{console.debug("Error estimating quota:",err);return [0,0]})}return [0,0]}},size:{value:()=>{let totalSize=0;Object.keys(globalThis.localStorage).forEach(key=>{const item=globalThis.localStorage.getItem(key);if(item)totalSize+=item.length;});return totalSize}}});Object.freeze(store);Object.defineProperty(globalThis,"session",{value:new Proxy({},{}),enumerable:false,configurable:true});Object.defineProperties(session,{get:{value:name=>{if(!name)return;try{const item=globalThis.sessionStorage.getItem(name);if(item)return JSON.parse(item);return item}catch(err){console.debug(`Error parsing session item '${name}':`,err);}return}},set:{value:(name,value)=>{if(!name)return;try{if(value===null||value===void 0)globalThis.sessionStorage.setItem(name,JSON.stringify(null));else if(typeof value==="object"||typeof value==="number"||typeof value==="boolean"||typeof value==="string")globalThis.sessionStorage.setItem(name,JSON.stringify(value));else if(typeof value==="function")console.debug("It's not secure to session functions.");}catch(err){console.debug(`Error setting session item '${name}':`,err);}return}},remove:{value:name=>{if(!name)return;if(globalThis.sessionStorage.getItem(name)){globalThis.sessionStorage.removeItem(name);return true}return}},delete:{value:name=>{session.remove(name);return true}},removeAll:{value:()=>{globalThis.sessionStorage.clear();return true}},clearAll:{value:()=>{session.removeAll();return true}},quota:{value:async()=>{if(globalThis.navigator&&"storage"in globalThis.navigator&&"estimate"in globalThis.navigator.storage){return globalThis.navigator.storage.estimate().then(({usage,quota})=>{const u=usage??0;const q=quota??0;if(u&&q)console.debug(`Using ${u/1024} out of ${q/1024} Mb.`);return [u/1024,q/1024]}).catch(err=>{console.debug("Error estimating quota:",err);return [0,0]})}return [0,0]}},size:{value:()=>{let totalSize=0;Object.keys(globalThis.sessionStorage).forEach(key=>{const item=globalThis.sessionStorage.getItem(key);if(item)totalSize+=item.length;});return totalSize}}});Object.freeze(session);var cacheData={};Object.defineProperty(globalThis,"cache",{value:new Proxy({},{get(target,prop){const key=prop;if(key==="get")return name=>cacheData[name];if(key==="set")return (name,value)=>{cacheData[name]=value;};if(key==="remove")return name=>{delete cacheData[name];return true};if(key==="removeAll")return ()=>{Object.keys(cacheData).forEach(k=>delete cacheData[k]);return true};if(key==="clear")return ()=>{Object.keys(cacheData).forEach(k=>delete cacheData[k]);return true};return cacheData[key]},set(target,prop,value){cacheData[prop]=value;return true},deleteProperty(target,prop){delete cacheData[prop];return true}}),enumerable:false,configurable:true});Object.freeze(cache);(async()=>{Object.defineProperty(globalThis,"idb",{value:{db:{},table:{},data:{}},writable:true,configurable:true,enumerable:false});Object.defineProperty(globalThis,"idbases",{value:[],writable:true,configurable:true,enumerable:false});await Promise.all([Promise.resolve().then(()=>(init_db_create(),db_create_exports)),Promise.resolve().then(()=>(init_db_list(),db_list_exports)),Promise.resolve().then(()=>(init_db_exist(),db_exist_exports)),Promise.resolve().then(()=>(init_db_quota(),db_quota_exports)),Promise.resolve().then(()=>(init_db_delete(),db_delete_exports)),Promise.resolve().then(()=>(init_db_size(),db_size_exports)),Promise.resolve().then(()=>(init_db_version(),db_version_exports)),Promise.resolve().then(()=>(init_db_support(),db_support_exports)),Promise.resolve().then(()=>(init_table_create(),table_create_exports)),Promise.resolve().then(()=>(init_table_size(),table_size_exports)),Promise.resolve().then(()=>(init_data_delete(),data_delete_exports)),Promise.resolve().then(()=>(init_data_set(),data_set_exports)),Promise.resolve().then(()=>(init_data_get(),data_get_exports))]);Object.preventExtensions(idb);Object.seal(idb);Object.freeze(idb);})(); |
| # Security | ||
| Please email [@passariello](https://github.com/passariello) or see https://dario.passariello.ca/contact/ if you have a potential security vulnerability to report. |
+1
-1
@@ -1,1 +0,1 @@ | ||
| var l=(e,r)=>()=>(e&&(r=e(e=0)),r);var p,h=l(()=>{p={name:"memorio",version:"2.5.3",type:"module",private:!1,main:"index.js",license:"MIT",typings:"./types/*",description:"Memorio, State + Observer and Store for an easy life",copyright:"Copyright (c) 2025 Dario Passariello",homepage:"https://a51.gitbook.io/memorio",author:{name:"Dario Passariello",url:"https://dario.passariello.ca/",email:"dariopassariello@gmail.com"},support:{name:"Dario Passariello",url:"https://github.com/passariello/",email:"dariopassariello@gmail.com"},contributors:[{name:"Dario Passariello",email:"dariopassarielloa@gmail.com"},{name:"Valeria Cala Scaglitta",email:"valeriacalascaglitta@gmail.com"}],keywords:["biglogic","a51","memorio","state","store","observer","useObserver","dario","passariello"],funding:[{type:"patreon",url:"https://www.patreon.com/passariello"}],typing:["types/*"],exports:{".":{types:"./types/index.d.ts",import:"./index.js",default:"./index.js"},"./types/*":"./types/*"},scripts:{build:"rimraf dist && node ./esbuild.config.mjs",watch:'rimraf dist && nodemon --watch * --exec "npm run build "',"npm:publish":"npm run build && npm publish ./dist",test:"cd tests && npm run test",lint:"cd tests && npm run lint",tsc:"tsc --noEmit"},devDependencies:{"@types/node":"25.3.3",esbuild:"0.27.3","esbuild-node-externals":"1.20.1","esbuild-plugin-alias":"0.2.1","esbuild-plugin-copy":"2.1.1",rimraf:"6.1.3",typescript:"5.9.3"}}});var y,m=l(()=>{"use strict";a();h();Object.defineProperty(globalThis,"memorio",{value:{},writable:!1,configurable:!0,enumerable:!1});Object.defineProperty(globalThis,"events",{value:{},writable:!0,enumerable:!1});Object.defineProperty(memorio,"version",{writable:!1,enumerable:!1,value:p.version});y=["list","state","store","idb","observer","useObserver","remove","removeAll"]});var v=l(()=>{"use strict";a();Object.defineProperty(memorio,"dispatch",{writable:!1,enumerable:!1,value:{set:(e,r={})=>{globalThis.dispatchEvent(new CustomEvent(String(e),r))},listen:(e,r=null,o=!1)=>{globalThis.observer?.list?.[e]?.length>0&&globalThis.observer?.remove?.(e);let i=r?t=>setTimeout(()=>r(t),1):void 0;i&&globalThis.addEventListener(e,i),i&&(globalThis.events[e]=i)},remove:e=>{let r=globalThis.events?.[e];r&&(globalThis.removeEventListener(e,r),delete globalThis.events[e])}}})});var T=l(()=>{"use strict";a();memorio.propertyName=(e,r)=>String(r).replace("() => ","")});var P,O=l(()=>{"use strict";a();m();Object.defineProperty(memorio,"objPath",{writable:!1,enumerable:!1,value:(e,r,o=".")=>{let i=r.concat(e).join(o);return globalThis.memorio._tracking&&globalThis.memorio._trackedPaths?.add("state."+i),i}});globalThis.memorio._tracking=!1;globalThis.memorio._trackedPaths=new Set;globalThis.memorio._locked=!1;P=(e,r,o=[])=>{let i=t=>{try{globalThis.memorio?.dispatch?.set?.(t,{detail:{name:t}})}catch{}};return new Proxy(e,{get(t,s){if(s==="__path")return o.length>0?"state."+o.join("."):"state";if(s==="list")return console.debug('Some state could be hidden when you use "state.list". Use "state" to see the complete list '),JSON.parse(JSON.stringify(globalThis.state));if(globalThis.memorio._tracking&&typeof s=="string"){let n=o.length>0?"state."+o.concat(s).join("."):"state."+s;globalThis.memorio._trackedPaths?.add(n)}if(s==="remove")return n=>(delete t[n],!0);if(s==="removeAll")return()=>{try{for(let n in t)typeof t[n]!="function"&&!["list","remove","removeAll"].includes(n)&&(Object.isFrozen(t[n])||delete t[n],delete t[n])}catch(n){console.debug(n)}};if(Object.isFrozen(t[s]))return t[s];if(s==="lock"||s==="unlock"){let n=Reflect.get(t,s);if(n)return n}try{let n=Reflect.get(t,s);return n&&typeof n=="object"&&["Array","Object"].includes(n.constructor.name)?P(n,r,o.concat(s)):n}catch(n){console.error("Error: ",n);return}},set(t,s,n){if(globalThis.memorio._locked)return console.error("Error: state is locked. Use state.unlock() to enable modifications."),!1;if(y.includes(s))return console.error("key "+s+" is protected"),!1;if(t[s]&&typeof t[s]=="object"&&Object.isFrozen(t[s]))return console.error(`Error: state '${s}' is locked`),!1;if(t[s]&&typeof t[s]=="object"&&t[s].__locked)return console.error(`Error: state '${s}' is locked. Use state.${s}.unlock() to enable modifications.`),!1;try{let u=globalThis.memorio.objPath?.(s,o)??s;if(r({action:"set",path:u,target:t,newValue:n,previousValue:Reflect.get(t,s)}),i("state."+u),Reflect.set(t,s,n),t[s]&&typeof t[s]=="object"){let b=t[s];if(b&&typeof b=="object")try{Object.defineProperty(b,"__locked",{writable:!0,enumerable:!1,configurable:!1,value:!1}),Object.defineProperty(b,"lock",{writable:!1,enumerable:!1,configurable:!1,value:()=>{Object.defineProperty(b,"__locked",{writable:!0,enumerable:!1,configurable:!1,value:!0}),console.info(`State '${s}' is now locked.`)}}),Object.defineProperty(b,"unlock",{writable:!1,enumerable:!1,configurable:!1,value:()=>{Object.defineProperty(b,"__locked",{writable:!0,enumerable:!1,configurable:!1,value:!1}),console.info(`State '${s}' is now unlocked.`)}})}catch{}}return!0}catch(u){return console.error("Error in set trap:",u),!1}},deleteProperty(t,s){try{let n=globalThis.memorio.objPath?.(s,o);return r({action:"delete",path:n,target:t}),Reflect.deleteProperty(t,s)}catch(n){return console.error("Error in deleteProperty trap:",n),!1}},ownKeys(t){return Reflect.ownKeys(t)},getOwnPropertyDescriptor(t,s){return Reflect.getOwnPropertyDescriptor(t,s)}})};globalThis?.state?globalThis.state=state:globalThis.state=P({},()=>{});globalThis.state.lock=()=>{globalThis.memorio._locked=!0,console.info("State is now locked. All modifications are blocked.")};globalThis.state.unlock=()=>{globalThis.memorio._locked=!1,console.info("State is now unlocked. Modifications are allowed.")};Object.defineProperty(globalThis,"state",{enumerable:!1,configurable:!0})});var F,S=l(()=>{"use strict";a();globalThis.observer||(globalThis.observer=null);Object.defineProperty(globalThis,"observer",{enumerable:!1,configurable:!0});F=(e,r=null,o=!0)=>{console.warn('DEPRECATED: "observer" is deprecated and will be removed in future versions. Please use "useObserver" instead.');try{if(!(t=>t.split(".")[0]!=="state"?(console.error(`Observer Error: You need to declare 'state.' or 'store.'. The '${t}' string is incorrect!`),!1):!0)(e))return}catch(i){console.error(i);return}if(!e&&!r){console.error("Observer Error: You need to setup observer correctly, Some parameters are missed!");return}if(!e&&r){console.error("Observer Error: You need to declare what state need to be monitored as string like 'state.test'.");return}if(e&&!r){let i=(String(e),{detail:{name:String(e)}}),t=globalThis.observer;t?.list?.[e]&&globalThis.memorio.dispatch.remove(i),t?.list?.[e]||globalThis.memorio.dispatch.listen(i),console.debug("called: ",e);return}if(e&&r){if(typeof e!="string"||typeof r!="function"){console.error("Observer Error: name of state need to be a 'string' like 'state.test' and the callback need to be a 'function'");return}let i=globalThis.observer;i?.list?.[e]&&globalThis.memorio.dispatch.remove(e,r,o),i?.list?.[e]||globalThis.memorio.dispatch.listen(e,r,o);return}};globalThis.observer=F;Object.defineProperties(globalThis.observer,{list:{get:()=>globalThis.events},remove:{value:e=>{e&&(globalThis.memorio.dispatch.remove(e),delete globalThis.events[e])}},removeAll:{get:()=>{let e=globalThis.observer,r=e?.list;return r&&Object.keys(r).forEach(o=>{e?.remove?.(o)}),!0}}});Object.freeze(observer)});var w=l(()=>{"use strict";a();globalThis.useObserver||(globalThis.useObserver=null);Object.defineProperty(globalThis,"useObserver",{value:null,writable:!0,enumerable:!1,configurable:!0});globalThis.useObserver=((e,r)=>{if(!r||typeof e!="function")return()=>{};let o=[],i=Array.isArray(r)&&!r.__path?r:[r];try{return i.forEach(t=>{let s="";if(typeof t=="function"){let n=globalThis.memorio.propertyName;if(typeof n=="function"){let u=n(globalThis.state,t);u&&(s=u)}}else typeof t=="object"&&t!==null?s=t.__path||(typeof t.toString=="function"&&t.toString()!=="[object Object]"?t.toString():""):typeof t=="string"&&(t.startsWith("state.")||t.startsWith("store."))&&(s=t);if(s){s=s.replace(/^(\(\)\s*=>\s*)/,"").replace(/^globalThis\./,"").replace(/^state\./,"");let n=s.startsWith("store.")||s.startsWith("state.")?s:"state."+s;globalThis.memorio.dispatch.listen(n,()=>e()),o.push(n)}else{globalThis.memorio._trackedPaths?.clear(),globalThis.memorio._tracking=!0;try{e()}catch{}globalThis.memorio._tracking=!1,globalThis.memorio._trackedPaths?.forEach(n=>{o.includes(n)||(console.info(`useObserver: [Auto-Discovery] -> "${n}"`),globalThis.memorio.dispatch.listen(n,()=>e()),o.push(n))})}}),o.length>0?console.info(`useObserver: Monitoring ${o.length} paths.`):console.warn("useObserver: No paths resolved for monitoring. Check your dependencies!"),()=>{o.forEach(t=>{globalThis.memorio.dispatch&&typeof globalThis.memorio.dispatch.remove=="function"&&(globalThis.memorio.dispatch.remove(t),console.debug(`useObserver: Stopped monitoring "${t}"`))})}}catch(t){return console.debug("useObserver Error:",t),()=>{}}});Object.freeze(globalThis.useObserver)});var j=l(()=>{"use strict";a();Object.defineProperty(globalThis,"store",{value:new Proxy({},{}),enumerable:!1,configurable:!0});Object.defineProperties(store,{get:{value:e=>{if(e){try{let r=globalThis.localStorage.getItem(e);return r&&JSON.parse(r)}catch(r){console.debug(`Error parsing store item '${e}':`,r)}return null}}},set:{value:(e,r)=>{if(e){try{r==null?globalThis.localStorage.setItem(e,JSON.stringify(null)):typeof r=="object"||typeof r=="number"||typeof r=="boolean"||typeof r=="string"?globalThis.localStorage.setItem(e,JSON.stringify(r)):typeof r=="function"&&console.debug("It's not secure to store functions.")}catch(o){console.debug(`Error setting store item '${e}':`,o)}return null}}},remove:{value:e=>{if(e)return globalThis.localStorage.getItem(e)?(globalThis.localStorage.removeItem(e),!0):!1}},delete:{value:e=>(store.remove(e),!0)},removeAll:{value:()=>(globalThis.localStorage.clear(),!0)},clearAll:{value:()=>(store.removeAll(),!0)},quota:{value:async()=>globalThis.navigator&&"storage"in globalThis.navigator&&"estimate"in globalThis.navigator.storage?globalThis.navigator.storage.estimate().then(({usage:e,quota:r})=>{let o=e??0,i=r??0;return o&&i&&console.debug(`Using ${o/1024} out of ${i/1024} Mb.`),[o/1024,i/1024]}).catch(e=>(console.debug("Error estimating quota:",e),[0,0])):[0,0]},size:{value:()=>{let e=0;return Object.keys(globalThis.localStorage).forEach(r=>{let o=globalThis.localStorage.getItem(r);o&&(e+=o.length)}),e}}});Object.freeze(store)});var x=l(()=>{"use strict";a();Object.defineProperty(globalThis,"session",{value:new Proxy({},{}),enumerable:!1,configurable:!0});Object.defineProperties(session,{get:{value:e=>{if(e)try{let r=globalThis.sessionStorage.getItem(e);return r&&JSON.parse(r)}catch(r){console.debug(`Error parsing session item '${e}':`,r)}}},set:{value:(e,r)=>{if(e)try{r==null?globalThis.sessionStorage.setItem(e,JSON.stringify(null)):typeof r=="object"||typeof r=="number"||typeof r=="boolean"||typeof r=="string"?globalThis.sessionStorage.setItem(e,JSON.stringify(r)):typeof r=="function"&&console.debug("It's not secure to session functions.")}catch(o){console.debug(`Error setting session item '${e}':`,o)}}},remove:{value:e=>{if(e&&globalThis.sessionStorage.getItem(e))return globalThis.sessionStorage.removeItem(e),!0}},delete:{value:e=>(session.remove(e),!0)},removeAll:{value:()=>(globalThis.sessionStorage.clear(),!0)},clearAll:{value:()=>(session.removeAll(),!0)},quota:{value:async()=>globalThis.navigator&&"storage"in globalThis.navigator&&"estimate"in globalThis.navigator.storage?globalThis.navigator.storage.estimate().then(({usage:e,quota:r})=>{let o=e??0,i=r??0;return o&&i&&console.debug(`Using ${o/1024} out of ${i/1024} Mb.`),[o/1024,i/1024]}).catch(e=>(console.debug("Error estimating quota:",e),[0,0])):[0,0]},size:{value:()=>{let e=0;return Object.keys(globalThis.sessionStorage).forEach(r=>{let o=globalThis.sessionStorage.getItem(r);o&&(e+=o.length)}),e}}});Object.freeze(session)});var d,E=l(()=>{"use strict";a();d={};Object.defineProperty(globalThis,"cache",{value:new Proxy({},{get(e,r){let o=r;return o==="get"?i=>d[i]:o==="set"?(i,t)=>{d[i]=t}:o==="remove"?i=>(delete d[i],!0):o==="removeAll"?()=>(Object.keys(d).forEach(i=>delete d[i]),!0):o==="clear"?()=>(Object.keys(d).forEach(i=>delete d[i]),!0):d[o]},set(e,r,o){return d[r]=o,!0},deleteProperty(e,r){return delete d[r],!0}}),enumerable:!1,configurable:!0});Object.freeze(cache)});var U={};var D=l(()=>{"use strict";a();idb.db.create=(e,r=1)=>new Promise((o,i)=>{if(!idb.db.support())return i(new Error("IndexedDB not supported"));let t=globalThis.indexedDB.open(e,r);t.onerror=()=>{console.debug(`IndexedDB error: ${t.error?.message}`),i(t.error)},t.onsuccess=()=>{console.debug(`Database ${e} connected successfully`),idb.db.list(),o(t.result)},t.onupgradeneeded=()=>{console.debug(`Database ${e} upgrade/creation initiated`)}})});var W={};var $=l(()=>{"use strict";a();idb.db.list=async()=>{if(!("indexedDB"in globalThis)||!indexedDB.databases)return[];try{let e=await indexedDB.databases();return globalThis.idbases=e||[],await idb.db.size(),globalThis.idbases}catch(e){return console.error("Error listing databases:",e),[]}};idb.db.list()});var Y={};var k=l(()=>{"use strict";a();idb.db.exist=e=>idbases?.some(r=>r.name===e)});var L={};var _=l(()=>{"use strict";a();idb.db.quota=()=>navigator.storage.estimate()});var K={};var I=l(()=>{"use strict";a();idb.db.delete=e=>new Promise((r,o)=>{console.debug(`Removing database ${e}...`);let i=()=>{let t=indexedDB.deleteDatabase(e);t.onsuccess=()=>{console.debug(`${e} database removed successfully`),idb.db.list(),r()},t.onerror=()=>{console.error(`Error removing ${e}:`,t.error),o(t.error)},t.onblocked=()=>{console.warn(`Deletion of ${e} is blocked. Please close other tabs.`)}};confirm(`Are you sure you want to remove the "${e}" database?`)?i():(console.debug("Database deletion cancelled by user."),r())})});var G={};var q=l(()=>{"use strict";a();idb.db.size=async()=>{if(!(!idbases||idbases.length===0))for(let e=0;e<idbases.length;e++){let r=idbases[e];try{let o=await idb.db.create(r.name,r.version),i=Array.from(o.objectStoreNames),t=0;for(let s of i){let n=await idb.table.size(o,s);t+=n}r.size=t,o.close()}catch(o){console.debug(`Could not calculate size for ${r.name}:`,o)}}}});var H={};var z=l(()=>{"use strict";a();idb.db.version=e=>{let r=0;for(let o of idbases){o.name===e&&(r=o.version);break}return r}});var Q={};var A=l(()=>{"use strict";a();idb.db.support=()=>{let e="indexedDB"in globalThis;return e||console.debug("Your environment doesn't support IndexedDB"),e}});var X={};var B=l(()=>{"use strict";a();idb.table.create=(e,r)=>new Promise(async(o,i)=>{try{let s=(Number(idb.db.version(e))||0)+1,n=indexedDB.open(e,s);n.onupgradeneeded=u=>{let b=u.target.result;if(!b.objectStoreNames.contains(r)){let c=b.createObjectStore(r,{keyPath:"id",autoIncrement:!0});c.createIndex("id","id",{unique:!0}),c.createIndex("data","data",{unique:!1}),console.debug(`Table ${r} created in ${e}`)}},n.onsuccess=()=>{n.result.close(),idb.db.list(),o()},n.onerror=()=>{console.error(`Error creating table ${r}:`,n.error),i(n.error)}}catch(t){console.error("Critical error in table.create:",t),i(t)}})});var Z={};var R=l(()=>{"use strict";a();idb.table.size=(e,r)=>new Promise((o,i)=>{if(!e)return i(new Error("Database instance is required"));if(!e.objectStoreNames.contains(r))return o(0);let t=0,s=0,b=e.transaction([r],"readonly").objectStore(r).openCursor();b.onsuccess=async c=>{let g=c.target.result;if(g){try{let f=g.value;t+=JSON.stringify(f).length}catch(f){console.debug("Error stringifying IDB value tracking size:",f)}s++,s%200===0&&await new Promise(f=>setTimeout(f,0)),g.continue()}else o(t)},b.onerror=()=>{i(b.error)}})});var ee={};var N=l(()=>{"use strict";a();idb.data.delete=(e,r,o)=>new Promise((i,t)=>{let s=indexedDB.open(e);s.onsuccess=()=>{let n=s.result;if(!n.objectStoreNames.contains(r))return n.close(),t(new Error(`Table ${r} not found`));let c=n.transaction(r,"readwrite").objectStore(r).delete(o);c.onsuccess=()=>{n.close(),console.debug(`Record ${o} deleted from ${r}`),i()},c.onerror=()=>{n.close(),t(c.error)}},s.onerror=()=>t(s.error)});idb.data.delete.all=(e,r)=>new Promise((o,i)=>{let t=indexedDB.open(e);t.onsuccess=s=>{let n=s.target.result;if(!n.objectStoreNames.contains(r))return n.close(),i(new Error(`Table ${r} not found`));let c=n.transaction(r,"readwrite").objectStore(r).clear();c.onsuccess=()=>{n.close(),console.debug(`All data cleared from ${r}`),o()},c.onerror=()=>{n.close(),i(c.error)}},t.onerror=()=>i(t.error)})});var re={};var C=l(()=>{"use strict";a();idb.data.set=(e,r,o)=>new Promise((i,t)=>{let s=indexedDB.open(e);s.onsuccess=()=>{let n=s.result;if(!n.objectStoreNames.contains(r))return n.close(),t(new Error(`Table ${r} does not exist in ${e}`));let c=n.transaction(r,"readwrite").objectStore(r).put(o);c.onsuccess=()=>{n.close(),console.debug(`Data saved in ${e}.${r}`),i(c.result)},c.onerror=g=>{n.close(),console.debug(`Database insert error: ${c.error?.message}`),t(c.error)}},s.onerror=()=>{t(s.error)}})});var te={};var J=l(()=>{"use strict";a();idb.data.get=(e,r,o)=>new Promise((i,t)=>{let s=indexedDB.open(e);s.onsuccess=n=>{let u=n.target.result;if(!u.objectStoreNames.contains(r))return u.close(),t(new Error(`Table ${r} not found in ${e}`));let g=u.transaction(r,"readonly").objectStore(r).get(o);g.onsuccess=()=>{u.close(),i(g.result)},g.onerror=()=>{u.close(),t(g.error)}},s.onerror=()=>{t(s.error)}})});var V=l(()=>{"use strict";a();(async()=>(Object.defineProperty(globalThis,"idb",{value:{db:{},table:{},data:{}},writable:!0,configurable:!0,enumerable:!1}),Object.defineProperty(globalThis,"idbases",{value:[],writable:!0,configurable:!0,enumerable:!1}),await Promise.all([Promise.resolve().then(()=>(D(),U)),Promise.resolve().then(()=>($(),W)),Promise.resolve().then(()=>(k(),Y)),Promise.resolve().then(()=>(_(),L)),Promise.resolve().then(()=>(I(),K)),Promise.resolve().then(()=>(q(),G)),Promise.resolve().then(()=>(z(),H)),Promise.resolve().then(()=>(A(),Q)),Promise.resolve().then(()=>(B(),X)),Promise.resolve().then(()=>(R(),Z)),Promise.resolve().then(()=>(N(),ee)),Promise.resolve().then(()=>(C(),re)),Promise.resolve().then(()=>(J(),te))]),Object.preventExtensions(idb),Object.seal(idb),Object.freeze(idb)))()});var a=l(()=>{m();v();T();O();S();w();j();x();E();V()});a(); | ||
| var __getOwnPropNames=Object.getOwnPropertyNames;var __esm=(fn,res)=>function __init(){return fn&&(res=(0, fn[__getOwnPropNames(fn)[0]])(fn=0)),res};var db_create_exports={};var init_db_create=__esm({"functions/idb/tools/db.create.ts"(){idb.db.create=(dbName,ver=1)=>{return new Promise((resolve,reject)=>{if(!idb.db.support()){return reject(new Error("IndexedDB not supported"))}const request=globalThis.indexedDB.open(dbName,ver);request.onerror=()=>{console.debug(`IndexedDB error: ${request.error?.message}`);reject(request.error);};request.onsuccess=()=>{console.debug(`Database ${dbName} connected successfully`);idb.db.list();resolve(request.result);};request.onupgradeneeded=()=>{console.debug(`Database ${dbName} upgrade/creation initiated`);};})};}});var db_list_exports={};var init_db_list=__esm({"functions/idb/tools/db.list.ts"(){idb.db.list=async()=>{if(!("indexedDB"in globalThis)||!indexedDB.databases)return [];try{const result=await indexedDB.databases();globalThis.idbases=result||[];await idb.db.size();return globalThis.idbases}catch(err){console.error("Error listing databases:",err);return []}};idb.db.list();}});var db_exist_exports={};var init_db_exist=__esm({"functions/idb/tools/db.exist.ts"(){idb.db.exist=storeName=>{return idbases?.some(db=>db.name===storeName)};}});var db_quota_exports={};var init_db_quota=__esm({"functions/idb/tools/db.quota.ts"(){idb.db.quota=()=>{return navigator.storage.estimate()};}});var db_delete_exports={};var init_db_delete=__esm({"functions/idb/tools/db.delete.ts"(){idb.db.delete=storeName=>{return new Promise((resolve,reject)=>{console.debug(`Removing database ${storeName}...`);const performDelete=()=>{const request=indexedDB.deleteDatabase(storeName);request.onsuccess=()=>{console.debug(`${storeName} database removed successfully`);idb.db.list();resolve();};request.onerror=()=>{console.error(`Error removing ${storeName}:`,request.error);reject(request.error);};request.onblocked=()=>{console.warn(`Deletion of ${storeName} is blocked. Please close other tabs.`);};};if(confirm(`Are you sure you want to remove the "${storeName}" database?`)){performDelete();}else {console.debug("Database deletion cancelled by user.");resolve();}})};}});var db_size_exports={};var init_db_size=__esm({"functions/idb/tools/db.size.ts"(){idb.db.size=async()=>{if(!idbases||idbases.length===0)return;for(let i=0;i<idbases.length;i++){const dbInfo=idbases[i];try{const db=await idb.db.create(dbInfo.name,dbInfo.version);const tableNames=Array.from(db.objectStoreNames);let totalDbSize=0;for(const tableName of tableNames){const tableSize=await idb.table.size(db,tableName);totalDbSize+=tableSize;}dbInfo.size=totalDbSize;db.close();}catch(err){console.debug(`Could not calculate size for ${dbInfo.name}:`,err);}}};}});var db_version_exports={};var init_db_version=__esm({"functions/idb/tools/db.version.ts"(){idb.db.version=storeName=>{let idbVer=0;for(const v of idbases){if(v.name===storeName)idbVer=v.version;break}return idbVer};}});var db_support_exports={};var init_db_support=__esm({"functions/idb/tools/db.support.ts"(){idb.db.support=()=>{const isSupported="indexedDB"in globalThis;if(!isSupported){console.debug("Your environment doesn't support IndexedDB");}return isSupported};}});var table_create_exports={};var init_table_create=__esm({"functions/idb/tools/table.create.ts"(){idb.table.create=(dbName,dbTable)=>{return new Promise(async(resolve,reject)=>{try{const currentVersion=Number(idb.db.version(dbName))||0;const nextVersion=currentVersion+1;const request=indexedDB.open(dbName,nextVersion);request.onupgradeneeded=e=>{const db=e.target.result;if(!db.objectStoreNames.contains(dbTable)){const store2=db.createObjectStore(dbTable,{keyPath:"id",autoIncrement:true});store2.createIndex("id","id",{unique:true});store2.createIndex("data","data",{unique:false});console.debug(`Table ${dbTable} created in ${dbName}`);}};request.onsuccess=()=>{request.result.close();idb.db.list();resolve();};request.onerror=()=>{console.error(`Error creating table ${dbTable}:`,request.error);reject(request.error);};}catch(err){console.error("Critical error in table.create:",err);reject(err);}})};}});var table_size_exports={};var init_table_size=__esm({"functions/idb/tools/table.size.ts"(){idb.table.size=(db,table)=>{return new Promise((resolve,reject)=>{if(!db)return reject(new Error("Database instance is required"));if(!db.objectStoreNames.contains(table))return resolve(0);let size=0;let count=0;const transaction=db.transaction([table],"readonly");const store2=transaction.objectStore(table);const request=store2.openCursor();request.onsuccess=async event=>{const cursor=event.target.result;if(cursor){try{const value=cursor.value;size+=JSON.stringify(value).length;}catch(e){console.debug("Error stringifying IDB value tracking size:",e);}count++;if(count%200===0){await new Promise(resolve2=>setTimeout(resolve2,0));}cursor.continue();}else {resolve(size);}};request.onerror=()=>{reject(request.error);};})};}});var data_delete_exports={};var init_data_delete=__esm({"functions/idb/crud/data.delete.ts"(){idb.data.delete=(storeName,table,key)=>{return new Promise((resolve,reject)=>{const request=indexedDB.open(storeName);request.onsuccess=()=>{const db=request.result;if(!db.objectStoreNames.contains(table)){db.close();return reject(new Error(`Table ${table} not found`))}const transaction=db.transaction(table,"readwrite");const objectStore=transaction.objectStore(table);const deleteRequest=objectStore.delete(key);deleteRequest.onsuccess=()=>{db.close();console.debug(`Record ${key} deleted from ${table}`);resolve();};deleteRequest.onerror=()=>{db.close();reject(deleteRequest.error);};};request.onerror=()=>reject(request.error);})};idb.data.delete.all=(storeName,table)=>{return new Promise((resolve,reject)=>{const request=indexedDB.open(storeName);request.onsuccess=event=>{const db=event.target.result;if(!db.objectStoreNames.contains(table)){db.close();return reject(new Error(`Table ${table} not found`))}const transaction=db.transaction(table,"readwrite");const store2=transaction.objectStore(table);const clearRequest=store2.clear();clearRequest.onsuccess=()=>{db.close();console.debug(`All data cleared from ${table}`);resolve();};clearRequest.onerror=()=>{db.close();reject(clearRequest.error);};};request.onerror=()=>reject(request.error);})};}});var data_set_exports={};var init_data_set=__esm({"functions/idb/crud/data.set.ts"(){idb.data.set=(storeName,table,value)=>{return new Promise((resolve,reject)=>{const request=indexedDB.open(storeName);request.onsuccess=()=>{const db=request.result;if(!db.objectStoreNames.contains(table)){db.close();return reject(new Error(`Table ${table} does not exist in ${storeName}`))}const transaction=db.transaction(table,"readwrite");const objectStore=transaction.objectStore(table);const putRequest=objectStore.put(value);putRequest.onsuccess=()=>{db.close();console.debug(`Data saved in ${storeName}.${table}`);resolve(putRequest.result);};putRequest.onerror=e=>{db.close();console.debug(`Database insert error: ${putRequest.error?.message}`);reject(putRequest.error);};};request.onerror=()=>{reject(request.error);};})};}});var data_get_exports={};var init_data_get=__esm({"functions/idb/crud/data.get.ts"(){idb.data.get=(storeName,table,key)=>{return new Promise((resolve,reject)=>{const request=indexedDB.open(storeName);request.onsuccess=event=>{const db=event.target.result;if(!db.objectStoreNames.contains(table)){db.close();return reject(new Error(`Table ${table} not found in ${storeName}`))}const transaction=db.transaction(table,"readonly");const store2=transaction.objectStore(table);const getRequest=store2.get(key);getRequest.onsuccess=()=>{db.close();resolve(getRequest.result);};getRequest.onerror=()=>{db.close();reject(getRequest.error);};};request.onerror=()=>{reject(request.error);};})};}});var package_default={version:"2.6.0"};Object.defineProperty(globalThis,"memorio",{value:{},writable:false,configurable:true,enumerable:false});Object.defineProperty(globalThis,"events",{value:{},writable:true,enumerable:false});Object.defineProperty(memorio,"version",{writable:false,enumerable:false,value:package_default.version});var protect=["list","state","store","idb","observer","useObserver","remove","removeAll"];Object.defineProperty(memorio,"dispatch",{writable:false,enumerable:false,value:{set:(name,value={})=>{globalThis.dispatchEvent(new CustomEvent(String(name),value));},listen:(name,cb=null,flag=false)=>{if(globalThis.observer?.list?.[name]?.length>0)globalThis.observer?.remove?.(name);const exec=cb?e=>setTimeout(()=>cb(e),1):void 0;if(exec)globalThis.addEventListener(name,exec);if(exec)globalThis.events[name]=exec;},remove:name=>{const listener=globalThis.events?.[name];if(listener){globalThis.removeEventListener(name,listener);delete globalThis.events[name];}}}});memorio.propertyName=(container,object)=>{const t=String(object).replace("() => ","");return t};Object.defineProperty(memorio,"objPath",{writable:false,enumerable:false,value:(prop,object,separator=".")=>{const path=object.concat(prop).join(separator);if(globalThis.memorio._tracking){globalThis.memorio._trackedPaths?.add("state."+path);}return path}});globalThis.memorio._tracking=false;globalThis.memorio._trackedPaths=new Set;globalThis.memorio._locked=false;var buildProxy=(obj,callback,tree=[])=>{const event=name=>{try{globalThis.memorio?.dispatch?.set?.(name,{detail:{name}});}catch(e){}return};return new Proxy(obj,{get(target,prop){if(prop==="__path"){return tree.length>0?"state."+tree.join("."):"state"}if(prop==="list"){console.debug('Some state could be hidden when you use "state.list". Use "state" to see the complete list ');return JSON.parse(JSON.stringify(globalThis.state))}if(globalThis.memorio._tracking&&typeof prop==="string"){const path=tree.length>0?"state."+tree.concat(prop).join("."):"state."+prop;globalThis.memorio._trackedPaths?.add(path);}if(prop==="remove"){return key=>{delete target[key];return true}}if(prop==="removeAll"){return ()=>{try{for(const key in target){if(typeof target[key]!=="function"&&!["list","remove","removeAll"].includes(key)){if(!Object.isFrozen(target[key]))delete target[key];delete target[key];}}}catch(error){console.debug(error);}return}}if(Object.isFrozen(target[prop]))return target[prop];if(prop==="lock"||prop==="unlock"){const value=Reflect.get(target,prop);if(value)return value}try{const value=Reflect.get(target,prop);if(value&&typeof value==="object"&&["Array","Object"].includes(value.constructor.name)){return buildProxy(value,callback,tree.concat(prop))}return value}catch(error){console.error("Error: ",error);return void 0}},set(target,key,value){if(globalThis.memorio._locked){console.error("Error: state is locked. Use state.unlock() to enable modifications.");return false}if(protect.includes(key)){console.error("key "+key+" is protected");return false}if(target[key]&&typeof target[key]==="object"&&Object.isFrozen(target[key])){console.error(`Error: state '${key}' is locked`);return false}if(target[key]&&typeof target[key]==="object"&&target[key].__locked){console.error(`Error: state '${key}' is locked. Use state.${key}.unlock() to enable modifications.`);return false}try{const path=globalThis.memorio.objPath?.(key,tree)??key;callback({action:"set",path,target,newValue:value,previousValue:Reflect.get(target,key)});event("state."+path);Reflect.set(target,key,value);if(target[key]&&typeof target[key]==="object"){const rawValue=target[key];if(rawValue&&typeof rawValue==="object"){try{Object.defineProperty(rawValue,"__locked",{writable:true,enumerable:false,configurable:false,value:false});Object.defineProperty(rawValue,"lock",{writable:false,enumerable:false,configurable:false,value:()=>{Object.defineProperty(rawValue,"__locked",{writable:true,enumerable:false,configurable:false,value:true});console.info(`State '${key}' is now locked.`);}});Object.defineProperty(rawValue,"unlock",{writable:false,enumerable:false,configurable:false,value:()=>{Object.defineProperty(rawValue,"__locked",{writable:true,enumerable:false,configurable:false,value:false});console.info(`State '${key}' is now unlocked.`);}});}catch(defineError){}}}return true}catch(error){console.error("Error in set trap:",error);return false}},deleteProperty(target,prop){try{const path=globalThis.memorio.objPath?.(prop,tree);callback({action:"delete",path,target});return Reflect.deleteProperty(target,prop)}catch(error){console.error("Error in deleteProperty trap:",error);return false}},ownKeys(target){return Reflect.ownKeys(target)},getOwnPropertyDescriptor(target,prop){return Reflect.getOwnPropertyDescriptor(target,prop)}})};!globalThis?.state?globalThis.state=buildProxy({},()=>{}):globalThis.state=state;globalThis.state.lock=()=>{globalThis.memorio._locked=true;console.info("State is now locked. All modifications are blocked.");};globalThis.state.unlock=()=>{globalThis.memorio._locked=false;console.info("State is now unlocked. Modifications are allowed.");};Object.defineProperty(globalThis,"state",{enumerable:false,configurable:true});if(!globalThis.observer){globalThis.observer=null;}Object.defineProperty(globalThis,"observer",{enumerable:false,configurable:true});var observerFunction=(s,cb=null,option=true)=>{console.warn('DEPRECATED: "observer" is deprecated and will be removed in future versions. Please use "useObserver" instead.');try{const checkStateOrStore=s2=>{const t=s2.split(".");if(t[0]!=="state"){console.error(`Observer Error: You need to declare 'state.' or 'store.'. The '${s2}' string is incorrect!`);return false}return true};if(!checkStateOrStore(s))return}catch(error){console.error(error);return}if(!s&&!cb){console.error("Observer Error: You need to setup observer correctly, Some parameters are missed!");return}if(!s&&cb){console.error(`Observer Error: You need to declare what state need to be monitored as string like 'state.test'.`);return}if(s&&!cb){const f=({detail:{name:String(s)}});const obs=globalThis.observer;if(obs?.list?.[s])globalThis.memorio.dispatch.remove(f);if(!obs?.list?.[s])globalThis.memorio.dispatch.listen(f);console.debug("called: ",s);return}if(s&&cb){if(typeof s!=="string"||typeof cb!=="function"){console.error(`Observer Error: name of state need to be a 'string' like 'state.test' and the callback need to be a 'function'`);return}const obs=globalThis.observer;if(obs?.list?.[s])globalThis.memorio.dispatch.remove(s,cb,option);if(!obs?.list?.[s])globalThis.memorio.dispatch.listen(s,cb,option);return}};globalThis.observer=observerFunction;Object.defineProperties(globalThis.observer,{list:{get:()=>globalThis.events},remove:{value:name=>{if(!name)return;globalThis.memorio.dispatch.remove(name);delete globalThis.events[name];return}},removeAll:{get:()=>{const obs=globalThis.observer;const list=obs?.list;if(list){Object.keys(list).forEach(key=>{obs?.remove?.(key);});}return true}}});Object.freeze(observer);if(!globalThis.useObserver)globalThis.useObserver=null;Object.defineProperty(globalThis,"useObserver",{value:null,writable:true,enumerable:false,configurable:true});globalThis.useObserver=((func,deps)=>{if(!deps||typeof func!=="function"){return ()=>{}}const handlers=[];const depList=Array.isArray(deps)&&!deps.__path?deps:[deps];try{depList.forEach(dep=>{let t="";if(typeof dep==="function"){const propName=globalThis.memorio.propertyName;if(typeof propName==="function"){const result=propName(globalThis.state,dep);if(result)t=result;}}else if(typeof dep==="object"&&dep!==null){t=dep.__path||(typeof dep.toString==="function"&&dep.toString()!=="[object Object]"?dep.toString():"");}else if(typeof dep==="string"&&(dep.startsWith("state.")||dep.startsWith("store."))){t=dep;}if(t){t=t.replace(/^(\(\)\s*=>\s*)/,"").replace(/^globalThis\./,"").replace(/^state\./,"");const path=t.startsWith("store.")||t.startsWith("state.")?t:"state."+t;globalThis.memorio.dispatch.listen(path,()=>func());handlers.push(path);}else {globalThis.memorio._trackedPaths?.clear();globalThis.memorio._tracking=true;try{func();}catch(e){}globalThis.memorio._tracking=false;globalThis.memorio._trackedPaths?.forEach(path=>{if(!handlers.includes(path)){console.info(`useObserver: [Auto-Discovery] -> "${path}"`);globalThis.memorio.dispatch.listen(path,()=>func());handlers.push(path);}});}});if(handlers.length>0){console.info(`useObserver: Monitoring ${handlers.length} paths.`);}else {console.warn(`useObserver: No paths resolved for monitoring. Check your dependencies!`);}return ()=>{handlers.forEach(path=>{if(globalThis.memorio.dispatch&&typeof globalThis.memorio.dispatch.remove==="function"){globalThis.memorio.dispatch.remove(path);console.debug(`useObserver: Stopped monitoring "${path}"`);}});}}catch(err){console.debug("useObserver Error:",err);return ()=>{}}});Object.freeze(globalThis.useObserver);Object.defineProperty(globalThis,"store",{value:new Proxy({},{}),enumerable:false,configurable:true});Object.defineProperties(store,{get:{value:name=>{if(!name)return;try{const item=globalThis.localStorage.getItem(name);if(item)return JSON.parse(item);return item}catch(err){console.debug(`Error parsing store item '${name}':`,err);}return null}},set:{value:(name,value)=>{if(!name)return;try{if(value===null||value===void 0)globalThis.localStorage.setItem(name,JSON.stringify(null));else if(typeof value==="object"||typeof value==="number"||typeof value==="boolean"||typeof value==="string")globalThis.localStorage.setItem(name,JSON.stringify(value));else if(typeof value==="function")console.debug("It's not secure to store functions.");}catch(err){console.debug(`Error setting store item '${name}':`,err);}return null}},remove:{value:name=>{if(!name)return;if(globalThis.localStorage.getItem(name)){globalThis.localStorage.removeItem(name);return true}return false}},delete:{value:name=>{store.remove(name);return true}},removeAll:{value:()=>{globalThis.localStorage.clear();return true}},clearAll:{value:()=>{store.removeAll();return true}},quota:{value:async()=>{if(globalThis.navigator&&"storage"in globalThis.navigator&&"estimate"in globalThis.navigator.storage){return globalThis.navigator.storage.estimate().then(({usage,quota})=>{const u=usage??0;const q=quota??0;if(u&&q)console.debug(`Using ${u/1024} out of ${q/1024} Mb.`);return [u/1024,q/1024]}).catch(err=>{console.debug("Error estimating quota:",err);return [0,0]})}return [0,0]}},size:{value:()=>{let totalSize=0;Object.keys(globalThis.localStorage).forEach(key=>{const item=globalThis.localStorage.getItem(key);if(item)totalSize+=item.length;});return totalSize}}});Object.freeze(store);Object.defineProperty(globalThis,"session",{value:new Proxy({},{}),enumerable:false,configurable:true});Object.defineProperties(session,{get:{value:name=>{if(!name)return;try{const item=globalThis.sessionStorage.getItem(name);if(item)return JSON.parse(item);return item}catch(err){console.debug(`Error parsing session item '${name}':`,err);}return}},set:{value:(name,value)=>{if(!name)return;try{if(value===null||value===void 0)globalThis.sessionStorage.setItem(name,JSON.stringify(null));else if(typeof value==="object"||typeof value==="number"||typeof value==="boolean"||typeof value==="string")globalThis.sessionStorage.setItem(name,JSON.stringify(value));else if(typeof value==="function")console.debug("It's not secure to session functions.");}catch(err){console.debug(`Error setting session item '${name}':`,err);}return}},remove:{value:name=>{if(!name)return;if(globalThis.sessionStorage.getItem(name)){globalThis.sessionStorage.removeItem(name);return true}return}},delete:{value:name=>{session.remove(name);return true}},removeAll:{value:()=>{globalThis.sessionStorage.clear();return true}},clearAll:{value:()=>{session.removeAll();return true}},quota:{value:async()=>{if(globalThis.navigator&&"storage"in globalThis.navigator&&"estimate"in globalThis.navigator.storage){return globalThis.navigator.storage.estimate().then(({usage,quota})=>{const u=usage??0;const q=quota??0;if(u&&q)console.debug(`Using ${u/1024} out of ${q/1024} Mb.`);return [u/1024,q/1024]}).catch(err=>{console.debug("Error estimating quota:",err);return [0,0]})}return [0,0]}},size:{value:()=>{let totalSize=0;Object.keys(globalThis.sessionStorage).forEach(key=>{const item=globalThis.sessionStorage.getItem(key);if(item)totalSize+=item.length;});return totalSize}}});Object.freeze(session);var cacheData={};Object.defineProperty(globalThis,"cache",{value:new Proxy({},{get(target,prop){const key=prop;if(key==="get")return name=>cacheData[name];if(key==="set")return (name,value)=>{cacheData[name]=value;};if(key==="remove")return name=>{delete cacheData[name];return true};if(key==="removeAll")return ()=>{Object.keys(cacheData).forEach(k=>delete cacheData[k]);return true};if(key==="clear")return ()=>{Object.keys(cacheData).forEach(k=>delete cacheData[k]);return true};return cacheData[key]},set(target,prop,value){cacheData[prop]=value;return true},deleteProperty(target,prop){delete cacheData[prop];return true}}),enumerable:false,configurable:true});Object.freeze(cache);(async()=>{Object.defineProperty(globalThis,"idb",{value:{db:{},table:{},data:{}},writable:true,configurable:true,enumerable:false});Object.defineProperty(globalThis,"idbases",{value:[],writable:true,configurable:true,enumerable:false});await Promise.all([Promise.resolve().then(()=>(init_db_create(),db_create_exports)),Promise.resolve().then(()=>(init_db_list(),db_list_exports)),Promise.resolve().then(()=>(init_db_exist(),db_exist_exports)),Promise.resolve().then(()=>(init_db_quota(),db_quota_exports)),Promise.resolve().then(()=>(init_db_delete(),db_delete_exports)),Promise.resolve().then(()=>(init_db_size(),db_size_exports)),Promise.resolve().then(()=>(init_db_version(),db_version_exports)),Promise.resolve().then(()=>(init_db_support(),db_support_exports)),Promise.resolve().then(()=>(init_table_create(),table_create_exports)),Promise.resolve().then(()=>(init_table_size(),table_size_exports)),Promise.resolve().then(()=>(init_data_delete(),data_delete_exports)),Promise.resolve().then(()=>(init_data_set(),data_set_exports)),Promise.resolve().then(()=>(init_data_get(),data_get_exports))]);Object.preventExtensions(idb);Object.seal(idb);Object.freeze(idb);})(); |
+51
-49
| { | ||
| "name": "memorio", | ||
| "version": "2.5.3", | ||
| "type": "module", | ||
| "private": false, | ||
| "main": "index.js", | ||
| "version": "2.6.0", | ||
| "description": "Memorio, State + Observer, Store and iDB for an easy life", | ||
| "main": "./index.cjs", | ||
| "browser": "./index.cjs", | ||
| "types": "./index.d.ts", | ||
| "typing": "./types/*", | ||
| "homepage": "https://a51.gitbook.io/memorio", | ||
| "license": "MIT", | ||
| "typings": "./types/*", | ||
| "description": "Memorio, State + Observer and Store for an easy life", | ||
| "copyright": "Copyright (c) 2025 Dario Passariello", | ||
| "homepage": "https://a51.gitbook.io/memorio", | ||
| "author": { | ||
| "name": "Dario Passariello", | ||
| "url": "https://dario.passariello.ca/", | ||
| "email": "dariopassariello@gmail.com" | ||
| }, | ||
| "support": { | ||
| "name": "Dario Passariello", | ||
| "url": "https://github.com/passariello/", | ||
| "email": "dariopassariello@gmail.com" | ||
| }, | ||
| "copyright": "Dario Passariello", | ||
| "author": "Dario Passariello", | ||
| "contributors": [ | ||
@@ -33,11 +24,11 @@ { | ||
| "keywords": [ | ||
| "biglogic", | ||
| "a51", | ||
| "memorio", | ||
| "state", | ||
| "store", | ||
| "observer", | ||
| "useObserver", | ||
| "dario", | ||
| "passariello" | ||
| "elements", | ||
| "ui", | ||
| "ux", | ||
| "inputs", | ||
| "buttons", | ||
| "frontend", | ||
| "gui", | ||
| "styles", | ||
| "customization" | ||
| ], | ||
@@ -50,30 +41,41 @@ "funding": [ | ||
| ], | ||
| "typing": [ | ||
| "types/*" | ||
| "engines": { | ||
| "node": ">=18.0.0" | ||
| }, | ||
| "files": [ | ||
| "**/*" | ||
| ], | ||
| "repository": { | ||
| "type": "git", | ||
| "url": "git+https://github.com/a51-dev/a51.memorio.git" | ||
| }, | ||
| "bugs": { | ||
| "url": "https://github.com/a51-dev/a51.memorio/issues" | ||
| }, | ||
| "support": { | ||
| "name": "Dario Passariello", | ||
| "url": "https://dario.passariello.ca/", | ||
| "email": "dariopassariello@gmail.com" | ||
| }, | ||
| "peerDependenciesMeta": { | ||
| "react": { | ||
| "optional": false | ||
| }, | ||
| "react-dom": { | ||
| "optional": false | ||
| }, | ||
| "jquery": { | ||
| "optional": false | ||
| } | ||
| }, | ||
| "module": "./index.js", | ||
| "exports": { | ||
| ".": { | ||
| "types": "./types/index.d.ts", | ||
| "import": "./index.js", | ||
| "default": "./index.js" | ||
| "require": "./index.cjs", | ||
| "types": "./index.d.ts" | ||
| }, | ||
| "./types/*": "./types/*" | ||
| }, | ||
| "scripts": { | ||
| "build": "rimraf dist && node ./esbuild.config.mjs", | ||
| "watch": "rimraf dist && nodemon --watch * --exec \"npm run build \"", | ||
| "npm:publish": "npm run build && npm publish ./dist", | ||
| "test": "cd tests && npm run test", | ||
| "lint": "cd tests && npm run lint", | ||
| "tsc": "tsc --noEmit" | ||
| }, | ||
| "devDependencies": { | ||
| "@types/node": "25.3.3", | ||
| "esbuild": "0.27.3", | ||
| "esbuild-node-externals": "1.20.1", | ||
| "esbuild-plugin-alias": "0.2.1", | ||
| "esbuild-plugin-copy": "2.1.1", | ||
| "rimraf": "6.1.3", | ||
| "typescript": "5.9.3" | ||
| } | ||
| } | ||
| "typings": "./index.d.ts" | ||
| } |
+14
-5
@@ -6,14 +6,23 @@ # [memorio](https://npmjs.com/package/memorio) | ||
| [](https://npmjs.org/package/memorio) | ||
| [](https://packagephobia.now.sh/result?p=memorio) | ||
| [](https://npmjs.org/package/memorio) | ||
|  | ||
| [](https://snyk.io/test/npm/memorio) | ||
| [](https://socket.dev/npm/package/memorio) | ||
|  | ||
|  | ||
|  | ||
|  | ||
|  | ||
|  | ||
|  | ||
|  | ||
|  | ||
|  | ||
|  | ||
|  | ||
| License is MIT - free to use, modify, and distribute | ||
| [](https://a51.gitbook.io/memorio) | ||
| --- | ||
| ## Table of Contents | ||
@@ -20,0 +29,0 @@ |
@@ -64,2 +64,10 @@ | ||
| interface Window { | ||
| [key: string]: any | ||
| } | ||
| interface globalThis { | ||
| [key: string]: any | ||
| } | ||
| export { } |
| # Cache - Memorio | ||
| Cache provides in-memory storage with a simple API. Data is lost on page refresh. | ||
| ## Installation | ||
| ```bash | ||
| npm install memorio | ||
| ``` | ||
| ```javascript | ||
| import 'memorio'; | ||
| ``` | ||
| --- | ||
| ## Quick Examples | ||
| ### Example 1: Basic Usage | ||
| ```javascript | ||
| // Save data | ||
| cache.set('username', 'Mario'); | ||
| cache.set('score', 1500); | ||
| // Read data | ||
| console.log(cache.get('username')); // "Mario" | ||
| console.log(cache.get('score')); // 1500 | ||
| ``` | ||
| ### Example 2: Intermediate | ||
| ```javascript | ||
| // Store objects | ||
| cache.set('user', { name: 'Luigi', level: 5 }); | ||
| const user = cache.get('user'); | ||
| console.log(user.name); // "Luigi" | ||
| // Remove single item | ||
| cache.remove('username'); | ||
| // Clear all cache | ||
| cache.removeAll(); | ||
| ``` | ||
| --- | ||
| ## API Reference | ||
| ### Methods | ||
| | Method | Parameters | Returns | Description | | ||
| |--------|------------|---------|-------------| | ||
| | `cache.get(name)` | `name: string` | `any` | Get value from cache | | ||
| | `cache.set(name, value)` | `name: string, value: any` | `void` | Save value to cache | | ||
| | `cache.remove(name)` | `name: string` | `boolean` | Remove single item | | ||
| | `cache.removeAll()` | `none` | `boolean` | Clear all cache | | ||
| --- | ||
| ## Storage Comparison | ||
| | Feature | Cache | Store | Session | IDB | | ||
| |---------|-------|-------|---------|-----| | ||
| | Storage | Memory | localStorage | sessionStorage | IndexedDB | | ||
| | Lifetime | Until refresh | Forever | Until tab closes | Forever | | ||
| | Capacity | Unlimited | ~5-10 MB | ~5-10 MB | 50+ MB | | ||
| | Use case | Temporary data | User preferences | Auth tokens | Large data | | ||
| --- | ||
| ## Best Practices | ||
| 1. Use for temporary data that doesn't need persistence | ||
| 2. Great for computed values or API response caching | ||
| 3. Data is lost on page refresh - don't use for important data | ||
| 4. Clear with `cache.removeAll()` when no longer needed |
-120
| # Memorio DevTools | ||
| Browser console debugging tools for inspecting and managing Memorio state. | ||
| ## Quick Start | ||
| ```javascript | ||
| // Load memorio first | ||
| import 'memorio' | ||
| ``` | ||
| ## Available Methods | ||
| ### inspect() | ||
| Inspect all Memorio modules in the console. | ||
| ```javascript | ||
| memorio.devtools.inspect() | ||
| ``` | ||
| ### stats() | ||
| Get statistics about all modules. | ||
| ```javascript | ||
| memorio.devtools.stats() | ||
| // Returns: { stateKeys, storeKeys, sessionKeys, cacheKeys, idbDatabases, lastUpdate } | ||
| ``` | ||
| ### clear(module) | ||
| Clear data from a specific module. | ||
| ```javascript | ||
| memorio.devtools.clear('state') | ||
| memorio.devtools.clear('store') | ||
| memorio.devtools.clear('session') | ||
| memorio.devtools.clear('cache') | ||
| ``` | ||
| ### clearAll() | ||
| Clear all Memorio data. | ||
| ```javascript | ||
| memorio.devtools.clearAll() | ||
| ``` | ||
| ### watch(module, path) | ||
| Watch a specific path for changes. | ||
| ```javascript | ||
| memorio.devtools.watch('state', 'user.name') | ||
| ``` | ||
| ### exportData() | ||
| Export all data as JSON. | ||
| ```javascript | ||
| const json = memorio.devtools.exportData() | ||
| console.log(json) | ||
| ``` | ||
| ### importData(jsonString) | ||
| Import data from JSON. | ||
| ```javascript | ||
| memorio.devtools.importData('{"state":{"key":"value"}}') | ||
| ``` | ||
| ### help() | ||
| Show help information. | ||
| ```javascript | ||
| memorio.devtools.help() | ||
| ``` | ||
| ## Console Shortcuts | ||
| Memorio provides global shortcuts for quick access: | ||
| ```javascript | ||
| $state // globalThis.state | ||
| $store // globalThis.store | ||
| $session // globalThis.session | ||
| $cache // globalThis.cache | ||
| ``` | ||
| ## Examples | ||
| ### Inspect current state | ||
| ```javascript | ||
| memorio.devtools.inspect() | ||
| ``` | ||
| ### Export and restore state | ||
| ```javascript | ||
| // Export | ||
| const backup = memorio.devtools.exportData() | ||
| // Later... import | ||
| memorio.devtools.importData(backup) | ||
| ``` | ||
| ### Monitor changes | ||
| ```javascript | ||
| // Watch a specific path | ||
| memorio.devtools.watch('state', 'counter') | ||
| // Now changes will be logged to console | ||
| state.counter = 42 // Console shows: 👁 Change: state.counter = 42 | ||
| ``` |
-156
| # IDB - Memorio | ||
| IDB provides access to browser IndexedDB for large data storage. Unlike localStorage, IDB can store large amounts of structured data. | ||
| ## Installation | ||
| ```bash | ||
| npm install memorio | ||
| ``` | ||
| ```javascript | ||
| import 'memorio'; | ||
| ``` | ||
| --- | ||
| ## Quick Examples | ||
| ### Example 1: Basic Usage | ||
| ```javascript | ||
| // Create a database | ||
| idb.db.create('myApp'); | ||
| // Add data | ||
| idb.data.set('myApp', 'users', { id: 1, name: 'Mario' }); | ||
| // Get data | ||
| const user = idb.data.get('myApp', 'users', 1); | ||
| console.log(user.name); // "Mario" | ||
| ``` | ||
| ### Example 2: Intermediate | ||
| ```javascript | ||
| // Create database with tables | ||
| idb.db.create('store'); | ||
| idb.table.create('store', 'products'); | ||
| // Add multiple records | ||
| idb.data.set('store', 'products', { id: 1, name: 'Apple', price: 1.5 }); | ||
| idb.data.set('store', 'products', { id: 2, name: 'Banana', price: 0.8 }); | ||
| // List databases | ||
| const databases = idb.db.list(); | ||
| console.log(databases); // ['myApp', 'store'] | ||
| ``` | ||
| ### Example 3: Advanced | ||
| ```javascript | ||
| // Check database support | ||
| if (idb.db.support()) { | ||
| // Use IDB | ||
| } | ||
| // Get database info | ||
| const version = idb.db.version('store'); | ||
| const size = idb.db.size('store'); | ||
| // Delete database | ||
| idb.db.delete('store'); | ||
| // Handle quota | ||
| const quota = idb.db.quota(); | ||
| console.log(`Using ${quota.used} of ${quota.total} bytes`); | ||
| ``` | ||
| --- | ||
| ## API Reference | ||
| ### Database Methods | ||
| | Method | Parameters | Returns | Description | | ||
| |--------|------------|---------|-------------| | ||
| | `idb.db.create(name)` | `name: string` | `void` | Create database | | ||
| | `idb.db.delete(name)` | `name: string` | `void` | Delete database | | ||
| | `idb.db.list()` | none | `string[]` | List all databases | | ||
| | `idb.db.exist(name)` | `name: string` | `boolean` | Check if exists | | ||
| | `idb.db.size(name)` | `name: string` | `number` | Get database size | | ||
| | `idb.db.version(name)` | `name: string` | `number` | Get version | | ||
| | `idb.db.support()` | none | `boolean` | Check browser support | | ||
| | `idb.db.quota()` | none | `object` | Get storage quota | | ||
| ### Table Methods | ||
| | Method | Parameters | Returns | Description | | ||
| |--------|------------|---------|-------------| | ||
| | `idb.table.create(db, table)` | `db: string, table: string` | `void` | Create table | | ||
| | `idb.table.size(db, table)` | `db: string, table: string` | `number` | Get table size | | ||
| ### Data Methods | ||
| | Method | Parameters | Returns | Description | | ||
| |--------|------------|---------|-------------| | ||
| | `idb.data.get(db, table, id)` | `db, table, id` | `any` | Get single record | | ||
| | `idb.data.set(db, table, data)` | `db, table, data` | `void` | Set record | | ||
| | `idb.data.delete(db, table, id)` | `db, table, id` | `void` | Delete record | | ||
| --- | ||
| ## Data Structure | ||
| Each record needs an `id` field: | ||
| ```javascript | ||
| idb.data.set('myDB', 'users', { | ||
| id: 1, // Required! | ||
| name: 'Mario', | ||
| email: 'm@test.com' | ||
| }); | ||
| ``` | ||
| --- | ||
| ## Storage Limits | ||
| - **Desktop browsers**: 50+ MB (often unlimited) | ||
| - **Mobile browsers**: 50-100 MB | ||
| - **More than localStorage**: Much higher limits | ||
| --- | ||
| ## Best Practices | ||
| 1. Always include `id` in records | ||
| 2. Use for large data: images, caches, offline data | ||
| 3. Check support: `idb.db.support()` | ||
| 4. Clean up: `idb.db.delete('tempDB')` | ||
| --- | ||
| ## Use Cases | ||
| ### Offline Data | ||
| ```javascript | ||
| // Cache API response | ||
| idb.data.set('cache', 'apiResponse', { | ||
| id: 'users', | ||
| data: usersArray, | ||
| timestamp: Date.now() | ||
| }); | ||
| ``` | ||
| ### Large User Data | ||
| ```javascript | ||
| // Store user-generated content | ||
| idb.data.set('app', 'uploads', { | ||
| id: Date.now(), | ||
| file: fileData, | ||
| userId: currentUser.id | ||
| }); | ||
| ``` |
-145
| # Memorio Logger | ||
| Automatic logging middleware for tracking all state changes in Memorio. | ||
| ## Overview | ||
| The logger automatically tracks all operations (set, delete, clear) across all modules: | ||
| - State | ||
| - Store | ||
| - Session | ||
| - Cache | ||
| ## Configuration | ||
| ### configure(options) | ||
| Configure the logger. | ||
| ```javascript | ||
| memorio.logger.configure({ | ||
| enabled: true, // Enable/disable logging | ||
| logToConsole: true, // Log to browser console | ||
| customHandler: function(entry) { ... }, // Custom handler | ||
| modules: ['state', 'store', 'session', 'cache'], // Modules to log | ||
| maxEntries: 1000 // Maximum log history size | ||
| }) | ||
| ``` | ||
| ### enable() | ||
| Enable logging. | ||
| ```javascript | ||
| memorio.logger.enable() | ||
| ``` | ||
| ### disable() | ||
| Disable logging. | ||
| ```javascript | ||
| memorio.logger.disable() | ||
| ``` | ||
| ## Methods | ||
| ### getHistory() | ||
| Get all log entries. | ||
| ```javascript | ||
| const history = memorio.logger.getHistory() | ||
| // Returns array of LogEntry objects | ||
| ``` | ||
| ### getStats() | ||
| Get statistics about logged operations. | ||
| ```javascript | ||
| const stats = memorio.logger.getStats() | ||
| // Returns: { total, state, store, session, cache, set, get, delete, clear } | ||
| ``` | ||
| ### clearHistory() | ||
| Clear log history. | ||
| ```javascript | ||
| memorio.logger.clearHistory() | ||
| ``` | ||
| ### exportLogs() | ||
| Export logs as JSON string. | ||
| ```javascript | ||
| const json = memorio.logger.exportLogs() | ||
| ``` | ||
| ## Log Entry Structure | ||
| ```javascript | ||
| { | ||
| timestamp: "2026-02-18T12:00:00.000Z", | ||
| module: "state", | ||
| action: "set", | ||
| path: "user.name", | ||
| value: "John", | ||
| previousValue: "Jane" | ||
| } | ||
| ``` | ||
| ## Examples | ||
| ### Basic usage | ||
| ```javascript | ||
| // Logging is enabled by default | ||
| state.user = { name: 'John' } | ||
| // Console: [Memorio:STATE] set user → value: { name: 'John' } | ||
| ``` | ||
| ### Get statistics | ||
| ```javascript | ||
| const stats = memorio.logger.getStats() | ||
| console.log(stats) | ||
| // { total: 15, state: 5, store: 3, session: 2, cache: 5, set: 10, get: 0, delete: 3, clear: 2 } | ||
| ``` | ||
| ### Disable specific modules | ||
| ```javascript | ||
| memorio.logger.configure({ | ||
| modules: ['state'] // Only log state changes | ||
| }) | ||
| ``` | ||
| ### Custom handler | ||
| ```javascript | ||
| memorio.logger.configure({ | ||
| customHandler: (entry) => { | ||
| // Send to analytics | ||
| analytics.track('memorio_change', entry) | ||
| } | ||
| }) | ||
| ``` | ||
| ### Export and analyze | ||
| ```javascript | ||
| // Get all logs | ||
| const logs = memorio.logger.getHistory() | ||
| // Filter by module | ||
| const stateLogs = logs.filter(l => l.module === 'state') | ||
| // Filter by action | ||
| const setOperations = logs.filter(l => l.action === 'set') | ||
| // Export for debugging | ||
| console.log(memorio.logger.exportLogs()) | ||
| ``` |
-180
| # Observer - Memorio | ||
| > ⚠️ **DEPRECATED**: This function is deprecated and will be removed in future versions. Please use [`useObserver`](USEOBSERVER.md) instead. | ||
| Observer lets you react to state changes. When a state key changes, your callback function runs. | ||
| ## Installation | ||
| ```bash | ||
| npm install memorio | ||
| ``` | ||
| ```javascript | ||
| import 'memorio'; | ||
| ``` | ||
| --- | ||
| ## Quick Examples | ||
| ### Example 1: Basic Usage | ||
| ```javascript | ||
| // Simple observer (DEPRECATED - use useObserver instead) | ||
| console.warn('observer() is deprecated. Please use useObserver() for React or memorio.dispatch for vanilla JS.'); | ||
| observer('state.counter', (newValue) => { | ||
| console.log('Counter is now:', newValue); | ||
| }); | ||
| state.counter = 1; | ||
| // Output: "Counter is now: 1" | ||
| state.counter = 5; | ||
| // Output: "Counter is now: 5" | ||
| ``` | ||
| > **Note**: For new projects, use [`useObserver`](USEOBSERVER.md) for React or [`memorio.dispatch`](SUMMARY.md) for vanilla JS. | ||
| ### Example 2: Intermediate | ||
| ```javascript | ||
| // Observer with old value | ||
| observer('state.user', (newValue, oldValue) => { | ||
| console.log(`User changed from ${oldValue?.name} to ${newValue?.name}`); | ||
| }); | ||
| state.user = { name: 'Mario' }; | ||
| // Output: "User changed from undefined to Mario" | ||
| state.user = { name: 'Luigi' }; | ||
| // Output: "User changed from Mario to Luigi" | ||
| ``` | ||
| ### Example 3: Advanced | ||
| ```javascript | ||
| // Multiple observers | ||
| const obs1 = observer('state.data', handler1); | ||
| const obs2 = observer('state.data', handler2); | ||
| // List all observers | ||
| console.log(observer.list); | ||
| // Output: [{ name: 'state.data', id: '...' }, ...] | ||
| // Remove specific observer | ||
| observer.remove('state.data'); | ||
| // Remove all observers | ||
| observer.removeAll(); | ||
| ``` | ||
| --- | ||
| ## API Reference | ||
| ### observer(path, callback) | ||
| | Parameter | Type | Description | | ||
| |-----------|------|-------------| | ||
| | `path` | `string` | State path to watch (e.g., `'state.counter'`) | | ||
| | `callback` | `function` | Function called on change | | ||
| ### Callback Parameters | ||
| ```javascript | ||
| observer('state.key', (newValue, oldValue) => { | ||
| // newValue: the new value | ||
| // oldValue: the previous value | ||
| }); | ||
| ``` | ||
| ### Properties | ||
| | Property | Type | Description | | ||
| |----------|------|-------------| | ||
| | `observer.list` | `Array` | Get all active observers | | ||
| ### Methods | ||
| | Method | Parameters | Description | | ||
| |--------|------------|-------------| | ||
| | `observer.remove(name)` | `string` | Remove observer for specific path | | ||
| | `observer.removeAll()` | none | Remove all observers | | ||
| --- | ||
| ## React Integration | ||
| ### With useState | ||
| ```javascript | ||
| const [count, setCount] = useState(0); | ||
| observer('state.counter', () => { | ||
| setCount(state.counter); | ||
| }); | ||
| ``` | ||
| ### With useEffect | ||
| ```javascript | ||
| useEffect(() => { | ||
| const handleChange = (newVal) => { | ||
| console.log('Changed:', newVal); | ||
| }; | ||
| observer('state.data', handleChange); | ||
| // Cleanup | ||
| return () => observer.remove('state.data'); | ||
| }, []); | ||
| ``` | ||
| --- | ||
| ## How It Works | ||
| Observer subscribes to state changes via the Proxy's set trap. When `state.key = value` is called: | ||
| 1. The Proxy intercepts the set | ||
| 2. Fires all callbacks registered for that path | ||
| 3. Callbacks receive newValue and oldValue | ||
| --- | ||
| ## Best Practices | ||
| 1. Clean up observers in React `useEffect` return | ||
| 2. Use specific paths: `'state.user.name'` not `'state'` | ||
| 3. Remove observers when components unmount | ||
| 4. Use `observer.removeAll()` on page navigation | ||
| --- | ||
| ## Common Patterns | ||
| ### Form Validation | ||
| ```javascript | ||
| observer('state.form.email', (email) => { | ||
| const isValid = email.includes('@'); | ||
| state.form.isValid = isValid; | ||
| }); | ||
| ``` | ||
| ### Analytics | ||
| ```javascript | ||
| observer('state.page', (page) => { | ||
| analytics.track('page_view', { page }); | ||
| }); | ||
| ``` | ||
| ### Auto-save | ||
| ```javascript | ||
| observer('state.draft', (content) => { | ||
| store.set('autosave', content); | ||
| }); | ||
| ``` |
-129
| # Session - Memorio | ||
| Session provides temporary storage using browser sessionStorage. Data persists until the tab or window is closed. | ||
| ## Installation | ||
| ```bash | ||
| npm install memorio | ||
| ``` | ||
| ```javascript | ||
| import 'memorio'; | ||
| ``` | ||
| --- | ||
| ## Quick Examples | ||
| ### Example 1: Basic Usage | ||
| ```javascript | ||
| // Save session data | ||
| session.set('token', 'abc123'); | ||
| session.set('userId', 42); | ||
| // Read session data | ||
| console.log(session.get('token')); // "abc123" | ||
| ``` | ||
| ### Example 2: Intermediate | ||
| ```javascript | ||
| // Store objects | ||
| session.set('user', { name: 'Mario', role: 'admin' }); | ||
| // Remove specific item | ||
| session.remove('token'); | ||
| // Clear all session data | ||
| session.removeAll(); | ||
| ``` | ||
| ### Example 3: Advanced | ||
| ```javascript | ||
| // Check if session has data | ||
| if (session.get('authToken')) { | ||
| // User is logged in | ||
| } | ||
| // Get storage quota (returns Promise<[usage, quota]> in KB) | ||
| const [used, total] = await session.quota(); | ||
| console.log(`Using ${used} out of ${total} KB`); | ||
| // Get total size in characters | ||
| const size = session.size(); | ||
| console.log(`${size} bytes`); | ||
| // Handle session expiry | ||
| window.addEventListener('storage', (e) => { | ||
| if (e.key === 'session' && !e.newValue) { | ||
| // Session cleared | ||
| redirectToLogin(); | ||
| } | ||
| }); | ||
| ``` | ||
| --- | ||
| ## API Reference | ||
| ### Methods | ||
| | Method | Parameters | Returns | Description | | ||
| |--------|------------|---------|-------------| | ||
| | `session.get(name)` | `name: string` | `any` | Get value from session | | ||
| | `session.set(name, value)` | `name: string, value: any` | `void` | Save value to session | | ||
| | `session.remove(name)` | `name: string` | `boolean` | Remove single item | | ||
| | `session.delete(name)` | `name: string` | `boolean` | Alias for remove | | ||
| | `session.removeAll()` | `none` | `boolean` | Clear all session data | | ||
| | `session.clearAll()` | `none` | `boolean` | Alias for removeAll | | ||
| | `session.size()` | `none` | `number` | Get total size in characters | | ||
| | `session.quota()` | `none` | `Promise<[number, number]>` | Get storage usage/quota in KB | | ||
| --- | ||
| ## Store vs Session | ||
| | Feature | Store | Session | | ||
| |---------|-------|---------| | ||
| | Storage | localStorage | sessionStorage | | ||
| | Lifetime | Forever | Until tab closes | | ||
| | Use case | User preferences | Temporary auth | | ||
| | Shared across tabs | Yes | No | | ||
| --- | ||
| ## Best Practices | ||
| 1. Use for auth tokens: `session.set('token', jwt)` | ||
| 2. Clear on logout: `session.removeAll()` | ||
| 3. Don't use for persistent data | ||
| 4. Check for null: `session.get('key') || defaultValue` | ||
| --- | ||
| ## Common Use Cases | ||
| ### Authentication | ||
| ```javascript | ||
| // Login | ||
| session.set('authToken', response.token); | ||
| session.set('user', response.user); | ||
| // Logout | ||
| session.removeAll(); | ||
| router.push('/login'); | ||
| ``` | ||
| ### Form Progress | ||
| ```javascript | ||
| // Save form draft | ||
| session.set('formDraft', formData); | ||
| // Restore on page refresh | ||
| const draft = session.get('formDraft'); | ||
| if (draft) restoreForm(draft); |
-135
| # State - Memorio | ||
| State is a reactive global state manager using JavaScript Proxies. It's simple, powerful, and requires no setup. Data persists only in memory during the session. | ||
| ## Installation | ||
| ```bash | ||
| npm install memorio | ||
| ``` | ||
| ```javascript | ||
| import 'memorio'; | ||
| ``` | ||
| That's it. `state` is now global. | ||
| --- | ||
| ## Quick Examples | ||
| ### Example 1: Basic Usage | ||
| ```javascript | ||
| // Set a value | ||
| state.name = 'Mario'; | ||
| state.age = 25; | ||
| // Get a value | ||
| console.log(state.name); // "Mario" | ||
| // Simple object | ||
| state.user = { name: 'Luigi', level: 1 }; | ||
| ``` | ||
| ### Example 2: Intermediate | ||
| ```javascript | ||
| // Array operations | ||
| state.items = [1, 2, 3]; | ||
| state.items.push(4); | ||
| console.log(state.items); // [1, 2, 3, 4] | ||
| // Nested objects | ||
| state.config = { theme: 'dark', lang: 'en' }; | ||
| state.config.theme = 'light'; | ||
| // List all states | ||
| console.log(state.list); | ||
| ``` | ||
| ### Example 3: Advanced | ||
| ```javascript | ||
| // Lock state to prevent modifications | ||
| state.frozenConfig = { maxUsers: 100 }; | ||
| state.frozenConfig.lock(); | ||
| // Now state.frozenConfig cannot be modified | ||
| // Path tracking | ||
| const path = state.user.path; | ||
| console.log(path.name); // "user" | ||
| console.log(path.profile.name); // "user.profile" | ||
| // Get full path as string | ||
| console.log(state.user.__path); // "state.user" | ||
| // Protected keys (internal use) | ||
| console.log(protect); // Array of protected keys | ||
| ``` | ||
| --- | ||
| ## API Reference | ||
| ### Properties | ||
| | Property | Type | Description | | ||
| |----------|------|-------------| | ||
| | `state.list` | Array | Get all current state keys (deep copy) | | ||
| | `state.path` | Object | Get path tracker for current location | | ||
| | `state.__path` | string | Get full path as string | | ||
| ### Methods | ||
| | Method | Parameters | Description | | ||
| |--------|------------|-------------| | ||
| | `state.remove(key)` | `key: string` | Remove a specific state | | ||
| | `state.removeAll()` | none | Clear all states | | ||
| ### Lock | ||
| ```javascript | ||
| // Lock an object or array | ||
| state.myArray = [1, 2, 3]; | ||
| state.myArray.lock(); | ||
| // Now any modification will fail | ||
| state.myArray.push(4); // Error: state 'myArray' is locked | ||
| ``` | ||
| --- | ||
| ## How It Works | ||
| Memorio uses JavaScript `Proxy` to intercept get/set operations on the global `state` object. This allows: | ||
| 1. **Reactivity** - Any change can trigger observers | ||
| 2. **Nested objects** - Deep path tracking | ||
| 3. **Type safety** - Full TypeScript support | ||
| --- | ||
| ## Best Practices | ||
| 1. Use descriptive keys: `state.userProfile` not `state.up` | ||
| 2. Group related data: `state.cart.items` not `state.cartItems` | ||
| 3. Lock static config: `state.appConfig.lock()` | ||
| 4. Clean up on logout: `state.removeAll()` | ||
| 5. Use path tracking for debugging: `state.myData.__path` | ||
| --- | ||
| ## Common Errors | ||
| ```javascript | ||
| // Error: protected key | ||
| state._internal = 'value'; | ||
| // Output: "key _internal is protected" | ||
| // Error: locked state | ||
| state.locked = { x: 1 }; | ||
| state.locked.lock(); | ||
| state.locked.x = 2; | ||
| // Output: "Error: state 'locked' is locked" | ||
| ``` |
-137
| # Store - Memorio | ||
| Store provides persistent localStorage management with a simple API. Data survives page refreshes and browser restarts. | ||
| ## Installation | ||
| ```bash | ||
| npm install memorio | ||
| ``` | ||
| ```javascript | ||
| import 'memorio'; | ||
| ``` | ||
| --- | ||
| ## Quick Examples | ||
| ### Example 1: Basic Usage | ||
| ```javascript | ||
| // Save data | ||
| store.set('username', 'Mario'); | ||
| store.set('score', 1500); | ||
| // Read data | ||
| console.log(store.get('username')); // "Mario" | ||
| console.log(store.get('score')); // 1500 | ||
| ``` | ||
| ### Example 2: Intermediate | ||
| ```javascript | ||
| // Store objects | ||
| store.set('user', { name: 'Luigi', level: 5 }); | ||
| const user = store.get('user'); | ||
| console.log(user.name); // "Luigi" | ||
| // Remove single item | ||
| store.remove('username'); | ||
| // Check size | ||
| const totalSize = store.size(); | ||
| console.log(`${totalSize} bytes`); | ||
| ``` | ||
| ### Example 3: Advanced | ||
| ```javascript | ||
| // Get storage quota (returns Promise<[usage, quota]> in KB) | ||
| const [used, total] = await store.quota(); | ||
| console.log(`Using ${used} out of ${total} KB`); | ||
| // Get total size in characters | ||
| const size = store.size(); | ||
| console.log(`${size} bytes`); | ||
| // Clear all data | ||
| store.removeAll(); | ||
| // or use alias | ||
| store.clearAll(); | ||
| // Handle errors gracefully | ||
| try { | ||
| store.set('largeData', hugeObject); | ||
| } catch (err) { | ||
| console.error('Storage full:', err); | ||
| } | ||
| ``` | ||
| --- | ||
| ## API Reference | ||
| ### Methods | ||
| | Method | Parameters | Returns | Description | | ||
| |--------|------------|---------|-------------| | ||
| | `store.get(name)` | `name: string` | `any` | Get value from storage | | ||
| | `store.set(name, value)` | `name: string, value: any` | `void` | Save value to storage | | ||
| | `store.remove(name)` | `name: string` | `boolean` | Remove single item | | ||
| | `store.delete(name)` | `name: string` | `boolean` | Alias for remove | | ||
| | `store.removeAll()` | none | `boolean` | Clear all storage | | ||
| | `store.clearAll()` | none | `boolean` | Alias for removeAll | | ||
| | `store.size()` | none | `number` | Get total size in characters | | ||
| | `store.quota()` | none | `Promise<[number, number]>` | Get storage usage/quota in KB | | ||
| ### Supported Types | ||
| ```javascript | ||
| // All JSON-serializable types work | ||
| store.set('string', 'hello'); | ||
| store.set('number', 42); | ||
| store.set('boolean', true); | ||
| store.set('array', [1, 2, 3]); | ||
| store.set('object', { key: 'value' }); | ||
| store.set('null', null); | ||
| store.set('undefined', null); // converted to null | ||
| ``` | ||
| ### Not Supported | ||
| ```javascript | ||
| // Functions will log an error | ||
| store.set('myFunc', () => {}); | ||
| // Output: "It's not secure to store functions." | ||
| ``` | ||
| --- | ||
| ## How It Works | ||
| Store wraps the browser's `localStorage` API with: | ||
| - Automatic JSON serialization/deserialization | ||
| - Error handling for parse failures | ||
| - Size calculation | ||
| - Quota monitoring | ||
| --- | ||
| ## Storage Limits | ||
| - **Chrome/Safari**: ~5-10 MB | ||
| - **Firefox**: ~10 MB | ||
| - **Edge**: ~5-10 MB | ||
| Use `store.quota()` to monitor usage. | ||
| --- | ||
| ## Best Practices | ||
| 1. Prefix keys: `store.set('app_username', '...')` | ||
| 2. Check before set: `if (store.get('key')) { ... }` | ||
| 3. Handle quota: Try/catch around large data | ||
| 4. Clean up: `store.removeAll()` on logout |
| # Table of contents | ||
| * [README](../README.md) | ||
| ## Core Modules | ||
| * [State](STATE.md) - Reactive global state management | ||
| * [Observer](OBSERVER.md) - ⚠️ Deprecated (use useObserver) | ||
| * [useObserver](USEOBSERVER.md) - React hook for state observation | ||
| * [Cache](CACHE.md) - In-memory caching (lost on refresh) | ||
| * [Store](STORE.md) - Persistent localStorage management | ||
| * [Session](SESSION.md) - Temporary sessionStorage management | ||
| * [IDB](IDB.md) - IndexedDB for large data storage | ||
| ## Additional Resources | ||
| * [License](../LICENSE.md) | ||
| * [Contributing](../CONTRIBUTING.md) | ||
| * [Code of Conduct](../CODE_OF_CONDUCT.md) | ||
| * [Security](../SECURITY.md) | ||
| ## Changelog | ||
| * [Changelog](../CHANGELOG.md) | ||
| * [History](../HISTORY.md) |
| # useObserver - Memorio | ||
| useObserver is a React hook for observing state changes. It automatically subscribes to state changes and includes powerful auto-discovery features. | ||
| ## Installation | ||
| ```bash | ||
| npm install memorio | ||
| ``` | ||
| ```javascript | ||
| import 'memorio'; | ||
| ``` | ||
| --- | ||
| ## Quick Examples | ||
| ### Example 1: Basic Usage | ||
| ```javascript | ||
| import { useObserver } from 'memorio'; | ||
| function Counter() { | ||
| useObserver(() => { | ||
| console.debug('Counter changed:', state.counter); | ||
| }, [state.counter]); | ||
| return <div>{state.counter}</div>; | ||
| } | ||
| ``` | ||
| ### Auto-Discovery (Magic Mode) | ||
| ```javascript | ||
| // Pass your callback WITHOUT dependencies - it auto-discovers! | ||
| function MyComponent() { | ||
| useObserver(() => { | ||
| // This will automatically track ALL state properties used inside | ||
| console.debug('Something changed:', state.user.name, state.items.length); | ||
| }); | ||
| return <div>{state.user.name}</div>; | ||
| } | ||
| ``` | ||
| ### Example 2: Intermediate | ||
| ```javascript | ||
| function UserProfile() { | ||
| const [localState, setLocalState] = useState(null); | ||
| useObserver(() => { | ||
| setLocalState(state.user); | ||
| }, [state.user]); | ||
| return <div>{localState?.name}</div>; | ||
| } | ||
| ``` | ||
| ### Example 3: Advanced | ||
| ```javascript | ||
| // Multiple watchers with array | ||
| function MultiWatch() { | ||
| useObserver(() => { | ||
| console.debug('A or B changed:', state.a, state.b); | ||
| }, [state.a, state.b]); | ||
| return <div>{state.a} - {state.b}</div>; | ||
| } | ||
| ``` | ||
| // With string path (for store) | ||
| function StoreWatcher() { | ||
| useObserver(() => { | ||
| console.debug('Store changed'); | ||
| }, 'store.userPreferences'); | ||
| return <div />; | ||
| } | ||
| ``` | ||
| --- | ||
| ## API Reference | ||
| ### useObserver(callback, deps) | ||
| | Parameter | Type | Description | | ||
| | --------- | ---- | ----------- | | ||
| | `callback` | `function` | Function to run on change | | ||
| | `deps` | `function \| string \| array` | State path(s) to watch | | ||
| ### Callback Parameters | ||
| ```javascript | ||
| useObserver((newValue, oldValue) => { | ||
| console.debug('Changed:', newValue); | ||
| }, [state.key]); | ||
| ``` | ||
| ### Auto-Discovery Mode | ||
| When `deps` is omitted, useObserver automatically discovers all state properties accessed inside the callback: | ||
| ```javascript | ||
| // No deps needed - magic auto-discovery! | ||
| useObserver(() => { | ||
| // Automatically tracks state.user, state.items, state.counter | ||
| console.log(state.user.name, state.items.length, state.counter); | ||
| }); | ||
| ``` | ||
| Returns a cleanup function: | ||
| ## useObserver vs observer | ||
| | Feature | observer | useObserver | | ||
| | ------- | -------- | ----------- | | ||
| | Framework | Vanilla JS | React | | ||
| | Auto-cleanup | Manual | Auto | | ||
| | React lifecycle | No | Yes | | ||
| --- | ||
| ## Common Patterns | ||
| ### Sync with useState | ||
| ```javascript | ||
| function MyComponent() { | ||
| const [data, setData] = useState(null); | ||
| useObserver((newVal) => { | ||
| setData(newVal); | ||
| }, [state.data]); | ||
| return <div>{data}</div>; | ||
| } | ||
| ``` | ||
| ### Multiple Watchers | ||
| ```javascript | ||
| }, [state.a, state.b]); | ||
| ``` | ||
| --- | ||
| ## Best Practices | ||
| 1. Always use in React components | ||
| 2. Use auto-discovery for simpler code: `useObserver(() => { ... })` | ||
| 3. No manual cleanup needed - returns cleanup function automatically | ||
| 4. Use with state for reactive UI | ||
| 5. Check console for auto-discovery logs |
Long strings
Supply chain riskContains long string literals, which may be a sign of obfuscated or packed code.
Found 1 instance in 1 package
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 1 instance in 1 package
URL strings
Supply chain riskPackage contains fragments of external URLs or IP addresses, which the package may be accessing at runtime.
Found 1 instance in 1 package
Long strings
Supply chain riskContains long string literals, which may be a sign of obfuscated or packed code.
Found 1 instance in 1 package
No bug tracker
MaintenancePackage does not have a linked bug tracker in package.json.
Found 1 instance in 1 package
No repository
Supply chain riskPackage does not have a linked source code repository. Without this field, a package will have no reference to the location of the source code use to generate the package.
Found 1 instance in 1 package
URL strings
Supply chain riskPackage contains fragments of external URLs or IP addresses, which the package may be accessing at runtime.
Found 1 instance in 1 package
98014
15.74%0
-100%1183
9.94%314
2.95%26
-16.13%2
100%9
200%No
NaN