@wirecat/cli-core 0.719.0 → 0.721.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 (81) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/dist/attachments/documents.d.ts +5 -0
  3. package/dist/attachments/documents.js +2 -2
  4. package/dist/background/daily-archive-timer.d.ts +1 -1
  5. package/dist/cli/config-command.js +8 -2
  6. package/dist/cli/config-issues.d.ts +3 -1
  7. package/dist/cli/config-issues.js +9 -2
  8. package/dist/cli/documents/file-conflicts.d.ts +25 -0
  9. package/dist/cli/documents/file-conflicts.js +102 -0
  10. package/dist/cli/documents/file-edit.d.ts +29 -0
  11. package/dist/cli/documents/file-edit.js +352 -0
  12. package/dist/cli/documents/file-update.d.ts +43 -0
  13. package/dist/cli/documents/file-update.js +95 -0
  14. package/dist/cli/documents/history.d.ts +34 -0
  15. package/dist/cli/documents/history.js +89 -0
  16. package/dist/cli/documents/index.d.ts +9 -2
  17. package/dist/cli/documents/index.js +9 -2
  18. package/dist/cli/documents/library.js +10 -0
  19. package/dist/cli/permission-keys.d.ts +6 -0
  20. package/dist/cli/permission-keys.js +15 -3
  21. package/dist/cli/service-api.d.ts +1 -1
  22. package/dist/cli/service-api.js +16 -34
  23. package/dist/documents/file-mirror-model.d.ts +32 -1
  24. package/dist/documents/index.d.ts +7 -4
  25. package/dist/documents/index.js +4 -1
  26. package/dist/documents/model.d.ts +16 -1
  27. package/dist/errors/reasons.js +6 -1
  28. package/dist/office/docx.d.ts +43 -0
  29. package/dist/office/docx.js +349 -0
  30. package/dist/office/index.d.ts +2 -0
  31. package/dist/office/index.js +2 -0
  32. package/dist/office/package.d.ts +39 -0
  33. package/dist/office/package.js +98 -0
  34. package/dist/office/xlsx.d.ts +55 -0
  35. package/dist/office/xlsx.js +550 -0
  36. package/dist/office/xml.d.ts +34 -0
  37. package/dist/office/xml.js +186 -0
  38. package/dist/office/zip.d.ts +10 -0
  39. package/dist/office/zip.js +116 -0
  40. package/dist/services/documents/block-diff.d.ts +13 -3
  41. package/dist/services/documents/block-diff.js +13 -7
  42. package/dist/services/documents/ingestion.d.ts +21 -2
  43. package/dist/services/documents/ingestion.js +29 -2
  44. package/dist/services/documents/plan.js +16 -7
  45. package/dist/services/documents/ports.d.ts +2 -0
  46. package/dist/services/documents/sync.d.ts +1 -0
  47. package/dist/services/documents/sync.js +9 -4
  48. package/dist/services/files/conflicts.d.ts +78 -0
  49. package/dist/services/files/conflicts.js +183 -0
  50. package/dist/services/files/guarded-write.d.ts +34 -0
  51. package/dist/services/files/guarded-write.js +42 -0
  52. package/dist/services/files/listing.d.ts +36 -0
  53. package/dist/services/files/listing.js +47 -0
  54. package/dist/services/files/local-files.d.ts +54 -0
  55. package/dist/services/files/local-files.js +143 -0
  56. package/dist/services/files/mirror-state.d.ts +14 -0
  57. package/dist/services/files/mirror-state.js +65 -0
  58. package/dist/services/files/mirror.d.ts +4 -14
  59. package/dist/services/files/mirror.js +177 -204
  60. package/dist/services/files/text-merge.d.ts +27 -0
  61. package/dist/services/files/text-merge.js +134 -0
  62. package/dist/services/files/versions.d.ts +36 -9
  63. package/dist/services/files/versions.js +40 -12
  64. package/dist/store/index.d.ts +2 -0
  65. package/dist/store/index.js +1 -0
  66. package/dist/store/people.d.ts +8 -0
  67. package/dist/store/people.js +2 -0
  68. package/dist/store/sqlite/account-purge.js +3 -0
  69. package/dist/store/sqlite/document-history.d.ts +84 -0
  70. package/dist/store/sqlite/document-history.js +158 -0
  71. package/dist/store/sqlite/manifest.js +2 -0
  72. package/dist/store/sqlite/migrations.generated.js +17 -0
  73. package/dist/store/sqlite/notes.d.ts +9 -10
  74. package/dist/store/sqlite/notes.js +33 -21
  75. package/dist/store/sqlite/person-erase.d.ts +39 -0
  76. package/dist/store/sqlite/person-erase.js +152 -0
  77. package/dist/store/sqlite/schema/document-changes.d.ts +136 -0
  78. package/dist/store/sqlite/schema/document-changes.js +11 -0
  79. package/dist/store/sqlite/schema.d.ts +65 -0
  80. package/dist/store/sqlite/schema.js +5 -0
  81. package/package.json +6 -2
