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
@@ -0,0 +1,127 @@
1
+ ---
2
+ name: local-lite-server
3
+ description: Configure and implement framework-neutral REST API routing and dispatching with local-lite/server. Use when setting up server endpoints (defineServerConfig, createServer), declaring route parameters, implementing middleware pipelines, managing HTTP methods (GET, POST, PUT, DELETE, OPTIONS), 405 Method Not Allowed handling, or dispatching single fetch() requests in Edge, Node, Next.js, or Expo Router API routes.
4
+ ---
5
+
6
+ # local-lite Server API Routing
7
+
8
+ Guide for building framework-neutral REST API handlers, route parameters, middleware pipelines, and request dispatchers using `local-lite/server`.
9
+
10
+ ---
11
+
12
+ ## 1. Overview
13
+
14
+ `local-lite/server` provides a lightweight, framework-agnostic HTTP routing layer using standard Web `Request` and `Response` objects. It is designed for:
15
+ * **Expo Router API Routes** (`app/api/...index+api.ts`)
16
+ * **Next.js App Router Route Handlers** (`app/api/.../route.ts`)
17
+ * **Cloudflare Workers / Edge / Node.js** standalone HTTP servers
18
+ * **Integration Tests** using single-call `server.fetch(request)` dispatchers
19
+
20
+ ---
21
+
22
+ ## 2. Defining Server Configuration (`defineServerConfig`)
23
+
24
+ ```typescript
25
+ // src/server/api.ts
26
+ import { defineServerConfig, createServer } from 'local-lite/server';
27
+
28
+ interface AppServerServices {
29
+ apiKey: string;
30
+ db: any;
31
+ }
32
+
33
+ const config = defineServerConfig<AppServerServices>({
34
+ config: {
35
+ apiKey: process.env.API_SECRET_KEY!,
36
+ db: myBackendDbClient,
37
+ },
38
+ // Middleware executes sequentially in declaration order
39
+ middleware: [
40
+ async (ctx, next) => {
41
+ const authHeader = ctx.request.headers.get('Authorization');
42
+ if (!authHeader) {
43
+ return Response.json({ error: 'Unauthorized' }, { status: 401 });
44
+ }
45
+ return await next();
46
+ },
47
+ ],
48
+ endpoints: {
49
+ '/api/tasks': {
50
+ GET: async (ctx) => {
51
+ const tasks = await ctx.config.db.query('SELECT * FROM tasks');
52
+ return Response.json({ tasks });
53
+ },
54
+ POST: async (ctx) => {
55
+ const body = await ctx.request.json();
56
+ const created = await ctx.config.db.insert('tasks', body);
57
+ return Response.json(created, { status: 201 });
58
+ },
59
+ },
60
+ '/api/tasks/:taskId': {
61
+ GET: async (ctx) => {
62
+ const task = await ctx.config.db.getById('tasks', ctx.params.taskId);
63
+ if (!task) {
64
+ return Response.json({ error: 'Task not found' }, { status: 404 });
65
+ }
66
+ return Response.json(task);
67
+ },
68
+ DELETE: async (ctx) => {
69
+ await ctx.config.db.delete('tasks', ctx.params.taskId);
70
+ return Response.json({ success: true });
71
+ },
72
+ },
73
+ },
74
+ onError(error, context) {
75
+ // Report internal server errors safely to telemetry without leaking stack trace to clients
76
+ console.error(`[Server Error] ${context.path}:`, error);
77
+ },
78
+ });
79
+
80
+ export const apiServer = createServer(config);
81
+ ```
82
+
83
+ ---
84
+
85
+ ## 3. Mounting in Framework Route Handlers
86
+
87
+ ### In Expo Router (`app/api/tasks+api.ts`):
88
+ ```typescript
89
+ import { apiServer } from '@/server/api';
90
+
91
+ export const GET = apiServer.handler('/api/tasks', 'GET');
92
+ export const POST = apiServer.handler('/api/tasks', 'POST');
93
+ ```
94
+
95
+ ### In Dynamic Expo Router Routes (`app/api/tasks/[taskId]+api.ts`):
96
+ ```typescript
97
+ import { apiServer } from '@/server/api';
98
+
99
+ export const GET = apiServer.handler('/api/tasks/:taskId', 'GET');
100
+ export const DELETE = apiServer.handler('/api/tasks/:taskId', 'DELETE');
101
+ ```
102
+
103
+ ---
104
+
105
+ ## 4. Single `fetch()` Dispatcher
106
+
107
+ For platforms mounting a single catch-all handler (Cloudflare Workers, Hono, Node.js HTTP server):
108
+
109
+ ```typescript
110
+ import { apiServer } from './api';
111
+
112
+ export default {
113
+ async fetch(request: Request): Promise<Response> {
114
+ return await apiServer.fetch(request);
115
+ },
116
+ };
117
+ ```
118
+
119
+ ---
120
+
121
+ ## 5. Built-in Behaviors
122
+
123
+ * **Path Matching & Parameters**: Segments prefixed with `:` (e.g. `:taskId`) are automatically extracted and URL-decoded into `ctx.params`.
124
+ * **Method Not Allowed (405)**: If a route exists for `GET` but receives a `DELETE`, it automatically returns status `405` with an RFC-compliant `Allow: GET` header.
125
+ * **Not Found (404)**: Unmatched paths return a standardized `{ error: 'Not Found' }` with status `404`.
126
+ * **Safe Error Handling (500)**: Unhandled errors in middleware or endpoints trigger `onError` server-side and return `{ error: 'Internal Server Error' }` without exposing internal implementation details.
127
+
package/docs/.nojekyll DELETED
@@ -1 +0,0 @@
1
- # Disable Jekyll processing on GitHub Pages
package/docs/README.md DELETED
@@ -1,108 +0,0 @@
1
- # ⚡ local-lite Documentation
2
-
3
- Welcome to the official documentation for **`local-lite`**, a lightweight, vendor-agnostic **local-first synchronization engine** for React Native, Expo, Web, and Node.js applications.
4
-
5
- ---
6
-
7
- ## 📚 Documentation Index
8
-
9
- 1. **[Getting Started](./getting-started.md)**
10
- - Installation & peer dependencies
11
- - 5-minute Quickstart with SQLite & Cloud
12
- 2. **[Architecture & Concepts](./architecture.md)**
13
- - The Transactional Outbox Pattern
14
- - 0ms local reads & writes
15
- - SyncWorker pipeline & infinite loop safety
16
- 3. **[Configuration Reference](./configuration.md)**
17
- - `defineSyncConfig()` and `LocalLiteConfig` options
18
- - User data isolation (`syncScope`), outbox coalescing, JSON auto-hydration, and advanced retry policies
19
- 4. **[Client API & Query Builder](./client-api.md)**
20
- - Atomic dual-write CRUD (`insert`, `update`, `delete`, `mutate`, `trackMutation`)
21
- - Batches (`batch`) and custom transactions (`transaction`)
22
- - Fluent `QueryBuilder` (`from`, `select`, `join`, `where`, `groupBy`, `orderBy`)
23
- - Native SQL aggregations (`count`, `sum`, `avg`, `aggregate`)
24
- - Telemetry & outbox management (`getMetrics`, `retryFailedMutations`, `clearFailedMutations`)
25
- 5. **[Fast Key-Value & Encrypted Preferences](./kv.md)**
26
- - Typed storage for strings, numbers, booleans, and JSON objects (`client.kv`)
27
- - TTL expiration with lazy cleanup and batch pruning
28
- - Zero-Knowledge client-side encrypted secrets (AES-256-GCM + PBKDF2)
29
- - Reactive `useKV()` React hook
30
- 6. **[Instant Full-Text Search](./search.md)**
31
- - Native SQLite FTS5 engine integration (`client.search`)
32
- - Prefix matching, BM25 ranking, and highlighted `<mark>` snippets
33
- - Reactive `useSearch()` React hook with automatic debouncing
34
- 7. **[Offline Media & Blob Storage](./storage.md)**
35
- - Decoupled binary storage from SQLite table queries (`client.storage`)
36
- - Local filesystem and in-memory file drivers with SHA-256 integrity verification
37
- - Background cloud sync queue for S3, Supabase, Cloudinary, and Firebase Storage
38
- 8. **[Offline Job Scheduler & Background Cron](./scheduler.md)**
39
- - Persistent offline job scheduling surviving app restarts (`client.scheduler`)
40
- - Human expressions (`'daily'`, `'hourly'`, `'every 15 minutes'`) and 5-part cron
41
- - Run history tracking, duration telemetry, and automatic error logging
42
- 9. **[Local SQLite Adapters](./adapters-local.md)**
43
- - Expo SQLite (`expo-sqlite`)
44
- - Bare React Native (`@op-engineering/op-sqlite`)
45
- - Node.js / Electron (`better-sqlite3`)
46
- - Built-in Node 22+ (`node:sqlite`)
47
- - Edge / Turso (`@libsql/client`)
48
- - Web / Browser (`sql.js`)
49
- 10. **[Remote Backend Adapters](./adapters-remote.md)**
50
- - Supabase (Postgres + Realtime)
51
- - Convex (Reactive documents + RPCs)
52
- - Firebase / Firestore
53
- - Memory Demo (Mock testing without cloud)
54
- - Building custom backend adapters
55
- 11. **[React & Expo Hooks](./react-hooks.md)**
56
- - `useLiveQuery()`: Zero-SQL single table reactive query
57
- - `useLiveQueries()`: Parallel multi-table queries with single atomic commit
58
- - `useLiveRow()`: Targeted single-record live query with row-level invalidation
59
- - `useLiveInfiniteQuery()`: Paginated infinite scrolling live query
60
- - `useKV()`: Reactive state binding for key-value preferences
61
- - `useSearch()`: Debounced instant full-text search hook
62
- - `useMutations()`: Null-safe memoized mutation helper methods
63
- - `useSyncStatus()`: Real-time sync engine & outbox queue inspector
64
- - `useDatabaseMaintenance()`: Reactive storage stats, outbox pruning, VACUUM, and WAL checkpoints
65
- - `<SyncInspector />` and `<BenchmarkModal />` (from `local-lite/devtools`): Developer UI debugging tools
66
- 12. **[Authentication (Google, Microsoft, GitHub, Apple)](./auth.md)**
67
- - Zero-backend OAuth 2.0 PKCE authentication
68
- - Automatic token refreshing & user profile fetching
69
- - Microsoft Graph & OneDrive integration
70
- - GitHub OAuth with verified email resolution
71
- - Sign in with Apple (Native iOS & OAuth)
72
- - Pluggable storage adapters (AsyncStorage, SecureStore, MMKV)
73
- 13. **[Google Sign-In & Drive Guide](./google-auth.md)**
74
- - Dedicated guide for zero-backend Google authentication
75
- - Unified Google Drive cloud backup synergy
76
- 14. **[Conflict Resolution & Field Merge](./conflict-resolution.md)**
77
- - Smart 3-Way field-level merge (`createFieldMergeResolver`)
78
- - Last-Write-Wins (LWW)
79
- - Client-Wins & Server-Wins
80
- - Custom conflict resolvers
81
- 15. **[Database Backups & Zero-Knowledge Encryption](./backups.md)**
82
- - Google Drive and Microsoft OneDrive sandboxed backups
83
- - Zero-Knowledge client-side encryption (AES-256-GCM + PBKDF2)
84
- - React backup hooks (`useGoogleDriveBackup`, `useOneDriveBackup`)
85
- - Universal binary database snapshots (`exportDatabase`, `importDatabase`)
86
- 16. **[Maintenance & Data Portability](./maintenance-portability.md)**
87
- - Storage breakdown, outbox pruning, VACUUM, and WAL checkpoints
88
- - PRAGMA analyze and structural integrity checks
89
- - Universal JSON & RFC-4180 CSV export and import
90
- 17. **[Action Outbox & Email Queue](./actions-email.md)**
91
- - 0ms offline transactional email enqueuing
92
- - Generic action dispatchers (push notifications, webhooks, analytics)
93
- - Idempotency deduplication, TTL expiration, and crash recovery
94
- 18. **[API Keys & Signed Tokens](./api-keys.md)**
95
- - Checksummed API key generation & verification (Stripe/GitHub pattern)
96
- - HMAC-SHA256 signed tokens with expiration and renewal
97
- - Local SQLite API key manager (`client.keys`)
98
-
99
- ---
100
-
101
- ## 💡 Core Philosophy
102
-
103
- * **Local-First By Default:** The app writes to and reads from local SQLite first. Operations never stall on slow cell connections or outages.
104
- * **Guaranteed Durability:** Every mutate operation executes in an atomic transaction that updates the user table and inserts a mutation into `sync_outbox` simultaneously. If the device restarts or loses power, pending changes are never lost.
105
- * **Zero Lock-In:** Switch seamlessly between Supabase, Convex, Firestore, or your own REST/GraphQL server without rewriting your UI layer.
106
- 5. **[Server API Routing](./server.md)**
107
- - Create server route handlers from one typed config
108
- - Add middleware and use provider-specific server services
package/docs/_sidebar.md DELETED
@@ -1,22 +0,0 @@
1
- * [🏠 Home](README.md)
2
- * [🚀 Getting Started](getting-started.md)
3
- * [🏛️ Architecture & Concepts](architecture.md)
4
- * [⚙️ Configuration](configuration.md)
5
- * [⚠️ Breaking Changes](breaking-changes.md)
6
- * [💻 Client API & Query Builder](client-api.md)
7
- * [⚡ Fast Key-Value & Preferences](kv.md)
8
- * [🔍 Full-Text Search (FTS5)](search.md)
9
- * [📁 Offline Media & Blob Storage](storage.md)
10
- * [⏰ Offline Job Scheduler & Cron](scheduler.md)
11
- * [📨 Action Outbox & Email Queue](actions-email.md)
12
- * [💾 Local SQLite Adapters](adapters-local.md)
13
- * [☁️ Remote Cloud Adapters](adapters-remote.md)
14
- * [⚛️ React & Expo Hooks](react-hooks.md)
15
- * [🔑 Authentication (Google, Microsoft, GitHub, Apple)](auth.md)
16
- * [🛡️ Offline Session Management](session.md)
17
- * [🔐 API Keys & Signed Tokens](api-keys.md)
18
- * [🌐 Google Sign-In & Drive Guide](google-auth.md)
19
- * [🔀 Conflict Resolution & Field Merge](conflict-resolution.md)
20
- * [📦 Cloud Backups & Zero-Knowledge Encryption](backups.md)
21
- * [🧹 Maintenance & Universal Data Portability](maintenance-portability.md)
22
- * [Server API Routing](server.md)
@@ -1,222 +0,0 @@
1
- # 📨 Generic Action Outbox & Inbuilt Email Queue
2
-
3
- In addition to database table synchronization, `local-lite` provides a dedicated **Generic Action Outbox** (`client.actions`). This engine is specifically designed for offline-queued commands and asynchronous side effects—such as **transactional emails, push notifications, webhooks, or payment intents**—that must execute reliably without data loss when network connectivity is intermittent.
4
-
5
- ---
6
-
7
- ## 🎯 Why an Action Outbox?
8
-
9
- Standard database record synchronization (CRUD) and external actions (RPC) have fundamentally different requirements:
10
-
11
- | Property | Standard Data Sync (CRUD) | Action Outbox (RPC / Side Effects) |
12
- | :--- | :--- | :--- |
13
- | **Example** | Update user profile, edit a note | Send order receipt email, send push alert |
14
- | **Duplicates** | Safe (Idempotent: last-write-wins) | **Dangerous** (Duplicate execution sends multiple emails or double charges) |
15
- | **Lifecycle** | Permanent SQLite records | **Transient**: `PENDING` ➔ `EXECUTING` ➔ `COMPLETED` / `FAILED` ➔ Pruned |
16
- | **Direction** | Two-way sync (push local, pull remote) | **One-way command execution** with a persistent receipt/result |
17
- | **Time Sensitivity** | Changes stay valid indefinitely | **Needs TTL / Expiration** (e.g. don't send time-sensitive alerts 2 days later) |
18
-
19
- `client.actions` solves these problems by providing atomic storage in a local `_local_actions` table, strict idempotency deduplication, crash recovery, and configurable retries.
20
-
21
- ---
22
-
23
- ## 📧 Inbuilt Email Queueing
24
-
25
- `local-lite` offers first-class, typed helpers for enqueuing and dispatching emails:
26
-
27
- ### Enqueuing an Email Offline
28
-
29
- Enqueuing an email is an instantaneous (0ms) local write to SQLite. If the user is offline or the app suddenly closes, the email is safely preserved in local storage.
30
-
31
- ```typescript
32
- import { client } from './sync.config';
33
-
34
- const emailAction = await client.actions.sendEmail({
35
- to: 'customer@example.com',
36
- subject: 'Order #1042 Confirmed',
37
- html: '<h1>Thank you for your purchase!</h1>',
38
- text: 'Thank you for your purchase!',
39
- template: 'order_receipt',
40
- templateData: { orderId: 1042, total: '$49.99' },
41
-
42
- // Guarantees at-most-once execution even if pressed multiple times
43
- idempotencyKey: 'receipt_order_1042',
44
-
45
- // Time-to-live: expire if device remains offline for > 24 hours
46
- ttlMs: 24 * 60 * 60 * 1000,
47
-
48
- // Maximum retry attempts before marking status as FAILED
49
- maxRetries: 3,
50
- });
51
-
52
- console.log('Enqueued email ID:', emailAction.id);
53
- ```
54
-
55
- ### Email Options Reference
56
-
57
- | Option | Type | Description |
58
- | :--- | :--- | :--- |
59
- | `to` | `string \| string[]` | **Required.** Recipient email address(es). |
60
- | `subject` | `string` | **Required.** Email subject line. |
61
- | `html` | `string` | Optional HTML email body. |
62
- | `text` | `string` | Optional plaintext fallback. |
63
- | `from` | `string` | Optional sender address (e.g. `support@yourdomain.com`). |
64
- | `replyTo` | `string` | Optional reply-to address. |
65
- | `cc` | `string \| string[]` | Optional carbon copy recipient(s). |
66
- | `bcc` | `string \| string[]` | Optional blind carbon copy recipient(s). |
67
- | `template` | `string` | Optional template identifier (for template-based engines). |
68
- | `templateData` | `Record<string, any>` | Optional variables passed to your email template. |
69
- | `attachments` | `EmailAttachment[]` | Array of `{ filename, content?, url?, contentType? }`. |
70
- | `headers` | `Record<string, string>` | Optional custom MIME headers. |
71
- | `idempotencyKey` | `string` | Unique key preventing duplicate action execution. |
72
- | `ttlMs` | `number` | Expiration window in milliseconds from time of enqueuing. |
73
- | `expiresAt` | `number` | Explicit Unix timestamp (ms) when the action expires. |
74
- | `maxRetries` | `number` | Maximum delivery attempts before marking as `FAILED` (default: `3`). |
75
-
76
- ---
77
-
78
- ## 🚀 Dispatching Emails
79
-
80
- There are two primary patterns for executing enqueued email actions:
81
-
82
- ### Pattern 1: Local Dispatcher via Provider API (Resend, SendGrid, etc.)
83
-
84
- Register a local handler that triggers whenever the device is online and flushes pending emails:
85
-
86
- ```typescript
87
- // Register handler (e.g. in your app initialization)
88
- client.actions.registerEmailHandler(async (email, action, context) => {
89
- // Call your email delivery service (e.g., Resend)
90
- const response = await fetch('https://api.resend.com/emails', {
91
- method: 'POST',
92
- headers: {
93
- 'Authorization': `Bearer ${process.env.RESEND_API_KEY}`,
94
- 'Content-Type': 'application/json',
95
- },
96
- body: JSON.stringify({
97
- from: email.from || 'Acme <onboarding@resend.dev>',
98
- to: email.to,
99
- subject: email.subject,
100
- html: email.html,
101
- }),
102
- });
103
-
104
- if (!response.ok) {
105
- const error = await response.json();
106
- throw new Error(error.message || 'Failed to dispatch email');
107
- }
108
-
109
- const data = await response.json();
110
- // Return result to store receipt in SQLite
111
- return { messageId: data.id };
112
- });
113
- ```
114
-
115
- ### Pattern 2: Cloud Function Trigger (Supabase / Convex / Firebase)
116
-
117
- If you prefer **not** to embed API keys in your mobile or web app, do not register a local handler. The pending actions in `_local_actions` will sync to your remote backend via `local-lite`'s normal table replication:
118
-
119
- 1. **Supabase:** Configure a Postgres Database Webhook on `_local_actions` for `action = 'send_email'`. An Edge Function executes the email send and updates the record's status to `COMPLETED`.
120
- 2. **Convex:** Define a Convex action watching `_local_actions` that invokes your email provider using secure server-side environment variables.
121
- 3. **Firebase:** Attach a Cloud Function `onDocumentCreated('_local_actions/{id}')` to send the email via SendGrid/Postmark.
122
-
123
- The updated `COMPLETED` status syncs back down to SQLite, updating your local client UI.
124
-
125
- ---
126
-
127
- ## ⚡ Generic Offline Actions
128
-
129
- You can use the action engine for any arbitrary offline command:
130
-
131
- ```typescript
132
- // 1. Register a handler for push notifications
133
- client.actions.registerHandler('push_notification', async (action, context) => {
134
- const { deviceToken, title, body } = action.payload;
135
-
136
- const res = await fetch('https://exp.host/--/api/v2/push/send', {
137
- method: 'POST',
138
- headers: { 'Content-Type': 'application/json' },
139
- body: JSON.stringify({ to: deviceToken, title, body }),
140
- });
141
-
142
- return await res.json();
143
- });
144
-
145
- // 2. Enqueue from anywhere in your app while offline
146
- await client.actions.enqueue({
147
- action: 'push_notification',
148
- payload: {
149
- deviceToken: 'ExponentPushToken[xxxxxxxxxxxxxx]',
150
- title: 'New Chat Message',
151
- body: 'You received a message from Sarah',
152
- },
153
- idempotencyKey: 'msg_push_4812',
154
- ttlMs: 60 * 60 * 1000, // 1 hour TTL
155
- });
156
- ```
157
-
158
- ---
159
-
160
- ## 🛠️ Action Management & Operations
161
-
162
- ### Manual Flush
163
- Trigger an immediate execution of all pending actions whose handlers are registered:
164
-
165
- ```typescript
166
- const result = await client.actions.flush();
167
- console.log(`Processed: ${result.processed}, Completed: ${result.completed}, Failed: ${result.failed}`);
168
- ```
169
-
170
- ### Querying Actions
171
- Query actions by ID, status, or action type:
172
-
173
- ```typescript
174
- // Get specific action by ID
175
- const action = await client.actions.get('action-uuid-123');
176
-
177
- // List actions by status
178
- const pendingEmails = await client.actions.list({
179
- action: 'send_email',
180
- status: 'PENDING',
181
- limit: 20,
182
- });
183
- ```
184
-
185
- ### Cancelling an Action
186
- Cancel a pending action before it is executed:
187
-
188
- ```typescript
189
- const wasCancelled = await client.actions.cancel('action-uuid-123');
190
- ```
191
-
192
- ### Pruning Old Records
193
- Clean up completed, failed, or expired action records:
194
-
195
- ```typescript
196
- // Prune records completed more than 7 days ago
197
- await client.actions.prune({
198
- completedOlderThanMs: 7 * 24 * 60 * 60 * 1000,
199
- failedOlderThanMs: 30 * 24 * 60 * 60 * 1000,
200
- expiredOlderThanMs: 24 * 60 * 60 * 1000,
201
- });
202
- ```
203
-
204
- ---
205
-
206
- ## 🛡️ Reliability & Crash Recovery
207
-
208
- 1. **At-Most-Once Delivery (Idempotency):**
209
- Passing `idempotencyKey` ensures that multiple calls (e.g. from a user tapping "Submit" multiple times) return the existing action record without creating duplicate outbox rows or sending multiple emails.
210
- 2. **Crash Recovery:**
211
- If the mobile app is terminated or crashes while an action is `EXECUTING`, on the next app launch `client.initialize()` automatically resets stale `EXECUTING` records back to `PENDING` so they can complete safely.
212
- 3. **Automatic Retries:**
213
- If a handler throws an error (e.g. temporary network error or rate limit), `retry_count` is incremented. The action is marked `FAILED` only after exceeding `maxRetries`.
214
- 4. **Lifecycle Events:**
215
- Listen to action lifecycle events directly through `client.events`:
216
- ```typescript
217
- client.events.on('action:enqueued', (action) => console.log('Enqueued:', action.id));
218
- client.events.on('action:executing', (action) => console.log('Executing:', action.id));
219
- client.events.on('action:completed', (action) => console.log('Completed:', action.id));
220
- client.events.on('action:failed', (action) => console.error('Failed:', action.id, action.lastError));
221
- client.events.on('action:expired', (action) => console.warn('Expired without executing:', action.id));
222
- ```