local-lite 1.0.2 → 1.0.4

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 (73) hide show
  1. package/README.md +4 -3
  2. package/dist/actions/manager.js +6 -2
  3. package/dist/actions/store.js +33 -19
  4. package/dist/adapters/local/expo-sqlite.js +4 -2
  5. package/dist/adapters/local/libsql.js +3 -1
  6. package/dist/adapters/local/op-sqlite.js +2 -1
  7. package/dist/adapters/network/index.js +10 -5
  8. package/dist/adapters/remote/convex.js +37 -10
  9. package/dist/adapters/remote/firestore.js +11 -4
  10. package/dist/adapters/remote/self-hosted.js +8 -4
  11. package/dist/adapters/remote/supabase.js +95 -29
  12. package/dist/auth/apple.js +8 -4
  13. package/dist/auth/github.js +15 -7
  14. package/dist/auth/google.js +7 -4
  15. package/dist/auth/identity.js +5 -1
  16. package/dist/auth/local.js +74 -21
  17. package/dist/auth/microsoft.js +22 -8
  18. package/dist/auth/session.js +45 -34
  19. package/dist/auth/unified.js +3 -2
  20. package/dist/backups/cloud-storage.js +10 -7
  21. package/dist/backups/encryption.js +4 -2
  22. package/dist/backups/onedrive.js +3 -3
  23. package/dist/backups/operations.js +4 -2
  24. package/dist/config/index.d.ts +1 -1
  25. package/dist/config/index.js +3 -0
  26. package/dist/config/resolve-local.js +18 -6
  27. package/dist/config/resolve-remote.js +2 -1
  28. package/dist/core/client.d.ts +2 -2
  29. package/dist/core/client.js +64 -26
  30. package/dist/core/index.d.ts +1 -1
  31. package/dist/core/maintenance.js +5 -4
  32. package/dist/core/meta-store.js +3 -3
  33. package/dist/core/outbox-store.js +32 -25
  34. package/dist/core/query-builder.js +23 -10
  35. package/dist/core/query.js +19 -7
  36. package/dist/core/schema-manager.js +6 -2
  37. package/dist/core/sync-worker.js +38 -12
  38. package/dist/core/table-manager.js +8 -2
  39. package/dist/core/types.d.ts +1 -1
  40. package/dist/devtools/BenchmarkModal.d.ts +1 -1
  41. package/dist/devtools/BenchmarkModal.js +234 -54
  42. package/dist/devtools/SyncInspector.js +260 -37
  43. package/dist/email/index.d.ts +17 -18
  44. package/dist/email/index.js +46 -72
  45. package/dist/keys/generator.js +4 -1
  46. package/dist/keys/manager.js +22 -4
  47. package/dist/keys/signed-token.js +12 -4
  48. package/dist/keys/store.js +23 -16
  49. package/dist/kv/manager.js +5 -2
  50. package/dist/kv/store.js +13 -13
  51. package/dist/react/auth.js +12 -12
  52. package/dist/react/backups.js +1 -1
  53. package/dist/react/index.js +14 -9
  54. package/dist/react/runner.js +1 -1
  55. package/dist/react/status.js +6 -2
  56. package/dist/reactive/event-emitter.js +2 -2
  57. package/dist/scheduler/cron.js +3 -1
  58. package/dist/scheduler/store.js +37 -31
  59. package/dist/schema/generator.js +37 -34
  60. package/dist/search/manager.js +3 -1
  61. package/dist/search/store.js +17 -16
  62. package/dist/server/email.d.ts +8 -0
  63. package/dist/server/email.js +48 -3
  64. package/dist/server/index.js +4 -4
  65. package/dist/server/sync.js +11 -4
  66. package/dist/storage/driver.js +2 -1
  67. package/dist/storage/expo.js +5 -2
  68. package/dist/storage/manager.js +3 -1
  69. package/dist/storage/store.js +26 -25
  70. package/dist/utils/dynamic.js +4 -2
  71. package/dist/utils/logger.js +13 -6
  72. package/dist/utils/portability.js +21 -9
  73. package/package.json +1 -1