@@ -0,0 +1,65 @@
1
+ import { join } from "node:path";
2
+ import * as v from "valibot";
3
+ import { jsonState } from "../documents/mirrors.js";
4
+ import { excludedBy } from "./exclusions.js";
5
+ import { listingSchema, remoteFileSchema } from "./listing.js";
6
+ import { scan, under } from "./local-files.js";
7
+ const entrySchema = v.object({
8
+ id: v.string(),
9
+ size: v.number(),
10
+ sha256: v.string(),
11
+ md5: v.optional(v.string()),
12
+ remoteModified: v.string(),
13
+ localMtimeMs: v.number(),
14
+ localSize: v.number(),
15
+ syncedAt: v.string(),
16
+ });
17
+ const stateSchema = v.object({
18
+ version: v.literal(1),
19
+ principal: v.string(),
20
+ root: v.string(),
21
+ target: v.string(),
22
+ rootId: v.optional(v.string()),
23
+ localRoot: v.optional(v.object({ dev: v.number(), ino: v.number() })),
24
+ entries: v.record(v.string(), entrySchema),
25
+ pending: v.record(v.string(), v.object({ op: v.string(), operationId: v.string(), created: v.optional(v.boolean()) })),
26
+ listing: v.optional(listingSchema),
27
+ conflicts: v.optional(v.record(v.string(), v.object({
28
+ reason: v.string(),
29
+ at: v.string(),
30
+ base: v.optional(v.string()),
31
+ local: v.optional(v.string()),
32
+ remote: v.optional(v.string()),
33
+ remoteFile: v.optional(remoteFileSchema),
34
+ kept: v.optional(v.boolean()),
35
+ }))),
36
+ });
37
+ /** A file mirror's state in `<dir>/<id>.json`, refused rather than reset when invalid. */
38
+ export const fileSyncState = (dir, mirror, principal) => jsonState(join(dir, `${mirror.id}.json`), stateSchema, () => ({
39
+ version: 1,
40
+ principal,
41
+ root: mirror.path,
42
+ target: mirror.folder,
43
+ entries: {},
44
+ pending: {},
45
+ }));
46
+ /** What each mirror's next sync would send from local changes alone; the remote is not asked. */
47
+ export const fileMirrorStatus = async (mirrors, stateOf) => {
48
+ const items = [];
49
+ for (const mirror of mirrors) {
50
+ const excluded = excludedBy(mirror.exclude);
51
+ const entries = Object.fromEntries(Object.entries(stateOf(mirror).read().entries).filter(([path]) => !excluded(path)));
52
+ const { files, links } = await scan(mirror.path, entries, excluded);
53
+ const seen = new Set(files.map((file) => file.path));
54
+ items.push({
55
+ id: mirror.id,
56
+ path: mirror.path,
57
+ folder: mirror.folder,
58
+ upload: files.filter((file) => entries[file.path]?.sha256 !== file.hash).map((file) => file.path),
59
+ delete: Object.keys(entries).filter((path) => !seen.has(path) && !links.some((link) => under(path, link))),
60
+ unchanged: files.length - files.filter((file) => entries[file.path]?.sha256 !== file.hash).length,
61
+ remote_checked: false,
62
+ });
63
+ }
64
+ return items;
65
+ };
@@ -4,6 +4,7 @@ import type { Keep } from "../../documents/push-model.js";
4
4
  import { type HeldLock, type Mirror } from "../documents/mirrors.js";
5
5
  import { type MirrorAction, type PushConflict } from "../documents/push.js";
6
6
  import type { FileVersions } from "./versions.js";
7
+ export { fileMirrorStatus, fileSyncState } from "./mirror-state.js";
7
8
  type Side = "local" | "remote";
