@syncular/client 0.59.0 → 0.60.1

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 (66) hide show
  1. package/README.md +27 -27
  2. package/dist/apply.d.ts +6 -5
  3. package/dist/apply.js +52 -25
  4. package/dist/authority.js +21 -16
  5. package/dist/blob.d.ts +4 -4
  6. package/dist/bun-database.js +3 -16
  7. package/dist/client.d.ts +57 -66
  8. package/dist/client.js +701 -796
  9. package/dist/devtools.d.ts +2 -2
  10. package/dist/devtools.js +3 -3
  11. package/dist/diagnostics.d.ts +17 -28
  12. package/dist/diagnostics.js +1 -2
  13. package/dist/errors.d.ts +1 -1
  14. package/dist/errors.js +1 -1
  15. package/dist/failed-overlay.js +4 -1
  16. package/dist/http.js +19 -5
  17. package/dist/invalidation.d.ts +3 -4
  18. package/dist/invalidation.js +9 -22
  19. package/dist/native-bridge.d.ts +7 -16
  20. package/dist/native-bridge.js +16 -41
  21. package/dist/node-database.js +16 -25
  22. package/dist/outbox.js +1 -0
  23. package/dist/progress.d.ts +2 -2
  24. package/dist/query-guard.d.ts +15 -6
  25. package/dist/query-guard.js +38 -6
  26. package/dist/reactive-store.js +2 -2
  27. package/dist/remote.js +9 -9
  28. package/dist/schema.d.ts +3 -2
  29. package/dist/schema.js +28 -12
  30. package/dist/state.d.ts +69 -36
  31. package/dist/state.js +178 -89
  32. package/dist/sync-scheduler.js +2 -2
  33. package/dist/transport.d.ts +2 -2
  34. package/dist/window.d.ts +30 -52
  35. package/dist/window.js +33 -77
  36. package/dist/worker-core.js +6 -6
  37. package/dist/worker-host.d.ts +9 -8
  38. package/dist/worker-host.js +23 -14
  39. package/dist/worker-protocol.d.ts +9 -8
  40. package/package.json +3 -3
  41. package/src/apply.ts +87 -33
  42. package/src/authority.ts +31 -17
  43. package/src/blob.ts +4 -3
  44. package/src/bun-database.ts +9 -14
  45. package/src/client.ts +886 -1037
  46. package/src/devtools.ts +5 -5
  47. package/src/diagnostics.ts +17 -37
  48. package/src/errors.ts +1 -1
  49. package/src/failed-overlay.ts +6 -1
  50. package/src/http.ts +22 -9
  51. package/src/invalidation.ts +9 -29
  52. package/src/native-bridge.ts +22 -58
  53. package/src/node-database.ts +26 -27
  54. package/src/outbox.ts +1 -0
  55. package/src/progress.ts +2 -2
  56. package/src/query-guard.ts +45 -8
  57. package/src/reactive-store.ts +2 -2
  58. package/src/remote.ts +12 -16
  59. package/src/schema.ts +48 -13
  60. package/src/state.ts +246 -125
  61. package/src/sync-scheduler.ts +2 -2
  62. package/src/transport.ts +2 -2
  63. package/src/window.ts +55 -134
  64. package/src/worker-core.ts +6 -6
  65. package/src/worker-host.ts +27 -19
  66. package/src/worker-protocol.ts +8 -8
@@ -3,8 +3,9 @@
3
3
  * `snapshotRead()`, the untrusted raw-SQL tier. Each `ClientDatabase` adapter
4
4
  * prepares only the first statement and reports what SQLite knows about it:
5
5
  *
6
- * 1. READ-ONLY. SQLite decides (`sqlite3_stmt_readonly`) and the statement
7
- * returns columns, which refuses `BEGIN`, `ATTACH` and the other
6
+ * 1. READ-ONLY. SQLite decides (`sqlite3_stmt_readonly`, or `query_only`
7
+ * on the first run of a text, `runReadOnly`) and the statement returns
8
+ * columns, which refuses `BEGIN`, `ATTACH` and the other
8
9
  * read-only statements that change the connection. A write against the
9
10
  * local mirror bypasses the outbox (SPEC §7.1); writes go through
10
11
  * `client.mutate([...])`.
@@ -23,10 +24,8 @@
23
24
  export class RawSqlError extends Error {
24
25
  name = 'RawSqlError';
25
26
  }
