local-lite 1.0.2 → 1.0.3
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/dist/actions/manager.js +6 -2
- package/dist/actions/store.js +33 -19
- package/dist/adapters/local/expo-sqlite.js +4 -2
- package/dist/adapters/local/libsql.js +3 -1
- package/dist/adapters/local/op-sqlite.js +2 -1
- package/dist/adapters/network/index.js +10 -5
- package/dist/adapters/remote/convex.js +37 -10
- package/dist/adapters/remote/firestore.js +11 -4
- package/dist/adapters/remote/self-hosted.js +8 -4
- package/dist/adapters/remote/supabase.js +95 -29
- package/dist/auth/apple.js +8 -4
- package/dist/auth/github.js +15 -7
- package/dist/auth/google.js +7 -4
- package/dist/auth/identity.js +5 -1
- package/dist/auth/local.js +74 -21
- package/dist/auth/microsoft.js +22 -8
- package/dist/auth/session.js +45 -34
- package/dist/auth/unified.js +3 -2
- package/dist/backups/cloud-storage.js +10 -7
- package/dist/backups/encryption.js +4 -2
- package/dist/backups/onedrive.js +3 -3
- package/dist/backups/operations.js +4 -2
- package/dist/config/index.d.ts +1 -1
- package/dist/config/resolve-local.js +18 -6
- package/dist/config/resolve-remote.js +2 -1
- package/dist/core/client.d.ts +2 -2
- package/dist/core/client.js +64 -26
- package/dist/core/index.d.ts +1 -1
- package/dist/core/maintenance.js +5 -4
- package/dist/core/meta-store.js +3 -3
- package/dist/core/outbox-store.js +32 -25
- package/dist/core/query-builder.js +23 -10
- package/dist/core/query.js +19 -7
- package/dist/core/schema-manager.js +6 -2
- package/dist/core/sync-worker.js +38 -12
- package/dist/core/table-manager.js +8 -2
- package/dist/core/types.d.ts +1 -1
- package/dist/devtools/BenchmarkModal.d.ts +1 -1
- package/dist/devtools/BenchmarkModal.js +234 -54
- package/dist/devtools/SyncInspector.js +260 -37
- package/dist/email/index.js +46 -18
- package/dist/keys/generator.js +4 -1
- package/dist/keys/manager.js +22 -4
- package/dist/keys/signed-token.js +12 -4
- package/dist/keys/store.js +23 -16
- package/dist/kv/manager.js +5 -2
- package/dist/kv/store.js +13 -13
- package/dist/react/auth.js +12 -12
- package/dist/react/backups.js +1 -1
- package/dist/react/index.js +14 -9
- package/dist/react/runner.js +1 -1
- package/dist/react/status.js +6 -2
- package/dist/reactive/event-emitter.js +2 -2
- package/dist/scheduler/cron.js +3 -1
- package/dist/scheduler/store.js +37 -31
- package/dist/schema/generator.js +37 -34
- package/dist/search/manager.js +3 -1
- package/dist/search/store.js +17 -16
- package/dist/server/email.js +3 -2
- package/dist/server/index.js +4 -4
- package/dist/server/sync.js +11 -4
- package/dist/storage/driver.js +2 -1
- package/dist/storage/expo.js +5 -2
- package/dist/storage/manager.js +3 -1
- package/dist/storage/store.js +26 -25
- package/dist/utils/dynamic.js +4 -2
- package/dist/utils/logger.js +13 -6
- package/dist/utils/portability.js +21 -9
- package/package.json +1 -1
package/dist/auth/microsoft.js
CHANGED
|
@@ -8,7 +8,12 @@ const sha2_js_1 = require("@noble/hashes/sha2.js");
|
|
|
8
8
|
const utils_js_1 = require("@noble/hashes/utils.js");
|
|
9
9
|
const onedrive_js_1 = require("../backups/onedrive.js");
|
|
10
10
|
exports.MICROSOFT_GRAPH_ENDPOINT = 'https://graph.microsoft.com/v1.0';
|
|
11
|
-
exports.DEFAULT_MICROSOFT_AUTH_SCOPES = [
|
|
11
|
+
exports.DEFAULT_MICROSOFT_AUTH_SCOPES = [
|
|
12
|
+
'openid',
|
|
13
|
+
'profile',
|
|
14
|
+
'email',
|
|
15
|
+
'User.Read',
|
|
16
|
+
];
|
|
12
17
|
function secureRandomBytes(length) {
|
|
13
18
|
const crypto = typeof globalThis !== 'undefined' ? globalThis.crypto : undefined;
|
|
14
19
|
if (!crypto?.getRandomValues) {
|
|
@@ -28,9 +33,11 @@ function base64UrlEncode(bytes) {
|
|
|
28
33
|
const second = bytes[index + 1];
|
|
29
34
|
const third = bytes[index + 2];
|
|
30
35
|
result += alphabet[first >> 2];
|
|
31
|
-
result +=
|
|
36
|
+
result +=
|
|
37
|
+
alphabet[((first & 3) << 4) | (second === undefined ? 0 : second >> 4)];
|
|
32
38
|
if (second !== undefined) {
|
|
33
|
-
result +=
|
|
39
|
+
result +=
|
|
40
|
+
alphabet[((second & 15) << 2) | (third === undefined ? 0 : third >> 6)];
|
|
34
41
|
}
|
|
35
42
|
if (third !== undefined)
|
|
36
43
|
result += alphabet[third & 63];
|
|
@@ -43,7 +50,8 @@ function validateTokens(value) {
|
|
|
43
50
|
const tokens = value;
|
|
44
51
|
return (typeof tokens.accessToken === 'string' &&
|
|
45
52
|
typeof tokens.expiresAt === 'number' &&
|
|
46
|
-
(tokens.refreshToken === undefined ||
|
|
53
|
+
(tokens.refreshToken === undefined ||
|
|
54
|
+
typeof tokens.refreshToken === 'string') &&
|
|
47
55
|
(tokens.idToken === undefined || typeof tokens.idToken === 'string'));
|
|
48
56
|
}
|
|
49
57
|
function validateUser(value) {
|
|
@@ -79,7 +87,7 @@ function createMicrosoftAuthTokenStore(storage, prefix = 'local-lite-microsoft-a
|
|
|
79
87
|
const raw = await storage.getItem(tokensKey);
|
|
80
88
|
return validateTokens(raw) ? raw : null;
|
|
81
89
|
},
|
|
82
|
-
setTokens: tokens => storage.setItem(tokensKey, tokens),
|
|
90
|
+
setTokens: (tokens) => storage.setItem(tokensKey, tokens),
|
|
83
91
|
removeTokens: () => storage.removeItem(tokensKey),
|
|
84
92
|
getUser: async () => {
|
|
85
93
|
const raw = await storage.getItem(userKey);
|
|
@@ -197,7 +205,9 @@ class MicrosoftAuthClient {
|
|
|
197
205
|
});
|
|
198
206
|
const payload = (await response.json());
|
|
199
207
|
if (!response.ok) {
|
|
200
|
-
throw new Error(payload.error_description ||
|
|
208
|
+
throw new Error(payload.error_description ||
|
|
209
|
+
payload.error ||
|
|
210
|
+
`Microsoft OAuth token request failed (${response.status}).`);
|
|
201
211
|
}
|
|
202
212
|
if (!payload.access_token) {
|
|
203
213
|
throw new Error('Microsoft OAuth did not return an access token.');
|
|
@@ -276,7 +286,9 @@ class MicrosoftAuthClient {
|
|
|
276
286
|
});
|
|
277
287
|
const payload = (await response.json());
|
|
278
288
|
if (!response.ok) {
|
|
279
|
-
throw new Error(payload.error_description ||
|
|
289
|
+
throw new Error(payload.error_description ||
|
|
290
|
+
payload.error ||
|
|
291
|
+
`Microsoft OAuth token refresh failed (${response.status}).`);
|
|
280
292
|
}
|
|
281
293
|
if (!payload.access_token) {
|
|
282
294
|
throw new Error('Microsoft OAuth token refresh did not return an access token.');
|
|
@@ -300,7 +312,9 @@ class MicrosoftAuthClient {
|
|
|
300
312
|
throw new Error(`Failed to fetch Microsoft user profile (${res.status}).`);
|
|
301
313
|
}
|
|
302
314
|
const raw = (await res.json());
|
|
303
|
-
const email = (raw.mail || raw.userPrincipalName || '')
|
|
315
|
+
const email = (raw.mail || raw.userPrincipalName || '')
|
|
316
|
+
.trim()
|
|
317
|
+
.toLowerCase();
|
|
304
318
|
const sub = String(raw.id || raw.sub || 'microsoft_user');
|
|
305
319
|
const id = (0, identity_js_1.resolveUnifiedUserId)({ id: sub, email, emailVerified: true }, 'microsoft');
|
|
306
320
|
const name = raw.displayName || email || 'Microsoft User';
|
package/dist/auth/session.js
CHANGED
|
@@ -11,7 +11,8 @@ function quoteIdentifier(identifier) {
|
|
|
11
11
|
function mapSessionRow(r) {
|
|
12
12
|
let userData;
|
|
13
13
|
try {
|
|
14
|
-
userData =
|
|
14
|
+
userData =
|
|
15
|
+
typeof r.user_data === 'string' ? JSON.parse(r.user_data) : r.user_data;
|
|
15
16
|
}
|
|
16
17
|
catch {
|
|
17
18
|
userData = r.user_data;
|
|
@@ -19,7 +20,8 @@ function mapSessionRow(r) {
|
|
|
19
20
|
let metadata = null;
|
|
20
21
|
if (r.metadata) {
|
|
21
22
|
try {
|
|
22
|
-
metadata =
|
|
23
|
+
metadata =
|
|
24
|
+
typeof r.metadata === 'string' ? JSON.parse(r.metadata) : r.metadata;
|
|
23
25
|
}
|
|
24
26
|
catch {
|
|
25
27
|
metadata = null;
|
|
@@ -56,26 +58,27 @@ class SessionManager {
|
|
|
56
58
|
this.sqlTableName = quoteIdentifier(this.tableName);
|
|
57
59
|
this.sqlUserIndexName = quoteIdentifier(`idx_${this.tableName}_user`);
|
|
58
60
|
this.sqlActiveIndexName = quoteIdentifier(`idx_${this.tableName}_active`);
|
|
59
|
-
this.defaultOfflineDurationMs =
|
|
61
|
+
this.defaultOfflineDurationMs =
|
|
62
|
+
options.defaultOfflineDurationMs ?? exports.DEFAULT_OFFLINE_DURATION_MS;
|
|
60
63
|
this.network = options.network;
|
|
61
64
|
}
|
|
62
65
|
/**
|
|
63
66
|
* Ensures the _local_sessions schema exists.
|
|
64
67
|
*/
|
|
65
68
|
async initialize() {
|
|
66
|
-
await this.db.execute(`CREATE TABLE IF NOT EXISTS ${this.sqlTableName} (
|
|
67
|
-
id TEXT PRIMARY KEY,
|
|
68
|
-
user_id TEXT NOT NULL,
|
|
69
|
-
user_data TEXT NOT NULL,
|
|
70
|
-
token TEXT,
|
|
71
|
-
refresh_token TEXT,
|
|
72
|
-
provider TEXT,
|
|
73
|
-
created_at INTEGER NOT NULL,
|
|
74
|
-
last_active_at INTEGER NOT NULL,
|
|
75
|
-
expires_at INTEGER,
|
|
76
|
-
offline_access_until INTEGER,
|
|
77
|
-
metadata TEXT,
|
|
78
|
-
is_active INTEGER NOT NULL DEFAULT 1
|
|
69
|
+
await this.db.execute(`CREATE TABLE IF NOT EXISTS ${this.sqlTableName} (
|
|
70
|
+
id TEXT PRIMARY KEY,
|
|
71
|
+
user_id TEXT NOT NULL,
|
|
72
|
+
user_data TEXT NOT NULL,
|
|
73
|
+
token TEXT,
|
|
74
|
+
refresh_token TEXT,
|
|
75
|
+
provider TEXT,
|
|
76
|
+
created_at INTEGER NOT NULL,
|
|
77
|
+
last_active_at INTEGER NOT NULL,
|
|
78
|
+
expires_at INTEGER,
|
|
79
|
+
offline_access_until INTEGER,
|
|
80
|
+
metadata TEXT,
|
|
81
|
+
is_active INTEGER NOT NULL DEFAULT 1
|
|
79
82
|
);`);
|
|
80
83
|
await this.db.execute(`CREATE INDEX IF NOT EXISTS ${this.sqlUserIndexName} ON ${this.sqlTableName} (user_id);`);
|
|
81
84
|
await this.db.execute(`CREATE INDEX IF NOT EXISTS ${this.sqlActiveIndexName} ON ${this.sqlTableName} (is_active);`);
|
|
@@ -103,25 +106,27 @@ class SessionManager {
|
|
|
103
106
|
: now + offlineDuration;
|
|
104
107
|
const setActive = options.setActive !== false;
|
|
105
108
|
const userDataStr = JSON.stringify(options.user ?? {});
|
|
106
|
-
const metadataStr = options.metadata
|
|
109
|
+
const metadataStr = options.metadata
|
|
110
|
+
? JSON.stringify(options.metadata)
|
|
111
|
+
: null;
|
|
107
112
|
if (setActive) {
|
|
108
113
|
// Deactivate other sessions
|
|
109
114
|
await this.db.execute(`UPDATE ${this.sqlTableName} SET is_active = ?;`, [0]);
|
|
110
115
|
}
|
|
111
|
-
const sql = `
|
|
112
|
-
INSERT INTO ${this.sqlTableName} (id, user_id, user_data, token, refresh_token, provider, created_at, last_active_at, expires_at, offline_access_until, metadata, is_active)
|
|
113
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
114
|
-
ON CONFLICT(id) DO UPDATE SET
|
|
115
|
-
user_id = excluded.user_id,
|
|
116
|
-
user_data = excluded.user_data,
|
|
117
|
-
token = excluded.token,
|
|
118
|
-
refresh_token = excluded.refresh_token,
|
|
119
|
-
provider = excluded.provider,
|
|
120
|
-
last_active_at = excluded.last_active_at,
|
|
121
|
-
expires_at = excluded.expires_at,
|
|
122
|
-
offline_access_until = excluded.offline_access_until,
|
|
123
|
-
metadata = excluded.metadata,
|
|
124
|
-
is_active = excluded.is_active;
|
|
116
|
+
const sql = `
|
|
117
|
+
INSERT INTO ${this.sqlTableName} (id, user_id, user_data, token, refresh_token, provider, created_at, last_active_at, expires_at, offline_access_until, metadata, is_active)
|
|
118
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
119
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
120
|
+
user_id = excluded.user_id,
|
|
121
|
+
user_data = excluded.user_data,
|
|
122
|
+
token = excluded.token,
|
|
123
|
+
refresh_token = excluded.refresh_token,
|
|
124
|
+
provider = excluded.provider,
|
|
125
|
+
last_active_at = excluded.last_active_at,
|
|
126
|
+
expires_at = excluded.expires_at,
|
|
127
|
+
offline_access_until = excluded.offline_access_until,
|
|
128
|
+
metadata = excluded.metadata,
|
|
129
|
+
is_active = excluded.is_active;
|
|
125
130
|
`;
|
|
126
131
|
await this.db.execute(sql, [
|
|
127
132
|
id,
|
|
@@ -166,7 +171,8 @@ class SessionManager {
|
|
|
166
171
|
const session = mapSessionRow(rows[0]);
|
|
167
172
|
const now = Date.now();
|
|
168
173
|
// Check if offline access grace period has expired
|
|
169
|
-
if (session.offlineAccessUntil != null &&
|
|
174
|
+
if (session.offlineAccessUntil != null &&
|
|
175
|
+
now > session.offlineAccessUntil) {
|
|
170
176
|
await this.clearSession();
|
|
171
177
|
return null;
|
|
172
178
|
}
|
|
@@ -236,7 +242,9 @@ class SessionManager {
|
|
|
236
242
|
if (!session)
|
|
237
243
|
return;
|
|
238
244
|
const token = tokens.token !== undefined ? tokens.token : session.token;
|
|
239
|
-
const refreshToken = tokens.refreshToken !== undefined
|
|
245
|
+
const refreshToken = tokens.refreshToken !== undefined
|
|
246
|
+
? tokens.refreshToken
|
|
247
|
+
: session.refreshToken;
|
|
240
248
|
const expiresAt = tokens.expiresAt !== undefined ? tokens.expiresAt : session.expiresAt;
|
|
241
249
|
const now = Date.now();
|
|
242
250
|
await this.db.execute(`UPDATE ${this.sqlTableName} SET token = ?, refresh_token = ?, expires_at = ?, last_active_at = ? WHERE id = ?;`, [token, refreshToken, expiresAt, now, session.id]);
|
|
@@ -279,7 +287,10 @@ class SessionManager {
|
|
|
279
287
|
await this.db.execute(`UPDATE ${this.sqlTableName} SET is_active = ?, last_active_at = ? WHERE id = ?;`, [1, Date.now(), targetSession.id]);
|
|
280
288
|
targetSession.isActive = true;
|
|
281
289
|
targetSession.lastActiveAt = Date.now();
|
|
282
|
-
this.events?.emit(this.tableName, {
|
|
290
|
+
this.events?.emit(this.tableName, {
|
|
291
|
+
operation: 'SWITCH_SESSION',
|
|
292
|
+
session: targetSession,
|
|
293
|
+
});
|
|
283
294
|
return targetSession;
|
|
284
295
|
}
|
|
285
296
|
}
|
package/dist/auth/unified.js
CHANGED
|
@@ -25,12 +25,13 @@ class UnifiedAuthManager {
|
|
|
25
25
|
this.local = config.local;
|
|
26
26
|
this.sessionManager = config.sessionManager;
|
|
27
27
|
this.unifyByEmail = config.unifyByEmail !== false;
|
|
28
|
-
this.emailNamespace =
|
|
28
|
+
this.emailNamespace =
|
|
29
|
+
config.emailNamespace || identity_js_1.DEFAULT_UNIFIED_EMAIL_NAMESPACE;
|
|
29
30
|
this.bindProviderListeners();
|
|
30
31
|
}
|
|
31
32
|
bindProviderListeners() {
|
|
32
33
|
if (this.google) {
|
|
33
|
-
this.unsubscribers.push(this.google.onAuthStateChange(user => {
|
|
34
|
+
this.unsubscribers.push(this.google.onAuthStateChange((user) => {
|
|
34
35
|
if (!user)
|
|
35
36
|
return;
|
|
36
37
|
const unified = (0, identity_js_1.createUnifiedAuthUser)(user, 'google', {
|
|
@@ -27,9 +27,11 @@ function base64UrlEncode(bytes) {
|
|
|
27
27
|
const second = bytes[index + 1];
|
|
28
28
|
const third = bytes[index + 2];
|
|
29
29
|
result += alphabet[first >> 2];
|
|
30
|
-
result +=
|
|
30
|
+
result +=
|
|
31
|
+
alphabet[((first & 3) << 4) | (second === undefined ? 0 : second >> 4)];
|
|
31
32
|
if (second !== undefined) {
|
|
32
|
-
result +=
|
|
33
|
+
result +=
|
|
34
|
+
alphabet[((second & 15) << 2) | (third === undefined ? 0 : third >> 6)];
|
|
33
35
|
}
|
|
34
36
|
if (third !== undefined)
|
|
35
37
|
result += alphabet[third & 63];
|
|
@@ -42,7 +44,8 @@ function validateGoogleTokens(value) {
|
|
|
42
44
|
const tokens = value;
|
|
43
45
|
return (typeof tokens.accessToken === 'string' &&
|
|
44
46
|
typeof tokens.expiresAt === 'number' &&
|
|
45
|
-
(tokens.refreshToken === undefined ||
|
|
47
|
+
(tokens.refreshToken === undefined ||
|
|
48
|
+
typeof tokens.refreshToken === 'string'));
|
|
46
49
|
}
|
|
47
50
|
function createInMemoryGoogleDriveTokenStore() {
|
|
48
51
|
let stored = null;
|
|
@@ -62,7 +65,7 @@ function createGoogleDriveTokenStore(storage, key = 'local-lite-google-drive-bac
|
|
|
62
65
|
const tokens = await storage.getItem(key);
|
|
63
66
|
return validateGoogleTokens(tokens) ? tokens : null;
|
|
64
67
|
},
|
|
65
|
-
set: tokens => storage.setItem(key, tokens),
|
|
68
|
+
set: (tokens) => storage.setItem(key, tokens),
|
|
66
69
|
remove: () => storage.removeItem(key),
|
|
67
70
|
};
|
|
68
71
|
}
|
|
@@ -198,8 +201,8 @@ class GoogleDriveBackupStorage {
|
|
|
198
201
|
throw await parseApiError(response);
|
|
199
202
|
const result = (await response.json());
|
|
200
203
|
return (result.files ?? [])
|
|
201
|
-
.filter(file => file.name.endsWith('.db'))
|
|
202
|
-
.map(file => ({
|
|
204
|
+
.filter((file) => file.name.endsWith('.db'))
|
|
205
|
+
.map((file) => ({
|
|
203
206
|
id: file.id,
|
|
204
207
|
name: file.name,
|
|
205
208
|
modifiedAt: file.modifiedTime,
|
|
@@ -221,7 +224,7 @@ class GoogleDriveBackupClient {
|
|
|
221
224
|
if (options.authClient) {
|
|
222
225
|
this.authClient = options.authClient;
|
|
223
226
|
this.storage = new GoogleDriveBackupStorage(() => this.authClient.getValidAccessToken(), this.fetcher);
|
|
224
|
-
this.authClient.onAuthStateChange(user => {
|
|
227
|
+
this.authClient.onAuthStateChange((user) => {
|
|
225
228
|
this.notify(Boolean(user));
|
|
226
229
|
});
|
|
227
230
|
}
|
|
@@ -21,7 +21,8 @@ function getRandomBytes(length) {
|
|
|
21
21
|
}
|
|
22
22
|
const ITERATIONS_LENGTH = 4;
|
|
23
23
|
function isEncryptedBackup(data) {
|
|
24
|
-
if (data.length <
|
|
24
|
+
if (data.length <
|
|
25
|
+
MAGIC_HEADER.length + ITERATIONS_LENGTH + SALT_LENGTH + IV_LENGTH + 16) {
|
|
25
26
|
return false;
|
|
26
27
|
}
|
|
27
28
|
for (let i = 0; i < MAGIC_HEADER.length; i++) {
|
|
@@ -69,7 +70,8 @@ async function decryptBackupData(encryptedData, passphrase, options = {}) {
|
|
|
69
70
|
}
|
|
70
71
|
const view = new DataView(encryptedData.buffer, encryptedData.byteOffset, encryptedData.byteLength);
|
|
71
72
|
const storedIterations = view.getUint32(MAGIC_HEADER.length, false);
|
|
72
|
-
const iterations = options.iterations ??
|
|
73
|
+
const iterations = options.iterations ??
|
|
74
|
+
(storedIterations > 0 ? storedIterations : DEFAULT_ITERATIONS);
|
|
73
75
|
const saltOffset = MAGIC_HEADER.length + ITERATIONS_LENGTH;
|
|
74
76
|
const ivOffset = saltOffset + SALT_LENGTH;
|
|
75
77
|
const ciphertextOffset = ivOffset + IV_LENGTH;
|
package/dist/backups/onedrive.js
CHANGED
|
@@ -78,8 +78,8 @@ class OneDriveBackupStorage {
|
|
|
78
78
|
}
|
|
79
79
|
const result = (await response.json());
|
|
80
80
|
return (result.value ?? [])
|
|
81
|
-
.filter(item => item.name.endsWith('.db'))
|
|
82
|
-
.map(item => ({
|
|
81
|
+
.filter((item) => item.name.endsWith('.db'))
|
|
82
|
+
.map((item) => ({
|
|
83
83
|
id: item.id,
|
|
84
84
|
name: item.name,
|
|
85
85
|
size: item.size,
|
|
@@ -117,7 +117,7 @@ class OneDriveBackupClient {
|
|
|
117
117
|
});
|
|
118
118
|
this.storage = new OneDriveBackupStorage(() => this.authClient.getValidAccessToken(), msOptions.fetch ?? fetch);
|
|
119
119
|
}
|
|
120
|
-
this.authClient.onAuthStateChange(user => {
|
|
120
|
+
this.authClient.onAuthStateChange((user) => {
|
|
121
121
|
this.notify(Boolean(user));
|
|
122
122
|
});
|
|
123
123
|
}
|
|
@@ -10,7 +10,8 @@ function resolveBackupDatabase(target) {
|
|
|
10
10
|
if (!target) {
|
|
11
11
|
throw new Error('A valid database or LocalFirstClient is required for backup.');
|
|
12
12
|
}
|
|
13
|
-
if (typeof target.exportDatabase === 'function' &&
|
|
13
|
+
if (typeof target.exportDatabase === 'function' &&
|
|
14
|
+
typeof target.importDatabase === 'function') {
|
|
14
15
|
return target;
|
|
15
16
|
}
|
|
16
17
|
if (target.db &&
|
|
@@ -27,7 +28,8 @@ function validateFileName(fileName) {
|
|
|
27
28
|
}
|
|
28
29
|
async function createDatabaseBackup(database, storage, options = {}) {
|
|
29
30
|
const resolved = resolveBackupDatabase(database);
|
|
30
|
-
const fileName = options.fileName ??
|
|
31
|
+
const fileName = options.fileName ??
|
|
32
|
+
`local-lite-${new Date().toISOString().replace(/[:.]/g, '-')}.db`;
|
|
31
33
|
validateFileName(fileName);
|
|
32
34
|
const databaseBytes = await resolved.exportDatabase();
|
|
33
35
|
if (databaseBytes.length === 0) {
|
package/dist/config/index.d.ts
CHANGED
|
@@ -14,7 +14,7 @@ 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
16
|
export { SelfHostedRemoteAdapter } from '../adapters/remote/self-hosted.js';
|
|
17
|
-
export { MemoryDemoRemoteAdapter, NoopRemoteAdapter } from '../adapters/remote/demo.js';
|
|
17
|
+
export { MemoryDemoRemoteAdapter, NoopRemoteAdapter, } from '../adapters/remote/demo.js';
|
|
18
18
|
export type { RemoteDBAdapter } from '../adapters/remote/index.js';
|
|
19
19
|
/**
|
|
20
20
|
* Type-safe configuration helper function (similar to defineConfig in Vite/Tailwind).
|
|
@@ -19,15 +19,21 @@ async function resolveLocalAdapter(config) {
|
|
|
19
19
|
rawDb = await rawDb();
|
|
20
20
|
}
|
|
21
21
|
// 1. @libsql/client (Turso / LibSQL) instance
|
|
22
|
-
if (rawDb &&
|
|
22
|
+
if (rawDb &&
|
|
23
|
+
typeof rawDb.batch === 'function' &&
|
|
24
|
+
typeof rawDb.execute === 'function') {
|
|
23
25
|
return new libsql_js_1.LibSQLAdapter(rawDb);
|
|
24
26
|
}
|
|
25
27
|
// 2. sql.js Database instance
|
|
26
|
-
if (rawDb &&
|
|
28
|
+
if (rawDb &&
|
|
29
|
+
typeof rawDb.export === 'function' &&
|
|
30
|
+
typeof rawDb.exec === 'function') {
|
|
27
31
|
return new sql_js_js_1.SqlJsAdapter(rawDb);
|
|
28
32
|
}
|
|
29
33
|
// 3. Custom object already implementing LocalDBAdapter
|
|
30
|
-
if (rawDb &&
|
|
34
|
+
if (rawDb &&
|
|
35
|
+
typeof rawDb.execute === 'function' &&
|
|
36
|
+
typeof rawDb.transaction === 'function') {
|
|
31
37
|
return rawDb;
|
|
32
38
|
}
|
|
33
39
|
// 4. Expo SQLite database instance (openDatabaseAsync)
|
|
@@ -39,11 +45,15 @@ async function resolveLocalAdapter(config) {
|
|
|
39
45
|
return new op_sqlite_js_1.OpSQLiteAdapter(rawDb);
|
|
40
46
|
}
|
|
41
47
|
// 6. better-sqlite3 database instance
|
|
42
|
-
if (rawDb &&
|
|
48
|
+
if (rawDb &&
|
|
49
|
+
typeof rawDb.prepare === 'function' &&
|
|
50
|
+
typeof rawDb.pragma === 'function') {
|
|
43
51
|
return new better_sqlite3_js_1.BetterSQLite3Adapter(rawDb);
|
|
44
52
|
}
|
|
45
53
|
// 7. Node.js 22+ built-in node:sqlite (DatabaseSync) instance
|
|
46
|
-
if (rawDb &&
|
|
54
|
+
if (rawDb &&
|
|
55
|
+
typeof rawDb.prepare === 'function' &&
|
|
56
|
+
typeof rawDb.exec === 'function') {
|
|
47
57
|
return new node_sqlite_js_1.NodeSQLiteAdapter(rawDb);
|
|
48
58
|
}
|
|
49
59
|
// 8. Fallback for prepare-based SQLite instances
|
|
@@ -52,7 +62,9 @@ async function resolveLocalAdapter(config) {
|
|
|
52
62
|
}
|
|
53
63
|
// 9. Auto-open by name using expo-sqlite if available
|
|
54
64
|
if (typeof rawDb === 'string' || config.databaseName) {
|
|
55
|
-
const dbName = typeof rawDb === 'string'
|
|
65
|
+
const dbName = typeof rawDb === 'string'
|
|
66
|
+
? rawDb
|
|
67
|
+
: (config.databaseName ?? 'local_lite.db');
|
|
56
68
|
let expoSqlite = (0, dynamic_js_1.safeDynamicRequire)(EXPO_SQLITE_PKG);
|
|
57
69
|
if (!expoSqlite) {
|
|
58
70
|
expoSqlite = await (0, dynamic_js_1.safeDynamicImport)(EXPO_SQLITE_PKG);
|
|
@@ -69,7 +69,8 @@ async function resolveRemoteAdapter(config) {
|
|
|
69
69
|
// 5. Supabase with URL + anonKey (lazy dynamic import)
|
|
70
70
|
if (config.supabase?.url && config.supabase?.anonKey) {
|
|
71
71
|
let supabaseModule = (0, dynamic_js_1.safeDynamicRequire)(SUPABASE_PKG);
|
|
72
|
-
if (!supabaseModule &&
|
|
72
|
+
if (!supabaseModule &&
|
|
73
|
+
typeof globalThis?.supabase?.createClient === 'function') {
|
|
73
74
|
supabaseModule = globalThis.supabase;
|
|
74
75
|
}
|
|
75
76
|
if (!supabaseModule) {
|
package/dist/core/client.d.ts
CHANGED
|
@@ -398,8 +398,8 @@ export declare class LocalFirstClient {
|
|
|
398
398
|
includeInternal?: boolean;
|
|
399
399
|
}): Promise<void>;
|
|
400
400
|
/**
|
|
401
|
-
|
|
402
|
-
|
|
401
|
+
* Checks if a table name belongs to internal system, FTS, or engine tables.
|
|
402
|
+
*/
|
|
403
403
|
isInternalTable(tableName: string): boolean;
|
|
404
404
|
/**
|
|
405
405
|
* Returns list of database tables.
|
package/dist/core/client.js
CHANGED
|
@@ -35,15 +35,22 @@ function normalizeSchemaMigrations(migrations) {
|
|
|
35
35
|
const ordered = [...migrations].sort((a, b) => a.version - b.version);
|
|
36
36
|
return ordered.map((migration, index) => {
|
|
37
37
|
const expectedVersion = index + 1;
|
|
38
|
-
if (!migration ||
|
|
38
|
+
if (!migration ||
|
|
39
|
+
!Number.isSafeInteger(migration.version) ||
|
|
40
|
+
migration.version !== expectedVersion) {
|
|
39
41
|
throw new TypeError(`schemaMigrations must use consecutive integer versions starting at 1; expected version ${expectedVersion}.`);
|
|
40
42
|
}
|
|
41
|
-
const statements = Array.isArray(migration.up)
|
|
43
|
+
const statements = Array.isArray(migration.up)
|
|
44
|
+
? migration.up
|
|
45
|
+
: [migration.up];
|
|
42
46
|
if (statements.length === 0 ||
|
|
43
47
|
statements.some((statement) => typeof statement !== 'string' || statement.trim().length === 0)) {
|
|
44
48
|
throw new TypeError(`schemaMigrations version ${migration.version} must contain non-empty SQL.`);
|
|
45
49
|
}
|
|
46
|
-
return {
|
|
50
|
+
return {
|
|
51
|
+
version: migration.version,
|
|
52
|
+
up: statements.map((statement) => statement.trim()),
|
|
53
|
+
};
|
|
47
54
|
});
|
|
48
55
|
}
|
|
49
56
|
function hasFunctionFilter(value) {
|
|
@@ -86,7 +93,9 @@ async function executeFindByIds(db, tableName, ids, primaryKey, hydrateRow, incl
|
|
|
86
93
|
if (!rows || rows.length === 0)
|
|
87
94
|
return [];
|
|
88
95
|
const hydrated = rows.map((r) => hydrateRow(tableName, r));
|
|
89
|
-
return !includeDeleted
|
|
96
|
+
return !includeDeleted
|
|
97
|
+
? hydrated.filter((r) => !(0, query_js_1.isDeletedRecord)(r))
|
|
98
|
+
: hydrated;
|
|
90
99
|
}
|
|
91
100
|
catch (err) {
|
|
92
101
|
const msg = String(err?.message || err || '');
|
|
@@ -202,7 +211,8 @@ class TransactionalClient {
|
|
|
202
211
|
return executeFindByIds(this.tx, tableName, ids, this.parent.getPrimaryKey(), (t, r) => this.parent.hydrateRow(t, r), options?.includeDeleted);
|
|
203
212
|
}
|
|
204
213
|
async findMany(tableName, options) {
|
|
205
|
-
if (!this.parent.db.supportsSqlPushdown ||
|
|
214
|
+
if (!this.parent.db.supportsSqlPushdown ||
|
|
215
|
+
shouldUseClientSideQuery(options)) {
|
|
206
216
|
const rows = await this.from(tableName).execute();
|
|
207
217
|
return (0, query_js_1.applyQueryOptions)(rows, options);
|
|
208
218
|
}
|
|
@@ -265,7 +275,9 @@ class LocalFirstClient {
|
|
|
265
275
|
this.tables = config.tables ?? [];
|
|
266
276
|
this.relationships = config.relationships ?? [];
|
|
267
277
|
for (const relationship of this.relationships) {
|
|
268
|
-
if (!relationship.table ||
|
|
278
|
+
if (!relationship.table ||
|
|
279
|
+
!relationship.foreignKey ||
|
|
280
|
+
!relationship.references) {
|
|
269
281
|
throw new TypeError('Each relationship requires table, foreignKey, and references.');
|
|
270
282
|
}
|
|
271
283
|
if (this.tables.length > 0) {
|
|
@@ -298,7 +310,8 @@ class LocalFirstClient {
|
|
|
298
310
|
? null
|
|
299
311
|
: typeof touch === 'string'
|
|
300
312
|
? touch
|
|
301
|
-
: this.remote?.updatedAtColumn ||
|
|
313
|
+
: this.remote?.updatedAtColumn ||
|
|
314
|
+
'updated_at';
|
|
302
315
|
this.schemaManager = new schema_manager_js_1.SchemaManager();
|
|
303
316
|
this.maintenance = new maintenance_js_1.DatabaseMaintenance(this.db, () => [
|
|
304
317
|
...this.tables,
|
|
@@ -319,8 +332,10 @@ class LocalFirstClient {
|
|
|
319
332
|
let storageUploader = config.storage?.uploader;
|
|
320
333
|
if (!storageUploader && config.storage) {
|
|
321
334
|
if (typeof this.remote?.createStorageUploader === 'function' &&
|
|
322
|
-
|
|
323
|
-
|
|
335
|
+
config.storage.autoRemote !== false &&
|
|
336
|
+
(config.storage.autoRemote ||
|
|
337
|
+
config.storage.bucket ||
|
|
338
|
+
config.storage.uploadMutation)) {
|
|
324
339
|
try {
|
|
325
340
|
storageUploader = this.remote.createStorageUploader(config.storage);
|
|
326
341
|
}
|
|
@@ -394,7 +409,8 @@ class LocalFirstClient {
|
|
|
394
409
|
return [];
|
|
395
410
|
},
|
|
396
411
|
setEnabled: async (jobId, enabled) => {
|
|
397
|
-
if (this.remote &&
|
|
412
|
+
if (this.remote &&
|
|
413
|
+
typeof this.remote.setAutomationEnabled === 'function') {
|
|
398
414
|
return this.remote.setAutomationEnabled(jobId, enabled);
|
|
399
415
|
}
|
|
400
416
|
throw new Error('Remote adapter does not support remote automations.');
|
|
@@ -444,7 +460,8 @@ class LocalFirstClient {
|
|
|
444
460
|
for (const col of cols) {
|
|
445
461
|
if (typeof copy[col] === 'string') {
|
|
446
462
|
const val = copy[col].trim();
|
|
447
|
-
if ((val.startsWith('{') && val.endsWith('}')) ||
|
|
463
|
+
if ((val.startsWith('{') && val.endsWith('}')) ||
|
|
464
|
+
(val.startsWith('[') && val.endsWith(']'))) {
|
|
448
465
|
try {
|
|
449
466
|
copy[col] = JSON.parse(val);
|
|
450
467
|
}
|
|
@@ -522,10 +539,24 @@ class LocalFirstClient {
|
|
|
522
539
|
}
|
|
523
540
|
}
|
|
524
541
|
const outboxId = (0, uuid_js_1.generateUUID)();
|
|
525
|
-
await outbox_store_js_1.OutboxStore.insertRecord(tx, {
|
|
542
|
+
await outbox_store_js_1.OutboxStore.insertRecord(tx, {
|
|
543
|
+
id: outboxId,
|
|
544
|
+
tableName,
|
|
545
|
+
rowId,
|
|
546
|
+
operation,
|
|
547
|
+
payload,
|
|
548
|
+
timestamp,
|
|
549
|
+
});
|
|
526
550
|
pendingOutboxMap?.set(pendingKey, {
|
|
527
|
-
id: outboxId,
|
|
528
|
-
|
|
551
|
+
id: outboxId,
|
|
552
|
+
tableName,
|
|
553
|
+
rowId,
|
|
554
|
+
operation,
|
|
555
|
+
payload,
|
|
556
|
+
timestamp,
|
|
557
|
+
status: 'PENDING',
|
|
558
|
+
retryCount: 0,
|
|
559
|
+
lastError: null,
|
|
529
560
|
});
|
|
530
561
|
return outboxId;
|
|
531
562
|
}
|
|
@@ -576,9 +607,9 @@ class LocalFirstClient {
|
|
|
576
607
|
if (this.schemaMigrations.length === 0)
|
|
577
608
|
return;
|
|
578
609
|
await this.db.transaction(async (tx) => {
|
|
579
|
-
await tx.execute(`CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
580
|
-
version INTEGER PRIMARY KEY,
|
|
581
|
-
applied_at INTEGER NOT NULL
|
|
610
|
+
await tx.execute(`CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
611
|
+
version INTEGER PRIMARY KEY,
|
|
612
|
+
applied_at INTEGER NOT NULL
|
|
582
613
|
);`);
|
|
583
614
|
const rows = await tx.execute('SELECT version FROM schema_migrations ORDER BY version ASC');
|
|
584
615
|
const appliedVersions = rows.map((row) => Number(row.version));
|
|
@@ -617,7 +648,10 @@ class LocalFirstClient {
|
|
|
617
648
|
this.events.emit(item.tableName, item.event);
|
|
618
649
|
}
|
|
619
650
|
if (queuedOutboxIds.length > 0) {
|
|
620
|
-
this.events.emit('sync_outbox', {
|
|
651
|
+
this.events.emit('sync_outbox', {
|
|
652
|
+
operation: 'INSERT',
|
|
653
|
+
rowId: 'batch',
|
|
654
|
+
});
|
|
621
655
|
this.syncWorker.schedulePush(20);
|
|
622
656
|
}
|
|
623
657
|
}
|
|
@@ -951,7 +985,8 @@ class LocalFirstClient {
|
|
|
951
985
|
const row = rows[0] || {};
|
|
952
986
|
const result = {};
|
|
953
987
|
if (spec.count) {
|
|
954
|
-
result.count =
|
|
988
|
+
result.count =
|
|
989
|
+
typeof row._count === 'number' ? row._count : Number(row._count) || 0;
|
|
955
990
|
}
|
|
956
991
|
if (spec.sum) {
|
|
957
992
|
result.sum = {};
|
|
@@ -964,7 +999,8 @@ class LocalFirstClient {
|
|
|
964
999
|
result.avg = {};
|
|
965
1000
|
for (const col of spec.avg) {
|
|
966
1001
|
const val = row[`avg_${col}`];
|
|
967
|
-
result.avg[col] =
|
|
1002
|
+
result.avg[col] =
|
|
1003
|
+
val === null || val === undefined ? null : Number(val) || 0;
|
|
968
1004
|
}
|
|
969
1005
|
}
|
|
970
1006
|
if (spec.min) {
|
|
@@ -1195,8 +1231,8 @@ class LocalFirstClient {
|
|
|
1195
1231
|
this.events.emit('reset', { dropTables: options.dropTables ?? false });
|
|
1196
1232
|
}
|
|
1197
1233
|
/**
|
|
1198
|
-
|
|
1199
|
-
|
|
1234
|
+
* Checks if a table name belongs to internal system, FTS, or engine tables.
|
|
1235
|
+
*/
|
|
1200
1236
|
isInternalTable(tableName) {
|
|
1201
1237
|
return (0, sql_js_1.isInternalTable)(tableName);
|
|
1202
1238
|
}
|
|
@@ -1211,7 +1247,7 @@ class LocalFirstClient {
|
|
|
1211
1247
|
if (includeInternal) {
|
|
1212
1248
|
return allTables;
|
|
1213
1249
|
}
|
|
1214
|
-
return allTables.filter(name => !(0, sql_js_1.isInternalTable)(name));
|
|
1250
|
+
return allTables.filter((name) => !(0, sql_js_1.isInternalTable)(name));
|
|
1215
1251
|
}
|
|
1216
1252
|
async getAllTableNames(options = {}) {
|
|
1217
1253
|
const includeInternal = options.includeInternal ?? false;
|
|
@@ -1236,7 +1272,7 @@ class LocalFirstClient {
|
|
|
1236
1272
|
// Non-SQLite database adapter, fallback to configured tables
|
|
1237
1273
|
}
|
|
1238
1274
|
if (!includeInternal) {
|
|
1239
|
-
return Array.from(list).filter(name => !(0, sql_js_1.isInternalTable)(name));
|
|
1275
|
+
return Array.from(list).filter((name) => !(0, sql_js_1.isInternalTable)(name));
|
|
1240
1276
|
}
|
|
1241
1277
|
return Array.from(list);
|
|
1242
1278
|
}
|
|
@@ -1335,9 +1371,11 @@ class LocalFirstClient {
|
|
|
1335
1371
|
const cols = Object.keys(row);
|
|
1336
1372
|
const safeCols = cols.map(sql_js_1.escapeIdentifier).join(', ');
|
|
1337
1373
|
const placeholders = cols.map(() => '?').join(', ');
|
|
1338
|
-
const values = cols.map(c => {
|
|
1374
|
+
const values = cols.map((c) => {
|
|
1339
1375
|
const val = row[c];
|
|
1340
|
-
return val !== null && typeof val === 'object'
|
|
1376
|
+
return val !== null && typeof val === 'object'
|
|
1377
|
+
? JSON.stringify(val)
|
|
1378
|
+
: val;
|
|
1341
1379
|
});
|
|
1342
1380
|
await tx.execute(`INSERT INTO ${safeTable} (${safeCols}) VALUES (${placeholders})`, values);
|
|
1343
1381
|
}
|
package/dist/core/index.d.ts
CHANGED
|
@@ -11,6 +11,6 @@ export * from './query-builder.js';
|
|
|
11
11
|
export * from './maintenance.js';
|
|
12
12
|
export * from '../reactive/event-emitter.js';
|
|
13
13
|
export * from '../adapters/network/index.js';
|
|
14
|
-
export type { LocalDBAdapter, LocalTransaction } from '../adapters/local/index.js';
|
|
14
|
+
export type { LocalDBAdapter, LocalTransaction, } from '../adapters/local/index.js';
|
|
15
15
|
export type { RemoteDBAdapter } from '../adapters/remote/index.js';
|
|
16
16
|
export * from '../utils/logger.js';
|