@syncular/client 0.57.0 → 0.59.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.
Files changed (82) hide show
  1. package/README.md +7 -7
  2. package/dist/apply.d.ts +20 -11
  3. package/dist/apply.js +67 -45
  4. package/dist/blob.d.ts +17 -9
  5. package/dist/blob.js +5 -6
  6. package/dist/bun-database.d.ts +1 -0
  7. package/dist/bun-database.js +28 -0
  8. package/dist/client.d.ts +27 -10
  9. package/dist/client.js +357 -190
  10. package/dist/database.d.ts +5 -0
  11. package/dist/encryption.d.ts +2 -2
  12. package/dist/encryption.js +8 -2
  13. package/dist/errors.d.ts +2 -0
  14. package/dist/errors.js +4 -0
  15. package/dist/failed-overlay.d.ts +0 -1
  16. package/dist/failed-overlay.js +3 -6
  17. package/dist/http.d.ts +4 -1
  18. package/dist/http.js +61 -39
  19. package/dist/index.d.ts +1 -1
  20. package/dist/index.js +1 -1
  21. package/dist/invalidation.d.ts +11 -10
  22. package/dist/invalidation.js +15 -26
  23. package/dist/local-purge.js +9 -12
  24. package/dist/local-rebootstrap.js +2 -2
  25. package/dist/multi-tab.d.ts +89 -1
  26. package/dist/multi-tab.js +70 -31
  27. package/dist/native-bridge.d.ts +235 -0
  28. package/dist/native-bridge.js +789 -0
  29. package/dist/node-database.d.ts +1 -0
  30. package/dist/node-database.js +29 -0
  31. package/dist/outbox.d.ts +9 -12
  32. package/dist/outbox.js +19 -36
  33. package/dist/outcomes.js +3 -3
  34. package/dist/previous-version.js +96 -114
  35. package/dist/query-guard.d.ts +25 -24
  36. package/dist/query-guard.js +34 -191
  37. package/dist/reactive-store.js +53 -11
  38. package/dist/realtime-supervisor.d.ts +9 -2
  39. package/dist/realtime-supervisor.js +31 -7
  40. package/dist/remote.js +11 -15
  41. package/dist/schema.js +15 -10
  42. package/dist/sync-scheduler.js +28 -2
  43. package/dist/transport.d.ts +19 -4
  44. package/dist/wasm-database.js +58 -21
  45. package/dist/worker-core.d.ts +5 -0
  46. package/dist/worker-core.js +80 -72
  47. package/dist/worker-host.d.ts +10 -5
  48. package/dist/worker-host.js +64 -7
  49. package/dist/worker-local-authority.js +2 -2
  50. package/dist/worker-protocol.d.ts +6 -2
  51. package/package.json +11 -3
  52. package/src/apply.ts +91 -55
  53. package/src/blob.ts +27 -15
  54. package/src/bun-database.ts +29 -0
  55. package/src/client.ts +477 -261
  56. package/src/database.ts +5 -0
  57. package/src/encryption.ts +10 -5
  58. package/src/errors.ts +8 -0
  59. package/src/failed-overlay.ts +3 -7
  60. package/src/http.ts +90 -79
  61. package/src/index.ts +1 -1
  62. package/src/invalidation.ts +17 -32
  63. package/src/local-purge.ts +11 -13
  64. package/src/local-rebootstrap.ts +2 -3
  65. package/src/multi-tab.ts +88 -30
  66. package/src/native-bridge.ts +1189 -0
  67. package/src/node-database.ts +32 -0
  68. package/src/outbox.ts +19 -41
  69. package/src/outcomes.ts +3 -5
  70. package/src/previous-version.ts +103 -114
  71. package/src/query-guard.ts +43 -180
  72. package/src/reactive-store.ts +50 -10
  73. package/src/realtime-supervisor.ts +37 -12
  74. package/src/remote.ts +12 -16
  75. package/src/schema.ts +19 -12
  76. package/src/sync-scheduler.ts +31 -1
  77. package/src/transport.ts +21 -2
  78. package/src/wasm-database.ts +76 -27
  79. package/src/worker-core.ts +94 -74
  80. package/src/worker-host.ts +63 -16
  81. package/src/worker-local-authority.ts +2 -5
  82. package/src/worker-protocol.ts +6 -2