26
- /** Leading whitespace, comments and empty statements. */
27
- export const SQL_BLANK = /^(?:[\s;]|--[^\n]*(?:\n|$)|\/\*(?:[^*]|\*(?!\/))*(?:\*\/|$))*/;
28
27
  /** Refuse a statement the raw-SQL tier does not run. */
29
- export function refuseRawSql() {
28
+ function refuseRawSql() {
30
29
  throw new RawSqlError('client.query() runs read-only statements and no PRAGMA; write through client.mutate() so the outbox records it (SPEC §7.1).');
31
30
  }
32
31
  /**
@@ -39,10 +38,43 @@ export function prepareReadOnly(sql, prepare) {
39
38
  refuseRawSql();
40
39
  }
41
40
  const [statement, first, reads] = prepare();
42
- if (sql.slice(first.length).replace(SQL_BLANK, '') !== '') {
41
+ if (sql
42
+ .slice(first.length)
43
+ .replace(/^(?:[\s;]|--[^\n]*(?:\n|$)|\/\*(?:[^*]|\*(?!\/))*(?:\*\/|$))*/, '') !== '') {
43
44
  throw new RawSqlError('client.query() runs one statement per call.');
44
45
  }
45
46
  if (!reads)
46
47
  refuseRawSql();
47
48
  return statement;
48
49
  }
