memorio 4.9.35 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/AGENTS.md +3 -3
  2. package/README.md +307 -359
  3. package/SECURITY.md +17 -1
  4. package/SUMMARY.md +59 -45
  5. package/adr/001-state-proxy-model.md +96 -0
  6. package/adr/002-observer-semantics.md +180 -0
  7. package/adr/003-deep-mutation-semantics.md +129 -0
  8. package/adr/004-array-mutation-semantics.md +128 -0
  9. package/adr/005-scheduler-contract.md +149 -0
  10. package/adr/006-context-isolation.md +92 -0
  11. package/adr/007-mutation-records.md +118 -0
  12. package/adr/008-transactions.md +106 -0
  13. package/adr/009-history-model.md +110 -0
  14. package/adr/README.md +46 -0
  15. package/adr/template.md +49 -0
  16. package/examples/basic.ts +115 -115
  17. package/examples/browser-vanilla.html +358 -358
  18. package/examples/cache.ts +72 -72
  19. package/examples/cross-platform-guards.ts +57 -57
  20. package/examples/history.ts +104 -0
  21. package/examples/idb.ts +109 -109
  22. package/examples/multi-tenant-context.ts +44 -44
  23. package/examples/node-server.ts +308 -308
  24. package/examples/observer.ts +60 -60
  25. package/examples/platform.ts +115 -115
  26. package/examples/react-app.tsx +362 -362
  27. package/examples/react-observer.tsx +63 -63
  28. package/examples/semantic-memory.ts +60 -60
  29. package/examples/session-advanced.ts +91 -91
  30. package/examples/sqlite-batched-writes.ts +57 -57
  31. package/examples/state-advanced.ts +89 -89
  32. package/examples/store-advanced.ts +117 -117
  33. package/examples/sync.ts +90 -0
  34. package/examples/typed-and-schema.ts +102 -100
  35. package/examples/useObserver.tsx +140 -141
  36. package/global.cjs +4594 -0
  37. package/global.d.ts +8 -0
  38. package/global.js +4532 -0
  39. package/index.cjs +700 -678
  40. package/index.d.ts +1 -0
  41. package/index.js +680 -677
  42. package/llms.txt +72 -4
  43. package/markdown/AUDIT-REPORT.md +135 -0
  44. package/markdown/CACHE.md +100 -0
  45. package/markdown/CHANGELOG.md +243 -0
  46. package/markdown/DEVTOOLS.md +129 -0
  47. package/markdown/DISPATCH.md +177 -0
  48. package/markdown/HISTORY.md +199 -0
  49. package/markdown/IDB.md +178 -0
  50. package/markdown/IMPORT.md +153 -0
  51. package/markdown/INSPECT.md +123 -0
  52. package/markdown/LOGGER.md +154 -0
  53. package/markdown/MEMORY-ATTACHMENT.md +96 -0
  54. package/markdown/MEMORY.md +162 -0
  55. package/markdown/OBSERVER.md +209 -0
  56. package/markdown/PLATFORM.md +271 -0
  57. package/markdown/PROJECT.md +311 -0
  58. package/markdown/SCHEMA.md +176 -0
  59. package/markdown/SECURITY.md +330 -0
  60. package/markdown/SESSION.md +165 -0
  61. package/markdown/SQLITE.md +190 -0
  62. package/markdown/STATE.md +160 -0
  63. package/markdown/STORE.md +171 -0
  64. package/markdown/SYNC.md +319 -0
  65. package/markdown/TYPED.md +165 -0
  66. package/markdown/USEOBSERVER.md +257 -0
  67. package/modules/redux.cjs +320 -167
  68. package/modules/redux.cjs.map +1 -1
  69. package/modules/redux.js +320 -167
  70. package/modules/redux.js.map +1 -1
  71. package/package.json +13 -3
  72. package/types/env.d.ts +19 -9
  73. package/types/exports.d.ts +20 -0
  74. package/types/history.d.ts +13 -1
  75. package/types/memorio.d.ts +17 -5
  76. package/types/mutation.d.ts +75 -0
