@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,352 @@
1
+ import { createHash } from "node:crypto";
2
+ import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { CliError, isCliError } from "@wirecat/cli-base";
6
+ import { annotate, sharedCommand } from "@wirecat/cli-base/commands";
7
+ import * as v from "valibot";
8
+ import { editDocxParagraphs, editXlsxCells, readDocxParagraphs, readXlsxCells, } from "../../office/index.js";
9
+ import { guardedFileWrite, remoteChanged } from "../../services/files/guarded-write.js";
10
+ import { honoursDryRun } from "../dry-run-guard.js";
11
+ import { REMOTE_READ, REMOTE_WRITE } from "../effects.js";
12
+ import { itemOf } from "../envelope.js";
13
+ import { addFileUpdateCommand, replacedOf, sha256Of, } from "./file-update.js";
14
+ import { examples, wordsOf } from "./words.js";
15
+ /** The whole file is held in memory to edit it. */
16
+ const MAX_OFFICE_BYTES = 64 * 1024 * 1024;
17
+ const sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex");
18
+ const inTemp = async (act) => {
19
+ const folder = await mkdtemp(join(tmpdir(), "wirecat-office-"));
20
+ try {
21
+ return await act(folder);
22
+ }
23
+ finally {
24
+ await rm(folder, { recursive: true, force: true });
25
+ }
26
+ };
27
+ const downloaded = ({ target, signal }, path) => inTemp(async (folder) => {
28
+ const into = join(folder, "file");
29
+ await target.download(path, into, signal);
30
+ const { size } = await stat(into);
31
+ if (size > MAX_OFFICE_BYTES)
32
+ throw new CliError("validation_error", `${path} is ${size} bytes; an Office file is read up to 64 MiB`, {
33
+ reason: "file.too-large",
34
+ });
35
+ const bytes = new Uint8Array(await readFile(into));
36
+ return { bytes, sha256: sha256(bytes) };
37
+ });
38
+ const jsonOf = (input, flag, schema, shape) => {
39
+ let parsed;
40
+ try {
41
+ parsed = JSON.parse(input);
42
+ }
43
+ catch {
44
+ throw new CliError("validation_error", `${flag} is not JSON; give ${shape}`, { param: flag });
45
+ }
46
+ const checked = v.safeParse(schema, parsed);
47
+ if (!checked.success)
48
+ throw new CliError("validation_error", `${flag} takes ${shape}`, { param: flag });
49
+ return checked.output;
50
+ };
51
+ const ADDRESS = /^([A-Z]{1,3})([1-9]\d{0,6})$/u;
52
+ const CELLS = /^[A-Z]{1,3}[1-9]\d*(:[A-Z]{1,3}[1-9]\d*)?$/iu;
53
+ const columnName = (column) => {
54
+ let name = "";
55
+ for (let left = column; left > 0; left = Math.floor((left - 1) / 26))
56
+ name = String.fromCharCode(65 + ((left - 1) % 26)) + name;
57
+ return name;
58
+ };
59
+ const cornerOf = (address) => {
60
+ const match = ADDRESS.exec(address.toUpperCase());
61
+ if (!match)
62
+ throw new CliError("validation_error", `${address} is not a cell like B7`, { reason: "office.invalid_cell" });
63
+ const letters = match[1];
64
+ return {
65
+ column: [...letters].reduce((sum, letter) => sum * 26 + letter.charCodeAt(0) - 64, 0),
66
+ row: Number(match[2]),
67
+ };
68
+ };
69
+ /** `Sheet1!A1:C10`, `'My sheet'!B2`, `Sheet1` or `A1:C10`, as the sheet and the cells. */
70
+ export const sheetRangeOf = (input) => {
71
+ if (!input)
72
+ return {};
73
+ const bang = input.lastIndexOf("!");
74
+ const quoted = (name) => (/^'.*'$/u.test(name) ? name.slice(1, -1).replaceAll("''", "'") : name);
75
+ if (bang >= 0) {
76
+ const range = input.slice(bang + 1);
77
+ return { sheet: quoted(input.slice(0, bang)), ...(range ? { range } : {}) };
78
+ }
79
+ return CELLS.test(input) ? { range: input } : { sheet: quoted(input) };
80
+ };
81
+ const VALUES = v.pipe(v.array(v.pipe(v.array(v.union([v.string(), v.number(), v.boolean(), v.null()])), v.minLength(1))), v.minLength(1));
82
+ const VALUES_SHAPE = 'rows of cell values as JSON, such as [["Total", 42], [null, true]]';
83
+ /** The cells `values` fills from the range's top-left cell; a range of more than one cell must have their shape. */
84
+ export const cellEditsOf = (sheet, range, values) => {
85
+ const [from, to] = range.split(":");
86
+ const start = cornerOf(from);
87
+ if (to !== undefined) {
88
+ const end = cornerOf(to);
89
+ const rows = end.row - start.row + 1;
90
+ const columns = end.column - start.column + 1;
91
+ if (rows < 1 || columns < 1 || values.length !== rows || values.some((row) => row.length !== columns))
92
+ throw new CliError("validation_error", `${range} is ${rows} rows by ${columns} columns; --values must have that shape, or name only its first cell`, { param: "--values" });
93
+ }
94
+ return values.flatMap((row, down) => row.map((value, across) => ({ sheet, cell: `${columnName(start.column + across)}${start.row + down}`, value })));
95
+ };
96
+ const PAYLOAD = v.pipe(v.array(v.union([
97
+ v.strictObject({ index: v.pipe(v.number(), v.integer()), text: v.string() }),
98
+ v.strictObject({
99
+ insert_after: v.pipe(v.number(), v.integer()),
100
+ text: v.string(),
101
+ style_from: v.optional(v.pipe(v.number(), v.integer())),
102
+ }),
103
+ v.strictObject({ delete: v.pipe(v.number(), v.integer()) }),
104
+ ])), v.minLength(1));
105
+ const PAYLOAD_SHAPE = 'paragraph edits as JSON: [{"index": 3, "text": "…"}, {"insert_after": 5, "text": "…"}, {"delete": 7}]';
106
+ const docxEditsOf = (payload) => payload.map((edit) => {
107
+ if ("insert_after" in edit)
108
+ return {
109
+ insertAfter: edit.insert_after,
110
+ text: edit.text,
111
+ ...(edit.style_from === undefined ? {} : { styleFrom: edit.style_from }),
112
+ };
113
+ return edit;
114
+ });
115
+ const addFileEditCommandsDefinition = (files, helpers) => {
116
+ const { prefix, place } = wordsOf(helpers.words);
117
+ const group = files.name();
118
+ const deleteKey = helpers.deleteKey ?? "files.delete";
119
+ const show = (kind, input) => `${prefix} ${group} ${kind} show ${input}`;
120
+ /** Downloads the file, edits it only at the sha256 it was read at, and writes it back as `files update` does. */
121
+ const editInPlace = async (command, kind, input, fingerprint, edit) => {
122
+ const reread = show(kind, input);
123
+ const expected = sha256Of(fingerprint);
124
+ if (expected === undefined)
125
+ throw new CliError("validation_error", `read the file first (${reread}) and pass its sha256 as --expected-fingerprint`, {
126
+ param: "--expected-fingerprint",
127
+ });
128
+ const path = helpers.path(input);
129
+ const answer = await helpers.write([deleteKey], async (port) => {
130
+ const read = await downloaded(port, path);
131
+ if (read.sha256 !== expected)
132
+ throw remoteChanged(path, "changed since it was read", reread);
133
+ const edited = await edit(read.bytes);
134
+ return inTemp(async (folder) => {
135
+ const from = join(folder, "edited");
136
+ await writeFile(from, edited.bytes, { mode: 0o600 });
137
+ const { target, versions, signal } = port;
138
+ const done = await guardedFileWrite({
139
+ target,
140
+ versions,
141
+ path,
142
+ from,
143
+ expected,
144
+ reread,
145
+ ...(signal ? { signal } : {}),
146
+ });
147
+ return { path, sha256: done.file.sha256 ?? null, replaced: replacedOf(done, versions), ...edited.answer };
148
+ });
149
+ }, command);
150
+ helpers.output(itemOf(answer), command);
151
+ };
152
+ const readOffice = async (command, input, answer) => {
153
+ const path = helpers.path(input);
154
+ const item = await helpers.read(async (port) => {
155
+ const read = await downloaded(port, path);
156
+ return { path, sha256: read.sha256, ...(await answer(read.bytes)) };
157
+ }, command);
158
+ helpers.output(itemOf(item), command);
159
+ };
160
+ const sheets = annotate(files.command("sheets"), { effects: REMOTE_READ }).description(`the cells of an Excel workbook (.xlsx) on ${place}, read and changed in place`);
161
+ examples(annotate(sheets.command("show"), { effects: REMOTE_READ, offline: false })
162
+ .summary("show a workbook's cells and the sha256 to edit them at")
163
+ .description("show a workbook's stored cells, each with its value, type, formula and format, and the file's sha256 to pass " +
164
+ "as --expected-fingerprint to sheets update. Formulas show the value Excel saved last")
165
+ .argument("<path>", `the .xlsx file on ${place}`)
166
+ .argument("[range]", "the cells to show: Sheet1!A1:C10, a sheet's name, or A1:C10 on every sheet; all without it"), [`${prefix} ${group} sheets show /budget.xlsx "Sheet1!A1:C10"`, `${prefix} ${group} sheets show /budget.xlsx`]).action(async function (input, range) {
167
+ const wanted = sheetRangeOf(range);
168
+ await readOffice(this, input, async (bytes) => ({
169
+ sheets: (await readXlsxCells(bytes, wanted)).map((sheet) => ({
170
+ name: sheet.name,
171
+ cells: sheet.cells.map((cell) => ({
172
+ address: cell.address,
173
+ row: cell.row,
174
+ column: cell.column,
175
+ value: cell.value,
176
+ type: cell.type,
177
+ ...(cell.formula === undefined ? {} : { formula: cell.formula }),
178
+ style: cell.style,
179
+ })),
180
+ })),
181
+ }));
182
+ });
183
+ examples(annotate(sheets.command("update"), { effects: REMOTE_WRITE, offline: false })
184
+ .summary("write values into a workbook's cells, at the sha256 it was read at")
185
+ .description("write values into a workbook's cells in place: the rest of the file, its formatting and its other sheets " +
186
+ `stay as they are. It needs --expected-fingerprint from sheets show and asks as ${deleteKey} does; what it ` +
187
+ "replaced is kept on this computer (see history). A text is written as text, even one that starts with =. " +
188
+ "A formula cell is refused unless --replace")
189
+ .argument("<path>", `the .xlsx file on ${place}`)
190
+ .argument("<range>", "where the values go: Sheet1!B2:C3, or its first cell Sheet1!B2; the sheet may be left out when there is one")
191
+ .option("--values <json>", "the cell values as JSON rows; null empties a cell")
192
+ .option("--expected-fingerprint <hash>", "the sha256 sheets show gave for the file")
193
+ .option("--replace", "replace a formula with the value instead of refusing it"), [
194
+ `${prefix} ${group} sheets update /budget.xlsx "Sheet1!B2:C2" --values '[[120, "paid"]]' --expected-fingerprint 9f86d081…`,
195
+ ]).action(async function (input, range, args) {
196
+ if (args.values === undefined)
197
+ throw new CliError("validation_error", `give the cells' values with --values: ${VALUES_SHAPE}`, {
198
+ param: "--values",
199
+ });
200
+ const values = jsonOf(args.values, "--values", VALUES, VALUES_SHAPE);
201
+ const wanted = sheetRangeOf(range);
202
+ if (wanted.range === undefined)
203
+ throw new CliError("validation_error", `${range} names no cell; give one like Sheet1!B2`, {
204
+ reason: "office.invalid_cell",
205
+ });
206
+ cellEditsOf("", wanted.range, values);
207
+ await editInPlace(this, "sheets", input, args.expectedFingerprint, async (bytes) => {
208
+ let sheet = wanted.sheet;
209
+ if (sheet === undefined) {
210
+ const names = (await readXlsxCells(bytes, { range: "A1" })).map((one) => one.name);
211
+ if (names.length !== 1)
212
+ throw new CliError("validation_error", `the workbook has ${names.length} sheets (${names.map((name) => `"${name}"`).join(", ")}); name one, like ${names[0] ?? "Sheet1"}!${wanted.range}`, { reason: "office.no_sheet" });
213
+ sheet = names[0];
214
+ }
215
+ try {
216
+ const done = await editXlsxCells(bytes, cellEditsOf(sheet, wanted.range, values), {
217
+ overwriteFormulas: args.replace === true,
218
+ });
219
+ return {
220
+ bytes: done.bytes,
221
+ answer: {
222
+ changed: done.changed,
223
+ calc_chain_dropped: done.calcChainDropped,
224
+ warnings: done.calcChainDropped
225
+ ? ["a formula was replaced, so Excel rebuilds the workbook's calculation order when it opens it"]
226
+ : [],
227
+ },
228
+ };
229
+ }
230
+ catch (error) {
231
+ if (isCliError(error) && error.details?.reason === "office.formula_cell")
232
+ throw new CliError("validation_error", error.message.replace("pass overwriteFormulas", "pass --replace"), error.details);
233
+ throw error;
234
+ }
235
+ });
236
+ });
237
+ const documents = annotate(files.command("documents"), { effects: REMOTE_READ }).description(`the paragraphs of a Word document (.docx) on ${place}, read and changed in place`);
238
+ examples(annotate(documents.command("show"), { effects: REMOTE_READ, offline: false })
239
+ .summary("show a document's paragraphs and the sha256 to edit them at")
240
+ .description("show a Word document's paragraphs by index, with their style, whether each can be edited and why not, and " +
241
+ "the file's sha256 to pass as --expected-fingerprint to documents update")
242
+ .argument("<path>", `the .docx file on ${place}`), [`${prefix} ${group} documents show /report.docx`]).action(async function (input) {
243
+ await readOffice(this, input, async (bytes) => ({
244
+ paragraphs: (await readDocxParagraphs(bytes)).map((paragraph) => ({
245
+ index: paragraph.index,
246
+ text: paragraph.text,
247
+ ...(paragraph.styleId === undefined ? {} : { style_id: paragraph.styleId }),
248
+ ...(paragraph.style === undefined ? {} : { style: paragraph.style }),
249
+ location: paragraph.location,
250
+ editable: paragraph.editable,
251
+ ...(paragraph.reason === undefined ? {} : { reason: paragraph.reason }),
252
+ mixed_formatting: paragraph.mixedFormatting,
253
+ })),
254
+ }));
255
+ });
256
+ examples(annotate(documents.command("update"), { effects: REMOTE_WRITE, offline: false })
257
+ .summary("replace, insert or delete paragraphs, at the sha256 it was read at")
258
+ .description("replace, insert or delete a Word document's paragraphs in place; the rest of the file stays as it is. " +
259
+ "Indexes are the ones documents show gave. It needs --expected-fingerprint from documents show and asks as " +
260
+ `${deleteKey} does; what it replaced is kept on this computer (see history). A paragraph that is not ` +
261
+ "editable is refused with its reason, and a replaced one with mixed formatting takes its first run's")
262
+ .argument("<path>", `the .docx file on ${place}`)
263
+ .option("--payload <json>", "the edits as JSON: {index, text}, {insert_after, text, style_from?} or {delete}")
264
+ .option("--expected-fingerprint <hash>", "the sha256 documents show gave for the file"), [
265
+ `${prefix} ${group} documents update /report.docx --payload '[{"index": 2, "text": "Revenue grew 12%."}]' --expected-fingerprint 9f86d081…`,
266
+ ]).action(async function (input, args) {
267
+ if (args.payload === undefined)
268
+ throw new CliError("validation_error", `give the edits with --payload: ${PAYLOAD_SHAPE}`, { param: "--payload" });
269
+ const edits = docxEditsOf(jsonOf(args.payload, "--payload", PAYLOAD, PAYLOAD_SHAPE));
270
+ await editInPlace(this, "documents", input, args.expectedFingerprint, async (bytes) => {
271
+ const done = await editDocxParagraphs(bytes, edits);
272
+ return {
273
+ bytes: done.bytes,
274
+ answer: {
275
+ paragraphs: { replaced: done.replaced, inserted: done.inserted, deleted: done.deleted },
276
+ warnings: done.collapsed.map((index) => `paragraph ${index} had mixed formatting; its new text has its first run's formatting`),
277
+ },
278
+ };
279
+ });
280
+ });
281
+ examples(annotate(files.command("history"), { effects: REMOTE_READ, offline: false })
282
+ .summary("list the earlier versions of a file kept on this computer")
283
+ .description("list what the writes and syncs of this profile replaced in a file, newest last. Each entry's version is the " +
284
+ `sha256 of the content it replaced, kept on this computer while available is true; ${group} restore puts it back`)
285
+ .argument("<path>", `the file on ${place}`), [`${prefix} ${group} history /budget.xlsx`]).action(async function (input) {
286
+ const path = helpers.path(input);
287
+ const item = await helpers.read(async ({ versions }) => ({
288
+ path,
289
+ versions: versions.list(path).map((event) => ({
290
+ at: event.at,
291
+ event: event.event,
292
+ direction: event.direction,
293
+ version: event.old ?? null,
294
+ available: event.available,
295
+ ...(event.new === undefined ? {} : { new: event.new }),
296
+ ...(event.size === undefined ? {} : { size: event.size }),
297
+ ...(event.to === undefined ? {} : { to: event.to }),
298
+ ...(event.oldIn === undefined ? {} : { old_in: event.oldIn }),
299
+ })),
300
+ }), this);
301
+ helpers.output(itemOf(item), this);
302
+ });
303
+ const trash = helpers.restoreFromTrash;
304
+ examples(annotate(files.command("restore"), { effects: REMOTE_WRITE, offline: false })
305
+ .summary(trash
306
+ ? "bring a file back from the trash, or put back a version kept here"
307
+ : "put back a version of a file kept here")
308
+ .description(`${trash ? `with no version, bring a file or folder back from ${place}'s trash. With one, put` : "put"} back ` +
309
+ `a version history lists: it is written as ${group} update writes, so a file there needs ` +
310
+ `--expected-fingerprint, asks as ${deleteKey} does, and is kept first`)
311
+ .argument("<path>", trash ? `the file on ${place}, or its path in the trash` : `the file on ${place}`)
312
+ .argument(trash ? "[version]" : "<version>", "the version's sha256, from history")
313
+ .option("--expected-fingerprint <hash>", "the sha256 the file has now; required when it exists"), [`${prefix} ${group} restore /budget.xlsx 2c26b46b… --expected-fingerprint 9f86d081…`]).action(async function (input, versionInput, args) {
314
+ if (versionInput === undefined) {
315
+ if (!trash)
316
+ throw new CliError("validation_error", `give the version from ${group} history`, { param: "version" });
317
+ helpers.output(itemOf(await trash(input, this)), this);
318
+ return;
319
+ }
320
+ const version = sha256Of(versionInput, "the version");
321
+ const expected = sha256Of(args.expectedFingerprint);
322
+ const path = helpers.path(input);
323
+ const reread = helpers.reread(input);
324
+ const answer = await helpers.write(expected ? [deleteKey] : [], async ({ target, versions, signal }) => inTemp(async (folder) => {
325
+ const from = join(folder, "version");
326
+ if (!(await versions.write(version, from)))
327
+ throw new CliError("not_found", `version ${version} of ${path} is no longer kept here; see ${group} history`, {
328
+ reason: "item.not-found",
329
+ });
330
+ const done = await guardedFileWrite({
331
+ target,
332
+ versions,
333
+ path,
334
+ from,
335
+ reread,
336
+ direction: "restored",
337
+ ...(expected ? { expected } : {}),
338
+ ...(signal ? { signal } : {}),
339
+ });
340
+ return { path, sha256: done.file.sha256 ?? null, restored: version, replaced: replacedOf(done, versions) };
341
+ }), this);
342
+ helpers.output(itemOf(answer), this);
343
+ });
344
+ addFileUpdateCommand(files, helpers);
345
+ };
346
+ /**
347
+ * Mounts `<files> update`, `sheets show|update`, `documents show|update`, `history` and `restore` under the CLI's own
348
+ * files group: Office files edited in place and earlier versions put back, every write at the sha256 it was read at
349
+ * and with the replaced content kept (`guardedFileWrite`). The CLI keeps no `restore` of its own; a trash restore
350
+ * goes in as `restoreFromTrash`.
351
+ */
352
+ export const addFileEditCommands = honoursDryRun(sharedCommand(addFileEditCommandsDefinition));
@@ -0,0 +1,43 @@
1
+ import type { Command } from "commander";
2
+ import type { FileTarget } from "../../documents/file-mirror-model.js";
3
+ import { type GuardedFileWriteResult } from "../../services/files/guarded-write.js";
4
+ import type { FileVersions } from "../../services/files/versions.js";
5
+ import { type Body } from "../envelope.js";
6
+ import { type DocumentWords } from "./words.js";
7
+ /** What `files update` writes through, signed in for one run. */
8
+ export interface FileUpdatePort {
9
+ target: FileTarget;
10
+ /** The profile's version store, under its state folder. */
11
+ versions: FileVersions;
12
+ signal?: AbortSignal;
13
+ }
14
+ export interface FileUpdateCommands {
15
+ words: DocumentWords;
16
+ /** `command` is the one running, in this and the helpers below: one set of helpers serves several commands. */
17
+ output(body: Body, command: Command): void;
18
+ /** What the user typed, as the target's path. */
19
+ path(input: string): string;
20
+ /** The command that reads the file and its sha256 again, for a conflict's message (`ydisk personal files show …`). */
21
+ reread(input: string): string;
22
+ /** Read for the text when --text is absent. */
23
+ stdin(): NodeJS.ReadableStream | undefined;
24
+ /**
25
+ * The CLI's own write path: its permission key for the command and `extra` (the delete key when a file is
26
+ * replaced), its run and send journal. Answers what `act` answered, with whatever the CLI adds (`operation_id`).
27
+ */
28
+ write(extra: readonly string[], act: (port: FileUpdatePort) => Promise<object>, command: Command): Promise<object>;
29
+ /** The key an overwrite also asks; `files.delete` when absent. */
30
+ deleteKey?: string;
31
+ }
32
+ /** A sha256 the user typed, in lower case; `flag` names it in the refusal. */
33
+ export declare const sha256Of: (input: string | undefined, flag?: string) => string | undefined;
34
+ /** The answer's `replaced`: the old sha256 and where its copy is kept, or null when nothing was there. */
35
+ export declare const replacedOf: (done: GuardedFileWriteResult, versions: FileVersions) => {
36
+ sha256: string;
37
+ kept_at?: string | undefined;
38
+ } | null;
39
+ /**
40
+ * `<files> update <path> (--text | stdin) [--expected-fingerprint <sha256>]`: a text written over a file only at the
41
+ * content it was read at, the replaced content kept in the profile's version store (`guardedFileWrite`).
42
+ */
43
+ export declare const addFileUpdateCommand: (files: Command, helpers: FileUpdateCommands) => Command;
@@ -0,0 +1,95 @@
1
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { CliError } from "@wirecat/cli-base";
5
+ import { annotate, sharedCommand } from "@wirecat/cli-base/commands";
6
+ import { guardedFileWrite } from "../../services/files/guarded-write.js";
7
+ import { honoursDryRun } from "../dry-run-guard.js";
8
+ import { REMOTE_WRITE } from "../effects.js";
9
+ import { itemOf } from "../envelope.js";
10
+ import { bufferedInput, MAX_BUFFERED_INPUT } from "../input-policy.js";
11
+ import { examples, wordsOf } from "./words.js";
12
+ const SHA256 = /^[0-9a-f]{64}$/u;
13
+ // A read gives the text extracted from these, never the file itself: written back, it would replace the whole file.
14
+ const EXTRACTED = /\.(pdf|docx|xlsx)$/iu;
15
+ /** A sha256 the user typed, in lower case; `flag` names it in the refusal. */
16
+ export const sha256Of = (input, flag = "--expected-fingerprint") => {
17
+ const hash = input?.toLowerCase();
18
+ if (hash !== undefined && !SHA256.test(hash))
19
+ throw new CliError("validation_error", `${flag} takes a 64-character sha256`, { param: flag });
20
+ return hash;
21
+ };
22
+ /** The answer's `replaced`: the old sha256 and where its copy is kept, or null when nothing was there. */
23
+ export const replacedOf = (done, versions) => done.replaced
24
+ ? {
25
+ sha256: done.replaced.sha256,
26
+ ...(versions.dir ? { kept_at: join(versions.dir, "objects", done.replaced.sha256) } : {}),
27
+ }
28
+ : null;
29
+ const newText = async (input, text) => {
30
+ if (text !== undefined)
31
+ return text;
32
+ if (!input || input.isTTY)
33
+ throw new CliError("validation_error", "give the new text with --text or on stdin", { param: "--text" });
34
+ const read = await bufferedInput(input, { maxBytes: MAX_BUFFERED_INPUT });
35
+ // An agent over MCP has no stdin: an empty one is a missing --text, not a wish to empty the file.
36
+ if (read.length === 0)
37
+ throw new CliError("validation_error", "stdin gave no text; give the new text with --text or on stdin", {
38
+ param: "--text",
39
+ });
40
+ return read.toString("utf8");
41
+ };
42
+ const addFileUpdateCommandDefinition = (files, helpers) => {
43
+ const { prefix, place } = wordsOf(helpers.words);
44
+ const group = files.name();
45
+ const deleteKey = helpers.deleteKey ?? "files.delete";
46
+ return examples(annotate(files.command("update"), { effects: REMOTE_WRITE, offline: false })
47
+ .summary(`replace a ${place} file's text, or create a text file`)
48
+ .description(`replace a ${place} file's text, or create a text file. A file already there is replaced only with ` +
49
+ `--expected-fingerprint, the sha256 read from it; it asks as ${deleteKey} does. The file is checked just ` +
50
+ "before the write, and what it replaced is kept on this computer. Write back only a whole plain-text file: " +
51
+ "a text cut with truncated: true would replace the whole file, and a .pdf, .docx or .xlsx is refused")
52
+ .argument("<path>", `the file on ${place}`)
53
+ .option("--text <text>", "the file's new text; without it, the text is read from stdin")
54
+ .option("--expected-fingerprint <hash>", "the sha256 the file had when it was read; required when it exists"), [
55
+ `${prefix} ${group} update /notes.md --text "# Notes"`,
56
+ `${prefix} ${group} update /notes.md --text "# Notes" --expected-fingerprint 9f86d081…`,
57
+ ]).action(async function (input, args) {
58
+ const expected = sha256Of(args.expectedFingerprint);
59
+ const path = helpers.path(input);
60
+ if (EXTRACTED.test(path))
61
+ throw new CliError("validation_error", `${path} is not a plain-text file; change a .docx with ${group} documents update and a .xlsx with ${group} ` +
62
+ "sheets update, where a CLI has them", { reason: "file.not-plain-text" });
63
+ const text = await newText(helpers.stdin(), args.text);
64
+ const answer = await helpers.write(expected ? [deleteKey] : [], async ({ target, versions, signal }) => {
65
+ const folder = await mkdtemp(join(tmpdir(), "wirecat-update-"));
66
+ try {
67
+ const from = join(folder, "text");
68
+ await writeFile(from, text, { mode: 0o600 });
69
+ const done = await guardedFileWrite({
70
+ target,
71
+ versions,
72
+ path,
73
+ from,
74
+ reread: helpers.reread(input),
75
+ ...(expected ? { expected } : {}),
76
+ ...(signal ? { signal } : {}),
77
+ });
78
+ return {
79
+ path,
80
+ sha256: done.file.sha256 ?? null,
81
+ replaced: replacedOf(done, versions),
82
+ };
83
+ }
84
+ finally {
85
+ await rm(folder, { recursive: true, force: true });
86
+ }
87
+ }, this);
88
+ helpers.output(itemOf(answer), this);
89
+ });
90
+ };
91
+ /**
92
+ * `<files> update <path> (--text | stdin) [--expected-fingerprint <sha256>]`: a text written over a file only at the
93
+ * content it was read at, the replaced content kept in the profile's version store (`guardedFileWrite`).
94
+ */
95
+ export const addFileUpdateCommand = honoursDryRun(sharedCommand(addFileUpdateCommandDefinition));
@@ -0,0 +1,34 @@
1
+ import { type Command } from "commander";
2
+ import * as v from "valibot";
3
+ import { type documentIngestion } from "../../documents.js";
4
+ import { type Body } from "../envelope.js";
5
+ import { type Settings } from "../settings.js";
6
+ import { type DocumentWords } from "./words.js";
7
+ /** The local history `documentIngestion` gives: what a CLI hands these commands. */
8
+ export type DocumentHistoryPort = ReturnType<typeof documentIngestion>["history"];
9
+ export interface DocumentHistoryCommands {
10
+ words: DocumentWords;
11
+ output(body: Body): void;
12
+ /** Opens the store read-only for the selected profile, with the source account its documents belong to. */
13
+ run<T>(fn: (history: DocumentHistoryPort, principal: string) => Promise<T>): Promise<T>;
14
+ /** The source's id from what was typed: an id or a link. A `document:<n>` ref may pass as it is. */
15
+ id(input: string): string;
16
+ }
17
+ /** `keep_versions_for_days`: a documents CLI adds it to `settingsFor` and passes `keepVersionsForDays` to its sync. */
18
+ export declare const DOCUMENT_HISTORY_SETTINGS: {
19
+ profile: {
20
+ keep_versions_for_days: v.OptionalSchema<v.SchemaWithPipe<readonly [v.NumberSchema<(issue: v.BaseIssue<unknown>) => string>, v.IntegerAction<number, (issue: v.BaseIssue<unknown>) => string>, v.MinValueAction<number, 1, (issue: v.BaseIssue<unknown>) => string>]>, undefined>;
21
+ };
22
+ settings: {
23
+ key: string;
24
+ default: number;
25
+ description: string;
26
+ }[];
27
+ };
28
+ /** The profile's `keep_versions_for_days`, or 365. */
29
+ export declare const keepVersionsForDays: (settings: Pick<Settings, "configured" | "shared">) => number;
30
+ /**
31
+ * `documents history <document>` and `changes`, over the selected profile's local history: every version a sync
32
+ * replaced or removed, and what changed since a time. A CLI whose `documents` group is its own gets them there too.
33
+ */
34
+ export declare const addDocumentHistoryCommands: (program: Command, helpers: DocumentHistoryCommands) => Command;
@@ -0,0 +1,89 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { annotate, sharedCommand } from "@wirecat/cli-base/commands";
3
+ import { InvalidArgumentError } from "commander";
4
+ import * as v from "valibot";
5
+ import { KEEP_VERSIONS_FOR_DAYS } from "../../documents.js";
6
+ import { momentOf } from "../../services/moment.js";
7
+ import { DOCUMENT_EVENTS } from "../../store/index.js";
8
+ import { honoursDryRun } from "../dry-run-guard.js";
9
+ import { LOCAL_READ } from "../effects.js";
10
+ import { itemOf, listOf } from "../envelope.js";
11
+ import { count, fromFile } from "../settings.js";
12
+ import { documentsGroup, examples, positive, wordsOf } from "./words.js";
13
+ /** `keep_versions_for_days`: a documents CLI adds it to `settingsFor` and passes `keepVersionsForDays` to its sync. */
14
+ export const DOCUMENT_HISTORY_SETTINGS = {
15
+ profile: { keep_versions_for_days: v.optional(count) },
16
+ settings: [
17
+ {
18
+ key: "keep_versions_for_days",
19
+ default: KEEP_VERSIONS_FOR_DAYS,
20
+ description: "days earlier versions of synced documents, and the change log, are kept",
21
+ },
22
+ ],
23
+ };
24
+ /** The profile's `keep_versions_for_days`, or 365. */
25
+ export const keepVersionsForDays = (settings) => fromFile(settings, "keep_versions_for_days", KEEP_VERSIONS_FOR_DAYS).value;
26
+ const eventList = (input, before = []) => {
27
+ const events = input.split(",").map((one) => one.trim());
28
+ for (const event of events)
29
+ if (!DOCUMENT_EVENTS.includes(event))
30
+ throw new InvalidArgumentError(`use ${DOCUMENT_EVENTS.join(", ")}`);
31
+ return [...before, ...events];
32
+ };
33
+ const addDocumentHistoryCommandsDefinition = (program, helpers) => {
34
+ const wording = wordsOf(helpers.words);
35
+ const { prefix, text } = wording;
36
+ const documents = documentsGroup(program, wording);
37
+ const reference = async (history, principal, input) => {
38
+ const found = await history.reference(principal, /^document:\d+$/.test(input) ? input : helpers.id(input));
39
+ if (!found)
40
+ throw new CliError("not_found", "this document is not in the selected profile's local copy", {
41
+ reason: "document.not-imported",
42
+ });
43
+ return found;
44
+ };
45
+ examples(annotate(documents.command("history"), { effects: LOCAL_READ })
46
+ .argument("<document>", text.documentArgument)
47
+ .description("list the versions of a document kept in the local copy, or show one with --revision"), [`${prefix} documents history DOC_ID`, `${prefix} documents history DOC_ID --revision 3`])
48
+ .option("--revision <n>", "show the text of this version", positive)
49
+ .action((input, args) => helpers.run(async (history, principal) => {
50
+ const ref = await reference(history, principal, input);
51
+ if (args.revision !== undefined) {
52
+ helpers.output(itemOf({ document: ref, ...(await history.version(ref, args.revision)) }));
53
+ return;
54
+ }
55
+ helpers.output(itemOf(await history.versions(ref)));
56
+ }));
57
+ return examples(annotate(program.command("changes"), { effects: LOCAL_READ }).description("list the documents the sync added, changed, removed or brought back, newest first"), [`${prefix} changes`, `${prefix} changes --since 7d --event deleted,unavailable`])
58
+ .option("--since <when>", "from this time: an ISO 8601 time, today, yesterday, or 30m, 2h, 1d ago", "1d")
59
+ .option("--until <when>", "up to this time, in the same forms")
60
+ .option(`--event <events>`, `only these, comma separated: ${DOCUMENT_EVENTS.join(", ")}`, eventList)
61
+ .option("--limit <n>", "how many changes to return", positive, 50)
62
+ .option("--page <n>", "which page to return", positive, 1)
63
+ .action((args) => helpers.run(async (history, principal) => {
64
+ const now = Date.now();
65
+ const since = new Date(momentOf(args.since, "--since", now)).toISOString();
66
+ const until = args.until === undefined
67
+ ? undefined
68
+ : new Date(momentOf(args.until, "--until", now, { end: true })).toISOString();
69
+ const found = await history.changes(principal, {
70
+ since,
71
+ ...(until ? { until } : {}),
72
+ ...(args.event ? { events: args.event } : {}),
73
+ limit: args.limit,
74
+ offset: (args.page - 1) * args.limit,
75
+ });
76
+ helpers.output(listOf("changes", {
77
+ items: found.items,
78
+ limit: args.limit,
79
+ has_more: found.hasMore,
80
+ page: args.page,
81
+ args: { since, ...(until ? { until } : {}), ...(args.event ? { event: args.event } : {}) },
82
+ }));
83
+ }));
84
+ };
85
+ /**
86
+ * `documents history <document>` and `changes`, over the selected profile's local history: every version a sync
87
+ * replaced or removed, and what changed since a time. A CLI whose `documents` group is its own gets them there too.
88
+ */
89
+ export const addDocumentHistoryCommands = honoursDryRun(sharedCommand(addDocumentHistoryCommandsDefinition));
@@ -2,6 +2,7 @@ import type { Command } from "commander";
2
2
  import { type DocumentCatalogCommands } from "./catalog.js";
