@wirecat/cli-core 0.720.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.
- package/CHANGELOG.md +36 -0
- package/dist/background/daily-archive-timer.d.ts +1 -1
- package/dist/cli/config-command.js +8 -2
- package/dist/cli/config-issues.d.ts +3 -1
- package/dist/cli/config-issues.js +9 -2
- package/dist/cli/documents/file-conflicts.d.ts +25 -0
- package/dist/cli/documents/file-conflicts.js +102 -0
- package/dist/cli/documents/file-edit.d.ts +29 -0
- package/dist/cli/documents/file-edit.js +352 -0
- package/dist/cli/documents/file-update.d.ts +43 -0
- package/dist/cli/documents/file-update.js +95 -0
- package/dist/cli/documents/history.d.ts +34 -0
- package/dist/cli/documents/history.js +89 -0
- package/dist/cli/documents/index.d.ts +9 -2
- package/dist/cli/documents/index.js +9 -2
- package/dist/cli/documents/library.js +10 -0
- package/dist/cli/permission-keys.d.ts +6 -0
- package/dist/cli/permission-keys.js +15 -3
- package/dist/cli/service-api.d.ts +1 -1
- package/dist/cli/service-api.js +16 -34
- package/dist/documents/file-mirror-model.d.ts +18 -1
- package/dist/documents/index.d.ts +7 -4
- package/dist/documents/index.js +4 -1
- package/dist/documents/model.d.ts +16 -1
- package/dist/errors/reasons.js +4 -0
- package/dist/services/documents/block-diff.d.ts +13 -3
- package/dist/services/documents/block-diff.js +13 -7
- package/dist/services/documents/ingestion.d.ts +21 -2
- package/dist/services/documents/ingestion.js +29 -2
- package/dist/services/documents/plan.js +16 -7
- package/dist/services/documents/ports.d.ts +2 -0
- package/dist/services/documents/sync.d.ts +1 -0
- package/dist/services/documents/sync.js +9 -4
- package/dist/services/files/conflicts.d.ts +78 -0
- package/dist/services/files/conflicts.js +183 -0
- package/dist/services/files/guarded-write.d.ts +34 -0
- package/dist/services/files/guarded-write.js +42 -0
- package/dist/services/files/listing.d.ts +8 -0
- package/dist/services/files/listing.js +1 -1
- package/dist/services/files/local-files.d.ts +54 -0
- package/dist/services/files/local-files.js +143 -0
- package/dist/services/files/mirror-state.d.ts +14 -0
- package/dist/services/files/mirror-state.js +65 -0
- package/dist/services/files/mirror.d.ts +3 -13
- package/dist/services/files/mirror.js +163 -204
- package/dist/services/files/text-merge.d.ts +27 -0
- package/dist/services/files/text-merge.js +134 -0
- package/dist/services/files/versions.d.ts +36 -9
- package/dist/services/files/versions.js +40 -12
- package/dist/services/metadata.d.ts +1 -1
- package/dist/store/index.d.ts +1 -0
- package/dist/store/index.js +1 -0
- package/dist/store/sqlite/document-history.d.ts +84 -0
- package/dist/store/sqlite/document-history.js +158 -0
- package/dist/store/sqlite/manifest.js +2 -0
- package/dist/store/sqlite/migrations.generated.js +17 -0
- package/dist/store/sqlite/notes.d.ts +9 -10
- package/dist/store/sqlite/notes.js +33 -21
- package/dist/store/sqlite/schema/document-changes.d.ts +136 -0
- package/dist/store/sqlite/schema/document-changes.js +11 -0
- package/dist/store/sqlite/schema.d.ts +65 -0
- package/dist/store/sqlite/schema.js +5 -0
- package/package.json +2 -2
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { mkdir, stat } from "node:fs/promises";
|
|
3
|
+
import { dirname, join, posix } from "node:path";
|
|
4
|
+
import { CliError } from "@wirecat/cli-base";
|
|
5
|
+
import { heldCheck } from "../documents/mirrors.js";
|
|
6
|
+
import { assertNoLink, hashFile, safePath } from "../documents/push.js";
|
|
7
|
+
import { copyName, trashLocal } from "./local-files.js";
|
|
8
|
+
import { conflictText, mergeable, mergeText } from "./text-merge.js";
|
|
9
|
+
/** The conflicts each mirror's last sync left, by mirror and path. */
|
|
10
|
+
export const listFileConflicts = (mirrors, stateOf) => mirrors.flatMap((mirror) => Object.entries(stateOf(mirror).read().conflicts ?? {}).map(([path, found]) => ({
|
|
11
|
+
id: mirror.id,
|
|
12
|
+
path,
|
|
13
|
+
reason: found.reason,
|
|
14
|
+
at: found.at,
|
|
15
|
+
kept: found.kept === true,
|
|
16
|
+
local: found.local ?? null,
|
|
17
|
+
remote: found.remote ?? null,
|
|
18
|
+
})));
|
|
19
|
+
const recorded = (state, path) => {
|
|
20
|
+
const found = state.read().conflicts?.[path];
|
|
21
|
+
if (!found)
|
|
22
|
+
throw new CliError("not_found", `${path} has no conflict; the last sync settled it or never saw one`, {
|
|
23
|
+
reason: "mirror.no-conflict",
|
|
24
|
+
});
|
|
25
|
+
return found;
|
|
26
|
+
};
|
|
27
|
+
/** A recorded conflict with its three versions and, for kept text, the line merge that failed. */
|
|
28
|
+
export const showFileConflict = async (options) => {
|
|
29
|
+
const { root, path, versions } = options;
|
|
30
|
+
if (!safePath(path))
|
|
31
|
+
throw new CliError("validation_error", `${path} is not a path inside the mirror`);
|
|
32
|
+
const found = recorded(options.state, path);
|
|
33
|
+
const read = async (sha256) => (sha256 ? await versions.read(sha256) : undefined);
|
|
34
|
+
const [base, local, remote] = await Promise.all([read(found.base), read(found.local), read(found.remote)]);
|
|
35
|
+
const text = mergeable(path, ...[base, local, remote].map((bytes) => bytes?.length ?? 0));
|
|
36
|
+
const version = (sha256, bytes) => ({
|
|
37
|
+
sha256: sha256 ?? null,
|
|
38
|
+
available: sha256 === undefined || bytes !== undefined,
|
|
39
|
+
...(text && bytes ? { text: bytes.toString("utf8") } : {}),
|
|
40
|
+
});
|
|
41
|
+
await assertNoLink(root, path);
|
|
42
|
+
const absolute = join(root, path);
|
|
43
|
+
const now = existsSync(absolute) ? (await hashFile(absolute)).sha256 : undefined;
|
|
44
|
+
const view = {
|
|
45
|
+
path,
|
|
46
|
+
reason: found.reason,
|
|
47
|
+
at: found.at,
|
|
48
|
+
base: version(found.base, base),
|
|
49
|
+
local: version(found.local, local),
|
|
50
|
+
remote: version(found.remote, remote),
|
|
51
|
+
localChanged: now !== found.local,
|
|
52
|
+
hunks: [],
|
|
53
|
+
};
|
|
54
|
+
if (!text || !base || !local || !remote)
|
|
55
|
+
return view;
|
|
56
|
+
const merge = await mergeText(path, base, local, remote);
|
|
57
|
+
view.hunks = merge.segments.filter((segment) => segment.kind !== "same");
|
|
58
|
+
view.merged = conflictText(merge.segments, options.remote);
|
|
59
|
+
return view;
|
|
60
|
+
};
|
|
61
|
+
const changed = (what, reason) => new CliError("conflict", `${what} changed since the conflict was found; nothing was written. Sync again to see it`, {
|
|
62
|
+
reason,
|
|
63
|
+
});
|
|
64
|
+
/**
|
|
65
|
+
* Settles a recorded conflict with the owner's choice, on both sides at once. Both sides are checked against what the
|
|
66
|
+
* conflict recorded: the local file by its hash, the remote by an upload or trash that expects its hash, made before
|
|
67
|
+
* the local file is touched, so a remote changed meanwhile refuses the resolution with nothing written. Every content
|
|
68
|
+
* replaced was kept by the conflict or is kept first, and the resolution is logged with all of them, kept for good.
|
|
69
|
+
* Runs under the mirrors' sync lock.
|
|
70
|
+
*/
|
|
71
|
+
export const resolveFileConflict = async (options) => {
|
|
72
|
+
const { root, folder, path, target, versions, choice, signal } = options;
|
|
73
|
+
if (!safePath(path))
|
|
74
|
+
throw new CliError("validation_error", `${path} is not a path inside the mirror`);
|
|
75
|
+
const now = options.now ?? Date.now;
|
|
76
|
+
const held = await options.lock();
|
|
77
|
+
try {
|
|
78
|
+
const assertHeld = heldCheck(held);
|
|
79
|
+
if ((await target.identity()) !== options.principal)
|
|
80
|
+
throw new CliError("authentication_error", "signed-in account does not match this profile", {
|
|
81
|
+
reason: "profile.wrong-account",
|
|
82
|
+
});
|
|
83
|
+
const found = recorded(options.state, path);
|
|
84
|
+
await assertNoLink(root, path);
|
|
85
|
+
const absolute = join(root, path);
|
|
86
|
+
await mkdir(dirname(absolute), { recursive: true });
|
|
87
|
+
const remotePath = (at) => posix.join(folder, at);
|
|
88
|
+
const localNow = existsSync(absolute) ? await versions.keep(absolute) : undefined;
|
|
89
|
+
if (localNow !== found.local)
|
|
90
|
+
throw changed("the local file", "mirror.local-changed");
|
|
91
|
+
if (found.remote && !versions.has(found.remote)) {
|
|
92
|
+
const got = await versions.keep((temp) => target.download(remotePath(path), temp, signal));
|
|
93
|
+
if (got !== found.remote)
|
|
94
|
+
throw changed(`the ${options.remote} file`, "mirror.remote-changed");
|
|
95
|
+
}
|
|
96
|
+
const supplied = "file" in choice ? await versions.keep(choice.file) : undefined;
|
|
97
|
+
const keep = "keep" in choice ? choice.keep : undefined;
|
|
98
|
+
const final = supplied ?? (keep === "remote" ? found.remote : keep === "local" ? found.local : (found.local ?? found.remote));
|
|
99
|
+
const date = new Date(now()).toISOString().slice(0, 10);
|
|
100
|
+
const write = async (action, side, at, act) => {
|
|
101
|
+
await assertHeld();
|
|
102
|
+
return options.guard({ action, side, path: at, operationId: options.operationId() }, act);
|
|
103
|
+
};
|
|
104
|
+
const send = async (at, from, hash, expect) => {
|
|
105
|
+
const parent = posix.dirname(at);
|
|
106
|
+
if (parent !== ".")
|
|
107
|
+
await write("folder", "remote", parent, () => target.ensureFolder(remotePath(parent), signal));
|
|
108
|
+
const sent = await write("absent" in expect ? "create" : "update", "remote", at, () => target.upload(remotePath(at), from, expect, signal));
|
|
109
|
+
if (sent.sha256 !== undefined && sent.sha256 !== hash)
|
|
110
|
+
throw new CliError("conflict", "the file changed during the upload", { reason: "upload.mismatch" });
|
|
111
|
+
return sent;
|
|
112
|
+
};
|
|
113
|
+
const expectRemote = found.remote
|
|
114
|
+
? { sha256: found.remote, ...(found.remoteFile?.md5 ? { md5: found.remoteFile.md5 } : {}) }
|
|
115
|
+
: { absent: true };
|
|
116
|
+
let sent = final === found.remote ? found.remoteFile : undefined;
|
|
117
|
+
if (final !== found.remote) {
|
|
118
|
+
if (final === undefined) {
|
|
119
|
+
await write("delete", "remote", path, () => target.trash(remotePath(path), expectRemote, signal));
|
|
120
|
+
}
|
|
121
|
+
else
|
|
122
|
+
sent = await send(path, "file" in choice ? choice.file : absolute, final, expectRemote);
|
|
123
|
+
}
|
|
124
|
+
if (final !== found.local) {
|
|
125
|
+
const placed = final === undefined
|
|
126
|
+
? await write("delete", "local", path, () => trashLocal(root, path, found.local, date))
|
|
127
|
+
: await write(found.local ? "update" : "create", "local", path, () => versions.write(final, absolute, found.local));
|
|
128
|
+
if (!placed)
|
|
129
|
+
throw changed("the local file", "mirror.local-changed");
|
|
130
|
+
}
|
|
131
|
+
let copy;
|
|
132
|
+
const state = options.state.read();
|
|
133
|
+
const entry = async (at, file, sha256) => {
|
|
134
|
+
const { size, mtimeMs } = await stat(join(root, at));
|
|
135
|
+
state.entries[at] = {
|
|
136
|
+
id: file.id,
|
|
137
|
+
size: file.size,
|
|
138
|
+
sha256,
|
|
139
|
+
...(file.md5 ? { md5: file.md5 } : {}),
|
|
140
|
+
remoteModified: file.modifiedAt,
|
|
141
|
+
localMtimeMs: mtimeMs,
|
|
142
|
+
localSize: size,
|
|
143
|
+
syncedAt: new Date(now()).toISOString(),
|
|
144
|
+
};
|
|
145
|
+
};
|
|
146
|
+
if (final === undefined)
|
|
147
|
+
delete state.entries[path];
|
|
148
|
+
else if (sent)
|
|
149
|
+
await entry(path, sent, final);
|
|
150
|
+
if (keep === "both" && found.local && found.remote) {
|
|
151
|
+
const name = copyName(path, options.remote, date, (at) => existsSync(join(root, at)) || at in state.entries);
|
|
152
|
+
await assertNoLink(root, name);
|
|
153
|
+
if (!(await write("create", "local", name, () => versions.write(found.remote, join(root, name)))))
|
|
154
|
+
throw changed("the local folder", "mirror.local-changed");
|
|
155
|
+
await entry(name, await send(name, join(root, name), found.remote, { absent: true }), found.remote);
|
|
156
|
+
copy = name;
|
|
157
|
+
}
|
|
158
|
+
if (state.conflicts) {
|
|
159
|
+
delete state.conflicts[path];
|
|
160
|
+
if (!Object.keys(state.conflicts).length)
|
|
161
|
+
delete state.conflicts;
|
|
162
|
+
}
|
|
163
|
+
options.state.save(state);
|
|
164
|
+
const parts = {
|
|
165
|
+
...(found.base ? { base: found.base } : {}),
|
|
166
|
+
...(found.local ? { local: found.local } : {}),
|
|
167
|
+
...(found.remote ? { remote: found.remote } : {}),
|
|
168
|
+
};
|
|
169
|
+
const resolution = keep ?? "file";
|
|
170
|
+
versions.log({
|
|
171
|
+
path,
|
|
172
|
+
event: "resolved",
|
|
173
|
+
direction: "both",
|
|
174
|
+
parts,
|
|
175
|
+
...(final ? { new: final } : {}),
|
|
176
|
+
resolution,
|
|
177
|
+
});
|
|
178
|
+
return { path, resolution, sha256: final ?? null, ...(copy ? { copy } : {}) };
|
|
179
|
+
}
|
|
180
|
+
finally {
|
|
181
|
+
await held.release();
|
|
182
|
+
}
|
|
183
|
+
};
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import type { FileTarget, RemoteFile } from "../../documents/file-mirror-model.js";
|
|
3
|
+
import type { FileVersions, VersionDirection } from "./versions.js";
|
|
4
|
+
export interface GuardedFileWrite {
|
|
5
|
+
target: FileTarget;
|
|
6
|
+
/** The profile's own version store, under its state folder; never inside a mirrored folder. */
|
|
7
|
+
versions: FileVersions;
|
|
8
|
+
/** The remote path, as the target takes it. */
|
|
9
|
+
path: string;
|
|
10
|
+
/** A local file with the new content. */
|
|
11
|
+
from: string;
|
|
12
|
+
/** The sha256 the caller read the file at; required when a file is there, refused when none is. */
|
|
13
|
+
expected?: string;
|
|
14
|
+
/** How the caller reads the file and its sha256 again, for the conflict's message. */
|
|
15
|
+
reread: string;
|
|
16
|
+
/** How the replaced content is logged; `restored` when the new content is a kept version. */
|
|
17
|
+
direction?: Extract<VersionDirection, "local-to-remote" | "restored">;
|
|
18
|
+
signal?: AbortSignal;
|
|
19
|
+
}
|
|
20
|
+
export interface GuardedFileWriteResult {
|
|
21
|
+
file: RemoteFile;
|
|
22
|
+
/** The content the write replaced, kept in `versions` before the upload. */
|
|
23
|
+
replaced?: {
|
|
24
|
+
sha256: string;
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
export declare const remoteChanged: (path: string, why: string, reread: string) => CliError;
|
|
28
|
+
/**
|
|
29
|
+
* Writes a file only over the content the caller read. Few providers offer a conditional upload, so the current
|
|
30
|
+
* content is downloaded into the version store and hashed (the proof that it is the one read), and the target checks
|
|
31
|
+
* it again just before the upload. A change landing between that check and the upload is not caught: the replaced
|
|
32
|
+
* content is kept, which is what makes the write safe to undo.
|
|
33
|
+
*/
|
|
34
|
+
export declare const guardedFileWrite: (write: GuardedFileWrite) => Promise<GuardedFileWriteResult>;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { CliError, isCliError } from "@wirecat/cli-base";
|
|
2
|
+
export const remoteChanged = (path, why, reread) => new CliError("conflict", `${path} ${why}; nothing was written. Read it again: ${reread}`, {
|
|
3
|
+
reason: "mirror.remote-changed",
|
|
4
|
+
});
|
|
5
|
+
/**
|
|
6
|
+
* Writes a file only over the content the caller read. Few providers offer a conditional upload, so the current
|
|
7
|
+
* content is downloaded into the version store and hashed (the proof that it is the one read), and the target checks
|
|
8
|
+
* it again just before the upload. A change landing between that check and the upload is not caught: the replaced
|
|
9
|
+
* content is kept, which is what makes the write safe to undo.
|
|
10
|
+
*/
|
|
11
|
+
export const guardedFileWrite = async (write) => {
|
|
12
|
+
const { target, versions, path, from, expected, reread, direction = "local-to-remote", signal } = write;
|
|
13
|
+
const there = await target.exists(path, signal);
|
|
14
|
+
if (there && expected === undefined)
|
|
15
|
+
throw new CliError("validation_error", `${path} exists; read it first (${reread}) and pass its sha256 as --expected-fingerprint`, { param: "--expected-fingerprint" });
|
|
16
|
+
if (!there && expected !== undefined)
|
|
17
|
+
throw remoteChanged(path, "is no longer there", reread);
|
|
18
|
+
const kept = expected === undefined ? undefined : await versions.keep((temp) => target.download(path, temp, signal));
|
|
19
|
+
if (kept !== expected)
|
|
20
|
+
throw remoteChanged(path, "changed since it was read", reread);
|
|
21
|
+
let file;
|
|
22
|
+
try {
|
|
23
|
+
file = await target.upload(path, from, kept === undefined ? { absent: true } : { sha256: kept }, signal);
|
|
24
|
+
}
|
|
25
|
+
catch (error) {
|
|
26
|
+
if (isCliError(error) && error.code === "conflict")
|
|
27
|
+
throw remoteChanged(path, kept === undefined ? "appeared since it was read" : "changed since it was read", reread);
|
|
28
|
+
throw error;
|
|
29
|
+
}
|
|
30
|
+
if (kept === undefined)
|
|
31
|
+
return { file };
|
|
32
|
+
versions.log({
|
|
33
|
+
path,
|
|
34
|
+
event: "changed",
|
|
35
|
+
direction,
|
|
36
|
+
old: kept,
|
|
37
|
+
from: "remote",
|
|
38
|
+
...(file.sha256 ? { new: file.sha256 } : {}),
|
|
39
|
+
size: file.size,
|
|
40
|
+
});
|
|
41
|
+
return { file, replaced: { sha256: kept } };
|
|
42
|
+
};
|
|
@@ -13,6 +13,14 @@ export declare const listRemote: (target: FileTarget, folder: string, signal: Ab
|
|
|
13
13
|
};
|
|
14
14
|
progress?: FileMirrorState["listing"];
|
|
15
15
|
}>;
|
|
16
|
+
export declare const remoteFileSchema: v.ObjectSchema<{
|
|
17
|
+
readonly path: v.StringSchema<undefined>;
|
|
18
|
+
readonly id: v.StringSchema<undefined>;
|
|
19
|
+
readonly size: v.NumberSchema<undefined>;
|
|
20
|
+
readonly sha256: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
|
|
21
|
+
readonly md5: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
|
|
22
|
+
readonly modifiedAt: v.StringSchema<undefined>;
|
|
23
|
+
}, undefined>;
|
|
16
24
|
export declare const listingSchema: v.ObjectSchema<{
|
|
17
25
|
readonly rootId: v.StringSchema<undefined>;
|
|
18
26
|
readonly startedAt: v.StringSchema<undefined>;
|
|
@@ -31,7 +31,7 @@ export const listRemote = async (target, folder, signal, excluded, saved, now, m
|
|
|
31
31
|
...(!listed.complete && next !== undefined ? { progress: { rootId, startedAt, next, files } } : {}),
|
|
32
32
|
};
|
|
33
33
|
};
|
|
34
|
-
const remoteFileSchema = v.object({
|
|
34
|
+
export const remoteFileSchema = v.object({
|
|
35
35
|
path: v.string(),
|
|
36
36
|
id: v.string(),
|
|
37
37
|
size: v.number(),
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { FileEntry, FileStepKind, RemoteFile } from "../../documents/file-mirror-model.js";
|
|
2
|
+
import type { LocalDocument } from "../../documents/push-model.js";
|
|
3
|
+
import type { FileVersions } from "./versions.js";
|
|
4
|
+
/** A local file as a mirror's scan finds it. */
|
|
5
|
+
export type Local = LocalDocument & {
|
|
6
|
+
size: number;
|
|
7
|
+
mtimeMs: number;
|
|
8
|
+
};
|
|
9
|
+
export declare const MAX_FILES = 100000;
|
|
10
|
+
export declare const TRASH = ".wirecat-trash";
|
|
11
|
+
/** What a run leaves free on a drive it writes to: a tenth of what it writes, from 100 MB up to 1 GB. */
|
|
12
|
+
export declare const spareFor: (needed: number) => number;
|
|
13
|
+
/** `name (conflict 2026-11-18 disk).ext`, numbered when that name is taken. */
|
|
14
|
+
export declare const copyName: (path: string, remote: string, date: string, taken: (path: string) => boolean) => string;
|
|
15
|
+
/** Moves a file into `<root>/.wirecat-trash/<date>/` while it still has `hash`; false when it changed. */
|
|
16
|
+
export declare const trashLocal: (root: string, path: string, hash: string, date: string) => Promise<boolean>;
|
|
17
|
+
/** Renames a local file while it still has `hash` and nothing holds the new name; false otherwise. */
|
|
18
|
+
export declare const renameLocal: (root: string, from: string, to: string, hash: string) => Promise<boolean>;
|
|
19
|
+
/** False when `path` or a folder on the way to it is a symbolic link, so nothing under it is touched. */
|
|
20
|
+
export declare const linkFree: (root: string, path: string) => Promise<boolean>;
|
|
21
|
+
/** True when the file at `absolute` is missing or has one of `hashes`: no partial copy is left there. */
|
|
22
|
+
export declare const whole: (absolute: string, hashes: (string | undefined)[]) => Promise<boolean>;
|
|
23
|
+
/** True when `path` is `link` or lies under it. */
|
|
24
|
+
export declare const under: (path: string, link: string) => boolean;
|
|
25
|
+
/** Free bytes and the device of the file system holding `path`, or of its nearest folder that exists. */
|
|
26
|
+
export declare const freeSpace: (path: string) => Promise<{
|
|
27
|
+
free: number;
|
|
28
|
+
dev: number;
|
|
29
|
+
}>;
|
|
30
|
+
export declare const gigabytes: (bytes: number) => string;
|
|
31
|
+
/**
|
|
32
|
+
* The free space a run needs that a file system lacks: downloads land under `root`, and the store keeps every
|
|
33
|
+
* content they replace or a deletion removes, plus each remote content an upload replaces that it lacks.
|
|
34
|
+
*/
|
|
35
|
+
export declare const shortOfSpace: (steps: {
|
|
36
|
+
kind: FileStepKind;
|
|
37
|
+
local?: {
|
|
38
|
+
size: number;
|
|
39
|
+
};
|
|
40
|
+
remote?: RemoteFile;
|
|
41
|
+
}[], root: string, versions: FileVersions, space: (path: string) => Promise<{
|
|
42
|
+
free: number;
|
|
43
|
+
dev: number;
|
|
44
|
+
}>) => Promise<{
|
|
45
|
+
path: string;
|
|
46
|
+
needed: number;
|
|
47
|
+
free: number;
|
|
48
|
+
} | undefined>;
|
|
49
|
+
export declare const ancestors: (path: string) => string[];
|
|
50
|
+
/** Every local file but excluded ones, hashed only when its size or mtime moved since the last sync. */
|
|
51
|
+
export declare const scan: (root: string, entries: Record<string, FileEntry>, excluded: (path: string) => boolean, maxFiles?: number) => Promise<{
|
|
52
|
+
files: Local[];
|
|
53
|
+
links: string[];
|
|
54
|
+
}>;
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { mkdir, stat, statfs, unlink } from "node:fs/promises";
|
|
2
|
+
import { dirname, join, posix } from "node:path";
|
|
3
|
+
import { isCliError } from "@wirecat/cli-base";
|
|
4
|
+
import { assertNoLink, hashFile, placeNew, scanLocal } from "../documents/push.js";
|
|
5
|
+
export const MAX_FILES = 100_000;
|
|
6
|
+
export const TRASH = ".wirecat-trash";
|
|
7
|
+
/** What a run leaves free on a drive it writes to: a tenth of what it writes, from 100 MB up to 1 GB. */
|
|
8
|
+
export const spareFor = (needed) => Math.min(1024 ** 3, Math.max(100 * 1024 ** 2, needed / 10));
|
|
9
|
+
/** `name (conflict 2026-11-18 disk).ext`, numbered when that name is taken. */
|
|
10
|
+
export const copyName = (path, remote, date, taken) => {
|
|
11
|
+
const extension = posix.extname(path);
|
|
12
|
+
const stem = path.slice(0, path.length - extension.length);
|
|
13
|
+
for (let n = 1;; n++) {
|
|
14
|
+
const candidate = `${stem} (conflict ${date} ${remote}${n > 1 ? ` ${n}` : ""})${extension}`;
|
|
15
|
+
if (!taken(candidate))
|
|
16
|
+
return candidate;
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
/** Moves a file into `<root>/.wirecat-trash/<date>/` while it still has `hash`; false when it changed. */
|
|
20
|
+
export const trashLocal = async (root, path, hash, date) => {
|
|
21
|
+
await assertNoLink(root, path);
|
|
22
|
+
await assertNoLink(root, posix.join(TRASH, date, path));
|
|
23
|
+
const from = join(root, path);
|
|
24
|
+
if ((await hashFile(from)).sha256 !== hash)
|
|
25
|
+
return false;
|
|
26
|
+
const into = join(root, TRASH, date, path);
|
|
27
|
+
await mkdir(dirname(into), { recursive: true });
|
|
28
|
+
for (let n = 1;; n++) {
|
|
29
|
+
try {
|
|
30
|
+
await placeNew(from, n > 1 ? `${into}.${n}` : into);
|
|
31
|
+
break;
|
|
32
|
+
}
|
|
33
|
+
catch (error) {
|
|
34
|
+
if (error.code !== "EEXIST")
|
|
35
|
+
throw error;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
await unlink(from);
|
|
39
|
+
return true;
|
|
40
|
+
};
|
|
41
|
+
/** Renames a local file while it still has `hash` and nothing holds the new name; false otherwise. */
|
|
42
|
+
export const renameLocal = async (root, from, to, hash) => {
|
|
43
|
+
await assertNoLink(root, from);
|
|
44
|
+
await assertNoLink(root, to);
|
|
45
|
+
const source = join(root, from);
|
|
46
|
+
if ((await hashFile(source)).sha256 !== hash)
|
|
47
|
+
return false;
|
|
48
|
+
await mkdir(dirname(join(root, to)), { recursive: true });
|
|
49
|
+
try {
|
|
50
|
+
await placeNew(source, join(root, to));
|
|
51
|
+
}
|
|
52
|
+
catch (error) {
|
|
53
|
+
if (error.code === "EEXIST")
|
|
54
|
+
return false;
|
|
55
|
+
throw error;
|
|
56
|
+
}
|
|
57
|
+
await unlink(source);
|
|
58
|
+
return true;
|
|
59
|
+
};
|
|
60
|
+
/** False when `path` or a folder on the way to it is a symbolic link, so nothing under it is touched. */
|
|
61
|
+
export const linkFree = (root, path) => assertNoLink(root, path).then(() => true, (error) => {
|
|
62
|
+
if (isCliError(error) && error.details?.reason === "mirror.symlink")
|
|
63
|
+
return false;
|
|
64
|
+
throw error;
|
|
65
|
+
});
|
|
66
|
+
/** True when the file at `absolute` is missing or has one of `hashes`: no partial copy is left there. */
|
|
67
|
+
export const whole = async (absolute, hashes) => {
|
|
68
|
+
try {
|
|
69
|
+
return hashes.includes((await hashFile(absolute)).sha256);
|
|
70
|
+
}
|
|
71
|
+
catch (error) {
|
|
72
|
+
return error.code === "ENOENT";
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
/** True when `path` is `link` or lies under it. */
|
|
76
|
+
export const under = (path, link) => path === link || path.startsWith(`${link}/`);
|
|
77
|
+
/** Free bytes and the device of the file system holding `path`, or of its nearest folder that exists. */
|
|
78
|
+
export const freeSpace = async (path) => {
|
|
79
|
+
for (let at = path;; at = dirname(at)) {
|
|
80
|
+
try {
|
|
81
|
+
const [{ bavail, bsize }, { dev }] = await Promise.all([statfs(at), stat(at)]);
|
|
82
|
+
return { free: bavail * bsize, dev };
|
|
83
|
+
}
|
|
84
|
+
catch (error) {
|
|
85
|
+
if (error.code !== "ENOENT" || dirname(at) === at)
|
|
86
|
+
throw error;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
export const gigabytes = (bytes) => `${(bytes / 1024 ** 3).toFixed(1)} GB`;
|
|
91
|
+
/**
|
|
92
|
+
* The free space a run needs that a file system lacks: downloads land under `root`, and the store keeps every
|
|
93
|
+
* content they replace or a deletion removes, plus each remote content an upload replaces that it lacks.
|
|
94
|
+
*/
|
|
95
|
+
export const shortOfSpace = async (steps, root, versions, space) => {
|
|
96
|
+
let incoming = 0;
|
|
97
|
+
let kept = 0;
|
|
98
|
+
for (const step of steps) {
|
|
99
|
+
const local = step.local?.size ?? 0;
|
|
100
|
+
const remote = step.remote?.size ?? 0;
|
|
101
|
+
if (step.kind === "download") {
|
|
102
|
+
incoming += remote;
|
|
103
|
+
kept += local;
|
|
104
|
+
}
|
|
105
|
+
if (step.kind === "keep-both") {
|
|
106
|
+
incoming += remote;
|
|
107
|
+
kept += remote;
|
|
108
|
+
}
|
|
109
|
+
if (step.kind === "merge") {
|
|
110
|
+
incoming += local + remote;
|
|
111
|
+
kept += 2 * (local + remote);
|
|
112
|
+
}
|
|
113
|
+
if (step.kind === "trash-local")
|
|
114
|
+
kept += local;
|
|
115
|
+
if (step.kind === "upload" && step.remote && !versions.has(step.remote.sha256))
|
|
116
|
+
kept += remote;
|
|
117
|
+
}
|
|
118
|
+
if (!incoming && !kept)
|
|
119
|
+
return undefined;
|
|
120
|
+
const here = await space(root);
|
|
121
|
+
const store = versions.dir === undefined ? here : await space(versions.dir);
|
|
122
|
+
const needs = store.dev === here.dev
|
|
123
|
+
? [{ path: root, needed: incoming + kept, free: here.free }]
|
|
124
|
+
: [
|
|
125
|
+
{ path: root, needed: incoming, free: here.free },
|
|
126
|
+
{ path: versions.dir, needed: kept, free: store.free },
|
|
127
|
+
];
|
|
128
|
+
return needs.find((need) => need.needed > 0 && need.free < need.needed + spareFor(need.needed));
|
|
129
|
+
};
|
|
130
|
+
export const ancestors = (path) => {
|
|
131
|
+
const found = [];
|
|
132
|
+
for (let up = posix.dirname(path); up !== "."; up = posix.dirname(up))
|
|
133
|
+
found.unshift(up);
|
|
134
|
+
return found;
|
|
135
|
+
};
|
|
136
|
+
/** Every local file but excluded ones, hashed only when its size or mtime moved since the last sync. */
|
|
137
|
+
export const scan = async (root, entries, excluded, maxFiles = MAX_FILES) => {
|
|
138
|
+
const { files, links } = await scanLocal(root, () => "file", maxFiles, (path) => {
|
|
139
|
+
const entry = entries[path];
|
|
140
|
+
return entry && { size: entry.localSize, mtimeMs: entry.localMtimeMs, hash: entry.sha256 };
|
|
141
|
+
}, excluded);
|
|
142
|
+
return { files: files, links };
|
|
143
|
+
};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { FileMirrorStatePort } from "../../documents/file-mirror-model.js";
|
|
2
|
+
import { type Mirror } from "../documents/mirrors.js";
|
|
3
|
+
/** A file mirror's state in `<dir>/<id>.json`, refused rather than reset when invalid. */
|
|
4
|
+
export declare const fileSyncState: (dir: string, mirror: Mirror, principal: string) => FileMirrorStatePort;
|
|
5
|
+
/** What each mirror's next sync would send from local changes alone; the remote is not asked. */
|
|
6
|
+
export declare const fileMirrorStatus: (mirrors: Mirror[], stateOf: (mirror: Mirror) => FileMirrorStatePort) => Promise<{
|
|
7
|
+
id: string;
|
|
8
|
+
path: string;
|
|
9
|
+
folder: string;
|
|
10
|
+
upload: string[];
|
|
11
|
+
delete: string[];
|
|
12
|
+
unchanged: number;
|
|
13
|
+
remote_checked: boolean;
|
|
14
|
+
}[]>;
|
|
@@ -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. */
|
|
@@ -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 {};
|