local-lite 0.1.3 → 0.1.4
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 +9 -1
- package/dist/utils/dynamic.js +0 -3
- package/package.json +1 -1
- package/skills/local-lite-auth/SKILL.md +189 -0
- package/skills/local-lite-backups/SKILL.md +164 -0
- package/skills/local-lite-offline-actions/SKILL.md +122 -0
- package/skills/local-lite-react/SKILL.md +124 -0
- package/skills/local-lite-schema/SKILL.md +171 -0
- package/skills/local-lite-setup/SKILL.md +203 -21
- package/skills/local-lite-storage/SKILL.md +116 -0
- package/skills/local-lite-upgrade/SKILL.md +45 -16
package/README.md
CHANGED
|
@@ -93,7 +93,15 @@ For an application-level upgrade checklist or AI-assisted code review, see the
|
|
|
93
93
|
## AI Skills
|
|
94
94
|
|
|
95
95
|
The package ships [Agent Skills](./skills) that AI coding assistants can load:
|
|
96
|
-
`local-lite-setup
|
|
96
|
+
* `local-lite-setup`: Multi-platform setup (Expo, Web, Node) and client initialization.
|
|
97
|
+
* `local-lite-auth`: Zero-backend SQLite authentication, PBKDF2 crypto, lockout, reset tokens, and OAuth.
|
|
98
|
+
* `local-lite-backups`: Cloud backups (OneDrive, Google Drive), AES-256-GCM database encryption, and restore.
|
|
99
|
+
* `local-lite-schema`: Declarative cascading deletions (`onDelete`), append-only migrations, and FTS5 search.
|
|
100
|
+
* `local-lite-storage`: Blob and file management, ExpoFileDriver, and cloud storage bucket sync.
|
|
101
|
+
* `local-lite-react`: Reactive hooks (`useLiveQuery`, `useSyncStatus`, `useLocalAuth`, `useKV`), and 0ms optimistic writes.
|
|
102
|
+
* `local-lite-offline-actions`: Queued mutation outbox, encrypted secret preferences, and background scheduler.
|
|
103
|
+
* `local-lite-custom-adapter`: Implementing custom REST, GraphQL, or WebSocket remote database adapters.
|
|
104
|
+
* `local-lite-upgrade`: Migration checklist and breaking change reviews across version upgrades.
|
|
97
105
|
|
|
98
106
|
```bash
|
|
99
107
|
npx local-lite install-skills # Copilot: .github/skills
|
package/dist/utils/dynamic.js
CHANGED
package/package.json
CHANGED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: local-lite-auth
|
|
3
|
+
description: Implement authentication and session management in local-lite. Use when setting up zero-backend local SQLite authentication (LocalAuthEngine, useLocalAuth), configuring PBKDF2 crypto, brute-force lockout, single-use reset tokens, or integrating OAuth providers (Google, Microsoft, GitHub, Apple) and offline sessions.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# local-lite Authentication
|
|
7
|
+
|
|
8
|
+
Comprehensive guide for implementing zero-backend local SQLite authentication and OAuth integrations in `local-lite`.
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## 1. Zero-Backend Local SQLite Auth (`LocalAuthEngine`)
|
|
13
|
+
|
|
14
|
+
`LocalAuthEngine` provides fully local, client-side authentication stored directly in private SQLite tables (`_local_users` and `_local_user_tokens`). It requires no remote servers or cloud accounts.
|
|
15
|
+
|
|
16
|
+
### Features
|
|
17
|
+
* **PBKDF2-SHA256 Cryptography**: Fast, unboxed 32-bit integer arithmetic optimized for mobile (Hermes) and hardware-accelerated WebCrypto on Web.
|
|
18
|
+
* **Cryptographic Salting**: 16-byte (128-bit) secure random salt per user to prevent rainbow table attacks.
|
|
19
|
+
* **Timing-Attack Protection**: Constant-time byte comparisons (`timingSafeEqual`) and dummy verification for non-existent accounts.
|
|
20
|
+
* **Brute-Force Lockout**: Automatically locks accounts after consecutive failed attempts for a configurable duration.
|
|
21
|
+
* **Single-Use Reset Tokens**: 32-byte high-entropy tokens with SHA-256 storage and automated expiration.
|
|
22
|
+
* **Offline Sessions**: Integrated with `SessionManager` for persistent multi-device or single-device offline session lifecycles.
|
|
23
|
+
|
|
24
|
+
---
|
|
25
|
+
|
|
26
|
+
## 2. Configuration
|
|
27
|
+
|
|
28
|
+
Configure local auth directly in `defineSyncConfig`:
|
|
29
|
+
|
|
30
|
+
```typescript
|
|
31
|
+
import { defineSyncConfig } from 'local-lite/config';
|
|
32
|
+
|
|
33
|
+
export const syncConfig = defineSyncConfig({
|
|
34
|
+
database: () => SQLite.openDatabaseAsync('app.db'),
|
|
35
|
+
tables: ['tasks'],
|
|
36
|
+
localAuth: {
|
|
37
|
+
// Optional table names (defaults: '_local_users', '_local_user_tokens')
|
|
38
|
+
usersTable: '_local_users',
|
|
39
|
+
tokensTable: '_local_user_tokens',
|
|
40
|
+
|
|
41
|
+
// Password requirements & validation
|
|
42
|
+
minPasswordLength: 8,
|
|
43
|
+
validatePassword: (password: string) => {
|
|
44
|
+
if (!/[0-9]/.test(password)) return 'Password must include at least one number.';
|
|
45
|
+
return true;
|
|
46
|
+
},
|
|
47
|
+
|
|
48
|
+
// Brute-force lockout protection
|
|
49
|
+
maxFailedAttempts: 5, // Set to 0 to disable
|
|
50
|
+
lockoutDurationMs: 15 * 60 * 1000, // 15 minutes
|
|
51
|
+
|
|
52
|
+
// Password reset token expiration
|
|
53
|
+
resetTokenExpiryMs: 60 * 60 * 1000, // 1 hour
|
|
54
|
+
|
|
55
|
+
// Tuning (defaults: 'PBKDF2-SHA256' with 1,000 rounds)
|
|
56
|
+
algorithm: 'PBKDF2-SHA256',
|
|
57
|
+
iterations: 1_000,
|
|
58
|
+
},
|
|
59
|
+
});
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
---
|
|
63
|
+
|
|
64
|
+
## 3. Using `useLocalAuth` in React / React Native
|
|
65
|
+
|
|
66
|
+
The `useLocalAuth` hook exposes reactive user state, active session info, and authentication actions:
|
|
67
|
+
|
|
68
|
+
```tsx
|
|
69
|
+
import React, { useState } from 'react';
|
|
70
|
+
import { View, Text, TextInput, Button, Alert } from 'react-native';
|
|
71
|
+
import { useLocalAuth } from 'local-lite/react';
|
|
72
|
+
import { getSyncClient } from './sync.config';
|
|
73
|
+
|
|
74
|
+
export function AuthScreen() {
|
|
75
|
+
const [client, setClient] = useState(null);
|
|
76
|
+
React.useEffect(() => { getSyncClient().then(setClient); }, []);
|
|
77
|
+
|
|
78
|
+
const {
|
|
79
|
+
user,
|
|
80
|
+
session,
|
|
81
|
+
isSignedIn,
|
|
82
|
+
loading,
|
|
83
|
+
error,
|
|
84
|
+
signIn,
|
|
85
|
+
signUp,
|
|
86
|
+
signOut,
|
|
87
|
+
refetchUser,
|
|
88
|
+
} = useLocalAuth(client?.auth);
|
|
89
|
+
|
|
90
|
+
const [email, setEmail] = useState('');
|
|
91
|
+
const [password, setPassword] = useState('');
|
|
92
|
+
|
|
93
|
+
if (isSignedIn && user) {
|
|
94
|
+
return (
|
|
95
|
+
<View>
|
|
96
|
+
<Text>Welcome, {user.displayName || user.email}!</Text>
|
|
97
|
+
<Text>Role: {user.role}</Text>
|
|
98
|
+
<Text>Session ID: {session?.id}</Text>
|
|
99
|
+
<Button title="Sign Out" onPress={() => signOut()} />
|
|
100
|
+
</View>
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return (
|
|
105
|
+
<View>
|
|
106
|
+
<TextInput placeholder="Email" value={email} onChangeText={setEmail} autoCapitalize="none" />
|
|
107
|
+
<TextInput placeholder="Password" value={password} onChangeText={setPassword} secureTextEntry />
|
|
108
|
+
|
|
109
|
+
<Button
|
|
110
|
+
title={loading ? 'Processing...' : 'Sign In'}
|
|
111
|
+
onPress={() => signIn(email, password).catch(err => Alert.alert('Error', err.message))}
|
|
112
|
+
disabled={loading}
|
|
113
|
+
/>
|
|
114
|
+
<Button
|
|
115
|
+
title="Register New Account"
|
|
116
|
+
onPress={() =>
|
|
117
|
+
signUp({
|
|
118
|
+
email,
|
|
119
|
+
password,
|
|
120
|
+
displayName: 'Alice',
|
|
121
|
+
role: 'admin',
|
|
122
|
+
metadata: { theme: 'dark' },
|
|
123
|
+
}).catch(err => Alert.alert('Error', err.message))
|
|
124
|
+
}
|
|
125
|
+
/>
|
|
126
|
+
</View>
|
|
127
|
+
);
|
|
128
|
+
}
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
---
|
|
132
|
+
|
|
133
|
+
## 4. Password Management & Cryptographic Resets
|
|
134
|
+
|
|
135
|
+
### Changing Passwords (User Authenticated)
|
|
136
|
+
```typescript
|
|
137
|
+
await client.auth.changePassword({
|
|
138
|
+
userId: user.id,
|
|
139
|
+
oldPassword: 'OldPassword123!',
|
|
140
|
+
newPassword: 'NewPassword456!',
|
|
141
|
+
});
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
### Password Reset Flow (Forgot Password)
|
|
145
|
+
```typescript
|
|
146
|
+
// 1. Generate a single-use 32-byte reset token (expires in 1 hour)
|
|
147
|
+
const { token, expiresAt } = await client.auth.createPasswordResetToken('user@example.com');
|
|
148
|
+
|
|
149
|
+
// 2. Deliver token to user via local notification, SMS, or QR code
|
|
150
|
+
|
|
151
|
+
// 3. User submits the token with their new password
|
|
152
|
+
await client.auth.resetPasswordWithToken(token, 'NewStrongPassword789!');
|
|
153
|
+
// The token is permanently invalidated in SQLite and the account is unlocked.
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
---
|
|
157
|
+
|
|
158
|
+
## 5. OAuth Providers & Cloud Auth
|
|
159
|
+
|
|
160
|
+
`local-lite/auth` also includes standalone OAuth clients and hooks for external identity providers:
|
|
161
|
+
|
|
162
|
+
### Google OAuth
|
|
163
|
+
```typescript
|
|
164
|
+
import { GoogleAuthClient } from 'local-lite/auth';
|
|
165
|
+
import { useGoogleAuth } from 'local-lite/react';
|
|
166
|
+
|
|
167
|
+
const googleClient = new GoogleAuthClient({
|
|
168
|
+
clientId: 'YOUR_GOOGLE_CLIENT_ID',
|
|
169
|
+
redirectUri: 'YOUR_REDIRECT_URI',
|
|
170
|
+
scopes: ['openid', 'profile', 'email'],
|
|
171
|
+
authorize: async (req) => { /* invoke browser or WebBrowser.openAuthSessionAsync */ },
|
|
172
|
+
});
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
### Microsoft OAuth & OneDrive
|
|
176
|
+
```typescript
|
|
177
|
+
import { MicrosoftAuthClient } from 'local-lite/auth';
|
|
178
|
+
|
|
179
|
+
const msClient = new MicrosoftAuthClient({
|
|
180
|
+
clientId: 'YOUR_MS_CLIENT_ID',
|
|
181
|
+
redirectUri: 'YOUR_REDIRECT_URI',
|
|
182
|
+
scopes: ['openid', 'profile', 'User.Read', 'Files.ReadWrite.AppFolder'],
|
|
183
|
+
authorize: async (req) => { /* invoke browser */ },
|
|
184
|
+
});
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
### Apple & GitHub OAuth
|
|
188
|
+
Clients are available via `AppleAuthClient` and `GitHubAuthClient` with matching React hooks (`useAppleAuth`, `useGitHubAuth`).
|
|
189
|
+
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: local-lite-backups
|
|
3
|
+
description: Implement cloud backups, AES-256-GCM database encryption, and restore operations in local-lite. Use when configuring OneDrive or Google Drive backups, encrypted SQLite backups with passphrases, backup progress hooks, or useCloudBackup / useOneDriveBackup.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# local-lite Backups & Encryption
|
|
7
|
+
|
|
8
|
+
Comprehensive guide for creating, encrypting, and restoring SQLite database backups to Microsoft OneDrive and Google Drive.
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## 1. Cloud Backup Providers
|
|
13
|
+
|
|
14
|
+
`local-lite/backups` provides dedicated clients for user-owned cloud drives. Backups are stored in an application-scoped folder (`approot:/backups/` on OneDrive, `appDataFolder` on Google Drive), so the user retains full ownership of their data.
|
|
15
|
+
|
|
16
|
+
### Supported Providers
|
|
17
|
+
* **Microsoft OneDrive**: `OneDriveBackupClient` (uses Microsoft Graph API).
|
|
18
|
+
* **Google Drive**: `GoogleDriveBackupClient` (uses Google Drive v3 REST API).
|
|
19
|
+
|
|
20
|
+
---
|
|
21
|
+
|
|
22
|
+
## 2. Setting Up Cloud Backups
|
|
23
|
+
|
|
24
|
+
### OneDrive Backup Setup
|
|
25
|
+
```typescript
|
|
26
|
+
import { OneDriveBackupClient } from 'local-lite/backups';
|
|
27
|
+
import { MicrosoftAuthClient } from 'local-lite/auth';
|
|
28
|
+
|
|
29
|
+
// 1. Create or reuse your Microsoft Auth Client
|
|
30
|
+
const authClient = new MicrosoftAuthClient({
|
|
31
|
+
clientId: process.env.EXPO_PUBLIC_MS_CLIENT_ID!,
|
|
32
|
+
redirectUri: 'myapp://auth',
|
|
33
|
+
scopes: ['openid', 'profile', 'Files.ReadWrite.AppFolder'],
|
|
34
|
+
authorize: async (req) => { /* Expo WebBrowser session */ },
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
// 2. Instantiate OneDriveBackupClient
|
|
38
|
+
export const oneDriveClient = new OneDriveBackupClient({
|
|
39
|
+
authClient,
|
|
40
|
+
});
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
### Google Drive Backup Setup
|
|
44
|
+
```typescript
|
|
45
|
+
import { GoogleDriveBackupClient } from 'local-lite/backups';
|
|
46
|
+
import { GoogleAuthClient } from 'local-lite/auth';
|
|
47
|
+
|
|
48
|
+
const authClient = new GoogleAuthClient({
|
|
49
|
+
clientId: process.env.EXPO_PUBLIC_GOOGLE_CLIENT_ID!,
|
|
50
|
+
redirectUri: 'myapp://auth',
|
|
51
|
+
scopes: ['https://www.googleapis.com/auth/drive.appdata'],
|
|
52
|
+
authorize: async (req) => { /* Expo WebBrowser session */ },
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
export const googleDriveClient = new GoogleDriveBackupClient({
|
|
56
|
+
authClient,
|
|
57
|
+
});
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
---
|
|
61
|
+
|
|
62
|
+
## 3. Creating & Restoring Backups
|
|
63
|
+
|
|
64
|
+
### Manual Backup Operation
|
|
65
|
+
```typescript
|
|
66
|
+
import { getSyncClient } from './sync.config';
|
|
67
|
+
|
|
68
|
+
const client = await getSyncClient();
|
|
69
|
+
|
|
70
|
+
// Upload current database snapshot to cloud
|
|
71
|
+
const result = await oneDriveClient.backup(client.db, {
|
|
72
|
+
fileName: `backup-${Date.now()}.db`,
|
|
73
|
+
});
|
|
74
|
+
console.log('Uploaded backup:', result.name, result.size);
|
|
75
|
+
|
|
76
|
+
// List available cloud backups
|
|
77
|
+
const files = await oneDriveClient.list();
|
|
78
|
+
|
|
79
|
+
// Restore from a specific backup file
|
|
80
|
+
await oneDriveClient.restore(client.db, files[0].id);
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
---
|
|
84
|
+
|
|
85
|
+
## 4. End-to-End Database Encryption (AES-256-GCM)
|
|
86
|
+
|
|
87
|
+
For maximum privacy, encrypt the SQLite database snapshot with an end-user passphrase before it leaves the device:
|
|
88
|
+
|
|
89
|
+
```typescript
|
|
90
|
+
// 1. Encrypted Backup
|
|
91
|
+
await oneDriveClient.backup(client.db, {
|
|
92
|
+
fileName: `encrypted-backup-${Date.now()}.db`,
|
|
93
|
+
passphrase: 'UserSecretPassphrase123!',
|
|
94
|
+
// Uses PBKDF2 key derivation and AES-256-GCM authenticated encryption
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
// 2. Encrypted Restore
|
|
98
|
+
await oneDriveClient.restore(client.db, files[0].id, {
|
|
99
|
+
passphrase: 'UserSecretPassphrase123!',
|
|
100
|
+
});
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
If the passphrase is incorrect or the backup payload has been tampered with, AES-256-GCM authentication fails immediately and protects the local database from corruption.
|
|
104
|
+
|
|
105
|
+
---
|
|
106
|
+
|
|
107
|
+
## 5. React Integration (`useCloudBackup`)
|
|
108
|
+
|
|
109
|
+
Use the `useCloudBackup` (or `useOneDriveBackup` / `useGoogleDriveBackup`) hook for reactive backup management:
|
|
110
|
+
|
|
111
|
+
```tsx
|
|
112
|
+
import React from 'react';
|
|
113
|
+
import { View, Text, Button, ActivityIndicator } from 'react-native';
|
|
114
|
+
import { useOneDriveBackup } from 'local-lite/react';
|
|
115
|
+
import { oneDriveClient } from './backup.config';
|
|
116
|
+
import { getSyncClient } from './sync.config';
|
|
117
|
+
|
|
118
|
+
export function BackupScreen() {
|
|
119
|
+
const [client, setClient] = React.useState(null);
|
|
120
|
+
React.useEffect(() => { getSyncClient().then(setClient); }, []);
|
|
121
|
+
|
|
122
|
+
const {
|
|
123
|
+
connected,
|
|
124
|
+
files,
|
|
125
|
+
isBackingUp,
|
|
126
|
+
isRestoring,
|
|
127
|
+
progress,
|
|
128
|
+
backup,
|
|
129
|
+
restore,
|
|
130
|
+
refreshFiles,
|
|
131
|
+
connect,
|
|
132
|
+
} = useOneDriveBackup(oneDriveClient, client?.db);
|
|
133
|
+
|
|
134
|
+
if (!connected) {
|
|
135
|
+
return <Button title="Connect to OneDrive" onPress={() => connect()} />;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
return (
|
|
139
|
+
<View>
|
|
140
|
+
<Text>Cloud Backups ({files.length} available)</Text>
|
|
141
|
+
|
|
142
|
+
{isBackingUp && <Text>Backing up: {progress}%</Text>}
|
|
143
|
+
{isRestoring && <Text>Restoring: {progress}%</Text>}
|
|
144
|
+
|
|
145
|
+
<Button
|
|
146
|
+
title="Create Encrypted Backup"
|
|
147
|
+
onPress={() => backup({ passphrase: 'MySecretPassphrase!' })}
|
|
148
|
+
disabled={isBackingUp || isRestoring}
|
|
149
|
+
/>
|
|
150
|
+
|
|
151
|
+
{files.map((file) => (
|
|
152
|
+
<View key={file.id}>
|
|
153
|
+
<Text>{file.name} ({(file.size / 1024).toFixed(1)} KB)</Text>
|
|
154
|
+
<Button
|
|
155
|
+
title="Restore"
|
|
156
|
+
onPress={() => restore(file.id, { passphrase: 'MySecretPassphrase!' })}
|
|
157
|
+
/>
|
|
158
|
+
</View>
|
|
159
|
+
))}
|
|
160
|
+
</View>
|
|
161
|
+
);
|
|
162
|
+
}
|
|
163
|
+
```
|
|
164
|
+
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: local-lite-offline-actions
|
|
3
|
+
description: Queue offline actions, schedule background jobs, store key-value preferences, and track sync telemetry in local-lite. Use when using client.actions, client.scheduler, client.kv, client.getMetrics(), or handling offline mutation retries.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# local-lite Offline Actions, KV & Scheduler
|
|
7
|
+
|
|
8
|
+
Guide for executing queued actions, running background jobs, persisting key-value pairs, and inspecting sync telemetry with `local-lite`.
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## 1. Action Manager & Outbox (`client.actions`)
|
|
13
|
+
|
|
14
|
+
The Action Manager handles complex business logic mutations that must be queued offline and executed reliably when connectivity is restored:
|
|
15
|
+
|
|
16
|
+
### Enqueueing an Action
|
|
17
|
+
```typescript
|
|
18
|
+
import { getSyncClient } from './sync.config';
|
|
19
|
+
|
|
20
|
+
const client = await getSyncClient();
|
|
21
|
+
|
|
22
|
+
// Enqueue an action (e.g. sending an email, processing a payment, or syncing with third-party API)
|
|
23
|
+
const action = await client.actions.enqueue({
|
|
24
|
+
type: 'SEND_INVITATION',
|
|
25
|
+
payload: {
|
|
26
|
+
inviteeEmail: 'colleague@example.com',
|
|
27
|
+
teamId: 'team_xyz',
|
|
28
|
+
},
|
|
29
|
+
maxRetries: 5,
|
|
30
|
+
retryDelayMs: 2000,
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
console.log('Queued action:', action.id, action.status);
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
### Registering Action Handlers
|
|
37
|
+
Register handlers that execute when the device is online:
|
|
38
|
+
|
|
39
|
+
```typescript
|
|
40
|
+
client.actions.registerHandler('SEND_INVITATION', async (payload) => {
|
|
41
|
+
const res = await fetch('https://api.example.com/invites', {
|
|
42
|
+
method: 'POST',
|
|
43
|
+
headers: { 'Content-Type': 'application/json' },
|
|
44
|
+
body: JSON.stringify(payload),
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
if (!res.ok) {
|
|
48
|
+
throw new Error(`Invitation failed with status ${res.status}`);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
return await res.json();
|
|
52
|
+
});
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
---
|
|
56
|
+
|
|
57
|
+
## 2. Key-Value Store & Secret Preferences (`client.kv`)
|
|
58
|
+
|
|
59
|
+
`client.kv` provides lightweight key-value storage directly within SQLite with optional TTL expiration and AES-256-GCM encryption.
|
|
60
|
+
|
|
61
|
+
### Basic KV Usage
|
|
62
|
+
```typescript
|
|
63
|
+
// Store with optional TTL (expires in 24 hours)
|
|
64
|
+
await client.kv.set('last_viewed_tab', 'dashboard', { ttlMs: 24 * 60 * 60 * 1000 });
|
|
65
|
+
|
|
66
|
+
// Read value (returns null if expired or missing)
|
|
67
|
+
const tab = await client.kv.get('last_viewed_tab');
|
|
68
|
+
|
|
69
|
+
// Delete value
|
|
70
|
+
await client.kv.delete('last_viewed_tab');
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
### Encrypted Secrets (AES-256-GCM)
|
|
74
|
+
Store sensitive API tokens or user secrets securely:
|
|
75
|
+
|
|
76
|
+
```typescript
|
|
77
|
+
// Encrypt and persist
|
|
78
|
+
await client.kv.setSecret('api_token', 'sk-live-secret-token-12345', 'PassphraseOrHardwareKey');
|
|
79
|
+
|
|
80
|
+
// Decrypt
|
|
81
|
+
const token = await client.kv.getSecret('api_token', 'PassphraseOrHardwareKey');
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
---
|
|
85
|
+
|
|
86
|
+
## 3. Background Job Scheduler (`client.scheduler`)
|
|
87
|
+
|
|
88
|
+
Schedule recurring cron-style or interval jobs that run within your application:
|
|
89
|
+
|
|
90
|
+
```typescript
|
|
91
|
+
// Register a recurring maintenance task
|
|
92
|
+
client.scheduler.registerJob({
|
|
93
|
+
name: 'CLEANUP_OLD_LOGS',
|
|
94
|
+
intervalMs: 60 * 60 * 1000, // Run every hour
|
|
95
|
+
runImmediately: false,
|
|
96
|
+
handler: async () => {
|
|
97
|
+
const oneWeekAgo = Date.now() - 7 * 24 * 60 * 60 * 1000;
|
|
98
|
+
await client.db.execute('DELETE FROM activity_logs WHERE created_at < ?;', [oneWeekAgo]);
|
|
99
|
+
console.log('Old activity logs purged.');
|
|
100
|
+
},
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
// Start scheduler execution
|
|
104
|
+
client.scheduler.start();
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
---
|
|
108
|
+
|
|
109
|
+
## 4. Sync Telemetry & Health Metrics (`client.getMetrics()`)
|
|
110
|
+
|
|
111
|
+
Monitor the health of your local-first sync pipeline in real time:
|
|
112
|
+
|
|
113
|
+
```typescript
|
|
114
|
+
const metrics = await client.getMetrics();
|
|
115
|
+
|
|
116
|
+
console.log('Outbox Queue Size:', metrics.outboxPendingCount);
|
|
117
|
+
console.log('Total Pushes Succeeded:', metrics.pushesSuccessCount);
|
|
118
|
+
console.log('Total Pushes Failed:', metrics.pushesFailedCount);
|
|
119
|
+
console.log('Average Push Latency:', metrics.avgPushDurationMs, 'ms');
|
|
120
|
+
console.log('Last Sync Timestamp:', new Date(metrics.lastSyncAt).toLocaleTimeString());
|
|
121
|
+
```
|
|
122
|
+
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: local-lite-react
|
|
3
|
+
description: Master reactive patterns, hooks, live queries, and optimistic state in React and React Native with local-lite. Use when writing useLiveQuery, useSyncStatus, useLocalAuth, useKV, useSearch, useQueryBuilder, or optimizing component re-renders.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# local-lite React & React Native Integration
|
|
7
|
+
|
|
8
|
+
Comprehensive guide to building reactive, offline-first user interfaces using `local-lite/react`.
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## 1. Core Hooks Overview
|
|
13
|
+
|
|
14
|
+
| Hook | Purpose |
|
|
15
|
+
| :--- | :--- |
|
|
16
|
+
| `useLiveQuery(client, sql, params, deps)` | Reactive SQLite query. Auto-re-runs whenever relevant tables mutate. |
|
|
17
|
+
| `useSyncStatus(client)` | Tracks online/offline status, sync worker state, and outbox changes. |
|
|
18
|
+
| `useLocalAuth(client.auth)` | Manages zero-backend SQLite authentication, user profiles, and sessions. |
|
|
19
|
+
| `useKV(client.kv, key, default)` | Reactive key-value store for preferences and application state. |
|
|
20
|
+
| `useEncryptedKV(client.kv, key, pass)` | End-to-end encrypted secret preferences with AES-256-GCM. |
|
|
21
|
+
| `useSearch(client, ftsTable, query)` | Real-time full-text search powered by SQLite FTS5. |
|
|
22
|
+
| `useQueryBuilder(client, table, filter)` | Declarative MongoDB-style query filters. |
|
|
23
|
+
| `useCloudBackup(backupClient, db)` | Cloud backups (OneDrive / Google Drive) with live progress. |
|
|
24
|
+
|
|
25
|
+
---
|
|
26
|
+
|
|
27
|
+
## 2. Live Queries (`useLiveQuery`)
|
|
28
|
+
|
|
29
|
+
`useLiveQuery` executes raw SQLite queries and re-runs them reactively when affected tables change:
|
|
30
|
+
|
|
31
|
+
```tsx
|
|
32
|
+
import React, { useMemo } from 'react';
|
|
33
|
+
import { FlatList, Text, View } from 'react-native';
|
|
34
|
+
import { useLiveQuery } from 'local-lite/react';
|
|
35
|
+
import type { LocalFirstClient } from 'local-lite/config';
|
|
36
|
+
|
|
37
|
+
interface Todo {
|
|
38
|
+
id: string;
|
|
39
|
+
title: string;
|
|
40
|
+
completed: number;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function TodoList({ client, projectId }: { client: LocalFirstClient; projectId: string }) {
|
|
44
|
+
// Always memoize params to prevent unnecessary query executions
|
|
45
|
+
const params = useMemo(() => [projectId], [projectId]);
|
|
46
|
+
|
|
47
|
+
const { data: todos, loading, error, refetch } = useLiveQuery<Todo>(
|
|
48
|
+
client,
|
|
49
|
+
'SELECT * FROM todos WHERE project_id = ? ORDER BY updated_at DESC;',
|
|
50
|
+
params
|
|
51
|
+
);
|
|
52
|
+
|
|
53
|
+
if (loading) return <Text>Loading...</Text>;
|
|
54
|
+
if (error) return <Text>Query error: {error.message}</Text>;
|
|
55
|
+
|
|
56
|
+
return (
|
|
57
|
+
<FlatList
|
|
58
|
+
data={todos}
|
|
59
|
+
keyExtractor={(item) => item.id}
|
|
60
|
+
renderItem={({ item }) => (
|
|
61
|
+
<Text style={{ textDecorationLine: item.completed ? 'line-through' : 'none' }}>
|
|
62
|
+
{item.title}
|
|
63
|
+
</Text>
|
|
64
|
+
)}
|
|
65
|
+
/>
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
---
|
|
71
|
+
|
|
72
|
+
## 3. Optimistic 0ms Writes (`client.mutate`)
|
|
73
|
+
|
|
74
|
+
For zero-latency user experiences, perform writes using `client.mutate()`. This writes directly to local SQLite in an atomic transaction and automatically triggers all matching `useLiveQuery` hooks across the UI:
|
|
75
|
+
|
|
76
|
+
```tsx
|
|
77
|
+
import { generateUUID } from 'local-lite';
|
|
78
|
+
|
|
79
|
+
async function addTodo(client: LocalFirstClient, title: string, projectId: string) {
|
|
80
|
+
const newTodo = {
|
|
81
|
+
id: generateUUID(),
|
|
82
|
+
project_id: projectId,
|
|
83
|
+
title,
|
|
84
|
+
completed: 0,
|
|
85
|
+
updated_at: Date.now(),
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
// 1. Dual-writes to local SQLite and queues in outbox for sync
|
|
89
|
+
await client.mutate('todos', 'INSERT', newTodo);
|
|
90
|
+
// All useLiveQuery hooks listening to 'todos' update instantly (0ms)!
|
|
91
|
+
}
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
---
|
|
95
|
+
|
|
96
|
+
## 4. Reactive Preferences & Encrypted KV
|
|
97
|
+
|
|
98
|
+
```tsx
|
|
99
|
+
import { useKV, useEncryptedKV } from 'local-lite/react';
|
|
100
|
+
|
|
101
|
+
export function SettingsScreen({ client }) {
|
|
102
|
+
// 1. Plain reactive setting
|
|
103
|
+
const [theme, setTheme] = useKV<'light' | 'dark'>(client?.kv, 'app_theme', 'light');
|
|
104
|
+
|
|
105
|
+
// 2. Encrypted setting (AES-256-GCM)
|
|
106
|
+
const [apiKey, setApiKey] = useEncryptedKV(client?.kv, 'openai_key', 'UserPassphrase!');
|
|
107
|
+
|
|
108
|
+
return (
|
|
109
|
+
<View>
|
|
110
|
+
<Text>Theme: {theme}</Text>
|
|
111
|
+
<Button title="Toggle Theme" onPress={() => setTheme(theme === 'light' ? 'dark' : 'light')} />
|
|
112
|
+
</View>
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
---
|
|
118
|
+
|
|
119
|
+
## 5. Performance Best Practices
|
|
120
|
+
|
|
121
|
+
1. **Memoize Query Parameters**: Pass memoized arrays or primitives to `useLiveQuery` to avoid re-triggering queries on every parent component render.
|
|
122
|
+
2. **Selective Column Projections**: In high-frequency queries, select only required columns (`SELECT id, title FROM ...`) instead of `SELECT *` to reduce SQLite serialization overhead.
|
|
123
|
+
3. **Batch Mutations**: Wrap bulk inserts in transactions or `client.mutateBatch()` rather than issuing individual `INSERT` statements in loops.
|
|
124
|
+
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: local-lite-schema
|
|
3
|
+
description: Design schemas, write migrations, configure cascading deletions, and build queries in local-lite. Use when defining foreign key relationships with onDelete (cascade, restrict, setNull), writing schemaMigrations, enabling touchUpdatedAt, setting up SQLite FTS5 search, or using query operators.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# local-lite Schema, Migrations & Queries
|
|
7
|
+
|
|
8
|
+
Guide for schema design, migrations, relationship management, and query execution in `local-lite`.
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## 1. Schema Conventions
|
|
13
|
+
|
|
14
|
+
Every synchronized table in `local-lite` requires two mandatory columns:
|
|
15
|
+
* `id TEXT PRIMARY KEY`: Typically an RFC4122 v4 UUID generated via `generateUUID()`.
|
|
16
|
+
* `updated_at INTEGER NOT NULL`: Epoch millisecond timestamp (`Date.now()`).
|
|
17
|
+
|
|
18
|
+
```sql
|
|
19
|
+
CREATE TABLE IF NOT EXISTS projects (
|
|
20
|
+
id TEXT PRIMARY KEY,
|
|
21
|
+
name TEXT NOT NULL,
|
|
22
|
+
created_at INTEGER NOT NULL,
|
|
23
|
+
updated_at INTEGER NOT NULL
|
|
24
|
+
);
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
---
|
|
28
|
+
|
|
29
|
+
## 2. Foreign Key Relationships & Cascading Deletions (`onDelete`)
|
|
30
|
+
|
|
31
|
+
Configure declarative relationship metadata directly in your client configuration so deletions automatically cascade or enforce integrity:
|
|
32
|
+
|
|
33
|
+
```typescript
|
|
34
|
+
import { defineSyncConfig } from 'local-lite/config';
|
|
35
|
+
|
|
36
|
+
export const syncConfig = defineSyncConfig({
|
|
37
|
+
database: () => SQLite.openDatabaseAsync('app.db'),
|
|
38
|
+
tables: ['projects', 'tasks', 'comments'],
|
|
39
|
+
|
|
40
|
+
relationships: [
|
|
41
|
+
{
|
|
42
|
+
parentTable: 'projects',
|
|
43
|
+
childTable: 'tasks',
|
|
44
|
+
foreignKey: 'project_id',
|
|
45
|
+
onDelete: 'cascade', // When a project is deleted, all its tasks are deleted
|
|
46
|
+
},
|
|
47
|
+
{
|
|
48
|
+
parentTable: 'tasks',
|
|
49
|
+
childTable: 'comments',
|
|
50
|
+
foreignKey: 'task_id',
|
|
51
|
+
onDelete: 'cascade', // Cascades down multiple levels
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
parentTable: 'users',
|
|
55
|
+
childTable: 'tasks',
|
|
56
|
+
foreignKey: 'assignee_id',
|
|
57
|
+
onDelete: 'setNull', // Sets task.assignee_id = NULL if user is removed
|
|
58
|
+
},
|
|
59
|
+
],
|
|
60
|
+
});
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
### Supported `onDelete` Actions:
|
|
64
|
+
* `'cascade'`: Deletes all matching child records when the parent record is deleted.
|
|
65
|
+
* `'restrict'`: Throws an error preventing parent deletion if child records exist.
|
|
66
|
+
* `'setNull'`: Updates the foreign key column on child records to `NULL`.
|
|
67
|
+
* `'noAction'`: Leaves child records intact without performing automated changes.
|
|
68
|
+
|
|
69
|
+
---
|
|
70
|
+
|
|
71
|
+
## 3. Schema Migrations (`schemaMigrations`)
|
|
72
|
+
|
|
73
|
+
Migrations are managed via the append-only `schemaMigrations` array. Applied versions are tracked in SQLite in the `_migrations` internal table.
|
|
74
|
+
|
|
75
|
+
```typescript
|
|
76
|
+
schemaMigrations: [
|
|
77
|
+
{
|
|
78
|
+
version: 1,
|
|
79
|
+
up: [
|
|
80
|
+
`CREATE TABLE IF NOT EXISTS users (
|
|
81
|
+
id TEXT PRIMARY KEY,
|
|
82
|
+
email TEXT NOT NULL,
|
|
83
|
+
updated_at INTEGER NOT NULL
|
|
84
|
+
);`,
|
|
85
|
+
],
|
|
86
|
+
},
|
|
87
|
+
{
|
|
88
|
+
version: 2,
|
|
89
|
+
up: [
|
|
90
|
+
// Add a column or index in a new version
|
|
91
|
+
`ALTER TABLE users ADD COLUMN display_name TEXT;`,
|
|
92
|
+
`CREATE INDEX IF NOT EXISTS idx_users_email ON users(email);`,
|
|
93
|
+
],
|
|
94
|
+
},
|
|
95
|
+
]
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
### Rules:
|
|
99
|
+
1. **Never edit an applied migration**: Modifying an existing migration version causes version drift. Always append a new `{ version: N + 1, up: [...] }`.
|
|
100
|
+
2. **Idempotence**: Prefer `IF NOT EXISTS` for table and index creation.
|
|
101
|
+
|
|
102
|
+
---
|
|
103
|
+
|
|
104
|
+
## 4. Automatic Timestamp Maintenance (`touchUpdatedAt`)
|
|
105
|
+
|
|
106
|
+
Ensure `updated_at` timestamps are always refreshed on every write by enabling `touchUpdatedAt`:
|
|
107
|
+
|
|
108
|
+
```typescript
|
|
109
|
+
export const syncConfig = defineSyncConfig({
|
|
110
|
+
// Automatically updates updated_at on all mutations
|
|
111
|
+
touchUpdatedAt: true,
|
|
112
|
+
|
|
113
|
+
// Or customize the timestamp column name
|
|
114
|
+
// touchUpdatedAt: 'modified_at',
|
|
115
|
+
});
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
---
|
|
119
|
+
|
|
120
|
+
## 5. Full-Text Search (SQLite FTS5)
|
|
121
|
+
|
|
122
|
+
Enable lightning-fast full-text search using SQLite's FTS5 virtual tables:
|
|
123
|
+
|
|
124
|
+
```typescript
|
|
125
|
+
// 1. Create the FTS5 virtual table in a schema migration
|
|
126
|
+
schemaMigrations: [
|
|
127
|
+
{
|
|
128
|
+
version: 3,
|
|
129
|
+
up: [
|
|
130
|
+
`CREATE VIRTUAL TABLE IF NOT EXISTS notes_fts USING fts5(
|
|
131
|
+
title,
|
|
132
|
+
content,
|
|
133
|
+
content='notes',
|
|
134
|
+
content_rowid='rowid'
|
|
135
|
+
);`,
|
|
136
|
+
],
|
|
137
|
+
},
|
|
138
|
+
]
|
|
139
|
+
|
|
140
|
+
// 2. Perform searches using client.search()
|
|
141
|
+
const results = await client.search('notes_fts', 'react native offline');
|
|
142
|
+
|
|
143
|
+
// 3. Or use the reactive React hook:
|
|
144
|
+
const { results, isSearching } = useSearch(client, 'notes_fts', searchQuery);
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
---
|
|
148
|
+
|
|
149
|
+
## 6. Query Builder & Complex Operators
|
|
150
|
+
|
|
151
|
+
Execute filtered queries with MongoDB-like declarative operators using `queryBuilder` or `useQueryBuilder`:
|
|
152
|
+
|
|
153
|
+
```typescript
|
|
154
|
+
const tasks = await client.query('tasks', {
|
|
155
|
+
status: { $in: ['todo', 'in_progress'] },
|
|
156
|
+
priority: { $gte: 2 },
|
|
157
|
+
title: { $like: '%release%' },
|
|
158
|
+
}, {
|
|
159
|
+
orderBy: { updated_at: 'DESC' },
|
|
160
|
+
limit: 20,
|
|
161
|
+
});
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
### Supported Operators:
|
|
165
|
+
* `$eq`, `$ne`: Equal, Not Equal
|
|
166
|
+
* `$gt`, `$gte`: Greater Than, Greater Than or Equal
|
|
167
|
+
* `$lt`, `$lte`: Less Than, Less Than or Equal
|
|
168
|
+
* `$in`, `$nin`: In Array, Not In Array
|
|
169
|
+
* `$like`: SQL LIKE pattern matching
|
|
170
|
+
* `$null`: Is NULL or Not NULL (`{ deleted_at: { $null: true } }`)
|
|
171
|
+
|
|
@@ -1,21 +1,203 @@
|
|
|
1
|
-
---
|
|
2
|
-
name: local-lite-setup
|
|
3
|
-
description: Set up the local-lite local-first SQLite sync engine in a React / React Native / Expo / Node app. Use when adding local-lite, writing a sync config with defineSyncConfig, schemaMigrations,
|
|
4
|
-
---
|
|
5
|
-
|
|
6
|
-
# local-lite setup
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
1.
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
1
|
+
---
|
|
2
|
+
name: local-lite-setup
|
|
3
|
+
description: Set up the local-lite local-first SQLite sync engine in a React / React Native / Expo / Web / Node app. Use when adding local-lite, writing a sync config with defineSyncConfig, schemaMigrations, configuring local authentication, foreign key cascading deletions, cloud backups, or wiring useLiveQuery and useLocalAuth.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# local-lite setup
|
|
7
|
+
|
|
8
|
+
Guide for initializing and configuring `local-lite` across mobile (iOS/Android), web (React/SPA), and desktop/backend (Node.js/Electron).
|
|
9
|
+
|
|
10
|
+
## 1. Installation
|
|
11
|
+
|
|
12
|
+
Install `local-lite` and the appropriate SQLite driver for your target platform:
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
# Expo / React Native
|
|
16
|
+
npx expo install local-lite expo-sqlite
|
|
17
|
+
|
|
18
|
+
# Node.js / Electron / Desktop
|
|
19
|
+
npm install local-lite better-sqlite3 # or @libsql/client
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
If connecting to a remote backend, also install the matching client SDK:
|
|
23
|
+
* **Supabase**: `@supabase/supabase-js`
|
|
24
|
+
* **Convex**: `convex`
|
|
25
|
+
* **Firestore**: `firebase`
|
|
26
|
+
|
|
27
|
+
---
|
|
28
|
+
|
|
29
|
+
## 2. Platform Bundler Setup (Expo & Web)
|
|
30
|
+
|
|
31
|
+
If targeting **Expo Web**, configure `metro.config.js` to support WebAssembly SQLite (`wa-sqlite.wasm`) and avoid dual React resolutions in monorepos:
|
|
32
|
+
|
|
33
|
+
```javascript
|
|
34
|
+
// metro.config.js
|
|
35
|
+
const { getDefaultConfig } = require('expo/metro-config');
|
|
36
|
+
const path = require('path');
|
|
37
|
+
|
|
38
|
+
const config = getDefaultConfig(__dirname);
|
|
39
|
+
|
|
40
|
+
// Enable WebAssembly (.wasm) for expo-sqlite on the web
|
|
41
|
+
config.resolver.assetExts.push('wasm');
|
|
42
|
+
|
|
43
|
+
// Handle web vs native react-native module aliasing
|
|
44
|
+
config.resolver.resolveRequest = (context, moduleName, platform) => {
|
|
45
|
+
if (platform === 'web' && moduleName === 'react-native') {
|
|
46
|
+
return context.resolveRequest(context, 'react-native-web', platform);
|
|
47
|
+
}
|
|
48
|
+
return context.resolveRequest(context, moduleName, platform);
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
module.exports = config;
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
In `app.json`, set client-side single-page output for the web:
|
|
55
|
+
```json
|
|
56
|
+
{
|
|
57
|
+
"expo": {
|
|
58
|
+
"web": {
|
|
59
|
+
"output": "single"
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
---
|
|
66
|
+
|
|
67
|
+
## 3. Configuration (`sync.config.ts`)
|
|
68
|
+
|
|
69
|
+
Create a singleton client configuration with `defineSyncConfig` and `createSyncClient`:
|
|
70
|
+
|
|
71
|
+
```typescript
|
|
72
|
+
import * as SQLite from 'expo-sqlite';
|
|
73
|
+
import { defineSyncConfig, createSyncClient, type LocalFirstClient } from 'local-lite/config';
|
|
74
|
+
|
|
75
|
+
export const syncConfig = defineSyncConfig({
|
|
76
|
+
// 1. Local Database instance or factory
|
|
77
|
+
database: () => SQLite.openDatabaseAsync('app.db'),
|
|
78
|
+
|
|
79
|
+
// 2. Synced table names
|
|
80
|
+
tables: ['todos', 'projects'],
|
|
81
|
+
|
|
82
|
+
// 3. Schema Migrations (strictly append-only)
|
|
83
|
+
schemaMigrations: [
|
|
84
|
+
{
|
|
85
|
+
version: 1,
|
|
86
|
+
up: [
|
|
87
|
+
`CREATE TABLE IF NOT EXISTS projects (
|
|
88
|
+
id TEXT PRIMARY KEY,
|
|
89
|
+
name TEXT NOT NULL,
|
|
90
|
+
updated_at INTEGER NOT NULL
|
|
91
|
+
);`,
|
|
92
|
+
`CREATE TABLE IF NOT EXISTS todos (
|
|
93
|
+
id TEXT PRIMARY KEY,
|
|
94
|
+
project_id TEXT,
|
|
95
|
+
title TEXT NOT NULL,
|
|
96
|
+
completed INTEGER NOT NULL DEFAULT 0,
|
|
97
|
+
updated_at INTEGER NOT NULL
|
|
98
|
+
);`,
|
|
99
|
+
],
|
|
100
|
+
},
|
|
101
|
+
],
|
|
102
|
+
|
|
103
|
+
// 4. Foreign key relationships and cascading deletions
|
|
104
|
+
relationships: [
|
|
105
|
+
{
|
|
106
|
+
parentTable: 'projects',
|
|
107
|
+
childTable: 'todos',
|
|
108
|
+
foreignKey: 'project_id',
|
|
109
|
+
onDelete: 'cascade', // 'cascade' | 'restrict' | 'setNull' | 'noAction'
|
|
110
|
+
},
|
|
111
|
+
],
|
|
112
|
+
|
|
113
|
+
// 5. Automatic updated_at timestamp maintenance
|
|
114
|
+
touchUpdatedAt: true,
|
|
115
|
+
|
|
116
|
+
// 6. Zero-backend local SQLite authentication
|
|
117
|
+
localAuth: {
|
|
118
|
+
minPasswordLength: 8,
|
|
119
|
+
maxFailedAttempts: 5,
|
|
120
|
+
lockoutDurationMs: 15 * 60 * 1000, // 15 minutes
|
|
121
|
+
},
|
|
122
|
+
|
|
123
|
+
// 7. Remote Backend (choose one or omit for local-only)
|
|
124
|
+
// localOnly: true, // Set to true if not syncing to a remote server
|
|
125
|
+
supabase: {
|
|
126
|
+
url: process.env.EXPO_PUBLIC_SUPABASE_URL!,
|
|
127
|
+
anonKey: process.env.EXPO_PUBLIC_SUPABASE_ANON_KEY!,
|
|
128
|
+
},
|
|
129
|
+
|
|
130
|
+
// 8. Sync tuning
|
|
131
|
+
pushIntervalMs: 500,
|
|
132
|
+
pullIntervalMs: 5000,
|
|
133
|
+
conflictResolver: 'last-write-wins',
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
// Singleton client promise
|
|
137
|
+
let clientPromise: Promise<LocalFirstClient> | null = null;
|
|
138
|
+
export function getSyncClient(): Promise<LocalFirstClient> {
|
|
139
|
+
if (!clientPromise) {
|
|
140
|
+
clientPromise = createSyncClient(syncConfig);
|
|
141
|
+
}
|
|
142
|
+
return clientPromise;
|
|
143
|
+
}
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
---
|
|
147
|
+
|
|
148
|
+
## 4. Schema & Migration Rules
|
|
149
|
+
|
|
150
|
+
1. Every synced table **must** include:
|
|
151
|
+
* `id TEXT PRIMARY KEY`
|
|
152
|
+
* `updated_at INTEGER NOT NULL`
|
|
153
|
+
2. Never edit an applied migration. Always increment the `version` and append a new migration object to `schemaMigrations`.
|
|
154
|
+
3. Use `generateUUID()` from `local-lite` to create unique IDs.
|
|
155
|
+
|
|
156
|
+
---
|
|
157
|
+
|
|
158
|
+
## 5. React Integration
|
|
159
|
+
|
|
160
|
+
Use `local-lite/react` hooks for reactive data binding and local authentication:
|
|
161
|
+
|
|
162
|
+
```tsx
|
|
163
|
+
import React, { useState, useEffect } from 'react';
|
|
164
|
+
import { View, Text, Button } from 'react-native';
|
|
165
|
+
import { useLiveQuery, useSyncStatus, useLocalAuth } from 'local-lite/react';
|
|
166
|
+
import { getSyncClient } from './sync.config';
|
|
167
|
+
import type { LocalFirstClient } from 'local-lite/config';
|
|
168
|
+
|
|
169
|
+
export function App() {
|
|
170
|
+
const [client, setClient] = useState<LocalFirstClient | null>(null);
|
|
171
|
+
|
|
172
|
+
useEffect(() => {
|
|
173
|
+
getSyncClient().then(setClient);
|
|
174
|
+
}, []);
|
|
175
|
+
|
|
176
|
+
// 1. Reactive live SQLite query (auto-updates when table mutates)
|
|
177
|
+
const { data: todos } = useLiveQuery<{ id: string; title: string }>(
|
|
178
|
+
client,
|
|
179
|
+
'SELECT * FROM todos ORDER BY updated_at DESC;',
|
|
180
|
+
[]
|
|
181
|
+
);
|
|
182
|
+
|
|
183
|
+
// 2. Real-time sync engine connectivity & outbox metrics
|
|
184
|
+
const { isOnline, isSyncing, pendingChanges } = useSyncStatus(client);
|
|
185
|
+
|
|
186
|
+
// 3. Reactive zero-backend local authentication
|
|
187
|
+
const { user, isSignedIn, signIn, signOut } = useLocalAuth(client?.auth);
|
|
188
|
+
|
|
189
|
+
return (
|
|
190
|
+
<View>
|
|
191
|
+
<Text>Status: {isOnline ? 'Online' : 'Offline'} ({pendingChanges} pending)</Text>
|
|
192
|
+
{isSignedIn ? (
|
|
193
|
+
<View>
|
|
194
|
+
<Text>Welcome, {user?.displayName || user?.email}!</Text>
|
|
195
|
+
<Button title="Sign Out" onPress={() => signOut()} />
|
|
196
|
+
</View>
|
|
197
|
+
) : (
|
|
198
|
+
<Button title="Sign In" onPress={() => signIn('user@example.com', 'Password123!')} />
|
|
199
|
+
)}
|
|
200
|
+
</View>
|
|
201
|
+
);
|
|
202
|
+
}
|
|
203
|
+
```
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: local-lite-storage
|
|
3
|
+
description: Manage binary files, images, and attachments with offline caching and cloud sync in local-lite. Use when configuring BlobStorageManager, ExpoFileDriver, syncing files to Supabase Storage, Firebase Storage, or Convex, and using useStorage or useBlobUpload.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# local-lite Blob & File Storage
|
|
7
|
+
|
|
8
|
+
Guide for managing binary files, media, and attachments with local offline caching and cloud bucket synchronization in `local-lite`.
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## 1. Storage Architecture
|
|
13
|
+
|
|
14
|
+
`local-lite/storage` decouples file metadata in SQLite from the actual binary data on disk:
|
|
15
|
+
* **Local File Drivers**: Persists binary blobs to disk (`ExpoFileDriver` on mobile, `NodeFsFileDriver` on Node.js/Electron).
|
|
16
|
+
* **Remote Storage Providers**: Synchronizes files to remote cloud buckets (Supabase Storage, Firebase Storage, Convex Files).
|
|
17
|
+
* **Metadata Store**: Automatically maintains offline status, upload progress, mime types, and SHA-256 checksums in the `_local_blobs` SQLite table.
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
## 2. Configuration
|
|
22
|
+
|
|
23
|
+
Enable storage in `defineSyncConfig`:
|
|
24
|
+
|
|
25
|
+
```typescript
|
|
26
|
+
import { defineSyncConfig } from 'local-lite/config';
|
|
27
|
+
import { ExpoFileDriver } from 'local-lite/storage';
|
|
28
|
+
|
|
29
|
+
export const syncConfig = defineSyncConfig({
|
|
30
|
+
database: () => SQLite.openDatabaseAsync('app.db'),
|
|
31
|
+
tables: ['documents', 'photos'],
|
|
32
|
+
|
|
33
|
+
// Blob storage configuration
|
|
34
|
+
storage: {
|
|
35
|
+
// 1. Local storage driver
|
|
36
|
+
driver: new ExpoFileDriver({
|
|
37
|
+
baseDirectory: 'attachments', // Stored in private app document directory
|
|
38
|
+
}),
|
|
39
|
+
|
|
40
|
+
// 2. Remote storage provider (e.g. Supabase Storage bucket)
|
|
41
|
+
provider: {
|
|
42
|
+
type: 'supabase',
|
|
43
|
+
bucket: 'user-attachments',
|
|
44
|
+
url: process.env.EXPO_PUBLIC_SUPABASE_URL!,
|
|
45
|
+
anonKey: process.env.EXPO_PUBLIC_SUPABASE_ANON_KEY!,
|
|
46
|
+
},
|
|
47
|
+
|
|
48
|
+
// 3. Auto-sync uploads when online
|
|
49
|
+
autoSync: true,
|
|
50
|
+
},
|
|
51
|
+
});
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
---
|
|
55
|
+
|
|
56
|
+
## 3. Saving & Reading Files
|
|
57
|
+
|
|
58
|
+
### Save a File (Immediate Offline Access)
|
|
59
|
+
```typescript
|
|
60
|
+
import { getSyncClient } from './sync.config';
|
|
61
|
+
|
|
62
|
+
const client = await getSyncClient();
|
|
63
|
+
|
|
64
|
+
// Saves to local disk immediately and queues for background cloud sync
|
|
65
|
+
const blob = await client.storage.save({
|
|
66
|
+
id: 'avatar-user-123.jpg',
|
|
67
|
+
data: fileBytes, // Uint8Array or Blob
|
|
68
|
+
mimeType: 'image/jpeg',
|
|
69
|
+
metadata: { userId: '123' },
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
console.log('Saved locally at:', blob.localPath);
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
### Retrieve a File
|
|
76
|
+
```typescript
|
|
77
|
+
// Read as raw Uint8Array
|
|
78
|
+
const data = await client.storage.read('avatar-user-123.jpg');
|
|
79
|
+
|
|
80
|
+
// Or get local file URI for <Image source={{ uri }} />
|
|
81
|
+
const uri = await client.storage.getLocalUri('avatar-user-123.jpg');
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
---
|
|
85
|
+
|
|
86
|
+
## 4. React Integration (`useStorage` & `useBlobUpload`)
|
|
87
|
+
|
|
88
|
+
Use reactive hooks from `local-lite/react` for image pickers, file attachments, and upload progress:
|
|
89
|
+
|
|
90
|
+
```tsx
|
|
91
|
+
import React from 'react';
|
|
92
|
+
import { View, Image, Text, Button } from 'react-native';
|
|
93
|
+
import { useStorage } from 'local-lite/react';
|
|
94
|
+
import { getSyncClient } from './sync.config';
|
|
95
|
+
|
|
96
|
+
export function DocumentViewer({ fileId }: { fileId: string }) {
|
|
97
|
+
const [client, setClient] = React.useState(null);
|
|
98
|
+
React.useEffect(() => { getSyncClient().then(setClient); }, []);
|
|
99
|
+
|
|
100
|
+
const { fileUri, isSyncing, progress, error } = useStorage(client?.storage, fileId);
|
|
101
|
+
|
|
102
|
+
if (error) return <Text>Error loading file: {error.message}</Text>;
|
|
103
|
+
|
|
104
|
+
return (
|
|
105
|
+
<View>
|
|
106
|
+
{fileUri ? (
|
|
107
|
+
<Image source={{ uri: fileUri }} style={{ width: 300, height: 300 }} />
|
|
108
|
+
) : (
|
|
109
|
+
<Text>Loading file from local storage...</Text>
|
|
110
|
+
)}
|
|
111
|
+
{isSyncing && <Text>Syncing to cloud: {progress}%</Text>}
|
|
112
|
+
</View>
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
```
|
|
116
|
+
|
|
@@ -1,16 +1,45 @@
|
|
|
1
|
-
---
|
|
2
|
-
name: local-lite-upgrade
|
|
3
|
-
description: Review a codebase that uses the local-lite npm package for code that must change after a local-lite upgrade. Use when upgrading local-lite,
|
|
4
|
-
---
|
|
5
|
-
|
|
6
|
-
# local-lite upgrade review
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
1
|
+
---
|
|
2
|
+
name: local-lite-upgrade
|
|
3
|
+
description: Review a codebase that uses the local-lite npm package for code that must change after a local-lite upgrade. Use when upgrading local-lite, migrating from legacy options, fixing bundler errors in Metro/Web, or updating authentication and adapters.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# local-lite upgrade review
|
|
7
|
+
|
|
8
|
+
Checklist and automated review instructions for upgrading apps to the latest version of `local-lite`.
|
|
9
|
+
|
|
10
|
+
## 1. Upgrade Checklist
|
|
11
|
+
|
|
12
|
+
Search the codebase for each affected pattern and apply the migration:
|
|
13
|
+
|
|
14
|
+
### Schema Migrations (`schemaMigrations` vs `migrations`)
|
|
15
|
+
* **Old**: `createSyncClient({ migrations: [ ... ] })`
|
|
16
|
+
* **New**: `createSyncClient({ schemaMigrations: [ { version: 1, up: [ ... ] } ] })`
|
|
17
|
+
* **Action**: `schemaMigrations` is strictly required. Each item requires `{ version: number, up: string[] }`.
|
|
18
|
+
|
|
19
|
+
### Custom Remote Adapters (`subscribeToLiveChanges`)
|
|
20
|
+
* **Contract**: `subscribeToLiveChanges(callback)` must return an unsubscribe cleanup function `() => void`. Returning `void` causes memory leaks and breaks lifecycle tearing.
|
|
21
|
+
|
|
22
|
+
### Expo Web & Metro Bundler Configuration
|
|
23
|
+
* **Symptom**: `Unable to resolve module ./wa-sqlite/wa-sqlite.wasm` or `Importing react-native internals is not supported on web`.
|
|
24
|
+
* **Fix**: In `metro.config.js`:
|
|
25
|
+
1. Add `.wasm` to `config.resolver.assetExts.push('wasm')`.
|
|
26
|
+
2. In `resolveRequest`, map `react-native` to `react-native-web` when `platform === 'web'`.
|
|
27
|
+
3. Set `"output": "single"` in `app.json` under `expo.web`.
|
|
28
|
+
|
|
29
|
+
### UUID Generation
|
|
30
|
+
* **Old**: `import { v4 } from 'uuid';`
|
|
31
|
+
* **New**: `import { generateUUID } from 'local-lite';`
|
|
32
|
+
* **Action**: External `uuid` (v10+) references bare `crypto.randomUUID` which throws `Property 'crypto' doesn't exist` on Hermes. Use `generateUUID()` directly from `local-lite`.
|
|
33
|
+
|
|
34
|
+
### File Storage Driver (`ExpoFileDriver`)
|
|
35
|
+
* **Old**: Injecting `fileSystem` via legacy `expo-file-system`.
|
|
36
|
+
* **New**: Uses standard Expo SDK 58+ `File`, `Directory`, and `Paths` APIs. Remove legacy `fileSystem` option.
|
|
37
|
+
|
|
38
|
+
---
|
|
39
|
+
|
|
40
|
+
## 2. Review Workflow
|
|
41
|
+
|
|
42
|
+
1. Scan `sync.config.ts` (or client creation files) for deprecated options (`migrations`, legacy adapters).
|
|
43
|
+
2. Verify all synced tables contain `id TEXT PRIMARY KEY` and `updated_at INTEGER NOT NULL`.
|
|
44
|
+
3. Verify `schemaMigrations` versions are strictly sequential integers starting from 1.
|
|
45
|
+
4. Report each match with file path and line number alongside minimal migration code.
|