@syncular/client 0.48.0 → 0.49.2

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
@@ -252,7 +252,24 @@ worker still holds the OPFS database and may be mid-commit, so a transfer
252
252
  needs a cooperative close-and-release handshake, and every focus change
253
253
  between tabs would restart the worker, reopen the database, and reconnect the
254
254
  realtime socket. A hidden leader answers its followers from its message
255
- handler, so leadership moves only when the leader tab closes.
255
+ handler, so leadership moves only when the leader tab closes, or when the
256
+ user takes over from an unresponsive one.
257
+
258
+ **Taking over from an unresponsive leader.** A leader whose main thread runs
259
+ no task (a frozen background tab, a hung window) blocks its followers with
260
+ `leader-unreachable`. Once that has lasted `takeOverAfterMs` (default twice
261
+ `followerCallTimeoutMs`), `handle.takeOver()`, called from a user action, steals
262
+ the leader's Web Lock, starts the worker in this tab on a higher epoch, and
263
+ steals the old worker's OPFS storage lock. OPFS sync access handles are
264
+ exclusive, so the new worker opens the database only after the old one closed
265
+ it. The old worker's database refuses every statement once its storage lock is
266
+ gone (`client.storage_fenced`) and closes its handles, and the old tab becomes
267
+ `blocked` with reason `leadership-taken` when it runs again. `takeOver()`
268
+ rejects with `client.takeover_refused` (`details.reason`: `not-unreachable`,
269
+ `too-early`, `in-progress`, `unsupported`) and with `client.storage_busy` while a
270
+ frozen worker still holds the files. `onLeaderUnreachable` reports the start of
271
+ each unreachable period with `takeOverAt`, and its end with `durationMs` and
272
+ the outcome.
256
273
 
257
274
  **Presence semantics — one device, one peer.** All tabs share the leader's
258
275
  single connection, so a device is exactly ONE presence peer collectively:
@@ -295,6 +312,38 @@ does not solve a coordination-partition mismatch by itself: an independent
295
312
  instance must also use an isolated database and lock identity. Changing only
296
313
  the channel, lock, or database name is unsafe or ineffective.
297
314
 
315
+ ## Your own core across tabs
316
+
317
+ `createTabCoordinator` is the election, promotion, probe, and build-check
318
+ machinery under `createSyncClientHandle`, around a core you start yourself
319
+ (for example a Rust core in your own worker):
320
+
321
+ ```ts
322
+ const tabs = await createTabCoordinator<ViewEvent>({
323
+ name: 'app-core',
324
+ version: BUILD_NUMBER,
325
+ lead: async ({ broadcast, send }) => {
326
+ const core = await startCore();
327
+ return {
328
+ clientId: core.id,
329
+ call: (tabId, method, args) => core.handle(tabId, method, args),
330
+ tabClosed: (tabId) => core.dropSession(tabId),
331
+ close: () => core.stop(),
332
+ };
333
+ },
334
+ onEvent: render,
335
+ });
336
+ await tabs.call('navigate', ['/campaigns']);
337
+ ```
338
+
339
+ Calls reach the core with the calling tab's id; `send(tabId, event)` targets
340
+ one tab and `broadcast(event)` reaches all of them. Every tab holds a Web Lock
341
+ named `<name>:tab:<tabId>` until it closes, and a core that defines
342
+ `tabClosed` learns when a tab that called it is gone. A promoted leader runs
343
+ `lead` again on a higher epoch, so followers re-send their per-tab state when
344
+ `state.epoch` changes. See
345
+ [platform specifics](https://syncular.dev/platform-web-specifics/#your-own-core-across-tabs).
346
+
298
347
  ## React availability guard
299
348
 
300
349
  The worker handle's schema and leadership snapshots feed the same public React
@@ -7,7 +7,7 @@ export type SyncAvailability = {
7
7
  readonly currentSchemaVersion: number;
8
8
  } | {
9
9
  readonly state: 'blocked';
10
- readonly reason: 'client-upgrade-required' | 'server-behind' | 'incompatible-schema' | 'leader-unreachable' | 'leader-incompatible';
10
+ readonly reason: 'client-upgrade-required' | 'server-behind' | 'incompatible-schema' | 'leader-unreachable' | 'leader-incompatible' | 'leadership-taken';
11
11
  readonly currentSchemaVersion: number;
12
12
  /** `leader-incompatible`: whether the tab holding the database runs an
13
13
  * older or a newer build than this one. */
@@ -10,7 +10,7 @@ export function blockedLeadershipAvailability(leadership, currentSchemaVersion)
10
10
  }
11
11
  : {
12
12
  state: 'blocked',
13
- reason: 'leader-unreachable',
13
+ reason: leadership.reason,
14
14
  currentSchemaVersion,
15
15
  retryable: true,
16
16
  };
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)
package/dist/errors.d.ts CHANGED
@@ -1,6 +1,11 @@
1
1
  import type { RealtimeState } from './diagnostics.js';
