@syncular/client 0.67.3 → 0.69.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/src/outbox.ts CHANGED
@@ -10,6 +10,7 @@ import type { OverlayScope } from './failed-overlay';
10
10
  * upgrade to N+1 by re-encoding.
11
11
  */
12
12
  import {
13
+ definedObject,
13
14
  encodeSparseRow,
14
15
  type PushCommitFrame,
15
16
  type PushOperation,
@@ -52,6 +53,27 @@ export interface OutboxCommit {
52
53
  readonly operations: readonly OutboxOperation[];
53
54
  }
54
55
 
56
+ /**
57
+ * §7.1 chained base: `later` repeats `earlier`'s positive base on the same row
58
+ * and presents only columns `earlier` presents.
59
+ */
60
+ export function chainsOn(
61
+ earlier: OutboxOperation,
62
+ later: OutboxOperation,
63
+ ): boolean {
64
+ // Only an upsert carries values, and it always carries its primary key.
65
+ return (
66
+ later.op === 'upsert' &&
67
+ earlier.rowId === later.rowId &&
68
+ earlier.table === later.table &&
69
+ later.baseVersion! > 0 &&
70
+ earlier.baseVersion === later.baseVersion &&
71
+ Object.keys(later.values ?? {}).every(
72
+ (column) => earlier.values?.[column] !== undefined,
73
+ )
74
+ );
75
+ }
76
+
55
77
  /** Protected local rollback image; never encoded or exposed in outcomes. */
56
78
  export interface OutboxBeforeImage {
57
79
  readonly opIndex: number;
@@ -209,8 +231,12 @@ export function replaceOutboxBeforeImages(
209
231
  * so the caller can drop the commit through the rejection channel.
210
232
  */
211
233
  export class OutboxEncodeError extends ClientSyncError {
212
- constructor(message: string) {
213
- super('sync.outbox_incompatible', message, false);
234
+ constructor() {
235
+ super(
236
+ 'sync.outbox_incompatible',
237
+ 'the persisted commit cannot encode under the current schema',
238
+ false,
239
+ );
214
240
  }
215
241
  }
216
242
 
@@ -223,9 +249,7 @@ function sparseValues(
223
249
  // bump removed (or renamed) it — the commit cannot be expressed now.
224
250
  for (const key of Object.keys(values)) {
225
251
  if (!table.columnIndex.has(key)) {
226
- throw new OutboxEncodeError(
227
- `outbox column ${JSON.stringify(key)} is absent from table ${JSON.stringify(table.name)} (§7.4.4)`,
228
- );
252
+ throw new OutboxEncodeError();
229
253
  }
230
254
  }
231
255
  return table.columns.map((column) => {
@@ -234,9 +258,7 @@ function sparseValues(
234
258
  if (!insert) return undefined;
235
259
  // §7.1: an insert-intent operation presents every current column.
236
260
  if (!column.nullable) {
237
- throw new OutboxEncodeError(
238
- 'an outbox insert lacks a non-nullable column (§7.4.4)',
239
- );
261
+ throw new OutboxEncodeError();
240
262
  }
241
263
  return null;
242
264
  });
@@ -262,27 +284,23 @@ export async function encodeOutboxCommit(
262
284
  const operations: PushOperation[] = [];
263
285
  for (const op of commit.operations) {
264
286
  if (op.op === 'delete') {
265
- operations.push({
266
- table: op.table,
267
- rowId: op.rowId,
268
- op: 'delete',
269
- ...(op.baseVersion !== undefined
270
- ? { baseVersion: op.baseVersion }
271
- : {}),
272
- });
287
+ operations.push(
288
+ definedObject({
289
+ table: op.table,
290
+ rowId: op.rowId,
291
+ op: 'delete',
292
+ baseVersion: op.baseVersion,
293
+ }),
294
+ );
273
295
  continue;
274
296
  }
275
297
  const table = schema.tables.get(op.table);
276
298
  if (table === undefined) {
277
299
  // §7.4.4: the bump removed this table — the commit cannot be encoded.
278
- throw new OutboxEncodeError(
279
- `outbox table ${JSON.stringify(op.table)} is absent from the current schema (§7.4.4)`,
280
- );
300
+ throw new OutboxEncodeError();
281
301
  }
282
302
  if (op.values === undefined) {
283
- throw invalidRequest(
284
- `outbox upsert on ${op.table}/${op.rowId} has no values`,
285
- );
303
+ throw invalidRequest('an outbox upsert has no values');
286
304
  }
287
305
  let values = sparseValues(table, op.values, op.insert === true);
288
306
  if (table.hasEncryptedColumns) {
@@ -296,13 +314,15 @@ export async function encodeOutboxCommit(
296
314
  storedKeyIdFor?.(table, op.rowId),
297
315
  );
298
316
  }
299
- operations.push({
300
- table: op.table,
301
- rowId: op.rowId,
302
- op: 'upsert',
303
- ...(op.baseVersion !== undefined ? { baseVersion: op.baseVersion } : {}),
304
- payload: encodeSparseRow(table.columns, table.primaryKeyIndex, values),
305
- });
317
+ operations.push(
318
+ definedObject({
319
+ table: op.table,
320
+ rowId: op.rowId,
321
+ op: 'upsert',
322
+ baseVersion: op.baseVersion,
323
+ payload: encodeSparseRow(table.columns, table.primaryKeyIndex, values),
324
+ }),
325
+ );
306
326
  }
307
327
  return {
308
328
  type: 'PUSH_COMMIT',
package/src/outcomes.ts CHANGED
@@ -365,13 +365,17 @@ export function recordCommitOutcome(
365
365
  return commitOutcome(db, outcome.clientCommitId) as CommitOutcome;
366
366
  }
367
367
 
368
+ function outcomeRow(db: ClientDatabase, clientCommitId: string) {
369
+ return db.query(`${SELECT_OUTCOME} WHERE client_commit_id=?`, [
370
+ clientCommitId,
371
+ ])[0];
372
+ }
373
+
368
374
  export function commitOutcome(
369
375
  db: ClientDatabase,
370
376
  clientCommitId: string,
371
377
  ): CommitOutcome | undefined {
372
- const row = db.query(`${SELECT_OUTCOME} WHERE client_commit_id=?`, [
373
- clientCommitId,
374
- ])[0];
378
+ const row = outcomeRow(db, clientCommitId);
375
379
  return row === undefined ? undefined : parseOutcome(db, row);
376
380
  }
377
381
 
@@ -385,9 +389,7 @@ export function persistedCommitOutcome(
385
389
  db: ClientDatabase,
386
390
  clientCommitId: string,
387
391
  ): CommitOutcome | undefined {
388
- const row = db.query(`${SELECT_OUTCOME} WHERE client_commit_id=?`, [
389
- clientCommitId,
390
- ])[0];
392
+ const row = outcomeRow(db, clientCommitId);
391
393
  if (row === undefined) return undefined;
392
394
  function corrupt(): never {
393
395
  throw new ClientSyncError(
package/src/progress.ts CHANGED
@@ -5,13 +5,13 @@ export interface SyncProgress {
5
5
  readonly attempt: number;
6
6
  readonly state: 'running' | 'complete' | 'failed';
7
7
  readonly phase: 'request' | 'download' | 'import';
8
- readonly unitId?: string;
9
- readonly table?: string;
8
+ readonly unitId?: string | undefined;
9
+ readonly table?: string | undefined;
10
10
  readonly segmentId?: string | undefined;
11
11
  readonly bytesReceived: number;
12
- readonly bytesTotal?: number;
12
+ readonly bytesTotal?: number | undefined;
13
13
  readonly rowsProcessed: number;
14
- readonly rowsTotal?: number;
14
+ readonly rowsTotal?: number | undefined;
15
15
  /** Time in this payload's import transactions before COMMIT, in ms. */
16
16
  readonly importWriteMs?: number | undefined;
17
17
  /** Time committing them and publishing their changes, in ms. */
@@ -81,8 +81,12 @@ export interface ExternalStoreEntry<T> {
81
81
  export interface WindowRetention {
82
82
  /** Resolves once this retained claim has reached the core window. */
83
83
  readonly ready: Promise<void>;
84
- /** Release only this retention owner's units from the composable union. */
85
- readonly release: () => void;
84
+ /**
85
+ * Release only this retention owner's units from the composable union.
86
+ * Settles with the core window edit that applies the release, after its
87
+ * eviction (§4.8); rejects with that edit's error.
88
+ */
89
+ readonly release: () => Promise<void>;
86
90
  }
87
91
 
88
92
  export interface StatusStoreSnapshot {
@@ -465,7 +469,9 @@ class QueryEntry<Row> implements ExternalStoreEntry<LiveQueryResult<Row>> {
465
469
  this.#offStatus = undefined;
466
470
  this.#offRound?.();
467
471
  this.#offRound = undefined;
468
- this.store.releaseWindowClaims(this.#owner);
472
+ // A failed release leaves the group unapplied; the next claim on
473
+ // the base applies it again. Only a retention handle reports it.
474
+ this.store.releaseWindowClaims(this.#owner).catch(() => {});
469
475
  }
470
476
  };
471
477
  };
@@ -541,7 +547,7 @@ class QueryEntry<Row> implements ExternalStoreEntry<LiveQueryResult<Row>> {
541
547
  this.#offStatus = undefined;
542
548
  this.#offRound?.();
543
549
  this.#offRound = undefined;
544
- this.store.releaseWindowClaims(this.#owner);
550
+ this.store.releaseWindowClaims(this.#owner).catch(() => {});
545
551
  this.reset();
546
552
  }
547
553
 
@@ -1069,9 +1075,9 @@ export class ReactiveClientStore {
1069
1075
  return {
1070
1076
  ready,
1071
1077
  release: () => {
1072
- if (!active) return;
1078
+ if (!active) return Promise.resolve();
1073
1079
  active = false;
1074
- this.releaseWindowClaims(owner);
1080
+ return this.releaseWindowClaims(owner);
1075
1081
  },
1076
1082
  };
1077
1083
  }
@@ -1125,10 +1131,19 @@ export class ReactiveClientStore {
1125
1131
  return result;
1126
1132
  }
1127
1133
 
1128
- releaseWindowClaims(owner: symbol): void {
1134
+ /** Settles once every core window edit that drops the owner's claims ran. */
1135
+ releaseWindowClaims(owner: symbol): Promise<void> {
1136
+ const edits: Promise<void>[] = [];
1129
1137
  for (const group of this.#windowClaims.values()) {
1130
- if (group.claims.delete(owner)) this.#scheduleWindow(group);
1138
+ if (!group.claims.delete(owner)) continue;
1139
+ edits.push(
1140
+ new Promise<void>((resolve, reject) => {
1141
+ group.waiters.push({ resolve, reject });
1142
+ }),
1143
+ );
1144
+ this.#scheduleWindow(group);
1131
1145
  }
1146
+ return Promise.all(edits).then(() => undefined);
1132
1147
  }
1133
1148
 
1134
1149
  /** Apply every claimed window group again and claim again for query entries
@@ -578,8 +578,8 @@ export function startSyncWorkerCore(
578
578
  setWindow: async (base, units) => {
579
579
  await requireClient().setWindowCommand(base, units);
580
580
  },
581
- mutate: (mutations) => {
582
- return requireClient().mutateCommand(mutations).value;
581
+ mutate: (mutations, options) => {
582
+ return requireClient().mutateCommand(mutations, options).value;
583
583
  },
584
584
  patch: (table, rowId, partial, options) => {
585
585
  // Same §8.4 rule as `mutate`: a local write must push without the app
@@ -74,7 +74,6 @@ import {
74
74
  import {
75
75
  type LeaderLease,
76
76
  type LeaderLock,
77
- singleOwnerLock,
78
77
  webLocksLeaderLock,
79
78
  } from './leader-lock';
80
79
  import type { LocalDataPurgeInput, LocalDataPurgeResult } from './local-purge';
@@ -224,7 +223,10 @@ export interface SyncClientHandleConfig {
224
223
  readonly previousVersionContext?: SyncClientConfig['previousVersionContext'];
225
224
  /** Worker-side host loop (§8.4); default true. */
226
225
  readonly autoSync?: boolean;
227
- /** Default: Web Locks when available, else single-owner. */
226
+ /**
227
+ * Default: Web Locks. A runtime without Web Locks refuses the handle with
228
+ * `client.web_locks_unavailable` unless the host injects a lock.
229
+ */
228
230
  readonly leaderLock?: LeaderLock;
229
231
  readonly lockName?: string;
230
232
  /** Shared by default; isolated derives the database/lock/channel tuple. */
@@ -287,9 +289,12 @@ interface Pending {
287
289
 
288
290
  function defaultLeaderLock(): LeaderLock {
289
291
  const nav = (globalThis as { navigator?: { locks?: LockManager } }).navigator;
290
- return nav?.locks !== undefined
291
- ? webLocksLeaderLock(nav.locks)
292
- : singleOwnerLock();
292
+ if (nav?.locks === undefined)
293
+ throw new ClientSyncError(
294
+ 'client.web_locks_unavailable',
295
+ 'this runtime has no Web Locks; inject a leaderLock',
296
+ );
297
+ return webLocksLeaderLock(nav.locks);
293
298
  }
294
299
 
295
300
  /**
@@ -659,8 +664,11 @@ export class SyncClientHandle implements PromiseMethods<WorkerApi> {
659
664
  return this.#call('windowState', [base]);
660
665
  }
661
666
 
662
- mutate(mutations: readonly MutationInput[]): Promise<string> {
663
- return this.#call('mutate', [mutations]);
667
+ mutate(
668
+ mutations: readonly MutationInput[],
669
+ options?: { readonly clientCommitId?: string },
670
+ ): Promise<string> {
671
+ return this.#call('mutate', [mutations, options]);
664
672
  }
665
673
 
666
674
  /** Partial-update convenience: read-merge-write one full-row upsert. */
@@ -190,7 +190,10 @@ export interface WorkerApi extends Omit<
190
190
  setWindow(base: WindowBase, units: readonly string[]): Promise<void>;
191
191
  /** §4.8 completeness oracle: the windowed-in values of a base. */
192
192
  windowState(base: WindowBase): WindowState;
193
- mutate(mutations: readonly MutationInput[]): string;
193
+ mutate(
194
+ mutations: readonly MutationInput[],
195
+ options?: { readonly clientCommitId?: string },
196
+ ): string;
194
197
  /** Partial-update convenience: read-merge-write one full-row upsert. */
195
198
  patch(
196
199
  table: string,