@wirecat/cli-core 0.703.0 → 0.704.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.
@@ -0,0 +1,603 @@
1
+ import { createHash } from "node:crypto";
2
+ import { mkdir, rm, stat, unlink } from "node:fs/promises";
3
+ import { dirname, join, posix } from "node:path";
4
+ import { CliError } from "@wirecat/cli-base";
5
+ import * as v from "valibot";
6
+ import { eachMirror, jsonState } from "../documents/mirrors.js";
7
+ import { assertNoLink, hashFile, localTemp, placeNew, replaceLocal, safePath, scanLocal, skippedName, } from "../documents/push.js";
8
+ /**
9
+ * A run that would delete more than `ALWAYS_DELETED` files and more than `MAX_DELETIONS` files or `MAX_DELETED_SHARE`
10
+ * of the mirror stops before writing.
11
+ */
12
+ const ALWAYS_DELETED = 2;
13
+ const MAX_DELETIONS = 50;
14
+ const MAX_DELETED_SHARE = 0.25;
15
+ const TRASH = ".wirecat-trash";
16
+ const SAVE_EVERY_MS = 1_000;
17
+ /** A temporary file's tag from any operation id, safe in a file name. */
18
+ const tagOf = (operationId) => createHash("sha256").update(operationId).digest("hex").slice(0, 8);
19
+ const sameFile = (local, remote) => local.hash === remote.sha256;
20
+ /**
21
+ * The three-way comparison of one path: the local file now, the remote file now and the last sync. A side is
22
+ * "same" when its content still has the last sync's hash.
23
+ */
24
+ const decide = (path, sure, local, remote, base, keep) => {
25
+ const step = (kind, reason) => ({
26
+ kind,
27
+ path,
28
+ ...(local ? { local } : {}),
29
+ ...(remote ? { remote } : {}),
30
+ ...(base ? { base } : {}),
31
+ ...(reason ? { reason } : {}),
32
+ });
33
+ // Only a file the last sync saw, missing from a complete listing of the same root, counts as deleted.
34
+ if (base && !local && !sure.local)
35
+ return step("unknown", "local");
36
+ if (base && !remote && !sure.remote)
37
+ return step("unknown", "remote");
38
+ if (!local && !remote)
39
+ return base ? step("forget") : undefined;
40
+ if (local && remote && sameFile(local, remote))
41
+ return base?.sha256 === local.hash && base.id === remote.id ? undefined : step("adopt");
42
+ if (!base) {
43
+ if (!remote)
44
+ return step("upload");
45
+ if (!local)
46
+ return step("download");
47
+ return settle("created on both sides with different content", "upload", "download", "keep-both");
48
+ }
49
+ const localSame = local?.hash === base.sha256;
50
+ const remoteSame = remote?.sha256 === base.sha256;
51
+ if (localSame)
52
+ return step(remote ? "download" : "trash-local");
53
+ if (remoteSame)
54
+ return step(local ? "upload" : "trash-remote");
55
+ if (!local)
56
+ return settle("deleted here, changed on the remote", "trash-remote", "download", "download");
57
+ if (!remote)
58
+ return settle("changed here, deleted on the remote", "upload", "trash-local", "upload");
59
+ return settle("changed on both sides", "upload", "download", "keep-both");
60
+ function settle(reason, ...[ifLocal, ifRemote, ifBoth]) {
61
+ if (keep === "local")
62
+ return step(ifLocal);
63
+ if (keep === "remote")
64
+ return step(ifRemote);
65
+ if (keep === "both")
66
+ return step(ifBoth);
67
+ return step("conflict", reason);
68
+ }
69
+ };
70
+ /** `name (conflict 2026-11-18 disk).ext`, numbered when that name is taken. */
71
+ const copyName = (path, remote, date, taken) => {
72
+ const extension = posix.extname(path);
73
+ const stem = path.slice(0, path.length - extension.length);
74
+ for (let n = 1;; n++) {
75
+ const candidate = `${stem} (conflict ${date} ${remote}${n > 1 ? ` ${n}` : ""})${extension}`;
76
+ if (!taken(candidate))
77
+ return candidate;
78
+ }
79
+ };
80
+ /** Moves a file into `<root>/.wirecat-trash/<date>/` while it still has `hash`; false when it changed. */
81
+ const trashLocal = async (root, path, hash, date) => {
82
+ await assertNoLink(root, path);
83
+ await assertNoLink(root, posix.join(TRASH, date, path));
84
+ const from = join(root, path);
85
+ if ((await hashFile(from)).sha256 !== hash)
86
+ return false;
87
+ const into = join(root, TRASH, date, path);
88
+ await mkdir(dirname(into), { recursive: true });
89
+ for (let n = 1;; n++) {
90
+ try {
91
+ await placeNew(from, n > 1 ? `${into}.${n}` : into);
92
+ break;
93
+ }
94
+ catch (error) {
95
+ if (error.code !== "EEXIST")
96
+ throw error;
97
+ }
98
+ }
99
+ await unlink(from);
100
+ return true;
101
+ };
102
+ /** Renames a local file while it still has `hash` and nothing holds the new name; false otherwise. */
103
+ const renameLocal = async (root, from, to, hash) => {
104
+ await assertNoLink(root, from);
105
+ await assertNoLink(root, to);
106
+ const source = join(root, from);
107
+ if ((await hashFile(source)).sha256 !== hash)
108
+ return false;
109
+ await mkdir(dirname(join(root, to)), { recursive: true });
110
+ try {
111
+ await placeNew(source, join(root, to));
112
+ }
113
+ catch (error) {
114
+ if (error.code === "EEXIST")
115
+ return false;
116
+ throw error;
117
+ }
118
+ await unlink(source);
119
+ return true;
120
+ };
121
+ /** Every local file, hashed only when its size or mtime moved since the last sync. */
122
+ const scan = async (root, entries, maxFiles) => {
123
+ const { files, links } = await scanLocal(root, () => "file", maxFiles, (path) => {
124
+ const entry = entries[path];
125
+ return entry && { size: entry.localSize, mtimeMs: entry.localMtimeMs, hash: entry.sha256 };
126
+ });
127
+ return { files: files, links };
128
+ };
129
+ /** Remote files the mirror covers: hidden files and editor leftovers are skipped, as they are locally. */
130
+ const mirrored = (files) => files.filter((file) => !file.path.split("/").some(skippedName));
131
+ /** True when `path` is `link` or lies under it. */
132
+ const under = (path, link) => path === link || path.startsWith(`${link}/`);
133
+ /**
134
+ * Syncs a local folder and a remote folder of plain files both ways, whole files at a time. Each path is compared
135
+ * three ways (local now, remote now, last sync): a change on one side is copied to the other, the same content on
136
+ * both is adopted, and different changes on both are a conflict unless `keep` settles it. Deletions go to the
137
+ * remote's trash and to `<root>/.wirecat-trash/`. A remote rename, found by the file's id, renames the local file.
138
+ * Every write is conditional on what the listing saw, so a crash at any point is settled by the next run.
139
+ */
140
+ export const syncFileMirror = async (options) => {
141
+ const { root, folder, target, principal, keep, signal, versions } = options;
142
+ const now = options.now ?? Date.now;
143
+ if (signal?.aborted)
144
+ throw new CliError("cancelled", "sync was cancelled");
145
+ if ((await target.identity()) !== principal)
146
+ throw new CliError("authentication_error", "signed-in account does not match this profile", {
147
+ reason: "profile.wrong-account",
148
+ });
149
+ const state = options.state.read();
150
+ if (state.principal !== principal || state.root !== root || state.target !== folder)
151
+ throw new CliError("configuration_error", "mirror state belongs to another account or mirror");
152
+ const listed = await target.list(folder, signal);
153
+ const localRoot = await stat(root).catch(() => undefined);
154
+ const remoteReplaced = listed !== undefined && state.rootId !== undefined && listed.rootId !== state.rootId;
155
+ const localReplaced = localRoot?.isDirectory() === true &&
156
+ state.localRoot !== undefined &&
157
+ (state.localRoot.dev !== localRoot.dev || state.localRoot.ino !== localRoot.ino);
158
+ // Only a mirror whose root really was replaced is re-pinned; `repin` on a sync of every mirror leaves the others be.
159
+ const repin = options.repin === true && (remoteReplaced || localReplaced);
160
+ // A re-pinned mirror starts over: the last sync's entries describe the folder it replaced.
161
+ const entries = repin ? {} : state.entries;
162
+ const scanned = localRoot?.isDirectory() ? await scan(root, entries, options.maxFiles) : { files: [], links: [] };
163
+ const local = new Map(scanned.files.map((file) => [file.path, file]));
164
+ const problem = (side, code, reason, repinnable = false) => ({ side, code, reason, repinnable });
165
+ // A folder that is gone, replaced, or empty where the state had files (an unmounted drive) is not this mirror.
166
+ const rootProblem = !listed
167
+ ? problem("remote", "not_found", `the ${options.remote} folder is gone`)
168
+ : remoteReplaced && !repin
169
+ ? problem("remote", "confirmation_required", `the ${options.remote} folder was replaced by another one`, true)
170
+ : !localRoot?.isDirectory()
171
+ ? problem("local", "not_found", "the local folder is gone")
172
+ : localReplaced && !repin
173
+ ? problem("local", "confirmation_required", "the local folder was replaced by another one", true)
174
+ : Object.keys(state.entries).length > 0 && !local.size
175
+ ? problem("local", "validation_error", "the local folder is empty; it may be an unmounted drive")
176
+ : undefined;
177
+ const refused = rootProblem ? [] : (listed?.files ?? []).filter((file) => !safePath(file.path));
178
+ const refusedIds = new Set(refused.map((file) => file.id));
179
+ const remote = new Map(rootProblem
180
+ ? []
181
+ : mirrored((listed?.files ?? []).filter((file) => safePath(file.path))).map((file) => [file.path, file]));
182
+ const sure = {
183
+ local: rootProblem?.side !== "local",
184
+ remote: rootProblem?.side !== "remote" && listed?.complete === true,
185
+ };
186
+ const base = { ...entries };
187
+ const steps = [];
188
+ const byId = new Map([...remote.values()].map((file) => [file.id, file]));
189
+ for (const [path, entry] of Object.entries(entries)) {
190
+ const moved = remote.has(path) ? undefined : byId.get(entry.id);
191
+ const file = local.get(path);
192
+ if (!moved || base[moved.path] || local.has(moved.path) || file?.hash !== entry.sha256)
193
+ continue;
194
+ steps.push({ kind: "rename-local", path, to: moved.path, local: file, base: entry });
195
+ base[moved.path] = entry;
196
+ delete base[path];
197
+ local.delete(path);
198
+ local.set(moved.path, { ...file, path: moved.path, absolute: join(root, moved.path) });
199
+ }
200
+ let unchanged = 0;
201
+ const touched = [];
202
+ const paths = [...new Set([...local.keys(), ...remote.keys(), ...Object.keys(base)])].sort();
203
+ const result = {
204
+ uploaded: [],
205
+ downloaded: [],
206
+ trashed: [],
207
+ renamed: [],
208
+ adopted: [],
209
+ unchanged: 0,
210
+ conflicts: [],
211
+ errors: [],
212
+ unknown: [],
213
+ };
214
+ if (rootProblem) {
215
+ const { side, code, reason, repinnable } = rootProblem;
216
+ result.unknown = Object.keys(state.entries).map((path) => ({ path, side, reason }));
217
+ result.errors.push({
218
+ path: ".",
219
+ code,
220
+ message: repinnable
221
+ ? `${reason}; if it is the right folder now, sync again with --repin to record it (that run deletes nothing)`
222
+ : reason,
223
+ });
224
+ return result;
225
+ }
226
+ for (const file of refused)
227
+ result.errors.push({
228
+ path: file.path,
229
+ code: "invalid_response",
230
+ message: `the ${options.remote} listed a path the mirror cannot use`,
231
+ });
232
+ const cutOff = new Set();
233
+ for (const path of paths) {
234
+ const entry = base[path];
235
+ if (entry && !local.has(path) && scanned.links.some((link) => under(path, link))) {
236
+ steps.push({
237
+ kind: "unknown",
238
+ path,
239
+ reason: "local",
240
+ why: "under a symbolic link, which the sync does not follow",
241
+ });
242
+ continue;
243
+ }
244
+ if (entry && !remote.has(path) && refusedIds.has(entry.id)) {
245
+ steps.push({ kind: "unknown", path, reason: "remote", why: `moved on the ${options.remote} to a refused path` });
246
+ continue;
247
+ }
248
+ const file = remote.get(path);
249
+ if (file && file.sha256 === undefined) {
250
+ result.errors.push({ path, code: "provider_error", message: `the ${options.remote} has no hash for it yet` });
251
+ continue;
252
+ }
253
+ const here = local.get(path);
254
+ // Where links fail, a download is copied into place; a crash midway leaves a partial file under the real name,
255
+ // which must be neither sent nor overwritten.
256
+ if (state.pending[path]?.op === "download" && here && here.hash !== file?.sha256 && here.hash !== entry?.sha256) {
257
+ cutOff.add(path);
258
+ steps.push({
259
+ kind: "conflict",
260
+ path,
261
+ local: here,
262
+ ...(file ? { remote: file } : {}),
263
+ reason: "an earlier download was cut off and the local file may be incomplete; move it away to download again",
264
+ });
265
+ continue;
266
+ }
267
+ // A re-pinned run settles nothing: whatever `keep` says, different content is a conflict.
268
+ const step = decide(path, sure, here, file, entry, repin ? undefined : keep);
269
+ if (step)
270
+ steps.push(step);
271
+ else
272
+ unchanged++;
273
+ // Saved without a write, so the next scan does not read a file only touched since the last sync.
274
+ if (!step && entry && here && (entry.localMtimeMs !== here.mtimeMs || entry.localSize !== here.size))
275
+ touched.push(path);
276
+ }
277
+ result.unchanged = unchanged;
278
+ const conflict = (step, reason) => result.conflicts.push({
279
+ path: step.path,
280
+ reason,
281
+ ...(step.local ? { localChangedAt: new Date(step.local.mtimeMs).toISOString(), localSize: step.local.size } : {}),
282
+ ...(step.remote ? { remoteChangedAt: step.remote.modifiedAt, remoteSize: step.remote.size } : {}),
283
+ });
284
+ for (const step of steps) {
285
+ if (step.kind === "conflict")
286
+ conflict(step, step.reason ?? "");
287
+ if (step.kind === "unknown")
288
+ result.unknown.push({
289
+ path: step.path,
290
+ side: step.reason,
291
+ reason: step.why ?? `missing from an incomplete ${options.remote} listing`,
292
+ });
293
+ }
294
+ const deletions = steps.filter((step) => step.kind === "trash-local" || step.kind === "trash-remote").length;
295
+ const tooMany = deletions > ALWAYS_DELETED &&
296
+ (deletions > MAX_DELETIONS || deletions > Object.keys(state.entries).length * MAX_DELETED_SHARE);
297
+ if (options.dryRun) {
298
+ result.plan = steps.map(({ kind, path, to }) => ({ kind, path, ...(to ? { to } : {}) }));
299
+ if (tooMany)
300
+ result.tooManyDeletions = deletions;
301
+ return result;
302
+ }
303
+ if (tooMany && (options.allowDeletions ?? 0) < deletions)
304
+ throw new CliError("confirmation_required", `this sync would delete ${deletions} files; check them with --dry-run and allow them explicitly`, { reason: "mirror.too-many-deletions", deletions });
305
+ if (repin) {
306
+ state.entries = {};
307
+ state.rootId = listed?.rootId;
308
+ if (localRoot)
309
+ state.localRoot = { dev: localRoot.dev, ino: localRoot.ino };
310
+ }
311
+ else {
312
+ state.rootId ??= listed?.rootId;
313
+ if (localRoot)
314
+ state.localRoot ??= { dev: localRoot.dev, ino: localRoot.ino };
315
+ }
316
+ for (const [path, pending] of Object.entries(state.pending)) {
317
+ if (pending.op === "download")
318
+ await rm(localTemp(join(root, path), tagOf(pending.operationId)), { force: true });
319
+ if (!cutOff.has(path))
320
+ delete state.pending[path];
321
+ }
322
+ let savedAt = now();
323
+ const save = (force = false) => {
324
+ if (!force && now() - savedAt < SAVE_EVERY_MS)
325
+ return;
326
+ options.state.save(state);
327
+ savedAt = now();
328
+ };
329
+ for (const path of touched) {
330
+ const here = local.get(path);
331
+ const entry = state.entries[path];
332
+ if (here && entry)
333
+ state.entries[path] = { ...entry, localMtimeMs: here.mtimeMs, localSize: here.size };
334
+ }
335
+ save(true);
336
+ const date = new Date(now()).toISOString().slice(0, 10);
337
+ const remotePath = (path) => posix.join(folder, path);
338
+ const folders = new Set([...remote.keys()].map((path) => posix.dirname(path)));
339
+ for (const path of [...folders])
340
+ for (let up = path; up !== "."; up = posix.dirname(up))
341
+ folders.add(up);
342
+ let lastOperation = "";
343
+ const write = (action, side, path, act, operationId) => {
344
+ options.assertHeld();
345
+ lastOperation = operationId ?? options.operationId();
346
+ return options.guard({ action, side, path, operationId: lastOperation }, act);
347
+ };
348
+ const record = (path, file, placed, sha256) => {
349
+ state.entries[path] = {
350
+ id: file.id,
351
+ size: file.size,
352
+ sha256,
353
+ ...(file.md5 ? { md5: file.md5 } : {}),
354
+ remoteModified: file.modifiedAt,
355
+ localMtimeMs: placed.mtimeMs,
356
+ localSize: placed.size,
357
+ syncedAt: new Date(now()).toISOString(),
358
+ };
359
+ save();
360
+ };
361
+ const upload = async (path, from, expect, created) => {
362
+ for (const up of ancestors(path))
363
+ if (!folders.has(up)) {
364
+ await write("folder", "remote", up, () => target.ensureFolder(remotePath(up), signal));
365
+ folders.add(up);
366
+ }
367
+ const sent = await write(created ? "create" : "update", "remote", path, () => target.upload(remotePath(path), from.absolute, expect, signal));
368
+ if (sent.sha256 !== undefined && sent.sha256 !== from.hash)
369
+ throw new CliError("conflict", "the local file changed during the upload", { reason: "upload.mismatch" });
370
+ record(path, sent, from, from.hash);
371
+ versions.log({
372
+ path,
373
+ event: created ? "created" : "changed",
374
+ direction: "local-to-remote",
375
+ ...("sha256" in expect ? { old: expect.sha256 } : {}),
376
+ new: from.hash,
377
+ size: from.size,
378
+ });
379
+ result.uploaded.push(path);
380
+ };
381
+ /**
382
+ * False when the local file changed (or appeared) during the sync, so nothing was written. Without `recorded`, the
383
+ * caller records the file once it is on both sides.
384
+ */
385
+ const download = async (path, file, over, recorded = true) => {
386
+ const operationId = options.operationId();
387
+ state.pending[path] = { op: "download", operationId };
388
+ save(true);
389
+ const absolute = join(root, path);
390
+ await assertNoLink(root, path);
391
+ await mkdir(dirname(absolute), { recursive: true });
392
+ const old = over ? await versions.keep(absolute) : undefined;
393
+ const written = await write(over ? "update" : "create", "local", path, () => replaceLocal(absolute, over?.hash, (temp) => target.download(remotePath(file.path), temp, signal), {
394
+ tag: tagOf(operationId),
395
+ sha256: file.sha256,
396
+ }), operationId);
397
+ delete state.pending[path];
398
+ if (!written)
399
+ return false;
400
+ if (recorded)
401
+ record(path, file, await stat(absolute), written.sha256);
402
+ versions.log({
403
+ path,
404
+ event: old ? "changed" : "created",
405
+ direction: "remote-to-local",
406
+ ...(old ? { old } : {}),
407
+ new: written.sha256,
408
+ size: file.size,
409
+ });
410
+ result.downloaded.push(path);
411
+ return true;
412
+ };
413
+ const expectOf = (file) => file ? { sha256: file.sha256, ...(file.md5 ? { md5: file.md5 } : {}) } : { absent: true };
414
+ const changedHere = (step) => conflict(step, "the local file changed during the sync");
415
+ const run = async (step) => {
416
+ const { path, local: here, remote: there, base: last } = step;
417
+ switch (step.kind) {
418
+ case "conflict":
419
+ return;
420
+ case "adopt":
421
+ if (here && there)
422
+ record(path, there, here, here.hash);
423
+ result.adopted.push(path);
424
+ return;
425
+ case "forget":
426
+ delete state.entries[path];
427
+ save();
428
+ return;
429
+ case "upload":
430
+ if (here)
431
+ await upload(path, here, expectOf(there), !there);
432
+ return;
433
+ case "download":
434
+ if (there && !(await download(path, there, here)))
435
+ changedHere(step);
436
+ return;
437
+ case "trash-remote":
438
+ if (!there)
439
+ return;
440
+ await write("delete", "remote", path, () => target.trash(remotePath(path), { sha256: there.sha256, ...(there.md5 ? { md5: there.md5 } : {}) }, signal));
441
+ delete state.entries[path];
442
+ save();
443
+ versions.log({
444
+ path,
445
+ event: "deleted",
446
+ direction: "local-to-remote",
447
+ old: there.sha256,
448
+ size: there.size,
449
+ });
450
+ result.trashed.push({ path, side: "remote" });
451
+ return;
452
+ case "trash-local": {
453
+ if (!here)
454
+ return;
455
+ const old = await versions.keep(here.absolute);
456
+ if (!(await write("delete", "local", path, () => trashLocal(root, path, here.hash, date))))
457
+ return changedHere(step);
458
+ delete state.entries[path];
459
+ save();
460
+ versions.log({ path, event: "deleted", direction: "remote-to-local", old, size: here.size });
461
+ result.trashed.push({ path, side: "local" });
462
+ return;
463
+ }
464
+ case "rename-local": {
465
+ const to = step.to;
466
+ if (!last || !(await write("move", "local", to, () => renameLocal(root, path, to, last.sha256))))
467
+ return changedHere(step);
468
+ const placed = await stat(join(root, to));
469
+ state.entries[to] = { ...last, localMtimeMs: placed.mtimeMs, localSize: placed.size };
470
+ delete state.entries[path];
471
+ save();
472
+ versions.log({ path, event: "renamed", direction: "remote-to-local", to, new: last.sha256, size: last.size });
473
+ result.renamed.push({ from: path, to });
474
+ return;
475
+ }
476
+ case "keep-both": {
477
+ if (!here || !there)
478
+ return;
479
+ // The remote version lands beside the local one first, so the overwrite below loses nothing. The copy is
480
+ // recorded only by its upload: recorded earlier, a failed upload would make it look deleted remotely.
481
+ const copy = copyName(path, options.remote, date, (name) => local.has(name) || remote.has(name));
482
+ if (!(await download(copy, there, undefined, false)))
483
+ return changedHere(step);
484
+ await upload(path, here, expectOf(there), false);
485
+ const { size, mtimeMs } = await stat(join(root, copy));
486
+ const copied = { ...here, path: copy, absolute: join(root, copy), hash: there.sha256, size, mtimeMs };
487
+ await upload(copy, copied, { absent: true }, true);
488
+ return;
489
+ }
490
+ }
491
+ };
492
+ try {
493
+ for (const step of steps) {
494
+ if (signal?.aborted) {
495
+ result.stopped = true;
496
+ break;
497
+ }
498
+ try {
499
+ await run(step);
500
+ }
501
+ catch (error) {
502
+ const failure = options.errorOf(error);
503
+ if (failure.code === "cancelled") {
504
+ result.stopped = true;
505
+ break;
506
+ }
507
+ if (failure.code === "conflict")
508
+ conflict(step, failure.details?.reason === "upload.mismatch"
509
+ ? failure.message
510
+ : `the ${options.remote} file changed during the sync`);
511
+ else
512
+ result.errors.push({ path: step.path, code: failure.code, message: failure.message });
513
+ // Not retried: the next listing shows whether it landed, and adopts it when it did.
514
+ if (failure.code === "outcome_unknown")
515
+ state.pending[step.path] = { op: step.kind, operationId: lastOperation };
516
+ }
517
+ }
518
+ }
519
+ finally {
520
+ save(true);
521
+ }
522
+ options.assertHeld();
523
+ await versions.prune();
524
+ return result;
525
+ };
526
+ const ancestors = (path) => {
527
+ const found = [];
528
+ for (let up = posix.dirname(path); up !== "."; up = posix.dirname(up))
529
+ found.unshift(up);
530
+ return found;
531
+ };
532
+ const entrySchema = v.object({
533
+ id: v.string(),
534
+ size: v.number(),
535
+ sha256: v.string(),
536
+ md5: v.optional(v.string()),
537
+ remoteModified: v.string(),
538
+ localMtimeMs: v.number(),
539
+ localSize: v.number(),
540
+ syncedAt: v.string(),
541
+ });
542
+ const stateSchema = v.object({
543
+ version: v.literal(1),
544
+ principal: v.string(),
545
+ root: v.string(),
546
+ target: v.string(),
547
+ rootId: v.optional(v.string()),
548
+ localRoot: v.optional(v.object({ dev: v.number(), ino: v.number() })),
549
+ entries: v.record(v.string(), entrySchema),
550
+ pending: v.record(v.string(), v.object({ op: v.string(), operationId: v.string() })),
551
+ });
552
+ /** A file mirror's state in `<dir>/<id>.json`, refused rather than reset when invalid. */
553
+ export const fileSyncState = (dir, mirror, principal) => jsonState(join(dir, `${mirror.id}.json`), stateSchema, () => ({
554
+ version: 1,
555
+ principal,
556
+ root: mirror.path,
557
+ target: mirror.folder,
558
+ entries: {},
559
+ pending: {},
560
+ }));
561
+ /** What each mirror's next sync would send from local changes alone; the remote is not asked. */
562
+ export const fileMirrorStatus = async (mirrors, stateOf) => {
563
+ const items = [];
564
+ for (const mirror of mirrors) {
565
+ const { entries } = stateOf(mirror).read();
566
+ const { files, links } = await scan(mirror.path, entries);
567
+ const seen = new Set(files.map((file) => file.path));
568
+ items.push({
569
+ id: mirror.id,
570
+ path: mirror.path,
571
+ folder: mirror.folder,
572
+ upload: files.filter((file) => entries[file.path]?.sha256 !== file.hash).map((file) => file.path),
573
+ delete: Object.keys(entries).filter((path) => !seen.has(path) && !links.some((link) => under(path, link))),
574
+ unchanged: files.length - files.filter((file) => entries[file.path]?.sha256 !== file.hash).length,
575
+ remote_checked: false,
576
+ });
577
+ }
578
+ return items;
579
+ };
580
+ /**
581
+ * A watch's `remoteChanges` for a file target: every mirror when the remote's revision moved since the last poll (or
582
+ * at the first poll), none when it did not, and every mirror at each poll when the target has no revision.
583
+ */
584
+ export const fileRemoteChanges = (target) => {
585
+ let last;
586
+ return async (signal) => {
587
+ if (!target.revision)
588
+ return "all";
589
+ const revision = await target.revision(signal);
590
+ const moved = revision !== last;
591
+ last = revision;
592
+ return moved ? "all" : [];
593
+ };
594
+ };
595
+ /** Syncs each file mirror under one lock, with one `mirror.partial` issue per mirror left with conflicts or errors. */
596
+ export const syncFileMirrors = (options) => eachMirror(options.mirrors, options.lock, options.remote, (mirror, assertHeld) => syncFileMirror({
597
+ ...options,
598
+ root: mirror.path,
599
+ folder: mirror.folder,
600
+ state: options.stateOf(mirror),
601
+ versions: options.versionsOf(mirror),
602
+ assertHeld,
603
+ }));
@@ -0,0 +1,50 @@
1
+ /** Which way a sync moved a change. */
2
+ export type VersionDirection = "local-to-remote" | "remote-to-local" | "restored";
3
+ /** One line of a mirror's version log: what a sync did to a path, with the content's hash before and after. */
4
+ export interface VersionEvent {
5
+ at: string;
6
+ path: string;
7
+ event: "created" | "changed" | "deleted" | "renamed";
8
+ direction: VersionDirection;
9
+ /** The content the change replaced: the local file kept before a pull or deletion, the remote version an upload replaced. */
10
+ old?: string;
11
+ new?: string;
12
+ size?: number;
13
+ /** A rename's new path. */
14
+ to?: string;
15
+ }
16
+ /** A version of a path, and whether its bytes are still in the store. */
17
+ export interface FileVersion extends VersionEvent {
18
+ available: boolean;
19
+ }
20
+ export interface FileVersions {
21
+ /** Copies the file into the store before the sync overwrites or deletes it; returns the hash of what it copied. */
22
+ keep(absolute: string): Promise<string>;
23
+ log(event: Omit<VersionEvent, "at">): void;
24
+ /** Every event of `path`, oldest first, including renames to or from it. */
25
+ list(path: string): FileVersion[];
26
+ /**
27
+ * Writes a kept version to `into`, replacing the file only while it has `over`, or creating it when `over` is
28
+ * undefined. False when the store no longer has the version or the file was not as `over` said.
29
+ */
30
+ write(sha256: string, into: string, over?: string): Promise<boolean>;
31
+ /** Applies the retention rule; see `fileVersions`. A sync runs it under its lock; call it only under that lock. */
32
+ prune(): Promise<void>;
33
+ }
34
+ /**
35
+ * A mirror's local version store: `<dir>/objects/<sha256>` holds each kept content once, `<dir>/log.jsonl` is
36
+ * append-only. The store lives under the profile's state folder, never inside the mirrored folder. Retention, one
37
+ * rule: a content stays while an event newer than 30 days names it, and the last content of a path whose newest
38
+ * event is a deletion stays for good. A content no event names stays 30 days after it was last kept, so a crash
39
+ * between keeping a file and logging the change loses nothing.
40
+ */
41
+ export declare const fileVersions: (dir: string, now?: () => number) => FileVersions;
42
+ /**
43
+ * Puts a kept version of `path` back into the mirrored folder; the file there now is kept first. The next sync sends
44
+ * it like any local change. False when the store no longer has the version or the file changed meanwhile. Runs under
45
+ * the mirrors' sync lock, so a sync never reads the folder halfway through.
46
+ */
47
+ export declare const restoreFileVersion: (root: string, path: string, sha256: string, versions: FileVersions, lock: () => Promise<{
48
+ assertHeld(): void;
49
+ release(): Promise<void> | void;
50
+ }>) => Promise<boolean>;