local-lite 0.2.5 → 1.0.0
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 +18 -13
- package/dist/actions/manager.d.ts +9 -1
- package/dist/actions/manager.js +143 -62
- package/dist/actions/types.d.ts +33 -0
- package/dist/adapters/remote/index.d.ts +1 -0
- package/dist/adapters/remote/index.js +1 -0
- package/dist/adapters/remote/self-hosted.d.ts +64 -0
- package/dist/adapters/remote/self-hosted.js +126 -0
- package/dist/config/index.d.ts +2 -0
- package/dist/config/index.js +18 -1
- package/dist/config/resolve-remote.js +12 -0
- package/dist/config/types.d.ts +70 -0
- package/dist/devtools/SyncInspector.js +9 -2
- package/dist/email/index.d.ts +128 -0
- package/dist/email/index.js +431 -0
- package/dist/server/email.d.ts +41 -0
- package/dist/server/email.js +79 -0
- package/dist/server/index.d.ts +2 -0
- package/dist/server/index.js +16 -0
- package/dist/server/sync.d.ts +77 -0
- package/dist/server/sync.js +178 -0
- package/package.json +12 -1
- package/skills/local-lite-custom-adapter/SKILL.md +3 -0
- package/skills/local-lite-offline-actions/SKILL.md +69 -28
- package/skills/local-lite-react/SKILL.md +17 -0
- package/skills/local-lite-server/SKILL.md +53 -1
- package/skills/local-lite-setup/SKILL.md +18 -5
- package/skills/local-lite-upgrade/SKILL.md +9 -0
package/README.md
CHANGED
|
@@ -24,6 +24,8 @@ Built around the **Transactional Outbox Pattern**, `local-lite` ensures instant,
|
|
|
24
24
|
* **[Database Backups & Encryption](https://georgechitechi.github.io/local-lite/#/backups)** - Google Drive, OneDrive, and Zero-Knowledge AES-256-GCM snapshots
|
|
25
25
|
* **[Conflict Resolution & Field Merge](https://georgechitechi.github.io/local-lite/#/conflict-resolution)** - 3-Way field merging, LWW, Client-Wins, and Server-Wins
|
|
26
26
|
* **[Maintenance & Data Portability](https://georgechitechi.github.io/local-lite/#/maintenance-portability)** - VACUUM, WAL checkpoints, outbox pruning, and JSON/CSV export/import
|
|
27
|
+
* **[Action Outbox & Email Queue](https://georgechitechi.github.io/local-lite/#/actions-email)** - 0ms offline email queue, Nodemailer/HTTP dispatchers, React Email, and type-safe actions
|
|
28
|
+
* **[Server Endpoints & Self-Hosted Sync](https://georgechitechi.github.io/local-lite/#/server)** - Turnkey sync backend and email relay endpoints for Express & Next.js
|
|
27
29
|
* **[React & Expo Hooks](https://georgechitechi.github.io/local-lite/#/react-hooks)** - `useLiveQuery()`, `useLiveQueries()`, `useLiveRow()`, `useLiveInfiniteQuery()`, `useMutations()`, `useSyncStatus()`, developer inspector tools, and backup/auth hooks
|
|
28
30
|
|
|
29
31
|
|
|
@@ -125,13 +127,14 @@ This recovers sync state; it does not repair corrupt SQLite files or cancel hung
|
|
|
125
127
|
|
|
126
128
|
* **⚡ 0ms Optimistic Writes:** Write to local SQLite immediately via atomic dual-write (`client.mutate()`).
|
|
127
129
|
* **📦 Transactional Outbox:** Mutations are stored atomically in a local `sync_outbox` table, preventing data loss if the app closes or loses connectivity mid-write.
|
|
128
|
-
* **🌐 Native Cloud Adapters:** First-class sync with Postgres tables (via **Supabase**), reactive document datastores (via **Convex**), and document collections (via **Firebase / Firestore**).
|
|
130
|
+
* **🌐 Native Cloud & Self-Hosted Adapters:** First-class sync with your own self-hosted sync server (`server: { url, token }`), Postgres tables (via **Supabase**), reactive document datastores (via **Convex**), and document collections (via **Firebase / Firestore**).
|
|
129
131
|
* **🛡️ Conflict Resolution:** Built-in strategies including **Last-Write-Wins (LWW)**, Server-Wins, Client-Wins, or custom resolver functions.
|
|
130
132
|
* **📶 Network-Aware:** Automatically pauses polling when offline and triggers immediate sync flushes the instant connectivity is restored.
|
|
131
133
|
* **🔄 Infinite-Loop Safe:** Incoming remote deltas update local tables and fire reactive UI listeners without echoing back into the outbox.
|
|
132
134
|
* **☁️ Database Backups:** Export and restore SQLite snapshots independently of your live sync backend.
|
|
133
135
|
* **🔑 Google Sign-In Out of the Box:** Secure, zero-backend Google OAuth 2.0 (PKCE) authentication with automatic token refresh, user profile retrieval, persistent session storage, and `useGoogleAuth()` hook.
|
|
134
|
-
* **📨 Action Outbox & Email
|
|
136
|
+
* **📨 Action Outbox & Direct Email:** Enqueue transactional emails offline with 0ms local latency. Send directly via Nodemailer SMTP, Resend, SendGrid, Postmark, or Dev Mailbox. Full support for React Email JSX, auto-hydrating mobile `file://` attachments, rate limiting, and type-safe contracts (`defineAction`).
|
|
137
|
+
* **🌐 Turnkey Server Endpoints (`local-lite/server`):** Mount self-hosted sync (`createSyncEndpoint`) and secure email relay (`createEmailEndpoint`) endpoints in 1 line of code for Next.js, Express, Fastify, or Node http.
|
|
135
138
|
* **⚡ Fast Key-Value & Encrypted Preferences (`client.kv`):** Typed storage, TTL expiration, and AES-256-GCM zero-knowledge secret protection.
|
|
136
139
|
* **🔍 Instant Full-Text Search (`client.search`):** SQLite FTS5 indexer with prefix matching, BM25 rank scoring, and highlighting.
|
|
137
140
|
* **📁 Offline Media & Blob Storage (`client.storage`):** Decoupled binary attachments, SHA-256 verification, and cloud sync queue (S3/Supabase/Firebase).
|
|
@@ -356,17 +359,19 @@ const emailAction = await client.actions.sendEmail({
|
|
|
356
359
|
ttlMs: 24 * 60 * 60 * 1000, // Expire if offline for >24 hours
|
|
357
360
|
});
|
|
358
361
|
|
|
359
|
-
// ⚡ 2.
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
});
|
|
362
|
+
// ⚡ 2. Direct email dispatch (Nodemailer SMTP, Resend, SendGrid, Postmark, or HTTP webhook)
|
|
363
|
+
import { createEmailHandler } from 'local-lite/email';
|
|
364
|
+
|
|
365
|
+
// Nodemailer transport:
|
|
366
|
+
client.actions.registerEmailHandler(createEmailHandler({
|
|
367
|
+
transport: { host: 'smtp.example.com', port: 587, auth: { user: '...', pass: '...' } },
|
|
368
|
+
defaultFrom: 'Support <support@mycompany.com>',
|
|
369
|
+
}));
|
|
370
|
+
|
|
371
|
+
// Or HTTP provider (e.g., Resend):
|
|
372
|
+
// client.actions.registerEmailHandler(createEmailHandler({ provider: 'resend', apiKey: '...' }));
|
|
373
|
+
|
|
374
|
+
// Or configure directly in defineSyncConfig({ email: { transport: { ... } } })!
|
|
370
375
|
|
|
371
376
|
// ⚡ 3. Enqueue arbitrary asynchronous actions (e.g., push notifications, analytics)
|
|
372
377
|
await client.actions.enqueue({
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { LocalDBAdapter } from '../adapters/local/index.js';
|
|
2
2
|
import { EventEmitter } from '../reactive/event-emitter.js';
|
|
3
|
-
import { ActionFilterOptions, ActionHandler, ActionManagerOptions, ActionPruneOptions, ActionRecord, EmailHandler, EmailPayload, EnqueueActionOptions, FlushActionsResult, SendEmailOptions } from './types.js';
|
|
3
|
+
import { ActionDefinition, ActionFilterOptions, ActionHandler, ActionManagerOptions, ActionPruneOptions, ActionRecord, EmailHandler, EmailPayload, EnqueueActionOptions, FlushActionsResult, SendEmailOptions } from './types.js';
|
|
4
4
|
export declare class ActionManager {
|
|
5
5
|
private db;
|
|
6
6
|
private events;
|
|
@@ -8,6 +8,8 @@ export declare class ActionManager {
|
|
|
8
8
|
private options;
|
|
9
9
|
private tableName;
|
|
10
10
|
private handlers;
|
|
11
|
+
private definitions;
|
|
12
|
+
private rateLimitTimestamps;
|
|
11
13
|
private isFlushing;
|
|
12
14
|
private flushRerunRequested;
|
|
13
15
|
private networkUnsubscribe?;
|
|
@@ -28,6 +30,10 @@ export declare class ActionManager {
|
|
|
28
30
|
* Convenience helper to enqueue a transactional email with offline resilience.
|
|
29
31
|
*/
|
|
30
32
|
sendEmail(options: SendEmailOptions): Promise<ActionRecord<EmailPayload, any>>;
|
|
33
|
+
/**
|
|
34
|
+
* Registers a type-safe action definition with optional runtime schema validation.
|
|
35
|
+
*/
|
|
36
|
+
defineAction<TPayload = any, TResult = any>(definition: ActionDefinition<TPayload, TResult>): () => void;
|
|
31
37
|
/**
|
|
32
38
|
* Registers a local executor for a specific action name.
|
|
33
39
|
* Returns an unregister function.
|
|
@@ -47,6 +53,8 @@ export declare class ActionManager {
|
|
|
47
53
|
* Actions without a registered handler remain in the queue (e.g. to be synced to cloud functions).
|
|
48
54
|
*/
|
|
49
55
|
flush(): Promise<FlushActionsResult>;
|
|
56
|
+
private waitForRateLimit;
|
|
57
|
+
private processAction;
|
|
50
58
|
private performFlush;
|
|
51
59
|
/**
|
|
52
60
|
* Retrieves an action record by ID.
|
package/dist/actions/manager.js
CHANGED
|
@@ -10,6 +10,8 @@ class ActionManager {
|
|
|
10
10
|
options;
|
|
11
11
|
tableName;
|
|
12
12
|
handlers = new Map();
|
|
13
|
+
definitions = new Map();
|
|
14
|
+
rateLimitTimestamps = [];
|
|
13
15
|
isFlushing = false;
|
|
14
16
|
flushRerunRequested = false;
|
|
15
17
|
networkUnsubscribe;
|
|
@@ -57,6 +59,32 @@ class ActionManager {
|
|
|
57
59
|
if (!opts.action || typeof opts.action !== 'string') {
|
|
58
60
|
throw new Error('Action name is required and must be a string');
|
|
59
61
|
}
|
|
62
|
+
// 0. Runtime Schema Validation if an action definition exists
|
|
63
|
+
let payload = opts.payload;
|
|
64
|
+
const definition = this.definitions.get(opts.action);
|
|
65
|
+
if (definition?.schema) {
|
|
66
|
+
const validator = definition.schema;
|
|
67
|
+
if (typeof validator.safeParse === 'function') {
|
|
68
|
+
const res = validator.safeParse(payload);
|
|
69
|
+
if (!res.success) {
|
|
70
|
+
const errDetail = res.error?.message || JSON.stringify(res.error);
|
|
71
|
+
throw new Error(`Schema validation failed for action '${opts.action}': ${errDetail}`);
|
|
72
|
+
}
|
|
73
|
+
payload = res.data ?? payload;
|
|
74
|
+
}
|
|
75
|
+
else if (typeof validator.parse === 'function') {
|
|
76
|
+
payload = validator.parse(payload);
|
|
77
|
+
}
|
|
78
|
+
else if (typeof validator === 'function') {
|
|
79
|
+
const res = await validator(payload);
|
|
80
|
+
if (res === false) {
|
|
81
|
+
throw new Error(`Schema validation failed for action '${opts.action}'`);
|
|
82
|
+
}
|
|
83
|
+
if (typeof res === 'object' && res !== null) {
|
|
84
|
+
payload = res;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
60
88
|
// 1. Idempotency check: if key already exists, return existing record
|
|
61
89
|
if (opts.idempotencyKey) {
|
|
62
90
|
const existing = await store_js_1.ActionStore.findByIdempotencyKey(this.db, this.tableName, opts.idempotencyKey);
|
|
@@ -114,6 +142,23 @@ class ActionManager {
|
|
|
114
142
|
maxRetries,
|
|
115
143
|
});
|
|
116
144
|
}
|
|
145
|
+
/**
|
|
146
|
+
* Registers a type-safe action definition with optional runtime schema validation.
|
|
147
|
+
*/
|
|
148
|
+
defineAction(definition) {
|
|
149
|
+
if (!definition.name) {
|
|
150
|
+
throw new Error('Action definition name is required');
|
|
151
|
+
}
|
|
152
|
+
this.definitions.set(definition.name, definition);
|
|
153
|
+
if (definition.handler) {
|
|
154
|
+
this.registerHandler(definition.name, definition.handler);
|
|
155
|
+
}
|
|
156
|
+
return () => {
|
|
157
|
+
if (this.definitions.get(definition.name) === definition) {
|
|
158
|
+
this.definitions.delete(definition.name);
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
}
|
|
117
162
|
/**
|
|
118
163
|
* Registers a local executor for a specific action name.
|
|
119
164
|
* Returns an unregister function.
|
|
@@ -151,6 +196,89 @@ class ActionManager {
|
|
|
151
196
|
});
|
|
152
197
|
return this.flushPromise;
|
|
153
198
|
}
|
|
199
|
+
async waitForRateLimit() {
|
|
200
|
+
if (!this.options.rateLimit)
|
|
201
|
+
return;
|
|
202
|
+
const { max, windowMs } = this.options.rateLimit;
|
|
203
|
+
while (true) {
|
|
204
|
+
const now = Date.now();
|
|
205
|
+
this.rateLimitTimestamps = this.rateLimitTimestamps.filter((t) => now - t < windowMs);
|
|
206
|
+
if (this.rateLimitTimestamps.length < max) {
|
|
207
|
+
this.rateLimitTimestamps.push(now);
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
const oldest = this.rateLimitTimestamps[0];
|
|
211
|
+
const waitTime = Math.max(10, windowMs - (now - oldest) + 5);
|
|
212
|
+
await new Promise((resolve) => setTimeout(resolve, waitTime));
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
async processAction(action, context, result) {
|
|
216
|
+
result.processed++;
|
|
217
|
+
const now = Date.now();
|
|
218
|
+
// 1. Check TTL expiration
|
|
219
|
+
if (action.expiresAt && action.expiresAt <= now) {
|
|
220
|
+
await store_js_1.ActionStore.updateStatus(this.db, this.tableName, action.id, 'EXPIRED');
|
|
221
|
+
const expiredRecord = { ...action, status: 'EXPIRED' };
|
|
222
|
+
result.expired++;
|
|
223
|
+
this.events.emit('action:expired', expiredRecord);
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
// 2. Lookup handler
|
|
227
|
+
const handler = this.handlers.get(action.action);
|
|
228
|
+
if (!handler) {
|
|
229
|
+
// No local handler; leave as PENDING for remote sync replication
|
|
230
|
+
result.skipped++;
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
// 3. Mark EXECUTING
|
|
234
|
+
await store_js_1.ActionStore.updateStatus(this.db, this.tableName, action.id, 'EXECUTING');
|
|
235
|
+
this.events.emit('action:executing', { ...action, status: 'EXECUTING' });
|
|
236
|
+
// 4. Rate-limiting throttle
|
|
237
|
+
await this.waitForRateLimit();
|
|
238
|
+
// 5. Execute handler
|
|
239
|
+
try {
|
|
240
|
+
const res = await handler(action, context);
|
|
241
|
+
const executedAt = Date.now();
|
|
242
|
+
await store_js_1.ActionStore.updateStatus(this.db, this.tableName, action.id, 'COMPLETED', {
|
|
243
|
+
executedAt,
|
|
244
|
+
result: res ?? null,
|
|
245
|
+
});
|
|
246
|
+
result.completed++;
|
|
247
|
+
this.events.emit('action:completed', {
|
|
248
|
+
...action,
|
|
249
|
+
status: 'COMPLETED',
|
|
250
|
+
executedAt,
|
|
251
|
+
result: res ?? null,
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
catch (err) {
|
|
255
|
+
const nextRetry = action.retryCount + 1;
|
|
256
|
+
const isFinalFailure = nextRetry >= action.maxRetries;
|
|
257
|
+
const newStatus = isFinalFailure ? 'FAILED' : 'PENDING';
|
|
258
|
+
const errorMsg = err instanceof Error ? err.message : String(err);
|
|
259
|
+
await store_js_1.ActionStore.updateStatus(this.db, this.tableName, action.id, newStatus, {
|
|
260
|
+
retryCount: nextRetry,
|
|
261
|
+
lastError: errorMsg,
|
|
262
|
+
});
|
|
263
|
+
if (isFinalFailure) {
|
|
264
|
+
result.failed++;
|
|
265
|
+
this.events.emit('action:failed', {
|
|
266
|
+
...action,
|
|
267
|
+
status: 'FAILED',
|
|
268
|
+
retryCount: nextRetry,
|
|
269
|
+
lastError: errorMsg,
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
else {
|
|
273
|
+
this.events.emit('action:retry', {
|
|
274
|
+
...action,
|
|
275
|
+
status: 'PENDING',
|
|
276
|
+
retryCount: nextRetry,
|
|
277
|
+
lastError: errorMsg,
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
}
|
|
154
282
|
async performFlush() {
|
|
155
283
|
const result = {
|
|
156
284
|
processed: 0,
|
|
@@ -174,70 +302,23 @@ class ActionManager {
|
|
|
174
302
|
db: this.db,
|
|
175
303
|
isOnline: this.isOnlineFn,
|
|
176
304
|
};
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
const
|
|
180
|
-
|
|
181
|
-
if (action.expiresAt && action.expiresAt <= now) {
|
|
182
|
-
await store_js_1.ActionStore.updateStatus(this.db, this.tableName, action.id, 'EXPIRED');
|
|
183
|
-
const expiredRecord = { ...action, status: 'EXPIRED' };
|
|
184
|
-
result.expired++;
|
|
185
|
-
this.events.emit('action:expired', expiredRecord);
|
|
186
|
-
continue;
|
|
187
|
-
}
|
|
188
|
-
// 2. Lookup handler
|
|
189
|
-
const handler = this.handlers.get(action.action);
|
|
190
|
-
if (!handler) {
|
|
191
|
-
// No local handler; leave as PENDING for remote sync replication
|
|
192
|
-
result.skipped++;
|
|
193
|
-
continue;
|
|
305
|
+
const concurrency = Math.max(1, this.options.concurrency ?? 1);
|
|
306
|
+
if (concurrency === 1) {
|
|
307
|
+
for (const action of pending) {
|
|
308
|
+
await this.processAction(action, context, result);
|
|
194
309
|
}
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
result: res ?? null,
|
|
205
|
-
});
|
|
206
|
-
result.completed++;
|
|
207
|
-
this.events.emit('action:completed', {
|
|
208
|
-
...action,
|
|
209
|
-
status: 'COMPLETED',
|
|
210
|
-
executedAt,
|
|
211
|
-
result: res ?? null,
|
|
212
|
-
});
|
|
213
|
-
}
|
|
214
|
-
catch (err) {
|
|
215
|
-
const nextRetry = action.retryCount + 1;
|
|
216
|
-
const isFinalFailure = nextRetry >= action.maxRetries;
|
|
217
|
-
const newStatus = isFinalFailure ? 'FAILED' : 'PENDING';
|
|
218
|
-
const errorMsg = err instanceof Error ? err.message : String(err);
|
|
219
|
-
await store_js_1.ActionStore.updateStatus(this.db, this.tableName, action.id, newStatus, {
|
|
220
|
-
retryCount: nextRetry,
|
|
221
|
-
lastError: errorMsg,
|
|
222
|
-
});
|
|
223
|
-
if (isFinalFailure) {
|
|
224
|
-
result.failed++;
|
|
225
|
-
this.events.emit('action:failed', {
|
|
226
|
-
...action,
|
|
227
|
-
status: 'FAILED',
|
|
228
|
-
retryCount: nextRetry,
|
|
229
|
-
lastError: errorMsg,
|
|
230
|
-
});
|
|
231
|
-
}
|
|
232
|
-
else {
|
|
233
|
-
this.events.emit('action:retry', {
|
|
234
|
-
...action,
|
|
235
|
-
status: 'PENDING',
|
|
236
|
-
retryCount: nextRetry,
|
|
237
|
-
lastError: errorMsg,
|
|
238
|
-
});
|
|
310
|
+
}
|
|
311
|
+
else {
|
|
312
|
+
let index = 0;
|
|
313
|
+
const workers = Array.from({ length: Math.min(concurrency, pending.length) }, async () => {
|
|
314
|
+
while (index < pending.length) {
|
|
315
|
+
const item = pending[index++];
|
|
316
|
+
if (item) {
|
|
317
|
+
await this.processAction(item, context, result);
|
|
318
|
+
}
|
|
239
319
|
}
|
|
240
|
-
}
|
|
320
|
+
});
|
|
321
|
+
await Promise.all(workers);
|
|
241
322
|
}
|
|
242
323
|
} while (this.flushRerunRequested);
|
|
243
324
|
}
|
package/dist/actions/types.d.ts
CHANGED
|
@@ -1,6 +1,22 @@
|
|
|
1
1
|
import { LocalDBAdapter } from '../adapters/local/index.js';
|
|
2
2
|
import { CustomLogger } from '../utils/logger.js';
|
|
3
3
|
import { NetworkStatusProvider } from '../core/types.js';
|
|
4
|
+
export type ActionSchemaValidator<T = any> = ((payload: unknown) => T | boolean | Promise<T | boolean>) | {
|
|
5
|
+
parse: (val: unknown) => T;
|
|
6
|
+
} | {
|
|
7
|
+
safeParse: (val: unknown) => {
|
|
8
|
+
success: boolean;
|
|
9
|
+
data?: T;
|
|
10
|
+
error?: any;
|
|
11
|
+
};
|
|
12
|
+
};
|
|
13
|
+
export interface ActionDefinition<TPayload = any, TResult = any> {
|
|
14
|
+
name: string;
|
|
15
|
+
schema?: ActionSchemaValidator<TPayload>;
|
|
16
|
+
handler?: ActionHandler<TPayload, TResult>;
|
|
17
|
+
maxRetries?: number;
|
|
18
|
+
defaultTtlMs?: number;
|
|
19
|
+
}
|
|
4
20
|
export type ActionStatus = 'PENDING' | 'EXECUTING' | 'COMPLETED' | 'FAILED' | 'EXPIRED' | 'CANCELLED';
|
|
5
21
|
export interface ActionRecord<TPayload = any, TResult = any> {
|
|
6
22
|
id: string;
|
|
@@ -48,6 +64,12 @@ export interface FlushActionsResult {
|
|
|
48
64
|
expired: number;
|
|
49
65
|
skipped: number;
|
|
50
66
|
}
|
|
67
|
+
export interface ActionRateLimitConfig {
|
|
68
|
+
/** Maximum number of actions allowed per time window */
|
|
69
|
+
max: number;
|
|
70
|
+
/** Window duration in milliseconds (e.g. 1000 for 1 second) */
|
|
71
|
+
windowMs: number;
|
|
72
|
+
}
|
|
51
73
|
export interface ActionManagerOptions {
|
|
52
74
|
tableName?: string;
|
|
53
75
|
defaultMaxRetries?: number;
|
|
@@ -56,6 +78,15 @@ export interface ActionManagerOptions {
|
|
|
56
78
|
autoFlushOnEnqueue?: boolean;
|
|
57
79
|
network?: NetworkStatusProvider;
|
|
58
80
|
logger?: boolean | CustomLogger;
|
|
81
|
+
/**
|
|
82
|
+
* Maximum concurrent action executions during flush.
|
|
83
|
+
* Default: 1 (strictly sequential). Set higher (e.g. 3 or 5) for parallel dispatch.
|
|
84
|
+
*/
|
|
85
|
+
concurrency?: number;
|
|
86
|
+
/**
|
|
87
|
+
* Rate limiting throttle across action dispatches (e.g. { max: 10, windowMs: 1000 }).
|
|
88
|
+
*/
|
|
89
|
+
rateLimit?: ActionRateLimitConfig;
|
|
59
90
|
}
|
|
60
91
|
export interface EmailAttachment {
|
|
61
92
|
filename: string;
|
|
@@ -76,6 +107,8 @@ export interface EmailPayload {
|
|
|
76
107
|
templateData?: Record<string, any>;
|
|
77
108
|
headers?: Record<string, string>;
|
|
78
109
|
attachments?: EmailAttachment[];
|
|
110
|
+
/** React Email component or JSX element to render automatically */
|
|
111
|
+
react?: any;
|
|
79
112
|
metadata?: Record<string, any>;
|
|
80
113
|
}
|
|
81
114
|
export interface SendEmailOptions extends EmailPayload {
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { RemoteDBAdapter } from './index.js';
|
|
2
|
+
import { DeltaChanges, PushResult, SyncOperation } from '../../core/types.js';
|
|
3
|
+
export interface SelfHostedRemoteAdapterOptions {
|
|
4
|
+
/**
|
|
5
|
+
* Endpoint base URL for the sync API (e.g. 'https://api.mycompany.com/api/sync').
|
|
6
|
+
*/
|
|
7
|
+
url: string;
|
|
8
|
+
/**
|
|
9
|
+
* Optional secret or JWT auth token sent in `Authorization: Bearer <token>`.
|
|
10
|
+
*/
|
|
11
|
+
token?: string;
|
|
12
|
+
/**
|
|
13
|
+
* List of tables to sync.
|
|
14
|
+
*/
|
|
15
|
+
tables?: string[];
|
|
16
|
+
/**
|
|
17
|
+
* Custom HTTP request headers.
|
|
18
|
+
*/
|
|
19
|
+
headers?: Record<string, string>;
|
|
20
|
+
/**
|
|
21
|
+
* Custom fetch implementation (defaults to globalThis.fetch).
|
|
22
|
+
*/
|
|
23
|
+
fetch?: typeof fetch;
|
|
24
|
+
/**
|
|
25
|
+
* Primary key field name (default: 'id').
|
|
26
|
+
*/
|
|
27
|
+
primaryKey?: string;
|
|
28
|
+
/**
|
|
29
|
+
* Polling interval in milliseconds for live change detection. Default: 5000.
|
|
30
|
+
*/
|
|
31
|
+
pollIntervalMs?: number;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Universal client remote adapter for self-hosted local-lite sync backends.
|
|
35
|
+
* Connects directly to server endpoints created via `createSyncEndpoint()` with zero vendor lock-in.
|
|
36
|
+
*/
|
|
37
|
+
export declare class SelfHostedRemoteAdapter implements RemoteDBAdapter {
|
|
38
|
+
private url;
|
|
39
|
+
private token?;
|
|
40
|
+
private tables;
|
|
41
|
+
private customHeaders;
|
|
42
|
+
private fetchFn;
|
|
43
|
+
private pollIntervalMs;
|
|
44
|
+
private syncScope?;
|
|
45
|
+
private activeSubscribers;
|
|
46
|
+
private pollTimer?;
|
|
47
|
+
private lastPollCursor;
|
|
48
|
+
constructor(options: SelfHostedRemoteAdapterOptions);
|
|
49
|
+
private getRequestHeaders;
|
|
50
|
+
/**
|
|
51
|
+
* Pushes client mutations to the self-hosted sync backend.
|
|
52
|
+
*/
|
|
53
|
+
pushChanges(operations: SyncOperation[]): Promise<PushResult>;
|
|
54
|
+
/**
|
|
55
|
+
* Pulls delta changes from the self-hosted sync backend since a given timestamp or cursor.
|
|
56
|
+
*/
|
|
57
|
+
fetchChanges(sinceTimestamp: number, _scope?: Record<string, any>): Promise<DeltaChanges>;
|
|
58
|
+
/**
|
|
59
|
+
* Subscribes to live server changes via periodic polling.
|
|
60
|
+
*/
|
|
61
|
+
subscribeToLiveChanges(callback: (changes: DeltaChanges) => void, scope?: Record<string, any> | (() => Record<string, any> | Promise<Record<string, any>>)): () => void;
|
|
62
|
+
private startPolling;
|
|
63
|
+
setSyncScope(scope?: Record<string, any> | (() => Record<string, any> | Promise<Record<string, any>>)): void;
|
|
64
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.SelfHostedRemoteAdapter = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Universal client remote adapter for self-hosted local-lite sync backends.
|
|
6
|
+
* Connects directly to server endpoints created via `createSyncEndpoint()` with zero vendor lock-in.
|
|
7
|
+
*/
|
|
8
|
+
class SelfHostedRemoteAdapter {
|
|
9
|
+
url;
|
|
10
|
+
token;
|
|
11
|
+
tables;
|
|
12
|
+
customHeaders;
|
|
13
|
+
fetchFn;
|
|
14
|
+
pollIntervalMs;
|
|
15
|
+
syncScope;
|
|
16
|
+
activeSubscribers = new Set();
|
|
17
|
+
pollTimer;
|
|
18
|
+
lastPollCursor = 0;
|
|
19
|
+
constructor(options) {
|
|
20
|
+
if (!options.url) {
|
|
21
|
+
throw new Error("A valid 'url' is required for SelfHostedRemoteAdapter.");
|
|
22
|
+
}
|
|
23
|
+
this.url = options.url.replace(/\/$/, '');
|
|
24
|
+
this.token = options.token;
|
|
25
|
+
this.tables = options.tables ?? [];
|
|
26
|
+
this.customHeaders = options.headers ?? {};
|
|
27
|
+
this.fetchFn = options.fetch || globalThis.fetch;
|
|
28
|
+
this.pollIntervalMs = options.pollIntervalMs ?? 5000;
|
|
29
|
+
if (!this.fetchFn) {
|
|
30
|
+
throw new Error('A global or configured fetch function is required for SelfHostedRemoteAdapter.');
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
getRequestHeaders() {
|
|
34
|
+
const headers = {
|
|
35
|
+
'Content-Type': 'application/json',
|
|
36
|
+
...this.customHeaders,
|
|
37
|
+
};
|
|
38
|
+
if (this.token) {
|
|
39
|
+
headers['Authorization'] = `Bearer ${this.token}`;
|
|
40
|
+
headers['X-Sync-Secret'] = this.token;
|
|
41
|
+
}
|
|
42
|
+
return headers;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Pushes client mutations to the self-hosted sync backend.
|
|
46
|
+
*/
|
|
47
|
+
async pushChanges(operations) {
|
|
48
|
+
if (operations.length === 0) {
|
|
49
|
+
return { success: true, successfulIds: [] };
|
|
50
|
+
}
|
|
51
|
+
const response = await this.fetchFn(this.url, {
|
|
52
|
+
method: 'POST',
|
|
53
|
+
headers: this.getRequestHeaders(),
|
|
54
|
+
body: JSON.stringify({ operations }),
|
|
55
|
+
});
|
|
56
|
+
if (!response.ok) {
|
|
57
|
+
const errText = await response.text().catch(() => response.statusText);
|
|
58
|
+
throw new Error(`Self-hosted sync push failed (${response.status}): ${errText}`);
|
|
59
|
+
}
|
|
60
|
+
const data = await response.json();
|
|
61
|
+
return {
|
|
62
|
+
success: true,
|
|
63
|
+
successfulIds: data.successfulIds ?? operations.map((op) => op.id),
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Pulls delta changes from the self-hosted sync backend since a given timestamp or cursor.
|
|
68
|
+
*/
|
|
69
|
+
async fetchChanges(sinceTimestamp, _scope) {
|
|
70
|
+
const tablesParam = encodeURIComponent(this.tables.join(','));
|
|
71
|
+
const url = `${this.url}?tables=${tablesParam}&since=${encodeURIComponent(String(sinceTimestamp))}`;
|
|
72
|
+
const response = await this.fetchFn(url, {
|
|
73
|
+
method: 'GET',
|
|
74
|
+
headers: this.getRequestHeaders(),
|
|
75
|
+
});
|
|
76
|
+
if (!response.ok) {
|
|
77
|
+
const errText = await response.text().catch(() => response.statusText);
|
|
78
|
+
throw new Error(`Self-hosted sync pull failed (${response.status}): ${errText}`);
|
|
79
|
+
}
|
|
80
|
+
const data = await response.json();
|
|
81
|
+
this.lastPollCursor = Math.max(this.lastPollCursor, data.cursor ?? sinceTimestamp);
|
|
82
|
+
return data.changes ?? { timestamp: Date.now(), changes: [] };
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Subscribes to live server changes via periodic polling.
|
|
86
|
+
*/
|
|
87
|
+
subscribeToLiveChanges(callback, scope) {
|
|
88
|
+
if (scope) {
|
|
89
|
+
this.syncScope = scope;
|
|
90
|
+
}
|
|
91
|
+
this.activeSubscribers.add(callback);
|
|
92
|
+
if (!this.pollTimer) {
|
|
93
|
+
this.startPolling();
|
|
94
|
+
}
|
|
95
|
+
return () => {
|
|
96
|
+
this.activeSubscribers.delete(callback);
|
|
97
|
+
if (this.activeSubscribers.size === 0 && this.pollTimer) {
|
|
98
|
+
clearInterval(this.pollTimer);
|
|
99
|
+
this.pollTimer = undefined;
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
startPolling() {
|
|
104
|
+
this.pollTimer = setInterval(async () => {
|
|
105
|
+
if (this.activeSubscribers.size === 0)
|
|
106
|
+
return;
|
|
107
|
+
try {
|
|
108
|
+
const changes = await this.fetchChanges(this.lastPollCursor);
|
|
109
|
+
const hasChanges = Object.values(changes).some((rows) => Array.isArray(rows) && rows.length > 0);
|
|
110
|
+
if (hasChanges) {
|
|
111
|
+
for (const subscriber of this.activeSubscribers) {
|
|
112
|
+
try {
|
|
113
|
+
subscriber(changes);
|
|
114
|
+
}
|
|
115
|
+
catch { }
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
catch { }
|
|
120
|
+
}, this.pollIntervalMs);
|
|
121
|
+
}
|
|
122
|
+
setSyncScope(scope) {
|
|
123
|
+
this.syncScope = scope;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
exports.SelfHostedRemoteAdapter = SelfHostedRemoteAdapter;
|
package/dist/config/index.d.ts
CHANGED
|
@@ -13,7 +13,9 @@ export { NodeSQLiteAdapter } from '../adapters/local/node-sqlite.js';
|
|
|
13
13
|
export { SupabaseRemoteAdapter } from '../adapters/remote/supabase.js';
|
|
14
14
|
export { ConvexRemoteAdapter } from '../adapters/remote/convex.js';
|
|
15
15
|
export { FirestoreRemoteAdapter } from '../adapters/remote/firestore.js';
|
|
16
|
+
export { SelfHostedRemoteAdapter } from '../adapters/remote/self-hosted.js';
|
|
16
17
|
export { MemoryDemoRemoteAdapter, NoopRemoteAdapter } from '../adapters/remote/demo.js';
|
|
18
|
+
export type { RemoteDBAdapter } from '../adapters/remote/index.js';
|
|
17
19
|
/**
|
|
18
20
|
* Type-safe configuration helper function (similar to defineConfig in Vite/Tailwind).
|
|
19
21
|
*/
|
package/dist/config/index.js
CHANGED
|
@@ -14,7 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
14
14
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
15
|
};
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
-
exports.NoopRemoteAdapter = exports.MemoryDemoRemoteAdapter = exports.FirestoreRemoteAdapter = exports.ConvexRemoteAdapter = exports.SupabaseRemoteAdapter = exports.NodeSQLiteAdapter = exports.SqlJsAdapter = exports.LibSQLAdapter = exports.BetterSQLite3Adapter = exports.OpSQLiteAdapter = exports.ExpoSQLiteAdapter = exports.LocalFirstClient = exports.resolveRemoteAdapter = exports.resolveLocalAdapter = void 0;
|
|
17
|
+
exports.NoopRemoteAdapter = exports.MemoryDemoRemoteAdapter = exports.SelfHostedRemoteAdapter = exports.FirestoreRemoteAdapter = exports.ConvexRemoteAdapter = exports.SupabaseRemoteAdapter = exports.NodeSQLiteAdapter = exports.SqlJsAdapter = exports.LibSQLAdapter = exports.BetterSQLite3Adapter = exports.OpSQLiteAdapter = exports.ExpoSQLiteAdapter = exports.LocalFirstClient = exports.resolveRemoteAdapter = exports.resolveLocalAdapter = void 0;
|
|
18
18
|
exports.defineSyncConfig = defineSyncConfig;
|
|
19
19
|
exports.createSyncClient = createSyncClient;
|
|
20
20
|
const client_js_1 = require("../core/client.js");
|
|
@@ -49,6 +49,8 @@ var convex_js_1 = require("../adapters/remote/convex.js");
|
|
|
49
49
|
Object.defineProperty(exports, "ConvexRemoteAdapter", { enumerable: true, get: function () { return convex_js_1.ConvexRemoteAdapter; } });
|
|
50
50
|
var firestore_js_1 = require("../adapters/remote/firestore.js");
|
|
51
51
|
Object.defineProperty(exports, "FirestoreRemoteAdapter", { enumerable: true, get: function () { return firestore_js_1.FirestoreRemoteAdapter; } });
|
|
52
|
+
var self_hosted_js_1 = require("../adapters/remote/self-hosted.js");
|
|
53
|
+
Object.defineProperty(exports, "SelfHostedRemoteAdapter", { enumerable: true, get: function () { return self_hosted_js_1.SelfHostedRemoteAdapter; } });
|
|
52
54
|
var demo_js_1 = require("../adapters/remote/demo.js");
|
|
53
55
|
Object.defineProperty(exports, "MemoryDemoRemoteAdapter", { enumerable: true, get: function () { return demo_js_1.MemoryDemoRemoteAdapter; } });
|
|
54
56
|
Object.defineProperty(exports, "NoopRemoteAdapter", { enumerable: true, get: function () { return demo_js_1.NoopRemoteAdapter; } });
|
|
@@ -101,5 +103,20 @@ async function createSyncClient(config) {
|
|
|
101
103
|
if (config.autoInitialize !== false) {
|
|
102
104
|
await client.initialize();
|
|
103
105
|
}
|
|
106
|
+
// 6. Direct Email Dispatch (Nodemailer, Resend, SendGrid, Postmark, HTTP, etc.)
|
|
107
|
+
if (config.email) {
|
|
108
|
+
const { createEmailHandler } = await import('../email/index.js');
|
|
109
|
+
const emailHandler = createEmailHandler({
|
|
110
|
+
provider: config.email.provider,
|
|
111
|
+
transport: config.email.transport,
|
|
112
|
+
apiKey: config.email.apiKey,
|
|
113
|
+
endpoint: config.email.endpoint,
|
|
114
|
+
headers: config.email.headers,
|
|
115
|
+
defaultFrom: config.email.defaults?.from,
|
|
116
|
+
defaults: config.email.defaults,
|
|
117
|
+
...config.email.options,
|
|
118
|
+
});
|
|
119
|
+
client.actions.registerEmailHandler(emailHandler);
|
|
120
|
+
}
|
|
104
121
|
return client;
|
|
105
122
|
}
|