memorio 4.8.0 → 4.9.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +232 -527
- package/SUMMARY.md +1 -5
- package/index.cjs +4401 -148
- package/index.js +4358 -102
- package/llms.txt +1 -1
- package/package.json +7 -8
- package/types/env.d.ts +9 -0
- package/types/exports.d.ts +50 -1
- package/types/memorio.d.ts +15 -11
- package/types/memory.d.ts +40 -2
- package/types/schema.d.ts +53 -53
- package/markdown/CACHE.md +0 -90
- package/markdown/CHANGELOG.md +0 -161
- package/markdown/DEVTOOLS.md +0 -122
- package/markdown/DISPATCH.md +0 -168
- package/markdown/HISTORY.md +0 -192
- package/markdown/IDB.md +0 -169
- package/markdown/IMPORT.md +0 -139
- package/markdown/INSPECT.md +0 -116
- package/markdown/LOGGER.md +0 -147
- package/markdown/MEMORY-ATTACHMENT.md +0 -95
- package/markdown/MEMORY.md +0 -155
- package/markdown/OBSERVER.md +0 -200
- package/markdown/PLATFORM.md +0 -265
- package/markdown/SCHEMA.md +0 -169
- package/markdown/SECURITY.md +0 -323
- package/markdown/SESSION.md +0 -154
- package/markdown/SQLITE.md +0 -181
- package/markdown/STATE.md +0 -153
- package/markdown/STORE.md +0 -164
- package/markdown/SYNC.md +0 -170
- package/markdown/TYPED.md +0 -158
- package/markdown/USEOBSERVER.md +0 -259
package/index.js
CHANGED
|
@@ -1,8 +1,2932 @@
|
|
|
1
1
|
import 'path';
|
|
2
2
|
import 'url';
|
|
3
3
|
|
|
4
|
-
var x=(e,t)=>()=>(e&&(t=e(e=0)),t);var a=x(()=>{});var y,dr,mt,Se,u,$=x(()=>{a();y={debug:false,tracking:false,trackedPaths:new Set,locked:false,lastAccessedPath:"",stateVersion:0,currentContext:null,mutations:[],undoStack:[],redoStack:[],maxHistory:100,historyEnabled:false},dr={get debug(){return y.debug},set debug(e){y.debug=e;},get tracking(){return y.tracking},set tracking(e){y.tracking=e;},get trackedPaths(){return y.trackedPaths},clearTrackedPaths(){y.trackedPaths.clear();},get locked(){return y.locked},set locked(e){y.locked=e;},get lastAccessedPath(){return y.lastAccessedPath},set lastAccessedPath(e){y.lastAccessedPath=e;},get stateVersion(){return y.stateVersion},bumpStateVersion(){return y.stateVersion=(y.stateVersion||0)+1,y.stateVersion},get currentContext(){return y.currentContext},set currentContext(e){y.currentContext=e;},get mutations(){return y.mutations},get undoStack(){return y.undoStack},get redoStack(){return y.redoStack},get maxHistory(){return y.maxHistory},set maxHistory(e){y.maxHistory=e;},get historyEnabled(){return y.historyEnabled},set historyEnabled(e){y.historyEnabled=e;},recordMutation(e){y.historyEnabled&&(y.mutations.push(e),y.mutations.length>y.maxHistory&&y.mutations.shift(),y.undoStack.push(e),y.undoStack.length>y.maxHistory&&y.undoStack.shift(),y.redoStack=[]);},popUndo(){let e=y.undoStack.pop();return e&&y.redoStack.push(e),e},popRedo(){let e=y.redoStack.pop();return e&&y.undoStack.push(e),e},canUndo(){return y.undoStack.length>0},canRedo(){return y.redoStack.length>0},clearHistory(){y.mutations=[],y.undoStack=[],y.redoStack=[];},clearRedo(){y.redoStack=[];}},mt=["list","state","store","idb","sqlite","observer","useObserver","remove","removeAll","_platform","_capabilities","_sessionId"],Se=(e,t)=>String(t!==void 0?t:e).replace("() => ",""),u=dr;});var P,c,w=x(()=>{a();$();P=(...e)=>{u.debug===true&&console.debug(...e);},c=P;});function ce(){let e=globalThis;if(typeof e.crypto<"u"&&e.crypto.randomUUID)return e.crypto.randomUUID();if(typeof e.crypto<"u"&&e.crypto.getRandomValues){let t=new Uint8Array(16);return e.crypto.getRandomValues(t),Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")}return `session_${Date.now()}_${Math.random().toString(36).substring(2,15)}`}function te(){let e=globalThis;return e.Deno&&e.Deno.version?"deno":typeof process<"u"&&process.versions&&process.versions.node?"node":typeof globalThis<"u"&&typeof globalThis.ServiceWorkerGlobalScope<"u"?"edge":typeof window<"u"&&typeof document<"u"?"browser":"unknown"}function we(){return te()==="browser"}function Ee(){return te()==="node"}function Te(){return te()==="deno"}function Pe(){return te()==="edge"}function _e(){try{if(typeof sessionStorage<"u"){let e="__memorio_test__";return sessionStorage.setItem(e,"1"),sessionStorage.removeItem(e),sessionStorage}}catch{}return null}function ke(){try{if(typeof localStorage<"u"){let e="__memorio_test__";return localStorage.setItem(e,"1"),localStorage.removeItem(e),localStorage}}catch{}return null}function Oe(){return typeof indexedDB<"u"}function re(){let e=globalThis;return typeof e.WebAssembly>"u"||typeof e.WebAssembly.instantiate!="function"?false:typeof e.window<"u"}function pr(){return typeof globalThis.dispatchEvent=="function"}function oe(){let e=te(),t=typeof globalThis.isSecureContext<"u"?globalThis.isSecureContext:e==="browser";return {platform:e,hasSessionStorage:_e()!==null,hasLocalStorage:ke()!==null,hasIndexedDB:Oe(),hasSqlJs:re(),hasDispatchEvent:pr(),hasNavigator:typeof navigator<"u",hasProcess:typeof process<"u",isSecureContext:t,sessionId:ce()}}function xt(){let e=oe(),t=globalThis;e.hasDispatchEvent||(t.dispatchEvent=function(r){return true},typeof CustomEvent>"u"&&(t.CustomEvent=class{type;detail;constructor(o,n={}){this.type=o,this.detail=n;}})),typeof t.addEventListener!="function"&&(t.addEventListener=function(r,o){ee.has(r)||ee.set(r,[]),ee.get(r).push(o);},t.removeEventListener=function(r,o){let n=ee.get(r);if(n){let s=n.indexOf(o);s>-1&&n.splice(s,1);}},t.dispatchEvent=function(r){let o=ee.get(r.type);return o&&o.forEach(n=>{try{n(r);}catch(s){console.error("Event listener error:",s);}}),true});}function ne(e){let t=e||`context_${ce()}`;Ce(t);let r={state:{},store:new Map,session:new Map,cache:new Map};return qe.set(t,r),{id:t,state:r.state,store:{get:o=>{let n=r.store.get(o);return n?JSON.parse(n):null},set:(o,n)=>{r.store.set(o,JSON.stringify(n));},remove:o=>r.store.delete(o),removeAll:()=>r.store.clear(),clearAll:()=>r.store.clear(),size:()=>r.store.size,isPersistent:false},session:{get:o=>{let n=r.session.get(o);return n?JSON.parse(n):null},set:(o,n)=>{r.session.set(o,JSON.stringify(n));},remove:o=>r.session.delete(o),removeAll:()=>r.session.clear(),clearAll:()=>r.session.clear(),size:()=>r.session.size,isPersistent:false},cache:{get:o=>r.cache.get(o),set:(o,n)=>r.cache.set(o,n),remove:o=>r.cache.delete(o),removeAll:()=>r.cache.clear(),clear:()=>r.cache.clear()}}}function Me(){return Array.from(qe.keys())}function $e(e){return qe.delete(e)}function Ce(e){u.currentContext=e;}var ee,qe,J=x(()=>{a();$();ee=new Map;qe=new Map;});function U(){let t=u.currentContext||""||"default";return je.has(t)||je.set(t,new Map),je.get(t)}function B(){let e=u.currentContext||"";return e?`${e}-`:"memorio_store_"}function De(e){return !e||typeof e!="string"?(console.warn("[memorio store] key is empty or not a string - operation aborted"),""):e.length>512?(console.warn(`[memorio store] key "${e}" exceeds 512 chars - operation aborted`),""):B()+e}function yr(e){let t=V?q.getItem(e):U().get(e);return t&&JSON.parse(t)}function gr(e,t){let r=JSON.stringify(t);V?q.setItem(e,r):U().set(e,r);}function br(e){if(V){if(q.getItem(e))return q.removeItem(e),true}else if(U().has(e))return U().delete(e),true;return false}var q,je,V,h,G=x(()=>{a();J();$();w();q=ke(),je=new Map;V=q!==null;h=new Proxy({},{});Object.defineProperty(globalThis,"store",{value:h,enumerable:false,configurable:true});Object.defineProperties(h,{get:{value:e=>{if(!e)return console.warn("[memorio store] store.get() called with empty or null key - returning null"),null;try{return yr(De(e))}catch(t){P(`Error parsing store item '${e}': ${t}`);}return null}},getMultiple:{value:e=>{let t={};for(let r of e)try{let o=h.get(r);o&&(t[r]=o);}catch(o){console.debug(`[memorio store] getMultiple error for key "${r}":`,o);}return t}},set:{value:(e,t)=>{if(!e)return console.warn("[memorio store] store.set() called with empty or null key - write aborted"),false;let r=De(e);if(!r)return false;if(typeof t=="function")return console.warn("[memorio store] functions are not storable - write aborted for key: "+e),P("Storing functions is not secure and is blocked for safety."),false;try{gr(r,t);}catch(o){return P(`Error setting store item '${e}': ${o}`),false}return true}},remove:{value:e=>{if(!e)return console.debug("[memorio store] store.remove() called with empty or null key - returning false"),false;let t=De(e);if(!t)return false;try{return br(t)}catch(r){P(`Error removing store item '${e}': ${r}`);}return false}},delete:{value:e=>h.remove(e)},removeAll:{value:()=>{if(V){let e=[];for(let t=0;t<q.length;t++){let r=q.key(t);r?.startsWith(B())&&e.push(r);}e.forEach(t=>q.removeItem(t));}else U().clear();return true}},clearAll:{value:()=>(h.removeAll(),true)},quota:{value:async()=>[0,0]},size:{value:()=>{let e=0;return V?Object.keys(q).forEach(t=>{if(t.startsWith(B())){let r=q.getItem(t);r&&(e+=r.length);}}):U().forEach(t=>{e+=t.length;}),e}},isPersistent:{get:()=>V},list:{value:()=>{let e={};try{if(V)for(let t=0;t<q.length;t++){let r=q.key(t);if(r?.startsWith(B())){let o=r.replace(B(),""),n=q.getItem(r);if(n!==null)try{e[o]=JSON.parse(n);}catch{e[o]=n;}}}else U().forEach((t,r)=>{if(r.startsWith(B())){let o=r.replace(B(),"");try{e[o]=JSON.parse(t);}catch{e[o]=t;}}});}catch(t){P(`Error listing store items: ${t}`);}return e}}});Object.freeze(h);});var Sr={};var St=x(()=>{a();T();w();d.db.create=(e,t=1)=>new Promise((r,o)=>{if(!d.db.support())return o(new Error("IndexedDB not supported"));let n=globalThis.indexedDB.open(e,t);n.onerror=()=>{c(`IndexedDB error: ${n.error?.message}`),o(n.error);},n.onsuccess=()=>{c(`Database ${e} connected successfully`),r(n.result);},n.onupgradeneeded=()=>{c(`Database ${e} upgrade/creation initiated`);};});});var wr={};var wt=x(()=>{a();T();d.db.list=async()=>{if(!("indexedDB"in globalThis)||!indexedDB.databases)return [];try{let e=await indexedDB.databases();return globalThis.idbases=e||[],await d.db.size(),globalThis.idbases}catch(e){return console.error("Error listing databases:",e),[]}};});var Er={};var Et=x(()=>{a();T();d.db.exist=e=>idbases?.some(t=>t.name===e);});var Tr={};var Tt=x(()=>{a();T();d.db.quota=()=>navigator.storage.estimate();});var Pr={};var Pt=x(()=>{a();T();w();d.db.delete=e=>new Promise((t,r)=>{c(`Removing database ${e}...`),(()=>{let n=indexedDB.deleteDatabase(e);n.onsuccess=()=>{c(`${e} database removed successfully`),d.db.list(),t();},n.onerror=()=>{console.error(`Error removing ${e}:`,n.error),r(n.error);},n.onblocked=()=>{console.warn(`Deletion of ${e} is blocked. Please close other tabs.`);};})();});});var _r={};var _t=x(()=>{a();T();w();d.db.size=async()=>{if(!(!idbases||idbases.length===0))for(let e=0;e<idbases.length;e++){let t=idbases[e];try{let r=await d.db.create(t.name,t.version),o=Array.from(r.objectStoreNames),n=0;for(let s of o){let i=await d.table.size(r,s);n+=i;}t.size=n,r.close();}catch(r){c(`Could not calculate size for ${t.name}:${r}`);}}};});var kr={};var kt=x(()=>{a();T();d.db.version=e=>{let t=0;for(let r of idbases){r.name===e&&(t=r.version);break}return t};});var Or={};var Ot=x(()=>{a();T();w();d.db.support=()=>{let e="indexedDB"in globalThis;return e||c("Your environment doesn't support IndexedDB"),e};});var qr={};var qt=x(()=>{a();T();w();d.table.create=(e,t)=>new Promise((r,o)=>{try{let s=(Number(d.db.version(e))||0)+1,i=indexedDB.open(e,s);i.onupgradeneeded=l=>{let g=l.target.result;if(!g.objectStoreNames.contains(t)){let b=g.createObjectStore(t,{keyPath:"id",autoIncrement:!0});b.createIndex("id","id",{unique:!0}),b.createIndex("data","data",{unique:!1}),c(`Table ${t} created in ${e}`);}},i.onsuccess=()=>{i.result.close(),d.db.list(),r();},i.onerror=()=>{console.error(`Error creating table ${t}:`,i.error),o(i.error);};}catch(n){console.error("Critical error in table.create:",n),o(n);}});});var Mr={};var Mt=x(()=>{a();T();w();d.table.size=(e,t)=>new Promise((r,o)=>{if(!e)return o(new Error("Database instance is required"));if(!e.objectStoreNames.contains(t))return r(0);let n=0,s=0,g=e.transaction([t],"readonly").objectStore(t).openCursor();g.onsuccess=async b=>{let v=b.target.result;if(v){try{let O=v.value;n+=JSON.stringify(O).length;}catch(O){c(`Error stringifying IDB value tracking size:${O}`);}s++,s%200===0&&await new Promise(O=>setTimeout(O,0)),v.continue();}else r(n);},g.onerror=()=>{o(g.error);};});});var $r={};var $t=x(()=>{a();T();w();d.data.delete=(e,t,r)=>new Promise((o,n)=>{let s=indexedDB.open(e);s.onsuccess=()=>{let i=s.result;if(!i.objectStoreNames.contains(t))return i.close(),n(new Error(`Table ${t} not found`));let b=i.transaction(t,"readwrite").objectStore(t).delete(r);b.onsuccess=()=>{i.close(),c(`Record ${r} deleted from ${t}`),o();},b.onerror=()=>{i.close(),n(b.error);};},s.onerror=()=>n(s.error);});d.data.delete.all=(e,t)=>new Promise((r,o)=>{let n=indexedDB.open(e);n.onsuccess=s=>{let i=s.target.result;if(!i.objectStoreNames.contains(t))return i.close(),o(new Error(`Table ${t} not found`));let b=i.transaction(t,"readwrite").objectStore(t).clear();b.onsuccess=()=>{i.close(),c(`All data cleared from ${t}`),r();},b.onerror=()=>{i.close(),o(b.error);};},n.onerror=()=>o(n.error);});});var Cr={};var Ct=x(()=>{a();T();w();d.data.set=(e,t,r)=>new Promise((o,n)=>{let s=indexedDB.open(e);s.onsuccess=()=>{let i=s.result;if(!i.objectStoreNames.contains(t))return i.close(),n(new Error(`Table ${t} does not exist in ${e}`));let b=i.transaction(t,"readwrite").objectStore(t).put(r);b.onsuccess=()=>{i.close(),c(`Data saved in ${e}.${t}`),o(b.result);},b.onerror=v=>{i.close(),c(`Database insert error: ${b.error?.message}`),n(b.error);};},s.onerror=()=>{n(s.error);};});});var jr={};var jt=x(()=>{a();T();d.data.get=(e,t,r)=>new Promise((o,n)=>{let s=indexedDB.open(e);s.onsuccess=i=>{let l=i.target.result;if(!l.objectStoreNames.contains(t))return l.close(),n(new Error(`Table ${t} not found in ${e}`));let v=l.transaction(t,"readonly").objectStore(t).get(r);v.onsuccess=()=>{l.close(),o(v.result);},v.onerror=()=>{l.close(),n(v.error);};},s.onerror=()=>{n(s.error);};});});var Dr,d,T=x(()=>{a();J();Dr=Oe(),d={db:{},table:{},data:{}};Dr?(async()=>(Object.defineProperty(d,"db",{value:{},writable:true,configurable:true}),Object.defineProperty(d,"table",{value:{},writable:true,configurable:true}),Object.defineProperty(d,"data",{value:{},writable:true,configurable:true}),Object.defineProperty(globalThis,"idbases",{value:[],writable:true,configurable:true,enumerable:false}),await Promise.all([Promise.resolve().then(()=>(St(),Sr)),Promise.resolve().then(()=>(wt(),wr)),Promise.resolve().then(()=>(Et(),Er)),Promise.resolve().then(()=>(Tt(),Tr)),Promise.resolve().then(()=>(Pt(),Pr)),Promise.resolve().then(()=>(_t(),_r)),Promise.resolve().then(()=>(kt(),kr)),Promise.resolve().then(()=>(Ot(),Or)),Promise.resolve().then(()=>(qt(),qr)),Promise.resolve().then(()=>(Mt(),Mr)),Promise.resolve().then(()=>($t(),$r)),Promise.resolve().then(()=>(Ct(),Cr)),Promise.resolve().then(()=>(jt(),jr))]),Object.preventExtensions(d),Object.seal(d),Object.freeze(d)))():(d._disabled=true,d._warning="IndexedDB is not available in this environment (Node.js/Deno). Use store or session for persistence.",console.warn("Memorio IDB: IndexedDB is not available in this environment. Use store or session for data persistence."));});var Nr={};function Ir(){let e=globalThis;return typeof e.document<"u"&&typeof e.document.createElement=="function"}function Lr(e){let t=globalThis;return t.__memorioSqlJsScript===e?Promise.resolve():(Ie||(Ie=new Promise((r,o)=>{if(t.initSqlJs&&typeof t.initSqlJs=="function"){t.__memorioSqlJsScript=e,r();return}if(!Ir()){o(new Error("memorio sqlite: no document available to load sql.js"));return}let n=t.document.createElement("script");n.src=e,n.async=true,n.onload=()=>{t.__memorioSqlJsScript=e,r();},n.onerror=()=>o(new Error(`memorio sqlite: failed to load sql.js from ${e}`)),t.document.head.appendChild(n);})),Ie)}var me,de,Dt,Ar,Rr,Ie,Jr,At=x(()=>{a();_();J();w();me=null,de=null,Dt="https://cdn.jsdelivr.net/npm/sql.js/dist/sql-wasm-browser.js",Ar=Dt.replace(/sql-wasm-browser\.js$/,""),Rr=e=>(globalThis.sqliteWasmBase||Ar)+e,Ie=null;Jr=async()=>{let e=globalThis;return typeof e.initSqlJs=="function"?e.initSqlJs:(await Lr(Dt),e.initSqlJs||e)};m.db.support=()=>re();m.db.getSQL=async()=>{if(de)return de;if(me)return me;let e=globalThis,t=e.sqliteConfig||{},r=(async()=>{if(typeof t.loader=="function")return await t.loader();let o=await Jr(),s=await(typeof o=="function"?o:o&&(o.default||o))({locateFile:t.locateFile||Rr});return e.sqliteVersion=s?.version||"sql.js",c("Memorio SQLite: sql.js engine loaded"),s})();me=r;try{return de=await r,de}catch(o){try{m._disabled=!0;}catch{}try{m._warning='Memorio SQLite: sql.js could not be loaded. Install sql.js (npm i sql.js) and configure a loader via sqlite.config({ loader: () => import("sql.js") }).';}catch{}throw console.warn("Memorio SQLite: failed to load sql.js",o),o}finally{me=null;}};m.db.version=()=>globalThis.sqliteVersion||null;});function Br(){let e=D.sqliteConfig||{};return e.namespace?`ns:${e.namespace}`:"default"}function Le(e){return `memorio:sqlite:db:${Br()}:${e}`}function Vr(e){let t=e instanceof Uint8Array?e:new Uint8Array(e),r="",o=t.byteLength;for(let n=0;n<o;n++)r+=String.fromCharCode(t[n]);return typeof btoa=="function"?btoa(r):typeof Buffer<"u"?Buffer.from(t).toString("base64"):""}function Ur(e){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(e,"base64"));if(typeof atob!="function")throw new Error("memorio sqlite: no base64 decoder available");let t=atob(e),r=t.length,o=new Uint8Array(r);for(let n=0;n<r;n++)o[n]=t.charCodeAt(n);return o}function fe(e){return new Promise(t=>{let r=D.__sqliteDbs&&D.__sqliteDbs[e];if(!r||typeof r.export!="function"){t(false);return}try{let o=r.export();h.set(Le(e),Vr(o)),c(`Memorio SQLite: persisted '${e}' to store`),t(!0);}catch(o){console.warn("Memorio SQLite: persist snapshot failed",o),t(false);}})}function Je(e){let t=h.get(Le(e));if(!t)return null;try{return Ur(t)}catch{return null}}function Hr(e){h.remove(Le(e));}function It(e,t){if(!(!t||typeof t.updateHook!="function")){Rt[e]=true;try{t.updateHook(()=>{K[e]&&clearTimeout(K[e]),K[e]=setTimeout(()=>{K[e]=null,fe(e);},250);});}catch(r){console.warn("Memorio SQLite: could not attach updateHook",r);}}}var D,Rt,K,Lt=x(()=>{a();_();G();w();D=globalThis,Rt={},K={};m.db.persist=async(e="memorio")=>fe(e);m.db.download=async(e="memorio",t=`${e}.sqlite`)=>{let r=globalThis;if(!(r.__sqliteDbs&&r.__sqliteDbs[e]))return console.warn(`Memorio SQLite: cannot download '${e}' \u2014 database not found. Create it with sqlite.db.create('${e}').`),false;let n;try{n=await m.db.export(e);}catch(g){return console.warn("Memorio SQLite: export failed during download",g),false}if(!n)return false;if(typeof r.document>"u"||typeof r.Blob>"u")return console.warn("Memorio SQLite: sqlite.db.download() requires a browser environment."),false;let s=r.URL||r.webkitURL;if(!s||typeof s.createObjectURL!="function")return false;let i=s.createObjectURL(new Blob([n],{type:"application/x-sqlite3"})),l=r.document.createElement("a");return l.style.display="none",l.href=i,l.download=t,r.document.body.appendChild(l),l.click(),setTimeout(()=>{try{s.revokeObjectURL(i);}catch{}l.remove();},1e3),true};m.db.close=async(e="memorio")=>{let t=D.__sqliteDbs&&D.__sqliteDbs[e];if(t&&typeof t.close=="function"){try{await fe(e);}catch{}try{t.close();}catch(r){console.warn("Memorio SQLite: close failed",r);}}if(D.__sqliteDbs&&delete D.__sqliteDbs[e],D.sqlbases){let r=D.sqlbases.findIndex(o=>o&&o.name===e);r>-1&&D.sqlbases.splice(r,1);}delete Rt[e],K[e]&&(clearTimeout(K[e]),K[e]=null),Hr(e);};m.db.loadSnapshot=Je;m.db.saveSnapshot=fe;});var zr={};var Jt=x(()=>{a();_();w();Lt();m.db.create=async(e="memorio",t={})=>{let r=await m.db.getSQL(),o=globalThis,n=!!(t&&t.persistence)||!!(o.sqliteConfig&&o.sqliteConfig.persistence),s;if(n&&!t.data){let v=Je(e);v&&(s=v);}let i=t&&t.data||s,l;i&&typeof i.byteLength=="number"?(l=new r.Database(i),c(`Memorio SQLite: database '${e}' opened (persistence=${n})`)):(l=new r.Database,c(`Memorio SQLite: database '${e}' created (persistence=${n})`));let g={...t,persistence:n};o.__sqliteDbs||(o.__sqliteDbs={}),o.__sqliteDbs[e]=l,o.sqlbases||(o.sqlbases=[]);let b=o.sqlbases.findIndex(v=>v&&v.name===e);return b>-1?o.sqlbases[b]={name:e,db:l,persistence:g.persistence}:o.sqlbases.push({name:e,db:l,persistence:g.persistence}),n&&It(e,l),l};});var Qr={};var Nt=x(()=>{a();_();m.db.get=(e="memorio")=>{let t=globalThis.__sqliteDbs;if(!t||!t[e])throw new Error(`SQLite database '${e}' does not exist. Create it with sqlite.db.create('${e}').`);return t[e]};});var Kr={};var Bt=x(()=>{a();_();w();m.db.delete=e=>{let t=globalThis.__sqliteDbs;if(!t||!t[e])return false;try{t[e].close();}catch{}delete t[e];let r=globalThis;return r.sqlbases&&(r.sqlbases=r.sqlbases.filter(o=>o&&o.name!==e)),c(`Memorio SQLite: database '${e}' deleted`),true};});var Wr={};var Vt=x(()=>{a();_();m.db.list=()=>{let e=globalThis.__sqliteDbs;return e?Object.keys(e):[]};});var Fr={};var Ut=x(()=>{a();_();m.db.size=async e=>{let t=globalThis.__sqliteDbs;if(!t)return 0;let r=n=>n&&(n.byteLength||n.length)||0;if(e){let n=m.db.get(e);return r(n.export())}let o=0;for(let n of Object.keys(t))try{o+=r(t[n].export());}catch{}return o};});var Gr={};var Ht=x(()=>{a();_();m.db.export=async(e="memorio")=>m.db.get(e).export();});var Yr={};var zt=x(()=>{a();_();m.db.import=async(e,t)=>m.db.create(e,{data:t});});var Xr={};var Qt=x(()=>{a();_();w();m.query.run=async(e="memorio",t,r=[])=>{let o=m.db.get(e);return c(`Memorio SQLite: run -> ${t}`),o.run(t,r),o.getRowsModified()};});var Zr={};var Kt=x(()=>{a();_();m.query.select=async(e="memorio",t,r=[])=>{let n=m.db.get(e).prepare(t,r),s=[];try{for(;n.step();)s.push(n.getAsObject());}finally{try{n.free();}catch{}}return s};});var eo={};var Wt=x(()=>{a();_();m.data.set=async(e="memorio",t,r=[])=>m.query.run(e,t,r);});var to={};var Ft=x(()=>{a();_();m.data.get=async(e="memorio",t,r=[])=>{let o=await m.query.select(e,t,r);return o.length?o[0]:null};});var ro,m,_=x(()=>{a();J();ro=re(),m={db:{},query:{},data:{}};m.config=e=>{let t=globalThis;return t.sqliteConfig={...t.sqliteConfig,...e},e&&e.wasmUrl&&(t.sqliteWasmBase=e.wasmUrl.endsWith("/")?e.wasmUrl:e.wasmUrl+"/"),m};Object.defineProperty(m,"ready",{enumerable:false,configurable:false,get:()=>{let e=globalThis;return e.sqliteReady||(e.sqliteReady=typeof m.db.getSQL=="function"?m.db.getSQL().then(()=>{}).catch(()=>{}):Promise.resolve()),e.sqliteReady}});ro?(async()=>(Object.defineProperty(m,"db",{value:{},writable:false,configurable:true,enumerable:true}),Object.defineProperty(m,"query",{value:{},writable:false,configurable:true,enumerable:true}),Object.defineProperty(m,"data",{value:{},writable:false,configurable:true,enumerable:true}),Object.defineProperty(globalThis,"sqlbases",{value:[],writable:true,configurable:true,enumerable:false}),await Promise.all([Promise.resolve().then(()=>(At(),Nr)),Promise.resolve().then(()=>(Jt(),zr)),Promise.resolve().then(()=>(Nt(),Qr)),Promise.resolve().then(()=>(Bt(),Kr)),Promise.resolve().then(()=>(Vt(),Wr)),Promise.resolve().then(()=>(Ut(),Fr)),Promise.resolve().then(()=>(Ht(),Gr)),Promise.resolve().then(()=>(zt(),Yr)),Promise.resolve().then(()=>(Qt(),Xr)),Promise.resolve().then(()=>(Kt(),Zr)),Promise.resolve().then(()=>(Wt(),eo)),Promise.resolve().then(()=>(Ft(),to))])))():(globalThis.sqliteDisabled=true,globalThis.sqliteWarning='SQLite (sql.js) is not available in this environment. It requires a browser with WebAssembly support. Install the optional "sql.js" package to enable it.',m._disabled=true,m._warning=globalThis.sqliteWarning,console.warn("Memorio SQLite: sql.js is not available in this environment (requires browser + WebAssembly). Use store or session for persistence."));});a();a();$();w();a();var E={set:(e,t={})=>{globalThis.dispatchEvent(new CustomEvent(String(e),t));},listen:(e,t=null,r)=>{if(globalThis.events?.[e])return;let o=t?n=>{let s=n;return globalThis.queueMicrotask?globalThis.queueMicrotask(()=>t(s)):Promise.resolve().then(()=>t(s))}:void 0;o&&globalThis.addEventListener(e,o),o&&(globalThis.events[e]=o);},remove:e=>{let t=globalThis.events?.[e];t&&(globalThis.removeEventListener(e,t),delete globalThis.events[e]);}};a();w();var F=new Map,dt=(e,t,r)=>{let o=[];if(t.type&&t.type!=="any"){let n=Array.isArray(e)?"array":typeof e;if(n!==t.type)return o.push(`${r}: expected ${t.type}, got ${n}`),{valid:false,errors:o}}if(t.enum&&!t.enum.includes(e)&&o.push(`${r}: value must be one of [${t.enum.map(String).join(", ")}]`),t.validator){let n=t.validator(e);n!==true&&o.push(`${r}: ${typeof n=="string"?n:"validation failed"}`);}if(typeof e=="number"&&(t.min!==void 0&&e<t.min&&o.push(`${r}: value ${e} is less than minimum ${t.min}`),t.max!==void 0&&e>t.max&&o.push(`${r}: value ${e} exceeds maximum ${t.max}`)),typeof e=="string"&&(t.min!==void 0&&e.length<t.min&&o.push(`${r}: string length ${e.length} is less than minimum ${t.min}`),t.max!==void 0&&e.length>t.max&&o.push(`${r}: string length ${e.length} exceeds maximum ${t.max}`),t.pattern&&!t.pattern.test(e)&&o.push(`${r}: string does not match required pattern`)),t.type==="object"&&e&&typeof e=="object"&&!Array.isArray(e)){if(t.required)for(let n of t.required)n in e||o.push(`${r}: missing required property '${n}'`);if(t.properties){for(let[n,s]of Object.entries(t.properties))if(n in e&&e[n]!==void 0){let i=dt(e[n],s,`${r}.${n}`);i.valid||o.push(...i.errors||[]);}}}return o.length===0?{valid:true}:{valid:false,errors:o}},ft=(e,t)=>{let r=F.get(e);return r?dt(t,r,e):{valid:true}},pt=(e,t)=>{typeof t=="function"?F.set(e,{validator:t}):F.set(e,t),c(`[memorio schema] Registered schema for '${e}'`);},yt=e=>F.delete(e),gt=()=>Array.from(F.keys()),fr=e=>F.get(e),L={register:pt,validate:ft,unregister:yt,list:gt,get:fr};var le=Symbol("memorio.target"),bt=new WeakMap,R=(e,t=null)=>{if(e===null||typeof e!="object")return e;if(e[le]!==void 0)return R(e[le],t);if(t){if(t.has(e))return e;t.add(e);}let r=e.constructor?.name;if(r!=="Object"&&r!=="Array")return e;let o=Array.isArray(e)?[]:{};for(let n of Reflect.ownKeys(e))o[n]=R(e[n],t);return o},ht=(e,t,r=".")=>t.concat(e).join(r),vt=(e,t,r=[])=>{let o=n=>{try{E.set(n,{detail:{name:n}});}catch{}};return new Proxy(e,{get(n,s){if(s==="__path")return r.length>0?"state."+r.join("."):"state";if(s===le||n[le]!==void 0)return n;if(s==="list")return c('Some state could be hidden when you use "state.list". Use "state" to see the complete list '),JSON.parse(JSON.stringify(n));if(typeof s=="string"){let i=r.length>0?"state."+r.concat(s).join("."):"state."+s;u.lastAccessedPath=i,u.tracking&&u.trackedPaths.add(i);}if(s==="_lastPath")return u.lastAccessedPath;if(s==="remove")return i=>(delete n[i],true);if(s==="removeAll")return ()=>{try{for(let i in n)typeof n[i]!="function"&&!["list","remove","removeAll","lock","unlock"].includes(i)&&delete n[i];}catch(i){console.error(i);}};if(Object.isFrozen(n[s]))return n[s];if(s==="lock"||s==="unlock"){let i=Reflect.get(n,s);if(i)return i}try{let i=Reflect.get(n,s);if(i&&typeof i=="object"&&["Array","Object"].includes(i.constructor.name)){let l=bt.get(i);return l||(l=vt(i,t,r.concat(s)),bt.set(i,l)),l}return i}catch(i){console.error("Error: ",i);return}},set(n,s,i){if(u.locked)return console.error("Error: state is locked. Use state.unlock() to enable modifications."),false;if(mt.includes(s))return console.error("key "+s+" is protected"),false;if(n[s]&&typeof n[s]=="object"&&Object.isFrozen(n[s]))return console.error(`Error: state '${s}' is locked`),false;if(n[s]&&typeof n[s]=="object"&&n[s].__locked)return console.error(`Error: state '${s}' is locked. Use state.${s}.unlock() to enable modifications.`),false;try{let l=ht(s,r),g=R(i),b=L.validate(l,g);if(!b.valid)return u.debug&&console.error(`[memorio schema] Validation failed for '${l}':`,b.errors),c(`[memorio schema] Validation failed for '${l}': `+(b.errors?.join(", ")||"unknown error")),!1;if(t({action:"set",path:l,target:n,newValue:g,previousValue:Reflect.get(n,s)}),o("state."+l),Reflect.set(n,s,g),u.bumpStateVersion(),n[s]&&typeof n[s]=="object"){let v=n[s];if(v&&typeof v=="object")try{Object.defineProperty(v,"__locked",{writable:!0,enumerable:!1,configurable:!1,value:!1}),Object.defineProperty(v,"lock",{writable:!1,enumerable:!1,configurable:!1,value:()=>{Object.defineProperty(v,"__locked",{writable:!0,enumerable:!1,configurable:!1,value:!0}),c(`State '${s}' is now locked.`);}}),Object.defineProperty(v,"unlock",{writable:!1,enumerable:!1,configurable:!1,value:()=>{Object.defineProperty(v,"__locked",{writable:!0,enumerable:!1,configurable:!1,value:!1}),c(`State '${s}' is now unlocked.`);}});}catch{}}return !0}catch(l){return console.error("Error in set trap:",l),false}},deleteProperty(n,s){try{let i=ht(s,r),l=Reflect.get(n,s);return t({action:"delete",path:i,target:n,previousValue:l}),Reflect.deleteProperty(n,s)}catch(i){return console.error("Error in deleteProperty trap:",i),false}},ownKeys(n){return Reflect.ownKeys(n)},getOwnPropertyDescriptor(n,s){return Reflect.getOwnPropertyDescriptor(n,s)}})},S=vt({},e=>{u.historyEnabled&&u.recordMutation({path:e.path,action:e.action,newValue:e.newValue,previousValue:e.previousValue,timestamp:Date.now()});});S.lock=()=>{u.locked=true,c("State is now locked. All modifications are blocked.");};S.unlock=()=>{u.locked=false,c("State is now unlocked. Modifications are allowed.");};G();a();J();$();w();var M=_e(),Ae=new Map;function Q(){let t=u.currentContext||""||"default";return Ae.has(t)||Ae.set(t,new Map),Ae.get(t)}var z=M!==null;function H(){let e=u.currentContext||"";return e?`${e}-`:"memorio_session_"}function Re(e){return !e||typeof e!="string"?(console.warn("[memorio session] key is empty or not a string - operation aborted"),""):e.length>512?(console.warn(`[memorio session] key "${e}" exceeds 512 chars - operation aborted`),""):H()+e}function hr(e){let t=z?M.getItem(e):Q().get(e);return t&&JSON.parse(t)}function vr(e,t){let r=JSON.stringify(t);z?M.setItem(e,r):Q().set(e,r);}function xr(e){if(z){if(M.getItem(e))return M.removeItem(e),true}else if(Q().has(e))return Q().delete(e),true;return false}var C=new Proxy({},{});Object.defineProperty(globalThis,"session",{value:C,enumerable:false,configurable:true});Object.defineProperties(C,{get:{value:e=>{if(!e)return console.warn("[memorio session] session.get() called with empty or null key - returning null"),null;try{return hr(Re(e))}catch(t){P(`Error parsing session item '${e}':${t}`);}return null}},set:{value:(e,t)=>{if(!e)return console.warn("[memorio session] session.set() called with empty or null key - write aborted"),false;let r=Re(e);if(!r)return false;if(typeof t=="function")return console.warn("[memorio session] functions are not storable - write aborted for key: "+e),P("It's not secure to session functions."),false;try{vr(r,t);}catch(o){return P(`Error setting session item '${e}': ${o}`),false}return true}},remove:{value:e=>{if(!e)return console.warn("[memorio session] session.remove() called with empty or null key - returning false"),false;let t=Re(e);if(!t)return false;try{return xr(t)}catch(r){P(`Error removing session item '${e}': ${r}`);}return false}},delete:{value:e=>C.remove(e)},removeAll:{value:()=>{if(z){let e=[];for(let t=0;t<M.length;t++){let r=M.key(t);r?.startsWith(H())&&e.push(r);}e.forEach(t=>M.removeItem(t));}else Q().clear();return true}},clearAll:{value:()=>(C.removeAll(),true)},quota:{value:async()=>[0,0]},size:{value:()=>{let e=0;return z?Object.keys(M).forEach(t=>{if(t.startsWith(H())){let r=M.getItem(t);r&&(e+=r.length);}}):Q().forEach(t=>{e+=t.length;}),e}},isPersistent:{get:()=>z},list:{value:()=>{let e={};try{if(z)for(let t=0;t<M.length;t++){let r=M.key(t);if(r?.startsWith(H())){let o=r.replace(H(),""),n=M.getItem(r);if(n!==null)try{e[o]=JSON.parse(n);}catch{e[o]=n;}}}else Q().forEach((t,r)=>{if(r.startsWith(H())){let o=r.replace(H(),"");try{e[o]=JSON.parse(t);}catch{e[o]=t;}}});}catch(t){P(`Error listing session items: ${t}`);}return e}}});Object.freeze(C);a();var j={},ue=new Proxy({},{get(e,t){let r=t;return r==="get"?o=>j[o]:r==="set"?(o,n)=>{j[o]=n;}:r==="remove"?o=>(delete j[o],true):r==="removeAll"?()=>(Object.keys(j).forEach(o=>delete j[o]),true):r==="clear"?()=>(Object.keys(j).forEach(o=>delete j[o]),true):r==="list"?()=>({...j}):j[r]},set(e,t,r){return j[t]=r,true},deleteProperty(e,t){return delete j[t],true}});Object.freeze(ue);T();_();a();w();var oo=(e,t=null,r=true)=>{let o=s=>typeof s=="string"?s:s&&typeof s=="object"&&s.__path?s.__path:null,n=o(e);if(!e&&!t){console.error("Observer Error: You need to setup observer correctly, Some parameters are missed!");return}if(!e&&t){console.error("Observer Error: You need to declare what state need to be monitored as string like 'state.test'.");return}if(n){let s=n.split(".");if(s[0]!=="state"&&s[0]!=="store"){console.error(`Observer Error: You need to declare 'state.' or 'store.'. The '${n}' string is incorrect!`);return}}if(e&&!t){let s=o(e);if(!s)return;globalThis.observer?.list?.[s]&&E.remove(s),c(`called: ${s}`);return}if(e&&t){let s=o(e);if(!s)return;if(typeof e!="string"&&!(e&&typeof e=="object")){console.error("Observer Error: name of state need to be a 'string' like 'state.test' or a direct state value");return}let i=Array.isArray(t)?t:[t];globalThis.observer?.list?.[s]&&E.remove(s),i.forEach(g=>{typeof g=="function"&&E.listen(s,g,r);});return}},pe=oo;Object.defineProperties(pe,{list:{get:()=>globalThis.events},remove:{value:e=>{e&&(E.remove(e),delete globalThis.events[e]);}},removeAll:{get:()=>{let e=globalThis.observer,t=e?.list;return t&&Object.keys(t).forEach(r=>{e?.remove?.(r);}),true}},has:{value:e=>!!globalThis.observer?.list?.[e]}});a();w();$();globalThis.useObserver||(globalThis.useObserver=null);Object.defineProperty(globalThis,"useObserver",{value:null,writable:true,enumerable:false,configurable:true});var ye=((e,t=[])=>{if(!t||typeof e!="function")return ()=>{};let r=[],o=Array.isArray(t)&&!t.__path?t:[t];try{return o.forEach(n=>{let s="";if(typeof n=="function"){let i=Se(n);i&&(s=i);}else typeof n=="object"&&n!==null&&(s=n.__path||(typeof n.toString=="function"&&n.toString()!=="[object Object]"?n.toString():""));if(s){s=s.replace(/^(\(\)\s*=>\s*)/,"").replace(/^globalThis\./,"").replace(/^state\./,"");let i=s.startsWith("store.")||s.startsWith("state.")?s:"state."+s;E.listen(i,()=>e()),r.push(i);}else {u.clearTrackedPaths(),u.tracking=!0;try{e();}catch{}u.tracking=!1,u.trackedPaths.forEach(i=>{r.includes(i)||(c(`useObserver: [Auto-Discovery] -> "${i}"`),E.listen(i,()=>e()),r.push(i));});}}),r.length>0?c(`useObserver: Monitoring ${r.length} paths.`):console.warn("useObserver: No paths resolved for monitoring. Check your dependencies!"),()=>{r.forEach(n=>{typeof E.remove=="function"&&(E.remove(n),c(`useObserver: Stopped monitoring "${n}"`));});}}catch(n){return c(`useObserver Error: ${n}`),()=>{}}});globalThis.useObserver=ye;Object.freeze(globalThis.useObserver);w();a();$();function no(){return u.debug===true}function Gt(){if(!globalThis.store)return {};let e={},t=globalThis.store;if(typeof t.list=="function")try{return t.list()}catch{}if(typeof t.get=="function"){for(let r of Object.keys(t))if(!["get","set","remove","delete","removeAll","clearAll","size","isPersistent","list"].includes(r))try{let o=t.get(r);o!=null&&(e[r]=o);}catch{}}return e}function Yt(){if(!globalThis.session)return {};let e={},t=globalThis.session;if(typeof t.list=="function")try{return t.list()}catch{}if(typeof t.get=="function"){for(let r of Object.keys(t))if(!["get","set","remove","delete","removeAll","clearAll","size","isPersistent","list"].includes(r))try{let o=t.get(r);o!=null&&(e[r]=o);}catch{}}return e}var so=()=>{if(no()){if(globalThis.state){let e=globalThis.state.list,t;typeof e=="function"?t=e():typeof e=="object"&&e!==null?t=e:t=globalThis.state,console.table(t);}if(globalThis.store&&console.table(Gt()),globalThis.session&&console.table(Yt()),globalThis.cache){let e=globalThis.cache.list,t;typeof e=="function"?t=e():typeof e=="object"&&e!==null?t=e:t=globalThis.cache,console.table(t);}}},io=()=>{let e=t=>{if(!t)return 0;if(typeof t.list=="function")try{let r=t.list();return Object.keys(r).length}catch{}return Object.keys(t).length};return {stateKeys:e(globalThis.state),storeKeys:e(globalThis.store),sessionKeys:e(globalThis.session),cacheKeys:e(globalThis.cache),idbDatabases:0,sqliteDbCount:typeof globalThis.sqlite?.db?.list=="function"?globalThis.sqlite.db.list().length:(globalThis.sqlbases||[]).length,lastUpdate:new Date().toISOString()}},se=e=>{globalThis[e]&&typeof globalThis[e].clear=="function"?globalThis[e].clear():console.error(`Module ${e} not found or does not support clear()`);},ao=()=>{se("state"),se("store"),se("session"),se("cache");},lo=()=>{let e=()=>{if(globalThis.state)try{return typeof globalThis.state.list=="function"?globalThis.state.list():globalThis.state}catch{return}},t=()=>Gt(),r=()=>Yt(),o=()=>{if(globalThis.cache)try{return typeof globalThis.cache.list=="function"?globalThis.cache.list():globalThis.cache}catch{return}},n={state:e(),store:t(),session:r(),cache:o(),exportedAt:new Date().toISOString()};return JSON.stringify(n,null,2)},co=e=>{try{let t=JSON.parse(e);t.state&&Object.entries(t.state).forEach(([r,o])=>{globalThis.state&&r!=="list"&&r!=="remove"&&r!=="removeAll"&&(globalThis.state[r]=o);}),t.store&&globalThis.store&&typeof globalThis.store.set=="function"&&Object.entries(t.store).forEach(([r,o])=>{globalThis.store.set(r,o);}),t.session&&globalThis.session&&typeof globalThis.session.set=="function"&&Object.entries(t.session).forEach(([r,o])=>{globalThis.session.set(r,o);}),t.cache&&globalThis.cache&&Object.entries(t.cache).forEach(([r,o])=>{globalThis.cache&&r!=="get"&&r!=="set"&&r!=="remove"&&r!=="clear"&&(globalThis.cache[r]=o);});}catch(t){console.error("%c\u2717 Import failed:","color: #F44336",t);}},uo=(e,t)=>{if(!globalThis[e]){console.error(`Module ${e} not found`);return}let r=globalThis[e],o=r[t];if(console.debug(`\u{1F441} Watching ${e}.${t} (initial: ${JSON.stringify(o)})`),e==="state"&&globalThis.memorio?.dispatch){let n=s=>{s.detail?.name?.includes(t)&&console.debug(`\u{1F441} Change: ${e}.${t} =`,s.detail.value);};r.addEventListener?.("memorio-change",n);}},mo=()=>{console.debug(`
|
|
5
|
-
|
|
4
|
+
var __defProp = Object.defineProperty;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
7
|
+
var __esm = (fn, res) => function __init() {
|
|
8
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
9
|
+
};
|
|
10
|
+
var init_esm_shims = __esm({
|
|
11
|
+
"node_modules/tsup/assets/esm_shims.js"() {
|
|
12
|
+
}
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
// core/env.ts
|
|
16
|
+
var DEV, PROD;
|
|
17
|
+
var init_env = __esm({
|
|
18
|
+
"core/env.ts"() {
|
|
19
|
+
init_esm_shims();
|
|
20
|
+
DEV = typeof process !== "undefined" ? false : true;
|
|
21
|
+
PROD = !DEV;
|
|
22
|
+
}
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
// core/internal.ts
|
|
26
|
+
var INTERNAL_KEY, state, internal, protect, propertyName, internal_default;
|
|
27
|
+
var init_internal = __esm({
|
|
28
|
+
"core/internal.ts"() {
|
|
29
|
+
init_esm_shims();
|
|
30
|
+
INTERNAL_KEY = "__memorio_internal_state";
|
|
31
|
+
state = globalThis[INTERNAL_KEY] || {
|
|
32
|
+
debug: false,
|
|
33
|
+
tracking: false,
|
|
34
|
+
trackedPaths: /* @__PURE__ */ new Set(),
|
|
35
|
+
locked: false,
|
|
36
|
+
lastAccessedPath: "",
|
|
37
|
+
stateVersion: 0,
|
|
38
|
+
currentContext: null,
|
|
39
|
+
mutations: [],
|
|
40
|
+
undoStack: [],
|
|
41
|
+
redoStack: [],
|
|
42
|
+
maxHistory: 100,
|
|
43
|
+
historyEnabled: false
|
|
44
|
+
};
|
|
45
|
+
if (!globalThis[INTERNAL_KEY]) {
|
|
46
|
+
globalThis[INTERNAL_KEY] = state;
|
|
47
|
+
}
|
|
48
|
+
internal = {
|
|
49
|
+
get debug() {
|
|
50
|
+
return state.debug;
|
|
51
|
+
},
|
|
52
|
+
set debug(value) {
|
|
53
|
+
state.debug = value;
|
|
54
|
+
},
|
|
55
|
+
get tracking() {
|
|
56
|
+
return state.tracking;
|
|
57
|
+
},
|
|
58
|
+
set tracking(value) {
|
|
59
|
+
state.tracking = value;
|
|
60
|
+
},
|
|
61
|
+
get trackedPaths() {
|
|
62
|
+
return state.trackedPaths;
|
|
63
|
+
},
|
|
64
|
+
clearTrackedPaths() {
|
|
65
|
+
state.trackedPaths.clear();
|
|
66
|
+
},
|
|
67
|
+
get locked() {
|
|
68
|
+
return state.locked;
|
|
69
|
+
},
|
|
70
|
+
set locked(value) {
|
|
71
|
+
state.locked = value;
|
|
72
|
+
},
|
|
73
|
+
get lastAccessedPath() {
|
|
74
|
+
return state.lastAccessedPath;
|
|
75
|
+
},
|
|
76
|
+
set lastAccessedPath(value) {
|
|
77
|
+
state.lastAccessedPath = value;
|
|
78
|
+
},
|
|
79
|
+
get stateVersion() {
|
|
80
|
+
return state.stateVersion;
|
|
81
|
+
},
|
|
82
|
+
bumpStateVersion() {
|
|
83
|
+
state.stateVersion = (state.stateVersion || 0) + 1;
|
|
84
|
+
return state.stateVersion;
|
|
85
|
+
},
|
|
86
|
+
get currentContext() {
|
|
87
|
+
return state.currentContext;
|
|
88
|
+
},
|
|
89
|
+
set currentContext(value) {
|
|
90
|
+
state.currentContext = value;
|
|
91
|
+
},
|
|
92
|
+
get mutations() {
|
|
93
|
+
return state.mutations;
|
|
94
|
+
},
|
|
95
|
+
get undoStack() {
|
|
96
|
+
return state.undoStack;
|
|
97
|
+
},
|
|
98
|
+
get redoStack() {
|
|
99
|
+
return state.redoStack;
|
|
100
|
+
},
|
|
101
|
+
get maxHistory() {
|
|
102
|
+
return state.maxHistory;
|
|
103
|
+
},
|
|
104
|
+
set maxHistory(value) {
|
|
105
|
+
state.maxHistory = value;
|
|
106
|
+
},
|
|
107
|
+
get historyEnabled() {
|
|
108
|
+
return state.historyEnabled;
|
|
109
|
+
},
|
|
110
|
+
set historyEnabled(value) {
|
|
111
|
+
state.historyEnabled = value;
|
|
112
|
+
},
|
|
113
|
+
/**
|
|
114
|
+
* Records a mutation in the trace log and undo/redo stacks.
|
|
115
|
+
* Called by the state proxy's callback.
|
|
116
|
+
*/
|
|
117
|
+
recordMutation(record) {
|
|
118
|
+
if (!state.historyEnabled) return;
|
|
119
|
+
state.mutations.push(record);
|
|
120
|
+
if (state.mutations.length > state.maxHistory) {
|
|
121
|
+
state.mutations.shift();
|
|
122
|
+
}
|
|
123
|
+
state.undoStack.push(record);
|
|
124
|
+
if (state.undoStack.length > state.maxHistory) {
|
|
125
|
+
state.undoStack.shift();
|
|
126
|
+
}
|
|
127
|
+
state.redoStack = [];
|
|
128
|
+
},
|
|
129
|
+
/**
|
|
130
|
+
* Pops a record from the undo stack and pushes to redo stack.
|
|
131
|
+
* Returns the record or undefined if empty.
|
|
132
|
+
*/
|
|
133
|
+
popUndo() {
|
|
134
|
+
const record = state.undoStack.pop();
|
|
135
|
+
if (record) {
|
|
136
|
+
state.redoStack.push(record);
|
|
137
|
+
}
|
|
138
|
+
return record;
|
|
139
|
+
},
|
|
140
|
+
/**
|
|
141
|
+
* Pops a record from the redo stack and pushes to undo stack.
|
|
142
|
+
* Returns the record or undefined if empty.
|
|
143
|
+
*/
|
|
144
|
+
popRedo() {
|
|
145
|
+
const record = state.redoStack.pop();
|
|
146
|
+
if (record) {
|
|
147
|
+
state.undoStack.push(record);
|
|
148
|
+
}
|
|
149
|
+
return record;
|
|
150
|
+
},
|
|
151
|
+
canUndo() {
|
|
152
|
+
return state.undoStack.length > 0;
|
|
153
|
+
},
|
|
154
|
+
canRedo() {
|
|
155
|
+
return state.redoStack.length > 0;
|
|
156
|
+
},
|
|
157
|
+
clearHistory() {
|
|
158
|
+
state.mutations = [];
|
|
159
|
+
state.undoStack = [];
|
|
160
|
+
state.redoStack = [];
|
|
161
|
+
},
|
|
162
|
+
clearRedo() {
|
|
163
|
+
state.redoStack = [];
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
protect = [
|
|
167
|
+
"list",
|
|
168
|
+
"state",
|
|
169
|
+
"store",
|
|
170
|
+
"idb",
|
|
171
|
+
"sqlite",
|
|
172
|
+
"observer",
|
|
173
|
+
"useObserver",
|
|
174
|
+
"remove",
|
|
175
|
+
"removeAll",
|
|
176
|
+
// Platform-related protected keys
|
|
177
|
+
"_platform",
|
|
178
|
+
"_capabilities",
|
|
179
|
+
"_sessionId"
|
|
180
|
+
];
|
|
181
|
+
propertyName = /* @__PURE__ */ __name((container, object) => {
|
|
182
|
+
const target = object !== void 0 ? object : container;
|
|
183
|
+
return String(target).replace("() => ", "");
|
|
184
|
+
}, "propertyName");
|
|
185
|
+
internal_default = internal;
|
|
186
|
+
}
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
// functions/message/index.ts
|
|
190
|
+
var message, message_default;
|
|
191
|
+
var init_message = __esm({
|
|
192
|
+
"functions/message/index.ts"() {
|
|
193
|
+
init_esm_shims();
|
|
194
|
+
init_internal();
|
|
195
|
+
init_env();
|
|
196
|
+
message = /* @__PURE__ */ __name((...args) => {
|
|
197
|
+
if (DEV && internal_default.debug === true) {
|
|
198
|
+
console.debug(...args);
|
|
199
|
+
}
|
|
200
|
+
}, "message");
|
|
201
|
+
message_default = message;
|
|
202
|
+
}
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
// core/platform.ts
|
|
206
|
+
function generateSessionId() {
|
|
207
|
+
const anyGlobal = globalThis;
|
|
208
|
+
if (typeof anyGlobal.crypto !== "undefined" && anyGlobal.crypto.randomUUID) {
|
|
209
|
+
return anyGlobal.crypto.randomUUID();
|
|
210
|
+
}
|
|
211
|
+
if (typeof anyGlobal.crypto !== "undefined" && anyGlobal.crypto.getRandomValues) {
|
|
212
|
+
const array = new Uint8Array(16);
|
|
213
|
+
anyGlobal.crypto.getRandomValues(array);
|
|
214
|
+
return Array.from(array, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
215
|
+
}
|
|
216
|
+
return `session_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`;
|
|
217
|
+
}
|
|
218
|
+
function detectPlatform() {
|
|
219
|
+
const globalAny = globalThis;
|
|
220
|
+
if (globalAny.Deno && globalAny.Deno.version) {
|
|
221
|
+
return "deno";
|
|
222
|
+
}
|
|
223
|
+
if (typeof process !== "undefined" && process.versions && process.versions.node) {
|
|
224
|
+
return "node";
|
|
225
|
+
}
|
|
226
|
+
if (typeof globalThis !== "undefined" && typeof globalThis.ServiceWorkerGlobalScope !== "undefined") {
|
|
227
|
+
return "edge";
|
|
228
|
+
}
|
|
229
|
+
if (typeof window !== "undefined" && typeof document !== "undefined") {
|
|
230
|
+
return "browser";
|
|
231
|
+
}
|
|
232
|
+
return "unknown";
|
|
233
|
+
}
|
|
234
|
+
function isBrowser() {
|
|
235
|
+
const platform = detectPlatform();
|
|
236
|
+
return platform === "browser";
|
|
237
|
+
}
|
|
238
|
+
function isNode() {
|
|
239
|
+
const platform = detectPlatform();
|
|
240
|
+
return platform === "node";
|
|
241
|
+
}
|
|
242
|
+
function isDeno() {
|
|
243
|
+
const platform = detectPlatform();
|
|
244
|
+
return platform === "deno";
|
|
245
|
+
}
|
|
246
|
+
function isEdge() {
|
|
247
|
+
const platform = detectPlatform();
|
|
248
|
+
return platform === "edge";
|
|
249
|
+
}
|
|
250
|
+
function getSessionStorage() {
|
|
251
|
+
try {
|
|
252
|
+
if (typeof sessionStorage !== "undefined") {
|
|
253
|
+
const testKey = "__memorio_test__";
|
|
254
|
+
sessionStorage.setItem(testKey, "1");
|
|
255
|
+
sessionStorage.removeItem(testKey);
|
|
256
|
+
return sessionStorage;
|
|
257
|
+
}
|
|
258
|
+
} catch (_) {
|
|
259
|
+
}
|
|
260
|
+
return null;
|
|
261
|
+
}
|
|
262
|
+
function getLocalStorage() {
|
|
263
|
+
try {
|
|
264
|
+
if (typeof localStorage !== "undefined") {
|
|
265
|
+
const testKey = "__memorio_test__";
|
|
266
|
+
localStorage.setItem(testKey, "1");
|
|
267
|
+
localStorage.removeItem(testKey);
|
|
268
|
+
return localStorage;
|
|
269
|
+
}
|
|
270
|
+
} catch (_) {
|
|
271
|
+
}
|
|
272
|
+
return null;
|
|
273
|
+
}
|
|
274
|
+
function hasIndexedDB() {
|
|
275
|
+
if (typeof indexedDB !== "undefined") {
|
|
276
|
+
return true;
|
|
277
|
+
}
|
|
278
|
+
return false;
|
|
279
|
+
}
|
|
280
|
+
function hasSqlJs() {
|
|
281
|
+
const anyGlobal = globalThis;
|
|
282
|
+
if (typeof anyGlobal.WebAssembly === "undefined" || typeof anyGlobal.WebAssembly.instantiate !== "function") {
|
|
283
|
+
return false;
|
|
284
|
+
}
|
|
285
|
+
return typeof anyGlobal.window !== "undefined";
|
|
286
|
+
}
|
|
287
|
+
function hasDispatchEvent() {
|
|
288
|
+
return typeof globalThis.dispatchEvent === "function";
|
|
289
|
+
}
|
|
290
|
+
function getCapabilities() {
|
|
291
|
+
const platform = detectPlatform();
|
|
292
|
+
const isSecure = typeof globalThis.isSecureContext !== "undefined" ? globalThis.isSecureContext : platform === "browser";
|
|
293
|
+
return {
|
|
294
|
+
platform,
|
|
295
|
+
hasSessionStorage: getSessionStorage() !== null,
|
|
296
|
+
hasLocalStorage: getLocalStorage() !== null,
|
|
297
|
+
hasIndexedDB: hasIndexedDB(),
|
|
298
|
+
hasSqlJs: hasSqlJs(),
|
|
299
|
+
hasDispatchEvent: hasDispatchEvent(),
|
|
300
|
+
hasNavigator: typeof navigator !== "undefined",
|
|
301
|
+
hasProcess: typeof process !== "undefined",
|
|
302
|
+
isSecureContext: isSecure,
|
|
303
|
+
sessionId: generateSessionId()
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
function initializePlatform() {
|
|
307
|
+
const capabilities = getCapabilities();
|
|
308
|
+
const anyGlobal = globalThis;
|
|
309
|
+
if (!capabilities.hasDispatchEvent) {
|
|
310
|
+
anyGlobal.dispatchEvent = function(_event) {
|
|
311
|
+
return true;
|
|
312
|
+
};
|
|
313
|
+
if (typeof CustomEvent === "undefined") {
|
|
314
|
+
anyGlobal.CustomEvent = class CustomEvent {
|
|
315
|
+
static {
|
|
316
|
+
__name(this, "CustomEvent");
|
|
317
|
+
}
|
|
318
|
+
type;
|
|
319
|
+
detail;
|
|
320
|
+
constructor(type, detail = {}) {
|
|
321
|
+
this.type = type;
|
|
322
|
+
this.detail = detail;
|
|
323
|
+
}
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
if (typeof anyGlobal.addEventListener !== "function") {
|
|
328
|
+
anyGlobal.addEventListener = function(type, listener) {
|
|
329
|
+
if (!_eventListenerStorage.has(type)) {
|
|
330
|
+
_eventListenerStorage.set(type, []);
|
|
331
|
+
}
|
|
332
|
+
_eventListenerStorage.get(type).push(listener);
|
|
333
|
+
};
|
|
334
|
+
anyGlobal.removeEventListener = function(type, listener) {
|
|
335
|
+
const listeners = _eventListenerStorage.get(type);
|
|
336
|
+
if (listeners) {
|
|
337
|
+
const index = listeners.indexOf(listener);
|
|
338
|
+
if (index > -1) {
|
|
339
|
+
listeners.splice(index, 1);
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
};
|
|
343
|
+
anyGlobal.dispatchEvent = function(event) {
|
|
344
|
+
const listeners = _eventListenerStorage.get(event.type);
|
|
345
|
+
if (listeners) {
|
|
346
|
+
listeners.forEach((listener) => {
|
|
347
|
+
try {
|
|
348
|
+
listener(event);
|
|
349
|
+
} catch (e) {
|
|
350
|
+
console.error("Event listener error:", e);
|
|
351
|
+
}
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
return true;
|
|
355
|
+
};
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
function createContext(name) {
|
|
359
|
+
const contextId = name || `context_${generateSessionId()}`;
|
|
360
|
+
setCurrentContext(contextId);
|
|
361
|
+
const contextStorage = {
|
|
362
|
+
state: {},
|
|
363
|
+
store: /* @__PURE__ */ new Map(),
|
|
364
|
+
session: /* @__PURE__ */ new Map(),
|
|
365
|
+
cache: /* @__PURE__ */ new Map()
|
|
366
|
+
};
|
|
367
|
+
_contexts.set(contextId, contextStorage);
|
|
368
|
+
return {
|
|
369
|
+
id: contextId,
|
|
370
|
+
state: contextStorage.state,
|
|
371
|
+
store: {
|
|
372
|
+
get: /* @__PURE__ */ __name((key) => {
|
|
373
|
+
const data = contextStorage.store.get(key);
|
|
374
|
+
return data ? JSON.parse(data) : null;
|
|
375
|
+
}, "get"),
|
|
376
|
+
set: /* @__PURE__ */ __name((key, value) => {
|
|
377
|
+
contextStorage.store.set(key, JSON.stringify(value));
|
|
378
|
+
}, "set"),
|
|
379
|
+
remove: /* @__PURE__ */ __name((key) => contextStorage.store.delete(key), "remove"),
|
|
380
|
+
removeAll: /* @__PURE__ */ __name(() => contextStorage.store.clear(), "removeAll"),
|
|
381
|
+
clearAll: /* @__PURE__ */ __name(() => contextStorage.store.clear(), "clearAll"),
|
|
382
|
+
size: /* @__PURE__ */ __name(() => contextStorage.store.size, "size"),
|
|
383
|
+
isPersistent: false
|
|
384
|
+
},
|
|
385
|
+
session: {
|
|
386
|
+
get: /* @__PURE__ */ __name((key) => {
|
|
387
|
+
const data = contextStorage.session.get(key);
|
|
388
|
+
return data ? JSON.parse(data) : null;
|
|
389
|
+
}, "get"),
|
|
390
|
+
set: /* @__PURE__ */ __name((key, value) => {
|
|
391
|
+
contextStorage.session.set(key, JSON.stringify(value));
|
|
392
|
+
}, "set"),
|
|
393
|
+
remove: /* @__PURE__ */ __name((key) => contextStorage.session.delete(key), "remove"),
|
|
394
|
+
removeAll: /* @__PURE__ */ __name(() => contextStorage.session.clear(), "removeAll"),
|
|
395
|
+
clearAll: /* @__PURE__ */ __name(() => contextStorage.session.clear(), "clearAll"),
|
|
396
|
+
size: /* @__PURE__ */ __name(() => contextStorage.session.size, "size"),
|
|
397
|
+
isPersistent: false
|
|
398
|
+
},
|
|
399
|
+
cache: {
|
|
400
|
+
get: /* @__PURE__ */ __name((key) => contextStorage.cache.get(key), "get"),
|
|
401
|
+
set: /* @__PURE__ */ __name((key, value) => contextStorage.cache.set(key, value), "set"),
|
|
402
|
+
remove: /* @__PURE__ */ __name((key) => contextStorage.cache.delete(key), "remove"),
|
|
403
|
+
removeAll: /* @__PURE__ */ __name(() => contextStorage.cache.clear(), "removeAll"),
|
|
404
|
+
clear: /* @__PURE__ */ __name(() => contextStorage.cache.clear(), "clear")
|
|
405
|
+
}
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
function listContexts() {
|
|
409
|
+
return Array.from(_contexts.keys());
|
|
410
|
+
}
|
|
411
|
+
function deleteContext(id) {
|
|
412
|
+
return _contexts.delete(id);
|
|
413
|
+
}
|
|
414
|
+
function setCurrentContext(id) {
|
|
415
|
+
internal_default.currentContext = id;
|
|
416
|
+
}
|
|
417
|
+
var _eventListenerStorage, CONTEXTS_KEY, _contexts;
|
|
418
|
+
var init_platform = __esm({
|
|
419
|
+
"core/platform.ts"() {
|
|
420
|
+
init_esm_shims();
|
|
421
|
+
init_internal();
|
|
422
|
+
__name(generateSessionId, "generateSessionId");
|
|
423
|
+
__name(detectPlatform, "detectPlatform");
|
|
424
|
+
__name(isBrowser, "isBrowser");
|
|
425
|
+
__name(isNode, "isNode");
|
|
426
|
+
__name(isDeno, "isDeno");
|
|
427
|
+
__name(isEdge, "isEdge");
|
|
428
|
+
__name(getSessionStorage, "getSessionStorage");
|
|
429
|
+
__name(getLocalStorage, "getLocalStorage");
|
|
430
|
+
__name(hasIndexedDB, "hasIndexedDB");
|
|
431
|
+
__name(hasSqlJs, "hasSqlJs");
|
|
432
|
+
__name(hasDispatchEvent, "hasDispatchEvent");
|
|
433
|
+
__name(getCapabilities, "getCapabilities");
|
|
434
|
+
_eventListenerStorage = /* @__PURE__ */ new Map();
|
|
435
|
+
__name(initializePlatform, "initializePlatform");
|
|
436
|
+
CONTEXTS_KEY = "__memorio_contexts__";
|
|
437
|
+
_contexts = globalThis[CONTEXTS_KEY] || /* @__PURE__ */ new Map();
|
|
438
|
+
if (!globalThis[CONTEXTS_KEY]) {
|
|
439
|
+
globalThis[CONTEXTS_KEY] = _contexts;
|
|
440
|
+
}
|
|
441
|
+
__name(createContext, "createContext");
|
|
442
|
+
__name(listContexts, "listContexts");
|
|
443
|
+
__name(deleteContext, "deleteContext");
|
|
444
|
+
__name(setCurrentContext, "setCurrentContext");
|
|
445
|
+
}
|
|
446
|
+
});
|
|
447
|
+
|
|
448
|
+
// functions/store/index.ts
|
|
449
|
+
function _getFallbackStorage() {
|
|
450
|
+
const contextName = internal_default.currentContext || "";
|
|
451
|
+
const key = contextName || "default";
|
|
452
|
+
if (!_fallbackStorageByContext.has(key)) {
|
|
453
|
+
_fallbackStorageByContext.set(key, /* @__PURE__ */ new Map());
|
|
454
|
+
}
|
|
455
|
+
return _fallbackStorageByContext.get(key);
|
|
456
|
+
}
|
|
457
|
+
function _getPrefix() {
|
|
458
|
+
const contextName = internal_default.currentContext || "";
|
|
459
|
+
return contextName ? `${contextName}-` : `memorio_store_`;
|
|
460
|
+
}
|
|
461
|
+
function _prefixKey(name) {
|
|
462
|
+
if (!name || typeof name !== "string") {
|
|
463
|
+
console.warn(`[memorio store] key is empty or not a string - operation aborted`);
|
|
464
|
+
return "";
|
|
465
|
+
}
|
|
466
|
+
if (name.length > 512) {
|
|
467
|
+
console.warn(`[memorio store] key "${name}" exceeds 512 chars - operation aborted`);
|
|
468
|
+
return "";
|
|
469
|
+
}
|
|
470
|
+
return _getPrefix() + name;
|
|
471
|
+
}
|
|
472
|
+
function _read(prefixedName) {
|
|
473
|
+
const raw = _hasStorage ? _localStorage.getItem(prefixedName) : _getFallbackStorage().get(prefixedName);
|
|
474
|
+
return raw ? JSON.parse(raw) : raw;
|
|
475
|
+
}
|
|
476
|
+
function _write(prefixedName, value) {
|
|
477
|
+
const json = JSON.stringify(value);
|
|
478
|
+
if (_hasStorage) _localStorage.setItem(prefixedName, json);
|
|
479
|
+
else _getFallbackStorage().set(prefixedName, json);
|
|
480
|
+
}
|
|
481
|
+
function _remove(prefixedName) {
|
|
482
|
+
if (_hasStorage) {
|
|
483
|
+
if (_localStorage.getItem(prefixedName)) {
|
|
484
|
+
_localStorage.removeItem(prefixedName);
|
|
485
|
+
return true;
|
|
486
|
+
}
|
|
487
|
+
} else if (_getFallbackStorage().has(prefixedName)) {
|
|
488
|
+
_getFallbackStorage().delete(prefixedName);
|
|
489
|
+
return true;
|
|
490
|
+
}
|
|
491
|
+
return false;
|
|
492
|
+
}
|
|
493
|
+
var _localStorage, _fallbackStorageByContext, _hasStorage, STORE_INSTANCE_KEY, store;
|
|
494
|
+
var init_store = __esm({
|
|
495
|
+
"functions/store/index.ts"() {
|
|
496
|
+
init_esm_shims();
|
|
497
|
+
init_platform();
|
|
498
|
+
init_internal();
|
|
499
|
+
init_message();
|
|
500
|
+
_localStorage = getLocalStorage();
|
|
501
|
+
_fallbackStorageByContext = /* @__PURE__ */ new Map();
|
|
502
|
+
__name(_getFallbackStorage, "_getFallbackStorage");
|
|
503
|
+
_hasStorage = _localStorage !== null;
|
|
504
|
+
__name(_getPrefix, "_getPrefix");
|
|
505
|
+
__name(_prefixKey, "_prefixKey");
|
|
506
|
+
__name(_read, "_read");
|
|
507
|
+
__name(_write, "_write");
|
|
508
|
+
__name(_remove, "_remove");
|
|
509
|
+
STORE_INSTANCE_KEY = "__memorio_store_instance__";
|
|
510
|
+
if (globalThis[STORE_INSTANCE_KEY]) {
|
|
511
|
+
store = globalThis[STORE_INSTANCE_KEY];
|
|
512
|
+
} else {
|
|
513
|
+
store = new Proxy({}, {});
|
|
514
|
+
Object.defineProperties(
|
|
515
|
+
store,
|
|
516
|
+
{
|
|
517
|
+
/**
|
|
518
|
+
* Gets a value from storage.
|
|
519
|
+
* @param name The key to retrieve.
|
|
520
|
+
* @returns The parsed value or null if not found.
|
|
521
|
+
*/
|
|
522
|
+
get: {
|
|
523
|
+
value: /* @__PURE__ */ __name((name) => {
|
|
524
|
+
if (!name) {
|
|
525
|
+
console.warn("[memorio store] store.get() called with empty or null key - returning null");
|
|
526
|
+
return null;
|
|
527
|
+
}
|
|
528
|
+
try {
|
|
529
|
+
return _read(_prefixKey(name));
|
|
530
|
+
} catch (err) {
|
|
531
|
+
message(`Error parsing store item '${name}': ${err}`);
|
|
532
|
+
}
|
|
533
|
+
return null;
|
|
534
|
+
}, "value")
|
|
535
|
+
},
|
|
536
|
+
getMultiple: {
|
|
537
|
+
value: /* @__PURE__ */ __name((keys) => {
|
|
538
|
+
const result = {};
|
|
539
|
+
for (const key of keys) {
|
|
540
|
+
try {
|
|
541
|
+
const item = store.get(key);
|
|
542
|
+
if (item) result[key] = item;
|
|
543
|
+
} catch (err) {
|
|
544
|
+
console.debug(`[memorio store] getMultiple error for key "${key}":`, err);
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
return result;
|
|
548
|
+
}, "value")
|
|
549
|
+
},
|
|
550
|
+
/**
|
|
551
|
+
* Sets a value in storage.
|
|
552
|
+
* @param name The key to set.
|
|
553
|
+
* @param value The value to store (objects, arrays, primitives).
|
|
554
|
+
* @returns true if written, false if the key was rejected.
|
|
555
|
+
*/
|
|
556
|
+
set: {
|
|
557
|
+
value: /* @__PURE__ */ __name((name, value) => {
|
|
558
|
+
if (!name) {
|
|
559
|
+
console.warn("[memorio store] store.set() called with empty or null key - write aborted");
|
|
560
|
+
return false;
|
|
561
|
+
}
|
|
562
|
+
const prefixedName = _prefixKey(name);
|
|
563
|
+
if (!prefixedName) return false;
|
|
564
|
+
if (typeof value === "function") {
|
|
565
|
+
console.warn("[memorio store] functions are not storable - write aborted for key: " + name);
|
|
566
|
+
message("Storing functions is not secure and is blocked for safety.");
|
|
567
|
+
return false;
|
|
568
|
+
}
|
|
569
|
+
try {
|
|
570
|
+
_write(prefixedName, value);
|
|
571
|
+
} catch (err) {
|
|
572
|
+
message(`Error setting store item '${name}': ${err}`);
|
|
573
|
+
return false;
|
|
574
|
+
}
|
|
575
|
+
return true;
|
|
576
|
+
}, "value")
|
|
577
|
+
},
|
|
578
|
+
/**
|
|
579
|
+
* Removes a value from storage.
|
|
580
|
+
* @param name The key to remove.
|
|
581
|
+
* @returns True if removed, false if not found.
|
|
582
|
+
*/
|
|
583
|
+
remove: {
|
|
584
|
+
value: /* @__PURE__ */ __name((name) => {
|
|
585
|
+
if (!name) {
|
|
586
|
+
console.debug("[memorio store] store.remove() called with empty or null key - returning false");
|
|
587
|
+
return false;
|
|
588
|
+
}
|
|
589
|
+
const prefixedName = _prefixKey(name);
|
|
590
|
+
if (!prefixedName) return false;
|
|
591
|
+
try {
|
|
592
|
+
return _remove(prefixedName);
|
|
593
|
+
} catch (err) {
|
|
594
|
+
message(`Error removing store item '${name}': ${err}`);
|
|
595
|
+
}
|
|
596
|
+
return false;
|
|
597
|
+
}, "value")
|
|
598
|
+
},
|
|
599
|
+
/**
|
|
600
|
+
* Alias for remove.
|
|
601
|
+
* @param name The key to delete.
|
|
602
|
+
*/
|
|
603
|
+
delete: {
|
|
604
|
+
value: /* @__PURE__ */ __name((name) => {
|
|
605
|
+
return store.remove(name);
|
|
606
|
+
}, "value")
|
|
607
|
+
},
|
|
608
|
+
/**
|
|
609
|
+
* Clears all memorio items from storage.
|
|
610
|
+
*/
|
|
611
|
+
removeAll: {
|
|
612
|
+
value: /* @__PURE__ */ __name(() => {
|
|
613
|
+
if (_hasStorage) {
|
|
614
|
+
const keysToRemove = [];
|
|
615
|
+
for (let i = 0; i < _localStorage.length; i++) {
|
|
616
|
+
const key = _localStorage.key(i);
|
|
617
|
+
if (key?.startsWith(_getPrefix())) keysToRemove.push(key);
|
|
618
|
+
}
|
|
619
|
+
keysToRemove.forEach((key) => _localStorage.removeItem(key));
|
|
620
|
+
} else {
|
|
621
|
+
_getFallbackStorage().clear();
|
|
622
|
+
}
|
|
623
|
+
return true;
|
|
624
|
+
}, "value")
|
|
625
|
+
},
|
|
626
|
+
/**
|
|
627
|
+
* Alias for removeAll.
|
|
628
|
+
*/
|
|
629
|
+
clearAll: {
|
|
630
|
+
value: /* @__PURE__ */ __name(() => {
|
|
631
|
+
store.removeAll();
|
|
632
|
+
return true;
|
|
633
|
+
}, "value")
|
|
634
|
+
},
|
|
635
|
+
/**
|
|
636
|
+
* Estimates storage quota usage.
|
|
637
|
+
* @returns Promise with [usage, quota].
|
|
638
|
+
*/
|
|
639
|
+
quota: {
|
|
640
|
+
value: /* @__PURE__ */ __name(async () => {
|
|
641
|
+
return [0, 0];
|
|
642
|
+
}, "value")
|
|
643
|
+
},
|
|
644
|
+
/**
|
|
645
|
+
* Calculates total size of all memorio items (characters).
|
|
646
|
+
*/
|
|
647
|
+
size: {
|
|
648
|
+
value: /* @__PURE__ */ __name(() => {
|
|
649
|
+
let totalSize = 0;
|
|
650
|
+
if (_hasStorage) {
|
|
651
|
+
Object.keys(_localStorage).forEach((key) => {
|
|
652
|
+
if (key.startsWith(_getPrefix())) {
|
|
653
|
+
const item = _localStorage.getItem(key);
|
|
654
|
+
if (item) totalSize += item.length;
|
|
655
|
+
}
|
|
656
|
+
});
|
|
657
|
+
} else {
|
|
658
|
+
_getFallbackStorage().forEach((value) => {
|
|
659
|
+
totalSize += value.length;
|
|
660
|
+
});
|
|
661
|
+
}
|
|
662
|
+
return totalSize;
|
|
663
|
+
}, "value")
|
|
664
|
+
},
|
|
665
|
+
/**
|
|
666
|
+
* Check if using real localStorage or fallback
|
|
667
|
+
*/
|
|
668
|
+
isPersistent: {
|
|
669
|
+
get: /* @__PURE__ */ __name(() => _hasStorage, "get")
|
|
670
|
+
},
|
|
671
|
+
/**
|
|
672
|
+
* Get a list of all memorio store items.
|
|
673
|
+
*/
|
|
674
|
+
list: {
|
|
675
|
+
value: /* @__PURE__ */ __name(() => {
|
|
676
|
+
const result = {};
|
|
677
|
+
try {
|
|
678
|
+
if (_hasStorage) {
|
|
679
|
+
for (let i = 0; i < _localStorage.length; i++) {
|
|
680
|
+
const key = _localStorage.key(i);
|
|
681
|
+
if (key?.startsWith(_getPrefix())) {
|
|
682
|
+
const cleanKey = key.replace(_getPrefix(), "");
|
|
683
|
+
const item = _localStorage.getItem(key);
|
|
684
|
+
if (item !== null) {
|
|
685
|
+
try {
|
|
686
|
+
result[cleanKey] = JSON.parse(item);
|
|
687
|
+
} catch {
|
|
688
|
+
result[cleanKey] = item;
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
} else {
|
|
694
|
+
_getFallbackStorage().forEach((value, key) => {
|
|
695
|
+
if (key.startsWith(_getPrefix())) {
|
|
696
|
+
const cleanKey = key.replace(_getPrefix(), "");
|
|
697
|
+
try {
|
|
698
|
+
result[cleanKey] = JSON.parse(value);
|
|
699
|
+
} catch {
|
|
700
|
+
result[cleanKey] = value;
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
});
|
|
704
|
+
}
|
|
705
|
+
} catch (err) {
|
|
706
|
+
message(`Error listing store items: ${err}`);
|
|
707
|
+
}
|
|
708
|
+
return result;
|
|
709
|
+
}, "value")
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
);
|
|
713
|
+
Object.freeze(store);
|
|
714
|
+
globalThis[STORE_INSTANCE_KEY] = store;
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
});
|
|
718
|
+
|
|
719
|
+
// functions/idb/tools/db.create.ts
|
|
720
|
+
var db_create_exports = {};
|
|
721
|
+
var init_db_create = __esm({
|
|
722
|
+
"functions/idb/tools/db.create.ts"() {
|
|
723
|
+
init_esm_shims();
|
|
724
|
+
init_idb();
|
|
725
|
+
init_message();
|
|
726
|
+
idb.db.create = (dbName, ver = 1) => {
|
|
727
|
+
return new Promise((resolve, reject) => {
|
|
728
|
+
if (!idb.db.support()) {
|
|
729
|
+
return reject(new Error("IndexedDB not supported"));
|
|
730
|
+
}
|
|
731
|
+
const request = globalThis.indexedDB.open(dbName, ver);
|
|
732
|
+
request.onerror = () => {
|
|
733
|
+
message_default(`IndexedDB error: ${request.error?.message}`);
|
|
734
|
+
reject(request.error);
|
|
735
|
+
};
|
|
736
|
+
request.onsuccess = () => {
|
|
737
|
+
message_default(`Database ${dbName} connected successfully`);
|
|
738
|
+
resolve(request.result);
|
|
739
|
+
};
|
|
740
|
+
request.onupgradeneeded = () => {
|
|
741
|
+
message_default(`Database ${dbName} upgrade/creation initiated`);
|
|
742
|
+
};
|
|
743
|
+
});
|
|
744
|
+
};
|
|
745
|
+
}
|
|
746
|
+
});
|
|
747
|
+
|
|
748
|
+
// functions/idb/tools/db.list.ts
|
|
749
|
+
var db_list_exports = {};
|
|
750
|
+
var init_db_list = __esm({
|
|
751
|
+
"functions/idb/tools/db.list.ts"() {
|
|
752
|
+
init_esm_shims();
|
|
753
|
+
init_idb();
|
|
754
|
+
idb.db.list = async () => {
|
|
755
|
+
if (!("indexedDB" in globalThis) || !indexedDB.databases) return [];
|
|
756
|
+
try {
|
|
757
|
+
const result = await indexedDB.databases();
|
|
758
|
+
globalThis.idbases = result || [];
|
|
759
|
+
await idb.db.size();
|
|
760
|
+
return globalThis.idbases;
|
|
761
|
+
} catch (err) {
|
|
762
|
+
console.error("Error listing databases:", err);
|
|
763
|
+
return [];
|
|
764
|
+
}
|
|
765
|
+
};
|
|
766
|
+
}
|
|
767
|
+
});
|
|
768
|
+
|
|
769
|
+
// functions/idb/tools/db.exist.ts
|
|
770
|
+
var db_exist_exports = {};
|
|
771
|
+
var init_db_exist = __esm({
|
|
772
|
+
"functions/idb/tools/db.exist.ts"() {
|
|
773
|
+
init_esm_shims();
|
|
774
|
+
init_idb();
|
|
775
|
+
idb.db.exist = (storeName) => {
|
|
776
|
+
return idbases?.some((db) => db.name === storeName);
|
|
777
|
+
};
|
|
778
|
+
}
|
|
779
|
+
});
|
|
780
|
+
|
|
781
|
+
// functions/idb/tools/db.quota.ts
|
|
782
|
+
var db_quota_exports = {};
|
|
783
|
+
var init_db_quota = __esm({
|
|
784
|
+
"functions/idb/tools/db.quota.ts"() {
|
|
785
|
+
init_esm_shims();
|
|
786
|
+
init_idb();
|
|
787
|
+
idb.db.quota = () => {
|
|
788
|
+
return navigator.storage.estimate();
|
|
789
|
+
};
|
|
790
|
+
}
|
|
791
|
+
});
|
|
792
|
+
|
|
793
|
+
// functions/idb/tools/db.delete.ts
|
|
794
|
+
var db_delete_exports = {};
|
|
795
|
+
var init_db_delete = __esm({
|
|
796
|
+
"functions/idb/tools/db.delete.ts"() {
|
|
797
|
+
init_esm_shims();
|
|
798
|
+
init_idb();
|
|
799
|
+
init_message();
|
|
800
|
+
idb.db.delete = (storeName) => {
|
|
801
|
+
return new Promise((resolve, reject) => {
|
|
802
|
+
message_default(`Removing database ${storeName}...`);
|
|
803
|
+
const performDelete = /* @__PURE__ */ __name(() => {
|
|
804
|
+
const request = indexedDB.deleteDatabase(storeName);
|
|
805
|
+
request.onsuccess = () => {
|
|
806
|
+
message_default(`${storeName} database removed successfully`);
|
|
807
|
+
idb.db.list();
|
|
808
|
+
resolve();
|
|
809
|
+
};
|
|
810
|
+
request.onerror = () => {
|
|
811
|
+
console.error(`Error removing ${storeName}:`, request.error);
|
|
812
|
+
reject(request.error);
|
|
813
|
+
};
|
|
814
|
+
request.onblocked = () => {
|
|
815
|
+
console.warn(`Deletion of ${storeName} is blocked. Please close other tabs.`);
|
|
816
|
+
};
|
|
817
|
+
}, "performDelete");
|
|
818
|
+
performDelete();
|
|
819
|
+
});
|
|
820
|
+
};
|
|
821
|
+
}
|
|
822
|
+
});
|
|
823
|
+
|
|
824
|
+
// functions/idb/tools/db.size.ts
|
|
825
|
+
var db_size_exports = {};
|
|
826
|
+
var init_db_size = __esm({
|
|
827
|
+
"functions/idb/tools/db.size.ts"() {
|
|
828
|
+
init_esm_shims();
|
|
829
|
+
init_idb();
|
|
830
|
+
init_message();
|
|
831
|
+
idb.db.size = async () => {
|
|
832
|
+
if (!idbases || idbases.length === 0) return;
|
|
833
|
+
for (let i = 0; i < idbases.length; i++) {
|
|
834
|
+
const dbInfo = idbases[i];
|
|
835
|
+
try {
|
|
836
|
+
const db = await idb.db.create(dbInfo.name, dbInfo.version);
|
|
837
|
+
const tableNames = Array.from(db.objectStoreNames);
|
|
838
|
+
let totalDbSize = 0;
|
|
839
|
+
for (const tableName of tableNames) {
|
|
840
|
+
const tableSize = await idb.table.size(db, tableName);
|
|
841
|
+
totalDbSize += tableSize;
|
|
842
|
+
}
|
|
843
|
+
dbInfo.size = totalDbSize;
|
|
844
|
+
db.close();
|
|
845
|
+
} catch (err) {
|
|
846
|
+
message_default(`Could not calculate size for ${dbInfo.name}:${err}`);
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
};
|
|
850
|
+
}
|
|
851
|
+
});
|
|
852
|
+
|
|
853
|
+
// functions/idb/tools/db.version.ts
|
|
854
|
+
var db_version_exports = {};
|
|
855
|
+
var init_db_version = __esm({
|
|
856
|
+
"functions/idb/tools/db.version.ts"() {
|
|
857
|
+
init_esm_shims();
|
|
858
|
+
init_idb();
|
|
859
|
+
idb.db.version = (storeName) => {
|
|
860
|
+
let idbVer = 0;
|
|
861
|
+
for (const v of idbases) {
|
|
862
|
+
if (v.name === storeName) idbVer = v.version;
|
|
863
|
+
break;
|
|
864
|
+
}
|
|
865
|
+
return idbVer;
|
|
866
|
+
};
|
|
867
|
+
}
|
|
868
|
+
});
|
|
869
|
+
|
|
870
|
+
// functions/idb/tools/db.support.ts
|
|
871
|
+
var db_support_exports = {};
|
|
872
|
+
var init_db_support = __esm({
|
|
873
|
+
"functions/idb/tools/db.support.ts"() {
|
|
874
|
+
init_esm_shims();
|
|
875
|
+
init_idb();
|
|
876
|
+
init_message();
|
|
877
|
+
idb.db.support = () => {
|
|
878
|
+
const isSupported = "indexedDB" in globalThis;
|
|
879
|
+
if (!isSupported) {
|
|
880
|
+
message_default("Your environment doesn't support IndexedDB");
|
|
881
|
+
}
|
|
882
|
+
return isSupported;
|
|
883
|
+
};
|
|
884
|
+
}
|
|
885
|
+
});
|
|
886
|
+
|
|
887
|
+
// functions/idb/tools/table.create.ts
|
|
888
|
+
var table_create_exports = {};
|
|
889
|
+
var init_table_create = __esm({
|
|
890
|
+
"functions/idb/tools/table.create.ts"() {
|
|
891
|
+
init_esm_shims();
|
|
892
|
+
init_idb();
|
|
893
|
+
init_message();
|
|
894
|
+
idb.table.create = (dbName, dbTable) => {
|
|
895
|
+
return new Promise((resolve, reject) => {
|
|
896
|
+
try {
|
|
897
|
+
const currentVersion = Number(idb.db.version(dbName)) || 0;
|
|
898
|
+
const nextVersion = currentVersion + 1;
|
|
899
|
+
const request = indexedDB.open(dbName, nextVersion);
|
|
900
|
+
request.onupgradeneeded = (e) => {
|
|
901
|
+
const db = e.target.result;
|
|
902
|
+
if (!db.objectStoreNames.contains(dbTable)) {
|
|
903
|
+
const store2 = db.createObjectStore(dbTable, {
|
|
904
|
+
keyPath: "id",
|
|
905
|
+
autoIncrement: true
|
|
906
|
+
});
|
|
907
|
+
store2.createIndex("id", "id", { unique: true });
|
|
908
|
+
store2.createIndex("data", "data", { unique: false });
|
|
909
|
+
message_default(`Table ${dbTable} created in ${dbName}`);
|
|
910
|
+
}
|
|
911
|
+
};
|
|
912
|
+
request.onsuccess = () => {
|
|
913
|
+
request.result.close();
|
|
914
|
+
idb.db.list();
|
|
915
|
+
resolve();
|
|
916
|
+
};
|
|
917
|
+
request.onerror = () => {
|
|
918
|
+
console.error(`Error creating table ${dbTable}:`, request.error);
|
|
919
|
+
reject(request.error);
|
|
920
|
+
};
|
|
921
|
+
} catch (err) {
|
|
922
|
+
console.error("Critical error in table.create:", err);
|
|
923
|
+
reject(err);
|
|
924
|
+
}
|
|
925
|
+
});
|
|
926
|
+
};
|
|
927
|
+
}
|
|
928
|
+
});
|
|
929
|
+
|
|
930
|
+
// functions/idb/tools/table.size.ts
|
|
931
|
+
var table_size_exports = {};
|
|
932
|
+
var init_table_size = __esm({
|
|
933
|
+
"functions/idb/tools/table.size.ts"() {
|
|
934
|
+
init_esm_shims();
|
|
935
|
+
init_idb();
|
|
936
|
+
init_message();
|
|
937
|
+
idb.table.size = (db, table) => {
|
|
938
|
+
return new Promise((resolve, reject) => {
|
|
939
|
+
if (!db) return reject(new Error("Database instance is required"));
|
|
940
|
+
if (!db.objectStoreNames.contains(table)) return resolve(0);
|
|
941
|
+
let size = 0;
|
|
942
|
+
let count = 0;
|
|
943
|
+
const transaction = db.transaction([table], "readonly");
|
|
944
|
+
const store2 = transaction.objectStore(table);
|
|
945
|
+
const request = store2.openCursor();
|
|
946
|
+
request.onsuccess = async (event) => {
|
|
947
|
+
const cursor = event.target.result;
|
|
948
|
+
if (cursor) {
|
|
949
|
+
try {
|
|
950
|
+
const value = cursor.value;
|
|
951
|
+
size += JSON.stringify(value).length;
|
|
952
|
+
} catch (err) {
|
|
953
|
+
message_default(`Error stringifying IDB value tracking size:${err}`);
|
|
954
|
+
}
|
|
955
|
+
count++;
|
|
956
|
+
if (count % 200 === 0) {
|
|
957
|
+
await new Promise((resolve2) => setTimeout(resolve2, 0));
|
|
958
|
+
}
|
|
959
|
+
cursor.continue();
|
|
960
|
+
} else {
|
|
961
|
+
resolve(size);
|
|
962
|
+
}
|
|
963
|
+
};
|
|
964
|
+
request.onerror = () => {
|
|
965
|
+
reject(request.error);
|
|
966
|
+
};
|
|
967
|
+
});
|
|
968
|
+
};
|
|
969
|
+
}
|
|
970
|
+
});
|
|
971
|
+
|
|
972
|
+
// functions/idb/crud/data.delete.ts
|
|
973
|
+
var data_delete_exports = {};
|
|
974
|
+
var init_data_delete = __esm({
|
|
975
|
+
"functions/idb/crud/data.delete.ts"() {
|
|
976
|
+
init_esm_shims();
|
|
977
|
+
init_idb();
|
|
978
|
+
init_message();
|
|
979
|
+
idb.data.delete = (storeName, table, key) => {
|
|
980
|
+
return new Promise((resolve, reject) => {
|
|
981
|
+
const request = indexedDB.open(storeName);
|
|
982
|
+
request.onsuccess = () => {
|
|
983
|
+
const db = request.result;
|
|
984
|
+
if (!db.objectStoreNames.contains(table)) {
|
|
985
|
+
db.close();
|
|
986
|
+
return reject(new Error(`Table ${table} not found`));
|
|
987
|
+
}
|
|
988
|
+
const transaction = db.transaction(table, "readwrite");
|
|
989
|
+
const objectStore = transaction.objectStore(table);
|
|
990
|
+
const deleteRequest = objectStore.delete(key);
|
|
991
|
+
deleteRequest.onsuccess = () => {
|
|
992
|
+
db.close();
|
|
993
|
+
message_default(`Record ${key} deleted from ${table}`);
|
|
994
|
+
resolve();
|
|
995
|
+
};
|
|
996
|
+
deleteRequest.onerror = () => {
|
|
997
|
+
db.close();
|
|
998
|
+
reject(deleteRequest.error);
|
|
999
|
+
};
|
|
1000
|
+
};
|
|
1001
|
+
request.onerror = () => reject(request.error);
|
|
1002
|
+
});
|
|
1003
|
+
};
|
|
1004
|
+
idb.data.delete.all = (storeName, table) => {
|
|
1005
|
+
return new Promise((resolve, reject) => {
|
|
1006
|
+
const request = indexedDB.open(storeName);
|
|
1007
|
+
request.onsuccess = (event) => {
|
|
1008
|
+
const db = event.target.result;
|
|
1009
|
+
if (!db.objectStoreNames.contains(table)) {
|
|
1010
|
+
db.close();
|
|
1011
|
+
return reject(new Error(`Table ${table} not found`));
|
|
1012
|
+
}
|
|
1013
|
+
const transaction = db.transaction(table, "readwrite");
|
|
1014
|
+
const store2 = transaction.objectStore(table);
|
|
1015
|
+
const clearRequest = store2.clear();
|
|
1016
|
+
clearRequest.onsuccess = () => {
|
|
1017
|
+
db.close();
|
|
1018
|
+
message_default(`All data cleared from ${table}`);
|
|
1019
|
+
resolve();
|
|
1020
|
+
};
|
|
1021
|
+
clearRequest.onerror = () => {
|
|
1022
|
+
db.close();
|
|
1023
|
+
reject(clearRequest.error);
|
|
1024
|
+
};
|
|
1025
|
+
};
|
|
1026
|
+
request.onerror = () => reject(request.error);
|
|
1027
|
+
});
|
|
1028
|
+
};
|
|
1029
|
+
}
|
|
1030
|
+
});
|
|
1031
|
+
|
|
1032
|
+
// functions/idb/crud/data.set.ts
|
|
1033
|
+
var data_set_exports = {};
|
|
1034
|
+
var init_data_set = __esm({
|
|
1035
|
+
"functions/idb/crud/data.set.ts"() {
|
|
1036
|
+
init_esm_shims();
|
|
1037
|
+
init_idb();
|
|
1038
|
+
init_message();
|
|
1039
|
+
idb.data.set = (storeName, table, value) => {
|
|
1040
|
+
return new Promise((resolve, reject) => {
|
|
1041
|
+
const request = indexedDB.open(storeName);
|
|
1042
|
+
request.onsuccess = () => {
|
|
1043
|
+
const db = request.result;
|
|
1044
|
+
if (!db.objectStoreNames.contains(table)) {
|
|
1045
|
+
db.close();
|
|
1046
|
+
return reject(new Error(`Table ${table} does not exist in ${storeName}`));
|
|
1047
|
+
}
|
|
1048
|
+
const transaction = db.transaction(table, "readwrite");
|
|
1049
|
+
const objectStore = transaction.objectStore(table);
|
|
1050
|
+
const putRequest = objectStore.put(value);
|
|
1051
|
+
putRequest.onsuccess = () => {
|
|
1052
|
+
db.close();
|
|
1053
|
+
message_default(`Data saved in ${storeName}.${table}`);
|
|
1054
|
+
resolve(putRequest.result);
|
|
1055
|
+
};
|
|
1056
|
+
putRequest.onerror = (_) => {
|
|
1057
|
+
db.close();
|
|
1058
|
+
message_default(`Database insert error: ${putRequest.error?.message}`);
|
|
1059
|
+
reject(putRequest.error);
|
|
1060
|
+
};
|
|
1061
|
+
};
|
|
1062
|
+
request.onerror = () => {
|
|
1063
|
+
reject(request.error);
|
|
1064
|
+
};
|
|
1065
|
+
});
|
|
1066
|
+
};
|
|
1067
|
+
}
|
|
1068
|
+
});
|
|
1069
|
+
|
|
1070
|
+
// functions/idb/crud/data.get.ts
|
|
1071
|
+
var data_get_exports = {};
|
|
1072
|
+
var init_data_get = __esm({
|
|
1073
|
+
"functions/idb/crud/data.get.ts"() {
|
|
1074
|
+
init_esm_shims();
|
|
1075
|
+
init_idb();
|
|
1076
|
+
idb.data.get = (storeName, table, key) => {
|
|
1077
|
+
return new Promise((resolve, reject) => {
|
|
1078
|
+
const request = indexedDB.open(storeName);
|
|
1079
|
+
request.onsuccess = (event) => {
|
|
1080
|
+
const db = event.target.result;
|
|
1081
|
+
if (!db.objectStoreNames.contains(table)) {
|
|
1082
|
+
db.close();
|
|
1083
|
+
return reject(new Error(`Table ${table} not found in ${storeName}`));
|
|
1084
|
+
}
|
|
1085
|
+
const transaction = db.transaction(table, "readonly");
|
|
1086
|
+
const store2 = transaction.objectStore(table);
|
|
1087
|
+
const getRequest = store2.get(key);
|
|
1088
|
+
getRequest.onsuccess = () => {
|
|
1089
|
+
db.close();
|
|
1090
|
+
resolve(getRequest.result);
|
|
1091
|
+
};
|
|
1092
|
+
getRequest.onerror = () => {
|
|
1093
|
+
db.close();
|
|
1094
|
+
reject(getRequest.error);
|
|
1095
|
+
};
|
|
1096
|
+
};
|
|
1097
|
+
request.onerror = () => {
|
|
1098
|
+
reject(request.error);
|
|
1099
|
+
};
|
|
1100
|
+
});
|
|
1101
|
+
};
|
|
1102
|
+
}
|
|
1103
|
+
});
|
|
1104
|
+
|
|
1105
|
+
// functions/idb/index.ts
|
|
1106
|
+
var _hasIDB, idb;
|
|
1107
|
+
var init_idb = __esm({
|
|
1108
|
+
"functions/idb/index.ts"() {
|
|
1109
|
+
init_esm_shims();
|
|
1110
|
+
init_platform();
|
|
1111
|
+
init_env();
|
|
1112
|
+
_hasIDB = hasIndexedDB();
|
|
1113
|
+
idb = {
|
|
1114
|
+
db: {},
|
|
1115
|
+
table: {},
|
|
1116
|
+
data: {}
|
|
1117
|
+
};
|
|
1118
|
+
if (_hasIDB) {
|
|
1119
|
+
(async () => {
|
|
1120
|
+
Object.defineProperty(idb, "db", { value: {}, writable: true, configurable: true });
|
|
1121
|
+
Object.defineProperty(idb, "table", { value: {}, writable: true, configurable: true });
|
|
1122
|
+
Object.defineProperty(idb, "data", { value: {}, writable: true, configurable: true });
|
|
1123
|
+
Object.defineProperty(globalThis, "idbases", {
|
|
1124
|
+
value: [],
|
|
1125
|
+
writable: true,
|
|
1126
|
+
configurable: true,
|
|
1127
|
+
enumerable: false
|
|
1128
|
+
});
|
|
1129
|
+
await Promise.all([
|
|
1130
|
+
Promise.resolve().then(() => (init_db_create(), db_create_exports)),
|
|
1131
|
+
Promise.resolve().then(() => (init_db_list(), db_list_exports)),
|
|
1132
|
+
Promise.resolve().then(() => (init_db_exist(), db_exist_exports)),
|
|
1133
|
+
Promise.resolve().then(() => (init_db_quota(), db_quota_exports)),
|
|
1134
|
+
Promise.resolve().then(() => (init_db_delete(), db_delete_exports)),
|
|
1135
|
+
Promise.resolve().then(() => (init_db_size(), db_size_exports)),
|
|
1136
|
+
Promise.resolve().then(() => (init_db_version(), db_version_exports)),
|
|
1137
|
+
Promise.resolve().then(() => (init_db_support(), db_support_exports)),
|
|
1138
|
+
Promise.resolve().then(() => (init_table_create(), table_create_exports)),
|
|
1139
|
+
Promise.resolve().then(() => (init_table_size(), table_size_exports)),
|
|
1140
|
+
Promise.resolve().then(() => (init_data_delete(), data_delete_exports)),
|
|
1141
|
+
Promise.resolve().then(() => (init_data_set(), data_set_exports)),
|
|
1142
|
+
Promise.resolve().then(() => (init_data_get(), data_get_exports))
|
|
1143
|
+
]);
|
|
1144
|
+
Object.preventExtensions(idb);
|
|
1145
|
+
Object.seal(idb);
|
|
1146
|
+
Object.freeze(idb);
|
|
1147
|
+
})();
|
|
1148
|
+
} else {
|
|
1149
|
+
idb._disabled = true;
|
|
1150
|
+
idb._warning = "IndexedDB is not available in this environment (Node.js/Deno). Use store or session for persistence.";
|
|
1151
|
+
if (DEV) {
|
|
1152
|
+
console.warn("Memorio IDB: IndexedDB is not available in this environment. Use store or session for data persistence.");
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
}
|
|
1156
|
+
});
|
|
1157
|
+
|
|
1158
|
+
// functions/sqlite/tools/db.support.ts
|
|
1159
|
+
var db_support_exports2 = {};
|
|
1160
|
+
function _inDocument() {
|
|
1161
|
+
const g3 = globalThis;
|
|
1162
|
+
return typeof g3.document !== "undefined" && typeof g3.document.createElement === "function";
|
|
1163
|
+
}
|
|
1164
|
+
function _loadSqlJsScript(url) {
|
|
1165
|
+
const g3 = globalThis;
|
|
1166
|
+
if (g3.__memorioSqlJsScript === url) return Promise.resolve();
|
|
1167
|
+
if (!_scriptLoaded) {
|
|
1168
|
+
_scriptLoaded = new Promise((resolve, reject) => {
|
|
1169
|
+
if (g3.initSqlJs && typeof g3.initSqlJs === "function") {
|
|
1170
|
+
g3.__memorioSqlJsScript = url;
|
|
1171
|
+
resolve();
|
|
1172
|
+
return;
|
|
1173
|
+
}
|
|
1174
|
+
if (!_inDocument()) {
|
|
1175
|
+
reject(new Error("memorio sqlite: no document available to load sql.js"));
|
|
1176
|
+
return;
|
|
1177
|
+
}
|
|
1178
|
+
const script = g3.document.createElement("script");
|
|
1179
|
+
script.src = url;
|
|
1180
|
+
script.async = true;
|
|
1181
|
+
script.onload = () => {
|
|
1182
|
+
g3.__memorioSqlJsScript = url;
|
|
1183
|
+
resolve();
|
|
1184
|
+
};
|
|
1185
|
+
script.onerror = () => reject(new Error(`memorio sqlite: failed to load sql.js from ${url}`));
|
|
1186
|
+
g3.document.head.appendChild(script);
|
|
1187
|
+
});
|
|
1188
|
+
}
|
|
1189
|
+
return _scriptLoaded;
|
|
1190
|
+
}
|
|
1191
|
+
var _loading, _SQL, _defaultLocateFile, _scriptLoaded, _loadSqlJsFromCdn;
|
|
1192
|
+
var init_db_support2 = __esm({
|
|
1193
|
+
"functions/sqlite/tools/db.support.ts"() {
|
|
1194
|
+
init_esm_shims();
|
|
1195
|
+
init_sqlite();
|
|
1196
|
+
init_platform();
|
|
1197
|
+
init_message();
|
|
1198
|
+
_loading = null;
|
|
1199
|
+
_SQL = null;
|
|
1200
|
+
_defaultLocateFile = /* @__PURE__ */ __name((file) => {
|
|
1201
|
+
const g3 = globalThis;
|
|
1202
|
+
const base = g3.sqliteWasmBase || "";
|
|
1203
|
+
return base + file;
|
|
1204
|
+
}, "_defaultLocateFile");
|
|
1205
|
+
_scriptLoaded = null;
|
|
1206
|
+
__name(_inDocument, "_inDocument");
|
|
1207
|
+
__name(_loadSqlJsScript, "_loadSqlJsScript");
|
|
1208
|
+
_loadSqlJsFromCdn = /* @__PURE__ */ __name(async (url) => {
|
|
1209
|
+
const g3 = globalThis;
|
|
1210
|
+
if (!url) {
|
|
1211
|
+
throw new Error('memorio sqlite: no loader configured. Install sql.js (npm i sql.js) and pass a loader via sqlite.config({ loader: () => import("sql.js") }).');
|
|
1212
|
+
}
|
|
1213
|
+
if (typeof g3.initSqlJs === "function") return g3.initSqlJs;
|
|
1214
|
+
await _loadSqlJsScript(url);
|
|
1215
|
+
return g3.initSqlJs || g3;
|
|
1216
|
+
}, "_loadSqlJsFromCdn");
|
|
1217
|
+
sqlite.db.support = () => {
|
|
1218
|
+
return hasSqlJs();
|
|
1219
|
+
};
|
|
1220
|
+
sqlite.db.getSQL = async () => {
|
|
1221
|
+
if (_SQL) return _SQL;
|
|
1222
|
+
if (_loading) return _loading;
|
|
1223
|
+
const g3 = globalThis;
|
|
1224
|
+
const cfg = g3.sqliteConfig || {};
|
|
1225
|
+
const p = (async () => {
|
|
1226
|
+
if (typeof cfg.loader === "function") {
|
|
1227
|
+
return await cfg.loader();
|
|
1228
|
+
}
|
|
1229
|
+
if (cfg.scriptUrl) {
|
|
1230
|
+
const mod = await _loadSqlJsFromCdn(cfg.scriptUrl);
|
|
1231
|
+
const initSqlJs = typeof mod === "function" ? mod : mod && (mod.default || mod);
|
|
1232
|
+
const SQL = await initSqlJs({ locateFile: cfg.locateFile || _defaultLocateFile });
|
|
1233
|
+
g3.sqliteVersion = SQL?.version || "sql.js";
|
|
1234
|
+
message_default("Memorio SQLite: sql.js engine loaded");
|
|
1235
|
+
return SQL;
|
|
1236
|
+
}
|
|
1237
|
+
throw new Error('memorio sqlite: no loader configured. Install sql.js (npm i sql.js) and pass a loader via sqlite.config({ loader: () => import("sql.js") }).');
|
|
1238
|
+
})();
|
|
1239
|
+
_loading = p;
|
|
1240
|
+
try {
|
|
1241
|
+
_SQL = await p;
|
|
1242
|
+
return _SQL;
|
|
1243
|
+
} catch (err) {
|
|
1244
|
+
try {
|
|
1245
|
+
sqlite._disabled = true;
|
|
1246
|
+
} catch (_) {
|
|
1247
|
+
}
|
|
1248
|
+
try {
|
|
1249
|
+
sqlite._warning = "Memorio SQLite: sql.js could not be loaded. Install sql.js (npm i sql.js) and pass a loader via sqlite.config({ loader: () => <your sql.js import>() }).";
|
|
1250
|
+
} catch (_) {
|
|
1251
|
+
}
|
|
1252
|
+
console.warn("Memorio SQLite: failed to load sql.js", err);
|
|
1253
|
+
throw err;
|
|
1254
|
+
} finally {
|
|
1255
|
+
_loading = null;
|
|
1256
|
+
}
|
|
1257
|
+
};
|
|
1258
|
+
sqlite.db.version = () => {
|
|
1259
|
+
return globalThis.sqliteVersion || null;
|
|
1260
|
+
};
|
|
1261
|
+
}
|
|
1262
|
+
});
|
|
1263
|
+
|
|
1264
|
+
// functions/sqlite/tools/persist.ts
|
|
1265
|
+
function _ns() {
|
|
1266
|
+
const cfg = g.sqliteConfig || {};
|
|
1267
|
+
return cfg.namespace ? `ns:${cfg.namespace}` : "default";
|
|
1268
|
+
}
|
|
1269
|
+
function _key(name) {
|
|
1270
|
+
return `memorio:sqlite:db:${_ns()}:${name}`;
|
|
1271
|
+
}
|
|
1272
|
+
function _b64encode(buf) {
|
|
1273
|
+
const bytes = buf instanceof Uint8Array ? buf : new Uint8Array(buf);
|
|
1274
|
+
let binary = "";
|
|
1275
|
+
const len = bytes.byteLength;
|
|
1276
|
+
for (let i = 0; i < len; i++) binary += String.fromCharCode(bytes[i]);
|
|
1277
|
+
if (typeof btoa === "function") return btoa(binary);
|
|
1278
|
+
return typeof Buffer !== "undefined" ? Buffer.from(bytes).toString("base64") : "";
|
|
1279
|
+
}
|
|
1280
|
+
function _b64decode(b64) {
|
|
1281
|
+
if (typeof Buffer !== "undefined") {
|
|
1282
|
+
return new Uint8Array(Buffer.from(b64, "base64"));
|
|
1283
|
+
}
|
|
1284
|
+
if (typeof atob !== "function") {
|
|
1285
|
+
throw new Error("memorio sqlite: no base64 decoder available");
|
|
1286
|
+
}
|
|
1287
|
+
const binary = atob(b64);
|
|
1288
|
+
const len = binary.length;
|
|
1289
|
+
const out = new Uint8Array(len);
|
|
1290
|
+
for (let i = 0; i < len; i++) out[i] = binary.charCodeAt(i);
|
|
1291
|
+
return out;
|
|
1292
|
+
}
|
|
1293
|
+
function saveSnapshot(name) {
|
|
1294
|
+
return new Promise((resolve) => {
|
|
1295
|
+
const db = g.__sqliteDbs && g.__sqliteDbs[name];
|
|
1296
|
+
if (!db || typeof db.export !== "function") {
|
|
1297
|
+
resolve(false);
|
|
1298
|
+
return;
|
|
1299
|
+
}
|
|
1300
|
+
try {
|
|
1301
|
+
const blob = db.export();
|
|
1302
|
+
store.set(_key(name), _b64encode(blob));
|
|
1303
|
+
message_default(`Memorio SQLite: persisted '${name}' to store`);
|
|
1304
|
+
resolve(true);
|
|
1305
|
+
} catch (err) {
|
|
1306
|
+
console.warn("Memorio SQLite: persist snapshot failed", err);
|
|
1307
|
+
resolve(false);
|
|
1308
|
+
}
|
|
1309
|
+
});
|
|
1310
|
+
}
|
|
1311
|
+
function loadSnapshot(name) {
|
|
1312
|
+
const b64 = store.get(_key(name));
|
|
1313
|
+
if (!b64) return null;
|
|
1314
|
+
try {
|
|
1315
|
+
return _b64decode(b64);
|
|
1316
|
+
} catch {
|
|
1317
|
+
return null;
|
|
1318
|
+
}
|
|
1319
|
+
}
|
|
1320
|
+
function removeSnapshot(name) {
|
|
1321
|
+
store.remove(_key(name));
|
|
1322
|
+
}
|
|
1323
|
+
function attachAutoExport(name, db) {
|
|
1324
|
+
if (!db || typeof db.updateHook !== "function") return;
|
|
1325
|
+
_persistDbs[name] = true;
|
|
1326
|
+
try {
|
|
1327
|
+
db.updateHook(() => {
|
|
1328
|
+
if (_exportTimers[name]) clearTimeout(_exportTimers[name]);
|
|
1329
|
+
_exportTimers[name] = setTimeout(() => {
|
|
1330
|
+
_exportTimers[name] = null;
|
|
1331
|
+
void saveSnapshot(name);
|
|
1332
|
+
}, 250);
|
|
1333
|
+
});
|
|
1334
|
+
} catch (err) {
|
|
1335
|
+
console.warn("Memorio SQLite: could not attach updateHook", err);
|
|
1336
|
+
}
|
|
1337
|
+
}
|
|
1338
|
+
var g, _persistDbs, _exportTimers;
|
|
1339
|
+
var init_persist = __esm({
|
|
1340
|
+
"functions/sqlite/tools/persist.ts"() {
|
|
1341
|
+
init_esm_shims();
|
|
1342
|
+
init_sqlite();
|
|
1343
|
+
init_store();
|
|
1344
|
+
init_message();
|
|
1345
|
+
g = globalThis;
|
|
1346
|
+
_persistDbs = {};
|
|
1347
|
+
_exportTimers = {};
|
|
1348
|
+
__name(_ns, "_ns");
|
|
1349
|
+
__name(_key, "_key");
|
|
1350
|
+
__name(_b64encode, "_b64encode");
|
|
1351
|
+
__name(_b64decode, "_b64decode");
|
|
1352
|
+
__name(saveSnapshot, "saveSnapshot");
|
|
1353
|
+
__name(loadSnapshot, "loadSnapshot");
|
|
1354
|
+
__name(removeSnapshot, "removeSnapshot");
|
|
1355
|
+
__name(attachAutoExport, "attachAutoExport");
|
|
1356
|
+
sqlite.db.persist = async (name = "memorio") => {
|
|
1357
|
+
return saveSnapshot(name);
|
|
1358
|
+
};
|
|
1359
|
+
sqlite.db.download = async (name = "memorio", filename = `${name}.sqlite`) => {
|
|
1360
|
+
const g3 = globalThis;
|
|
1361
|
+
const db = g3.__sqliteDbs && g3.__sqliteDbs[name];
|
|
1362
|
+
if (!db) {
|
|
1363
|
+
console.warn(`Memorio SQLite: cannot download '${name}' - database not found. Create it with sqlite.db.create('${name}').`);
|
|
1364
|
+
return false;
|
|
1365
|
+
}
|
|
1366
|
+
let blob;
|
|
1367
|
+
try {
|
|
1368
|
+
blob = await sqlite.db.export(name);
|
|
1369
|
+
} catch (err) {
|
|
1370
|
+
console.warn("Memorio SQLite: export failed during download", err);
|
|
1371
|
+
return false;
|
|
1372
|
+
}
|
|
1373
|
+
if (!blob) return false;
|
|
1374
|
+
if (typeof g3.document === "undefined" || typeof g3.Blob === "undefined") {
|
|
1375
|
+
console.warn("Memorio SQLite: sqlite.db.download() requires a browser environment.");
|
|
1376
|
+
return false;
|
|
1377
|
+
}
|
|
1378
|
+
const URL = g3.URL || g3.webkitURL;
|
|
1379
|
+
if (!URL || typeof URL.createObjectURL !== "function") return false;
|
|
1380
|
+
const objectUrl = URL.createObjectURL(new Blob([blob], { type: "application/x-sqlite3" }));
|
|
1381
|
+
const a = g3.document.createElement("a");
|
|
1382
|
+
a.style.display = "none";
|
|
1383
|
+
a.href = objectUrl;
|
|
1384
|
+
a.download = filename;
|
|
1385
|
+
g3.document.body.appendChild(a);
|
|
1386
|
+
a.click();
|
|
1387
|
+
setTimeout(() => {
|
|
1388
|
+
try {
|
|
1389
|
+
URL.revokeObjectURL(objectUrl);
|
|
1390
|
+
} catch (_) {
|
|
1391
|
+
}
|
|
1392
|
+
a.remove();
|
|
1393
|
+
}, 1e3);
|
|
1394
|
+
return true;
|
|
1395
|
+
};
|
|
1396
|
+
sqlite.db.close = async (name = "memorio") => {
|
|
1397
|
+
const db = g.__sqliteDbs && g.__sqliteDbs[name];
|
|
1398
|
+
if (db && typeof db.close === "function") {
|
|
1399
|
+
try {
|
|
1400
|
+
await saveSnapshot(name);
|
|
1401
|
+
} catch (_) {
|
|
1402
|
+
}
|
|
1403
|
+
try {
|
|
1404
|
+
db.close();
|
|
1405
|
+
} catch (err) {
|
|
1406
|
+
console.warn("Memorio SQLite: close failed", err);
|
|
1407
|
+
}
|
|
1408
|
+
}
|
|
1409
|
+
if (g.__sqliteDbs) delete g.__sqliteDbs[name];
|
|
1410
|
+
if (g.sqlbases) {
|
|
1411
|
+
const idx = g.sqlbases.findIndex((x) => x && x.name === name);
|
|
1412
|
+
if (idx > -1) g.sqlbases.splice(idx, 1);
|
|
1413
|
+
}
|
|
1414
|
+
delete _persistDbs[name];
|
|
1415
|
+
if (_exportTimers[name]) {
|
|
1416
|
+
clearTimeout(_exportTimers[name]);
|
|
1417
|
+
_exportTimers[name] = null;
|
|
1418
|
+
}
|
|
1419
|
+
removeSnapshot(name);
|
|
1420
|
+
};
|
|
1421
|
+
sqlite.db.loadSnapshot = loadSnapshot;
|
|
1422
|
+
sqlite.db.saveSnapshot = saveSnapshot;
|
|
1423
|
+
}
|
|
1424
|
+
});
|
|
1425
|
+
|
|
1426
|
+
// functions/sqlite/tools/db.create.ts
|
|
1427
|
+
var db_create_exports2 = {};
|
|
1428
|
+
var init_db_create2 = __esm({
|
|
1429
|
+
"functions/sqlite/tools/db.create.ts"() {
|
|
1430
|
+
init_esm_shims();
|
|
1431
|
+
init_sqlite();
|
|
1432
|
+
init_message();
|
|
1433
|
+
init_persist();
|
|
1434
|
+
sqlite.db.create = async (name = "memorio", opts = {}) => {
|
|
1435
|
+
const SQL = await sqlite.db.getSQL();
|
|
1436
|
+
const g3 = globalThis;
|
|
1437
|
+
const persistence = !!(opts && opts.persistence) || !!(g3.sqliteConfig && g3.sqliteConfig.persistence);
|
|
1438
|
+
let data;
|
|
1439
|
+
if (persistence && !opts.data) {
|
|
1440
|
+
const restored = loadSnapshot(name);
|
|
1441
|
+
if (restored) data = restored;
|
|
1442
|
+
}
|
|
1443
|
+
const useData = opts && opts.data || data;
|
|
1444
|
+
let db;
|
|
1445
|
+
if (useData && typeof useData.byteLength === "number") {
|
|
1446
|
+
db = new SQL.Database(useData);
|
|
1447
|
+
message_default(`Memorio SQLite: database '${name}' opened (persistence=${persistence})`);
|
|
1448
|
+
} else {
|
|
1449
|
+
db = new SQL.Database();
|
|
1450
|
+
message_default(`Memorio SQLite: database '${name}' created (persistence=${persistence})`);
|
|
1451
|
+
}
|
|
1452
|
+
const createOpts = { ...opts, persistence };
|
|
1453
|
+
if (!g3.__sqliteDbs) g3.__sqliteDbs = {};
|
|
1454
|
+
g3.__sqliteDbs[name] = db;
|
|
1455
|
+
if (!g3.sqlbases) g3.sqlbases = [];
|
|
1456
|
+
const idx = g3.sqlbases.findIndex((x) => x && x.name === name);
|
|
1457
|
+
if (idx > -1) {
|
|
1458
|
+
g3.sqlbases[idx] = { name, db, persistence: createOpts.persistence };
|
|
1459
|
+
} else {
|
|
1460
|
+
g3.sqlbases.push({ name, db, persistence: createOpts.persistence });
|
|
1461
|
+
}
|
|
1462
|
+
if (persistence) attachAutoExport(name, db);
|
|
1463
|
+
return db;
|
|
1464
|
+
};
|
|
1465
|
+
}
|
|
1466
|
+
});
|
|
1467
|
+
|
|
1468
|
+
// functions/sqlite/tools/db.get.ts
|
|
1469
|
+
var db_get_exports = {};
|
|
1470
|
+
var init_db_get = __esm({
|
|
1471
|
+
"functions/sqlite/tools/db.get.ts"() {
|
|
1472
|
+
init_esm_shims();
|
|
1473
|
+
init_sqlite();
|
|
1474
|
+
sqlite.db.get = (name = "memorio") => {
|
|
1475
|
+
const dbs = globalThis.__sqliteDbs;
|
|
1476
|
+
if (!dbs || !dbs[name]) {
|
|
1477
|
+
throw new Error(
|
|
1478
|
+
`SQLite database '${name}' does not exist. Create it with sqlite.db.create('${name}').`
|
|
1479
|
+
);
|
|
1480
|
+
}
|
|
1481
|
+
return dbs[name];
|
|
1482
|
+
};
|
|
1483
|
+
}
|
|
1484
|
+
});
|
|
1485
|
+
|
|
1486
|
+
// functions/sqlite/tools/db.delete.ts
|
|
1487
|
+
var db_delete_exports2 = {};
|
|
1488
|
+
var init_db_delete2 = __esm({
|
|
1489
|
+
"functions/sqlite/tools/db.delete.ts"() {
|
|
1490
|
+
init_esm_shims();
|
|
1491
|
+
init_sqlite();
|
|
1492
|
+
init_message();
|
|
1493
|
+
sqlite.db.delete = (name) => {
|
|
1494
|
+
const dbs = globalThis.__sqliteDbs;
|
|
1495
|
+
if (!dbs || !dbs[name]) return false;
|
|
1496
|
+
try {
|
|
1497
|
+
dbs[name].close();
|
|
1498
|
+
} catch (_) {
|
|
1499
|
+
}
|
|
1500
|
+
delete dbs[name];
|
|
1501
|
+
const g3 = globalThis;
|
|
1502
|
+
if (g3.sqlbases) g3.sqlbases = g3.sqlbases.filter((x) => x && x.name !== name);
|
|
1503
|
+
message_default(`Memorio SQLite: database '${name}' deleted`);
|
|
1504
|
+
return true;
|
|
1505
|
+
};
|
|
1506
|
+
}
|
|
1507
|
+
});
|
|
1508
|
+
|
|
1509
|
+
// functions/sqlite/tools/db.list.ts
|
|
1510
|
+
var db_list_exports2 = {};
|
|
1511
|
+
var init_db_list2 = __esm({
|
|
1512
|
+
"functions/sqlite/tools/db.list.ts"() {
|
|
1513
|
+
init_esm_shims();
|
|
1514
|
+
init_sqlite();
|
|
1515
|
+
sqlite.db.list = () => {
|
|
1516
|
+
const dbs = globalThis.__sqliteDbs;
|
|
1517
|
+
return dbs ? Object.keys(dbs) : [];
|
|
1518
|
+
};
|
|
1519
|
+
}
|
|
1520
|
+
});
|
|
1521
|
+
|
|
1522
|
+
// functions/sqlite/tools/db.size.ts
|
|
1523
|
+
var db_size_exports2 = {};
|
|
1524
|
+
var init_db_size2 = __esm({
|
|
1525
|
+
"functions/sqlite/tools/db.size.ts"() {
|
|
1526
|
+
init_esm_shims();
|
|
1527
|
+
init_sqlite();
|
|
1528
|
+
sqlite.db.size = async (name) => {
|
|
1529
|
+
const dbs = globalThis.__sqliteDbs;
|
|
1530
|
+
if (!dbs) return 0;
|
|
1531
|
+
const _bytes = /* @__PURE__ */ __name((b) => b ? b.byteLength || b.length || 0 : 0, "_bytes");
|
|
1532
|
+
if (name) {
|
|
1533
|
+
const db = sqlite.db.get(name);
|
|
1534
|
+
return _bytes(db.export());
|
|
1535
|
+
}
|
|
1536
|
+
let total = 0;
|
|
1537
|
+
for (const n of Object.keys(dbs)) {
|
|
1538
|
+
try {
|
|
1539
|
+
total += _bytes(dbs[n].export());
|
|
1540
|
+
} catch (_) {
|
|
1541
|
+
}
|
|
1542
|
+
}
|
|
1543
|
+
return total;
|
|
1544
|
+
};
|
|
1545
|
+
}
|
|
1546
|
+
});
|
|
1547
|
+
|
|
1548
|
+
// functions/sqlite/tools/db.export.ts
|
|
1549
|
+
var db_export_exports = {};
|
|
1550
|
+
var init_db_export = __esm({
|
|
1551
|
+
"functions/sqlite/tools/db.export.ts"() {
|
|
1552
|
+
init_esm_shims();
|
|
1553
|
+
init_sqlite();
|
|
1554
|
+
sqlite.db.export = async (name = "memorio") => {
|
|
1555
|
+
const db = sqlite.db.get(name);
|
|
1556
|
+
return db.export();
|
|
1557
|
+
};
|
|
1558
|
+
}
|
|
1559
|
+
});
|
|
1560
|
+
|
|
1561
|
+
// functions/sqlite/tools/db.import.ts
|
|
1562
|
+
var db_import_exports = {};
|
|
1563
|
+
var init_db_import = __esm({
|
|
1564
|
+
"functions/sqlite/tools/db.import.ts"() {
|
|
1565
|
+
init_esm_shims();
|
|
1566
|
+
init_sqlite();
|
|
1567
|
+
sqlite.db.import = async (name, data) => {
|
|
1568
|
+
return sqlite.db.create(name, { data });
|
|
1569
|
+
};
|
|
1570
|
+
}
|
|
1571
|
+
});
|
|
1572
|
+
|
|
1573
|
+
// functions/sqlite/crud/query.run.ts
|
|
1574
|
+
var query_run_exports = {};
|
|
1575
|
+
var init_query_run = __esm({
|
|
1576
|
+
"functions/sqlite/crud/query.run.ts"() {
|
|
1577
|
+
init_esm_shims();
|
|
1578
|
+
init_sqlite();
|
|
1579
|
+
init_message();
|
|
1580
|
+
sqlite.query.run = async (name = "memorio", sql, params = []) => {
|
|
1581
|
+
const db = sqlite.db.get(name);
|
|
1582
|
+
message_default(`Memorio SQLite: run -> ${sql}`);
|
|
1583
|
+
db.run(sql, params);
|
|
1584
|
+
return db.getRowsModified();
|
|
1585
|
+
};
|
|
1586
|
+
}
|
|
1587
|
+
});
|
|
1588
|
+
|
|
1589
|
+
// functions/sqlite/crud/query.select.ts
|
|
1590
|
+
var query_select_exports = {};
|
|
1591
|
+
var init_query_select = __esm({
|
|
1592
|
+
"functions/sqlite/crud/query.select.ts"() {
|
|
1593
|
+
init_esm_shims();
|
|
1594
|
+
init_sqlite();
|
|
1595
|
+
sqlite.query.select = async (name = "memorio", sql, params = []) => {
|
|
1596
|
+
const db = sqlite.db.get(name);
|
|
1597
|
+
const stmt = db.prepare(sql, params);
|
|
1598
|
+
const result = [];
|
|
1599
|
+
try {
|
|
1600
|
+
while (stmt.step()) {
|
|
1601
|
+
result.push(stmt.getAsObject());
|
|
1602
|
+
}
|
|
1603
|
+
} finally {
|
|
1604
|
+
try {
|
|
1605
|
+
stmt.free();
|
|
1606
|
+
} catch (_) {
|
|
1607
|
+
}
|
|
1608
|
+
}
|
|
1609
|
+
return result;
|
|
1610
|
+
};
|
|
1611
|
+
}
|
|
1612
|
+
});
|
|
1613
|
+
|
|
1614
|
+
// functions/sqlite/crud/data.set.ts
|
|
1615
|
+
var data_set_exports2 = {};
|
|
1616
|
+
var init_data_set2 = __esm({
|
|
1617
|
+
"functions/sqlite/crud/data.set.ts"() {
|
|
1618
|
+
init_esm_shims();
|
|
1619
|
+
init_sqlite();
|
|
1620
|
+
sqlite.data.set = async (name = "memorio", sql, params = []) => {
|
|
1621
|
+
return sqlite.query.run(name, sql, params);
|
|
1622
|
+
};
|
|
1623
|
+
}
|
|
1624
|
+
});
|
|
1625
|
+
|
|
1626
|
+
// functions/sqlite/crud/data.get.ts
|
|
1627
|
+
var data_get_exports2 = {};
|
|
1628
|
+
var init_data_get2 = __esm({
|
|
1629
|
+
"functions/sqlite/crud/data.get.ts"() {
|
|
1630
|
+
init_esm_shims();
|
|
1631
|
+
init_sqlite();
|
|
1632
|
+
sqlite.data.get = async (name = "memorio", sql, params = []) => {
|
|
1633
|
+
const rows = await sqlite.query.select(name, sql, params);
|
|
1634
|
+
return rows.length ? rows[0] : null;
|
|
1635
|
+
};
|
|
1636
|
+
}
|
|
1637
|
+
});
|
|
1638
|
+
|
|
1639
|
+
// functions/sqlite/index.ts
|
|
1640
|
+
var _hasSqlJs, sqlite;
|
|
1641
|
+
var init_sqlite = __esm({
|
|
1642
|
+
"functions/sqlite/index.ts"() {
|
|
1643
|
+
init_esm_shims();
|
|
1644
|
+
init_platform();
|
|
1645
|
+
init_env();
|
|
1646
|
+
_hasSqlJs = hasSqlJs();
|
|
1647
|
+
sqlite = {
|
|
1648
|
+
db: {},
|
|
1649
|
+
query: {},
|
|
1650
|
+
data: {}
|
|
1651
|
+
};
|
|
1652
|
+
sqlite.config = (opts) => {
|
|
1653
|
+
const g3 = globalThis;
|
|
1654
|
+
g3.sqliteConfig = { ...g3.sqliteConfig, ...opts };
|
|
1655
|
+
if (opts && opts.wasmUrl) {
|
|
1656
|
+
g3.sqliteWasmBase = opts.wasmUrl.endsWith("/") ? opts.wasmUrl : opts.wasmUrl + "/";
|
|
1657
|
+
}
|
|
1658
|
+
return sqlite;
|
|
1659
|
+
};
|
|
1660
|
+
Object.defineProperty(sqlite, "ready", {
|
|
1661
|
+
enumerable: false,
|
|
1662
|
+
configurable: false,
|
|
1663
|
+
get: /* @__PURE__ */ __name(() => {
|
|
1664
|
+
const g3 = globalThis;
|
|
1665
|
+
if (!g3.sqliteReady) {
|
|
1666
|
+
g3.sqliteReady = typeof sqlite.db.getSQL === "function" ? sqlite.db.getSQL().then(() => {
|
|
1667
|
+
}).catch(() => {
|
|
1668
|
+
}) : Promise.resolve();
|
|
1669
|
+
}
|
|
1670
|
+
return g3.sqliteReady;
|
|
1671
|
+
}, "get")
|
|
1672
|
+
});
|
|
1673
|
+
if (_hasSqlJs) {
|
|
1674
|
+
(async () => {
|
|
1675
|
+
Object.defineProperty(sqlite, "db", { value: {}, writable: false, configurable: true, enumerable: true });
|
|
1676
|
+
Object.defineProperty(sqlite, "query", { value: {}, writable: false, configurable: true, enumerable: true });
|
|
1677
|
+
Object.defineProperty(sqlite, "data", { value: {}, writable: false, configurable: true, enumerable: true });
|
|
1678
|
+
Object.defineProperty(globalThis, "sqlbases", {
|
|
1679
|
+
value: [],
|
|
1680
|
+
writable: true,
|
|
1681
|
+
configurable: true,
|
|
1682
|
+
enumerable: false
|
|
1683
|
+
});
|
|
1684
|
+
await Promise.all([
|
|
1685
|
+
Promise.resolve().then(() => (init_db_support2(), db_support_exports2)),
|
|
1686
|
+
Promise.resolve().then(() => (init_db_create2(), db_create_exports2)),
|
|
1687
|
+
Promise.resolve().then(() => (init_db_get(), db_get_exports)),
|
|
1688
|
+
Promise.resolve().then(() => (init_db_delete2(), db_delete_exports2)),
|
|
1689
|
+
Promise.resolve().then(() => (init_db_list2(), db_list_exports2)),
|
|
1690
|
+
Promise.resolve().then(() => (init_db_size2(), db_size_exports2)),
|
|
1691
|
+
Promise.resolve().then(() => (init_db_export(), db_export_exports)),
|
|
1692
|
+
Promise.resolve().then(() => (init_db_import(), db_import_exports)),
|
|
1693
|
+
Promise.resolve().then(() => (init_query_run(), query_run_exports)),
|
|
1694
|
+
Promise.resolve().then(() => (init_query_select(), query_select_exports)),
|
|
1695
|
+
Promise.resolve().then(() => (init_data_set2(), data_set_exports2)),
|
|
1696
|
+
Promise.resolve().then(() => (init_data_get2(), data_get_exports2))
|
|
1697
|
+
]);
|
|
1698
|
+
})();
|
|
1699
|
+
} else {
|
|
1700
|
+
sqlite._disabled = true;
|
|
1701
|
+
sqlite._warning = 'SQLite (sql.js) is not available in this environment. It requires a browser with WebAssembly support. Install the optional "sql.js" package to enable it.';
|
|
1702
|
+
if (DEV) {
|
|
1703
|
+
globalThis.sqliteDisabled = true;
|
|
1704
|
+
globalThis.sqliteWarning = sqlite._warning;
|
|
1705
|
+
console.warn("Memorio SQLite: sql.js is not available in this environment (requires browser + WebAssembly). Use store or session for persistence.");
|
|
1706
|
+
}
|
|
1707
|
+
}
|
|
1708
|
+
}
|
|
1709
|
+
});
|
|
1710
|
+
|
|
1711
|
+
// index.ts
|
|
1712
|
+
init_esm_shims();
|
|
1713
|
+
init_env();
|
|
1714
|
+
|
|
1715
|
+
// functions/state/index.ts
|
|
1716
|
+
init_esm_shims();
|
|
1717
|
+
init_internal();
|
|
1718
|
+
init_message();
|
|
1719
|
+
|
|
1720
|
+
// core/dispatch.ts
|
|
1721
|
+
init_esm_shims();
|
|
1722
|
+
var dispatch = {
|
|
1723
|
+
/**
|
|
1724
|
+
* Dispatches a custom event with the specified name and value.
|
|
1725
|
+
* @param name The name of the event.
|
|
1726
|
+
* @param value The value to pass with the event.
|
|
1727
|
+
*/
|
|
1728
|
+
set: /* @__PURE__ */ __name((name, value = {}) => {
|
|
1729
|
+
globalThis.dispatchEvent(new CustomEvent(String(name), value));
|
|
1730
|
+
}, "set"),
|
|
1731
|
+
///
|
|
1732
|
+
/**
|
|
1733
|
+
* Listens for the specified event names and executes the callback when the event is triggered.
|
|
1734
|
+
* @param name The name of the event to listen for.
|
|
1735
|
+
* @param cb The callback function to execute when the event is triggered.
|
|
1736
|
+
*/
|
|
1737
|
+
listen: /* @__PURE__ */ __name((name, cb = null, _flag) => {
|
|
1738
|
+
if (globalThis.events?.[name]) return;
|
|
1739
|
+
const exec = cb ? (e) => {
|
|
1740
|
+
const target = e;
|
|
1741
|
+
return globalThis.queueMicrotask ? globalThis.queueMicrotask(() => cb(target)) : Promise.resolve().then(() => cb(target));
|
|
1742
|
+
} : void 0;
|
|
1743
|
+
if (exec) globalThis.addEventListener(name, exec);
|
|
1744
|
+
if (exec) globalThis.events[name] = exec;
|
|
1745
|
+
}, "listen"),
|
|
1746
|
+
///
|
|
1747
|
+
/**
|
|
1748
|
+
* Removes the event listener for the specified event names.
|
|
1749
|
+
* @param name The name of the event to remove the listener for.
|
|
1750
|
+
*/
|
|
1751
|
+
remove: /* @__PURE__ */ __name((name) => {
|
|
1752
|
+
const listener = globalThis.events?.[name];
|
|
1753
|
+
if (listener) {
|
|
1754
|
+
globalThis.removeEventListener(name, listener);
|
|
1755
|
+
delete globalThis.events[name];
|
|
1756
|
+
}
|
|
1757
|
+
}, "remove")
|
|
1758
|
+
};
|
|
1759
|
+
|
|
1760
|
+
// functions/schema/index.ts
|
|
1761
|
+
init_esm_shims();
|
|
1762
|
+
init_message();
|
|
1763
|
+
var _schemas = /* @__PURE__ */ new Map();
|
|
1764
|
+
var _validateValue = /* @__PURE__ */ __name((value, schema2, path2) => {
|
|
1765
|
+
const errors = [];
|
|
1766
|
+
if (schema2.type && schema2.type !== "any") {
|
|
1767
|
+
const actualType = Array.isArray(value) ? "array" : typeof value;
|
|
1768
|
+
if (actualType !== schema2.type) {
|
|
1769
|
+
errors.push(`${path2}: expected ${schema2.type}, got ${actualType}`);
|
|
1770
|
+
return { valid: false, errors };
|
|
1771
|
+
}
|
|
1772
|
+
}
|
|
1773
|
+
if (schema2.enum && !schema2.enum.includes(value)) {
|
|
1774
|
+
errors.push(`${path2}: value must be one of [${schema2.enum.map(String).join(", ")}]`);
|
|
1775
|
+
}
|
|
1776
|
+
if (schema2.validator) {
|
|
1777
|
+
const result = schema2.validator(value);
|
|
1778
|
+
if (result !== true) {
|
|
1779
|
+
errors.push(`${path2}: ${typeof result === "string" ? result : "validation failed"}`);
|
|
1780
|
+
}
|
|
1781
|
+
}
|
|
1782
|
+
if (typeof value === "number") {
|
|
1783
|
+
if (schema2.min !== void 0 && value < schema2.min) {
|
|
1784
|
+
errors.push(`${path2}: value ${value} is less than minimum ${schema2.min}`);
|
|
1785
|
+
}
|
|
1786
|
+
if (schema2.max !== void 0 && value > schema2.max) {
|
|
1787
|
+
errors.push(`${path2}: value ${value} exceeds maximum ${schema2.max}`);
|
|
1788
|
+
}
|
|
1789
|
+
}
|
|
1790
|
+
if (typeof value === "string") {
|
|
1791
|
+
if (schema2.min !== void 0 && value.length < schema2.min) {
|
|
1792
|
+
errors.push(`${path2}: string length ${value.length} is less than minimum ${schema2.min}`);
|
|
1793
|
+
}
|
|
1794
|
+
if (schema2.max !== void 0 && value.length > schema2.max) {
|
|
1795
|
+
errors.push(`${path2}: string length ${value.length} exceeds maximum ${schema2.max}`);
|
|
1796
|
+
}
|
|
1797
|
+
if (schema2.pattern && !schema2.pattern.test(value)) {
|
|
1798
|
+
errors.push(`${path2}: string does not match required pattern`);
|
|
1799
|
+
}
|
|
1800
|
+
}
|
|
1801
|
+
if (schema2.type === "object" && value && typeof value === "object" && !Array.isArray(value)) {
|
|
1802
|
+
if (schema2.required) {
|
|
1803
|
+
for (const req of schema2.required) {
|
|
1804
|
+
if (!(req in value)) {
|
|
1805
|
+
errors.push(`${path2}: missing required property '${req}'`);
|
|
1806
|
+
}
|
|
1807
|
+
}
|
|
1808
|
+
}
|
|
1809
|
+
if (schema2.properties) {
|
|
1810
|
+
for (const [prop, propSchema] of Object.entries(schema2.properties)) {
|
|
1811
|
+
if (prop in value && value[prop] !== void 0) {
|
|
1812
|
+
const propResult = _validateValue(value[prop], propSchema, `${path2}.${prop}`);
|
|
1813
|
+
if (!propResult.valid) {
|
|
1814
|
+
errors.push(...propResult.errors || []);
|
|
1815
|
+
}
|
|
1816
|
+
}
|
|
1817
|
+
}
|
|
1818
|
+
}
|
|
1819
|
+
}
|
|
1820
|
+
return errors.length === 0 ? { valid: true } : { valid: false, errors };
|
|
1821
|
+
}, "_validateValue");
|
|
1822
|
+
var validate = /* @__PURE__ */ __name((path2, value) => {
|
|
1823
|
+
const schema2 = _schemas.get(path2);
|
|
1824
|
+
if (!schema2) {
|
|
1825
|
+
return { valid: true };
|
|
1826
|
+
}
|
|
1827
|
+
return _validateValue(value, schema2, path2);
|
|
1828
|
+
}, "validate");
|
|
1829
|
+
var registerSchema = /* @__PURE__ */ __name((path2, schema2) => {
|
|
1830
|
+
if (typeof schema2 === "function") {
|
|
1831
|
+
_schemas.set(path2, { validator: schema2 });
|
|
1832
|
+
} else {
|
|
1833
|
+
_schemas.set(path2, schema2);
|
|
1834
|
+
}
|
|
1835
|
+
message_default(`[memorio schema] Registered schema for '${path2}'`);
|
|
1836
|
+
}, "registerSchema");
|
|
1837
|
+
var unregisterSchema = /* @__PURE__ */ __name((path2) => {
|
|
1838
|
+
return _schemas.delete(path2);
|
|
1839
|
+
}, "unregisterSchema");
|
|
1840
|
+
var listSchemas = /* @__PURE__ */ __name(() => {
|
|
1841
|
+
return Array.from(_schemas.keys());
|
|
1842
|
+
}, "listSchemas");
|
|
1843
|
+
var getSchema = /* @__PURE__ */ __name((path2) => {
|
|
1844
|
+
return _schemas.get(path2);
|
|
1845
|
+
}, "getSchema");
|
|
1846
|
+
var schema = {
|
|
1847
|
+
register: registerSchema,
|
|
1848
|
+
validate,
|
|
1849
|
+
unregister: unregisterSchema,
|
|
1850
|
+
list: listSchemas,
|
|
1851
|
+
get: getSchema
|
|
1852
|
+
};
|
|
1853
|
+
|
|
1854
|
+
// functions/state/index.ts
|
|
1855
|
+
init_env();
|
|
1856
|
+
var TARGET = /* @__PURE__ */ Symbol("memorio.target");
|
|
1857
|
+
var wrapperCache = /* @__PURE__ */ new WeakMap();
|
|
1858
|
+
var deepRaw = /* @__PURE__ */ __name((val, seen = null) => {
|
|
1859
|
+
if (val === null || typeof val !== "object") return val;
|
|
1860
|
+
if (val[TARGET] !== void 0) return deepRaw(val[TARGET], seen);
|
|
1861
|
+
if (seen) {
|
|
1862
|
+
if (seen.has(val)) return val;
|
|
1863
|
+
seen.add(val);
|
|
1864
|
+
}
|
|
1865
|
+
const ctor = val.constructor?.name;
|
|
1866
|
+
if (ctor !== "Object" && ctor !== "Array") return val;
|
|
1867
|
+
const copy = Array.isArray(val) ? [] : {};
|
|
1868
|
+
for (const k of Reflect.ownKeys(val)) {
|
|
1869
|
+
copy[k] = deepRaw(val[k], seen);
|
|
1870
|
+
}
|
|
1871
|
+
return copy;
|
|
1872
|
+
}, "deepRaw");
|
|
1873
|
+
var objPath = /* @__PURE__ */ __name((prop, object, separator = ".") => {
|
|
1874
|
+
return object.concat(prop).join(separator);
|
|
1875
|
+
}, "objPath");
|
|
1876
|
+
var buildProxy = /* @__PURE__ */ __name((obj, callback, tree = []) => {
|
|
1877
|
+
const event = /* @__PURE__ */ __name((name) => {
|
|
1878
|
+
try {
|
|
1879
|
+
dispatch.set(name, { detail: { name } });
|
|
1880
|
+
} catch (_) {
|
|
1881
|
+
}
|
|
1882
|
+
return;
|
|
1883
|
+
}, "event");
|
|
1884
|
+
return new Proxy(
|
|
1885
|
+
obj,
|
|
1886
|
+
{
|
|
1887
|
+
get(target, prop) {
|
|
1888
|
+
if (prop === "__path") {
|
|
1889
|
+
return tree.length > 0 ? "state." + tree.join(".") : "state";
|
|
1890
|
+
}
|
|
1891
|
+
if (prop === TARGET) {
|
|
1892
|
+
return target;
|
|
1893
|
+
}
|
|
1894
|
+
if (target[TARGET] !== void 0) {
|
|
1895
|
+
return target;
|
|
1896
|
+
}
|
|
1897
|
+
if (prop === "list") {
|
|
1898
|
+
message_default('Some state could be hidden when you use "state.list". Use "state" to see the complete list ');
|
|
1899
|
+
return JSON.parse(JSON.stringify(target));
|
|
1900
|
+
}
|
|
1901
|
+
if (typeof prop === "string") {
|
|
1902
|
+
const path2 = tree.length > 0 ? "state." + tree.concat(prop).join(".") : "state." + prop;
|
|
1903
|
+
internal_default.lastAccessedPath = path2;
|
|
1904
|
+
if (internal_default.tracking) {
|
|
1905
|
+
internal_default.trackedPaths.add(path2);
|
|
1906
|
+
}
|
|
1907
|
+
}
|
|
1908
|
+
if (prop === "_lastPath") {
|
|
1909
|
+
return internal_default.lastAccessedPath;
|
|
1910
|
+
}
|
|
1911
|
+
if (prop === "remove") {
|
|
1912
|
+
return (key) => {
|
|
1913
|
+
delete target[key];
|
|
1914
|
+
return true;
|
|
1915
|
+
};
|
|
1916
|
+
}
|
|
1917
|
+
if (prop === "removeAll") {
|
|
1918
|
+
return () => {
|
|
1919
|
+
try {
|
|
1920
|
+
for (const key in target) {
|
|
1921
|
+
if (typeof target[key] !== "function" && !["list", "remove", "removeAll", "lock", "unlock"].includes(key)) {
|
|
1922
|
+
delete target[key];
|
|
1923
|
+
}
|
|
1924
|
+
}
|
|
1925
|
+
} catch (error) {
|
|
1926
|
+
console.error(error);
|
|
1927
|
+
}
|
|
1928
|
+
return;
|
|
1929
|
+
};
|
|
1930
|
+
}
|
|
1931
|
+
if (Object.isFrozen(target[prop])) return target[prop];
|
|
1932
|
+
if (prop === "lock" || prop === "unlock") {
|
|
1933
|
+
const value = Reflect.get(target, prop);
|
|
1934
|
+
if (value) return value;
|
|
1935
|
+
}
|
|
1936
|
+
try {
|
|
1937
|
+
const value = Reflect.get(target, prop);
|
|
1938
|
+
if (value && typeof value === "object" && ["Array", "Object"].includes(value.constructor.name)) {
|
|
1939
|
+
let wrapper = wrapperCache.get(value);
|
|
1940
|
+
if (!wrapper) {
|
|
1941
|
+
wrapper = buildProxy(value, callback, tree.concat(prop));
|
|
1942
|
+
wrapperCache.set(value, wrapper);
|
|
1943
|
+
}
|
|
1944
|
+
return wrapper;
|
|
1945
|
+
}
|
|
1946
|
+
return value;
|
|
1947
|
+
} catch (error) {
|
|
1948
|
+
console.error("Error: ", error);
|
|
1949
|
+
return void 0;
|
|
1950
|
+
}
|
|
1951
|
+
},
|
|
1952
|
+
set(target, key, value) {
|
|
1953
|
+
if (internal_default.locked) {
|
|
1954
|
+
console.error("Error: state is locked. Use state.unlock() to enable modifications.");
|
|
1955
|
+
return false;
|
|
1956
|
+
}
|
|
1957
|
+
if (protect.includes(key)) {
|
|
1958
|
+
console.error("key " + key + " is protected");
|
|
1959
|
+
return false;
|
|
1960
|
+
}
|
|
1961
|
+
if (target[key] && typeof target[key] === "object" && Object.isFrozen(target[key])) {
|
|
1962
|
+
console.error(`Error: state '${key}' is locked`);
|
|
1963
|
+
return false;
|
|
1964
|
+
}
|
|
1965
|
+
if (target[key] && typeof target[key] === "object" && target[key].__locked) {
|
|
1966
|
+
console.error(`Error: state '${key}' is locked. Use state.${key}.unlock() to enable modifications.`);
|
|
1967
|
+
return false;
|
|
1968
|
+
}
|
|
1969
|
+
try {
|
|
1970
|
+
const path2 = objPath(key, tree);
|
|
1971
|
+
const rawValue = deepRaw(value);
|
|
1972
|
+
const _schemaResult = schema.validate(path2, rawValue);
|
|
1973
|
+
if (!_schemaResult.valid) {
|
|
1974
|
+
if (DEV && internal_default.debug) {
|
|
1975
|
+
console.error(
|
|
1976
|
+
`[memorio schema] Validation failed for '${path2}':`,
|
|
1977
|
+
_schemaResult.errors
|
|
1978
|
+
);
|
|
1979
|
+
}
|
|
1980
|
+
message_default(
|
|
1981
|
+
`[memorio schema] Validation failed for '${path2}': ` + (_schemaResult.errors?.join(", ") || "unknown error")
|
|
1982
|
+
);
|
|
1983
|
+
return false;
|
|
1984
|
+
}
|
|
1985
|
+
callback(
|
|
1986
|
+
{
|
|
1987
|
+
action: "set",
|
|
1988
|
+
path: path2,
|
|
1989
|
+
target,
|
|
1990
|
+
newValue: rawValue,
|
|
1991
|
+
previousValue: Reflect.get(target, key)
|
|
1992
|
+
}
|
|
1993
|
+
);
|
|
1994
|
+
event("state." + path2);
|
|
1995
|
+
Reflect.set(target, key, rawValue);
|
|
1996
|
+
internal_default.bumpStateVersion();
|
|
1997
|
+
if (target[key] && typeof target[key] === "object") {
|
|
1998
|
+
const lockValue = target[key];
|
|
1999
|
+
if (lockValue && typeof lockValue === "object") {
|
|
2000
|
+
try {
|
|
2001
|
+
Object.defineProperty(lockValue, "__locked", {
|
|
2002
|
+
writable: true,
|
|
2003
|
+
enumerable: false,
|
|
2004
|
+
configurable: false,
|
|
2005
|
+
value: false
|
|
2006
|
+
});
|
|
2007
|
+
Object.defineProperty(lockValue, "lock", {
|
|
2008
|
+
writable: false,
|
|
2009
|
+
enumerable: false,
|
|
2010
|
+
configurable: false,
|
|
2011
|
+
value: /* @__PURE__ */ __name(() => {
|
|
2012
|
+
Object.defineProperty(lockValue, "__locked", {
|
|
2013
|
+
writable: true,
|
|
2014
|
+
enumerable: false,
|
|
2015
|
+
configurable: false,
|
|
2016
|
+
value: true
|
|
2017
|
+
});
|
|
2018
|
+
message_default(`State '${key}' is now locked.`);
|
|
2019
|
+
}, "value")
|
|
2020
|
+
});
|
|
2021
|
+
Object.defineProperty(lockValue, "unlock", {
|
|
2022
|
+
writable: false,
|
|
2023
|
+
enumerable: false,
|
|
2024
|
+
configurable: false,
|
|
2025
|
+
value: /* @__PURE__ */ __name(() => {
|
|
2026
|
+
Object.defineProperty(lockValue, "__locked", {
|
|
2027
|
+
writable: true,
|
|
2028
|
+
enumerable: false,
|
|
2029
|
+
configurable: false,
|
|
2030
|
+
value: false
|
|
2031
|
+
});
|
|
2032
|
+
message_default(`State '${key}' is now unlocked.`);
|
|
2033
|
+
}, "value")
|
|
2034
|
+
});
|
|
2035
|
+
} catch (_) {
|
|
2036
|
+
}
|
|
2037
|
+
}
|
|
2038
|
+
}
|
|
2039
|
+
return true;
|
|
2040
|
+
} catch (error) {
|
|
2041
|
+
console.error("Error in set trap:", error);
|
|
2042
|
+
return false;
|
|
2043
|
+
}
|
|
2044
|
+
},
|
|
2045
|
+
deleteProperty(target, prop) {
|
|
2046
|
+
try {
|
|
2047
|
+
const path2 = objPath(prop, tree);
|
|
2048
|
+
const previousValue = Reflect.get(target, prop);
|
|
2049
|
+
callback({ action: "delete", path: path2, target, previousValue });
|
|
2050
|
+
return Reflect.deleteProperty(target, prop);
|
|
2051
|
+
} catch (error) {
|
|
2052
|
+
console.error("Error in deleteProperty trap:", error);
|
|
2053
|
+
return false;
|
|
2054
|
+
}
|
|
2055
|
+
},
|
|
2056
|
+
ownKeys(target) {
|
|
2057
|
+
return Reflect.ownKeys(target);
|
|
2058
|
+
},
|
|
2059
|
+
getOwnPropertyDescriptor(target, prop) {
|
|
2060
|
+
return Reflect.getOwnPropertyDescriptor(target, prop);
|
|
2061
|
+
}
|
|
2062
|
+
}
|
|
2063
|
+
);
|
|
2064
|
+
}, "buildProxy");
|
|
2065
|
+
var STATE_INSTANCE_KEY = "__memorio_state_instance__";
|
|
2066
|
+
var state2;
|
|
2067
|
+
if (globalThis[STATE_INSTANCE_KEY]) {
|
|
2068
|
+
state2 = globalThis[STATE_INSTANCE_KEY];
|
|
2069
|
+
} else {
|
|
2070
|
+
state2 = buildProxy({}, (mutation) => {
|
|
2071
|
+
if (internal_default.historyEnabled) {
|
|
2072
|
+
internal_default.recordMutation({
|
|
2073
|
+
path: mutation.path,
|
|
2074
|
+
action: mutation.action,
|
|
2075
|
+
newValue: mutation.newValue,
|
|
2076
|
+
previousValue: mutation.previousValue,
|
|
2077
|
+
timestamp: Date.now()
|
|
2078
|
+
});
|
|
2079
|
+
}
|
|
2080
|
+
});
|
|
2081
|
+
state2.lock = () => {
|
|
2082
|
+
internal_default.locked = true;
|
|
2083
|
+
message_default("State is now locked. All modifications are blocked.");
|
|
2084
|
+
};
|
|
2085
|
+
state2.unlock = () => {
|
|
2086
|
+
internal_default.locked = false;
|
|
2087
|
+
message_default("State is now unlocked. Modifications are allowed.");
|
|
2088
|
+
};
|
|
2089
|
+
globalThis[STATE_INSTANCE_KEY] = state2;
|
|
2090
|
+
}
|
|
2091
|
+
|
|
2092
|
+
// index.ts
|
|
2093
|
+
init_store();
|
|
2094
|
+
|
|
2095
|
+
// functions/session/index.ts
|
|
2096
|
+
init_esm_shims();
|
|
2097
|
+
init_platform();
|
|
2098
|
+
init_internal();
|
|
2099
|
+
init_message();
|
|
2100
|
+
var _sessionStorage = getSessionStorage();
|
|
2101
|
+
var _fallbackStorageByContext2 = /* @__PURE__ */ new Map();
|
|
2102
|
+
function _getFallbackStorage2() {
|
|
2103
|
+
const contextName = internal_default.currentContext || "";
|
|
2104
|
+
const key = contextName || "default";
|
|
2105
|
+
if (!_fallbackStorageByContext2.has(key)) {
|
|
2106
|
+
_fallbackStorageByContext2.set(key, /* @__PURE__ */ new Map());
|
|
2107
|
+
}
|
|
2108
|
+
return _fallbackStorageByContext2.get(key);
|
|
2109
|
+
}
|
|
2110
|
+
__name(_getFallbackStorage2, "_getFallbackStorage");
|
|
2111
|
+
var _hasStorage2 = _sessionStorage !== null;
|
|
2112
|
+
function _getPrefix2() {
|
|
2113
|
+
const contextName = internal_default.currentContext || "";
|
|
2114
|
+
return contextName ? `${contextName}-` : `memorio_session_`;
|
|
2115
|
+
}
|
|
2116
|
+
__name(_getPrefix2, "_getPrefix");
|
|
2117
|
+
function _prefixKey2(name) {
|
|
2118
|
+
if (!name || typeof name !== "string") {
|
|
2119
|
+
console.warn("[memorio session] key is empty or not a string - operation aborted");
|
|
2120
|
+
return "";
|
|
2121
|
+
}
|
|
2122
|
+
if (name.length > 512) {
|
|
2123
|
+
console.warn(`[memorio session] key "${name}" exceeds 512 chars - operation aborted`);
|
|
2124
|
+
return "";
|
|
2125
|
+
}
|
|
2126
|
+
return _getPrefix2() + name;
|
|
2127
|
+
}
|
|
2128
|
+
__name(_prefixKey2, "_prefixKey");
|
|
2129
|
+
function _read2(prefixedName) {
|
|
2130
|
+
const raw = _hasStorage2 ? _sessionStorage.getItem(prefixedName) : _getFallbackStorage2().get(prefixedName);
|
|
2131
|
+
return raw ? JSON.parse(raw) : raw;
|
|
2132
|
+
}
|
|
2133
|
+
__name(_read2, "_read");
|
|
2134
|
+
function _write2(prefixedName, value) {
|
|
2135
|
+
const json = JSON.stringify(value);
|
|
2136
|
+
if (_hasStorage2) _sessionStorage.setItem(prefixedName, json);
|
|
2137
|
+
else _getFallbackStorage2().set(prefixedName, json);
|
|
2138
|
+
}
|
|
2139
|
+
__name(_write2, "_write");
|
|
2140
|
+
function _remove2(prefixedName) {
|
|
2141
|
+
if (_hasStorage2) {
|
|
2142
|
+
if (_sessionStorage.getItem(prefixedName)) {
|
|
2143
|
+
_sessionStorage.removeItem(prefixedName);
|
|
2144
|
+
return true;
|
|
2145
|
+
}
|
|
2146
|
+
} else if (_getFallbackStorage2().has(prefixedName)) {
|
|
2147
|
+
_getFallbackStorage2().delete(prefixedName);
|
|
2148
|
+
return true;
|
|
2149
|
+
}
|
|
2150
|
+
return false;
|
|
2151
|
+
}
|
|
2152
|
+
__name(_remove2, "_remove");
|
|
2153
|
+
var SESSION_INSTANCE_KEY = "__memorio_session_instance__";
|
|
2154
|
+
var session;
|
|
2155
|
+
if (globalThis[SESSION_INSTANCE_KEY]) {
|
|
2156
|
+
session = globalThis[SESSION_INSTANCE_KEY];
|
|
2157
|
+
} else {
|
|
2158
|
+
session = new Proxy({}, {});
|
|
2159
|
+
Object.defineProperties(
|
|
2160
|
+
session,
|
|
2161
|
+
{
|
|
2162
|
+
/**
|
|
2163
|
+
* Gets a value from storage.
|
|
2164
|
+
* @param name The key to retrieve.
|
|
2165
|
+
* @returns The parsed value or null if not found.
|
|
2166
|
+
*/
|
|
2167
|
+
get: {
|
|
2168
|
+
value: /* @__PURE__ */ __name((name) => {
|
|
2169
|
+
if (!name) {
|
|
2170
|
+
console.warn("[memorio session] session.get() called with empty or null key - returning null");
|
|
2171
|
+
return null;
|
|
2172
|
+
}
|
|
2173
|
+
try {
|
|
2174
|
+
return _read2(_prefixKey2(name));
|
|
2175
|
+
} catch (err) {
|
|
2176
|
+
message(`Error parsing session item '${name}':${err}`);
|
|
2177
|
+
}
|
|
2178
|
+
return null;
|
|
2179
|
+
}, "value")
|
|
2180
|
+
},
|
|
2181
|
+
/**
|
|
2182
|
+
* Sets a value in storage.
|
|
2183
|
+
* @param name The key to set.
|
|
2184
|
+
* @param value The value to store.
|
|
2185
|
+
* @returns true if written, false if the key was rejected.
|
|
2186
|
+
*/
|
|
2187
|
+
set: {
|
|
2188
|
+
value: /* @__PURE__ */ __name((name, value) => {
|
|
2189
|
+
if (!name) {
|
|
2190
|
+
console.warn("[memorio session] session.set() called with empty or null key - write aborted");
|
|
2191
|
+
return false;
|
|
2192
|
+
}
|
|
2193
|
+
const prefixedName = _prefixKey2(name);
|
|
2194
|
+
if (!prefixedName) return false;
|
|
2195
|
+
if (typeof value === "function") {
|
|
2196
|
+
console.warn("[memorio session] functions are not storable - write aborted for key: " + name);
|
|
2197
|
+
message("It's not secure to session functions.");
|
|
2198
|
+
return false;
|
|
2199
|
+
}
|
|
2200
|
+
try {
|
|
2201
|
+
_write2(prefixedName, value);
|
|
2202
|
+
} catch (err) {
|
|
2203
|
+
message(`Error setting session item '${name}': ${err}`);
|
|
2204
|
+
return false;
|
|
2205
|
+
}
|
|
2206
|
+
return true;
|
|
2207
|
+
}, "value")
|
|
2208
|
+
},
|
|
2209
|
+
/**
|
|
2210
|
+
* Removes a value from storage.
|
|
2211
|
+
* @param name The key to remove.
|
|
2212
|
+
* @returns True if removed.
|
|
2213
|
+
*/
|
|
2214
|
+
remove: {
|
|
2215
|
+
value: /* @__PURE__ */ __name((name) => {
|
|
2216
|
+
if (!name) {
|
|
2217
|
+
console.warn("[memorio session] session.remove() called with empty or null key - returning false");
|
|
2218
|
+
return false;
|
|
2219
|
+
}
|
|
2220
|
+
const prefixedName = _prefixKey2(name);
|
|
2221
|
+
if (!prefixedName) return false;
|
|
2222
|
+
try {
|
|
2223
|
+
return _remove2(prefixedName);
|
|
2224
|
+
} catch (err) {
|
|
2225
|
+
message(`Error removing session item '${name}': ${err}`);
|
|
2226
|
+
}
|
|
2227
|
+
return false;
|
|
2228
|
+
}, "value")
|
|
2229
|
+
},
|
|
2230
|
+
/**
|
|
2231
|
+
* Alias for remove.
|
|
2232
|
+
* @param name The key to delete.
|
|
2233
|
+
* @returns True if removed.
|
|
2234
|
+
*/
|
|
2235
|
+
delete: {
|
|
2236
|
+
value: /* @__PURE__ */ __name((name) => {
|
|
2237
|
+
return session.remove(name);
|
|
2238
|
+
}, "value")
|
|
2239
|
+
},
|
|
2240
|
+
/**
|
|
2241
|
+
* Clears all sessionStorage items.
|
|
2242
|
+
*/
|
|
2243
|
+
removeAll: {
|
|
2244
|
+
value: /* @__PURE__ */ __name(() => {
|
|
2245
|
+
if (_hasStorage2) {
|
|
2246
|
+
const keysToRemove = [];
|
|
2247
|
+
for (let i = 0; i < _sessionStorage.length; i++) {
|
|
2248
|
+
const key = _sessionStorage.key(i);
|
|
2249
|
+
if (key?.startsWith(_getPrefix2())) {
|
|
2250
|
+
keysToRemove.push(key);
|
|
2251
|
+
}
|
|
2252
|
+
}
|
|
2253
|
+
keysToRemove.forEach((key) => _sessionStorage.removeItem(key));
|
|
2254
|
+
} else {
|
|
2255
|
+
_getFallbackStorage2().clear();
|
|
2256
|
+
}
|
|
2257
|
+
return true;
|
|
2258
|
+
}, "value")
|
|
2259
|
+
},
|
|
2260
|
+
/**
|
|
2261
|
+
* Alias for removeAll.
|
|
2262
|
+
*/
|
|
2263
|
+
clearAll: {
|
|
2264
|
+
value: /* @__PURE__ */ __name(() => {
|
|
2265
|
+
session.removeAll();
|
|
2266
|
+
return true;
|
|
2267
|
+
}, "value")
|
|
2268
|
+
},
|
|
2269
|
+
quota: {
|
|
2270
|
+
value: /* @__PURE__ */ __name(async () => {
|
|
2271
|
+
return [0, 0];
|
|
2272
|
+
}, "value")
|
|
2273
|
+
},
|
|
2274
|
+
/**
|
|
2275
|
+
* Gets total size of all sessionStorage items.
|
|
2276
|
+
* @returns Total size in characters.
|
|
2277
|
+
*/
|
|
2278
|
+
size: {
|
|
2279
|
+
value: /* @__PURE__ */ __name(() => {
|
|
2280
|
+
let totalSize = 0;
|
|
2281
|
+
if (_hasStorage2) {
|
|
2282
|
+
Object.keys(_sessionStorage).forEach(
|
|
2283
|
+
(key) => {
|
|
2284
|
+
if (key.startsWith(_getPrefix2())) {
|
|
2285
|
+
const item = _sessionStorage.getItem(key);
|
|
2286
|
+
if (item) totalSize += item.length;
|
|
2287
|
+
}
|
|
2288
|
+
}
|
|
2289
|
+
);
|
|
2290
|
+
} else {
|
|
2291
|
+
_getFallbackStorage2().forEach((value) => {
|
|
2292
|
+
totalSize += value.length;
|
|
2293
|
+
});
|
|
2294
|
+
}
|
|
2295
|
+
return totalSize;
|
|
2296
|
+
}, "value")
|
|
2297
|
+
},
|
|
2298
|
+
/**
|
|
2299
|
+
* Check if using real sessionStorage or fallback
|
|
2300
|
+
*/
|
|
2301
|
+
isPersistent: {
|
|
2302
|
+
get: /* @__PURE__ */ __name(() => _hasStorage2, "get")
|
|
2303
|
+
},
|
|
2304
|
+
/**
|
|
2305
|
+
* Get a list of all memorio session items.
|
|
2306
|
+
*/
|
|
2307
|
+
list: {
|
|
2308
|
+
value: /* @__PURE__ */ __name(() => {
|
|
2309
|
+
const result = {};
|
|
2310
|
+
try {
|
|
2311
|
+
if (_hasStorage2) {
|
|
2312
|
+
for (let i = 0; i < _sessionStorage.length; i++) {
|
|
2313
|
+
const key = _sessionStorage.key(i);
|
|
2314
|
+
if (key?.startsWith(_getPrefix2())) {
|
|
2315
|
+
const cleanKey = key.replace(_getPrefix2(), "");
|
|
2316
|
+
const item = _sessionStorage.getItem(key);
|
|
2317
|
+
if (item !== null) {
|
|
2318
|
+
try {
|
|
2319
|
+
result[cleanKey] = JSON.parse(item);
|
|
2320
|
+
} catch {
|
|
2321
|
+
result[cleanKey] = item;
|
|
2322
|
+
}
|
|
2323
|
+
}
|
|
2324
|
+
}
|
|
2325
|
+
}
|
|
2326
|
+
} else {
|
|
2327
|
+
_getFallbackStorage2().forEach((value, key) => {
|
|
2328
|
+
if (key.startsWith(_getPrefix2())) {
|
|
2329
|
+
const cleanKey = key.replace(_getPrefix2(), "");
|
|
2330
|
+
try {
|
|
2331
|
+
result[cleanKey] = JSON.parse(value);
|
|
2332
|
+
} catch {
|
|
2333
|
+
result[cleanKey] = value;
|
|
2334
|
+
}
|
|
2335
|
+
}
|
|
2336
|
+
});
|
|
2337
|
+
}
|
|
2338
|
+
} catch (err) {
|
|
2339
|
+
message(`Error listing session items: ${err}`);
|
|
2340
|
+
}
|
|
2341
|
+
return result;
|
|
2342
|
+
}, "value")
|
|
2343
|
+
}
|
|
2344
|
+
}
|
|
2345
|
+
);
|
|
2346
|
+
Object.freeze(session);
|
|
2347
|
+
globalThis[SESSION_INSTANCE_KEY] = session;
|
|
2348
|
+
}
|
|
2349
|
+
|
|
2350
|
+
// functions/cache/index.ts
|
|
2351
|
+
init_esm_shims();
|
|
2352
|
+
var CACHE_INSTANCE_KEY = "__memorio_cache_instance__";
|
|
2353
|
+
var cacheData = {};
|
|
2354
|
+
var cache = globalThis[CACHE_INSTANCE_KEY] ? globalThis[CACHE_INSTANCE_KEY] : new Proxy({}, {
|
|
2355
|
+
get(target, prop) {
|
|
2356
|
+
const key = prop;
|
|
2357
|
+
if (key === "get") return (name) => cacheData[name];
|
|
2358
|
+
if (key === "set") return (name, value) => {
|
|
2359
|
+
cacheData[name] = value;
|
|
2360
|
+
};
|
|
2361
|
+
if (key === "remove") return (name) => {
|
|
2362
|
+
delete cacheData[name];
|
|
2363
|
+
return true;
|
|
2364
|
+
};
|
|
2365
|
+
if (key === "removeAll") return () => {
|
|
2366
|
+
Object.keys(cacheData).forEach((k) => delete cacheData[k]);
|
|
2367
|
+
return true;
|
|
2368
|
+
};
|
|
2369
|
+
if (key === "clear") return () => {
|
|
2370
|
+
Object.keys(cacheData).forEach((k) => delete cacheData[k]);
|
|
2371
|
+
return true;
|
|
2372
|
+
};
|
|
2373
|
+
if (key === "list") return () => ({ ...cacheData });
|
|
2374
|
+
return cacheData[key];
|
|
2375
|
+
},
|
|
2376
|
+
set(target, prop, value) {
|
|
2377
|
+
cacheData[prop] = value;
|
|
2378
|
+
return true;
|
|
2379
|
+
},
|
|
2380
|
+
deleteProperty(target, prop) {
|
|
2381
|
+
delete cacheData[prop];
|
|
2382
|
+
return true;
|
|
2383
|
+
}
|
|
2384
|
+
});
|
|
2385
|
+
if (!globalThis[CACHE_INSTANCE_KEY]) {
|
|
2386
|
+
globalThis[CACHE_INSTANCE_KEY] = cache;
|
|
2387
|
+
if (!Object.isFrozen(cache)) {
|
|
2388
|
+
Object.freeze(cache);
|
|
2389
|
+
}
|
|
2390
|
+
}
|
|
2391
|
+
|
|
2392
|
+
// index.ts
|
|
2393
|
+
init_idb();
|
|
2394
|
+
init_sqlite();
|
|
2395
|
+
|
|
2396
|
+
// functions/observer/index.ts
|
|
2397
|
+
init_esm_shims();
|
|
2398
|
+
init_message();
|
|
2399
|
+
var observerFunction = /* @__PURE__ */ __name((s, cb = null, option = true) => {
|
|
2400
|
+
const resolvePath = /* @__PURE__ */ __name((path3) => {
|
|
2401
|
+
if (typeof path3 === "string") return path3;
|
|
2402
|
+
if (path3 && typeof path3 === "object" && path3.__path) return path3.__path;
|
|
2403
|
+
return null;
|
|
2404
|
+
}, "resolvePath");
|
|
2405
|
+
const path2 = resolvePath(s);
|
|
2406
|
+
if (!s && !cb) {
|
|
2407
|
+
console.error("Observer Error: You need to setup observer correctly, Some parameters are missed!");
|
|
2408
|
+
return;
|
|
2409
|
+
}
|
|
2410
|
+
if (!s && cb) {
|
|
2411
|
+
console.error(`Observer Error: You need to declare what state need to be monitored as string like 'state.test'.`);
|
|
2412
|
+
return;
|
|
2413
|
+
}
|
|
2414
|
+
if (path2) {
|
|
2415
|
+
const t = path2.split(".");
|
|
2416
|
+
if (t[0] !== "state" && t[0] !== "store") {
|
|
2417
|
+
console.error(`Observer Error: You need to declare 'state.' or 'store.'. The '${path2}' string is incorrect!`);
|
|
2418
|
+
return;
|
|
2419
|
+
}
|
|
2420
|
+
}
|
|
2421
|
+
if (s && !cb) {
|
|
2422
|
+
const resolvedPath = resolvePath(s);
|
|
2423
|
+
if (!resolvedPath) return;
|
|
2424
|
+
const obs = globalThis.observer;
|
|
2425
|
+
if (obs?.list?.[resolvedPath]) dispatch.remove(resolvedPath);
|
|
2426
|
+
message_default(`called: ${resolvedPath}`);
|
|
2427
|
+
return;
|
|
2428
|
+
}
|
|
2429
|
+
if (s && cb) {
|
|
2430
|
+
const resolvedPath = resolvePath(s);
|
|
2431
|
+
if (!resolvedPath) return;
|
|
2432
|
+
if (typeof s !== "string" && !(s && typeof s === "object")) {
|
|
2433
|
+
console.error(`Observer Error: name of state need to be a 'string' like 'state.test' or a direct state value`);
|
|
2434
|
+
return;
|
|
2435
|
+
}
|
|
2436
|
+
const callbacks = Array.isArray(cb) ? cb : [cb];
|
|
2437
|
+
const obs = globalThis.observer;
|
|
2438
|
+
if (obs?.list?.[resolvedPath]) dispatch.remove(resolvedPath);
|
|
2439
|
+
callbacks.forEach((callback) => {
|
|
2440
|
+
if (typeof callback === "function") {
|
|
2441
|
+
dispatch.listen(resolvedPath, callback, option);
|
|
2442
|
+
}
|
|
2443
|
+
});
|
|
2444
|
+
return;
|
|
2445
|
+
}
|
|
2446
|
+
}, "observerFunction");
|
|
2447
|
+
var observer = observerFunction;
|
|
2448
|
+
Object.defineProperties(
|
|
2449
|
+
observer,
|
|
2450
|
+
{
|
|
2451
|
+
/**
|
|
2452
|
+
* See the list of all your observer (eventListener) actually installed.
|
|
2453
|
+
* @returns The list of all installed observers.
|
|
2454
|
+
*/
|
|
2455
|
+
list: {
|
|
2456
|
+
get: /* @__PURE__ */ __name(() => globalThis.events, "get")
|
|
2457
|
+
},
|
|
2458
|
+
///
|
|
2459
|
+
/**
|
|
2460
|
+
* Remove an observer.
|
|
2461
|
+
* @param name The name of the observer to remove.
|
|
2462
|
+
*/
|
|
2463
|
+
remove: {
|
|
2464
|
+
value: /* @__PURE__ */ __name((name) => {
|
|
2465
|
+
if (!name) return;
|
|
2466
|
+
dispatch.remove(name);
|
|
2467
|
+
delete globalThis.events[name];
|
|
2468
|
+
return;
|
|
2469
|
+
}, "value")
|
|
2470
|
+
},
|
|
2471
|
+
///
|
|
2472
|
+
/**
|
|
2473
|
+
* Remove all observers.
|
|
2474
|
+
* @returns void
|
|
2475
|
+
*/
|
|
2476
|
+
removeAll: {
|
|
2477
|
+
get: /* @__PURE__ */ __name(() => {
|
|
2478
|
+
const obs = globalThis.observer;
|
|
2479
|
+
const list = obs?.list;
|
|
2480
|
+
if (list) {
|
|
2481
|
+
Object.keys(list).forEach((key) => {
|
|
2482
|
+
obs?.remove?.(key);
|
|
2483
|
+
});
|
|
2484
|
+
}
|
|
2485
|
+
return true;
|
|
2486
|
+
}, "get")
|
|
2487
|
+
},
|
|
2488
|
+
///
|
|
2489
|
+
/**
|
|
2490
|
+
* Check if an observer exists for the given path.
|
|
2491
|
+
* @param name The state path to check.
|
|
2492
|
+
* @returns true if an observer exists for the path, false otherwise.
|
|
2493
|
+
*/
|
|
2494
|
+
has: {
|
|
2495
|
+
value: /* @__PURE__ */ __name((name) => {
|
|
2496
|
+
const obs = globalThis.observer;
|
|
2497
|
+
return !!obs?.list?.[name];
|
|
2498
|
+
}, "value")
|
|
2499
|
+
}
|
|
2500
|
+
}
|
|
2501
|
+
);
|
|
2502
|
+
|
|
2503
|
+
// functions/useObserver/index.ts
|
|
2504
|
+
init_esm_shims();
|
|
2505
|
+
init_message();
|
|
2506
|
+
init_internal();
|
|
2507
|
+
init_env();
|
|
2508
|
+
var useObserver = /* @__PURE__ */ __name(((func, deps = []) => {
|
|
2509
|
+
if (!deps || typeof func !== "function") {
|
|
2510
|
+
return () => {
|
|
2511
|
+
};
|
|
2512
|
+
}
|
|
2513
|
+
const handlers = [];
|
|
2514
|
+
const depList = Array.isArray(deps) && !deps.__path ? deps : [deps];
|
|
2515
|
+
try {
|
|
2516
|
+
depList.forEach((dep) => {
|
|
2517
|
+
let t = "";
|
|
2518
|
+
if (typeof dep === "function") {
|
|
2519
|
+
const result = propertyName(dep);
|
|
2520
|
+
if (result) t = result;
|
|
2521
|
+
} else if (typeof dep === "object" && dep !== null) {
|
|
2522
|
+
t = dep.__path || (typeof dep.toString === "function" && dep.toString() !== "[object Object]" ? dep.toString() : "");
|
|
2523
|
+
}
|
|
2524
|
+
if (t) {
|
|
2525
|
+
t = t.replace(/^(\(\)\s*=>\s*)/, "").replace(/^globalThis\./, "").replace(/^state\./, "");
|
|
2526
|
+
const path2 = t.startsWith("store.") || t.startsWith("state.") ? t : "state." + t;
|
|
2527
|
+
dispatch.listen(path2, () => func());
|
|
2528
|
+
handlers.push(path2);
|
|
2529
|
+
} else {
|
|
2530
|
+
internal_default.clearTrackedPaths();
|
|
2531
|
+
internal_default.tracking = true;
|
|
2532
|
+
try {
|
|
2533
|
+
func();
|
|
2534
|
+
} catch (_) {
|
|
2535
|
+
}
|
|
2536
|
+
internal_default.tracking = false;
|
|
2537
|
+
internal_default.trackedPaths.forEach((path2) => {
|
|
2538
|
+
if (!handlers.includes(path2)) {
|
|
2539
|
+
message_default(`useObserver: [Auto-Discovery] -> "${path2}"`);
|
|
2540
|
+
dispatch.listen(path2, () => func());
|
|
2541
|
+
handlers.push(path2);
|
|
2542
|
+
}
|
|
2543
|
+
});
|
|
2544
|
+
}
|
|
2545
|
+
});
|
|
2546
|
+
if (handlers.length > 0) {
|
|
2547
|
+
message_default(`useObserver: Monitoring ${handlers.length} paths.`);
|
|
2548
|
+
} else {
|
|
2549
|
+
console.warn(`useObserver: No paths resolved for monitoring. Check your dependencies!`);
|
|
2550
|
+
}
|
|
2551
|
+
return () => {
|
|
2552
|
+
handlers.forEach((path2) => {
|
|
2553
|
+
if (typeof dispatch.remove === "function") {
|
|
2554
|
+
dispatch.remove(path2);
|
|
2555
|
+
message_default(`useObserver: Stopped monitoring "${path2}"`);
|
|
2556
|
+
}
|
|
2557
|
+
});
|
|
2558
|
+
};
|
|
2559
|
+
} catch (err) {
|
|
2560
|
+
message_default(`useObserver Error: ${err}`);
|
|
2561
|
+
return () => {
|
|
2562
|
+
};
|
|
2563
|
+
}
|
|
2564
|
+
}), "useObserver");
|
|
2565
|
+
if (DEV && !("useObserver" in globalThis)) {
|
|
2566
|
+
if (!globalThis.useObserver) globalThis.useObserver = null;
|
|
2567
|
+
Object.defineProperty(
|
|
2568
|
+
globalThis,
|
|
2569
|
+
"useObserver",
|
|
2570
|
+
{
|
|
2571
|
+
value: useObserver,
|
|
2572
|
+
writable: true,
|
|
2573
|
+
enumerable: false,
|
|
2574
|
+
configurable: true
|
|
2575
|
+
}
|
|
2576
|
+
);
|
|
2577
|
+
Object.freeze(globalThis.useObserver);
|
|
2578
|
+
}
|
|
2579
|
+
|
|
2580
|
+
// index.ts
|
|
2581
|
+
init_message();
|
|
2582
|
+
|
|
2583
|
+
// functions/logger/index.ts
|
|
2584
|
+
init_esm_shims();
|
|
2585
|
+
init_internal();
|
|
2586
|
+
init_message();
|
|
2587
|
+
init_env();
|
|
2588
|
+
var defaultConfig = {
|
|
2589
|
+
enabled: true,
|
|
2590
|
+
logToConsole: true,
|
|
2591
|
+
modules: ["state", "store", "session", "cache", "idb"],
|
|
2592
|
+
maxEntries: 1e3
|
|
2593
|
+
};
|
|
2594
|
+
function isDebugEnabled() {
|
|
2595
|
+
return DEV && internal_default.debug === true;
|
|
2596
|
+
}
|
|
2597
|
+
__name(isDebugEnabled, "isDebugEnabled");
|
|
2598
|
+
var config = { ...defaultConfig };
|
|
2599
|
+
var logHistory = [];
|
|
2600
|
+
var configure = /* @__PURE__ */ __name((options) => {
|
|
2601
|
+
config = { ...config, ...options };
|
|
2602
|
+
}, "configure");
|
|
2603
|
+
var enable = /* @__PURE__ */ __name(() => {
|
|
2604
|
+
config.enabled = true;
|
|
2605
|
+
}, "enable");
|
|
2606
|
+
var disable = /* @__PURE__ */ __name(() => {
|
|
2607
|
+
config.enabled = false;
|
|
2608
|
+
}, "disable");
|
|
2609
|
+
var isEnabled = /* @__PURE__ */ __name((module) => {
|
|
2610
|
+
return config.enabled && config.modules.includes(module);
|
|
2611
|
+
}, "isEnabled");
|
|
2612
|
+
var log = /* @__PURE__ */ __name((module, action, path2, value, previousValue) => {
|
|
2613
|
+
if (!isEnabled(module)) return;
|
|
2614
|
+
const entry = {
|
|
2615
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2616
|
+
module,
|
|
2617
|
+
action,
|
|
2618
|
+
path: path2,
|
|
2619
|
+
value,
|
|
2620
|
+
previousValue
|
|
2621
|
+
};
|
|
2622
|
+
logHistory.push(entry);
|
|
2623
|
+
if (logHistory.length > config.maxEntries) {
|
|
2624
|
+
logHistory.shift();
|
|
2625
|
+
}
|
|
2626
|
+
if (config.logToConsole && isDebugEnabled()) {
|
|
2627
|
+
const prefix = `[Memorio:${module.toUpperCase()}]`;
|
|
2628
|
+
const color = getModuleColor(module);
|
|
2629
|
+
message_default(
|
|
2630
|
+
`%c${prefix}%c ${action} ${path2},
|
|
2631
|
+
color: ${color}; font-weight: bold,
|
|
2632
|
+
color: inherit`
|
|
2633
|
+
);
|
|
2634
|
+
if (value !== void 0) {
|
|
2635
|
+
message_default(` \u2192 value:${value}`);
|
|
2636
|
+
}
|
|
2637
|
+
if (previousValue !== void 0) {
|
|
2638
|
+
message_default(` \u2190 previous:${previousValue}`);
|
|
2639
|
+
}
|
|
2640
|
+
}
|
|
2641
|
+
if (config.customHandler) {
|
|
2642
|
+
config.customHandler(entry);
|
|
2643
|
+
}
|
|
2644
|
+
}, "log");
|
|
2645
|
+
var getModuleColor = /* @__PURE__ */ __name((module) => {
|
|
2646
|
+
const colors = {
|
|
2647
|
+
state: "#4CAF50",
|
|
2648
|
+
store: "#2196F3",
|
|
2649
|
+
session: "#FF9800",
|
|
2650
|
+
cache: "#9C27B0",
|
|
2651
|
+
idb: "#F44336"
|
|
2652
|
+
};
|
|
2653
|
+
return colors[module] || "#888888";
|
|
2654
|
+
}, "getModuleColor");
|
|
2655
|
+
var getHistory = /* @__PURE__ */ __name(() => {
|
|
2656
|
+
return [...logHistory];
|
|
2657
|
+
}, "getHistory");
|
|
2658
|
+
var clearHistory = /* @__PURE__ */ __name(() => {
|
|
2659
|
+
logHistory.length = 0;
|
|
2660
|
+
}, "clearHistory");
|
|
2661
|
+
var getStats = /* @__PURE__ */ __name(() => {
|
|
2662
|
+
const stats2 = {
|
|
2663
|
+
total: logHistory.length,
|
|
2664
|
+
state: 0,
|
|
2665
|
+
store: 0,
|
|
2666
|
+
session: 0,
|
|
2667
|
+
cache: 0,
|
|
2668
|
+
idb: 0,
|
|
2669
|
+
set: 0,
|
|
2670
|
+
get: 0,
|
|
2671
|
+
delete: 0,
|
|
2672
|
+
clear: 0
|
|
2673
|
+
};
|
|
2674
|
+
for (const entry of logHistory) {
|
|
2675
|
+
if (entry) {
|
|
2676
|
+
const module = entry.module;
|
|
2677
|
+
const action = entry.action;
|
|
2678
|
+
if (module && typeof stats2[module] === "number") stats2[module]++;
|
|
2679
|
+
if (action && typeof stats2[action] === "number") stats2[action]++;
|
|
2680
|
+
}
|
|
2681
|
+
}
|
|
2682
|
+
return stats2;
|
|
2683
|
+
}, "getStats");
|
|
2684
|
+
var exportLogs = /* @__PURE__ */ __name(() => {
|
|
2685
|
+
return JSON.stringify(logHistory, null, 2);
|
|
2686
|
+
}, "exportLogs");
|
|
2687
|
+
var logger = {
|
|
2688
|
+
configure,
|
|
2689
|
+
enable,
|
|
2690
|
+
disable,
|
|
2691
|
+
isEnabled,
|
|
2692
|
+
log,
|
|
2693
|
+
getHistory,
|
|
2694
|
+
clearHistory,
|
|
2695
|
+
getStats,
|
|
2696
|
+
exportLogs
|
|
2697
|
+
};
|
|
2698
|
+
|
|
2699
|
+
// functions/devtools/index.ts
|
|
2700
|
+
init_esm_shims();
|
|
2701
|
+
init_internal();
|
|
2702
|
+
init_env();
|
|
2703
|
+
var _state = globalThis.__memorio_state_instance__;
|
|
2704
|
+
var _store = globalThis.__memorio_store_instance__;
|
|
2705
|
+
var _session = globalThis.__memorio_session_instance__;
|
|
2706
|
+
var _cache = globalThis.__memorio_cache_instance__;
|
|
2707
|
+
function isDebugEnabled2() {
|
|
2708
|
+
return DEV && internal_default.debug === true;
|
|
2709
|
+
}
|
|
2710
|
+
__name(isDebugEnabled2, "isDebugEnabled");
|
|
2711
|
+
function extractStoreData() {
|
|
2712
|
+
if (!_store) return {};
|
|
2713
|
+
const result = {};
|
|
2714
|
+
const store2 = _store;
|
|
2715
|
+
if (typeof store2.list === "function") {
|
|
2716
|
+
try {
|
|
2717
|
+
return store2.list();
|
|
2718
|
+
} catch {
|
|
2719
|
+
}
|
|
2720
|
+
}
|
|
2721
|
+
if (typeof store2.get === "function") {
|
|
2722
|
+
for (const key of Object.keys(store2)) {
|
|
2723
|
+
if (!["get", "set", "remove", "delete", "removeAll", "clearAll", "size", "isPersistent", "list"].includes(key)) {
|
|
2724
|
+
try {
|
|
2725
|
+
const val = store2.get(key);
|
|
2726
|
+
if (val !== null && val !== void 0) {
|
|
2727
|
+
result[key] = val;
|
|
2728
|
+
}
|
|
2729
|
+
} catch {
|
|
2730
|
+
}
|
|
2731
|
+
}
|
|
2732
|
+
}
|
|
2733
|
+
}
|
|
2734
|
+
return result;
|
|
2735
|
+
}
|
|
2736
|
+
__name(extractStoreData, "extractStoreData");
|
|
2737
|
+
function extractSessionData() {
|
|
2738
|
+
if (!_session) return {};
|
|
2739
|
+
const result = {};
|
|
2740
|
+
const session2 = _session;
|
|
2741
|
+
if (typeof session2.list === "function") {
|
|
2742
|
+
try {
|
|
2743
|
+
return session2.list();
|
|
2744
|
+
} catch {
|
|
2745
|
+
}
|
|
2746
|
+
}
|
|
2747
|
+
if (typeof session2.get === "function") {
|
|
2748
|
+
for (const key of Object.keys(session2)) {
|
|
2749
|
+
if (!["get", "set", "remove", "delete", "removeAll", "clearAll", "size", "isPersistent", "list"].includes(key)) {
|
|
2750
|
+
try {
|
|
2751
|
+
const val = session2.get(key);
|
|
2752
|
+
if (val !== null && val !== void 0) {
|
|
2753
|
+
result[key] = val;
|
|
2754
|
+
}
|
|
2755
|
+
} catch {
|
|
2756
|
+
}
|
|
2757
|
+
}
|
|
2758
|
+
}
|
|
2759
|
+
}
|
|
2760
|
+
return result;
|
|
2761
|
+
}
|
|
2762
|
+
__name(extractSessionData, "extractSessionData");
|
|
2763
|
+
var inspect = /* @__PURE__ */ __name(() => {
|
|
2764
|
+
if (!isDebugEnabled2()) return;
|
|
2765
|
+
if (_state) {
|
|
2766
|
+
const stateList = _state.list;
|
|
2767
|
+
let stateData;
|
|
2768
|
+
if (typeof stateList === "function") {
|
|
2769
|
+
stateData = stateList();
|
|
2770
|
+
} else if (typeof stateList === "object" && stateList !== null) {
|
|
2771
|
+
stateData = stateList;
|
|
2772
|
+
} else {
|
|
2773
|
+
stateData = _state;
|
|
2774
|
+
}
|
|
2775
|
+
console.table(stateData);
|
|
2776
|
+
}
|
|
2777
|
+
if (_store) {
|
|
2778
|
+
console.table(extractStoreData());
|
|
2779
|
+
}
|
|
2780
|
+
if (_session) {
|
|
2781
|
+
console.table(extractSessionData());
|
|
2782
|
+
}
|
|
2783
|
+
if (_cache) {
|
|
2784
|
+
const cacheList = _cache.list;
|
|
2785
|
+
let cacheData2;
|
|
2786
|
+
if (typeof cacheList === "function") {
|
|
2787
|
+
cacheData2 = cacheList();
|
|
2788
|
+
} else if (typeof cacheList === "object" && cacheList !== null) {
|
|
2789
|
+
cacheData2 = cacheList;
|
|
2790
|
+
} else {
|
|
2791
|
+
cacheData2 = _cache;
|
|
2792
|
+
}
|
|
2793
|
+
console.table(cacheData2);
|
|
2794
|
+
}
|
|
2795
|
+
}, "inspect");
|
|
2796
|
+
var stats = /* @__PURE__ */ __name(() => {
|
|
2797
|
+
const getKeys = /* @__PURE__ */ __name((obj) => {
|
|
2798
|
+
if (!obj) return 0;
|
|
2799
|
+
if (typeof obj.list === "function") {
|
|
2800
|
+
try {
|
|
2801
|
+
const list = obj.list();
|
|
2802
|
+
return Object.keys(list).length;
|
|
2803
|
+
} catch {
|
|
2804
|
+
}
|
|
2805
|
+
}
|
|
2806
|
+
return Object.keys(obj).length;
|
|
2807
|
+
}, "getKeys");
|
|
2808
|
+
return {
|
|
2809
|
+
stateKeys: getKeys(_state),
|
|
2810
|
+
storeKeys: getKeys(_store),
|
|
2811
|
+
sessionKeys: getKeys(_session),
|
|
2812
|
+
cacheKeys: getKeys(_cache),
|
|
2813
|
+
idbDatabases: 0,
|
|
2814
|
+
sqliteDbCount: 0,
|
|
2815
|
+
lastUpdate: (/* @__PURE__ */ new Date()).toISOString()
|
|
2816
|
+
};
|
|
2817
|
+
}, "stats");
|
|
2818
|
+
var clear = /* @__PURE__ */ __name((moduleName) => {
|
|
2819
|
+
const targets = { state: _state, store: _store, session: _session, cache: _cache };
|
|
2820
|
+
const target = targets[moduleName];
|
|
2821
|
+
if (target && typeof target.clear === "function") {
|
|
2822
|
+
target.clear();
|
|
2823
|
+
} else if (target && typeof target.removeAll === "function") {
|
|
2824
|
+
target.removeAll();
|
|
2825
|
+
} else {
|
|
2826
|
+
console.debug(`Module ${moduleName} not found or does not support clear()/removeAll()`);
|
|
2827
|
+
}
|
|
2828
|
+
}, "clear");
|
|
2829
|
+
var clearAll = /* @__PURE__ */ __name(() => {
|
|
2830
|
+
clear("state");
|
|
2831
|
+
clear("store");
|
|
2832
|
+
clear("session");
|
|
2833
|
+
clear("cache");
|
|
2834
|
+
}, "clearAll");
|
|
2835
|
+
var exportData = /* @__PURE__ */ __name(() => {
|
|
2836
|
+
const getStateData = /* @__PURE__ */ __name(() => {
|
|
2837
|
+
if (!_state) return void 0;
|
|
2838
|
+
try {
|
|
2839
|
+
if (typeof _state.list === "function") {
|
|
2840
|
+
return _state.list();
|
|
2841
|
+
}
|
|
2842
|
+
return _state;
|
|
2843
|
+
} catch {
|
|
2844
|
+
return void 0;
|
|
2845
|
+
}
|
|
2846
|
+
}, "getStateData");
|
|
2847
|
+
const getStoreData = /* @__PURE__ */ __name(() => {
|
|
2848
|
+
return extractStoreData();
|
|
2849
|
+
}, "getStoreData");
|
|
2850
|
+
const getSessionData = /* @__PURE__ */ __name(() => {
|
|
2851
|
+
return extractSessionData();
|
|
2852
|
+
}, "getSessionData");
|
|
2853
|
+
const getCacheData = /* @__PURE__ */ __name(() => {
|
|
2854
|
+
if (!_cache) return void 0;
|
|
2855
|
+
try {
|
|
2856
|
+
if (typeof _cache.list === "function") {
|
|
2857
|
+
return _cache.list();
|
|
2858
|
+
}
|
|
2859
|
+
return _cache;
|
|
2860
|
+
} catch {
|
|
2861
|
+
return void 0;
|
|
2862
|
+
}
|
|
2863
|
+
}, "getCacheData");
|
|
2864
|
+
const data = {
|
|
2865
|
+
state: getStateData(),
|
|
2866
|
+
store: getStoreData(),
|
|
2867
|
+
session: getSessionData(),
|
|
2868
|
+
cache: getCacheData(),
|
|
2869
|
+
exportedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
2870
|
+
};
|
|
2871
|
+
return JSON.stringify(data, null, 2);
|
|
2872
|
+
}, "exportData");
|
|
2873
|
+
var importData = /* @__PURE__ */ __name((jsonString) => {
|
|
2874
|
+
try {
|
|
2875
|
+
const data = JSON.parse(jsonString);
|
|
2876
|
+
if (data.state) {
|
|
2877
|
+
Object.entries(data.state).forEach(([key, value]) => {
|
|
2878
|
+
if (_state && key !== "list" && key !== "remove" && key !== "removeAll") {
|
|
2879
|
+
;
|
|
2880
|
+
_state[key] = value;
|
|
2881
|
+
}
|
|
2882
|
+
});
|
|
2883
|
+
}
|
|
2884
|
+
if (data.store && _store && typeof _store.set === "function") {
|
|
2885
|
+
Object.entries(data.store).forEach(([key, value]) => {
|
|
2886
|
+
;
|
|
2887
|
+
_store.set(key, value);
|
|
2888
|
+
});
|
|
2889
|
+
}
|
|
2890
|
+
if (data.session && _session && typeof _session.set === "function") {
|
|
2891
|
+
Object.entries(data.session).forEach(([key, value]) => {
|
|
2892
|
+
;
|
|
2893
|
+
_session.set(key, value);
|
|
2894
|
+
});
|
|
2895
|
+
}
|
|
2896
|
+
if (data.cache && _cache) {
|
|
2897
|
+
Object.entries(data.cache).forEach(([key, value]) => {
|
|
2898
|
+
if (_cache && key !== "get" && key !== "set" && key !== "remove" && key !== "clear") {
|
|
2899
|
+
;
|
|
2900
|
+
_cache[key] = value;
|
|
2901
|
+
}
|
|
2902
|
+
});
|
|
2903
|
+
}
|
|
2904
|
+
} catch (error) {
|
|
2905
|
+
console.debug("Import failed:", error);
|
|
2906
|
+
}
|
|
2907
|
+
}, "importData");
|
|
2908
|
+
var watch = /* @__PURE__ */ __name((moduleName, path2) => {
|
|
2909
|
+
const targets = { state: _state, store: _store, session: _session, cache: _cache };
|
|
2910
|
+
const target = targets[moduleName];
|
|
2911
|
+
if (!target) {
|
|
2912
|
+
console.debug(`Module ${moduleName} not found`);
|
|
2913
|
+
return;
|
|
2914
|
+
}
|
|
2915
|
+
const initialValue = target[path2];
|
|
2916
|
+
console.debug(`Watching ${moduleName}.${path2} (initial: ${JSON.stringify(initialValue)})`);
|
|
2917
|
+
if (moduleName === "state" && globalThis.memorio?.dispatch) {
|
|
2918
|
+
const handler = /* @__PURE__ */ __name((e) => {
|
|
2919
|
+
const detail = e.detail;
|
|
2920
|
+
if (detail?.name?.includes(path2)) {
|
|
2921
|
+
console.debug(`Change: ${moduleName}.${path2} =`, e.detail.value);
|
|
2922
|
+
}
|
|
2923
|
+
}, "handler");
|
|
2924
|
+
target.addEventListener?.("memorio-change", handler);
|
|
2925
|
+
}
|
|
2926
|
+
}, "watch");
|
|
2927
|
+
var help = /* @__PURE__ */ __name(() => {
|
|
2928
|
+
console.debug(`
|
|
2929
|
+
Memorio DevTools Help
|
|
6
2930
|
|
|
7
2931
|
Available commands:
|
|
8
2932
|
memorio.devtools.inspect() - Inspect all state modules
|
|
@@ -14,99 +2938,1424 @@ Available commands:
|
|
|
14
2938
|
memorio.devtools.watch(module, path) - Watch a path for changes
|
|
15
2939
|
memorio.devtools.help() - Show this help
|
|
16
2940
|
|
|
17
|
-
Shortcuts:
|
|
18
|
-
state -
|
|
19
|
-
store -
|
|
20
|
-
session -
|
|
21
|
-
cache -
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
color: inherit`),o!==void 0&&c(` \u2192 value:${o}`),n!==void 0&&c(` \u2190 previous:${n}`);}A.customHandler&&A.customHandler(s);},vo=e=>({state:"#4CAF50",store:"#2196F3",session:"#FF9800",cache:"#9C27B0",idb:"#F44336"})[e]||"#888888",xo=()=>[...N],So=()=>{N.length=0;},wo=()=>{let e={total:N.length,state:0,store:0,session:0,cache:0,idb:0,set:0,get:0,delete:0,clear:0};for(let t of N)if(t){let r=t.module,o=t.action;r&&typeof e[r]=="number"&&e[r]++,o&&typeof e[o]=="number"&&e[o]++;}return e},Eo=()=>JSON.stringify(N,null,2),Be={configure:yo,enable:go,disable:bo,isEnabled:Xt,log:ho,getHistory:xo,clearHistory:So,getStats:wo,exportLogs:Eo};$();J();a();J();$();var ge={version:"4.8.0"};G();T();_();w();a();function Ve(){return S}a();$();w();function Zt(e){if(e===null||typeof e!="object")return e;let t=e.constructor?.name;if(t!=="Object"&&t!=="Array")return e;try{return JSON.parse(JSON.stringify(e))}catch{return e}}var He=()=>Zt(R(S)),ze=e=>{let t=[],r=(o,n,s)=>{let i=o?Object.keys(o):[],l=n?Object.keys(n):[];for(let g of l){let b=s?`${s}.${g}`:g,v=o?o[g]:void 0,O=n[g];v!==O&&(typeof v!==typeof O||v===void 0?t.push({path:b,oldValue:v,newValue:O}):v&&typeof v=="object"?r(v,O,b):v!==O&&t.push({path:b,oldValue:v,newValue:O}));}for(let g of i)if(!(g in(n||{}))){let b=s?`${s}.${g}`:g;t.push({path:b,oldValue:o[g],newValue:void 0});}};return r(e,R(S),""),t},Qe=(e=true)=>{u.historyEnabled=e,c(`[memorio history] Tracking ${e?"enabled":"disabled"}`);};var Ke=()=>[...u.mutations],We=()=>u.canUndo(),Fe=()=>u.canRedo(),Ge=()=>{if(!u.historyEnabled){c("[memorio history] History is not enabled");return}let e=u.popUndo();if(e)return Po(e),c(`[memorio history] Undid: ${e.action} ${e.path}`),e},Ye=()=>{if(!u.historyEnabled){c("[memorio history] History is not enabled");return}let e=u.popRedo();if(e)return _o(e),c(`[memorio history] Redid: ${e.action} ${e.path}`),e};function Po(e){let t=u.historyEnabled;u.historyEnabled=false;try{e.action==="set"?e.previousValue===void 0?er(e.path):Ue(e.path,e.previousValue):e.action==="delete"&&e.previousValue!==void 0&&Ue(e.path,e.previousValue);}finally{u.historyEnabled=t;}}function _o(e){let t=u.historyEnabled;u.historyEnabled=false;try{e.action==="set"?Ue(e.path,e.newValue):e.action==="delete"&&er(e.path);}finally{u.historyEnabled=t;}}function Ue(e,t){let r=e.split("."),o=S;for(let n=0;n<r.length-1;n++){let s=r[n];o[s]===void 0&&(o[s]={}),o=o[s];}o[r[r.length-1]]=t;}function er(e){let t=e.split(".");if(t.length===1){S.remove(t[0]);return}let r=S;for(let o=0;o<t.length-1;o++){let n=t[o];if(r[n]===void 0)return;r=r[n];}delete r[t[t.length-1]];}var Xe=e=>{S.removeAll();for(let t of Object.keys(e))S[t]=Zt(e[t]);u.clearHistory(),c("[memorio history] State rolled back to snapshot");},Ze=()=>{u.clearHistory(),c("[memorio history] History cleared");},et=()=>{u.clearRedo();};a();var tt=()=>{let e=R(S);return Object.keys(e).filter(t=>!["list","remove","removeAll","lock","unlock"].includes(t))},rt=e=>{if(!e||typeof e!="string")return false;let t=e.replace(/^state\./,"").split("."),r=S;for(let o of t){if(r==null)return false;r=r[o];}return r!==void 0},ot=e=>{let[t,r]=tr(e);return !t||r===void 0?"undefined":Array.isArray(r)?"array":typeof r},nt=e=>{let[t,r]=tr(e);if(!(!t||r===void 0))return ko(r)},st=()=>{let e=[],t=(r,o)=>{if(r===null||typeof r!="object"||Array.isArray(r))return;let n=Object.keys(r).filter(s=>!["list","remove","removeAll","lock","unlock"].includes(s));for(let s of n){let i=o?`${o}.${s}`:s,l=r[s],g=l!==void 0,b=g?Array.isArray(l)?"array":typeof l:"undefined";e.push({path:i,type:b,defined:g}),g&&typeof l=="object"&&!Array.isArray(l)&&l.constructor?.name==="Object"&&t(l,i);}};return t(R(S),""),e};function tr(e){if(!e||typeof e!="string")return [false,void 0];let t=e.replace(/^state\./,"").split("."),r=S;for(let o of t){if(r==null)return [false,void 0];r=r[o];}return [r!==void 0,r]}function ko(e){if(e===null||typeof e!="object")return e;let t=e.constructor?.name;if(t!=="Object"&&t!=="Array")return e;try{return JSON.parse(JSON.stringify(e))}catch{return e}}a();G();T();a();G();var I=globalThis,Oo=10*1024*1024;function ie(){let e=I.memorioSyncConfig;if(e&&typeof e.namespace=="string"&&e.namespace)return `ns:${e.namespace}`;let t=I.memorio?I.memorio._currentContext:void 0,r=typeof t=="string"&&t?t:"";return r?`ctx:${r}`:"default"}function rr(){return !!I.memorioSyncConfig}var X=e=>`memorio:sync:${e}:`,Y=e=>`${X(e)}index`;function qo(e){let t=JSON.stringify(e);if(t.length>Oo)throw new Error("memorio sync: memory entry exceeds maximum size");return t}function it(e){try{return JSON.parse(e)}catch{return null}}var at={async append(e,t){let r=ie(),o={...e,operation:t,updatedAt:e.updatedAt||Date.now(),version:e.version||1,sync:"pending"},n=qo(o),s=`${X(r)}${o.id}`;h.set(s,n);let i=h.get(Y(r))||[];return i.includes(o.id)||i.push(o.id),h.set(Y(r),JSON.stringify(i)),o},async pending(){let e=ie(),t=[],r=h.get(Y(e))||[];for(let o of r){let n=h.get(`${X(e)}${o}`);if(!n)continue;let s=it(n);s&&s.sync!=="synced"&&t.push(s);}return t.sort((o,n)=>(o.updatedAt||0)-(n.updatedAt||0)),t},async markSynced(e){if(!e.length)return 0;let t=ie(),r=0,o=h.get(Y(t))||[];for(let n of o){if(!e.includes(n))continue;let s=`${X(t)}${n}`,i=h.get(s);if(!i)continue;let l=it(i);!l||l.sync==="synced"||(l.sync="synced",h.set(s,JSON.stringify(l)),r++);}return r},async get(e){let t=ie(),r=h.get(`${X(t)}${e}`);return it(r??"")},async clear(){let e=ie(),t=h.get(Y(e))||[];for(let r of t)h.remove(`${X(e)}${r}`);h.remove(Y(e));},async replay(){let e={synced:[]};if(!rr())return e;let r=(I.memorioSyncConfig||{}).provider;if(!r||typeof r.push!="function")return e;let o=await this.pending();if(o.length)try{let n=await r.push(o);e.synced=n?.synced||[],e.conflicts=n?.conflicts,e.error=n?.error,e.synced.length&&await this.markSynced(e.synced);}catch(n){e.error=String(n);}if(typeof r.pull=="function")try{let n=o.length?Math.min(...o.map(i=>i.updatedAt||0)):0,s=await r.pull(n);for(let i of s||[])await this.append(i,i.operation||"confirm"),await this.markSynced([i.id]);}catch{}return e},status(){return Promise.resolve("store")}};function or(e){let t=I.memorioSyncConfig||{};return I.memorioSyncConfig={...t,...e},at}if(typeof I.addEventListener=="function"){let e=false;I.addEventListener("focus",()=>{e||!rr()||(e=true,at.replay().finally(()=>{e=false;}));});}var lt=at;var ve="__memorio_memory_index__",nr="__memorio_superseded__";function ct(){return !!globalThis.memorioSyncConfig}async function Z(e,t){if(ct()&&e.scope!=="hot")try{await lt.append(e,t);}catch{}}function ut(e){return e.startsWith(nr)?e:`${nr}${e}`}function sr(e){return e?Array.isArray(e)?e:[e]:[]}function Mo(e,t){if(t.scope)return t.scope;let r=JSON.stringify(e).length;return r>1e6?"durable":("local")}function k(){return Date.now()}function he(e){return e.ttl===null||e.ttl===void 0?false:k()-e.createdAt>e.ttl}function $o(e,t){return e.status==="obsolete"||e.status==="superseded"||he(e)?t.includeObsolete??false:!(t.type&&!(Array.isArray(t.type)?t.type:[t.type]).includes(e.type)||t.minConfidence!==void 0&&e.confidence<t.minConfidence)}function Co(e,t){return !(e.status!=="active"||he(e)||t.tags&&!(Array.isArray(t.tags)?t.tags:[t.tags]).some(n=>e.tags.includes(n))||t.types&&!(Array.isArray(t.types)?t.types:[t.types]).includes(e.type)||t.minConfidence!==void 0&&e.confidence<t.minConfidence||t.scopes&&!t.scopes.includes(e.scope))}function jo(e){let t=(k()-e.createdAt)/36e5,r=Math.max(.1,1/(1+t*.5)),o=e.confidence,n=1+e.tags.length*.1,s={decision:1.5,context:1.3,preference:1.2,task:1,fact:.8},i={hot:1.5,session:1.2,local:1,durable:.8};return r*o*n*s[e.type]*i[e.scope]}function ar(e,t){if(!t||typeof t!="string")return;let r=t.replace(/^state\./,"").split("."),o=e;for(let n of r){if(o==null)return;o=o[n];}return o}function lr(e,t,r){if(!t||typeof t!="string")return;let o=t.replace(/^state\./,"").split("."),n=e;for(let s=0;s<o.length-1;s++){let i=o[s];(n[i]===void 0||n[i]===null)&&(n[i]={}),n=n[i];}n[o[o.length-1]]=r;}async function W(e){let t=e.status==="superseded"?ut(e.id||e.key):e.key,r=JSON.stringify(e);switch(e.scope){case "hot":lr(S,t,e.value);break;case "session":C.set(t,r);break;case "local":h.set(t,r);break;case "durable":await d.set("memories",t,r);break}await Do(e.id||e.key,e.scope,e.status==="superseded");}async function cr(e,t,r=false){let o=r?ut(e):e,n;switch(t){case "hot":{let s=ar(S,o);return s===void 0?null:ur(e,s,t)}case "session":n=C.get(o);break;case "local":n=h.get(o);break;case "durable":n=await d.get("memories",o);break}if(!n)return null;try{let s=JSON.parse(n);return s.id=s.id||e,s}catch{return null}}function ur(e,t,r){return {id:e,key:e,value:t,type:"fact",confidence:1,scope:r,ttl:null,tags:[],status:"active",createdAt:k(),lastConfirmedAt:k(),supersededId:null}}async function ir(e,t,r=false){let o=r?ut(e):e;switch(t){case "hot":lr(S,o,void 0);break;case "session":C.remove(o);break;case "local":h.remove(o);break;case "durable":await d.deleteKey("memories",o);break}await Ao(e,r);}async function ae(){try{let e=h.get(ve);return e?JSON.parse(e):{}}catch{return {}}}async function Do(e,t,r=false){let o=await ae();o[e]={scope:t,superseded:r},h.set(ve,JSON.stringify(o));}async function Ao(e,t=false){let r=await ae(),o=r[e];o&&(t&&o.superseded||!t&&!o.superseded)&&delete r[e],h.set(ve,JSON.stringify(r));}async function be(){let e=await ae(),t=[];for(let[r,o]of Object.entries(e)){let n=await cr(r,o.scope,o.superseded);n&&(n.id=n.id||r,n.supersededId=n.supersededId??null,t.push(n));}return t}var xe={async remember(e,t,r={}){let o=await this._getEntry(e);if(o&&o.status==="active"){let l=`${o.id}__v${Date.now()}`,g={...o,id:l,key:o.key,status:"superseded",supersededId:null,lastConfirmedAt:k()};await W(g),await Z(g,"supersede");}let n=Mo(t,r),s=sr(r.tags),i={id:r.id||e,key:e,value:t,type:r.type||"fact",confidence:r.confidence??1,scope:n,ttl:r.ttl??null,tags:s,source:r.source,status:"active",createdAt:k(),lastConfirmedAt:k(),updatedAt:k(),version:o&&o.version?o.version+1:1,sync:ct()?"pending":void 0,supersededId:o?o.id:null};await W(i),await Z(i,"remember"),E.set("memorio:memory:remembered",{key:e,scope:n,entryId:i.id});},async recall(e,t={}){let r=await this._getEntry(e);return !r||!$o(r,t)?null:(r.lastConfirmedAt=k(),await W(r),E.set("memorio:memory:recalled",{key:e}),r.value)},async context(e={}){return (await be()).filter(n=>Co(n,e)).map(n=>({entry:n,score:jo(n)})).sort((n,s)=>s.score-n.score).slice(0,e.maxEntries??25).map(({entry:n})=>({key:n.key,value:n.value,type:n.type,confidence:n.confidence,scope:n.scope,tags:n.tags,age:k()-n.createdAt,accessCount:n.tags.length+1,lastAccessedAt:n.lastConfirmedAt}))},async forget(e){let t=await this._getEntry(e);t&&(await ir(t.id||e,t.scope,t.status==="superseded"),await Z(t,"forget"),E.set("memorio:memory:forgotten",{key:e}));},async update(e,t,r={}){let o=await this._getEntry(e);if(!o){await this.remember(e,t,r);return}let n=`${o.id}__v${k()}`,s={...o,id:n,key:o.key,status:"superseded",supersededId:null,lastConfirmedAt:k()};await W(s),await Z(s,"supersede");let i={...o,value:t,lastConfirmedAt:k(),updatedAt:k(),version:(o.version?o.version:0)+1,sync:ct()?"pending":void 0,...r.scope?{scope:r.scope}:{},...r.ttl!==void 0?{ttl:r.ttl}:{},...r.type?{type:r.type}:{},...r.confidence!==void 0?{confidence:r.confidence}:{},...r.tags!==void 0?{tags:sr(r.tags)}:{},...r.source?{source:r.source}:{}};await W(i),await Z(i,"update"),E.set("memorio:memory:updated",{key:e,entryId:i.id});},async stats(){let e=await be(),t={hot:0,session:0,local:0,durable:0},r={},o=0;for(let n of e)t[n.scope]=(t[n.scope]||0)+1,he(n)&&o++,r[n.type]=(r[n.type]||0)+1;return {total:e.length,byScope:t,byType:r,expired:o}},async forgetExpired(){let e=await be(),t=0;for(let r of e)he(r)&&r.status==="active"&&(r.status="obsolete",r.updatedAt=k(),r.operation="expire",await W(r),await Z(r,"expire"),t++);return t},async clear(){let e=await ae();for(let[t,r]of Object.entries(e))await ir(t,r.scope,r.superseded);h.remove(ve);},async _getEntry(e){let r=(await ae())[e];if(!r){let o=ar(S,e);return o!==void 0?ur(e,o,"hot"):null}return cr(e,r.scope,r.superseded)},async _loadAll(){return be()},async _save(e){await W(e);},journal:lt,configure(e){return or(e),this}};Object.defineProperty(globalThis,"memorio",{value:{setProps:()=>{},obj:{},array:[],dispatch:E,message:P,devtools:Ne,logger:Be,setDescription:()=>{}},writable:false,configurable:true,enumerable:false});Object.defineProperty(globalThis,"events",{value:{},writable:true,enumerable:false});typeof globalThis.addEventListener=="function"&&E.listen("memorio:memory:cleanup",async()=>xe.forgetExpired?.());Object.defineProperty(memorio,"version",{writable:false,enumerable:false,value:ge.version});Object.defineProperty(memorio,"debug",{get:()=>u.debug,set:e=>{u.debug=e;},enumerable:false});var mr=oe();Object.defineProperty(memorio,"_platform",{writable:false,enumerable:false,value:mr.platform});Object.defineProperty(memorio,"_capabilities",{writable:false,enumerable:false,value:mr});Object.defineProperty(memorio,"_sessionId",{writable:false,enumerable:false,value:ce()});xt();memorio.isBrowser=we;memorio.isNode=Ee;memorio.isDeno=Te;memorio.isEdge=Pe;memorio.getCapabilities=oe;memorio.createContext=ne;memorio.listContexts=Me;memorio.deleteContext=$e;memorio.isolate=e=>ne(e);memorio.registerSchema=L.register;memorio.validate=L.validate;memorio.unregisterSchema=L.unregister;memorio.listSchemas=L.list;memorio.typed=Ve;memorio.snapshot=He;memorio.diff=ze;memorio.undo=Ge;memorio.redo=Ye;memorio.canUndo=We;memorio.canRedo=Fe;memorio.rollback=Xe;memorio.trace=Ke;memorio.enableHistory=Qe;memorio.clearHistory=Ze;memorio.clearRedo=et;memorio.stateKeys=tt;memorio.pathExists=rt;memorio.stateType=ot;memorio.stateGet=nt;memorio.stateSchema=st;memorio.memory=xe;Object.defineProperty(globalThis,"state",{value:S,writable:true,enumerable:false,configurable:true});Object.defineProperty(globalThis,"store",{value:h,writable:true,enumerable:false,configurable:true});Object.defineProperty(globalThis,"session",{value:C,writable:true,enumerable:false,configurable:true});Object.defineProperty(globalThis,"cache",{value:ue,writable:true,enumerable:false,configurable:true});Object.defineProperty(globalThis,"idb",{value:d,writable:true,enumerable:false,configurable:true});Object.defineProperty(globalThis,"sqlite",{value:m,writable:true,enumerable:false,configurable:true});Object.defineProperty(globalThis,"observer",{value:pe,writable:true,enumerable:false,configurable:true});Object.defineProperty(globalThis,"useObserver",{value:ye,writable:true,enumerable:false,configurable:true});Object.defineProperty(memorio,"dispatch",{value:E,writable:true,enumerable:false,configurable:true});Object.defineProperty(memorio,"setContext",{writable:false,enumerable:false,value:e=>Ce(e)});Object.defineProperty(memorio,"getContext",{writable:false,enumerable:false,value:()=>u.currentContext});Object.defineProperty(globalThis,"$state",{get:()=>globalThis.state,configurable:true});Object.defineProperty(globalThis,"$store",{get:()=>globalThis.store,configurable:true});Object.defineProperty(globalThis,"$session",{get:()=>globalThis.session,configurable:true});Object.defineProperty(globalThis,"$cache",{get:()=>globalThis.cache,configurable:true});memorio.help=function(){console.debug(`
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
sqlite - SQLite in browser (sql.js, optional)
|
|
2941
|
+
Shortcuts (dev only):
|
|
2942
|
+
state - global state proxy
|
|
2943
|
+
store - localStorage wrapper
|
|
2944
|
+
session - sessionStorage wrapper
|
|
2945
|
+
cache - in-memory cache
|
|
2946
|
+
`);
|
|
2947
|
+
}, "help");
|
|
2948
|
+
var devtools = {
|
|
2949
|
+
inspect,
|
|
2950
|
+
stats,
|
|
2951
|
+
clear,
|
|
2952
|
+
clearAll,
|
|
2953
|
+
exportData,
|
|
2954
|
+
importData,
|
|
2955
|
+
watch,
|
|
2956
|
+
help
|
|
2957
|
+
};
|
|
35
2958
|
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
2959
|
+
// core/hlc.ts
|
|
2960
|
+
init_esm_shims();
|
|
2961
|
+
var NODE_ID_KEY = "__memorio_hlc_node";
|
|
2962
|
+
function getNodeId() {
|
|
2963
|
+
if (typeof globalThis === "undefined") return "node";
|
|
2964
|
+
try {
|
|
2965
|
+
if (typeof sessionStorage !== "undefined" && sessionStorage) {
|
|
2966
|
+
let id = sessionStorage.getItem(NODE_ID_KEY);
|
|
2967
|
+
if (!id) {
|
|
2968
|
+
id = generateNodeId();
|
|
2969
|
+
sessionStorage.setItem(NODE_ID_KEY, id);
|
|
2970
|
+
}
|
|
2971
|
+
return id;
|
|
2972
|
+
}
|
|
2973
|
+
} catch {
|
|
2974
|
+
}
|
|
2975
|
+
if (!globalThis.__memorioHlcNodeId) {
|
|
2976
|
+
globalThis.__memorioHlcNodeId = generateNodeId();
|
|
2977
|
+
}
|
|
2978
|
+
return globalThis.__memorioHlcNodeId;
|
|
2979
|
+
}
|
|
2980
|
+
__name(getNodeId, "getNodeId");
|
|
2981
|
+
function generateNodeId() {
|
|
2982
|
+
if (typeof crypto !== "undefined" && crypto.randomUUID) {
|
|
2983
|
+
return crypto.randomUUID().slice(0, 8);
|
|
2984
|
+
}
|
|
2985
|
+
return Math.random().toString(36).slice(2, 10);
|
|
2986
|
+
}
|
|
2987
|
+
__name(generateNodeId, "generateNodeId");
|
|
2988
|
+
var HLC_KEY = "__memorio_hlc_local";
|
|
2989
|
+
var local = globalThis[HLC_KEY] || {
|
|
2990
|
+
physical: 0,
|
|
2991
|
+
logical: 0,
|
|
2992
|
+
node: getNodeId()
|
|
2993
|
+
};
|
|
2994
|
+
if (!globalThis[HLC_KEY]) {
|
|
2995
|
+
globalThis[HLC_KEY] = local;
|
|
2996
|
+
}
|
|
2997
|
+
function tick(_incoming) {
|
|
2998
|
+
const now2 = Date.now();
|
|
2999
|
+
const base = local.physical;
|
|
3000
|
+
let physical;
|
|
3001
|
+
let logical;
|
|
3002
|
+
if (now2 > base) {
|
|
3003
|
+
physical = now2;
|
|
3004
|
+
logical = 0;
|
|
3005
|
+
} else if (now2 < base) {
|
|
3006
|
+
physical = base;
|
|
3007
|
+
logical = local.logical + 1;
|
|
3008
|
+
} else {
|
|
3009
|
+
physical = base;
|
|
3010
|
+
logical = local.logical + 1;
|
|
3011
|
+
}
|
|
3012
|
+
local.physical = physical;
|
|
3013
|
+
local.logical = logical;
|
|
3014
|
+
return { physical, logical, node: local.node };
|
|
3015
|
+
}
|
|
3016
|
+
__name(tick, "tick");
|
|
3017
|
+
function receive(remote) {
|
|
3018
|
+
const now2 = Date.now();
|
|
3019
|
+
if (remote.physical > local.physical) {
|
|
3020
|
+
local.physical = remote.physical > now2 ? remote.physical : now2;
|
|
3021
|
+
local.logical = 1;
|
|
3022
|
+
} else if (remote.physical === local.physical) {
|
|
3023
|
+
local.logical = Math.max(local.logical, remote.logical) + 1;
|
|
3024
|
+
}
|
|
3025
|
+
local.node = getNodeId();
|
|
3026
|
+
return { ...local };
|
|
3027
|
+
}
|
|
3028
|
+
__name(receive, "receive");
|
|
3029
|
+
function compare(a, b) {
|
|
3030
|
+
if (a.physical !== b.physical) {
|
|
3031
|
+
return a.physical < b.physical ? -1 : 1;
|
|
3032
|
+
}
|
|
3033
|
+
if (a.logical !== b.logical) {
|
|
3034
|
+
return a.logical < b.logical ? -1 : 1;
|
|
3035
|
+
}
|
|
3036
|
+
if (a.node !== b.node) {
|
|
3037
|
+
return a.node < b.node ? -1 : 1;
|
|
3038
|
+
}
|
|
3039
|
+
return 0;
|
|
3040
|
+
}
|
|
3041
|
+
__name(compare, "compare");
|
|
3042
|
+
function happenedBefore(a, b) {
|
|
3043
|
+
return compare(a, b) < 0;
|
|
3044
|
+
}
|
|
3045
|
+
__name(happenedBefore, "happenedBefore");
|
|
3046
|
+
function serialize(hlc2) {
|
|
3047
|
+
return `hlc:${hlc2.physical}:${hlc2.logical}:${hlc2.node}`;
|
|
3048
|
+
}
|
|
3049
|
+
__name(serialize, "serialize");
|
|
3050
|
+
function parse(serialized) {
|
|
3051
|
+
if (!serialized.startsWith("hlc:")) return null;
|
|
3052
|
+
const parts = serialized.split(":");
|
|
3053
|
+
if (parts.length !== 4) return null;
|
|
3054
|
+
const physical = parseInt(parts[1], 10);
|
|
3055
|
+
const logical = parseInt(parts[2], 10);
|
|
3056
|
+
const node = parts[3];
|
|
3057
|
+
if (isNaN(physical) || isNaN(logical)) return null;
|
|
3058
|
+
return { physical, logical, node };
|
|
3059
|
+
}
|
|
3060
|
+
__name(parse, "parse");
|
|
3061
|
+
var hlc = {
|
|
3062
|
+
tick,
|
|
3063
|
+
receive,
|
|
3064
|
+
compare,
|
|
3065
|
+
happenedBefore,
|
|
3066
|
+
serialize,
|
|
3067
|
+
parse,
|
|
3068
|
+
getNodeId
|
|
3069
|
+
};
|
|
42
3070
|
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
3071
|
+
// core/fractional.ts
|
|
3072
|
+
init_esm_shims();
|
|
3073
|
+
function generateBetween(left, right, minChars = 2) {
|
|
3074
|
+
if (left !== null && right !== null && left >= right) {
|
|
3075
|
+
throw new Error(`left (${left}) must be < right (${right})`);
|
|
3076
|
+
}
|
|
3077
|
+
if (left === null && right === null) {
|
|
3078
|
+
return "a";
|
|
3079
|
+
}
|
|
3080
|
+
if (left === null) {
|
|
3081
|
+
return generateLower(right, minChars);
|
|
3082
|
+
}
|
|
3083
|
+
if (right === null) {
|
|
3084
|
+
return generateUpper(left, minChars);
|
|
3085
|
+
}
|
|
3086
|
+
return generateMiddle(left, right, minChars);
|
|
3087
|
+
}
|
|
3088
|
+
__name(generateBetween, "generateBetween");
|
|
3089
|
+
function generateLower(right, minChars) {
|
|
3090
|
+
const rightDigits = right.split(".");
|
|
3091
|
+
const first = rightDigits[0];
|
|
3092
|
+
const firstChar = first.charCodeAt(0);
|
|
3093
|
+
if (firstChar > "a".charCodeAt(0)) {
|
|
3094
|
+
const prev = String.fromCharCode(firstChar - 1);
|
|
3095
|
+
const rest = first.slice(1);
|
|
3096
|
+
if (rest === "") {
|
|
3097
|
+
return leftPad(prev, minChars);
|
|
3098
|
+
}
|
|
3099
|
+
return prev + rest;
|
|
3100
|
+
}
|
|
3101
|
+
if (first[0] === "a") {
|
|
3102
|
+
let i = 0;
|
|
3103
|
+
while (i < first.length && first[i] === "a") i++;
|
|
3104
|
+
if (i === first.length) {
|
|
3105
|
+
return ".z." + ".z".repeat(Math.floor(minChars / 2) + 1);
|
|
3106
|
+
}
|
|
3107
|
+
const char = first.charCodeAt(i);
|
|
3108
|
+
const next = String.fromCharCode(char - 1);
|
|
3109
|
+
if (next >= "a") {
|
|
3110
|
+
return next + first.slice(i + 1);
|
|
3111
|
+
}
|
|
3112
|
+
return "a" + next + first.slice(i + 1);
|
|
3113
|
+
}
|
|
3114
|
+
return ".z." + ".z".repeat(Math.floor(minChars / 2) + 1);
|
|
3115
|
+
}
|
|
3116
|
+
__name(generateLower, "generateLower");
|
|
3117
|
+
function generateUpper(left, minChars) {
|
|
3118
|
+
const leftDigits = left.split(".");
|
|
3119
|
+
const first = leftDigits[0];
|
|
3120
|
+
const firstChar = first.charCodeAt(0);
|
|
3121
|
+
const nextChar = String.fromCharCode(firstChar + 1);
|
|
3122
|
+
if (nextChar <= "z") {
|
|
3123
|
+
const rest = first.slice(1);
|
|
3124
|
+
if (rest === "") {
|
|
3125
|
+
return rightPad(nextChar, minChars);
|
|
3126
|
+
}
|
|
3127
|
+
return nextChar + rest;
|
|
3128
|
+
}
|
|
3129
|
+
if (first.length > 1) {
|
|
3130
|
+
const lastChar = first[first.length - 1];
|
|
3131
|
+
if (lastChar < "z") {
|
|
3132
|
+
return first.slice(0, -1) + String.fromCharCode(lastChar.charCodeAt(0) + 1);
|
|
3133
|
+
}
|
|
3134
|
+
}
|
|
3135
|
+
const carry = handleCarry(first, 0);
|
|
3136
|
+
if (carry !== null) {
|
|
3137
|
+
return carry + leftPad("a", minChars);
|
|
3138
|
+
}
|
|
3139
|
+
return "b" + leftPad("a", minChars);
|
|
3140
|
+
}
|
|
3141
|
+
__name(generateUpper, "generateUpper");
|
|
3142
|
+
function handleCarry(digits, carryPos) {
|
|
3143
|
+
if (carryPos >= digits.length) return null;
|
|
3144
|
+
const char = digits.charCodeAt(carryPos);
|
|
3145
|
+
if (char < "z".charCodeAt(0)) {
|
|
3146
|
+
return digits.slice(0, carryPos) + String.fromCharCode(char + 1);
|
|
3147
|
+
}
|
|
3148
|
+
return handleCarry(digits, carryPos + 1);
|
|
3149
|
+
}
|
|
3150
|
+
__name(handleCarry, "handleCarry");
|
|
3151
|
+
function generateMiddle(left, right, minChars) {
|
|
3152
|
+
const leftDigits = left.split(".");
|
|
3153
|
+
const rightDigits = right.split(".");
|
|
3154
|
+
const maxLen = Math.max(leftDigits.length, rightDigits.length);
|
|
3155
|
+
const leftParts = padParts(leftDigits, maxLen);
|
|
3156
|
+
const rightParts = padParts(rightDigits, maxLen);
|
|
3157
|
+
let prefix = [];
|
|
3158
|
+
for (let i = 0; i < maxLen; i++) {
|
|
3159
|
+
const l = leftParts[i] || "a";
|
|
3160
|
+
const r = rightParts[i] || "z";
|
|
3161
|
+
if (l === r) {
|
|
3162
|
+
prefix.push(l);
|
|
3163
|
+
} else {
|
|
3164
|
+
const lCode = l.charCodeAt(0);
|
|
3165
|
+
const rCode = r.charCodeAt(0);
|
|
3166
|
+
if (rCode - lCode > 1) {
|
|
3167
|
+
prefix.push(String.fromCharCode(lCode + 1));
|
|
3168
|
+
while (prefix.length < minChars) {
|
|
3169
|
+
prefix.push("a");
|
|
3170
|
+
}
|
|
3171
|
+
return prefix.join(".");
|
|
3172
|
+
}
|
|
3173
|
+
prefix.push(l);
|
|
3174
|
+
prefix.push(generateUpper(l, minChars));
|
|
3175
|
+
return prefix.join(".");
|
|
3176
|
+
}
|
|
3177
|
+
}
|
|
3178
|
+
return generateUpper(left, minChars);
|
|
3179
|
+
}
|
|
3180
|
+
__name(generateMiddle, "generateMiddle");
|
|
3181
|
+
function padParts(parts, maxLen) {
|
|
3182
|
+
while (parts.length < maxLen) parts.push("a");
|
|
3183
|
+
return parts;
|
|
3184
|
+
}
|
|
3185
|
+
__name(padParts, "padParts");
|
|
3186
|
+
function leftPad(key, minChars) {
|
|
3187
|
+
let result = key;
|
|
3188
|
+
while (result.length < minChars) result = "a" + result;
|
|
3189
|
+
return result;
|
|
3190
|
+
}
|
|
3191
|
+
__name(leftPad, "leftPad");
|
|
3192
|
+
function rightPad(key, minChars) {
|
|
3193
|
+
let result = key;
|
|
3194
|
+
while (result.length < minChars) result = result + "a";
|
|
3195
|
+
return result;
|
|
3196
|
+
}
|
|
3197
|
+
__name(rightPad, "rightPad");
|
|
3198
|
+
function firstKey() {
|
|
3199
|
+
return generateBetween(null, null);
|
|
3200
|
+
}
|
|
3201
|
+
__name(firstKey, "firstKey");
|
|
3202
|
+
function after(left) {
|
|
3203
|
+
return generateBetween(left, null);
|
|
3204
|
+
}
|
|
3205
|
+
__name(after, "after");
|
|
3206
|
+
function before(right) {
|
|
3207
|
+
return generateBetween(null, right);
|
|
3208
|
+
}
|
|
3209
|
+
__name(before, "before");
|
|
3210
|
+
function between(left, right) {
|
|
3211
|
+
return generateBetween(left, right);
|
|
3212
|
+
}
|
|
3213
|
+
__name(between, "between");
|
|
3214
|
+
function reorder(items, fromIndex, toIndex) {
|
|
3215
|
+
if (fromIndex === toIndex) return items.map((i) => i.key);
|
|
3216
|
+
const reordered = [...items];
|
|
3217
|
+
const [removed] = reordered.splice(fromIndex, 1);
|
|
3218
|
+
reordered.splice(toIndex, 0, removed);
|
|
3219
|
+
return reordered.map((i) => i.key);
|
|
3220
|
+
}
|
|
3221
|
+
__name(reorder, "reorder");
|
|
3222
|
+
function reindex(items) {
|
|
3223
|
+
if (items.length === 0) return items;
|
|
3224
|
+
const result = [];
|
|
3225
|
+
let prev = null;
|
|
3226
|
+
for (let i = 0; i < items.length; i++) {
|
|
3227
|
+
const next = i < items.length - 1 ? items[i + 1].key : null;
|
|
3228
|
+
const newItem = { ...items[i] };
|
|
3229
|
+
if (prev === null) {
|
|
3230
|
+
newItem.key = before(items[0].key);
|
|
3231
|
+
} else if (next === null) {
|
|
3232
|
+
newItem.key = after(prev);
|
|
3233
|
+
} else {
|
|
3234
|
+
newItem.key = between(prev, next);
|
|
3235
|
+
}
|
|
3236
|
+
result.push(newItem);
|
|
3237
|
+
prev = newItem.key;
|
|
3238
|
+
}
|
|
3239
|
+
return result;
|
|
3240
|
+
}
|
|
3241
|
+
__name(reindex, "reindex");
|
|
3242
|
+
var fractional = {
|
|
3243
|
+
generateBetween,
|
|
3244
|
+
firstKey,
|
|
3245
|
+
after,
|
|
3246
|
+
before,
|
|
3247
|
+
between,
|
|
3248
|
+
reorder,
|
|
3249
|
+
reindex
|
|
3250
|
+
};
|
|
47
3251
|
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
memorio.isDeno() - Deno environment
|
|
52
|
-
memorio.isEdge() - Edge/Worker environment
|
|
53
|
-
memorio.getCapabilities() - Full capabilities object
|
|
3252
|
+
// index.ts
|
|
3253
|
+
init_internal();
|
|
3254
|
+
init_platform();
|
|
54
3255
|
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
memorio.devtools.exportData() - Export as JSON
|
|
60
|
-
memorio.devtools.importData() - Import from JSON
|
|
61
|
-
memorio.devtools.clear() - Clear specific module
|
|
62
|
-
memorio.devtools.clearAll() - Clear all modules
|
|
3256
|
+
// core/global.ts
|
|
3257
|
+
init_esm_shims();
|
|
3258
|
+
init_platform();
|
|
3259
|
+
init_internal();
|
|
63
3260
|
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
memorio.memory.update(key, value, opts) - Update an existing memory
|
|
68
|
-
memorio.memory.forget(key) - Delete a specific memory
|
|
69
|
-
memorio.memory.context(opts) - Get ranked relevant memories (semantic context for AI)
|
|
70
|
-
memorio.memory.stats() - Memory usage statistics
|
|
71
|
-
memorio.memory.forgetExpired() - Remove all expired entries
|
|
72
|
-
memorio.memory.clear() - Wipe all memories
|
|
73
|
-
memorio.memory.configure({ sync }) - Optional cloud-sync provider + namespace
|
|
74
|
-
memorio.memory.journal.pending() - Local op journal (SQLite/store)
|
|
3261
|
+
// package.json
|
|
3262
|
+
var package_default = {
|
|
3263
|
+
version: "4.9.7"};
|
|
75
3264
|
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
3265
|
+
// core/global.ts
|
|
3266
|
+
init_env();
|
|
3267
|
+
init_store();
|
|
3268
|
+
init_idb();
|
|
3269
|
+
init_sqlite();
|
|
3270
|
+
init_message();
|
|
82
3271
|
|
|
83
|
-
|
|
84
|
-
|
|
3272
|
+
// functions/typed/index.ts
|
|
3273
|
+
init_esm_shims();
|
|
3274
|
+
function typed() {
|
|
3275
|
+
return state2;
|
|
3276
|
+
}
|
|
3277
|
+
__name(typed, "typed");
|
|
85
3278
|
|
|
86
|
-
|
|
87
|
-
|
|
3279
|
+
// functions/history/index.ts
|
|
3280
|
+
init_esm_shims();
|
|
3281
|
+
init_internal();
|
|
3282
|
+
init_message();
|
|
3283
|
+
function _clone(value) {
|
|
3284
|
+
if (value === null || typeof value !== "object") return value;
|
|
3285
|
+
const ctor = value.constructor?.name;
|
|
3286
|
+
if (ctor !== "Object" && ctor !== "Array") return value;
|
|
3287
|
+
try {
|
|
3288
|
+
return JSON.parse(JSON.stringify(value));
|
|
3289
|
+
} catch {
|
|
3290
|
+
return value;
|
|
3291
|
+
}
|
|
3292
|
+
}
|
|
3293
|
+
__name(_clone, "_clone");
|
|
3294
|
+
var snapshot = /* @__PURE__ */ __name(() => {
|
|
3295
|
+
return _clone(deepRaw(state2));
|
|
3296
|
+
}, "snapshot");
|
|
3297
|
+
var diff = /* @__PURE__ */ __name((snap) => {
|
|
3298
|
+
const changes = [];
|
|
3299
|
+
const _walk = /* @__PURE__ */ __name((oldObj, newObj, prefix) => {
|
|
3300
|
+
const oldKeys = oldObj ? Object.keys(oldObj) : [];
|
|
3301
|
+
const newKeys = newObj ? Object.keys(newObj) : [];
|
|
3302
|
+
for (const key of newKeys) {
|
|
3303
|
+
const newPath = prefix ? `${prefix}.${key}` : key;
|
|
3304
|
+
const oldVal = oldObj ? oldObj[key] : void 0;
|
|
3305
|
+
const newVal = newObj[key];
|
|
3306
|
+
if (oldVal !== newVal) {
|
|
3307
|
+
const oldType = typeof oldVal;
|
|
3308
|
+
const newType = typeof newVal;
|
|
3309
|
+
if (oldType !== newType || oldVal === void 0) {
|
|
3310
|
+
changes.push({ path: newPath, oldValue: oldVal, newValue: newVal });
|
|
3311
|
+
} else if (oldVal && typeof oldVal === "object") {
|
|
3312
|
+
_walk(oldVal, newVal, newPath);
|
|
3313
|
+
} else if (oldVal !== newVal) {
|
|
3314
|
+
changes.push({ path: newPath, oldValue: oldVal, newValue: newVal });
|
|
3315
|
+
}
|
|
3316
|
+
}
|
|
3317
|
+
}
|
|
3318
|
+
for (const key of oldKeys) {
|
|
3319
|
+
if (!(key in (newObj || {}))) {
|
|
3320
|
+
const newPath = prefix ? `${prefix}.${key}` : key;
|
|
3321
|
+
changes.push({ path: newPath, oldValue: oldObj[key], newValue: void 0 });
|
|
3322
|
+
}
|
|
3323
|
+
}
|
|
3324
|
+
}, "_walk");
|
|
3325
|
+
_walk(snap, deepRaw(state2), "");
|
|
3326
|
+
return changes;
|
|
3327
|
+
}, "diff");
|
|
3328
|
+
var enableHistory = /* @__PURE__ */ __name((enabled = true) => {
|
|
3329
|
+
internal_default.historyEnabled = enabled;
|
|
3330
|
+
message_default(`[memorio history] Tracking ${enabled ? "enabled" : "disabled"}`);
|
|
3331
|
+
}, "enableHistory");
|
|
3332
|
+
var trace = /* @__PURE__ */ __name(() => {
|
|
3333
|
+
return [...internal_default.mutations];
|
|
3334
|
+
}, "trace");
|
|
3335
|
+
var canUndo = /* @__PURE__ */ __name(() => {
|
|
3336
|
+
return internal_default.canUndo();
|
|
3337
|
+
}, "canUndo");
|
|
3338
|
+
var canRedo = /* @__PURE__ */ __name(() => {
|
|
3339
|
+
return internal_default.canRedo();
|
|
3340
|
+
}, "canRedo");
|
|
3341
|
+
var undo = /* @__PURE__ */ __name(() => {
|
|
3342
|
+
if (!internal_default.historyEnabled) {
|
|
3343
|
+
message_default("[memorio history] History is not enabled");
|
|
3344
|
+
return void 0;
|
|
3345
|
+
}
|
|
3346
|
+
const record = internal_default.popUndo();
|
|
3347
|
+
if (!record) return void 0;
|
|
3348
|
+
_applyInverse(record);
|
|
3349
|
+
message_default(`[memorio history] Undid: ${record.action} ${record.path}`);
|
|
3350
|
+
return record;
|
|
3351
|
+
}, "undo");
|
|
3352
|
+
var redo = /* @__PURE__ */ __name(() => {
|
|
3353
|
+
if (!internal_default.historyEnabled) {
|
|
3354
|
+
message_default("[memorio history] History is not enabled");
|
|
3355
|
+
return void 0;
|
|
3356
|
+
}
|
|
3357
|
+
const record = internal_default.popRedo();
|
|
3358
|
+
if (!record) return void 0;
|
|
3359
|
+
_applyForward(record);
|
|
3360
|
+
message_default(`[memorio history] Redid: ${record.action} ${record.path}`);
|
|
3361
|
+
return record;
|
|
3362
|
+
}, "redo");
|
|
3363
|
+
function _applyInverse(record) {
|
|
3364
|
+
const wasEnabled = internal_default.historyEnabled;
|
|
3365
|
+
internal_default.historyEnabled = false;
|
|
3366
|
+
try {
|
|
3367
|
+
if (record.action === "set") {
|
|
3368
|
+
if (record.previousValue === void 0) {
|
|
3369
|
+
_deletePath(record.path);
|
|
3370
|
+
} else {
|
|
3371
|
+
_setPath(record.path, record.previousValue);
|
|
3372
|
+
}
|
|
3373
|
+
} else if (record.action === "delete") {
|
|
3374
|
+
if (record.previousValue !== void 0) {
|
|
3375
|
+
_setPath(record.path, record.previousValue);
|
|
3376
|
+
}
|
|
3377
|
+
}
|
|
3378
|
+
} finally {
|
|
3379
|
+
internal_default.historyEnabled = wasEnabled;
|
|
3380
|
+
}
|
|
3381
|
+
}
|
|
3382
|
+
__name(_applyInverse, "_applyInverse");
|
|
3383
|
+
function _applyForward(record) {
|
|
3384
|
+
const wasEnabled = internal_default.historyEnabled;
|
|
3385
|
+
internal_default.historyEnabled = false;
|
|
3386
|
+
try {
|
|
3387
|
+
if (record.action === "set") {
|
|
3388
|
+
_setPath(record.path, record.newValue);
|
|
3389
|
+
} else if (record.action === "delete") {
|
|
3390
|
+
_deletePath(record.path);
|
|
3391
|
+
}
|
|
3392
|
+
} finally {
|
|
3393
|
+
internal_default.historyEnabled = wasEnabled;
|
|
3394
|
+
}
|
|
3395
|
+
}
|
|
3396
|
+
__name(_applyForward, "_applyForward");
|
|
3397
|
+
function _setPath(path2, value) {
|
|
3398
|
+
const parts = path2.split(".");
|
|
3399
|
+
let current = state2;
|
|
3400
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
3401
|
+
const part = parts[i];
|
|
3402
|
+
if (current[part] === void 0) {
|
|
3403
|
+
current[part] = {};
|
|
3404
|
+
}
|
|
3405
|
+
current = current[part];
|
|
3406
|
+
}
|
|
3407
|
+
current[parts[parts.length - 1]] = value;
|
|
3408
|
+
}
|
|
3409
|
+
__name(_setPath, "_setPath");
|
|
3410
|
+
function _deletePath(path2) {
|
|
3411
|
+
const parts = path2.split(".");
|
|
3412
|
+
if (parts.length === 1) {
|
|
3413
|
+
state2.remove(parts[0]);
|
|
3414
|
+
return;
|
|
3415
|
+
}
|
|
3416
|
+
let current = state2;
|
|
3417
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
3418
|
+
const part = parts[i];
|
|
3419
|
+
if (current[part] === void 0) return;
|
|
3420
|
+
current = current[part];
|
|
3421
|
+
}
|
|
3422
|
+
delete current[parts[parts.length - 1]];
|
|
3423
|
+
}
|
|
3424
|
+
__name(_deletePath, "_deletePath");
|
|
3425
|
+
var rollback = /* @__PURE__ */ __name((snap) => {
|
|
3426
|
+
state2.removeAll();
|
|
3427
|
+
for (const key of Object.keys(snap)) {
|
|
3428
|
+
state2[key] = _clone(snap[key]);
|
|
3429
|
+
}
|
|
3430
|
+
internal_default.clearHistory();
|
|
3431
|
+
message_default("[memorio history] State rolled back to snapshot");
|
|
3432
|
+
}, "rollback");
|
|
3433
|
+
var clearHistory2 = /* @__PURE__ */ __name(() => {
|
|
3434
|
+
internal_default.clearHistory();
|
|
3435
|
+
message_default("[memorio history] History cleared");
|
|
3436
|
+
}, "clearHistory");
|
|
3437
|
+
var clearRedo = /* @__PURE__ */ __name(() => {
|
|
3438
|
+
internal_default.clearRedo();
|
|
3439
|
+
}, "clearRedo");
|
|
88
3440
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
3441
|
+
// functions/memory/index.ts
|
|
3442
|
+
init_esm_shims();
|
|
3443
|
+
init_store();
|
|
3444
|
+
init_idb();
|
|
3445
|
+
|
|
3446
|
+
// functions/memory/journal.ts
|
|
3447
|
+
init_esm_shims();
|
|
3448
|
+
init_store();
|
|
3449
|
+
var g2 = globalThis;
|
|
3450
|
+
function namespace() {
|
|
3451
|
+
const cfg = g2.memorioSyncConfig;
|
|
3452
|
+
if (cfg && typeof cfg.namespace === "string" && cfg.namespace) return `ns:${cfg.namespace}`;
|
|
3453
|
+
const ctx = g2.memorio ? g2.memorio._currentContext : void 0;
|
|
3454
|
+
const ctxName = typeof ctx === "string" && ctx ? ctx : "";
|
|
3455
|
+
return ctxName ? `ctx:${ctxName}` : "default";
|
|
3456
|
+
}
|
|
3457
|
+
__name(namespace, "namespace");
|
|
3458
|
+
function isSyncEnabled() {
|
|
3459
|
+
return !!g2.memorioSyncConfig;
|
|
3460
|
+
}
|
|
3461
|
+
__name(isSyncEnabled, "isSyncEnabled");
|
|
3462
|
+
var STORE_PREFIX = /* @__PURE__ */ __name((ns) => `memorio:sync:${ns}:`, "STORE_PREFIX");
|
|
3463
|
+
var INDEX_KEY = /* @__PURE__ */ __name((ns) => `${STORE_PREFIX(ns)}index`, "INDEX_KEY");
|
|
3464
|
+
function parseEntry(raw) {
|
|
3465
|
+
try {
|
|
3466
|
+
if (typeof raw === "string") return JSON.parse(raw);
|
|
3467
|
+
return raw;
|
|
3468
|
+
} catch {
|
|
3469
|
+
return null;
|
|
3470
|
+
}
|
|
3471
|
+
}
|
|
3472
|
+
__name(parseEntry, "parseEntry");
|
|
3473
|
+
var journal = {
|
|
3474
|
+
/** Append (or replace) a journal row for the current namespace. */
|
|
3475
|
+
async append(entry, operation) {
|
|
3476
|
+
const ns = namespace();
|
|
3477
|
+
const row = {
|
|
3478
|
+
...entry,
|
|
3479
|
+
operation,
|
|
3480
|
+
updatedAt: entry.updatedAt || Date.now(),
|
|
3481
|
+
version: entry.version || 1,
|
|
3482
|
+
sync: "pending",
|
|
3483
|
+
hlc: entry.hlc || hlc.serialize(hlc.tick())
|
|
3484
|
+
};
|
|
3485
|
+
const key = `${STORE_PREFIX(ns)}${row.id}`;
|
|
3486
|
+
store.set(key, row);
|
|
3487
|
+
const idx = store.get(INDEX_KEY(ns)) || [];
|
|
3488
|
+
if (!idx.includes(row.id)) idx.push(row.id);
|
|
3489
|
+
store.set(INDEX_KEY(ns), idx);
|
|
3490
|
+
return row;
|
|
3491
|
+
},
|
|
3492
|
+
/** All pending (not-yet-synced) entries for the current namespace. */
|
|
3493
|
+
async pending() {
|
|
3494
|
+
const ns = namespace();
|
|
3495
|
+
const out = [];
|
|
3496
|
+
const idx = store.get(INDEX_KEY(ns)) || [];
|
|
3497
|
+
for (const id of idx) {
|
|
3498
|
+
const raw = store.get(`${STORE_PREFIX(ns)}${id}`);
|
|
3499
|
+
if (!raw) continue;
|
|
3500
|
+
const e = parseEntry(raw);
|
|
3501
|
+
if (e && e.sync !== "synced") out.push(e);
|
|
3502
|
+
}
|
|
3503
|
+
out.sort((a, b) => {
|
|
3504
|
+
if (a.hlc && b.hlc) {
|
|
3505
|
+
const ha = hlc.parse(a.hlc);
|
|
3506
|
+
const hb = hlc.parse(b.hlc);
|
|
3507
|
+
if (ha && hb) return hlc.compare(ha, hb);
|
|
3508
|
+
}
|
|
3509
|
+
return (a.updatedAt || 0) - (b.updatedAt || 0);
|
|
3510
|
+
});
|
|
3511
|
+
return out;
|
|
3512
|
+
},
|
|
3513
|
+
/**
|
|
3514
|
+
* Mark entries as synced. Returns the number of rows actually advanced to
|
|
3515
|
+
* `synced` (namespace-scoped).
|
|
3516
|
+
*/
|
|
3517
|
+
async markSynced(ids) {
|
|
3518
|
+
if (!ids.length) return 0;
|
|
3519
|
+
const ns = namespace();
|
|
3520
|
+
let count = 0;
|
|
3521
|
+
const idx = store.get(INDEX_KEY(ns)) || [];
|
|
3522
|
+
for (const id of idx) {
|
|
3523
|
+
if (!ids.includes(id)) continue;
|
|
3524
|
+
const key = `${STORE_PREFIX(ns)}${id}`;
|
|
3525
|
+
const raw = store.get(key);
|
|
3526
|
+
if (!raw) continue;
|
|
3527
|
+
const e = parseEntry(raw);
|
|
3528
|
+
if (!e || e.sync === "synced") continue;
|
|
3529
|
+
e.sync = "synced";
|
|
3530
|
+
store.set(key, e);
|
|
3531
|
+
count++;
|
|
3532
|
+
}
|
|
3533
|
+
return count;
|
|
3534
|
+
},
|
|
3535
|
+
async get(id) {
|
|
3536
|
+
const ns = namespace();
|
|
3537
|
+
const raw = store.get(`${STORE_PREFIX(ns)}${id}`);
|
|
3538
|
+
return parseEntry(raw ?? "");
|
|
3539
|
+
},
|
|
3540
|
+
/** Remove all journal rows for the current namespace. */
|
|
3541
|
+
async clear() {
|
|
3542
|
+
const ns = namespace();
|
|
3543
|
+
const idx = store.get(INDEX_KEY(ns)) || [];
|
|
3544
|
+
for (const id of idx) store.remove(`${STORE_PREFIX(ns)}${id}`);
|
|
3545
|
+
store.remove(INDEX_KEY(ns));
|
|
3546
|
+
},
|
|
3547
|
+
/**
|
|
3548
|
+
* Reconcile the local journal against the configured provider. Pushes pending
|
|
3549
|
+
* local operations, then optionally pulls newer remote operations and applies
|
|
3550
|
+
* them. No-op (empty ack) when no provider is configured.
|
|
3551
|
+
*
|
|
3552
|
+
* When pulling remote entries, HLC timestamps are used to order operations
|
|
3553
|
+
* causally. Concurrent writes to the same key are resolved via the provider's
|
|
3554
|
+
* `resolveConflict` method (if provided), falling back to HLC timestamp
|
|
3555
|
+
* comparison.
|
|
3556
|
+
*/
|
|
3557
|
+
async replay() {
|
|
3558
|
+
const ack = { synced: [], resolved: [] };
|
|
3559
|
+
if (!isSyncEnabled()) return ack;
|
|
3560
|
+
const transport = g2.memorioSyncConfig || {};
|
|
3561
|
+
const provider = transport.provider;
|
|
3562
|
+
if (!provider || typeof provider.push !== "function") return ack;
|
|
3563
|
+
const pending = await this.pending();
|
|
3564
|
+
if (pending.length) {
|
|
3565
|
+
try {
|
|
3566
|
+
const res = await provider.push(pending);
|
|
3567
|
+
ack.synced = res?.synced || [];
|
|
3568
|
+
ack.conflicts = res?.conflicts;
|
|
3569
|
+
ack.error = res?.error;
|
|
3570
|
+
if (ack.synced.length) await this.markSynced(ack.synced);
|
|
3571
|
+
} catch (err) {
|
|
3572
|
+
ack.error = String(err);
|
|
3573
|
+
}
|
|
3574
|
+
}
|
|
3575
|
+
if (typeof provider.pull === "function") {
|
|
3576
|
+
try {
|
|
3577
|
+
const since = pending.length ? Math.min(...pending.map((p) => p.updatedAt || 0)) : 0;
|
|
3578
|
+
const remote = await provider.pull(since);
|
|
3579
|
+
for (const e of remote || []) {
|
|
3580
|
+
if (e.hlc) {
|
|
3581
|
+
const parsed = hlc.parse(e.hlc);
|
|
3582
|
+
if (parsed) hlc.receive(parsed);
|
|
3583
|
+
}
|
|
3584
|
+
const localEntry = await this.get(e.id);
|
|
3585
|
+
if (localEntry && e.hlc && localEntry.hlc) {
|
|
3586
|
+
const ha = hlc.parse(localEntry.hlc);
|
|
3587
|
+
const hb = hlc.parse(e.hlc);
|
|
3588
|
+
if (ha && hb) {
|
|
3589
|
+
const cmp = hlc.compare(ha, hb);
|
|
3590
|
+
if (cmp === 0) {
|
|
3591
|
+
const resolution = typeof provider.resolveConflict === "function" ? await provider.resolveConflict(localEntry, e) : "remote";
|
|
3592
|
+
ack.resolved?.push({ id: e.id, resolution });
|
|
3593
|
+
if (resolution === "local") continue;
|
|
3594
|
+
} else if (cmp > 0) {
|
|
3595
|
+
continue;
|
|
3596
|
+
}
|
|
3597
|
+
}
|
|
3598
|
+
}
|
|
3599
|
+
await this.append(e, e.operation || "confirm");
|
|
3600
|
+
await this.markSynced([e.id]);
|
|
3601
|
+
}
|
|
3602
|
+
} catch (_) {
|
|
3603
|
+
}
|
|
3604
|
+
}
|
|
3605
|
+
return ack;
|
|
3606
|
+
},
|
|
3607
|
+
status() {
|
|
3608
|
+
return Promise.resolve("store");
|
|
3609
|
+
}
|
|
3610
|
+
};
|
|
3611
|
+
function configure2(opts) {
|
|
3612
|
+
const prev = g2.memorioSyncConfig || {};
|
|
3613
|
+
g2.memorioSyncConfig = { ...prev, ...opts };
|
|
3614
|
+
return journal;
|
|
3615
|
+
}
|
|
3616
|
+
__name(configure2, "configure");
|
|
3617
|
+
if (typeof g2.addEventListener === "function") {
|
|
3618
|
+
let armed = false;
|
|
3619
|
+
g2.addEventListener("focus", () => {
|
|
3620
|
+
if (armed || !isSyncEnabled()) return;
|
|
3621
|
+
armed = true;
|
|
3622
|
+
void journal.replay().finally(() => {
|
|
3623
|
+
armed = false;
|
|
3624
|
+
});
|
|
3625
|
+
});
|
|
3626
|
+
}
|
|
3627
|
+
var journal_default = journal;
|
|
3628
|
+
|
|
3629
|
+
// functions/memory/index.ts
|
|
3630
|
+
var MEMORY_INDEX_KEY = "__memorio_memory_index__";
|
|
3631
|
+
var SUPERSEDED_PREFIX = "__memorio_superseded__";
|
|
3632
|
+
function isSyncEnabled2() {
|
|
3633
|
+
return !!globalThis.memorioSyncConfig;
|
|
3634
|
+
}
|
|
3635
|
+
__name(isSyncEnabled2, "isSyncEnabled");
|
|
3636
|
+
async function recordJournal(entry, operation) {
|
|
3637
|
+
if (!isSyncEnabled2()) return;
|
|
3638
|
+
if (entry.scope === "hot") return;
|
|
3639
|
+
try {
|
|
3640
|
+
await journal_default.append(entry, operation);
|
|
3641
|
+
} catch (_) {
|
|
3642
|
+
}
|
|
3643
|
+
}
|
|
3644
|
+
__name(recordJournal, "recordJournal");
|
|
3645
|
+
function memoryEntryKey(id) {
|
|
3646
|
+
return id.startsWith(SUPERSEDED_PREFIX) ? id : `${SUPERSEDED_PREFIX}${id}`;
|
|
3647
|
+
}
|
|
3648
|
+
__name(memoryEntryKey, "memoryEntryKey");
|
|
3649
|
+
function normalizeTags(tags) {
|
|
3650
|
+
if (!tags) return [];
|
|
3651
|
+
return Array.isArray(tags) ? tags : [tags];
|
|
3652
|
+
}
|
|
3653
|
+
__name(normalizeTags, "normalizeTags");
|
|
3654
|
+
function resolveScope(value, opts) {
|
|
3655
|
+
if (opts.scope) return opts.scope;
|
|
3656
|
+
const size = JSON.stringify(value).length;
|
|
3657
|
+
if (size > 1e6) return "durable";
|
|
3658
|
+
if (size > 1e5) return "local";
|
|
3659
|
+
return "local";
|
|
3660
|
+
}
|
|
3661
|
+
__name(resolveScope, "resolveScope");
|
|
3662
|
+
function now() {
|
|
3663
|
+
return Date.now();
|
|
3664
|
+
}
|
|
3665
|
+
__name(now, "now");
|
|
3666
|
+
function isExpired(entry) {
|
|
3667
|
+
if (entry.ttl === null || entry.ttl === void 0) return false;
|
|
3668
|
+
return now() - entry.createdAt > entry.ttl;
|
|
3669
|
+
}
|
|
3670
|
+
__name(isExpired, "isExpired");
|
|
3671
|
+
function matchesFilters(entry, opts) {
|
|
3672
|
+
if (entry.status === "obsolete") return opts.includeObsolete ?? false;
|
|
3673
|
+
if (entry.status === "superseded") return opts.includeObsolete ?? false;
|
|
3674
|
+
if (isExpired(entry)) {
|
|
3675
|
+
return opts.includeObsolete ?? false;
|
|
3676
|
+
}
|
|
3677
|
+
if (opts.type) {
|
|
3678
|
+
const types = Array.isArray(opts.type) ? opts.type : [opts.type];
|
|
3679
|
+
if (!types.includes(entry.type)) return false;
|
|
3680
|
+
}
|
|
3681
|
+
if (opts.minConfidence !== void 0 && entry.confidence < opts.minConfidence) return false;
|
|
3682
|
+
return true;
|
|
3683
|
+
}
|
|
3684
|
+
__name(matchesFilters, "matchesFilters");
|
|
3685
|
+
function matchesContextFilters(entry, opts) {
|
|
3686
|
+
if (entry.status !== "active") return false;
|
|
3687
|
+
if (isExpired(entry)) return false;
|
|
3688
|
+
if (opts.tags) {
|
|
3689
|
+
const tags = Array.isArray(opts.tags) ? opts.tags : [opts.tags];
|
|
3690
|
+
const hasMatch = tags.some((t) => entry.tags.includes(t));
|
|
3691
|
+
if (!hasMatch) return false;
|
|
3692
|
+
}
|
|
3693
|
+
if (opts.types) {
|
|
3694
|
+
const types = Array.isArray(opts.types) ? opts.types : [opts.types];
|
|
3695
|
+
if (!types.includes(entry.type)) return false;
|
|
3696
|
+
}
|
|
3697
|
+
if (opts.minConfidence !== void 0 && entry.confidence < opts.minConfidence) return false;
|
|
3698
|
+
if (opts.scopes && !opts.scopes.includes(entry.scope)) return false;
|
|
3699
|
+
return true;
|
|
3700
|
+
}
|
|
3701
|
+
__name(matchesContextFilters, "matchesContextFilters");
|
|
3702
|
+
function computeRelevance(entry) {
|
|
3703
|
+
const ageHours = (now() - entry.createdAt) / (1e3 * 3600);
|
|
3704
|
+
const recencyScore = Math.max(0.1, 1 / (1 + ageHours * 0.5));
|
|
3705
|
+
const confidenceScore = entry.confidence;
|
|
3706
|
+
const accessScore = 1 + entry.tags.length * 0.1;
|
|
3707
|
+
const typeBoost = {
|
|
3708
|
+
decision: 1.5,
|
|
3709
|
+
context: 1.3,
|
|
3710
|
+
preference: 1.2,
|
|
3711
|
+
task: 1,
|
|
3712
|
+
fact: 0.8
|
|
3713
|
+
};
|
|
3714
|
+
const scopeBoost = {
|
|
3715
|
+
hot: 1.5,
|
|
3716
|
+
session: 1.2,
|
|
3717
|
+
local: 1,
|
|
3718
|
+
durable: 0.8
|
|
3719
|
+
};
|
|
3720
|
+
return recencyScore * confidenceScore * accessScore * typeBoost[entry.type] * scopeBoost[entry.scope];
|
|
3721
|
+
}
|
|
3722
|
+
__name(computeRelevance, "computeRelevance");
|
|
3723
|
+
function getNestedPath(obj, path2) {
|
|
3724
|
+
if (!path2 || typeof path2 !== "string") return void 0;
|
|
3725
|
+
const parts = path2.replace(/^state\./, "").split(".");
|
|
3726
|
+
let current = obj;
|
|
3727
|
+
for (const part of parts) {
|
|
3728
|
+
if (current === null || current === void 0) return void 0;
|
|
3729
|
+
current = current[part];
|
|
3730
|
+
}
|
|
3731
|
+
return current;
|
|
3732
|
+
}
|
|
3733
|
+
__name(getNestedPath, "getNestedPath");
|
|
3734
|
+
function setNestedPath(obj, path2, value) {
|
|
3735
|
+
if (!path2 || typeof path2 !== "string") return;
|
|
3736
|
+
const parts = path2.replace(/^state\./, "").split(".");
|
|
3737
|
+
let current = obj;
|
|
3738
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
3739
|
+
const part = parts[i];
|
|
3740
|
+
if (current[part] === void 0 || current[part] === null) {
|
|
3741
|
+
current[part] = {};
|
|
3742
|
+
}
|
|
3743
|
+
current = current[part];
|
|
3744
|
+
}
|
|
3745
|
+
current[parts[parts.length - 1]] = value;
|
|
3746
|
+
}
|
|
3747
|
+
__name(setNestedPath, "setNestedPath");
|
|
3748
|
+
function deleteNestedPath(obj, path2) {
|
|
3749
|
+
if (!path2 || typeof path2 !== "string") return;
|
|
3750
|
+
const parts = path2.replace(/^state\./, "").split(".");
|
|
3751
|
+
let current = obj;
|
|
3752
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
3753
|
+
const part = parts[i];
|
|
3754
|
+
if (current[part] === void 0 || current[part] === null) return;
|
|
3755
|
+
current = current[part];
|
|
3756
|
+
}
|
|
3757
|
+
delete current[parts[parts.length - 1]];
|
|
3758
|
+
}
|
|
3759
|
+
__name(deleteNestedPath, "deleteNestedPath");
|
|
3760
|
+
async function saveToScope(entry) {
|
|
3761
|
+
const storageKey = entry.status === "superseded" ? memoryEntryKey(entry.id || entry.key) : entry.key;
|
|
3762
|
+
const serialized = JSON.stringify(entry);
|
|
3763
|
+
switch (entry.scope) {
|
|
3764
|
+
case "hot":
|
|
3765
|
+
setNestedPath(state2, storageKey, entry.value);
|
|
3766
|
+
break;
|
|
3767
|
+
case "session":
|
|
3768
|
+
session.set(storageKey, serialized);
|
|
3769
|
+
break;
|
|
3770
|
+
case "local":
|
|
3771
|
+
store.set(storageKey, serialized);
|
|
3772
|
+
break;
|
|
3773
|
+
case "durable":
|
|
3774
|
+
await idb.set("memories", storageKey, serialized);
|
|
3775
|
+
break;
|
|
3776
|
+
}
|
|
3777
|
+
await updateIndex(entry.id || entry.key, entry.scope, entry.status === "superseded");
|
|
3778
|
+
}
|
|
3779
|
+
__name(saveToScope, "saveToScope");
|
|
3780
|
+
async function loadFromScope(id, scope, isSuperseded = false) {
|
|
3781
|
+
const storageKey = isSuperseded ? memoryEntryKey(id) : id;
|
|
3782
|
+
let raw;
|
|
3783
|
+
switch (scope) {
|
|
3784
|
+
case "hot": {
|
|
3785
|
+
const val = getNestedPath(state2, storageKey);
|
|
3786
|
+
if (val === void 0) return null;
|
|
3787
|
+
return reconstructEntry(id, val, scope);
|
|
3788
|
+
}
|
|
3789
|
+
case "session":
|
|
3790
|
+
raw = session.get(storageKey);
|
|
3791
|
+
break;
|
|
3792
|
+
case "local":
|
|
3793
|
+
raw = store.get(storageKey);
|
|
3794
|
+
break;
|
|
3795
|
+
case "durable":
|
|
3796
|
+
raw = await idb.get("memories", storageKey);
|
|
3797
|
+
break;
|
|
3798
|
+
}
|
|
3799
|
+
if (!raw) return null;
|
|
3800
|
+
try {
|
|
3801
|
+
const entry = JSON.parse(raw);
|
|
3802
|
+
entry.id = entry.id || id;
|
|
3803
|
+
return entry;
|
|
3804
|
+
} catch {
|
|
3805
|
+
return null;
|
|
3806
|
+
}
|
|
3807
|
+
}
|
|
3808
|
+
__name(loadFromScope, "loadFromScope");
|
|
3809
|
+
function reconstructEntry(key, value, scope) {
|
|
3810
|
+
return {
|
|
3811
|
+
id: key,
|
|
3812
|
+
key,
|
|
3813
|
+
value,
|
|
3814
|
+
type: "fact",
|
|
3815
|
+
confidence: 1,
|
|
3816
|
+
scope,
|
|
3817
|
+
ttl: null,
|
|
3818
|
+
tags: [],
|
|
3819
|
+
status: "active",
|
|
3820
|
+
createdAt: now(),
|
|
3821
|
+
lastConfirmedAt: now(),
|
|
3822
|
+
supersededId: null
|
|
3823
|
+
};
|
|
3824
|
+
}
|
|
3825
|
+
__name(reconstructEntry, "reconstructEntry");
|
|
3826
|
+
async function removeFromScope(id, scope, isSuperseded = false) {
|
|
3827
|
+
const storageKey = isSuperseded ? memoryEntryKey(id) : id;
|
|
3828
|
+
switch (scope) {
|
|
3829
|
+
case "hot":
|
|
3830
|
+
setNestedPath(state2, storageKey, void 0);
|
|
3831
|
+
break;
|
|
3832
|
+
case "session":
|
|
3833
|
+
session.remove(storageKey);
|
|
3834
|
+
break;
|
|
3835
|
+
case "local":
|
|
3836
|
+
store.remove(storageKey);
|
|
3837
|
+
break;
|
|
3838
|
+
case "durable":
|
|
3839
|
+
await idb.deleteKey("memories", storageKey);
|
|
3840
|
+
break;
|
|
3841
|
+
}
|
|
3842
|
+
await removeFromIndex(id, isSuperseded);
|
|
3843
|
+
}
|
|
3844
|
+
__name(removeFromScope, "removeFromScope");
|
|
3845
|
+
async function getAllIndexes() {
|
|
3846
|
+
try {
|
|
3847
|
+
const raw = store.get(MEMORY_INDEX_KEY);
|
|
3848
|
+
if (!raw) return {};
|
|
3849
|
+
return JSON.parse(raw);
|
|
3850
|
+
} catch {
|
|
3851
|
+
return {};
|
|
3852
|
+
}
|
|
3853
|
+
}
|
|
3854
|
+
__name(getAllIndexes, "getAllIndexes");
|
|
3855
|
+
async function updateIndex(id, scope, isSuperseded = false) {
|
|
3856
|
+
const index = await getAllIndexes();
|
|
3857
|
+
index[id] = { scope, superseded: isSuperseded };
|
|
3858
|
+
store.set(MEMORY_INDEX_KEY, JSON.stringify(index));
|
|
3859
|
+
}
|
|
3860
|
+
__name(updateIndex, "updateIndex");
|
|
3861
|
+
async function removeFromIndex(id, isSuperseded = false) {
|
|
3862
|
+
const index = await getAllIndexes();
|
|
3863
|
+
const entry = index[id];
|
|
3864
|
+
if (entry) {
|
|
3865
|
+
if (isSuperseded && entry.superseded) {
|
|
3866
|
+
delete index[id];
|
|
3867
|
+
} else if (!isSuperseded && !entry.superseded) {
|
|
3868
|
+
delete index[id];
|
|
3869
|
+
}
|
|
3870
|
+
}
|
|
3871
|
+
store.set(MEMORY_INDEX_KEY, JSON.stringify(index));
|
|
3872
|
+
}
|
|
3873
|
+
__name(removeFromIndex, "removeFromIndex");
|
|
3874
|
+
async function loadAll() {
|
|
3875
|
+
const index = await getAllIndexes();
|
|
3876
|
+
const entries = [];
|
|
3877
|
+
for (const [id, info] of Object.entries(index)) {
|
|
3878
|
+
const entry = await loadFromScope(id, info.scope, info.superseded);
|
|
3879
|
+
if (entry) {
|
|
3880
|
+
entry.id = entry.id || id;
|
|
3881
|
+
entry.supersededId = entry.supersededId ?? null;
|
|
3882
|
+
entries.push(entry);
|
|
3883
|
+
}
|
|
3884
|
+
}
|
|
3885
|
+
return entries;
|
|
3886
|
+
}
|
|
3887
|
+
__name(loadAll, "loadAll");
|
|
3888
|
+
var memory = {
|
|
3889
|
+
async remember(key, value, opts = {}) {
|
|
3890
|
+
const existing = await this._getEntry(key);
|
|
3891
|
+
if (existing && existing.status === "active") {
|
|
3892
|
+
const supersededId = `${existing.id}__v${Date.now()}`;
|
|
3893
|
+
const superseded = {
|
|
3894
|
+
...existing,
|
|
3895
|
+
id: supersededId,
|
|
3896
|
+
key: existing.key,
|
|
3897
|
+
status: "superseded",
|
|
3898
|
+
supersededId: null,
|
|
3899
|
+
lastConfirmedAt: now()
|
|
3900
|
+
};
|
|
3901
|
+
await saveToScope(superseded);
|
|
3902
|
+
await recordJournal(superseded, "supersede");
|
|
3903
|
+
}
|
|
3904
|
+
const scope = resolveScope(value, opts);
|
|
3905
|
+
const tags = normalizeTags(opts.tags);
|
|
3906
|
+
const entry = {
|
|
3907
|
+
id: opts.id || key,
|
|
3908
|
+
key,
|
|
3909
|
+
value,
|
|
3910
|
+
type: opts.type || "fact",
|
|
3911
|
+
confidence: opts.confidence ?? 1,
|
|
3912
|
+
scope,
|
|
3913
|
+
ttl: opts.ttl ?? null,
|
|
3914
|
+
tags,
|
|
3915
|
+
source: opts.source,
|
|
3916
|
+
status: "active",
|
|
3917
|
+
createdAt: now(),
|
|
3918
|
+
lastConfirmedAt: now(),
|
|
3919
|
+
updatedAt: now(),
|
|
3920
|
+
version: existing ? existing.version ? existing.version + 1 : 1 : 1,
|
|
3921
|
+
sync: isSyncEnabled2() ? "pending" : void 0,
|
|
3922
|
+
supersededId: existing ? existing.id : null,
|
|
3923
|
+
hlc: hlc.serialize(hlc.tick())
|
|
3924
|
+
};
|
|
3925
|
+
await saveToScope(entry);
|
|
3926
|
+
await recordJournal(entry, "remember");
|
|
3927
|
+
dispatch.set("memorio:memory:remembered", { key, scope, entryId: entry.id });
|
|
3928
|
+
},
|
|
3929
|
+
async recall(query, opts = {}) {
|
|
3930
|
+
const entry = await this._getEntry(query);
|
|
3931
|
+
if (!entry) return null;
|
|
3932
|
+
if (!matchesFilters(entry, opts)) return null;
|
|
3933
|
+
entry.lastConfirmedAt = now();
|
|
3934
|
+
await saveToScope(entry);
|
|
3935
|
+
dispatch.set("memorio:memory:recalled", { key: query });
|
|
3936
|
+
return entry.value;
|
|
3937
|
+
},
|
|
3938
|
+
async context(opts = {}) {
|
|
3939
|
+
const entries = await loadAll();
|
|
3940
|
+
const filtered = entries.filter((e) => matchesContextFilters(e, opts));
|
|
3941
|
+
const ranked = filtered.map((entry) => ({
|
|
3942
|
+
entry,
|
|
3943
|
+
score: computeRelevance(entry)
|
|
3944
|
+
})).sort((a, b) => b.score - a.score).slice(0, opts.maxEntries ?? 25);
|
|
3945
|
+
return ranked.map(({ entry }) => ({
|
|
3946
|
+
key: entry.key,
|
|
3947
|
+
value: entry.value,
|
|
3948
|
+
type: entry.type,
|
|
3949
|
+
confidence: entry.confidence,
|
|
3950
|
+
scope: entry.scope,
|
|
3951
|
+
tags: entry.tags,
|
|
3952
|
+
age: now() - entry.createdAt,
|
|
3953
|
+
accessCount: entry.tags.length + 1,
|
|
3954
|
+
lastAccessedAt: entry.lastConfirmedAt
|
|
3955
|
+
}));
|
|
3956
|
+
},
|
|
3957
|
+
async forget(key) {
|
|
3958
|
+
const entry = await this._getEntry(key);
|
|
3959
|
+
if (!entry) {
|
|
3960
|
+
const tombstone2 = {
|
|
3961
|
+
id: key,
|
|
3962
|
+
key,
|
|
3963
|
+
value: null,
|
|
3964
|
+
type: "fact",
|
|
3965
|
+
confidence: 1,
|
|
3966
|
+
scope: "local",
|
|
3967
|
+
ttl: null,
|
|
3968
|
+
tags: [],
|
|
3969
|
+
status: "obsolete",
|
|
3970
|
+
operation: "delete",
|
|
3971
|
+
createdAt: now(),
|
|
3972
|
+
lastConfirmedAt: now(),
|
|
3973
|
+
updatedAt: now(),
|
|
3974
|
+
version: 1,
|
|
3975
|
+
sync: isSyncEnabled2() ? "pending" : void 0,
|
|
3976
|
+
hlc: hlc.serialize(hlc.tick())
|
|
3977
|
+
};
|
|
3978
|
+
await recordJournal(tombstone2, "delete");
|
|
3979
|
+
return;
|
|
3980
|
+
}
|
|
3981
|
+
await removeFromScope(entry.id || key, entry.scope, entry.status === "superseded");
|
|
3982
|
+
const tombstone = {
|
|
3983
|
+
...entry,
|
|
3984
|
+
value: null,
|
|
3985
|
+
status: "obsolete",
|
|
3986
|
+
operation: "delete",
|
|
3987
|
+
updatedAt: now(),
|
|
3988
|
+
version: (entry.version ? entry.version : 0) + 1,
|
|
3989
|
+
sync: isSyncEnabled2() ? "pending" : void 0,
|
|
3990
|
+
hlc: hlc.serialize(hlc.tick())
|
|
3991
|
+
};
|
|
3992
|
+
await recordJournal(tombstone, "delete");
|
|
3993
|
+
dispatch.set("memorio:memory:forgotten", { key });
|
|
3994
|
+
},
|
|
3995
|
+
async update(key, value, opts = {}) {
|
|
3996
|
+
const existing = await this._getEntry(key);
|
|
3997
|
+
if (!existing) {
|
|
3998
|
+
await this.remember(key, value, opts);
|
|
3999
|
+
return;
|
|
4000
|
+
}
|
|
4001
|
+
const supersededId = `${existing.id}__v${now()}`;
|
|
4002
|
+
const superseded = {
|
|
4003
|
+
...existing,
|
|
4004
|
+
id: supersededId,
|
|
4005
|
+
key: existing.key,
|
|
4006
|
+
status: "superseded",
|
|
4007
|
+
supersededId: null,
|
|
4008
|
+
lastConfirmedAt: now()
|
|
4009
|
+
};
|
|
4010
|
+
await saveToScope(superseded);
|
|
4011
|
+
await recordJournal(superseded, "supersede");
|
|
4012
|
+
const updated = {
|
|
4013
|
+
...existing,
|
|
4014
|
+
value,
|
|
4015
|
+
lastConfirmedAt: now(),
|
|
4016
|
+
updatedAt: now(),
|
|
4017
|
+
version: (existing.version ? existing.version : 0) + 1,
|
|
4018
|
+
sync: isSyncEnabled2() ? "pending" : void 0,
|
|
4019
|
+
hlc: hlc.serialize(hlc.tick()),
|
|
4020
|
+
...opts.scope ? { scope: opts.scope } : {},
|
|
4021
|
+
...opts.ttl !== void 0 ? { ttl: opts.ttl } : {},
|
|
4022
|
+
...opts.type ? { type: opts.type } : {},
|
|
4023
|
+
...opts.confidence !== void 0 ? { confidence: opts.confidence } : {},
|
|
4024
|
+
...opts.tags !== void 0 ? { tags: normalizeTags(opts.tags) } : {},
|
|
4025
|
+
...opts.source ? { source: opts.source } : {}
|
|
4026
|
+
};
|
|
4027
|
+
await saveToScope(updated);
|
|
4028
|
+
await recordJournal(updated, "update");
|
|
4029
|
+
dispatch.set("memorio:memory:updated", { key, entryId: updated.id });
|
|
4030
|
+
},
|
|
4031
|
+
async stats() {
|
|
4032
|
+
const entries = await loadAll();
|
|
4033
|
+
const byScope = { hot: 0, session: 0, local: 0, durable: 0 };
|
|
4034
|
+
const byType = {};
|
|
4035
|
+
let expired = 0;
|
|
4036
|
+
for (const entry of entries) {
|
|
4037
|
+
byScope[entry.scope] = (byScope[entry.scope] || 0) + 1;
|
|
4038
|
+
if (isExpired(entry)) expired++;
|
|
4039
|
+
byType[entry.type] = (byType[entry.type] || 0) + 1;
|
|
4040
|
+
}
|
|
4041
|
+
return { total: entries.length, byScope, byType, expired };
|
|
4042
|
+
},
|
|
4043
|
+
async forgetExpired() {
|
|
4044
|
+
const entries = await loadAll();
|
|
4045
|
+
let count = 0;
|
|
4046
|
+
for (const entry of entries) {
|
|
4047
|
+
if (isExpired(entry) && entry.status === "active") {
|
|
4048
|
+
entry.status = "obsolete";
|
|
4049
|
+
entry.updatedAt = now();
|
|
4050
|
+
entry.operation = "expire";
|
|
4051
|
+
await saveToScope(entry);
|
|
4052
|
+
await recordJournal(entry, "expire");
|
|
4053
|
+
count++;
|
|
4054
|
+
}
|
|
4055
|
+
}
|
|
4056
|
+
return count;
|
|
4057
|
+
},
|
|
4058
|
+
async clear() {
|
|
4059
|
+
const index = await getAllIndexes();
|
|
4060
|
+
for (const [id, info] of Object.entries(index)) {
|
|
4061
|
+
await removeFromScope(id, info.scope, info.superseded);
|
|
4062
|
+
}
|
|
4063
|
+
store.remove(MEMORY_INDEX_KEY);
|
|
4064
|
+
},
|
|
4065
|
+
async _getEntry(key) {
|
|
4066
|
+
const index = await getAllIndexes();
|
|
4067
|
+
const info = index[key];
|
|
4068
|
+
if (!info) {
|
|
4069
|
+
const val = getNestedPath(state2, key);
|
|
4070
|
+
if (val !== void 0) return reconstructEntry(key, val, "hot");
|
|
4071
|
+
return null;
|
|
4072
|
+
}
|
|
4073
|
+
return loadFromScope(key, info.scope, info.superseded);
|
|
4074
|
+
},
|
|
4075
|
+
async _loadAll() {
|
|
4076
|
+
return loadAll();
|
|
4077
|
+
},
|
|
4078
|
+
async _save(entry) {
|
|
4079
|
+
await saveToScope(entry);
|
|
4080
|
+
},
|
|
4081
|
+
/** Apply a field-level path patch to an existing memory entry. */
|
|
4082
|
+
async patch(key, patches) {
|
|
4083
|
+
const entry = await this._getEntry(key);
|
|
4084
|
+
if (!entry) return;
|
|
4085
|
+
let patched = false;
|
|
4086
|
+
for (const p of patches) {
|
|
4087
|
+
if (p.op === "set") {
|
|
4088
|
+
setNestedPath({ [entry.key]: entry.value }, p.path.replace(/^[^.]+\./, ""), p.value);
|
|
4089
|
+
patched = true;
|
|
4090
|
+
} else if (p.op === "delete") {
|
|
4091
|
+
deleteNestedPath({ [entry.key]: entry.value }, p.path.replace(/^[^.]+\./, ""));
|
|
4092
|
+
patched = true;
|
|
4093
|
+
}
|
|
4094
|
+
}
|
|
4095
|
+
if (!patched) return;
|
|
4096
|
+
const updated = {
|
|
4097
|
+
...entry,
|
|
4098
|
+
updatedAt: now(),
|
|
4099
|
+
lastConfirmedAt: now(),
|
|
4100
|
+
version: (entry.version ? entry.version : 0) + 1,
|
|
4101
|
+
sync: isSyncEnabled2() ? "pending" : void 0,
|
|
4102
|
+
hlc: hlc.serialize(hlc.tick()),
|
|
4103
|
+
patches,
|
|
4104
|
+
path: patches[0]?.path
|
|
4105
|
+
};
|
|
4106
|
+
await saveToScope(updated);
|
|
4107
|
+
await recordJournal(updated, "patch");
|
|
4108
|
+
dispatch.set("memorio:memory:patched", { key, patches });
|
|
4109
|
+
},
|
|
4110
|
+
/** Local operation journal (namespaced). No-op substrate when sqlite/idb unavailable. */
|
|
4111
|
+
journal: journal_default,
|
|
4112
|
+
/** Configure the optional cloud-sync layer (namespace + provider). Chainable. */
|
|
4113
|
+
configure(opts) {
|
|
4114
|
+
configure2(opts);
|
|
4115
|
+
return this;
|
|
4116
|
+
}
|
|
4117
|
+
};
|
|
93
4118
|
|
|
94
|
-
|
|
95
|
-
|
|
4119
|
+
// functions/inspect/index.ts
|
|
4120
|
+
init_esm_shims();
|
|
4121
|
+
var stateKeys = /* @__PURE__ */ __name(() => {
|
|
4122
|
+
const raw = deepRaw(state2);
|
|
4123
|
+
return Object.keys(raw).filter(
|
|
4124
|
+
(k) => !["list", "remove", "removeAll", "lock", "unlock"].includes(k)
|
|
4125
|
+
);
|
|
4126
|
+
}, "stateKeys");
|
|
4127
|
+
var pathExists = /* @__PURE__ */ __name((path2) => {
|
|
4128
|
+
if (!path2 || typeof path2 !== "string") return false;
|
|
4129
|
+
const parts = path2.replace(/^state\./, "").split(".");
|
|
4130
|
+
let current = state2;
|
|
4131
|
+
for (const part of parts) {
|
|
4132
|
+
if (current === null || current === void 0) {
|
|
4133
|
+
return false;
|
|
4134
|
+
}
|
|
4135
|
+
current = current[part];
|
|
4136
|
+
}
|
|
4137
|
+
return current !== void 0;
|
|
4138
|
+
}, "pathExists");
|
|
4139
|
+
var stateType = /* @__PURE__ */ __name((path2) => {
|
|
4140
|
+
const [exists, value] = _getValue(path2);
|
|
4141
|
+
if (!exists || value === void 0) return "undefined";
|
|
4142
|
+
return Array.isArray(value) ? "array" : typeof value;
|
|
4143
|
+
}, "stateType");
|
|
4144
|
+
var stateGet = /* @__PURE__ */ __name((path2) => {
|
|
4145
|
+
const [exists, value] = _getValue(path2);
|
|
4146
|
+
if (!exists || value === void 0) return void 0;
|
|
4147
|
+
return _clone2(value);
|
|
4148
|
+
}, "stateGet");
|
|
4149
|
+
var stateSchema = /* @__PURE__ */ __name(() => {
|
|
4150
|
+
const result = [];
|
|
4151
|
+
const _walk = /* @__PURE__ */ __name((obj, prefix) => {
|
|
4152
|
+
if (obj === null || typeof obj !== "object" || Array.isArray(obj)) {
|
|
4153
|
+
return;
|
|
4154
|
+
}
|
|
4155
|
+
const keys = Object.keys(obj).filter(
|
|
4156
|
+
(k) => !["list", "remove", "removeAll", "lock", "unlock"].includes(k)
|
|
4157
|
+
);
|
|
4158
|
+
for (const key of keys) {
|
|
4159
|
+
const newPath = prefix ? `${prefix}.${key}` : key;
|
|
4160
|
+
const value = obj[key];
|
|
4161
|
+
const defined = value !== void 0;
|
|
4162
|
+
const type = defined ? Array.isArray(value) ? "array" : typeof value : "undefined";
|
|
4163
|
+
result.push({ path: newPath, type, defined });
|
|
4164
|
+
if (defined && typeof value === "object" && !Array.isArray(value) && value.constructor?.name === "Object") {
|
|
4165
|
+
_walk(value, newPath);
|
|
4166
|
+
}
|
|
4167
|
+
}
|
|
4168
|
+
}, "_walk");
|
|
4169
|
+
_walk(deepRaw(state2), "");
|
|
4170
|
+
return result;
|
|
4171
|
+
}, "stateSchema");
|
|
4172
|
+
function _getValue(path2) {
|
|
4173
|
+
if (!path2 || typeof path2 !== "string") return [false, void 0];
|
|
4174
|
+
const parts = path2.replace(/^state\./, "").split(".");
|
|
4175
|
+
let current = state2;
|
|
4176
|
+
for (const part of parts) {
|
|
4177
|
+
if (current === null || current === void 0) {
|
|
4178
|
+
return [false, void 0];
|
|
4179
|
+
}
|
|
4180
|
+
current = current[part];
|
|
4181
|
+
}
|
|
4182
|
+
return [current !== void 0, current];
|
|
4183
|
+
}
|
|
4184
|
+
__name(_getValue, "_getValue");
|
|
4185
|
+
function _clone2(value) {
|
|
4186
|
+
if (value === null || typeof value !== "object") return value;
|
|
4187
|
+
const ctor = value.constructor?.name;
|
|
4188
|
+
if (ctor !== "Object" && ctor !== "Array") return value;
|
|
4189
|
+
try {
|
|
4190
|
+
return JSON.parse(JSON.stringify(value));
|
|
4191
|
+
} catch {
|
|
4192
|
+
return value;
|
|
4193
|
+
}
|
|
4194
|
+
}
|
|
4195
|
+
__name(_clone2, "_clone");
|
|
4196
|
+
|
|
4197
|
+
// core/global.ts
|
|
4198
|
+
if (!("memorio" in globalThis)) {
|
|
4199
|
+
Object.defineProperty(
|
|
4200
|
+
globalThis,
|
|
4201
|
+
"memorio",
|
|
4202
|
+
{
|
|
4203
|
+
value: {
|
|
4204
|
+
setProps: /* @__PURE__ */ __name(() => {
|
|
4205
|
+
}, "setProps"),
|
|
4206
|
+
obj: {},
|
|
4207
|
+
array: [],
|
|
4208
|
+
dispatch,
|
|
4209
|
+
message,
|
|
4210
|
+
setDescription: /* @__PURE__ */ __name(() => {
|
|
4211
|
+
}, "setDescription")
|
|
4212
|
+
},
|
|
4213
|
+
writable: false,
|
|
4214
|
+
configurable: true,
|
|
4215
|
+
enumerable: false
|
|
4216
|
+
}
|
|
4217
|
+
);
|
|
4218
|
+
Object.defineProperty(
|
|
4219
|
+
globalThis,
|
|
4220
|
+
"events",
|
|
4221
|
+
{
|
|
4222
|
+
value: {},
|
|
4223
|
+
writable: true,
|
|
4224
|
+
enumerable: false
|
|
4225
|
+
}
|
|
4226
|
+
);
|
|
4227
|
+
if (typeof globalThis.addEventListener === "function") {
|
|
4228
|
+
dispatch.listen("memorio:memory:cleanup", async () => memory.forgetExpired?.());
|
|
4229
|
+
}
|
|
4230
|
+
Object.defineProperty(
|
|
4231
|
+
memorio,
|
|
4232
|
+
"version",
|
|
4233
|
+
{
|
|
4234
|
+
writable: false,
|
|
4235
|
+
enumerable: false,
|
|
4236
|
+
value: package_default.version
|
|
4237
|
+
}
|
|
4238
|
+
);
|
|
4239
|
+
memorio.memory = memory;
|
|
4240
|
+
initializePlatform();
|
|
4241
|
+
memorio.isBrowser = isBrowser;
|
|
4242
|
+
memorio.isNode = isNode;
|
|
4243
|
+
memorio.isDeno = isDeno;
|
|
4244
|
+
memorio.isEdge = isEdge;
|
|
4245
|
+
memorio.getCapabilities = getCapabilities;
|
|
4246
|
+
memorio.createContext = createContext;
|
|
4247
|
+
memorio.listContexts = listContexts;
|
|
4248
|
+
memorio.deleteContext = deleteContext;
|
|
4249
|
+
memorio.isolate = (name) => createContext(name);
|
|
4250
|
+
Object.defineProperty(memorio, "setContext", { writable: false, enumerable: false, value: /* @__PURE__ */ __name((id) => setCurrentContext(id), "value") });
|
|
4251
|
+
Object.defineProperty(memorio, "getContext", { writable: false, enumerable: false, value: /* @__PURE__ */ __name(() => internal_default.currentContext, "value") });
|
|
4252
|
+
memorio.registerSchema = schema.register;
|
|
4253
|
+
memorio.validate = schema.validate;
|
|
4254
|
+
memorio.unregisterSchema = schema.unregister;
|
|
4255
|
+
memorio.listSchemas = schema.list;
|
|
4256
|
+
memorio.typed = typed;
|
|
4257
|
+
memorio.snapshot = snapshot;
|
|
4258
|
+
memorio.diff = diff;
|
|
4259
|
+
memorio.undo = undo;
|
|
4260
|
+
memorio.redo = redo;
|
|
4261
|
+
memorio.canUndo = canUndo;
|
|
4262
|
+
memorio.canRedo = canRedo;
|
|
4263
|
+
memorio.rollback = rollback;
|
|
4264
|
+
memorio.trace = trace;
|
|
4265
|
+
memorio.enableHistory = enableHistory;
|
|
4266
|
+
memorio.clearHistory = clearHistory2;
|
|
4267
|
+
memorio.clearRedo = clearRedo;
|
|
4268
|
+
Object.defineProperty(memorio, "dispatch", { value: dispatch, writable: true, enumerable: false, configurable: true });
|
|
4269
|
+
const isDev = DEV;
|
|
4270
|
+
memorio.env = {
|
|
4271
|
+
isDev,
|
|
4272
|
+
isProd: PROD
|
|
4273
|
+
};
|
|
4274
|
+
memorio.global = function() {
|
|
4275
|
+
const globalDefinitions = {
|
|
4276
|
+
state: state2,
|
|
4277
|
+
store,
|
|
4278
|
+
session,
|
|
4279
|
+
cache,
|
|
4280
|
+
idb,
|
|
4281
|
+
sqlite,
|
|
4282
|
+
observer,
|
|
4283
|
+
useObserver
|
|
4284
|
+
};
|
|
4285
|
+
for (const key of Object.keys(globalDefinitions)) {
|
|
4286
|
+
if (!(key in globalThis)) {
|
|
4287
|
+
Object.defineProperty(globalThis, key, {
|
|
4288
|
+
value: globalDefinitions[key],
|
|
4289
|
+
writable: true,
|
|
4290
|
+
enumerable: false,
|
|
4291
|
+
configurable: true
|
|
4292
|
+
});
|
|
4293
|
+
}
|
|
4294
|
+
}
|
|
4295
|
+
};
|
|
4296
|
+
if (isDev) {
|
|
4297
|
+
memorio.global();
|
|
4298
|
+
}
|
|
4299
|
+
if (DEV) {
|
|
4300
|
+
Object.defineProperty(
|
|
4301
|
+
memorio,
|
|
4302
|
+
"debug",
|
|
4303
|
+
{
|
|
4304
|
+
get: /* @__PURE__ */ __name(() => internal_default.debug, "get"),
|
|
4305
|
+
set: /* @__PURE__ */ __name((v) => {
|
|
4306
|
+
internal_default.debug = v;
|
|
4307
|
+
}, "set"),
|
|
4308
|
+
enumerable: false
|
|
4309
|
+
}
|
|
4310
|
+
);
|
|
4311
|
+
const caps = getCapabilities();
|
|
4312
|
+
Object.defineProperty(memorio, "_platform", { writable: false, enumerable: false, value: caps.platform });
|
|
4313
|
+
Object.defineProperty(memorio, "_capabilities", { writable: false, enumerable: false, value: caps });
|
|
4314
|
+
Object.defineProperty(memorio, "_sessionId", { writable: false, enumerable: false, value: generateSessionId() });
|
|
4315
|
+
memorio.logger = logger;
|
|
4316
|
+
if (!("$state" in globalThis)) Object.defineProperty(globalThis, "$state", { get: /* @__PURE__ */ __name(() => globalThis.state, "get"), configurable: true });
|
|
4317
|
+
if (!("$store" in globalThis)) Object.defineProperty(globalThis, "$store", { get: /* @__PURE__ */ __name(() => globalThis.store, "get"), configurable: true });
|
|
4318
|
+
if (!("$session" in globalThis)) Object.defineProperty(globalThis, "$session", { get: /* @__PURE__ */ __name(() => globalThis.session, "get"), configurable: true });
|
|
4319
|
+
if (!("$cache" in globalThis)) Object.defineProperty(globalThis, "$cache", { get: /* @__PURE__ */ __name(() => globalThis.cache, "get"), configurable: true });
|
|
4320
|
+
memorio.devtools = devtools;
|
|
4321
|
+
memorio.inspect = stateKeys;
|
|
4322
|
+
memorio.stateKeys = stateKeys;
|
|
4323
|
+
memorio.pathExists = pathExists;
|
|
4324
|
+
memorio.stateType = stateType;
|
|
4325
|
+
memorio.stateGet = stateGet;
|
|
4326
|
+
memorio.stateSchema = stateSchema;
|
|
4327
|
+
memorio.help = function() {
|
|
4328
|
+
console.debug(`
|
|
4329
|
+
\u{1F9E0} Memorio ${package_default.version} - Help
|
|
4330
|
+
|
|
4331
|
+
Core Modules (runtime):
|
|
4332
|
+
state - Reactive state management (DEV global)
|
|
96
4333
|
store - Persistent storage (localStorage/Map)
|
|
97
4334
|
session - Session storage (sessionStorage/Map)
|
|
98
4335
|
cache - In-memory cache
|
|
99
4336
|
idb - IndexedDB (browser only)
|
|
100
4337
|
sqlite - SQLite in browser (sql.js, optional)
|
|
101
4338
|
|
|
102
|
-
|
|
103
|
-
memorio.
|
|
4339
|
+
Platform Detection:
|
|
4340
|
+
memorio.isBrowser() - Browser environment
|
|
4341
|
+
memorio.isNode() - Node.js environment
|
|
4342
|
+
memorio.isDeno() - Deno environment
|
|
4343
|
+
memorio.isEdge() - Edge/Worker environment
|
|
4344
|
+
memorio.getCapabilities() - Full capabilities object
|
|
4345
|
+
|
|
4346
|
+
Context Management:
|
|
4347
|
+
memorio.isolate(name) - Create isolated context
|
|
4348
|
+
memorio.listContexts() - List all contexts
|
|
4349
|
+
memorio.deleteContext(id) - Delete a context
|
|
4350
|
+
|
|
4351
|
+
Schema Validation (runtime):
|
|
104
4352
|
memorio.registerSchema() - Register a validator for a state path
|
|
105
4353
|
memorio.validate() - Manually validate a value
|
|
106
4354
|
memorio.unregisterSchema() - Remove a registered schema
|
|
107
4355
|
memorio.listSchemas() - List all registered schema paths
|
|
4356
|
+
memorio.typed<T>() - Type-safe view of global state (compile-time only)
|
|
108
4357
|
|
|
109
|
-
History & Time Travel:
|
|
4358
|
+
History & Time Travel (runtime):
|
|
110
4359
|
memorio.snapshot() - Capture a deep snapshot of state
|
|
111
4360
|
memorio.diff(snap) - Diff snapshot against current state
|
|
112
4361
|
memorio.undo() / redo() - Undo / redo the last mutation
|
|
@@ -116,26 +4365,7 @@ History & Time Travel:
|
|
|
116
4365
|
memorio.enableHistory() - Enable/disable mutation tracking
|
|
117
4366
|
memorio.clearHistory() - Clear undo/redo stacks and trace log
|
|
118
4367
|
|
|
119
|
-
|
|
120
|
-
memorio.stateKeys() - List top-level state keys
|
|
121
|
-
memorio.pathExists(path) - Check if a state path exists
|
|
122
|
-
memorio.stateType(path) - Get runtime type of a state value
|
|
123
|
-
memorio.stateGet(path) - Get a deep-cloned value at a path
|
|
124
|
-
memorio.stateSchema() - Get a schema report of all state paths
|
|
125
|
-
|
|
126
|
-
Context Management:
|
|
127
|
-
memorio.isolate(name) - Create isolated context
|
|
128
|
-
memorio.listContexts() - List all contexts
|
|
129
|
-
memorio.deleteContext(id) - Delete a context
|
|
130
|
-
|
|
131
|
-
Platform Detection:
|
|
132
|
-
memorio.isBrowser() - Browser environment
|
|
133
|
-
memorio.isNode() - Node.js environment
|
|
134
|
-
memorio.isDeno() - Deno environment
|
|
135
|
-
memorio.isEdge() - Edge/Worker environment
|
|
136
|
-
memorio.getCapabilities() - Full capabilities object
|
|
137
|
-
|
|
138
|
-
DevTools:
|
|
4368
|
+
DevTools (development-only):
|
|
139
4369
|
memorio.devtools.inspect() - Inspect all modules
|
|
140
4370
|
memorio.devtools.stats() - Show statistics
|
|
141
4371
|
memorio.devtools.watch() - Watch a path
|
|
@@ -144,17 +4374,27 @@ DevTools:
|
|
|
144
4374
|
memorio.devtools.clear() - Clear specific module
|
|
145
4375
|
memorio.devtools.clearAll() - Clear all modules
|
|
146
4376
|
|
|
147
|
-
|
|
4377
|
+
Introspection (development-only):
|
|
4378
|
+
memorio.stateKeys() - List top-level state keys
|
|
4379
|
+
memorio.pathExists(path) - Check if a state path exists
|
|
4380
|
+
memorio.stateType(path) - Get runtime type of a state value
|
|
4381
|
+
memorio.stateGet(path) - Get a deep-cloned value at a path
|
|
4382
|
+
memorio.stateSchema() - Get a schema report of all state paths
|
|
4383
|
+
|
|
4384
|
+
Debug:
|
|
4385
|
+
memorio.debug = true - Enable debug output (DEV only)
|
|
4386
|
+
|
|
4387
|
+
Memory System (runtime):
|
|
148
4388
|
memorio.memory.remember(key, value, opts) - Store a memory with type, confidence, scope, TTL, tags
|
|
149
4389
|
memorio.memory.recall(key, opts) - Retrieve a memory with filtering
|
|
150
4390
|
memorio.memory.update(key, value, opts) - Update an existing memory
|
|
151
4391
|
memorio.memory.forget(key) - Delete a specific memory
|
|
152
4392
|
memorio.memory.context(opts) - Get ranked relevant memories (semantic context for AI)
|
|
153
4393
|
memorio.memory.stats() - Memory usage statistics
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
4394
|
+
memorio.memory.forgetExpired() - Remove all expired entries
|
|
4395
|
+
memorio.memory.clear() - Wipe all memories
|
|
4396
|
+
memorio.memory.configure({ sync }) - Optional cloud-sync provider + namespace
|
|
4397
|
+
memorio.memory.journal.pending() - Local op journal (SQLite/store)
|
|
158
4398
|
|
|
159
4399
|
Scopes:
|
|
160
4400
|
hot - In-memory reactive state (volatile, fastest)
|
|
@@ -169,8 +4409,24 @@ TTL options:
|
|
|
169
4409
|
Memory types:
|
|
170
4410
|
fact, preference, decision, task, context
|
|
171
4411
|
|
|
172
|
-
|
|
4412
|
+
Console shortcuts (DEV only):
|
|
173
4413
|
state, store, session, cache, idb, sqlite - direct access to modules
|
|
174
|
-
|
|
4414
|
+
$state, $store, $session, $cache - aliases for the above
|
|
4415
|
+
`);
|
|
4416
|
+
};
|
|
4417
|
+
}
|
|
4418
|
+
}
|
|
4419
|
+
|
|
4420
|
+
// index.ts
|
|
4421
|
+
var devtools2 = DEV ? devtools : void 0;
|
|
4422
|
+
var memorio2 = globalThis.memorio;
|
|
4423
|
+
var events = globalThis.events;
|
|
4424
|
+
var isolate = /* @__PURE__ */ __name((name) => createContext(name), "isolate");
|
|
4425
|
+
var help2 = globalThis.memorio?.help;
|
|
4426
|
+
var setContext = /* @__PURE__ */ __name((id) => internal_default.currentContext = id, "setContext");
|
|
4427
|
+
var getContext = /* @__PURE__ */ __name(() => internal_default.currentContext, "getContext");
|
|
4428
|
+
var index_default = memorio2;
|
|
175
4429
|
|
|
176
|
-
export {
|
|
4430
|
+
export { DEV, PROD, cache, canRedo, canUndo, clearHistory2 as clearHistory, clearRedo, createContext, index_default as default, deleteContext, devtools2 as devtools, diff, dispatch, enableHistory, events, fractional, getCapabilities, getContext, help2 as help, hlc, idb, internal_default as internal, isBrowser, isDeno, isEdge, isNode, isolate, listContexts, listSchemas, logger, memorio2 as memorio, memory, message, observer, propertyName, redo, registerSchema, rollback, schema, session, setContext, snapshot, sqlite, state2 as state, store, trace, typed, undo, unregisterSchema, useObserver, validate };
|
|
4431
|
+
//# sourceMappingURL=index.js.map
|
|
4432
|
+
//# sourceMappingURL=index.js.map
|