package/src/transport.ts CHANGED
@@ -5,8 +5,15 @@
5
5
  * loopback doctrine; HTTP/WebSocket bindings live in `./http`.
6
6
  */
7
7
 
8
- /** One combined push+pull round trip: SSP2 request bytes → response bytes. */
9
- export type SyncTransport = (request: Uint8Array) => Promise<Uint8Array>;
8
+ /**
9
+ * One combined push+pull round trip: SSP2 request bytes → response bytes.
10
+ * `signal` aborts when the `syncUntilIdle` deadline elapses (§7.7); a
11
+ * transport that honors it releases the round instead of holding it open.
12
+ */
13
+ export type SyncTransport = (
14
+ request: Uint8Array,
15
+ signal?: AbortSignal,
16
+ ) => Promise<Uint8Array>;
10
17
 
11
18
  /** One registered authoritative query or command request. */
12
19
  export type RemoteOperationTransport = (
@@ -32,7 +39,14 @@ export interface SegmentFetchRequest {
32
39
  readonly table: string;
33
40
  /** Canonical JSON (§11.2) of the requested scope map (§5.5 header). */
34
41
  readonly requestedScopesJson: string;
42
+ /**
43
+ * The descriptor's `byteLength` (§5.4): the downloader stops reading once
44
+ * the body exceeds it, and the client core rejects the result.
45
+ */
46
+ readonly byteLength?: number;
35
47
  readonly onProgress?: (bytesReceived: number) => void;
48
+ /** Aborts with the round when the `syncUntilIdle` deadline elapses (§7.7). */
49
+ readonly signal?: AbortSignal;
36
50
  }
37
51
 
38
52
  /**
@@ -48,6 +62,9 @@ export interface SegmentDownloader {
48
62
  readonly fetchUrl?: (
49
63
  url: string,
50
64
  onProgress?: (bytesReceived: number) => void,
65
+ signal?: AbortSignal,
66
+ /** The descriptor's `byteLength`; reading stops once the body exceeds it. */
67
+ byteLength?: number,
51
68
  ) => Promise<Uint8Array>;
52
69
  }
53
70
 
@@ -72,4 +89,6 @@ export interface RealtimeSocket {
72
89
 
73
90
  export type RealtimeConnector = (
74
91
  handlers: RealtimeHandlers,
92
+ /** The client's id; the client passes it on every connect. */
93
+ clientId?: string,
75
94
  ) => Promise<RealtimeSocket> | RealtimeSocket;
@@ -39,6 +39,7 @@ import {
39
39
  STORAGE_FENCED_CODE,
40
40
  STORAGE_UNAVAILABLE_CODE,
41
41
  } from './errors';
42
+ import { prepareReadOnly } from './query-guard';
42
43
 
43
44
  /** Structural view of the sqlite3 oo1 surface this binding uses. */
44
45
  interface Oo1Database {
@@ -50,9 +51,24 @@ interface Oo1Database {
50
51
  rowMode: 'object';
51
52
  resultRows: unknown[];
52
53
  }): unknown;
54
+ prepare(sql: string): Oo1Statement;
53
55
  close(): void;
54
56
  }
55
57
 
