@syncular/client 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.
Files changed (99) hide show
  1. package/README.md +34 -34
  2. package/dist/apply.d.ts +24 -14
  3. package/dist/apply.js +119 -70
  4. package/dist/authority.js +21 -16
  5. package/dist/blob.d.ts +17 -9
  6. package/dist/blob.js +5 -6
  7. package/dist/bun-database.d.ts +1 -0
  8. package/dist/bun-database.js +15 -0
  9. package/dist/client.d.ts +83 -75
  10. package/dist/client.js +982 -910
  11. package/dist/database.d.ts +5 -0
  12. package/dist/devtools.d.ts +2 -2
  13. package/dist/devtools.js +3 -3
  14. package/dist/diagnostics.d.ts +17 -28
  15. package/dist/diagnostics.js +1 -2
  16. package/dist/encryption.d.ts +2 -2
  17. package/dist/encryption.js +8 -2
  18. package/dist/errors.d.ts +3 -1
  19. package/dist/errors.js +5 -1
  20. package/dist/failed-overlay.d.ts +0 -1
  21. package/dist/failed-overlay.js +6 -6
  22. package/dist/http.d.ts +4 -1
  23. package/dist/http.js +67 -39
  24. package/dist/index.d.ts +1 -1
  25. package/dist/index.js +1 -1
  26. package/dist/invalidation.d.ts +14 -14
  27. package/dist/invalidation.js +24 -48
  28. package/dist/local-purge.js +9 -12
  29. package/dist/local-rebootstrap.js +2 -2
  30. package/dist/multi-tab.d.ts +89 -1
  31. package/dist/multi-tab.js +70 -31
  32. package/dist/native-bridge.d.ts +226 -0
  33. package/dist/native-bridge.js +764 -0
  34. package/dist/node-database.d.ts +1 -0
  35. package/dist/node-database.js +21 -1
  36. package/dist/outbox.d.ts +9 -12
  37. package/dist/outbox.js +20 -36
  38. package/dist/outcomes.js +3 -3
  39. package/dist/previous-version.js +96 -114
  40. package/dist/progress.d.ts +2 -2
  41. package/dist/query-guard.d.ts +34 -24
  42. package/dist/query-guard.js +61 -186
  43. package/dist/reactive-store.js +55 -13
  44. package/dist/realtime-supervisor.d.ts +9 -2
  45. package/dist/realtime-supervisor.js +31 -7
  46. package/dist/remote.js +19 -23
  47. package/dist/schema.d.ts +3 -2
  48. package/dist/schema.js +43 -22
  49. package/dist/state.d.ts +69 -36
  50. package/dist/state.js +178 -89
  51. package/dist/sync-scheduler.js +28 -2
  52. package/dist/transport.d.ts +19 -4
  53. package/dist/wasm-database.js +58 -21
  54. package/dist/window.d.ts +30 -52
  55. package/dist/window.js +33 -77
  56. package/dist/worker-core.d.ts +5 -0
  57. package/dist/worker-core.js +83 -75
  58. package/dist/worker-host.d.ts +19 -13
  59. package/dist/worker-host.js +75 -18
  60. package/dist/worker-local-authority.js +2 -2
  61. package/dist/worker-protocol.d.ts +15 -10
  62. package/package.json +11 -3
  63. package/src/apply.ts +176 -86
  64. package/src/authority.ts +31 -17
  65. package/src/blob.ts +28 -15
  66. package/src/bun-database.ts +24 -0
  67. package/src/client.ts +1282 -1217
  68. package/src/database.ts +5 -0
  69. package/src/devtools.ts +5 -5
  70. package/src/diagnostics.ts +17 -37
  71. package/src/encryption.ts +10 -5
  72. package/src/errors.ts +9 -1
  73. package/src/failed-overlay.ts +8 -7
  74. package/src/http.ts +95 -79
  75. package/src/index.ts +1 -1
  76. package/src/invalidation.ts +26 -61
  77. package/src/local-purge.ts +11 -13
  78. package/src/local-rebootstrap.ts +2 -3
  79. package/src/multi-tab.ts +88 -30
  80. package/src/native-bridge.ts +1153 -0
  81. package/src/node-database.ts +32 -1
  82. package/src/outbox.ts +20 -41
  83. package/src/outcomes.ts +3 -5
  84. package/src/previous-version.ts +103 -114
  85. package/src/progress.ts +2 -2
  86. package/src/query-guard.ts +77 -177
  87. package/src/reactive-store.ts +52 -12
  88. package/src/realtime-supervisor.ts +37 -12
  89. package/src/remote.ts +23 -31
  90. package/src/schema.ts +67 -25
  91. package/src/state.ts +246 -125
  92. package/src/sync-scheduler.ts +31 -1
  93. package/src/transport.ts +21 -2
  94. package/src/wasm-database.ts +76 -27
  95. package/src/window.ts +55 -134
  96. package/src/worker-core.ts +97 -77
  97. package/src/worker-host.ts +76 -32
  98. package/src/worker-local-authority.ts +2 -5
  99. package/src/worker-protocol.ts +14 -10
