@syncular/client 0.48.0 → 0.49.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.
package/README.md CHANGED
@@ -295,6 +295,38 @@ does not solve a coordination-partition mismatch by itself: an independent
295
295
  instance must also use an isolated database and lock identity. Changing only
296
296
  the channel, lock, or database name is unsafe or ineffective.
297
297
 
298
+ ## Your own core across tabs
299
+
300
+ `createTabCoordinator` is the election, promotion, probe, and build-check
301
+ machinery under `createSyncClientHandle`, around a core you start yourself
302
+ (for example a Rust core in your own worker):
303
+
304
+ ```ts
305
+ const tabs = await createTabCoordinator<ViewEvent>({
306
+ name: 'app-core',
307
+ version: BUILD_NUMBER,
308
+ lead: async ({ broadcast, send }) => {
309
+ const core = await startCore();
310
+ return {
311
+ clientId: core.id,
312
+ call: (tabId, method, args) => core.handle(tabId, method, args),
313
+ tabClosed: (tabId) => core.dropSession(tabId),
314
+ close: () => core.stop(),
315
+ };
316
+ },
317
+ onEvent: render,
318
+ });
319
+ await tabs.call('navigate', ['/campaigns']);
320
+ ```
321
+
322
+ Calls reach the core with the calling tab's id; `send(tabId, event)` targets
323
+ one tab and `broadcast(event)` reaches all of them. Every tab holds a Web Lock
324
+ named `<name>:tab:<tabId>` until it closes, and a core that defines
325
+ `tabClosed` learns when a tab that called it is gone. A promoted leader runs
326
+ `lead` again on a higher epoch, so followers re-send their per-tab state when
327
+ `state.epoch` changes. See
328
+ [platform specifics](https://syncular.dev/platform-web-specifics/#your-own-core-across-tabs).
329
+
298
330
  ## React availability guard
299
331
 
300
332
  The worker handle's schema and leadership snapshots feed the same public React
package/dist/client.js CHANGED
@@ -2185,12 +2185,17 @@ export class SyncClient {
2185
2185
  throw new ClientSyncError('sync.invalid_request', 'the authoring request is invalid', false, {
2186
2186
  legacyCause: `sync.invalid_request: table ${table.name}: ${refusal}`,
2187
2187
  });
2188
+ // §7.1 insert intent: a full-row write of a row the replica does not
2189
+ // show replays and encodes as a full row under every later schema.
2190
+ const insert = mutation.op !== 'patch' &&
2191
+ this.#db.query(`SELECT 1 FROM ${quoteIdent(table.name)} WHERE ${quoteIdent(table.primaryKey)}=? LIMIT 1`, [pkSqlValue(table, pkValue)]).length === 0;
2188
2192
  return definedObject({
2189
2193
  table: mutation.table,
2190
2194
  rowId: pkValue,
2191
2195
  op: 'upsert',
2192
2196
  baseVersion: mutation.baseVersion,
2193
2197
  values: json,
2198
+ insert: insert ? true : undefined,
2194
2199
  });
2195
2200
  });
2196
2201
  this.#applyBatch((batch) => {
