zen-fs-config 0.7.25 → 0.9.0

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/DESIGN.md CHANGED
@@ -90,13 +90,17 @@ A **sync group** is a set of backends that synchronize with each other. There ar
90
90
  - Backends: full credentials + storage location, but typically reusing the same account as a config-sync backend with a different storage target (e.g., same token/owner, different repo/branch)
91
91
  - Can be referenced by a config-sync group as an app's data storage (via `ConfigRepo.createAppDataGroup`)
92
92
 
93
- **Group type detection**: When connecting to a backend, the library reads `.meta/group-type` to determine the group type. If the file is absent, the backend is treated as a new empty group and the caller decides which type to create.
93
+ **Group type detection**: When connecting to a backend, the library reads `.meta/group.json` first and takes its `kind` as the group type. Only when no descriptor exists does it fall back to the legacy `group-type` markers (`/.config/group-type`, `/.meta/group-type`). If neither exists, the backend is treated as a new empty group and the caller decides which type to create.
94
94
 
95
- | `.meta/group-type` | Behavior |
95
+ | `.meta/group.json` `kind` (legacy marker) | Behavior |
96
96
  |---|---|
97
- | `config-sync` | Full system: IndexedDB primary + config replicas + optional data-sync groups |
98
- | `data-sync` | Lightweight: data backends only, direct read/write, no config meta layer |
99
- | absent | New empty backend; caller decides group type at creation time |
97
+ | `config` (`config-sync`) | Full system: IndexedDB primary + config replicas + optional data-sync groups |
98
+ | `data` (`data-sync`) | Lightweight: data backends only, direct read/write, no config meta layer |
99
+ | absent (no marker either) | New empty backend; caller decides group type at creation time |
100
+
101
+ Since 0.9.0 the library **no longer writes** any `group-type` marker; `kind` is the only
102
+ source of truth. Markers remain read-compatible for remotes created by older versions and
103
+ are deleted on sight.
100
104
 
101
105
  **Group type is write-once, and sync may not change it**: besides the connect-time
