@syncular/tauri 0.58.0 → 0.60.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/dist/remote.js CHANGED
@@ -1,982 +1,120 @@
1
- import { ProgressEmitter, } from '@syncular/client';
2
- // -- Types the bridge speaks (structurally the web-client's) -----------------
3
- // Most imports stay type-only; the stable preflight error code is shared at
4
- // runtime so every host surfaces byte-identical policy evidence.
5
- import { decodeLocalDataRebootstrapResult, decodePreviousVersionAuditResult, decodePreviousVersionDiscardResult, decodePreviousVersionSnapshot, SECURITY_PREFLIGHT_REQUIRED_CODE, withClientDiagnosticsHost, } from '@syncular/client';
6
- /** The plugin's Tauri event name — mirror of `tauri-plugin-syncular`. */
7
- export const SYNCULAR_EVENT = 'syncular://event';
1
+ import { NativeBridgeClient, NativeSyncError, nativeCreateParams, } from '@syncular/client/native-bridge';
8
2
  const PLUGIN = 'plugin:syncular|';
9
- function isBytesEnvelope(value) {
10
- if (typeof value !== 'object' || value === null)
11
- return false;
12
- const record = value;
13
- return (Object.keys(record).length === 1 &&
14
- typeof record.$bytes === 'string' &&
15
- /^(?:[0-9a-fA-F]{2})*$/.test(record.$bytes));
16
- }
17
- /**
18
- * §7.1: a host reply that carries an envelope-shaped object with a malformed
19
- * body is refused, never padded into different bytes. Objects without a
20
- * `$bytes` key keep the defensive JSON text round-trip below.
21
- */
22
- function assertBytesEnvelope(value) {
23
- if (typeof value !== 'object' || value === null || !('$bytes' in value))
24
- return;
25
- if (!isBytesEnvelope(value))
26
- throw new TauriSyncError('sync.invalid_request', 'a $bytes envelope requires exactly one $bytes key holding an even-length hexadecimal string');
27
- }
28
- function isBigIntEnvelope(value) {
29
- return (typeof value === 'object' &&
30
- value !== null &&
31
- typeof value.$bigint === 'string');
32
- }
33
- function bytesToHex(bytes) {
34
- let out = '';
35
- for (const b of bytes) {
36
- out += b.toString(16).padStart(2, '0');
37
- }
38
- return out;
39
- }
40
- function hexToBytes(hex) {
41
- if (!/^(?:[0-9a-fA-F]{2})*$/.test(hex))
42
- throw new TauriSyncError('sync.invalid_request', 'a $bytes envelope requires an even-length hexadecimal string');
43
- const out = new Uint8Array(hex.length / 2);
44
- for (let i = 0; i < out.length; i++) {
45
- out[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
46
- }
47
- return out;
48
- }
49
- /** Encode an SQL param for the command JSON (bytes → `{$bytes: hex}`). */
50
- function encodeParam(value) {
51
- if (value instanceof Uint8Array)
52
- return { $bytes: bytesToHex(value) };
53
- if (typeof value === 'bigint')
54
- return { $bigint: value.toString() };
55
- return value;
56
- }
57
- function encodeJsonValue(value) {
58
- if (value instanceof Uint8Array)
59
- return { $bytes: bytesToHex(value) };
60
- if (typeof value === 'bigint')
61
- return { $bigint: value.toString() };
62
- if (Array.isArray(value))
63
- return value.map(encodeJsonValue);
64
- if (value !== null && typeof value === 'object') {
65
- const encoded = {};
66
- for (const [key, member] of Object.entries(value)) {
67
- encoded[key] = encodeJsonValue(member);
68
- }
69
- return encoded;
70
- }
71
- return value;
72
- }
73
- function encodeEncryption(config) {
74
- return {
75
- keys: Object.fromEntries(Object.entries(config.keys).map(([keyId, key]) => [
76
- keyId,
77
- { $bytes: bytesToHex(key) },
78
- ])),
79
- ...(config.keyIdColumns !== undefined
80
- ? { keyIdColumns: config.keyIdColumns }
81
- : {}),
82
- };
83
- }
84
- /** Decode one query-result cell back to an `SqlValue` (`{$bytes}` → bytes). */
85
- function decodeCell(value) {
86
- assertBytesEnvelope(value);
87
- if (isBytesEnvelope(value))
88
- return hexToBytes(value.$bytes);
89
- if (isBigIntEnvelope(value))
90
- return BigInt(value.$bigint);
91
- if (value === null ||
92
- typeof value === 'string' ||
93
- typeof value === 'number' ||
94
- typeof value === 'boolean') {
95
- return value;
96
- }
97
- // Objects/arrays that are not the bytes envelope round-trip as their JSON
98
- // string (SQLite json columns arrive as text already; this is defensive).
99
- return JSON.stringify(value);
100
- }
101
- /** Decode one native outcome row image. Only the `{$bytes}` envelope is
102
- * honored; operation `values` stay `JsonRowValue` and are not passed here. */
103
- function decodeOutcomeRow(row) {
104
- const out = {};
105
- for (const [key, value] of Object.entries(row)) {
106
- // Reserved `_sync_*` columns stay engine-internal, matching `decodeRow`.
107
- if (key.startsWith('_sync_'))
108
- continue;
109
- assertBytesEnvelope(value);
110
- if (value === null ||
111
- typeof value === 'string' ||
112
- typeof value === 'number' ||
113
- typeof value === 'boolean') {
114
- out[key] = value;
115
- }
116
- else if (isBytesEnvelope(value)) {
117
- out[key] = hexToBytes(value.$bytes);
118
- }
119
- else {
120
- out[key] = JSON.stringify(value);
121
- }
122
- }
123
- return out;
124
- }
125
- function decodeRetainedRows(rows) {
126
- return rows.map((row) => ({
127
- ...row,
128
- localRow: row.localRow === null ? null : decodeOutcomeRow(row.localRow),
129
- serverRow: row.serverRow === null ? null : decodeOutcomeRow(row.serverRow),
130
- ...(row.uniqueConflicts !== undefined
131
- ? {
132
- uniqueConflicts: row.uniqueConflicts.map((conflict) => ({
133
- ...conflict,
134
- serverRow: decodeOutcomeRow(conflict.serverRow),
135
- })),
136
- }
137
- : {}),
138
- }));
139
- }
140
- /** Decode the row images a native `CommitOutcome` carries: conflict server
141
- * rows and retained-row images. */
142
- function decodeCommitOutcome(outcome) {
143
- return {
144
- ...outcome,
145
- results: outcome.results.map((result) => result.status === 'conflict'
146
- ? {
147
- ...result,
148
- conflict: {
149
- ...result.conflict,
150
- serverRow: decodeOutcomeRow(result.conflict.serverRow),
151
- },
152
- }
153
- : result),
154
- ...(outcome.retainedRows !== undefined
155
- ? {
156
- retainedRows: decodeRetainedRows(outcome.retainedRows),
157
- }
158
- : {}),
159
- };
160
- }
161
- /** @internal Shared native row codec. */
162
- export function decodeRow(row) {
163
- const out = {};
164
- for (const [key, value] of Object.entries(row)) {
165
- // Reserved `_sync_*` columns stay engine-internal (parity with the
166
- // web client's `query()`), so a `SELECT *` row round-trips straight
167
- // into `mutate()` values. Alias (`_sync_version AS v`) to read one.
168
- if (key.startsWith('_sync_'))
169
- continue;
170
- out[key] = decodeCell(value);
171
- }
172
- return out;
173
- }
174
- /**
175
- * Decode the JSON cell envelopes in an RFC 0005 snapshot reply's rows before
176
- * the strict bridge decoder sees them; a malformed reply is passed through
177
- * untouched so `decodePreviousVersionSnapshot` rejects it.
178
- */
179
- function decodeSnapshotRows(value) {
180
- if (value === null || typeof value !== 'object' || Array.isArray(value)) {
181
- return value;
182
- }
183
- const source = value;
184
- if (!Array.isArray(source.rows))
185
- return value;
186
- return {
187
- ...source,
188
- rows: source.rows.map((row) => row !== null && typeof row === 'object' && !Array.isArray(row)
189
- ? decodeRow(row)
190
- : row),
191
- };
3
+ /** The error a `{error}` reply surfaces (mirrors the web-client `ClientSyncError`). */
4
+ export class TauriSyncError extends NativeSyncError {
5
+ name = 'TauriSyncError';
192
6
  }
193
7
  /** Resolve the Tauri primitives from the ambient environment when not injected. */
194
8
  async function resolveTauri(injected) {
195
9
  if (injected !== undefined)
196
10
  return injected;
197
11
  // Prefer the ambient global (present when `withGlobalTauri` is enabled).
198
- const ambient = globalThis.__TAURI__;
199
- if (ambient?.core?.invoke && ambient.event?.listen) {
200
- return {
201
- invoke: ambient.core.invoke.bind(ambient.core),
202
- listen: ambient.event.listen.bind(ambient.event),
203
- };
204
- }
205
- // Fall back to the ESM package (the common path). These must remain literal,
206
- // bundler-visible specifiers: hiding a bare package import behind
12
+ // Otherwise use the ESM package (the common path). The specifier must remain
13
+ // literal and bundler-visible: hiding a bare package import behind
207
14
  // `@vite-ignore` makes WebKit resolve it as a URL at runtime instead of
208
15
  // letting Vite/Bun include the Tauri API in the webview bundle.
209
- const [core, event] = await Promise.all([
210
- import('@tauri-apps/api/core'),
211
- import('@tauri-apps/api/event'),
212
- ]);
213
- return { invoke: core.invoke, listen: event.listen };
16
+ const ambient = globalThis
17
+ .__TAURI__?.core;
18
+ const core = ambient?.invoke !== undefined && ambient.Channel !== undefined
19
+ ? { invoke: ambient.invoke.bind(ambient), Channel: ambient.Channel }
20
+ : await import('@tauri-apps/api/core');
21
+ return {
22
+ invoke: core.invoke,
23
+ channel: (onMessage) => {
24
+ const channel = new core.Channel();
25
+ channel.onmessage = onMessage;
26
+ return channel;
27
+ },
28
+ };
214
29
  }
215
- /**
216
- * The webview-side proxy implementing `SyncClientLike` over the plugin. Every
217
- * snapshot method returns a promise from an IPC round trip. React hooks accept
218
- * the canonical snapshot interface directly.
219
- */
220
- export class TauriSyncClient {
30
+ /** The webview-side proxy implementing `SyncClientLike` over the plugin. */
31
+ export class TauriSyncClient extends NativeBridgeClient {
221
32
  #tauri;
222
- #invalidationListeners = new Set();
223
- #changeListeners = new Set();
224
- #progress = new ProgressEmitter();
225
- #diagnosticsListeners = new Set();
226
- #presenceListeners = new Set();
227
- #unlisten;
228
- #closed = false;
229
- #closing;
230
- #securityLifecycle;
231
- #preflightBarrier;
232
33
  #diagnosticsEnabled = false;
233
34
  /** @internal — use {@link createTauriSyncClient}. */
234
- constructor(tauri, unlisten, securityLifecycle = 'active') {
35
+ constructor(tauri, release, securityLifecycle = 'active') {
36
+ super('tauri', TauriSyncError, release, securityLifecycle);
235
37
  this.#tauri = tauri;
236
- this.#unlisten = unlisten;
237
- this.#securityLifecycle = securityLifecycle;
238
- }
239
- /** Dispatch a `syncular_command` and unwrap `{result}` / throw on `{error}`. */
240
- async #command(method, params) {
241
- this.#requireOpen();
242
- if (this.#securityLifecycle === 'preflight' &&
243
- ![
244
- 'authoritySnapshot',
245
- 'securityLifecycle',
246
- 'beginSecurityPreflight',
247
- 'activateSecurity',
248
- 'setTransportEnabled',
249
- 'purgeLocalData',
250
- 'previousVersionDiscard',
251
- 'localRevision',
252
- 'statusSnapshot',
253
- 'shutdown',
254
- ].includes(method) &&
255
- !this.allowPreflightCommand(method)) {
256
- this.#throwSecurityPreflight();
257
- }
258
- const reply = await this.#tauri.invoke(`${PLUGIN}syncular_command`, { command: { method, params } });
259
- if (reply.error !== undefined) {
260
- throw new TauriSyncError(reply.error.code, reply.error.message, reply.error.details ?? undefined, reply.error.retryable ?? false);
261
- }
262
- return reply.result;
263
- }
264
- #throwSecurityPreflight() {
265
- throw new TauriSyncError(SECURITY_PREFLIGHT_REQUIRED_CODE, 'the local replica is in security preflight; complete quarantine checks and call activateSecurity before accessing protected data');
266
- }
267
- #requireOpen() {
268
- if (this.#closed) {
269
- throw new TauriSyncError('client.closed', 'the Tauri sync client is closed');
270
- }
271
- }
272
- /** @internal Shared command gate for explicit bridge extensions. */
273
- command(method, params) {
274
- return this.#command(method, params);
275
- }
276
- /** @internal Additional preflight operations supplied by bridge extensions. */
277
- allowPreflightCommand(_method) {
278
- return false;
279
- }
280
- /** @internal Recheck local close after an extension's asynchronous reply. */
281
- requireOpen() {
282
- this.#requireOpen();
283
38
  }
284
- #requireActive() {
285
- this.#requireOpen();
286
- if (this.#securityLifecycle === 'preflight')
287
- this.#throwSecurityPreflight();
288
- }
289
- /** @internal — fan an incoming plugin event out to the local listeners. */
290
- __dispatchEvent(event) {
291
- switch (event.type) {
292
- case 'progress': {
293
- this.#progress.emit(event.progress);
294
- break;
295
- }
296
- case 'change': {
297
- const batch = decodeChangeBatch(event.batch);
298
- if (batch === undefined)
299
- break;
300
- for (const listener of this.#changeListeners) {
301
- try {
302
- listener(batch);
303
- }
304
- catch {
305
- /* a UI listener must never break event dispatch */
306
- }
307
- }
308
- const payload = invalidationFromChange(batch);
309
- if (payload === undefined)
310
- break;
311
- for (const listener of this.#invalidationListeners) {
312
- try {
313
- listener(payload);
314
- }
315
- catch {
316
- /* a UI listener must never break event dispatch */
317
- }
318
- }
319
- break;
320
- }
321
- case 'presence': {
322
- const scopeKey = typeof event.scopeKey === 'string' ? event.scopeKey : '';
323
- for (const listener of this.#presenceListeners) {
324
- try {
325
- listener(scopeKey);
326
- }
327
- catch {
328
- /* never break dispatch */
329
- }
330
- }
331
- break;
332
- }
333
- case 'diagnostics': {
334
- const snapshot = decodeDiagnosticsSnapshot(event.snapshot, 'tauri');
335
- if (snapshot === undefined)
336
- break;
337
- for (const listener of this.#diagnosticsListeners) {
338
- try {
339
- listener(snapshot);
340
- }
341
- catch {
342
- /* a diagnostics observer must never break event dispatch */
343
- }
344
- }
345
- break;
346
- }
347
- default:
348
- // Unknown extension events are deliberately ignored. All durable
349
- // observable state arrives in the revisioned `change` batch.
350
- break;
351
- }
352
- }
353
- // -- SyncClientLike --------------------------------------------------------
354
- async securityLifecycle() {
355
- this.#requireOpen();
356
- return Promise.resolve(this.#securityLifecycle);
357
- }
358
- beginSecurityPreflight() {
359
- if (this.#closed) {
360
- return Promise.reject(new TauriSyncError('client.closed', 'the Tauri sync client is closed'));
361
- }
362
- if (this.#preflightBarrier !== undefined)
363
- return this.#preflightBarrier;
364
- // Flip synchronously so a same-webview query cannot race the IPC barrier.
365
- this.#securityLifecycle = 'preflight';
366
- const barrier = this.#command('beginSecurityPreflight', {}).then(() => { });
367
- this.#preflightBarrier = barrier;
368
- void barrier.then(() => {
369
- if (this.#preflightBarrier === barrier)
370
- this.#preflightBarrier = undefined;
371
- }, () => {
372
- if (this.#preflightBarrier === barrier)
373
- this.#preflightBarrier = undefined;
39
+ send(method, params) {
40
+ return this.#tauri.invoke(`${PLUGIN}syncular_command`, {
41
+ command: { method, params },
374
42
  });
375
- return barrier;
376
43
  }
377
- /**
378
- * Complete the security preflight. `headers` optionally carries a fresh
379
- * FULL transport header set that the native host applies atomically with
380
- * the activation, before the startup sync it enqueues — so a preflight
381
- * that outlives the boot token starts its first round with valid
382
- * credentials (the direct `setHeaders` path stays refused while gated).
383
- */
384
- async activateSecurity(options = {}) {
385
- this.#requireOpen();
386
- if (this.#securityLifecycle === 'active') {
387
- throw new TauriSyncError('sync.invalid_request', 'activateSecurity requires the client to be in security preflight');
388
- }
389
- await this.#preflightBarrier;
390
- await this.#command('activateSecurity', {
391
- ...(options.encryption !== undefined
392
- ? { encryption: encodeEncryption(options.encryption) }
393
- : {}),
394
- ...(options.headers !== undefined ? { headers: options.headers } : {}),
395
- });
396
- this.#securityLifecycle = 'active';
44
+ sendQuery(sql, params) {
45
+ return this.#tauri.invoke(`${PLUGIN}syncular_query`, { sql, params });
397
46
  }
398
- onInvalidate(listener) {
399
- this.#requireOpen();
400
- this.#invalidationListeners.add(listener);
401
- return () => this.#invalidationListeners.delete(listener);
47
+ sendQuerySnapshot(params) {
48
+ return this.#tauri.invoke(`${PLUGIN}syncular_query_snapshot`, params);
402
49
  }
403
- onProgress(listener) {
404
- this.#requireOpen();
405
- return this.#progress.on(listener);
50
+ sendHeaders(headers) {
51
+ return this.#tauri.invoke(`${PLUGIN}syncular_set_headers`, { headers });
406
52
  }
407
- progressSnapshot() {
408
- this.#requireOpen();
409
- return this.#progress.snapshot();
410
- }
411
- onChange(listener) {
412
- this.#requireOpen();
413
- this.#changeListeners.add(listener);
414
- return () => this.#changeListeners.delete(listener);
415
- }
416
- onDiagnostics(listener) {
417
- this.#requireOpen();
418
- this.#diagnosticsListeners.add(listener);
419
- this.#enableDiagnosticsPush();
420
- return () => this.#diagnosticsListeners.delete(listener);
421
- }
422
- /**
423
- * Host-local push registration: the native core emits pushed diagnostics
424
- * snapshots only once a consumer is known (a `diagnosticsSnapshot` pull, or
425
- * this explicit `enableDiagnostics` signal). Fired once, on the first
426
- * registered listener, fire-and-forget. The invoke deliberately bypasses
427
- * the bridge's preflight gate — the command is a pure observability
428
- * registration handled before dispatch, and the native side stays silent
429
- * until activation anyway. Errors are tolerated: an older native core
430
- * rejects the unknown command, and the mount-time snapshot pull path keeps
431
- * `useDiagnostics` working there.
432
- */
433
- #enableDiagnosticsPush() {
434
- if (this.#diagnosticsEnabled || this.#closed)
435
- return;
436
- this.#diagnosticsEnabled = true;
437
- void this.#tauri
438
- .invoke(`${PLUGIN}syncular_command`, {
439
- command: { method: 'enableDiagnostics', params: {} },
440
- })
441
- .catch(() => {
442
- /* fire-and-forget; an error reply is equally ignored above */
443
- });
444
- }
445
- onPresence(listener) {
446
- this.#requireOpen();
447
- this.#presenceListeners.add(listener);
448
- return () => this.#presenceListeners.delete(listener);
449
- }
450
- async query(sql, params) {
451
- this.#requireActive();
452
- const reply = await this.#tauri.invoke(`${PLUGIN}syncular_query`, { sql, params: (params ?? []).map(encodeParam) });
453
- if (reply.error !== undefined) {
454
- throw new TauriSyncError(reply.error.code, reply.error.message, reply.error.details ?? undefined, reply.error.retryable ?? false);
455
- }
456
- const rows = reply.result.rows ?? [];
457
- return rows.map((r) => decodeRow(r));
458
- }
459
- async querySnapshot(spec) {
460
- this.#requireActive();
461
- const reply = await this.#tauri.invoke(`${PLUGIN}syncular_query_snapshot`, {
462
- sql: spec.sql,
463
- params: (spec.params ?? []).map(encodeParam),
464
- coverage: spec.coverage ?? [],
465
- ...(spec.owner !== undefined ? { owner: spec.owner } : {}),
466
- });
467
- if (reply.error !== undefined) {
468
- throw new TauriSyncError(reply.error.code, reply.error.message, reply.error.details ?? undefined, reply.error.retryable ?? false);
469
- }
470
- const result = reply.result;
471
- return {
472
- revision: BigInt(result.revision),
473
- rows: result.rows.map(decodeRow),
474
- coverage: result.coverage,
475
- };
476
- }
477
- async localRevision() {
478
- const result = (await this.#command('localRevision', {}));
479
- return BigInt(result.revision);
53
+ /** Shut down the native core and release its keyring. */
54
+ async shutdown() {
55
+ await this.command('shutdown', {});
480
56
  }
481
57
  /**
482
- * §7.5: one atomic read over the file-backed sidecar. Every statement and
483
- * every catch-up/delivery read shares one revision (a `bigint`, matching
484
- * `querySnapshot`) and one read transaction; every query row is decoded.
58
+ * The native core pushes diagnostics snapshots only once a consumer is
59
+ * known (a `diagnosticsSnapshot` pull, or this `enableDiagnostics` signal).
60
+ * The first listener sends it once, fire-and-forget and outside the
61
+ * preflight gate: it is a pure observability registration, and the native
62
+ * side stays silent until activation. An error is tolerated, because the
63
+ * mount-time snapshot pull keeps `useDiagnostics` working without it.
485
64
  */
486
- async snapshotRead(request) {
487
- this.#requireActive();
488
- const reply = await this.#tauri.invoke(`${PLUGIN}syncular_snapshot_read`, {
489
- statements: request.statements.map((statement) => ({
490
- sql: statement.sql,
491
- params: (statement.params ?? []).map(encodeParam),
492
- })),
493
- coverage: request.coverage ?? [],
494
- subscriptions: request.subscriptions ?? [],
495
- commitIds: request.commitIds ?? [],
496
- ...(request.owner !== undefined ? { owner: request.owner } : {}),
497
- });
498
- if (reply.error !== undefined) {
499
- throw new TauriSyncError(reply.error.code, reply.error.message, reply.error.details ?? undefined, reply.error.retryable ?? false);
65
+ onDiagnostics(listener) {
66
+ const off = super.onDiagnostics(listener);
67
+ if (!this.#diagnosticsEnabled) {
68
+ this.#diagnosticsEnabled = true;
69
+ void this.send('enableDiagnostics', {}).catch(() => { });
500
70
  }
501
- const result = reply.result;
502
- return {
503
- revision: BigInt(result.revision),
504
- queries: result.queries.map((rows) => rows.map(decodeRow)),
505
- coverage: result.coverage,
506
- subscriptions: result.subscriptions,
507
- deliveries: result.deliveries.map((delivery) => delivery.status === 'known'
508
- ? { ...delivery, outcome: decodeCommitOutcome(delivery.outcome) }
509
- : delivery),
510
- };
511
- }
512
- async statusSnapshot() {
513
- return (await this.#command('statusSnapshot', {}));
514
- }
515
- async diagnosticsSnapshot(request = {}) {
516
- const snapshot = (await this.#command('diagnosticsSnapshot', {
517
- expectedSubscriptions: request.expectedSubscriptions ?? [],
518
- }));
519
- return withClientDiagnosticsHost(snapshot, {
520
- ...snapshot.host,
521
- kind: 'tauri',
522
- role: 'single',
523
- });
524
- }
525
- async mutate(mutations) {
526
- const result = (await this.#command('mutate', {
527
- mutations: mutations.map(encodeMutation),
528
- }));
529
- return result.clientCommitId;
530
- }
531
- async patch(table, rowId, partial, options) {
532
- const result = (await this.#command('patch', {
533
- table,
534
- rowId,
535
- partial: encodeJsonValue(partial),
536
- ...(options?.baseVersion !== undefined
537
- ? { baseVersion: options.baseVersion }
538
- : {}),
539
- }));
540
- return result.clientCommitId;
541
- }
542
- async purgeLocalData(input) {
543
- return (await this.#command('purgeLocalData', {
544
- input,
545
- }));
546
- }
547
- async rebootstrapLocalData(input) {
548
- return decodeLocalDataRebootstrapResult(await this.#command('rebootstrapLocalData', { input }));
549
- }
550
- async previousVersionSnapshot(spec) {
551
- return decodePreviousVersionSnapshot(decodeSnapshotRows(await this.#command('previousVersionSnapshot', { spec })));
552
- }
553
- async previousVersionAudit() {
554
- return decodePreviousVersionAuditResult(await this.#command('previousVersionAudit', {}));
555
- }
556
- async previousVersionDiscard() {
557
- return decodePreviousVersionDiscardResult(await this.#command('previousVersionDiscard', {}));
71
+ return off;
558
72
  }
559
73
  /** Suspend new network work while retaining local access and queued commits. */
560
74
  async setTransportEnabled(enabled) {
561
- await this.#command('setTransportEnabled', { enabled });
75
+ await this.command('setTransportEnabled', { enabled });
562
76
  }
563
77
  /** Browser offline-control parity; local reads and commits remain available. */
564
78
  async setOffline(offline) {
565
79
  await this.setTransportEnabled(!offline);
566
80
  }
567
- /**
568
- * Replace the native transport's request headers at runtime — the auth
569
- * rotation path. Pass the FULL header set (it replaces,
570
- * it does not merge). HTTP requests use the new set from the next call;
571
- * the realtime socket applies it on its next (re)connect.
572
- */
573
- async setHeaders(headers) {
574
- this.#requireActive();
575
- const reply = await this.#tauri.invoke(`${PLUGIN}syncular_set_headers`, { headers });
576
- if (reply.error !== undefined) {
577
- throw new TauriSyncError(reply.error.code, reply.error.message, reply.error.details ?? undefined, reply.error.retryable ?? false);
578
- }
579
- }
580
- // -- Native CRDT (SPEC.md §5.10.5; needs the plugin `crdt-yjs` feature) ------
581
- /** Materialize a `crdt` column's collaborative text — decoded from the
582
- * stored (server-merged) Yjs bytes. `name` selects the shared text
583
- * (default `"text"`). An absent row / NULL column is the empty document. */
584
- async crdtText(table, rowId, column, name = 'text') {
585
- const result = (await this.#command('crdtText', {
586
- table,
587
- rowId,
588
- column,
589
- name,
590
- }));
591
- return result.text;
592
- }
593
- /** Insert `value` at UTF-16 offset `index` in a `crdt` column's text and
594
- * push the resulting Yjs update (baseVersion-less). Returns the commit id. */
595
- async crdtInsertText(table, rowId, column, index, value, name = 'text') {
596
- const result = (await this.#command('crdtInsertText', {
597
- table,
598
- rowId,
599
- column,
600
- name,
601
- index,
602
- value,
603
- }));
604
- return result.clientCommitId;
605
- }
606
- /** Delete `len` UTF-16 code units at `index` in a `crdt` column's text. */
607
- async crdtDeleteText(table, rowId, column, index, len, name = 'text') {
608
- const result = (await this.#command('crdtDeleteText', {
609
- table,
610
- rowId,
611
- column,
612
- name,
613
- index,
614
- len,
615
- }));
616
- return result.clientCommitId;
617
- }
618
- /** Escape hatch: apply an arbitrary Yjs update onto a `crdt` column. */
619
- async crdtApplyUpdate(table, rowId, column, update) {
620
- const result = (await this.#command('crdtApplyUpdate', {
621
- table,
622
- rowId,
623
- column,
624
- update: { $bytes: bytesToHex(update) },
625
- }));
626
- return result.clientCommitId;
627
- }
628
- /**
629
- * Stage a blob for attachment (§5.9.7) and return the canonical `BlobRef`
630
- * string to store in a `blob_ref` column. The native core owns the upload
631
- * queue; write the referencing row after this resolves (§5.9.3).
632
- */
633
- async uploadBlob(bytes, options) {
634
- const result = (await this.#command('uploadBlob', {
635
- bytes: { $bytes: bytesToHex(bytes) },
636
- ...(options?.mediaType !== undefined
637
- ? { mediaType: options.mediaType }
638
- : {}),
639
- ...(options?.name !== undefined ? { name: options.name } : {}),
640
- }));
641
- return result.ref;
642
- }
643
- /**
644
- * Resolve blob bytes for a `blob_ref` column value or a bare `blobId`
645
- * (§5.9.7): the native core serves a local cache hit and otherwise
646
- * downloads and verifies the content address.
647
- */
648
- async fetchBlob(ref) {
649
- const result = (await this.#command('fetchBlob', { blob: ref }));
650
- const bytes = result.blob.bytes;
651
- if (!isBytesEnvelope(bytes))
652
- throw new TauriSyncError('sync.invalid_request', 'fetchBlob reply carried no $bytes envelope');
653
- return {
654
- blobId: result.blob.blobId,
655
- byteLength: result.blob.byteLength,
656
- bytes: hexToBytes(bytes.$bytes),
657
- ...(result.blob.mediaType !== undefined
658
- ? { mediaType: result.blob.mediaType }
659
- : {}),
660
- };
661
- }
662
- async subscribe(input) {
663
- await this.#command('subscribe', {
664
- id: input.id,
665
- table: input.table,
666
- scopes: input.scopes ?? {},
667
- ...(input.params !== undefined ? { params: input.params } : {}),
668
- });
669
- }
670
- /** Register several subscriptions in one local transaction. */
671
- async subscribeMany(inputs) {
672
- await this.#command('subscribeMany', {
673
- subscriptions: inputs.map((input) => ({
674
- id: input.id,
675
- table: input.table,
676
- scopes: input.scopes ?? {},
677
- ...(input.params !== undefined ? { params: input.params } : {}),
678
- })),
679
- });
680
- }
681
- async unsubscribe(id) {
682
- await this.#command('unsubscribe', { id });
683
- }
684
- async setWindow(base, units) {
685
- await this.#command('setWindow', {
686
- base: base,
687
- units: units,
688
- });
689
- }
690
- async windowState(base) {
691
- const result = (await this.#command('windowState', {
692
- base: base,
693
- }));
694
- return { units: result.units, pending: result.pending };
695
- }
696
- async sync() {
697
- return this.#command('sync', {});
698
- }
699
81
  /**
700
82
  * Rotate the client id (§1.5) after a `sync.invalid_client_id` refusal
701
83
  * (`recommendedAction: resetClientId`). The next round carries the new id;
702
84
  * the replica and outbox stay in place.
703
85
  */
