@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.
@@ -5,7 +5,7 @@ import { ClientSyncError } from './errors.js';
5
5
  import { ChangeEmitter, InvalidationEmitter, invalidationFromChange, } from './invalidation.js';
6
6
  import { singleOwnerLock, webLocksLeaderLock, } from './leader-lock.js';
7
7
  import { decodeLocalDataRebootstrapResult, } from './local-rebootstrap.js';
8
- import { broadcastChannelFactory, FollowerLink, LEADER_INCOMPATIBLE_CODE, LeaderBridge, MULTI_TAB_PROTOCOL_VERSION, multiTabChannelName, newTabId, } from './multi-tab.js';
8
+ import { createTabCoordinator, multiTabChannelName, TAKEOVER_REFUSED_CODE, } from './multi-tab.js';
9
9
  import { decodePreviousVersionAuditResult, decodePreviousVersionDiscardResult, decodePreviousVersionSnapshot, } from './previous-version.js';
10
10
  import { NOT_LEADER_CODE, WORKER_FAILED_CODE, WORKER_RESTART_REQUIRED_CODE, } from './worker-protocol.js';
11
11
  const WORKER_BUNDLE_LOAD_FAILURE = /(?:failed to fetch dynamically imported module|error loading dynamically imported module|importing a module script failed|failed to load module script)/iu;
@@ -67,8 +67,10 @@ export class SyncClientHandle {
67
67
  #clientId;
68
68
  #currentSchemaVersion;
69
69
  #leadership;
70
+ /** The multi-tab route: this tab's core when it leads, the leader's otherwise. */
71
+ #tabs;
72
+ /** The `multiTab: false` leader's own core. */
70
73
  #core;
71
- #follower;
72
74
  #invalidation;
73
75
  #progress = new ProgressEmitter();
74
76
  #changes;
@@ -76,6 +78,7 @@ export class SyncClientHandle {
76
78
  #diagnostics;
77
79
  #roleListeners;
78
80
  #leadershipListeners;
81
+ #unreachableListeners;
79
82
  #devtoolsUnregister;
80
83
  #closed = false;
81
84
  /** @internal — use {@link createSyncClientHandle}. */
@@ -85,22 +88,24 @@ export class SyncClientHandle {
85
88
  this.#currentSchemaVersion = internals.currentSchemaVersion;
86
89
  this.#leadership =
87
90
  internals.leadership ??
91
+ internals.tabs?.state ??
88
92
  (internals.role === 'leader'
89
93
  ? { state: 'leader', clientId: internals.clientId }
90
- : (internals.follower?.leadershipState ?? {
94
+ : {
91
95
  state: 'blocked',
92
96
  reason: 'leader-unreachable',
93
97
  code: 'client.follower_timeout',
94
98
  retryable: true,
95
- }));
99
+ });
96
100
  this.#core = internals.core;
97
- this.#follower = internals.follower;
101
+ this.#tabs = internals.tabs;
98
102
  this.#invalidation = internals.invalidation;
99
103
  this.#changes = internals.changes;
100
104
  this.#presence = internals.presence;
101
105
  this.#diagnostics = internals.diagnostics;
102
106
  this.#roleListeners = internals.roleListeners ?? new Set();
103
107
  this.#leadershipListeners = internals.leadershipListeners ?? new Set();
108
+ this.#unreachableListeners = internals.unreachableListeners ?? new Set();
104
109
  // Console introspection is a no-op outside a dev page.
105
110
  this.#devtoolsUnregister = registerDevtools({
106
111
  kind: 'handle',
@@ -117,64 +122,13 @@ export class SyncClientHandle {
117
122
  });
118
123
  }
119
124
  /**
120
- * @internal — whether `close()` has run.
121
- *
122
- * A follower keeps a blocking `acquire` outstanding for the whole time it is a
123
- * follower, so its promotion can fire long after the application has discarded
124
- * the handle. The promotion path consults this before opening anything.
125
+ * @internal — apply a leadership snapshot in place: a promotion flips the
126
+ * role to `'leader'`, stepping down for a newer tab flips it back.
125
127
  */