102
106
  check (`connect()` throws when `options.groupType` disagrees with the detected
@@ -125,7 +129,7 @@ group wiring instead of syncing the marker.
125
129
  ```
126
130
  /
127
131
  ├─ .meta/ [synced to replicas]
128
- │ ├─ group-type Group type marker: "config-sync"
132
+ │ ├─ group.json Unified descriptor { schemaVersion, kind, id, instanceId?, name?, features }
129
133
  │ ├─ backends/ Backend topology (one file per backend)
130
134
  │ │ ├─ local-idb.json { id, type, options, description }
131
135
  │ │ ├─ gitee-prod.json
@@ -162,8 +166,8 @@ group wiring instead of syncing the marker.
162
166
 
163
167
  ```
164
168
  /
165
- ├─ .meta/ [synced to replicas]
166
- │ ├─ group-type Group type marker: "data-sync"
169
+ ├─ .meta/ [group.json excluded from sync]
170
+ │ ├─ group.json Descriptor { schemaVersion:2, kind:"data", id, instanceId?, name?, features }
167
171
  │ └─ backends/ Data backend topology (one file per backend)
168
172
  │ ├─ gitee-data-1.json { id, type, options, description }
169
173
  │ └─ gitee-data-2.json
@@ -712,9 +716,11 @@ createConfigRepo('my-app', options?)
712
716
  ├─ 1. Create IndexedDB backend (always, ID = 'local-idb')
713
717
  │ storeName = options.idbStoreName || `zen-fs-config-${appId}`
714
718
  │
715
- ├─ 2. Ensure /.meta/ directory exists
719
+ ├─ 2. Ensure /.meta/ and /.config/ directories exist
716
720
  │
717
- ├─ 3. Write /.meta/group-type = "config-sync" (if not exists)
721
+ ├─ 3. Delete stale group-type markers (/.config/group-type, /.meta/group-type)
722
+ │ └─ No marker is written since 0.9.0: type lives in .meta/group.json's kind
723
+ │ markers stay readable for old remotes (getGroupType / probe fallback)
718
724
  │
719
725
  ├─ 4. Migrate legacy .meta/backends.json → .meta/backends/*.json (if exists)
720
726
  │
@@ -934,18 +940,19 @@ connect('my-app', options?)
934
940
  │
935
941
  ├─ 1. Determine config-sync repo (create or reuse) — this always hosts the data groups
936
942
  │
937
- ├─ 2. If options.backendInfo provided, read /.meta/group-type
943
+ ├─ 2. If options.backendInfo provided, read /.meta/group.json's kind
944
+ │ (fall back to the legacy .config/group-type or .meta/group-type marker)
938
945
  │
939
- ├─ "config-sync" → connect the repo to that backend; then load every app
946
+ ├─ kind=config / "config-sync" → connect the repo to that backend; then load every app
940
947
  │ data group from .meta/app-data-groups/{appId}/*.json (UC2)
941
948
  │ return { groupType: "config-sync", repo, appDataGroups }
942
949
  │
943
- ├─ "data-sync" → keep the config repo local-only; ensure the default data
950
+ ├─ kind=data / "data-sync" → keep the config repo local-only; ensure the default data
944
951
  │ group exists and attach the backend to it (UC3). The backend
945
952
  │ info is written back into app-data-groups by addBackend.
946
953
  │ return { groupType: "data-sync", repo, dataGroup }
947
954
  │
948
- └─ absent (no backendInfo) → local-only config repo + a default data group
955
+ └─ absent (no descriptor, no marker, no backendInfo) → local-only config repo + a default data group
949
956
  └─ return { groupType: "config-sync" (or options.groupType), repo, dataGroup }
950
957
  ```
951
958
 
package/README.md CHANGED
@@ -155,6 +155,9 @@ const { repo } = await connect('my-app', {
155
155
  options: { token: 'xxx', owner: 'xxx', repo: 'xxx', branch: 'main' },
156
156
  },
157
157
  idbStoreName: 'my-app-config', // custom IndexedDB store name
158
+ // A brand-new (empty) remote has no group type of its own: state it explicitly,
159
+ // otherwise connect() throws NeedsInitError instead of guessing.
160
+ initGroupType: 'config-sync',
158
161
  });
159
162
 
160
163
  // Next time you don't need to pass backend info again
@@ -190,16 +193,44 @@ if (result.groupType === 'data-sync') {
190
193
  Detection & dispatch rules:
191
194
 
192
195
  - Always creates (or reuses) a **config-sync `ConfigRepo`** as the anchor.
193
- - Reads `/.meta/group-type` from the backend: `config-sync` → connect the repo to that backend; `data-sync` → attach the backend to the default app data group inside the config-sync repo.
194
- - If that file is absent (a brand-new backend), falls back to `options.groupType` (default `config-sync`).
195
- - If you pass `options.groupType` and it conflicts with the backend's actual type, `connect()` throws a `Group type mismatch` error.
196
- - The returned `ConnectResult` always carries `groupType` and `repo` (the config-sync repo). It also carries `dataGroup` (the default app data group) on first launch and when a data-sync backend was connected.
196
+ - Probes the backend before creating anything local: it reads `/.meta/group.json` strictly (only a genuine "not found" counts as empty — a 401/403 is surfaced, not swallowed) and then the legacy `.config/group-type` / `.meta/group-type` markers. The probe yields one of `unreachable | empty | marked | occupied`.
197
+ - **The library no longer writes any `group-type` marker** (since 0.9.0): the group type lives only in `group.json`'s `kind`; legacy markers stay readable and are deleted on sight. `getGroupType()` therefore returns `null` on new deployments — use the descriptor's `kind` (or the `groupType` returned by `connect()`) instead.
198
+ - `unreachable` → throws `RemoteUnreachableError` (`code: 'REMOTE_UNREACHABLE'`); no local group is created.
199
+ - `empty` (no descriptor and no marker) → throws `NeedsInitError` (`code: 'NEEDS_INIT'`, `requiresInit: true`) unless you pass `initGroupType` (or the older `groupType`). **The library never guesses a group type for a brand-new backend** — ask the user and retry.
200
+ - `marked` → `config-sync` connects the repo to that backend; `data-sync` attaches the backend to the default app data group inside the config-sync repo.
201
+ - If `options.groupType` conflicts with the detected type, `connect()` throws a `Group type mismatch` error. An `occupied` descriptor with an invalid `kind` is rejected outright.
202
+ - The returned `ConnectResult` always carries `groupType` and `repo` (the config-sync repo). It also carries `dataGroup` (the default app data group) when a data-sync backend was connected.
197
203
 
198
204
  | Method | Description |
199
205
  |--------|-------------|
200
206
  | `connect(appId, options?)` | Unified entry: always returns a `ConfigRepo`, optionally with a default data group |
207
+ | `probeGroupTypeDetailed(type, options)` | Raw probe (no local writes): returns `{ state, groupType, remote, error?, descriptor? }` |
201
208
 
202
- `connect()` accepts the same options as `createConfigRepo` (`backendInfo`, `primaryBackendId`, `idbStoreName`, `nodeId`, `folderPath`, `cache`, `serializer`, `onConflict`, `syncPollIntervalMs`) plus `groupType`. On Node.js, pass `folderPath` (or set `ZEN_FS_CONFIG_HOME`) to enable local disk persistence.
209
+ `connect()` accepts the same options as `createConfigRepo` (`backendInfo`, `primaryBackendId`, `idbStoreName`, `nodeId`, `folderPath`, `cache`, `serializer`, `onConflict`, `syncPollIntervalMs`) plus `groupType`, `initGroupType` (the type to use when the remote is empty) and `deferReplicaSetup`. On Node.js, pass `folderPath` (or set `ZEN_FS_CONFIG_HOME`) to enable local disk persistence.
210
+
211
+ ### Deferred replica setup: two signals
212
+
213
+ `connect()` no longer verifies every remote backend's group identity (a network round-trip per replica) before returning — that is deferred to the background by default. Pass `deferReplicaSetup: false` to restore the old blocking behaviour (where one unresponsive backend could stall `connect()` indefinitely):
214
+
215
+ ```typescript
216
+ const result = await connect('my-app', {
217
+ backendInfo: { type: 'Gitee', options: { token, owner, repo, branch } },
218
+ deferReplicaSetup: true,
219
+ });
220
+
221
+ // Signal ① — connect() has returned. Local config works right now.
222
+ result.repo.getConfig('/theme');
223
+ result.replicasPending; // true
224
+
225
+ // Signal ② — remote identity check + pair creation finished.
226
+ const summary = await result.whenReplicasReady?.();
227
+ // { ready: ['Gitee-replica'], skipped: [], failed: [] }
228
+ ```
229
+
230
+ - Signal ① (`connect()` resolved): the local repo is fully usable — reads/writes, `getBackends()` (descriptors are on disk), `listAppDataGroups()`. But no sync pair exists yet, so `getSyncStatuses()` is empty. **Never render an empty pair list as "no remote backend"**: check `replicasPending` first.
231
+ - Signal ② (`whenReplicasReady()`): resolves with `{ ready, skipped, failed }`. `skipped` holds `{ backendId, reason }` for backends that belong to another group (identity conflict) — these are **not thrown** from `connect()` any more. `failed` holds `{ backendId, error }` for backend/network failures. The promise never rejects; it resolves immediately (with the current state) when defer is off, so consumers can `await` unconditionally.
232
+ - No pair is created before verification succeeds. That removes the "create then tear down on conflict" window (and any need to gate syncing behind a flag); the price is that consumers must honour the two signals.
233
+ - `dispose()` and `flush()` await the background setup, so a late pair can never attach to a disposed engine and `flush()` never runs against zero pairs.
203
234
 
204
235
  ## App data group path semantics
205
236
 
@@ -253,6 +284,7 @@ Each config file has a sidecar version file: `db.json` → `.db.json.version` (v
253
284
  | `publishNodeConfig(nodeId)` | Explicit one-shot push of node config to all backends (auto-sync also covers it) |
254
285
  | `peekNodeConfig<T>(nodeId, path)` | Read another node's config (from the synced-in local copy) |
255
286
  | `flush()` | Manually trigger all pending syncs |
287
+ | `whenReplicasReady?()` | Optional; resolves with the replica setup summary (see deferred setup above) |
256
288
  | `listConflicts()` | List all archived conflicts |
257
289
  | `resolveConflict(id, merged)` | Resolve a conflict with merged content |
258
290
  | `fs.promises.*` | Standard fs API, chrooted to `/{appId}/` |
package/README.zh-CN.md CHANGED
@@ -153,6 +153,9 @@ const { repo } = await connect('my-app', {
153
153
  options: { token: 'xxx', owner: 'xxx', repo: 'xxx', branch: 'main' },
154
154
  },
155
155
  idbStoreName: 'my-app-config', // 自定义 IndexedDB store 名称
156
+ // 全新(空)远端自己没有组类型:必须显式声明,
157
+ // 否则 connect() 抛 NeedsInitError,而不是替你猜。
158
+ initGroupType: 'config-sync',
156
159
  });
157
160
 
158
161
  // 之后重新打开时不需要再传后端参数
@@ -183,16 +186,44 @@ if (result.groupType === 'data-sync') {
183
186
  探测与分发规则:
184
187
 
185
188
  - 始终创建(或复用)一个**配置同步组 `ConfigRepo`** 作为锚点。
186
- - 读取后端上的 `/.meta/group-type`:`config-sync` → 将该后端连到配置同步组;`data-sync` → 把它挂到配置同步组下的默认数据组。
187
- - 若该文件不存在(全新后端),回退到 `options.groupType`(默认 `config-sync`)。
188
- - 如果你显式传了 `options.groupType`,且与后端实际类型不符,`connect()` 会抛出 `Group type mismatch` 错误。
189
- - 返回的 `ConnectResult` 始终带 `groupType` 和 `repo`(配置同步组);首次启动或接入 data-sync 后端时还带 `dataGroup`(默认数据组)。
189
+ - 建任何本地东西之前先探测后端:严格读 `/.meta/group.json`(只有真正的「不存在」才算空,401/403 会照实报错而不是被吞成空库),没有描述符时再读旧标记 `/.config/group-type`、`/.meta/group-type`。探测结果是 `unreachable | empty | marked | occupied` 四态之一。
190
+ - **库不再生成任何 `group-type` 标记**(0.9.0 起):组类型只由 `group.json` 的 `kind` 表达,旧标记仅作读取兼容,遇到就删除。所以 `getGroupType()` 在新部署上返回 `null`,判断类型请读描述符的 `kind`(或直接看 `connect()` 返回的 `groupType`)。
191
+ - `unreachable` → 抛 `RemoteUnreachableError`(`code: 'REMOTE_UNREACHABLE'`),不创建本地组。
192
+ - `empty`(无描述符也无标记)→ 抛 `NeedsInitError`(`code: 'NEEDS_INIT'`,`requiresInit: true`),除非你传了 `initGroupType`(或旧选项 `groupType`)。**库不会替全新后端猜组类型** —— 先问用户,再带类型重连。
193
+ - `marked` → `config-sync` 把该后端连到配置同步组;`data-sync` 把它挂到配置同步组下的默认数据组。
194
+ - 显式传的 `options.groupType` 与探测结果不符 → `Group type mismatch`;`occupied` 但描述符 `kind` 非法 → 直接报错。
195
+ - 返回的 `ConnectResult` 始终带 `groupType` 和 `repo`(配置同步组);接入 data-sync 后端时还带 `dataGroup`(默认数据组)。
190
196
 
191
197
  | 方法 | 说明 |
192
198
  |---|---|
193
199
  | `connect(appId, options?)` | 统一入口:始终返回 `ConfigRepo`,可选附带默认数据组 |
200
+ | `probeGroupTypeDetailed(type, options)` | 只探测、不写本地:返回 `{ state, groupType, remote, error?, descriptor? }` |
194
201
 
195
- `connect()` 接受与 `createConfigRepo` 相同的选项(`backendInfo`、`primaryBackendId`、`idbStoreName`、`nodeId`、`folderPath`、`cache`、`serializer`、`onConflict`、`syncPollIntervalMs`),另加 `groupType`。在 Node.js 上通过 `folderPath`(或设 `ZEN_FS_CONFIG_HOME`)开启本地磁盘持久化。
202
+ `connect()` 接受与 `createConfigRepo` 相同的选项(`backendInfo`、`primaryBackendId`、`idbStoreName`、`nodeId`、`folderPath`、`cache`、`serializer`、`onConflict`、`syncPollIntervalMs`),另加 `groupType`、`initGroupType`(远端为空时用户选定的组类型)与 `deferReplicaSetup`。在 Node.js 上通过 `folderPath`(或设 `ZEN_FS_CONFIG_HOME`)开启本地磁盘持久化。
203
+
204
+ ### deferReplicaSetup:两个信号
205
+
206
+ **默认就是本地优先**:`connect()` 不再逐个校验远端后端(每个副本一次网络往返)才返回,这段直接挪到后台;传 `deferReplicaSetup: false` 才恢复「等所有副本校验完再返回」的旧行为(此时一个不响应的后端会把 `connect()` 挂住):
207
+
208
+ ```typescript
209
+ const result = await connect('my-app', {
210
+ backendInfo: { type: 'Gitee', options: { token, owner, repo, branch } },
211
+ deferReplicaSetup: true,
212
+ });
213
+
214
+ // 信号① —— connect() 已返回,本地配置立刻可用
215
+ result.repo.getConfig('/theme');
216
+ result.replicasPending; // true
217
+
218
+ // 信号② —— 远端校验 + 建对完成
219
+ const summary = await result.whenReplicasReady?.();
220
+ // { ready: ['Gitee-replica'], skipped: [], failed: [] }
221
+ ```
222
+
223
+ - 信号①(`connect()` resolve):本地仓完整可用 —— 读写、`getBackends()`(描述符已落盘)、`listAppDataGroups()` 都正常。但此时还没有同步对,`getSyncStatuses()` 是空的。**不能把空的同步对列表当成「没有远端后端」**,先看 `replicasPending`。
224
+ - 信号②(`whenReplicasReady()`):resolve 出 `{ ready, skipped, failed }`。`skipped` 是 `{ backendId, reason }`,表示该后端归属别的同步组(身份冲突)—— 这类情况**不再从 `connect()` 抛出**;`failed` 是 `{ backendId, error }`,表示建实例 / 网络失败。该方法永不 reject;未开 defer 时也会立即 resolve(读当前状态),所以调用方可以无分支地 `await`。
225
+ - 校验通过前不建任何同步对,因此没有「建了又拆」的冲突窗口,也不需要给同步加闸门。代价是消费方必须认上面两个信号。
226
+ - `dispose()` 与 `flush()` 都会等待后台建对,晚到的 pair 不会挂到已销毁的引擎上,`flush()` 也不会跑在 0 个 pair 上。
196
227
 
197
228
  ## 数据组的路径语义
198
229
 
@@ -244,6 +275,7 @@ await dataGroup.fs.promises.writeFile('/struct/host.json', json);
244
275
  | `publishNodeConfig(nodeId)` | 显式一次性推送节点配置到所有后端(自动同步已覆盖) |
245
276
  | `peekNodeConfig<T>(nodeId, path)` | 只读查看其他节点的已发布配置 |
246
277
  | `flush()` | 手动触发所有同步 |
278
+ | `whenReplicasReady?()` | 可选;resolve 出副本建对摘要(见上文 defer 模式) |
247
279
  | `listConflicts()` | 列出所有冲突归档 |
248
280
  | `resolveConflict(id, merged)` | 用合并内容解决冲突 |
249
281
  | `fs.promises.*` | 标准 fs API,chroot 隔离到 `/{appId}/` |
@@ -9,7 +9,7 @@ import {
9
9
  registerBackend,
10
10
  unregisterBackend,
11
11
  wrapZenFSFileSystem
12
- } from "./chunk-JS3F3RBC.mjs";
12
+ } from "./chunk-J6QHNG4F.mjs";
13
13
  export {
14
14
  createBackend,
15
15
  getAccountFields,
@@ -232,7 +232,10 @@ async function wrapZenFSFileSystem(config) {
232
232
  const size = st.size;
233
233
  const buf = new Uint8Array(size);
234
234
  await isolatedFS.read(path, buf, 0, size);
235
- if (args[0] === "utf-8") return new TextDecoder().decode(buf);
235
+ const enc = typeof args[0] === "string" ? args[0] : args[0] && typeof args[0] === "object" ? args[0].encoding : void 0;
236
+ if (enc === "utf-8" || enc === "utf8" || enc === "UTF-8") {
237
+ return new TextDecoder().decode(buf);
238
+ }
236
239
  return buf;
237
240
  },
238
241
  async writeFile(path, data, _options) {
package/dist/index.d.mts CHANGED
@@ -264,6 +264,23 @@ interface ConfigRepoOptions {
264
264
  type: string;
265
265
  options: Record<string, unknown>;
266
266
  };
267
+ /**
268
+ * 连接前已探测到的远端描述符(内部优化):同一个 type+options 的副本在
269
+ * `setupSync()` 里直接复用,省掉一次重复的 `group.json` 远端读。
270
+ * `descriptor: null` 表示已确认远端没有描述符(空库 / 老仓库)。
271
+ */
272
+ prefetchedRemote?: {
273
+ type: string;
274
+ options?: Record<string, unknown>;
275
+ descriptor: GroupDescriptor | null;
276
+ };
277
+ /**
278
+ * 把副本建对推迟到后台(默认 true)。`createConfigRepo` 先用本地缓存可用,
279
+ * 副本校验与建对由 `whenReplicasReady()` 通知;校验完成前不会建任何 pair,
280
+ * 也不会启动首同步。传 `false` 恢复旧行为(逐个校验远端后再返回,任一后端
281
+ * 不响应会一直等下去)。
282
+ */
283
+ deferReplicaSetup?: boolean;
267
284
  /** IndexedDB store name for the local primary backend. Default: `zen-fs-config-{appId}` */
268
285
  idbStoreName?: string;
269
286
  /**
@@ -385,6 +402,27 @@ interface BackendSyncState {
385
402
  timestamp: number;
386
403
  };
387
404
  }
405
+ /**
406
+ * 同步对事件(`onSyncEvent`)。
407
+ *
408
+ * `sync:end` 每轮同步结束都会发(**包含零变更轮**),调用方可用 `result`
409
+ * 里的计数过滤自己关心的变更;`sync:error` 只在整轮抛错时发。
410
+ */
411
+ interface SyncGroupSyncEvent {
412
+ type: 'sync:end' | 'sync:error';
413
+ /** 事件所属组的类型。 */
414
+ groupKind: SyncGroupKind;
415
+ /** 配置组固定为 `config`;数据组为其 groupId。 */
416
+ groupId: string;
417
+ /** 该同步对对应的后端 id(不含隐式本地主库)。 */
418
+ backendId: string;
419
+ pairId: string;
420
+ timestamp: number;
421
+ /** `sync:end` 时附带本轮结果。 */
422
+ result?: SyncResult;
423
+ /** `sync:error` 时的错误消息。 */
424
+ error?: string;
425
+ }
388
426
  /** Structural discriminator for a sync group. */
389
427
  type SyncGroupKind = 'config' | 'data';
390
428
  /** Capability switches, derived from `kind` + the group descriptor. */
@@ -576,6 +614,11 @@ interface SyncGroupHandle {
576
614
  readonly fs: typeof node_fs;
577
615
  getSyncStatuses(): Map<string, SyncPairStatus>;
578
616
  getBackendSyncStates(): Map<string, BackendSyncState>;
617
+ /**
618
+ * 订阅同步对事件(`sync:end` / `sync:error`)。返回取消订阅函数。
619
+ * 可选:老版本实现可能没有该方法,调用方按可选处理。
620
+ */
621
+ onSyncEvent?(handler: (event: SyncGroupSyncEvent) => void): () => void;
579
622
  flush(): Promise<SyncResult[]>;
580
623
  dispose(): Promise<void>;
581
624
  addBackend(id: string, type: string, options: Record<string, unknown>, description?: string): Promise<void>;
@@ -608,6 +651,14 @@ interface SyncGroupHandle {
608
651
  /** Handle to a data-sync group, providing direct fs access. */
609
652
  interface AppDataGroup extends SyncGroupHandle {
610
653
  readonly kind: 'data';
654
+ /**
655
+ * 远端阶段(建实例 → 定身份 → 建同步对 → 首同步 → watch)的完成信号。
656
+ *
657
+ * 组实例在本地就绪后即返回,远端后端在后台逐个(并发 + 超时)探测;调用方可以
658
+ * 先渲染组的本地状态,再等这个 Promise 结束后刷新为真实的同步对计数 / 错误。
659
+ * 未启动时立即 resolve,永不 reject。旧版本没有该方法,调用方按可选处理。
660
+ */
661
+ whenBackendsReady?: () => Promise<void>;
611
662
  }
612
663
  /** Options for the unified connect() entry point. */
613
664
  interface ConnectOptions {
@@ -616,8 +667,17 @@ interface ConnectOptions {
616
667
  type: string;
617
668
  options: Record<string, unknown>;
618
669
  };
619
- /** Force a specific group type (skips auto-detection for new backends). */
670
+ /**
671
+ * Force a specific group type. For an already-marked remote it must match the
672
+ * remote's type; for an empty remote it is treated as the user's explicit
673
+ * choice (legacy callers). New callers should use `initGroupType` instead.
674
+ */
620
675
  groupType?: SyncGroupType;
676
+ /**
677
+ * 空库初始化授权:仅当远端完全为空(无 group.json、无 group-type 标记)时使用。
678
+ * 未提供时 connect() 抛 `NeedsInitError`,由 UI 询问用户后带上本字段重试。
679
+ */
680
+ initGroupType?: SyncGroupType;
621
681
  /** IndexedDB store name. Default: `zen-fs-config-{appId}` */
622
682
  idbStoreName?: string;
623
683
  /**
@@ -646,6 +706,28 @@ interface ConnectOptions {
646
706
  onConflict?: (conflict: ConflictInfo) => Promise<unknown | null>;
647
707
  /** Sync polling interval in ms. Default: 1800000 (30 min). */
648
708
  syncPollIntervalMs?: number;
709
+ /**
710
+ * 把「建副本同步对」整体推迟到后台:`connect()` 只做探测 + 本地仓初始化,
711
+ * 返回后由 `whenReplicasReady` 通知结果。默认 true(本地缓存优先启动);
712
+ * 传 false 恢复旧行为(等待所有副本校验完成才返回)。
713
+ * 校验完成前不建任何 pair,因此不存在「建了又拆」的冲突窗口。
714
+ */
715
+ deferReplicaSetup?: boolean;
716
+ }
717
+ /** `whenReplicasReady()` 的结果:哪些副本已可用、哪些被跳过、哪些失败。 */
718
+ interface ReplicaSetupSummary {
719
+ /** 校验通过并已建同步对的副本 id。 */
720
+ ready: string[];
721
+ /** 因归属冲突/不可读被跳过的副本。 */
722
+ skipped: {
723
+ backendId: string;
724
+ reason: string;
725
+ }[];
726
+ /** 建实例或建对失败的副本。 */
727
+ failed: {
728
+ backendId: string;
729
+ error: string;
730
+ }[];
649
731
  }
650
732
  /** Result of connect(). */
651
733
  interface ConnectResult {
@@ -667,6 +749,16 @@ interface ConnectResult {
667
749
  dataGroup?: AppDataGroup;
668
750
  /** All app data group handles loaded for this app (may be empty). */
669
751
  appDataGroups?: AppDataGroup[];
752
+ /**
753
+ * 副本是否还在后台准备中。`true` 时 `repo` 已可用(本地数据可读),
754
+ * 但远端同步对尚未建好,调用方应等待 `whenReplicasReady` 再做远端相关操作。
755
+ */
756
+ replicasPending?: boolean;
757
+ /**
758
+ * 副本准备结果。未开启 `deferReplicaSetup` 时是一个已 resolve 的 Promise。
759
+ * 永不 reject:失败信息放在 `failed` / `skipped` 里。
760
+ */
761
+ whenReplicasReady?: Promise<ReplicaSetupSummary>;
670
762
  }
671
763
  /** The main configuration repository interface. */
672
764
  interface IConfigRepo {
@@ -674,6 +766,11 @@ interface IConfigRepo {
674
766
  readonly appId: string;
675
767
  /** Node ID. */
676
768
  readonly nodeId: string;
769
+ /**
770
+ * 副本后台准备的结果(`deferReplicaSetup` 时才有意义)。
771
+ * 未推迟时立即 resolve;永不 reject。
772
+ */
773
+ whenReplicasReady?(): Promise<ReplicaSetupSummary>;
677
774
  /** Fixed group id of the config-sync group (`config`). */
678
775
  readonly groupId: string;
679
776
  /** Structural discriminator — always `'config'`. */
@@ -706,6 +803,11 @@ interface IConfigRepo {
706
803
  flush(): Promise<SyncResult[]>;
707
804
  /** Get sync status for all registered sync pairs. */
708
805
  getSyncStatuses(): Map<string, SyncPairStatus>;
806
+ /**
807
+ * Subscribe to pair-level sync events (`sync:end` / `sync:error`).
808
+ * Returns an unsubscribe function. Optional for older implementations.
809
+ */
810
+ onSyncEvent?(handler: (event: SyncGroupSyncEvent) => void): () => void;
709
811
  /**
710
812
  * Per-backend sync state, including replica descriptors that failed to
711
813
  * connect and therefore have no pair (they do not appear in
@@ -843,9 +945,18 @@ interface IConfigRepo {
843
945
  * primary). Unified handle method shared with data groups.
844
946
  */
845
947
  listBackends(): AppDataBackendDescriptor[];
846
- /** Write the group-type marker file if it doesn't exist. */
948
+ /**
949
+ * Ensure the unified group descriptor (`.meta/group.json`) exists.
950
+ *
951
+ * No longer writes any `group-type` marker (since 0.9.0); `type` is kept for
952
+ * API compatibility only. Stale markers are deleted when encountered.
953
+ */
847
954
  ensureGroupType(type: SyncGroupType): Promise<void>;
848
- /** Read the group-type marker. Returns null if not set. */
955
+ /**
956
+ * Read the legacy `group-type` marker (`/.config/group-type`, then
957
+ * `/.meta/group-type`). Returns null when neither exists — which is now the
958
+ * normal case, since type is carried by `.meta/group.json`'s `kind`.
959
+ */
849
960
  getGroupType(): Promise<SyncGroupType | null>;
850
961
  /** Dispose: stop all sync, release cache FS and resources. */
851
962
  dispose(): Promise<void>;
@@ -1108,6 +1219,11 @@ declare class ConfigRepo implements IConfigRepo {
1108
1219
  private onConflictCallback?;
1109
1220
  private disposed;
1110
1221
  private configCache;
1222
+ /** 后台建对(deferReplicaSetup)的状态,见 `whenReplicasReady()`。 */
1223
+ private replicaSetupPromise;
1224
+ private replicaSetupSummary;
1225
+ /** 同步对事件订阅者,见 `onSyncEvent()`。 */
1226
+ private syncEventHandlers;
1111
1227
  private readonly primaryBackendId;
1112
1228
  private readonly cacheOptions?;
1113
1229
  private readonly pollIntervalMs?;
@@ -1359,6 +1475,13 @@ declare class ConfigRepo implements IConfigRepo {
1359
1475
  */
1360
1476
  syncMetaToReplicas(): Promise<void>;
1361
1477
  getSyncStatuses(): Map<string, SyncPairStatus>;
1478
+ /**
1479
+ * Subscribe to sync-pair events (`sync:end` / `sync:error`). Returns an
1480
+ * unsubscribe function. Handlers run after the existing state bookkeeping,
1481
+ * so `getSyncStatuses()` is already up to date when they fire.
1482
+ */
1483
+ onSyncEvent(handler: (event: SyncGroupSyncEvent) => void): () => void;
1484
+ private emitSyncEvent;
1362
1485
  /**
1363
1486
  * Per-backend sync state. Includes replica descriptors that failed to connect
1364
1487
  * (they have no sync pair, so they never show up in getSyncStatuses()).
@@ -1384,7 +1507,21 @@ declare class ConfigRepo implements IConfigRepo {
1384
1507
  listConflicts(): Promise<ConflictArchive[]>;
1385
1508
  readConflictBackup(conflictId: string, fileType: 'source' | 'target' | 'resolved'): Promise<string>;
1386
1509
  dispose(): Promise<void>;
1387
- setupSync(backends: BackendDescriptor[], primaryBackendId: string, pollIntervalMs?: number): Promise<void>;
1510
+ /** 当前副本准备结果(不等待)。 */
1511
+ private collectReplicaSetupSummary;
1512
+ /** 副本后台准备的结果。未开启 defer 时立即 resolve。永不 reject。 */
1513
+ whenReplicasReady(): Promise<ReplicaSetupSummary>;
1514
+ /**
1515
+ * 后台建对:`connect()` 只做探测 + 本地初始化,副本的 createBackend /
1516
+ * 归属校验 / addPair 全部放在这里。
1517
+ *
1518
+ * 关键点:**校验完成前不建任何 pair**,因此不存在「pair 已存在但还没校验」
1519
+ * 的冲突窗口,也不需要给同步加闸门;首同步与 watch 在 pair 建好之后才启动。
1520
+ */
1521
+ startReplicaSetupInBackground(backends: BackendDescriptor[], primaryBackendId: string, pollIntervalMs?: number, prefetchedRemote?: ConfigRepoOptions['prefetchedRemote'], opts?: {
1522
+ migrateVersionSidecars?: boolean;
1523
+ }): Promise<ReplicaSetupSummary>;
1524
+ setupSync(backends: BackendDescriptor[], primaryBackendId: string, pollIntervalMs?: number, prefetchedRemote?: ConfigRepoOptions['prefetchedRemote']): Promise<void>;
1388
1525
  /** Write version sidecar for a config file (no-op for .version files). */
1389
1526
  private writeVersionSidecar;
1390
1527
  /** Delete version sidecar on a backend (no-op for .version files). */
@@ -1466,13 +1603,15 @@ declare class ConfigRepo implements IConfigRepo {
1466
1603
  * tombstoned, so this never delete-then-recreates it.
1467
1604
  */
1468
1605
  replaceBackend(id: string, type: string, options: Record<string, unknown>, description?: string): Promise<void>;
1606
+ private identityPromise;
1607
+ private ensureGroupIdentity;
1469
1608
  /**
1470
1609
  * 本组的同步身份(kind + id + 不可变 instanceId)。
1471
1610
  *
1472
1611
  * 首次调用时若 `.meta/group.json` 里还没有 `instanceId`(老部署),生成一个
1473
1612
  * 并就地写回 —— 只写一次,之后字节相同不再落盘。
1474
1613
  */
1475
- private ensureGroupIdentity;
1614
+ private resolveGroupIdentity;
1476
1615
  /**
1477
1616
  * 只读收集配置组身份的候选:本地描述符 + 每个已注册后端根的 `group.json`。
1478
1617
  * 只看 `kind` / `id` 与本组一致的根;读失败的根不参与裁决(不猜)。
@@ -1513,7 +1652,14 @@ declare class ConfigRepo implements IConfigRepo {
1513
1652
  listBackendConflicts(): BackendConflictInfo[];
1514
1653
  /** 用户确认后解决配置组某个后端的归属冲突。 */
1515
1654
  resolveBackendConflict(backendId: string, mode: BackendConflictResolution): Promise<BackendConflictResolutionResult>;
1516
- /** Write the group-type marker file if it doesn't exist. */
1655
+ /**
1656
+ * 确保统一组描述符(`.meta/group.json`)就位。
1657
+ *
1658
+ * **已停写 `group-type` 标记**:`/.config/group-type` 与 `/.meta/group-type`
1659
+ * 都不再生成。组类型现在只由描述符的 `kind` 表达,标记仅作旧部署的读取兼容
1660
+ * (`getGroupType()`、`probeGroupTypeDetailed()` 的 legacy 分支),遗留文件会被顺手清掉。
1661
+ * `type` 参数只为兼容既有调用方保留,不再决定任何写入内容。
1662
+ */
1517
1663
  ensureGroupType(type: SyncGroupType): Promise<void>;
1518
1664
  /** Read the group-type marker. Returns null if not set (new path, then legacy). */
1519
1665
  getGroupType(): Promise<SyncGroupType | null>;
@@ -1902,6 +2048,46 @@ declare function resolveRemoteIdentity(remoteFS: any, identity: GroupIdentity, m
1902
2048
  * dispatches to the appropriate factory function.
1903
2049
  */
1904
2050
 
2051
+ /** 探测结果:不可达 / 空库 / 只有 group-type 标记 / 已有组描述符。 */
2052
+ type GroupProbeState = 'unreachable' | 'empty' | 'marked' | 'occupied';
2053
+ interface GroupProbeResult {
2054
+ state: GroupProbeState;
2055
+ /** 已知的组类型;`empty`/`unreachable` 下为 null。 */
2056
+ groupType: SyncGroupType | null;
2057
+ /** 远端已有的身份摘要(仅 occupied 时可能非空)。 */
2058
+ remote: RemoteIdentitySnapshot | null;
2059
+ /** 出错原因(unreachable 时是失败原因;occupied 但 kind 非法时是说明)。 */
2060
+ error?: string;
2061
+ /**
2062
+ * 探测时读到的完整描述符(`null` = 已确认远端没有描述符)。
2063
+ * 供 `createConfigRepo` 复用,避免 setupSync 再读一次同一个 `group.json`。
2064
+ */
2065
+ descriptor?: GroupDescriptor | null;
2066
+ }
2067
+ /** 远端连不上(网络/鉴权/超时):不能当成空库处理,直接拒绝,避免误建本地组。 */
2068
+ declare class RemoteUnreachableError extends Error {
2069
+ readonly backendType: string;
2070
+ readonly reason?: string | undefined;
2071
+ readonly code = "REMOTE_UNREACHABLE";
2072
+ constructor(backendType: string, reason?: string | undefined);
2073
+ }
2074
+ /** 远端是空库:必须由用户显式选择组类型(initGroupType)才允许初始化。 */
2075
+ declare class NeedsInitError extends Error {
2076
+ readonly backendType: string;
2077
+ readonly rootHint?: string | undefined;
2078
+ readonly code = "NEEDS_INIT";
2079
+ readonly requiresInit = true;
2080
+ constructor(backendType: string, rootHint?: string | undefined);
2081
+ }
2082
+ /**
2083
+ * 三态探测:严格区分「远端不可达」与「真·空库」。
2084
+ *
2085
+ * - 严格读 `/.meta/group.json`:只有明确的“文件不存在”才继续;
2086
+ * 其它错误一律视为不可达,不再 `catch {}` 吞掉。
2087
+ * - 无描述符时读 `/.config/group-type`、`/.meta/group-type`:
2088
+ * 读到合法值 = `marked`;都不存在 = `empty`。
2089
+ */
2090
+ declare function probeGroupTypeDetailed(type: string, options: Record<string, unknown>): Promise<GroupProbeResult>;
1905
2091
  /**
1906
2092
  * Unified entry point for connecting to a zen-fs-config sync group.
1907
2093
  *
@@ -2150,4 +2336,4 @@ declare class ConflictStore {
2150
2336
  resolve(conflictId: string, mergedContent: string | Uint8Array): Promise<void>;
2151
2337
  }
2152
2338
 
2153
- export { type AppDataBackendDescriptor, type AppDataGroup, type AppDataGroupDescriptor, type BackendConflictInfo, type BackendConflictReason, type BackendConflictResolution, type BackendConflictResolutionResult, type BackendDescriptor, type BackendFactory, type BackendInstance, type BackendMetadata, type BackendParamDef, type BackendSyncState, type BackendsMeta, CONFIG_DIR, CONFLICTS_DIR, type CacheOptions, ConfigRepo, type ConfigRepoOptions, type ConfigSerializer, type ConfigSyncGroupDescriptor, type ConfigSyncGroupHandle, type ConflictArchive, type ConflictInfo, ConflictStore, type ConnectOptions, type ConnectResult, DATA_GROUP_DEFAULT_FEATURES, FolderStore, GROUP_DESCRIPTOR_FILE, type GroupDescriptor, type GroupIdentity, type GroupInstanceIdRootResult, type IConfigRepo, type IdentityBindingResult, type IdentityCandidate, type IdentityCandidateSource, type IdentityConflictReason, type IdentityResolutionMode, type IdentityResolutionResult, type KeepPurgeResult, LEGACY_CONFLICTS_DIR, LEGACY_TOMBSTONES_DIR, LOCAL_IDB_BACKEND_ID, LOCAL_STORAGE_UNAVAILABLE, type LocalStorageUnavailableDetails, LocalStorageUnavailableError, type LocalStoreDeletionResult, META_DIR, type MigrateLocalFS, type MigrateReplicaFS, type MtimePurgeResult, type PurgeKeepOptions, type PurgeLocalSyncConfigOptions, type PurgeLocalSyncConfigResult, type PurgeMtimeOptions, type PurgeableFS$1 as PurgeableFS, type RemoteIdentitySnapshot, type RemoteIdentityState, type SetGroupInstanceIdOptions, type SetGroupInstanceIdResult, type SyncGroupFeatures, type SyncGroupHandle, type SyncGroupKind, type SyncGroupType, TOMBSTONES_DIR, type TombstoneMeta, TombstoneStore, VERSIONS_DIR, type VersionMeta, type VersionMigrationOptions, type VersionMigrationResult, VersionStore, bindRemoteGroupIdentity, bindRemoteGroupIdentityDetailed, configKeyToFilePath, connect, createBackend, createConfigRepo, createSerializerChain, dataGroupLocalStoreName, deleteDataGroupLocalStore, deleteIndexedDbStore, encodeMetaPath, getAccountFields, getBackendMetadata, getExtension, hasBackend, incrementVersion, isBrowserEnv, isKeepFile, isLocalStorageUnavailableError, isMtimeSidecar, isValidGroupInstanceId, legacyVersionPathFor, listBackendMetadata, listBackends, localPrimaryType, localSyncStoreNames, mergeAccountFields, migrateVersionSidecars, newGroupInstanceId, purgeKeepFiles, purgeLocalSyncConfig, purgeMtimeSidecars, readGroupDescriptor, readVersion, registerBackend, registerFolderBackend, resolveLocalPrimary, resolveRemoteIdentity, sha256, shortInstanceId, summarizeIdentity, unregisterBackend, verifyOrRepairVersion, versionPathFor, wrapZenFSFileSystem, writeGroupDescriptor, writeVersion };
2339
+ export { type AppDataBackendDescriptor, type AppDataGroup, type AppDataGroupDescriptor, type BackendConflictInfo, type BackendConflictReason, type BackendConflictResolution, type BackendConflictResolutionResult, type BackendDescriptor, type BackendFactory, type BackendInstance, type BackendMetadata, type BackendParamDef, type BackendSyncState, type BackendsMeta, CONFIG_DIR, CONFLICTS_DIR, type CacheOptions, ConfigRepo, type ConfigRepoOptions, type ConfigSerializer, type ConfigSyncGroupDescriptor, type ConfigSyncGroupHandle, type ConflictArchive, type ConflictInfo, ConflictStore, type ConnectOptions, type ConnectResult, DATA_GROUP_DEFAULT_FEATURES, FolderStore, GROUP_DESCRIPTOR_FILE, type GroupDescriptor, type GroupIdentity, type GroupInstanceIdRootResult, type GroupProbeResult, type GroupProbeState, type IConfigRepo, type IdentityBindingResult, type IdentityCandidate, type IdentityCandidateSource, type IdentityConflictReason, type IdentityResolutionMode, type IdentityResolutionResult, type KeepPurgeResult, LEGACY_CONFLICTS_DIR, LEGACY_TOMBSTONES_DIR, LOCAL_IDB_BACKEND_ID, LOCAL_STORAGE_UNAVAILABLE, type LocalStorageUnavailableDetails, LocalStorageUnavailableError, type LocalStoreDeletionResult, META_DIR, type MigrateLocalFS, type MigrateReplicaFS, type MtimePurgeResult, NeedsInitError, type PurgeKeepOptions, type PurgeLocalSyncConfigOptions, type PurgeLocalSyncConfigResult, type PurgeMtimeOptions, type PurgeableFS$1 as PurgeableFS, type RemoteIdentitySnapshot, type RemoteIdentityState, RemoteUnreachableError, type ReplicaSetupSummary, type SetGroupInstanceIdOptions, type SetGroupInstanceIdResult, type SyncGroupFeatures, type SyncGroupHandle, type SyncGroupKind, type SyncGroupSyncEvent, type SyncGroupType, TOMBSTONES_DIR, type TombstoneMeta, TombstoneStore, VERSIONS_DIR, type VersionMeta, type VersionMigrationOptions, type VersionMigrationResult, VersionStore, bindRemoteGroupIdentity, bindRemoteGroupIdentityDetailed, configKeyToFilePath, connect, createBackend, createConfigRepo, createSerializerChain, dataGroupLocalStoreName, deleteDataGroupLocalStore, deleteIndexedDbStore, encodeMetaPath, getAccountFields, getBackendMetadata, getExtension, hasBackend, incrementVersion, isBrowserEnv, isKeepFile, isLocalStorageUnavailableError, isMtimeSidecar, isValidGroupInstanceId, legacyVersionPathFor, listBackendMetadata, listBackends, localPrimaryType, localSyncStoreNames, mergeAccountFields, migrateVersionSidecars, newGroupInstanceId, probeGroupTypeDetailed, purgeKeepFiles, purgeLocalSyncConfig, purgeMtimeSidecars, readGroupDescriptor, readVersion, registerBackend, registerFolderBackend, resolveLocalPrimary, resolveRemoteIdentity, sha256, shortInstanceId, summarizeIdentity, unregisterBackend, verifyOrRepairVersion, versionPathFor, wrapZenFSFileSystem, writeGroupDescriptor, writeVersion };