memorio 2.5.2 → 2.5.3

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.
@@ -0,0 +1,129 @@
1
+ # Session - Memorio
2
+
3
+ Session provides temporary storage using browser sessionStorage. Data persists until the tab or window is closed.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install memorio
9
+ ```
10
+
11
+ ```javascript
12
+ import 'memorio';
13
+ ```
14
+
15
+ ---
16
+
17
+ ## Quick Examples
18
+
19
+ ### Example 1: Basic Usage
20
+
21
+ ```javascript
22
+ // Save session data
23
+ session.set('token', 'abc123');
24
+ session.set('userId', 42);
25
+
26
+ // Read session data
27
+ console.log(session.get('token')); // "abc123"
28
+ ```
29
+
30
+ ### Example 2: Intermediate
31
+
32
+ ```javascript
33
+ // Store objects
34
+ session.set('user', { name: 'Mario', role: 'admin' });
35
+
36
+ // Remove specific item
37
+ session.remove('token');
38
+
39
+ // Clear all session data
40
+ session.removeAll();
41
+ ```
42
+
43
+ ### Example 3: Advanced
44
+
45
+ ```javascript
46
+ // Check if session has data
47
+ if (session.get('authToken')) {
48
+ // User is logged in
49
+ }
50
+
51
+ // Get storage quota (returns Promise<[usage, quota]> in KB)
52
+ const [used, total] = await session.quota();
53
+ console.log(`Using ${used} out of ${total} KB`);
54
+
55
+ // Get total size in characters
56
+ const size = session.size();
57
+ console.log(`${size} bytes`);
58
+
59
+ // Handle session expiry
60
+ window.addEventListener('storage', (e) => {
61
+ if (e.key === 'session' && !e.newValue) {
62
+ // Session cleared
63
+ redirectToLogin();
64
+ }
65
+ });
66
+ ```
67
+
68
+ ---
69
+
70
+ ## API Reference
71
+
72
+ ### Methods
73
+
74
+ | Method | Parameters | Returns | Description |
75
+ |--------|------------|---------|-------------|
76
+ | `session.get(name)` | `name: string` | `any` | Get value from session |
77
+ | `session.set(name, value)` | `name: string, value: any` | `void` | Save value to session |
78
+ | `session.remove(name)` | `name: string` | `boolean` | Remove single item |
79
+ | `session.delete(name)` | `name: string` | `boolean` | Alias for remove |
80
+ | `session.removeAll()` | `none` | `boolean` | Clear all session data |
81
+ | `session.clearAll()` | `none` | `boolean` | Alias for removeAll |
82
+ | `session.size()` | `none` | `number` | Get total size in characters |
83
+ | `session.quota()` | `none` | `Promise<[number, number]>` | Get storage usage/quota in KB |
84
+
85
+ ---
86
+
87
+ ## Store vs Session
88
+
89
+ | Feature | Store | Session |
90
+ |---------|-------|---------|
91
+ | Storage | localStorage | sessionStorage |
92
+ | Lifetime | Forever | Until tab closes |
93
+ | Use case | User preferences | Temporary auth |
94
+ | Shared across tabs | Yes | No |
95
+
96
+ ---
97
+
98
+ ## Best Practices
99
+
100
+ 1. Use for auth tokens: `session.set('token', jwt)`
101
+ 2. Clear on logout: `session.removeAll()`
102
+ 3. Don't use for persistent data
103
+ 4. Check for null: `session.get('key') || defaultValue`
104
+
105
+ ---
106
+
107
+ ## Common Use Cases
108
+
109
+ ### Authentication
110
+
111
+ ```javascript
112
+ // Login
113
+ session.set('authToken', response.token);
114
+ session.set('user', response.user);
115
+
116
+ // Logout
117
+ session.removeAll();
118
+ router.push('/login');
119
+ ```
120
+
121
+ ### Form Progress
122
+
123
+ ```javascript
124
+ // Save form draft
125
+ session.set('formDraft', formData);
126
+
127
+ // Restore on page refresh
128
+ const draft = session.get('formDraft');
129
+ if (draft) restoreForm(draft);
package/docs/STATE.md ADDED
@@ -0,0 +1,135 @@
1
+ # State - Memorio
2
+
3
+ State is a reactive global state manager using JavaScript Proxies. It's simple, powerful, and requires no setup. Data persists only in memory during the session.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install memorio
9
+ ```
10
+
11
+ ```javascript
12
+ import 'memorio';
13
+ ```
14
+
15
+ That's it. `state` is now global.
16
+
17
+ ---
18
+
19
+ ## Quick Examples
20
+
21
+ ### Example 1: Basic Usage
22
+
23
+ ```javascript
24
+ // Set a value
25
+ state.name = 'Mario';
26
+ state.age = 25;
27
+
28
+ // Get a value
29
+ console.log(state.name); // "Mario"
30
+
31
+ // Simple object
32
+ state.user = { name: 'Luigi', level: 1 };
33
+ ```
34
+
35
+ ### Example 2: Intermediate
36
+
37
+ ```javascript
38
+ // Array operations
39
+ state.items = [1, 2, 3];
40
+ state.items.push(4);
41
+ console.log(state.items); // [1, 2, 3, 4]
42
+
43
+ // Nested objects
44
+ state.config = { theme: 'dark', lang: 'en' };
45
+ state.config.theme = 'light';
46
+
47
+ // List all states
48
+ console.log(state.list);
49
+ ```
50
+
51
+ ### Example 3: Advanced
52
+
53
+ ```javascript
54
+ // Lock state to prevent modifications
55
+ state.frozenConfig = { maxUsers: 100 };
56
+ state.frozenConfig.lock();
57
+ // Now state.frozenConfig cannot be modified
58
+
59
+ // Path tracking
60
+ const path = state.user.path;
61
+ console.log(path.name); // "user"
62
+ console.log(path.profile.name); // "user.profile"
63
+
64
+ // Get full path as string
65
+ console.log(state.user.__path); // "state.user"
66
+
67
+ // Protected keys (internal use)
68
+ console.log(protect); // Array of protected keys
69
+ ```
70
+
71
+ ---
72
+
73
+ ## API Reference
74
+
75
+ ### Properties
76
+
77
+ | Property | Type | Description |
78
+ |----------|------|-------------|
79
+ | `state.list` | Array | Get all current state keys (deep copy) |
80
+ | `state.path` | Object | Get path tracker for current location |
81
+ | `state.__path` | string | Get full path as string |
82
+
83
+ ### Methods
84
+
85
+ | Method | Parameters | Description |
86
+ |--------|------------|-------------|
87
+ | `state.remove(key)` | `key: string` | Remove a specific state |
88
+ | `state.removeAll()` | none | Clear all states |
89
+
90
+ ### Lock
91
+
92
+ ```javascript
93
+ // Lock an object or array
94
+ state.myArray = [1, 2, 3];
95
+ state.myArray.lock();
96
+
97
+ // Now any modification will fail
98
+ state.myArray.push(4); // Error: state 'myArray' is locked
99
+ ```
100
+
101
+ ---
102
+
103
+ ## How It Works
104
+
105
+ Memorio uses JavaScript `Proxy` to intercept get/set operations on the global `state` object. This allows:
106
+
107
+ 1. **Reactivity** - Any change can trigger observers
108
+ 2. **Nested objects** - Deep path tracking
109
+ 3. **Type safety** - Full TypeScript support
110
+
111
+ ---
112
+
113
+ ## Best Practices
114
+
115
+ 1. Use descriptive keys: `state.userProfile` not `state.up`
116
+ 2. Group related data: `state.cart.items` not `state.cartItems`
117
+ 3. Lock static config: `state.appConfig.lock()`
118
+ 4. Clean up on logout: `state.removeAll()`
119
+ 5. Use path tracking for debugging: `state.myData.__path`
120
+
121
+ ---
122
+
123
+ ## Common Errors
124
+
125
+ ```javascript
126
+ // Error: protected key
127
+ state._internal = 'value';
128
+ // Output: "key _internal is protected"
129
+
130
+ // Error: locked state
131
+ state.locked = { x: 1 };
132
+ state.locked.lock();
133
+ state.locked.x = 2;
134
+ // Output: "Error: state 'locked' is locked"
135
+ ```
package/docs/STORE.md ADDED
@@ -0,0 +1,137 @@
1
+ # Store - Memorio
2
+
3
+ Store provides persistent localStorage management with a simple API. Data survives page refreshes and browser restarts.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install memorio
9
+ ```
10
+
11
+ ```javascript
12
+ import 'memorio';
13
+ ```
14
+
15
+ ---
16
+
17
+ ## Quick Examples
18
+
19
+ ### Example 1: Basic Usage
20
+
21
+ ```javascript
22
+ // Save data
23
+ store.set('username', 'Mario');
24
+ store.set('score', 1500);
25
+
26
+ // Read data
27
+ console.log(store.get('username')); // "Mario"
28
+ console.log(store.get('score')); // 1500
29
+ ```
30
+
31
+ ### Example 2: Intermediate
32
+
33
+ ```javascript
34
+ // Store objects
35
+ store.set('user', { name: 'Luigi', level: 5 });
36
+ const user = store.get('user');
37
+ console.log(user.name); // "Luigi"
38
+
39
+ // Remove single item
40
+ store.remove('username');
41
+
42
+ // Check size
43
+ const totalSize = store.size();
44
+ console.log(`${totalSize} bytes`);
45
+ ```
46
+
47
+ ### Example 3: Advanced
48
+
49
+ ```javascript
50
+ // Get storage quota (returns Promise<[usage, quota]> in KB)
51
+ const [used, total] = await store.quota();
52
+ console.log(`Using ${used} out of ${total} KB`);
53
+
54
+ // Get total size in characters
55
+ const size = store.size();
56
+ console.log(`${size} bytes`);
57
+
58
+ // Clear all data
59
+ store.removeAll();
60
+ // or use alias
61
+ store.clearAll();
62
+
63
+ // Handle errors gracefully
64
+ try {
65
+ store.set('largeData', hugeObject);
66
+ } catch (err) {
67
+ console.error('Storage full:', err);
68
+ }
69
+ ```
70
+
71
+ ---
72
+
73
+ ## API Reference
74
+
75
+ ### Methods
76
+
77
+ | Method | Parameters | Returns | Description |
78
+ |--------|------------|---------|-------------|
79
+ | `store.get(name)` | `name: string` | `any` | Get value from storage |
80
+ | `store.set(name, value)` | `name: string, value: any` | `void` | Save value to storage |
81
+ | `store.remove(name)` | `name: string` | `boolean` | Remove single item |
82
+ | `store.delete(name)` | `name: string` | `boolean` | Alias for remove |
83
+ | `store.removeAll()` | none | `boolean` | Clear all storage |
84
+ | `store.clearAll()` | none | `boolean` | Alias for removeAll |
85
+ | `store.size()` | none | `number` | Get total size in characters |
86
+ | `store.quota()` | none | `Promise<[number, number]>` | Get storage usage/quota in KB |
87
+
88
+ ### Supported Types
89
+
90
+ ```javascript
91
+ // All JSON-serializable types work
92
+ store.set('string', 'hello');
93
+ store.set('number', 42);
94
+ store.set('boolean', true);
95
+ store.set('array', [1, 2, 3]);
96
+ store.set('object', { key: 'value' });
97
+ store.set('null', null);
98
+ store.set('undefined', null); // converted to null
99
+ ```
100
+
101
+ ### Not Supported
102
+
103
+ ```javascript
104
+ // Functions will log an error
105
+ store.set('myFunc', () => {});
106
+ // Output: "It's not secure to store functions."
107
+ ```
108
+
109
+ ---
110
+
111
+ ## How It Works
112
+
113
+ Store wraps the browser's `localStorage` API with:
114
+
115
+ - Automatic JSON serialization/deserialization
116
+ - Error handling for parse failures
117
+ - Size calculation
118
+ - Quota monitoring
119
+
120
+ ---
121
+
122
+ ## Storage Limits
123
+
124
+ - **Chrome/Safari**: ~5-10 MB
125
+ - **Firefox**: ~10 MB
126
+ - **Edge**: ~5-10 MB
127
+
128
+ Use `store.quota()` to monitor usage.
129
+
130
+ ---
131
+
132
+ ## Best Practices
133
+
134
+ 1. Prefix keys: `store.set('app_username', '...')`
135
+ 2. Check before set: `if (store.get('key')) { ... }`
136
+ 3. Handle quota: Try/catch around large data
137
+ 4. Clean up: `store.removeAll()` on logout
@@ -0,0 +1,25 @@
1
+ # Table of contents
2
+
3
+ * [README](../README.md)
4
+
5
+ ## Core Modules
6
+
7
+ * [State](STATE.md) - Reactive global state management
8
+ * [Observer](OBSERVER.md) - ⚠️ Deprecated (use useObserver)
9
+ * [useObserver](USEOBSERVER.md) - React hook for state observation
10
+ * [Cache](CACHE.md) - In-memory caching (lost on refresh)
11
+ * [Store](STORE.md) - Persistent localStorage management
12
+ * [Session](SESSION.md) - Temporary sessionStorage management
13
+ * [IDB](IDB.md) - IndexedDB for large data storage
14
+
15
+ ## Additional Resources
16
+
17
+ * [License](../LICENSE.md)
18
+ * [Contributing](../CONTRIBUTING.md)
19
+ * [Code of Conduct](../CODE_OF_CONDUCT.md)
20
+ * [Security](../SECURITY.md)
21
+
22
+ ## Changelog
23
+
24
+ * [Changelog](../CHANGELOG.md)
25
+ * [History](../HISTORY.md)
@@ -0,0 +1,156 @@
1
+ # useObserver - Memorio
2
+
3
+ useObserver is a React hook for observing state changes. It automatically subscribes to state changes and includes powerful auto-discovery features.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install memorio
9
+ ```
10
+
11
+ ```javascript
12
+ import 'memorio';
13
+ ```
14
+
15
+ ---
16
+
17
+ ## Quick Examples
18
+
19
+ ### Example 1: Basic Usage
20
+
21
+ ```javascript
22
+ import { useObserver } from 'memorio';
23
+
24
+ function Counter() {
25
+ useObserver(() => {
26
+ console.debug('Counter changed:', state.counter);
27
+ }, [state.counter]);
28
+
29
+ return <div>{state.counter}</div>;
30
+ }
31
+ ```
32
+
33
+ ### Auto-Discovery (Magic Mode)
34
+
35
+ ```javascript
36
+ // Pass your callback WITHOUT dependencies - it auto-discovers!
37
+ function MyComponent() {
38
+ useObserver(() => {
39
+ // This will automatically track ALL state properties used inside
40
+ console.debug('Something changed:', state.user.name, state.items.length);
41
+ });
42
+
43
+ return <div>{state.user.name}</div>;
44
+ }
45
+ ```
46
+
47
+ ### Example 2: Intermediate
48
+
49
+ ```javascript
50
+ function UserProfile() {
51
+ const [localState, setLocalState] = useState(null);
52
+
53
+ useObserver(() => {
54
+ setLocalState(state.user);
55
+ }, [state.user]);
56
+
57
+ return <div>{localState?.name}</div>;
58
+ }
59
+ ```
60
+
61
+ ### Example 3: Advanced
62
+
63
+ ```javascript
64
+ // Multiple watchers with array
65
+ function MultiWatch() {
66
+ useObserver(() => {
67
+ console.debug('A or B changed:', state.a, state.b);
68
+ }, [state.a, state.b]);
69
+
70
+ return <div>{state.a} - {state.b}</div>;
71
+ }
72
+ ```
73
+ // With string path (for store)
74
+ function StoreWatcher() {
75
+ useObserver(() => {
76
+ console.debug('Store changed');
77
+ }, 'store.userPreferences');
78
+
79
+ return <div />;
80
+ }
81
+ ```
82
+
83
+ ---
84
+
85
+ ## API Reference
86
+
87
+ ### useObserver(callback, deps)
88
+
89
+ | Parameter | Type | Description |
90
+ | --------- | ---- | ----------- |
91
+ | `callback` | `function` | Function to run on change |
92
+ | `deps` | `function \| string \| array` | State path(s) to watch |
93
+
94
+ ### Callback Parameters
95
+
96
+ ```javascript
97
+ useObserver((newValue, oldValue) => {
98
+ console.debug('Changed:', newValue);
99
+ }, [state.key]);
100
+ ```
101
+
102
+ ### Auto-Discovery Mode
103
+
104
+ When `deps` is omitted, useObserver automatically discovers all state properties accessed inside the callback:
105
+
106
+ ```javascript
107
+ // No deps needed - magic auto-discovery!
108
+ useObserver(() => {
109
+ // Automatically tracks state.user, state.items, state.counter
110
+ console.log(state.user.name, state.items.length, state.counter);
111
+ });
112
+ ```
113
+
114
+ Returns a cleanup function:
115
+
116
+ ## useObserver vs observer
117
+
118
+ | Feature | observer | useObserver |
119
+ | ------- | -------- | ----------- |
120
+ | Framework | Vanilla JS | React |
121
+ | Auto-cleanup | Manual | Auto |
122
+ | React lifecycle | No | Yes |
123
+
124
+ ---
125
+
126
+ ## Common Patterns
127
+
128
+ ### Sync with useState
129
+
130
+ ```javascript
131
+ function MyComponent() {
132
+ const [data, setData] = useState(null);
133
+
134
+ useObserver((newVal) => {
135
+ setData(newVal);
136
+ }, [state.data]);
137
+
138
+ return <div>{data}</div>;
139
+ }
140
+ ```
141
+
142
+ ### Multiple Watchers
143
+
144
+ ```javascript
145
+ }, [state.a, state.b]);
146
+ ```
147
+
148
+ ---
149
+
150
+ ## Best Practices
151
+
152
+ 1. Always use in React components
153
+ 2. Use auto-discovery for simpler code: `useObserver(() => { ... })`
154
+ 3. No manual cleanup needed - returns cleanup function automatically
155
+ 4. Use with state for reactive UI
156
+ 5. Check console for auto-discovery logs
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Memorio Basic Example
3
+ *
4
+ * This example shows the fundamental features of Memorio:
5
+ * - State management
6
+ * - Store (localStorage)
7
+ * - Session storage
8
+ *
9
+ * Run: npx ts-node examples/basic.ts
10
+ */
11
+
12
+ import '../index'
13
+
14
+ // ============================================
15
+ // STATE - In-memory reactive state
16
+ // ============================================
17
+
18
+ // Set some state values
19
+ state.name = 'Mario'
20
+ state.age = 30
21
+ state.isActive = true
22
+ state.profile = {
23
+ email: 'mario@example.com',
24
+ avatar: 'https://example.com/mario.png'
25
+ }
26
+
27
+ // Get state values
28
+ console.log('Name:', state.name)
29
+ console.log('Age:', state.age)
30
+ console.log('Profile:', state.profile)
31
+
32
+ // List all states
33
+ console.log('All states:', state.list)
34
+
35
+ // ============================================
36
+ // STORE - Persistent localStorage
37
+ // ============================================
38
+
39
+ // Save to localStorage
40
+ store.set('username', 'mario')
41
+ store.set('preferences', { theme: 'dark', language: 'en' })
42
+ store.set('lastLogin', Date.now())
43
+
44
+ // Read from localStorage
45
+ console.log('Username:', store.get('username'))
46
+ console.log('Preferences:', store.get('preferences'))
47
+
48
+ // Get storage size
49
+ console.log('Storage size:', store.size(), 'bytes')
50
+
51
+ // ============================================
52
+ // SESSION - Temporary session storage
53
+ // ============================================
54
+
55
+ // Save session data (cleared when tab closes)
56
+ session.set('token', 'abc123xyz')
57
+ session.set('userId', 42)
58
+
59
+ // Read session data
60
+ console.log('Token:', session.get('token'))
61
+ console.log('User ID:', session.get('userId'))
62
+
63
+ // ============================================
64
+ // CLEANUP
65
+ // ============================================
66
+
67
+ // Clear specific items
68
+ store.remove('username')
69
+ session.remove('token')
70
+
71
+ // Clear all
72
+ store.removeAll()
73
+ session.removeAll()
74
+
75
+ console.log('Example complete!')