126
- get __isClosed() {
127
- return this.#closed;
128
- }
129
- /** @internal — swap this handle from follower to leader (promotion). */
130
- __becomeLeader(core) {
131
- // Calls queued for the next leader run on this tab's own core.
132
- this.#follower?.handOver(core.invoke);
133
- this.#follower = undefined;
134
- this.#core = core;
135
- this.#clientId = core.clientId;
136
- this.#role = 'leader';
137
- this.__setLeadership({ state: 'leader', clientId: core.clientId });
138
- for (const listener of this.#roleListeners) {
139
- try {
140
- listener('leader');
141
- }
142
- catch {
143
- /* a UI listener must never break promotion */
144
- }
145
- }
146
- }
147
- /**
148
- * @internal — a newer tab asked for the database: close the core and
149
- * release the lock so that tab promotes. This tab stays blocked until it
150
- * reloads with the newer build.
151
- */
152
- __yieldToNewerTab() {
153
- const core = this.#core;
154
- if (core === undefined)
155
- return;
156
- this.#core = undefined;
157
- this.#role = 'follower';
158
- this.__setLeadership({
159
- state: 'blocked',
160
- reason: 'leader-incompatible',
161
- code: LEADER_INCOMPATIBLE_CODE,
162
- leader: 'newer',
163
- retryable: true,
164
- });
165
- for (const listener of this.#roleListeners) {
166
- try {
167
- listener('follower');
168
- }
169
- catch {
170
- /* a UI listener must never break the handover */
171
- }
172
- }
173
- void core.close(true);
174
- }
175
- /** @internal — apply a follower reachability snapshot in place. */
176
128
  __setLeadership(state) {
177
129
  this.#leadership = state;
130
+ if (state.state === 'leader')
131
+ this.#clientId = state.clientId;
178
132
  if (state.state === 'follower')
179
133
  this.#clientId = state.leaderClientId;
180
134
  for (const listener of this.#leadershipListeners) {
@@ -185,6 +139,18 @@ export class SyncClientHandle {
185
139
  /* a UI listener must never break leadership transitions */
186
140
  }
187
141
  }
142
+ const role = state.state === 'leader' ? 'leader' : 'follower';
143
+ if (role === this.#role)
144
+ return;
145
+ this.#role = role;
146
+ for (const listener of this.#roleListeners) {
147
+ try {
148
+ listener(role);
149
+ }
150
+ catch {
151
+ /* a UI listener must never break a promotion or a handover */
152
+ }
153
+ }
188
154
  }
189
155
  /** @internal — dispatch a worker/relayed event to handle-local listeners. */
190
156
  __dispatchEvent(event) {
@@ -259,24 +225,42 @@ export class SyncClientHandle {
259
225
  this.#leadershipListeners.delete(listener);
260
226
  };
261
227
  }
262
- #call(method, args) {
228
+ /** Start and end of every `leader-unreachable` period, with its duration. */
229
+ onLeaderUnreachable(listener) {
230
+ this.#unreachableListeners.add(listener);
231
+ return () => {
232
+ this.#unreachableListeners.delete(listener);
233
+ };
234
+ }
235
+ /**
236
+ * Take the database from a leader tab that has been `leader-unreachable`
237
+ * for `takeOverAfterMs`, and run the worker in this tab. Call it from an
238
+ * explicit user action. The old leader's worker refuses every statement
239
+ * from then on (`client.storage_fenced`) and its tab reports
240
+ * `leadership-taken`. Rejects with `client.takeover_refused` when the
241
+ * conditions do not hold, and with `client.storage_busy` when the old
242
+ * worker still holds the database files.
243
+ */
244
+ takeOver() {
263
245
  if (this.#closed) {
264
246
  return Promise.reject(new ClientSyncError(WORKER_FAILED_CODE, 'the handle is closed'));
265
247
  }
266
- if (this.#leadership.state === 'blocked' &&
267
- this.#leadership.reason === 'leader-incompatible') {
268
- return Promise.reject(new ClientSyncError(LEADER_INCOMPATIBLE_CODE, 'the tab that owns the database runs a different protocol or schema version', true));
248
+ if (this.#tabs === undefined) {
249
+ return Promise.reject(new ClientSyncError(TAKEOVER_REFUSED_CODE, 'takeOver() requires a multi-tab handle', false, { reason: 'unsupported' }));
269
250
  }
270
- if (this.#role === 'follower') {
271
- if (this.#follower === undefined) {
272
- return Promise.reject(new ClientSyncError(NOT_LEADER_CODE, 'this tab is not the leader — another tab owns the syncular ' +
273
- 'core for this origin (this handle opted out of follower ' +
274
- 'proxying with multiTab: false)'));
275
- }
276
- return this.#follower.call(method, args);
251
+ return this.#tabs.takeOver();
252
+ }
253
+ #call(method, args) {
254
+ if (this.#closed) {
255
+ return Promise.reject(new ClientSyncError(WORKER_FAILED_CODE, 'the handle is closed'));
256
+ }
257
+ if (this.#tabs !== undefined) {
258
+ return this.#tabs.call(method, args);
277
259
  }
278
260
  if (this.#core === undefined) {
279
- return Promise.reject(new ClientSyncError(WORKER_FAILED_CODE, 'the handle is closed'));
261
+ return Promise.reject(new ClientSyncError(NOT_LEADER_CODE, 'this tab is not the leader — another tab owns the syncular ' +
262
+ 'core for this origin (this handle opted out of follower ' +
263
+ 'proxying with multiTab: false)'));
280
264
  }
281
265
  return this.#core.invoke(method, args);
282
266
  }
@@ -430,28 +414,40 @@ export class SyncClientHandle {
430
414
  setOffline(offline) {
431
415
  return this.#call('setOffline', [offline]);
432
416
  }
433
- /** Close the core (leader) or unbind the link (follower), release leadership. */
417
+ /** SPEC §12.3 local-authority state; `undefined` without `localAuthority`. */
418
+ localAuthorityState() {
419
+ return this.#call('localAuthorityState', []);
420
+ }
421
+ /**
422
+ * SPEC §12.3: upload the local authority's rows to `endpoints.syncUrl`,
423
+ * then sync with that server. Rejects with `sync.attach_rejected` when the
424
+ * server refuses an upload commit.
425
+ */
426
+ attachLocalAuthority() {
427
+ return this.#call('attachLocalAuthority', []);
428
+ }
429
+ /** SPEC §12.3: delete the rows a stopped attach uploaded, then sync locally. */
430
+ abandonLocalAuthorityAttach() {
431
+ return this.#call('abandonLocalAuthorityAttach', []);
432
+ }
433
+ /** Close the core (leader) or the link (follower), release leadership. */
434
434
  async close() {
435
435
  if (this.#closed)
436
436
  return;
437
437
  this.#closed = true;
438
438
  this.#progress.clear();
439
439
  this.#devtoolsUnregister();
440
- if (this.#follower !== undefined) {
441
- this.#follower.close();
442
- this.#follower = undefined;
443
- }
440
+ await this.#tabs?.close();
444
441
  if (this.#core !== undefined) {
445
442
  const core = this.#core;
446
443
  this.#core = undefined;
447
- await core.close(true);
444
+ await core.close();
448
445
  }
449
446
  }
450
447
  }
451
448
  /**
452
449
  * Spawn the worker, run the init handshake, and return a running leader core.
453
- * `dispatchEvent` receives every worker event; `bridge` (when supplied) is
454
- * the follower relay whose lifetime is tied to this core.
450
+ * `dispatchEvent` receives every worker event.
455
451
  */
456
452
  async function startWorkerCore(options) {
457
453
  const { config, initConfig, lease } = options;
@@ -466,7 +462,6 @@ async function startWorkerCore(options) {
466
462
  return;
467
463
  terminated = true;
468
464
  globalThis.removeEventListener?.('pagehide', terminate);
469
- bridge?.close();
470
465
  worker.terminate();
471
466
  rejectReady?.(closedError);
472
467
  for (const entry of pending.values())
@@ -492,7 +487,6 @@ async function startWorkerCore(options) {
492
487
  });
493
488
  });
494
489
  };
495
- let bridge;
496
490
  const ready = new Promise((resolve, reject) => {
497
491
  rejectReady = reject;
498
492
  const onMessage = (event) => {
@@ -515,7 +509,6 @@ async function startWorkerCore(options) {
515
509
  }
516
510
  case 'event':
517
511
  options.dispatchEvent(message.event);
518
- bridge?.broadcastEvent(message.event);
519
512
  break;
520
513
  }
521
514
  };
@@ -543,33 +536,19 @@ async function startWorkerCore(options) {
543
536
  config: initConfig,
544
537
  });
545
538
  });
