local-lite 2.0.7 → 3.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 +0 -30
- package/dist/adapters/local/index.d.ts +1 -0
- package/dist/adapters/local/index.js +1 -0
- package/dist/adapters/local/sqlite-wasm.d.ts +25 -0
- package/dist/adapters/local/sqlite-wasm.js +55 -0
- package/dist/adapters/remote/convex.d.ts +1 -1
- package/dist/adapters/remote/convex.js +25 -3
- package/dist/adapters/remote/demo.d.ts +3 -3
- package/dist/adapters/remote/demo.js +11 -3
- package/dist/adapters/remote/firestore.d.ts +1 -1
- package/dist/adapters/remote/firestore.js +57 -91
- package/dist/adapters/remote/index.d.ts +2 -1
- package/dist/adapters/remote/index.js +1 -0
- package/dist/adapters/remote/postgres.d.ts +37 -0
- package/dist/adapters/remote/postgres.js +119 -0
- package/dist/adapters/remote/self-hosted.d.ts +12 -0
- package/dist/adapters/remote/self-hosted.js +55 -4
- package/dist/adapters/remote/supabase.d.ts +1 -1
- package/dist/adapters/remote/supabase.js +22 -5
- package/dist/auth/apple.js +0 -6
- package/dist/auth/github.js +0 -3
- package/dist/auth/google.js +0 -3
- package/dist/auth/identity.d.ts +0 -5
- package/dist/auth/identity.js +0 -3
- package/dist/auth/microsoft.js +0 -3
- package/dist/auth/unified.d.ts +5 -5
- package/dist/auth/unified.js +1 -1
- package/dist/config/index.d.ts +0 -12
- package/dist/config/index.js +3 -26
- package/dist/config/types.d.ts +3 -2
- package/dist/core/audit.d.ts +52 -0
- package/dist/core/audit.js +153 -0
- package/dist/core/client.d.ts +4 -0
- package/dist/core/client.js +7 -0
- package/dist/core/conflict.d.ts +24 -0
- package/dist/core/conflict.js +77 -0
- package/dist/core/field-encryption.d.ts +25 -0
- package/dist/core/field-encryption.js +128 -0
- package/dist/core/index.d.ts +2 -0
- package/dist/core/index.js +2 -0
- package/dist/core/query-builder.d.ts +51 -0
- package/dist/core/query-builder.js +278 -35
- package/dist/core/query.js +6 -1
- package/dist/core/types.d.ts +2 -1
- package/dist/devtools/BenchmarkModal.js +285 -1
- package/dist/email/index.d.ts +1 -1
- package/dist/email/index.js +2 -2
- package/dist/index.d.ts +2 -27
- package/dist/index.js +2 -27
- package/dist/presence/index.d.ts +45 -0
- package/dist/presence/index.js +142 -0
- package/dist/reactive/event-emitter.d.ts +10 -1
- package/dist/reactive/event-emitter.js +44 -1
- package/dist/reactive/live-query.d.ts +18 -0
- package/dist/reactive/live-query.js +71 -0
- package/dist/schema/index.d.ts +1 -0
- package/dist/schema/index.js +1 -0
- package/dist/schema/typed.d.ts +38 -0
- package/dist/schema/typed.js +33 -0
- package/dist/server/dashboard.d.ts +2 -0
- package/dist/server/dashboard.js +182 -2
- package/dist/solid/index.d.ts +24 -0
- package/dist/solid/index.js +35 -0
- package/dist/storage/firebase.d.ts +3 -3
- package/dist/storage/firebase.js +40 -94
- package/dist/svelte/index.d.ts +15 -0
- package/dist/svelte/index.js +27 -0
- package/dist/testing/index.d.ts +22 -0
- package/dist/testing/index.js +74 -0
- package/dist/vue/index.d.ts +27 -0
- package/dist/vue/index.js +37 -0
- package/package.json +46 -9
- package/dist/kv/index.d.ts +0 -3
- package/dist/kv/index.js +0 -19
- package/dist/kv/manager.d.ts +0 -52
- package/dist/kv/manager.js +0 -167
- package/dist/kv/store.d.ts +0 -13
- package/dist/kv/store.js +0 -85
- package/dist/kv/types.d.ts +0 -27
- package/dist/kv/types.js +0 -2
- package/dist/react/kv.d.ts +0 -9
- package/dist/react/kv.js +0 -53
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { LocalFirstClient } from '../core/client.js';
|
|
2
|
+
import type { QueryOptions, SyncStatusEvent } from '../core/types.js';
|
|
3
|
+
export interface LiveQueryState<T> {
|
|
4
|
+
data: T[];
|
|
5
|
+
loading: boolean;
|
|
6
|
+
error: Error | null;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Framework-agnostic live query subscription helper shared by Svelte, Vue, and Solid bindings.
|
|
10
|
+
*/
|
|
11
|
+
export declare function subscribeLiveQuery<T = any>(client: LocalFirstClient, tableName: string, options: QueryOptions | undefined, onUpdate: (state: LiveQueryState<T>) => void): {
|
|
12
|
+
refresh: () => Promise<void>;
|
|
13
|
+
dispose: () => void;
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Framework-agnostic sync status subscription helper shared by Svelte, Vue, and Solid bindings.
|
|
17
|
+
*/
|
|
18
|
+
export declare function subscribeSyncStatus(client: LocalFirstClient, onUpdate: (status: SyncStatusEvent) => void): () => void;
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.subscribeLiveQuery = subscribeLiveQuery;
|
|
4
|
+
exports.subscribeSyncStatus = subscribeSyncStatus;
|
|
5
|
+
/**
|
|
6
|
+
* Framework-agnostic live query subscription helper shared by Svelte, Vue, and Solid bindings.
|
|
7
|
+
*/
|
|
8
|
+
function subscribeLiveQuery(client, tableName, options, onUpdate) {
|
|
9
|
+
let active = true;
|
|
10
|
+
let current = { data: [], loading: true, error: null };
|
|
11
|
+
const refresh = async () => {
|
|
12
|
+
try {
|
|
13
|
+
const rows = await client
|
|
14
|
+
.from(tableName)
|
|
15
|
+
.applyOptions(options)
|
|
16
|
+
.execute();
|
|
17
|
+
if (!active)
|
|
18
|
+
return;
|
|
19
|
+
current = { data: rows, loading: false, error: null };
|
|
20
|
+
onUpdate(current);
|
|
21
|
+
}
|
|
22
|
+
catch (err) {
|
|
23
|
+
if (!active)
|
|
24
|
+
return;
|
|
25
|
+
current = {
|
|
26
|
+
...current,
|
|
27
|
+
loading: false,
|
|
28
|
+
error: err instanceof Error ? err : new Error(String(err)),
|
|
29
|
+
};
|
|
30
|
+
onUpdate(current);
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
void refresh();
|
|
34
|
+
const unsubTable = client.events.on(tableName, () => {
|
|
35
|
+
void refresh();
|
|
36
|
+
});
|
|
37
|
+
const unsubReset = client.events.on('reset', () => {
|
|
38
|
+
void refresh();
|
|
39
|
+
});
|
|
40
|
+
return {
|
|
41
|
+
refresh,
|
|
42
|
+
dispose() {
|
|
43
|
+
active = false;
|
|
44
|
+
unsubTable();
|
|
45
|
+
unsubReset();
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Framework-agnostic sync status subscription helper shared by Svelte, Vue, and Solid bindings.
|
|
51
|
+
*/
|
|
52
|
+
function subscribeSyncStatus(client, onUpdate) {
|
|
53
|
+
onUpdate({
|
|
54
|
+
isOnline: true,
|
|
55
|
+
isPushing: false,
|
|
56
|
+
isPulling: false,
|
|
57
|
+
pendingCount: 0,
|
|
58
|
+
});
|
|
59
|
+
void client
|
|
60
|
+
.getMetrics()
|
|
61
|
+
.then((m) => onUpdate({
|
|
62
|
+
isOnline: m.isOnline,
|
|
63
|
+
isPushing: m.isPushing,
|
|
64
|
+
isPulling: m.isPulling,
|
|
65
|
+
pendingCount: m.outboxPendingCount,
|
|
66
|
+
}))
|
|
67
|
+
.catch(() => { });
|
|
68
|
+
return client.events.on('sync:status', (next) => {
|
|
69
|
+
onUpdate(next);
|
|
70
|
+
});
|
|
71
|
+
}
|
package/dist/schema/index.d.ts
CHANGED
package/dist/schema/index.js
CHANGED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { LocalFirstClient } from '../core/client.js';
|
|
2
|
+
import type { QueryOptions, WhereFilter } from '../core/types.js';
|
|
3
|
+
export type ColumnTypeTag = 'string' | 'number' | 'boolean' | 'json' | 'string?' | 'number?' | 'boolean?' | 'json?';
|
|
4
|
+
export type InferColumnType<T extends ColumnTypeTag> = T extends 'string' ? string : T extends 'number' ? number : T extends 'boolean' ? boolean : T extends 'json' ? Record<string, any> | any[] : T extends 'string?' ? string | null : T extends 'number?' ? number | null : T extends 'boolean?' ? boolean | null : T extends 'json?' ? Record<string, any> | any[] | null : unknown;
|
|
5
|
+
export type SchemaDefinition = Record<string, Record<string, ColumnTypeTag>>;
|
|
6
|
+
export type InferTableRow<TCols extends Record<string, ColumnTypeTag>> = {
|
|
7
|
+
[K in keyof TCols]: InferColumnType<TCols[K]>;
|
|
8
|
+
};
|
|
9
|
+
export type InferSchema<TSchema extends SchemaDefinition> = {
|
|
10
|
+
[T in keyof TSchema]: InferTableRow<TSchema[T]>;
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* Defines a declarative schema dictionary for compile-time TypeScript row inference.
|
|
14
|
+
*/
|
|
15
|
+
export declare function defineTypedSchema<TSchema extends SchemaDefinition>(schema: TSchema): TSchema;
|
|
16
|
+
export interface TypedQueryBuilder<TRow extends Record<string, any>> {
|
|
17
|
+
select<K extends keyof TRow & string>(...columns: K[]): TypedQueryBuilder<Pick<TRow, K>>;
|
|
18
|
+
where(filter: Partial<Record<keyof TRow & string, any>> | WhereFilter): TypedQueryBuilder<TRow>;
|
|
19
|
+
orderBy(column: keyof TRow & string, direction?: 'asc' | 'desc' | 'ASC' | 'DESC'): TypedQueryBuilder<TRow>;
|
|
20
|
+
limit(count: number): TypedQueryBuilder<TRow>;
|
|
21
|
+
offset(count: number): TypedQueryBuilder<TRow>;
|
|
22
|
+
distinct(enabled?: boolean): TypedQueryBuilder<TRow>;
|
|
23
|
+
execute(): Promise<TRow[]>;
|
|
24
|
+
first(): Promise<TRow | null>;
|
|
25
|
+
count(): Promise<number>;
|
|
26
|
+
}
|
|
27
|
+
export interface TypedLocalFirstClient<TSchema extends SchemaDefinition> {
|
|
28
|
+
readonly raw: LocalFirstClient;
|
|
29
|
+
from<T extends keyof TSchema & string>(tableName: T): TypedQueryBuilder<InferTableRow<TSchema[T]>>;
|
|
30
|
+
findById<T extends keyof TSchema & string>(tableName: T, id: string, options?: Pick<QueryOptions, 'includeDeleted'>): Promise<InferTableRow<TSchema[T]> | null>;
|
|
31
|
+
insert<T extends keyof TSchema & string>(tableName: T, payload: Partial<InferTableRow<TSchema[T]>> & Record<string, any>): Promise<string>;
|
|
32
|
+
update<T extends keyof TSchema & string>(tableName: T, id: string, payload: Partial<InferTableRow<TSchema[T]>>): Promise<void>;
|
|
33
|
+
delete<T extends keyof TSchema & string>(tableName: T, id: string): Promise<void>;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Wraps a `LocalFirstClient` with strict TypeScript table and column inference derived from `defineTypedSchema()`.
|
|
37
|
+
*/
|
|
38
|
+
export declare function createTypedClient<TSchema extends SchemaDefinition>(client: LocalFirstClient, _schema?: TSchema): TypedLocalFirstClient<TSchema>;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.defineTypedSchema = defineTypedSchema;
|
|
4
|
+
exports.createTypedClient = createTypedClient;
|
|
5
|
+
/**
|
|
6
|
+
* Defines a declarative schema dictionary for compile-time TypeScript row inference.
|
|
7
|
+
*/
|
|
8
|
+
function defineTypedSchema(schema) {
|
|
9
|
+
return schema;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Wraps a `LocalFirstClient` with strict TypeScript table and column inference derived from `defineTypedSchema()`.
|
|
13
|
+
*/
|
|
14
|
+
function createTypedClient(client, _schema) {
|
|
15
|
+
return {
|
|
16
|
+
raw: client,
|
|
17
|
+
from(tableName) {
|
|
18
|
+
return client.from(tableName);
|
|
19
|
+
},
|
|
20
|
+
findById(tableName, id, options) {
|
|
21
|
+
return client.findById(tableName, id, options);
|
|
22
|
+
},
|
|
23
|
+
insert(tableName, payload) {
|
|
24
|
+
return client.insert(tableName, payload);
|
|
25
|
+
},
|
|
26
|
+
update(tableName, id, payload) {
|
|
27
|
+
return client.update(tableName, id, payload);
|
|
28
|
+
},
|
|
29
|
+
async delete(tableName, id) {
|
|
30
|
+
await client.delete(tableName, id);
|
|
31
|
+
},
|
|
32
|
+
};
|
|
33
|
+
}
|
|
@@ -6,6 +6,8 @@ export interface DashboardHandlerOptions {
|
|
|
6
6
|
readOnly?: boolean;
|
|
7
7
|
/** Optional bearer/query token required to access the dashboard and its APIs. */
|
|
8
8
|
authToken?: string;
|
|
9
|
+
/** Require local-lite user login to access dashboard APIs. Defaults to true. */
|
|
10
|
+
requireAuth?: boolean;
|
|
9
11
|
/** Base path if mounted under a sub-path (e.g. '/_dashboard'). Defaults to ''. */
|
|
10
12
|
basePath?: string;
|
|
11
13
|
}
|
package/dist/server/dashboard.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.createDashboardHandler = createDashboardHandler;
|
|
4
|
+
const local_js_1 = require("../auth/local.js");
|
|
4
5
|
const encryption_js_1 = require("../backups/encryption.js");
|
|
5
6
|
const store_js_1 = require("../kv-store/store.js");
|
|
6
7
|
const sql_js_1 = require("../utils/sql.js");
|
|
@@ -26,6 +27,30 @@ function isAuthorized(request, url, authToken) {
|
|
|
26
27
|
return true;
|
|
27
28
|
return false;
|
|
28
29
|
}
|
|
30
|
+
function extractSessionToken(request, url) {
|
|
31
|
+
const header = request.headers.get('authorization');
|
|
32
|
+
if (header && header.startsWith('Bearer ')) {
|
|
33
|
+
const token = header.slice(7).trim();
|
|
34
|
+
if (token)
|
|
35
|
+
return token;
|
|
36
|
+
}
|
|
37
|
+
const queryToken = url.searchParams.get('token');
|
|
38
|
+
if (queryToken)
|
|
39
|
+
return queryToken;
|
|
40
|
+
const cookieHeader = request.headers.get('cookie');
|
|
41
|
+
if (cookieHeader) {
|
|
42
|
+
for (const part of cookieHeader.split(';')) {
|
|
43
|
+
const eq = part.indexOf('=');
|
|
44
|
+
if (eq === -1)
|
|
45
|
+
continue;
|
|
46
|
+
const k = part.slice(0, eq).trim();
|
|
47
|
+
if (k === 'local_lite_session') {
|
|
48
|
+
return decodeURIComponent(part.slice(eq + 1).trim());
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
29
54
|
async function listTables(db) {
|
|
30
55
|
const tablesRows = await db.execute(`SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name ASC;`);
|
|
31
56
|
const summaries = [];
|
|
@@ -113,7 +138,45 @@ function toCsv(columns, rows) {
|
|
|
113
138
|
function createDashboardHandler(db, options = {}) {
|
|
114
139
|
const title = options.title ?? 'local-lite Dashboard';
|
|
115
140
|
const readOnly = Boolean(options.readOnly);
|
|
141
|
+
const requireAuth = options.requireAuth !== false;
|
|
116
142
|
const basePath = (options.basePath ?? '').replace(/\/+$/, '');
|
|
143
|
+
const authEngine = new local_js_1.LocalAuthEngine(db);
|
|
144
|
+
let authInitPromise = null;
|
|
145
|
+
const ensureAuth = () => (authInitPromise ??= authEngine.initialize());
|
|
146
|
+
const countUsers = async () => {
|
|
147
|
+
await ensureAuth();
|
|
148
|
+
const rows = (await db.execute(`SELECT COUNT(*) AS cnt FROM _local_users;`)) ?? [];
|
|
149
|
+
return Number(rows[0]?.cnt ?? 0);
|
|
150
|
+
};
|
|
151
|
+
const verifyLocalSession = async (request, url) => {
|
|
152
|
+
const token = extractSessionToken(request, url);
|
|
153
|
+
if (!token)
|
|
154
|
+
return null;
|
|
155
|
+
await ensureAuth();
|
|
156
|
+
const rows = (await db.execute(`SELECT s.id AS session_id, s.user_id, s.expires_at, u.email, u.username, u.display_name, u.role
|
|
157
|
+
FROM _local_sessions s
|
|
158
|
+
INNER JOIN _local_users u ON u.id = s.user_id
|
|
159
|
+
WHERE s.token = ?
|
|
160
|
+
LIMIT 1;`, [token])) ?? [];
|
|
161
|
+
const row = rows[0];
|
|
162
|
+
if (!row)
|
|
163
|
+
return null;
|
|
164
|
+
if (row.expires_at !== null && row.expires_at !== undefined && Number(row.expires_at) <= Date.now()) {
|
|
165
|
+
return null;
|
|
166
|
+
}
|
|
167
|
+
return {
|
|
168
|
+
id: String(row.user_id),
|
|
169
|
+
email: row.email ? String(row.email) : undefined,
|
|
170
|
+
username: row.username ? String(row.username) : undefined,
|
|
171
|
+
name: row.display_name ? String(row.display_name) : undefined,
|
|
172
|
+
role: row.role ? String(row.role) : undefined,
|
|
173
|
+
};
|
|
174
|
+
};
|
|
175
|
+
const withSessionCookie = (res, token, maxAgeSeconds = 60 * 60 * 24 * 7) => {
|
|
176
|
+
const headers = new Headers(res.headers);
|
|
177
|
+
headers.append('Set-Cookie', `local_lite_session=${encodeURIComponent(token)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAgeSeconds}`);
|
|
178
|
+
return new Response(res.body, { status: res.status, headers });
|
|
179
|
+
};
|
|
117
180
|
const logs = [];
|
|
118
181
|
let nextLogId = 1;
|
|
119
182
|
const recordLog = (method, path, status, startedAt, detail) => {
|
|
@@ -132,16 +195,133 @@ function createDashboardHandler(db, options = {}) {
|
|
|
132
195
|
logs.length = 200;
|
|
133
196
|
};
|
|
134
197
|
return async (request) => {
|
|
198
|
+
const origin = request.headers.get('origin');
|
|
199
|
+
const applyCors = (response) => {
|
|
200
|
+
if (!origin)
|
|
201
|
+
return response;
|
|
202
|
+
const headers = new Headers(response.headers);
|
|
203
|
+
headers.set('Access-Control-Allow-Origin', origin);
|
|
204
|
+
headers.set('Access-Control-Allow-Credentials', 'true');
|
|
205
|
+
headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
|
|
206
|
+
headers.set('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, DELETE, OPTIONS');
|
|
207
|
+
headers.set('Vary', 'Origin');
|
|
208
|
+
return new Response(response.body, {
|
|
209
|
+
status: response.status,
|
|
210
|
+
statusText: response.statusText,
|
|
211
|
+
headers,
|
|
212
|
+
});
|
|
213
|
+
};
|
|
214
|
+
if (request.method === 'OPTIONS') {
|
|
215
|
+
return applyCors(new Response(null, { status: 204 }));
|
|
216
|
+
}
|
|
135
217
|
const startedAt = performance.now();
|
|
136
218
|
const url = new URL(request.url);
|
|
137
219
|
let pathname = url.pathname;
|
|
138
220
|
if (basePath && pathname.startsWith(basePath)) {
|
|
139
221
|
pathname = pathname.slice(basePath.length) || '/';
|
|
140
222
|
}
|
|
141
|
-
if (!isAuthorized(request, url, options.authToken)) {
|
|
223
|
+
if (options.authToken && !isAuthorized(request, url, options.authToken)) {
|
|
142
224
|
recordLog(request.method, pathname, 401, startedAt, 'Unauthorized');
|
|
143
225
|
return errorResponse('Unauthorized.', 401);
|
|
144
226
|
}
|
|
227
|
+
// ── Local Auth endpoints (accessible before login) ──────────────────
|
|
228
|
+
if (pathname === '/api/dashboard-auth/status' && request.method === 'GET') {
|
|
229
|
+
try {
|
|
230
|
+
const userCount = await countUsers();
|
|
231
|
+
const sessionUser = requireAuth ? await verifyLocalSession(request, url) : null;
|
|
232
|
+
return jsonResponse({
|
|
233
|
+
requireAuth,
|
|
234
|
+
authenticated: !requireAuth || Boolean(options.authToken && isAuthorized(request, url, options.authToken)) || Boolean(sessionUser),
|
|
235
|
+
userCount,
|
|
236
|
+
user: sessionUser,
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
catch (err) {
|
|
240
|
+
return errorResponse(err?.message ?? 'Auth status failed.', 500);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
if (pathname === '/api/dashboard-auth/setup' && request.method === 'POST') {
|
|
244
|
+
try {
|
|
245
|
+
const userCount = await countUsers();
|
|
246
|
+
if (userCount > 0) {
|
|
247
|
+
return errorResponse('Admin account already exists. Please sign in.', 403);
|
|
248
|
+
}
|
|
249
|
+
const body = (await request.json().catch(() => null));
|
|
250
|
+
const result = await authEngine.signUp({
|
|
251
|
+
email: String(body?.email ?? ''),
|
|
252
|
+
username: body?.username ? String(body.username) : undefined,
|
|
253
|
+
password: String(body?.password ?? ''),
|
|
254
|
+
displayName: body?.name ? String(body.name) : undefined,
|
|
255
|
+
role: 'admin',
|
|
256
|
+
});
|
|
257
|
+
let token = result.session?.token ?? '';
|
|
258
|
+
if (!token && result.session?.id) {
|
|
259
|
+
token = (0, local_js_1.generateCryptoToken)(32).token;
|
|
260
|
+
await db.execute(`UPDATE _local_sessions SET token = ? WHERE id = ?;`, [
|
|
261
|
+
token,
|
|
262
|
+
result.session.id,
|
|
263
|
+
]);
|
|
264
|
+
}
|
|
265
|
+
const res = jsonResponse({
|
|
266
|
+
user: result.user,
|
|
267
|
+
token,
|
|
268
|
+
expiresAt: result.session?.expiresAt ?? null,
|
|
269
|
+
}, 201);
|
|
270
|
+
return token ? withSessionCookie(res, token) : res;
|
|
271
|
+
}
|
|
272
|
+
catch (err) {
|
|
273
|
+
return errorResponse(err?.message ?? 'Setup failed.', 400);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
if (pathname === '/api/dashboard-auth/login' && request.method === 'POST') {
|
|
277
|
+
try {
|
|
278
|
+
await ensureAuth();
|
|
279
|
+
const body = (await request.json().catch(() => null));
|
|
280
|
+
const result = await authEngine.signIn({
|
|
281
|
+
identifier: String(body?.identifier ?? ''),
|
|
282
|
+
password: String(body?.password ?? ''),
|
|
283
|
+
});
|
|
284
|
+
let token = result.session?.token ?? '';
|
|
285
|
+
if (!token && result.session?.id) {
|
|
286
|
+
token = (0, local_js_1.generateCryptoToken)(32).token;
|
|
287
|
+
await db.execute(`UPDATE _local_sessions SET token = ? WHERE id = ?;`, [
|
|
288
|
+
token,
|
|
289
|
+
result.session.id,
|
|
290
|
+
]);
|
|
291
|
+
}
|
|
292
|
+
const res = jsonResponse({
|
|
293
|
+
user: result.user,
|
|
294
|
+
token,
|
|
295
|
+
expiresAt: result.session?.expiresAt ?? null,
|
|
296
|
+
});
|
|
297
|
+
return token ? withSessionCookie(res, token) : res;
|
|
298
|
+
}
|
|
299
|
+
catch (err) {
|
|
300
|
+
return errorResponse(err?.message ?? 'Invalid credentials.', 401);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
if (pathname === '/api/dashboard-auth/logout' && request.method === 'POST') {
|
|
304
|
+
try {
|
|
305
|
+
const token = extractSessionToken(request, url);
|
|
306
|
+
if (token) {
|
|
307
|
+
await ensureAuth();
|
|
308
|
+
await db.execute(`DELETE FROM _local_sessions WHERE token = ?;`, [token]);
|
|
309
|
+
}
|
|
310
|
+
return withSessionCookie(jsonResponse({ ok: true }), '', 0);
|
|
311
|
+
}
|
|
312
|
+
catch (err) {
|
|
313
|
+
return errorResponse(err?.message ?? 'Logout failed.', 500);
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
// Gate all other /api/* requests behind local-lite session auth when requireAuth is enabled
|
|
317
|
+
if (requireAuth && pathname.startsWith('/api/')) {
|
|
318
|
+
const staticTokenOk = Boolean(options.authToken && isAuthorized(request, url, options.authToken));
|
|
319
|
+
const sessionUser = staticTokenOk ? { id: 'token' } : await verifyLocalSession(request, url);
|
|
320
|
+
if (!sessionUser) {
|
|
321
|
+
recordLog(request.method, pathname, 401, startedAt, 'Unauthorized');
|
|
322
|
+
return errorResponse('Authentication required.', 401);
|
|
323
|
+
}
|
|
324
|
+
}
|
|
145
325
|
let loggedThisRequest = false;
|
|
146
326
|
const reply = (res, detail) => {
|
|
147
327
|
if (pathname.startsWith('/api/')) {
|
|
@@ -1355,7 +1535,7 @@ function createDashboardHandler(db, options = {}) {
|
|
|
1355
1535
|
if (!loggedThisRequest && pathname.startsWith('/api/')) {
|
|
1356
1536
|
recordLog(request.method, pathname, res.status, startedAt);
|
|
1357
1537
|
}
|
|
1358
|
-
return res;
|
|
1538
|
+
return applyCors(res);
|
|
1359
1539
|
};
|
|
1360
1540
|
}
|
|
1361
1541
|
function escapeHtml(text) {
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { LocalFirstClient } from '../core/client.js';
|
|
2
|
+
import { QueryOptions, SyncStatusEvent } from '../core/types.js';
|
|
3
|
+
export interface SolidApi {
|
|
4
|
+
createSignal<T>(value: T): [() => T, (next: T) => void];
|
|
5
|
+
onCleanup?: (fn: () => void) => void;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* SolidJS primitive for live local-lite queries.
|
|
9
|
+
* Pass `{ createSignal, onCleanup }` from `'solid-js'`.
|
|
10
|
+
*/
|
|
11
|
+
export declare function createLiveQuery<T = any>(client: LocalFirstClient, tableName: string, options: QueryOptions | undefined, solid: SolidApi): {
|
|
12
|
+
data: () => T[];
|
|
13
|
+
loading: () => boolean;
|
|
14
|
+
error: () => Error | null;
|
|
15
|
+
refresh: () => Promise<void>;
|
|
16
|
+
dispose: () => void;
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* SolidJS signal for tracking `client.syncWorker` status.
|
|
20
|
+
*/
|
|
21
|
+
export declare function createSyncStatus(client: LocalFirstClient, solid: SolidApi): {
|
|
22
|
+
status: () => SyncStatusEvent;
|
|
23
|
+
dispose: () => void;
|
|
24
|
+
};
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createLiveQuery = createLiveQuery;
|
|
4
|
+
exports.createSyncStatus = createSyncStatus;
|
|
5
|
+
const live_query_js_1 = require("../reactive/live-query.js");
|
|
6
|
+
/**
|
|
7
|
+
* SolidJS primitive for live local-lite queries.
|
|
8
|
+
* Pass `{ createSignal, onCleanup }` from `'solid-js'`.
|
|
9
|
+
*/
|
|
10
|
+
function createLiveQuery(client, tableName, options, solid) {
|
|
11
|
+
const [data, setData] = solid.createSignal([]);
|
|
12
|
+
const [loading, setLoading] = solid.createSignal(true);
|
|
13
|
+
const [error, setError] = solid.createSignal(null);
|
|
14
|
+
const { refresh, dispose } = (0, live_query_js_1.subscribeLiveQuery)(client, tableName, options, (state) => {
|
|
15
|
+
setData(state.data);
|
|
16
|
+
setLoading(state.loading);
|
|
17
|
+
setError(state.error);
|
|
18
|
+
});
|
|
19
|
+
solid.onCleanup?.(dispose);
|
|
20
|
+
return { data, loading, error, refresh, dispose };
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* SolidJS signal for tracking `client.syncWorker` status.
|
|
24
|
+
*/
|
|
25
|
+
function createSyncStatus(client, solid) {
|
|
26
|
+
const [status, setStatus] = solid.createSignal({
|
|
27
|
+
isOnline: true,
|
|
28
|
+
isPushing: false,
|
|
29
|
+
isPulling: false,
|
|
30
|
+
pendingCount: 0,
|
|
31
|
+
});
|
|
32
|
+
const dispose = (0, live_query_js_1.subscribeSyncStatus)(client, setStatus);
|
|
33
|
+
solid.onCleanup?.(dispose);
|
|
34
|
+
return { status, dispose };
|
|
35
|
+
}
|
|
@@ -38,7 +38,7 @@ export interface FirebaseStorageUploaderInstance extends RemoteStorageUploader {
|
|
|
38
38
|
delete(keyOrPath: string): Promise<void>;
|
|
39
39
|
}
|
|
40
40
|
/**
|
|
41
|
-
* Creates a RemoteStorageUploader that syncs binary files to Firebase Cloud Storage
|
|
42
|
-
*
|
|
41
|
+
* Creates a RemoteStorageUploader that syncs binary files to Firebase Cloud Storage
|
|
42
|
+
* using the Firebase v11+ modular SDK (`firebase/storage`).
|
|
43
43
|
*/
|
|
44
|
-
export declare function createFirebaseStorageUploader(
|
|
44
|
+
export declare function createFirebaseStorageUploader(storage: any, options?: FirebaseStorageUploaderOptions): FirebaseStorageUploaderInstance;
|
package/dist/storage/firebase.js
CHANGED
|
@@ -2,20 +2,26 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.createFirebaseStorageUploader = createFirebaseStorageUploader;
|
|
4
4
|
/**
|
|
5
|
-
* Creates a RemoteStorageUploader that syncs binary files to Firebase Cloud Storage
|
|
6
|
-
*
|
|
5
|
+
* Creates a RemoteStorageUploader that syncs binary files to Firebase Cloud Storage
|
|
6
|
+
* using the Firebase v11+ modular SDK (`firebase/storage`).
|
|
7
7
|
*/
|
|
8
|
-
function createFirebaseStorageUploader(
|
|
9
|
-
if (!
|
|
10
|
-
throw new Error('
|
|
8
|
+
function createFirebaseStorageUploader(storage, options = {}) {
|
|
9
|
+
if (!storage) {
|
|
10
|
+
throw new Error('FirebaseStorage instance must be provided.');
|
|
11
11
|
}
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
12
|
+
let cachedMod = options.storageModule ?? null;
|
|
13
|
+
const getMod = async () => {
|
|
14
|
+
if (cachedMod)
|
|
15
|
+
return cachedMod;
|
|
16
|
+
try {
|
|
17
|
+
const modName = 'firebase/storage';
|
|
18
|
+
cachedMod = (await import(/* @vite-ignore */ modName));
|
|
19
|
+
return cachedMod;
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
throw new Error('Modular firebase/storage SDK is required. Install firebase >=11 or pass options.storageModule.');
|
|
23
|
+
}
|
|
24
|
+
};
|
|
19
25
|
const resolveRemotePath = (key, blob) => {
|
|
20
26
|
if (options.pathTransform) {
|
|
21
27
|
return options.pathTransform(key, blob);
|
|
@@ -27,26 +33,14 @@ function createFirebaseStorageUploader(storageOrApp, options = {}) {
|
|
|
27
33
|
}
|
|
28
34
|
return cleanKey;
|
|
29
35
|
};
|
|
30
|
-
const getRef = (path) => {
|
|
31
|
-
// 1. Modular SDK ref(storage, path)
|
|
32
|
-
if (typeof mod.ref === 'function') {
|
|
33
|
-
return mod.ref(storageInstance, path);
|
|
34
|
-
}
|
|
35
|
-
// 2. Storage instance ref(path) method
|
|
36
|
-
if (typeof storageInstance.ref === 'function') {
|
|
37
|
-
return storageInstance.ref(path);
|
|
38
|
-
}
|
|
39
|
-
// 3. Storage instance from bucket
|
|
40
|
-
if (typeof storageInstance.bucket === 'function') {
|
|
41
|
-
const b = storageInstance.bucket(options.bucket);
|
|
42
|
-
return typeof b.file === 'function' ? b.file(path) : b;
|
|
43
|
-
}
|
|
44
|
-
throw new Error('Cannot resolve Firebase Storage reference. Pass storageModule ({ ref, uploadBytes, getDownloadURL }) or a FirebaseStorage instance.');
|
|
45
|
-
};
|
|
46
36
|
return {
|
|
47
37
|
async upload(blob, data) {
|
|
38
|
+
const mod = await getMod();
|
|
39
|
+
if (typeof mod.ref !== 'function' || typeof mod.uploadBytes !== 'function') {
|
|
40
|
+
throw new Error('Modular firebase/storage functions (ref, uploadBytes) are required.');
|
|
41
|
+
}
|
|
48
42
|
const remotePath = resolveRemotePath(blob.key, blob);
|
|
49
|
-
const fileRef =
|
|
43
|
+
const fileRef = mod.ref(storage, remotePath);
|
|
50
44
|
const metadata = {
|
|
51
45
|
contentType: blob.mimeType || 'application/octet-stream',
|
|
52
46
|
};
|
|
@@ -59,77 +53,29 @@ function createFirebaseStorageUploader(storageOrApp, options = {}) {
|
|
|
59
53
|
: options.customMetadata;
|
|
60
54
|
metadata.customMetadata = extra;
|
|
61
55
|
}
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
await mod.
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
remoteUrl = await mod.getDownloadURL(fileRef);
|
|
68
|
-
}
|
|
69
|
-
return { remoteUrl, metadata };
|
|
70
|
-
}
|
|
71
|
-
// Method B: Compat put() or upload()
|
|
72
|
-
if (typeof fileRef.put === 'function') {
|
|
73
|
-
const snapshot = await fileRef.put(data, metadata);
|
|
74
|
-
let remoteUrl;
|
|
75
|
-
if (typeof snapshot?.ref?.getDownloadURL === 'function') {
|
|
76
|
-
remoteUrl = await snapshot.ref.getDownloadURL();
|
|
77
|
-
}
|
|
78
|
-
else if (typeof fileRef.getDownloadURL === 'function') {
|
|
79
|
-
remoteUrl = await fileRef.getDownloadURL();
|
|
80
|
-
}
|
|
81
|
-
else {
|
|
82
|
-
remoteUrl = remotePath;
|
|
83
|
-
}
|
|
84
|
-
return { remoteUrl, metadata };
|
|
85
|
-
}
|
|
86
|
-
// Method C: GCS admin save()
|
|
87
|
-
if (typeof fileRef.save === 'function') {
|
|
88
|
-
await fileRef.save(Buffer.isBuffer(data) ? data : Buffer.from(data), {
|
|
89
|
-
contentType: metadata.contentType,
|
|
90
|
-
metadata: metadata.customMetadata,
|
|
91
|
-
});
|
|
92
|
-
let remoteUrl = remotePath;
|
|
93
|
-
if (typeof fileRef.getSignedUrl === 'function') {
|
|
94
|
-
const [url] = await fileRef.getSignedUrl({
|
|
95
|
-
action: 'read',
|
|
96
|
-
expires: Date.now() + 86400 * 1000,
|
|
97
|
-
});
|
|
98
|
-
remoteUrl = url;
|
|
99
|
-
}
|
|
100
|
-
return { remoteUrl, metadata };
|
|
101
|
-
}
|
|
102
|
-
throw new Error('Unsupported Firebase Storage client: missing uploadBytes, put, or save method.');
|
|
56
|
+
await mod.uploadBytes(fileRef, data, metadata);
|
|
57
|
+
const remoteUrl = typeof mod.getDownloadURL === 'function'
|
|
58
|
+
? await mod.getDownloadURL(fileRef)
|
|
59
|
+
: remotePath;
|
|
60
|
+
return { remoteUrl, metadata };
|
|
103
61
|
},
|
|
104
62
|
async getDownloadUrl(keyOrPath) {
|
|
105
|
-
const
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
return await mod.getDownloadURL(fileRef);
|
|
109
|
-
}
|
|
110
|
-
if (typeof fileRef.getDownloadURL === 'function') {
|
|
111
|
-
return await fileRef.getDownloadURL();
|
|
112
|
-
}
|
|
113
|
-
if (typeof fileRef.getSignedUrl === 'function') {
|
|
114
|
-
const [url] = await fileRef.getSignedUrl({
|
|
115
|
-
action: 'read',
|
|
116
|
-
expires: Date.now() + 86400 * 1000,
|
|
117
|
-
});
|
|
118
|
-
return url;
|
|
63
|
+
const mod = await getMod();
|
|
64
|
+
if (typeof mod.ref !== 'function' || typeof mod.getDownloadURL !== 'function') {
|
|
65
|
+
throw new Error('Modular firebase/storage functions (ref, getDownloadURL) are required.');
|
|
119
66
|
}
|
|
120
|
-
|
|
67
|
+
const remotePath = resolveRemotePath(keyOrPath);
|
|
68
|
+
const fileRef = mod.ref(storage, remotePath);
|
|
69
|
+
return await mod.getDownloadURL(fileRef);
|
|
121
70
|
},
|
|
122
71
|
async delete(keyOrPath) {
|
|
123
|
-
const
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
await mod.deleteObject(fileRef);
|
|
127
|
-
return;
|
|
128
|
-
}
|
|
129
|
-
if (typeof fileRef.delete === 'function') {
|
|
130
|
-
await fileRef.delete();
|
|
131
|
-
return;
|
|
72
|
+
const mod = await getMod();
|
|
73
|
+
if (typeof mod.ref !== 'function' || typeof mod.deleteObject !== 'function') {
|
|
74
|
+
throw new Error('Modular firebase/storage functions (ref, deleteObject) are required.');
|
|
132
75
|
}
|
|
76
|
+
const remotePath = resolveRemotePath(keyOrPath);
|
|
77
|
+
const fileRef = mod.ref(storage, remotePath);
|
|
78
|
+
await mod.deleteObject(fileRef);
|
|
133
79
|
},
|
|
134
80
|
};
|
|
135
81
|
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { LocalFirstClient } from '../core/client.js';
|
|
2
|
+
import { QueryOptions, SyncStatusEvent } from '../core/types.js';
|
|
3
|
+
import { type LiveQueryState } from '../reactive/live-query.js';
|
|
4
|
+
export type { LiveQueryState };
|
|
5
|
+
export interface SvelteReadable<T> {
|
|
6
|
+
subscribe(run: (value: T) => void): () => void;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Creates a Svelte-compatible Readable store (`$store` reactive) backed by a live local-lite query.
|
|
10
|
+
*/
|
|
11
|
+
export declare function liveQuery<T = any>(client: LocalFirstClient, tableName: string, options?: QueryOptions): SvelteReadable<LiveQueryState<T>>;
|
|
12
|
+
/**
|
|
13
|
+
* Creates a Svelte-compatible Readable store tracking `client.syncWorker` status.
|
|
14
|
+
*/
|
|
15
|
+
export declare function syncStatusStore(client: LocalFirstClient): SvelteReadable<SyncStatusEvent>;
|