@zveltio/sdk 3.0.0-beta.1 → 3.0.0-beta.101
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 +17 -4
- package/dist/client.d.ts +103 -7
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +117 -27
- package/dist/core.d.ts.map +1 -1
- package/dist/core.js +21 -3
- package/dist/crdt.d.ts.map +1 -1
- package/dist/crdt.js +11 -2
- package/dist/ddl/index.d.ts +20 -0
- package/dist/ddl/index.d.ts.map +1 -1
- package/dist/errors.d.ts +58 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +124 -0
- package/dist/extension/action-refusal.d.ts +27 -0
- package/dist/extension/action-refusal.d.ts.map +1 -0
- package/dist/extension/action-refusal.js +29 -0
- package/dist/extension/capabilities.d.ts +71 -0
- package/dist/extension/capabilities.d.ts.map +1 -0
- package/dist/extension/capabilities.js +79 -0
- package/dist/extension/dates.d.ts +7 -0
- package/dist/extension/dates.d.ts.map +1 -0
- package/dist/extension/dates.js +14 -0
- package/dist/extension/index.d.ts +1086 -38
- package/dist/extension/index.d.ts.map +1 -1
- package/dist/extension/index.js +16 -0
- package/dist/extension/jsonb.d.ts +62 -0
- package/dist/extension/jsonb.d.ts.map +1 -0
- package/dist/extension/jsonb.js +64 -0
- package/dist/extension/multipart.d.ts +58 -0
- package/dist/extension/multipart.d.ts.map +1 -0
- package/dist/extension/multipart.js +61 -0
- package/dist/extension/numeric.d.ts +94 -0
- package/dist/extension/numeric.d.ts.map +1 -0
- package/dist/extension/numeric.js +162 -0
- package/dist/extension/permission-gate.d.ts +15 -0
- package/dist/extension/permission-gate.d.ts.map +1 -1
- package/dist/extension/permission-gate.js +33 -1
- package/dist/extension/reserved-paths.d.ts +10 -0
- package/dist/extension/reserved-paths.d.ts.map +1 -0
- package/dist/extension/reserved-paths.js +23 -0
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/local-store.d.ts +14 -1
- package/dist/local-store.d.ts.map +1 -1
- package/dist/local-store.js +92 -13
- package/dist/offline/index.d.ts +25 -55
- package/dist/offline/index.d.ts.map +1 -1
- package/dist/offline/index.js +173 -157
- package/dist/publish/index.d.ts.map +1 -1
- package/dist/publish/index.js +6 -1
- package/dist/realtime.d.ts +25 -1
- package/dist/realtime.d.ts.map +1 -1
- package/dist/realtime.js +47 -3
- package/dist/rpc/index.d.ts.map +1 -1
- package/dist/rpc/index.js +2 -0
- package/dist/schema-codegen.d.ts +25 -1
- package/dist/schema-codegen.d.ts.map +1 -1
- package/dist/schema-codegen.js +141 -7
- package/dist/schema-watcher.d.ts +10 -2
- package/dist/schema-watcher.d.ts.map +1 -1
- package/dist/schema-watcher.js +25 -10
- package/dist/studio/index.d.ts +1 -0
- package/dist/studio/index.d.ts.map +1 -1
- package/dist/studio/index.js +3 -0
- package/dist/studio/slot-owner-registry.d.ts +13 -0
- package/dist/studio/slot-owner-registry.d.ts.map +1 -0
- package/dist/studio/slot-owner-registry.js +21 -0
- package/dist/svelte.d.ts +1 -1
- package/dist/svelte.d.ts.map +1 -1
- package/dist/svelte.js +4 -2
- package/dist/sync-manager.d.ts +49 -4
- package/dist/sync-manager.d.ts.map +1 -1
- package/dist/sync-manager.js +173 -15
- package/dist/testing/index.d.ts.map +1 -1
- package/dist/testing/index.js +23 -1
- package/dist/testing/with-test-db.d.ts +1 -1
- package/dist/testing/with-test-db.d.ts.map +1 -1
- package/dist/testing/with-test-db.js +22 -15
- package/dist/tests/action-refusal.test.d.ts +2 -0
- package/dist/tests/action-refusal.test.d.ts.map +1 -0
- package/dist/tests/action-refusal.test.js +13 -0
- package/dist/tests/client.test.d.ts +2 -0
- package/dist/tests/client.test.d.ts.map +1 -0
- package/dist/tests/client.test.js +164 -0
- package/dist/tests/crdt-orset.test.d.ts +2 -0
- package/dist/tests/crdt-orset.test.d.ts.map +1 -0
- package/dist/tests/crdt-orset.test.js +23 -0
- package/dist/tests/local-store.test.js +44 -0
- package/dist/tests/migration-parse.test.d.ts +2 -0
- package/dist/tests/migration-parse.test.d.ts.map +1 -0
- package/dist/tests/migration-parse.test.js +17 -0
- package/dist/tests/multipart.test.d.ts +2 -0
- package/dist/tests/multipart.test.d.ts.map +1 -0
- package/dist/tests/multipart.test.js +37 -0
- package/dist/tests/offline-provider-crdt.test.d.ts +2 -0
- package/dist/tests/offline-provider-crdt.test.d.ts.map +1 -0
- package/dist/tests/offline-provider-crdt.test.js +206 -0
- package/dist/tests/realtime.test.d.ts +2 -0
- package/dist/tests/realtime.test.d.ts.map +1 -0
- package/dist/tests/realtime.test.js +220 -0
- package/dist/tests/reserved-paths.test.d.ts +2 -0
- package/dist/tests/reserved-paths.test.d.ts.map +1 -0
- package/dist/tests/reserved-paths.test.js +21 -0
- package/dist/tests/sync-manager.test.d.ts +2 -0
- package/dist/tests/sync-manager.test.d.ts.map +1 -0
- package/dist/tests/sync-manager.test.js +123 -0
- package/dist/tests/today-in.test.d.ts +2 -0
- package/dist/tests/today-in.test.d.ts.map +1 -0
- package/dist/tests/today-in.test.js +14 -0
- package/dist/tests/validate-manifest-actions.test.d.ts +2 -0
- package/dist/tests/validate-manifest-actions.test.d.ts.map +1 -0
- package/dist/tests/validate-manifest-actions.test.js +82 -0
- package/dist/tests/validate-manifest-dependencies.test.d.ts +2 -0
- package/dist/tests/validate-manifest-dependencies.test.d.ts.map +1 -0
- package/dist/tests/validate-manifest-dependencies.test.js +27 -0
- package/dist/tests/validate-manifest-forward-credentials.test.d.ts +2 -0
- package/dist/tests/validate-manifest-forward-credentials.test.d.ts.map +1 -0
- package/dist/tests/validate-manifest-forward-credentials.test.js +35 -0
- package/dist/tests/validate-sdui-data-endpoints.test.d.ts +2 -0
- package/dist/tests/validate-sdui-data-endpoints.test.d.ts.map +1 -0
- package/dist/tests/validate-sdui-data-endpoints.test.js +41 -0
- package/dist/tests/with-test-db.test.d.ts +2 -0
- package/dist/tests/with-test-db.test.d.ts.map +1 -0
- package/dist/tests/with-test-db.test.js +57 -0
- package/dist/types/index.d.ts.map +1 -1
- package/dist/validate/index.d.ts +53 -0
- package/dist/validate/index.d.ts.map +1 -1
- package/dist/validate/index.js +693 -7
- package/dist/validate/migration-parse.d.ts +10 -5
- package/dist/validate/migration-parse.d.ts.map +1 -1
- package/dist/validate/migration-parse.js +1 -1
- package/dist/validate/shared-message-keys.d.ts +16 -0
- package/dist/validate/shared-message-keys.d.ts.map +1 -0
- package/dist/validate/shared-message-keys.js +227 -0
- package/package.json +8 -8
- package/dist/client/Auth.d.ts +0 -19
- package/dist/client/Auth.d.ts.map +0 -1
- package/dist/client/Auth.js +0 -45
- package/dist/client/QueryBuilder.d.ts +0 -17
- package/dist/client/QueryBuilder.d.ts.map +0 -1
- package/dist/client/QueryBuilder.js +0 -85
- package/dist/client/RealtimeClient.d.ts +0 -22
- package/dist/client/RealtimeClient.d.ts.map +0 -1
- package/dist/client/RealtimeClient.js +0 -98
- package/dist/client/ZveltioClient.d.ts +0 -20
- package/dist/client/ZveltioClient.d.ts.map +0 -1
- package/dist/client/ZveltioClient.js +0 -78
- package/dist/generate-types.d.ts +0 -37
- package/dist/generate-types.d.ts.map +0 -1
- package/dist/generate-types.js +0 -157
package/dist/sync-manager.js
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import { LocalStore } from './local-store.js';
|
|
2
2
|
import { mergeLWW, fromDocument } from './crdt.js';
|
|
3
3
|
import { generateUUID } from './utils.js';
|
|
4
|
+
import { ZveltioApiError } from './errors.js';
|
|
5
|
+
/** Local-store meta key holding `/api/sync/pull` positions, per table. */
|
|
6
|
+
const PULL_CURSORS = 'sync_pull_cursors';
|
|
4
7
|
export class SyncManager {
|
|
5
8
|
store;
|
|
6
9
|
client;
|
|
@@ -9,6 +12,16 @@ export class SyncManager {
|
|
|
9
12
|
syncTimer = null;
|
|
10
13
|
isOnline = true;
|
|
11
14
|
isSyncing = false;
|
|
15
|
+
/** Set by `stop()`; `start()` checks it after every await it makes. */
|
|
16
|
+
stopped = false;
|
|
17
|
+
onOnline = () => {
|
|
18
|
+
this.isOnline = true;
|
|
19
|
+
this.syncNow(); // Sync immediately on reconnect
|
|
20
|
+
};
|
|
21
|
+
onOffline = () => {
|
|
22
|
+
this.isOnline = false;
|
|
23
|
+
};
|
|
24
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
12
25
|
listeners = new Map();
|
|
13
26
|
constructor(client, config = {}) {
|
|
14
27
|
this.store = new LocalStore();
|
|
@@ -22,21 +35,24 @@ export class SyncManager {
|
|
|
22
35
|
};
|
|
23
36
|
}
|
|
24
37
|
async start(realtimeUrl) {
|
|
38
|
+
this.stopped = false;
|
|
25
39
|
await this.store.open();
|
|
40
|
+
// A caller that unmounts before `start()` settles calls `stop()` first — a
|
|
41
|
+
// React effect cleanup, and StrictMode runs one on every mount in
|
|
42
|
+
// development. Arming the timer and socket after that leaked both forever.
|
|
43
|
+
if (this.stopped)
|
|
44
|
+
return this.store.close();
|
|
26
45
|
// Online/offline detection
|
|
27
46
|
if (typeof window !== 'undefined') {
|
|
28
|
-
window.addEventListener('online',
|
|
29
|
-
|
|
30
|
-
this.syncNow(); // Sync immediately on reconnect
|
|
31
|
-
});
|
|
32
|
-
window.addEventListener('offline', () => {
|
|
33
|
-
this.isOnline = false;
|
|
34
|
-
});
|
|
47
|
+
window.addEventListener('online', this.onOnline);
|
|
48
|
+
window.addEventListener('offline', this.onOffline);
|
|
35
49
|
this.isOnline = navigator.onLine;
|
|
36
50
|
}
|
|
37
51
|
// Realtime: receives push updates from server
|
|
38
52
|
if (realtimeUrl) {
|
|
39
53
|
const { ZveltioRealtime } = await import('./realtime.js');
|
|
54
|
+
if (this.stopped)
|
|
55
|
+
return;
|
|
40
56
|
this.realtime = new ZveltioRealtime(realtimeUrl);
|
|
41
57
|
this.realtime.connect();
|
|
42
58
|
// Subscriptions are per-collection via collection()
|
|
@@ -75,6 +91,7 @@ export class SyncManager {
|
|
|
75
91
|
};
|
|
76
92
|
},
|
|
77
93
|
/** Create — writes LOCAL + queues sync */
|
|
94
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
78
95
|
create: async (data) => {
|
|
79
96
|
const id = data.id || generateUUID();
|
|
80
97
|
const record = await this.store.put(name, id, data);
|
|
@@ -87,6 +104,7 @@ export class SyncManager {
|
|
|
87
104
|
};
|
|
88
105
|
},
|
|
89
106
|
/** Update — writes LOCAL + queues sync */
|
|
107
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
90
108
|
update: async (id, data) => {
|
|
91
109
|
const existing = await this.store.get(name, id);
|
|
92
110
|
const merged = { ...(existing?.data || {}), ...data };
|
|
@@ -106,6 +124,7 @@ export class SyncManager {
|
|
|
106
124
|
this.syncNow();
|
|
107
125
|
},
|
|
108
126
|
/** Subscribe la changes (realtime + local writes) */
|
|
127
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
109
128
|
subscribe: (callback) => {
|
|
110
129
|
if (!this.listeners.has(name))
|
|
111
130
|
this.listeners.set(name, new Set());
|
|
@@ -114,19 +133,24 @@ export class SyncManager {
|
|
|
114
133
|
let unsubRealtime;
|
|
115
134
|
if (this.realtime) {
|
|
116
135
|
unsubRealtime = this.realtime.subscribe(name, async (event) => {
|
|
117
|
-
// Apply update from server to local store
|
|
118
|
-
|
|
136
|
+
// Apply update from server to local store. The engine's socket
|
|
137
|
+
// sends `{ type: 'event', event: 'insert'|'update'|'delete', data }`
|
|
138
|
+
// (routes/ws.ts `broadcastEvent`); the id lives on `data`.
|
|
139
|
+
const id = event.data?.id;
|
|
140
|
+
if (event.type !== 'event' || !id)
|
|
141
|
+
return;
|
|
142
|
+
if (event.event === 'insert' || event.event === 'update') {
|
|
119
143
|
try {
|
|
120
|
-
const serverRecord = await this.client.collection(name).get(
|
|
121
|
-
await this.store.applyServerUpdate(name,
|
|
144
|
+
const serverRecord = await this.client.collection(name).get(id);
|
|
145
|
+
await this.store.applyServerUpdate(name, id, serverRecord, Date.now());
|
|
122
146
|
this.notifyListeners(name);
|
|
123
147
|
}
|
|
124
148
|
catch {
|
|
125
149
|
/* offline or error — ignore, periodic sync will resolve */
|
|
126
150
|
}
|
|
127
151
|
}
|
|
128
|
-
else if (event.event === '
|
|
129
|
-
await this.store.
|
|
152
|
+
else if (event.event === 'delete') {
|
|
153
|
+
await this.store.applyServerDelete(name, id);
|
|
130
154
|
this.notifyListeners(name);
|
|
131
155
|
}
|
|
132
156
|
});
|
|
@@ -150,6 +174,7 @@ export class SyncManager {
|
|
|
150
174
|
return this.store.getConflicts(name);
|
|
151
175
|
},
|
|
152
176
|
/** Resolve a conflict manually */
|
|
177
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
153
178
|
resolveConflict: async (id, resolvedData) => {
|
|
154
179
|
await this.store.resolveConflict(name, id, resolvedData);
|
|
155
180
|
this.notifyListeners(name);
|
|
@@ -170,6 +195,7 @@ export class SyncManager {
|
|
|
170
195
|
const file = new File([blobItem.blob], `offline_${blobItem.id}`, {
|
|
171
196
|
type: blobItem.blob.type,
|
|
172
197
|
});
|
|
198
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
173
199
|
const result = (await this.client.storage.upload(file));
|
|
174
200
|
const url = result?.url || result?.publicUrl || result?.path || '';
|
|
175
201
|
if (!url)
|
|
@@ -214,6 +240,7 @@ export class SyncManager {
|
|
|
214
240
|
}
|
|
215
241
|
await this.store.markSynced(op.id, op.collection, op.recordId, serverVersion);
|
|
216
242
|
this.notifyListeners(op.collection);
|
|
243
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
217
244
|
}
|
|
218
245
|
catch (err) {
|
|
219
246
|
// Conflict from server (409) — apply conflict resolution
|
|
@@ -224,15 +251,23 @@ export class SyncManager {
|
|
|
224
251
|
// CRDT LWW merge if both sides have CRDT docs and strategy is 'lww'
|
|
225
252
|
if (this.config.conflictResolution === 'lww' &&
|
|
226
253
|
localRecord?._crdtDoc &&
|
|
254
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
227
255
|
serverRecord.__crdt) {
|
|
256
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
228
257
|
const merged = mergeLWW(localRecord._crdtDoc, serverRecord.__crdt);
|
|
229
|
-
|
|
230
|
-
await this.store.resolveConflict(op.collection, op.recordId, resolvedData);
|
|
258
|
+
await this.store.resolveConflict(op.collection, op.recordId, fromDocument(merged));
|
|
231
259
|
}
|
|
232
260
|
else {
|
|
233
261
|
const resolved = this.config.onConflict(localRecord?.data, serverRecord);
|
|
234
262
|
await this.store.resolveConflict(op.collection, op.recordId, resolved);
|
|
235
263
|
}
|
|
264
|
+
// The operation the server just rejected stayed in the queue with
|
|
265
|
+
// its original payload and its attempt count untouched, so the next
|
|
266
|
+
// tick sent the same payload, took the same 409 and resolved the
|
|
267
|
+
// same conflict again — every `syncInterval`, with no end. Count
|
|
268
|
+
// the attempt so `maxRetries` retires it; the resolved row is
|
|
269
|
+
// queued by `resolveConflict` as its own operation.
|
|
270
|
+
await this.store.markFailed(op.id, 'rejected with 409 — resolved locally');
|
|
236
271
|
}
|
|
237
272
|
catch {
|
|
238
273
|
/* fallback: server wins — ignore error */
|
|
@@ -268,6 +303,109 @@ export class SyncManager {
|
|
|
268
303
|
}
|
|
269
304
|
});
|
|
270
305
|
}
|
|
306
|
+
/**
|
|
307
|
+
* Open the local store without starting background sync.
|
|
308
|
+
*
|
|
309
|
+
* `start()` opens the store, attaches online/offline listeners, connects
|
|
310
|
+
* realtime and installs a periodic timer. A caller driving `pull()` and
|
|
311
|
+
* `push()` explicitly — the `OfflineProvider` contract in `offline/` — wants
|
|
312
|
+
* the store and none of the rest, and a timer firing `syncNow()` underneath it
|
|
313
|
+
* makes "how many operations did that push send" unanswerable.
|
|
314
|
+
*/
|
|
315
|
+
async open() {
|
|
316
|
+
await this.store.open();
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* Pull rows for the named collections from the server into the local store.
|
|
320
|
+
*
|
|
321
|
+
* There was no way to do this. Records reached the local store only through
|
|
322
|
+
* realtime events, one at a time, which means a client that was offline while
|
|
323
|
+
* a row was created never learns it exists: it missed the event and nothing
|
|
324
|
+
* ever asks the server what it has. `syncNow()` is push-only despite the name.
|
|
325
|
+
*
|
|
326
|
+
* Reads `POST /api/sync/pull`, which returns what changed since the cursors
|
|
327
|
+
* kept in the local store, deletes included. Paging `list()` instead — what
|
|
328
|
+
* this did before — never removed anything: a row deleted on the server
|
|
329
|
+
* stayed in every local store that had pulled it.
|
|
330
|
+
*
|
|
331
|
+
* A collection pulled for the first time, or one the server answers with
|
|
332
|
+
* `resync`, loses its synced local rows before the page is applied; local
|
|
333
|
+
* edits not yet pushed stay. `/api/sync` takes sessions only, so a client
|
|
334
|
+
* authenticated by an API key (403) falls back to paging `list()`, without
|
|
335
|
+
* deletes.
|
|
336
|
+
*/
|
|
337
|
+
async pull(collections, pageSize = 200) {
|
|
338
|
+
let applied = 0;
|
|
339
|
+
// The server takes at most 20 collections per pull.
|
|
340
|
+
for (let i = 0; i < collections.length; i += 20) {
|
|
341
|
+
const names = collections.slice(i, i + 20);
|
|
342
|
+
try {
|
|
343
|
+
applied += await this.pullChanges(names);
|
|
344
|
+
}
|
|
345
|
+
catch (err) {
|
|
346
|
+
if (!(err instanceof ZveltioApiError && err.status === 403))
|
|
347
|
+
throw err;
|
|
348
|
+
applied += await this.pullPages(names, pageSize);
|
|
349
|
+
}
|
|
350
|
+
for (const name of names)
|
|
351
|
+
await this.notifyListeners(name);
|
|
352
|
+
}
|
|
353
|
+
return applied;
|
|
354
|
+
}
|
|
355
|
+
async pullChanges(names) {
|
|
356
|
+
const byTable = new Map(names.map((n) => [n.startsWith('zvd_') ? n : `zvd_${n}`, n]));
|
|
357
|
+
const cursors = (await this.store.getMeta(PULL_CURSORS)) ?? {};
|
|
358
|
+
for (const [table, name] of byTable) {
|
|
359
|
+
if (!cursors[table])
|
|
360
|
+
await this.store.dropSynced(name);
|
|
361
|
+
}
|
|
362
|
+
let applied = 0;
|
|
363
|
+
for (;;) {
|
|
364
|
+
const res = await this.client.post('/api/sync/pull', { collections: [...byTable.keys()], cursors });
|
|
365
|
+
for (const [table, flag] of Object.entries(res.resync ?? {})) {
|
|
366
|
+
const name = byTable.get(table);
|
|
367
|
+
if (flag && name)
|
|
368
|
+
await this.store.dropSynced(name);
|
|
369
|
+
}
|
|
370
|
+
for (const ch of res.changes) {
|
|
371
|
+
const name = byTable.get(ch.collection) ?? ch.collection;
|
|
372
|
+
if (ch.operation === 'delete')
|
|
373
|
+
await this.store.applyServerDelete(name, ch.id);
|
|
374
|
+
else
|
|
375
|
+
await this.store.applyServerUpdate(name, ch.id, ch.data ?? {}, Date.now());
|
|
376
|
+
applied++;
|
|
377
|
+
}
|
|
378
|
+
// Saved only after the page is applied: a pull cut short resumes here.
|
|
379
|
+
Object.assign(cursors, res.cursors);
|
|
380
|
+
await this.store.setMeta(PULL_CURSORS, cursors);
|
|
381
|
+
if (!res.hasMore)
|
|
382
|
+
return applied;
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
/** Pages through `list()`; stops on the first page that comes back short. */
|
|
386
|
+
async pullPages(collections, pageSize) {
|
|
387
|
+
let applied = 0;
|
|
388
|
+
for (const name of collections) {
|
|
389
|
+
for (let page = 1;; page++) {
|
|
390
|
+
const result = await this.client.collection(name).list({ page, limit: pageSize });
|
|
391
|
+
const rows = result?.records ?? [];
|
|
392
|
+
for (const row of rows) {
|
|
393
|
+
const id = row.id;
|
|
394
|
+
if (!id)
|
|
395
|
+
continue;
|
|
396
|
+
// `Date.now()` as the server version: the collections API does not
|
|
397
|
+
// return a version column, and the local store only compares versions
|
|
398
|
+
// to decide whether an incoming row is newer than one it already has.
|
|
399
|
+
// A server row arriving now IS newer than anything already local.
|
|
400
|
+
await this.store.applyServerUpdate(name, id, row, Date.now());
|
|
401
|
+
applied++;
|
|
402
|
+
}
|
|
403
|
+
if (rows.length < pageSize)
|
|
404
|
+
break;
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
return applied;
|
|
408
|
+
}
|
|
271
409
|
/** Status: pending operations count, conflicts count */
|
|
272
410
|
async getStatus() {
|
|
273
411
|
const pending = await this.store.getPendingOps();
|
|
@@ -278,10 +416,30 @@ export class SyncManager {
|
|
|
278
416
|
isOnline: this.isOnline,
|
|
279
417
|
};
|
|
280
418
|
}
|
|
419
|
+
/**
|
|
420
|
+
* Delete everything the local store holds — records, pending writes, blobs,
|
|
421
|
+
* pull positions — so the next user of this browser neither sees this user's
|
|
422
|
+
* data nor sends this user's queued writes under their own session. Call it
|
|
423
|
+
* after sign-out (a sync started then is refused and stores nothing); call
|
|
424
|
+
* `syncNow()` before sign-out to push what is pending, which is lost otherwise.
|
|
425
|
+
*/
|
|
426
|
+
async clearLocalData() {
|
|
427
|
+
// ponytail: polls the in-flight sync; a stored promise if it ever matters.
|
|
428
|
+
while (this.isSyncing)
|
|
429
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
430
|
+
await this.store.clear();
|
|
431
|
+
}
|
|
281
432
|
async stop() {
|
|
433
|
+
this.stopped = true;
|
|
282
434
|
if (this.syncTimer)
|
|
283
435
|
clearInterval(this.syncTimer);
|
|
436
|
+
this.syncTimer = null;
|
|
437
|
+
if (typeof window !== 'undefined') {
|
|
438
|
+
window.removeEventListener('online', this.onOnline);
|
|
439
|
+
window.removeEventListener('offline', this.onOffline);
|
|
440
|
+
}
|
|
284
441
|
this.realtime?.disconnect();
|
|
442
|
+
this.realtime = null;
|
|
285
443
|
await this.store.close();
|
|
286
444
|
}
|
|
287
445
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/testing/index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AK,MAAM,EACX,KAAK,iBAAiB,GACvB,MAAM,mBAAmB,CAAC"}
|
package/dist/testing/index.js
CHANGED
|
@@ -24,10 +24,13 @@ import { Hono } from 'hono';
|
|
|
24
24
|
* `.executeTakeFirstOrThrow()` returns a preset if matched, otherwise
|
|
25
25
|
* an empty list (for execute) or undefined.
|
|
26
26
|
*/
|
|
27
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
27
28
|
export function mockDb(presets = {}) {
|
|
28
29
|
const calls = [];
|
|
29
30
|
const presetMap = new Map(Object.entries(presets));
|
|
31
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
30
32
|
function buildChain(prefix) {
|
|
33
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
31
34
|
const proxy = new Proxy(() => { }, {
|
|
32
35
|
get(_, prop) {
|
|
33
36
|
if (typeof prop === 'symbol')
|
|
@@ -78,6 +81,7 @@ export function mockDb(presets = {}) {
|
|
|
78
81
|
});
|
|
79
82
|
return proxy;
|
|
80
83
|
}
|
|
84
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
81
85
|
return buildChain([]);
|
|
82
86
|
}
|
|
83
87
|
function matchPreset(chain, presets) {
|
|
@@ -93,7 +97,9 @@ function matchPreset(chain, presets) {
|
|
|
93
97
|
}
|
|
94
98
|
export function mockEventBus() {
|
|
95
99
|
const emitted = [];
|
|
100
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
96
101
|
const listeners = new Map();
|
|
102
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
97
103
|
const beforeHandlers = new Map();
|
|
98
104
|
return {
|
|
99
105
|
emit(event, payload) {
|
|
@@ -128,12 +134,14 @@ export function mockEventBus() {
|
|
|
128
134
|
};
|
|
129
135
|
},
|
|
130
136
|
async runBefore(event, seed) {
|
|
137
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
131
138
|
const payload = { ...seed };
|
|
132
139
|
let aborted = false;
|
|
133
140
|
let abortReason = '';
|
|
134
141
|
payload.abort = (reason) => {
|
|
135
142
|
aborted = true;
|
|
136
143
|
abortReason = reason;
|
|
144
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
137
145
|
const err = new Error(`Aborted: ${reason}`);
|
|
138
146
|
err.name = 'AbortHookError';
|
|
139
147
|
err.reason = reason;
|
|
@@ -187,8 +195,10 @@ export function mockServiceRegistry() {
|
|
|
187
195
|
}
|
|
188
196
|
// ─── Mock queryAlter / entityAccess scoped registries ──────────────────────
|
|
189
197
|
function mockQueryAlterScope() {
|
|
198
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
190
199
|
const entries = [];
|
|
191
200
|
return {
|
|
201
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
192
202
|
register(def) {
|
|
193
203
|
entries.push(def);
|
|
194
204
|
},
|
|
@@ -201,8 +211,10 @@ function mockQueryAlterScope() {
|
|
|
201
211
|
};
|
|
202
212
|
}
|
|
203
213
|
function mockEntityAccessScope() {
|
|
214
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
204
215
|
const entries = [];
|
|
205
216
|
return {
|
|
217
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
206
218
|
register(def) {
|
|
207
219
|
entries.push(def);
|
|
208
220
|
},
|
|
@@ -214,6 +226,7 @@ function mockEntityAccessScope() {
|
|
|
214
226
|
},
|
|
215
227
|
};
|
|
216
228
|
}
|
|
229
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
217
230
|
export function mockAuth(opts = {}) {
|
|
218
231
|
const user = opts.user === undefined ? { id: 'test-user', email: 'test@example.com', roles: [] } : opts.user;
|
|
219
232
|
return {
|
|
@@ -224,6 +237,7 @@ export function mockAuth(opts = {}) {
|
|
|
224
237
|
},
|
|
225
238
|
};
|
|
226
239
|
}
|
|
240
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
227
241
|
export function createTestContext(opts = {}) {
|
|
228
242
|
const db = opts.db ?? mockDb();
|
|
229
243
|
const events = opts.events ?? mockEventBus();
|
|
@@ -239,14 +253,20 @@ export function createTestContext(opts = {}) {
|
|
|
239
253
|
deserialize: (_t, v) => v,
|
|
240
254
|
serialize: (_t, v) => v,
|
|
241
255
|
},
|
|
256
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
242
257
|
events: events,
|
|
243
258
|
checkPermission: async () => true,
|
|
244
259
|
getUserRoles: async () => ['admin'],
|
|
260
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
245
261
|
DDLManager: {},
|
|
262
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
246
263
|
services: mockServiceRegistry(),
|
|
264
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
247
265
|
queryAlter: mockQueryAlterScope(),
|
|
266
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
248
267
|
entityAccess: mockEntityAccessScope(),
|
|
249
268
|
registerPublicRoute: () => { },
|
|
269
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
250
270
|
internals: {},
|
|
251
271
|
...(opts.extra ?? {}),
|
|
252
272
|
};
|
|
@@ -259,7 +279,9 @@ export function createTestContext(opts = {}) {
|
|
|
259
279
|
* mounts the sub-app at `/ext/<extension.name>` by default — same shape
|
|
260
280
|
* the engine produces in production.
|
|
261
281
|
*/
|
|
262
|
-
export async function createTestApp(
|
|
282
|
+
export async function createTestApp(
|
|
283
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
284
|
+
extension, opts = {}) {
|
|
263
285
|
const ctx = opts.ctx ?? createTestContext();
|
|
264
286
|
const strategy = extension.mountStrategy ?? 'global';
|
|
265
287
|
if (strategy === 'subapp') {
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
*/
|
|
27
27
|
import type { Kysely } from 'kysely';
|
|
28
28
|
export interface WithTestDbOptions {
|
|
29
|
-
/** Postgres image. Default: `
|
|
29
|
+
/** Postgres image. Default: `pgvector/pgvector:pg18` (the image CI and docker-compose use). */
|
|
30
30
|
image?: string;
|
|
31
31
|
/** DB name to create. Default: `zveltio_test`. */
|
|
32
32
|
database?: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"with-test-db.d.ts","sourceRoot":"","sources":["../../src/testing/with-test-db.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;
|
|
1
|
+
{"version":3,"file":"with-test-db.d.ts","sourceRoot":"","sources":["../../src/testing/with-test-db.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAGrC,MAAM,WAAW,iBAAiB;IAChC,+FAA+F;IAC/F,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,kDAAkD;IAClD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,gEAAgE;IAChE,UAAU,CAAC,EAAE,MAAM,EAAE,CAAC;IACtB;;;OAGG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B;;;OAGG;IACH,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB;AAED,MAAM,WAAW,MAAM;IACrB,8DA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Sql } from '../validate/migration-parse.js';
|
|
27
28
|
// ── Module-level reuse cache ────────────────────────────────────────────────
|
|
28
29
|
//
|
|
29
30
|
// When `reuse: true`, we keep a single container alive for the process
|
|
30
31
|
// lifetime. The first call to `withTestDb` boots it; subsequent calls open
|
|
31
32
|
// fresh DBs *inside* the same container (CREATE DATABASE per-call), so
|
|
32
33
|
// tests stay isolated without paying the container-start cost again.
|
|
34
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
33
35
|
let _sharedContainer = null;
|
|
34
|
-
let _sharedClient = null;
|
|
35
|
-
let _sharedDbCounter = 0;
|
|
36
36
|
async function loadPgContainer() {
|
|
37
37
|
try {
|
|
38
38
|
return await import('@testcontainers/postgresql');
|
|
@@ -55,7 +55,7 @@ async function loadKysely() {
|
|
|
55
55
|
* pattern, prefer `withTestDb(fn)` below.
|
|
56
56
|
*/
|
|
57
57
|
export async function startTestDb(opts = {}) {
|
|
58
|
-
const image = opts.image ?? '
|
|
58
|
+
const image = opts.image ?? 'pgvector/pgvector:pg18';
|
|
59
59
|
const database = opts.database ?? `zveltio_test_${Date.now()}_${Math.floor(Math.random() * 10_000)}`;
|
|
60
60
|
const startupTimeoutMs = opts.startupTimeoutMs ?? 60_000;
|
|
61
61
|
const tc = await loadPgContainer();
|
|
@@ -64,6 +64,7 @@ export async function startTestDb(opts = {}) {
|
|
|
64
64
|
let port;
|
|
65
65
|
let username;
|
|
66
66
|
let password;
|
|
67
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
67
68
|
let createdContainer = null;
|
|
68
69
|
if (opts.reuse && _sharedContainer) {
|
|
69
70
|
host = _sharedContainer.getHost();
|
|
@@ -87,14 +88,15 @@ export async function startTestDb(opts = {}) {
|
|
|
87
88
|
const adminPool = await openPgPool(adminConnStr);
|
|
88
89
|
try {
|
|
89
90
|
await adminPool.query(`CREATE DATABASE "${database}"`);
|
|
90
|
-
_sharedDbCounter++;
|
|
91
91
|
}
|
|
92
92
|
finally {
|
|
93
93
|
await adminPool.end();
|
|
94
94
|
}
|
|
95
95
|
const connectionString = `postgres://${username}:${password}@${host}:${port}/${database}`;
|
|
96
96
|
const pool = await openPgPool(connectionString);
|
|
97
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
97
98
|
const db = new Kysely({
|
|
99
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
98
100
|
dialect: new PostgresDialect({ pool: pool }),
|
|
99
101
|
});
|
|
100
102
|
if (opts.migrations && opts.migrations.length > 0) {
|
|
@@ -147,7 +149,11 @@ export async function startTestDb(opts = {}) {
|
|
|
147
149
|
* });
|
|
148
150
|
* });
|
|
149
151
|
*/
|
|
150
|
-
export async function withTestDb(
|
|
152
|
+
export async function withTestDb(
|
|
153
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
154
|
+
fnOrOpts,
|
|
155
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
156
|
+
maybeFn) {
|
|
151
157
|
const opts = typeof fnOrOpts === 'function' ? {} : fnOrOpts;
|
|
152
158
|
const fn = typeof fnOrOpts === 'function' ? fnOrOpts : maybeFn;
|
|
153
159
|
if (typeof fn !== 'function') {
|
|
@@ -173,10 +179,17 @@ export async function withTestDb(fnOrOpts, maybeFn) {
|
|
|
173
179
|
* const files = glob('engine/migrations/*.sql').map((p) => readFileSync(p, 'utf8'));
|
|
174
180
|
* await applyMigrationStrings(db, files);
|
|
175
181
|
*/
|
|
182
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
176
183
|
export async function applyMigrationStrings(db, sqlStrings) {
|
|
177
184
|
const { sql } = await loadKysely();
|
|
178
185
|
for (const raw of sqlStrings) {
|
|
179
|
-
|
|
186
|
+
// Only the UP half. A Zveltio migration keeps its rollback in the same file
|
|
187
|
+
// behind a `-- DOWN` marker, and the runner that applies it in production
|
|
188
|
+
// splits on that marker — this helper did not, so the documented example
|
|
189
|
+
// (glob `engine/migrations/*.sql`, hand them all to this function) created
|
|
190
|
+
// the schema and then dropped it again, in the same call. Every assertion
|
|
191
|
+
// after it failed on a table that had existed a statement earlier.
|
|
192
|
+
const statements = splitStatements(parseMigrationSql(raw).up);
|
|
180
193
|
for (const stmt of statements) {
|
|
181
194
|
const trimmed = stmt.trim();
|
|
182
195
|
if (!trimmed)
|
|
@@ -189,6 +202,7 @@ export async function applyMigrationStrings(db, sqlStrings) {
|
|
|
189
202
|
* Same as `applyMigrationStrings` but takes file paths. Reads each file
|
|
190
203
|
* synchronously, applies in order. Bun-native — uses `Bun.file()`.
|
|
191
204
|
*/
|
|
205
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
192
206
|
export async function applyMigrationFiles(db, paths) {
|
|
193
207
|
// Bun.file().text() returns a Promise<string>.
|
|
194
208
|
const contents = await Promise.all(paths.map((p) => Bun.file(p).text()));
|
|
@@ -200,15 +214,6 @@ export async function applyMigrationFiles(db, paths) {
|
|
|
200
214
|
* reuse container is active.
|
|
201
215
|
*/
|
|
202
216
|
export async function stopReusedTestDb() {
|
|
203
|
-
if (_sharedClient) {
|
|
204
|
-
try {
|
|
205
|
-
await _sharedClient.end();
|
|
206
|
-
}
|
|
207
|
-
catch {
|
|
208
|
-
/* */
|
|
209
|
-
}
|
|
210
|
-
_sharedClient = null;
|
|
211
|
-
}
|
|
212
217
|
if (_sharedContainer) {
|
|
213
218
|
try {
|
|
214
219
|
await _sharedContainer.stop();
|
|
@@ -221,12 +226,14 @@ export async function stopReusedTestDb() {
|
|
|
221
226
|
}
|
|
222
227
|
// ── Internals ───────────────────────────────────────────────────────────────
|
|
223
228
|
/** Open a pg connection pool. Uses `pg` (peer dep with testcontainers). */
|
|
229
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
224
230
|
async function openPgPool(connectionString) {
|
|
225
231
|
const pg = await import('pg').catch(() => {
|
|
226
232
|
throw new Error(`withTestDb requires the 'pg' npm package. Install it alongside testcontainers:\n` +
|
|
227
233
|
` bun add -d testcontainers pg @types/pg`);
|
|
228
234
|
});
|
|
229
235
|
// pg's Pool — the Kysely PostgresDialect accepts this directly.
|
|
236
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
230
237
|
return new pg.Pool({ connectionString });
|
|
231
238
|
}
|
|
232
239
|
/**
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"action-refusal.test.d.ts","sourceRoot":"","sources":["../../src/tests/action-refusal.test.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { describe, expect, it } from 'bun:test';
|
|
2
|
+
import { ACTION_REFUSAL, ActionRefusal } from '../extension/action-refusal.js';
|
|
3
|
+
// extension-api v1: the engine recognises a refusal by this registered key,
|
|
4
|
+
// not by `instanceof` (each extension bundles its own SDK copy). Changing the
|
|
5
|
+
// key silently turns every v1 extension's refusal into a 500.
|
|
6
|
+
describe('ActionRefusal (extension-api v1)', () => {
|
|
7
|
+
it('marks itself with the registered key the engine reads', () => {
|
|
8
|
+
expect(ACTION_REFUSAL).toBe(Symbol.for('zveltio.extension.action-refusal'));
|
|
9
|
+
const r = new ActionRefusal(409, 'already_paid', 'Invoice already paid');
|
|
10
|
+
expect(r[ACTION_REFUSAL]).toBe(true);
|
|
11
|
+
expect([r.status, r.code, r.message]).toEqual([409, 'already_paid', 'Invoice already paid']);
|
|
12
|
+
});
|
|
13
|
+
});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.test.d.ts","sourceRoot":"","sources":["../../src/tests/client.test.ts"],"names":[],"mappings":""}
|