zen-fs-config 0.7.13 → 0.7.15

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
@@ -719,6 +719,8 @@ __export(index_exports, {
719
719
  TombstoneStore: () => TombstoneStore,
720
720
  VERSIONS_DIR: () => VERSIONS_DIR,
721
721
  VersionStore: () => VersionStore,
722
+ bindRemoteGroupIdentity: () => bindRemoteGroupIdentity,
723
+ bindRemoteGroupIdentityDetailed: () => bindRemoteGroupIdentityDetailed,
722
724
  configKeyToFilePath: () => configKeyToFilePath,
723
725
  connect: () => connect,
724
726
  createBackend: () => createBackend,
@@ -726,6 +728,7 @@ __export(index_exports, {
726
728
  createSerializerChain: () => createSerializerChain,
727
729
  dataGroupLocalStoreName: () => dataGroupLocalStoreName,
728
730
  deleteDataGroupLocalStore: () => deleteDataGroupLocalStore,
731
+ deleteIndexedDbStore: () => deleteIndexedDbStore,
729
732
  encodeMetaPath: () => encodeMetaPath,
730
733
  getAccountFields: () => getAccountFields,
731
734
  getBackendMetadata: () => getBackendMetadata,
@@ -736,20 +739,27 @@ __export(index_exports, {
736
739
  isKeepFile: () => isKeepFile,
737
740
  isLocalStorageUnavailableError: () => isLocalStorageUnavailableError,
738
741
  isMtimeSidecar: () => isMtimeSidecar,
742
+ isValidGroupInstanceId: () => isValidGroupInstanceId,
739
743
  legacyVersionPathFor: () => legacyVersionPathFor,
740
744
  listBackendMetadata: () => listBackendMetadata,
741
745
  listBackends: () => listBackends,
742
746
  localPrimaryType: () => localPrimaryType,
747
+ localSyncStoreNames: () => localSyncStoreNames,
743
748
  mergeAccountFields: () => mergeAccountFields,
744
749
  migrateVersionSidecars: () => migrateVersionSidecars,
750
+ newGroupInstanceId: () => newGroupInstanceId,
745
751
  purgeKeepFiles: () => purgeKeepFiles,
752
+ purgeLocalSyncConfig: () => purgeLocalSyncConfig,
746
753
  purgeMtimeSidecars: () => purgeMtimeSidecars,
747
754
  readGroupDescriptor: () => readGroupDescriptor,
748
755
  readVersion: () => readVersion,
749
756
  registerBackend: () => registerBackend,
750
757
  registerFolderBackend: () => registerFolderBackend,
751
758
  resolveLocalPrimary: () => resolveLocalPrimary,
759
+ resolveRemoteIdentity: () => resolveRemoteIdentity,
752
760
  sha256: () => sha256,
761
+ shortInstanceId: () => shortInstanceId,
762
+ summarizeIdentity: () => summarizeIdentity,
753
763
  unregisterBackend: () => unregisterBackend,
754
764
  verifyOrRepairVersion: () => verifyOrRepairVersion,
755
765
  versionPathFor: () => versionPathFor,
@@ -2033,6 +2043,28 @@ async function readGroupDescriptor(fs) {
2033
2043
  const { updatedAt: _ignored, ...rest } = parsed;
2034
2044
  return rest;
2035
2045
  }
2046
+ function isNotFoundError(err) {
2047
+ const e = err;
2048
+ if (!e) return false;
2049
+ if (e.code === "ENOENT" || e.code === "ENOTDIR" || e.name === "NotFoundError" || e.errno === -2) return true;
2050
+ return /no such file|not found|不存在/i.test(String(e.message ?? ""));
2051
+ }
2052
+ async function readGroupDescriptorStrict(fs) {
2053
+ let raw;
2054
+ try {
2055
+ raw = new TextDecoder().decode(toBytes(await fs.readFile(GROUP_DESCRIPTOR_FILE2)));
2056
+ } catch (err) {
2057
+ if (isNotFoundError(err)) return null;
2058
+ throw err;
2059
+ }
2060
+ try {
2061
+ const parsed = JSON.parse(raw);
2062
+ const { updatedAt: _ignored, ...rest } = parsed;
2063
+ return rest;
2064
+ } catch {
2065
+ return null;
2066
+ }
2067
+ }
2036
2068
  async function writeGroupDescriptor(fs, descriptor) {
2037
2069
  const bytes = serializeGroupDescriptor(descriptor);
2038
2070
  if (await readText(fs, GROUP_DESCRIPTOR_FILE2) === bytes) return;
@@ -2450,20 +2482,62 @@ function isValidGroupInstanceId(value) {
2450
2482
  return typeof value === "string" && INSTANCE_ID_RE.test(value.trim());
2451
2483
  }
2452
2484
  async function bindRemoteGroupIdentity(remoteFS, identity) {
2485
+ const result = await bindRemoteGroupIdentityDetailed(remoteFS, identity);
2486
+ return result.state;
2487
+ }
2488
+ function summarizeIdentity(identity) {
2489
+ if (!identity) return "\uFF08\u65E0\u63CF\u8FF0\u7B26\uFF09";
2490
+ const parts = [
2491
+ `kind=${identity.kind ?? "?"}`,
2492
+ `id=${identity.id ?? "?"}`,
2493
+ `\u5B9E\u4F8B ID=${identity.instanceId ? shortInstanceId(identity.instanceId) : "\uFF08\u65E0\uFF09"}`
2494
+ ];
2495
+ return parts.join(" \xB7 ");
2496
+ }
2497
+ function shortInstanceId(instanceId) {
2498
+ return `${instanceId.slice(0, 8)}\u2026`;
2499
+ }
2500
+ function snapshotOf(descriptor) {
2501
+ if (!descriptor) return null;
2502
+ return {
2503
+ kind: descriptor.kind,
2504
+ id: descriptor.id,
2505
+ instanceId: pickInstanceId(descriptor),
2506
+ ...descriptor.name ? { name: descriptor.name } : {}
2507
+ };
2508
+ }
2509
+ async function bindRemoteGroupIdentityDetailed(remoteFS, identity) {
2453
2510
  let remote = null;
2454
2511
  try {
2455
- remote = await readGroupDescriptor(remoteFS);
2512
+ remote = await readGroupDescriptorStrict(remoteFS);
2456
2513
  } catch (err) {
2457
2514
  log4.warn(`[GroupIdentity] failed to read remote ${identity.kind}/"${identity.id}" group.json:`, err);
2458
- throw err;
2515
+ return {
2516
+ state: "conflict",
2517
+ remote: null,
2518
+ local: identity,
2519
+ conflict: "unreadable",
2520
+ unreadable: true,
2521
+ error: err?.message ?? String(err)
2522
+ };
2523
+ }
2524
+ const snapshot = snapshotOf(remote);
2525
+ const current = snapshot?.instanceId;
2526
+ if (snapshot?.kind && snapshot.kind !== identity.kind) {
2527
+ log4.warn(
2528
+ `[GroupIdentity] remote kind "${snapshot.kind}" \u2260 this group kind "${identity.kind}" \u2014 sync pair NOT created`
2529
+ );
2530
+ return { state: "conflict", remote: snapshot, local: identity, conflict: "kind-mismatch" };
2459
2531
  }
2460
- const current = remote?.instanceId;
2461
2532
  if (isValidGroupInstanceId(current)) {
2462
- if (current === identity.instanceId) return "match";
2533
+ if (current === identity.instanceId) {
2534
+ return { state: "match", remote: snapshot, local: identity };
2535
+ }
2536
+ const reason = snapshot?.id && snapshot.id !== identity.id ? "id-mismatch" : "instance-mismatch";
2463
2537
  log4.warn(
2464
- `[GroupIdentity] backend belongs to another sync group (remote instanceId=${current}, this group=${identity.instanceId}, kind ${remote?.kind ?? "?"}/"${remote?.id ?? "?"}") \u2014 sync pair NOT created`
2538
+ `[GroupIdentity] backend belongs to another sync group (remote ${summarizeIdentity(snapshot)}, this group ${summarizeIdentity(identity)}) \u2014 sync pair NOT created`
2465
2539
  );
2466
- return "conflict";
2540
+ return { state: "conflict", remote: snapshot, local: identity, conflict: reason };
2467
2541
  }
2468
2542
  const next = {
2469
2543
  schemaVersion: 2,
@@ -2473,22 +2547,79 @@ async function bindRemoteGroupIdentity(remoteFS, identity) {
2473
2547
  ...remote?.name ?? identity.name ? { name: remote?.name ?? identity.name } : {},
2474
2548
  ...remote?.features ?? identity.features ? { features: remote?.features ?? identity.features } : {}
2475
2549
  };
2476
- if (next.kind !== identity.kind) {
2477
- log4.warn(
2478
- `[GroupIdentity] remote kind "${next.kind}" \u2260 this group kind "${identity.kind}" \u2014 sync pair NOT created`
2479
- );
2480
- return "conflict";
2481
- }
2482
2550
  try {
2483
2551
  await writeGroupDescriptor(remoteFS, next);
2484
2552
  } catch (err) {
2485
2553
  log4.warn(`[GroupIdentity] failed to claim remote root for "${identity.id}":`, err);
2486
- return "conflict";
2554
+ return {
2555
+ state: "conflict",
2556
+ remote: snapshot,
2557
+ local: identity,
2558
+ conflict: "claim-failed",
2559
+ error: err?.message ?? String(err)
2560
+ };
2487
2561
  }
2488
2562
  log4.log(
2489
2563
  `[GroupIdentity] claimed remote root for ${identity.kind}/"${identity.id}" (instanceId=${identity.instanceId})`
2490
2564
  );
2491
- return "claimed";
2565
+ return { state: "claimed", remote: snapshot, local: identity };
2566
+ }
2567
+ async function resolveRemoteIdentity(remoteFS, identity, mode) {
2568
+ let remote = null;
2569
+ try {
2570
+ remote = await readGroupDescriptorStrict(remoteFS);
2571
+ } catch (err) {
2572
+ return { mode, ok: false, reason: `\u8FDC\u7AEF\u63CF\u8FF0\u7B26\u8BFB\u4E0D\u5230\uFF1A${err?.message ?? String(err)}` };
2573
+ }
2574
+ const snapshot = snapshotOf(remote);
2575
+ if (mode === "adopt-remote-instance") {
2576
+ const remoteInstanceId = snapshot?.instanceId;
2577
+ if (!isValidGroupInstanceId(remoteInstanceId)) {
2578
+ return { mode, ok: false, reason: "\u8FDC\u7AEF\u6CA1\u6709\u5B9E\u4F8B\u8EAB\u4EFD\uFF0C\u65E0\u9700\u5BF9\u9F50", remote: snapshot };
2579
+ }
2580
+ if (snapshot?.kind !== identity.kind) {
2581
+ return {
2582
+ mode,
2583
+ ok: false,
2584
+ reason: `\u8FDC\u7AEF kind=${snapshot?.kind ?? "?"}\uFF0C\u672C\u7EC4 kind=${identity.kind}\uFF1A\u7C7B\u578B\u4E0D\u540C\u4E0D\u80FD\u53EA\u5BF9\u9F50\u5B9E\u4F8B\u8EAB\u4EFD`,
2585
+ remote: snapshot
2586
+ };
2587
+ }
2588
+ if (snapshot?.id !== identity.id) {
2589
+ return {
2590
+ mode,
2591
+ ok: false,
2592
+ reason: `\u8FDC\u7AEF id=${snapshot?.id ?? "?"}\uFF0C\u672C\u7EC4 id=${identity.id}\uFF1A\u7EC4 id \u4E0D\u540C\u8BF4\u660E\u8FDC\u7AEF\u6839\u88AB\u53E6\u4E00\u4E2A\u903B\u8F91\u7EC4\u5360\u7528\uFF0C\u4E0D\u80FD\u5BF9\u9F50`,
2593
+ remote: snapshot
2594
+ };
2595
+ }
2596
+ return { mode, ok: true, instanceId: remoteInstanceId, remote: snapshot };
2597
+ }
2598
+ if (snapshot && snapshot.kind !== identity.kind) {
2599
+ return {
2600
+ mode,
2601
+ ok: false,
2602
+ reason: `\u8FDC\u7AEF kind=${snapshot.kind}\uFF0C\u672C\u7EC4 kind=${identity.kind}\uFF1A\u7C7B\u578B\u4E0D\u540C\u4E0D\u5141\u8BB8\u6539\u5199\u8FDC\u7AEF`,
2603
+ remote: snapshot
2604
+ };
2605
+ }
2606
+ const next = {
2607
+ schemaVersion: 2,
2608
+ kind: identity.kind,
2609
+ id: identity.id,
2610
+ instanceId: identity.instanceId,
2611
+ ...identity.name ? { name: identity.name } : {},
2612
+ ...identity.features ? { features: identity.features } : {}
2613
+ };
2614
+ try {
2615
+ await writeGroupDescriptor(remoteFS, next);
2616
+ } catch (err) {
2617
+ return { mode, ok: false, reason: `\u5199\u8FDC\u7AEF\u5931\u8D25\uFF1A${err?.message ?? String(err)}`, remote: snapshot };
2618
+ }
2619
+ log4.log(
2620
+ `[GroupIdentity] rewrote remote identity to ${identity.kind}/"${identity.id}" (instanceId=${identity.instanceId})`
2621
+ );
2622
+ return { mode, ok: true, remote: snapshot };
2492
2623
  }
2493
2624
  function pickInstanceId(descriptor) {
2494
2625
  const value = descriptor?.instanceId;
@@ -2739,6 +2870,24 @@ async function migrateVersionSidecars(fs, options = {}) {
2739
2870
  }
2740
2871
 
2741
2872
  // src/config-repo.ts
2873
+ function describeConflict(result) {
2874
+ const remote = summarizeIdentity(result.remote);
2875
+ const local = summarizeIdentity(result.local);
2876
+ switch (result.conflict) {
2877
+ case "kind-mismatch":
2878
+ return `\u7EC4\u7C7B\u578B\u4E0D\u4E00\u81F4\uFF1A\u8FDC\u7AEF ${remote}\uFF0C\u672C\u7EC4 ${local}\u3002\u8BE5\u8FDC\u7AEF\u6839\u5DF2\u88AB\u53E6\u4E00\u7C7B\u7EC4\u5360\u7528\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u540E\u7AEF`;
2879
+ case "id-mismatch":
2880
+ return `\u7EC4 id \u4E0D\u4E00\u81F4\uFF1A\u8FDC\u7AEF ${remote}\uFF0C\u672C\u7EC4 ${local}\u3002\u540C\u4E00\u8FDC\u7AEF\u6839\u88AB\u53E6\u4E00\u4E2A\u903B\u8F91\u7EC4\u5360\u7528\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u540E\u7AEF`;
2881
+ case "instance-mismatch":
2882
+ return `\u5B9E\u4F8B\u8EAB\u4EFD\u4E0D\u4E00\u81F4\uFF1A\u8FDC\u7AEF ${remote}\uFF0C\u672C\u7EC4 ${local}\u3002\u5DF2\u8DF3\u8FC7\u8BE5\u540E\u7AEF\uFF08\u786E\u8BA4\u540E\u53EF\u5728\u754C\u9762\u4E0A\u5BF9\u9F50\uFF09`;
2883
+ case "unreadable":
2884
+ return `\u8FDC\u7AEF group.json \u8BFB\u4E0D\u5230\uFF08${result.error ?? "\u672A\u77E5\u9519\u8BEF"}\uFF09\uFF0C\u65E0\u6CD5\u5224\u65AD\u5F52\u5C5E\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u540E\u7AEF`;
2885
+ case "claim-failed":
2886
+ return `\u8BA4\u9886\u8FDC\u7AEF\u6839\u5931\u8D25\uFF08${result.error ?? "\u672A\u77E5\u9519\u8BEF"}\uFF09\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u540E\u7AEF`;
2887
+ default:
2888
+ return `\u8FDC\u7AEF\u6839\u5F52\u5C5E\u51B2\u7A81\uFF1A\u8FDC\u7AEF ${remote}\uFF0C\u672C\u7EC4 ${local}`;
2889
+ }
2890
+ }
2742
2891
  var log5 = (0, import_localstorage_logger5.createLogger)("zen-fs-config:config-repo");
2743
2892
  var GROUP_DESCRIPTOR_FILE3 = `${META_DIR}/group.json`;
2744
2893
  var GROUP_TYPE_FILE = `${CONFIG_DIR}/group-type`;
@@ -2778,7 +2927,7 @@ async function isDirectoryAny(surfaces, path) {
2778
2927
  }
2779
2928
  return false;
2780
2929
  }
2781
- function isNotFoundError(err) {
2930
+ function isNotFoundError2(err) {
2782
2931
  const code = err?.code;
2783
2932
  if (code === "ENOENT" || code === "ENOTDIR") return true;
2784
2933
  const message = String(err?.message ?? err);
@@ -2917,6 +3066,8 @@ var ConfigRepo = class {
2917
3066
  instanceId;
2918
3067
  /** 因归属他人而被跳过的后端 id → 原因,供 UI 展示。 */
2919
3068
  skippedBackends = /* @__PURE__ */ new Map();
3069
+ /** 归属冲突的完整信息(两侧 kind / id / instanceId + 可执行动作)。 */
3070
+ backendConflicts = /* @__PURE__ */ new Map();
2920
3071
  /** Last known backend descriptors, for the synchronous unified handle API. */
2921
3072
  backendDescriptorCache = [];
2922
3073
  /**
@@ -3336,7 +3487,7 @@ var ConfigRepo = class {
3336
3487
  await replica.instance.unlink(tombstone.path);
3337
3488
  gone = true;
3338
3489
  } catch (err) {
3339
- gone = isNotFoundError(err);
3490
+ gone = isNotFoundError2(err);
3340
3491
  }
3341
3492
  if (gone) processed++;
3342
3493
  }
@@ -4641,17 +4792,37 @@ var ConfigRepo = class {
4641
4792
  async bindBackendIdentity(instance, backendId) {
4642
4793
  try {
4643
4794
  const identity = await this.ensureGroupIdentity();
4644
- const state = await bindRemoteGroupIdentity(instance, identity);
4645
- if (state === "conflict") {
4646
- this.skippedBackends.set(
4795
+ const result = await bindRemoteGroupIdentityDetailed(instance, identity);
4796
+ if (result.state === "conflict") {
4797
+ this.skippedBackends.set(backendId, describeConflict(result));
4798
+ this.backendConflicts.set(backendId, {
4647
4799
  backendId,
4648
- `\u8FDC\u7AEF\u6839\u5C5E\u4E8E\u53E6\u4E00\u4E2A\u540C\u6B65\u7EC4\uFF08instanceId \u4E0D\u4E00\u81F4\uFF09\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u540E\u7AEF`
4649
- );
4800
+ reason: describeConflict(result),
4801
+ ...result.conflict ? { conflict: result.conflict } : {},
4802
+ remote: result.remote,
4803
+ local: { kind: identity.kind, id: identity.id, instanceId: identity.instanceId },
4804
+ canAdoptRemoteInstance: !!result.remote?.instanceId && result.remote.kind === identity.kind && result.remote.id === identity.id,
4805
+ canRewriteRemoteIdentity: result.remote ? result.remote.kind === identity.kind : false,
4806
+ ...result.unreadable ? { unreadable: true } : {},
4807
+ ...result.error ? { error: result.error } : {}
4808
+ });
4809
+ } else {
4810
+ this.skippedBackends.delete(backendId);
4811
+ this.backendConflicts.delete(backendId);
4650
4812
  }
4651
- return state;
4813
+ return result.state;
4652
4814
  } catch (err) {
4653
4815
  log5.warn(`[ConfigRepo] identity check failed for backend "${backendId}", skipping it:`, err);
4654
- this.skippedBackends.set(backendId, `\u5F52\u5C5E\u6821\u9A8C\u5931\u8D25\uFF1A${err?.message ?? String(err)}`);
4816
+ const message = err?.message ?? String(err);
4817
+ this.skippedBackends.set(backendId, `\u5F52\u5C5E\u6821\u9A8C\u5931\u8D25\uFF1A${message}`);
4818
+ this.backendConflicts.set(backendId, {
4819
+ backendId,
4820
+ reason: `\u5F52\u5C5E\u6821\u9A8C\u5931\u8D25\uFF1A${message}`,
4821
+ remote: null,
4822
+ local: { kind: "config", id: CONFIG_GROUP_ID, instanceId: this.instanceId },
4823
+ canAdoptRemoteInstance: false,
4824
+ canRewriteRemoteIdentity: false
4825
+ });
4655
4826
  return "conflict";
4656
4827
  }
4657
4828
  }
@@ -4659,6 +4830,53 @@ var ConfigRepo = class {
4659
4830
  listSkippedBackends() {
4660
4831
  return Array.from(this.skippedBackends, ([backendId, reason]) => ({ backendId, reason }));
4661
4832
  }
4833
+ /** 归属冲突的完整信息(配置组也会被别的组占用同一个根)。 */
4834
+ listBackendConflicts() {
4835
+ return Array.from(this.backendConflicts.values());
4836
+ }
4837
+ /** 用户确认后解决配置组某个后端的归属冲突。 */
4838
+ async resolveBackendConflict(backendId, mode) {
4839
+ const identity = await this.ensureGroupIdentity();
4840
+ const desc = (this.backendDescriptorCache ?? []).find((b) => b.id === backendId);
4841
+ if (!desc) {
4842
+ return { mode, ok: false, reason: `\u627E\u4E0D\u5230\u540E\u7AEF ${backendId}\uFF08\u53EF\u80FD\u5DF2\u88AB\u5220\u9664\uFF09` };
4843
+ }
4844
+ let instance;
4845
+ try {
4846
+ instance = await createBackend({ type: desc.type, options: desc.options });
4847
+ } catch (err) {
4848
+ return { mode, ok: false, reason: `\u521B\u5EFA\u540E\u7AEF\u5931\u8D25\uFF1A${err?.message ?? String(err)}` };
4849
+ }
4850
+ try {
4851
+ const result = await resolveRemoteIdentity(instance, identity, mode);
4852
+ if (!result.ok) return { mode, ok: false, ...result.reason ? { reason: result.reason } : {} };
4853
+ if (mode === "adopt-remote-instance" && result.instanceId) {
4854
+ this.instanceId = result.instanceId;
4855
+ try {
4856
+ await writeGroupDescriptor(this.cachedFS, {
4857
+ schemaVersion: 2,
4858
+ kind: identity.kind,
4859
+ id: identity.id,
4860
+ instanceId: this.instanceId,
4861
+ ...this.name ? { name: this.name } : {},
4862
+ features: CONFIG_GROUP_FEATURES
4863
+ });
4864
+ } catch (err) {
4865
+ log5.warn("[ConfigRepo] failed to persist adopted instanceId:", err);
4866
+ }
4867
+ }
4868
+ this.backendConflicts.delete(backendId);
4869
+ this.skippedBackends.delete(backendId);
4870
+ return { mode, ok: true, ...result.instanceId ? { instanceId: result.instanceId } : {} };
4871
+ } catch (err) {
4872
+ return { mode, ok: false, reason: `\u5BF9\u9F50\u5931\u8D25\uFF1A${err?.message ?? String(err)}` };
4873
+ } finally {
4874
+ try {
4875
+ await instance.dispose?.();
4876
+ } catch {
4877
+ }
4878
+ }
4879
+ }
4662
4880
  /** Write the group-type marker file if it doesn't exist. */
4663
4881
  async ensureGroupType(type) {
4664
4882
  this.assertNotDisposed();
@@ -4863,7 +5081,7 @@ var ConfigRepo = class {
4863
5081
  const features = meta?.features ?? existing?.features;
4864
5082
  const liveGroup = this.appDataGroups.get(id);
4865
5083
  const liveInstanceId = liveGroup?.getGroupInstanceId();
4866
- const instanceId = pickInstanceId(existing) ?? (isValidGroupInstanceId(liveInstanceId) ? liveInstanceId : void 0);
5084
+ const instanceId = isValidGroupInstanceId(meta?.instanceId) ? meta.instanceId : pickInstanceId(existing) ?? (isValidGroupInstanceId(liveInstanceId) ? liveInstanceId : void 0);
4867
5085
  const descriptor = {
4868
5086
  id,
4869
5087
  groupType: "data-sync",
@@ -5174,6 +5392,8 @@ var AppDataGroupImpl = class {
5174
5392
  instanceId;
5175
5393
  /** 因归属他人而被跳过的后端 id → 原因。 */
5176
5394
  skippedBackends = /* @__PURE__ */ new Map();
5395
+ /** 归属冲突的完整信息(两侧 kind / id / instanceId + 可执行动作)。 */
5396
+ backendConflicts = /* @__PURE__ */ new Map();
5177
5397
  _pollIntervalMs;
5178
5398
  _backendsAreAuthoritative;
5179
5399
  /** 引导副本(`.config/` 里的描述符)原有的能力位,用于回刷时不丢信息。 */
@@ -5302,32 +5522,126 @@ var AppDataGroupImpl = class {
5302
5522
  async checkBackendOwnership(instance, backendId) {
5303
5523
  if (!this.instanceId) {
5304
5524
  this.skippedBackends.set(backendId, "\u672C\u7EC4\u5C1A\u672A\u5206\u914D instanceId\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u540E\u7AEF");
5525
+ this.backendConflicts.set(backendId, {
5526
+ backendId,
5527
+ reason: "\u672C\u7EC4\u5C1A\u672A\u5206\u914D instanceId\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u540E\u7AEF",
5528
+ remote: null,
5529
+ local: { kind: "data", id: this.groupId, instanceId: void 0 },
5530
+ canAdoptRemoteInstance: false,
5531
+ canRewriteRemoteIdentity: false
5532
+ });
5305
5533
  return "conflict";
5306
5534
  }
5307
5535
  try {
5308
- const state = await bindRemoteGroupIdentity(instance, {
5536
+ const identity = {
5309
5537
  kind: "data",
5310
5538
  id: this.groupId,
5311
5539
  instanceId: this.instanceId,
5312
5540
  ...this.name ? { name: this.name } : {},
5313
5541
  features: this.features
5314
- });
5315
- if (state === "conflict") {
5316
- this.skippedBackends.set(
5542
+ };
5543
+ const result = await bindRemoteGroupIdentityDetailed(instance, identity);
5544
+ if (result.state === "conflict") {
5545
+ this.skippedBackends.set(backendId, describeConflict(result));
5546
+ this.backendConflicts.set(backendId, {
5317
5547
  backendId,
5318
- "\u8FDC\u7AEF\u6839\u5C5E\u4E8E\u53E6\u4E00\u4E2A\u540C\u6B65\u7EC4\uFF08instanceId \u4E0D\u4E00\u81F4\uFF09\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u540E\u7AEF"
5319
- );
5548
+ reason: describeConflict(result),
5549
+ ...result.conflict ? { conflict: result.conflict } : {},
5550
+ remote: result.remote,
5551
+ local: { kind: "data", id: this.groupId, instanceId: this.instanceId },
5552
+ // 只对齐 instanceId:要求 kind 与 id 都相同(同一个逻辑组,只有身份不同)。
5553
+ canAdoptRemoteInstance: !!result.remote?.instanceId && result.remote.kind === "data" && result.remote.id === this.groupId,
5554
+ // 改写远端:要求 kind 相同(组 id 不同才需要它,代价是动了共享的远端根)。
5555
+ canRewriteRemoteIdentity: result.remote ? result.remote.kind === "data" : false,
5556
+ ...result.unreadable ? { unreadable: true } : {},
5557
+ ...result.error ? { error: result.error } : {}
5558
+ });
5320
5559
  log5.warn(
5321
5560
  `[AppDataGroup:${this.groupId}] backend "${backendId}" belongs to another sync group \u2014 sync pair skipped`
5322
5561
  );
5562
+ } else {
5563
+ this.skippedBackends.delete(backendId);
5564
+ this.backendConflicts.delete(backendId);
5323
5565
  }
5324
- return state;
5566
+ return result.state;
5325
5567
  } catch (err) {
5326
5568
  log5.warn(`[AppDataGroup:${this.groupId}] ownership check failed for "${backendId}":`, err);
5327
- this.skippedBackends.set(backendId, `\u5F52\u5C5E\u6821\u9A8C\u5931\u8D25\uFF1A${err?.message ?? String(err)}`);
5569
+ const message = err?.message ?? String(err);
5570
+ this.skippedBackends.set(backendId, `\u5F52\u5C5E\u6821\u9A8C\u5931\u8D25\uFF1A${message}`);
5571
+ this.backendConflicts.set(backendId, {
5572
+ backendId,
5573
+ reason: `\u5F52\u5C5E\u6821\u9A8C\u5931\u8D25\uFF1A${message}`,
5574
+ remote: null,
5575
+ local: { kind: "data", id: this.groupId, instanceId: this.instanceId },
5576
+ canAdoptRemoteInstance: false,
5577
+ canRewriteRemoteIdentity: false
5578
+ });
5328
5579
  return "conflict";
5329
5580
  }
5330
5581
  }
5582
+ /** 归属冲突的完整信息(UI 直接展示两侧身份,不用猜)。 */
5583
+ listBackendConflicts() {
5584
+ return Array.from(this.backendConflicts.values());
5585
+ }
5586
+ /**
5587
+ * 用户确认后解决归属冲突。
5588
+ *
5589
+ * - `adopt-remote-instance`:只把本地 instanceId 对齐成远端值(本地库名、
5590
+ * 引导副本路径都不变),随后重写 `.meta/group.json` 与引导副本。
5591
+ * - `rewrite-remote-identity`:把远端 `group.json` 改写成本组的 kind/id/
5592
+ * instanceId。会影响到共享该远端根的其它副本,调用方必须先警告用户。
5593
+ *
5594
+ * 成功后冲突记录被移除;调用方应重新连接(本组需要重新 init 才能建对)。
5595
+ */
5596
+ async resolveBackendConflict(backendId, mode) {
5597
+ if (!this.instanceId) {
5598
+ return { mode, ok: false, reason: "\u672C\u7EC4\u5C1A\u672A\u5206\u914D instanceId\uFF0C\u65E0\u6CD5\u5BF9\u9F50" };
5599
+ }
5600
+ const desc = this._backends?.find((b) => b.id === backendId);
5601
+ if (!desc) {
5602
+ return { mode, ok: false, reason: `\u627E\u4E0D\u5230\u540E\u7AEF ${backendId}\uFF08\u53EF\u80FD\u5DF2\u88AB\u5220\u9664\uFF09` };
5603
+ }
5604
+ let instance;
5605
+ try {
5606
+ instance = await createBackend({ type: desc.type, options: desc.options });
5607
+ } catch (err) {
5608
+ return { mode, ok: false, reason: `\u521B\u5EFA\u540E\u7AEF\u5931\u8D25\uFF1A${err?.message ?? String(err)}` };
5609
+ }
5610
+ try {
5611
+ const identity = {
5612
+ kind: "data",
5613
+ id: this.groupId,
5614
+ instanceId: this.instanceId,
5615
+ ...this.name ? { name: this.name } : {},
5616
+ features: this.features
5617
+ };
5618
+ const result = await resolveRemoteIdentity(instance, identity, mode);
5619
+ if (!result.ok) return { mode, ok: false, ...result.reason ? { reason: result.reason } : {} };
5620
+ if (mode === "adopt-remote-instance" && result.instanceId) {
5621
+ this.instanceId = result.instanceId;
5622
+ await this.writeOwnGroupDescriptor();
5623
+ try {
5624
+ await this.parent.updateAppDataGroupDescriptor(this.groupId, this._backends ?? [], {
5625
+ name: this.name,
5626
+ features: this._declaredFeatures,
5627
+ instanceId: this.instanceId
5628
+ });
5629
+ } catch (err) {
5630
+ log5.warn(`[AppDataGroup:${this.groupId}] failed to update bootstrap descriptor instanceId:`, err);
5631
+ }
5632
+ }
5633
+ this.backendConflicts.delete(backendId);
5634
+ this.skippedBackends.delete(backendId);
5635
+ return { mode, ok: true, ...result.instanceId ? { instanceId: result.instanceId } : {} };
5636
+ } catch (err) {
5637
+ return { mode, ok: false, reason: `\u5BF9\u9F50\u5931\u8D25\uFF1A${err?.message ?? String(err)}` };
5638
+ } finally {
5639
+ try {
5640
+ await instance.dispose?.();
5641
+ } catch {
5642
+ }
5643
+ }
5644
+ }
5331
5645
  async init() {
5332
5646
  const storeName = dataGroupLocalStoreName(this.appId, this.groupId);
5333
5647
  try {
@@ -6004,14 +6318,142 @@ function sidecarOwnerPath(path) {
6004
6318
  return owner === "" ? null : owner;
6005
6319
  }
6006
6320
 
6321
+ // src/local-purge.ts
6322
+ var CONFIG_STORE_PREFIX = "zen-fs-config-config-";
6323
+ var DATA_STORE_PREFIX = "zen-fs-config-data-";
6324
+ function getIdb() {
6325
+ const idb2 = globalThis.indexedDB;
6326
+ if (!idb2 || typeof idb2.deleteDatabase !== "function") return null;
6327
+ return idb2;
6328
+ }
6329
+ function deleteIndexedDbStore(name, timeoutMs = 4e3) {
6330
+ const idb2 = getIdb();
6331
+ if (!idb2) {
6332
+ return Promise.resolve({
6333
+ storeName: name,
6334
+ deleted: false,
6335
+ blocked: false,
6336
+ unsupported: true,
6337
+ error: "\u5F53\u524D\u73AF\u5883\u6CA1\u6709 IndexedDB\uFF1A\u65E0\u6CD5\u5220\u9664\u672C\u5730\u5E93"
6338
+ });
6339
+ }
6340
+ return new Promise((resolve) => {
6341
+ let settled = false;
6342
+ let blocked = false;
6343
+ let timer;
6344
+ const finish = (result) => {
6345
+ if (settled) return;
6346
+ settled = true;
6347
+ if (timer) clearTimeout(timer);
6348
+ resolve(result);
6349
+ };
6350
+ let request2;
6351
+ try {
6352
+ request2 = idb2.deleteDatabase(name);
6353
+ } catch (err) {
6354
+ finish({ storeName: name, deleted: false, blocked: false, error: summarizeError(err).message });
6355
+ return;
6356
+ }
6357
+ request2.onsuccess = () => finish({ storeName: name, deleted: true, blocked: false });
6358
+ request2.onerror = () => finish({
6359
+ storeName: name,
6360
+ deleted: false,
6361
+ blocked: false,
6362
+ error: summarizeError(request2.error).message
6363
+ });
6364
+ request2.onblocked = () => {
6365
+ blocked = true;
6366
+ };
6367
+ timer = setTimeout(() => {
6368
+ finish({
6369
+ storeName: name,
6370
+ deleted: false,
6371
+ blocked,
6372
+ error: blocked ? "\u5220\u9664\u88AB\u5176\u5B83\u9875\u9762/\u5B9E\u4F8B\u5360\u7528\uFF08blocked\uFF09\uFF1A\u8BF7\u5173\u95ED\u5176\u5B83\u6253\u5F00\u8BE5\u9875\u9762\u7684\u6807\u7B7E\u9875\u540E\u91CD\u8BD5" : "\u5220\u9664\u8D85\u65F6\uFF1AIndexedDB \u672A\u5728\u9884\u671F\u65F6\u95F4\u5185\u54CD\u5E94"
6373
+ });
6374
+ }, timeoutMs);
6375
+ });
6376
+ }
6377
+ function localSyncStoreNames(appId, groupIds = []) {
6378
+ const names = /* @__PURE__ */ new Set([
6379
+ `${CONFIG_STORE_PREFIX}${appId}`,
6380
+ `${DATA_STORE_PREFIX}${appId}`
6381
+ ]);
6382
+ for (const groupId of groupIds) {
6383
+ if (!groupId) continue;
6384
+ names.add(`${DATA_STORE_PREFIX}${appId}-${groupId}`);
6385
+ }
6386
+ return Array.from(names);
6387
+ }
6388
+ async function purgeLocalSyncConfig(appId, options = {}) {
6389
+ const idb2 = getIdb();
6390
+ const names = new Set(localSyncStoreNames(appId, options.groupIds));
6391
+ const removedStorageKeys = [];
6392
+ const removeStorageKeys = () => {
6393
+ try {
6394
+ const ls = globalThis.localStorage;
6395
+ if (!ls) return;
6396
+ for (const key of options.extraStorageKeys ?? []) {
6397
+ try {
6398
+ if (ls.getItem(key) !== null) {
6399
+ ls.removeItem(key);
6400
+ removedStorageKeys.push(key);
6401
+ }
6402
+ } catch {
6403
+ }
6404
+ }
6405
+ } catch {
6406
+ }
6407
+ };
6408
+ if (!idb2) {
6409
+ removeStorageKeys();
6410
+ return { appId, databases: [], removedStorageKeys, unsupported: true };
6411
+ }
6412
+ try {
6413
+ const list = await idb2.databases?.();
6414
+ for (const entry of list ?? []) {
6415
+ const name = entry?.name;
6416
+ if (!name) continue;
6417
+ if (name === `${CONFIG_STORE_PREFIX}${appId}`) names.add(name);
6418
+ if (name === `${DATA_STORE_PREFIX}${appId}` || name.startsWith(`${DATA_STORE_PREFIX}${appId}-`)) {
6419
+ names.add(name);
6420
+ }
6421
+ }
6422
+ } catch {
6423
+ }
6424
+ const databases = [];
6425
+ for (const name of names) {
6426
+ databases.push(await deleteIndexedDbStore(name, options.timeoutMs));
6427
+ }
6428
+ removeStorageKeys();
6429
+ return { appId, databases, removedStorageKeys };
6430
+ }
6431
+
6007
6432
  // src/connect.ts
6008
6433
  init_backend_registry();
6434
+ var isInstanceIdLike = (value) => typeof value === "string" && isValidGroupInstanceId(value);
6009
6435
  var log6 = createLogger2("connect");
6010
6436
  var GROUP_TYPE_FILE2 = "/.config/group-type";
6011
6437
  var LEGACY_GROUP_TYPE_FILE2 = "/.meta/group-type";
6012
- async function detectGroupType(type, options) {
6438
+ async function detectGroupTypeDetailed(type, options) {
6013
6439
  log6(`detectGroupType: connecting to ${type}...`);
6014
6440
  const tempBackend = await createBackend({ type, options });
6441
+ let remote = null;
6442
+ try {
6443
+ try {
6444
+ const descriptor = await readGroupDescriptor(tempBackend);
6445
+ if (descriptor) {
6446
+ remote = {
6447
+ kind: descriptor.kind,
6448
+ id: descriptor.id,
6449
+ instanceId: isInstanceIdLike(descriptor.instanceId) ? descriptor.instanceId : void 0,
6450
+ ...descriptor.name ? { name: descriptor.name } : {}
6451
+ };
6452
+ }
6453
+ } catch {
6454
+ }
6455
+ } finally {
6456
+ }
6015
6457
  try {
6016
6458
  for (const path of [GROUP_TYPE_FILE2, LEGACY_GROUP_TYPE_FILE2]) {
6017
6459
  try {
@@ -6019,15 +6461,15 @@ async function detectGroupType(type, options) {
6019
6461
  const groupType = raw.trim();
6020
6462
  if (groupType === "config-sync" || groupType === "data-sync") {
6021
6463
  log6(`detectGroupType: detected "${groupType}" at ${path}`);
6022
- return groupType;
6464
+ return { groupType, remote };
6023
6465
  }
6024
6466
  log6(`detectGroupType: unknown group-type value "${groupType}" at ${path}, treating as null`);
6025
- return null;
6467
+ return { groupType: null, remote };
6026
6468
  } catch {
6027
6469
  }
6028
6470
  }
6029
6471
  log6(`detectGroupType: no group-type file found (new backend)`);
6030
- return null;
6472
+ return { groupType: null, remote };
6031
6473
  } finally {
6032
6474
  if (tempBackend?.dispose) {
6033
6475
  await tempBackend.dispose();
@@ -6072,12 +6514,15 @@ async function connect(appId, options = {}) {
6072
6514
  };
6073
6515
  }
6074
6516
  const { type, options: backendOptions } = options.backendInfo;
6075
- const detectedType = await detectGroupType(type, backendOptions);
6517
+ const detected = await detectGroupTypeDetailed(type, backendOptions);
6518
+ const detectedType = detected.groupType;
6076
6519
  let groupType;
6077
6520
  if (detectedType) {
6078
6521
  if (options.groupType && options.groupType !== detectedType) {
6522
+ const remoteText = summarizeIdentity(detected.remote);
6523
+ const advice = detectedType === "config-sync" ? "\u8BE5\u8FDC\u7AEF\u6839\u5DF2\u88AB\u4E00\u4E2A\u914D\u7F6E\u7EC4\u5360\u7528\uFF1A\u8BF7\u7ED9\u6570\u636E\u7EC4\u6362\u4E00\u4E2A\u4E13\u5C5E\u7684\u8FDC\u7AEF\u6839\uFF0C\u6216\u5728\u914D\u7F6E\u7EC4\u4FA7\u89E3\u9664\u5BF9\u8BE5\u6839\u7684\u7ED1\u5B9A" : "\u8BE5\u8FDC\u7AEF\u6839\u5DF2\u88AB\u4E00\u4E2A\u6570\u636E\u7EC4\u5360\u7528\uFF1A\u8BF7\u7ED9\u914D\u7F6E\u7EC4\u6362\u4E00\u4E2A\u8FDC\u7AEF\u6839\uFF0C\u6216\u5220\u9664\u90A3\u4E2A\u6570\u636E\u7EC4\u540E\u7AEF";
6079
6524
  throw new Error(
6080
- `Group type mismatch: remote backend is "${detectedType}" but options.groupType is "${options.groupType}"`
6525
+ `Group type mismatch: \u8FDC\u7AEF\u6807\u8BB0\u4E3A "${detectedType}"\uFF08${remoteText}\uFF09\uFF0C\u672C\u7AEF\u8981\u6C42 "${options.groupType}"\u3002${advice}`
6081
6526
  );
6082
6527
  }
6083
6528
  groupType = detectedType;
@@ -6163,6 +6608,8 @@ init_backend_registry();
6163
6608
  TombstoneStore,
6164
6609
  VERSIONS_DIR,
6165
6610
  VersionStore,
6611
+ bindRemoteGroupIdentity,
6612
+ bindRemoteGroupIdentityDetailed,
6166
6613
  configKeyToFilePath,
6167
6614
  connect,
6168
6615
  createBackend,
@@ -6170,6 +6617,7 @@ init_backend_registry();
6170
6617
  createSerializerChain,
6171
6618
  dataGroupLocalStoreName,
6172
6619
  deleteDataGroupLocalStore,
6620
+ deleteIndexedDbStore,
6173
6621
  encodeMetaPath,
6174
6622
  getAccountFields,
6175
6623
  getBackendMetadata,
@@ -6180,20 +6628,27 @@ init_backend_registry();
6180
6628
  isKeepFile,
6181
6629
  isLocalStorageUnavailableError,
6182
6630
  isMtimeSidecar,
6631
+ isValidGroupInstanceId,
6183
6632
  legacyVersionPathFor,
6184
6633
  listBackendMetadata,
6185
6634
  listBackends,
6186
6635
  localPrimaryType,
6636
+ localSyncStoreNames,
6187
6637
  mergeAccountFields,
6188
6638
  migrateVersionSidecars,
6639
+ newGroupInstanceId,
6189
6640
  purgeKeepFiles,
6641
+ purgeLocalSyncConfig,
6190
6642
  purgeMtimeSidecars,
6191
6643
  readGroupDescriptor,
6192
6644
  readVersion,
6193
6645
  registerBackend,
6194
6646
  registerFolderBackend,
6195
6647
  resolveLocalPrimary,
6648
+ resolveRemoteIdentity,
6196
6649
  sha256,
6650
+ shortInstanceId,
6651
+ summarizeIdentity,
6197
6652
  unregisterBackend,
6198
6653
  verifyOrRepairVersion,
6199
6654
  versionPathFor,