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