package/dist/window.js CHANGED
@@ -1,20 +1,18 @@
1
- export const PENDING_EVICTIONS = '_syncular_window_pending_evict';
1
+ export const PENDING_EVICTIONS = '_syncular_pending_evictions';
2
2
  export const WINDOWS_TABLE = '_syncular_windows';
3
3
  /**
4
- * Windowed subscriptions (SPEC.md §4.8).
4
+ * Windows (SPEC.md §4.8).
5
5
  *
6
6
  * A window is a partial local replica keyed by scope VALUES: the client
7
- * holds rows for a chosen set of units (one scope value each) of a window
8
- * BASE (a table + one scope variable + the fixed remainder of the scope
9
- * map). Windowing is a set-difference on §4 subscriptions — never a
10
- * mutation of one — so it needs zero wire or server changes.
7
+ * holds the units of a chosen set of values of a window BASE (one scope
8
+ * variable plus fixed values). Windowing is a set difference on §4.1 units,
9
+ * never a mutation of one, so it needs no wire or server change.
11
10
  *
12
- * This module owns the registry bookkeeping and the deterministic
13
- * per-unit subscription-id derivation (§4.1 guidance). The eviction that
14
- * fuses with a shrink (E1–E4) lives on the client, which holds the DB
15
- * transaction and the invalidation choke point.
11
+ * This module owns the registry bookkeeping. The eviction that fuses with a
12
+ * shrink (E1–E4) lives on the client, which holds the DB transaction and the
13
+ * invalidation choke point.
16
14
  */
17
- import { canonicalScopeJson } from '@syncular/core';
15
+ import { canonicalUnitJson, } from '@syncular/core';
18
16
  import { invalidRequest } from './errors.js';
19
17
  const MAX_TIME_BUCKET_MS = 253_402_300_799_999;
20
18
  function monthBucket(year, month) {
@@ -54,85 +52,43 @@ export function last(count, unit, nowMs = Date.now()) {
54
52
  }
55
53
  return units;
56
54
  }
57
- /**
58
- * A stable, server-opaque key for a window base — table + variable +
59
- * canonical fixed scopes. Two `setWindow` calls with the same base
60
- * address the same registry rows.
61
- */
55
+ /** A stable key for a window base: variable + canonical fixed scopes. */
62
56
  export function windowBaseKey(base) {
63
- const fixed = canonicalScopeJson(base.fixedScopes ?? {});
64
- return `${base.table}\0${base.variable}\0${fixed}`;
65
- }
66
- /** The full requested scope map for one unit (fixed scopes + the unit). */
67
- export function unitScopes(base, unit) {
68
- const scopes = {};
69
- for (const [variable, values] of Object.entries(base.fixedScopes ?? {})) {
70
- scopes[variable] = [...values];
71
- }
72
- scopes[base.variable] = [unit];
73
- return scopes;
57
+ return `${base.variable}\0${canonicalUnitJson(base.fixedScopes ?? {})}`;
74
58
  }
75
- /**
76
- * Deterministic per-unit subscription id (§4.1 guidance):
77
- * `w:<table>:<sha256(canonical scope map, §11.2)[0..16]>`. Ids are echoed
78
- * not interpreted by the server (§4.1), so the exact hash is pure client
79
- * convention; SHA-256 matches the SPEC's worked example.
80
- */
81
- export async function deriveSubId(base, unit) {
82
- const canonical = canonicalScopeJson(unitScopes(base, unit));
83
- const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(canonical));
84
- let hex = '';
85
- for (const byte of new Uint8Array(digest)) {
86
- hex += byte.toString(16).padStart(2, '0');
87
- }
88
- return `w:${base.table}:${hex.slice(0, 16)}`;
59
+ /** The unit of one window value: the fixed scopes plus the value. */
60
+ export function windowUnitScopes(base, value) {
61
+ return { ...base.fixedScopes, [base.variable]: value };
89
62
  }
