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.
- package/README.md +5 -2
- package/bin/local-lite.mjs +65 -61
- package/dist/auth/apple.d.ts +3 -4
- package/dist/auth/apple.js +26 -3
- package/dist/auth/github.d.ts +3 -5
- package/dist/auth/github.js +18 -4
- package/dist/auth/google.d.ts +3 -6
- package/dist/auth/google.js +19 -5
- package/dist/auth/identity.d.ts +42 -0
- package/dist/auth/identity.js +63 -0
- package/dist/auth/index.d.ts +2 -0
- package/dist/auth/index.js +2 -0
- package/dist/auth/local.d.ts +33 -1
- package/dist/auth/local.js +94 -13
- package/dist/auth/microsoft.d.ts +3 -5
- package/dist/auth/microsoft.js +16 -3
- package/dist/auth/session.d.ts +4 -0
- package/dist/auth/session.js +19 -1
- package/dist/auth/unified.d.ts +73 -0
- package/dist/auth/unified.js +188 -0
- package/package.json +1 -2
- package/skills/local-lite-auth/SKILL.md +67 -27
- package/skills/local-lite-server/SKILL.md +127 -0
- package/docs/.nojekyll +0 -1
- package/docs/README.md +0 -108
- package/docs/_sidebar.md +0 -22
- package/docs/actions-email.md +0 -222
- package/docs/adapters-local.md +0 -272
- package/docs/adapters-remote.md +0 -291
- package/docs/api-keys.md +0 -114
- package/docs/architecture.md +0 -106
- package/docs/auth.md +0 -342
- package/docs/backups.md +0 -214
- package/docs/breaking-changes.md +0 -147
- package/docs/client-api.md +0 -412
- package/docs/configuration.md +0 -228
- package/docs/conflict-resolution.md +0 -78
- package/docs/getting-started.md +0 -190
- package/docs/google-auth.md +0 -234
- package/docs/index.html +0 -166
- package/docs/kv.md +0 -89
- package/docs/maintenance-portability.md +0 -133
- package/docs/react-hooks.md +0 -457
- package/docs/scheduler.md +0 -81
- package/docs/search.md +0 -71
- package/docs/server.md +0 -101
- package/docs/session.md +0 -129
- package/docs/storage.md +0 -265
package/docs/breaking-changes.md
DELETED
|
@@ -1,147 +0,0 @@
|
|
|
1
|
-
# Breaking Changes and AI Code-Review Guide
|
|
2
|
-
|
|
3
|
-
This guide records breaking changes introduced in `local-lite` 0.0.30 and gives
|
|
4
|
-
an actionable checklist for reviewing an application or repository update.
|
|
5
|
-
Use it when upgrading to this version or when asking an AI assistant to check
|
|
6
|
-
whether dependent code needs changes.
|
|
7
|
-
|
|
8
|
-
## AI review prompt
|
|
9
|
-
|
|
10
|
-
Copy this prompt into your code-review request:
|
|
11
|
-
|
|
12
|
-
> Review this codebase for required updates against
|
|
13
|
-
> [`docs/breaking-changes.md`](./breaking-changes.md). Search application code,
|
|
14
|
-
> configuration, tests, examples, and custom adapters for every affected API.
|
|
15
|
-
> Report each match with file and line, explain whether it needs a change, and
|
|
16
|
-
> suggest a minimal migration. Do not edit files unless asked. Do not treat
|
|
17
|
-
> unrelated uses of the same words as API usage.
|
|
18
|
-
|
|
19
|
-
This guide ships with the package at
|
|
20
|
-
`node_modules/local-lite/docs/breaking-changes.md`. A ready-made skill is at
|
|
21
|
-
`node_modules/local-lite/skills/local-lite-upgrade/SKILL.md` (setup and custom
|
|
22
|
-
adapter skills live beside it); copy the folders
|
|
23
|
-
into `.github/skills/` (Copilot) or `.claude/skills/` (Claude Code).
|
|
24
|
-
|
|
25
|
-
## Changes in 0.0.30
|
|
26
|
-
|
|
27
|
-
### 1. Repeat-on-initialize `migrations` option removed
|
|
28
|
-
|
|
29
|
-
The `migrations: string[]` option was removed from `LocalLiteConfig` and
|
|
30
|
-
`LocalFirstClientConfig`. Passing it to `createSyncClient()` or the
|
|
31
|
-
`LocalFirstClient` constructor now throws. Use versioned `schemaMigrations`
|
|
32
|
-
instead.
|
|
33
|
-
|
|
34
|
-
```typescript
|
|
35
|
-
schemaMigrations: [
|
|
36
|
-
{
|
|
37
|
-
version: 1,
|
|
38
|
-
up: 'CREATE TABLE notes (id TEXT PRIMARY KEY, title TEXT NOT NULL)',
|
|
39
|
-
},
|
|
40
|
-
{
|
|
41
|
-
version: 2,
|
|
42
|
-
up: 'ALTER TABLE notes ADD COLUMN archived INTEGER NOT NULL DEFAULT 0',
|
|
43
|
-
},
|
|
44
|
-
],
|
|
45
|
-
```
|
|
46
|
-
|
|
47
|
-
**Review checklist**
|
|
48
|
-
|
|
49
|
-
- Find configuration properties named `migrations` and confirm they are the
|
|
50
|
-
removed local-lite option, not another library's setting or a local variable.
|
|
51
|
-
- Convert SQL into consecutive, one-time `schemaMigrations` entries.
|
|
52
|
-
- Preserve the complete migration history in the application so existing
|
|
53
|
-
installations can upgrade. Do not simply rename the array: old statements
|
|
54
|
-
ran on every initialization, while versioned migrations run once.
|
|
55
|
-
- Update config helpers, test fixtures, and migration-related documentation.
|
|
56
|
-
|
|
57
|
-
### 2. Expo legacy FileSystem API removed
|
|
58
|
-
|
|
59
|
-
`ExpoFileDriver` now uses Expo SDK 58+ `File`, `Directory`, and `Paths`.
|
|
60
|
-
The `fileSystem` constructor option and legacy `expo-file-system` methods such
|
|
61
|
-
as `writeAsStringAsync`, `getInfoAsync`, `copyAsync`, and `downloadAsync` are no
|
|
62
|
-
longer supported.
|
|
63
|
-
|
|
64
|
-
```typescript
|
|
65
|
-
import { File, Directory, Paths } from 'expo-file-system';
|
|
66
|
-
import { ExpoFileDriver } from 'local-lite/storage';
|
|
67
|
-
|
|
68
|
-
const driver = new ExpoFileDriver({ File, Directory, Paths });
|
|
69
|
-
```
|
|
70
|
-
|
|
71
|
-
The `baseDir` and `useCache` options remain available.
|
|
72
|
-
|
|
73
|
-
**Review checklist**
|
|
74
|
-
|
|
75
|
-
- Find `new ExpoFileDriver({ fileSystem: ... })` and replace it with the modern
|
|
76
|
-
named API options.
|
|
77
|
-
- Check Expo dependencies and runtime versions; the modern APIs require Expo
|
|
78
|
-
SDK 58 or newer.
|
|
79
|
-
- Replace direct legacy FileSystem calls in integrations with `File` operations
|
|
80
|
-
or `ExpoFileDriver` methods.
|
|
81
|
-
- Review tests and examples for legacy mocks or imports.
|
|
82
|
-
|
|
83
|
-
### 3. Custom realtime adapters must return cleanup
|
|
84
|
-
|
|
85
|
-
`RemoteDBAdapter.subscribeToLiveChanges()` now has the required return type
|
|
86
|
-
`() => void`. Every custom adapter implementation must return a function that
|
|
87
|
-
unsubscribes its listener. If no listener is created, return a no-op function.
|
|
88
|
-
|
|
89
|
-
```typescript
|
|
90
|
-
subscribeToLiveChanges(callback: (changes: DeltaChanges) => void): () => void {
|
|
91
|
-
if (!this.canSubscribe()) return () => {};
|
|
92
|
-
|
|
93
|
-
const subscription = this.startSubscription(callback);
|
|
94
|
-
return () => subscription.unsubscribe();
|
|
95
|
-
}
|
|
96
|
-
```
|
|
97
|
-
|
|
98
|
-
**Review checklist**
|
|
99
|
-
|
|
100
|
-
- Find classes and object literals implementing `RemoteDBAdapter`.
|
|
101
|
-
- Confirm all code paths, including missing clients, empty table lists, and
|
|
102
|
-
initialization failures, return a cleanup function.
|
|
103
|
-
- Confirm cleanup is safe to call once and prevents callbacks from a stopped or
|
|
104
|
-
replaced subscription.
|
|
105
|
-
- Update mocks and test adapters to match the required signature.
|
|
106
|
-
|
|
107
|
-
### 4. `_migrations` is no longer an internal table name
|
|
108
|
-
|
|
109
|
-
`isInternalTable('_migrations')` now returns `false`. The name is not treated as
|
|
110
|
-
a local-lite engine table and may consequently appear in APIs that filter
|
|
111
|
-
internal tables, such as `getTables()` and maintenance reports.
|
|
112
|
-
|
|
113
|
-
**Review checklist**
|
|
114
|
-
|
|
115
|
-
- Find uses of `_migrations` as an application table or as a local-lite
|
|
116
|
-
bookkeeping table.
|
|
117
|
-
- If an application uses this name and expects it to be hidden, rename the
|
|
118
|
-
application table or filter it explicitly in the application.
|
|
119
|
-
- Do not rename or delete stored tables as part of an automated upgrade without
|
|
120
|
-
confirming their ownership and contents.
|
|
121
|
-
|
|
122
|
-
### 5. FTS tokenizer errors now propagate
|
|
123
|
-
|
|
124
|
-
FTS table creation no longer retries without the `tokenize` option after a
|
|
125
|
-
tokenizer error. A configured tokenizer that the SQLite build does not support
|
|
126
|
-
causes search initialization to fail instead of silently creating a table with
|
|
127
|
-
different tokenization behavior.
|
|
128
|
-
|
|
129
|
-
**Review checklist**
|
|
130
|
-
|
|
131
|
-
- Find `client.search` configurations that set a custom tokenizer.
|
|
132
|
-
- Verify the target SQLite build supports the configured tokenizer and FTS5.
|
|
133
|
-
- Test search initialization and representative queries on every supported
|
|
134
|
-
platform/build.
|
|
135
|
-
- Resolve an unsupported tokenizer by selecting one supported by the target
|
|
136
|
-
runtime or correcting the SQLite build; do not rely on an implicit tokenizer
|
|
137
|
-
fallback.
|
|
138
|
-
|
|
139
|
-
## Suggested review output
|
|
140
|
-
|
|
141
|
-
For each potential issue, report:
|
|
142
|
-
|
|
143
|
-
1. File and line.
|
|
144
|
-
2. Which change above applies.
|
|
145
|
-
3. Whether a code update is required or the match is unrelated.
|
|
146
|
-
4. The smallest safe migration.
|
|
147
|
-
5. Any behavior or stored-data risk that needs application-owner confirmation.
|
package/docs/client-api.md
DELETED
|
@@ -1,412 +0,0 @@
|
|
|
1
|
-
# 💻 Client API & Query Builder
|
|
2
|
-
|
|
3
|
-
The `LocalFirstClient` is the core synchronization and database interface for `local-lite`. It manages local SQLite operations, the transactional outbox queue, background synchronization, and reactive listeners.
|
|
4
|
-
|
|
5
|
-
```typescript
|
|
6
|
-
import { LocalFirstClient } from 'local-lite';
|
|
7
|
-
// or from 'local-lite/config' via createSyncClient(config)
|
|
8
|
-
```
|
|
9
|
-
|
|
10
|
-
---
|
|
11
|
-
|
|
12
|
-
## 1. Lifecycle & Connection Management
|
|
13
|
-
|
|
14
|
-
### `client.initialize(): Promise<void>`
|
|
15
|
-
Initializes SQLite storage: sets PRAGMA modes (WAL, synchronous NORMAL), ensures internal tables (`sync_outbox`, `sync_meta`), applies configured versioned `schemaMigrations`, creates tables if `autoSchema: true`, and starts background sync loops if `autoStart: true`. Migrations are applied once and recorded locally before sync starts.
|
|
16
|
-
Safe to call concurrently or repeatedly.
|
|
17
|
-
|
|
18
|
-
```typescript
|
|
19
|
-
await client.initialize();
|
|
20
|
-
console.log('Client ready:', client.isReady);
|
|
21
|
-
```
|
|
22
|
-
|
|
23
|
-
### `client.stop(): void`
|
|
24
|
-
Pauses all background sync loops, intervals, and network event listeners. Queued mutations remain safe in the outbox.
|
|
25
|
-
|
|
26
|
-
```typescript
|
|
27
|
-
client.stop();
|
|
28
|
-
```
|
|
29
|
-
|
|
30
|
-
### `client.close(): Promise<void>`
|
|
31
|
-
Stops sync workers, destroys remote subscriptions, and closes the local SQLite connection, safely releasing native database locks.
|
|
32
|
-
|
|
33
|
-
```typescript
|
|
34
|
-
await client.close();
|
|
35
|
-
```
|
|
36
|
-
|
|
37
|
-
### `client.reset(options?: { dropTables?: boolean }): Promise<void>`
|
|
38
|
-
Resets local state by stopping sync, deleting or dropping all managed tables, clearing `sync_outbox` and `sync_meta`, and resetting the sync watermark cursor.
|
|
39
|
-
|
|
40
|
-
```typescript
|
|
41
|
-
// Clear all rows from managed tables and reset outbox
|
|
42
|
-
await client.reset();
|
|
43
|
-
|
|
44
|
-
// Or completely drop all tables from SQLite
|
|
45
|
-
await client.reset({ dropTables: true });
|
|
46
|
-
```
|
|
47
|
-
|
|
48
|
-
---
|
|
49
|
-
|
|
50
|
-
## 2. Atomic Dual-Write Mutations (CRUD)
|
|
51
|
-
|
|
52
|
-
Every write operation executes inside an atomic SQLite transaction that modifies the target table and appends a record to `sync_outbox` simultaneously.
|
|
53
|
-
|
|
54
|
-
### `client.insert(table, payload, options?): Promise<string>`
|
|
55
|
-
Inserts a record and generates a UUID v4 if an `id` is not provided.
|
|
56
|
-
|
|
57
|
-
```typescript
|
|
58
|
-
// Auto-generated UUID
|
|
59
|
-
const todoId = await client.insert('todos', {
|
|
60
|
-
title: 'Review PR',
|
|
61
|
-
completed: 0,
|
|
62
|
-
});
|
|
63
|
-
|
|
64
|
-
// Explicit ID
|
|
65
|
-
await client.insert('todos', 'custom-uuid-123', {
|
|
66
|
-
title: 'Custom ID Item',
|
|
67
|
-
completed: 0,
|
|
68
|
-
});
|
|
69
|
-
```
|
|
70
|
-
|
|
71
|
-
### `client.insertMany(table, records, options?): Promise<string[]>`
|
|
72
|
-
Inserts multiple records in a single atomic database transaction.
|
|
73
|
-
|
|
74
|
-
```typescript
|
|
75
|
-
const ids = await client.insertMany('todos', [
|
|
76
|
-
{ title: 'Task 1', completed: 0 },
|
|
77
|
-
{ title: 'Task 2', completed: 1 },
|
|
78
|
-
]);
|
|
79
|
-
```
|
|
80
|
-
|
|
81
|
-
### `client.update(table, id, payload, options?): Promise<void>`
|
|
82
|
-
Updates an existing record by its primary key.
|
|
83
|
-
|
|
84
|
-
```typescript
|
|
85
|
-
await client.update('todos', todoId, {
|
|
86
|
-
completed: 1,
|
|
87
|
-
});
|
|
88
|
-
```
|
|
89
|
-
|
|
90
|
-
### `client.updateMany(table, updates, options?): Promise<void>`
|
|
91
|
-
Updates multiple records atomically in a single transaction.
|
|
92
|
-
|
|
93
|
-
```typescript
|
|
94
|
-
await client.updateMany('todos', [
|
|
95
|
-
{ id: 'id-1', payload: { completed: 1 } },
|
|
96
|
-
{ id: 'id-2', payload: { completed: 0 } },
|
|
97
|
-
]);
|
|
98
|
-
```
|
|
99
|
-
|
|
100
|
-
### `client.delete(table, id, options?): Promise<void>`
|
|
101
|
-
Deletes a record by its primary key.
|
|
102
|
-
|
|
103
|
-
```typescript
|
|
104
|
-
await client.delete('todos', todoId);
|
|
105
|
-
```
|
|
106
|
-
|
|
107
|
-
### `client.mutate(table, id, operation, payload, options?): Promise<void>`
|
|
108
|
-
Low-level atomic dual-write method:
|
|
109
|
-
|
|
110
|
-
```typescript
|
|
111
|
-
await client.mutate('todos', 'todo-1', 'UPDATE', { completed: 1 }, {
|
|
112
|
-
skipOutbox: false, // Set true to skip cloud sync (local only)
|
|
113
|
-
customTimestamp: Date.now(), // Override mutation timestamp
|
|
114
|
-
});
|
|
115
|
-
```
|
|
116
|
-
|
|
117
|
-
### `client.trackMutation(table, id, operation, payload, options?): Promise<string>`
|
|
118
|
-
Appends a mutation to `sync_outbox` without modifying the local table. Useful when performing custom raw SQL operations that need to be synchronized with the remote backend.
|
|
119
|
-
|
|
120
|
-
---
|
|
121
|
-
|
|
122
|
-
## 3. Atomic Batches & Custom Transactions
|
|
123
|
-
|
|
124
|
-
### `client.batch(mutations, options?): Promise<string[]>`
|
|
125
|
-
Executes multiple diverse operations across multiple tables atomically.
|
|
126
|
-
|
|
127
|
-
```typescript
|
|
128
|
-
await client.batch([
|
|
129
|
-
{
|
|
130
|
-
tableName: 'projects',
|
|
131
|
-
rowId: 'proj-1',
|
|
132
|
-
operation: 'INSERT',
|
|
133
|
-
payload: { name: 'Mobile App' },
|
|
134
|
-
},
|
|
135
|
-
{
|
|
136
|
-
tableName: 'tasks',
|
|
137
|
-
operation: 'INSERT',
|
|
138
|
-
payload: { project_id: 'proj-1', title: 'Setup Expo' },
|
|
139
|
-
},
|
|
140
|
-
{
|
|
141
|
-
tableName: 'notifications',
|
|
142
|
-
rowId: 'notif-99',
|
|
143
|
-
operation: 'DELETE',
|
|
144
|
-
},
|
|
145
|
-
]);
|
|
146
|
-
```
|
|
147
|
-
|
|
148
|
-
### `client.transaction(action): Promise<T>`
|
|
149
|
-
Executes an arbitrary callback inside an ACID transaction with a scoped `TransactionalClient`. If an error is thrown, all SQLite changes and outbox records roll back, and no change events are emitted.
|
|
150
|
-
|
|
151
|
-
```typescript
|
|
152
|
-
await client.transaction(async (txClient) => {
|
|
153
|
-
await txClient.insert('accounts', { id: 'acc-1', balance: 500 });
|
|
154
|
-
await txClient.update('transfers', 'tr-1', { status: 'COMPLETED' });
|
|
155
|
-
});
|
|
156
|
-
```
|
|
157
|
-
|
|
158
|
-
---
|
|
159
|
-
|
|
160
|
-
## 4. Reading Data & Declarative Queries
|
|
161
|
-
|
|
162
|
-
### `client.findById(table, id, options?): Promise<T | null>`
|
|
163
|
-
Fetches a single record by its primary key. Excludes soft-deleted records by default.
|
|
164
|
-
|
|
165
|
-
```typescript
|
|
166
|
-
const todo = await client.findById('todos', 'todo-1');
|
|
167
|
-
// Include soft-deleted rows:
|
|
168
|
-
const deletedTodo = await client.findById('todos', 'todo-1', { includeDeleted: true });
|
|
169
|
-
```
|
|
170
|
-
|
|
171
|
-
### `client.findByIds(table, ids, options?): Promise<T[]>`
|
|
172
|
-
Fetches multiple records by their primary keys in a single `WHERE id IN (...)` query.
|
|
173
|
-
|
|
174
|
-
```typescript
|
|
175
|
-
const items = await client.findByIds('todos', ['todo-1', 'todo-2', 'todo-3']);
|
|
176
|
-
```
|
|
177
|
-
|
|
178
|
-
### `client.findMany(table, options?): Promise<T[]>`
|
|
179
|
-
Fetches records matching declarative filtering and sorting options.
|
|
180
|
-
|
|
181
|
-
```typescript
|
|
182
|
-
const activeWork = await client.findMany('tasks', {
|
|
183
|
-
where: {
|
|
184
|
-
completed: 0,
|
|
185
|
-
priority: { $gte: 2 },
|
|
186
|
-
tags: { $contains: 'urgent' },
|
|
187
|
-
},
|
|
188
|
-
orderBy: 'due_date',
|
|
189
|
-
order: 'asc',
|
|
190
|
-
limit: 25,
|
|
191
|
-
offset: 0,
|
|
192
|
-
});
|
|
193
|
-
```
|
|
194
|
-
|
|
195
|
-
### Supported Query Operators:
|
|
196
|
-
|
|
197
|
-
| Operator | Syntax | Description | Example |
|
|
198
|
-
| :--- | :--- | :--- | :--- |
|
|
199
|
-
| **`$eq`** | `{ col: { $eq: val } }` or `{ col: val }` | Equal to | `{ status: 'ACTIVE' }` |
|
|
200
|
-
| **`$ne`** | `{ col: { $ne: val } }` | Not equal to | `{ status: { $ne: 'DELETED' } }` |
|
|
201
|
-
| **`$gt` / `$gte`** | `{ col: { $gt: val } }` | Greater than (or equal) | `{ age: { $gte: 18 } }` |
|
|
202
|
-
| **`$lt` / `$lte`** | `{ col: { $lt: val } }` | Less than (or equal) | `{ price: { $lte: 99.99 } }` |
|
|
203
|
-
| **`$in`** | `{ col: { $in: [a, b] } }` | In set | `{ role: { $in: ['admin', 'manager'] } }` |
|
|
204
|
-
| **`$nin`** | `{ col: { $nin: [a, b] } }` | Not in set | `{ status: { $nin: ['archived'] } }` |
|
|
205
|
-
| **`$like`** | `{ col: { $like: '%term%' } }` | SQL LIKE pattern | `{ name: { $like: 'John%' } }` |
|
|
206
|
-
| **`$contains`** | `{ col: { $contains: 'word' } }` | Case-insensitive substring | `{ email: { $contains: '@gmail' } }` |
|
|
207
|
-
| **`$between`** | `{ col: { $between: [min, max] } }` | Between range (inclusive) | `{ score: { $between: [70, 100] } }` |
|
|
208
|
-
| **`$isNull`** | `{ col: { $isNull: true } }` | IS NULL | `{ deleted_at: { $isNull: true } }` |
|
|
209
|
-
| **`$isNotNull`** | `{ col: { $isNotNull: true } }` | IS NOT NULL | `{ verified_at: { $isNotNull: true } }` |
|
|
210
|
-
| **`$or`** | `{ $or: [condA, condB] }` | Logical OR | `{ $or: [{ role: 'admin' }, { points: { $gt: 100 } }] }` |
|
|
211
|
-
| **`$and`** | `{ $and: [condA, condB] }` | Logical AND | `{ $and: [{ active: 1 }, { verified: 1 }] }` |
|
|
212
|
-
|
|
213
|
-
---
|
|
214
|
-
|
|
215
|
-
## 5. Fluent SQL QueryBuilder (`client.from()`)
|
|
216
|
-
|
|
217
|
-
Build optimized relational queries with joins, grouping, and method chaining:
|
|
218
|
-
|
|
219
|
-
```typescript
|
|
220
|
-
const report = await client
|
|
221
|
-
.from('orders')
|
|
222
|
-
.select(
|
|
223
|
-
'orders.id',
|
|
224
|
-
'orders.total',
|
|
225
|
-
'customers.name AS customer_name',
|
|
226
|
-
'customers.email'
|
|
227
|
-
)
|
|
228
|
-
.join('customers', 'orders.customer_id', 'customers.id')
|
|
229
|
-
.leftJoin('discounts', 'orders.discount_id', 'discounts.id')
|
|
230
|
-
.where({
|
|
231
|
-
'orders.status': 'COMPLETED',
|
|
232
|
-
'orders.total': { $gte: 100 },
|
|
233
|
-
})
|
|
234
|
-
.orderBy('orders.created_at', 'desc')
|
|
235
|
-
.limit(50)
|
|
236
|
-
.execute();
|
|
237
|
-
```
|
|
238
|
-
|
|
239
|
-
---
|
|
240
|
-
|
|
241
|
-
## 6. Native SQL Aggregations
|
|
242
|
-
|
|
243
|
-
Compute metrics natively in SQLite without fetching all rows into memory:
|
|
244
|
-
|
|
245
|
-
### Simple Aggregates:
|
|
246
|
-
```typescript
|
|
247
|
-
const totalUsers = await client.count('users', { where: { active: 1 } });
|
|
248
|
-
const totalRevenue = await client.sum('orders', 'total', { where: { status: 'PAID' } });
|
|
249
|
-
const avgRating = await client.avg('reviews', 'rating');
|
|
250
|
-
```
|
|
251
|
-
|
|
252
|
-
### Multi-Metric Aggregation:
|
|
253
|
-
Calculate count, sums, averages, minimums, and maximums in a single query:
|
|
254
|
-
|
|
255
|
-
```typescript
|
|
256
|
-
const stats = await client.aggregate('receipts', {
|
|
257
|
-
where: { business_id: 'biz_01' },
|
|
258
|
-
count: true,
|
|
259
|
-
sum: ['amount', 'tax', 'discount'],
|
|
260
|
-
avg: ['amount'],
|
|
261
|
-
min: ['created_at'],
|
|
262
|
-
max: ['amount'],
|
|
263
|
-
});
|
|
264
|
-
|
|
265
|
-
console.log(stats.count); // e.g. 150
|
|
266
|
-
console.log(stats.sum?.amount); // e.g. 4520.50
|
|
267
|
-
console.log(stats.avg?.amount); // e.g. 30.14
|
|
268
|
-
console.log(stats.max?.amount); // e.g. 500.00
|
|
269
|
-
```
|
|
270
|
-
|
|
271
|
-
---
|
|
272
|
-
|
|
273
|
-
## 7. Direct Raw SQL (`client.query`)
|
|
274
|
-
|
|
275
|
-
Execute arbitrary SQL statements directly on SQLite with bound parameters:
|
|
276
|
-
|
|
277
|
-
```typescript
|
|
278
|
-
const result = await client.query(`
|
|
279
|
-
SELECT
|
|
280
|
-
strftime('%Y-%m', created_at) AS month,
|
|
281
|
-
COUNT(*) AS total_count,
|
|
282
|
-
SUM(amount) AS monthly_revenue
|
|
283
|
-
FROM invoices
|
|
284
|
-
WHERE deleted = 0
|
|
285
|
-
GROUP BY month
|
|
286
|
-
ORDER BY month DESC
|
|
287
|
-
`);
|
|
288
|
-
```
|
|
289
|
-
|
|
290
|
-
---
|
|
291
|
-
|
|
292
|
-
## 8. JSON Columns & Auto-Hydration
|
|
293
|
-
|
|
294
|
-
SQLite stores JSON as text strings. `local-lite` supports automatic serialization on write and auto-deserialization on read:
|
|
295
|
-
|
|
296
|
-
```typescript
|
|
297
|
-
export const client = new LocalFirstClient({
|
|
298
|
-
local: dbAdapter,
|
|
299
|
-
remote: remoteAdapter,
|
|
300
|
-
// Automatically deserialize specific table columns
|
|
301
|
-
jsonColumns: {
|
|
302
|
-
patients: ['allergies', 'emergency_contacts', 'metadata'],
|
|
303
|
-
milestones: ['measurements'],
|
|
304
|
-
},
|
|
305
|
-
// Or automatically hydrate any column containing valid JSON object/array strings
|
|
306
|
-
autoHydrateJSON: true,
|
|
307
|
-
});
|
|
308
|
-
|
|
309
|
-
// Write normal JavaScript objects:
|
|
310
|
-
await client.insert('patients', {
|
|
311
|
-
name: 'Jane Doe',
|
|
312
|
-
allergies: ['Penicillin', 'Peanuts'],
|
|
313
|
-
});
|
|
314
|
-
|
|
315
|
-
// Read automatically returns arrays/objects, not JSON strings:
|
|
316
|
-
const patient = await client.findById('patients', id);
|
|
317
|
-
console.log(Array.isArray(patient.allergies)); // true
|
|
318
|
-
```
|
|
319
|
-
|
|
320
|
-
---
|
|
321
|
-
|
|
322
|
-
## 9. Dynamic Multi-Tenant User Data Isolation (`syncScope`)
|
|
323
|
-
|
|
324
|
-
For multi-tenant apps or applications where users should only pull and push their own data:
|
|
325
|
-
|
|
326
|
-
```typescript
|
|
327
|
-
export const client = new LocalFirstClient({
|
|
328
|
-
local: dbAdapter,
|
|
329
|
-
remote: remoteAdapter,
|
|
330
|
-
// Static scope:
|
|
331
|
-
syncScope: { user_id: 'user_abc123' },
|
|
332
|
-
|
|
333
|
-
// Or dynamic async scope function:
|
|
334
|
-
syncScope: async () => {
|
|
335
|
-
const session = await authClient.getUser();
|
|
336
|
-
return session ? { user_id: session.id, organization_id: session.orgId } : {};
|
|
337
|
-
},
|
|
338
|
-
});
|
|
339
|
-
|
|
340
|
-
// Update tenant or active user dynamically upon login or switch:
|
|
341
|
-
client.setSyncScope({ user_id: 'new_user_456' });
|
|
342
|
-
```
|
|
343
|
-
|
|
344
|
-
---
|
|
345
|
-
|
|
346
|
-
## 10. Outbox Inspection & Telemetry
|
|
347
|
-
|
|
348
|
-
Inspect and control the transactional outbox:
|
|
349
|
-
|
|
350
|
-
```typescript
|
|
351
|
-
// 1. Get real-time performance telemetry
|
|
352
|
-
const metrics = await client.getMetrics();
|
|
353
|
-
console.log(metrics.totalPushedMutations);
|
|
354
|
-
console.log(metrics.totalPulledDeltas);
|
|
355
|
-
console.log(metrics.lastPushDurationMs);
|
|
356
|
-
console.log(metrics.lastPullDurationMs);
|
|
357
|
-
|
|
358
|
-
// 2. Fetch pending or failed outbox records
|
|
359
|
-
const records = await client.getOutboxRecords({
|
|
360
|
-
status: 'FAILED',
|
|
361
|
-
limit: 50,
|
|
362
|
-
});
|
|
363
|
-
|
|
364
|
-
// 3. Retry failed mutations (resets status to PENDING and triggers immediate push)
|
|
365
|
-
await client.retryFailedMutations();
|
|
366
|
-
|
|
367
|
-
// 4. Remove poison-pill mutations permanently
|
|
368
|
-
await client.clearFailedMutations();
|
|
369
|
-
|
|
370
|
-
// 5. Inspect and reset pull cursor
|
|
371
|
-
const lastSyncedAt = await client.getLastSyncedAt();
|
|
372
|
-
await client.resetSyncCursor(); // Forces next pull to re-fetch all cloud data
|
|
373
|
-
```
|
|
374
|
-
|
|
375
|
-
---
|
|
376
|
-
|
|
377
|
-
## 11. Action Outbox & Email Queue (`client.actions`)
|
|
378
|
-
|
|
379
|
-
Enqueues asynchronous actions (emails, notifications, webhooks) with offline durability, idempotency deduplication, and automatic retries.
|
|
380
|
-
|
|
381
|
-
```typescript
|
|
382
|
-
// Enqueue an email offline (instant 0ms local write)
|
|
383
|
-
const emailAction = await client.actions.sendEmail({
|
|
384
|
-
to: 'customer@example.com',
|
|
385
|
-
subject: 'Order Confirmed',
|
|
386
|
-
html: '<h1>Thank you!</h1>',
|
|
387
|
-
idempotencyKey: 'order_123',
|
|
388
|
-
ttlMs: 24 * 60 * 60 * 1000,
|
|
389
|
-
});
|
|
390
|
-
|
|
391
|
-
// Register an email dispatcher
|
|
392
|
-
client.actions.registerEmailHandler(async (email) => {
|
|
393
|
-
const res = await sendWithProvider(email);
|
|
394
|
-
return { messageId: res.id };
|
|
395
|
-
});
|
|
396
|
-
|
|
397
|
-
// Enqueue generic offline actions
|
|
398
|
-
await client.actions.enqueue({
|
|
399
|
-
action: 'push_notification',
|
|
400
|
-
payload: { title: 'New message', token: 'fcm-xxx' },
|
|
401
|
-
});
|
|
402
|
-
|
|
403
|
-
// Flush pending actions immediately
|
|
404
|
-
await client.actions.flush();
|
|
405
|
-
|
|
406
|
-
// Query, cancel, or prune actions
|
|
407
|
-
const action = await client.actions.get(emailAction.id);
|
|
408
|
-
await client.actions.cancel(emailAction.id);
|
|
409
|
-
await client.actions.prune({ completedOlderThanMs: 86400000 });
|
|
410
|
-
```
|
|
411
|
-
|
|
412
|
-
See the dedicated [**Action Outbox & Email Queue Guide**](./actions-email.md) for full architecture, cloud function integration, and options reference.
|