50
+ /**
51
+ * Run a statement `prepareReadOnly` accepted on an adapter without
52
+ * `sqlite3_stmt_readonly` (bun:sqlite before 1.4.4, node:sqlite). SQLite
53
+ * refuses a write when it runs: under `query_only` a write transaction fails
54
+ * before it changes anything, and `refused` recognizes that error. The
55
+ * verdict depends on the text alone, since a write fails at its write
56
+ * transaction whether or not it touches a row, so a text that completed
57
+ * under `query_only` joins `proven` and later runs skip the pragma: a flag
58
+ * pragma expires every prepared statement of the connection. `proven` is per
59
+ * connection and cleared at 512 texts, so dynamic SQL cannot grow it.
60
+ */
61
+ export function runReadOnly(proven, sql, pragma, refused, run) {
62
+ if (proven.has(sql))
63
+ return run();
64
+ pragma('PRAGMA query_only = ON');
65
+ try {
66
+ const result = run();
67
+ if (proven.size >= 512)
68
+ proven.clear();
69
+ proven.add(sql);
70
+ return result;
71
+ }
72
+ catch (error) {
73
+ if (refused(error))
74
+ refuseRawSql();
75
+ throw error;
76
+ }
77
+ finally {
78
+ pragma('PRAGMA query_only = OFF');
79
+ }
80
+ }
@@ -404,7 +404,7 @@ class QueryEntry {
404
404
  this.store.releaseWindowClaims(this.#owner);
405
405
  this.reset();
406
406
  }
407
- /** SPEC §7.7: a rejected claim is claimed again; its stored error would
407
+ /** SPEC §7.8: a rejected claim is claimed again; its stored error would
408
408
  * fail every read until the last subscriber leaves. */
409
409
  reclaim() {
410
410
  if (this.#delegate !== undefined || this.#claimError === undefined)
@@ -1048,7 +1048,7 @@ export class ReactiveClientStore {
1048
1048
  const roundFailure = this.roundFailure;
1049
1049
  let claimedAttempt;
1050
1050
  this.#offProgress = this.client.onProgress((progress) => {
1051
- // A new sync attempt is the client's retry schedule (§7.6): window
1051
+ // A new sync attempt is the client's retry schedule (§7.7): window
1052
1052
  // claims that failed are claimed again once per attempt.
1053
1053
  if (progress.state === 'running' && progress.attempt !== claimedAttempt) {
1054
1054
  claimedAttempt = progress.attempt;
package/dist/remote.js CHANGED
@@ -2,7 +2,7 @@
2
2
  * Database-less SSP2 producer (§6.10). It prepares and sends ordinary commits
3
3
  * through the existing push path without creating a local replica or outbox.
4
4
  */
5
- import { decodeMessage, decodeRemoteOperationResponse, decodeRemoteOperationRealtimeMessage, encodeMessage, encodeRemoteOperationRequest, encodeRemoteOperationRealtimeMessage, encodeSparseRow, normalizeRejectionDetails, PROTOCOL_WIRE_VERSION, } from '@syncular/core';
5
+ import { decodeResponse, decodeRemoteOperationResponse, decodeRemoteOperationRealtimeMessage, encodeRequest, encodeRemoteOperationRequest, encodeRemoteOperationRealtimeMessage, encodeSparseRow, normalizeRejectionDetails, PROTOCOL_WIRE_VERSION, registrationDigest, } from '@syncular/core';
6
6
  import { encryptRowValues } from './encryption.js';
7
7
  import { ClientSyncError, invalidRequest } from './errors.js';
8
8
  import { compileClientSchema, recordToRowValues, normalizeRecordKeys, coerceSqlRepresentation, } from './schema.js';
@@ -117,7 +117,7 @@ export class SyncRemoteClient {
117
117
  if (this.#transport === undefined) {
118
118
  throw new ClientSyncError('client.remote_sync_unconfigured', 'SyncRemoteClient has no sync transport for ordinary commits');
119
119
  }
120
- const acquisition = decodeMessage(await this.#transport(encodeMessage({
120
+ const acquisition = decodeResponse(await this.#transport(encodeRequest({
121
121
  wireVersion: PROTOCOL_WIRE_VERSION,
122
122
  msgKind: 'request',
123
123
  frames: [
@@ -133,12 +133,14 @@ export class SyncRemoteClient {
133
133
  limitSnapshotRows: 0,
134
134
  maxSnapshotPages: 0,
135
135
  accept: 0b0011,
136
+ cursor: -1,
137
+ registrationDigest: registrationDigest([]),
138
+ echoDigest: new Uint8Array(),
136
139
  },
137
140
  ],
138
141
  })));
139
142
  const acquisitionHeader = acquisition.frames[0];
140
- if (acquisition.msgKind !== 'response' ||
141
- acquisitionHeader?.type !== 'RESP_HEADER') {
143
+ if (acquisitionHeader?.type !== 'RESP_HEADER') {
142
144
  throw new ClientSyncError('client.invalid_host_response', 'remote epoch acquisition returned an invalid response');
143
145
  }
144
146
  logEpoch = acquisitionHeader.logEpoch;
@@ -195,7 +197,7 @@ export class SyncRemoteClient {
195
197
  }
196
198
  return {
197
199
  requestId: input.requestId,
198
- bytes: encodeMessage({
200
+ bytes: encodeRequest({
199
201
  wireVersion: PROTOCOL_WIRE_VERSION,
200
202
  msgKind: 'request',
201
203
  frames: [
@@ -208,6 +210,7 @@ export class SyncRemoteClient {
208
210
  {
209
211
  type: 'PUSH_COMMIT',
210
212
  clientCommitId: input.requestId,
213
+ clientSeq: 0,
211
214
  operations,
212
215
  },
213
216
  ],
@@ -218,10 +221,7 @@ export class SyncRemoteClient {
218
221
  if (this.#transport === undefined) {
219
222
  throw new ClientSyncError('client.remote_sync_unconfigured', 'SyncRemoteClient has no sync transport for ordinary commits');
220
223
  }
221
- const response = decodeMessage(await this.#transport(prepared.bytes));
222
- if (response.msgKind !== 'response') {
223
- throw new ClientSyncError('client.invalid_host_response', 'remote commit transport returned a non-response SSP2 message');
224
- }
224
+ const response = decodeResponse(await this.#transport(prepared.bytes));
225
225
  const error = response.frames.find((frame) => frame.type === 'ERROR');
226
226
  if (error?.type === 'ERROR') {
227
227
  throw new ClientSyncError(error.code, error.message, error.retryable);
package/dist/schema.d.ts CHANGED
@@ -130,10 +130,10 @@ export declare function ensureLocalSchema(db: ClientDatabase, schema: CompiledCl
130
130
  * generated schema created — discovered from `sqlite_master`, since a
131
131
  * bump may add/remove tables) and recreate the synced tables from the
132
132
  * NEW schema. Bookkeeping tables (`_syncular_*`: outbox, meta,
133
- * subscriptions, blob cache) are preserved. RFC 0005's container is not
133
+ * units, blob cache) are preserved. RFC 0005's container is not
134
134
  * reachable from here: it lives in its own database file, so this reset cannot
135
135
  * see or destroy it. Caller owns the surrounding transaction and the
136
- * subscription-state reset (state.ts).
136
+ * unit-state reset (state.ts).
137
137
  */
138
138
  export declare function dropAndRecreateSyncedTables(db: ClientDatabase, schema: CompiledClientSchema): void;
139
139
  /** RowValue → SQL bind value for the local mirror tables. */
@@ -165,6 +165,7 @@ export declare function recordToRowValues(table: CompiledClientTable, record: Re
165
165
  export type JsonRowValue = string | number | boolean | null | {
166
166
  readonly $bytes: string;
167
167
  };
168
+ export declare function bytesToHex(bytes: Uint8Array): string;
168
169
  /**
169
170
  * The canonical §7.1 byte envelope: exactly one `$bytes` key holding a string
170
171
  * of hexadecimal digit pairs. Uppercase digits are accepted; encoders emit
package/dist/schema.js CHANGED
@@ -3,9 +3,9 @@ import { PENDING_EVICTIONS } from './window.js';
3
3
  import { WINDOWS_TABLE } from './window.js';
4
4
  import { OUTBOX_TABLE, OUTBOX_IMAGES } from './outbox.js';
5
5
  import { OUTCOMES_TABLE } from './outcomes.js';
6
- import { SUBSCRIPTIONS_TABLE, META_TABLE } from './state.js';
6
+ import { META_TABLE, resetUnits, UNITS_TABLE } from './state.js';
7
7
  import { ensureFailedOverlaySchema } from './failed-overlay.js';
8
- import { invalidRequest } from './errors.js';
8
+ import { ClientSyncError, invalidRequest } from './errors.js';
9
9
  import { snakeToCamel } from './naming.js';
10
10
  const PATTERN_RE = /^([^{}]+):\{([^{}:]+)\}$/;
11
11
  const ALLOWED_FTS_TOKENIZERS = new Set([
@@ -405,7 +405,11 @@ export function ensureLocalBookkeepingSchema(db) {
405
405
  createTable(BLOB_COMMIT_REFS, 'commit_id TEXT NOT NULL,blob_id TEXT NOT NULL,PRIMARY KEY(commit_id,blob_id)');
406
406
  db.exec(`CREATE INDEX IF NOT EXISTS ${BLOB_COMMIT_REFS}_body ON ${BLOB_COMMIT_REFS}(blob_id)`);
407
407
  db.exec(`INSERT OR IGNORE INTO ${META_TABLE}(key,value)VALUES('localRevision','0')`);
408
+ const outboxExisted = db.query(`SELECT 1 FROM sqlite_master WHERE type='table' AND name='${OUTBOX_TABLE}'`).length > 0;
408
409
  createTable(OUTBOX_TABLE, 'seq INTEGER PRIMARY KEY AUTOINCREMENT,client_commit_id TEXT NOT NULL UNIQUE,created_at_ms INTEGER NOT NULL,operations TEXT NOT NULL');
410
+ // §7.1: `outboxId` names the outbox sequence. A new outbox table starts
411
+ // a new sequence, so it replaces the id in the same transaction.
412
+ db.exec(`INSERT OR ${outboxExisted ? 'IGNORE' : 'REPLACE'} INTO ${META_TABLE}(key,value)VALUES('outboxId',?)`, [crypto.randomUUID()]);
409
413
  createTable(OUTBOX_IMAGES, 'client_commit_id TEXT NOT NULL,op_index INTEGER NOT NULL,existed INTEGER NOT NULL CHECK(existed IN (0,1)),sync_version INTEGER,values_json TEXT,PRIMARY KEY(client_commit_id,op_index)');
410
414
  const imageColumns = db.query(`PRAGMA table_info(${OUTBOX_IMAGES})`);
411
415
  for (const column of ['delivery_seq INTEGER', 'tbl TEXT', 'row_id TEXT'])
@@ -425,14 +429,26 @@ export function ensureLocalBookkeepingSchema(db) {
425
429
  // column already exists — the CREATE above included it
426
430
  }
427
431
  db.exec(`CREATE INDEX IF NOT EXISTS ${OUTCOMES_TABLE}_resolution_seq ON ${OUTCOMES_TABLE}(resolution,seq)`);
428
- createTable(SUBSCRIPTIONS_TABLE, "id TEXT PRIMARY KEY,tbl TEXT NOT NULL,requested_scopes TEXT NOT NULL,params TEXT,cursor INTEGER NOT NULL DEFAULT -1,bootstrap_state TEXT,effective_scopes TEXT,status TEXT NOT NULL DEFAULT 'active',reason_code TEXT");
429
- // §4.8 window registry: which units (scope values) of a window base are
430
- // live locally — the completeness oracle (I3) and the shrink driver
431
- // (a unit's omission from the next pull unregisters it, §4.1).
432
+ createTable(UNITS_TABLE, "id TEXT PRIMARY KEY,scopes TEXT NOT NULL,explicit INTEGER NOT NULL DEFAULT 0,status TEXT NOT NULL DEFAULT 'active',reason_code TEXT,cursor INTEGER DEFAULT -1,bootstrap_state TEXT,seeded TEXT NOT NULL DEFAULT '[]',echo TEXT");
433
+ // §4.8 window registry: base + value → the unit it holds, the
434
+ // completeness oracle and one of a unit's references (§4.1).
432
435
  createTable(WINDOWS_TABLE, 'base TEXT NOT NULL,unit TEXT NOT NULL,sub_id TEXT NOT NULL,PRIMARY KEY(base,unit)');
433
- // §4.8 E1: units that left the window but still had outbox-pinned rows.
434
- // Retried when the outbox drains; cancelled if the unit re-enters.
435
- createTable(PENDING_EVICTIONS, 'sub_id TEXT PRIMARY KEY,tbl TEXT NOT NULL,effective_scopes TEXT NOT NULL');
436
+ // §4.8 E1: per-table scopes of units that left with pinned or unevicted
437
+ // rows. Retried when the outbox drains; cancelled when the unit re-enters.
438
+ createTable(PENDING_EVICTIONS, 'unit_id TEXT NOT NULL,tbl TEXT NOT NULL,effective_scopes TEXT NOT NULL,PRIMARY KEY(unit_id,tbl)');
439
+ // §9: a replica written under wire version 3 keeps its outbox, journal,
440
+ // rows and pending evictions and registers its units fresh. Its
441
+ // subscriptions, cursors, echoes, resume tokens and window entries go.
442
+ const legacyEvictions = '_syncular_window_pending_evict';
443
+ if (db.query(`SELECT 1 FROM sqlite_master WHERE type='table' AND name='${legacyEvictions}'`).length > 0) {
444
+ if (db.query(`SELECT 1 FROM ${legacyEvictions} WHERE NOT json_valid(effective_scopes) OR json_type(effective_scopes)<>'object' OR EXISTS(SELECT 1 FROM json_each(effective_scopes) WHERE json_type(value)<>'array' OR EXISTS(SELECT 1 FROM json_each(value) v WHERE v.type<>'text'))`).length > 0)
445
+ throw new ClientSyncError('sync.local_corrupt', 'a version 3 pending eviction cannot be upgraded');
446
+ db.exec(`INSERT OR REPLACE INTO ${PENDING_EVICTIONS} SELECT sub_id,tbl,effective_scopes FROM ${legacyEvictions}`);
447
+ db.exec(`DROP TABLE ${legacyEvictions}`);
448
+ db.exec('DROP TABLE IF EXISTS _syncular_subscriptions');
449
+ db.exec(`DELETE FROM ${WINDOWS_TABLE}`);
450
+ resetUnits(db);
451
+ }
436
452
  });
437
453
  }
438
454
  /** Create both application and protected bookkeeping tables. */
@@ -447,10 +463,10 @@ const RESERVED_TABLE_PREFIX = '_syncular_';
447
463
  * generated schema created — discovered from `sqlite_master`, since a
448
464
  * bump may add/remove tables) and recreate the synced tables from the
449
465
  * NEW schema. Bookkeeping tables (`_syncular_*`: outbox, meta,
450
- * subscriptions, blob cache) are preserved. RFC 0005's container is not
466
+ * units, blob cache) are preserved. RFC 0005's container is not
451
467
  * reachable from here: it lives in its own database file, so this reset cannot
452
468
  * see or destroy it. Caller owns the surrounding transaction and the
453
- * subscription-state reset (state.ts).
469
+ * unit-state reset (state.ts).
454
470
  */
455
471
  export function dropAndRecreateSyncedTables(db, schema) {
456
472
  // Drop virtual tables first. SQLite then removes their shadow tables as one
@@ -562,7 +578,7 @@ export function recordToRowValues(table, record) {
562
578
  return coerceSqlRepresentation(column, value);
563
579
  });
564
580
  }
565
- function bytesToHex(bytes) {
581
+ export function bytesToHex(bytes) {
566
582
  let out = '';
567
583
  for (const byte of bytes)
568
584
  out += byte.toString(16).padStart(2, '0');
package/dist/state.d.ts CHANGED
@@ -1,50 +1,83 @@
1
1
  export declare const META_TABLE = "_syncular_meta";
2
- export declare const SUBSCRIPTIONS_TABLE = "_syncular_subscriptions";
2
+ export declare const UNITS_TABLE = "_syncular_units";
3
3
  /**
4
- * Durable client sync state: per-subscription cursor, bootstrap resume
5
- * token (round-tripped opaquely, §4.7), and the last-echoed effective
6
- * scopes the §3.3 purge contract is keyed on — persisted per subscription
7
- * exactly for that purpose.
4
+ * Durable unit state (SPEC.md §4.1): per unit its scope map, status, live
5
+ * membership, catch-up cursor and opaque resume token (§4.7), the tables its
6
+ * current bootstrap seeded (§5.6) and the last echo (§4.4) the §3.3 purge
7
+ * contract is keyed on. The replica cursor, the echo digest and the
8
+ * registration digest the server holds live in meta.
8
9
  */
9
- import type { ScopeMap } from '@syncular/core';
10
- import type { CompiledClientSchema } from './schema.js';
10
+ import type { FencedRecord, ScopeMap, UnitScopes } from '@syncular/core';
11
+ import type { CompiledClientSchema, CompiledClientTable } from './schema.js';
11
12
  import type { ClientDatabase } from './database.js';
12
13
  import type { LocalRevision } from './invalidation.js';
13
14
  export declare const LOCAL_REVISION_KEY = "localRevision";
14
- export type SubscriptionStatus = 'active' | 'revoked' | 'failed';
15
- export interface SubscriptionRecord {
15
+ /** §4.5 replica cursor; absent means `-1`. */
16
+ export declare const REPLICA_CURSOR_KEY = "replicaCursor";
17
+ /** Hex of the last pull `LIVE_END.echoDigest` (§4.2); absent means empty. */
18
+ export declare const ECHO_DIGEST_KEY = "echoDigest";
19
+ /** Hex of the registration digest of the list the server stores (§4.1). */
20
+ export declare const REGISTERED_DIGEST_KEY = "registrationDigest";
21
+ export type UnitStatus = 'active' | 'revoked' | 'failed';
22
+ export interface UnitRecord {
23
+ /** §4.1: derived from the scope map. */
16
24
  readonly id: string;
17
- readonly table: string;
18
- /** Requested scopes (§3.2), chosen by the app. */
19
- readonly scopes: ScopeMap;
20
- /** Host-opaque JSON params, preserved verbatim. */
21
- readonly params?: string;
22
- /** Last fully-applied commitSeq; -1 = never synced (§4.3). */
23
- readonly cursor: number;
25
+ readonly scopes: UnitScopes;
26
+ /** An explicit `subscribe` holds the unit; window bases hold it through
27
+ * the window registry (§4.1 references). */
28
+ readonly explicit: boolean;
29
+ readonly status: UnitStatus;
30
+ /** §10 code when not active, or `sync.cursor_expired` after a reset. */
31
+ readonly reasonCode?: string | undefined;
32
+ /** Absent while the unit is live (§4.5); otherwise `-1`, the pin, or the
33
+ * post-bootstrap cursor `P`. */
34
+ readonly cursor?: number | undefined;
24
35
  /** Opaque resume token from `SUB_END` (§4.7); present mid-bootstrap. */
25
- readonly bootstrapState?: string;
26
- /** Last effective scopes echoed while active (§3.3 purge key). */
27
- readonly effectiveScopes?: ScopeMap;
28
- readonly status: SubscriptionStatus;
29
- /** §10 code when not active (`sync.scope_revoked`, …). */
30
- readonly reasonCode?: string;
36
+ readonly bootstrapState?: string | undefined;
37
+ /** Tables that received a segment in the current bootstrap (§5.6). */
38
+ readonly seeded: readonly string[];
39
+ /** The echo persisted at the last `SUB_END` (§4.4). */
40
+ readonly echo?: readonly FencedRecord[] | undefined;
31
41
  }
32
- export declare function loadSubscriptions(db: ClientDatabase): SubscriptionRecord[];
33
- export declare function getSubscription(db: ClientDatabase, id: string): SubscriptionRecord | undefined;
34
- export declare function saveSubscription(db: ClientDatabase, record: SubscriptionRecord): void;
35
- export declare function deleteSubscription(db: ClientDatabase, id: string): void;
42
+ /** §4.1: a catching-up unit holding cursor `-1` or a resume token. */
43
+ export declare function bootstrapping(unit: UnitRecord): boolean;
44
+ /** §3.3 row ownership: active, live or post-bootstrap, with an echo. */
45
+ export declare function owning(unit: UnitRecord): boolean;
46
+ /** §4.1: the unit covers every table declaring all of its variables. */
47
+ export declare function covers(table: CompiledClientTable, scopes: UnitScopes): boolean;
36
48
  /**
37
- * §7.4.3 reset: keep compatible subscription REGISTRATIONS (id, table,
38
- * requested scopes, params — the app's declared intent) but discard all
39
- * synced state (cursor → -1, no resume token, no effective-scope map,
40
- * status → active), so the next round fresh-bootstraps exactly the
41
- * subscriptions the app still wants. Caller owns the transaction.
49
+ * §4.4: the effective scopes of the (unit, table) pair under `echo`: the
50
+ * scope map as one-element lists plus the fenced lists. Undefined when the
51
+ * fence revoked the pair.
42
52
  */
43
- export declare function resetSubscriptionsForBump(db: ClientDatabase): void;
44
- /** Persist declarations separately from the previous-version row descriptor. */
45
- export declare function saveSubscriptionScopeSchema(db: ClientDatabase, schema: CompiledClientSchema): void;
46
- /** Drop incompatible registrations and their windows; never translate scopes. */
47
- export declare function pruneUnknownSubscriptions(db: ClientDatabase, subscriptions: readonly SubscriptionRecord[], schema: CompiledClientSchema, bump?: boolean): SubscriptionRecord[];
53
+ export declare function pairScopes(scopes: UnitScopes, table: string, echo: readonly FencedRecord[] | undefined): ScopeMap | undefined;
54
+ /** §3.3 row ownership: the pair scopes of every owner of `table` but one.
55
+ * A bootstrapping unit owns the tables its current bootstrap seeded. */
56
+ export declare function unitOwners(units: readonly UnitRecord[], table: CompiledClientTable, exceptId: string): ScopeMap[];
57
+ /** Every unit in registration order (§4.1). */
58
+ export declare function loadUnits(db: ClientDatabase): UnitRecord[];
59
+ export declare function getUnit(db: ClientDatabase, id: string): UnitRecord | undefined;
60
+ /** Insert or update in place: an update keeps the registration order. */
61
+ export declare function saveUnit(db: ClientDatabase, record: UnitRecord): void;
62
+ export declare function deleteUnit(db: ClientDatabase, id: string): void;
63
+ /**
64
+ * §7.4.3 reset, §2.1 log reset and local rebootstrap: keep the unit
65
+ * registrations (the app's declared intent) and discard every synced state,
66
+ * so the next round sends the list and fresh-bootstraps every unit. Caller
67
+ * owns the transaction.
68
+ */
69
+ export declare function resetUnits(db: ClientDatabase): void;
70
+ /** §4.5: the replica cursor, `-1` while no unit is live. */
71
+ export declare function replicaCursor(db: ClientDatabase): number;
72
+ /** §7.4.3 declaration evidence, persisted beside the schema marker. */
73
+ export declare function saveUnitScopeSchema(db: ClientDatabase, schema: CompiledClientSchema): void;
74
+ /**
75
+ * Drop units that cover no table of the running schema, with their window
76
+ * registry rows and pending evictions; never translate scopes. At a bump
77
+ * (§7.4.3) a unit also needs every variable unchanged in prefix and column on
78
+ * every table it covered before.
79
+ */
80
+ export declare function pruneUnknownUnits(db: ClientDatabase, schema: CompiledClientSchema, bump?: boolean): void;
48
81
  export declare function getMeta(db: ClientDatabase, key: string): string | undefined;
49
82
  export declare function setMeta(db: ClientDatabase, key: string, value: string): void;
50
83
  /** Read the durable client-local observer revision (SPEC §7.5). */