@@ -9,7 +9,8 @@ function mapJobRow(r) {
9
9
  let payload = undefined;
10
10
  if (r.payload) {
11
11
  try {
12
- payload = typeof r.payload === 'string' ? JSON.parse(r.payload) : r.payload;
12
+ payload =
13
+ typeof r.payload === 'string' ? JSON.parse(r.payload) : r.payload;
13
14
  }
14
15
  catch {
15
16
  payload = r.payload;
@@ -40,40 +41,40 @@ function mapJobRunRow(r) {
40
41
  }
41
42
  class JobStore {
42
43
  static async ensureSchema(db, jobsTable = exports.DEFAULT_JOBS_TABLE, runsTable = exports.DEFAULT_JOB_RUNS_TABLE) {
43
- await db.execute(`CREATE TABLE IF NOT EXISTS ${jobsTable} (
44
- id TEXT PRIMARY KEY,
45
- name TEXT NOT NULL,
46
- schedule TEXT NOT NULL,
47
- interval_ms INTEGER NOT NULL,
48
- last_run_at INTEGER,
49
- next_run_at INTEGER NOT NULL,
50
- enabled INTEGER NOT NULL DEFAULT 1,
51
- payload TEXT,
52
- created_at INTEGER NOT NULL
44
+ await db.execute(`CREATE TABLE IF NOT EXISTS ${jobsTable} (
45
+ id TEXT PRIMARY KEY,
46
+ name TEXT NOT NULL,
47
+ schedule TEXT NOT NULL,
48
+ interval_ms INTEGER NOT NULL,
49
+ last_run_at INTEGER,
50
+ next_run_at INTEGER NOT NULL,
51
+ enabled INTEGER NOT NULL DEFAULT 1,
52
+ payload TEXT,
53
+ created_at INTEGER NOT NULL
53
54
  );`);
54
55
  await db.execute(`CREATE INDEX IF NOT EXISTS idx_${jobsTable}_next ON ${jobsTable} (next_run_at);`);
55
- await db.execute(`CREATE TABLE IF NOT EXISTS ${runsTable} (
56
- id TEXT PRIMARY KEY,
57
- job_id TEXT NOT NULL,
58
- status TEXT NOT NULL,
59
- started_at INTEGER NOT NULL,
60
- finished_at INTEGER,
61
- duration_ms INTEGER,
62
- error TEXT
56
+ await db.execute(`CREATE TABLE IF NOT EXISTS ${runsTable} (
57
+ id TEXT PRIMARY KEY,
58
+ job_id TEXT NOT NULL,
59
+ status TEXT NOT NULL,
60
+ started_at INTEGER NOT NULL,
61
+ finished_at INTEGER,
62
+ duration_ms INTEGER,
63
+ error TEXT
63
64
  );`);
64
65
  await db.execute(`CREATE INDEX IF NOT EXISTS idx_${runsTable}_job ON ${runsTable} (job_id, started_at);`);
65
66
  }
66
67
  static async upsertJob(db, jobsTable = exports.DEFAULT_JOBS_TABLE, job) {
67
68
  const payloadStr = job.payload !== undefined ? JSON.stringify(job.payload) : null;
68
- await db.execute(`INSERT INTO ${jobsTable} (id, name, schedule, interval_ms, last_run_at, next_run_at, enabled, payload, created_at)
69
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
70
- ON CONFLICT(id) DO UPDATE SET
71
- name = excluded.name,
72
- schedule = excluded.schedule,
73
- interval_ms = excluded.interval_ms,
74
- last_run_at = excluded.last_run_at,
75
- next_run_at = excluded.next_run_at,
76
- enabled = excluded.enabled,
69
+ await db.execute(`INSERT INTO ${jobsTable} (id, name, schedule, interval_ms, last_run_at, next_run_at, enabled, payload, created_at)
70
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
71
+ ON CONFLICT(id) DO UPDATE SET
72
+ name = excluded.name,
73
+ schedule = excluded.schedule,
74
+ interval_ms = excluded.interval_ms,
75
+ last_run_at = excluded.last_run_at,
76
+ next_run_at = excluded.next_run_at,
77
+ enabled = excluded.enabled,
77
78
  payload = excluded.payload;`, [
78
79
  job.id,
79
80
  job.name,
@@ -104,14 +105,17 @@ class JobStore {
104
105
  await db.execute(`UPDATE ${jobsTable} SET last_run_at = ?, next_run_at = ? WHERE id = ?;`, [lastRunAt, nextRunAt, id]);
105
106
  }
106
107
  static async setJobEnabled(db, jobsTable = exports.DEFAULT_JOBS_TABLE, id, enabled) {
107
- await db.execute(`UPDATE ${jobsTable} SET enabled = ? WHERE id = ?;`, [enabled ? 1 : 0, id]);
108
+ await db.execute(`UPDATE ${jobsTable} SET enabled = ? WHERE id = ?;`, [
109
+ enabled ? 1 : 0,
110
+ id,
111
+ ]);
108
112
  }
109
113
  static async deleteJob(db, jobsTable = exports.DEFAULT_JOBS_TABLE, id) {
110
114
  await db.execute(`DELETE FROM ${jobsTable} WHERE id = ?;`, [id]);
111
115
  }
112
116
  // --- Run History ---
113
117
  static async recordRunStart(db, runsTable = exports.DEFAULT_JOB_RUNS_TABLE, run) {
114
- await db.execute(`INSERT INTO ${runsTable} (id, job_id, status, started_at, finished_at, duration_ms, error)
118
+ await db.execute(`INSERT INTO ${runsTable} (id, job_id, status, started_at, finished_at, duration_ms, error)
115
119
  VALUES (?, ?, ?, ?, ?, ?, ?);`, [run.id, run.jobId, run.status, run.startedAt, null, null, null]);
116
120
  }
117
121
  static async recordRunFinish(db, runsTable = exports.DEFAULT_JOB_RUNS_TABLE, id, status, finishedAt, durationMs, error) {
@@ -128,7 +132,9 @@ class JobStore {
128
132
  return (rows || []).map(mapJobRunRow);
129
133
  }
130
134
  static async pruneRuns(db, runsTable = exports.DEFAULT_JOB_RUNS_TABLE, cutoffTimestamp) {
131
- await db.execute(`DELETE FROM ${runsTable} WHERE started_at < ?;`, [cutoffTimestamp]);
135
+ await db.execute(`DELETE FROM ${runsTable} WHERE started_at < ?;`, [
136
+ cutoffTimestamp,
137
+ ]);
132
138
  }
133
139
  }
134
140
  exports.JobStore = JobStore;
@@ -63,7 +63,8 @@ function parseSchemaIndexes(content, options = {}) {
63
63
  }
64
64
  }
65
65
  // Skip empty relationships
66
- if (line.includes('Relationships: [];') || line.includes('Relationships: []')) {
66
+ if (line.includes('Relationships: [];') ||
67
+ line.includes('Relationships: []')) {
67
68
  continue;
68
69
  }
69
70
  if (line.includes('Relationships: [')) {
@@ -79,14 +80,16 @@ function parseSchemaIndexes(content, options = {}) {
79
80
  const itemRegex = /foreignKeyName:\s*['"]([^'"]+)['"][\s\S]*?columns:\s*\[([^\]]+)\][\s\S]*?isOneToOne:\s*(true|false)[\s\S]*?referencedRelation:\s*['"]([^'"]+)['"](?:[\s\S]*?referencedColumns:\s*\[([^\]]+)\])?/g;
80
81
  const matches = [...block.matchAll(itemRegex)];
81
82
  for (const m of matches) {
82
- const columns = m[2].split(',').map(c => c.trim().replace(/['"]/g, ''));
83
+ const columns = m[2]
84
+ .split(',')
85
+ .map((c) => c.trim().replace(/['"]/g, ''));
83
86
  const isOneToOne = m[3] === 'true';
84
87
  const referencedRelation = m[4];
85
88
  const referencedColumns = m[5]
86
- ? m[5].split(',').map(c => c.trim().replace(/['"]/g, ''))
89
+ ? m[5].split(',').map((c) => c.trim().replace(/['"]/g, ''))
87
90
  : undefined;
88
91
  const isUnique = isOneToOne ? 'UNIQUE ' : '';
89
- const colSql = columns.map(c => `"${c}"`).join(', ');
92
+ const colSql = columns.map((c) => `"${c}"`).join(', ');
90
93
  const colSlug = columns.join('_');
91
94
  const indexName = `idx_${currentTable}_${colSlug}`;
92
95
  relationships.push({
@@ -112,7 +115,7 @@ function parseSchemaIndexes(content, options = {}) {
112
115
  for (const [table, cols] of tableColumns.entries()) {
113
116
  if (cols.has('business_id') && cols.has('deleted')) {
114
117
  const idxName = `idx_${table}_biz_del`;
115
- if (!relationships.some(r => r.table === table &&
118
+ if (!relationships.some((r) => r.table === table &&
116
119
  r.columns.length === 2 &&
117
120
  r.columns.includes('business_id') &&
118
121
  r.columns.includes('deleted'))) {
@@ -133,35 +136,35 @@ function parseSchemaIndexes(content, options = {}) {
133
136
  * Generates TypeScript source code containing index definitions and an applicator helper.
134
137
  */
135
138
  function formatSchemaIndexesCode(indexes) {
136
- const sqlStatements = indexes.map(i => i.sql).join('\n');
137
- return `/**
138
- * AUTO-GENERATED FILE - DO NOT EDIT MANUALLY.
139
- * Generated by local-lite schema index generator.
140
- */
141
-
142
- /**
143
- * SQLite index statements extracted from Supabase database schema.
144
- * Total indexes: ${indexes.length}
145
- */
146
- export const SCHEMA_INDEXES: readonly string[] = \`
147
- ${sqlStatements}
148
- \`.trim().split('\\n');
149
-
150
- /**
151
- * Applies all schema indexes into SQLite to ensure zero-latency local reads.
152
- * Executes each statement safely, ignoring errors if tables are not yet created.
153
- */
154
- export async function ensureSchemaIndexes(db: {
155
- execute: (query: string, params?: any[]) => Promise<any>;
156
- }): Promise<void> {
157
- for (const sql of SCHEMA_INDEXES) {
158
- try {
159
- await db.execute(sql);
160
- } catch {
161
- // Safe fallback if table has not been created yet
162
- }
163
- }
164
- }
139
+ const sqlStatements = indexes.map((i) => i.sql).join('\n');
140
+ return `/**
141
+ * AUTO-GENERATED FILE - DO NOT EDIT MANUALLY.
142
+ * Generated by local-lite schema index generator.
143
+ */
144
+
145
+ /**
146
+ * SQLite index statements extracted from Supabase database schema.
147
+ * Total indexes: ${indexes.length}
148
+ */
149
+ export const SCHEMA_INDEXES: readonly string[] = \`
150
+ ${sqlStatements}
151
+ \`.trim().split('\\n');
152
+
153
+ /**
154
+ * Applies all schema indexes into SQLite to ensure zero-latency local reads.
155
+ * Executes each statement safely, ignoring errors if tables are not yet created.
156
+ */
157
+ export async function ensureSchemaIndexes(db: {
158
+ execute: (query: string, params?: any[]) => Promise<any>;
159
+ }): Promise<void> {
160
+ for (const sql of SCHEMA_INDEXES) {
161
+ try {
162
+ await db.execute(sql);
163
+ } catch {
164
+ // Safe fallback if table has not been created yet
165
+ }
166
+ }
167
+ }
165
168
  `;
166
169
  }
167
170
  /**
@@ -45,7 +45,9 @@ class SearchManager {
45
45
  */
46
46
  async indexRecord(table, rowId, values) {
47
47
  const config = this.indices.get(table);
48
- const columns = config ? config.columns : Object.keys(values).filter((k) => k !== 'id');
48
+ const columns = config
49
+ ? config.columns
50
+ : Object.keys(values).filter((k) => k !== 'id');
49
51
  await store_js_1.SearchStore.indexRow(this.db, table, rowId, columns, values);
50
52
  }
51
53
  /**
@@ -85,15 +85,15 @@ class SearchStore {
85
85
  // Snippet column index in FTS5: columns are 0-based: col 0 is row_id, col 1 is columns[0], etc.
86
86
  // We pick column index 1 (or the first indexed text column) for snippet extraction
87
87
  const snippetColIndex = 1;
88
- let sql = `
89
- SELECT
90
- row_id,
91
- rank,
92
- snippet(${ftsTable}, ${snippetColIndex}, '${preTag}', '${postTag}', '...', 15) as snippet_text
93
- FROM ${ftsTable}
94
- WHERE ${ftsTable} MATCH ?
95
- ORDER BY rank
96
- LIMIT ? OFFSET ?;
88
+ let sql = `
89
+ SELECT
90
+ row_id,
91
+ rank,
92
+ snippet(${ftsTable}, ${snippetColIndex}, '${preTag}', '${postTag}', '...', 15) as snippet_text
93
+ FROM ${ftsTable}
94
+ WHERE ${ftsTable} MATCH ?
95
+ ORDER BY rank
96
+ LIMIT ? OFFSET ?;
97
97
  `;
98
98
  try {
99
99
  const rows = await db.execute(sql, [matchQuery, limit, offset]);
@@ -105,13 +105,14 @@ class SearchStore {
105
105
  }
106
106
  catch (err) {
107
107
  // In case snippet() function is unavailable in the environment, fallback to rank-only search
108
- if (err?.message?.includes('snippet') || err?.message?.includes('no such function')) {
109
- const fallbackSql = `
110
- SELECT row_id, rank
111
- FROM ${ftsTable}
112
- WHERE ${ftsTable} MATCH ?
113
- ORDER BY rank
114
- LIMIT ? OFFSET ?;
108
+ if (err?.message?.includes('snippet') ||
109
+ err?.message?.includes('no such function')) {
110
+ const fallbackSql = `
111
+ SELECT row_id, rank
112
+ FROM ${ftsTable}
113
+ WHERE ${ftsTable} MATCH ?
114
+ ORDER BY rank
115
+ LIMIT ? OFFSET ?;
115
116
  `;
116
117
  const rows = await db.execute(fallbackSql, [matchQuery, limit, offset]);
117
118
  return (rows || []).map((r) => ({
@@ -1,4 +1,12 @@
1
1
  import type { ApiEndpoint } from './index.js';
2
+ import { type ConcreteEmailHandler, type EmailHandlerOptions, type EmailMailOptions } from '../email/index.js';
3
+ export type NodemailerTransportInput = {
4
+ sendMail?: (options: EmailMailOptions) => Promise<any>;
5
+ [key: string]: any;
6
+ } | string;
7
+ export declare function loadNodemailer(): Promise<any>;
8
+ export declare function resolveTransporter(input: NodemailerTransportInput, defaults?: Partial<EmailMailOptions>): Promise<any>;
9
+ export declare function createNodemailerHandler(transporterOrOptions: NodemailerTransportInput, handlerOptions?: EmailHandlerOptions): ConcreteEmailHandler;
2
10
  export interface EmailEndpointOptions {
3
11
  /**
4
12
  * Secret token required in `Authorization: Bearer <secret>` or `x-app-secret` header.
@@ -1,6 +1,51 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.loadNodemailer = loadNodemailer;
4
+ exports.resolveTransporter = resolveTransporter;
5
+ exports.createNodemailerHandler = createNodemailerHandler;
3
6
  exports.createEmailEndpoint = createEmailEndpoint;
7
+ const index_js_1 = require("../email/index.js");
8
+ async function loadNodemailer() {
9
+ try {
10
+ const mod = await import('nodemailer');
11
+ return mod.default || mod;
12
+ }
13
+ catch {
14
+ throw new Error("The 'nodemailer' package is required to send emails via Nodemailer transport. Please install it via 'npm install nodemailer'.");
15
+ }
16
+ }
17
+ async function resolveTransporter(input, defaults) {
18
+ if (input && typeof input !== 'string' && typeof input.sendMail === 'function') {
19
+ return input;
20
+ }
21
+ const nodemailer = await loadNodemailer();
22
+ return nodemailer.createTransport(input, defaults);
23
+ }
24
+ function createNodemailerHandler(transporterOrOptions, handlerOptions = {}) {
25
+ let cachedTransporter = transporterOrOptions &&
26
+ typeof transporterOrOptions !== 'string' &&
27
+ typeof transporterOrOptions.sendMail === 'function'
28
+ ? transporterOrOptions
29
+ : null;
30
+ const getTransporter = async () => {
31
+ if (!cachedTransporter) {
32
+ cachedTransporter = await resolveTransporter(transporterOrOptions, handlerOptions.defaults);
33
+ }
34
+ return cachedTransporter;
35
+ };
36
+ return async (payload, record, _context) => {
37
+ const transporter = await getTransporter();
38
+ const mailOptions = await (0, index_js_1.prepareMailOptions)(payload, handlerOptions, record);
39
+ const info = await transporter.sendMail(mailOptions);
40
+ await handlerOptions.afterSend?.(info, payload, record);
41
+ return {
42
+ messageId: info.messageId,
43
+ response: info.response,
44
+ accepted: info.accepted,
45
+ rejected: info.rejected,
46
+ };
47
+ };
48
+ }
4
49
  /**
5
50
  * Creates a turnkey Request/Response API endpoint for receiving offline-enqueued emails
6
51
  * from local-lite clients and dispatching them via Nodemailer or cloud providers.
@@ -11,10 +56,11 @@ function createEmailEndpoint(options = {}) {
11
56
  'Access-Control-Allow-Methods': 'POST, OPTIONS',
12
57
  'Access-Control-Allow-Headers': 'Content-Type, Authorization, X-App-Secret, X-Message-ID',
13
58
  };
14
- const handlePost = async ({ request }) => {
59
+ const handlePost = async ({ request, }) => {
15
60
  // 1. Check secret token if configured
16
61
  if (options.secret) {
17
- const authHeader = request.headers.get('authorization') || request.headers.get('x-app-secret');
62
+ const authHeader = request.headers.get('authorization') ||
63
+ request.headers.get('x-app-secret');
18
64
  const expectedBearer = `Bearer ${options.secret}`;
19
65
  if (authHeader !== expectedBearer && authHeader !== options.secret) {
20
66
  return Response.json({ error: 'Unauthorized: Invalid email endpoint secret' }, { status: 401, headers: corsHeaders });
@@ -46,7 +92,6 @@ function createEmailEndpoint(options = {}) {
46
92
  result = await options.dispatch(payload, request);
47
93
  }
48
94
  else if (options.transport || (!options.provider && !options.apiKey)) {
49
- const { createNodemailerHandler } = await import('../email/index.js');
50
95
  const handler = createNodemailerHandler(options.transport || {}, {
51
96
  defaultFrom: options.defaultFrom,
52
97
  });
@@ -53,7 +53,7 @@ function defineServerConfig(config) {
53
53
  for (const [path, endpoint] of Object.entries(config.endpoints)) {
54
54
  if (!path.startsWith('/'))
55
55
  throw new TypeError(`API endpoint path must start with '/': ${path}`);
56
- if (!Object.values(endpoint).some(handler => typeof handler === 'function')) {
56
+ if (!Object.values(endpoint).some((handler) => typeof handler === 'function')) {
57
57
  throw new TypeError(`API endpoint '${path}' must define at least one method handler.`);
58
58
  }
59
59
  }
@@ -119,7 +119,7 @@ function createServer(config) {
119
119
  handlers,
120
120
  handler(path, method) {
121
121
  const normalized = normalizePath(path);
122
- const definition = definitions.find(item => item.path === normalized);
122
+ const definition = definitions.find((item) => item.path === normalized);
123
123
  if (!definition || !definition.endpoint[method]) {
124
124
  throw new Error(`No ${method} API handler is configured for '${normalized}'.`);
125
125
  }
@@ -139,8 +139,8 @@ function createServer(config) {
139
139
  }
140
140
  if (pathMatched) {
141
141
  const allowed = definitions
142
- .filter(definition => matchPath(definition.path, url.pathname))
143
- .flatMap(definition => Object.keys(definition.endpoint));
142
+ .filter((definition) => matchPath(definition.path, url.pathname))
143
+ .flatMap((definition) => Object.keys(definition.endpoint));
144
144
  return methodNotAllowed([...new Set(allowed)]);
145
145
  }
146
146
  return Response.json({ error: 'Not Found' }, { status: 404 });
@@ -117,7 +117,7 @@ function createSyncEndpoint(options = {}) {
117
117
  return match ? { type: 'admin', isAdmin: true } : false;
118
118
  };
119
119
  // POST: Push batch of mutations (or combined push+pull batch)
120
- const handlePost = async ({ request }) => {
120
+ const handlePost = async ({ request, }) => {
121
121
  const auth = await verifyAuth(request);
122
122
  if (!auth) {
123
123
  return Response.json({ error: 'Unauthorized: Invalid sync authentication' }, { status: 401, headers: corsHeaders });
@@ -129,7 +129,9 @@ function createSyncEndpoint(options = {}) {
129
129
  catch {
130
130
  return Response.json({ error: 'Bad Request: Invalid JSON body' }, { status: 400, headers: corsHeaders });
131
131
  }
132
- let operations = Array.isArray(body?.operations) ? body.operations : [];
132
+ let operations = Array.isArray(body?.operations)
133
+ ? body.operations
134
+ : [];
133
135
  if (options.onBeforePush) {
134
136
  const modified = await options.onBeforePush(operations, request, auth);
135
137
  if (Array.isArray(modified))
@@ -166,7 +168,7 @@ function createSyncEndpoint(options = {}) {
166
168
  }, { status: 200, headers: corsHeaders });
167
169
  };
168
170
  // GET: Pull deltas since cursor/timestamp
169
- const handleGet = async ({ request }) => {
171
+ const handleGet = async ({ request, }) => {
170
172
  const auth = await verifyAuth(request);
171
173
  if (!auth) {
172
174
  return Response.json({ error: 'Unauthorized: Invalid sync authentication' }, { status: 401, headers: corsHeaders });
@@ -175,7 +177,12 @@ function createSyncEndpoint(options = {}) {
175
177
  const tablesParam = url.searchParams.get('tables');
176
178
  const sinceParam = url.searchParams.get('since');
177
179
  const limitParam = url.searchParams.get('limit');
178
- let tables = tablesParam ? tablesParam.split(',').map((t) => t.trim()).filter(Boolean) : [];
180
+ let tables = tablesParam
181
+ ? tablesParam
182
+ .split(',')
183
+ .map((t) => t.trim())
184
+ .filter(Boolean)
185
+ : [];
179
186
  let since = sinceParam ? Number(sinceParam) : 0;
180
187
  let limit = limitParam ? Number(limitParam) : 500;
181
188
  if (options.onBeforePull) {
@@ -40,7 +40,8 @@ class NodeFileDriver {
40
40
  try {
41
41
  const fs = (0, dynamic_js_1.safeDynamicRequire)(NODE_FS_PROMISES_PKG) ??
42
42
  (await (0, dynamic_js_1.safeDynamicImport)(NODE_FS_PROMISES_PKG));
43
- const path = (0, dynamic_js_1.safeDynamicRequire)(NODE_PATH_PKG) ?? (await (0, dynamic_js_1.safeDynamicImport)(NODE_PATH_PKG));
43
+ const path = (0, dynamic_js_1.safeDynamicRequire)(NODE_PATH_PKG) ??
44
+ (await (0, dynamic_js_1.safeDynamicImport)(NODE_PATH_PKG));
44
45
  if (!fs || !path) {
45
46
  throw new Error('Node fs/path unavailable');
46
47
  }
@@ -102,7 +102,8 @@ class ExpoFileDriver {
102
102
  }
103
103
  if (this.resolvedBaseDir) {
104
104
  try {
105
- if (!this.resolvedBaseDir.exists && typeof this.resolvedBaseDir.create === 'function') {
105
+ if (!this.resolvedBaseDir.exists &&
106
+ typeof this.resolvedBaseDir.create === 'function') {
106
107
  this.resolvedBaseDir.create({ idempotent: true });
107
108
  }
108
109
  }
@@ -239,7 +240,9 @@ class ExpoFileDriver {
239
240
  const file = await this.resolveFile(key);
240
241
  if (typeof this.FileClass.downloadFileAsync === 'function') {
241
242
  try {
242
- await this.FileClass.downloadFileAsync(remoteUrl, file, { idempotent: true });
243
+ await this.FileClass.downloadFileAsync(remoteUrl, file, {
244
+ idempotent: true,
245
+ });
243
246
  return file.uri;
244
247
  }
245
248
  catch { }
@@ -111,7 +111,9 @@ class BlobStorageManager {
111
111
  async delete(key) {
112
112
  await this.driver.delete(key);
113
113
  await store_js_1.BlobStore.deleteByKey(this.db, this.tableName, key);
114
- if (this.deleteRemoteOnDelete && this.uploader && typeof this.uploader.delete === 'function') {
114
+ if (this.deleteRemoteOnDelete &&
115
+ this.uploader &&
116
+ typeof this.uploader.delete === 'function') {
115
117
  try {
116
118
  await this.uploader.delete(key);
117
119
  }
@@ -7,7 +7,8 @@ function mapBlobRow(r) {
7
7
  let meta;
8
8
  if (r.metadata) {
9
9
  try {
10
- meta = typeof r.metadata === 'string' ? JSON.parse(r.metadata) : r.metadata;
10
+ meta =
11
+ typeof r.metadata === 'string' ? JSON.parse(r.metadata) : r.metadata;
11
12
  }
12
13
  catch {
13
14
  meta = undefined;
@@ -30,36 +31,36 @@ function mapBlobRow(r) {
30
31
  }
31
32
  class BlobStore {
32
33
  static async ensureSchema(db, tableName = exports.DEFAULT_BLOBS_TABLE) {
33
- await db.execute(`CREATE TABLE IF NOT EXISTS ${tableName} (
34
- id TEXT PRIMARY KEY,
35
- key TEXT UNIQUE NOT NULL,
36
- name TEXT NOT NULL,
37
- mime_type TEXT NOT NULL,
38
- size INTEGER NOT NULL,
39
- local_path TEXT NOT NULL,
40
- remote_url TEXT,
41
- status TEXT NOT NULL,
42
- sha256 TEXT,
43
- metadata TEXT,
44
- created_at INTEGER NOT NULL,
45
- updated_at INTEGER NOT NULL
34
+ await db.execute(`CREATE TABLE IF NOT EXISTS ${tableName} (
35
+ id TEXT PRIMARY KEY,
36
+ key TEXT UNIQUE NOT NULL,
37
+ name TEXT NOT NULL,
38
+ mime_type TEXT NOT NULL,
39
+ size INTEGER NOT NULL,
40
+ local_path TEXT NOT NULL,
41
+ remote_url TEXT,
42
+ status TEXT NOT NULL,
43
+ sha256 TEXT,
44
+ metadata TEXT,
45
+ created_at INTEGER NOT NULL,
46
+ updated_at INTEGER NOT NULL
46
47
  );`);
47
48
  await db.execute(`CREATE INDEX IF NOT EXISTS idx_${tableName}_status ON ${tableName} (status);`);
48
49
  await db.execute(`CREATE INDEX IF NOT EXISTS idx_${tableName}_key ON ${tableName} (key);`);
49
50
  }
50
51
  static async insertOrUpdate(db, tableName = exports.DEFAULT_BLOBS_TABLE, record) {
51
52
  const metaStr = record.metadata ? JSON.stringify(record.metadata) : null;
52
- await db.execute(`INSERT INTO ${tableName} (id, key, name, mime_type, size, local_path, remote_url, status, sha256, metadata, created_at, updated_at)
53
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
54
- ON CONFLICT(key) DO UPDATE SET
55
- name = excluded.name,
56
- mime_type = excluded.mime_type,
57
- size = excluded.size,
58
- local_path = excluded.local_path,
59
- remote_url = excluded.remote_url,
60
- status = excluded.status,
61
- sha256 = excluded.sha256,
62
- metadata = excluded.metadata,
53
+ await db.execute(`INSERT INTO ${tableName} (id, key, name, mime_type, size, local_path, remote_url, status, sha256, metadata, created_at, updated_at)
54
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
55
+ ON CONFLICT(key) DO UPDATE SET
56
+ name = excluded.name,
57
+ mime_type = excluded.mime_type,
58
+ size = excluded.size,
59
+ local_path = excluded.local_path,
60
+ remote_url = excluded.remote_url,
61
+ status = excluded.status,
62
+ sha256 = excluded.sha256,
63
+ metadata = excluded.metadata,
63
64
  updated_at = excluded.updated_at;`, [
64
65
  record.id,
65
66
  record.key,
@@ -16,7 +16,8 @@ function safeDynamicRequire(pkgName) {
16
16
  }
17
17
  // In Metro bundler (__r), calling require(variableString) triggers Metro's
18
18
  // unknownModuleError console.error before throwing. Skip non-literal require in Metro.
19
- if (typeof globalThis !== 'undefined' && typeof globalThis.__r === 'function') {
19
+ if (typeof globalThis !== 'undefined' &&
20
+ typeof globalThis.__r === 'function') {
20
21
  return undefined;
21
22
  }
22
23
  const req = typeof __non_webpack_require__ !== 'undefined'
@@ -36,7 +37,8 @@ async function safeDynamicImport(pkgName) {
36
37
  if (syncMod !== undefined) {
37
38
  return syncMod;
38
39
  }
39
- if (typeof globalThis !== 'undefined' && typeof globalThis.__r === 'function') {
40
+ if (typeof globalThis !== 'undefined' &&
41
+ typeof globalThis.__r === 'function') {
40
42
  return undefined;
41
43
  }
42
44
  // Metro's AST worker rejects `import(dynamicVariable)` with "Invalid call at line ...: import(...)".
@@ -76,7 +76,8 @@ class SyncLogger {
76
76
  error(message, ...args) {
77
77
  if (!this.shouldLog('error'))
78
78
  return;
79
- if (message.includes('Network Offline') || message.includes('Failed to reach')) {
79
+ if (message.includes('Network Offline') ||
80
+ message.includes('Failed to reach')) {
80
81
  this.warn(message, ...args);
81
82
  return;
82
83
  }
@@ -155,17 +156,21 @@ function formatSupabaseError(error, context = {}) {
155
156
  function formatFirestoreError(error, context = {}) {
156
157
  if (!error)
157
158
  return 'Unknown Firestore error';
158
- const collection = context.collection ? `"${context.collection}"` : 'collection';
159
+ const collection = context.collection
160
+ ? `"${context.collection}"`
161
+ : 'collection';
159
162
  const op = context.operation ? ` (${context.operation})` : '';
160
163
  const code = String(error.code || '').toLowerCase();
161
164
  const rawMsg = error.message || String(error);
162
- if (code.includes('permission-denied') || rawMsg.toLowerCase().includes('insufficient permissions')) {
165
+ if (code.includes('permission-denied') ||
166
+ rawMsg.toLowerCase().includes('insufficient permissions')) {
163
167
  return `🔒 Permission Denied on collection ${collection}${op}: Check your Firestore Security Rules.`;
164
168
  }
165
169
  if (code.includes('unauthenticated')) {
166
170
  return `🔑 Unauthenticated on collection ${collection}${op}: User must be signed into Firebase Auth.`;
167
171
  }
168
- if (code.includes('unavailable') || rawMsg.toLowerCase().includes('network')) {
172
+ if (code.includes('unavailable') ||
173
+ rawMsg.toLowerCase().includes('network')) {
169
174
  return `📡 Firestore Offline: Backend unreachable. Mutations preserved in local SQLite outbox.`;
170
175
  }
171
176
  return `❌ Firestore error on ${collection}${op}: ${rawMsg}`;
@@ -179,10 +184,12 @@ function formatConvexError(error, context = {}) {
179
184
  const table = context.table ? `"${context.table}"` : 'table';
180
185
  const op = context.operation ? ` (${context.operation})` : '';
181
186
  const rawMsg = error.message || String(error);
182
- if (rawMsg.toLowerCase().includes('unauthorized') || rawMsg.toLowerCase().includes('unauthenticated')) {
187
+ if (rawMsg.toLowerCase().includes('unauthorized') ||
188
+ rawMsg.toLowerCase().includes('unauthenticated')) {
183
189
  return `🔒 Convex Permission Denied on ${table}${op}: Request unauthorized.`;
184
190
  }
185
- if (rawMsg.toLowerCase().includes('network') || rawMsg.toLowerCase().includes('failed to fetch')) {
191
+ if (rawMsg.toLowerCase().includes('network') ||
192
+ rawMsg.toLowerCase().includes('failed to fetch')) {
186
193
  return `📡 Convex Offline: Server unreachable. Mutations preserved in local SQLite outbox.`;
187
194
  }
188
195
  return `❌ Convex error on ${table}${op}: ${rawMsg}`;