local-lite 0.2.6 → 1.0.1

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.
@@ -0,0 +1,207 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MemoryServerSyncStorage = void 0;
4
+ exports.createSyncEndpoint = createSyncEndpoint;
5
+ /**
6
+ * In-memory server sync storage.
7
+ * Ideal for development, testing, serverless functions, or lightweight microservices.
8
+ */
9
+ class MemoryServerSyncStorage {
10
+ tables = new Map();
11
+ changeLog = [];
12
+ monotonicCursor = 0;
13
+ async applyOperations(operations, overrideTime) {
14
+ const serverTime = overrideTime ?? Date.now();
15
+ let applied = 0;
16
+ const successfulIds = [];
17
+ for (const op of operations) {
18
+ if (!op.tableName || !op.rowId)
19
+ continue;
20
+ if (!this.tables.has(op.tableName)) {
21
+ this.tables.set(op.tableName, new Map());
22
+ }
23
+ const tableMap = this.tables.get(op.tableName);
24
+ const existing = tableMap.get(String(op.rowId));
25
+ const opTime = op.timestamp ?? serverTime;
26
+ // Last-Write-Wins: if existing record is newer than the operation, skip overwriting
27
+ if (existing && existing.timestamp > opTime) {
28
+ successfulIds.push(op.id);
29
+ continue;
30
+ }
31
+ this.monotonicCursor += 1;
32
+ const isDelete = op.operation === 'DELETE';
33
+ const recordPayload = isDelete
34
+ ? { id: op.rowId, deleted: true }
35
+ : { ...(existing?.payload || {}), ...(op.payload || {}), id: op.rowId };
36
+ const record = {
37
+ rowId: String(op.rowId),
38
+ tableName: op.tableName,
39
+ payload: recordPayload,
40
+ timestamp: Math.max(opTime, serverTime),
41
+ operation: op.operation,
42
+ cursor: this.monotonicCursor,
43
+ };
44
+ tableMap.set(record.rowId, record);
45
+ this.changeLog.push(record);
46
+ applied += 1;
47
+ successfulIds.push(op.id);
48
+ }
49
+ return { applied, successfulIds, serverTime, cursor: this.monotonicCursor };
50
+ }
51
+ async getDeltas(tables, since, limit = 1000) {
52
+ const serverTime = Date.now();
53
+ // Filter log entries that belong to requested tables and happened strictly after `since`
54
+ const candidateEntries = this.changeLog.filter((entry) => (tables.length === 0 || tables.includes(entry.tableName)) &&
55
+ (entry.cursor > since || entry.timestamp > since));
56
+ const hasMore = candidateEntries.length > limit;
57
+ const paged = candidateEntries.slice(0, limit);
58
+ // Deduplicate by (tableName, rowId) to return the most recent delta for each row
59
+ const latestMap = new Map();
60
+ let maxCursor = since;
61
+ for (const entry of paged) {
62
+ const key = `${entry.tableName}:${entry.rowId}`;
63
+ latestMap.set(key, entry);
64
+ if (entry.cursor > maxCursor)
65
+ maxCursor = entry.cursor;
66
+ if (entry.timestamp > maxCursor)
67
+ maxCursor = entry.timestamp;
68
+ }
69
+ const deltaList = Array.from(latestMap.values()).map((entry) => ({
70
+ tableName: entry.tableName,
71
+ operation: entry.operation,
72
+ rowId: entry.rowId,
73
+ payload: entry.payload,
74
+ timestamp: entry.timestamp,
75
+ }));
76
+ return {
77
+ changes: {
78
+ timestamp: serverTime,
79
+ changes: deltaList,
80
+ },
81
+ cursor: maxCursor,
82
+ hasMore,
83
+ serverTime,
84
+ };
85
+ }
86
+ /**
87
+ * Resets all in-memory tables and logs.
88
+ */
89
+ clear() {
90
+ this.tables.clear();
91
+ this.changeLog = [];
92
+ this.monotonicCursor = 0;
93
+ }
94
+ }
95
+ exports.MemoryServerSyncStorage = MemoryServerSyncStorage;
96
+ /**
97
+ * Creates turnkey push and pull API endpoints for self-hosted multi-device data synchronization.
98
+ */
99
+ function createSyncEndpoint(options = {}) {
100
+ const storage = options.storage || new MemoryServerSyncStorage();
101
+ const corsHeaders = {
102
+ 'Access-Control-Allow-Origin': options.corsOrigin || '*',
103
+ 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
104
+ 'Access-Control-Allow-Headers': 'Content-Type, Authorization',
105
+ };
106
+ const verifyAuth = async (request) => {
107
+ if (options.authHandler) {
108
+ const authUser = await options.authHandler(request);
109
+ if (!authUser)
110
+ return false;
111
+ return authUser;
112
+ }
113
+ if (!options.secret)
114
+ return true;
115
+ const authHeader = request.headers.get('authorization');
116
+ const match = authHeader === `Bearer ${options.secret}`;
117
+ return match ? { type: 'admin', isAdmin: true } : false;
118
+ };
119
+ // POST: Push batch of mutations (or combined push+pull batch)
120
+ const handlePost = async ({ request }) => {
121
+ const auth = await verifyAuth(request);
122
+ if (!auth) {
123
+ return Response.json({ error: 'Unauthorized: Invalid sync authentication' }, { status: 401, headers: corsHeaders });
124
+ }
125
+ let body;
126
+ try {
127
+ body = await request.json();
128
+ }
129
+ catch {
130
+ return Response.json({ error: 'Bad Request: Invalid JSON body' }, { status: 400, headers: corsHeaders });
131
+ }
132
+ let operations = Array.isArray(body?.operations) ? body.operations : [];
133
+ if (options.onBeforePush) {
134
+ const modified = await options.onBeforePush(operations, request, auth);
135
+ if (Array.isArray(modified))
136
+ operations = modified;
137
+ }
138
+ const pushResult = await storage.applyOperations(operations);
139
+ // If client requested a combined batch sync (push + pull in single roundtrip):
140
+ if (Array.isArray(body?.tables)) {
141
+ let tables = body.tables;
142
+ let since = Number(body.since ?? 0);
143
+ let limit = body.limit ? Number(body.limit) : 500;
144
+ if (options.onBeforePull) {
145
+ const pullMod = await options.onBeforePull(tables, since, limit, request, auth);
146
+ if (pullMod?.tables)
147
+ tables = pullMod.tables;
148
+ if (pullMod?.since !== undefined)
149
+ since = pullMod.since;
150
+ if (pullMod?.limit !== undefined)
151
+ limit = pullMod.limit;
152
+ }
153
+ const pullResult = await storage.getDeltas(tables, since, limit);
154
+ return Response.json({
155
+ success: true,
156
+ push: pushResult,
157
+ pull: pullResult,
158
+ }, { status: 200, headers: corsHeaders });
159
+ }
160
+ return Response.json({
161
+ success: true,
162
+ successfulIds: pushResult.successfulIds,
163
+ processed: pushResult.applied,
164
+ serverTime: pushResult.serverTime,
165
+ cursor: pushResult.cursor,
166
+ }, { status: 200, headers: corsHeaders });
167
+ };
168
+ // GET: Pull deltas since cursor/timestamp
169
+ const handleGet = async ({ request }) => {
170
+ const auth = await verifyAuth(request);
171
+ if (!auth) {
172
+ return Response.json({ error: 'Unauthorized: Invalid sync authentication' }, { status: 401, headers: corsHeaders });
173
+ }
174
+ const url = new URL(request.url);
175
+ const tablesParam = url.searchParams.get('tables');
176
+ const sinceParam = url.searchParams.get('since');
177
+ const limitParam = url.searchParams.get('limit');
178
+ let tables = tablesParam ? tablesParam.split(',').map((t) => t.trim()).filter(Boolean) : [];
179
+ let since = sinceParam ? Number(sinceParam) : 0;
180
+ let limit = limitParam ? Number(limitParam) : 500;
181
+ if (options.onBeforePull) {
182
+ const pullMod = await options.onBeforePull(tables, since, limit, request, auth);
183
+ if (pullMod?.tables)
184
+ tables = pullMod.tables;
185
+ if (pullMod?.since !== undefined)
186
+ since = pullMod.since;
187
+ if (pullMod?.limit !== undefined)
188
+ limit = pullMod.limit;
189
+ }
190
+ const result = await storage.getDeltas(tables, since, limit);
191
+ return Response.json({
192
+ success: true,
193
+ changes: result.changes,
194
+ cursor: result.cursor,
195
+ hasMore: result.hasMore,
196
+ serverTime: result.serverTime,
197
+ }, { status: 200, headers: corsHeaders });
198
+ };
199
+ const handleOptions = async () => {
200
+ return new Response(null, { status: 204, headers: corsHeaders });
201
+ };
202
+ return {
203
+ POST: handlePost,
204
+ GET: handleGet,
205
+ OPTIONS: handleOptions,
206
+ };
207
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "local-lite",
3
- "version": "0.2.6",
3
+ "version": "1.0.1",
4
4
  "description": "Never let a lost connection break a promise. Local-first sync that faithfully keeps data safe until you're back online.",
5
5
  "license": "MIT",
6
6
  "main": "dist/index.js",
@@ -150,6 +150,11 @@
150
150
  "types": "./dist/scheduler/index.d.ts",
151
151
  "import": "./dist/scheduler/index.js",
152
152
  "default": "./dist/scheduler/index.js"
153
+ },
154
+ "./email": {
155
+ "types": "./dist/email/index.d.ts",
156
+ "import": "./dist/email/index.js",
157
+ "default": "./dist/email/index.js"
153
158
  }
