@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.
- package/CHANGELOG.md +69 -0
- package/dist/attachments/documents.d.ts +5 -0
- package/dist/attachments/documents.js +2 -2
- 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 +32 -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 +6 -1
- package/dist/office/docx.d.ts +43 -0
- package/dist/office/docx.js +349 -0
- package/dist/office/index.d.ts +2 -0
- package/dist/office/index.js +2 -0
- package/dist/office/package.d.ts +39 -0
- package/dist/office/package.js +98 -0
- package/dist/office/xlsx.d.ts +55 -0
- package/dist/office/xlsx.js +550 -0
- package/dist/office/xml.d.ts +34 -0
- package/dist/office/xml.js +186 -0
- package/dist/office/zip.d.ts +10 -0
- package/dist/office/zip.js +116 -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 +36 -0
- package/dist/services/files/listing.js +47 -0
- 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 +4 -14
- package/dist/services/files/mirror.js +177 -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/store/index.d.ts +2 -0
- package/dist/store/index.js +1 -0
- package/dist/store/people.d.ts +8 -0
- package/dist/store/people.js +2 -0
- package/dist/store/sqlite/account-purge.js +3 -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/person-erase.d.ts +39 -0
- package/dist/store/sqlite/person-erase.js +152 -0
- 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 +6 -2
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import type { FileMirrorStatePort } from "../../documents/file-mirror-model.js";
|
|
2
|
+
import type { Keep } from "../../documents/push-model.js";
|
|
3
|
+
import { type HeldLock, type Mirror } from "../documents/mirrors.js";
|
|
4
|
+
import type { FileMirrorOptions } from "./mirror.js";
|
|
5
|
+
import { type TextSegment } from "./text-merge.js";
|
|
6
|
+
import type { FileVersions } from "./versions.js";
|
|
7
|
+
/** The conflicts each mirror's last sync left, by mirror and path. */
|
|
8
|
+
export declare const listFileConflicts: (mirrors: Mirror[], stateOf: (mirror: Mirror) => FileMirrorStatePort) => {
|
|
9
|
+
id: string;
|
|
10
|
+
path: string;
|
|
11
|
+
reason: string;
|
|
12
|
+
at: string;
|
|
13
|
+
kept: boolean;
|
|
14
|
+
local: string | null;
|
|
15
|
+
remote: string | null;
|
|
16
|
+
}[];
|
|
17
|
+
export interface FileConflictVersion {
|
|
18
|
+
sha256: string | null;
|
|
19
|
+
available: boolean;
|
|
20
|
+
/** The content as text, when the store has it and the file is text a merge reads. */
|
|
21
|
+
text?: string;
|
|
22
|
+
}
|
|
23
|
+
export interface FileConflictView {
|
|
24
|
+
path: string;
|
|
25
|
+
reason: string;
|
|
26
|
+
at: string;
|
|
27
|
+
base: FileConflictVersion;
|
|
28
|
+
local: FileConflictVersion;
|
|
29
|
+
remote: FileConflictVersion;
|
|
30
|
+
/** The local file was changed since the conflict was found: a resolution is refused until a sync sees it. */
|
|
31
|
+
localChanged: boolean;
|
|
32
|
+
/** Each changed stretch of the line merge, conflicts included; empty when the versions are not all kept text. */
|
|
33
|
+
hunks: TextSegment[];
|
|
34
|
+
/** The whole file as the merge would write it, with Git's markers around each conflict: a start for `--file`. */
|
|
35
|
+
merged?: string;
|
|
36
|
+
}
|
|
37
|
+
/** A recorded conflict with its three versions and, for kept text, the line merge that failed. */
|
|
38
|
+
export declare const showFileConflict: (options: {
|
|
39
|
+
root: string;
|
|
40
|
+
path: string;
|
|
41
|
+
state: FileMirrorStatePort;
|
|
42
|
+
versions: FileVersions;
|
|
43
|
+
/** How the app names the remote side in the conflict markers. */
|
|
44
|
+
remote: string;
|
|
45
|
+
}) => Promise<FileConflictView>;
|
|
46
|
+
export interface FileConflictResolveOptions extends Pick<FileMirrorOptions, "target" | "principal" | "guard" | "operationId" | "signal" | "now"> {
|
|
47
|
+
root: string;
|
|
48
|
+
folder: string;
|
|
49
|
+
path: string;
|
|
50
|
+
state: FileMirrorStatePort;
|
|
51
|
+
versions: FileVersions;
|
|
52
|
+
/** How the app names the remote side; it ends a kept copy's name. */
|
|
53
|
+
remote: string;
|
|
54
|
+
/** The mirrors' sync lock, as `acquireLock` returns it. */
|
|
55
|
+
lock(): Promise<HeldLock>;
|
|
56
|
+
/** Keep one side or both whole, or `file`: the absolute path of the final content, written to both sides. */
|
|
57
|
+
choice: {
|
|
58
|
+
keep: Keep;
|
|
59
|
+
} | {
|
|
60
|
+
file: string;
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
export interface FileConflictResolution {
|
|
64
|
+
path: string;
|
|
65
|
+
resolution: "local" | "remote" | "both" | "file";
|
|
66
|
+
/** The content both sides now have; null when the resolution deleted the file. */
|
|
67
|
+
sha256: string | null;
|
|
68
|
+
/** The remote version's copy beside the local file, for `keep: "both"`. */
|
|
69
|
+
copy?: string;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Settles a recorded conflict with the owner's choice, on both sides at once. Both sides are checked against what the
|
|
73
|
+
* conflict recorded: the local file by its hash, the remote by an upload or trash that expects its hash, made before
|
|
74
|
+
* the local file is touched, so a remote changed meanwhile refuses the resolution with nothing written. Every content
|
|
75
|
+
* replaced was kept by the conflict or is kept first, and the resolution is logged with all of them, kept for good.
|
|
76
|
+
* Runs under the mirrors' sync lock.
|
|
77
|
+
*/
|
|
78
|
+
export declare const resolveFileConflict: (options: FileConflictResolveOptions) => Promise<FileConflictResolution>;
|
|
@@ -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
|
+
};
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import * as v from "valibot";
|
|
2
|
+
import type { FileMirrorState, FileTarget, RemoteFile } from "../../documents/file-mirror-model.js";
|
|
3
|
+
/**
|
|
4
|
+
* The remote listing, gone on from where the last run's stopped, and what to save of it when it is incomplete. This
|
|
5
|
+
* run's files win over the saved ones by path and by id, so a file met twice, or moved between runs, is kept once at
|
|
6
|
+
* its latest path.
|
|
7
|
+
*/
|
|
8
|
+
export declare const listRemote: (target: FileTarget, folder: string, signal: AbortSignal | undefined, excluded: (path: string) => boolean, saved: FileMirrorState["listing"], now: number, maxFiles: number) => Promise<{
|
|
9
|
+
listed?: {
|
|
10
|
+
rootId: string;
|
|
11
|
+
files: RemoteFile[];
|
|
12
|
+
complete: boolean;
|
|
13
|
+
};
|
|
14
|
+
progress?: FileMirrorState["listing"];
|
|
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>;
|
|
24
|
+
export declare const listingSchema: v.ObjectSchema<{
|
|
25
|
+
readonly rootId: v.StringSchema<undefined>;
|
|
26
|
+
readonly startedAt: v.StringSchema<undefined>;
|
|
27
|
+
readonly next: v.StringSchema<undefined>;
|
|
28
|
+
readonly files: v.ArraySchema<v.ObjectSchema<{
|
|
29
|
+
readonly path: v.StringSchema<undefined>;
|
|
30
|
+
readonly id: v.StringSchema<undefined>;
|
|
31
|
+
readonly size: v.NumberSchema<undefined>;
|
|
32
|
+
readonly sha256: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
|
|
33
|
+
readonly md5: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
|
|
34
|
+
readonly modifiedAt: v.StringSchema<undefined>;
|
|
35
|
+
}, undefined>, undefined>;
|
|
36
|
+
}, undefined>;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import * as v from "valibot";
|
|
2
|
+
/**
|
|
3
|
+
* A stopped listing older than this starts over. Staleness costs a conflict or a deletion found a run later, never
|
|
4
|
+
* data; the bound is days so that a sync run once a day still finishes a listing that takes several runs.
|
|
5
|
+
*/
|
|
6
|
+
const MAX_LISTING_AGE_MS = 7 * 24 * 3_600_000;
|
|
7
|
+
/**
|
|
8
|
+
* The remote listing, gone on from where the last run's stopped, and what to save of it when it is incomplete. This
|
|
9
|
+
* run's files win over the saved ones by path and by id, so a file met twice, or moved between runs, is kept once at
|
|
10
|
+
* its latest path.
|
|
11
|
+
*/
|
|
12
|
+
export const listRemote = async (target, folder, signal, excluded, saved, now, maxFiles) => {
|
|
13
|
+
const resumed = saved && now - Date.parse(saved.startedAt) <= MAX_LISTING_AGE_MS ? saved : undefined;
|
|
14
|
+
const listed = await target.list(folder, signal, { excluded, ...(resumed ? { from: resumed.next } : {}) });
|
|
15
|
+
if (!listed)
|
|
16
|
+
return {};
|
|
17
|
+
const { rootId, next } = listed;
|
|
18
|
+
// Its pages went on part-way through another folder, so they are not a whole listing of this one.
|
|
19
|
+
if (resumed && rootId !== resumed.rootId)
|
|
20
|
+
return { listed: { rootId, files: listed.files, complete: false } };
|
|
21
|
+
const paths = new Set(listed.files.map((file) => file.path));
|
|
22
|
+
const ids = new Set(listed.files.map((file) => file.id));
|
|
23
|
+
const files = resumed
|
|
24
|
+
? [...resumed.files.filter((file) => !paths.has(file.path) && !ids.has(file.id)), ...listed.files]
|
|
25
|
+
: listed.files;
|
|
26
|
+
if (resumed && files.filter((file) => !excluded(file.path)).length > maxFiles)
|
|
27
|
+
return { listed: { rootId, files, complete: false } };
|
|
28
|
+
const startedAt = resumed?.startedAt ?? new Date(now).toISOString();
|
|
29
|
+
return {
|
|
30
|
+
listed: { rootId, files, complete: listed.complete },
|
|
31
|
+
...(!listed.complete && next !== undefined ? { progress: { rootId, startedAt, next, files } } : {}),
|
|
32
|
+
};
|
|
33
|
+
};
|
|
34
|
+
export const remoteFileSchema = v.object({
|
|
35
|
+
path: v.string(),
|
|
36
|
+
id: v.string(),
|
|
37
|
+
size: v.number(),
|
|
38
|
+
sha256: v.optional(v.string()),
|
|
39
|
+
md5: v.optional(v.string()),
|
|
40
|
+
modifiedAt: v.string(),
|
|
41
|
+
});
|
|
42
|
+
export const listingSchema = v.object({
|
|
43
|
+
rootId: v.string(),
|
|
44
|
+
startedAt: v.string(),
|
|
45
|
+
next: v.string(),
|
|
46
|
+
files: v.array(remoteFileSchema),
|
|
47
|
+
});
|
|
@@ -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
|
+
}[]>;
|