3
3
  import { type LocalDocumentCommands } from "./documents.js";
4
4
  import { type DocumentFolderCommands } from "./folders.js";
5
+ import { type DocumentHistoryCommands } from "./history.js";
5
6
  import { type DocumentKnowledgeCommands } from "./knowledge.js";
6
7
  import { type DocumentMirrorCommands } from "./mirrors.js";
7
8
  import { type DocumentSearchCommands } from "./search.js";
@@ -9,7 +10,11 @@ import { type DocumentSyncCommands } from "./sync.js";
9
10
  import type { DocumentWords } from "./words.js";
10
11
  export { addDocumentCatalogCommands, CATALOG_FIELDS, type CatalogTree, type CatalogTreeSource, catalogId, catalogOutput, catalogSource, catalogTree, type DocumentCatalog, type DocumentCatalogCommands, type DocumentCatalogStores, } from "./catalog.js";
11
12
  export { addLocalDocumentCommands, type ImportedDocument, type LocalDocumentCommands } from "./documents.js";
13
+ export { type FileConflictCommands, fileConflictsCommand } from "./file-conflicts.js";
14
+ export { addFileEditCommands, type FileEditCommands } from "./file-edit.js";
15
+ export { addFileUpdateCommand, type FileUpdateCommands, type FileUpdatePort } from "./file-update.js";
12
16
  export { addDocumentFolderCommands, type DocumentFolderCommands } from "./folders.js";