154
159
  },
155
160
  "scripts": {
@@ -168,10 +173,14 @@
168
173
  "expo-file-system": ">=58.0.0",
169
174
  "expo-sqlite": ">=58.0.0",
170
175
  "firebase": ">=9.0.0",
176
+ "nodemailer": ">=6.9.0",
171
177
  "react": ">=18.0.0",
172
178
  "sql.js": "^1.8.0"
173
179
  },
174
180
  "peerDependenciesMeta": {
181
+ "nodemailer": {
182
+ "optional": true
183
+ },
175
184
  "react": {
176
185
  "optional": true
177
186
  },
@@ -206,9 +215,11 @@
206
215
  "devDependencies": {
207
216
  "@supabase/supabase-js": "^2.118.0",
208
217
  "@types/node": "^26.6.5",
218
+ "@types/nodemailer": "^8.0.2",
209
219
  "@types/react": "^19.3.0",
210
220
  "@types/uuid": "^11.0.0",
211
221
  "expo-sqlite": "^58.0.14",
222
+ "nodemailer": "^10.5.0",
212
223
  "react": "^19.3.1",
213
224
  "typescript": "^7.0.2",
214
225
  "vitest": "^5.0.5"
@@ -21,6 +21,9 @@ Implement `RemoteDBAdapter` (exported from `local-lite`, with `SyncOperation`, `
21
21
  - `scope` may be an object or a (possibly async) function. If setup is async, guard against cleanup running before setup finishes (generation counter or cancelled flag) so listeners do not leak.
22
22
  - `setSyncScope?(scope)`: optional; implement it if the backend filters by scope, and re-subscribe live listeners when scope changes.
23
23
 
24
+ > [!TIP]
25
+ > **Built-in Self-Hosted Adapter**: Before writing a custom adapter from scratch, consider using `SelfHostedRemoteAdapter` (or `server: { url, token }` in `defineSyncConfig`) paired with `createSyncEndpoint()` from `local-lite/server`. It implements an idempotent push/pull sync protocol out-of-the-box.
26
+
24
27
  ## Skeleton
25
28
 
26
29
  ```typescript
@@ -13,45 +13,86 @@ Guide for executing queued actions, running background jobs, persisting key-valu
13
13
 
14
14
  The Action Manager handles complex business logic mutations that must be queued offline and executed reliably when connectivity is restored:
15
15
 
16
- ### Enqueueing an Action
17
- ```typescript
18
- import { getSyncClient } from './sync.config';
19
-
20
- const client = await getSyncClient();
16
+ ### Type-Safe Action Contracts (`defineAction`)
17
+ Validate payloads before writing to SQLite using runtime schema validators (custom predicates or Zod/TypeBox schemas):
21
18
 
22
- // Enqueue an action (e.g. sending an email, processing a payment, or syncing with third-party API)
23
- const action = await client.actions.enqueue({
24
- type: 'SEND_INVITATION',
25
- payload: {
26
- inviteeEmail: 'colleague@example.com',
27
- teamId: 'team_xyz',
19
+ ```typescript
20
+ // Define action with runtime schema validation
21
+ client.actions.defineAction({
22
+ name: 'PROCESS_PAYMENT',
23
+ schema: (payload: any) => {
24
+ if (!payload.amount || payload.amount <= 0) throw new Error('Positive amount required');
25
+ if (!payload.currency) throw new Error('Currency required');
26
+ return payload;
27
+ },
28
+ handler: async (action, context) => {
29
+ const res = await fetch('https://api.stripe.com/v1/payment_intents', {
30
+ method: 'POST',
31
+ body: JSON.stringify(action.payload),
32
+ });
33
+ return await res.json();
28
34
  },
29
- maxRetries: 5,
30
- retryDelayMs: 2000,
31
35
  });
36
+ ```
37
+
38
+ ### Rate Limiting & Concurrency Control
39
+ Configure worker concurrency and token-bucket rate limiting to avoid tripping downstream API rate limits:
32
40
 
33
- console.log('Queued action:', action.id, action.status);
41
+ ```typescript
42
+ const client = await createSyncClient({
43
+ database: 'app.db',
44
+ // Concurrency & rate-limiting for action outbox
45
+ // ActionManager options can be configured directly or on client actions
46
+ });
34
47
  ```
35
48
 
36
- ### Registering Action Handlers
37
- Register handlers that execute when the device is online:
49
+ ### Inbuilt Offline Email Queue (`client.actions.sendEmail`)
50
+ Enqueue transactional emails with 0ms local write latency:
38
51
 
39
52
  ```typescript
40
- client.actions.registerHandler('SEND_INVITATION', async (payload) => {
41
- const res = await fetch('https://api.example.com/invites', {
42
- method: 'POST',
43
- headers: { 'Content-Type': 'application/json' },
44
- body: JSON.stringify(payload),
45
- });
46
-
47
- if (!res.ok) {
48
- throw new Error(`Invitation failed with status ${res.status}`);
49
- }
50
-
51
- return await res.json();
53
+ const emailAction = await client.actions.sendEmail({
54
+ to: 'user@example.com',
55
+ subject: 'Order #{{orderId}} Confirmed',
56
+ html: '<h2>Thanks {{name}}!</h2>',
57
+ templateData: { name: 'Alice', orderId: 1042 },
58
+ idempotencyKey: 'order_1042',
59
+ attachments: [
60
+ { filename: 'receipt.pdf', url: 'file:///data/user/0/receipt.pdf' } // Auto-hydrates mobile file:// URIs
61
+ ],
62
+ react: <ReceiptEmail orderId={1042} />, // Optional React Email JSX rendering
52
63
  });
53
64
  ```
54
65
 
66
+ ### Unified Email Providers (`local-lite/email`)
67
+ Dispatch via Nodemailer SMTP, HTTP APIs (Resend, SendGrid, Postmark), or In-Memory Dev Mode:
68
+
69
+ ```typescript
70
+ import { createEmailHandler, DevMailbox } from 'local-lite/email';
71
+
72
+ // 1. In-Memory Dev Mode (no external credentials needed in development)
73
+ client.actions.registerEmailHandler(
74
+ createEmailHandler({ provider: 'dev' })
75
+ );
76
+ console.log('Dev Mailbox:', DevMailbox.getInbox());
77
+
78
+ // 2. Nodemailer SMTP
79
+ client.actions.registerEmailHandler(
80
+ createEmailHandler({
81
+ transport: { host: 'smtp.mailgun.org', port: 587, auth: { user: '...', pass: '...' } },
82
+ defaultFrom: '"Support" <support@myapp.com>',
83
+ })
84
+ );
85
+
86
+ // 3. HTTP Provider (Resend, SendGrid, Postmark)
87
+ client.actions.registerEmailHandler(
88
+ createEmailHandler({
89
+ provider: 'resend',
90
+ apiKey: process.env.RESEND_API_KEY,
91
+ defaultFrom: 'onboarding@resend.dev',
92
+ })
93
+ );
94
+ ```
95
+
55
96
  ---
56
97
 
57
98
  ## 2. Key-Value Store & Secret Preferences (`client.kv`)
@@ -122,3 +122,20 @@ export function SettingsScreen({ client }) {
122
122
  2. **Selective Column Projections**: In high-frequency queries, select only required columns (`SELECT id, title FROM ...`) instead of `SELECT *` to reduce SQLite serialization overhead.
123
123
  3. **Batch Mutations**: Wrap bulk inserts in transactions or `client.mutateBatch()` rather than issuing individual `INSERT` statements in loops.
124
124
 
125
+ ---
126
+
127
+ ## 6. DevTools & Debugging (`<SyncInspector />`)
128
+
129
+ Inspect database tables, live outbox operations, and trigger one-tap manual flushes of mutations and queued emails using the developer widget:
130
+
131
+ ```tsx
132
+ import { SyncInspector } from 'local-lite/devtools';
133
+
134
+ export function DevOverlay({ client }) {
135
+ if (__DEV__) {
136
+ return <SyncInspector client={client} position="bottom-right" defaultOpen={false} />;
137
+ }
138
+ return null;
139
+ }
140
+ ```
141
+
@@ -1,6 +1,6 @@
1
1
  ---
2
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.
3
+ description: Configure and implement framework-neutral REST API routing, turnkey self-hosted sync endpoints, and email dispatch endpoints with local-lite/server. Use when setting up server endpoints (defineServerConfig, createServer, createSyncEndpoint, createEmailEndpoint), 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
4
  ---
5
5
 
6
6
  # local-lite Server API Routing
@@ -125,3 +125,134 @@ export default {
125
125
  * **Not Found (404)**: Unmatched paths return a standardized `{ error: 'Not Found' }` with status `404`.
126
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
127
 
128
+ ---
129
+
130
+ ## 6. Turnkey Self-Hosted Sync Endpoint (`createSyncEndpoint`)
131
+
132
+ Zero-boilerplate multi-device synchronization endpoint replacing third-party backends (Supabase, Convex, Firebase):
133
+
134
+ ```typescript
135
+ import { defineServerConfig, createServer, createSyncEndpoint, MemoryServerSyncStorage } from 'local-lite/server';
136
+
137
+ export const apiServer = createServer(
138
+ defineServerConfig({
139
+ config: {},
140
+ endpoints: {
141
+ // Mount turnkey sync endpoint (POST for push/batch, GET for pull)
142
+ '/api/sync': createSyncEndpoint({
143
+ secret: process.env.SYNC_SECRET_TOKEN,
144
+ storage: new MemoryServerSyncStorage(), // Or persistent database storage
145
+ }),
146
+ },
147
+ })
148
+ );
149
+ ```
150
+
151
+ Clients connect to this simply by setting `server: { url: 'https://api.domain.com/api/sync', token: '...' }` in `defineSyncConfig`.
152
+
153
+ ### Production MySQL Storage Recipe
154
+
155
+ ```typescript
156
+ import mysql from 'mysql2/promise';
157
+ import { createServer, defineServerConfig, createSyncEndpoint, type ServerSyncStorage } from 'local-lite/server';
158
+
159
+ const pool = mysql.createPool({
160
+ uri: process.env.DATABASE_URL,
161
+ waitForConnections: true,
162
+ connectionLimit: 10,
163
+ });
164
+
165
+ const mysqlStorage: ServerSyncStorage = {
166
+ async applyOperations(operations, serverTime = Date.now()) {
167
+ const conn = await pool.getConnection();
168
+ const successfulIds: string[] = [];
169
+ let applied = 0;
170
+ try {
171
+ await conn.beginTransaction();
172
+ for (const op of operations) {
173
+ if (!op.tableName || !op.rowId) continue;
174
+ const opTime = op.timestamp || serverTime;
175
+ await conn.execute(
176
+ 'INSERT INTO _server_changes (table_name, row_id, payload, operation, timestamp) VALUES (?, ?, ?, ?, ?)',
177
+ [op.tableName, String(op.rowId), JSON.stringify(op.payload || {}), op.operation, opTime]
178
+ );
179
+ successfulIds.push(op.id);
180
+ applied++;
181
+ }
182
+ const [cursorRows]: any = await conn.query('SELECT COALESCE(MAX(`cursor`), 0) AS max_cursor FROM _server_changes');
183
+ await conn.commit();
184
+ return { applied, successfulIds, serverTime, cursor: Number(cursorRows[0]?.max_cursor || 0) };
185
+ } catch (err) {
186
+ await conn.rollback();
187
+ throw err;
188
+ } finally {
189
+ conn.release();
190
+ }
191
+ },
192
+
193
+ async getDeltas(tables, since, limit = 200) {
194
+ if (tables.length === 0) return { changes: { timestamp: Date.now(), changes: [] }, cursor: since, hasMore: false, serverTime: Date.now() };
195
+ const placeholders = tables.map(() => '?').join(',');
196
+ const [rows]: any = await pool.query(
197
+ `SELECT * FROM _server_changes WHERE \`cursor\` > ? AND table_name IN (${placeholders}) ORDER BY \`cursor\` ASC LIMIT ?`,
198
+ [since, ...tables, Number(limit)]
199
+ );
200
+ const changes = {
201
+ timestamp: Date.now(),
202
+ changes: rows.map((r: any) => ({
203
+ tableName: r.table_name,
204
+ rowId: r.row_id,
205
+ operation: r.operation,
206
+ payload: typeof r.payload === 'string' ? JSON.parse(r.payload) : r.payload,
207
+ timestamp: Number(r.timestamp),
208
+ })),
209
+ };
210
+ const maxCursor = rows.length > 0 ? Number(rows[rows.length - 1].cursor) : since;
211
+ return { changes, cursor: maxCursor, hasMore: rows.length === Number(limit), serverTime: Date.now() };
212
+ },
213
+ };
214
+
215
+ export const apiServer = createServer(
216
+ defineServerConfig({
217
+ config: {},
218
+ endpoints: {
219
+ '/api/sync': createSyncEndpoint({
220
+ storage: mysqlStorage,
221
+ secret: process.env.SYNC_SECRET_TOKEN,
222
+ }),
223
+ },
224
+ })
225
+ );
226
+
227
+ export const POST = apiServer.handler('/api/sync', 'POST');
228
+ export const GET = apiServer.handler('/api/sync', 'GET');
229
+ export const OPTIONS = apiServer.handler('/api/sync', 'OPTIONS');
230
+ ```
231
+
232
+ ---
233
+
234
+ ## 7. Turnkey Email Relay Endpoint (`createEmailEndpoint`)
235
+
236
+ Mount a pre-built email endpoint that receives offline-queued emails from mobile/Expo apps and sends them via Nodemailer or cloud providers:
237
+
238
+ ```typescript
239
+ import { createServer, defineServerConfig, createEmailEndpoint } from 'local-lite/server';
240
+
241
+ export const apiServer = createServer(
242
+ defineServerConfig({
243
+ config: {},
244
+ endpoints: {
245
+ '/api/send-email': createEmailEndpoint({
246
+ secret: process.env.EMAIL_API_SECRET,
247
+ transport: {
248
+ host: 'smtp.mailgun.org',
249
+ port: 587,
250
+ auth: { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS },
251
+ },
252
+ defaultFrom: '"My App" <noreply@myapp.com>',
253
+ }),
254
+ },
255
+ })
256
+ );
257
+ ```
258
+
@@ -121,13 +121,26 @@ export const syncConfig = defineSyncConfig({
121
121
  },
122
122
 
123
123
  // 7. Remote Backend (choose one or omit for local-only)
124
- // localOnly: true, // Set to true if not syncing to a remote server
125
- supabase: {
126
- url: process.env.EXPO_PUBLIC_SUPABASE_URL!,
127
- anonKey: process.env.EXPO_PUBLIC_SUPABASE_ANON_KEY!,
124
+ // Option A: Turnkey Self-Hosted Server (Zero cloud dependencies)
125
+ server: {
126
+ url: 'https://api.mydomain.com/api/sync',
127
+ token: process.env.EXPO_PUBLIC_SYNC_SECRET,
128
+ },
129
+ // Option B: Supabase
130
+ // supabase: { url: process.env.EXPO_PUBLIC_SUPABASE_URL!, anonKey: process.env.EXPO_PUBLIC_SUPABASE_ANON_KEY! },
131
+ // Option C: Convex
132
+ // convex: { client: convexClient },
133
+ // Option D: Pure Local-Only
134
+ // localOnly: true,
135
+
136
+ // 8. Offline Email Delivery Configuration
137
+ email: {
138
+ provider: 'resend', // 'nodemailer' | 'resend' | 'sendgrid' | 'postmark' | 'dev'
139
+ apiKey: process.env.EXPO_PUBLIC_RESEND_API_KEY,
140
+ defaults: { from: 'Support <support@mydomain.com>' },
128
141
  },
129
142
 
130
- // 8. Sync tuning
143
+ // 9. Sync tuning
131
144
  pushIntervalMs: 500,
132
145
  pullIntervalMs: 5000,
133
146
  conflictResolver: 'last-write-wins',
@@ -35,6 +35,15 @@ Search the codebase for each affected pattern and apply the migration:
35
35
  * **Old**: Injecting `fileSystem` via legacy `expo-file-system`.
36
36
  * **New**: Uses standard Expo SDK 58+ `File`, `Directory`, and `Paths` APIs. Remove legacy `fileSystem` option.
37
37
 
38
+ ### Email Module Imports (`local-lite/nodemailer` ➔ `local-lite/email`)
39
+ * **Old**: `import { ... } from 'local-lite/nodemailer'`
40
+ * **New**: `import { ... } from 'local-lite/email'`
41
+ * **Action**: Update imports to the unified email module supporting Nodemailer, Resend, SendGrid, Postmark, and Dev Mailbox.
42
+
43
+ ### Self-Hosted Sync
44
+ * **Old**: Requiring Supabase or Convex for multi-client synchronization.
45
+ * **New**: Use `defineSyncConfig({ server: { url: 'https://api.yourdomain.com/sync', token: '...' } })` with turnkey `createSyncEndpoint()` from `local-lite/server`.
46
+
38
47
  ---
39
48
 
40
49
  ## 2. Review Workflow