@syncular/client 0.47.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.
@@ -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, } 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;
@@ -85,16 +87,17 @@ export class SyncClientHandle {
85
87
  this.#currentSchemaVersion = internals.currentSchemaVersion;
86
88
  this.#leadership =
87
89
  internals.leadership ??
90
+ internals.tabs?.state ??
88
91
  (internals.role === 'leader'
89
92
  ? { state: 'leader', clientId: internals.clientId }
90
- : (internals.follower?.leadershipState ?? {
93
+ : {
91
94
  state: 'blocked',
92
95
  reason: 'leader-unreachable',
93
96
  code: 'client.follower_timeout',
94
97
  retryable: true,
95
- }));
98
+ });
96
99
  this.#core = internals.core;
97
- this.#follower = internals.follower;
100
+ this.#tabs = internals.tabs;
98
101
  this.#invalidation = internals.invalidation;
99
102
  this.#changes = internals.changes;
100
103
  this.#presence = internals.presence;
@@ -117,64 +120,13 @@ export class SyncClientHandle {
117
120
  });
118
121
  }
119
122
  /**
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.
123
+ * @internal — apply a leadership snapshot in place: a promotion flips the
124
+ * role to `'leader'`, stepping down for a newer tab flips it back.
125
125
  */
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
126
  __setLeadership(state) {
177
127
  this.#leadership = state;
128
+ if (state.state === 'leader')
129
+ this.#clientId = state.clientId;
178
130
  if (state.state === 'follower')
179
131
  this.#clientId = state.leaderClientId;
180
132
  for (const listener of this.#leadershipListeners) {
@@ -185,6 +137,18 @@ export class SyncClientHandle {
185
137
  /* a UI listener must never break leadership transitions */
186
138
  }
187
139
  }
140
+ const role = state.state === 'leader' ? 'leader' : 'follower';
141
+ if (role === this.#role)
142
+ return;
143
+ this.#role = role;
144
+ for (const listener of this.#roleListeners) {
145
+ try {
146
+ listener(role);
147
+ }
148
+ catch {
149
+ /* a UI listener must never break a promotion or a handover */
150
+ }
151
+ }
188
152
  }
189
153
  /** @internal — dispatch a worker/relayed event to handle-local listeners. */
190
154
  __dispatchEvent(event) {
@@ -263,20 +227,13 @@ export class SyncClientHandle {
263
227
  if (this.#closed) {
264
228
  return Promise.reject(new ClientSyncError(WORKER_FAILED_CODE, 'the handle is closed'));
265
229
  }
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));
269
- }
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);
230
+ if (this.#tabs !== undefined) {
231
+ return this.#tabs.call(method, args);
277
232
  }
278
233
  if (this.#core === undefined) {
279
- return Promise.reject(new ClientSyncError(WORKER_FAILED_CODE, 'the handle is closed'));
234
+ return Promise.reject(new ClientSyncError(NOT_LEADER_CODE, 'this tab is not the leader — another tab owns the syncular ' +
235
+ 'core for this origin (this handle opted out of follower ' +
236
+ 'proxying with multiTab: false)'));
280
237
  }
281
238
  return this.#core.invoke(method, args);
282
239
  }