90
- /** Live units for a base, ordered by unit value. */
63
+ /** Registry rows for a base, ordered by value: value → unit id. */
91
64
  export function loadWindowUnits(db, baseKey) {
92
65
  return db
93
66
  .query(`SELECT unit,sub_id FROM ${WINDOWS_TABLE} WHERE base=? ORDER BY unit`, [baseKey])
94
- .map((row) => ({ unit: row.unit, subId: row.sub_id }));
95
- }
96
- /** Registry lookup used to emit exact completion changes for a sub id. */
97
- export function getWindowUnitBySubId(db, subId) {
98
- const row = db.query(`SELECT base, unit, sub_id FROM ${WINDOWS_TABLE}
99
- WHERE sub_id = ? LIMIT 1`, [subId])[0];
100
- return row === undefined
101
- ? undefined
102
- : {
103
- baseKey: row.base,
104
- unit: row.unit,
105
- subId: row.sub_id,
106
- };
107
- }
108
- export function insertWindowUnit(db, baseKey, unit, subId) {
109
- db.exec(`INSERT OR REPLACE INTO ${WINDOWS_TABLE}(base,unit,sub_id)VALUES(?,?,?)`, [baseKey, unit, subId]);
110
- }
111
- export function deleteWindowUnit(db, baseKey, unit) {
112
- db.exec(`DELETE FROM ${WINDOWS_TABLE} WHERE base=? AND unit=?`, [
113
- baseKey,
114
- unit,
115
- ]);
67
+ .map((row) => ({
68
+ value: row.unit,
69
+ unitId: row.sub_id,
70
+ }));
116
71
  }
