local-lite 0.1.4 โ†’ 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +5 -2
  2. package/bin/local-lite.mjs +65 -61
  3. package/dist/auth/apple.d.ts +3 -4
  4. package/dist/auth/apple.js +26 -3
  5. package/dist/auth/github.d.ts +3 -5
  6. package/dist/auth/github.js +18 -4
  7. package/dist/auth/google.d.ts +3 -6
  8. package/dist/auth/google.js +19 -5
  9. package/dist/auth/identity.d.ts +42 -0
  10. package/dist/auth/identity.js +63 -0
  11. package/dist/auth/index.d.ts +2 -0
  12. package/dist/auth/index.js +2 -0
  13. package/dist/auth/local.d.ts +33 -1
  14. package/dist/auth/local.js +94 -13
  15. package/dist/auth/microsoft.d.ts +3 -5
  16. package/dist/auth/microsoft.js +16 -3
  17. package/dist/auth/session.d.ts +4 -0
  18. package/dist/auth/session.js +19 -1
  19. package/dist/auth/unified.d.ts +73 -0
  20. package/dist/auth/unified.js +188 -0
  21. package/package.json +1 -2
  22. package/skills/local-lite-auth/SKILL.md +67 -27
  23. package/skills/local-lite-server/SKILL.md +127 -0
  24. package/docs/.nojekyll +0 -1
  25. package/docs/README.md +0 -108
  26. package/docs/_sidebar.md +0 -22
  27. package/docs/actions-email.md +0 -222
  28. package/docs/adapters-local.md +0 -272
  29. package/docs/adapters-remote.md +0 -291
  30. package/docs/api-keys.md +0 -114
  31. package/docs/architecture.md +0 -106
  32. package/docs/auth.md +0 -342
  33. package/docs/backups.md +0 -214
  34. package/docs/breaking-changes.md +0 -147
  35. package/docs/client-api.md +0 -412
  36. package/docs/configuration.md +0 -228
  37. package/docs/conflict-resolution.md +0 -78
  38. package/docs/getting-started.md +0 -190
  39. package/docs/google-auth.md +0 -234
  40. package/docs/index.html +0 -166
  41. package/docs/kv.md +0 -89
  42. package/docs/maintenance-portability.md +0 -133
  43. package/docs/react-hooks.md +0 -457
  44. package/docs/scheduler.md +0 -81
  45. package/docs/search.md +0 -71
  46. package/docs/server.md +0 -101
  47. package/docs/session.md +0 -129
  48. package/docs/storage.md +0 -265