2
2
  /** A persistent local store is temporarily owned by another live engine. */
3
3
  export declare const STORAGE_BUSY_CODE = "client.storage_busy";
4
+ /**
5
+ * Another tab took this engine's persistent store with `takeOver()`; the
6
+ * engine closed the store and refuses every further statement.
7
+ */
8
+ export declare const STORAGE_FENCED_CODE = "client.storage_fenced";
4
9
  /** The browser cannot provide the persistent storage APIs Syncular requires. */
5
10
  export declare const STORAGE_UNAVAILABLE_CODE = "client.storage_unavailable";
6
11
  /** A local read hit SQLITE_CORRUPT or SQLITE_NOTADB (SPEC §7.5). */
package/dist/errors.js CHANGED
@@ -1,5 +1,10 @@
1
1
  /** A persistent local store is temporarily owned by another live engine. */
2
2
  export const STORAGE_BUSY_CODE = 'client.storage_busy';
3
+ /**
4
+ * Another tab took this engine's persistent store with `takeOver()`; the
5
+ * engine closed the store and refuses every further statement.
6
+ */
7
+ export const STORAGE_FENCED_CODE = 'client.storage_fenced';
3
8
  /** The browser cannot provide the persistent storage APIs Syncular requires. */
4
9
  export const STORAGE_UNAVAILABLE_CODE = 'client.storage_unavailable';
5
10
  /** A local read hit SQLITE_CORRUPT or SQLITE_NOTADB (SPEC §7.5). */
@@ -1,11 +1,16 @@
1
1
  /**
2
2
  * Multi-tab ownership seam: exactly one core instance owns the
3
- * local database. The interface is the whole B3 deliverable — cross-tab
4
- * follower fanout is post-gate. Browsers use Web Locks; tests use the
5
- * no-op single-owner lock.
3
+ * local database. Browsers use Web Locks; tests use the no-op single-owner
4
+ * lock or an injected exclusive lock.
6
5
  */
7
6
  export interface LeaderLease {
8
7
  release(): void | Promise<void>;
8
+ /**
9
+ * Resolves when another context took this lease with
10
+ * {@link LeaderLock.steal}. The holder no longer owns the lock and must stop
11
+ * writing. Absent for locks that cannot be stolen.
12
+ */
13
+ readonly lost?: Promise<void>;
9
14
  }