58
+ interface Oo1Statement {
59
+ readonly pointer?: number;
60
+ readonly columnCount: number;
61
+ isReadOnly(): boolean;
62
+ finalize(): unknown;
63
+ bind(values: readonly unknown[]): unknown;
64
+ step(): boolean;
65
+ get(target: Record<string, unknown>): Record<string, unknown>;
66
+ reset(clearBindings: boolean): unknown;
67
+ }
68
+
69
+ /** Compiled statements one database keeps; a full cache is finalized and cleared. */
70
+ const STATEMENT_CACHE_LIMIT = 128;
71
+
56
72
  interface SahPoolUtil {
57
73
  OpfsSAHPoolDb: new (filename: string) => Oo1Database;
58
74
  /** RFC 0005: the runtime exposes naming and removal on the pool util. */
@@ -77,6 +93,7 @@ interface Sqlite3Static {
77
93
  SQLITE_DESERIALIZE_FREEONCLOSE: number;
78
94
  SQLITE_DESERIALIZE_READONLY: number;
79
95
  SQLITE_FCNTL_FILE_POINTER: number;
96
+ sqlite3_sql(statement: number | undefined): string;
80
97
  sqlite3_file_control(
81
98
  db: number,
82
99
  schema: string,
@@ -128,7 +145,7 @@ function coerceParams(params: readonly SqlValue[]): unknown[] {
128
145
  */
129
146
  interface StorageFence {
130
147
  fenced: boolean;
131
- readonly siblings: Set<Oo1Database>;
148
+ readonly siblings: Set<WasmClientDatabase>;
132
149
  }
133
150
 
134
151
  class WasmClientDatabase implements ClientDatabase {
@@ -139,6 +156,7 @@ class WasmClientDatabase implements ClientDatabase {
139
156
  | { readonly util: SahPoolUtil; readonly lease: LeaderLease }
140
157
  | undefined;
141
158
  readonly #fence: StorageFence | undefined;
159
+ readonly #statements = new Map<string, Oo1Statement>();
142
160
  #closed = false;
143
161
  #tx = { depth: 0 };
144
162
 
@@ -159,7 +177,6 @@ class WasmClientDatabase implements ClientDatabase {
159
177
  if (fence === undefined || this.#closed) return;
160
178
  fence.fenced = true;
161
179
  for (const sibling of fence.siblings) sibling.close();
162
- fence.siblings.clear();
163
180
  this.close();
164
181
  });
165
182
  }
@@ -174,25 +191,55 @@ class WasmClientDatabase implements ClientDatabase {
174
191
  }
175
192
 
176
193
  exec(sql: string, params: readonly SqlValue[] = []): void {
177
- this.#assertOwned();
178
- this.#db.exec({
179
- sql,
180
- ...(params.length > 0 ? { bind: coerceParams(params) } : {}),
181
- rowMode: 'object',
182
- resultRows: [],
183
- });
194
+ this.query(sql, params);
184
195
  }
185
196
 
197
+ /**
198
+ * Parameterized SQL (one statement per call, the `ClientDatabase` contract)
199
+ * runs through a compiled statement cached by its SQL text. SQL without
200
+ * parameters may hold several statements and compiles through `exec`.
201
+ */
186
202
  query(sql: string, params: readonly SqlValue[] = []): SqlRow[] {
187
203
  this.#assertOwned();
188
- const resultRows: unknown[] = [];
189
- this.#db.exec({
190
- sql,
191
- ...(params.length > 0 ? { bind: coerceParams(params) } : {}),
192
- rowMode: 'object',
193
- resultRows,
204
+ if (params.length === 0) {
205
+ const resultRows: unknown[] = [];
206
+ this.#db.exec({ sql, rowMode: 'object', resultRows });
207
+ return resultRows as SqlRow[];
208
+ }
209
+ let statement = this.#statements.get(sql);
210
+ if (statement === undefined) {
211
+ statement = this.#db.prepare(sql);
212
+ if (this.#statements.size === STATEMENT_CACHE_LIMIT) {
213
+ this.#statements.forEach((evicted) => evicted.finalize());
214
+ this.#statements.clear();
215
+ }
216
+ this.#statements.set(sql, statement);
217
+ }
218
+ const rows: SqlRow[] = [];
219
+ try {
220
+ statement.bind(coerceParams(params));
221
+ while (statement.step()) rows.push(statement.get({}) as SqlRow);
222
+ } finally {
223
+ statement.reset(true);
224
+ }
225
+ return rows;
226
+ }
227
+
228
+ queryReadOnly(sql: string, params: readonly SqlValue[] = []): SqlRow[] {
229
+ this.#assertOwned();
230
+ prepareReadOnly(sql, () => {
231
+ const statement = this.#db.prepare(sql);
232
+ try {
233
+ return [
234
+ undefined,
235
+ this.#sqlite3.capi.sqlite3_sql(statement.pointer),
236
+ statement.isReadOnly() && statement.columnCount > 0,
237
+ ] as const;
238
+ } finally {
239
+ statement.finalize();
240
+ }
194
241
  });
195
- return resultRows as SqlRow[];
242
+ return this.query(sql, params);
196
243
  }
197
244
 
198
245
  transaction<T>(fn: () => T): T {
@@ -218,18 +265,16 @@ class WasmClientDatabase implements ClientDatabase {
218
265
  db.close();
219
266
  throw error;
220
267
  }
221
- this.#fence?.siblings.add(db);
268
+ const database = new WasmClientDatabase(
269
+ db,
270
+ this.#sqlite3,
271
+ undefined,
272
+ this.#fence,
273
+ );
274
+ this.#fence?.siblings.add(database);
222
275
  return {
223
- database: new WasmClientDatabase(
224
- db,
225
- this.#sqlite3,
226
- undefined,
227
- this.#fence,
228
- ),
229
- close: () => {
230
- this.#fence?.siblings.delete(db);
231
- db.close();
232
- },
276
+ database,
277
+ close: () => database.close(),
233
278
  removeFile: () => {
234
279
  sah.util.unlink(fileName);
235
280
  },
@@ -287,6 +332,10 @@ class WasmClientDatabase implements ClientDatabase {
287
332
 
288
333
  close(): void {
289
334
  if (this.#closed) return;
335
+ this.#fence?.siblings.delete(this);
336
+ // oo1 DB.close() does not finalize prepared statements, and an open one
337
+ // keeps the database file open, so pauseVfs() below would throw.
338
+ this.#statements.forEach((statement) => statement.finalize());
290
339
  this.#db.close();
291
340
  // DB.close() leaves the SAH pool live. Close siblings first, then pause the
292
341
  // VFS without deleting files, before releasing this worker's physical lock.
@@ -24,6 +24,7 @@ import { encryptionConfigFromKeyring } from './encryption';
24
24
  import {
25
25
  classifySqliteFailure,
26
26
  ClientSyncError,
27
+ invalidRequest,
27
28
  STORAGE_BUSY_CODE,
28
29
  } from './errors';
29
30
  import {
@@ -64,6 +65,14 @@ export interface SyncWorkerOverrides {
64
65
  ) => Promise<ClientDatabase> | ClientDatabase;
65
66
  /** Retry deadline indirection for deterministic worker-host tests. */
66
67
  readonly waitForStorageRetry?: (delayMs: number) => Promise<void>;
68
+ /**
69
+ * Timer indirection for deterministic worker-host tests: background-intent
70
+ * deadlines and the client's §8.5 heartbeat watchdog.
71
+ */
72
+ readonly scheduleBackground?: (
73
+ callback: () => void,
74
+ delayMs: number,
75
+ ) => () => void;
67
76
  readonly createTransport?: (config: WorkerInitConfig) => SyncTransport;
68
77
  readonly createSegments?: (
69
78
  config: WorkerInitConfig,
@@ -201,6 +210,7 @@ export function startSyncWorkerCore(
201
210
  let offline = false;
202
211
  let headers: Readonly<Record<string, string>> = {};
203
212
  let closed = false;
213
+ let pushingDiagnostics = false;
204
214
 
205
215
  // -- one sync loop: RPC-driven and auto-driven rounds serialize ----------
206
216
  let syncChain: Promise<unknown> = Promise.resolve();
@@ -216,8 +226,32 @@ export function startSyncWorkerCore(
216
226
  // -- SPEC §7.5 host loop: event-driven intents, no interactive polling --
217
227
  let autoSync = true;
218
228
  let autoSyncScheduled = false;
219
- let backgroundTimer: ReturnType<typeof setTimeout> | undefined;
229
+ let cancelBackground: (() => void) | undefined;
220
230
  let backgroundDue = Number.POSITIVE_INFINITY;
231
+ // §7.6 backoff for drives that end without a client retry intent.
232
+ let retryDelayMs = 250;
233
+ const scheduleBackground =
234
+ overrides.scheduleBackground ??
235
+ ((callback: () => void, delayMs: number): (() => void) => {
236
+ const timer = setTimeout(callback, delayMs);
237
+ return () => clearTimeout(timer);
238
+ });
239
+
240
+ const workerDiagnostics = (snapshot: ClientDiagnosticsSnapshot) =>
241
+ withClientDiagnosticsHost(snapshot, {
242
+ kind: 'worker',
243
+ role: 'leader',
244
+ connectivity: offline ? 'offline' : snapshot.host.connectivity,
245
+ realtime: snapshot.host.realtime,
246
+ });
247
+ const postDiagnostics = (snapshot: ClientDiagnosticsSnapshot): void => {
248
+ if (!closed) {
249
+ post({
250
+ t: 'event',
251
+ event: { kind: 'diagnostics', snapshot: workerDiagnostics(snapshot) },
252
+ });
253
+ }
254
+ };
221
255
 
222
256
  function runAutoSync(): void {
223
257
  if (
@@ -238,19 +272,44 @@ export function startSyncWorkerCore(
238
272
  return running.syncUntilIdle();
239
273
  })
240
274
  .then((summary) => {
275
+ retryDelayMs = 250;
241
276
  if (!closed) post({ t: 'event', event: { kind: 'synced', summary } });
242
277
  if (summary.budgetExhausted) consumeSyncIntent({ kind: 'interactive' });
243
278
  })
244
279
  .catch((error: unknown) => {
245
- if (!closed) {
246
- post({
247
- t: 'event',
248
- event: { kind: 'synced', error: toErrorShape(error) },
249
- });
280
+ if (closed) return;
281
+ post({
282
+ t: 'event',
283
+ event: { kind: 'synced', error: toErrorShape(error) },
284
+ });
285
+ // §7.7: a retryable drive rejection owes another drive. A retryable
286
+ // round failure already handed this loop its background intent; the
287
+ // drive deadline did not. An unreachable endpoint waits for the
288
+ // host's connectivity resume (§1.8).
289
+ const causeKind =
290
+ error instanceof ClientSyncError
291
+ ? error.details?.['causeKind']
292
+ : undefined;
293
+ if (
294
+ error instanceof ClientSyncError &&
295
+ error.retryable &&
296
+ causeKind !== 'network' &&
297
+ causeKind !== 'connect' &&
298
+ cancelBackground === undefined &&
299
+ !autoSyncScheduled
300
+ ) {
301
+ consumeSyncIntent({ kind: 'background', delayMs: retryDelayMs });
302
+ retryDelayMs = Math.min(retryDelayMs * 2, 30_000);
250
303
  }
251
304
  });
252
305
  }
253
306
 
307
+ function stopBackground(): void {
308
+ cancelBackground?.();
309
+ cancelBackground = undefined;
310
+ backgroundDue = Number.POSITIVE_INFINITY;
311
+ }
312
+
254
313
  function consumeSyncIntent(intent: SyncIntent): void {
255
314
  if (
256
315
  !autoSync ||
@@ -265,12 +324,12 @@ export function startSyncWorkerCore(
265
324
  if (intent.kind === 'background') {
266
325
  if (autoSyncScheduled) return;
267
326
  const due = Date.now() + Math.max(0, intent.delayMs);
268
- if (backgroundTimer !== undefined && due >= backgroundDue) return;
269
- if (backgroundTimer !== undefined) clearTimeout(backgroundTimer);
327
+ if (cancelBackground !== undefined && due >= backgroundDue) return;
328
+ cancelBackground?.();
270
329
  backgroundDue = due;
271
- backgroundTimer = setTimeout(
330
+ cancelBackground = scheduleBackground(
272
331
  () => {
273
- backgroundTimer = undefined;
332
+ cancelBackground = undefined;
274
333
  backgroundDue = Number.POSITIVE_INFINITY;
275
334
  if (!autoSyncScheduled) {
276
335
  autoSyncScheduled = true;
@@ -281,11 +340,7 @@ export function startSyncWorkerCore(
281
340
  );
282
341
  return;
283
342
  }
284
- if (backgroundTimer !== undefined) {
285
- clearTimeout(backgroundTimer);
286
- backgroundTimer = undefined;
287
- backgroundDue = Number.POSITIVE_INFINITY;
288
- }
343
+ stopBackground();
289
344
  if (!autoSync || autoSyncScheduled || closed || client === undefined) {
290
345
  return;
291
346
  }
@@ -393,15 +448,12 @@ export function startSyncWorkerCore(
393
448
  ? { segments: bindings.segments }
394
449
  : {}),
395
450
  ...(blobs !== undefined ? { blobs } : {}),
396
- realtime: (handlers) => {
451
+ realtime: (handlers, clientId) => {
397
452
  // §12.2: a local authority has no realtime channel.
398
453
  if (realtimeConnector === undefined || local?.active()) {
399
- throw new ClientSyncError(
400
- 'sync.invalid_request',
401
- 'no realtime connector configured',
402
- );
454
+ throw invalidRequest('no realtime connector configured');
403
455
  }
404
- return realtimeConnector(handlers);
456
+ return realtimeConnector(handlers, clientId);
405
457
  },
406
458
  ...(config.clientId !== undefined ? { clientId: config.clientId } : {}),
407
459
  ...(config.limits !== undefined ? { limits: config.limits } : {}),
@@ -411,6 +463,10 @@ export function startSyncWorkerCore(
411
463
  ...(config.realtimePolicy !== undefined
412
464
  ? { realtimePolicy: config.realtimePolicy }
413
465
  : {}),
466
+ ...(config.realtimeHeartbeatMs !== undefined
467
+ ? { realtimeHeartbeatMs: config.realtimeHeartbeatMs }
468
+ : {}),
469
+ schedule: scheduleBackground,
414
470
  ...(config.encryption !== undefined
415
471
  ? { encryption: encryptionConfigFromKeyring(config.encryption) }
416
472
  : {}),
@@ -439,9 +495,9 @@ export function startSyncWorkerCore(
439
495
  // §7.4.5: surface the schema-bump reset + completion to the UI thread.
440
496
  post({ t: 'event', event: { kind: 'upgrading', upgrading } });
441
497
  },
442
- onPresence: (scopeKey) => {
443
- // §8.6: surface a presence change to the UI thread.
444
- post({ t: 'event', event: { kind: 'presence', scopeKey } });
498
+ onPresence: (scopeKey, error) => {
499
+ // §8.6: surface a presence change or rejection to the UI thread.
500
+ post({ t: 'event', event: { kind: 'presence', scopeKey, error } });
445
501
  },
446
502
  });
447
503
  started.onProgress((progress) => {
@@ -450,33 +506,12 @@ export function startSyncWorkerCore(
450
506
  started.onChange((batch) => {
451
507
  if (!closed) post({ t: 'event', event: { kind: 'change', batch } });
452
508
  });
453
- const postDiagnostics = (snapshot: ClientDiagnosticsSnapshot): void => {
454
- if (closed) return;
455
- post({
456
- t: 'event',
457
- event: {
458
- kind: 'diagnostics',
459
- snapshot: withClientDiagnosticsHost(snapshot, {
460
- kind: 'worker',
461
- role: 'leader',
462
- connectivity: offline ? 'offline' : snapshot.host.connectivity,
463
- realtime: snapshot.host.realtime,
464
- }),
465
- },
466
- });
467
- };
468
- started.onDiagnostics(postDiagnostics);
469
509
  await started.start();
470
510
  realtimeConnector =
471
511
  overrides.createRealtime !== undefined
472
512
  ? overrides.createRealtime(config, started.clientId, http.headers)
473
513
  : config.endpoints.realtimeUrl !== undefined
474
- ? webSocketRealtimeConnector(
475
- config.endpoints.realtimeUrl.replace(
476
- '{clientId}',
477
- encodeURIComponent(started.clientId),
478
- ),
479
- )
514
+ ? webSocketRealtimeConnector(config.endpoints.realtimeUrl)
480
515
  : undefined;
481
516
  client = started;
482
517
  // `start()` may discover persisted subscriptions/outbox work. Its callback
@@ -530,9 +565,7 @@ export function startSyncWorkerCore(
530
565
  ]),
531
566
  ) as Pick<WorkerApi, (typeof coreMethods)[number]>),
532
567
  beginSecurityPreflight: async () => {
533
- if (backgroundTimer !== undefined) clearTimeout(backgroundTimer);
534
- backgroundTimer = undefined;
535
- backgroundDue = Number.POSITIVE_INFINITY;
568
+ stopBackground();
536
569
  autoSyncScheduled = false;
537
570
  await requireClient().beginSecurityPreflight();
538
571
  },
@@ -575,13 +608,14 @@ export function startSyncWorkerCore(
575
608
  resetClientId: () => requireClient().resetClientId(),
576
609
  localRevision: () => requireClient().localRevision,
577
610
  diagnosticsSnapshot: (request) => {
578
- const snapshot = requireClient().diagnosticsSnapshot(request);
579
- return withClientDiagnosticsHost(snapshot, {
580
- kind: 'worker',
581
- role: 'leader',
582
- connectivity: offline ? 'offline' : snapshot.host.connectivity,
583
- realtime: snapshot.host.realtime,
584
- });
611
+ const running = requireClient();
612
+ // The first pull makes the worker a push source: no tab has asked for
613
+ // diagnostics before it, so no snapshot is built per revision until then.
614
+ if (!pushingDiagnostics) {
615
+ pushingDiagnostics = true;
616
+ running.onDiagnostics(postDiagnostics);
617
+ }
618
+ return workerDiagnostics(running.diagnosticsSnapshot(request));
585
619
  },
586
620
  setHeaders: (next) => {
587
621
  headers = next;
@@ -590,29 +624,15 @@ export function startSyncWorkerCore(
590
624
  offline = value;
591
625
  requireClient().setTransportEnabled(!value);
592
626
  if (offline) {
593
- if (backgroundTimer !== undefined) clearTimeout(backgroundTimer);
594
- backgroundTimer = undefined;
595
- backgroundDue = Number.POSITIVE_INFINITY;
596
- } else if (client !== undefined) {
597
- const snapshot = client.diagnosticsSnapshot();
598
- post({
599
- t: 'event',
600
- event: {
601
- kind: 'diagnostics',
602
- snapshot: withClientDiagnosticsHost(snapshot, {
603
- kind: 'worker',
604
- role: 'leader',
605
- connectivity: snapshot.host.connectivity,
606
- realtime: snapshot.host.realtime,
607
- }),
608
- },
609
- });
627
+ stopBackground();
628
+ } else if (client !== undefined && pushingDiagnostics) {
629
+ postDiagnostics(client.diagnosticsSnapshot());
610
630
  }
611
631
  },
612
632
  ...local?.methods,
613
633
  close: async () => {
614
634
  closed = true;
615
- if (backgroundTimer !== undefined) clearTimeout(backgroundTimer);
635
+ cancelBackground?.();
616
636
  await client?.close();
617
637
  local?.close();
618
638
  database?.close();