@@ -430,28 +387,40 @@ export class SyncClientHandle {
430
387
  setOffline(offline) {
431
388
  return this.#call('setOffline', [offline]);
432
389
  }
433
- /** Close the core (leader) or unbind the link (follower), release leadership. */
390
+ /** SPEC §12.3 local-authority state; `undefined` without `localAuthority`. */
391
+ localAuthorityState() {
392
+ return this.#call('localAuthorityState', []);
393
+ }
394
+ /**
395
+ * SPEC §12.3: upload the local authority's rows to `endpoints.syncUrl`,
396
+ * then sync with that server. Rejects with `sync.attach_rejected` when the
397
+ * server refuses an upload commit.
398
+ */
399
+ attachLocalAuthority() {
400
+ return this.#call('attachLocalAuthority', []);
401
+ }
402
+ /** SPEC §12.3: delete the rows a stopped attach uploaded, then sync locally. */
403
+ abandonLocalAuthorityAttach() {
404
+ return this.#call('abandonLocalAuthorityAttach', []);
405
+ }
406
+ /** Close the core (leader) or the link (follower), release leadership. */
434
407
  async close() {
435
408
  if (this.#closed)
436
409
  return;
437
410
  this.#closed = true;
438
411
  this.#progress.clear();
439
412
  this.#devtoolsUnregister();
440
- if (this.#follower !== undefined) {
441
- this.#follower.close();
442
- this.#follower = undefined;
443
- }
413
+ await this.#tabs?.close();
444
414
  if (this.#core !== undefined) {
445
415
  const core = this.#core;
446
416
  this.#core = undefined;
447
- await core.close(true);
417
+ await core.close();
448
418
  }
449
419
  }
450
420
  }
451
421
  /**
452
422
  * 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.
423
+ * `dispatchEvent` receives every worker event.
455
424
  */
456
425
  async function startWorkerCore(options) {
457
426
  const { config, initConfig, lease } = options;
@@ -466,7 +435,6 @@ async function startWorkerCore(options) {
466
435
  return;
467
436
  terminated = true;
468
437
  globalThis.removeEventListener?.('pagehide', terminate);
469
- bridge?.close();
470
438
  worker.terminate();
471
439
  rejectReady?.(closedError);
472
440
  for (const entry of pending.values())
@@ -492,7 +460,6 @@ async function startWorkerCore(options) {
492
460
  });
493
461
  });
494
462
  };
495
- let bridge;
496
463
  const ready = new Promise((resolve, reject) => {
497
464
  rejectReady = reject;
498
465
  const onMessage = (event) => {
@@ -515,7 +482,6 @@ async function startWorkerCore(options) {
515
482
  }
516
483
  case 'event':
517
484
  options.dispatchEvent(message.event);
518
- bridge?.broadcastEvent(message.event);
519
485
  break;
520
486
  }
521
487
  };
@@ -543,33 +509,19 @@ async function startWorkerCore(options) {
543
509
  config: initConfig,
544
510
  });
545
511
  });
546
- if (options.makeBridge !== undefined) {
547
- bridge = options.makeBridge(initResult.clientId, invoke);
548
- }
549
512
  return {
550
513
  clientId: initResult.clientId,
551
514
  invoke,
552
- bridge,
553
- lease,
554
- close: async (terminateWorker) => {
515
+ close: async () => {
555
516
  if (terminated)
556
517
  return;
557
- bridge?.close();
558
518
  try {
559
519
  await invoke('close', []);
560
520
  }
561
521
  catch {
562
522
  // A terminated or failed worker has no further close RPC to service.
563
523
  }
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
- }
524
+ terminate();
573
525
  },
574
526
  };
575
527
  }
