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,228 +0,0 @@
1
- # ⚙️ Configuration Reference
2
-
3
- The configuration engine uses `defineSyncConfig(config)` to provide full TypeScript autocompletion and compile-time validation.
4
-
5
- ```typescript
6
- import { defineSyncConfig, createSyncClient } from 'local-lite/config';
7
- ```
8
-
9
- ---
10
-
11
- ## Complete `LocalLiteConfig` Options
12
-
13
- ### Database, Tables & Schema
14
-
15
- | Option | Type | Default | Description |
16
- | :--- | :--- | :--- | :--- |
17
- | `database` | `any \| string \| (() => Promise<any>) \| LocalDBAdapter` | Optional | Database instance, factory function, or custom adapter. |
18
- | `databaseName` | `string` | Not set | Database filename when auto-opening via `expo-sqlite`. |
19
- | `tables` | `string[]` | `[]` | List of table names to synchronize. |
20
- | `relationships` | `RelationshipDefinition[]` | `[]` | Parent-child relationships and delete behavior handled by local-lite mutation methods. |
21
- | `autoSchema` | `boolean` | `false` | When true, automatically creates tables and adds missing columns dynamically on insert/update. |
22
- | `primaryKey` | `string` | `'id'` | Primary key column name used across tables. |
23
- | `schemaMigrations` | `SchemaMigration[]` | `[]` | Consecutive, versioned SQL migrations applied once and recorded in the local `schema_migrations` table. |
24
- | `autoStart` | `boolean` | `true` | Start automatic sync after initialization. Set false to queue writes and push/pull manually. |
25
- | `autoInitialize` | `boolean` | `true` | Automatically creates internal outbox tables and initializes the client on startup. |
26
-
27
- ### Relationship delete behavior
28
-
29
- Configure child-table foreign keys in `relationships`. When a parent is deleted through
30
- `client.delete()`, `client.mutate(..., 'DELETE')`, a transaction, or `client.batch()`,
31
- local-lite applies each relationship's `onDelete` action atomically and records the
32
- resulting child mutations in the outbox. Include both parent and child tables in
33
- `tables` when that list is configured. Relationship table/column names are checked
34
- for required values and supported delete actions are validated during client setup.
35
-
36
- ```typescript
37
- const config = defineSyncConfig({
38
- tables: ['children', 'milestones', 'visits'],
39
- relationships: [
40
- {
41
- table: 'milestones',
42
- foreignKey: 'childId',
43
- references: 'children',
44
- onDelete: 'cascade',
45
- },
46
- {
47
- table: 'visits',
48
- foreignKey: 'childId',
49
- references: 'children',
50
- onDelete: 'restrict',
51
- },
52
- ],
53
- });
54
- ```
55
-
56
- Supported actions are `cascade` (delete referencing rows recursively), `restrict`
57
- (reject when referencing rows exist), `setNull` (clear the foreign key), and `noAction`
58
- (the default, which also rejects immediately when referencing rows exist). `restrict`
59
- and `noAction` therefore have the same behavior in local-lite. The child foreign-key
60
- column must allow `NULL` when using `setNull`. `references` names the parent table;
61
- local-lite uses the configured primary key, which defaults to `id`.
62
-
63
- ### Versioned schema migrations
64
-
65
- Use `schemaMigrations` to apply app schema changes once in ascending version order.
66
- Keep the full migration history in the app so an older local database can catch up
67
- after an upgrade. Versions must be consecutive integers starting at `1`. Each
68
- migration runs in the database transaction and is recorded only after its SQL
69
- succeeds. A migration failure rolls back the migration batch and prevents sync
70
- from starting. Migrations only move forward; write additive SQL when old app
71
- versions or stored data must remain compatible.
72
-
73
- ```typescript
74
- schemaMigrations: [
75
- {
76
- version: 1,
77
- up: 'CREATE TABLE todos (id TEXT PRIMARY KEY, title TEXT NOT NULL)',
78
- },
79
- {
80
- version: 2,
81
- up: 'ALTER TABLE todos ADD COLUMN completed INTEGER NOT NULL DEFAULT 0',
82
- },
83
- ],
84
- ```
85
-
86
- The legacy `migrations` option has been removed. Move each SQL statement into a
87
- versioned entry in `schemaMigrations`; migrations now run once and are tracked in
88
- the local `schema_migrations` table.
89
-
90
- `autoSchema` remains available for inferred schemas, but explicit migrations are
91
- recommended when you need predictable upgrades. If both are configured, migrations
92
- run before `autoSchema`.
93
-
94
- ---
95
-
96
- ### Sync Performance & Advanced SQLite Policies
97
-
98
- | Option | Type | Default | Description |
99
- | :--- | :--- | :--- | :--- |
100
- | `coalesceOutbox` | `boolean` | `true` | When true, multiple pending mutations for the same row are coalesced into a single outbox record before pushing (e.g. intermediate updates are merged, and an insert followed by an offline delete is discarded), drastically reducing bandwidth. |
101
- | `touchUpdatedAt` | `boolean \| string` | `true` | Stamps an `updated_at` (or specified column name) on every local INSERT/UPDATE write in SQLite so reactive queries (which compare rows by `id` + `updated_at`) immediately detect offline edits. Only the local row is stamped; remote outbox payloads are untouched. |
102
- | `autoPauseOnBackground` | `boolean` | `true` | When true on React Native/Expo, automatically pauses polling intervals and timers when the app moves to the background to conserve device battery and CPU, and resumes immediately upon foregrounding. |
103
- | `jsonColumns` | `Record<string, string[]>` | `{}` | Map of table names to arrays of column names containing JSON data. These columns are automatically serialized to JSON strings on write and parsed back to JavaScript objects/arrays on read. |
104
- | `autoHydrateJSON` | `boolean` | `false` | When true, any string value that begins and ends with `{}` or `[]` is automatically parsed with `JSON.parse` upon query execution. |
105
-
106
- ---
107
-
108
- ### Dynamic User Data Isolation & Multi-Tenancy (`syncScope`)
109
-
110
- For multi-tenant apps or applications where users should only push and pull records matching their account ID:
111
-
112
- ```typescript
113
- export const syncConfig = defineSyncConfig({
114
- database: () => SQLite.openDatabaseAsync('app.db'),
115
- tables: ['milestones', 'records'],
116
-
117
- // Static user scope:
118
- syncScope: { user_id: 'user_123' },
119
-
120
- // Or dynamic async scope function:
121
- syncScope: async () => {
122
- const user = await authClient.getUser();
123
- return user ? { user_id: user.id } : {};
124
- },
125
- });
126
- ```
127
-
128
- * The active scope is passed down to `remoteAdapter.fetchChanges(since, syncScope)` to filter remote delta queries.
129
- * In Supabase, queries filter matching columns automatically.
130
- * You can update the scope dynamically after login with `client.setSyncScope({ user_id: user.id })`.
131
-
132
- ---
133
-
134
- ### Remote Cloud Backends
135
-
136
- Provide **one** of the following backend options:
137
-
138
- #### `supabase`
139
- ```typescript
140
- supabase: {
141
- url?: string; // Supabase Project URL (e.g. process.env.EXPO_PUBLIC_SUPABASE_URL)
142
- anonKey?: string; // Supabase Anon / Publishable Key
143
- client?: SupabaseClient; // Optional pre-instantiated Supabase client
144
- schema?: string; // Postgres schema (Default: 'public')
145
- updatedAtColumn?: string; // Timestamp column for deltas (Default: 'updated_at')
146
- deletedColumn?: string; // Column for soft deletes (Default: 'deleted')
147
- deletedValue?: any; // Value for deleted rows (Default: true)
148
- pushRpcName?: string; // Optional custom RPC name for bulk operations
149
- channelName?: string; // Realtime broadcast channel name (Default: 'local_first_sync')
150
- }
151
- ```
152
-
153
- #### `convex`
154
- ```typescript
155
- convex: {
156
- client: ConvexClient; // Instantiated ConvexClient
157
- pushMutation?: any; // Mutation function/name for pushes (Default: 'sync:pushBatch')
158
- pullQuery?: any; // Query function/name for deltas (Default: 'sync:pullDeltas')
159
- primaryKey?: string; // Primary key column name (Default: 'id')
160
- deletedColumn?: string; // Column for soft deletes (Default: 'deleted')
161
- updatedAtColumn?: string; // Timestamp column for deltas (Default: 'updatedAt')
162
- }
163
- ```
164
-
165
- #### `firebase`
166
- ```typescript
167
- firebase: {
168
- firestore: Firestore; // Modular Firestore instance or @react-native-firebase/firestore
169
- primaryKey?: string; // Primary key field (Default: 'id')
170
- updatedAtColumn?: string; // Timestamp field for delta pulls (Default: 'updatedAt')
171
- deletedColumn?: string; // Boolean field for soft deletes (Default: 'deleted')
172
- firestoreModule?: any; // Optional reference to modular firebase/firestore SDK
173
- }
174
- ```
175
-
176
- #### `remote`
177
- Pass an object implementing `RemoteDBAdapter` to connect to custom REST, GraphQL, or WebSocket servers.
178
-
179
- #### `inMemoryRemote`
180
- * Type: `boolean` (Default: `false`)
181
- * Missing backend configuration throws unless `inMemoryRemote: true` is explicitly enabled.
182
- * Simulates an in-memory remote backend with 300ms artificial network delay for unit testing and offline development.
183
-
184
- ---
185
-
186
- ### Timing, Retry & Exponential Backoff
187
-
188
- | Option | Type | Default | Description |
189
- | :--- | :--- | :--- | :--- |
190
- | `pushIntervalMs` | `number` | `5000` | Periodic timer interval (in ms) to flush pending outbox records to remote. |
191
- | `pullIntervalMs` | `number` | `10000` | Periodic timer interval (in ms) to fetch remote deltas. |
192
- | `maxRetries` | `number` | `5` | Maximum push attempts before a failing mutation is marked as `FAILED`. |
193
- | `retry` | `number \| RetryConfig` | — | Advanced retry settings with exponential backoff and jitter. |
194
-
195
- #### Advanced Retry Configuration:
196
- ```typescript
197
- retry: {
198
- maxRetries: Infinity, // Supports infinite retries for persistent background sync
199
- initialDelayMs: 1000, // Delay before the first retry (1 second)
200
- maxDelayMs: 30000, // Max ceiling delay (30 seconds)
201
- backoffMultiplier: 1.5, // Exponential backoff multiplier
202
- jitter: true, // Add randomized jitter to avoid synchronized server stampedes
203
- shouldRetry: (err, op) => {
204
- // Only retry transient network/server errors; fail immediately on 400 Bad Request
205
- if (err?.status === 400) return false;
206
- return true;
207
- },
208
- }
209
- ```
210
-
211
- ---
212
-
213
- ### Logging & Diagnostics
214
-
215
- | Option | Type | Default | Description |
216
- | :--- | :--- | :--- | :--- |
217
- | `logLevel` | `'debug' \| 'info' \| 'warn' \| 'error' \| 'none'` | `'info'` | Minimum log verbosity. |
218
- | `logger` | `SyncLogger \| CustomLogger \| boolean` | Default | Pass `false` to silence all logs, or supply a custom logger (e.g., Sentry, Winston, Datadog). |
219
-
220
- #### Custom Logger Example:
221
- ```typescript
222
- logger: {
223
- debug: (msg, ...args) => console.debug('[Sync]', msg, ...args),
224
- info: (msg, ...args) => console.info('[Sync]', msg, ...args),
225
- warn: (msg, ...args) => console.warn('[Sync]', msg, ...args),
226
- error: (msg, ...args) => Sentry.captureMessage(msg),
227
- }
228
- ```
@@ -1,78 +0,0 @@
1
- # 🛡️ Conflict Resolution
2
-
3
- When multiple offline clients modify the same record concurrently, `local-lite` resolves conflicts during the pull phase.
4
-
5
- ---
6
-
7
- ## 1. Built-in Strategies
8
-
9
- Specify your strategy directly in `defineSyncConfig`:
10
-
11
- ```typescript
12
- export const config = defineSyncConfig({
13
- conflictResolver: 'field-merge', // Options: 'last-write-wins' | 'server-wins' | 'client-wins' | 'field-merge'
14
- });
15
- ```
16
-
17
- ### Strategy Summary:
18
-
19
- | Strategy | Description | Best For |
20
- | :--- | :--- | :--- |
21
- | **`field-merge`** (Recommended) | 3-Way field-level merge. Merges disjoint fields from both local and remote offline edits, and uses timestamps or custom rules for conflicting fields. | Collaborative apps where multiple users edit different properties of the same item. |
22
- | **`last-write-wins`** (Default) | Compares mutation timestamps. The mutation with the most recent timestamp wins the entire record. | Standard apps where record replacement is acceptable. |
23
- | **`server-wins`** | Any incoming remote record overrides uncommitted local edits. | Authoritative server data (banking, ticket inventory). |
24
- | **`client-wins`** | Local changes always override incoming remote changes. | Personal draft tools, private preferences. |
25
-
26
- ---
27
-
28
- ## 2. Smart 3-Way Field-Level Conflict Resolver (`createFieldMergeResolver`)
29
-
30
- Instead of picking all-local or all-remote, `createFieldMergeResolver` intelligently inspects individual columns:
31
- * **Disjoint edits preserved:** If user A modifies `title` offline and user B modifies `notes` on the server, both changes are preserved in the merged row.
32
- * **Granular field rules:** Apply `max`, `min`, `newer`, `local`, `remote`, or custom functions per table and column.
33
- * **Custom delete handling:** Choose whether deletions win (`delete-wins`) or offline edits take precedence (`update-wins`).
34
-
35
- ```typescript
36
- import { createFieldMergeResolver } from 'local-lite';
37
- import { defineSyncConfig } from 'local-lite/config';
38
-
39
- export const config = defineSyncConfig({
40
- conflictResolver: createFieldMergeResolver({
41
- defaultWinner: 'newer', // Default for overlapping fields without explicit rules
42
- deleteHandling: 'delete-wins',
43
- fieldRules: {
44
- notes: {
45
- // Automatically union tag arrays
46
- tags: (localTags, remoteTags) =>
47
- Array.from(new Set([...(localTags ?? []), ...(remoteTags ?? [])])),
48
- // Highest counter wins
49
- view_count: 'max',
50
- },
51
- '*': {
52
- updated_at: 'newer',
53
- },
54
- },
55
- }),
56
- });
57
- ```
58
-
59
- ---
60
-
61
- ## 3. Low-Level Custom Conflict Resolvers
62
-
63
- You can also provide a completely custom resolver function:
64
-
65
- ```typescript
66
- import { defineSyncConfig } from 'local-lite/config';
67
- import { ConflictContext } from 'local-lite';
68
-
69
- export const config = defineSyncConfig({
70
- conflictResolver: (context: ConflictContext) => {
71
- const { localOutboxRecord, remoteChange, localRow } = context;
72
-
73
- // Return 'apply-remote' | 'keep-local' | { mergePayload: Record<string, any> }
74
- return 'apply-remote';
75
- },
76
- });
77
- ```
78
-
@@ -1,190 +0,0 @@
1
- # 🚀 Getting Started with local-lite
2
-
3
- This guide walks you through installing `local-lite` and setting up your first offline-first sync pipeline in 5 minutes.
4
-
5
- ---
6
-
7
- ## 1. Installation
8
-
9
- Install the core package:
10
-
11
- ```bash
12
- npm install local-lite
13
- ```
14
-
15
- ### Install Drivers & Backend Dependencies
16
-
17
- Install the SQLite driver for your target platform and your chosen cloud backend:
18
-
19
- #### For Expo (iOS, Android, Web)
20
- ```bash
21
- npx expo install expo-sqlite @react-native-community/netinfo
22
- ```
23
-
24
- #### For Bare React Native
25
- ```bash
26
- npm install @op-engineering/op-sqlite @react-native-community/netinfo
27
- ```
28
-
29
- #### For Node.js / Electron / Desktop
30
- ```bash
31
- npm install better-sqlite3
32
- ```
33
-
34
- #### Cloud Backends (choose one)
35
- ```bash
36
- # If using Supabase
37
- npm install @supabase/supabase-js
38
-
39
- # If using Convex
40
- npm install convex
41
-
42
- # If using Firebase / Firestore
43
- npm install firebase # or @react-native-firebase/firestore
44
- ```
45
-
46
- ---
47
-
48
- ## 2. Define Your Configuration
49
-
50
- Create a file named `sync.config.ts`:
51
-
52
- ```typescript
53
- // src/sync.config.ts
54
- import { defineSyncConfig, createSyncClient, LocalFirstClient } from 'local-lite/config';
55
- import * as SQLite from 'expo-sqlite';
56
-
57
- export const syncConfig = defineSyncConfig({
58
- // 1. Local Database instance or factory
59
- database: () => SQLite.openDatabaseAsync('app.db'),
60
-
61
- // 2. Tables to synchronize
62
- tables: ['todos', 'notes'],
63
-
64
- // 3. Create and evolve the local schema with ordered migrations
65
- schemaMigrations: [
66
- {
67
- version: 1,
68
- up: [
69
- 'CREATE TABLE todos (id TEXT PRIMARY KEY, title TEXT NOT NULL, completed INTEGER NOT NULL DEFAULT 0, updated_at INTEGER NOT NULL)',
70
- 'CREATE TABLE notes (id TEXT PRIMARY KEY, title TEXT, updated_at INTEGER NOT NULL DEFAULT 0)',
71
- ],
72
- },
73
- ],
74
-
75
- // 4. Remote backend credentials (e.g. Supabase, Convex, or in-memory demo)
76
- supabase: {
77
- url: process.env.EXPO_PUBLIC_SUPABASE_URL,
78
- anonKey: process.env.EXPO_PUBLIC_SUPABASE_ANON_KEY,
79
- },
80
-
81
- // 5. Conflict strategy & sync intervals
82
- conflictResolver: 'last-write-wins',
83
- pushIntervalMs: 3000,
84
- pullIntervalMs: 8000,
85
- });
86
-
87
- // Singleton client initializer
88
- let clientPromise: Promise<LocalFirstClient> | null = null;
89
- export function getSyncClient(): Promise<LocalFirstClient> {
90
- if (!clientPromise) {
91
- clientPromise = createSyncClient(syncConfig);
92
- }
93
- return clientPromise;
94
- }
95
- ```
96
-
97
- ---
98
-
99
- ## 3. Build a Reactive UI Component
100
-
101
- Use `useLiveQuery` and `useSyncStatus` in your React or React Native components:
102
-
103
- ```tsx
104
- // src/app/index.tsx
105
- import React, { useState, useEffect } from 'react';
106
- import { View, Text, TextInput, TouchableOpacity, FlatList } from 'react-native';
107
- import { useLiveQuery, useSyncStatus } from 'local-lite/react';
108
- import { LocalFirstClient, generateUUID } from 'local-lite';
109
- import { getSyncClient } from '../sync.config';
110
-
111
- export default function TodoApp() {
112
- const [client, setClient] = useState<LocalFirstClient | null>(null);
113
- const [text, setText] = useState('');
114
-
115
- // 1. Initialize client on mount
116
- useEffect(() => {
117
- getSyncClient().then(setClient);
118
- }, []);
119
-
120
- // 2. Live query: automatically re-renders on local writes & remote pulls
121
- const { data: todos } = useLiveQuery(client, 'todos', {
122
- orderBy: 'updated_at',
123
- order: 'desc',
124
- });
125
-
126
- // 3. Monitor sync engine & pending outbox queue
127
- const { pendingCount, isSyncing, isOnline } = useSyncStatus(client);
128
-
129
- // 4. Instant local write
130
- const handleAddTodo = async () => {
131
- if (!client || !text.trim()) return;
132
- const title = text.trim();
133
- setText('');
134
-
135
- await client.insert('todos', {
136
- id: generateUUID(),
137
- title,
138
- completed: 0,
139
- updated_at: Date.now(),
140
- });
141
- };
142
-
143
- const handleToggle = async (id: string, current: number) => {
144
- if (!client) return;
145
- await client.update('todos', id, {
146
- completed: current ? 0 : 1,
147
- updated_at: Date.now(),
148
- });
149
- };
150
-
151
- return (
152
- <View style={{ flex: 1, padding: 24 }}>
153
- <Text style={{ fontSize: 20, fontWeight: 'bold' }}>Local-First Todos</Text>
154
- <Text style={{ color: '#666', marginBottom: 16 }}>
155
- {pendingCount > 0 ? `Syncing (${pendingCount} pending)...` : 'All changes synced'}
156
- </Text>
157
-
158
- <View style={{ flexDirection: 'row', marginBottom: 16 }}>
159
- <TextInput
160
- value={text}
161
- onChangeText={setText}
162
- placeholder="New task..."
163
- style={{ flex: 1, borderWidth: 1, borderColor: '#ccc', padding: 8, borderRadius: 4 }}
164
- />
165
- <TouchableOpacity onPress={handleAddTodo} style={{ backgroundColor: '#0284c7', padding: 10, marginLeft: 8, borderRadius: 4 }}>
166
- <Text style={{ color: '#fff' }}>Add</Text>
167
- </TouchableOpacity>
168
- </View>
169
-
170
- <FlatList
171
- data={todos}
172
- keyExtractor={(item) => item.id}
173
- renderItem={({ item }) => (
174
- <TouchableOpacity onPress={() => handleToggle(item.id, item.completed)}>
175
- <Text style={{ paddingVertical: 8, textDecorationLine: item.completed ? 'line-through' : 'none' }}>
176
- {item.completed ? '✅' : '⬜'} {item.title}
177
- </Text>
178
- </TouchableOpacity>
179
- )}
180
- />
181
- </View>
182
- );
183
- }
184
- ```
185
-
186
- ---
187
-
188
- ## Next Steps
189
- - Learn how the [Transactional Outbox Architecture](./architecture.md) works under the hood.
190
- - Explore driver guides in [Local Adapters](./adapters-local.md) and [Remote Adapters](./adapters-remote.md).