zen-fs-config 0.7.3 → 0.7.5

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
@@ -117,7 +117,14 @@ async function wrapZenFSFileSystem(config) {
117
117
  await isolatedFS.mkdir(dir, { uid: 0, gid: 0, mode: 493 });
118
118
  }
119
119
  }
120
- if (!await isolatedFS.exists(path)) {
120
+ let currentSize = 0;
121
+ if (await isolatedFS.exists(path)) {
122
+ currentSize = (await isolatedFS.stat(path)).size;
123
+ } else {
124
+ await isolatedFS.createFile(path, { uid: 0, gid: 0, mode: 420 });
125
+ }
126
+ if (currentSize > 0) {
127
+ await isolatedFS.unlink(path);
121
128
  await isolatedFS.createFile(path, { uid: 0, gid: 0, mode: 420 });
122
129
  }
123
130
  await isolatedFS.write(path, bytes, 0);
@@ -519,10 +526,12 @@ __export(index_exports, {
519
526
  ConflictStore: () => ConflictStore,
520
527
  DATA_GROUP_DEFAULT_FEATURES: () => DATA_GROUP_DEFAULT_FEATURES,
521
528
  FolderStore: () => FolderStore,
522
- GROUP_DESCRIPTOR_FILE: () => GROUP_DESCRIPTOR_FILE,
529
+ GROUP_DESCRIPTOR_FILE: () => GROUP_DESCRIPTOR_FILE2,
523
530
  LEGACY_CONFLICTS_DIR: () => LEGACY_CONFLICTS_DIR,
524
531
  LEGACY_TOMBSTONES_DIR: () => LEGACY_TOMBSTONES_DIR,
525
532
  LOCAL_IDB_BACKEND_ID: () => LOCAL_IDB_BACKEND_ID,
533
+ LOCAL_STORAGE_UNAVAILABLE: () => LOCAL_STORAGE_UNAVAILABLE,
534
+ LocalStorageUnavailableError: () => LocalStorageUnavailableError,
526
535
  META_DIR: () => META_DIR,
527
536
  TOMBSTONES_DIR: () => TOMBSTONES_DIR,
528
537
  TombstoneStore: () => TombstoneStore,
@@ -533,6 +542,8 @@ __export(index_exports, {
533
542
  createBackend: () => createBackend,
534
543
  createConfigRepo: () => createConfigRepo,
535
544
  createSerializerChain: () => createSerializerChain,
545
+ dataGroupLocalStoreName: () => dataGroupLocalStoreName,
546
+ deleteDataGroupLocalStore: () => deleteDataGroupLocalStore,
536
547
  encodeMetaPath: () => encodeMetaPath,
537
548
  getAccountFields: () => getAccountFields,
538
549
  getBackendMetadata: () => getBackendMetadata,
@@ -541,6 +552,7 @@ __export(index_exports, {
541
552
  incrementVersion: () => incrementVersion,
542
553
  isBrowserEnv: () => isBrowserEnv,
543
554
  isKeepFile: () => isKeepFile,
555
+ isLocalStorageUnavailableError: () => isLocalStorageUnavailableError,
544
556
  isMtimeSidecar: () => isMtimeSidecar,
545
557
  legacyVersionPathFor: () => legacyVersionPathFor,
546
558
  listBackendMetadata: () => listBackendMetadata,
@@ -765,6 +777,92 @@ function createChrootFS(inner, root, options = {}) {
765
777
  async function ensureParentDir(absolutePath) {
766
778
  }
767
779
 
780
+ // src/group-type-guard.ts
781
+ var import_localstorage_logger = require("@richard432/localstorage-logger");
782
+ var log = (0, import_localstorage_logger.createLogger)("zen-fs-config:group-type-guard");
783
+ var GROUP_TYPE_FILES = /* @__PURE__ */ new Set(["/.config/group-type", "/.meta/group-type"]);
784
+ var GROUP_DESCRIPTOR_FILE = "/.meta/group.json";
785
+ var APP_DATA_GROUP_DESCRIPTOR_RE = /^\/\.config\/app-data-groups\/[^/]+\/[^/]+\.json$/;
786
+ function decode(data) {
787
+ if (typeof data === "string") return data;
788
+ if (data instanceof ArrayBuffer) return new TextDecoder().decode(new Uint8Array(data));
789
+ return new TextDecoder().decode(data);
790
+ }
791
+ function safeParse(text) {
792
+ try {
793
+ return JSON.parse(text);
794
+ } catch {
795
+ return null;
796
+ }
797
+ }
798
+ function readGroupIdentity(path, data) {
799
+ const normalized = path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path;
800
+ const isGroupType = GROUP_TYPE_FILES.has(normalized);
801
+ const isGroupDescriptor = normalized === GROUP_DESCRIPTOR_FILE;
802
+ const isAppDataGroup = APP_DATA_GROUP_DESCRIPTOR_RE.test(normalized);
803
+ if (!isGroupType && !isGroupDescriptor && !isAppDataGroup) return null;
804
+ const text = decode(data);
805
+ if (isGroupType) {
806
+ const value = text.trim();
807
+ return value || null;
808
+ }
809
+ const parsed = safeParse(text);
810
+ if (isGroupDescriptor) {
811
+ return typeof parsed?.kind === "string" ? `kind:${parsed.kind}` : null;
812
+ }
813
+ return typeof parsed?.groupType === "string" ? `groupType:${parsed.groupType}` : null;
814
+ }
815
+ async function readExistingIdentity(fs, path) {
816
+ try {
817
+ const raw = await fs.readFile(path, "utf-8");
818
+ return readGroupIdentity(path, raw);
819
+ } catch {
820
+ return null;
821
+ }
822
+ }
823
+ function wrapGroupTypeGuard(fs, side, onBlock) {
824
+ const reported = /* @__PURE__ */ new Set();
825
+ const guarded = Object.create(fs);
826
+ const lastBlock = { current: null };
827
+ guarded.getLastBlockedGroupType = () => lastBlock.current;
828
+ const allow = async (path, data) => {
829
+ const incoming = readGroupIdentity(path, data);
830
+ if (incoming === null) return true;
831
+ const existing = await readExistingIdentity(fs, path);
832
+ if (existing === null || existing === incoming) return true;
833
+ const signature = `${side}|${path}|${existing}->${incoming}`;
834
+ const block = { side, path, existing, incoming };
835
+ lastBlock.current = block;
836
+ if (!reported.has(signature)) {
837
+ reported.add(signature);
838
+ log.warn(
839
+ `[GroupType] blocked group-type change on ${side}: ${path} would change "${existing}" \u2192 "${incoming}" \u2014 identity is write-once, the incoming value is dropped (fix the group wiring instead of syncing it)`
840
+ );
841
+ }
842
+ try {
843
+ onBlock?.(block);
844
+ } catch {
845
+ }
846
+ return false;
847
+ };
848
+ guarded.writeFile = async (path, data) => {
849
+ if (!await allow(path, data)) return;
850
+ return fs.writeFile(path, data);
851
+ };
852
+ if (typeof fs.writeFileWithMtime === "function") {
853
+ guarded.writeFileWithMtime = async (path, data, mtime) => {
854
+ if (!await allow(path, data)) return;
855
+ return fs.writeFileWithMtime(path, data, mtime);
856
+ };
857
+ }
858
+ guarded.backendName = sideLabel(fs.backendName, side);
859
+ return guarded;
860
+ }
861
+ function sideLabel(name, side) {
862
+ if (!name) return side;
863
+ return name.includes(side) ? name : `${name}\xB7${side}`;
864
+ }
865
+
768
866
  // src/adapters.ts
769
867
  function toUint8Array(data) {
770
868
  if (data instanceof Uint8Array) return data;
@@ -838,7 +936,7 @@ function backendToSyncableFS(backend, name) {
838
936
  } else {
839
937
  syncable.backendName = backend.constructor.name || "Backend";
840
938
  }
841
- return syncable;
939
+ return wrapGroupTypeGuard(syncable, syncable.backendName || "backend");
842
940
  }
843
941
 
844
942
  // src/config-repo.ts
@@ -849,15 +947,15 @@ init_backend_registry();
849
947
  var import_core = require("@zenfs/core");
850
948
 
851
949
  // src/logger.ts
852
- var import_localstorage_logger = require("@richard432/localstorage-logger");
950
+ var import_localstorage_logger2 = require("@richard432/localstorage-logger");
853
951
  var MODULE_PREFIX = "zen-fs-config";
854
- function createLogger(prefix) {
855
- const logger = (0, import_localstorage_logger.createLogger)(`${MODULE_PREFIX}:${prefix}`);
952
+ function createLogger2(prefix) {
953
+ const logger = (0, import_localstorage_logger2.createLogger)(`${MODULE_PREFIX}:${prefix}`);
856
954
  return (...args) => logger.log(...args);
857
955
  }
858
956
 
859
957
  // src/folder-backend.ts
860
- var log = createLogger("folder-backend");
958
+ var log2 = createLogger2("folder-backend");
861
959
  var FolderStore = class {
862
960
  name = "folder";
863
961
  label;
@@ -944,7 +1042,7 @@ function registerFolderBackend() {
944
1042
  defaultOptions: { path: "" }
945
1043
  }
946
1044
  );
947
- log("Folder backend registered");
1045
+ log2("Folder backend registered");
948
1046
  }
949
1047
  registerFolderBackend();
950
1048
  function isBrowserEnv() {
@@ -977,8 +1075,127 @@ async function defaultNodeDir(appId, kind, groupId) {
977
1075
  return kindDir;
978
1076
  }
979
1077
 
1078
+ // src/errors.ts
1079
+ var LOCAL_STORAGE_UNAVAILABLE = "LOCAL_STORAGE_UNAVAILABLE";
1080
+ function dataGroupLocalStoreName(appId, groupId) {
1081
+ return groupId === "default" ? `zen-fs-config-data-${appId}` : `zen-fs-config-data-${appId}-${groupId}`;
1082
+ }
1083
+ var LocalStorageUnavailableError = class extends Error {
1084
+ code = LOCAL_STORAGE_UNAVAILABLE;
1085
+ appId;
1086
+ groupId;
1087
+ storeName;
1088
+ cause;
1089
+ constructor(details) {
1090
+ super(
1091
+ `Local storage for data group "${details.groupId}" is unavailable (IndexedDB "${details.storeName}"): ${describeError(details.cause)}`
1092
+ );
1093
+ this.name = "LocalStorageUnavailableError";
1094
+ this.appId = details.appId;
1095
+ this.groupId = details.groupId;
1096
+ this.storeName = details.storeName;
1097
+ this.cause = details.cause;
1098
+ }
1099
+ /** 原始异常的可序列化摘要(code / name / message),便于日志与诊断面板展示。 */
1100
+ toJSON() {
1101
+ return {
1102
+ name: this.name,
1103
+ code: this.code,
1104
+ appId: this.appId,
1105
+ groupId: this.groupId,
1106
+ storeName: this.storeName,
1107
+ message: this.message,
1108
+ cause: summarizeError(this.cause)
1109
+ };
1110
+ }
1111
+ };
1112
+ function summarizeError(err) {
1113
+ if (err instanceof Error || err && typeof err === "object") {
1114
+ const anyErr = err;
1115
+ return {
1116
+ name: anyErr.name,
1117
+ code: anyErr.code,
1118
+ message: anyErr.message ?? String(err),
1119
+ stack: anyErr.stack
1120
+ };
1121
+ }
1122
+ return { message: String(err) };
1123
+ }
1124
+ function describeError(err) {
1125
+ const s = summarizeError(err);
1126
+ return [s.name, s.code, s.message].filter(Boolean).join(": ");
1127
+ }
1128
+ var STORAGE_MESSAGE_HINTS = [
1129
+ /Data lost due to missing file/i,
1130
+ /should be considered irrecoverable/i,
1131
+ /IndexedDB.*(corrupt|unreadable)/i
1132
+ ];
1133
+ function isLocalStorageUnavailableError(err) {
1134
+ let cur = err;
1135
+ for (let depth = 0; cur && depth < 6; depth++) {
1136
+ if (cur instanceof LocalStorageUnavailableError) return true;
1137
+ const anyErr = cur;
1138
+ if (anyErr.name === "NotReadableError") return true;
1139
+ if (anyErr.code === "EIO") return true;
1140
+ const message = typeof anyErr.message === "string" ? anyErr.message : "";
1141
+ if (message && STORAGE_MESSAGE_HINTS.some((re) => re.test(message))) return true;
1142
+ cur = anyErr.cause;
1143
+ }
1144
+ return false;
1145
+ }
1146
+ function deleteDataGroupLocalStore(appId, groupId, options = {}) {
1147
+ const storeName = dataGroupLocalStoreName(appId, groupId);
1148
+ const idb = globalThis.indexedDB;
1149
+ if (!idb || typeof idb.deleteDatabase !== "function") {
1150
+ return Promise.resolve({
1151
+ storeName,
1152
+ deleted: false,
1153
+ blocked: false,
1154
+ unsupported: true,
1155
+ error: "\u5F53\u524D\u73AF\u5883\u6CA1\u6709 IndexedDB\uFF1A\u65E0\u6CD5\u5220\u9664\u672C\u5730\u6570\u636E\u7EC4\u5B58\u50A8"
1156
+ });
1157
+ }
1158
+ const timeoutMs = options.timeoutMs ?? 4e3;
1159
+ return new Promise((resolve) => {
1160
+ let settled = false;
1161
+ let blocked = false;
1162
+ let timer;
1163
+ const finish = (result) => {
1164
+ if (settled) return;
1165
+ settled = true;
1166
+ if (timer) clearTimeout(timer);
1167
+ resolve(result);
1168
+ };
1169
+ let request;
1170
+ try {
1171
+ request = idb.deleteDatabase(storeName);
1172
+ } catch (err) {
1173
+ finish({ storeName, deleted: false, blocked: false, error: summarizeError(err).message });
1174
+ return;
1175
+ }
1176
+ request.onsuccess = () => finish({ storeName, deleted: true, blocked: false });
1177
+ request.onerror = () => finish({
1178
+ storeName,
1179
+ deleted: false,
1180
+ blocked: false,
1181
+ error: summarizeError(request.error).message
1182
+ });
1183
+ request.onblocked = () => {
1184
+ blocked = true;
1185
+ };
1186
+ timer = setTimeout(() => {
1187
+ finish({
1188
+ storeName,
1189
+ deleted: false,
1190
+ blocked,
1191
+ 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"
1192
+ });
1193
+ }, timeoutMs);
1194
+ });
1195
+ }
1196
+
980
1197
  // src/config-repo.ts
981
- var import_localstorage_logger3 = require("@richard432/localstorage-logger");
1198
+ var import_localstorage_logger4 = require("@richard432/localstorage-logger");
982
1199
 
983
1200
  // src/version.ts
984
1201
  function versionPathFor(configFilePath) {
@@ -1465,7 +1682,7 @@ async function migrateVersionSidecars(fs, options = {}) {
1465
1682
  }
1466
1683
 
1467
1684
  // src/group-meta.ts
1468
- var import_localstorage_logger2 = require("@richard432/localstorage-logger");
1685
+ var import_localstorage_logger3 = require("@richard432/localstorage-logger");
1469
1686
 
1470
1687
  // src/canonical-json.ts
1471
1688
  var FEATURE_ORDER = ["tombstones", "versions", "conflicts", "configHost", "appData"];
@@ -1540,11 +1757,25 @@ function mergeDescriptorCreatedAt(descriptor, existing) {
1540
1757
  }
1541
1758
 
1542
1759
  // src/group-meta.ts
1543
- var log2 = (0, import_localstorage_logger2.createLogger)("zen-fs-config:tombstones");
1760
+ var log3 = (0, import_localstorage_logger3.createLogger)("zen-fs-config:tombstones");
1544
1761
  var META_DIR = "/.meta";
1545
- var GROUP_DESCRIPTOR_FILE = `${META_DIR}/group.json`;
1762
+ var GROUP_DESCRIPTOR_FILE2 = `${META_DIR}/group.json`;
1546
1763
  var META_BACKENDS_DIR = `${META_DIR}/backends`;
1547
1764
  var TOMBSTONES_DIR = `${META_DIR}/tombstones`;
1765
+ var RECREATE_AFTER_DELETE_SKEW_MS = 3e3;
1766
+ var TOMBSTONE_RETENTION_MS = 24 * 60 * 60 * 1e3;
1767
+ var TOMBSTONE_PLACEHOLDER_RETENTION_MS = 10 * 60 * 1e3;
1768
+ function tombstoneRetentionMs(tombstonePath) {
1769
+ if (tombstonePath.endsWith(".mtime") || tombstonePath === "/.keep" || tombstonePath.endsWith("/.keep")) {
1770
+ return TOMBSTONE_PLACEHOLDER_RETENTION_MS;
1771
+ }
1772
+ return TOMBSTONE_RETENTION_MS;
1773
+ }
1774
+ function isTombstoneRetentionElapsed(tombstone, now = Date.now()) {
1775
+ const deletedAt = Number(tombstone.deletedAt);
1776
+ if (!Number.isFinite(deletedAt)) return true;
1777
+ return now - deletedAt >= tombstoneRetentionMs(tombstone.path);
1778
+ }
1548
1779
  var LEGACY_TOMBSTONES_DIR = `${META_DIR}/.deleted`;
1549
1780
  var VERSIONS_DIR = `${META_DIR}/versions`;
1550
1781
  var CONFLICTS_DIR = `${META_DIR}/conflicts`;
@@ -1748,16 +1979,16 @@ async function readTombstonesFromFs(fs, warn) {
1748
1979
  return Array.from(byPath.values());
1749
1980
  }
1750
1981
  async function readGroupDescriptor(fs) {
1751
- const parsed = await readJson(fs, GROUP_DESCRIPTOR_FILE);
1982
+ const parsed = await readJson(fs, GROUP_DESCRIPTOR_FILE2);
1752
1983
  if (!parsed) return null;
1753
1984
  const { updatedAt: _ignored, ...rest } = parsed;
1754
1985
  return rest;
1755
1986
  }
1756
1987
  async function writeGroupDescriptor(fs, descriptor) {
1757
1988
  const bytes = serializeGroupDescriptor(descriptor);
1758
- if (await readText(fs, GROUP_DESCRIPTOR_FILE) === bytes) return;
1759
- await ensureParentDir2(fs, GROUP_DESCRIPTOR_FILE);
1760
- await fs.writeFile(GROUP_DESCRIPTOR_FILE, new TextEncoder().encode(bytes));
1989
+ if (await readText(fs, GROUP_DESCRIPTOR_FILE2) === bytes) return;
1990
+ await ensureParentDir2(fs, GROUP_DESCRIPTOR_FILE2);
1991
+ await fs.writeFile(GROUP_DESCRIPTOR_FILE2, new TextEncoder().encode(bytes));
1761
1992
  }
1762
1993
  function assertValidBackendId(id) {
1763
1994
  if (typeof id !== "string" || id.trim() === "") {
@@ -1824,7 +2055,7 @@ var TombstoneStore = class {
1824
2055
  }
1825
2056
  /** All tombstones. */
1826
2057
  async list() {
1827
- return readTombstonesFromFs(this.fs, (message) => log2.warn(message));
2058
+ return readTombstonesFromFs(this.fs, (message) => log3.warn(message));
1828
2059
  }
1829
2060
  /** Write a tombstone. */
1830
2061
  async write(tombstone) {
@@ -1852,15 +2083,52 @@ var TombstoneStore = class {
1852
2083
  /**
1853
2084
  * Delete every tombstoned file (and its version record) on the local store
1854
2085
  * and on each target backend, so bi-directional sync cannot resurrect it.
2086
+ *
2087
+ * 墓碑只对「删除之后没有再写入」的路径有效。同步类工具会不断重建某些文件
2088
+ * (最典型的是 `.sync.lock`:每轮删除 → 重建),若墓碑永久生效,路径会被每一
2089
+ * 轮 preSync 删掉,表现为「刚写完 1 秒就消失、锁永远拿不到」。因此这里先判定
2090
+ * 目标路径是否在 `deletedAt` 之后被重新写入:是则墓碑已被用户写操作撤销,保留
2091
+ * 文件并删除墓碑;否则按删除传播处理。
1855
2092
  */
1856
2093
  async process(targets = []) {
1857
2094
  const tombstones = await this.list();
2095
+ const expired = [];
1858
2096
  for (const tombstone of tombstones) {
2097
+ if (await this.wasRecreatedAfterDeletion(tombstone)) {
2098
+ expired.push(tombstone);
2099
+ continue;
2100
+ }
1859
2101
  await this.deleteEverywhere(this.fs, tombstone.path);
1860
2102
  for (const target of targets) {
1861
2103
  await this.deleteEverywhere(target.fs, tombstone.path);
1862
2104
  }
1863
2105
  }
2106
+ for (const tombstone of expired) {
2107
+ await this.remove(tombstone);
2108
+ log3.log(
2109
+ `[TombstoneStore] expired tombstone for ${tombstone.path} \u2014 recreated after deletion`
2110
+ );
2111
+ }
2112
+ }
2113
+ /**
2114
+ * 本地存储上该路径的 mtime 是否晚于墓碑的删除时刻。
2115
+ *
2116
+ * 只看本地主存储:副本上的同路径文件可能只是「删除之前的旧副本」,它的 mtime
2117
+ * 本来就旧,用副本判定既不可靠又会掩盖真正的删除传播。
2118
+ */
2119
+ async wasRecreatedAfterDeletion(tombstone) {
2120
+ const mtimeMs = await this.mtimeOf(this.fs, tombstone.path);
2121
+ if (mtimeMs === null) return false;
2122
+ return mtimeMs > tombstone.deletedAt + RECREATE_AFTER_DELETE_SKEW_MS;
2123
+ }
2124
+ async mtimeOf(fs, filePath) {
2125
+ try {
2126
+ const stat = await fs.stat?.(filePath);
2127
+ const mtimeMs = Number(stat?.mtimeMs);
2128
+ return Number.isFinite(mtimeMs) ? mtimeMs : null;
2129
+ } catch {
2130
+ return null;
2131
+ }
1864
2132
  }
1865
2133
  async deleteEverywhere(fs, filePath) {
1866
2134
  if (!isMtimeSidecarPath(filePath) && !await existsSafe(fs, filePath)) return;
@@ -1894,6 +2162,7 @@ var TombstoneStore = class {
1894
2162
  async gc(allBackendIds, targets = []) {
1895
2163
  const tombstones = await this.list();
1896
2164
  for (const tombstone of tombstones) {
2165
+ if (!isTombstoneRetentionElapsed(tombstone)) continue;
1897
2166
  const allConfirmed = allBackendIds.every((id) => tombstone.confirmedBy.includes(id));
1898
2167
  if (!allConfirmed) continue;
1899
2168
  const p = this.pathFor(tombstone.path);
@@ -2045,8 +2314,8 @@ var ConflictStore = class {
2045
2314
  };
2046
2315
 
2047
2316
  // src/config-repo.ts
2048
- var log3 = (0, import_localstorage_logger3.createLogger)("zen-fs-config:config-repo");
2049
- var GROUP_DESCRIPTOR_FILE2 = `${META_DIR}/group.json`;
2317
+ var log4 = (0, import_localstorage_logger4.createLogger)("zen-fs-config:config-repo");
2318
+ var GROUP_DESCRIPTOR_FILE3 = `${META_DIR}/group.json`;
2050
2319
  var GROUP_TYPE_FILE = `${CONFIG_DIR}/group-type`;
2051
2320
  var LEGACY_GROUP_TYPE_FILE = `${META_DIR}/group-type`;
2052
2321
  var BACKENDS_FILE = `${META_DIR}/backends.json`;
@@ -2180,6 +2449,7 @@ function normalizeGroupName(value) {
2180
2449
  }
2181
2450
  var CONFIG_ONLY_PREFIXES = [CONFIG_DIR, NODES_DIR, SHARED_DIR];
2182
2451
  var LOCAL_IDB_BACKEND_ID = "local-idb";
2452
+ var TOMBSTONE_RECREATE_SKEW_MS = 3e3;
2183
2453
  function tombstoneFileName(filePath) {
2184
2454
  return `${encodeMetaPath(filePath)}.json`;
2185
2455
  }
@@ -2359,7 +2629,7 @@ var ConfigRepo = class {
2359
2629
  const bytes = this.serializer.serialize(data, fullPath);
2360
2630
  this.configCache.set(fullPath, data);
2361
2631
  this.persistConfig(fullPath, bytes).catch((err) => {
2362
- log3.error(`[zen-fs-config] Failed to persist ${fullPath}:`, err);
2632
+ log4.error(`[zen-fs-config] Failed to persist ${fullPath}:`, err);
2363
2633
  });
2364
2634
  }
2365
2635
  // -----------------------------------------------------------------------
@@ -2506,7 +2776,7 @@ var ConfigRepo = class {
2506
2776
  }
2507
2777
  const onEnumerateError = (label, error) => {
2508
2778
  const reason = error?.message ?? String(error);
2509
- log3.warn(
2779
+ log4.warn(
2510
2780
  `[ConfigRepo] deleteFile(directory): cannot enumerate "${label}" under ${normalizedPath}: ${reason}`
2511
2781
  );
2512
2782
  };
@@ -2521,7 +2791,7 @@ var ConfigRepo = class {
2521
2791
  await removeDirectoryTree(this.cachedFS, normalizedPath);
2522
2792
  this.invalidateTombstoneCache();
2523
2793
  this.schedulePostDeleteSync();
2524
- log3.log(`[ConfigRepo] deleteFile(directory): ${normalizedPath} (${files.length} file(s))`);
2794
+ log4.log(`[ConfigRepo] deleteFile(directory): ${normalizedPath} (${files.length} file(s))`);
2525
2795
  return;
2526
2796
  }
2527
2797
  await this.writeTombstoneFor(normalizedPath);
@@ -2542,7 +2812,7 @@ var ConfigRepo = class {
2542
2812
  } catch {
2543
2813
  }
2544
2814
  }
2545
- log3.log(`[ConfigRepo] deleteFile: ${normalizedPath} (tombstone at ${tombstonePathFor(normalizedPath)})`);
2815
+ log4.log(`[ConfigRepo] deleteFile: ${normalizedPath} (tombstone at ${tombstonePathFor(normalizedPath)})`);
2546
2816
  this.invalidateTombstoneCache();
2547
2817
  this.schedulePostDeleteSync();
2548
2818
  }
@@ -2560,7 +2830,7 @@ var ConfigRepo = class {
2560
2830
  this.postDeleteSyncTimer = void 0;
2561
2831
  if (this.disposed) return;
2562
2832
  this.syncEngine.syncAll().catch((err) => {
2563
- log3.warn("[ConfigRepo] post-delete sync failed:", err);
2833
+ log4.warn("[ConfigRepo] post-delete sync failed:", err);
2564
2834
  });
2565
2835
  }, 500);
2566
2836
  }
@@ -2572,7 +2842,7 @@ var ConfigRepo = class {
2572
2842
  if (this.tombstoneCache !== null) {
2573
2843
  return this.tombstoneCache;
2574
2844
  }
2575
- this.tombstoneCache = await readTombstonesFromFs(this.cachedFS, (message) => log3.warn(message));
2845
+ this.tombstoneCache = await readTombstonesFromFs(this.cachedFS, (message) => log4.warn(message));
2576
2846
  this.refreshSyncExclusions(this.tombstoneCache);
2577
2847
  return this.tombstoneCache;
2578
2848
  }
@@ -2590,16 +2860,40 @@ var ConfigRepo = class {
2590
2860
  for (const tombstone of tombstones) {
2591
2861
  if (!tombstone.path) continue;
2592
2862
  add(tombstone.path);
2593
- if (tombstone.path === "/.keep" || tombstone.path.endsWith("/.keep") || tombstone.path.endsWith("/.keep.mtime")) {
2594
- const dir = tombstone.path.slice(0, tombstone.path.lastIndexOf("/")) || "/";
2595
- if (dir !== "/") add(dir);
2596
- }
2597
2863
  }
2598
2864
  }
2599
2865
  /** Invalidate the tombstone cache — call after tombstones are modified. */
2600
2866
  invalidateTombstoneCache() {
2601
2867
  this.tombstoneCache = null;
2602
2868
  }
2869
+ /**
2870
+ * 判定墓碑目标路径是否在删除之后被重新创建。
2871
+ *
2872
+ * 墓碑表达的是「删除意图」,但删除之后同一路径完全可能被再次写入。同步类工具
2873
+ * 的锁文件(`.sync.lock`)就是每轮「删除 → 重建」;若把墓碑当作永久否决权,
2874
+ * 这个路径会被每一轮 sync 反复删除,表现为「刚写进去 1 秒后就消失」、锁永远拿
2875
+ * 不到、深层目录刚建就没了。
2876
+ *
2877
+ * 判定依据是文件 mtime 晚于 `deletedAt`:写入必然刷新 mtime,因此 mtime 比删除
2878
+ * 时刻新就意味着这条墓碑已经被写操作撤销。
2879
+ */
2880
+ async isPathRecreatedAfterTombstone(tombstone) {
2881
+ const surfaces = [{ label: "local-cache", fs: this.cachedFS }];
2882
+ for (const [id, replica] of this.replicaBackends) {
2883
+ surfaces.push({ label: id, fs: replica.instance });
2884
+ }
2885
+ for (const surface of surfaces) {
2886
+ let mtimeMs;
2887
+ try {
2888
+ const inode = await surface.fs.stat(tombstone.path);
2889
+ mtimeMs = Number(inode?.mtimeMs ?? 0);
2890
+ } catch {
2891
+ continue;
2892
+ }
2893
+ if (mtimeMs > tombstone.deletedAt + TOMBSTONE_RECREATE_SKEW_MS) return true;
2894
+ }
2895
+ return false;
2896
+ }
2603
2897
  /**
2604
2898
  * Before sync: for each tombstone, delete the actual file on all replicas.
2605
2899
  * This prevents bi-directional sync from copying the file back.
@@ -2617,10 +2911,15 @@ var ConfigRepo = class {
2617
2911
  let processed = 0;
2618
2912
  let alreadyDeleted = 0;
2619
2913
  let unresolved = 0;
2914
+ const expired = [];
2620
2915
  for (const tombstone of tombstones) {
2621
2916
  const isKeepPlaceholder = tombstone.path === "/.keep" || tombstone.path.endsWith("/.keep");
2622
2917
  const forceDelete = isMtimeSidecar(tombstone.path) || isKeepPlaceholder;
2623
2918
  const tVersionPath = forceDelete ? null : versionPathFor(tombstone.path);
2919
+ if (!forceDelete && await this.isPathRecreatedAfterTombstone(tombstone)) {
2920
+ expired.push(tombstone);
2921
+ continue;
2922
+ }
2624
2923
  const sidecarOwner = sidecarOwnerPath(tombstone.path);
2625
2924
  const isKeepSidecar = sidecarOwner === "/.keep" || (sidecarOwner?.endsWith("/.keep") ?? false);
2626
2925
  const liveSidecarCandidate = sidecarOwner !== null && !isKeepSidecar;
@@ -2674,14 +2973,27 @@ var ConfigRepo = class {
2674
2973
  confirmed.add(replicaId);
2675
2974
  } else {
2676
2975
  unresolved++;
2677
- log3.warn(
2976
+ log4.warn(
2678
2977
  `[ConfigRepo] tombstone kept: ${tombstone.path} still present on replica ${replicaId}`
2679
2978
  );
2680
2979
  }
2681
2980
  }
2682
2981
  }
2982
+ if (expired.length > 0) {
2983
+ for (const tombstone of expired) {
2984
+ try {
2985
+ await this.cachedFS.unlink(tombstonePathFor(tombstone.path, TOMBSTONES_DIR));
2986
+ } catch {
2987
+ }
2988
+ }
2989
+ this.invalidateTombstoneCache();
2990
+ await this.readTombstones();
2991
+ log4.log(
2992
+ `[ConfigRepo] processTombstones: expired ${expired.length} tombstone(s) \u2014 path recreated after deletion`
2993
+ );
2994
+ }
2683
2995
  if (processed > 0 || alreadyDeleted > 0 || unresolved > 0) {
2684
- log3.log(
2996
+ log4.log(
2685
2997
  `[ConfigRepo] processTombstones: ${tombstones.length} tombstone(s), ${processed} deleted, ${alreadyDeleted} already gone, ${unresolved} unresolved`
2686
2998
  );
2687
2999
  }
@@ -2782,21 +3094,21 @@ var ConfigRepo = class {
2782
3094
  const innerBackendName = fs?.inner?.backendName;
2783
3095
  const directBackendName = fs?.backendName;
2784
3096
  const backendLabel = innerBackendName ?? directBackendName ?? innerBackend ?? ctorName;
2785
- log3.log(`[TOMB-TRACE] safeExists(${path}): fs type=${ctorName} backend=${backendLabel} hasExists=${hasExists} hasStat=${hasStat} inner=${innerBackend ?? "N/A"}`);
3097
+ log4.log(`[TOMB-TRACE] safeExists(${path}): fs type=${ctorName} backend=${backendLabel} hasExists=${hasExists} hasStat=${hasStat} inner=${innerBackend ?? "N/A"}`);
2786
3098
  if (hasExists) {
2787
- log3.log(`[TOMB-TRACE] safeExists(${path}): \u2192 calling fs.exists() [backend=${backendLabel}]`);
3099
+ log4.log(`[TOMB-TRACE] safeExists(${path}): \u2192 calling fs.exists() [backend=${backendLabel}]`);
2788
3100
  const result = await fs.exists(path);
2789
- log3.log(`[TOMB-TRACE] safeExists(${path}): \u2190 fs.exists() [backend=${backendLabel}] \u2192 ${result}`);
3101
+ log4.log(`[TOMB-TRACE] safeExists(${path}): \u2190 fs.exists() [backend=${backendLabel}] \u2192 ${result}`);
2790
3102
  return result;
2791
3103
  }
2792
- log3.log(`[TOMB-TRACE] safeExists(${path}): no exists(), calling fs.stat() [backend=${backendLabel}]`);
3104
+ log4.log(`[TOMB-TRACE] safeExists(${path}): no exists(), calling fs.stat() [backend=${backendLabel}]`);
2793
3105
  await fs.stat(path);
2794
- log3.log(`[TOMB-TRACE] safeExists(${path}): \u2190 fs.stat() [backend=${backendLabel}] \u2192 OK (exists)`);
3106
+ log4.log(`[TOMB-TRACE] safeExists(${path}): \u2190 fs.stat() [backend=${backendLabel}] \u2192 OK (exists)`);
2795
3107
  return true;
2796
3108
  } catch (err) {
2797
3109
  const errCode = err?.code ?? err?.status ?? "";
2798
3110
  const errName = err?.constructor?.name ?? "";
2799
- log3.log(`[TOMB-TRACE] safeExists(${path}): \u2190 ERROR ${errName} ${errCode} ${err?.message ?? err}`);
3111
+ log4.log(`[TOMB-TRACE] safeExists(${path}): \u2190 ERROR ${errName} ${errCode} ${err?.message ?? err}`);
2800
3112
  return false;
2801
3113
  }
2802
3114
  }
@@ -2823,13 +3135,13 @@ var ConfigRepo = class {
2823
3135
  this.assertNotDisposed();
2824
3136
  const result = await purgeMtimeSidecars(this.cachedFS, options);
2825
3137
  if (result.removed.length > 0) {
2826
- log3.log(
3138
+ log4.log(
2827
3139
  `[ConfigRepo] purged ${result.removed.length} .mtime sidecar(s) from local primary` + (options?.dryRun ? " (dry run)" : ""),
2828
3140
  result.removed
2829
3141
  );
2830
3142
  }
2831
3143
  if (result.failed.length > 0) {
2832
- log3.warn(`[ConfigRepo] failed to purge ${result.failed.length} .mtime sidecar(s):`, result.failed);
3144
+ log4.warn(`[ConfigRepo] failed to purge ${result.failed.length} .mtime sidecar(s):`, result.failed);
2833
3145
  }
2834
3146
  return result;
2835
3147
  }
@@ -2849,13 +3161,13 @@ var ConfigRepo = class {
2849
3161
  this.assertNotDisposed();
2850
3162
  const result = await purgeKeepFiles(this.cachedFS, options);
2851
3163
  if (result.removed.length > 0) {
2852
- log3.log(
3164
+ log4.log(
2853
3165
  `[ConfigRepo] purged ${result.removed.length} .keep placeholder(s) from local primary` + (options?.dryRun ? " (dry run)" : ""),
2854
3166
  result.removed
2855
3167
  );
2856
3168
  }
2857
3169
  if (result.failed.length > 0) {
2858
- log3.warn(`[ConfigRepo] failed to purge ${result.failed.length} .keep placeholder(s):`, result.failed);
3170
+ log4.warn(`[ConfigRepo] failed to purge ${result.failed.length} .keep placeholder(s):`, result.failed);
2859
3171
  }
2860
3172
  return result;
2861
3173
  }
@@ -2874,24 +3186,24 @@ var ConfigRepo = class {
2874
3186
  }));
2875
3187
  const result = await migrateVersionSidecars(this.cachedFS, { replicas });
2876
3188
  if (result.renamed.length > 0) {
2877
- log3.log(
3189
+ log4.log(
2878
3190
  `[ConfigRepo] migrated ${result.renamed.length} legacy version sidecar(s) to new naming`,
2879
3191
  result.renamed
2880
3192
  );
2881
3193
  }
2882
3194
  if (result.deleted.length > 0) {
2883
- log3.log(
3195
+ log4.log(
2884
3196
  `[ConfigRepo] removed ${result.deleted.length} orphaned legacy version sidecar(s)`,
2885
3197
  result.deleted
2886
3198
  );
2887
3199
  }
2888
3200
  if (result.remoteDeleted.length > 0) {
2889
- log3.log(
3201
+ log4.log(
2890
3202
  `[ConfigRepo] removed ${result.remoteDeleted.length} remote residual legacy version sidecar(s)`
2891
3203
  );
2892
3204
  }
2893
3205
  if (result.failed.length > 0) {
2894
- log3.warn(`[ConfigRepo] failed to migrate ${result.failed.length} legacy version sidecar(s):`, result.failed);
3206
+ log4.warn(`[ConfigRepo] failed to migrate ${result.failed.length} legacy version sidecar(s):`, result.failed);
2895
3207
  }
2896
3208
  return result;
2897
3209
  }
@@ -2914,9 +3226,9 @@ var ConfigRepo = class {
2914
3226
  */
2915
3227
  startBackgroundSync() {
2916
3228
  this.initialSyncPromise = this.initialSyncAndDedup().then(() => {
2917
- log3.log("[ConfigRepo] Background initial sync complete");
3229
+ log4.log("[ConfigRepo] Background initial sync complete");
2918
3230
  }).catch((err) => {
2919
- log3.error("[ConfigRepo] Background initial sync failed:", err);
3231
+ log4.error("[ConfigRepo] Background initial sync failed:", err);
2920
3232
  }).finally(() => {
2921
3233
  this.initialSyncPromise = null;
2922
3234
  });
@@ -2955,7 +3267,7 @@ var ConfigRepo = class {
2955
3267
  }
2956
3268
  }
2957
3269
  }
2958
- log3.log(`[ConfigRepo] updateTombstoneConfirmations: ${modified} tombstone(s) updated`);
3270
+ log4.log(`[ConfigRepo] updateTombstoneConfirmations: ${modified} tombstone(s) updated`);
2959
3271
  if (modified > 0) this.invalidateTombstoneCache();
2960
3272
  }
2961
3273
  /**
@@ -2993,7 +3305,12 @@ var ConfigRepo = class {
2993
3305
  const tombstones = await this.readTombstones();
2994
3306
  if (tombstones.length === 0) return;
2995
3307
  const allBackendIds = [...this.replicaBackends.keys()];
3308
+ let keptByRetention = 0;
2996
3309
  for (const tombstone of tombstones) {
3310
+ if (!isTombstoneRetentionElapsed(tombstone)) {
3311
+ keptByRetention++;
3312
+ continue;
3313
+ }
2997
3314
  const allConfirmed = await this.allReplicasConfirmAbsent(tombstone.path);
2998
3315
  if (allConfirmed) {
2999
3316
  const tombstonePath = tombstonePathFor(tombstone.path, TOMBSTONES_DIR);
@@ -3009,9 +3326,12 @@ var ConfigRepo = class {
3009
3326
  }
3010
3327
  }
3011
3328
  }
3012
- log3.log(`[ConfigRepo] gcTombstones: removed ${tombstonePath} (all ${allBackendIds.length} backends confirmed)`);
3329
+ log4.log(`[ConfigRepo] gcTombstones: removed ${tombstonePath} (all ${allBackendIds.length} backends confirmed)`);
3013
3330
  }
3014
3331
  }
3332
+ if (keptByRetention > 0) {
3333
+ log4.log(`[ConfigRepo] gcTombstones: kept ${keptByRetention} tombstone(s) within retention window`);
3334
+ }
3015
3335
  }
3016
3336
  /**
3017
3337
  * Sync .meta/ files (backends.json) to all replica backends.
@@ -3025,7 +3345,7 @@ var ConfigRepo = class {
3025
3345
  this.assertNotDisposed();
3026
3346
  const results = await this.flush();
3027
3347
  for (const result of results) {
3028
- log3.log(
3348
+ log4.log(
3029
3349
  `[ConfigRepo] syncMetaToReplicas: ${result.pairId} +${result.filesCreated}/~${result.filesUpdated}/-${result.filesDeleted} skip:${result.filesSkipped} ${result.durationMs}ms`
3030
3350
  );
3031
3351
  }
@@ -3198,21 +3518,21 @@ var ConfigRepo = class {
3198
3518
  // Internal — Setup
3199
3519
  // -----------------------------------------------------------------------
3200
3520
  async setupSync(backends, primaryBackendId, pollIntervalMs) {
3201
- log3.log(`[ConfigRepo] setupSync: ${backends.length} backends, primary=${primaryBackendId} pollInterval=${pollIntervalMs ?? "default"}ms`);
3521
+ log4.log(`[ConfigRepo] setupSync: ${backends.length} backends, primary=${primaryBackendId} pollInterval=${pollIntervalMs ?? "default"}ms`);
3202
3522
  for (const desc of backends) {
3203
3523
  if (desc.id === primaryBackendId) continue;
3204
3524
  if (desc.enabled === false) {
3205
- log3.log(`[ConfigRepo] Skipping disabled replica: ${desc.id}`);
3525
+ log4.log(`[ConfigRepo] Skipping disabled replica: ${desc.id}`);
3206
3526
  continue;
3207
3527
  }
3208
- log3.log(`[ConfigRepo] Creating replica backend: id=${desc.id}, type=${desc.type}`);
3528
+ log4.log(`[ConfigRepo] Creating replica backend: id=${desc.id}, type=${desc.type}`);
3209
3529
  try {
3210
3530
  const instance = await createBackend(desc);
3211
3531
  let fsInstance = instance;
3212
3532
  if (this.cacheOptions) {
3213
3533
  const { wrapWithCache: wrapWithCache2 } = await Promise.resolve().then(() => (init_cache_wrapper(), cache_wrapper_exports));
3214
3534
  fsInstance = wrapWithCache2(instance, desc.id, this.cacheOptions);
3215
- log3.log(`[ConfigRepo] Replica ${desc.id} wrapped with CachedFileSystem (store=${this.cacheOptions.storeType ?? "IdbCacheStore"})`);
3535
+ log4.log(`[ConfigRepo] Replica ${desc.id} wrapped with CachedFileSystem (store=${this.cacheOptions.storeType ?? "IdbCacheStore"})`);
3216
3536
  }
3217
3537
  const syncable = backendToSyncableFS(fsInstance, `${desc.type}(${desc.id})`);
3218
3538
  const pair = this.syncEngine.addPair(
@@ -3230,7 +3550,7 @@ var ConfigRepo = class {
3230
3550
  this.invalidateTombstoneCache();
3231
3551
  await this.processTombstones();
3232
3552
  } catch (err) {
3233
- log3.warn("[ConfigRepo] preSyncHook processTombstones failed:", err);
3553
+ log4.warn("[ConfigRepo] preSyncHook processTombstones failed:", err);
3234
3554
  }
3235
3555
  },
3236
3556
  postSyncHook: async () => {
@@ -3239,7 +3559,7 @@ var ConfigRepo = class {
3239
3559
  await this.processTombstones();
3240
3560
  await this.updateTombstoneConfirmations();
3241
3561
  } catch (err) {
3242
- log3.warn("[ConfigRepo] postSyncHook tombstone processing failed:", err);
3562
+ log4.warn("[ConfigRepo] postSyncHook tombstone processing failed:", err);
3243
3563
  }
3244
3564
  }
3245
3565
  },
@@ -3252,9 +3572,9 @@ var ConfigRepo = class {
3252
3572
  };
3253
3573
  this.syncEngine.on(pair.pairId, "conflict", conflictHandler);
3254
3574
  this.trackSyncErrors(desc.id, pair.pairId);
3255
- log3.log(`[ConfigRepo] Replica ${desc.id} created, sync pair=${pair.pairId}`);
3575
+ log4.log(`[ConfigRepo] Replica ${desc.id} created, sync pair=${pair.pairId}`);
3256
3576
  } catch (err) {
3257
- log3.error(`[ConfigRepo] Failed to create replica ${desc.id} (${desc.type}):`, err);
3577
+ log4.error(`[ConfigRepo] Failed to create replica ${desc.id} (${desc.type}):`, err);
3258
3578
  this.backendStates.set(desc.id, {
3259
3579
  backendId: desc.id,
3260
3580
  error: {
@@ -3264,8 +3584,8 @@ var ConfigRepo = class {
3264
3584
  });
3265
3585
  }
3266
3586
  }
3267
- log3.log(`[ConfigRepo] setupSync complete. Replicas:`, Array.from(this.replicaBackends.keys()));
3268
- log3.log(`[ConfigRepo] Sync statuses:`, this.getSyncStatuses());
3587
+ log4.log(`[ConfigRepo] setupSync complete. Replicas:`, Array.from(this.replicaBackends.keys()));
3588
+ log4.log(`[ConfigRepo] Sync statuses:`, this.getSyncStatuses());
3269
3589
  }
3270
3590
  // -----------------------------------------------------------------------
3271
3591
  // Internal — Persistence
@@ -3277,12 +3597,12 @@ var ConfigRepo = class {
3277
3597
  try {
3278
3598
  const existing = await readVersion(this.fullFS, vPath);
3279
3599
  if (existing && existing.hash === version.hash) {
3280
- log3.log("[ConfigRepo] skip version sidecar (hash unchanged):", vPath);
3600
+ log4.log("[ConfigRepo] skip version sidecar (hash unchanged):", vPath);
3281
3601
  return;
3282
3602
  }
3283
3603
  } catch {
3284
3604
  }
3285
- log3.log("[ConfigRepo] write version sidecar:", vPath, "v" + version.version);
3605
+ log4.log("[ConfigRepo] write version sidecar:", vPath, "v" + version.version);
3286
3606
  await this.ensureDir(vPath);
3287
3607
  await writeVersion(this.fullFS, vPath, version);
3288
3608
  }
@@ -3386,7 +3706,7 @@ var ConfigRepo = class {
3386
3706
  await this.resolveConflict(`${conflictId}/meta.json`, customMerge);
3387
3707
  }
3388
3708
  } catch (err) {
3389
- log3.error("[zen-fs-config] Conflict handler error:", err);
3709
+ log4.error("[zen-fs-config] Conflict handler error:", err);
3390
3710
  }
3391
3711
  }
3392
3712
  }
@@ -3502,11 +3822,11 @@ var ConfigRepo = class {
3502
3822
  }
3503
3823
  return { kind: "ok", desc, mtime };
3504
3824
  } else {
3505
- log3.warn(`[ConfigRepo] Backend descriptor ${entry} is missing id/type fields, marking for cleanup`);
3825
+ log4.warn(`[ConfigRepo] Backend descriptor ${entry} is missing id/type fields, marking for cleanup`);
3506
3826
  return { kind: "corrupt", filePath };
3507
3827
  }
3508
3828
  } catch (parseErr) {
3509
- log3.warn(`[ConfigRepo] Backend descriptor ${entry} has corrupted JSON: ${parseErr}. Marking for cleanup.`);
3829
+ log4.warn(`[ConfigRepo] Backend descriptor ${entry} has corrupted JSON: ${parseErr}. Marking for cleanup.`);
3510
3830
  return { kind: "corrupt", filePath };
3511
3831
  }
3512
3832
  })
@@ -3572,7 +3892,7 @@ var ConfigRepo = class {
3572
3892
  }
3573
3893
  }
3574
3894
  if (duplicates.length > 0) {
3575
- log3.log(
3895
+ log4.log(
3576
3896
  `[ConfigRepo] readAllBackendDescriptors: removing ${duplicates.length} duplicate(s): ${duplicates.join(", ")}`
3577
3897
  );
3578
3898
  for (const dupId of duplicates) {
@@ -3704,7 +4024,7 @@ var ConfigRepo = class {
3704
4024
  * Shared by addBackend() and replaceBackend().
3705
4025
  */
3706
4026
  async setupReplica(id, type, options, description) {
3707
- log3.log(`[ConfigRepo] addBackend: creating ${id} (${type})...`);
4027
+ log4.log(`[ConfigRepo] addBackend: creating ${id} (${type})...`);
3708
4028
  const instance = await createBackend({ type, options });
3709
4029
  const syncable = backendToSyncableFS(instance, `${type}(${id})`);
3710
4030
  const desc = { id, type, options, description };
@@ -3722,7 +4042,7 @@ var ConfigRepo = class {
3722
4042
  this.invalidateTombstoneCache();
3723
4043
  await this.processTombstones();
3724
4044
  } catch (err) {
3725
- log3.warn("[ConfigRepo] preSyncHook processTombstones failed:", err);
4045
+ log4.warn("[ConfigRepo] preSyncHook processTombstones failed:", err);
3726
4046
  }
3727
4047
  },
3728
4048
  postSyncHook: async () => {
@@ -3731,7 +4051,7 @@ var ConfigRepo = class {
3731
4051
  await this.processTombstones();
3732
4052
  await this.updateTombstoneConfirmations();
3733
4053
  } catch (err) {
3734
- log3.warn("[ConfigRepo] postSyncHook tombstone processing failed:", err);
4054
+ log4.warn("[ConfigRepo] postSyncHook tombstone processing failed:", err);
3735
4055
  }
3736
4056
  }
3737
4057
  },
@@ -3744,7 +4064,7 @@ var ConfigRepo = class {
3744
4064
  };
3745
4065
  this.syncEngine.on(pair.pairId, "conflict", conflictHandler);
3746
4066
  this.trackSyncErrors(id, pair.pairId);
3747
- log3.log(`[ConfigRepo] addBackend: ${id} (${type}) added, sync pair=${pair.pairId}`);
4067
+ log4.log(`[ConfigRepo] addBackend: ${id} (${type}) added, sync pair=${pair.pairId}`);
3748
4068
  await this.syncMetaToReplicas();
3749
4069
  this.syncEngine.watch(pair.pairId);
3750
4070
  return pair.pairId;
@@ -3770,13 +4090,13 @@ var ConfigRepo = class {
3770
4090
  }
3771
4091
  }
3772
4092
  this.syncEngine.removePair(replica.pairId);
3773
- log3.log(`[ConfigRepo] removeBackend: sync pair ${replica.pairId} removed`);
4093
+ log4.log(`[ConfigRepo] removeBackend: sync pair ${replica.pairId} removed`);
3774
4094
  this.replicaBackends.delete(id);
3775
4095
  if (replica.instance?.dispose) {
3776
4096
  await replica.instance.dispose();
3777
4097
  }
3778
4098
  } else {
3779
- log3.log(`[ConfigRepo] removeBackend: "${id}" not in replicaBackends, cleaning up descriptor only`);
4099
+ log4.log(`[ConfigRepo] removeBackend: "${id}" not in replicaBackends, cleaning up descriptor only`);
3780
4100
  for (const descPath of descPaths) {
3781
4101
  try {
3782
4102
  await this.deleteFile(descPath);
@@ -3787,7 +4107,7 @@ var ConfigRepo = class {
3787
4107
  }
3788
4108
  this.backendStates.delete(id);
3789
4109
  this.schedulePostDeleteSync();
3790
- log3.log(`[ConfigRepo] removeBackend: ${id} removed (tombstone written, remote cleaned)`);
4110
+ log4.log(`[ConfigRepo] removeBackend: ${id} removed (tombstone written, remote cleaned)`);
3791
4111
  }
3792
4112
  /**
3793
4113
  * Replace a config-sync backend's parameters in place (same id).
@@ -3834,11 +4154,11 @@ var ConfigRepo = class {
3834
4154
  await this.setupReplica(id, type, options, description ?? before.description);
3835
4155
  } catch (err) {
3836
4156
  const reason = err instanceof Error ? err.message : String(err);
3837
- log3.warn(`[ConfigRepo] replaceBackend: "${id}" failed, rolling back old options:`, err);
4157
+ log4.warn(`[ConfigRepo] replaceBackend: "${id}" failed, rolling back old options:`, err);
3838
4158
  try {
3839
4159
  await this.setupReplica(id, before.type, before.options, before.description);
3840
4160
  } catch (rollbackErr) {
3841
- log3.error(`[ConfigRepo] replaceBackend: rollback for "${id}" ALSO failed:`, rollbackErr);
4161
+ log4.error(`[ConfigRepo] replaceBackend: rollback for "${id}" ALSO failed:`, rollbackErr);
3842
4162
  }
3843
4163
  throw new Error(`\u66F4\u65B0\u540E\u7AEF\u53C2\u6570\u5931\u8D25\uFF1A${reason}\uFF08\u5DF2\u5C1D\u8BD5\u56DE\u6EDA\u65E7\u53C2\u6570\uFF09`);
3844
4164
  }
@@ -3854,7 +4174,7 @@ var ConfigRepo = class {
3854
4174
  const existing = await this.cachedFS.readFile(path, "utf-8");
3855
4175
  const current = existing.trim();
3856
4176
  if (current && current !== type) {
3857
- log3.warn(`[ConfigRepo] group-type already set to "${current}" at ${path}, ignoring request to set "${type}"`);
4177
+ log4.warn(`[ConfigRepo] group-type already set to "${current}" at ${path}, ignoring request to set "${type}"`);
3858
4178
  return;
3859
4179
  }
3860
4180
  } catch {
@@ -3885,7 +4205,7 @@ var ConfigRepo = class {
3885
4205
  features: existingDescriptor.features ?? CONFIG_GROUP_FEATURES
3886
4206
  });
3887
4207
  }
3888
- log3.log(`[ConfigRepo] group-type set to "${type}"`);
4208
+ log4.log(`[ConfigRepo] group-type set to "${type}"`);
3889
4209
  }
3890
4210
  /** Read the group-type marker. Returns null if not set (new path, then legacy). */
3891
4211
  async getGroupType() {
@@ -3980,7 +4300,7 @@ var ConfigRepo = class {
3980
4300
  if (this.appDataGroups.has(id)) {
3981
4301
  throw new Error(`App data group "${id}" already exists. Use removeAppDataGroup() first.`);
3982
4302
  }
3983
- log3.log(`[ConfigRepo] createAppDataGroup: creating "${id}" with ${backends.length} backend(s)`);
4303
+ log4.log(`[ConfigRepo] createAppDataGroup: creating "${id}" with ${backends.length} backend(s)`);
3984
4304
  const resolvedBackends = [];
3985
4305
  for (const desc of backends) {
3986
4306
  assertValidBackendId(desc.id);
@@ -4007,7 +4327,7 @@ var ConfigRepo = class {
4007
4327
  };
4008
4328
  await this.writeAppDataGroupDescriptorFile(id, descriptor);
4009
4329
  this.appDataGroups.set(id, group);
4010
- log3.log(`[ConfigRepo] createAppDataGroup: "${id}" created`);
4330
+ log4.log(`[ConfigRepo] createAppDataGroup: "${id}" created`);
4011
4331
  return group;
4012
4332
  }
4013
4333
  /**
@@ -4050,7 +4370,7 @@ var ConfigRepo = class {
4050
4370
  try {
4051
4371
  await live.writeOwnGroupDescriptor();
4052
4372
  } catch (err) {
4053
- log3.warn(`[ConfigRepo] updateAppDataGroupName: "${id}" group.json update failed:`, err);
4373
+ log4.warn(`[ConfigRepo] updateAppDataGroupName: "${id}" group.json update failed:`, err);
4054
4374
  }
4055
4375
  }
4056
4376
  const descriptor = {
@@ -4113,7 +4433,7 @@ var ConfigRepo = class {
4113
4433
  return group;
4114
4434
  } catch (err) {
4115
4435
  const reason = err instanceof Error ? err.message : String(err);
4116
- log3.warn(`[ConfigRepo] replaceAppDataGroupBackend: "${backendId}" failed, rolling back:`, err);
4436
+ log4.warn(`[ConfigRepo] replaceAppDataGroupBackend: "${backendId}" failed, rolling back:`, err);
4117
4437
  try {
4118
4438
  const restored = new AppDataGroupImpl(
4119
4439
  groupId,
@@ -4127,7 +4447,7 @@ var ConfigRepo = class {
4127
4447
  await this.updateAppDataGroupDescriptor(groupId, restored.listDeclaredBackends());
4128
4448
  this.appDataGroups.set(groupId, restored);
4129
4449
  } catch (rollbackErr) {
4130
- log3.error("[ConfigRepo] replaceAppDataGroupBackend: rollback ALSO failed:", rollbackErr);
4450
+ log4.error("[ConfigRepo] replaceAppDataGroupBackend: rollback ALSO failed:", rollbackErr);
4131
4451
  }
4132
4452
  throw new Error(`\u66F4\u65B0\u540E\u7AEF\u53C2\u6570\u5931\u8D25\uFF1A${reason}\uFF08\u5DF2\u5C1D\u8BD5\u56DE\u6EDA\u65E7\u53C2\u6570\uFF09`);
4133
4453
  }
@@ -4245,7 +4565,7 @@ var ConfigRepo = class {
4245
4565
  try {
4246
4566
  await this.deleteFile(descPath);
4247
4567
  } catch (err) {
4248
- log3.log(`[ConfigRepo] removeAppDataGroup: deleteFile failed for "${id}" at ${descPath}:`, err);
4568
+ log4.log(`[ConfigRepo] removeAppDataGroup: deleteFile failed for "${id}" at ${descPath}:`, err);
4249
4569
  try {
4250
4570
  await this.cachedFS.unlink(descPath);
4251
4571
  } catch {
@@ -4253,7 +4573,7 @@ var ConfigRepo = class {
4253
4573
  await this.unlinkVersionSidecar(this.cachedFS, descPath);
4254
4574
  }
4255
4575
  }
4256
- log3.log(`[ConfigRepo] removeAppDataGroup: "${id}" removed`);
4576
+ log4.log(`[ConfigRepo] removeAppDataGroup: "${id}" removed`);
4257
4577
  }
4258
4578
  async listAccountBackends() {
4259
4579
  this.assertNotDisposed();
@@ -4416,36 +4736,50 @@ var AppDataGroupImpl = class {
4416
4736
  });
4417
4737
  }
4418
4738
  async init() {
4739
+ const storeName = dataGroupLocalStoreName(this.appId, this.groupId);
4419
4740
  try {
4420
4741
  const localPrimary = await resolveLocalPrimary(this.appId, "data", {
4421
4742
  groupId: this.groupId,
4422
- ...this.groupId === "default" ? {} : { idbStoreName: `zen-fs-config-data-${this.appId}-${this.groupId}` }
4743
+ ...this.groupId === "default" ? {} : { idbStoreName: storeName }
4423
4744
  });
4424
4745
  this.localFS = await createBackend(localPrimary);
4425
- } catch {
4426
- throw new Error(`Failed to create local primary for data group "${this.groupId}"`);
4746
+ } catch (err) {
4747
+ if (isLocalStorageUnavailableError(err)) {
4748
+ throw new LocalStorageUnavailableError({
4749
+ appId: this.appId,
4750
+ groupId: this.groupId,
4751
+ storeName,
4752
+ cause: err
4753
+ });
4754
+ }
4755
+ const detail = summarizeError(err);
4756
+ const wrapped = new Error(
4757
+ `Failed to create local primary for data group "${this.groupId}" (${[detail.name, detail.code, detail.message].filter(Boolean).join(": ")})`,
4758
+ { cause: err }
4759
+ );
4760
+ throw wrapped;
4427
4761
  }
4428
4762
  try {
4429
4763
  const purged = await purgeMtimeSidecars(this.localFS);
4430
4764
  if (purged.removed.length > 0) {
4431
- log3.warn(
4765
+ log4.warn(
4432
4766
  `[AppDataGroup:${this.groupId}] purged ${purged.removed.length} leaked .mtime sidecar(s):`,
4433
4767
  purged.removed
4434
4768
  );
4435
4769
  }
4436
4770
  } catch (err) {
4437
- log3.warn(`[AppDataGroup:${this.groupId}] .mtime purge failed:`, err?.message ?? err);
4771
+ log4.warn(`[AppDataGroup:${this.groupId}] .mtime purge failed:`, err?.message ?? err);
4438
4772
  }
4439
4773
  try {
4440
4774
  const purgedKeep = await purgeKeepFiles(this.localFS);
4441
4775
  if (purgedKeep.removed.length > 0) {
4442
- log3.warn(
4776
+ log4.warn(
4443
4777
  `[AppDataGroup:${this.groupId}] purged ${purgedKeep.removed.length} leaked .keep placeholder(s):`,
4444
4778
  purgedKeep.removed
4445
4779
  );
4446
4780
  }
4447
4781
  } catch (err) {
4448
- log3.warn(`[AppDataGroup:${this.groupId}] .keep purge failed:`, err?.message ?? err);
4782
+ log4.warn(`[AppDataGroup:${this.groupId}] .keep purge failed:`, err?.message ?? err);
4449
4783
  }
4450
4784
  const localSyncable = backendToSyncableFS(this.localFS, `local(${this.groupId})`);
4451
4785
  this.tombstones = new TombstoneStore(this.localFS, this.localBackendId);
@@ -4455,13 +4789,13 @@ var AppDataGroupImpl = class {
4455
4789
  try {
4456
4790
  backendsChanged = await this.loadBackendDescriptors();
4457
4791
  } catch (err) {
4458
- log3.warn(`[AppDataGroup:${this.groupId}] failed to load .meta/backends:`, err);
4792
+ log4.warn(`[AppDataGroup:${this.groupId}] failed to load .meta/backends:`, err);
4459
4793
  this._backends = this._backends ?? [];
4460
4794
  }
4461
4795
  try {
4462
4796
  await this.writeOwnGroupDescriptor();
4463
4797
  } catch (err) {
4464
- log3.warn(`[AppDataGroup:${this.groupId}] failed to write .meta/group.json:`, err);
4798
+ log4.warn(`[AppDataGroup:${this.groupId}] failed to write .meta/group.json:`, err);
4465
4799
  }
4466
4800
  this.fs = createChrootFS(this.localFS, "/", {
4467
4801
  hiddenPrefixes: [META_DIR, CONFIG_DIR],
@@ -4471,7 +4805,7 @@ var AppDataGroupImpl = class {
4471
4805
  });
4472
4806
  const { kept, removed } = dedupeAppDataBackends(this._backends);
4473
4807
  if (removed.length > 0) {
4474
- log3.warn(
4808
+ log4.warn(
4475
4809
  `[AppDataGroup:${this.groupId}] dedupe: removing ${removed.length} duplicate backend(s) (${removed.map((b) => b.id).join(", ")}) \u2014 keeping ${kept.map((b) => b.id).join(", ")}`
4476
4810
  );
4477
4811
  this._backends = kept;
@@ -4485,7 +4819,7 @@ var AppDataGroupImpl = class {
4485
4819
  features: this._declaredFeatures
4486
4820
  });
4487
4821
  } catch (err) {
4488
- log3.warn(`[AppDataGroup:${this.groupId}] failed to persist backend topology:`, err);
4822
+ log4.warn(`[AppDataGroup:${this.groupId}] failed to persist backend topology:`, err);
4489
4823
  }
4490
4824
  }
4491
4825
  for (const desc of this._backends) {
@@ -4517,26 +4851,26 @@ var AppDataGroupImpl = class {
4517
4851
  if (this.features.conflicts) {
4518
4852
  const conflictHandler = (event) => {
4519
4853
  this.archiveConflict(event).catch((err) => {
4520
- log3.warn(`[AppDataGroup:${this.groupId}] conflict archive failed:`, err);
4854
+ log4.warn(`[AppDataGroup:${this.groupId}] conflict archive failed:`, err);
4521
4855
  });
4522
4856
  };
4523
4857
  this.syncEngine.on(pair.pairId, "conflict", conflictHandler);
4524
4858
  }
4525
4859
  this.trackSyncErrors(desc.id, pair.pairId);
4526
- log3.log(`[AppDataGroup:${this.groupId}] backend ${desc.id} (${desc.type}) connected, pair=${pair.pairId}`);
4860
+ log4.log(`[AppDataGroup:${this.groupId}] backend ${desc.id} (${desc.type}) connected, pair=${pair.pairId}`);
4527
4861
  } catch (err) {
4528
4862
  const message = err instanceof Error ? err.message : String(err);
4529
4863
  this.backendStates.set(desc.id, {
4530
4864
  backendId: desc.id,
4531
4865
  error: { message, timestamp: Date.now() }
4532
4866
  });
4533
- log3.error(`[AppDataGroup:${this.groupId}] Failed to create backend ${desc.id} (${desc.type}):`, err);
4867
+ log4.error(`[AppDataGroup:${this.groupId}] Failed to create backend ${desc.id} (${desc.type}):`, err);
4534
4868
  }
4535
4869
  }
4536
4870
  try {
4537
4871
  await this.syncEngine.syncAll();
4538
4872
  } catch (err) {
4539
- log3.warn(`[AppDataGroup:${this.groupId}] Initial sync failed:`, err);
4873
+ log4.warn(`[AppDataGroup:${this.groupId}] Initial sync failed:`, err);
4540
4874
  }
4541
4875
  this.syncEngine.watchAll();
4542
4876
  }
@@ -4551,7 +4885,7 @@ var AppDataGroupImpl = class {
4551
4885
  try {
4552
4886
  await this.tombstones.gc(this.allBackendIds(), this.tombstoneTargets());
4553
4887
  } catch (err) {
4554
- log3.warn(`[AppDataGroup:${this.groupId}] tombstone GC failed:`, err);
4888
+ log4.warn(`[AppDataGroup:${this.groupId}] tombstone GC failed:`, err);
4555
4889
  }
4556
4890
  return Array.from(results.values());
4557
4891
  }
@@ -4586,7 +4920,7 @@ var AppDataGroupImpl = class {
4586
4920
  const bytes = typeof data === "string" ? new TextEncoder().encode(data) : toUint8Array2(data);
4587
4921
  await this.versions.record(path, bytes);
4588
4922
  } catch (err) {
4589
- log3.warn(`[AppDataGroup:${this.groupId}] version record failed for ${path}:`, err);
4923
+ log4.warn(`[AppDataGroup:${this.groupId}] version record failed for ${path}:`, err);
4590
4924
  }
4591
4925
  }
4592
4926
  /** Delete tombstoned files on local + every connected backend before/after sync. */
@@ -4594,14 +4928,14 @@ var AppDataGroupImpl = class {
4594
4928
  try {
4595
4929
  await this.tombstones.process(this.tombstoneTargets());
4596
4930
  } catch (err) {
4597
- log3.warn(`[AppDataGroup:${this.groupId}] ${stage} tombstone pass failed:`, err);
4931
+ log4.warn(`[AppDataGroup:${this.groupId}] ${stage} tombstone pass failed:`, err);
4598
4932
  }
4599
4933
  }
4600
4934
  async confirmTombstones() {
4601
4935
  try {
4602
4936
  await this.tombstones.confirm(this.allBackendIds());
4603
4937
  } catch (err) {
4604
- log3.warn(`[AppDataGroup:${this.groupId}] tombstone confirmations failed:`, err);
4938
+ log4.warn(`[AppDataGroup:${this.groupId}] tombstone confirmations failed:`, err);
4605
4939
  }
4606
4940
  }
4607
4941
  /** Write a tombstone for `filePath`. Records metadata only — it never creates the file. */
@@ -4634,7 +4968,7 @@ var AppDataGroupImpl = class {
4634
4968
  }
4635
4969
  await removeDirectoryTree(this.localFS, normalized);
4636
4970
  this.schedulePostDeleteSync();
4637
- log3.log(`[AppDataGroup:${this.groupId}] deleteFile(directory): ${normalized} (${files.length} file(s))`);
4971
+ log4.log(`[AppDataGroup:${this.groupId}] deleteFile(directory): ${normalized} (${files.length} file(s))`);
4638
4972
  return;
4639
4973
  }
4640
4974
  await this.writeTombstoneFor(normalized);
@@ -4673,7 +5007,7 @@ var AppDataGroupImpl = class {
4673
5007
  try {
4674
5008
  await this.syncEngine.syncAll();
4675
5009
  } catch (err) {
4676
- log3.warn(`[AppDataGroup:${this.groupId}] sync after conflict resolve failed:`, err);
5010
+ log4.warn(`[AppDataGroup:${this.groupId}] sync after conflict resolve failed:`, err);
4677
5011
  }
4678
5012
  }
4679
5013
  readConflictBackup(conflictId, fileType) {
@@ -4708,7 +5042,7 @@ var AppDataGroupImpl = class {
4708
5042
  if (this.dataBackends.has(id)) {
4709
5043
  throw new Error(`Backend "${id}" already exists in data group "${this.groupId}"`);
4710
5044
  }
4711
- log3.log(`[AppDataGroup:${this.groupId}] addBackend: creating ${id} (${type})...`);
5045
+ log4.log(`[AppDataGroup:${this.groupId}] addBackend: creating ${id} (${type})...`);
4712
5046
  const instance = await createBackend({ type, options });
4713
5047
  const syncable = backendToSyncableFS(instance, `${type}(${id})`);
4714
5048
  const localSyncable = backendToSyncableFS(this.localFS, `local(${this.groupId})`);
@@ -4736,13 +5070,13 @@ var AppDataGroupImpl = class {
4736
5070
  if (this.features.conflicts) {
4737
5071
  this.syncEngine.on(pair.pairId, "conflict", (event) => {
4738
5072
  this.archiveConflict(event).catch((err) => {
4739
- log3.warn(`[AppDataGroup:${this.groupId}] conflict archive failed:`, err);
5073
+ log4.warn(`[AppDataGroup:${this.groupId}] conflict archive failed:`, err);
4740
5074
  });
4741
5075
  });
4742
5076
  }
4743
5077
  this.trackSyncErrors(id, pair.pairId);
4744
5078
  this._backends = [...this._backends.filter((b) => b.id !== id), desc];
4745
- log3.log(`[AppDataGroup:${this.groupId}] addBackend: ${id} (${type}) connected, pair=${pair.pairId}`);
5079
+ log4.log(`[AppDataGroup:${this.groupId}] addBackend: ${id} (${type}) connected, pair=${pair.pairId}`);
4746
5080
  try {
4747
5081
  const stale = (await this.tombstones.list()).find(
4748
5082
  (t) => t.path === backendMetaFilePath(id)
@@ -4750,12 +5084,12 @@ var AppDataGroupImpl = class {
4750
5084
  if (stale) await this.tombstones.remove(stale);
4751
5085
  await writeBackendMetaDescriptor(this.localFS, desc);
4752
5086
  } catch (err) {
4753
- log3.warn(`[AppDataGroup:${this.groupId}] addBackend: failed to write .meta/backends/${id}.json:`, err);
5087
+ log4.warn(`[AppDataGroup:${this.groupId}] addBackend: failed to write .meta/backends/${id}.json:`, err);
4754
5088
  }
4755
5089
  try {
4756
5090
  await this.syncEngine.sync(pair.pairId);
4757
5091
  } catch (err) {
4758
- log3.warn(`[AppDataGroup:${this.groupId}] addBackend: initial sync failed for ${id}:`, err);
5092
+ log4.warn(`[AppDataGroup:${this.groupId}] addBackend: initial sync failed for ${id}:`, err);
4759
5093
  }
4760
5094
  this.syncEngine.watch(pair.pairId);
4761
5095
  await this.parent.updateAppDataGroupDescriptor(this.groupId, this._backends, {
@@ -4786,7 +5120,7 @@ var AppDataGroupImpl = class {
4786
5120
  if (backend?.instance?.dispose) {
4787
5121
  await backend.instance.dispose();
4788
5122
  }
4789
- log3.log(`[AppDataGroup:${this.groupId}] removeBackend: ${id} removed`);
5123
+ log4.log(`[AppDataGroup:${this.groupId}] removeBackend: ${id} removed`);
4790
5124
  }
4791
5125
  listBackends() {
4792
5126
  return Array.from(this.dataBackends.values()).map((b) => b.desc);
@@ -4828,44 +5162,44 @@ async function createConfigRepo(appId, options = {}) {
4828
5162
  idbStoreName: options.idbStoreName,
4829
5163
  folderPath: options.folderPath
4830
5164
  });
4831
- log3.log(`[createConfigRepo] Creating local primary (type: ${localPrimary.type})...`);
5165
+ log4.log(`[createConfigRepo] Creating local primary (type: ${localPrimary.type})...`);
4832
5166
  const primaryInstance = await createBackend(localPrimary);
4833
5167
  const cachedFS = primaryInstance;
4834
5168
  if (options.purgeMtimeSidecars !== false) {
4835
5169
  try {
4836
5170
  const purged = await purgeMtimeSidecars(cachedFS);
4837
5171
  if (purged.removed.length > 0) {
4838
- log3.warn(
5172
+ log4.warn(
4839
5173
  `[createConfigRepo] purged ${purged.removed.length} leaked .mtime sidecar(s) from local primary:`,
4840
5174
  purged.removed
4841
5175
  );
4842
5176
  }
4843
5177
  } catch (err) {
4844
- log3.warn(`[createConfigRepo] .mtime purge failed:`, err?.message ?? err);
5178
+ log4.warn(`[createConfigRepo] .mtime purge failed:`, err?.message ?? err);
4845
5179
  }
4846
5180
  }
4847
5181
  if (options.purgeKeepFiles !== false) {
4848
5182
  try {
4849
5183
  const purged = await purgeKeepFiles(cachedFS);
4850
5184
  if (purged.removed.length > 0) {
4851
- log3.warn(
5185
+ log4.warn(
4852
5186
  `[createConfigRepo] purged ${purged.removed.length} leaked .keep placeholder(s) from local primary:`,
4853
5187
  purged.removed
4854
5188
  );
4855
5189
  }
4856
5190
  } catch (err) {
4857
- log3.warn(`[createConfigRepo] .keep purge failed:`, err?.message ?? err);
5191
+ log4.warn(`[createConfigRepo] .keep purge failed:`, err?.message ?? err);
4858
5192
  }
4859
5193
  }
4860
5194
  const cacheOptions = options.cache === false ? void 0 : options.cache ?? {};
4861
5195
  try {
4862
5196
  await primaryInstance.mkdir(META_DIR);
4863
- log3.log(`[createConfigRepo] /.meta/ ready`);
5197
+ log4.log(`[createConfigRepo] /.meta/ ready`);
4864
5198
  } catch (err) {
4865
5199
  const msg = err.message || "";
4866
5200
  if (msg.includes("File exists") || msg.includes("EEXIST") || err.code === "EEXIST") {
4867
5201
  } else {
4868
- log3.error(`[createConfigRepo] Failed to ensure /.meta/:`, err.message);
5202
+ log4.error(`[createConfigRepo] Failed to ensure /.meta/:`, err.message);
4869
5203
  }
4870
5204
  }
4871
5205
  try {
@@ -4876,7 +5210,7 @@ async function createConfigRepo(appId, options = {}) {
4876
5210
  } catch {
4877
5211
  await ensureParentDir2(primaryInstance, path);
4878
5212
  await primaryInstance.writeFile(path, groupTypeBytes);
4879
- log3.log(`[createConfigRepo] group-type set to "config-sync" at ${path}`);
5213
+ log4.log(`[createConfigRepo] group-type set to "config-sync" at ${path}`);
4880
5214
  }
4881
5215
  }
4882
5216
  if (!await readGroupDescriptor(primaryInstance)) {
@@ -4888,7 +5222,7 @@ async function createConfigRepo(appId, options = {}) {
4888
5222
  });
4889
5223
  }
4890
5224
  } catch (err) {
4891
- log3.warn(`[createConfigRepo] Failed to write group metadata:`, err.message);
5225
+ log4.warn(`[createConfigRepo] Failed to write group metadata:`, err.message);
4892
5226
  }
4893
5227
  const tempRepo = new ConfigRepo(
4894
5228
  appId,
@@ -4902,11 +5236,11 @@ async function createConfigRepo(appId, options = {}) {
4902
5236
  );
4903
5237
  const oldBackendsMeta = await tempRepo.readMetaFile(BACKENDS_FILE);
4904
5238
  if (oldBackendsMeta && oldBackendsMeta.backends?.length > 0) {
4905
- log3.log(`[createConfigRepo] Migrating ${oldBackendsMeta.backends.length} backend(s) from backends.json to individual files...`);
5239
+ log4.log(`[createConfigRepo] Migrating ${oldBackendsMeta.backends.length} backend(s) from backends.json to individual files...`);
4906
5240
  await tempRepo.ensureDir(`${BACKENDS_DIR}/.keep`);
4907
5241
  for (const desc of oldBackendsMeta.backends) {
4908
5242
  if (desc.id === LOCAL_IDB_BACKEND_ID) {
4909
- log3.log(`[createConfigRepo] Skipping local backend ${desc.id} during migration`);
5243
+ log4.log(`[createConfigRepo] Skipping local backend ${desc.id} during migration`);
4910
5244
  continue;
4911
5245
  }
4912
5246
  await tempRepo.writeBackendDescriptor(desc);
@@ -4924,7 +5258,7 @@ async function createConfigRepo(appId, options = {}) {
4924
5258
  }
4925
5259
  }
4926
5260
  }
4927
- log3.log(`[createConfigRepo] Migration complete`);
5261
+ log4.log(`[createConfigRepo] Migration complete`);
4928
5262
  }
4929
5263
  let allBackends = await tempRepo.readAllBackendDescriptors();
4930
5264
  if (options.backendInfo) {
@@ -4942,19 +5276,19 @@ async function createConfigRepo(appId, options = {}) {
4942
5276
  type: options.backendInfo.type,
4943
5277
  options: options.backendInfo.options
4944
5278
  });
4945
- log3.log(`[createConfigRepo] Added replica backend: ${replicaId} (${options.backendInfo.type})`);
5279
+ log4.log(`[createConfigRepo] Added replica backend: ${replicaId} (${options.backendInfo.type})`);
4946
5280
  allBackends = [...allBackends, { id: replicaId, type: options.backendInfo.type, options: options.backendInfo.options }];
4947
5281
  } else if (dupConfig) {
4948
- log3.log(`[createConfigRepo] Replica with same config already registered as "${dupConfig.id}", skipping`);
5282
+ log4.log(`[createConfigRepo] Replica with same config already registered as "${dupConfig.id}", skipping`);
4949
5283
  } else {
4950
- log3.log(`[createConfigRepo] Replica ${replicaId} already registered`);
5284
+ log4.log(`[createConfigRepo] Replica ${replicaId} already registered`);
4951
5285
  }
4952
5286
  }
4953
- log3.log(`[createConfigRepo] Replica backends: ${allBackends.map((b) => b.id).join(", ") || "(none)"}`);
5287
+ log4.log(`[createConfigRepo] Replica backends: ${allBackends.map((b) => b.id).join(", ") || "(none)"}`);
4954
5288
  let nodeId = options.nodeId;
4955
5289
  if (!nodeId) {
4956
5290
  nodeId = `node-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
4957
- log3.log(`[createConfigRepo] Generated nodeId: ${nodeId}`);
5291
+ log4.log(`[createConfigRepo] Generated nodeId: ${nodeId}`);
4958
5292
  }
4959
5293
  const serializer = createSerializerChain(options.serializer);
4960
5294
  const repo = new ConfigRepo(
@@ -4977,19 +5311,19 @@ async function createConfigRepo(appId, options = {}) {
4977
5311
  try {
4978
5312
  const mig = await repo.migrateLegacyVersionSidecars();
4979
5313
  if (mig.renamed.length === 0 && mig.deleted.length === 0 && mig.remoteDeleted.length === 0) {
4980
- log3.log("[createConfigRepo] no legacy version sidecars to migrate");
5314
+ log4.log("[createConfigRepo] no legacy version sidecars to migrate");
4981
5315
  }
4982
5316
  } catch (err) {
4983
- log3.warn(`[createConfigRepo] version sidecar migration failed:`, err?.message ?? err);
5317
+ log4.warn(`[createConfigRepo] version sidecar migration failed:`, err?.message ?? err);
4984
5318
  }
4985
5319
  }
4986
5320
  await repo.load();
4987
5321
  if (repo.replicaCount > 0) {
4988
- log3.log("[createConfigRepo] Starting background initial sync + dedup...");
5322
+ log4.log("[createConfigRepo] Starting background initial sync + dedup...");
4989
5323
  repo.startBackgroundSync();
4990
5324
  }
4991
5325
  repo.syncMetaToReplicas().catch((err) => {
4992
- log3.error("[createConfigRepo] background syncMetaToReplicas failed:", err);
5326
+ log4.error("[createConfigRepo] background syncMetaToReplicas failed:", err);
4993
5327
  });
4994
5328
  return repo;
4995
5329
  }
@@ -5003,11 +5337,11 @@ function sidecarOwnerPath(path) {
5003
5337
 
5004
5338
  // src/connect.ts
5005
5339
  init_backend_registry();
5006
- var log4 = createLogger("connect");
5340
+ var log5 = createLogger2("connect");
5007
5341
  var GROUP_TYPE_FILE2 = "/.config/group-type";
5008
5342
  var LEGACY_GROUP_TYPE_FILE2 = "/.meta/group-type";
5009
5343
  async function detectGroupType(type, options) {
5010
- log4(`detectGroupType: connecting to ${type}...`);
5344
+ log5(`detectGroupType: connecting to ${type}...`);
5011
5345
  const tempBackend = await createBackend({ type, options });
5012
5346
  try {
5013
5347
  for (const path of [GROUP_TYPE_FILE2, LEGACY_GROUP_TYPE_FILE2]) {
@@ -5015,15 +5349,15 @@ async function detectGroupType(type, options) {
5015
5349
  const raw = await tempBackend.readFile(path, "utf-8");
5016
5350
  const groupType = raw.trim();
5017
5351
  if (groupType === "config-sync" || groupType === "data-sync") {
5018
- log4(`detectGroupType: detected "${groupType}" at ${path}`);
5352
+ log5(`detectGroupType: detected "${groupType}" at ${path}`);
5019
5353
  return groupType;
5020
5354
  }
5021
- log4(`detectGroupType: unknown group-type value "${groupType}" at ${path}, treating as null`);
5355
+ log5(`detectGroupType: unknown group-type value "${groupType}" at ${path}, treating as null`);
5022
5356
  return null;
5023
5357
  } catch {
5024
5358
  }
5025
5359
  }
5026
- log4(`detectGroupType: no group-type file found (new backend)`);
5360
+ log5(`detectGroupType: no group-type file found (new backend)`);
5027
5361
  return null;
5028
5362
  } finally {
5029
5363
  if (tempBackend?.dispose) {
@@ -5032,7 +5366,7 @@ async function detectGroupType(type, options) {
5032
5366
  }
5033
5367
  }
5034
5368
  async function connect(appId, options = {}) {
5035
- log4(`connect: appId=${appId}`);
5369
+ log5(`connect: appId=${appId}`);
5036
5370
  if (!options.backendInfo) {
5037
5371
  const repo2 = await createConfigRepo(appId, {
5038
5372
  idbStoreName: options.idbStoreName,
@@ -5050,12 +5384,12 @@ async function connect(appId, options = {}) {
5050
5384
  try {
5051
5385
  appDataGroups2.push(await repo2.getAppDataGroup(d.id));
5052
5386
  } catch (err) {
5053
- log4(`connect: failed to load app data group "${d.id}":`, err);
5387
+ log5(`connect: failed to load app data group "${d.id}":`, err);
5054
5388
  }
5055
5389
  }
5056
5390
  const dataGroup2 = appDataGroups2[0];
5057
5391
  if (!dataGroup2 && descriptors2.length > 0) {
5058
- log4(
5392
+ log5(
5059
5393
  `connect: ${descriptors2.length} data group descriptor(s) found but none could be loaded; leaving them untouched (no empty group is created)`
5060
5394
  );
5061
5395
  }
@@ -5080,7 +5414,7 @@ async function connect(appId, options = {}) {
5080
5414
  groupType = detectedType;
5081
5415
  } else {
5082
5416
  groupType = options.groupType ?? "config-sync";
5083
- log4(`connect: new backend, using groupType="${groupType}"`);
5417
+ log5(`connect: new backend, using groupType="${groupType}"`);
5084
5418
  }
5085
5419
  const repo = await createConfigRepo(
5086
5420
  appId,
@@ -5109,14 +5443,14 @@ async function connect(appId, options = {}) {
5109
5443
  try {
5110
5444
  appDataGroups.push(await repo.getAppDataGroup(d.id));
5111
5445
  } catch (err) {
5112
- log4(`connect: failed to load app data group "${d.id}":`, err);
5446
+ log5(`connect: failed to load app data group "${d.id}":`, err);
5113
5447
  }
5114
5448
  }
5115
5449
  let dataGroup = appDataGroups[0];
5116
5450
  if (groupType === "data-sync") {
5117
5451
  if (!dataGroup) {
5118
5452
  if (descriptors.length > 0) {
5119
- log4(
5453
+ log5(
5120
5454
  `connect: ${descriptors.length} data group descriptor(s) exist but could not be loaded; refusing to create/overwrite "default"`
5121
5455
  );
5122
5456
  } else {
@@ -5153,6 +5487,8 @@ init_backend_registry();
5153
5487
  LEGACY_CONFLICTS_DIR,
5154
5488
  LEGACY_TOMBSTONES_DIR,
5155
5489
  LOCAL_IDB_BACKEND_ID,
5490
+ LOCAL_STORAGE_UNAVAILABLE,
5491
+ LocalStorageUnavailableError,
5156
5492
  META_DIR,
5157
5493
  TOMBSTONES_DIR,
5158
5494
  TombstoneStore,
@@ -5163,6 +5499,8 @@ init_backend_registry();
5163
5499
  createBackend,
5164
5500
  createConfigRepo,
5165
5501
  createSerializerChain,
5502
+ dataGroupLocalStoreName,
5503
+ deleteDataGroupLocalStore,
5166
5504
  encodeMetaPath,
5167
5505
  getAccountFields,
5168
5506
  getBackendMetadata,
@@ -5171,6 +5509,7 @@ init_backend_registry();
5171
5509
  incrementVersion,
5172
5510
  isBrowserEnv,
5173
5511
  isKeepFile,
5512
+ isLocalStorageUnavailableError,
5174
5513
  isMtimeSidecar,
5175
5514
  legacyVersionPathFor,
5176
5515
  listBackendMetadata,