704
86
  async resetClientId() {
705
- const result = (await this.#command('resetClientId', {}));
87
+ const result = (await this.command('resetClientId', {}));
706
88
  return result.clientId;
707
89
  }
708
- async syncUntilIdle(maxRounds) {
709
- return this.#command('syncUntilIdle', {
710
- ...(maxRounds !== undefined ? { maxRounds } : {}),
711
- });
712
- }
713
- async proveCurrentBase(outcome, maxRounds) {
714
- if (maxRounds !== undefined &&
715
- (!Number.isInteger(maxRounds) || maxRounds < 1 || maxRounds > 0xffffffff))
716
- throw new TauriSyncError('sync.invalid_request', 'maxRounds must be a positive integer');
717
- const proof = (await this.#command('proveCurrentBase', {
718
- outcome: {
719
- clientCommitId: outcome.clientCommitId,
720
- sequence: outcome.sequence,
721
- },
722
- ...(maxRounds !== undefined ? { maxRounds } : {}),
723
- }));
724
- return proof.proven
725
- ? { proven: true, rows: decodeRetainedRows(proof.rows) }
726
- : proof;
727
- }
728
- async conflicts() {
729
- const result = (await this.#command('conflicts', {}));
730
- return result.conflicts;
731
- }
732
- async rejections() {
733
- const result = (await this.#command('rejections', {}));
734
- return result.rejections;
735
- }
736
- async commitOutcome(clientCommitId) {
737
- const result = (await this.#command('commitOutcome', {
738
- clientCommitId,
739
- }));
740
- return result.outcome === undefined
741
- ? undefined
742
- : decodeCommitOutcome(result.outcome);
743
- }
744
- async commitOutcomes(query = {}) {
745
- const result = (await this.#command('commitOutcomes', { query }));
746
- return result.outcomes.map(decodeCommitOutcome);
747
- }
748
- async resolveCommitOutcome(input) {
749
- const result = (await this.#command('resolveCommitOutcome', {
750
- input,
751
- }));
752
- return decodeCommitOutcome(result.outcome);
753
- }
754
- async pendingCommits() {
755
- const result = (await this.#command('pendingCommitIds', {}));
756
- return result.ids;
757
- }
758
- async presence(scopeKey) {
759
- const result = (await this.#command('presence', { scopeKey }));
760
- return result.peers;
761
- }
762
- async setPresence(scopeKey, doc) {
763
- await this.#command('setPresence', { scopeKey, doc });
764
- }
765
- async connectRealtime() {
766
- await this.#command('connectRealtime', {});
767
- }
768
- async disconnectRealtime() {
769
- await this.#command('disconnectRealtime', {});
770
- }
771
- /**
772
- * Shut down the native core, release its keyring, then detach listeners.
773
- * Every call returns the same promise, so a concurrent or repeated close
774
- * settles only when the one native shutdown settles, with its outcome.
775
- */
776
- close() {
777
- if (this.#closing === undefined) {
778
- const shutdown = this.#command('shutdown', {});
779
- this.#closed = true;
780
- this.#closing = shutdown
781
- .then(() => { })
782
- .finally(() => {
783
- this.#unlisten?.();
784
- this.#unlisten = undefined;
785
- this.#invalidationListeners.clear();
786
- this.#progress.clear();
787
- this.#changeListeners.clear();
788
- this.#diagnosticsListeners.clear();
789
- this.#presenceListeners.clear();
790
- });
791
- }
792
- return this.#closing;
793
- }
794
- }
795
- function decodeDiagnosticsSnapshot(value, kind) {
796
- if (value === null || typeof value !== 'object')
797
- return undefined;
798
- const snapshot = value;
799
- if (snapshot.version !== 1 || snapshot.host === undefined)
800
- return undefined;
801
- return withClientDiagnosticsHost(snapshot, {
802
- ...snapshot.host,
803
- kind,
804
- role: 'single',
805
- });
806
- }
807
- /** The error a `{error}` reply surfaces (mirrors the web-client `ClientSyncError`). */
808
- export class TauriSyncError extends Error {
809
- code;
810
- details;
811
- retryable;
812
- constructor(code, message, details, retryable = false) {
813
- super(message);
814
- this.name = 'TauriSyncError';
815
- this.code = code;
816
- this.details = details;
817
- this.retryable = retryable;
818
- }
819
- }
820
- function toStringSet(value) {
821
- if (Array.isArray(value)) {
822
- return new Set(value.filter((v) => typeof v === 'string'));
823
- }
824
- return new Set();
825
- }
826
- function decodeChangeBatch(value) {
827
- if (value === null || typeof value !== 'object')
828
- return undefined;
829
- const raw = value;
830
- if (typeof raw.revision !== 'string')
831
- return undefined;
832
- const tables = Array.isArray(raw.tables)
833
- ? raw.tables.flatMap((entry) => {
834
- if (entry === null || typeof entry !== 'object')
835
- return [];
836
- const item = entry;
837
- if (typeof item.table !== 'string')
838
- return [];
839
- return [
840
- {
841
- table: item.table,
842
- ...(Array.isArray(item.scopeKeys)
843
- ? { scopeKeys: toStringSet(item.scopeKeys) }
844
- : {}),
845
- },
846
- ];
847
- })
848
- : [];
849
- const windows = Array.isArray(raw.windows)
850
- ? raw.windows.flatMap((entry) => {
851
- if (entry === null || typeof entry !== 'object')
852
- return [];
853
- const item = entry;
854
- if (typeof item.baseKey !== 'string' ||
855
- typeof item.table !== 'string') {
856
- return [];
857
- }
858
- return [
859
- {
860
- baseKey: item.baseKey,
861
- table: item.table,
862
- units: toStringSet(item.units),
863
- },
864
- ];
865
- })
866
- : [];
867
- const appliedCommits = [];
868
- if (raw.appliedCommits !== undefined) {
869
- if (!Array.isArray(raw.appliedCommits))
870
- return undefined;
871
- for (const entry of raw.appliedCommits) {
872
- if (entry === null || typeof entry !== 'object')
873
- return undefined;
874
- const item = entry;
875
- if (typeof item.subscriptionId !== 'string' ||
876
- typeof item.table !== 'string' ||
877
- typeof item.commitSeq !== 'number' ||
878
- !Number.isSafeInteger(item.commitSeq) ||
879
- item.commitSeq < 1 ||
880
- (item.source !== 'delta' && item.source !== 'pull'))
881
- return undefined;
882
- appliedCommits.push({
883
- subscriptionId: item.subscriptionId,
884
- table: item.table,
885
- commitSeq: item.commitSeq,
886
- source: item.source,
887
- });
888
- }
889
- }
890
- return {
891
- revision: BigInt(raw.revision),
892
- tables,
893
- windows,
894
- ...(raw.appliedCommits !== undefined ? { appliedCommits } : {}),
895
- ...(raw.status !== undefined
896
- ? { status: raw.status }
897
- : {}),
898
- conflictsChanged: raw.conflictsChanged === true,
899
- rejectionsChanged: raw.rejectionsChanged === true,
900
- outcomesChanged: raw.outcomesChanged === true,
901
- };
902
- }
903
- function invalidationFromChange(batch) {
904
- if (batch.tables.length === 0 && batch.windows.length === 0)
905
- return undefined;
906
- const tables = new Set();
907
- const scopeKeys = new Set();
908
- for (const table of batch.tables) {
909
- tables.add(table.table);
910
- for (const key of table.scopeKeys ?? [])
911
- scopeKeys.add(key);
912
- }
913
- for (const window of batch.windows)
914
- tables.add(window.table);
915
- return { tables, scopeKeys };
916
- }
917
- /** Encode one mutation for the command JSON (bytes inside `values` handled by
918
- * the native side; the driver form is already JSON-able). */
919
- function encodeMutation(mutation) {
920
- if (mutation.op === 'delete')
921
- return mutation;
922
- const values = {};
923
- for (const [key, value] of Object.entries(mutation.values)) {
924
- values[key] = encodeJsonValue(value);
925
- }
926
- return { ...mutation, values };
927
90
  }
928
91
  export async function createTauriSyncClient(config, createClient = (...args) => new TauriSyncClient(...args)) {
929
- const tauri = await resolveTauri(config.tauri);
930
- // Wire the event stream BEFORE create, so no early change batch is missed.
931
- const clientRef = {
932
- client: undefined,
933
- };
934
- const unlisten = await tauri.listen(SYNCULAR_EVENT, (event) => {
935
- clientRef.client?.__dispatchEvent(event.payload);
936
- });
937
- if (config.securityPreflight === true && config.encryption !== undefined) {
938
- unlisten();
939
- throw new TauriSyncError('sync.invalid_request', 'securityPreflight and encryption are mutually exclusive; install keys with activateSecurity after preflight');
940
- }
941
- const client = createClient(tauri, unlisten, config.securityPreflight === true ? 'preflight' : 'active');
942
- clientRef.client = client;
943
92
  // The native side owns every path (plugin config); the JS side names a
944
93
  // database and supplies the schema, clientId, and limits.
945
- const reply = await tauri.invoke(`${PLUGIN}syncular_command`, {
946
- command: {
947
- method: 'create',
948
- params: {
949
- ...(config.clientId !== undefined ? { clientId: config.clientId } : {}),
950
- ...(config.database !== undefined ? { database: config.database } : {}),
951
- schema: config.schema,
952
- ...(config.limits !== undefined ? { limits: config.limits } : {}),
953
- ...(config.retainFailedCommits !== undefined
954
- ? { retainFailedCommits: config.retainFailedCommits }
955
- : {}),
956
- ...(config.realtimePolicy !== undefined
957
- ? { realtimePolicy: config.realtimePolicy }
958
- : {}),
959
- ...(config.encryption !== undefined
960
- ? { encryption: encodeEncryption(config.encryption) }
961
- : {}),
962
- ...(config.transportEnabled !== undefined
963
- ? { transportEnabled: config.transportEnabled }
964
- : {}),
965
- ...(config.authorityReads !== undefined
966
- ? { authorityReads: config.authorityReads.declarations }
967
- : {}),
968
- ...(config.securityPreflight !== undefined
969
- ? { securityPreflight: config.securityPreflight }
970
- : {}),
971
- ...(config.previousVersionContext !== undefined
972
- ? { previousVersionContext: config.previousVersionContext }
973
- : {}),
974
- },
975
- },
976
- });
977
- if (reply.error !== undefined) {
978
- unlisten();
979
- throw new TauriSyncError(reply.error.code, reply.error.message, reply.error.details ?? undefined, reply.error.retryable ?? false);
980
- }
981
- return client;
94
+ const params = {
95
+ ...nativeCreateParams(config, TauriSyncError),
96
+ ...(config.database !== undefined ? { database: config.database } : {}),
97
+ ...(config.retainFailedCommits !== undefined
98
+ ? { retainFailedCommits: config.retainFailedCommits }
99
+ : {}),
100
+ ...(config.transportEnabled !== undefined
101
+ ? { transportEnabled: config.transportEnabled }
102
+ : {}),
103
+ ...(config.authorityReads !== undefined
104
+ ? { authorityReads: config.authorityReads.declarations }
105
+ : {}),
106
+ };
107
+ const tauri = await resolveTauri(config.tauri);
108
+ // The create carries the event channel, so no early change batch is missed.
109
+ // Releasing the bridge drops its reference, which ends dispatch.
110
+ let client;
111
+ const events = tauri.channel((event) => client?.__dispatchEvent(event));
112
+ const opened = createClient(tauri, () => {
113
+ client = undefined;
114
+ }, config.securityPreflight === true ? 'preflight' : 'active');
115
+ client = opened;
116
+ await opened.__open(() => tauri.invoke(`${PLUGIN}syncular_command`, {
117
+ command: { method: 'create', params: { ...params, events } },
118
+ }));
119
+ return opened;
982
120
  }