memorio 4.8.0 → 4.9.5
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 +84 -152
- package/index.js +44 -107
- package/llms.txt +1 -1
- package/package.json +1 -1
- 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/markdown/SECURITY.md
DELETED
|
@@ -1,323 +0,0 @@
|
|
|
1
|
-
# Memorio Security Documentation
|
|
2
|
-
|
|
3
|
-
> Last Updated: v3.0.2
|
|
4
|
-
|
|
5
|
-
This document describes the security measures implemented in Memorio to protect against common vulnerabilities and ensure safe operation across different platforms.
|
|
6
|
-
|
|
7
|
-
---
|
|
8
|
-
|
|
9
|
-
## Security Overview
|
|
10
|
-
|
|
11
|
-
Memorio implements multiple layers of security to protect user data and prevent common attack vectors:
|
|
12
|
-
|
|
13
|
-
| Security Feature | Status | Description |
|
|
14
|
-
|------------------|--------|-------------|
|
|
15
|
-
| Cryptographically Secure IDs | ✅ Enabled | Session/Context IDs use crypto.randomUUID |
|
|
16
|
-
| Input Validation | ✅ Enabled | Key length limits + character filtering |
|
|
17
|
-
| Session Isolation | ✅ Enabled | Unique namespaces per session |
|
|
18
|
-
| Context Isolation | ✅ Enabled | Separate storage per tenant |
|
|
19
|
-
| No Code Injection | ✅ Enabled | No eval() or dynamic code execution |
|
|
20
|
-
| XSS Prevention | ✅ Enabled | No innerHTML or document.write |
|
|
21
|
-
|
|
22
|
-
---
|
|
23
|
-
|
|
24
|
-
## 1. Cryptographically Secure Random Generation
|
|
25
|
-
|
|
26
|
-
### Implementation
|
|
27
|
-
|
|
28
|
-
Session and context IDs are generated using cryptographically secure random values:
|
|
29
|
-
|
|
30
|
-
```typescript
|
|
31
|
-
// config/platform.ts
|
|
32
|
-
function generateSessionId(): string {
|
|
33
|
-
// Priority 1: crypto.randomUUID (most secure)
|
|
34
|
-
if (typeof crypto !== 'undefined' && crypto.randomUUID) {
|
|
35
|
-
return crypto.randomUUID()
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
// Priority 2: crypto.getRandomValues (secure fallback)
|
|
39
|
-
if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
|
|
40
|
-
const array = new Uint8Array(16)
|
|
41
|
-
crypto.getRandomValues(array)
|
|
42
|
-
return Array.from(array, b => b.toString(16).padStart(2, '0')).join('')
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
// Priority 3: Math.random (last resort - less secure)
|
|
46
|
-
return `session_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`
|
|
47
|
-
}
|
|
48
|
-
```
|
|
49
|
-
|
|
50
|
-
### Random Source Priority
|
|
51
|
-
|
|
52
|
-
| Priority | Method | Security Level |
|
|
53
|
-
|----------|--------|----------------|
|
|
54
|
-
| 1 | `crypto.randomUUID()` | 🔒 FIPS 140-2 compliant |
|
|
55
|
-
| 2 | `crypto.getRandomValues()` | 🔒 Cryptographically secure |
|
|
56
|
-
| 3 | `Math.random()` | ⚠️ Not for security purposes |
|
|
57
|
-
|
|
58
|
-
---
|
|
59
|
-
|
|
60
|
-
## 2. Input Validation & Key Sanitization
|
|
61
|
-
|
|
62
|
-
All storage keys are validated before use to prevent injection attacks:
|
|
63
|
-
|
|
64
|
-
### Validation Rules
|
|
65
|
-
|
|
66
|
-
| Rule | Limit | Action on Violation |
|
|
67
|
-
|------|-------|---------------------|
|
|
68
|
-
| Key Length | Max 512 chars | Reject with debug message |
|
|
69
|
-
| Character Set | `[a-zA-Z0-9_.-]` | Reject with debug message |
|
|
70
|
-
| Type Check | Must be string | Return empty/null |
|
|
71
|
-
|
|
72
|
-
### Implementation
|
|
73
|
-
|
|
74
|
-
```typescript
|
|
75
|
-
function _prefixKey(name: string): string {
|
|
76
|
-
// Validate key
|
|
77
|
-
if (!name || typeof name !== 'string') return ''
|
|
78
|
-
if (name.length > 512) {
|
|
79
|
-
console.debug('Key too long (max 512 characters)')
|
|
80
|
-
return ''
|
|
81
|
-
}
|
|
82
|
-
// Sanitize: only allow alphanumeric, underscore, dash, dot
|
|
83
|
-
if (!/^[a-zA-Z0-9_.-]+$/.test(name)) {
|
|
84
|
-
console.debug('Key contains invalid characters')
|
|
85
|
-
return ''
|
|
86
|
-
}
|
|
87
|
-
return _sessionPrefix + name
|
|
88
|
-
}
|
|
89
|
-
```
|
|
90
|
-
|
|
91
|
-
### Allowed Characters Table
|
|
92
|
-
|
|
93
|
-
| Character Type | Allowed | Example |
|
|
94
|
-
|----------------|---------|---------|
|
|
95
|
-
| Lowercase | ✅ | `username`, `user_data` |
|
|
96
|
-
| Uppercase | ✅ | `USER`, `UserName` |
|
|
97
|
-
| Numbers | ✅ | `user123`, `data_2024` |
|
|
98
|
-
| Underscore | ✅ | `user_name`, `_private` |
|
|
99
|
-
| Dash | ✅ | `user-id`, `data-set` |
|
|
100
|
-
| Dot | ✅ | `user.profile`, `data.json` |
|
|
101
|
-
| Special Chars | ❌ | `<script>`, `../../../etc` |
|
|
102
|
-
|
|
103
|
-
---
|
|
104
|
-
|
|
105
|
-
## 3. Session Isolation
|
|
106
|
-
|
|
107
|
-
Each session gets a unique namespace to prevent data leakage:
|
|
108
|
-
|
|
109
|
-
### Isolation Mechanism
|
|
110
|
-
|
|
111
|
-
| Component | Without Context | With Context |
|
|
112
|
-
|-----------|-----------------|--------------|
|
|
113
|
-
| Session ID | `crypto.randomUUID()` | Context name |
|
|
114
|
-
| Store Keys | `memorio_store_[uuid]-keyname` | `[contextName]-keyname` |
|
|
115
|
-
| Session Keys | `memorio_session_[uuid]-keyname` | `[contextName]-keyname` |
|
|
116
|
-
| State | In-memory (per-instance) | In-memory (per-instance) |
|
|
117
|
-
|
|
118
|
-
### Key Prefix Format
|
|
119
|
-
|
|
120
|
-
```
|
|
121
|
-
// Without context:
|
|
122
|
-
memorio_store-[session-uuid]-username
|
|
123
|
-
memorio_session-[session-uuid]-auth-token
|
|
124
|
-
|
|
125
|
-
// With context (createContext('user-123')):
|
|
126
|
-
user-123-username
|
|
127
|
-
user-123-auth-token
|
|
128
|
-
```
|
|
129
|
-
|
|
130
|
-
### Cross-Session Protection
|
|
131
|
-
|
|
132
|
-
| Scenario | Protection |
|
|
133
|
-
|----------|------------|
|
|
134
|
-
| Browser Tabs | Each tab has unique session ID |
|
|
135
|
-
| Server Requests | Each request can use separate context |
|
|
136
|
-
| Multi-Tenant | `memorio.createContext()` isolates tenants |
|
|
137
|
-
|
|
138
|
-
---
|
|
139
|
-
|
|
140
|
-
## 4. Context Isolation (Multi-Tenant)
|
|
141
|
-
|
|
142
|
-
For server-side applications, contexts provide complete data isolation:
|
|
143
|
-
|
|
144
|
-
```typescript
|
|
145
|
-
// Create isolated context per tenant
|
|
146
|
-
const tenantA = memorio.isolate('tenant-A')
|
|
147
|
-
const tenantB = memorio.isolate('tenant-B')
|
|
148
|
-
|
|
149
|
-
// Each context has completely separate storage
|
|
150
|
-
tenantA.state.secret = 'Tenant A data' // Isolated
|
|
151
|
-
tenantB.state.secret = 'Tenant B data' // Isolated
|
|
152
|
-
```
|
|
153
|
-
|
|
154
|
-
### Context Security
|
|
155
|
-
|
|
156
|
-
| Feature | Description |
|
|
157
|
-
|---------|-------------|
|
|
158
|
-
| Unique ID | Each context gets unique identifier |
|
|
159
|
-
| Separate Storage | State, Store, Session, Cache all isolated |
|
|
160
|
-
| No Cross-Context Access | Impossible to read other contexts |
|
|
161
|
-
| Cleanup | `deleteContext()` removes all data |
|
|
162
|
-
|
|
163
|
-
---
|
|
164
|
-
|
|
165
|
-
## 5. Data Serialization Security
|
|
166
|
-
|
|
167
|
-
### Safe Operations
|
|
168
|
-
|
|
169
|
-
| Operation | Security Measure |
|
|
170
|
-
|-----------|-----------------|
|
|
171
|
-
| `store.set()` | JSON.stringify only allowed types |
|
|
172
|
-
| `store.get()` | JSON.parse with try-catch |
|
|
173
|
-
| Functions | Blocked with debug message |
|
|
174
|
-
| Objects | Deep-cloned on read |
|
|
175
|
-
|
|
176
|
-
### Blocked Types
|
|
177
|
-
|
|
178
|
-
```typescript
|
|
179
|
-
// These are blocked and logged:
|
|
180
|
-
store.set('myFunc', () => {}) // "It's not secure to store functions."
|
|
181
|
-
store.set('mySymbol', Symbol('test')) // Would fail serialization
|
|
182
|
-
```
|
|
183
|
-
|
|
184
|
-
---
|
|
185
|
-
|
|
186
|
-
## 6. Platform-Specific Security
|
|
187
|
-
|
|
188
|
-
### Browser Environment
|
|
189
|
-
|
|
190
|
-
| Feature | Security |
|
|
191
|
-
|---------|----------|
|
|
192
|
-
| localStorage | Same-origin policy applies |
|
|
193
|
-
| sessionStorage | Tab isolation |
|
|
194
|
-
| IndexedDB | Same-origin policy |
|
|
195
|
-
| HTTPS Required | Recommended for production |
|
|
196
|
-
|
|
197
|
-
### Server Environment (Node.js/Deno)
|
|
198
|
-
|
|
199
|
-
| Feature | Security |
|
|
200
|
-
|---------|----------|
|
|
201
|
-
| In-Memory Storage | Process-scoped only |
|
|
202
|
-
| Context Isolation | Per-request isolation recommended |
|
|
203
|
-
| No Persistence | Data lost on restart (by design) |
|
|
204
|
-
|
|
205
|
-
---
|
|
206
|
-
|
|
207
|
-
## 7. Security Best Practices
|
|
208
|
-
|
|
209
|
-
### For Developers
|
|
210
|
-
|
|
211
|
-
1. **Use Contexts in Server Apps**
|
|
212
|
-
```typescript
|
|
213
|
-
// Express middleware
|
|
214
|
-
app.use((req, res, next) => {
|
|
215
|
-
req.memorio = memorio.createContext(`req-${req.id}`)
|
|
216
|
-
next()
|
|
217
|
-
})
|
|
218
|
-
```
|
|
219
|
-
|
|
220
|
-
2. **Validate Keys**
|
|
221
|
-
```typescript
|
|
222
|
-
// Don't use user input directly as keys
|
|
223
|
-
const safeKey = sanitize(userInput) // Input validation
|
|
224
|
-
store.set(safeKey, value)
|
|
225
|
-
```
|
|
226
|
-
|
|
227
|
-
3. **Check Persistence**
|
|
228
|
-
```typescript
|
|
229
|
-
if (!store.isPersistent) {
|
|
230
|
-
console.warn('Data not persisted!')
|
|
231
|
-
}
|
|
232
|
-
```
|
|
233
|
-
|
|
234
|
-
4. **Clear Sensitive Data**
|
|
235
|
-
```typescript
|
|
236
|
-
// On logout
|
|
237
|
-
session.removeAll()
|
|
238
|
-
state.removeAll()
|
|
239
|
-
```
|
|
240
|
-
|
|
241
|
-
### For Security Audits
|
|
242
|
-
|
|
243
|
-
| Check | Location |
|
|
244
|
-
|-------|----------|
|
|
245
|
-
| Random Generation | `config/platform.ts:44` |
|
|
246
|
-
| Key Validation | `functions/store/index.ts:31` |
|
|
247
|
-
| Session Isolation | `functions/session/index.ts:27` |
|
|
248
|
-
| Context System | `config/platform.ts:301` |
|
|
249
|
-
|
|
250
|
-
---
|
|
251
|
-
|
|
252
|
-
## 8. Vulnerability Prevention
|
|
253
|
-
|
|
254
|
-
### Prevention Matrix
|
|
255
|
-
|
|
256
|
-
| Vulnerability | Prevention | Status |
|
|
257
|
-
|---------------|------------|--------|
|
|
258
|
-
| XSS | No innerHTML/document.write | ✅ |
|
|
259
|
-
| Code Injection | No eval/Function | ✅ |
|
|
260
|
-
| Key Injection | Character whitelist | ✅ |
|
|
261
|
-
| DoS | 512 char key limit | ✅ |
|
|
262
|
-
| Session Hijacking | Unique session IDs | ✅ |
|
|
263
|
-
| Data Leakage | Namespace isolation | ✅ |
|
|
264
|
-
| CSRF | Browser Same-Origin | ✅ |
|
|
265
|
-
|
|
266
|
-
---
|
|
267
|
-
|
|
268
|
-
## 9. Compliance
|
|
269
|
-
|
|
270
|
-
### Standards Alignment
|
|
271
|
-
|
|
272
|
-
| Standard | Compliance |
|
|
273
|
-
|----------|------------|
|
|
274
|
-
| NIST SP 800-53 | ✅ Cryptographic standards |
|
|
275
|
-
| OWASP Top 10 | ✅ Key injection prevention |
|
|
276
|
-
| CWE | ✅ Common weaknesses addressed |
|
|
277
|
-
| FIPS 140-2 | ✅ crypto.randomUUID |
|
|
278
|
-
|
|
279
|
-
---
|
|
280
|
-
|
|
281
|
-
## 10. Reporting Security Issues
|
|
282
|
-
|
|
283
|
-
If you discover a security vulnerability in Memorio:
|
|
284
|
-
|
|
285
|
-
1. **Do NOT** open a public GitHub issue
|
|
286
|
-
2. **Email**: security@example.com (replace with actual contact)
|
|
287
|
-
3. **Include**: Vulnerability details, steps to reproduce, potential impact
|
|
288
|
-
|
|
289
|
-
### Response Timeline
|
|
290
|
-
|
|
291
|
-
| Phase | Timeline |
|
|
292
|
-
|-------|----------|
|
|
293
|
-
| Acknowledgment | 48 hours |
|
|
294
|
-
| Initial Assessment | 7 days |
|
|
295
|
-
| Fix Released | Based on severity |
|
|
296
|
-
|
|
297
|
-
---
|
|
298
|
-
|
|
299
|
-
## Security Changelog
|
|
300
|
-
|
|
301
|
-
### v3.0.2 (Current)
|
|
302
|
-
|
|
303
|
-
- ✅ Removed esbuild-sass-plugin / esbuild-scss-modules-plugin (SCSS attack vector eliminated)
|
|
304
|
-
- ✅ `store.set()` now blocks function values instead of silently continuing
|
|
305
|
-
- ✅ All `PRIVATE License` headers in `functions/idb/` replaced with `MIT`
|
|
306
|
-
- ✅ `buildPathTracker` dead code removed from state
|
|
307
|
-
- ✅ `Object.freeze(observer)` call removed (undeclared variable, caused `ReferenceError`)
|
|
308
|
-
- ✅ `confirm()` removed from `idb.db.delete()` (no blocking UI calls in libraries)
|
|
309
|
-
- ✅ Fully generated changelog for v3.0.2 across all github docs
|
|
310
|
-
|
|
311
|
-
---
|
|
312
|
-
|
|
313
|
-
### v2.7.0 - Previous
|
|
314
|
-
|
|
315
|
-
- ✅ Added `crypto.getRandomValues()` fallback
|
|
316
|
-
- ✅ Added key length validation (512 chars)
|
|
317
|
-
- ✅ Added character whitelist validation
|
|
318
|
-
- ✅ Improved session isolation
|
|
319
|
-
- ✅ Context isolation for multi-tenancy
|
|
320
|
-
|
|
321
|
-
---
|
|
322
|
-
|
|
323
|
-
*This document was last updated for Memorio v3.0.2*
|
package/markdown/SESSION.md
DELETED
|
@@ -1,154 +0,0 @@
|
|
|
1
|
-
# Session - Memorio
|
|
2
|
-
|
|
3
|
-
> 🖥️ **Browser & Edge**: Uses sessionStorage for persistence
|
|
4
|
-
> ⚙️ **Node.js/Deno**: Falls back to in-memory storage (not persistent)
|
|
5
|
-
|
|
6
|
-
Session provides temporary storage using browser sessionStorage. Data persists until the tab or window is closed.
|
|
7
|
-
|
|
8
|
-
## Installation
|
|
9
|
-
|
|
10
|
-
```bash
|
|
11
|
-
npm install memorio
|
|
12
|
-
```
|
|
13
|
-
|
|
14
|
-
```javascript
|
|
15
|
-
import 'memorio';
|
|
16
|
-
```
|
|
17
|
-
|
|
18
|
-
---
|
|
19
|
-
|
|
20
|
-
## Quick Examples
|
|
21
|
-
|
|
22
|
-
### Example 1: Basic Usage
|
|
23
|
-
|
|
24
|
-
```javascript
|
|
25
|
-
// Save session data
|
|
26
|
-
session.set('token', 'abc123');
|
|
27
|
-
session.set('userId', 42);
|
|
28
|
-
|
|
29
|
-
// Read session data
|
|
30
|
-
console.debug(session.get('token')); // "abc123"
|
|
31
|
-
|
|
32
|
-
// Check persistence
|
|
33
|
-
console.debug(session.isPersistent); // true in browser, false in Node.js/Deno
|
|
34
|
-
```
|
|
35
|
-
|
|
36
|
-
### Example 2: Intermediate
|
|
37
|
-
|
|
38
|
-
```javascript
|
|
39
|
-
// Store objects
|
|
40
|
-
session.set('user', { name: 'Mario', role: 'admin' });
|
|
41
|
-
|
|
42
|
-
// Remove specific item
|
|
43
|
-
session.remove('token');
|
|
44
|
-
|
|
45
|
-
// Clear all session data
|
|
46
|
-
session.removeAll();
|
|
47
|
-
```
|
|
48
|
-
|
|
49
|
-
### Example 3: Advanced
|
|
50
|
-
|
|
51
|
-
```javascript
|
|
52
|
-
// Check if session has data
|
|
53
|
-
if (session.get('authToken')) {
|
|
54
|
-
// User is logged in
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
// Get storage quota (returns Promise<[usage, quota]> in KB)
|
|
58
|
-
const [used, total] = await session.quota();
|
|
59
|
-
console.debug(`Using ${used} out of ${total} KB`);
|
|
60
|
-
|
|
61
|
-
// Get total size in characters
|
|
62
|
-
const size = session.size();
|
|
63
|
-
console.debug(`${size} bytes`);
|
|
64
|
-
|
|
65
|
-
// Handle session expiry
|
|
66
|
-
window.addEventListener('storage', (e) => {
|
|
67
|
-
if (e.key === 'session' && !e.newValue) {
|
|
68
|
-
// Session cleared
|
|
69
|
-
redirectToLogin();
|
|
70
|
-
}
|
|
71
|
-
});
|
|
72
|
-
```
|
|
73
|
-
|
|
74
|
-
---
|
|
75
|
-
|
|
76
|
-
## API Reference
|
|
77
|
-
|
|
78
|
-
### Methods
|
|
79
|
-
|
|
80
|
-
| Method | Parameters | Returns | Description |
|
|
81
|
-
|--------|------------|---------|-------------|
|
|
82
|
-
| `session.get(name)` | `name: string` | `any` | Get value from session |
|
|
83
|
-
| `session.set(name, value)` | `name: string, value: any` | `void` | Save value to session |
|
|
84
|
-
| `session.remove(name)` | `name: string` | `boolean` | Remove single item |
|
|
85
|
-
| `session.delete(name)` | `name: string` | `boolean` | Alias for remove |
|
|
86
|
-
| `session.removeAll()` | `none` | `boolean` | Clear all session data |
|
|
87
|
-
| `session.clearAll()` | `none` | `boolean` | Alias for removeAll |
|
|
88
|
-
| `session.size()` | `none` | `number` | Get total size in characters |
|
|
89
|
-
| `session.quota()` | `none` | `Promise<[number, number]>` | Get storage usage/quota in KB |
|
|
90
|
-
|
|
91
|
-
### Properties
|
|
92
|
-
|
|
93
|
-
| Property | Type | Description |
|
|
94
|
-
|----------|------|-------------|
|
|
95
|
-
| `session.isPersistent` | `boolean` | `true` if using real sessionStorage, `false` if in-memory fallback |
|
|
96
|
-
|
|
97
|
-
---
|
|
98
|
-
|
|
99
|
-
## Store vs Session
|
|
100
|
-
|
|
101
|
-
| Feature | Store | Session |
|
|
102
|
-
|---------|-------|---------|
|
|
103
|
-
| Storage | localStorage | sessionStorage |
|
|
104
|
-
| Lifetime | Forever | Until tab closes |
|
|
105
|
-
| Use case | User preferences | Temporary auth |
|
|
106
|
-
| Shared across tabs | Yes | No |
|
|
107
|
-
| Platform | Browser/Edge | Browser/Edge |
|
|
108
|
-
| Persistence | ✅ Always | ✅ Browser only |
|
|
109
|
-
|
|
110
|
-
---
|
|
111
|
-
|
|
112
|
-
## Platform Notes
|
|
113
|
-
|
|
114
|
-
| Platform | Behavior |
|
|
115
|
-
|----------|----------|
|
|
116
|
-
| Browser | Uses real sessionStorage - data persists until tab closes |
|
|
117
|
-
| Edge Worker | Uses real sessionStorage |
|
|
118
|
-
| Node.js | In-memory fallback - data lost on process restart |
|
|
119
|
-
| Deno | In-memory fallback - data lost on process restart |
|
|
120
|
-
|
|
121
|
-
---
|
|
122
|
-
|
|
123
|
-
## Best Practices
|
|
124
|
-
|
|
125
|
-
1. Use for auth tokens: `session.set('token', jwt)`
|
|
126
|
-
2. Clear on logout: `session.removeAll()`
|
|
127
|
-
3. Don't use for persistent data
|
|
128
|
-
4. Check for null: `session.get('key') || defaultValue`
|
|
129
|
-
|
|
130
|
-
---
|
|
131
|
-
|
|
132
|
-
## Common Use Cases
|
|
133
|
-
|
|
134
|
-
### Authentication
|
|
135
|
-
|
|
136
|
-
```javascript
|
|
137
|
-
// Login
|
|
138
|
-
session.set('authToken', response.token);
|
|
139
|
-
session.set('user', response.user);
|
|
140
|
-
|
|
141
|
-
// Logout
|
|
142
|
-
session.removeAll();
|
|
143
|
-
router.push('/login');
|
|
144
|
-
```
|
|
145
|
-
|
|
146
|
-
### Form Progress
|
|
147
|
-
|
|
148
|
-
```javascript
|
|
149
|
-
// Save form draft
|
|
150
|
-
session.set('formDraft', formData);
|
|
151
|
-
|
|
152
|
-
// Restore on page refresh
|
|
153
|
-
const draft = session.get('formDraft');
|
|
154
|
-
if (draft) restoreForm(draft);
|
package/markdown/SQLITE.md
DELETED
|
@@ -1,181 +0,0 @@
|
|
|
1
|
-
# SQLite - Memorio
|
|
2
|
-
|
|
3
|
-
> The `sql.js` package is **optional** — if it is not installed, Memorio loads `sql.js` on first use by injecting the `sql-wasm-browser.js` UMD build from the jsDelivr CDN as a classic `<script>` (which exposes the `initSqlJs` factory on `globalThis`). No bare `import('sql.js')` is ever emitted, so bundlers never resolve the optional dependency at build time. Not available in Node.js/Deno.
|
|
4
|
-
|
|
5
|
-
SQLite brings a full SQL engine into the browser through [`sql.js`](https://sql.js.org), a port of SQLite to JavaScript via WebAssembly. Memorio loads it **lazily** on first use, so it only affects bundles that actually use the `sqlite` module.
|
|
6
|
-
|
|
7
|
-
## Installation
|
|
8
|
-
|
|
9
|
-
```bash
|
|
10
|
-
npm install memorio
|
|
11
|
-
# Optional: install the SQLite engine locally (the default loader fetches it from the CDN)
|
|
12
|
-
npm install sql.js
|
|
13
|
-
```
|
|
14
|
-
|
|
15
|
-
```javascript
|
|
16
|
-
import 'memorio';
|
|
17
|
-
```
|
|
18
|
-
|
|
19
|
-
> The default loader injects the sql.js UMD build (`sql-wasm-browser.js`) from the jsDelivr CDN as a classic `<script>`, exposing the `initSqlJs` factory on `globalThis`. This keeps `sql.js` (and its WASM) out of your build graph entirely — it's only fetched when `sqlite` is first used. For production/self-hosted setups, install `sql.js` and configure a custom `loader` (e.g. `sqlite.config({ loader: () => import('sql.js') })` under a bundler), or set the wasm base with `sqlite.config({ wasmUrl })` / `sqlite.config({ locateFile })`.
|
|
20
|
-
|
|
21
|
-
---
|
|
22
|
-
|
|
23
|
-
## Quick Examples
|
|
24
|
-
|
|
25
|
-
### Example 1: Basic Usage
|
|
26
|
-
|
|
27
|
-
```javascript
|
|
28
|
-
// Create an in-memory database and a table
|
|
29
|
-
await sqlite.db.create('myApp');
|
|
30
|
-
await sqlite.query.run('myApp', 'CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)');
|
|
31
|
-
|
|
32
|
-
// Insert data
|
|
33
|
-
await sqlite.query.run('myApp', 'INSERT INTO users (name) VALUES (?)', ['Mario']);
|
|
34
|
-
|
|
35
|
-
// Select data
|
|
36
|
-
const rows = await sqlite.query.select('myApp', 'SELECT * FROM users');
|
|
37
|
-
console.debug(rows); // [{ id: 1, name: 'Mario' }]
|
|
38
|
-
```
|
|
39
|
-
|
|
40
|
-
### Example 2: CRUD shortcuts
|
|
41
|
-
|
|
42
|
-
```javascript
|
|
43
|
-
const db = 'store';
|
|
44
|
-
|
|
45
|
-
await sqlite.db.create(db);
|
|
46
|
-
await sqlite.query.run(db, 'CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT, price REAL)');
|
|
47
|
-
await sqlite.data.set(db, 'INSERT INTO products (name, price) VALUES (?, ?)', ['Apple', 1.5]);
|
|
48
|
-
await sqlite.data.set(db, 'INSERT INTO products (name, price) VALUES (?, ?)', ['Banana', 0.8]);
|
|
49
|
-
|
|
50
|
-
// First matching row
|
|
51
|
-
const apple = await sqlite.data.get(db, 'SELECT * FROM products WHERE name = ?', ['Apple']);
|
|
52
|
-
console.debug(apple); // { id: 1, name: 'Apple', price: 1.5 }
|
|
53
|
-
```
|
|
54
|
-
|
|
55
|
-
### Example 3: Export / Import
|
|
56
|
-
|
|
57
|
-
```javascript
|
|
58
|
-
await sqlite.db.create('myApp');
|
|
59
|
-
await sqlite.query.run('myApp', 'CREATE TABLE todos (id INTEGER PRIMARY KEY, task TEXT)');
|
|
60
|
-
await sqlite.data.set('myApp', 'INSERT INTO todos (task) VALUES (?)', ['Write docs']);
|
|
61
|
-
|
|
62
|
-
// Export the in-memory database to a portable binary dump
|
|
63
|
-
const dump = await sqlite.db.export('myApp');
|
|
64
|
-
|
|
65
|
-
// Later... import it back
|
|
66
|
-
await sqlite.db.import('restored', dump);
|
|
67
|
-
const rows = await sqlite.query.select('restored', 'SELECT * FROM todos');
|
|
68
|
-
```
|
|
69
|
-
|
|
70
|
-
### Example 4: Engine control
|
|
71
|
-
|
|
72
|
-
```javascript
|
|
73
|
-
// Configure the wasm location BEFORE first use (sets the locateFile base)
|
|
74
|
-
sqlite.config({ wasmUrl: '/static/sql.js/' });
|
|
75
|
-
|
|
76
|
-
// Or provide a fully custom loader (e.g. a local/npm build of sql.js)
|
|
77
|
-
sqlite.config({ loader: async () => {
|
|
78
|
-
return await import('sql.js'); // local install — resolves at runtime
|
|
79
|
-
}});
|
|
80
|
-
|
|
81
|
-
// Enable automatic persistence of one or more databases (see Example 5)
|
|
82
|
-
sqlite.config({ persistence: true });
|
|
83
|
-
|
|
84
|
-
// Wait until the engine is ready
|
|
85
|
-
await sqlite.ready;
|
|
86
|
-
console.debug('SQLite version:', sqlite.db.version());
|
|
87
|
-
```
|
|
88
|
-
|
|
89
|
-
### Example 5: Persistence & dev download
|
|
90
|
-
|
|
91
|
-
> **Important:** sql.js databases live in **WebAssembly memory** — they are
|
|
92
|
-
> in-memory and **volatile** (lost on page refresh) unless you persist them.
|
|
93
|
-
|
|
94
|
-
```javascript
|
|
95
|
-
// Opt into auto-persistence at create time (global config or per-create)
|
|
96
|
-
await sqlite.db.create('app', { persistence: true });
|
|
97
|
-
|
|
98
|
-
await sqlite.query.run('app', 'CREATE TABLE notes (id INTEGER PRIMARY KEY, body TEXT)');
|
|
99
|
-
// writes are snapshotted to localStorage automatically (debounced via updateHook)
|
|
100
|
-
|
|
101
|
-
await sqlite.db.persist('app'); // force an immediate snapshot
|
|
102
|
-
// After a refresh, reopening restores the data:
|
|
103
|
-
await sqlite.db.create('app', { persistence: true });
|
|
104
|
-
|
|
105
|
-
// Dev convenience: download the current db as a .sqlite file from the browser
|
|
106
|
-
await sqlite.db.download('app', 'app.sqlite');
|
|
107
|
-
|
|
108
|
-
// Flush + persist + release the handle
|
|
109
|
-
await sqlite.db.close('app');
|
|
110
|
-
```
|
|
111
|
-
|
|
112
|
-
Persistence is stored on `store` (localStorage, namespaced per
|
|
113
|
-
`sqlite.config({ namespace })` / memorio context) as a base64 snapshot under
|
|
114
|
-
`memorio:sqlite:db:<ns>:<name>`. It is best-effort: if `store` is unavailable
|
|
115
|
-
the database simply behaves as in-memory.
|
|
116
|
-
|
|
117
|
-
---
|
|
118
|
-
|
|
119
|
-
## API Reference
|
|
120
|
-
|
|
121
|
-
### Engine Control
|
|
122
|
-
|
|
123
|
-
| Method | Parameters | Returns | Description |
|
|
124
|
-
|--------|------------|---------|-------------|
|
|
125
|
-
| `sqlite.config(opts)` | `opts: { loader?, locateFile?, wasmUrl?, persistence?, namespace? }` | `sqlite` | Configure the engine. `loader` fully replaces the initializer (default = CDN `<script>`); `locateFile` customizes wasm resolution; `wasmUrl` sets the wasm base directory; `persistence` toggles automatic db snapshots; `namespace` partitions persisted snapshots. Chainable. |
|
|
126
|
-
| `sqlite.db.create(name, opts)` | `name: string, opts?: { data?, persistence? }` | `Database` | Opens/creates a named in-memory db. With `persistence: true` (or global config), a snapshot is restored if present and writes are auto-saved. |
|
|
127
|
-
| `sqlite.db.persist(name)` | `name: string` | `Promise<boolean>` | Force an immediate snapshot of a persisted database to `store`. |
|
|
128
|
-
| `sqlite.db.download(name, filename?)` | `name: string, filename?: string` | `Promise<boolean>` | Dev-only: trigger a browser download of the db as a `.sqlite` file. |
|
|
129
|
-
| `sqlite.db.close(name)` | `name: string` | `Promise<void>` | Persist (if enabled), close, and release the handle. |
|
|
130
|
-
| `sqlite.ready` | none | `Promise<void>` | Resolves once `sql.js` has been initialized. Rejects (and sets `_disabled`) if the engine can't load. |
|
|
131
|
-
| `sqlite.db.version()` | none | `string \| null` | Engine version, available after initialization. |
|
|
132
|
-
| `sqlite._disabled` | none | `boolean` | `true` when the module is disabled (non-browser env / load failure). |
|
|
133
|
-
| `sqlite._warning` | none | `string \| undefined` | Reason text when disabled, if applicable. |
|
|
134
|
-
|
|
135
|
-
### Database Methods
|
|
136
|
-
|
|
137
|
-
| Method | Parameters | Returns | Description |
|
|
138
|
-
|--------|------------|---------|-------------|
|
|
139
|
-
| `sqlite.db.support()` | none | `boolean` | Check whether SQLite can run in this environment. |
|
|
140
|
-
| `sqlite.db.create(name, opts?)` | `name: string`, `opts?: { data }` | `Promise<Database>` | Create an in-memory database (or reopen one from a binary dump). |
|
|
141
|
-
| `sqlite.db.get(name)` | `name: string` | `Database` | Retrieve an open database handle. |
|
|
142
|
-
| `sqlite.db.delete(name)` | `name: string` | `boolean` | Close and remove a database handle. |
|
|
143
|
-
| `sqlite.db.list()` | none | `string[]` | List open database names. |
|
|
144
|
-
| `sqlite.db.size(name?)` | `name?: string` | `Promise<number>` | Size in bytes of one or all databases. |
|
|
145
|
-
| `sqlite.db.export(name)` | `name: string` | `Promise<Uint8Array>` | Export a database to a binary dump. |
|
|
146
|
-
| `sqlite.db.import(name, data)` | `name: string`, `data` | `Promise<Database>` | Create/replace a database from a binary dump. |
|
|
147
|
-
|
|
148
|
-
### Query Methods
|
|
149
|
-
|
|
150
|
-
| Method | Parameters | Returns | Description |
|
|
151
|
-
|--------|------------|---------|-------------|
|
|
152
|
-
| `sqlite.query.run(name, sql, params?)` | `name: string`, `sql: string`, `params?: any[]` | `Promise<number>` | Run a statement that does not return rows (INSERT / UPDATE / DELETE / CREATE). Returns modified-row count. |
|
|
153
|
-
| `sqlite.query.select(name, sql, params?)` | `name: string`, `sql: string`, `params?: any[]` | `Promise<object[]>` | Run a query and return the rows as plain objects. |
|
|
154
|
-
|
|
155
|
-
### Data Methods (CRUD shortcuts)
|
|
156
|
-
|
|
157
|
-
| Method | Parameters | Returns | Description |
|
|
158
|
-
|--------|------------|---------|-------------|
|
|
159
|
-
| `sqlite.data.set(name, sql, params?)` | `name: string`, `sql: string`, `params?: any[]` | `Promise<number>` | Alias of `sqlite.query.run`. |
|
|
160
|
-
| `sqlite.data.get(name, sql, params?)` | `name: string`, `sql: string`, `params?: any[]` | `Promise<object \| null>` | Alias of `sqlite.query.select` returning the first row (or `null`). |
|
|
161
|
-
|
|
162
|
-
---
|
|
163
|
-
|
|
164
|
-
## Platform Support
|
|
165
|
-
|
|
166
|
-
| Platform | Support | Notes |
|
|
167
|
-
|----------|---------|-------|
|
|
168
|
-
| Browser | ✅ Full | Requires WebAssembly + the `sql.js` package (or CDN fallback) |
|
|
169
|
-
| Edge Worker | ⚠️ Limited | WebAssembly may be available; configure a `loader` manually |
|
|
170
|
-
| Node.js | ❌ Not available | Use `store` or `session` instead |
|
|
171
|
-
| Deno | ❌ Not available | Use `store` or `session` instead |
|
|
172
|
-
|
|
173
|
-
---
|
|
174
|
-
|
|
175
|
-
## Best Practices
|
|
176
|
-
|
|
177
|
-
1. Configure the wasm path for production: `sqlite.config({ wasmUrl })` or `sqlite.config({ loader })`.
|
|
178
|
-
2. Create one named database per feature and reuse the handle: `const db = await sqlite.db.create('app')`.
|
|
179
|
-
3. Always release databases you no longer need: `sqlite.db.delete('temp')`.
|
|
180
|
-
4. Use `await sqlite.ready` before running statements to ensure the engine is loaded.
|
|
181
|
-
5. Use `?` placeholders and `params` to avoid SQL injection.
|