17
+ export { addDocumentHistoryCommands, DOCUMENT_HISTORY_SETTINGS, type DocumentHistoryCommands, type DocumentHistoryPort, keepVersionsForDays, } from "./history.js";
13
18
  export { addDocumentKnowledgeCommands, type DocumentKnowledgeCommands, type DocumentKnowledgePort, } from "./knowledge.js";
14
19
  export { addDocumentMirrorCommands, type DocumentMirrorCommands, type DocumentMirrorConnection } from "./mirrors.js";
15
20
  export { documentQueries, FACT_QUERY, factItem, folderRow, IDENTITY_ROLES, identityRow, linkRow, MEMORY_QUERY, MEMORY_SEARCH_QUERY, memoryItem, memorySearch, mirrorRow, tagRow, } from "./queries.js";
@@ -28,10 +33,12 @@ export interface DocumentCommands<S> {
28
33
  catalog: Group<DocumentCatalogCommands>;
29
34
  knowledge: Group<DocumentKnowledgeCommands>;
30
35
  mirrors?: Group<DocumentMirrorCommands<S>>;
36
+ /** `documents history` and `changes`, over the local history; left out, a CLI has neither. */
37
+ history?: Group<DocumentHistoryCommands>;
31
38
  }
32
39
  /**
33
- * `folders`, `sync`, `status`, `documents list|show|export|context`, `search`, `catalog`, the knowledge groups and,
34
- * when given, `mirrors`, in that order. Answers the `documents` group, for the CLI's live subcommands.
40
+ * `folders`, `sync`, `status`, `documents list|show|export|context`, when given `documents history` and `changes`,
41
+ * `search`, `catalog`, the knowledge groups and, when given, `mirrors`, in that order. Answers the `documents` group, for the CLI's live subcommands.
35
42
  */
36
43
  export declare const addDocumentCommands: <S>(program: Command, options: DocumentCommands<S>) => Command;
37
44
  export { claimDocumentAccount, type DocumentLibraryOptions, type DocumentLibraryTools, type DocumentSourceRun, type DocumentWarning, documentLibraryCommands, documentProfile, } from "./library.js";