@@ -1,234 +0,0 @@
1
- # ๐Ÿ”‘ Google Sign-In & Authentication
2
-
3
- `local-lite` provides a zero-backend, zero-lock-in **Google OAuth 2.0 PKCE client** and React hook out of the box.
4
-
5
- Built specifically for local-first architectures, it allows your Expo, React Native, or Web application to sign in users directly with Google without requiring a dedicated auth server, Supabase, or Firebase.
6
-
7
- ```typescript
8
- import { GoogleAuthClient } from 'local-lite/auth';
9
- import { useGoogleAuth } from 'local-lite/react';
10
- ```
11
-
12
- ---
13
-
14
- ## ๐ŸŒŸ Features
15
-
16
- * **๐Ÿ›ก๏ธ PKCE Security (RFC 7636):** Automatic cryptographically secure 32-byte `code_verifier`, SHA-256 (`S256`) code challenge generation, and CSRF state validation.
17
- * **๐Ÿ‘ค User Profile Fetching:** Retrieves verified user profile (`id`, `email`, `name`, `picture`, `locale`) from Google's UserInfo endpoint upon sign-in.
18
- * **๐Ÿ”„ Transparent Token Refreshing:** Automatically checks token expiration and uses Google's `refresh_token` endpoint if the access token is within 60 seconds of expiry.
19
- * **๐Ÿ’พ Pluggable Storage:** Use `createInMemoryGoogleTokenStore()` (default) or `createGoogleAuthTokenStore(storage)` for persistent storage (AsyncStorage, MMKV, SecureStore, etc.).
20
- * **โš›๏ธ First-Class React Hook:** `useGoogleAuth()` provides reactive user state, sign-in, sign-out, and auto-subscriptions.
21
- * **โ˜๏ธ Google Drive Backup Synergy:** Pair with `local-lite/backups` to back up and restore SQLite database snapshots directly to the user's Google Drive using the same authenticated session.
22
-
23
- ---
24
-
25
- ## ๐Ÿš€ Quickstart in Expo / React Native
26
-
27
- ### 1. Install Dependencies
28
-
29
- ```bash
30
- npx expo install expo-web-browser expo-linking
31
- ```
32
-
33
- ### 2. Configure Google Cloud Console
34
-
35
- 1. Go to the [Google Cloud Console](https://console.cloud.google.com/apis/credentials).
36
- 2. Create an **OAuth 2.0 Client ID** (select **Web application** or native app depending on your redirect flow).
37
- 3. Add your app's redirect URI (e.g. `myapp://oauth` or `https://auth.expo.io/@yourname/myapp`).
38
-
39
- ### 3. Initialize `GoogleAuthClient`
40
-
41
- Create a shared authentication instance:
42
-
43
- ```typescript
44
- // auth.ts
45
- import * as WebBrowser from 'expo-web-browser';
46
- import * as Linking from 'expo-linking';
47
- import { GoogleAuthClient, createGoogleAuthTokenStore } from 'local-lite/auth';
48
-
49
- // Tell WebBrowser to complete any pending auth sessions on web/native
50
- WebBrowser.maybeCompleteAuthSession();
51
-
52
- export const googleAuth = new GoogleAuthClient({
53
- clientId: process.env.EXPO_PUBLIC_GOOGLE_CLIENT_ID || 'YOUR_CLIENT_ID.apps.googleusercontent.com',
54
- redirectUri: Linking.createURL('oauth'),
55
- scopes: ['openid', 'email', 'profile'],
56
- authorize: async ({ authorizationUrl, redirectUri }) => {
57
- const result = await WebBrowser.openAuthSessionAsync(authorizationUrl, redirectUri);
58
- if (result.type !== 'success' || !result.url) {
59
- return null; // User cancelled
60
- }
61
- const callback = new URL(result.url);
62
- return {
63
- code: callback.searchParams.get('code') ?? '',
64
- state: callback.searchParams.get('state') ?? '',
65
- };
66
- },
67
- });
68
- ```
69
-
70
- ---
71
-
72
- ## โš›๏ธ React Integration with `useGoogleAuth`
73
-
74
- Use the `useGoogleAuth` hook to bind user login state directly to your UI:
75
-
76
- ```tsx
77
- import React from 'react';
78
- import { View, Text, Button, Image, StyleSheet } from 'react-native';
79
- import { useGoogleAuth } from 'local-lite/react';
80
- import { googleAuth } from './auth';
81
-
82
- export function UserHeader() {
83
- const { user, isSignedIn, loading, signIn, signOut } = useGoogleAuth(googleAuth);
84
-
85
- if (loading) {
86
- return <Text style={styles.status}>Checking authentication...</Text>;
87
- }
88
-
89
- if (!isSignedIn || !user) {
90
- return (
91
- <View style={styles.card}>
92
- <Text style={styles.title}>Guest Mode</Text>
93
- <Text style={styles.subtitle}>Sign in with Google to enable cloud backups.</Text>
94
- <Button title="Sign In with Google" onPress={signIn} />
95
- </View>
96
- );
97
- }
98
-
99
- return (
100
- <View style={styles.card}>
101
- {user.picture && (
102
- <Image source={{ uri: user.picture }} style={styles.avatar} />
103
- )}
104
- <View style={styles.info}>
105
- <Text style={styles.name}>{user.name}</Text>
106
- <Text style={styles.email}>{user.email}</Text>
107
- </View>
108
- <Button title="Sign Out" onPress={signOut} color="#ef4444" />
109
- </View>
110
- );
111
- }
112
-
113
- const styles = StyleSheet.create({
114
- card: { padding: 16, borderRadius: 12, backgroundColor: '#f8fafc', marginBottom: 12 },
115
- status: { padding: 16, color: '#64748b' },
116
- avatar: { width: 44, height: 44, borderRadius: 22, marginBottom: 8 },
117
- title: { fontSize: 16, fontWeight: '700', color: '#0f172a' },
118
- subtitle: { fontSize: 13, color: '#64748b', marginBottom: 10 },
119
- info: { marginBottom: 10 },
120
- name: { fontSize: 15, fontWeight: '600', color: '#0f172a' },
121
- email: { fontSize: 13, color: '#64748b' },
122
- });
123
- ```
124
-
125
- ---
126
-
127
- ## ๐Ÿ’พ Persistent Token & Profile Storage
128
-
129
- By default, `GoogleAuthClient` stores credentials in memory. To keep users signed in across app restarts, pass a key-value storage adapter (such as `AsyncStorage` or `expo-secure-store`):
130
-
131
- ```typescript
132
- import AsyncStorage from '@react-native-async-storage/async-storage';
133
- import { GoogleAuthClient, createGoogleAuthTokenStore } from 'local-lite/auth';
134
-
135
- const persistentStore = createGoogleAuthTokenStore({
136
- getItem: async (key) => {
137
- const value = await AsyncStorage.getItem(key);
138
- return value ? JSON.parse(value) : null;
139
- },
140
- setItem: async (key, value) => {
141
- await AsyncStorage.setItem(key, JSON.stringify(value));
142
- },
143
- removeItem: async (key) => {
144
- await AsyncStorage.removeItem(key);
145
- },
146
- }, 'my-app-auth');
147
-
148
- export const googleAuth = new GoogleAuthClient({
149
- clientId: 'YOUR_CLIENT_ID.apps.googleusercontent.com',
150
- redirectUri: 'myapp://oauth',
151
- tokenStore: persistentStore,
152
- authorize: openBrowserSession,
153
- });
154
- ```
155
-
156
- ---
157
-
158
- ## โ˜๏ธ Google Drive Backup Synergy
159
-
160
- If you request the `'https://www.googleapis.com/auth/drive.file'` scope during login, the same `GoogleAuthClient` can power SQLite database backups to Google Drive without requiring the user to authenticate a second time:
161
-
162
- ```typescript
163
- import { GoogleAuthClient } from 'local-lite/auth';
164
- import { createDatabaseBackup, restoreDatabaseBackup } from 'local-lite/backups';
165
-
166
- export const googleAuth = new GoogleAuthClient({
167
- clientId: 'YOUR_CLIENT_ID.apps.googleusercontent.com',
168
- redirectUri: 'myapp://oauth',
169
- scopes: [
170
- 'openid',
171
- 'email',
172
- 'profile',
173
- 'https://www.googleapis.com/auth/drive.file', // Request Drive access
174
- ],
175
- authorize: openBrowserSession,
176
- });
177
-
178
- // Create Google Drive storage powered by the authenticated user's session
179
- const driveStorage = googleAuth.createDriveBackupStorage();
180
-
181
- // Export SQLite database to Google Drive
182
- export async function backupToDrive(databaseAdapter) {
183
- const fileName = await createDatabaseBackup(databaseAdapter, driveStorage);
184
- console.log(`Database saved to Google Drive: ${fileName}`);
185
- }
186
-
187
- // List and restore backups
188
- export async function restoreFromDrive(databaseAdapter, fileName) {
189
- const backups = await driveStorage.list();
190
- console.log('Available backups on Drive:', backups);
191
- await restoreDatabaseBackup(databaseAdapter, driveStorage, fileName);
192
- }
193
- ```
194
-
195
- ---
196
-
197
- ## ๐Ÿ“– API Reference
198
-
199
- ### `GoogleAuthClientOptions`
200
-
201
- | Option | Type | Default | Description |
202
- | :--- | :--- | :--- | :--- |
203
- | `clientId` | `string` | *(Required)* | Google OAuth 2.0 Web or Native client ID. |
204
- | `redirectUri` | `string` | *(Required)* | Redirect callback URI registered in Google Console. |
205
- | `scopes` | `string[]` | `['openid', 'email', 'profile']` | OAuth scopes to request from Google. |
206
- | `authorize` | `(req) => Promise<res \| null>` | *(Required)* | Function that opens the system browser session and returns code + state. |
207
- | `tokenStore` | `GoogleAuthTokenStore` | In-memory store | Token & profile storage adapter. |
208
- | `prompt` | `'select_account' \| 'consent' \| 'none'` | `'select_account'` | Google consent prompt behavior. |
209
- | `accessType` | `'offline' \| 'online'` | `'offline'` | Requests a refresh token when set to `'offline'`. |
210
-
211
- ### `GoogleUser`
212
-
213
- ```typescript
214
- export interface GoogleUser {
215
- id: string; // Google sub identifier
216
- email: string; // User's verified email address
217
- emailVerified: boolean;
218
- name: string; // Full name
219
- givenName?: string; // First name
220
- familyName?: string; // Last name
221
- picture?: string; // Avatar URL
222
- locale?: string; // Preferred language/locale
223
- }
224
- ```
225
-
226
- ### `GoogleAuthClient` Methods
227
-
228
- * **`signIn(): Promise<GoogleUser | null>`**: Starts PKCE authorization flow, exchanges code for tokens, fetches user profile, and notifies listeners. Returns `null` if user cancels.
229
- * **`signOut(): Promise<void>`**: Clears stored tokens and cached profile, notifying all subscribers.
230
- * **`isSignedIn(): Promise<boolean>`**: Checks whether a valid or refreshable session exists.
231
- * **`getUser(): Promise<GoogleUser | null>`**: Returns the current signed-in user profile, reading from cache or fetching via valid access token.
232
- * **`getValidAccessToken(): Promise<string>`**: Returns a fresh access token, automatically refreshing if expired or expiring within 60 seconds.
233
- * **`onAuthStateChange(listener): () => void`**: Subscribes to auth status changes (`GoogleUser | null`). Returns an unsubscribe function.
234
- * **`createDriveBackupStorage(): GoogleDriveBackupStorage`**: Returns a `GoogleDriveBackupStorage` instance ready for use with `createDatabaseBackup()` / `restoreDatabaseBackup()`.
package/docs/index.html DELETED
@@ -1,166 +0,0 @@
1
- <!DOCTYPE html>
2
- <html lang="en">
3
-
4
- <head>
5
- <meta charset="UTF-8">
6
- <title>Offline-First SQLite Sync Engine</title>
7
- <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
8
- <meta name="description"
9
- content="Never let a lost connection break a promise. Local-first sync engine for Expo, React Native, and Node.js.">
10
- <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
11
- <link rel="icon"
12
- href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220%22%20viewBox=%220%200%20100%20100%22><text y=%22.9em%22 font-size=%2290%22>โšก</text></svg>">
13
-
14
- <!-- Fonts -->
15
- <link rel="preconnect" href="https://fonts.googleapis.com">
16
- <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
17
- <link
18
- href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=JetBrains+Mono:wght@400;500;600&display=swap"
19
- rel="stylesheet">
20
-
21
- <!-- Docsify Theme & Dark/Light Switcher -->
22
- <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/docsify-darklight-theme@latest/dist/style.min.css">
23
- <style>
24
- :root {
25
- --docsify-font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
26
- --code-font-family: 'JetBrains Mono', Consolas, Monaco, monospace;
27
- }
28
-
29
- body {
30
- font-family: var(--docsify-font-family);
31
- }
32
-
33
- code,
34
- pre {
35
- font-family: var(--code-font-family) !important;
36
- }
37
-
38
- .sidebar {
39
- font-weight: 500;
40
- }
41
-
42
- .app-name {
43
- display: none !important;
44
- }
45
-
46
- .markdown-section h1 {
47
- font-weight: 800;
48
- letter-spacing: -0.025em;
49
- }
50
-
51
- .markdown-section h2 {
52
- font-weight: 700;
53
- letter-spacing: -0.02em;
54
- }
55
-
56
- .docsify-pagination-container {
57
- margin-top: 2.5rem;
58
- padding-top: 1.25rem;
59
- border-top: 1px solid rgba(148, 163, 184, 0.15);
60
- }
61
-
62
- .pagination-item {
63
- max-width: 45%;
64
- }
65
-
66
- .pagination-item a {
67
- text-decoration: none !important;
68
- }
69
-
70
- .pagination-item-label {
71
- font-size: 0.72rem !important;
72
- font-weight: 600 !important;
73
- letter-spacing: 0.05em;
74
- text-transform: uppercase;
75
- opacity: 0.65;
76
- }
77
-
78
- .pagination-item-title {
79
- font-size: 0.95rem !important;
80
- font-weight: 600 !important;
81
- margin-top: 0.15rem;
82
- line-height: 1.35 !important;
83
- }
84
- </style>
85
- </head>
86
-
87
- <body>
88
- <div id="app">Loading documentation...</div>
89
- <script>
90
- window.$docsify = {
91
- name: 'Local Lite',
92
- repo: 'https://github.com/georgechitechi/local-lite',
93
- loadSidebar: true,
94
- subMaxLevel: 3,
95
- auto2top: true,
96
- homepage: 'README.md',
97
- search: {
98
- maxAge: 86400000,
99
- paths: 'auto',
100
- placeholder: 'Search documentation...',
101
- noData: 'No results found',
102
- depth: 4
103
- },
104
- copyCode: {
105
- buttonText: 'Copy',
106
- successText: 'Copied!'
107
- },
108
- darklightTheme: {
109
- siteFont: 'Inter',
110
- defaultTheme: 'dark',
111
- codeFontFamily: 'JetBrains Mono',
112
- bodyFontSize: '15px',
113
- dark: {
114
- accent: '#38bdf8',
115
- toogleBackground: '#ffffff',
116
- background: '#090d16',
117
- textColor: '#e2e8f0',
118
- codeTextColor: '#f8fafc',
119
- codeBackgroundColor: '#0f172a',
120
- borderColor: '#1e293b',
121
- blockQuoteColor: '#38bdf8',
122
- highlightColor: '#f59e0b',
123
- sidebarSublabel: '#94a3b8'
124
- },
125
- light: {
126
- accent: '#0284c7',
127
- toogleBackground: '#0f172a',
128
- background: '#ffffff',
129
- textColor: '#0f172a',
130
- codeTextColor: '#0f172a',
131
- codeBackgroundColor: '#f8fafc',
132
- borderColor: '#e2e8f0',
133
- blockQuoteColor: '#0284c7',
134
- highlightColor: '#f59e0b',
135
- sidebarSublabel: '#64748b'
136
- }
137
- },
138
- pagination: {
139
- previousText: 'Previous',
140
- nextText: 'Next',
141
- crossChapter: true,
142
- crossChapterText: true
143
- }
144
- }
145
- </script>
146
- <!-- Docsify Core -->
147
- <script src="//cdn.jsdelivr.net/npm/docsify@4/lib/docsify.min.js"></script>
148
-
149
- <!-- Plugins -->
150
- <script src="//cdn.jsdelivr.net/npm/docsify@4/lib/plugins/search.min.js"></script>
151
- <script src="//cdn.jsdelivr.net/npm/docsify-copy-code/dist/docsify-copy-code.min.js"></script>
152
- <script src="//cdn.jsdelivr.net/npm/docsify-pagination/dist/docsify-pagination.min.js"></script>
153
- <script src="//cdn.jsdelivr.net/npm/docsify-darklight-theme@latest/dist/index.min.js"></script>
154
-
155
- <!-- Prism Syntax Highlighting -->
156
- <script src="//cdn.jsdelivr.net/npm/prismjs@1/components/prism-bash.min.js"></script>
157
- <script src="//cdn.jsdelivr.net/npm/prismjs@1/components/prism-typescript.min.js"></script>
158
- <script src="//cdn.jsdelivr.net/npm/prismjs@1/components/prism-javascript.min.js"></script>
159
- <script src="//cdn.jsdelivr.net/npm/prismjs@1/components/prism-json.min.js"></script>
160
- <script src="//cdn.jsdelivr.net/npm/prismjs@1/components/prism-sql.min.js"></script>
161
- <script src="//cdn.jsdelivr.net/npm/prismjs@1/components/prism-jsx.min.js"></script>
162
- <script src="//cdn.jsdelivr.net/npm/prismjs@1/components/prism-tsx.min.js"></script>
163
- <script src="//cdn.jsdelivr.net/npm/prismjs@1/components/prism-markdown.min.js"></script>
164
- </body>
165
-
166
- </html>
package/docs/kv.md DELETED
@@ -1,89 +0,0 @@
1
- # Fast Key-Value & Encrypted Preferences (`client.kv`)
2
-
3
- `local-lite` includes a built-in, lightning-fast key-value store directly inside your SQLite database (`_local_kv`), providing zero-overhead storage for application state, user preferences, offline session flags, and zero-knowledge encrypted secrets.
4
-
5
- ---
6
-
7
- ## Features
8
-
9
- - **Typed Storage**: Transparently handles strings, numbers, booleans, and JSON objects.
10
- - **TTL Support**: Built-in TTL expiration (e.g., tokens expiring in 15 minutes, caches expiring in 24 hours).
11
- - **Lazy & Immediate Cleanup**: Expired keys return `undefined` on access and are automatically purged via `client.kv.pruneExpired()`.
12
- - **Zero-Knowledge Encrypted Preferences**: Store sensitive tokens, API credentials, and personal encryption keys using military-grade **AES-256-GCM** + **PBKDF2** encryption.
13
- - **Cross-Platform**: Works everywhere without native dependencies on Web, Expo/React Native, and Node.js.
14
-
15
- ---
16
-
17
- ## Basic Usage
18
-
19
- Access the store directly from your `LocalFirstClient` instance:
20
-
21
- ```typescript
22
- // Strings
23
- await client.kv.set('theme', 'dark');
24
- const theme = await client.kv.get('theme'); // 'dark'
25
-
26
- // Numbers & Booleans
27
- await client.kv.set('retryCount', 3);
28
- await client.kv.set('offlineMode', true);
29
-
30
- // JSON Objects
31
- await client.kv.set('userPreferences', {
32
- language: 'en-US',
33
- currency: 'USD',
34
- notifications: true,
35
- });
36
-
37
- const prefs = await client.kv.get('userPreferences');
38
- console.log(prefs.currency); // 'USD'
39
-
40
- // Check existence
41
- const hasTheme = await client.kv.has('theme'); // true
42
-
43
- // Delete key
44
- await client.kv.delete('theme');
45
-
46
- // List keys
47
- const allKeys = await client.kv.keys();
48
- ```
49
-
50
- ---
51
-
52
- ## TTL & Expiration
53
-
54
- ```typescript
55
- // Expire in 10 minutes (600,000 ms)
56
- await client.kv.set('tempSessionToken', 'session_123', {
57
- ttlMs: 10 * 60 * 1000,
58
- });
59
-
60
- // Or set an absolute timestamp
61
- await client.kv.set('flashPromo', { discount: 20 }, {
62
- expiresAt: Date.now() + 3600000,
63
- });
64
-
65
- // Prune expired entries
66
- await client.kv.pruneExpired();
67
- ```
68
-
69
- ---
70
-
71
- ## Encrypted Preferences (AES-256-GCM)
72
-
73
- Protect sensitive secrets, OAuth refresh tokens, and payment API keys at rest on the client:
74
-
75
- ```typescript
76
- const userPassphrase = 'user-provided-secure-passphrase';
77
-
78
- // Store encrypted secret
79
- await client.kv.setSecret('stripe_config', {
80
- secretKey: 'sk_live_123456789',
81
- webhookSecret: 'whsec_abcdef',
82
- }, {
83
- passphrase: userPassphrase,
84
- });
85
-
86
- // Decrypt secret
87
- const stripeConfig = await client.kv.getSecret('stripe_config', userPassphrase);
88
- console.log(stripeConfig.secretKey); // 'sk_live_123456789'
89
- ```
@@ -1,133 +0,0 @@
1
- # ๐Ÿงน Database Maintenance & Universal Data Portability
2
-
3
- Keep your local SQLite database lean, responsive, and easily exportable.
4
-
5
- ```typescript
6
- import {
7
- exportTablesToJson,
8
- importTablesFromJson,
9
- exportTableToCsv,
10
- importTableFromCsv,
11
- } from 'local-lite';
12
-
13
- import { useDatabaseMaintenance } from 'local-lite/react';
14
- ```
15
-
16
- ---
17
-
18
- ## ๐Ÿงน 1. Database Maintenance (`client.maintenance`)
19
-
20
- `LocalFirstClient` includes a dedicated `DatabaseMaintenance` instance:
21
-
22
- ```typescript
23
- // 1. Get complete storage metrics breakdown
24
- const stats = await client.maintenance.getStorageStats();
25
- console.log('Database size on disk:', stats.databaseSizeBytes, 'bytes');
26
- console.log('Table rows:', stats.tables);
27
- console.log('Outbox queue status:', stats.outbox);
28
-
29
- // 2. Prune old or completed sync outbox records
30
- const pruned = await client.maintenance.pruneOutbox({
31
- retentionDays: 14, // Delete records older than 14 days
32
- maxEntries: 1000, // Keep at most 1,000 completed/failed records
33
- statuses: ['COMPLETED', 'FAILED'],
34
- });
35
- console.log(`Pruned ${pruned} outbox records`);
36
-
37
- // 3. Defragment database and reclaim unused pages
38
- await client.maintenance.vacuum();
39
-
40
- // 4. Force WAL log checkpointing back into database file
41
- // Modes: 'PASSIVE' | 'FULL' | 'RESTART' | 'TRUNCATE'
42
- await client.maintenance.checkpoint('TRUNCATE');
43
-
44
- // 5. Query planner optimization (PRAGMA optimize / analyze)
45
- await client.maintenance.analyze();
46
-
47
- // 6. SQLite structural integrity check (PRAGMA integrity_check)
48
- const isHealthy = await client.maintenance.integrityCheck();
49
- console.log('Database health:', isHealthy ? 'OK' : 'Corrupted');
50
- ```
51
-
52
- ---
53
-
54
- ## โš›๏ธ 2. React Maintenance Hook (`useDatabaseMaintenance`)
55
-
56
- Manage database health directly from your settings screen:
57
-
58
- ```tsx
59
- import React from 'react';
60
- import { View, Text, Button } from 'react-native';
61
- import { useDatabaseMaintenance } from 'local-lite/react';
62
-
63
- export function StorageSettings({ client }) {
64
- const {
65
- stats,
66
- loading,
67
- refreshStats,
68
- pruneOutbox,
69
- vacuum,
70
- checkpoint,
71
- } = useDatabaseMaintenance(client);
72
-
73
- return (
74
- <View style={{ padding: 16 }}>
75
- <Text style={{ fontSize: 18, fontWeight: 'bold' }}>Database Storage</Text>
76
- <Text>Database Size: {stats?.databaseSizeBytes ? `${(stats.databaseSizeBytes / 1024).toFixed(1)} KB` : '...'}</Text>
77
- <Text>Pending Mutations: {stats?.outbox.pending ?? 0}</Text>
78
- <Text>Completed History: {stats?.outbox.completed ?? 0}</Text>
79
-
80
- <Button
81
- title="Prune Old Outbox Records"
82
- onPress={() => pruneOutbox({ retentionDays: 7 })}
83
- />
84
- <Button
85
- title="Reclaim Free Disk Space (VACUUM)"
86
- onPress={vacuum}
87
- />
88
- <Button
89
- title="Checkpoint WAL File"
90
- onPress={() => checkpoint('TRUNCATE')}
91
- />
92
- </View>
93
- );
94
- }
95
- ```
96
-
97
- ---
98
-
99
- ## ๐Ÿ“ค 3. Universal Data Portability (JSON & CSV)
100
-
101
- Allow users to export and import their data at any time for GDPR compliance, account switching, local backups, or spreadsheet analysis.
102
-
103
- ### JSON Export & Import:
104
- ```typescript
105
- // Export specific tables (or all managed tables) to JSON string
106
- const jsonString = await client.exportToJson(['milestones', 'vaccines'], {
107
- pretty: true,
108
- });
109
-
110
- // Import tables from JSON string
111
- const summary = await client.importFromJson(jsonString, {
112
- mode: 'merge', // 'merge' (updates existing rows by ID & inserts new) or 'replace' (deletes all existing rows first)
113
- skipOutbox: true, // When true, does not re-queue restored rows to the sync outbox
114
- });
115
-
116
- console.log('Import summary:', summary.tables, summary.rowCounts);
117
- ```
118
-
119
- ### RFC-4180 CSV Export & Import:
120
- ```typescript
121
- // Export a single table to CSV
122
- const csvData = await client.exportToCsv('vaccines', {
123
- delimiter: ',',
124
- includeHeaders: true,
125
- });
126
-
127
- // Import CSV data with auto-detection of numbers, booleans, and JSON structures
128
- const { rowCount } = await client.importFromCsv('vaccines', csvData, {
129
- mode: 'merge', // 'merge' or 'replace'
130
- skipOutbox: true,
131
- });
132
- console.log(`Successfully imported ${rowCount} rows`);
133
- ```