@@ -590,6 +542,9 @@ function buildInitConfig(config, headers = config.headers) {
590
542
  ...(config.transportEnabled !== undefined
591
543
  ? { transportEnabled: config.transportEnabled }
592
544
  : {}),
545
+ ...(config.localAuthority !== undefined
546
+ ? { localAuthority: config.localAuthority }
547
+ : {}),
593
548
  ...(config.authorityReads !== undefined
594
549
  ? { authorityReads: config.authorityReads.declarations }
595
550
  : {}),
@@ -656,239 +611,95 @@ export async function createSyncClientHandle(config) {
656
611
  if (resolvedConfig.onLeadershipChange !== undefined) {
657
612
  leadershipListeners.add(resolvedConfig.onLeadershipChange);
658
613
  }
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
- });
678
- }
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, {
614
+ const handleRef = {
615
+ handle: undefined,
616
+ };
617
+ const parts = {
618
+ currentSchemaVersion: resolvedConfig.schema.version,
696
619
  invalidation,
697
620
  changes,
698
621
  presence,
699
622
  diagnostics,
700
623
  roleListeners,
701
624
  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,
708
- };
709
- const dispatchEvent = (event) => {
710
- fireConfigCallbacks(config, event);
711
- handleRef.handle?.__dispatchEvent(event);
712
625
  };
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
- });
626
+ if (resolvedConfig.multiTab === false) {
627
+ // Single-tab contract: the leader runs its core with no channel; a losing
628
+ // tab is a dead not-leader handle that never boots a database.
629
+ const lease = lock.tryAcquire !== undefined
630
+ ? await lock.tryAcquire(lockName)
631
+ : await lock.acquire(lockName);
632
+ if (lease === undefined) {
633
+ return new SyncClientHandle({ role: 'follower', clientId: '', ...parts });
730
634
  }
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 }
635
+ const core = await startWorkerCore({
636
+ config: resolvedConfig,
637
+ initConfig: buildInitConfig(resolvedConfig),
638
+ lease,
639
+ dispatchEvent: (event) => {
640
+ fireConfigCallbacks(resolvedConfig, event);
641
+ handleRef.handle?.__dispatchEvent(event);
642
+ },
643
+ });
644
+ const handle = new SyncClientHandle({
645
+ role: 'leader',
646
+ clientId: core.clientId,
647
+ core,
648
+ ...parts,
649
+ });
650
+ handleRef.handle = handle;
651
+ return handle;
652
+ }
653
+ // One core per origin: the tab that wins the lock runs the worker, every
654
+ // other tab forwards to it and promotes when it closes.
655
+ const tabs = await createTabCoordinator({
656
+ name: lockName,
657
+ version: resolvedConfig.schema.version,
658
+ lock,
659
+ ...(resolvedConfig.channelFactory !== undefined
660
+ ? { channelFactory: resolvedConfig.channelFactory }
785
661
  : {}),
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 {
662
+ ...(resolvedConfig.followerCallTimeoutMs !== undefined
663
+ ? { callTimeoutMs: resolvedConfig.followerCallTimeoutMs }
664
+ : {}),
665
+ lead: async (context) => {
813
666
  const core = await startWorkerCore({
814
- config,
815
- initConfig: buildInitConfig(config, handle.__headers ?? config.headers),
816
- lease,
667
+ config: resolvedConfig,
668
+ // A promoted tab carries the latest `setHeaders` set.
669
+ initConfig: buildInitConfig(resolvedConfig, handleRef.handle?.__headers ?? resolvedConfig.headers),
670
+ lease: context.lease,
817
671
  dispatchEvent: (event) => {
818
- fireConfigCallbacks(config, event);
819
- handle.__dispatchEvent(event);
672
+ fireConfigCallbacks(resolvedConfig, event);
673
+ context.broadcast(event);
820
674
  },
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
675
  });
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
- }
676
+ return {
677
+ clientId: core.clientId,
678
+ call: (_tabId, method, args) => core.invoke(method, args),
679
+ close: () => core.close(),
680
+ };
681
+ },
682
+ onEvent: (event) => handleRef.handle?.__dispatchEvent(event),
683
+ onStateChange: (state) => handleRef.handle?.__setLeadership(state),
855
684
  });
685
+ const leadership = tabs.state;
856
686
  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,
687
+ role: leadership.state === 'leader' ? 'leader' : 'follower',
688
+ clientId: leadership.state === 'leader'
689
+ ? leadership.clientId
690
+ : leadership.state === 'follower'
691
+ ? leadership.leaderClientId
692
+ : '',
693
+ tabs,
694
+ ...parts,
871
695
  });
872
696
  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
697
  // Init configuration belongs to the one leader worker. A newly opened
888
698
  // follower that explicitly requests security preflight must therefore put
889
699
  // the shared origin replica behind the same barrier before it is returned;
890
700
  // otherwise an already-running leader would silently ignore the request.