@@ -4496,9 +4501,19 @@ export class SyncClient {
4496
4501
  // §7.1 overlay: apply the operation's PRESENT columns over the current
4497
4502
  // local row. A partial operation over an absent local row leaves it
4498
4503
  // absent — the server answers it with sync.row_deleted or
4499
- // sync.row_missing, and the local mirror never invents a base.
4504
+ // sync.row_missing, and the local mirror never invents a base. An
4505
+ // insert-intent operation is a full row: a column it lacks is NULL.
4500
4506
  const opValues = op.values ?? {};
4501
- const full = table.columns.every((column) => column.name in opValues);
4507
+ const full = op.insert === true ||
4508
+ table.columns.every((column) => column.name in opValues);
4509
+ // An insert lacking a non-nullable column cannot encode (§7.4.4); it
4510
+ // stays hidden until the send-time drop classifies it.
4511
+ if (op.insert === true &&
4512
+ table.columns.some((column) => !column.nullable && opValues[column.name] === undefined)) {
4513
+ if (batch !== undefined && !precise)
4514
+ batch.table(op.table);
4515
+ continue;
4516
+ }
4502
4517
  const local = this.#db.query(`SELECT * FROM ${quoteIdent(table.name)} WHERE ${quoteIdent(table.primaryKey)}=?`, [pkSqlValue(table, op.rowId)])[0];
4503
4518
  if (local === undefined && !full) {
4504
4519
  if (batch !== undefined && !precise)
@@ -4509,7 +4524,7 @@ export class SyncClient {
4509
4524
  const value = opValues[column.name];
4510
4525
  if (value !== undefined)
4511
4526
  return jsonToRowValue(value);
4512
- return local === undefined
4527
+ return local === undefined || op.insert === true
4513
4528
  ? null
4514
4529
  : replay
4515
4530
  ? coerceSqlRepresentation(column, local[column.name] ?? null)
@@ -1,3 +1,4 @@
1
+ import { type LeaderLease, type LeaderLock } from './leader-lock.js';
1
2
  import type { SyncWorkerEvent } from './worker-protocol.js';
2
3
  /** Client-local: a follower call could not reach a leader before its deadline. */
3
4
  export declare const FOLLOWER_TIMEOUT_CODE = "client.follower_timeout";
@@ -10,7 +11,7 @@ export declare const LEADER_HANDOVER_CODE = "client.leader_handover";
10
11
  * with every change to a message shape or to a forwarded method's arguments
11
12
  * or result, so tabs of different builds never serve each other.
12
13
  */
13
- export declare const MULTI_TAB_PROTOCOL_VERSION = 1;
14
+ export declare const MULTI_TAB_PROTOCOL_VERSION = 2;
14
15
  /** What a tab must share with its leader to be served by it. */
15
16
  export interface TabIdentity {
16
17
  readonly protocol: number;
@@ -89,54 +90,59 @@ interface ResMessage {
89
90
  details?: Readonly<Record<string, unknown>>;
90
91
  };
91
92
  }
92
- interface EventMessage {
93
+ interface EventMessage<E> {
93
94
  readonly t: 'event';
94
95
  readonly epoch: number;
95
- readonly event: SyncWorkerEvent;
96
+ readonly event: E;
97
+ /** The one tab this event is for; absent for a fan-out to every tab. */
98
+ readonly to?: string;
96
99
  }
97
- export type MultiTabMessage = HelloMessage | ReqMessage | AnnounceMessage | ResMessage | EventMessage;
100
+ export type MultiTabMessage<E = SyncWorkerEvent> = HelloMessage | ReqMessage | AnnounceMessage | ResMessage | EventMessage<E>;
98
101
  /**
99
102
  * The tiny cross-tab channel surface we depend on — the DOM `BroadcastChannel`
100
103
  * satisfies it. Injectable so bun tests can pair two instances by name.
101
104
  */
102
- export interface CrossTabChannel {
103
- postMessage(message: MultiTabMessage): void;
105
+ export interface CrossTabChannel<E = SyncWorkerEvent> {
106
+ postMessage(message: MultiTabMessage<E>): void;
104
107
  addEventListener(type: 'message', listener: (event: {
105
- data: MultiTabMessage;
108
+ data: MultiTabMessage<E>;
106
109
  }) => void): void;
107
110
  removeEventListener(type: 'message', listener: (event: {
108
- data: MultiTabMessage;
111
+ data: MultiTabMessage<E>;
109
112
  }) => void): void;
110
113
  close(): void;
111
114
  }
112
115
  /** Default channel factory: a real `BroadcastChannel` named per lock. */
113
- export declare function broadcastChannelFactory(): (name: string) => CrossTabChannel;
116
+ export declare function broadcastChannelFactory<E = SyncWorkerEvent>(): (name: string) => CrossTabChannel<E>;
114
117
  /** The channel name a leader and its followers rendezvous on. */
115
118
  export declare function multiTabChannelName(lockName: string): string;
116
119
  /** A per-tab identity for addressing (not a presence identity). */
117
120
  export declare function newTabId(): string;
118
121
  /**
119
122
  * Runs on the leader tab. Announces leadership, answers follower `req`s by
120
- * invoking the (already-running) worker via `invoke`, and rebroadcasts every
121
- * worker event to followers. Owns nothing about the worker lifecycle — the
122
- * worker-host stays the single core owner; this is a relay. A hello from a
123
- * newer tab calls `onNewerTab`, whose owner closes the core and releases the
124
- * lock.
123
+ * invoking the (already-running) core via `invoke` with the calling tab's id,
124
+ * and relays core events to followers. Owns nothing about the core lifecycle;
125
+ * this is a relay. `onFirstCall` runs once per tab, at its first request. A
126
+ * hello from a newer tab calls `onNewerTab`, whose owner closes the core and
127
+ * releases the lock.
125
128
  */
126
- export declare class LeaderBridge {
129
+ export declare class LeaderBridge<E = SyncWorkerEvent> {
127
130
  #private;
128
131
  constructor(options: {
129
- channel: CrossTabChannel;
132
+ channel: CrossTabChannel<E>;
130
133
  epoch: number;
131
134
  clientId: string;
132
135
  identity: TabIdentity;
133
- invoke: (method: string, args: readonly unknown[]) => Promise<unknown>;
136
+ invoke: (tabId: string, method: string, args: readonly unknown[]) => Promise<unknown>;
137
+ onFirstCall?: (tabId: string) => void;
134
138
  onNewerTab: () => void;
135
139
  });
136
140
  /** Announce leadership (on promotion and in answer to every `hello`). */
137
141
  announce(): void;
138
- /** Fan a worker event out to all followers on the current epoch. */
139
- broadcastEvent(event: SyncWorkerEvent): void;
142
+ /** Fan an event out to all followers on the current epoch. */
143
+ broadcastEvent(event: E): void;
144
+ /** Post an event that only the follower `tabId` delivers. */
145
+ sendEvent(tabId: string, event: E): void;
140
146
  close(): void;
141
147
  }
142
148
  /**
@@ -154,13 +160,13 @@ type FollowerSchedule = (callback: () => void, delayMs: number) => () => void;
154
160
  * when a probe goes unanswered, or when the leader's identity differs from
155
161
  * this tab's (see the module comment).
156
162
  */
157
- export declare class FollowerLink {
163
+ export declare class FollowerLink<E = SyncWorkerEvent> {
158
164
  #private;
159
165
  constructor(options: {
160
- channel: CrossTabChannel;
166
+ channel: CrossTabChannel<E>;
161
167
  fromId: string;
162
168
  identity: TabIdentity;
163
- onEvent: (event: SyncWorkerEvent) => void;
169
+ onEvent: (event: E) => void;
164
170
  onLeaderChange: (clientId: string) => void;
165
171
  onStateChange?: (state: LeadershipState) => void;
166
172
  callTimeoutMs?: number;
@@ -200,4 +206,72 @@ export declare class FollowerLink {
200
206
  handOver(invoke: (method: string, args: readonly unknown[]) => Promise<unknown>): void;
201
207
  close(): void;
202
208
  }
209
+ /** What a leader's core receives when this tab wins or promotes. */
210
+ export interface TabLeaderContext<E> {
211
+ /** This leadership's epoch; a promotion runs on a higher one. */
212
+ readonly epoch: number;
213
+ /** This tab's id. The leader's own calls arrive under it. */
214
+ readonly tabId: string;
215
+ /**
216
+ * The leader lock. The coordinator releases it after {@link TabLeader.close}
217
+ * resolves. Release it earlier only when the core is already gone, such as a
218
+ * worker terminated on `pagehide`.
219
+ */
220
+ readonly lease: LeaderLease;
221
+ /** Deliver an event to every tab, this one included. */
222
+ broadcast(event: E): void;
223
+ /** Deliver an event to the tab `tabId` only. */
224
+ send(tabId: string, event: E): void;
225
+ }
226
+ /** The core a leader tab runs for every tab of the coordinator. */
227
+ export interface TabLeader {
228
+ /** Announced to followers as `LeadershipState.leaderClientId`. */
229
+ readonly clientId: string;
230
+ /** Serve one call from the tab `tabId`. */
231
+ call(tabId: string, method: string, args: readonly unknown[]): Promise<unknown>;
232
+ /**
233
+ * The tab `tabId`, which called this leader, closed. Defined only by cores
234
+ * that keep per-tab state; the coordinator then waits on each caller's tab
235
+ * lock.
236
+ */
237
+ tabClosed?(tabId: string): void;
238
+ /** Stop the core. The coordinator releases the leader lock afterwards. */
239
+ close(): Promise<void>;
240
+ }
241
+ export interface TabCoordinatorConfig<E> {
242
+ /** Web Lock name of the leadership; the channel and tab locks derive from it. */
243
+ readonly name: string;
244
+ /**
245
+ * The application build. Tabs of different versions never serve each other:
246
+ * a leader steps down for a higher version, and a tab next to a leader of
247
+ * another version is `blocked` with reason `leader-incompatible`.
248
+ */
249
+ readonly version: number;
250
+ /** Start the core. Runs when this tab wins the lock, and on every promotion. */
251
+ lead(context: TabLeaderContext<E>): Promise<TabLeader>;
252
+ /** Events the leader broadcast, or sent to this tab. */
253
+ onEvent?(event: E): void;
254
+ onStateChange?(state: LeadershipState): void;
255
+ /** Defaults to Web Locks; tests inject a name-keyed exclusive lock. */
256
+ readonly lock?: LeaderLock;
257
+ readonly channelFactory?: (name: string) => CrossTabChannel<E>;
258
+ /** Liveness and handover-queue deadline; defaults to 10 s. */
259
+ readonly callTimeoutMs?: number;
260
+ }
261
+ /** One tab's end of the coordinator, the same in leader and follower tabs. */
262
+ export interface TabCoordinator {
263
+ readonly tabId: string;
264
+ readonly state: LeadershipState;
265
+ /** Run a call on the leader's core, in this tab or over the channel. */
266
+ call(method: string, args: readonly unknown[]): Promise<unknown>;
267
+ /** Stop the core (leader) or the link (follower), and release this tab's locks. */
268
+ close(): Promise<void>;
269
+ }
270
+ /**
271
+ * Elect one leader tab per `name` and run `lead` there; every other tab
272
+ * forwards its calls to that core and receives its events. When the leader
273
+ * tab closes, one follower promotes in place on a higher epoch and runs
274
+ * `lead` itself. Resolves once this tab leads or is bound to a leader.
275
+ */
276
+ export declare function createTabCoordinator<E>(config: TabCoordinatorConfig<E>): Promise<TabCoordinator>;
203
277
  export {};
package/dist/multi-tab.js CHANGED
@@ -20,7 +20,8 @@
20
20
  * — "I am the leader, this epoch";
21
21
  * the answer to every hello
22
22
  * res {t,epoch,reqId,ok,value|error} — reply to one req
23
- * event {t,epoch,event} — fan-out (invalidate/presence/…)
23
+ * event {t,epoch,event,to?} — fan-out (invalidate/presence/…),
24
+ * or one tab's event when `to` is set
24
25
  *
25
26
  * Epoch (leader generation token): a monotonic counter carried in a shared
26
27
  * BroadcastChannel and bumped by every promotion. Followers stamp requests
@@ -57,8 +58,14 @@
57
58
  * is exactly ONE presence peer collectively — `(actorId, leaderClientId)`.
58
59
  * A follower's `setPresence` forwards to the leader's single publisher; there
59
60
  * is no per-tab presence peer (documented in the web-client README).
61
+ *
62
+ * Tab lifetime: every tab of a {@link TabCoordinator} holds an exclusive Web
63
+ * Lock named for its tab id until it closes. A leader whose core keeps per-tab
64
+ * state waits on that lock for each tab that called it; the grant means the
65
+ * tab is gone.
60
66
  */
61
67
  import { ClientSyncError } from './errors.js';
68
+ import { webLocksLeaderLock, } from './leader-lock.js';
62
69
  import { WORKER_FAILED_CODE } from './worker-protocol.js';
63
70
  /** Client-local: a follower call could not reach a leader before its deadline. */
64
71
  export const FOLLOWER_TIMEOUT_CODE = 'client.follower_timeout';
@@ -71,7 +78,7 @@ export const LEADER_HANDOVER_CODE = 'client.leader_handover';
71
78
  * with every change to a message shape or to a forwarded method's arguments
72
79
  * or result, so tabs of different builds never serve each other.
73
80
  */
74
- export const MULTI_TAB_PROTOCOL_VERSION = 1;
81
+ export const MULTI_TAB_PROTOCOL_VERSION = 2;
75
82
  /**
76
83
  * Order a peer's identity against our own: -1 older, 0 same, 1 newer. A peer
77
84
  * from before protocol 1 sends no identity and is older.
@@ -110,11 +117,11 @@ export function newTabId() {
110
117
  // ---------------------------------------------------------------------------
111
118
  /**
112
119
  * Runs on the leader tab. Announces leadership, answers follower `req`s by
113
- * invoking the (already-running) worker via `invoke`, and rebroadcasts every
114
- * worker event to followers. Owns nothing about the worker lifecycle — the
115
- * worker-host stays the single core owner; this is a relay. A hello from a
116
- * newer tab calls `onNewerTab`, whose owner closes the core and releases the
117
- * lock.
120
+ * invoking the (already-running) core via `invoke` with the calling tab's id,
121
+ * and relays core events to followers. Owns nothing about the core lifecycle;
122
+ * this is a relay. `onFirstCall` runs once per tab, at its first request. A
123
+ * hello from a newer tab calls `onNewerTab`, whose owner closes the core and
124
+ * releases the lock.
118
125
  */
119
126
  export class LeaderBridge {
120
127
  #channel;
@@ -122,8 +129,10 @@ export class LeaderBridge {
122
129
  #clientId;
123
130
  #identity;
124
131
  #invoke;
132
+ #onFirstCall;
125
133
  #onNewerTab;
126
134
  #onMessage;
135
+ #callers = new Set();
127
136
  #closed = false;
128
137
  constructor(options) {
129
138
  this.#channel = options.channel;
@@ -131,6 +140,7 @@ export class LeaderBridge {
131
140
  this.#clientId = options.clientId;
132
141
  this.#identity = options.identity;
133
142
  this.#invoke = options.invoke;
143
+ this.#onFirstCall = options.onFirstCall;
134
144
  this.#onNewerTab = options.onNewerTab;
135
145
  this.#onMessage = (event) => this.#handle(event.data);
136
146
  this.#channel.addEventListener('message', this.#onMessage);
@@ -147,12 +157,23 @@ export class LeaderBridge {
147
157
  ...this.#identity,
148
158
  });
149
159
  }
150
- /** Fan a worker event out to all followers on the current epoch. */
160
+ /** Fan an event out to all followers on the current epoch. */
151
161
  broadcastEvent(event) {
152
162
  if (this.#closed)
153
163
  return;
154
164
  this.#channel.postMessage({ t: 'event', epoch: this.#epoch, event });
155
165
  }
166
+ /** Post an event that only the follower `tabId` delivers. */
167
+ sendEvent(tabId, event) {
168
+ if (this.#closed)
169
+ return;
170
+ this.#channel.postMessage({
171
+ t: 'event',
172
+ epoch: this.#epoch,
173
+ event,
174
+ to: tabId,
175
+ });
176
+ }
156
177
  #handle(message) {
157
178
  if (this.#closed)
158
179
  return;
@@ -172,7 +193,7 @@ export class LeaderBridge {
172
193
  // follower will re-stamp once it sees our announce.
173
194
  if (message.epoch !== this.#epoch)
174
195
  return;
175
- const { reqId, method, args } = message;
196
+ const { reqId, method, args, fromId } = message;
176
197
  if (compareTabIdentity(message, this.#identity) !== 0) {
177
198
  this.#channel.postMessage({
178
199
  t: 'res',
@@ -187,8 +208,12 @@ export class LeaderBridge {
187
208
  });
188
209
  return;
189
210
  }
211
+ if (!this.#callers.has(fromId)) {
212
+ this.#callers.add(fromId);
213
+ this.#onFirstCall?.(fromId);
214
+ }
190
215
  // A call can outlive close(); a closed BroadcastChannel throws on post.
191
- this.#invoke(method, args).then((value) => {
216
+ this.#invoke(fromId, method, args).then((value) => {
192
217
  if (this.#closed)
193
218
  return;
194
219
  this.#channel.postMessage({
@@ -480,6 +505,8 @@ export class FollowerLink {
480
505
  if (message.t === 'event') {
481
506
  if (message.epoch !== this.#epoch)
482
507
  return;
508
+ if (message.to !== undefined && message.to !== this.#fromId)
509
+ return;
483
510
  this.#onEvent(message.event);
484
511
  return;
485
512
  }
@@ -648,3 +675,208 @@ export class FollowerLink {
648
675
  this.#cancelBlocked = undefined;
649
676
  }
650
677
  }
678
+ function tabLockName(name, tabId) {
679
+ return `${name}:tab:${tabId}`;
680
+ }
681
+ /**
682
+ * Elect one leader tab per `name` and run `lead` there; every other tab
683
+ * forwards its calls to that core and receives its events. When the leader
684
+ * tab closes, one follower promotes in place on a higher epoch and runs
685
+ * `lead` itself. Resolves once this tab leads or is bound to a leader.
686
+ */
687
+ export async function createTabCoordinator(config) {
688
+ const lock = config.lock ?? webLocksLeaderLock();
689
+ const openChannel = config.channelFactory ?? broadcastChannelFactory();
690
+ const channelName = multiTabChannelName(config.name);
691
+ const identity = {
692
+ protocol: MULTI_TAB_PROTOCOL_VERSION,
693
+ schemaVersion: config.version,
694
+ };
695
+ const tabId = newTabId();
696
+ let state = {
697
+ state: 'waiting',
698
+ reason: 'leader-announcement',
699
+ };
700
+ let leading;
701
+ let follower;
702
+ let closed = false;
703
+ const setState = (next) => {
704
+ state = next;
705
+ try {
706
+ config.onStateChange?.(next);
707
+ }
708
+ catch {
709
+ // A status listener must never break cross-tab coordination.
710
+ }
711
+ };
712
+ // Held until close: a leader waits on it to learn this tab is gone.
713
+ const tabLease = await lock.acquire(tabLockName(config.name, tabId));
714
+ const lead = async (lease, epoch) => {
715
+ let bridge;
716
+ let current = true;
717
+ const leader = await config.lead({
718
+ epoch,
719
+ tabId,
720
+ lease,
721
+ broadcast: (event) => {
722
+ if (!current)
723
+ return;
724
+ bridge?.broadcastEvent(event);
725
+ config.onEvent?.(event);
726
+ },
727
+ send: (to, event) => {
728
+ if (!current)
729
+ return;
730
+ if (to === tabId)
731
+ config.onEvent?.(event);
732
+ else
733
+ bridge?.sendEvent(to, event);
734
+ },
735
+ });
736
+ if (closed) {
737
+ // Closed while the core was starting: nobody holds this tab any more.
738
+ current = false;
739
+ await leader.close();
740
+ await lease.release();
741
+ return;
742
+ }
743
+ const ending = {
744
+ leader,
745
+ lease,
746
+ end: () => {
747
+ current = false;
748
+ bridge?.close();
749
+ },
750
+ };
751
+ leading = ending;
752
+ bridge = new LeaderBridge({
753
+ channel: openChannel(channelName),
754
+ epoch,
755
+ clientId: leader.clientId,
756
+ identity,
757
+ invoke: (from, method, args) => leader.call(from, method, args),
758
+ ...(leader.tabClosed !== undefined
759
+ ? {
760
+ onFirstCall: (from) => {
761
+ void lock
762
+ .acquire(tabLockName(config.name, from))
763
+ .then(async (gone) => {
764
+ await gone.release();
765
+ if (current)
766
+ leader.tabClosed?.(from);
767
+ });
768
+ },
769
+ }
770
+ : {}),
771
+ onNewerTab: () => {
772
+ // A newer build asked for the core: stop it and release the lock so
773
+ // that tab promotes. This tab stays blocked until it reloads.
774
+ if (leading !== ending)
775
+ return;
776
+ leading = undefined;
777
+ ending.end();
778
+ setState({
779
+ state: 'blocked',
780
+ reason: 'leader-incompatible',
781
+ code: LEADER_INCOMPATIBLE_CODE,
782
+ leader: 'newer',
783
+ retryable: true,
784
+ });
785
+ void leader.close().finally(() => lease.release());
786
+ },
787
+ });
788
+ // Calls queued for the next leader run on this tab's own core.
789
+ follower?.handOver((method, args) => leader.call(tabId, method, args));
790
+ follower = undefined;
791
+ setState({ state: 'leader', clientId: leader.clientId });
792
+ };
793
+ const coordinator = {
794
+ tabId,
795
+ get state() {
796
+ return state;
797
+ },
798
+ call: (method, args) => {
799
+ if (closed) {
800
+ return Promise.reject(new ClientSyncError(WORKER_FAILED_CODE, 'the tab coordinator is closed'));
801
+ }
802
+ if (leading !== undefined)
803
+ return leading.leader.call(tabId, method, args);
804
+ if (state.state === 'blocked' && state.reason === 'leader-incompatible') {
805
+ return Promise.reject(new ClientSyncError(LEADER_INCOMPATIBLE_CODE, 'the tab that owns the database runs a different protocol or schema version', true));
806
+ }
807
+ if (follower !== undefined)
808
+ return follower.call(method, args);
809
+ return Promise.reject(new ClientSyncError(WORKER_FAILED_CODE, 'no core serves this tab'));
810
+ },
811
+ close: async () => {
812
+ if (closed)
813
+ return;
814
+ closed = true;
815
+ follower?.close();
816
+ follower = undefined;
817
+ const ending = leading;
818
+ leading = undefined;
819
+ if (ending !== undefined) {
820
+ ending.end();
821
+ await ending.leader.close();
822
+ await ending.lease.release();
823
+ }
824
+ await tabLease.release();
825
+ },
826
+ };
827
+ // Leadership before any core exists: a losing tab never starts one.
828
+ const lease = lock.tryAcquire !== undefined
829
+ ? await lock.tryAcquire(config.name)
830
+ : await lock.acquire(config.name);
831
+ if (lease !== undefined) {
832
+ try {
833
+ await lead(lease, 0);
834
+ }
835
+ catch (error) {
836
+ await lease.release();
837
+ await tabLease.release();
838
+ throw error;
839
+ }
840
+ return coordinator;
841
+ }
842
+ const link = new FollowerLink({
843
+ channel: openChannel(channelName),
844
+ fromId: tabId,
845
+ identity,
846
+ onEvent: (event) => config.onEvent?.(event),
847
+ onLeaderChange: () => { },
848
+ onStateChange: setState,
849
+ ...(config.callTimeoutMs !== undefined
850
+ ? { callTimeoutMs: config.callTimeoutMs }
851
+ : {}),
852
+ });
853
+ follower = link;
854
+ // Granted only when the leader releases the lock (its tab closed).
855
+ void lock.acquire(config.name).then(async (promoted) => {
856
+ if (closed) {
857
+ // Promoting a closed coordinator would hold the lock forever.
858
+ await promoted.release();
859
+ return;
860
+ }
861
+ // The new leader must exceed every epoch this tab saw, so stale replies
862
+ // and events are discarded everywhere.
863
+ const epoch = link.maxEpochSeen + 1;
864
+ link.unbind();
865
+ try {
866
+ await lead(promoted, epoch);
867
+ }
868
+ catch {
869
+ // The core failed to start: release so the next tab tries.
870
+ await promoted.release();
871
+ }
872
+ });
873
+ // Return bound: an event the leader fans out before binding is dropped.
874
+ try {
875
+ await link.waitUntilBound();
876
+ }
877
+ catch {
878
+ // Bind timed out: the link keeps probing, queued calls flush on the next
879
+ // announce, and the state says `blocked`.
880
+ }
881
+ return coordinator;
882
+ }
package/dist/outbox.d.ts CHANGED
@@ -26,6 +26,11 @@ export interface OutboxOperation {
26
26
  * presence set — `mutate` marks every column, `patch` the supplied ones).
27
27
  */
28
28
  readonly values?: Readonly<Record<string, JsonRowValue>>;
29
+ /**
30
+ * §7.1 insert intent: a `mutate` of a row absent from the replica. Replay
31
+ * and encoding treat the operation as a full row; a missing column is NULL.
32
+ */
33
+ readonly insert?: true;
29
34
  }
30
35
  export interface OutboxCommit {
31
36
  readonly seq: number;
package/dist/outbox.js CHANGED
@@ -106,7 +106,7 @@ export class OutboxEncodeError extends ClientSyncError {
106
106
  super('sync.outbox_incompatible', message, false);
107
107
  }
108
108
  }
109
- function sparseValues(table, values) {
109
+ function sparseValues(table, values, insert) {
110
110
  // Any persisted key that is not a column of the CURRENT schema means the
111
111
  // bump removed (or renamed) it — the commit cannot be expressed now.
112
112
  for (const key of Object.keys(values)) {
@@ -116,7 +116,15 @@ function sparseValues(table, values) {
116
116
  }
117
117
  return table.columns.map((column) => {
118
118
  const value = values[column.name];
119
- return value === undefined ? undefined : jsonToRowValue(value);
119
+ if (value !== undefined)
120
+ return jsonToRowValue(value);
121
+ if (!insert)
122
+ return undefined;
123
+ // §7.1: an insert-intent operation presents every current column.
124
+ if (!column.nullable) {
125
+ throw new OutboxEncodeError('an outbox insert lacks a non-nullable column (§7.4.4)');
126
+ }
127
+ return null;
120
128
  });
121
129
  }
122
130
  /**
@@ -149,7 +157,7 @@ export async function encodeOutboxCommit(schema, commit, encryption, storedKeyId
149
157
  if (op.values === undefined) {
150
158
  throw new ClientSyncError('sync.invalid_request', `outbox upsert on ${op.table}/${op.rowId} has no values`);
151
159
  }
152
- let values = sparseValues(table, op.values);
160
+ let values = sparseValues(table, op.values, op.insert === true);
153
161
  if (encryption !== undefined && table.hasEncryptedColumns) {
154
162
  // Lazy: opt-in E2EE never enters an encryption-free app's bundle.
155
163
  const { encryptRowValues } = await import('./encryption.js');
package/dist/outcomes.js CHANGED
@@ -44,8 +44,12 @@ export function isStoredOperation(value) {
44
44
  typeof value.rowId === 'string' &&
45
45
  (value.baseVersion === undefined ||
46
46
  Number.isSafeInteger(value.baseVersion)) &&
47
- ((value.op === 'upsert' && isStoredRow(value.values)) ||
48
- (value.op === 'delete' && value.values === undefined)));
47
+ ((value.op === 'upsert' &&
48
+ isStoredRow(value.values) &&
49
+ (value.insert === undefined || value.insert === true)) ||
50
+ (value.op === 'delete' &&
51
+ value.values === undefined &&
52
+ value.insert === undefined)));
49
53
  }
50
54
  function decodeResults(raw) {
51
55
  function corrupt() {