10
15
  export interface LeaderLock {
11
16
  /** Resolves when this instance holds leadership for `name`. */
@@ -13,16 +18,22 @@ export interface LeaderLock {
13
18
  /**
14
19
  * Resolves immediately: the lease when leadership was free, `undefined`
15
20
  * when another owner holds it. The worker handle uses this so a second
16
- * tab gets a clear not-leader state instead of blocking forever
17
- * (followers are post-gate).
21
+ * tab gets a clear not-leader state instead of blocking forever.
18
22
  */
19
23
  tryAcquire?(name: string): Promise<LeaderLease | undefined>;
24
+ /**
25
+ * Takes `name` from its current holder at once; the holder's lease reports
26
+ * `lost`. Waiting requests stay queued behind the new holder.
27
+ */
28
+ steal?(name: string): Promise<LeaderLease>;
20
29
  }
21
30
  /** Single-owner environments (tests, dedicated workers): always leader. */
22
31
  export declare function singleOwnerLock(): LeaderLock;
23
32
  /**
24
33
  * Web Locks leader election: resolves once the exclusive lock is granted
25
34
  * and holds it until the lease is released (tab close releases it
26
- * implicitly, letting the next tab take over).
35
+ * implicitly, letting the next tab take over). A `steal` from another
36
+ * context rejects the holder's request with `AbortError`, which resolves the
37
+ * holder's `lost`.
27
38
  */
28
- export declare function webLocksLeaderLock(locks?: LockManager): LeaderLock;
39
+ export declare function webLocksLeaderLock(locks?: LockManager): Required<LeaderLock>;
@@ -8,31 +8,49 @@ export function singleOwnerLock() {
8
8
  /**
9
9
  * Web Locks leader election: resolves once the exclusive lock is granted
10
10
  * and holds it until the lease is released (tab close releases it
11
- * implicitly, letting the next tab take over).
11
+ * implicitly, letting the next tab take over). A `steal` from another
12
+ * context rejects the holder's request with `AbortError`, which resolves the
13
+ * holder's `lost`.
12
14
  */
13
15
  export function webLocksLeaderLock(locks) {
14
16
  const manager = locks ?? navigator.locks;
17
+ const request = (name, options) => new Promise((resolveRequest, rejectRequest) => {
18
+ let granted = false;
19
+ let markLost = () => { };
20
+ const lost = new Promise((resolve) => {
21
+ markLost = resolve;
22
+ });
23
+ manager
24
+ .request(name, options, (lock) => {
25
+ // `ifAvailable` grants `null` instead of waiting (Web Locks).
26
+ if (lock === null) {
27
+ resolveRequest(undefined);
28
+ return undefined;
29
+ }
30
+ granted = true;
31
+ return new Promise((resolveHold) => {
32
+ resolveRequest({ release: () => resolveHold(), lost });
33
+ });
34
+ })
35
+ .catch((error) => {
36
+ if (granted &&
37
+ error instanceof DOMException &&
38
+ error.name === 'AbortError') {
39
+ markLost();
40
+ return;
41
+ }
42
+ rejectRequest(error);
43
+ });
44
+ });
45
+ const held = async (name, options) => {
46
+ const lease = await request(name, options);
47
+ if (lease === undefined)
48
+ throw new Error('a waiting lock request returned no lock');
49
+ return lease;
50
+ };
15
51
  return {
16
- acquire: (name) => new Promise((resolveAcquire, rejectAcquire) => {
17
- manager
18
- .request(name, { mode: 'exclusive' }, () => new Promise((resolveHold) => {
19
- resolveAcquire({ release: () => resolveHold() });
20
- }))
21
- .catch((error) => rejectAcquire(error));
22
- }),
23
- tryAcquire: (name) => new Promise((resolveTry, rejectTry) => {
24
- manager
25
- .request(name, { mode: 'exclusive', ifAvailable: true }, (lock) => {
26
- // `ifAvailable` grants `null` instead of waiting (Web Locks).
27
- if (lock === null) {
28
- resolveTry(undefined);
29
- return undefined;
30
- }
31
- return new Promise((resolveHold) => {
32
- resolveTry({ release: () => resolveHold() });
33
- });
34
- })
35
- .catch((error) => rejectTry(error));
36
- }),
52
+ acquire: (name) => held(name, { mode: 'exclusive' }),
53
+ tryAcquire: (name) => request(name, { mode: 'exclusive', ifAvailable: true }),
54
+ steal: (name) => held(name, { mode: 'exclusive', steal: true }),
37
55
  };
38
56
  }
@@ -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";
@@ -5,12 +6,16 @@ export declare const FOLLOWER_TIMEOUT_CODE = "client.follower_timeout";
5
6
  export declare const LEADER_INCOMPATIBLE_CODE = "client.leader_incompatible";
6
7
  /** Client-local: the leader that received a call stopped leading before it answered. */
7
8
  export declare const LEADER_HANDOVER_CODE = "client.leader_handover";
9
+ /** Client-local: another tab took this tab's leadership with `takeOver()`. */
10
+ export declare const LEADERSHIP_TAKEN_CODE = "client.leadership_taken";
11
+ /** Client-local: `takeOver()` was called while its conditions do not hold. */
12
+ export declare const TAKEOVER_REFUSED_CODE = "client.takeover_refused";
8
13
  /**
9
14
  * Version of the leader/follower wire and the forwarded handle API. Bump it
10
15
  * with every change to a message shape or to a forwarded method's arguments
11
16
  * or result, so tabs of different builds never serve each other.
12
17
  */
13
- export declare const MULTI_TAB_PROTOCOL_VERSION = 1;
18
+ export declare const MULTI_TAB_PROTOCOL_VERSION = 2;
14
19
  /** What a tab must share with its leader to be served by it. */
15
20
  export interface TabIdentity {
16
21
  readonly protocol: number;
@@ -50,6 +55,11 @@ export type LeadershipState = {
50
55
  /** Whether the tab holding the database runs an older or a newer build. */
51
56
  readonly leader: 'older' | 'newer';
52
57
  readonly retryable: true;
58
+ } | {
59
+ readonly state: 'blocked';
60
+ readonly reason: 'leadership-taken';
61
+ readonly code: typeof LEADERSHIP_TAKEN_CODE;
62
+ readonly retryable: true;
53
63
  };
54
64
  /** Identity fields; absent in messages from tabs before protocol 1. */
55
65
  interface IdentityFields {
@@ -89,54 +99,59 @@ interface ResMessage {
89
99
  details?: Readonly<Record<string, unknown>>;
90
100
  };
91
101
  }
92
- interface EventMessage {
102
+ interface EventMessage<E> {
93
103
  readonly t: 'event';
94
104
  readonly epoch: number;
95
- readonly event: SyncWorkerEvent;
105
+ readonly event: E;
106
+ /** The one tab this event is for; absent for a fan-out to every tab. */
107
+ readonly to?: string;
96
108
  }
97
- export type MultiTabMessage = HelloMessage | ReqMessage | AnnounceMessage | ResMessage | EventMessage;
109
+ export type MultiTabMessage<E = SyncWorkerEvent> = HelloMessage | ReqMessage | AnnounceMessage | ResMessage | EventMessage<E>;
98
110
  /**
99
111
  * The tiny cross-tab channel surface we depend on — the DOM `BroadcastChannel`
100
112
  * satisfies it. Injectable so bun tests can pair two instances by name.
101
113
  */
102
- export interface CrossTabChannel {
103
- postMessage(message: MultiTabMessage): void;
114
+ export interface CrossTabChannel<E = SyncWorkerEvent> {
115
+ postMessage(message: MultiTabMessage<E>): void;
104
116
  addEventListener(type: 'message', listener: (event: {
105
- data: MultiTabMessage;
117
+ data: MultiTabMessage<E>;
106
118
  }) => void): void;
107
119
  removeEventListener(type: 'message', listener: (event: {
108
- data: MultiTabMessage;
120
+ data: MultiTabMessage<E>;
109
121
  }) => void): void;
110
122
  close(): void;
111
123
  }
112
124
  /** Default channel factory: a real `BroadcastChannel` named per lock. */
113
- export declare function broadcastChannelFactory(): (name: string) => CrossTabChannel;
125
+ export declare function broadcastChannelFactory<E = SyncWorkerEvent>(): (name: string) => CrossTabChannel<E>;
114
126
  /** The channel name a leader and its followers rendezvous on. */
115
127
  export declare function multiTabChannelName(lockName: string): string;
116
128
  /** A per-tab identity for addressing (not a presence identity). */
117
129
  export declare function newTabId(): string;
118
130
  /**
119
131
  * 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.
132
+ * invoking the (already-running) core via `invoke` with the calling tab's id,
133
+ * and relays core events to followers. Owns nothing about the core lifecycle;
134
+ * this is a relay. `onFirstCall` runs once per tab, at its first request. A
135
+ * hello from a newer tab calls `onNewerTab`, whose owner closes the core and
136
+ * releases the lock.
125
137
  */
126
- export declare class LeaderBridge {
138
+ export declare class LeaderBridge<E = SyncWorkerEvent> {
127
139
  #private;
128
140
  constructor(options: {
129
- channel: CrossTabChannel;
141
+ channel: CrossTabChannel<E>;
130
142
  epoch: number;
131
143
  clientId: string;
132
144
  identity: TabIdentity;
133
- invoke: (method: string, args: readonly unknown[]) => Promise<unknown>;
145
+ invoke: (tabId: string, method: string, args: readonly unknown[]) => Promise<unknown>;
146
+ onFirstCall?: (tabId: string) => void;
134
147
  onNewerTab: () => void;
135
148
  });
136
149
  /** Announce leadership (on promotion and in answer to every `hello`). */
137
150
  announce(): void;
138
- /** Fan a worker event out to all followers on the current epoch. */
139
- broadcastEvent(event: SyncWorkerEvent): void;
151
+ /** Fan an event out to all followers on the current epoch. */
152
+ broadcastEvent(event: E): void;
153
+ /** Post an event that only the follower `tabId` delivers. */
154
+ sendEvent(tabId: string, event: E): void;
140
155
  close(): void;
141
156
  }
142
157
  /**
@@ -154,13 +169,13 @@ type FollowerSchedule = (callback: () => void, delayMs: number) => () => void;
154
169
  * when a probe goes unanswered, or when the leader's identity differs from
155
170
  * this tab's (see the module comment).
156
171
  */
157
- export declare class FollowerLink {
172
+ export declare class FollowerLink<E = SyncWorkerEvent> {
158
173
  #private;
159
174
  constructor(options: {
160
- channel: CrossTabChannel;
175
+ channel: CrossTabChannel<E>;
161
176
  fromId: string;
162
177
  identity: TabIdentity;
163
- onEvent: (event: SyncWorkerEvent) => void;
178
+ onEvent: (event: E) => void;
164
179
  onLeaderChange: (clientId: string) => void;
165
180
  onStateChange?: (state: LeadershipState) => void;
166
181
  callTimeoutMs?: number;
@@ -200,4 +215,125 @@ export declare class FollowerLink {
200
215
  handOver(invoke: (method: string, args: readonly unknown[]) => Promise<unknown>): void;
201
216
  close(): void;
202
217
  }
218
+ /** What a leader's core receives when this tab wins or promotes. */
219
+ export interface TabLeaderContext<E> {
220
+ /** This leadership's epoch; a promotion runs on a higher one. */
221
+ readonly epoch: number;
222
+ /** This tab's id. The leader's own calls arrive under it. */
223
+ readonly tabId: string;
224
+ /**
225
+ * True when this tab took the lock from an unreachable leader with
226
+ * `takeOver()`. That leader's worker can still hold the database files;
227
+ * the core must take over its storage lock and retry opening until the
228
+ * old worker releases them.
229
+ */
230
+ readonly takeover: boolean;
231
+ /**
232
+ * The leader lock. The coordinator releases it after {@link TabLeader.close}
233
+ * resolves. Release it earlier only when the core is already gone, such as a
234
+ * worker terminated on `pagehide`.
235
+ */
236
+ readonly lease: LeaderLease;
237
+ /** Deliver an event to every tab, this one included. */
238
+ broadcast(event: E): void;
239
+ /** Deliver an event to the tab `tabId` only. */
240
+ send(tabId: string, event: E): void;
241
+ }
242
+ /** The core a leader tab runs for every tab of the coordinator. */
243
+ export interface TabLeader {
244
+ /** Announced to followers as `LeadershipState.leaderClientId`. */
245
+ readonly clientId: string;
246
+ /** Serve one call from the tab `tabId`. */
247
+ call(tabId: string, method: string, args: readonly unknown[]): Promise<unknown>;
248
+ /**
249
+ * The tab `tabId`, which called this leader, closed. Defined only by cores
250
+ * that keep per-tab state; the coordinator then waits on each caller's tab
251
+ * lock.
252
+ */
253
+ tabClosed?(tabId: string): void;
254
+ /**
255
+ * Stop the core. The coordinator releases the leader lock afterwards. It
256
+ * also runs when another tab took the lock: the core must not write again.
257
+ */
258
+ close(): Promise<void>;
259
+ }
260
+ /**
261
+ * A follower's link to its leader went `leader-unreachable`, or left that
262
+ * state. Times are `clock.now()` milliseconds (wall-clock by default).
263
+ */
264
+ export type LeaderUnreachableEvent = {
265
+ readonly phase: 'started';
266
+ readonly at: number;
267
+ /** The earliest time `takeOver()` is allowed. */
268
+ readonly takeOverAt: number;
269
+ } | {
270
+ readonly phase: 'ended';
271
+ readonly at: number;
272
+ readonly durationMs: number;
273
+ /**
274
+ * `rebound`: the leader answered again. `promoted`: its lock passed to
275
+ * this tab. `taken-over`: this tab's `takeOver()` succeeded.
276
+ * `incompatible`: a leader of another build answered. `closed`: this
277
+ * tab closed first.
278
+ */
279
+ readonly outcome: 'rebound' | 'promoted' | 'taken-over' | 'incompatible' | 'closed';
280
+ };
281
+ /** Time source and timer seam; tests inject a manual clock. */
282
+ export interface TabClock {
283
+ now(): number;
284
+ schedule(callback: () => void, delayMs: number): () => void;
285
+ }
286
+ export interface TabCoordinatorConfig<E> {
287
+ /** Web Lock name of the leadership; the channel and tab locks derive from it. */
288
+ readonly name: string;
289
+ /**
290
+ * The application build. Tabs of different versions never serve each other:
291
+ * a leader steps down for a higher version, and a tab next to a leader of
292
+ * another version is `blocked` with reason `leader-incompatible`.
293
+ */
294
+ readonly version: number;
295
+ /** Start the core. Runs when this tab wins the lock, and on every promotion. */
296
+ lead(context: TabLeaderContext<E>): Promise<TabLeader>;
297
+ /** Events the leader broadcast, or sent to this tab. */
298
+ onEvent?(event: E): void;
299
+ onStateChange?(state: LeadershipState): void;
300
+ /** Start and end of every `leader-unreachable` period, for host telemetry. */
301
+ onLeaderUnreachable?(event: LeaderUnreachableEvent): void;
302
+ /** Defaults to Web Locks; tests inject a name-keyed exclusive lock. */
303
+ readonly lock?: LeaderLock;
304
+ readonly channelFactory?: (name: string) => CrossTabChannel<E>;
305
+ /** Liveness and handover-queue deadline; defaults to 10 s. */
306
+ readonly callTimeoutMs?: number;
307
+ /**
308
+ * How long a follower must have been `leader-unreachable` before
309
+ * `takeOver()` is allowed; defaults to twice `callTimeoutMs`.
310
+ */
311
+ readonly takeOverAfterMs?: number;
312
+ readonly clock?: TabClock;
313
+ }
314
+ /** One tab's end of the coordinator, the same in leader and follower tabs. */
315
+ export interface TabCoordinator {
316
+ readonly tabId: string;
317
+ readonly state: LeadershipState;
318
+ /** Run a call on the leader's core, in this tab or over the channel. */
319
+ call(method: string, args: readonly unknown[]): Promise<unknown>;
320
+ /**
321
+ * Take the lock from a leader that has been `leader-unreachable` for
322
+ * `takeOverAfterMs`, and start the core in this tab. The old leader reports
323
+ * `leadership-taken` and closes its core once it runs again. Rejects with
324
+ * `client.takeover_refused` (`details.reason`: `not-unreachable`,
325
+ * `too-early`, `in-progress` or `unsupported`) when the conditions do not
326
+ * hold, and with the core's start error when the core cannot start.
327
+ */
328
+ takeOver(): Promise<void>;
329
+ /** Stop the core (leader) or the link (follower), and release this tab's locks. */
330
+ close(): Promise<void>;
331
+ }
332
+ /**
333
+ * Elect one leader tab per `name` and run `lead` there; every other tab
334
+ * forwards its calls to that core and receives its events. When the leader
335
+ * tab closes, one follower promotes in place on a higher epoch and runs
336
+ * `lead` itself. Resolves once this tab leads or is bound to a leader.
337
+ */
338
+ export declare function createTabCoordinator<E>(config: TabCoordinatorConfig<E>): Promise<TabCoordinator>;
203
339
  export {};