8
9
  export interface FileMirrorOptions {
9
10
  /** Absolute path of the local folder. */
@@ -50,7 +51,7 @@ export interface FileMirrorOptions {
50
51
  /** Throws once the sync lock is lost; checked before every write. */
51
52
  assertHeld(): void | Promise<void>;
52
53
  signal?: AbortSignal;
53
- /** Local files the mirror takes at most; more fail the run. */
54
+ /** Files the mirror takes at most: more local ones fail the run, more remote ones leave the listing incomplete. */
54
55
  maxFiles?: number;
55
56
  /** Bytes free for this process on the file system holding `path`, and its device. */
56
57
  space?(path: string): Promise<{
@@ -83,6 +84,8 @@ export interface FileStep {
83
84
  export interface FileMirrorResult {
84
85
  uploaded: string[];
85
86
  downloaded: string[];
87
+ /** Text files both sides changed, merged and written to both. */
88
+ merged: string[];
86
89
  trashed: {
87
90
  path: string;
88
91
  side: Side;
@@ -139,18 +142,6 @@ export declare const MAX_REPLACEMENTS = 50;
139
142
  * Every write is conditional on what the listing saw, so a crash at any point is settled by the next run.
140
143
  */
141
144
  export declare const syncFileMirror: (options: FileMirrorOptions) => Promise<FileMirrorResult>;
142
- /** A file mirror's state in `<dir>/<id>.json`, refused rather than reset when invalid. */
143
- export declare const fileSyncState: (dir: string, mirror: Mirror, principal: string) => FileMirrorStatePort;
144
- /** What each mirror's next sync would send from local changes alone; the remote is not asked. */
145
- export declare const fileMirrorStatus: (mirrors: Mirror[], stateOf: (mirror: Mirror) => FileMirrorStatePort) => Promise<{
146
- id: string;
147
- path: string;
148
- folder: string;
149
- upload: string[];
150
- delete: string[];
151
- unchanged: number;
152
- remote_checked: boolean;
153
- }[]>;
154
145
  /**
155
146
  * A watch's `remoteChanges` for a file target: every mirror when the remote's revision moved since the last poll (or
156
147
  * at the first poll), none when it did not, and every mirror at each poll when the target has no revision.
@@ -190,4 +181,3 @@ export declare const syncFileMirrors: (options: FileMirrorSyncOptions) => Promis
190
181
  source: string;
191
182
  }[];
192
183
  }>;
193
- export {};
@@ -1,11 +1,14 @@
1
1
  import { createHash } from "node:crypto";
2
- import { mkdir, rm, stat, statfs, unlink } from "node:fs/promises";
2
+ import { mkdir, rm, stat, writeFile } from "node:fs/promises";
3
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";
4
+ import { CliError } from "@wirecat/cli-base";
5
+ import { eachMirror, heldCheck } from "../documents/mirrors.js";
6
+ import { assertNoLink, localTemp, replaceLocal, safePath, skippedName, } from "../documents/push.js";
8
7
  import { excludedBy } from "./exclusions.js";
8
+ import { listRemote } from "./listing.js";
9
+ import { ancestors, copyName, freeSpace, gigabytes, linkFree, MAX_FILES, renameLocal, scan, shortOfSpace, spareFor, trashLocal, under, whole, } from "./local-files.js";
10
+ import { mergeable, mergeText } from "./text-merge.js";
11
+ export { fileMirrorStatus, fileSyncState } from "./mirror-state.js";
9
12
  const HINTS = {
10
13
  preview: "--dry-run",
11
14
  repin: "--repin",
@@ -21,11 +24,9 @@ const HINTS = {
21
24
  */
22
25
  export const MAX_DELETIONS = 10;
23
26
  export const MAX_REPLACEMENTS = 50;
24
- /** What a run leaves free on a drive it writes to: a tenth of what it writes, from 100 MB up to 1 GB. */
25
- const spareFor = (needed) => Math.min(1024 ** 3, Math.max(100 * 1024 ** 2, needed / 10));
26
- const MAX_FILES = 100_000;
27
+ /** The whole-file step `keep` settles a conflict with when both sides changed. */
28
+ const KEPT = { local: "upload", remote: "download", both: "keep-both" };
27
29
  const CHECKS = 8;
28
- const TRASH = ".wirecat-trash";
29
30
  const SAVE_EVERY_MS = 1_000;
30
31
  /** A temporary file's tag from any operation id, safe in a file name. */
31
32
  const tagOf = (operationId) => createHash("sha256").update(operationId).digest("hex").slice(0, 8);
@@ -34,7 +35,7 @@ const sameFile = (local, remote) => local.hash === remote.sha256;
34
35
  * The three-way comparison of one path: the local file now, the remote file now and the last sync. A side is
35
36
  * "same" when its content still has the last sync's hash.
36
37
  */
37
- const decide = (path, sure, local, remote, base, keep) => {
38
+ const decide = (path, sure, local, remote, base, keep, merges = false) => {
38
39
  const step = (kind, reason) => ({
39
40
  kind,
40
41
  path,
@@ -69,6 +70,8 @@ const decide = (path, sure, local, remote, base, keep) => {
69
70
  return settle("deleted here, changed on the remote", "trash-remote", "download", "download");
70
71
  if (!remote)
71
72
  return settle("changed here, deleted on the remote", "upload", "trash-local", "upload");
73
+ if (merges)
74
+ return step("merge");
72
75
  return settle("changed on both sides", "upload", "download", "keep-both");
73
76
  function settle(reason, ...[ifLocal, ifRemote, ifBoth]) {
74
77
  if (keep === "local")
@@ -80,98 +83,8 @@ const decide = (path, sure, local, remote, base, keep) => {
80
83
  return step("conflict", reason);
81
84
  }
82
85
  };
83
- /** `name (conflict 2026-11-18 disk).ext`, numbered when that name is taken. */
84
- const copyName = (path, remote, date, taken) => {
85
- const extension = posix.extname(path);
86
- const stem = path.slice(0, path.length - extension.length);
87
- for (let n = 1;; n++) {
88
- const candidate = `${stem} (conflict ${date} ${remote}${n > 1 ? ` ${n}` : ""})${extension}`;
89
- if (!taken(candidate))
90
- return candidate;
91
- }
92
- };
93
- /** Moves a file into `<root>/.wirecat-trash/<date>/` while it still has `hash`; false when it changed. */
94
- const trashLocal = async (root, path, hash, date) => {
95
- await assertNoLink(root, path);
96
- await assertNoLink(root, posix.join(TRASH, date, path));
97
- const from = join(root, path);
98
- if ((await hashFile(from)).sha256 !== hash)
99
- return false;
100
- const into = join(root, TRASH, date, path);
101
- await mkdir(dirname(into), { recursive: true });
102
- for (let n = 1;; n++) {
103
- try {
104
- await placeNew(from, n > 1 ? `${into}.${n}` : into);
105
- break;
106
- }
107
- catch (error) {
108
- if (error.code !== "EEXIST")
109
- throw error;
110
- }
111
- }
112
- await unlink(from);
113
- return true;
114
- };
115
- /** Renames a local file while it still has `hash` and nothing holds the new name; false otherwise. */
116
- const renameLocal = async (root, from, to, hash) => {
117
- await assertNoLink(root, from);
118
- await assertNoLink(root, to);
119
- const source = join(root, from);
120
- if ((await hashFile(source)).sha256 !== hash)
121
- return false;
122
- await mkdir(dirname(join(root, to)), { recursive: true });
123
- try {
124
- await placeNew(source, join(root, to));
125
- }
126
- catch (error) {
127
- if (error.code === "EEXIST")
128
- return false;
129
- throw error;
130
- }
131
- await unlink(source);
132
- return true;
133
- };
134
- /** Every local file but excluded ones, hashed only when its size or mtime moved since the last sync. */
135
- const scan = async (root, entries, excluded, maxFiles = MAX_FILES) => {
136
- const { files, links } = await scanLocal(root, () => "file", maxFiles, (path) => {
137
- const entry = entries[path];
138
- return entry && { size: entry.localSize, mtimeMs: entry.localMtimeMs, hash: entry.sha256 };
139
- }, excluded);
140
- return { files: files, links };
141
- };
142
86
  /** Remote files the mirror covers: hidden files and editor leftovers are skipped, as they are locally. */
143
87
  const mirrored = (files) => files.filter((file) => !file.path.split("/").some(skippedName));
144
- /** False when `path` or a folder on the way to it is a symbolic link, so nothing under it is touched. */
145
- const linkFree = (root, path) => assertNoLink(root, path).then(() => true, (error) => {
146
- if (isCliError(error) && error.details?.reason === "mirror.symlink")
147
- return false;
148
- throw error;
149
- });
150
- /** True when the file at `absolute` is missing or has one of `hashes`: no partial copy is left there. */
151
- const whole = async (absolute, hashes) => {
152
- try {
153
- return hashes.includes((await hashFile(absolute)).sha256);
154
- }
155
- catch (error) {
156
- return error.code === "ENOENT";
157
- }
158
- };
159
- /** True when `path` is `link` or lies under it. */
160
- const under = (path, link) => path === link || path.startsWith(`${link}/`);
161
- /** Free bytes and the device of the file system holding `path`, or of its nearest folder that exists. */
162
- const freeSpace = async (path) => {
163
- for (let at = path;; at = dirname(at)) {
164
- try {
165
- const [{ bavail, bsize }, { dev }] = await Promise.all([statfs(at), stat(at)]);
166
- return { free: bavail * bsize, dev };
167
- }
168
- catch (error) {
169
- if (error.code !== "ENOENT" || dirname(at) === at)
170
- throw error;
171
- }
172
- }
173
- };
174
- const gigabytes = (bytes) => `${(bytes / 1024 ** 3).toFixed(1)} GB`;
175
88
  /**
176
89
  * Syncs a local folder and a remote folder of plain files both ways, whole files at a time. Each path is compared
177
90
  * three ways (local now, remote now, last sync): a change on one side is copied to the other, the same content on
@@ -194,7 +107,16 @@ export const syncFileMirror = async (options) => {
194
107
  const state = options.state.read();
195
108
  if (state.principal !== principal || state.root !== root || state.target !== folder)
196
109
  throw new CliError("configuration_error", "mirror state belongs to another account or mirror");
197
- const listed = await target.list(folder, signal, { excluded });
110
+ const { listed, progress } = await listRemote(target, folder, signal, excluded, state.listing, now(), options.maxFiles ?? MAX_FILES);
111
+ // Kept before any refusal below, so a stopped run's pages are not listed again. A completed listing's progress is
112
+ // cleared only once the run gets past its refusals: a run stopped by the guard goes on from there.
113
+ if (!options.dryRun && listed?.complete !== true && (progress || state.listing)) {
114
+ if (progress)
115
+ state.listing = progress;
116
+ else
117
+ delete state.listing;
118
+ options.state.save(state);
119
+ }
198
120
  const localRoot = await stat(root).catch(() => undefined);
199
121
  const remoteReplaced = listed !== undefined && state.rootId !== undefined && listed.rootId !== state.rootId;
200
122
  const localReplaced = localRoot?.isDirectory() === true &&
@@ -254,6 +176,7 @@ export const syncFileMirror = async (options) => {
254
176
  const result = {
255
177
  uploaded: [],
256
178
  downloaded: [],
179
+ merged: [],
257
180
  trashed: [],
258
181
  renamed: [],
259
182
  adopted: [],
@@ -332,7 +255,23 @@ export const syncFileMirror = async (options) => {
332
255
  continue;
333
256
  }
334
257
  // A re-pinned run settles nothing: whatever `keep` says, different content is a conflict.
335
- const step = decide(path, sure, here, file, entry, repin ? undefined : keep);
258
+ // Asked only of a file both sides changed: the store is not read for every unchanged one.
259
+ const merges = here !== undefined &&
260
+ file !== undefined &&
261
+ entry !== undefined &&
262
+ here.hash !== entry.sha256 &&
263
+ file.sha256 !== entry.sha256 &&
264
+ mergeable(path, here.size, file.size, entry.size) &&
265
+ versions.has(entry.sha256);
266
+ const step = decide(path, sure, here, file, entry, repin ? undefined : keep, merges);
267
+ // The same three contents the last run could not merge are not downloaded and merged again at every watch cycle.
268
+ const known = state.conflicts?.[path];
269
+ if (step?.kind === "merge" &&
270
+ known?.kept &&
271
+ known.base === entry?.sha256 &&
272
+ known.local === here?.hash &&
273
+ known.remote === file?.sha256)
274
+ Object.assign(step, keep ? { kind: KEPT[keep] } : { kind: "conflict", reason: known.reason });
336
275
  if (step)
337
276
  steps.push(step);
338
277
  else
@@ -356,12 +295,37 @@ export const syncFileMirror = async (options) => {
356
295
  if (why)
357
296
  Object.assign(step, { kind: "unknown", reason: "remote", why });
358
297
  }));
359
- const conflict = (step, reason) => result.conflicts.push({
360
- path: step.path,
361
- reason,
362
- ...(step.local ? { localChangedAt: new Date(step.local.mtimeMs).toISOString(), localSize: step.local.size } : {}),
363
- ...(step.remote ? { remoteChangedAt: step.remote.modifiedAt, remoteSize: step.remote.size } : {}),
364
- });
298
+ const earlier = state.conflicts ?? {};
299
+ const conflicts = {};
300
+ /** Reports and records a conflict; `kept` are the contents a failed merge kept, logged once per set of them. */
301
+ const conflict = (step, reason, kept) => {
302
+ result.conflicts.push({
303
+ path: step.path,
304
+ reason,
305
+ ...(kept?.segments ? { parts: kept.segments } : {}),
306
+ ...(step.local ? { localChangedAt: new Date(step.local.mtimeMs).toISOString(), localSize: step.local.size } : {}),
307
+ ...(step.remote ? { remoteChangedAt: step.remote.modifiedAt, remoteSize: step.remote.size } : {}),
308
+ });
309
+ const found = {
310
+ reason,
311
+ at: new Date(now()).toISOString(),
312
+ ...(step.base ? { base: step.base.sha256 } : {}),
313
+ ...(step.local ? { local: step.local.hash } : {}),
314
+ ...(step.remote ? { remote: step.remote.sha256, remoteFile: step.remote } : {}),
315
+ };
316
+ const before = earlier[step.path];
317
+ const same = before?.base === found.base && before?.local === found.local && before?.remote === found.remote;
318
+ if (kept) {
319
+ found.kept = true;
320
+ // A conflict `keep` settles at once is no conflict anyone resolves later.
321
+ if (!keep && (!same || !before?.kept))
322
+ versions.log({ path: step.path, event: "conflict", direction: "both", parts: kept.parts });
323
+ }
324
+ else if (same && before?.kept)
325
+ found.kept = true;
326
+ // A conflict seen again keeps the time it was first found.
327
+ conflicts[step.path] = same && before ? { ...found, at: before.at } : found;
328
+ };
365
329
  for (const step of steps) {
366
330
  if (step.kind === "conflict")
367
331
  conflict(step, step.reason ?? "");
@@ -373,7 +337,10 @@ export const syncFileMirror = async (options) => {
373
337
  });
374
338
  }
375
339
  const deletions = steps.filter((step) => step.kind === "trash-local" || step.kind === "trash-remote").length;
376
- const replacements = steps.filter((step) => (step.kind === "upload" && step.remote) || (step.kind === "download" && step.local) || step.kind === "keep-both").length;
340
+ const replacements = steps.filter((step) => (step.kind === "upload" && step.remote) ||
341
+ (step.kind === "download" && step.local) ||
342
+ step.kind === "keep-both" ||
343
+ step.kind === "merge").length;
377
344
  const over = [
378
345
  ...(deletions > MAX_DELETIONS
379
346
  ? [
@@ -445,9 +412,12 @@ export const syncFileMirror = async (options) => {
445
412
  if (!cutOff.has(path))
446
413
  delete state.pending[path];
447
414
  }
415
+ if (listed?.complete)
416
+ delete state.listing;
448
417
  let savedAt = now();
449
418
  // A big mirror's state is megabytes of JSON: saved less often, it costs no more than a small one's.
450
- const saveEvery = SAVE_EVERY_MS * Math.max(1, Object.keys(state.entries).length / 10_000);
419
+ const saved = Object.keys(state.entries).length + (state.listing?.files.length ?? 0);
420
+ const saveEvery = SAVE_EVERY_MS * Math.max(1, saved / 10_000);
451
421
  const save = (force = false) => {
452
422
  if (!force && now() - savedAt < saveEvery)
453
423
  return;
@@ -499,7 +469,13 @@ export const syncFileMirror = async (options) => {
499
469
  reason: "mirror.remote-changed",
500
470
  });
501
471
  };
502
- const upload = async (path, from, expect, created, replaced) => {
472
+ /** Keeps a mergeable file's synced content, the base of its next merge; a file that changed meanwhile has none. */
473
+ const keepBase = async (path, absolute, sha256, size) => {
474
+ // A base that could not be kept costs a conflict at the next change on both sides, never this run's write.
475
+ if (mergeable(path, size) && !versions.has(sha256))
476
+ await versions.keep(absolute).catch(() => undefined);
477
+ };
478
+ const upload = async (path, from, expect, created, replaced, merged = false) => {
503
479
  if (replaced)
504
480
  await keepRemote(path, replaced);
505
481
  for (const up of ancestors(path))
@@ -511,6 +487,9 @@ export const syncFileMirror = async (options) => {
511
487
  if (sent.sha256 !== undefined && sent.sha256 !== from.hash)
512
488
  throw new CliError("conflict", "the local file changed during the upload", { reason: "upload.mismatch" });
513
489
  record(path, sent, from, from.hash);
490
+ await keepBase(path, from.absolute, from.hash, from.size);
491
+ if (merged)
492
+ return;
514
493
  versions.log({
515
494
  path,
516
495
  event: created ? "created" : "changed",
@@ -551,8 +530,10 @@ export const syncFileMirror = async (options) => {
551
530
  delete state.pending[path];
552
531
  if (!written)
553
532
  return false;
554
- if (recorded)
533
+ if (recorded) {
555
534
  record(path, file, await stat(absolute), written.sha256);
535
+ await keepBase(path, absolute, written.sha256, file.size);
536
+ }
556
537
  versions.log({
557
538
  path,
558
539
  event: old ? "changed" : "created",
@@ -566,14 +547,72 @@ export const syncFileMirror = async (options) => {
566
547
  };
567
548
  const expectOf = (file) => file ? { sha256: file.sha256, ...(file.md5 ? { md5: file.md5 } : {}) } : { absent: true };
568
549
  const changedHere = (step) => conflict(step, "the local file changed during the sync");
550
+ /**
551
+ * Merges a text file both sides changed: the remote and the local contents are kept first, the merge reads all
552
+ * three from the store, and the result is written locally, then uploaded over the remote the listing saw. False
553
+ * when the lines conflict, so `keep` can settle the file whole.
554
+ */
555
+ const merge = async (step, here, there, last) => {
556
+ const { path } = step;
557
+ const remoteHash = there.sha256;
558
+ await keepRemote(path, there);
559
+ if ((await versions.keep(here.absolute)) !== here.hash) {
560
+ changedHere(step);
561
+ return true;
562
+ }
563
+ const parts = { base: last.sha256, local: here.hash, remote: remoteHash };
564
+ const [base, mine, theirs] = await Promise.all([last.sha256, here.hash, remoteHash].map((hash) => versions.read(hash)));
565
+ if (!base || !mine || !theirs) {
566
+ conflict(step, "changed on both sides, and the earlier version to merge against is no longer kept");
567
+ return false;
568
+ }
569
+ const merged = await mergeText(path, base, mine, theirs);
570
+ if (!("merged" in merged)) {
571
+ conflict(step, "changed on both sides in the same lines", {
572
+ parts,
573
+ segments: merged.conflicts.map(({ base, local, remote }) => ({ base, local, remote })),
574
+ });
575
+ return false;
576
+ }
577
+ const outcome = await versions.keep((temp) => writeFile(temp, merged.merged, { flag: "wx", mode: 0o600 }));
578
+ const absolute = join(root, path);
579
+ await assertNoLink(root, path);
580
+ const operationId = options.operationId();
581
+ const written = await write("update", "local", path, () => replaceLocal(absolute, here.hash, merged.merged, { tag: tagOf(operationId), sha256: outcome }), operationId);
582
+ if (!written) {
583
+ changedHere(step);
584
+ return true;
585
+ }
586
+ const placed = await stat(absolute);
587
+ // Both sides as the remote is now, with a local size no file has: a crash before the upload leaves the merged
588
+ // file a local change, hashed again and sent by the next run, never merged twice.
589
+ state.entries[path] = {
590
+ id: there.id,
591
+ size: there.size,
592
+ sha256: remoteHash,
593
+ ...(there.md5 ? { md5: there.md5 } : {}),
594
+ remoteModified: there.modifiedAt,
595
+ localMtimeMs: -1,
596
+ localSize: -1,
597
+ syncedAt: new Date(now()).toISOString(),
598
+ };
599
+ save(true);
600
+ versions.log({ path, event: "merged", direction: "both", parts, new: outcome, size: placed.size });
601
+ const sent = { ...here, hash: outcome, size: placed.size, mtimeMs: placed.mtimeMs };
602
+ await upload(path, sent, expectOf(there), false, undefined, true);
603
+ result.merged.push(path);
604
+ return true;
605
+ };
569
606
  const run = async (step) => {
570
607
  const { path, local: here, remote: there, base: last } = step;
571
608
  switch (step.kind) {
572
609
  case "conflict":
573
610
  return;
574
611
  case "adopt":
575
- if (here && there)
612
+ if (here && there) {
576
613
  record(path, there, here, here.hash);
614
+ await keepBase(path, here.absolute, here.hash, here.size);
615
+ }
577
616
  result.adopted.push(path);
578
617
  return;
579
618
  case "forget":
@@ -630,6 +669,15 @@ export const syncFileMirror = async (options) => {
630
669
  result.renamed.push({ from: path, to });
631
670
  return;
632
671
  }
672
+ case "merge":
673
+ if (!here || !there || !last)
674
+ return;
675
+ if (!(await merge(step, here, there, last)) && keep) {
676
+ result.conflicts.pop();
677
+ delete conflicts[path];
678
+ return run({ ...step, kind: KEPT[keep] });
679
+ }
680
+ return;
633
681
  case "keep-both": {
634
682
  if (!here || !there)
635
683
  return;
@@ -675,108 +723,33 @@ export const syncFileMirror = async (options) => {
675
723
  state.pending[step.path] = { op: step.kind, operationId: lastOperation };
676
724
  }
677
725
  }
726
+ // A mirror synced before merges existed has no bases: an unchanged text file's content becomes its base now.
727
+ const stepped = new Set(steps.map((step) => step.path));
728
+ for (const [path, entry] of Object.entries(state.entries)) {
729
+ if (signal?.aborted)
730
+ break;
731
+ const here = local.get(path);
732
+ if (here?.hash === entry.sha256 && !stepped.has(path))
733
+ await keepBase(path, here.absolute, entry.sha256, here.size);
734
+ }
678
735
  }
679
736
  finally {
680
737
  // Forgotten, so a file whose exclusion is removed later is a new file, never a deletion.
681
738
  for (const path of Object.keys(state.entries))
682
739
  if (excluded(path))
683
740
  delete state.entries[path];
741
+ if (Object.keys(conflicts).length)
742
+ state.conflicts = conflicts;
743
+ else
744
+ delete state.conflicts;
684
745
  save(true);
685
746
  }
686
747
  await options.assertHeld();
687
- await versions.prune();
748
+ await versions.prune(Object.entries(state.entries)
749
+ .filter(([path, entry]) => mergeable(path, entry.size))
750
+ .map(([, entry]) => entry.sha256));
688
751
  return result;
689
752
  };
690
- /**
691
- * The free space a run needs that a file system lacks: downloads land under `root`, and the store keeps every
692
- * content they replace or a deletion removes, plus each remote content an upload replaces that it lacks.
693
- */
694
- const shortOfSpace = async (steps, root, versions, space) => {
695
- let incoming = 0;
696
- let kept = 0;
697
- for (const step of steps) {
698
- const local = step.local?.size ?? 0;
699
- const remote = step.remote?.size ?? 0;
700
- if (step.kind === "download") {
701
- incoming += remote;
702
- kept += local;
703
- }
704
- if (step.kind === "keep-both") {
705
- incoming += remote;
706
- kept += remote;
707
- }
708
- if (step.kind === "trash-local")
709
- kept += local;
710
- if (step.kind === "upload" && step.remote && !versions.has(step.remote.sha256))
711
- kept += remote;
712
- }
713
- if (!incoming && !kept)
714
- return undefined;
715
- const here = await space(root);
716
- const store = versions.dir === undefined ? here : await space(versions.dir);
717
- const needs = store.dev === here.dev
718
- ? [{ path: root, needed: incoming + kept, free: here.free }]
719
- : [
720
- { path: root, needed: incoming, free: here.free },
721
- { path: versions.dir, needed: kept, free: store.free },
722
- ];
723
- return needs.find((need) => need.needed > 0 && need.free < need.needed + spareFor(need.needed));
724
- };
725
- const ancestors = (path) => {
726
- const found = [];
727
- for (let up = posix.dirname(path); up !== "."; up = posix.dirname(up))
728
- found.unshift(up);
729
- return found;
730
- };
731
- const entrySchema = v.object({
732
- id: v.string(),
733
- size: v.number(),
734
- sha256: v.string(),
735
- md5: v.optional(v.string()),
736
- remoteModified: v.string(),
737
- localMtimeMs: v.number(),
738
- localSize: v.number(),
739
- syncedAt: v.string(),
740
- });
741
- const stateSchema = v.object({
742
- version: v.literal(1),
743
- principal: v.string(),
744
- root: v.string(),
745
- target: v.string(),
746
- rootId: v.optional(v.string()),
747
- localRoot: v.optional(v.object({ dev: v.number(), ino: v.number() })),
748
- entries: v.record(v.string(), entrySchema),
749
- pending: v.record(v.string(), v.object({ op: v.string(), operationId: v.string(), created: v.optional(v.boolean()) })),
750
- });
751
- /** A file mirror's state in `<dir>/<id>.json`, refused rather than reset when invalid. */
752
- export const fileSyncState = (dir, mirror, principal) => jsonState(join(dir, `${mirror.id}.json`), stateSchema, () => ({
753
- version: 1,
754
- principal,
755
- root: mirror.path,
756
- target: mirror.folder,
757
- entries: {},
758
- pending: {},
759
- }));
760
- /** What each mirror's next sync would send from local changes alone; the remote is not asked. */
761
- export const fileMirrorStatus = async (mirrors, stateOf) => {
762
- const items = [];
763
- for (const mirror of mirrors) {
764
- const excluded = excludedBy(mirror.exclude);
765
- const entries = Object.fromEntries(Object.entries(stateOf(mirror).read().entries).filter(([path]) => !excluded(path)));
766
- const { files, links } = await scan(mirror.path, entries, excluded);
767
- const seen = new Set(files.map((file) => file.path));
768
- items.push({
769
- id: mirror.id,
770
- path: mirror.path,
771
- folder: mirror.folder,
772
- upload: files.filter((file) => entries[file.path]?.sha256 !== file.hash).map((file) => file.path),
773
- delete: Object.keys(entries).filter((path) => !seen.has(path) && !links.some((link) => under(path, link))),
774
- unchanged: files.length - files.filter((file) => entries[file.path]?.sha256 !== file.hash).length,
775
- remote_checked: false,
776
- });
777
- }
778
- return items;
779
- };
780
753
  /**
781
754
  * A watch's `remoteChanges` for a file target: every mirror when the remote's revision moved since the last poll (or
782
755
  * at the first poll), none when it did not, and every mirror at each poll when the target has no revision.
@@ -0,0 +1,27 @@
1
+ import type { ConflictPart } from "../../documents/push-model.js";
2
+ /** Above this a text file is merged no more than a binary one: three copies are read whole into memory. */
3
+ export declare const MAX_MERGE_BYTES: number;
4
+ /** Whether a file both sides changed is merged line by line rather than reported as a conflict. */
5
+ export declare const mergeable: (path: string, ...sizes: number[]) => boolean;
6
+ /** One stretch of the merge: unchanged, changed on one side, the same change on both, or two different changes. */
7
+ export interface TextSegment extends ConflictPart {
8
+ kind: "same" | "local" | "remote" | "both" | "conflict";
9
+ /** The stretch's first line in the base, from 1. */
10
+ line: number;
11
+ }
12
+ export type TextMerge = {
13
+ merged: Buffer;
14
+ segments: TextSegment[];
15
+ } | {
16
+ conflicts: TextSegment[];
17
+ segments: TextSegment[];
18
+ };
19
+ /**
20
+ * Merges a text file both sides changed since `base`, the content of the last sync. Lines are compared as bytes
21
+ * (read as latin1, which maps each byte to one character), so any 8-bit encoding, line endings and a byte-order mark
22
+ * pass through unchanged. Markdown that conflicts by lines gets a second try by blocks. `segments` always describe the
23
+ * line merge, so a conflict can be shown.
24
+ */
25
+ export declare const mergeText: (path: string, base: Buffer, local: Buffer, remote: Buffer) => Promise<TextMerge>;
26
+ /** The segments' text as one file, with Git's markers around each conflict; `remote` names the other side. */
27
+ export declare const conflictText: (segments: TextSegment[], remote: string) => string;