zen-fs-config 0.9.3 → 0.9.4

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/dist/index.js CHANGED
@@ -705,13 +705,24 @@ var init_cache_wrapper = __esm({
705
705
  // src/index.ts
706
706
  var index_exports = {};
707
707
  __export(index_exports, {
708
+ BackendAlreadyExistsError: () => BackendAlreadyExistsError,
709
+ BackendEndpointConflictError: () => BackendEndpointConflictError,
710
+ BackendIdentityError: () => BackendIdentityError,
708
711
  CONFIG_DIR: () => CONFIG_DIR,
709
712
  CONFLICTS_DIR: () => CONFLICTS_DIR,
713
+ ConfigNotReadyError: () => ConfigNotReadyError,
710
714
  ConfigRepo: () => ConfigRepo,
711
715
  ConflictStore: () => ConflictStore,
716
+ ConnectFailedError: () => ConnectFailedError,
717
+ ConnectV2Error: () => ConnectV2Error,
712
718
  DATA_GROUP_DEFAULT_FEATURES: () => DATA_GROUP_DEFAULT_FEATURES,
719
+ DataGroupBackendError: () => DataGroupBackendError,
720
+ DataGroupCreateError: () => DataGroupCreateError,
721
+ DataGroupNotFoundError: () => DataGroupNotFoundError,
722
+ DataGroupOperationError: () => DataGroupOperationError,
713
723
  FolderStore: () => FolderStore,
714
724
  GROUP_DESCRIPTOR_FILE: () => GROUP_DESCRIPTOR_FILE2,
725
+ InvalidBackendError: () => InvalidBackendError,
715
726
  LEGACY_CONFLICTS_DIR: () => LEGACY_CONFLICTS_DIR,
716
727
  LEGACY_TOMBSTONES_DIR: () => LEGACY_TOMBSTONES_DIR,
717
728
  LOCAL_IDB_BACKEND_ID: () => LOCAL_IDB_BACKEND_ID,
@@ -728,6 +739,8 @@ __export(index_exports, {
728
739
  bindRemoteGroupIdentityDetailed: () => bindRemoteGroupIdentityDetailed,
729
740
  configKeyToFilePath: () => configKeyToFilePath,
730
741
  connect: () => connect,
742
+ connectV2: () => connectV2,
743
+ connectionToAppRepo: () => connectionToAppRepo,
731
744
  createBackend: () => createBackend,
732
745
  createConfigRepo: () => createConfigRepo,
733
746
  createSerializerChain: () => createSerializerChain,
@@ -738,6 +751,7 @@ __export(index_exports, {
738
751
  getAccountFields: () => getAccountFields,
739
752
  getBackendMetadata: () => getBackendMetadata,
740
753
  getExtension: () => getExtension,
754
+ getUiConnection: () => getUiConnection,
741
755
  hasBackend: () => hasBackend,
742
756
  incrementVersion: () => incrementVersion,
743
757
  isBrowserEnv: () => isBrowserEnv,
@@ -2912,6 +2926,11 @@ function describeConflict(result) {
2912
2926
  }
2913
2927
  }
2914
2928
  var log5 = (0, import_localstorage_logger5.createLogger)("zen-fs-config:config-repo");
2929
+ function isMissingDescriptorError(err) {
2930
+ if (isNotFoundError2(err)) return true;
2931
+ const message = String(err?.message ?? err ?? "");
2932
+ return /(^|\W)404(\W|$)|not found|no such file|不存在/i.test(message);
2933
+ }
2915
2934
  var GROUP_DESCRIPTOR_FILE3 = `${META_DIR}/group.json`;
2916
2935
  var GROUP_TYPE_FILE = `${CONFIG_DIR}/group-type`;
2917
2936
  var LEGACY_GROUP_TYPE_FILE = `${META_DIR}/group-type`;
@@ -5402,6 +5421,41 @@ var ConfigRepo = class _ConfigRepo {
5402
5421
  }
5403
5422
  return mergeAccountFields(desc.type, accountBackend.options, desc.options);
5404
5423
  }
5424
+ /**
5425
+ * 读一个数据组后端根上的 `.meta/group.json`(只读,不写、不建同步对)。
5426
+ *
5427
+ * `null` = 空仓库(可以认领);抛错 = 读不到(调用方必须 fail-closed)。
5428
+ * 复用的实例由调用方负责 dispose。
5429
+ */
5430
+ async readRemoteGroupDescriptor(desc, instance) {
5431
+ const own = instance ?? await createBackend({ type: desc.type, options: desc.options });
5432
+ try {
5433
+ return await withTimeout(
5434
+ readGroupDescriptorStrict(own),
5435
+ REPLICA_SETUP_TIMEOUT_MS,
5436
+ `\u6570\u636E\u7EC4\u540E\u7AEF ${desc.id} \u8BFB group.json`
5437
+ );
5438
+ } finally {
5439
+ if (!instance) {
5440
+ try {
5441
+ await own?.dispose?.();
5442
+ } catch {
5443
+ }
5444
+ }
5445
+ }
5446
+ }
5447
+ /**
5448
+ * 同一个远端目录只能归一个组。`.meta/group.json` 里的 `kind`/`id` 就是归属
5449
+ * 记录 —— 它与「本地方知不知道这个组」无关,描述符丢了也照样能判定。
5450
+ */
5451
+ assertRemoteNotOwnedByOthers(remote, backendId, ownerId) {
5452
+ if (!remote) return;
5453
+ if (remote.kind === "data" && remote.id === ownerId) return;
5454
+ const who = remote.kind === "data" ? `\u6570\u636E\u7EC4\u300C${remote.id}\u300D${remote.instanceId ? `\uFF08instanceId=${remote.instanceId}\uFF09` : ""}` : `\u914D\u7F6E\u540C\u6B65\u7EC4\uFF08kind=${remote.kind ?? "\u672A\u77E5"}${remote.id ? `\uFF0Cid=${remote.id}` : ""}\uFF09`;
5455
+ throw new Error(
5456
+ `\u540E\u7AEF\u300C${backendId}\u300D\u6307\u5411\u7684\u8FDC\u7AEF\u76EE\u5F55\u5DF2\u88AB${who}\u5360\u7528\uFF1A\u540C\u4E00\u4E2A\u8FDC\u7AEF\u76EE\u5F55\u4E0D\u80FD\u5F52\u4E24\u4E2A\u7EC4\uFF08\u5426\u5219\u4E24\u6761\u540C\u6B65\u94FE\u4F1A\u4E92\u76F8\u6539\u5199\u8EAB\u4EFD\u3001\u7248\u672C\u4E0E\u5893\u7891\uFF09\u3002\u8BF7\u76F4\u63A5\u52A0\u8F7D\u8BE5\u7EC4\uFF0C\u6216\u4E3A\u5B83\u6539\u7528\u4E0D\u540C\u7684 basePath/repo`
5457
+ );
5458
+ }
5405
5459
  /**
5406
5460
  * Reject two groups pointing at the exact same remote endpoint. Two groups
5407
5461
  * syncing the same files independently would fight over deletions and
@@ -5427,6 +5481,37 @@ var ConfigRepo = class _ConfigRepo {
5427
5481
  }
5428
5482
  }
5429
5483
  }
5484
+ for (const backend of backends) {
5485
+ if (backend.type === localPrimaryType()) continue;
5486
+ let instance;
5487
+ try {
5488
+ instance = await withTimeout(
5489
+ createBackend({ type: backend.type, options: backend.options }),
5490
+ REPLICA_SETUP_TIMEOUT_MS,
5491
+ `\u6570\u636E\u7EC4\u540E\u7AEF ${backend.id} \u521B\u5EFA\u5B9E\u4F8B\uFF08\u5F52\u5C5E\u63A2\u6D4B\uFF09`
5492
+ );
5493
+ } catch (err) {
5494
+ log5.warn(
5495
+ `[ConfigRepo] assertNoSharedRemote: \u65E0\u6CD5\u521B\u5EFA\u540E\u7AEF\u300C${backend.id}\u300D\uFF08${err?.message ?? String(err)}\uFF09\uFF0C\u8DF3\u8FC7\u8FDC\u7AEF\u5F52\u5C5E\u63A2\u6D4B`
5496
+ );
5497
+ continue;
5498
+ }
5499
+ let remote;
5500
+ try {
5501
+ remote = await this.readRemoteGroupDescriptor(backend, instance);
5502
+ } catch (err) {
5503
+ if (isMissingDescriptorError(err)) continue;
5504
+ throw new Error(
5505
+ `\u65E0\u6CD5\u8BFB\u53D6\u540E\u7AEF\u300C${backend.id}\u300D\u7684\u8FDC\u7AEF .meta/group.json\uFF08${err?.message ?? String(err)}\uFF09\uFF1A\u65E0\u6CD5\u5224\u65AD\u8BE5\u8FDC\u7AEF\u76EE\u5F55\u662F\u5426\u5DF2\u88AB\u5176\u5B83\u540C\u6B65\u7EC4\u5360\u7528\uFF0C\u5DF2\u62D2\u7EDD\u521B\u5EFA\u6570\u636E\u7EC4\u300C${ownerId}\u300D\u3002\u8BF7\u68C0\u67E5\u540E\u7AEF\u53C2\u6570\u4E0E\u7F51\u7EDC\u540E\u91CD\u8BD5`
5506
+ );
5507
+ } finally {
5508
+ try {
5509
+ await instance.dispose?.();
5510
+ } catch {
5511
+ }
5512
+ }
5513
+ this.assertRemoteNotOwnedByOthers(remote, backend.id, ownerId);
5514
+ }
5430
5515
  }
5431
5516
  async createAppDataGroup(id, backends, options = {}) {
5432
5517
  this.assertNotDisposed();
@@ -5572,10 +5657,29 @@ var ConfigRepo = class _ConfigRepo {
5572
5657
  const candidate = { ...declared[index], type, options, description: description ?? declared[index].description };
5573
5658
  const mergedOptions = await this.resolveAppDataBackendOptions(candidate);
5574
5659
  const probe = await createBackend({ type, options: mergedOptions });
5660
+ let probeRemote = null;
5661
+ let probeError = null;
5575
5662
  try {
5576
- await probe.dispose?.();
5577
- } catch {
5663
+ if (type !== localPrimaryType()) {
5664
+ probeRemote = await this.readRemoteGroupDescriptor(
5665
+ { id: backendId, type, options: mergedOptions },
5666
+ probe
5667
+ );
5668
+ }
5669
+ } catch (err) {
5670
+ probeError = err;
5671
+ } finally {
5672
+ try {
5673
+ await probe.dispose?.();
5674
+ } catch {
5675
+ }
5676
+ }
5677
+ if (probeError && !isMissingDescriptorError(probeError)) {
5678
+ throw new Error(
5679
+ `\u65E0\u6CD5\u8BFB\u53D6\u540E\u7AEF\u300C${backendId}\u300D\u7684\u8FDC\u7AEF .meta/group.json\uFF08${probeError?.message ?? String(probeError)}\uFF09\uFF1A\u65E0\u6CD5\u5224\u65AD\u8BE5\u8FDC\u7AEF\u76EE\u5F55\u662F\u5426\u5DF2\u88AB\u5176\u5B83\u540C\u6B65\u7EC4\u5360\u7528\uFF0C\u5DF2\u4FDD\u7559\u539F\u53C2\u6570\u3002\u8BF7\u68C0\u67E5\u540E\u7AEF\u53C2\u6570\u4E0E\u7F51\u7EDC\u540E\u91CD\u8BD5`
5680
+ );
5578
5681
  }
5682
+ this.assertRemoteNotOwnedByOthers(probeRemote, backendId, groupId);
5579
5683
  const oldBackends = declared.map((b) => ({ ...b }));
5580
5684
  const nextBackends = declared.map(
5581
5685
  (b, i) => i === index ? { ...candidate, options: mergedOptions } : b
@@ -6576,14 +6680,6 @@ var AppDataGroupImpl = class _AppDataGroupImpl {
6576
6680
  );
6577
6681
  this.dataBackends.set(desc.id, { instance, syncable, pairId: pair.pairId, desc });
6578
6682
  this.backendStates.set(desc.id, { backendId: desc.id, pairId: pair.pairId });
6579
- if (this.features.conflicts) {
6580
- const conflictHandler = (event) => {
6581
- this.archiveConflict(event).catch((err) => {
6582
- log5.warn(`[AppDataGroup:${this.groupId}] conflict archive failed:`, err);
6583
- });
6584
- };
6585
- this.syncEngine.on(pair.pairId, "conflict", conflictHandler);
6586
- }
6587
6683
  this.trackSyncErrors(desc.id, pair.pairId);
6588
6684
  log5.log(`[AppDataGroup:${this.groupId}] backend ${desc.id} (${desc.type}) connected, pair=${pair.pairId}`);
6589
6685
  } catch (err) {
@@ -6641,6 +6737,32 @@ var AppDataGroupImpl = class _AppDataGroupImpl {
6641
6737
  }
6642
6738
  /** Mirror per-pair `sync:error` into `getBackendSyncStates()` (see ConfigRepo). */
6643
6739
  trackSyncErrors(backendId, pairId) {
6740
+ this.syncEngine.on(pairId, "sync:start", (event) => {
6741
+ this.emitSyncEvent({
6742
+ type: "sync:start",
6743
+ groupKind: "data",
6744
+ groupId: this.groupId,
6745
+ backendId,
6746
+ pairId,
6747
+ timestamp: event.timestamp ?? Date.now()
6748
+ });
6749
+ });
6750
+ this.syncEngine.on(pairId, "conflict", (event) => {
6751
+ if (this.features.conflicts) {
6752
+ this.archiveConflict(event).catch((err) => {
6753
+ log5.warn(`[AppDataGroup:${this.groupId}] conflict archive failed:`, err);
6754
+ });
6755
+ }
6756
+ this.emitSyncEvent({
6757
+ type: "conflict",
6758
+ groupKind: "data",
6759
+ groupId: this.groupId,
6760
+ backendId,
6761
+ pairId,
6762
+ timestamp: event.timestamp ?? Date.now(),
6763
+ conflict: event.conflict
6764
+ });
6765
+ });
6644
6766
  this.syncEngine.on(pairId, "sync:error", (event) => {
6645
6767
  const error = event.error;
6646
6768
  const message = error instanceof Error ? error.message : String(error ?? "sync failed");
@@ -6871,13 +6993,6 @@ var AppDataGroupImpl = class _AppDataGroupImpl {
6871
6993
  const desc = { id, type, options, description, createdAt: Date.now() };
6872
6994
  this.dataBackends.set(id, { instance, syncable, pairId: pair.pairId, desc });
6873
6995
  this.backendStates.set(id, { backendId: id, pairId: pair.pairId });
6874
- if (this.features.conflicts) {
6875
- this.syncEngine.on(pair.pairId, "conflict", (event) => {
6876
- this.archiveConflict(event).catch((err) => {
6877
- log5.warn(`[AppDataGroup:${this.groupId}] conflict archive failed:`, err);
6878
- });
6879
- });
6880
- }
6881
6996
  this.trackSyncErrors(id, pair.pairId);
6882
6997
  this._backends = [...this._backends.filter((b) => b.id !== id), desc];
6883
6998
  log5.log(`[AppDataGroup:${this.groupId}] addBackend: ${id} (${type}) connected, pair=${pair.pairId}`);
@@ -7543,17 +7658,549 @@ async function connect(appId, options = {}) {
7543
7658
  };
7544
7659
  }
7545
7660
 
7661
+ // src/api-v2.ts
7662
+ init_backend_registry();
7663
+ var ConnectV2Error = class extends Error {
7664
+ constructor(message, code) {
7665
+ super(message);
7666
+ this.code = code;
7667
+ this.name = new.target.name;
7668
+ }
7669
+ code;
7670
+ };
7671
+ var ConnectFailedError = class extends ConnectV2Error {
7672
+ constructor(message) {
7673
+ super(message, "CONNECT_FAILED");
7674
+ }
7675
+ };
7676
+ var ConfigNotReadyError = class extends ConnectV2Error {
7677
+ constructor(message) {
7678
+ super(message, "CONFIG_NOT_READY");
7679
+ }
7680
+ };
7681
+ var InvalidBackendError = class extends ConnectV2Error {
7682
+ constructor(message) {
7683
+ super(message, "INVALID_BACKEND");
7684
+ }
7685
+ };
7686
+ var BackendAlreadyExistsError = class extends ConnectV2Error {
7687
+ constructor(message) {
7688
+ super(message, "BACKEND_ALREADY_EXISTS");
7689
+ }
7690
+ };
7691
+ var BackendEndpointConflictError = class extends ConnectV2Error {
7692
+ constructor(message) {
7693
+ super(message, "BACKEND_ENDPOINT_CONFLICT");
7694
+ }
7695
+ };
7696
+ var BackendIdentityError = class extends ConnectV2Error {
7697
+ constructor(message) {
7698
+ super(message, "BACKEND_IDENTITY_ERROR");
7699
+ }
7700
+ };
7701
+ var DataGroupCreateError = class extends ConnectV2Error {
7702
+ constructor(message) {
7703
+ super(message, "DATA_GROUP_CREATE_FAILED");
7704
+ }
7705
+ };
7706
+ var DataGroupBackendError = class extends ConnectV2Error {
7707
+ constructor(message) {
7708
+ super(message, "DATA_GROUP_BACKEND_FAILED");
7709
+ }
7710
+ };
7711
+ var DataGroupNotFoundError = class extends ConnectV2Error {
7712
+ constructor(message) {
7713
+ super(message, "DATA_GROUP_NOT_FOUND");
7714
+ }
7715
+ };
7716
+ var DataGroupOperationError = class extends ConnectV2Error {
7717
+ constructor(message) {
7718
+ super(message, "DATA_GROUP_OPERATION_FAILED");
7719
+ }
7720
+ };
7721
+ var connectionToRepo = /* @__PURE__ */ new WeakMap();
7722
+ var repoToConnection = /* @__PURE__ */ new WeakMap();
7723
+ function connectionToAppRepo(connection) {
7724
+ const existing = connectionToRepo.get(connection);
7725
+ if (existing) return existing;
7726
+ const repo = new AppRepoImpl(connection);
7727
+ connectionToRepo.set(connection, repo);
7728
+ repoToConnection.set(repo, connection);
7729
+ return repo;
7730
+ }
7731
+ function getUiConnection(repo) {
7732
+ const connection = repoToConnection.get(repo);
7733
+ if (!connection) {
7734
+ throw new ConnectV2Error(
7735
+ "getUiConnection() received an AppRepo that was not created by connectV2()",
7736
+ "UNKNOWN_APP_REPO"
7737
+ );
7738
+ }
7739
+ return connection;
7740
+ }
7741
+ var AppRepoImpl = class {
7742
+ appId;
7743
+ repo;
7744
+ defaultGroupPromise = null;
7745
+ groups = /* @__PURE__ */ new Map();
7746
+ groupPromises = /* @__PURE__ */ new Map();
7747
+ constructor(connection) {
7748
+ if (!connection.repo) {
7749
+ throw new ConnectV2Error(
7750
+ "connectV2() requires a config-sync connection; no repo was returned",
7751
+ "CONNECT_FAILED"
7752
+ );
7753
+ }
7754
+ this.appId = connection.appId;
7755
+ this.repo = connection.repo;
7756
+ }
7757
+ async getDefaultDataGroup() {
7758
+ if (this.defaultGroupPromise) {
7759
+ try {
7760
+ const current = await this.defaultGroupPromise;
7761
+ if (await this.stillExists(current.id)) return current;
7762
+ this.groups.delete(current.id);
7763
+ this.groupPromises.delete(current.id);
7764
+ } catch {
7765
+ }
7766
+ this.defaultGroupPromise = null;
7767
+ }
7768
+ this.defaultGroupPromise = this.resolveDefaultGroup();
7769
+ try {
7770
+ return await this.defaultGroupPromise;
7771
+ } catch (err) {
7772
+ this.defaultGroupPromise = null;
7773
+ throw err;
7774
+ }
7775
+ }
7776
+ async getDataGroup(id) {
7777
+ const groupId = id?.trim();
7778
+ if (!groupId) {
7779
+ throw new DataGroupNotFoundError("Data group id is required");
7780
+ }
7781
+ const groups = await this.repo.listAppDataGroups();
7782
+ const descriptor = groups.find((group) => group.id === groupId);
7783
+ if (!descriptor) {
7784
+ throw new DataGroupNotFoundError(`Data group "${groupId}" does not exist`);
7785
+ }
7786
+ return this.loadGroup(descriptor);
7787
+ }
7788
+ async listDataGroups() {
7789
+ const groups = await this.repo.listAppDataGroups();
7790
+ return groups.map((group) => ({
7791
+ id: group.id,
7792
+ name: group.name?.trim() || group.id,
7793
+ hasRemote: (group.backends ?? []).length > 0
7794
+ }));
7795
+ }
7796
+ async stillExists(id) {
7797
+ try {
7798
+ const groups = await this.repo.listAppDataGroups();
7799
+ return groups.some((group) => group.id === id);
7800
+ } catch {
7801
+ return true;
7802
+ }
7803
+ }
7804
+ async resolveDefaultGroup() {
7805
+ let groups = await this.repo.listAppDataGroups();
7806
+ if (groups.length > 0) {
7807
+ return this.loadGroup(selectDefaultDescriptor(groups));
7808
+ }
7809
+ await this.waitForConfigPull();
7810
+ groups = await this.repo.listAppDataGroups();
7811
+ if (groups.length > 0) {
7812
+ return this.loadGroup(selectDefaultDescriptor(groups));
7813
+ }
7814
+ return this.createDefaultGroup();
7815
+ }
7816
+ async waitForConfigPull() {
7817
+ let remoteCount = 0;
7818
+ try {
7819
+ const meta = await this.repo.getBackends();
7820
+ remoteCount = (meta?.backends ?? []).filter(
7821
+ (backend) => backend.id !== LOCAL_IDB_BACKEND_ID
7822
+ ).length;
7823
+ } catch {
7824
+ throw new ConfigNotReadyError(
7825
+ "Cannot read config-sync backends; refusing to create a local default data group"
7826
+ );
7827
+ }
7828
+ if (remoteCount === 0) return;
7829
+ let summary;
7830
+ try {
7831
+ summary = await this.repo.whenReplicasReady?.();
7832
+ } catch (err) {
7833
+ throw new ConfigNotReadyError(
7834
+ `Config replicas failed before initial pull: ${errorMessage(err)}`
7835
+ );
7836
+ }
7837
+ if (summary && (summary.failed.length > 0 || summary.skipped.length > 0)) {
7838
+ const details = [
7839
+ ...summary.failed.map((item) => `${item.backendId}: ${item.error}`),
7840
+ ...summary.skipped.map((item) => `${item.backendId}: ${item.reason}`)
7841
+ ].join("; ");
7842
+ throw new ConfigNotReadyError(
7843
+ `Config group is not ready; refusing to create a local default data group (${details})`
7844
+ );
7845
+ }
7846
+ try {
7847
+ await this.repo.flush();
7848
+ } catch (err) {
7849
+ throw new ConfigNotReadyError(
7850
+ `Initial config pull did not complete: ${errorMessage(err)}`
7851
+ );
7852
+ }
7853
+ }
7854
+ async loadGroup(descriptor) {
7855
+ const cached = this.groups.get(descriptor.id);
7856
+ if (cached) return cached;
7857
+ const pending = this.groupPromises.get(descriptor.id);
7858
+ if (pending) return pending;
7859
+ const promise = (async () => {
7860
+ try {
7861
+ const live = await this.repo.getAppDataGroup(descriptor.id);
7862
+ const group = new DataGroupImpl(this.repo, live, descriptor.id);
7863
+ this.groups.set(descriptor.id, group);
7864
+ return group;
7865
+ } catch (err) {
7866
+ throw new DataGroupCreateError(
7867
+ `Failed to load data group "${descriptor.id}": ${errorMessage(err)}`
7868
+ );
7869
+ }
7870
+ })();
7871
+ this.groupPromises.set(descriptor.id, promise);
7872
+ try {
7873
+ return await promise;
7874
+ } finally {
7875
+ this.groupPromises.delete(descriptor.id);
7876
+ }
7877
+ }
7878
+ async createDefaultGroup() {
7879
+ try {
7880
+ const live = await this.repo.createAppDataGroup("default", []);
7881
+ const group = new DataGroupImpl(this.repo, live, "default");
7882
+ this.groups.set("default", group);
7883
+ return group;
7884
+ } catch (err) {
7885
+ let groups = [];
7886
+ try {
7887
+ groups = await this.repo.listAppDataGroups();
7888
+ } catch {
7889
+ }
7890
+ if (groups.length > 0) {
7891
+ return this.loadGroup(selectDefaultDescriptor(groups));
7892
+ }
7893
+ throw new DataGroupCreateError(
7894
+ `Failed to create local default data group: ${errorMessage(err)}`
7895
+ );
7896
+ }
7897
+ }
7898
+ };
7899
+ function selectDefaultDescriptor(groups) {
7900
+ return groups.find((group) => group.id === "default") ?? groups[0];
7901
+ }
7902
+ function errorMessage(err) {
7903
+ return err instanceof Error ? err.message : String(err);
7904
+ }
7905
+ var DataGroupImpl = class {
7906
+ id;
7907
+ fs;
7908
+ repo;
7909
+ group;
7910
+ constructor(repo, group, id) {
7911
+ this.repo = repo;
7912
+ this.group = group;
7913
+ this.id = id;
7914
+ this.fs = group.fs;
7915
+ }
7916
+ async addBackend(input) {
7917
+ const type = input.type?.trim();
7918
+ if (!type) throw new InvalidBackendError("Backend type is required");
7919
+ if (!hasBackend(type)) {
7920
+ throw new InvalidBackendError(`Backend type "${type}" is not registered`);
7921
+ }
7922
+ if (!input.options || typeof input.options !== "object") {
7923
+ throw new InvalidBackendError("Backend options must be an object");
7924
+ }
7925
+ if (input.id) {
7926
+ if (input.id === LOCAL_IDB_BACKEND_ID) {
7927
+ throw new InvalidBackendError(
7928
+ `"${LOCAL_IDB_BACKEND_ID}" is the implicit local primary and cannot be added`
7929
+ );
7930
+ }
7931
+ assertValidBackendId(input.id);
7932
+ }
7933
+ const declared = this.listDeclaredBackends();
7934
+ const byId = input.id ? declared.find((backend) => backend.id === input.id) : void 0;
7935
+ if (byId) {
7936
+ return { backendId: byId.id, addedBackend: false };
7937
+ }
7938
+ const endpointKey = backendEndpointKey(type, input.options);
7939
+ const sameEndpoint = declared.find(
7940
+ (backend) => backendEndpointKey(backend.type, backend.options) === endpointKey
7941
+ );
7942
+ if (sameEndpoint) {
7943
+ return { backendId: sameEndpoint.id, addedBackend: false };
7944
+ }
7945
+ await this.assertEndpointUnusedElsewhere(type, input.options);
7946
+ const id = input.id ?? generateBackendId(type, declared);
7947
+ try {
7948
+ await this.group.addBackend(id, type, input.options, input.description);
7949
+ } catch (err) {
7950
+ throw new DataGroupBackendError(
7951
+ `Failed to add backend "${id}" to data group "${this.id}": ${errorMessage(err)}`
7952
+ );
7953
+ }
7954
+ return { backendId: id, addedBackend: true };
7955
+ }
7956
+ async flush() {
7957
+ try {
7958
+ const results = await this.group.flush();
7959
+ return (results ?? []).map((result) => ({
7960
+ pairId: result.pairId,
7961
+ ...normalizeSyncResult(result)
7962
+ }));
7963
+ } catch (err) {
7964
+ throw new DataGroupOperationError(
7965
+ `Failed to flush data group "${this.id}": ${errorMessage(err)}`
7966
+ );
7967
+ }
7968
+ }
7969
+ async deleteFile(path) {
7970
+ try {
7971
+ await this.group.deleteFile(path);
7972
+ } catch (err) {
7973
+ throw new DataGroupOperationError(
7974
+ `Failed to delete "${path}" from data group "${this.id}": ${errorMessage(err)}`
7975
+ );
7976
+ }
7977
+ }
7978
+ onSyncEvent(handler) {
7979
+ const subscribe = this.group.onSyncEvent;
7980
+ if (typeof subscribe !== "function") {
7981
+ return () => {
7982
+ };
7983
+ }
7984
+ return subscribe.call(this.group, (event) => {
7985
+ const mapped = mapSyncEvent(event, this.id);
7986
+ if (mapped) handler(mapped);
7987
+ });
7988
+ }
7989
+ listDeclaredBackends() {
7990
+ const list = this.group.listDeclaredBackends;
7991
+ if (typeof list === "function") {
7992
+ return list.call(this.group);
7993
+ }
7994
+ return [];
7995
+ }
7996
+ async assertEndpointUnusedElsewhere(type, options) {
7997
+ const key = backendEndpointKey(type, options);
7998
+ const configMeta = await this.repo.getBackends().catch(() => null);
7999
+ for (const backend of configMeta?.backends ?? []) {
8000
+ if (backend.id === LOCAL_IDB_BACKEND_ID) continue;
8001
+ if (backendEndpointKey(backend.type, backend.options) === key) {
8002
+ throw new BackendEndpointConflictError(
8003
+ `Backend endpoint is already used by config group backend "${backend.id}"`
8004
+ );
8005
+ }
8006
+ }
8007
+ const groups = await this.repo.listAppDataGroups().catch(() => []);
8008
+ for (const descriptor of groups) {
8009
+ if (descriptor.id === this.id) continue;
8010
+ for (const backend of descriptor.backends ?? []) {
8011
+ if (backendEndpointKey(backend.type, backend.options) === key) {
8012
+ throw new BackendEndpointConflictError(
8013
+ `Backend endpoint is already used by data group "${descriptor.id}" backend "${backend.id}"`
8014
+ );
8015
+ }
8016
+ }
8017
+ }
8018
+ }
8019
+ };
8020
+ function mapSyncEvent(event, groupId) {
8021
+ const base = {
8022
+ groupId,
8023
+ backendId: event.backendId,
8024
+ pairId: event.pairId,
8025
+ timestamp: event.timestamp
8026
+ };
8027
+ switch (event.type) {
8028
+ case "sync:start":
8029
+ return { type: "sync:start", ...base };
8030
+ case "sync:progress":
8031
+ if (!event.progress) return null;
8032
+ return { type: "sync:progress", ...base, progress: event.progress };
8033
+ case "sync:end":
8034
+ return {
8035
+ type: "sync:end",
8036
+ ...base,
8037
+ result: normalizeSyncResult(event.result)
8038
+ };
8039
+ case "sync:error":
8040
+ return {
8041
+ type: "sync:error",
8042
+ ...base,
8043
+ error: event.error ?? "sync failed"
8044
+ };
8045
+ case "conflict":
8046
+ return { type: "conflict", ...base, conflict: event.conflict };
8047
+ default:
8048
+ return null;
8049
+ }
8050
+ }
8051
+ function normalizeSyncResult(result) {
8052
+ return {
8053
+ filesCreated: result?.filesCreated ?? 0,
8054
+ filesUpdated: result?.filesUpdated ?? 0,
8055
+ filesDeleted: result?.filesDeleted ?? 0,
8056
+ filesSkipped: result?.filesSkipped ?? 0,
8057
+ conflicts: result?.conflicts ?? [],
8058
+ errors: result?.errors ?? [],
8059
+ durationMs: result?.durationMs ?? 0
8060
+ };
8061
+ }
8062
+ function backendEndpointKey(type, options) {
8063
+ const identityFields = getBackendMetadata(type)?.identityFields;
8064
+ const picked = {};
8065
+ if (identityFields && identityFields.length > 0) {
8066
+ for (const field of identityFields) picked[field] = options[field];
8067
+ } else {
8068
+ Object.assign(picked, options);
8069
+ }
8070
+ return `${type}:${stableStringify(picked)}`;
8071
+ }
8072
+ function stableStringify(value, seen = /* @__PURE__ */ new WeakSet()) {
8073
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
8074
+ if (seen.has(value)) return '"[circular]"';
8075
+ seen.add(value);
8076
+ if (Array.isArray(value)) {
8077
+ return `[${value.map((item) => stableStringify(item, seen)).join(",")}]`;
8078
+ }
8079
+ const entries = Object.entries(value).filter(([, item]) => item !== void 0).sort(([a], [b]) => a.localeCompare(b));
8080
+ return `{${entries.map(([key, item]) => `${JSON.stringify(key)}:${stableStringify(item, seen)}`).join(",")}}`;
8081
+ }
8082
+ function generateBackendId(type, existing) {
8083
+ const prefix = type.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "backend";
8084
+ let id = `${prefix}-${Date.now().toString(36)}`;
8085
+ let suffix = 1;
8086
+ while (existing.some((backend) => backend.id === id)) {
8087
+ id = `${prefix}-${Date.now().toString(36)}-${suffix++}`;
8088
+ }
8089
+ return id;
8090
+ }
8091
+ var connectCache = /* @__PURE__ */ new Map();
8092
+ async function connectV2(appId, options = {}) {
8093
+ const normalized = normalizeOptions(options);
8094
+ const key = `${appId}\0${stableStringify(normalized)}`;
8095
+ const cached = connectCache.get(key);
8096
+ if (cached) return cached;
8097
+ const pending = createConnection(appId, normalized).catch((err) => {
8098
+ connectCache.delete(key);
8099
+ throw err instanceof ConnectV2Error ? err : new ConnectFailedError(errorMessage(err));
8100
+ });
8101
+ connectCache.set(key, pending);
8102
+ return pending;
8103
+ }
8104
+ async function createConnection(appId, options) {
8105
+ const { configBackends, connectOptions } = options;
8106
+ let result;
8107
+ try {
8108
+ result = await connect(appId, connectOptions);
8109
+ } catch (err) {
8110
+ throw new ConnectFailedError(
8111
+ `connectV2("${appId}") failed: ${errorMessage(err)}`
8112
+ );
8113
+ }
8114
+ if (!result.repo) {
8115
+ throw new ConnectFailedError(
8116
+ `connectV2("${appId}") did not return a config-sync repo`
8117
+ );
8118
+ }
8119
+ await addExtraConfigBackends(result.repo, configBackends);
8120
+ return connectionToAppRepo({ ...result, appId });
8121
+ }
8122
+ async function addExtraConfigBackends(repo, backends) {
8123
+ if (backends.length === 0) return;
8124
+ let existing = [];
8125
+ try {
8126
+ const meta = await repo.getBackends();
8127
+ existing = meta?.backends ?? [];
8128
+ } catch {
8129
+ }
8130
+ for (const backend of backends) {
8131
+ const id = backend.id ?? generateBackendId(backend.type, existing);
8132
+ const byId = existing.find((item) => item.id === id);
8133
+ if (byId) continue;
8134
+ const key = backendEndpointKey(backend.type, backend.options);
8135
+ if (existing.some(
8136
+ (item) => backendEndpointKey(item.type, item.options) === key
8137
+ )) {
8138
+ continue;
8139
+ }
8140
+ try {
8141
+ await repo.addBackend(id, backend.type, backend.options, backend.description);
8142
+ existing = [
8143
+ ...existing,
8144
+ {
8145
+ id,
8146
+ type: backend.type,
8147
+ options: backend.options,
8148
+ description: backend.description
8149
+ }
8150
+ ];
8151
+ } catch (err) {
8152
+ throw new DataGroupBackendError(
8153
+ `Failed to add config backend "${id}": ${errorMessage(err)}`
8154
+ );
8155
+ }
8156
+ }
8157
+ }
8158
+ function normalizeOptions(options) {
8159
+ const {
8160
+ configBackends = [],
8161
+ backendInfo,
8162
+ dataBackends: _ignored,
8163
+ ...rest
8164
+ } = options;
8165
+ void _ignored;
8166
+ const extra = configBackends.map((backend) => ({ ...backend }));
8167
+ let primary = backendInfo;
8168
+ if (!primary && extra.length > 0) {
8169
+ const first = extra.shift();
8170
+ primary = { type: first.type, options: first.options };
8171
+ if (!rest.primaryBackendId && first.id) rest.primaryBackendId = first.id;
8172
+ }
8173
+ return {
8174
+ connectOptions: {
8175
+ ...rest,
8176
+ ...primary ? { backendInfo: primary } : {}
8177
+ },
8178
+ configBackends: extra
8179
+ };
8180
+ }
8181
+
7546
8182
  // src/index.ts
7547
8183
  init_backend_registry();
7548
8184
  // Annotate the CommonJS export names for ESM import in node:
7549
8185
  0 && (module.exports = {
8186
+ BackendAlreadyExistsError,
8187
+ BackendEndpointConflictError,
8188
+ BackendIdentityError,
7550
8189
  CONFIG_DIR,
7551
8190
  CONFLICTS_DIR,
8191
+ ConfigNotReadyError,
7552
8192
  ConfigRepo,
7553
8193
  ConflictStore,
8194
+ ConnectFailedError,
8195
+ ConnectV2Error,
7554
8196
  DATA_GROUP_DEFAULT_FEATURES,
8197
+ DataGroupBackendError,
8198
+ DataGroupCreateError,
8199
+ DataGroupNotFoundError,
8200
+ DataGroupOperationError,
7555
8201
  FolderStore,
7556
8202
  GROUP_DESCRIPTOR_FILE,
8203
+ InvalidBackendError,
7557
8204
  LEGACY_CONFLICTS_DIR,
7558
8205
  LEGACY_TOMBSTONES_DIR,
7559
8206
  LOCAL_IDB_BACKEND_ID,
@@ -7570,6 +8217,8 @@ init_backend_registry();
7570
8217
  bindRemoteGroupIdentityDetailed,
7571
8218
  configKeyToFilePath,
7572
8219
  connect,
8220
+ connectV2,
8221
+ connectionToAppRepo,
7573
8222
  createBackend,
7574
8223
  createConfigRepo,
7575
8224
  createSerializerChain,
@@ -7580,6 +8229,7 @@ init_backend_registry();
7580
8229
  getAccountFields,
7581
8230
  getBackendMetadata,
7582
8231
  getExtension,
8232
+ getUiConnection,
7583
8233
  hasBackend,
7584
8234
  incrementVersion,
7585
8235
  isBrowserEnv,