546
- if (options.makeBridge !== undefined) {
547
- bridge = options.makeBridge(initResult.clientId, invoke);
548
- }
549
539
  return {
550
540
  clientId: initResult.clientId,
551
541
  invoke,
552
- bridge,
553
- lease,
554
- close: async (terminateWorker) => {
542
+ close: async () => {
555
543
  if (terminated)
556
544
  return;
557
- bridge?.close();
558
545
  try {
559
546
  await invoke('close', []);
560
547
  }
561
548
  catch {
562
549
  // A terminated or failed worker has no further close RPC to service.
563
550
  }
564
- if (terminateWorker)
565
- terminate();
566
- else {
567
- globalThis.removeEventListener?.('pagehide', terminate);
568
- for (const entry of pending.values())
569
- entry.reject(closedError);
570
- pending.clear();
571
- await lease.release();
572
- }
551
+ terminate();
573
552
  },
574
553
  };
575
554
  }
@@ -590,6 +569,9 @@ function buildInitConfig(config, headers = config.headers) {
590
569
  ...(config.transportEnabled !== undefined
591
570
  ? { transportEnabled: config.transportEnabled }
592
571
  : {}),
572
+ ...(config.localAuthority !== undefined
573
+ ? { localAuthority: config.localAuthority }
574
+ : {}),
593
575
  ...(config.authorityReads !== undefined
594
576
  ? { authorityReads: config.authorityReads.declarations }
595
577
  : {}),
@@ -656,239 +638,119 @@ export async function createSyncClientHandle(config) {
656
638
  if (resolvedConfig.onLeadershipChange !== undefined) {
657
639
  leadershipListeners.add(resolvedConfig.onLeadershipChange);
658
640
  }
659
- // Leadership BEFORE the worker exists: one core per origin, and a losing
660
- // tab never boots a database it must not own.
661
- const lease = lock.tryAcquire !== undefined
662
- ? await lock.tryAcquire(lockName)
663
- : await lock.acquire(lockName);
664
- // ---- Won the election: leader. ----
665
- if (lease !== undefined) {
666
- // Epoch derivation for a fresh boot: epoch 0. A promoter (below) reads
667
- // the highest epoch it has seen and adds one, so leaders monotonically
668
- // increase it across handovers.
669
- return await bootLeader(resolvedConfig, lockName, lease, {
670
- epoch: 0,
671
- invalidation,
672
- changes,
673
- presence,
674
- diagnostics,
675
- roleListeners,
676
- leadershipListeners,
677
- });
641
+ const unreachableListeners = new Set();
642
+ if (resolvedConfig.onLeaderUnreachable !== undefined) {
643
+ unreachableListeners.add(resolvedConfig.onLeaderUnreachable);
678
644
  }
679
- // ---- Lost the election. ----
680
- if (resolvedConfig.multiTab === false) {
681
- // Opted-out single-tab contract: a dead not-leader handle.
682
- return new SyncClientHandle({
683
- role: 'follower',
684
- clientId: '',
685
- currentSchemaVersion: resolvedConfig.schema.version,
686
- invalidation,
687
- changes,
688
- presence,
689
- diagnostics,
690
- roleListeners,
691
- leadershipListeners,
692
- });
693
- }
694
- // ---- Follower: proxy to the leader; contest + promote on its close. ----
695
- return await bootFollower(resolvedConfig, lockName, lock, {
645
+ const handleRef = {
646
+ handle: undefined,
647
+ };
648
+ const parts = {
649
+ currentSchemaVersion: resolvedConfig.schema.version,
696
650
  invalidation,
697
651
  changes,
698
652
  presence,
699
653
  diagnostics,
700
654
  roleListeners,
701
655
  leadershipListeners,
702
- });
703
- }
704
- /** Boot (or promote to) a leader: spawn the worker, wire the bridge. */
705
- async function bootLeader(config, lockName, lease, parts) {
706
- const handleRef = {
707
- handle: undefined,
656
+ unreachableListeners,
708
657
  };
709
- const dispatchEvent = (event) => {
710
- fireConfigCallbacks(config, event);
711
- handleRef.handle?.__dispatchEvent(event);
712
- };
713
- // A newer tab may say hello before the handle exists; yield once it does.
714
- let newerTab = false;
715
- const makeBridge = config.multiTab !== false
716
- ? (clientId, invoke) => {
717
- const factory = config.channelFactory ?? broadcastChannelFactory();
718
- const channel = factory(multiTabChannelName(lockName));
719
- return new LeaderBridge({
720
- channel,
721
- epoch: parts.epoch ?? 0,
722
- clientId,
723
- identity: tabIdentity(config),
724
- invoke,
725
- onNewerTab: () => {
726
- newerTab = true;
727
- handleRef.handle?.__yieldToNewerTab();
728
- },
729
- });
658
+ if (resolvedConfig.multiTab === false) {
659
+ // Single-tab contract: the leader runs its core with no channel; a losing
660
+ // tab is a dead not-leader handle that never boots a database.
661
+ const lease = lock.tryAcquire !== undefined
662
+ ? await lock.tryAcquire(lockName)
663
+ : await lock.acquire(lockName);
664
+ if (lease === undefined) {
665
+ return new SyncClientHandle({ role: 'follower', clientId: '', ...parts });
730
666
  }
731
- : undefined;
732
- const core = await startWorkerCore({
733
- config,
734
- initConfig: buildInitConfig(config),
735
- lease,
736
- dispatchEvent,
737
- ...(makeBridge !== undefined ? { makeBridge } : {}),
738
- });
739
- const handle = new SyncClientHandle({
740
- role: 'leader',
741
- clientId: core.clientId,
742
- currentSchemaVersion: config.schema.version,
743
- core,
744
- invalidation: parts.invalidation,
745
- changes: parts.changes,
746
- presence: parts.presence,
747
- diagnostics: parts.diagnostics,
748
- roleListeners: parts.roleListeners,
749
- leadershipListeners: parts.leadershipListeners,
750
- });
751
- handleRef.handle = handle;
752
- if (newerTab)
753
- handle.__yieldToNewerTab();
754
- return handle;
755
- }
756
- function tabIdentity(config) {
757
- return {
758
- protocol: MULTI_TAB_PROTOCOL_VERSION,
759
- schemaVersion: config.schema.version,
760
- };
761
- }
762
- /**
763
- * Boot a follower: open the channel, bind to the leader, and race the lock in
764
- * the background so this tab promotes itself the instant the leader closes.
765
- */
766
- async function bootFollower(config, lockName, lock, parts) {
767
- const factory = config.channelFactory ?? broadcastChannelFactory();
768
- const channel = factory(multiTabChannelName(lockName));
769
- const handleRef = {
770
- handle: undefined,
771
- };
772
- const follower = new FollowerLink({
773
- channel,
774
- fromId: newTabId(),
775
- identity: tabIdentity(config),
776
- onEvent: (event) => handleRef.handle?.__dispatchEvent(event),
777
- onLeaderChange: (clientId) => {
778
- // Learn the leader's shared client id (best-effort; the handle exposes
779
- // it after binding). Nothing else to do — calls already flush.
780
- void clientId;
781
- },
782
- onStateChange: (state) => handleRef.handle?.__setLeadership(state),
783
- ...(config.followerCallTimeoutMs !== undefined
784
- ? { callTimeoutMs: config.followerCallTimeoutMs }
667
+ const core = await startWorkerCore({
668
+ config: resolvedConfig,
669
+ initConfig: buildInitConfig(resolvedConfig),
670
+ lease,
671
+ dispatchEvent: (event) => {
672
+ fireConfigCallbacks(resolvedConfig, event);
673
+ handleRef.handle?.__dispatchEvent(event);
674
+ },
675
+ });
676
+ const handle = new SyncClientHandle({
677
+ role: 'leader',
678
+ clientId: core.clientId,
679
+ core,
680
+ ...parts,
681
+ });
682
+ handleRef.handle = handle;
683
+ return handle;
684
+ }
685
+ // One core per origin: the tab that wins the lock runs the worker, every
686
+ // other tab forwards to it and promotes when it closes.
687
+ const tabs = await createTabCoordinator({
688
+ name: lockName,
689
+ version: resolvedConfig.schema.version,
690
+ lock,
691
+ ...(resolvedConfig.channelFactory !== undefined
692
+ ? { channelFactory: resolvedConfig.channelFactory }
785
693
  : {}),
786
- });
787
- // A follower waits (blocking) on the exclusive lock: it resolves ONLY when
788
- // the current leader releases it (tab close). Winning it triggers promotion.
789
- // We do NOT hold this promise — it settles asynchronously.
790
- void lock.acquire(lockName).then(async (lease) => {
791
- const handle = handleRef.handle;
792
- if (handle === undefined) {
793
- // Handle was never assembled (shouldn't happen); drop the lease.
794
- await lease.release();
795
- return;
796
- }
797
- if (handle.__isClosed) {
798
- // The application discarded this handle while it was queued for
799
- // leadership. Promoting now would open a database nobody is holding and
800
- // then keep the lock forever, so no other tab could ever take over.
801
- // Release instead, and let the next waiter have it.
802
- await lease.release();
803
- return;
804
- }
805
- // The follower saw the departing leader's epoch; the new leader must
806
- // strictly exceed it so stale replies/events are discarded everywhere.
807
- const nextEpoch = follower.maxEpochSeen + 1;
808
- // Unbind the link so any late leader traffic is ignored, then promote.
809
- follower.unbind();
810
- // A newer tab may say hello before this core is installed.
811
- let newerTab = false;
812
- try {
694
+ ...(resolvedConfig.followerCallTimeoutMs !== undefined
695
+ ? { callTimeoutMs: resolvedConfig.followerCallTimeoutMs }
696
+ : {}),
697
+ ...(resolvedConfig.takeOverAfterMs !== undefined
698
+ ? { takeOverAfterMs: resolvedConfig.takeOverAfterMs }
699
+ : {}),
700
+ ...(resolvedConfig.tabClock !== undefined
701
+ ? { clock: resolvedConfig.tabClock }
702
+ : {}),
703
+ onLeaderUnreachable: (event) => {
704
+ for (const listener of unreachableListeners) {
705
+ try {
706
+ listener(event);
707
+ }
708
+ catch {
709
+ /* a telemetry listener must never break cross-tab coordination */
710
+ }
711
+ }
712
+ },
713
+ lead: async (context) => {
813
714
  const core = await startWorkerCore({
814
- config,
815
- initConfig: buildInitConfig(config, handle.__headers ?? config.headers),
816
- lease,
715
+ config: resolvedConfig,
716
+ // A promoted tab carries the latest `setHeaders` set.
717
+ initConfig: {
718
+ ...buildInitConfig(resolvedConfig, handleRef.handle?.__headers ?? resolvedConfig.headers),
719
+ ...(context.takeover ? { takeOverStorage: true } : {}),
720
+ },
721
+ lease: context.lease,
817
722
  dispatchEvent: (event) => {
818
- fireConfigCallbacks(config, event);
819
- handle.__dispatchEvent(event);
723
+ fireConfigCallbacks(resolvedConfig, event);
724
+ context.broadcast(event);
820
725
  },
821
- ...(config.multiTab !== false
822
- ? {
823
- makeBridge: (clientId, invoke) => {
824
- const promoteChannel = factory(multiTabChannelName(lockName));
825
- return new LeaderBridge({
826
- channel: promoteChannel,
827
- epoch: nextEpoch,
828
- clientId,
829
- identity: tabIdentity(config),
830
- invoke,
831
- onNewerTab: () => {
832
- newerTab = true;
833
- handle.__yieldToNewerTab();
834
- },
835
- });
836
- },
837
- }
838
- : {}),
839
726
  });
840
- if (handle.__isClosed) {
841
- // Closed while the worker was starting. `close()` already ran and found
842
- // no core to shut down, so this one would leak: tear it down here rather
843
- // than hand it to a discarded handle. `close(true)` releases the lease.
844
- await core.close(true);
845
- return;
846
- }
847
- handle.__becomeLeader(core);
848
- if (newerTab)
849
- handle.__yieldToNewerTab();
850
- }
851
- catch {
852
- // Promotion failed to spawn a worker — release so the next tab tries.
853
- await lease.release();
854
- }
727
+ return {
728
+ clientId: core.clientId,
729
+ call: (_tabId, method, args) => core.invoke(method, args),
730
+ close: () => core.close(),
731
+ };
732
+ },
733
+ onEvent: (event) => handleRef.handle?.__dispatchEvent(event),
734
+ onStateChange: (state) => handleRef.handle?.__setLeadership(state),
855
735
  });
736
+ const leadership = tabs.state;
856
737
  const handle = new SyncClientHandle({
857
- role: 'follower',
858
- // The follower learns the leader's shared client id once bound; expose it
859
- // lazily via `clientId` is not possible on a getter over the link, so we
860
- // leave '' until promotion (the shared id is the leader's — hooks that
861
- // need it read it after a round). Followers rarely need clientId directly.
862
- clientId: '',
863
- currentSchemaVersion: config.schema.version,
864
- follower,
865
- invalidation: parts.invalidation,
866
- changes: parts.changes,
867
- presence: parts.presence,
868
- diagnostics: parts.diagnostics,
869
- roleListeners: parts.roleListeners,
870
- leadershipListeners: parts.leadershipListeners,
738
+ role: leadership.state === 'leader' ? 'leader' : 'follower',
739
+ clientId: leadership.state === 'leader'
740
+ ? leadership.clientId
741
+ : leadership.state === 'follower'
742
+ ? leadership.leaderClientId
743
+ : '',
744
+ tabs,
745
+ ...parts,
871
746
  });
872
747
  handleRef.handle = handle;
873
- // Do not hand back a follower until its link has bound to the leader (the
874
- // hello→announce round trip completed). Before binding, epoch is -1 and any
875
- // event the leader fans out is dropped, so a caller that subscribes and then
876
- // relies on push invalidation would silently miss events emitted in the
877
- // binding window — a real multi-tab race, not just a test flake. Binding is
878
- // fast (the leader answers every hello with an announce); on the off chance
879
- // it times out we still return the handle (queued calls flush and events
880
- // resume on the next announce) rather than failing handle construction.
881
- try {
882
- await follower.waitUntilBound();
883
- }
884
- catch {
885
- /* bind timed out — return the (degraded but functional) handle anyway */
886
- }
887
748
  // Init configuration belongs to the one leader worker. A newly opened
888
749
  // follower that explicitly requests security preflight must therefore put
889
750
  // the shared origin replica behind the same barrier before it is returned;
890
751
  // otherwise an already-running leader would silently ignore the request.
891
- if (config.securityPreflight === true) {
752
+ if (leadership.state !== 'leader' &&
753
+ resolvedConfig.securityPreflight === true) {
892
754
  try {
893
755
  await handle.beginSecurityPreflight();
894
756
  }