891
- if (config.securityPreflight === true) {
701
+ if (leadership.state !== 'leader' &&
702
+ resolvedConfig.securityPreflight === true) {
892
703
  try {
893
704
  await handle.beginSecurityPreflight();
894
705
  }
@@ -37,6 +37,10 @@ export declare const NOT_LEADER_CODE = "client.not_leader";
37
37
  export declare const WORKER_FAILED_CODE = "client.worker_failed";
38
38
  /** A page/worker bundle identity changed and a full host reload is required. */
39
39
  export declare const WORKER_RESTART_REQUIRED_CODE = "client.worker_restart_required";
40
+ /** SPEC §12: local-authority use without `startSyncWorker({ openLocalAuthority })`. */
41
+ export declare const LOCAL_AUTHORITY_UNCONFIGURED_CODE = "client.local_authority_unconfigured";
42
+ /** SPEC §12.3 local-authority state. */
43
+ export type LocalAuthorityState = 'local' | 'attaching' | 'attached';
40
44
  export type WorkerDatabaseInit = {
41
45
  /** Reload-persistent OPFS mode; origin eviction policy stays page-owned. */
42
46
  readonly mode: 'persistent';
@@ -80,6 +84,12 @@ export interface WorkerInitConfig {
80
84
  readonly authorityReads?: readonly import('./authority.js').AuthorityReadDeclaration[];
81
85
  readonly securityPreflight?: boolean;
82
86
  readonly transportEnabled?: boolean;
87
+ /**
88
+ * SPEC §12: sync against a local authority in a sibling file until
89
+ * `attachLocalAuthority` moves its rows to `endpoints.syncUrl`. Requires
90
+ * `startSyncWorker({ openLocalAuthority })`.
91
+ */
92
+ readonly localAuthority?: boolean;
83
93
  readonly clientId?: string;
84
94
  readonly limits?: SyncClientLimits;
85
95
  readonly retainFailedCommits?: boolean;
@@ -163,6 +173,12 @@ export interface WorkerApi extends Omit<ClientSnapshotMethods, 'querySnapshot'>
163
173
  setHeaders(headers: Readonly<Record<string, string>>): void;
164
174
  /** Sever/restore the transport + realtime (offline simulation, demos). */
165
175
  setOffline(offline: boolean): void;
176
+ /** SPEC §12.3 state; `undefined` when init did not enable the local authority. */
177
+ localAuthorityState(): LocalAuthorityState | undefined;
178
+ /** SPEC §12.3: upload the local authority's rows to `endpoints.syncUrl`. */
179
+ attachLocalAuthority(): Promise<void>;
180
+ /** SPEC §12.3: roll back a stopped attach and sync locally again. */
181
+ abandonLocalAuthorityAttach(): Promise<void>;
166
182
  close(): Promise<void>;
167
183
  }
168
184
  export type WorkerMethod = keyof WorkerApi;
@@ -7,3 +7,5 @@ export const NOT_LEADER_CODE = 'client.not_leader';
7
7
  export const WORKER_FAILED_CODE = 'client.worker_failed';
8
8
  /** A page/worker bundle identity changed and a full host reload is required. */
9
9
  export const WORKER_RESTART_REQUIRED_CODE = 'client.worker_restart_required';
10
+ /** SPEC §12: local-authority use without `startSyncWorker({ openLocalAuthority })`. */
11
+ export const LOCAL_AUTHORITY_UNCONFIGURED_CODE = 'client.local_authority_unconfigured';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@syncular/client",
3
- "version": "0.47.0",
3
+ "version": "0.49.1",
4
4
  "description": "Syncular TypeScript client core — offline-first sync over SQLite (WASM/OPFS, Bun, Node)",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Benjamin Kniffler",
@@ -97,10 +97,10 @@
97
97
  },
98
98
  "dependencies": {
99
99
  "@sqlite.org/sqlite-wasm": "^3.53.0-build1",
100
- "@syncular/core": "0.47.0"
100
+ "@syncular/core": "0.49.1"
101
101
  },
102
102
  "devDependencies": {
103
- "@syncular/server": "0.47.0",
103
+ "@syncular/server": "0.49.1",
104
104
  "playwright": "1.63.0",
105
105
  "@electric-sql/pglite": "^0.5.4"
106
106
  }