@@ -0,0 +1,209 @@
1
+ > **Status:** Published
2
+ > **Date:** 2026-09-12
3
+ > **Deciders:** Memorio 5.x Core Team
4
+ > **Scope**: API Reference
5
+ > **Standard**: Memorio API Specification v5
6
+ >
7
+ ---
8
+ # Observer - Memorio
9
+
10
+ Observer lets you react to state changes. When a state key changes, your callback function runs.
11
+
12
+ ## Installation
13
+
14
+ ```bash
15
+ npm install memorio
16
+ ```
17
+
18
+ ```javascript
19
+ import { observer } from 'memorio';
20
+ ```
21
+
22
+ > **Global API**: `import 'memorio/global'` is the opt-in entrypoint that also exposes `state`, `store`, `session`, `cache`, `idb`, `sqlite`, `observer`, and `useObserver` on `globalThis`.
23
+
24
+ ---
25
+
26
+ ## Quick Examples
27
+
28
+ ### Example 1: Basic Usage
29
+
30
+ ```javascript
31
+ observer('state.counter', (newValue) => {
32
+ console.debug('Counter is now:', newValue);
33
+ });
34
+
35
+ state.counter = 1;
36
+ // Output: "Counter is now: 1"
37
+
38
+ state.counter = 5;
39
+ // Output: "Counter is now: 5"
40
+ ```
41
+
42
+ ### Example 2: Intermediate
43
+
44
+ ```javascript
45
+ // Observer with old value
46
+ observer('state.user', (newValue, oldValue) => {
47
+ console.debug(`User changed from ${oldValue?.name} to ${newValue?.name}`);
48
+ });
49
+
50
+ state.user = { name: 'Mario' };
51
+ // Output: "User changed from undefined to Mario"
52
+
53
+ state.user = { name: 'Luigi' };
54
+ // Output: "User changed from Mario to Luigi"
55
+ ```
56
+
57
+ ### Example 3: Advanced
58
+
59
+ ```javascript
60
+ // Multiple callbacks for same path
61
+ observer('state.data', [handler1, handler2]);
62
+
63
+ // List all observers
64
+ console.debug(observer.list);
65
+ // Output: [{ name: 'state.data', id: '...' }, ...]
66
+
67
+ // Remove specific observer
68
+ observer.remove('state.data');
69
+
70
+ // Remove all observers
71
+ observer.removeAll();
72
+
73
+ // Check if observer exists
74
+ if (observer.has('state.counter')) {
75
+ console.debug('Observer exists for counter');
76
+ }
77
+ ```
78
+
79
+ ---
80
+
81
+ ## Direct Values (Vanilla JS)
82
+
83
+ Observer supports direct state values, not just string paths:
84
+
85
+ ```javascript
86
+ // Direct value - no string needed!
87
+ observer(state.counter, (newValue) => {
88
+ console.debug('Counter:', newValue);
89
+ });
90
+
91
+ // Works with objects too
92
+ observer(state.user, (newValue) => {
93
+ console.debug('User:', newValue?.name);
94
+ });
95
+
96
+ // Multiple callbacks as array
97
+ observer('state.data', [cb1, cb2, cb3]);
98
+ ```
99
+
100
+ ---
101
+
102
+ ## API Reference
103
+
104
+ ### observer(path, callback, option)
105
+
106
+ | Parameter | Type | Description |
107
+ |-----------|------|-------------|
108
+ | `path` | `string \| object` | State path (e.g., `'state.counter'`) or direct state value |
109
+ | `callback` | `function \| array` | Function(s) called on change. Can be a single function or array of functions |
110
+ | `option` | `boolean` | Listen continuously (default: `true`) |
111
+
112
+ ### Callback Parameters
113
+
114
+ ```javascript
115
+ observer('state.key', (newValue, oldValue) => {
116
+ // newValue: the new value
117
+ // oldValue: the previous value
118
+ });
119
+ ```
120
+
121
+ ### Properties
122
+
123
+ | Property | Type | Description |
124
+ |----------|------|-------------|
125
+ | `observer.list` | `Array` | Get all active observers |
126
+
127
+ ### Methods
128
+
129
+ | Method | Parameters | Description |
130
+ |--------|------------|-------------|
131
+ | `observer.remove(name)` | `string` | Remove observer for specific path |
132
+ | `observer.removeAll()` | none | Remove all observers |
133
+ | `observer.has(name)` | `string` | Check if observer exists for path (returns boolean) |
134
+
135
+ ---
136
+
137
+ ## React Integration
138
+
139
+ ### With useState
140
+
141
+ ```javascript
142
+ const [count, setCount] = useState(0);
143
+
144
+ observer('state.counter', () => {
145
+ setCount(state.counter);
146
+ });
147
+ ```
148
+
149
+ ### With useEffect
150
+
151
+ ```javascript
152
+ useEffect(() => {
153
+ const handleChange = (newVal) => {
154
+ console.debug('Changed:', newVal);
155
+ };
156
+
157
+ observer('state.data', handleChange);
158
+
159
+ // Cleanup
160
+ return () => observer.remove('state.data');
161
+ }, []);
162
+ ```
163
+
164
+ ---
165
+
166
+ ## How It Works
167
+
168
+ Observer subscribes to state changes via the Proxy's set trap. When `state.key = value` is called:
169
+ 1. The Proxy intercepts the set
170
+ 2. Fires all callbacks registered for that path
171
+ 3. Callbacks receive newValue and oldValue
172
+
173
+ ---
174
+
175
+ ## Best Practices
176
+
177
+ 1. Clean up observers in React `useEffect` return
178
+ 2. Use specific paths: `'state.user.name'` not `'state'`
179
+ 3. Remove observers when components unmount
180
+ 4. Use `observer.removeAll()` on page navigation
181
+
182
+ ---
183
+
184
+ ## Common Patterns
185
+
186
+ ### Form Validation
187
+
188
+ ```javascript
189
+ observer('state.form.email', (email) => {
190
+ const isValid = email.includes('@');
191
+ state.form.isValid = isValid;
192
+ });
193
+ ```
194
+
195
+ ### Analytics
196
+
197
+ ```javascript
198
+ observer('state.page', (page) => {
199
+ analytics.track('page_view', { page });
200
+ });
201
+ ```
202
+
203
+ ### Auto-save
204
+
205
+ ```javascript
206
+ observer('state.draft', (content) => {
207
+ store.set('autosave', content);
208
+ });
209
+ ```
@@ -0,0 +1,271 @@
1
+ # Platform & Context Isolation - Memorio
2
+
3
+ > ℹ️ **New in v2.7.0, expanded in v3.0.2**: Context isolation system for multi-tenant server-side applications
4
+
5
+ Memorio automatically detects the runtime environment and adapts its behavior accordingly. This document explains platform compatibility, session isolation, and the new context system.
6
+
7
+ ---
8
+
9
+ ## Quick Reference: Client vs Server
10
+
11
+ ### Which Module to Use?
12
+
13
+ | Scenario | Recommended Module | Persistence |
14
+ |----------|-------------------|-------------|
15
+ | UI State (React/components) | `state` | Memory |
16
+ | Temporary computed data | `cache` | Memory |
17
+ | User preferences | `store` | Browser localStorage |
18
+ | Auth tokens | `session` | Browser sessionStorage |
19
+ | Large offline data | `idb` | IndexedDB |
20
+ | Server request isolation | `memorio.createContext()` | Memory |
21
+
22
+ ### Module Availability
23
+
24
+ | Module | Browser | Node.js | Deno | Edge |
25
+ |--------|--------|---------|------|------|
26
+ | `state` | ✅ | ✅ | ✅ | ✅ |
27
+ | `cache` | ✅ | ✅ | ✅ | ✅ |
28
+ | `store` | ✅ (localStorage) | ⚠️ (memory) | ⚠️ (memory) | ✅ |
29
+ | `session` | ✅ (sessionStorage) | ⚠️ (memory) | ⚠️ (memory) | ✅ |
30
+ | `idb` | ✅ | ❌ | ❌ | ⚠️ |
31
+ | `useObserver` | ✅ | ⚠️ | ⚠️ | ✅ |
32
+ | `devtools` | ✅ | ❌ | ❌ | ❌ |
33
+
34
+ ---
35
+
36
+ ## Platform Detection
37
+
38
+ Memorio automatically detects the environment on import:
39
+
40
+ ```javascript
41
+ import { memorio, store } from 'memorio';
42
+
43
+ // Check current platform
44
+ console.debug(memorio.getCapabilities().platform); // 'browser' | 'node' | 'deno' | 'edge'
45
+ console.debug(store.isPersistent); // true if using real localStorage
46
+ ```
47
+
48
+ ### Available Platform APIs
49
+
50
+ ```javascript
51
+ // Check platform
52
+ memorio.isBrowser() // true in browser
53
+ memorio.isNode() // true in Node.js
54
+ memorio.isDeno() // true in Deno
55
+ memorio.isEdge() // true in Edge Workers
56
+
57
+ // Get capabilities
58
+ const caps = memorio.getCapabilities();
59
+ // caps.platform, caps.hasSessionStorage, caps.hasLocalStorage, etc.
60
+ ```
61
+
62
+ ---
63
+
64
+ ## Platform Compatibility Matrix
65
+
66
+ | Feature | Browser | Node.js | Deno | Edge Workers |
67
+ |---------|---------|---------|------|--------------|
68
+ | `state` | ✅ | ✅ | ✅ | ✅ |
69
+ | `observer` | ✅ | ✅ | ✅ | ✅ |
70
+ | `useObserver` | ✅ | ⚠️ React only | ⚠️ React only | ✅ |
71
+ | `cache` | ✅ | ✅ | ✅ | ✅ |
72
+ | `store` | ✅ (localStorage) | ⚠️ (memory) | ⚠️ (memory) | ✅ (localStorage) |
73
+ | `session` | ✅ (sessionStorage) | ⚠️ (memory) | ⚠️ (memory) | ✅ (sessionStorage) |
74
+ | `idb` | ✅ | ❌ | ❌ | ⚠️ |
75
+
76
+ - ✅ Full support
77
+ - ⚠️ Partial support (fallback to in-memory)
78
+ - ❌ Not available
79
+
80
+ ---
81
+
82
+ ## Client vs Server Usage
83
+
84
+ ### 🖥️ Client-Side (Browser)
85
+
86
+ All features work with real browser storage:
87
+
88
+ ```javascript
89
+ import { store, session, idb } from 'memorio'
90
+
91
+ // Store - persistent localStorage
92
+ store.set('preferences', { theme: 'dark' });
93
+ store.isPersistent; // true
94
+
95
+ // Session - temporary sessionStorage
96
+ session.set('token', 'jwt-token');
97
+ session.isPersistent; // true (survives refresh)
98
+
99
+ // IDB - large data storage
100
+ idb.db.create('myApp');
101
+ ```
102
+
103
+ ### 🖥️ Server-Side (Node.js/Deno)
104
+
105
+ Use `state` and `cache` for in-memory data. Store/session fall back to memory:
106
+
107
+ ```javascript
108
+ import { state, store, session, cache } from 'memorio'
109
+
110
+ // State - in-memory global state
111
+ state.user = { name: 'Server User' };
112
+
113
+ // Cache - in-memory temporary cache
114
+ cache.set('apiResponse', data);
115
+
116
+ // Store - in-memory fallback (not persistent)
117
+ store.set('temp', data);
118
+ store.isPersistent; // false - data lost on restart
119
+
120
+ // Session - in-memory fallback
121
+ session.set('requestData', data);
122
+ session.isPersistent; // false - data lost on restart
123
+ ```
124
+
125
+ ---
126
+
127
+ ## Session Isolation
128
+
129
+ Each instance/session gets unique storage keys to prevent conflicts:
130
+
131
+ ```javascript
132
+ // Without context: "memorio_store_[sessionId]_key"
133
+ // With context: "[contextName]-key"
134
+ ```
135
+
136
+ This ensures:
137
+ - Multiple browser tabs don't share session data
138
+ - Server-side requests are isolated
139
+
140
+ ---
141
+
142
+ ## Context Isolation (Server-Side Multi-Tenancy)
143
+
144
+ > ⚠️ **Server-Side Only**: This feature is designed for multi-tenant server environments (Node.js, Deno). Not needed for client-side applications.
145
+
146
+ For server-side applications handling multiple tenants (e.g., different users/requests), use **contexts** to isolate data:
147
+
148
+ ### Creating a Context
149
+
150
+ ```javascript
151
+ import { memorio, state } from 'memorio'
152
+
153
+ // Create isolated context for a user/session
154
+ const ctx = memorio.isolate('user-123');
155
+
156
+ // Keys in store/session are prefixed with context name
157
+ // store: "user-123-key"
158
+ // session: "user-123-key"
159
+
160
+ // Use context's isolated storage
161
+ ctx.state.user = { name: 'Isolated User' };
162
+ ctx.store.set('settings', { theme: 'dark' });
163
+ ctx.session.set('token', 'abc123');
164
+ ctx.cache.set('temp', data);
165
+
166
+ // Context is completely isolated from global state
167
+ console.debug(state.user); // undefined - global state is separate
168
+ ```
169
+
170
+ ### Managing Contexts
171
+
172
+ ```javascript
173
+ // List all contexts
174
+ const contexts = memorio.listContexts();
175
+ console.debug(contexts); // ['user-123', 'user-456', ...]
176
+
177
+ // Delete a context (cleanup)
178
+ memorio.deleteContext('user-123');
179
+ ```
180
+
181
+ > **Note**: `memorio.isolate('name')` is a shorthand alias for creating isolated contexts.
182
+
183
+ ### Context Use Cases
184
+
185
+ #### 1. Per-Request Isolation (Express/Fastify)
186
+
187
+ ```javascript
188
+ // Middleware to isolate each request
189
+ app.use((req, res, next) => {
190
+ const ctx = memorio.createContext(`req-${req.id}`);
191
+ req.memorioContext = ctx;
192
+ next();
193
+ });
194
+
195
+ // In route handler
196
+ app.get('/user', (req, res) => {
197
+ const ctx = req.memorioContext;
198
+ ctx.state.user = getUserData();
199
+ // Each request has isolated state
200
+ });
201
+ ```
202
+
203
+ #### 2. Multi-Tenant SaaS
204
+
205
+ ```javascript
206
+ // Each tenant gets isolated storage
207
+ function handleTenant(tenantId) {
208
+ const ctx = memorio.createContext(tenantId);
209
+
210
+ ctx.state.config = getTenantConfig(tenantId);
211
+ ctx.store.set('data', tenantData);
212
+
213
+ return ctx;
214
+ }
215
+ ```
216
+
217
+ ---
218
+
219
+ ## Best Practices
220
+
221
+ ### Client-Side (Browser)
222
+
223
+ 1. Use `store` for persistent data (preferences, user settings)
224
+ 2. Use `session` for temporary data (auth tokens)
225
+ 3. Use `cache` for computed values
226
+ 4. Use `state` for reactive UI state
227
+
228
+ ### Server-Side (Node.js/Deno)
229
+
230
+ 1. Use `memorio.createContext()` for each request/tenant
231
+ 2. Don't use global `state`/`store`/`session` across requests
232
+ 3. Use `cache` for request-scoped caching
233
+ 4. Check `store.isPersistent` / `session.isPersistent` if persistence matters
234
+
235
+ ### Edge Workers
236
+
237
+ Same as browser - localStorage and sessionStorage are available.
238
+
239
+ ---
240
+
241
+ ## API Reference
242
+
243
+ ### Global Functions
244
+
245
+ | Function | Returns | Description |
246
+ |----------|---------|-------------|
247
+ | `memorio.isBrowser()` | `boolean` | Check if running in browser |
248
+ | `memorio.isNode()` | `boolean` | Check if running in Node.js |
249
+ | `memorio.isDeno()` | `boolean` | Check if running in Deno |
250
+ | `memorio.isEdge()` | `boolean` | Check if running in Edge |
251
+ | `memorio.getCapabilities()` | `object` | Get platform capabilities |
252
+
253
+ ### Context Management
254
+
255
+ | Function | Returns | Description |
256
+ |----------|---------|-------------|
257
+ | `memorio.isolate(name?)` | `Context` | Create isolated context |
258
+ | `memorio.listContexts()` | `string[]` | List all context IDs |
259
+ | `memorio.deleteContext(id)` | `boolean` | Delete a context |
260
+
261
+ ### Properties
262
+
263
+ | Property | Type | Description |
264
+ |----------|------|-------------|
265
+ | `memorio.version` | `string` | Memorio version |
266
+ | `memorio.getCapabilities().platform` | `string` | Current platform |
267
+ | `memorio.isBrowser()` / `isNode()` / `isDeno()` / `isEdge()` | `boolean` | Platform checks |
268
+ | `memorio._sessionId` | `string` | Unique session identifier |
269
+
270
+ > **Classic `import`**: context APIs are also named exports.
271
+ > `import { createContext, listContexts, deleteContext, isolate } from 'memorio'`.