117
- /** Is a single scope value windowed-in for this base? (the oracle, I3) */
118
- export function isUnitLive(db, baseKey, unit) {
119
- return (db.query(`SELECT 1 FROM ${WINDOWS_TABLE} WHERE base=? AND unit=? LIMIT 1`, [
120
- baseKey,
121
- unit,
122
- ]).length > 0);
72
+ /** Every window registry row that references a unit (§4.1 references). */
73
+ export function windowRefs(db, unitId) {
74
+ return db
75
+ .query(`SELECT base,unit FROM ${WINDOWS_TABLE} WHERE sub_id=?`, [unitId])
76
+ .map((row) => ({
77
+ baseKey: row.base,
78
+ value: row.unit,
79
+ }));
123
80
  }
124
- export function savePendingEviction(db, subId, table, effective) {
125
- db.exec(`INSERT OR REPLACE INTO ${PENDING_EVICTIONS}(sub_id, tbl, effective_scopes)
126
- VALUES (?, ?, ?)`, [subId, table, JSON.stringify(effective)]);
81
+ export function savePendingEviction(db, entry) {
82
+ db.exec(`INSERT OR REPLACE INTO ${PENDING_EVICTIONS}(unit_id,tbl,effective_scopes)VALUES(?,?,?)`, [entry.unitId, entry.table, JSON.stringify(entry.effective)]);
127
83
  }
128
- export function deletePendingEviction(db, subId) {
129
- db.exec(`DELETE FROM ${PENDING_EVICTIONS} WHERE sub_id = ?`, [subId]);
84
+ export function deletePendingEviction(db, unitId, table) {
85
+ db.exec(`DELETE FROM ${PENDING_EVICTIONS} WHERE unit_id=?${table === undefined ? '' : ' AND tbl=?'}`, table === undefined ? [unitId] : [unitId, table]);
130
86
  }
131
87
  export function loadPendingEvictions(db) {
132
88
  return db
133
- .query(`SELECT sub_id, tbl, effective_scopes FROM ${PENDING_EVICTIONS}`)
89
+ .query(`SELECT unit_id,tbl,effective_scopes FROM ${PENDING_EVICTIONS}`)
134
90
  .map((row) => ({
135
- subId: row.sub_id,
91
+ unitId: row.unit_id,
136
92
  table: row.tbl,
137
93
  effective: JSON.parse(row.effective_scopes),
138
94
  }));
@@ -26,6 +26,11 @@ export interface SyncWorkerOverrides {
26
26
  readonly openDatabase?: (config: WorkerInitConfig) => Promise<ClientDatabase> | ClientDatabase;
27
27
  /** Retry deadline indirection for deterministic worker-host tests. */
28
28
  readonly waitForStorageRetry?: (delayMs: number) => Promise<void>;
29
+ /**
30
+ * Timer indirection for deterministic worker-host tests: background-intent
31
+ * deadlines and the client's §8.5 heartbeat watchdog.
32
+ */
33
+ readonly scheduleBackground?: (callback: () => void, delayMs: number) => () => void;
29
34
  readonly createTransport?: (config: WorkerInitConfig) => SyncTransport;
30
35
  readonly createSegments?: (config: WorkerInitConfig) => SegmentDownloader | undefined;
31
36
  /**
@@ -1,7 +1,7 @@
1
1
  import { SyncClient } from './client.js';
2
2
  import { withClientDiagnosticsHost, } from './diagnostics.js';
3
3
  import { encryptionConfigFromKeyring } from './encryption.js';
4
- import { classifySqliteFailure, ClientSyncError, STORAGE_BUSY_CODE, } from './errors.js';
4
+ import { classifySqliteFailure, ClientSyncError, invalidRequest, STORAGE_BUSY_CODE, } from './errors.js';
5
5
  import { httpBlobTransport, httpSegmentDownloader, httpSyncTransport, webSocketRealtimeConnector, } from './http.js';
6
6
  import { openPersistentWasmDatabase } from './wasm-database.js';
7
7
  import { LOCAL_AUTHORITY_UNCONFIGURED_CODE, WORKER_FAILED_CODE, WORKER_METHOD_UNAVAILABLE_CODE, } from './worker-protocol.js';
@@ -63,6 +63,7 @@ export function startSyncWorkerCore(overrides, createLocalAuthority) {
63
63
  let offline = false;
64
64
  let headers = {};
65
65
  let closed = false;
66
+ let pushingDiagnostics = false;
66
67
  // -- one sync loop: RPC-driven and auto-driven rounds serialize ----------
67
68
  let syncChain = Promise.resolve();
68
69
  function serializedSync(fn) {
@@ -73,8 +74,29 @@ export function startSyncWorkerCore(overrides, createLocalAuthority) {
73
74
  // -- SPEC §7.5 host loop: event-driven intents, no interactive polling --
74
75
  let autoSync = true;
75
76
  let autoSyncScheduled = false;
76
- let backgroundTimer;
77
+ let cancelBackground;
77
78
  let backgroundDue = Number.POSITIVE_INFINITY;
79
+ // §7.7 backoff for drives that end without a client retry intent.
80
+ let retryDelayMs = 250;
81
+ const scheduleBackground = overrides.scheduleBackground ??
82
+ ((callback, delayMs) => {
83
+ const timer = setTimeout(callback, delayMs);
84
+ return () => clearTimeout(timer);
85
+ });
86
+ const workerDiagnostics = (snapshot) => withClientDiagnosticsHost(snapshot, {
87
+ kind: 'worker',
88
+ role: 'leader',
89
+ connectivity: offline ? 'offline' : snapshot.host.connectivity,
90
+ realtime: snapshot.host.realtime,
91
+ });
92
+ const postDiagnostics = (snapshot) => {
93
+ if (!closed) {
94
+ post({
95
+ t: 'event',
96
+ event: { kind: 'diagnostics', snapshot: workerDiagnostics(snapshot) },
97
+ });
98
+ }
99
+ };
78
100
  function runAutoSync() {
79
101
  if (closed ||
80
102
  client === undefined ||
@@ -92,20 +114,42 @@ export function startSyncWorkerCore(overrides, createLocalAuthority) {
92
114
  return running.syncUntilIdle();
93
115
  })
94
116
  .then((summary) => {
117
+ retryDelayMs = 250;
95
118
  if (!closed)
96
119
  post({ t: 'event', event: { kind: 'synced', summary } });
97
120
  if (summary.budgetExhausted)
98
121
  consumeSyncIntent({ kind: 'interactive' });
99
122
  })
100
123
  .catch((error) => {
101
- if (!closed) {
102
- post({
103
- t: 'event',
104
- event: { kind: 'synced', error: toErrorShape(error) },
105
- });
124
+ if (closed)
125
+ return;
126
+ post({
127
+ t: 'event',
128
+ event: { kind: 'synced', error: toErrorShape(error) },
129
+ });
130
+ // §7.8: a retryable drive rejection owes another drive. A retryable
131
+ // round failure already handed this loop its background intent; the
132
+ // drive deadline did not. An unreachable endpoint waits for the
133
+ // host's connectivity resume (§1.8).
134
+ const causeKind = error instanceof ClientSyncError
135
+ ? error.details?.['causeKind']
136
+ : undefined;
137
+ if (error instanceof ClientSyncError &&
138
+ error.retryable &&
139
+ causeKind !== 'network' &&
140
+ causeKind !== 'connect' &&
141
+ cancelBackground === undefined &&
142
+ !autoSyncScheduled) {
143
+ consumeSyncIntent({ kind: 'background', delayMs: retryDelayMs });
144
+ retryDelayMs = Math.min(retryDelayMs * 2, 30_000);
106
145
  }
107
146
  });
108
147
  }
148
+ function stopBackground() {
149
+ cancelBackground?.();
150
+ cancelBackground = undefined;
151
+ backgroundDue = Number.POSITIVE_INFINITY;
152
+ }
109
153
  function consumeSyncIntent(intent) {
110
154
  if (!autoSync ||
111
155
  closed ||
@@ -119,13 +163,12 @@ export function startSyncWorkerCore(overrides, createLocalAuthority) {
119
163
  if (autoSyncScheduled)
120
164
  return;
121
165
  const due = Date.now() + Math.max(0, intent.delayMs);
122
- if (backgroundTimer !== undefined && due >= backgroundDue)
166
+ if (cancelBackground !== undefined && due >= backgroundDue)
123
167
  return;
124
- if (backgroundTimer !== undefined)
125
- clearTimeout(backgroundTimer);
168
+ cancelBackground?.();
126
169
  backgroundDue = due;
127
- backgroundTimer = setTimeout(() => {
128
- backgroundTimer = undefined;
170
+ cancelBackground = scheduleBackground(() => {
171
+ cancelBackground = undefined;
129
172
  backgroundDue = Number.POSITIVE_INFINITY;
130
173
  if (!autoSyncScheduled) {
131
174
  autoSyncScheduled = true;
@@ -134,11 +177,7 @@ export function startSyncWorkerCore(overrides, createLocalAuthority) {
134
177
  }, Math.max(0, due - Date.now()));
135
178
  return;
136
179
  }
137
- if (backgroundTimer !== undefined) {
138
- clearTimeout(backgroundTimer);
139
- backgroundTimer = undefined;
140
- backgroundDue = Number.POSITIVE_INFINITY;
141
- }
180
+ stopBackground();
142
181
  if (!autoSync || autoSyncScheduled || closed || client === undefined) {
143
182
  return;
144
183
  }
@@ -225,12 +264,12 @@ export function startSyncWorkerCore(overrides, createLocalAuthority) {
225
264
  ? { segments: bindings.segments }
226
265
  : {}),
227
266
  ...(blobs !== undefined ? { blobs } : {}),
228
- realtime: (handlers) => {
267
+ realtime: (handlers, clientId) => {
229
268
  // §12.2: a local authority has no realtime channel.
230
269
  if (realtimeConnector === undefined || local?.active()) {
231
- throw new ClientSyncError('sync.invalid_request', 'no realtime connector configured');
270
+ throw invalidRequest('no realtime connector configured');
232
271
  }
233
- return realtimeConnector(handlers);
272
+ return realtimeConnector(handlers, clientId);
234
273
  },
235
274
  ...(config.clientId !== undefined ? { clientId: config.clientId } : {}),
236
275
  ...(config.limits !== undefined ? { limits: config.limits } : {}),
@@ -240,6 +279,10 @@ export function startSyncWorkerCore(overrides, createLocalAuthority) {
240
279
  ...(config.realtimePolicy !== undefined
241
280
  ? { realtimePolicy: config.realtimePolicy }
242
281
  : {}),
282
+ ...(config.realtimeHeartbeatMs !== undefined
283
+ ? { realtimeHeartbeatMs: config.realtimeHeartbeatMs }
284
+ : {}),
285
+ schedule: scheduleBackground,
243
286
  ...(config.encryption !== undefined
244
287
  ? { encryption: encryptionConfigFromKeyring(config.encryption) }
245
288
  : {}),
@@ -266,9 +309,9 @@ export function startSyncWorkerCore(overrides, createLocalAuthority) {
266
309
  // §7.4.5: surface the schema-bump reset + completion to the UI thread.
267
310
  post({ t: 'event', event: { kind: 'upgrading', upgrading } });
268
311
  },
269
- onPresence: (scopeKey) => {
270
- // §8.6: surface a presence change to the UI thread.
271
- post({ t: 'event', event: { kind: 'presence', scopeKey } });
312
+ onPresence: (scopeKey, error) => {
313
+ // §8.6: surface a presence change or rejection to the UI thread.
314
+ post({ t: 'event', event: { kind: 'presence', scopeKey, error } });
272
315
  },
273
316
  });
274
317
  started.onProgress((progress) => {
@@ -279,29 +322,12 @@ export function startSyncWorkerCore(overrides, createLocalAuthority) {
279
322
  if (!closed)
280
323
  post({ t: 'event', event: { kind: 'change', batch } });
281
324
  });
282
- const postDiagnostics = (snapshot) => {
283
- if (closed)
284
- return;
285
- post({
286
- t: 'event',
287
- event: {
288
- kind: 'diagnostics',
289
- snapshot: withClientDiagnosticsHost(snapshot, {
290
- kind: 'worker',
291
- role: 'leader',
292
- connectivity: offline ? 'offline' : snapshot.host.connectivity,
293
- realtime: snapshot.host.realtime,
294
- }),
295
- },
296
- });
297
- };
298
- started.onDiagnostics(postDiagnostics);
299
325
  await started.start();
300
326
  realtimeConnector =
301
327
  overrides.createRealtime !== undefined
302
328
  ? overrides.createRealtime(config, started.clientId, http.headers)
303
329
  : config.endpoints.realtimeUrl !== undefined
304
- ? webSocketRealtimeConnector(config.endpoints.realtimeUrl.replace('{clientId}', encodeURIComponent(started.clientId)))
330
+ ? webSocketRealtimeConnector(config.endpoints.realtimeUrl)
305
331
  : undefined;
306
332
  client = started;
307
333
  // `start()` may discover persisted subscriptions/outbox work. Its callback
@@ -334,8 +360,8 @@ export function startSyncWorkerCore(overrides, createLocalAuthority) {
334
360
  'commitOutcomes',
335
361
  'resolveCommitOutcome',
336
362
  'pendingCommits',
337
- 'subscriptions',
338
- 'subscription',
363
+ 'units',
364
+ 'unit',
339
365
  'connectRealtime',
340
366
  'disconnectRealtime',
341
367
  'setPresence',
@@ -352,10 +378,7 @@ export function startSyncWorkerCore(overrides, createLocalAuthority) {
352
378
  },
353
379
  ])),
354
380
  beginSecurityPreflight: async () => {
355
- if (backgroundTimer !== undefined)
356
- clearTimeout(backgroundTimer);
357
- backgroundTimer = undefined;
358
- backgroundDue = Number.POSITIVE_INFINITY;
381
+ stopBackground();
359
382
  autoSyncScheduled = false;
360
383
  await requireClient().beginSecurityPreflight();
361
384
  },
@@ -392,14 +415,15 @@ export function startSyncWorkerCore(overrides, createLocalAuthority) {
392
415
  },
393
416
  resetClientId: () => requireClient().resetClientId(),
394
417
  localRevision: () => requireClient().localRevision,
395
- diagnosticsSnapshot: (request) => {
396
- const snapshot = requireClient().diagnosticsSnapshot(request);
397
- return withClientDiagnosticsHost(snapshot, {
398
- kind: 'worker',
399
- role: 'leader',
400
- connectivity: offline ? 'offline' : snapshot.host.connectivity,
401
- realtime: snapshot.host.realtime,
402
- });
418
+ diagnosticsSnapshot: () => {
419
+ const running = requireClient();
420
+ // The first pull makes the worker a push source: no tab has asked for
421
+ // diagnostics before it, so no snapshot is built per revision until then.
422
+ if (!pushingDiagnostics) {
423
+ pushingDiagnostics = true;
424
+ running.onDiagnostics(postDiagnostics);
425
+ }
426
+ return workerDiagnostics(running.diagnosticsSnapshot());
403
427
  },
404
428
  setHeaders: (next) => {
405
429
  headers = next;
@@ -408,32 +432,16 @@ export function startSyncWorkerCore(overrides, createLocalAuthority) {
408
432
  offline = value;
409
433
  requireClient().setTransportEnabled(!value);
410
434
  if (offline) {
411
- if (backgroundTimer !== undefined)
412
- clearTimeout(backgroundTimer);
413
- backgroundTimer = undefined;
414
- backgroundDue = Number.POSITIVE_INFINITY;
435
+ stopBackground();
415
436
  }
416
- else if (client !== undefined) {
417
- const snapshot = client.diagnosticsSnapshot();
418
- post({
419
- t: 'event',
420
- event: {
421
- kind: 'diagnostics',
422
- snapshot: withClientDiagnosticsHost(snapshot, {
423
- kind: 'worker',
424
- role: 'leader',
425
- connectivity: snapshot.host.connectivity,
426
- realtime: snapshot.host.realtime,
427
- }),
428
- },
429
- });
437
+ else if (client !== undefined && pushingDiagnostics) {
438
+ postDiagnostics(client.diagnosticsSnapshot());
430
439
  }
431
440
  },
432
441
  ...local?.methods,
433
442
  close: async () => {
434
443
  closed = true;
435
- if (backgroundTimer !== undefined)
436
- clearTimeout(backgroundTimer);
444
+ cancelBackground?.();
437
445
  await client?.close();
438
446
  local?.close();
439
447
  database?.close();
@@ -23,12 +23,12 @@ import type { PromiseMethods } from './client.js';
23
23
  * With `multiTab: false`, the loser is an `isLeader === false` handle whose
24
24
  * calls reject with `client.not_leader` (the single-tab contract).
25
25
  */
26
- import type { WakeReason } from '@syncular/core';
26
+ import { type PresenceErrorCode, type WakeReason } from '@syncular/core';
27
27
  import type { BlobRef, CachedBlob } from './blob.js';
28
- import type { ConflictRecord, CurrentBaseProof, MutationInput, PresencePeer, QueryReadSpec, QuerySnapshot, RejectionRecord, SecurityLifecycle, SnapshotRead, SnapshotReadRequest, SubscribeInput, SyncClientConfig, SyncClientLimits, SyncSummary, SyncIdleOptions, SyncIdleResult, WindowState } from './client.js';
28
+ import type { ConflictRecord, CurrentBaseProof, MutationInput, PresencePeer, QueryReadSpec, QuerySnapshot, RejectionRecord, SecurityLifecycle, SnapshotRead, SnapshotReadRequest, SyncClientConfig, SyncClientLimits, SyncSummary, SyncIdleOptions, SyncIdleResult, WindowState } from './client.js';
29
29
  import type { SqlRow, SqlValue } from './database.js';
30
30
  import type { DevtoolsRegistrar } from './devtools.js';
31
- import { ClientDiagnosticsEmitter, type ClientDiagnosticsListener, type ClientDiagnosticsRequest, type ClientDiagnosticsSnapshot, type RealtimePolicy } from './diagnostics.js';
31
+ import { ClientDiagnosticsEmitter, type ClientDiagnosticsListener, type ClientDiagnosticsSnapshot, type RealtimePolicy } from './diagnostics.js';
32
32
  import type { EncryptionKeyringConfig } from './encryption.js';
33
33
  import { ClientSyncError } from './errors.js';
34
34
  import { ChangeEmitter, type ClientChangeListener, InvalidationEmitter, type InvalidationListener, type LocalRevision, type SyncStatusSnapshot } from './invalidation.js';
@@ -40,7 +40,8 @@ import type { OutboxCommit } from './outbox.js';
40
40
  import type { CommitOutcome, CommitOutcomeQuery, ResolveCommitOutcomeInput } from './outcomes.js';
41
41
  import { type PreviousVersionAudit, type PreviousVersionReadSpec, type PreviousVersionSnapshot } from './previous-version.js';
42
42
  import type { ClientSchema } from './schema.js';
43
- import type { SubscriptionRecord } from './state.js';
43
+ import type { UnitScopes } from '@syncular/core';
44
+ import type { UnitRecord } from './state.js';
44
45
  import type { WindowBase } from './window.js';
45
46
  import { type LocalAuthorityState, type SyncWorkerEvent, type WorkerApi, type WorkerDatabaseInit, type WorkerEndpoints, type WorkerErrorShape, type WorkerSecurityActivation } from './worker-protocol.js';
46
47
  /** Classify startup without echoing a chunk URL or bundler text to UI/logs. */
@@ -101,6 +102,8 @@ export interface SyncClientHandleConfig {
101
102
  * `WorkerInitConfig`. Absent ⇒ `optional`.
102
103
  */
103
104
  readonly realtimePolicy?: RealtimePolicy;
105
+ /** SPEC §8.5 heartbeat interval, forwarded into `WorkerInitConfig`. */
106
+ readonly realtimeHeartbeatMs?: number;
104
107
  /**
105
108
  * RFC 0005 previous-version context, forwarded into the worker's
106
109
  * `SyncClientConfig`. Absent ⇒ the feature stays off (default-off).
@@ -151,8 +154,9 @@ export interface SyncClientHandleConfig {
151
154
  }) => void;
152
155
  /** §7.4.5: schema-bump `upgrading` state changed (reset began/completed). */
153
156
  readonly onUpgrading?: (upgrading: boolean) => void;
154
- /** §8.6: presence on a scope key changed. */
155
- readonly onPresence?: (scopeKey: string) => void;
157
+ /** §8.6: presence on a scope key changed, or the server refused this
158
+ * client's publish on it (`error`, §8.6.2). */
159
+ readonly onPresence?: (scopeKey: string, error?: PresenceErrorCode) => void;
156
160
  /** Atomic privacy-safe diagnostics changed. */
157
161
  readonly onDiagnostics?: (snapshot: ClientDiagnosticsSnapshot) => void;
158
162
  }
@@ -190,7 +194,7 @@ export declare class SyncClientHandle implements PromiseMethods<WorkerApi> {
190
194
  tabs?: TabCoordinator;
191
195
  invalidation: InvalidationEmitter;
192
196
  changes: ChangeEmitter;
193
- presence: Set<(scopeKey: string) => void>;
197
+ presence: Set<(scopeKey: string, error?: PresenceErrorCode) => void>;
194
198
  diagnostics: ClientDiagnosticsEmitter;
195
199
  roleListeners?: Set<(role: HandleRole) => void>;
196
200
  leadershipListeners?: Set<(state: LeadershipState) => void>;
@@ -220,7 +224,7 @@ export declare class SyncClientHandle implements PromiseMethods<WorkerApi> {
220
224
  * §8.6: subscribe to presence changes — the identical surface as
221
225
  * `SyncClient.onPresence`. Returns an unsubscribe function.
222
226
  */
223
- onPresence(listener: (scopeKey: string) => void): () => void;
227
+ onPresence(listener: (scopeKey: string, error?: PresenceErrorCode) => void): () => void;
224
228
  /** Subscribe to role transitions (follower → leader on promotion). */
225
229
  onRoleChange(listener: (role: HandleRole) => void): () => void;
226
230
  onLeadershipChange(listener: (state: LeadershipState) => void): () => void;
@@ -236,8 +240,8 @@ export declare class SyncClientHandle implements PromiseMethods<WorkerApi> {
236
240
  * worker still holds the database files.
237
241
  */
238
242
  takeOver(): Promise<void>;
239
- subscribe(input: SubscribeInput): Promise<void>;
240
- subscribeMany(inputs: readonly SubscribeInput[]): Promise<void>;
243
+ subscribe(scopes: UnitScopes): Promise<string>;
244
+ subscribeMany(units: readonly UnitScopes[]): Promise<string[]>;
241
245
  securityLifecycle(): Promise<SecurityLifecycle>;
242
246
  beginSecurityPreflight(): Promise<void>;
243
247
  activateSecurity(options?: WorkerSecurityActivation): Promise<void>;
@@ -272,7 +276,7 @@ export declare class SyncClientHandle implements PromiseMethods<WorkerApi> {
272
276
  snapshotRead<Row = SqlRow>(spec: SnapshotReadRequest): Promise<SnapshotRead<Row>>;
273
277
  localRevision(): Promise<LocalRevision>;
274
278
  statusSnapshot(): Promise<SyncStatusSnapshot>;
275
- diagnosticsSnapshot(request?: ClientDiagnosticsRequest): Promise<ClientDiagnosticsSnapshot>;
279
+ diagnosticsSnapshot(): Promise<ClientDiagnosticsSnapshot>;
276
280
  conflicts(): Promise<readonly ConflictRecord[]>;
277
281
  rejections(): Promise<readonly RejectionRecord[]>;
278
282
  commitOutcome(clientCommitId: string): Promise<CommitOutcome | undefined>;
@@ -280,8 +284,8 @@ export declare class SyncClientHandle implements PromiseMethods<WorkerApi> {
280
284
  resolveCommitOutcome(input: ResolveCommitOutcomeInput): Promise<CommitOutcome>;
281
285
  /** §7.4.5: true while a schema-bump reset + first re-bootstrap runs. */
282
286
  pendingCommits(): Promise<OutboxCommit[]>;
283
- subscriptions(): Promise<SubscriptionRecord[]>;
284
- subscription(id: string): Promise<SubscriptionRecord | undefined>;
287
+ units(): Promise<UnitRecord[]>;
288
+ unit(id: string): Promise<UnitRecord | undefined>;
285
289
  connectRealtime(): Promise<void>;
286
290
  disconnectRealtime(): Promise<void>;
287
291
  /** §8.6: publish/clear a scope-keyed presence document. */
@@ -292,6 +296,8 @@ export declare class SyncClientHandle implements PromiseMethods<WorkerApi> {
292
296
  readonly mediaType?: string;
293
297
  readonly name?: string;
294
298
  }): Promise<BlobRef>;
299
+ /** Serialize a BlobRef to the canonical string a `blob_ref` column holds. */
300
+ blobRefString(ref: BlobRef): string;
295
301
  fetchBlob(blobIdOrRef: string): Promise<CachedBlob>;
296
302
  /**
297
303
  * Replace the full host auth header set. The next HTTP request uses it;