@wirecat/cli-core 0.738.0 → 0.739.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 CHANGED
@@ -5,6 +5,46 @@ Notable changes to `@wirecat/cli-core` (`@wirecat/cli-messaging` up to 0.261.0,
5
5
  minor version may break callers, and says how under "Changed — may break callers". `pnpm docs:check` checks the
6
6
  shape of this file.
7
7
 
8
+ ## 0.739.0 — 24.11.2026
9
+
10
+ ### Added
11
+
12
+ - **A documents sync reads every format cli-core's readers read.** `readableFile` now takes Word 97–2003 (`.doc`),
13
+ RTF, HTML, OpenDocument (`.odt`, `.ods`, `.odp`), PowerPoint (`.pptx`) and EPUB beside PDF, docx, xlsx, CSV, TSV,
14
+ plain text and Markdown, so Yandex Disk and other CLIs built on it no longer keep them by name only. Images and
15
+ scans stay by name only.
16
+ - **A documents sync lists several folders at once on a source that sets `parallelListings`** (a whole number up to
17
+ 8). A source whose one listing takes seconds (Yandex Disk) can set it, for example to 4, so a sync of many folders
18
+ can take less time. Each listing takes its own request from the run's budget, and the walk files the same
19
+ documents, though the order they are saved in may differ. A call cut short or a failed listing loses nothing: the
20
+ folder stays on the saved walk and is listed again in the next sync. Unset, a sync lists one folder at a time as
21
+ before.
22
+ - **`addFileEditCommands` takes `creates: false`** for a provider that names a file by an id it gives, as Google
23
+ Drive does. `sheets create` and `documents create` are then left out, since a path the user types can't name a
24
+ new file there. The edits, `history` and `restore` stay.
25
+ - **`sheets create` makes several sheets, formulas and bold cells.** `--values` also takes
26
+ `[{"name": "Budget", "header": true, "rows": [...]}]` for several sheets, and a cell may be
27
+ `{"formula": "SUM(B2:B3)"}` or `{"value": "Total", "bold": true}`. Excel and LibreOffice compute the formulas when
28
+ the file opens. A text that starts with `=` still stays text, so data from elsewhere never becomes a formula. Today's
29
+ rows keep working. `createXlsx` takes the same cells and a sheet's `header` ([Editing Office files](docs/office.md#new-files)).
30
+ - **`documents create` makes bold and italic text and tables.** `--payload` also takes `{"text", "bold", "italic"}`,
31
+ `{"runs": [{"text": "grew", "bold": true}]}` and `{"table": [["Item", "Cost"], ["Rent", "950"]], "header": true}`.
32
+ Today's `[{"text", "style"}]` keeps working, and `createDocx` takes the same entries.
33
+ - **`rekeySyncedDocument`** (`@wirecat/cli-core/documents/cli`) moves a synced document to the new id a provider gave
34
+ the file after a replace, so the owner's tags, the notes about it and its links follow the file. A sync that ran in
35
+ between and filed the file anew is folded into the old document; a failure only warns. Behind it, the documents
36
+ ingestion's `rekey` and `renameFileNote(…, { fold: true })`
37
+ ([DOCUMENTS](docs/dev/DOCUMENTS.md#write-one-file-at-the-hash-read)).
38
+
39
+ ### Fixed
40
+
41
+ - **A file an older version kept by name as `unsupported type: …` is read on the next sync** once its type is
42
+ readable, even when the file did not change. A file whose read failed (damaged, no text layer) is not read again.
43
+ - **A target's own conflict keeps its words.** `guardedFileWrite` and a mirror's sync replaced every `conflict` from
44
+ `upload` with "changed since it was read; nothing was written", even when the target had done something and said
45
+ so. A conflict with a reason other than `mirror.remote-changed`, such as the new `upload.replace-interrupted`, now
46
+ reaches the caller unchanged.
47
+
8
48
  ## 0.738.0 — 24.11.2026
9
49
 
10
50
  ### Added
@@ -113,8 +113,35 @@ const docxEditsOf = (payload) => payload.map((edit) => {
113
113
  };
114
114
  return edit;
115
115
  });
116
- const NEW_PARAGRAPHS = v.pipe(v.array(v.strictObject({ text: v.string(), style: v.optional(v.picklist(NEW_PARAGRAPH_STYLES)) })), v.minLength(1));
117
- const NEW_PARAGRAPHS_SHAPE = `paragraphs as JSON: [{"text": "…", "style": "Heading1"}]; a style is one of ${NEW_PARAGRAPH_STYLES.join(", ")}`;
116
+ const SCALAR = v.union([v.string(), v.number(), v.boolean(), v.null()]);
117
+ const BOLD = v.optional(v.boolean());
118
+ const NEW_ROWS = v.array(v.array(v.union([
119
+ SCALAR,
120
+ v.strictObject({ formula: v.string(), bold: BOLD }),
121
+ v.strictObject({ value: SCALAR, bold: BOLD }),
122
+ ])));
123
+ const NEW_VALUES = v.union([
124
+ v.pipe(NEW_ROWS, v.minLength(1)),
125
+ v.pipe(v.array(v.strictObject({ name: v.string(), rows: NEW_ROWS, header: v.optional(v.boolean()) })), v.minLength(1)),
126
+ ]);
127
+ const isRows = (values) => values.every(Array.isArray);
128
+ const NEW_VALUES_SHAPE = 'rows of cells as JSON, such as [["Item", "Cost"], ["Rent", 950], ["Total", {"formula": "SUM(B2)"}]], or sheets ' +
129
+ 'as [{"name": "Budget", "rows": [...], "header": true}]; a cell is a text, number, boolean, null, ' +
130
+ '{"formula": "…"} or {"value": …, "bold": true}';
131
+ const STYLE = v.optional(v.picklist(NEW_PARAGRAPH_STYLES));
132
+ const NEW_PARAGRAPHS = v.pipe(v.array(v.union([
133
+ v.strictObject({ text: v.string(), style: STYLE, bold: BOLD, italic: BOLD }),
134
+ v.strictObject({
135
+ runs: v.pipe(v.array(v.strictObject({ text: v.string(), bold: BOLD, italic: BOLD })), v.minLength(1)),
136
+ style: STYLE,
137
+ }),
138
+ v.strictObject({
139
+ table: v.array(v.array(v.pipe(v.union([v.string(), v.number()]), v.toString()))),
140
+ header: v.optional(v.boolean()),
141
+ }),
142
+ ])), v.minLength(1));
143
+ const NEW_PARAGRAPHS_SHAPE = 'paragraphs and tables as JSON: [{"text": "…", "style": "Heading1"}, {"runs": [{"text": "…", "bold": true}]}, ' +
144
+ `{"table": [["Item", "Cost"], ["Rent", "950"]], "header": true}]; a style is one of ${NEW_PARAGRAPH_STYLES.join(", ")}`;
118
145
  const addFileEditCommandsDefinition = (files, helpers) => {
119
146
  const { prefix, place } = wordsOf(helpers.words);
120
147
  const group = files.name();
@@ -268,22 +295,35 @@ const addFileEditCommandsDefinition = (files, helpers) => {
268
295
  }
269
296
  });
270
297
  });
271
- examples(annotate(sheets.command("create"), { effects: REMOTE_WRITE, offline: false })
272
- .summary("create a new workbook from rows of values")
273
- .description(`create a new .xlsx on ${place} with one sheet holding these rows from A1. Numbers and booleans are typed, a ` +
274
- "text stays text, even one that starts with =. A file already there is refused: change it with sheets update")
275
- .argument("<path>", `the new .xlsx file on ${place}`)
276
- .option("--values <json>", "the rows as JSON; null leaves a cell empty")
277
- .option("--name <name>", "the sheet's name; Sheet1 without it"), [`${prefix} ${group} sheets create /budget.xlsx --values '[["Item", "Cost"], ["Rent", 950]]' --name Budget`]).action(async function (input, args) {
278
- if (args.values === undefined)
279
- throw new CliError("validation_error", `give the rows with --values: ${VALUES_SHAPE}`, { param: "--values" });
280
- const rows = jsonOf(args.values, "--values", VALUES, VALUES_SHAPE);
281
- const name = args.name ?? "Sheet1";
282
- await createNew(this, "sheets", input, ".xlsx", {
283
- bytes: createXlsx({ sheets: [{ name, rows }] }),
284
- answer: { sheets: [{ name, rows: rows.length }] },
298
+ if (helpers.creates !== false)
299
+ examples(annotate(sheets.command("create"), { effects: REMOTE_WRITE, offline: false })
300
+ .summary("create a new workbook from rows of values and formulas")
301
+ .description(`create a new .xlsx on ${place} from rows from A1: one sheet, or several given as [{name, rows, header?}]. ` +
302
+ "Numbers and booleans are typed, a text stays text, even one that starts with =. A formula is only " +
303
+ '{"formula": "SUM(B2:B3)"}, computed when the file opens; {"value": "Total", "bold": true} is a bold cell ' +
304
+ "and header: true makes a sheet's first row bold. A file already there is refused: change it with sheets update")
305
+ .argument("<path>", `the new .xlsx file on ${place}`)
306
+ .option("--values <json>", 'the rows as JSON, or [{"name", "rows", "header"?}] for several sheets; a cell is a text, number, ' +
307
+ 'boolean, null (empty), {"formula": "…", "bold"?} or {"value": …, "bold"?}')
308
+ .option("--name <name>", "the sheet's name when --values is rows; Sheet1 without it"), [
309
+ `${prefix} ${group} sheets create /budget.xlsx --values '[["Item", "Cost"], ["Rent", 950]]' --name Budget`,
310
+ `${prefix} ${group} sheets create /budget.xlsx --values '[{"name": "Budget", "header": true, "rows": [["Item", "Cost"], ["Rent", 950], ["Food", 300], [{"value": "Total", "bold": true}, {"formula": "SUM(B2:B3)"}]]}]'`,
311
+ ]).action(async function (input, args) {
312
+ if (args.values === undefined)
313
+ throw new CliError("validation_error", `give the rows with --values: ${NEW_VALUES_SHAPE}`, {
314
+ param: "--values",
315
+ });
316
+ const values = jsonOf(args.values, "--values", NEW_VALUES, NEW_VALUES_SHAPE);
317
+ const sheets = isRows(values) ? [{ name: args.name ?? "Sheet1", rows: values }] : values;
318
+ if (args.name !== undefined && !isRows(values))
319
+ throw new CliError("validation_error", "--name names the one sheet of rows; with sheets, each has its name", {
320
+ param: "--name",
321
+ });
322
+ await createNew(this, "sheets", input, ".xlsx", {
323
+ bytes: createXlsx({ sheets }),
324
+ answer: { sheets: sheets.map(({ name, rows }) => ({ name, rows: rows.length })) },
325
+ });
285
326
  });
286
- });
287
327
  const documents = annotate(files.command("documents"), { effects: REMOTE_READ }).description(`the paragraphs of a Word document (.docx) on ${place}, read and changed in place`);
288
328
  examples(marksUntrusted(annotate(documents.command("show"), { effects: REMOTE_READ, offline: false }), ["paragraphs.text"])
289
329
  .summary("show a document's paragraphs and the sha256 to edit them at")
@@ -328,25 +368,30 @@ const addFileEditCommandsDefinition = (files, helpers) => {
328
368
  };
329
369
  });
330
370
  });
331
- examples(annotate(documents.command("create"), { effects: REMOTE_WRITE, offline: false })
332
- .summary("create a new Word document from paragraphs")
333
- .description(`create a new .docx on ${place} with these paragraphs, each in a style: ${NEW_PARAGRAPH_STYLES.join(", ")} ` +
334
- "(Normal without one; ListBullet is a bullet list). A file already there is refused: change it with " +
335
- "documents update")
336
- .argument("<path>", `the new .docx file on ${place}`)
337
- .option("--payload <json>", "the paragraphs as JSON: [{text, style?}]"), [
338
- `${prefix} ${group} documents create /report.docx --payload '[{"text": "Report", "style": "Title"}, {"text": "Revenue grew 12%."}]'`,
339
- ]).action(async function (input, args) {
340
- if (args.payload === undefined)
341
- throw new CliError("validation_error", `give the paragraphs with --payload: ${NEW_PARAGRAPHS_SHAPE}`, {
342
- param: "--payload",
371
+ if (helpers.creates !== false)
372
+ examples(annotate(documents.command("create"), { effects: REMOTE_WRITE, offline: false })
373
+ .summary("create a new Word document from paragraphs and tables")
374
+ .description(`create a new .docx on ${place} with these paragraphs, each in a style: ${NEW_PARAGRAPH_STYLES.join(", ")} ` +
375
+ "(Normal without one; ListBullet is a bullet list), and tables. A paragraph is bold or italic as a whole, " +
376
+ "or made of runs that each are; a table is rows of cell texts, its first row bold with header: true. A " +
377
+ "file already there is refused: change it with documents update")
378
+ .argument("<path>", `the new .docx file on ${place}`)
379
+ .option("--payload <json>", "the body as JSON, in order: [{text, style?, bold?, italic?}, {runs: [{text, bold?, italic?}], style?}, " +
380
+ "{table: [[cell, …], …], header?}]"), [
381
+ `${prefix} ${group} documents create /report.docx --payload '[{"text": "Report", "style": "Title"}, {"text": "Revenue grew 12%."}]'`,
382
+ `${prefix} ${group} documents create /report.docx --payload '[{"runs": [{"text": "Revenue "}, {"text": "grew 12%", "bold": true}]}, {"table": [["Item", "Cost"], ["Rent", "950"]], "header": true}]'`,
383
+ ]).action(async function (input, args) {
384
+ if (args.payload === undefined)
385
+ throw new CliError("validation_error", `give the paragraphs with --payload: ${NEW_PARAGRAPHS_SHAPE}`, {
386
+ param: "--payload",
387
+ });
388
+ const paragraphs = jsonOf(args.payload, "--payload", NEW_PARAGRAPHS, NEW_PARAGRAPHS_SHAPE);
389
+ const tables = paragraphs.filter((block) => "table" in block).length;
390
+ await createNew(this, "documents", input, ".docx", {
391
+ bytes: createDocx({ paragraphs }),
392
+ answer: { paragraphs: paragraphs.length - tables, ...(tables ? { tables } : {}) },
343
393
  });
344
- const paragraphs = jsonOf(args.payload, "--payload", NEW_PARAGRAPHS, NEW_PARAGRAPHS_SHAPE);
345
- await createNew(this, "documents", input, ".docx", {
346
- bytes: createDocx({ paragraphs }),
347
- answer: { paragraphs: paragraphs.length },
348
394
  });
349
- });
350
395
  examples(annotate(files.command("history"), { effects: REMOTE_READ, offline: false })
351
396
  .summary("list the earlier versions of a file kept on this computer")
352
397
  .description("list what the writes and syncs of this profile replaced in a file, newest last. Each entry's version is the " +
@@ -28,6 +28,11 @@ export interface FileUpdateCommands {
28
28
  write(extra: readonly string[], act: (port: FileUpdatePort) => Promise<object>, command: Command): Promise<object>;
29
29
  /** The key an overwrite also asks; `files.delete` when absent. */
30
30
  deleteKey?: string;
31
+ /**
32
+ * False where the provider names a file by an id it gives, so a path the user types can't name a new file:
33
+ * `sheets create` and `documents create` are left out.
34
+ */
35
+ creates?: boolean;
31
36
  }
32
37
  /** A sha256 the user typed, in lower case; `flag` names it in the refusal. */
33
38
  export declare const sha256Of: (input: string | undefined, flag?: string) => string | undefined;
@@ -20,6 +20,7 @@ export { addDocumentHistoryCommands, DOCUMENT_HISTORY_SETTINGS, type DocumentHis
20
20
  export { addDocumentKnowledgeCommands, type DocumentKnowledgeCommands, type DocumentKnowledgePort, } from "./knowledge.js";
21
21
  export { addDocumentMirrorCommands, type DocumentMirrorCommands, type DocumentMirrorConnection } from "./mirrors.js";
22
22
  export { documentQueries, FACT_QUERY, factItem, folderRow, IDENTITY_ROLES, identityRow, linkRow, MEMORY_QUERY, MEMORY_SEARCH_QUERY, memoryItem, memorySearch, mirrorRow, tagRow, } from "./queries.js";
23
+ export { rekeySyncedDocument, type SyncedDocumentRekey } from "./rekey.js";
23
24
  export { addDocumentSearchCommand, type DocumentSearchCommands, type DocumentSearchOptions } from "./search.js";
24
25
  export { addDocumentSyncCommands, type DocumentSyncArgs, type DocumentSyncCommands } from "./sync.js";
25
26
  export { ageOf, type CopyAge, type DocumentTexts, type DocumentWords, staleCopy } from "./words.js";
@@ -18,6 +18,7 @@ export { addDocumentHistoryCommands, DOCUMENT_HISTORY_SETTINGS, keepVersionsForD
18
18
  export { addDocumentKnowledgeCommands, } from "./knowledge.js";
19
19
  export { addDocumentMirrorCommands } from "./mirrors.js";
20
20
  export { documentQueries, FACT_QUERY, factItem, folderRow, IDENTITY_ROLES, identityRow, linkRow, MEMORY_QUERY, MEMORY_SEARCH_QUERY, memoryItem, memorySearch, mirrorRow, tagRow, } from "./queries.js";
21
+ export { rekeySyncedDocument } from "./rekey.js";
21
22
  export { addDocumentSearchCommand } from "./search.js";
22
23
  export { addDocumentSyncCommands } from "./sync.js";
23
24
  export { ageOf, staleCopy } from "./words.js";
@@ -360,7 +360,9 @@ const libraryOf = (options, withSync) => {
360
360
  isFolder: options.isFolder,
361
361
  ...(options.isDocument ? { isDocument: options.isDocument } : {}),
362
362
  skipReason: options.skipReason ?? (() => undefined),
363
- retryable: () => false,
363
+ // A file an older version kept by name for its type is read once a newer one reads that type; the
364
+ // planner asks only when `skipReason` no longer gives a reason. The words are the CLIs' own.
365
+ retryable: (skip) => skip.reason.startsWith("unsupported type: "),
364
366
  errorOf,
365
367
  assertHeld,
366
368
  storeVersion: app.version,
@@ -0,0 +1,22 @@
1
+ import type { ProviderEntry } from "../../domain/providers.js";
2
+ import type { AppIdentity } from "../../ports/app.js";
3
+ import type { MessageStore } from "../../store/index.js";
4
+ export interface SyncedDocumentRekey {
5
+ env: NodeJS.ProcessEnv;
6
+ app: Pick<AppIdentity, "command" | "version">;
7
+ provider: ProviderEntry;
8
+ /** The same ingestion the CLI's documents commands file documents with. */
9
+ ingestion(store: MessageStore): {
10
+ rekey(principal: string, from: string, to: string): Promise<boolean>;
11
+ };
12
+ /** The account's principal, as the documents sync names it. */
13
+ account: string;
14
+ from: string;
15
+ to: string;
16
+ warn(message: string): void;
17
+ }
18
+ /**
19
+ * After a write that gave a file a new id at the provider, moves its synced copy to that id, so the owner's tags and
20
+ * notes follow the file. The write already happened, so a failure only warns; a store never opened stays unopened.
21
+ */
22
+ export declare const rekeySyncedDocument: (input: SyncedDocumentRekey) => Promise<boolean>;
@@ -0,0 +1,25 @@
1
+ import { existsSync } from "node:fs";
2
+ import { storePath } from "../../store/path.js";
3
+ import { openAppStore } from "../app-store.js";
4
+ /**
5
+ * After a write that gave a file a new id at the provider, moves its synced copy to that id, so the owner's tags and
6
+ * notes follow the file. The write already happened, so a failure only warns; a store never opened stays unopened.
7
+ */
8
+ export const rekeySyncedDocument = async (input) => {
9
+ if (!existsSync(storePath(input.env)))
10
+ return false;
11
+ try {
12
+ const store = await openAppStore(input.env, { app: input.app, provider: input.provider });
13
+ try {
14
+ return await input.ingestion(store).rekey(input.account, input.from, input.to);
15
+ }
16
+ finally {
17
+ await store.close();
18
+ }
19
+ }
20
+ catch (error) {
21
+ const why = error instanceof Error ? error.message : String(error);
22
+ input.warn(`the synced copy keeps its tags and notes under the old id ${input.from}: ${why}`);
23
+ return false;
24
+ }
25
+ };
@@ -2,7 +2,10 @@
2
2
  export interface RemoteFile {
3
3
  /** Relative to the listed folder, with `/` separators. */
4
4
  path: string;
5
- /** Stays the same across a move or an overwrite, so a remote rename is found by it. */
5
+ /**
6
+ * Stays the same across a move, so a remote rename is found by it. A replace may give a new one (Yandex Disk's
7
+ * replace through a temporary file); the mirror records what the upload returns.
8
+ */
6
9
  id: string;
7
10
  size: number;
8
11
  /** The plain sha256 of the content. A file without one (still being processed) is left for the next run. */
@@ -67,6 +67,12 @@ export interface FeedlessDocumentSource<M extends SourceFile = SourceFile> {
67
67
  }>;
68
68
  content(id: string, maxChars?: number, file?: M): Promise<SourceContent<M>>;
69
69
  bytes(id: string, file?: M): Promise<Uint8Array>;
70
+ /**
71
+ * How many folders a sync lists at once, for a provider whose one listing takes seconds (Yandex Disk): a whole
72
+ * number up to 8; one when unset or anything else. Each listing takes its own request from the run's budget; a source that paces its requests keeps pacing
73
+ * them, so stay within the provider's rate limit.
74
+ */
75
+ parallelListings?: number;
70
76
  /**
71
77
  * Whether a saved document is read again though it did not change: one saved before the source learned to read
72
78
  * something (a page's authors). The sync reads at most `REREAD_BATCH` of them a pass, so new edits are not held back;
@@ -1,7 +1,7 @@
1
1
  import { QUERY_REASONS } from "@wirecat/cli-base/query";
2
2
  import { defineReasons } from "@wirecat/cli-base/standards";
3
3
  import { CHAT_SENDING_ASK_DETAILS } from "../models/chat-sending.js";
4
- const validation = (reason, message) => [reason, "validation_error", message];
4
+ import { SFTP, validation } from "./sftp-reasons.js";
5
5
  /** The query reasons only message search raises; the shared ones are cli-base's `QUERY_REASONS`. */
6
6
  const QUERY = [
7
7
  ["query.aborted", "the search was stopped before it finished"],
@@ -97,20 +97,6 @@ const PROVIDER_API = [
97
97
  validation("file.too-large", "the file is larger than the limit set for this read"),
98
98
  validation("file.not-plain-text", "the file's text is extracted on a read; writing it back would replace the file"),
99
99
  ];
100
- /** The read-only SFTP client (`./sftp`). */
101
- const SFTP = [
102
- ["sftp.host-key-missing", "configuration_error", "no host key is pinned for the SFTP server"],
103
- ["sftp.host-key-mismatch", "authentication_error", "the SFTP server's host key is not the pinned one"],
104
- ["sftp.auth-missing", "configuration_error", "an SFTP connection needs a password or a private key"],
105
- ["sftp.key-invalid", "configuration_error", "the SFTP private key or its passphrase cannot be read"],
106
- ["sftp.library-missing", "configuration_error", "SFTP needs the ssh2 package in the CLI's dependencies"],
107
- ["sftp.timeout", "timeout", "the SFTP server did not answer in time"],
108
- validation("sftp.too-large", "the file is larger than the read's byte limit"),
109
- validation("sftp.closed", "the SFTP connection was closed before the operation"),
110
- validation("sftp.file-changed", "the file changed on the server while a stream read it; read it again"),
111
- ["ssh.forward-refused", "permission_error", "the SSH server does not allow forwarding to that address"],
112
- ["ssh.forward-failed", "network_error", "the SSH server could not reach the address behind it"],
113
- ];
114
100
  /** The read-only SQL reader (`./sql`). */
115
101
  const SQL = [
116
102
  validation("sql.bad-identifier", "a table or column name is not a plain identifier"),
@@ -307,6 +293,7 @@ const OTHERS = [
307
293
  ["mirror.remote-changed", "conflict", "the remote file changed since the listing; the next sync settles it"],
308
294
  ["mirror.local-changed", "conflict", "the local file changed since the conflict was found; nothing was written"],
309
295
  ["mirror.no-conflict", "not_found", "the path has no recorded conflict; the last sync settled it or never saw one"],
296
+ ["upload.replace-interrupted", "conflict", "another file took the path during a replace; the new content is kept"],
310
297
  ["upload.mismatch", "conflict", "the uploaded file reads back with other content; the local file changed meanwhile"],
311
298
  ["download.mismatch", "invalid_response", "the downloaded file has other content than the listing said"],
312
299
  ["catalog.unavailable", "configuration_error", "the store has no shared catalog for this account"],
@@ -0,0 +1,5 @@
1
+ import type { ErrorReason } from "@wirecat/cli-base/standards";
2
+ export type Entry = [reason: string, code: ErrorReason["code"], message: string];
3
+ export declare const validation: (reason: string, message: string) => Entry;
4
+ /** The read-only SFTP client (`./sftp`). */
5
+ export declare const SFTP: Entry[];
@@ -0,0 +1,15 @@
1
+ export const validation = (reason, message) => [reason, "validation_error", message];
2
+ /** The read-only SFTP client (`./sftp`). */
3
+ export const SFTP = [
4
+ ["sftp.host-key-missing", "configuration_error", "no host key is pinned for the SFTP server"],
5
+ ["sftp.host-key-mismatch", "authentication_error", "the SFTP server's host key is not the pinned one"],
6
+ ["sftp.auth-missing", "configuration_error", "an SFTP connection needs a password or a private key"],
7
+ ["sftp.key-invalid", "configuration_error", "the SFTP private key or its passphrase cannot be read"],
8
+ ["sftp.library-missing", "configuration_error", "SFTP needs the ssh2 package in the CLI's dependencies"],
9
+ ["sftp.timeout", "timeout", "the SFTP server did not answer in time"],
10
+ validation("sftp.too-large", "the file is larger than the read's byte limit"),
11
+ validation("sftp.closed", "the SFTP connection was closed before the operation"),
12
+ validation("sftp.file-changed", "the file changed on the server while a stream read it; read it again"),
13
+ ["ssh.forward-refused", "permission_error", "the SSH server does not allow forwarding to that address"],
14
+ ["ssh.forward-failed", "network_error", "the SSH server could not reach the address behind it"],
15
+ ];
@@ -1,9 +1,22 @@
1
1
  import type { CellValue } from "./xlsx.js";
2
+ /** A formula without a cached result, computed when the file opens; `=` in front is optional. */
3
+ export interface NewFormulaCell {
4
+ readonly formula: string;
5
+ readonly bold?: boolean;
6
+ }
7
+ /** A value with formatting; a text that starts with `=` stays text here too. */
8
+ export interface NewValueCell {
9
+ readonly value: CellValue;
10
+ readonly bold?: boolean;
11
+ }
12
+ export type NewCell = CellValue | NewFormulaCell | NewValueCell;
2
13
  export interface NewSheet {
3
14
  /** 1 to 31 characters, none of `[]:*?/\`, not starting or ending with `'`; unique in the workbook, ignoring case. */
4
15
  readonly name: string;
5
16
  /** Rows from A1 down; `null` leaves a cell empty. */
6
- readonly rows: readonly (readonly CellValue[])[];
17
+ readonly rows: readonly (readonly NewCell[])[];
18
+ /** This sheet's first row in bold. */
19
+ readonly header?: boolean;
7
20
  }
8
21
  export interface CreateXlsxOptions {
9
22
  readonly sheets: readonly NewSheet[];
@@ -12,23 +25,41 @@ export interface CreateXlsxOptions {
12
25
  }
13
26
  /**
14
27
  * A new workbook with these sheets and values: strings in a shared strings part (a string that starts with `=` stays
15
- * text), numbers and booleans typed. No document properties, so the same input gives the same bytes.
28
+ * text), numbers and booleans typed, `{formula}` a formula. No document properties, so the same input gives the same
29
+ * bytes.
16
30
  */
17
31
  export declare const createXlsx: (options: CreateXlsxOptions) => Uint8Array;
18
32
  export declare const NEW_PARAGRAPH_STYLES: readonly ["Title", "Heading1", "Heading2", "Heading3", "Normal", "ListBullet"];
19
33
  export type NewParagraphStyle = (typeof NEW_PARAGRAPH_STYLES)[number];
20
- export interface NewParagraph {
34
+ export interface NewRun {
21
35
  /** A tab is `\t`, a line break `\n`. */
22
36
  readonly text: string;
37
+ readonly bold?: boolean;
38
+ readonly italic?: boolean;
39
+ }
40
+ export type NewParagraph = ({
41
+ readonly text: string;
42
+ readonly bold?: boolean;
43
+ readonly italic?: boolean;
44
+ } | {
45
+ readonly runs: readonly NewRun[];
46
+ }) & {
23
47
  /** `Normal` when absent. */
24
48
  readonly style?: NewParagraphStyle;
49
+ };
50
+ export interface NewTable {
51
+ /** Rows of cell texts; a shorter row is filled with empty cells. */
52
+ readonly table: readonly (readonly string[])[];
53
+ /** The first row in bold, repeated at the top of each page. */
54
+ readonly header?: boolean;
25
55
  }
26
56
  export interface CreateDocxOptions {
27
- readonly paragraphs: readonly NewParagraph[];
57
+ /** The body in order: paragraphs and tables. */
58
+ readonly paragraphs: readonly (NewParagraph | NewTable)[];
28
59
  }
29
60
  /**
30
- * A new Word document with these paragraphs, on A4 with 2.5 cm margins, and a styles part that defines Title,
31
- * Heading1 to Heading3, Normal and ListBullet (a bullet list). No document properties, so the same input gives the
32
- * same bytes.
61
+ * A new Word document with these paragraphs and tables, on A4 with 2.5 cm margins, and a styles part that defines
62
+ * Title, Heading1 to Heading3, Normal and ListBullet (a bullet list). No document properties, so the same input gives
63
+ * the same bytes.
33
64
  */
34
65
  export declare const createDocx: (options: CreateDocxOptions) => Uint8Array;
@@ -6,6 +6,8 @@ import { escapeText } from "./xml.js";
6
6
  const MAX_ROW = 1_048_576;
7
7
  const MAX_COLUMN = 16_384;
8
8
  const MAX_CELL_TEXT = 32_767;
9
+ const MAX_FORMULA = 8_192;
10
+ const MAX_TABLE_COLUMNS = 63;
9
11
  const XML = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n';
10
12
  const CONTENT_TYPES = "http://schemas.openxmlformats.org/package/2006/content-types";
11
13
  const PACKAGE_REL = "http://schemas.openxmlformats.org/package/2006/relationships";
@@ -64,6 +66,14 @@ class SharedStrings {
64
66
  return `<sst xmlns="${SHEET_NS}" count="${this.count}" uniqueCount="${this.size}">${items.join("")}</sst>`;
65
67
  }
66
68
  }
69
+ const formulaXml = (address, formula, style) => {
70
+ const text = formula.startsWith("=") ? formula.slice(1) : formula;
71
+ if (!text.trim())
72
+ throw refuse(`${address}: a formula cannot be empty`, "office.invalid-value");
73
+ if (text.length > MAX_FORMULA)
74
+ throw refuse(`${address}: a formula holds at most 8,192 characters`, "office.invalid-value");
75
+ return `<c r="${address}"${style}><f>${escapeText(text)}</f></c>`;
76
+ };
67
77
  const cellXml = (address, value, style, strings) => {
68
78
  if (typeof value === "boolean")
69
79
  return `<c r="${address}"${style} t="b"><v>${value ? 1 : 0}</v></c>`;
@@ -76,7 +86,7 @@ const cellXml = (address, value, style, strings) => {
76
86
  throw refuse(`${address}: a cell holds at most 32,767 characters`, "office.invalid-value");
77
87
  return `<c r="${address}"${style} t="s"><v>${strings.index(value)}</v></c>`;
78
88
  };
79
- const worksheetXml = (sheet, strings, boldHeader) => {
89
+ const worksheetXml = (sheet, strings, boldHeader, formulas) => {
80
90
  if (sheet.rows.length > MAX_ROW)
81
91
  throw refuse(`sheet "${sheet.name}" has more than 1,048,576 rows`, "office.invalid-cell");
82
92
  let right = 0;
@@ -84,12 +94,20 @@ const worksheetXml = (sheet, strings, boldHeader) => {
84
94
  const rows = sheet.rows.flatMap((values, down) => {
85
95
  if (values.length > MAX_COLUMN)
86
96
  throw refuse(`row ${down + 1} of "${sheet.name}" has more than 16,384 cells`, "office.invalid-cell");
87
- const style = boldHeader && down === 0 ? ' s="1"' : "";
88
- const cells = values.flatMap((value, across) => {
97
+ const header = (boldHeader || sheet.header === true) && down === 0;
98
+ const cells = values.flatMap((cell, across) => {
99
+ const formatted = cell !== null && typeof cell === "object";
100
+ const value = formatted ? ("formula" in cell ? undefined : cell.value) : cell;
89
101
  if (value === null)
90
102
  return [];
91
103
  right = Math.max(right, across + 1);
92
- return [cellXml(`${columnName(across + 1)}${down + 1}`, value, style, strings)];
104
+ const address = `${columnName(across + 1)}${down + 1}`;
105
+ const style = header || (formatted && cell.bold === true) ? ' s="1"' : "";
106
+ if (formatted && "formula" in cell) {
107
+ formulas.count++;
108
+ return [formulaXml(address, cell.formula, style)];
109
+ }
110
+ return [cellXml(address, value, style, strings)];
93
111
  });
94
112
  if (!cells.length)
95
113
  return [];
@@ -113,16 +131,18 @@ const STYLES = `<styleSheet xmlns="${SHEET_NS}">` +
113
131
  "</styleSheet>";
114
132
  /**
115
133
  * A new workbook with these sheets and values: strings in a shared strings part (a string that starts with `=` stays
116
- * text), numbers and booleans typed. No document properties, so the same input gives the same bytes.
134
+ * text), numbers and booleans typed, `{formula}` a formula. No document properties, so the same input gives the same
135
+ * bytes.
117
136
  */
118
137
  export const createXlsx = (options) => {
119
138
  const { sheets, boldHeader = false } = options;
120
139
  checkSheetNames(sheets);
121
140
  const strings = new SharedStrings();
141
+ const formulas = { count: 0 };
122
142
  const parts = {};
123
143
  const types = { "xl/workbook.xml": "spreadsheetml.sheet.main+xml" };
124
144
  sheets.forEach((sheet, index) => {
125
- parts[`xl/worksheets/sheet${index + 1}.xml`] = worksheetXml(sheet, strings, boldHeader);
145
+ parts[`xl/worksheets/sheet${index + 1}.xml`] = worksheetXml(sheet, strings, boldHeader, formulas);
126
146
  types[`xl/worksheets/sheet${index + 1}.xml`] = "spreadsheetml.worksheet+xml";
127
147
  });
128
148
  types["xl/styles.xml"] = "spreadsheetml.styles+xml";
@@ -137,10 +157,12 @@ export const createXlsx = (options) => {
137
157
  const listed = sheets
138
158
  .map((sheet, index) => `<sheet name="${escapeAttribute(sheet.name)}" sheetId="${index + 1}" r:id="rId${index + 1}"/>`)
139
159
  .join("");
160
+ // No cached results are written, so Excel and LibreOffice must compute every formula as the file opens.
161
+ const calculation = formulas.count ? '<calcPr calcId="191029" fullCalcOnLoad="1"/>' : "";
140
162
  return packed({
141
163
  "[Content_Types].xml": contentTypes(types),
142
164
  "_rels/.rels": relationships([["officeDocument", "xl/workbook.xml"]]),
143
- "xl/workbook.xml": `<workbook xmlns="${SHEET_NS}" xmlns:r="${OFFICE_REL}"><sheets>${listed}</sheets></workbook>`,
165
+ "xl/workbook.xml": `<workbook xmlns="${SHEET_NS}" xmlns:r="${OFFICE_REL}"><sheets>${listed}</sheets>${calculation}</workbook>`,
144
166
  "xl/_rels/workbook.xml.rels": relationships(links),
145
167
  "xl/styles.xml": STYLES,
146
168
  ...(strings.size ? { "xl/sharedStrings.xml": strings.xml() } : {}),
@@ -173,29 +195,71 @@ const NUMBERING = `<w:numbering xmlns:w="${WORD_NS}"><w:abstractNum w:abstractNu
173
195
  '<w:multiLevelType w:val="singleLevel"/><w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="bullet"/>' +
174
196
  '<w:lvlText w:val="•"/><w:lvlJc w:val="left"/><w:pPr><w:ind w:left="720" w:hanging="360"/></w:pPr></w:lvl>' +
175
197
  '</w:abstractNum><w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num></w:numbering>';
176
- const paragraphXml = ({ text, style = "Normal" }) => {
177
- if (!NEW_PARAGRAPH_STYLES.includes(style))
178
- throw refuse(`${style} is not a style here; use ${NEW_PARAGRAPH_STYLES.join(", ")}`, "office.invalid-value");
179
- // The list's numbering is on the paragraph too: a reader that ignores a style's numbering still sees a bullet.
180
- const properties = style === "Normal"
181
- ? ""
182
- : `<w:pPr><w:pStyle w:val="${style}"/>${style === "ListBullet" ? '<w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr>' : ""}</w:pPr>`;
198
+ const runXml = ({ text, bold, italic }) => {
183
199
  const content = text
184
200
  .replace(/\r\n?/gu, "\n")
185
201
  .split(/(\n|\t)/u)
186
202
  .filter((piece) => piece !== "")
187
203
  .map((piece) => piece === "\n" ? "<w:br/>" : piece === "\t" ? "<w:tab/>" : `<w:t xml:space="preserve">${escapeText(piece)}</w:t>`)
188
204
  .join("");
189
- return `<w:p>${properties}${content ? `<w:r>${content}</w:r>` : ""}</w:p>`;
205
+ if (!content)
206
+ return "";
207
+ const properties = (bold ? "<w:b/><w:bCs/>" : "") + (italic ? "<w:i/><w:iCs/>" : "");
208
+ return `<w:r>${properties ? `<w:rPr>${properties}</w:rPr>` : ""}${content}</w:r>`;
209
+ };
210
+ const paragraphXml = (paragraph) => {
211
+ const { style = "Normal" } = paragraph;
212
+ if (!NEW_PARAGRAPH_STYLES.includes(style))
213
+ throw refuse(`${style} is not a style here; use ${NEW_PARAGRAPH_STYLES.join(", ")}`, "office.invalid-value");
214
+ // The list's numbering is on the paragraph too: a reader that ignores a style's numbering still sees a bullet.
215
+ const properties = style === "Normal"
216
+ ? ""
217
+ : `<w:pPr><w:pStyle w:val="${style}"/>${style === "ListBullet" ? '<w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr>' : ""}</w:pPr>`;
218
+ const runs = "runs" in paragraph ? paragraph.runs : [paragraph];
219
+ return `<w:p>${properties}${runs.map(runXml).join("")}</w:p>`;
220
+ };
221
+ // The text width of the A4 page between its margins, in twentieths of a point.
222
+ const TEXT_WIDTH = 11_906 - 2 * 1_417;
223
+ const BORDER = 'w:val="single" w:sz="4" w:space="0" w:color="auto"';
224
+ const tableXml = ({ table, header = false }) => {
225
+ const columns = table.reduce((widest, row) => Math.max(widest, row.length), 1);
226
+ if (columns > MAX_TABLE_COLUMNS)
227
+ throw refuse("a Word table has at most 63 columns", "office.invalid-value");
228
+ const width = Math.floor(TEXT_WIDTH / columns);
229
+ const borders = ["top", "left", "bottom", "right", "insideH", "insideV"].map((side) => `<w:${side} ${BORDER}/>`);
230
+ const rows = (table.length ? table : [[]]).map((cells, down) => {
231
+ const bold = header && down === 0;
232
+ const tcs = Array.from({ length: columns }, (_, across) => {
233
+ const text = cells[across] ?? "";
234
+ return `<w:tc><w:tcPr><w:tcW w:w="${width}" w:type="dxa"/></w:tcPr><w:p>${runXml({ text, bold })}</w:p></w:tc>`;
235
+ });
236
+ return `<w:tr>${bold ? "<w:trPr><w:tblHeader/></w:trPr>" : ""}${tcs.join("")}</w:tr>`;
237
+ });
238
+ return (`<w:tbl><w:tblPr><w:tblW w:w="${width * columns}" w:type="dxa"/><w:tblBorders>${borders.join("")}</w:tblBorders>` +
239
+ `</w:tblPr><w:tblGrid>${`<w:gridCol w:w="${width}"/>`.repeat(columns)}</w:tblGrid>` +
240
+ `${rows.join("")}</w:tbl>`);
241
+ };
242
+ // Word merges two tables that touch and needs a paragraph to end the body, so a table is never last or next to another.
243
+ const bodyXml = (blocks) => {
244
+ let previousTable = false;
245
+ const parts = blocks.flatMap((block) => {
246
+ const isTable = "table" in block;
247
+ const xml = isTable ? tableXml(block) : paragraphXml(block);
248
+ const between = isTable && previousTable ? ["<w:p/>"] : [];
249
+ previousTable = isTable;
250
+ return [...between, xml];
251
+ });
252
+ if (!parts.length || previousTable)
253
+ parts.push("<w:p/>");
254
+ return parts.join("");
190
255
  };
191
256
  /**
192
- * A new Word document with these paragraphs, on A4 with 2.5 cm margins, and a styles part that defines Title,
193
- * Heading1 to Heading3, Normal and ListBullet (a bullet list). No document properties, so the same input gives the
194
- * same bytes.
257
+ * A new Word document with these paragraphs and tables, on A4 with 2.5 cm margins, and a styles part that defines
258
+ * Title, Heading1 to Heading3, Normal and ListBullet (a bullet list). No document properties, so the same input gives
259
+ * the same bytes.
195
260
  */
196
261
  export const createDocx = (options) => {
197
- // The body must end with a paragraph before its section properties.
198
- const body = options.paragraphs.length ? options.paragraphs.map(paragraphXml).join("") : "<w:p/>";
262
+ const body = bodyXml(options.paragraphs);
199
263
  const section = '<w:sectPr><w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="1417" w:right="1417" w:bottom="1417" w:left="1417" ' +
200
264
  'w:header="708" w:footer="708" w:gutter="0"/></w:sectPr>';
201
265
  return packed({
@@ -1,3 +1,3 @@
1
- export { type CreateDocxOptions, type CreateXlsxOptions, createDocx, createXlsx, NEW_PARAGRAPH_STYLES, type NewParagraph, type NewParagraphStyle, type NewSheet, } from "./create.js";
1
+ export { type CreateDocxOptions, type CreateXlsxOptions, createDocx, createXlsx, NEW_PARAGRAPH_STYLES, type NewCell, type NewFormulaCell, type NewParagraph, type NewParagraphStyle, type NewRun, type NewSheet, type NewTable, type NewValueCell, } from "./create.js";
2
2
  export { type DocxEdit, type DocxParagraph, type EditDocxResult, editDocxParagraphs, readDocxParagraphs, } from "./docx.js";
3
3
  export { type CellType, type CellValue, type EditXlsxOptions, type EditXlsxResult, editXlsxCells, type ReadXlsxOptions, readXlsxCells, type XlsxCell, type XlsxEdit, type XlsxSheet, } from "./xlsx.js";
@@ -1,4 +1,7 @@
1
- /** A file a documents sync reads the text of: PDF, docx, xlsx, CSV, TSV, plain text and Markdown. */
1
+ /**
2
+ * A file a documents sync reads the text of: PDF, Word (doc, docx), RTF, OpenDocument (odt, ods, odp), xlsx, pptx,
3
+ * EPUB, HTML, CSV, TSV, plain text and Markdown. Images and scans are kept by name only.
4
+ */
2
5
  export declare const readableFile: ({ name, mime }: {
3
6
  name: string;
4
7
  mime: string;
@@ -3,15 +3,29 @@ import { engineHint, extractText, importEngine, MAX_TEXT_CHARS } from "../../att
3
3
  import { attachmentMaxBytes } from "../../attachments/limits.js";
4
4
  const READABLE = new Set([
5
5
  "application/pdf",
6
+ "application/msword",
6
7
  "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
7
8
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
9
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation",
10
+ "application/vnd.oasis.opendocument.text",
11
+ "application/vnd.oasis.opendocument.spreadsheet",
12
+ "application/vnd.oasis.opendocument.presentation",
13
+ "application/epub+zip",
14
+ "application/rtf",
15
+ "text/rtf",
16
+ "text/html",
17
+ "application/xhtml+xml",
8
18
  "text/csv",
9
19
  "text/tab-separated-values",
10
20
  "text/plain",
11
21
  "text/markdown",
12
22
  ]);
13
- /** A file a documents sync reads the text of: PDF, docx, xlsx, CSV, TSV, plain text and Markdown. */
14
- export const readableFile = ({ name, mime }) => READABLE.has(mime) || /\.(md|markdown|txt|pdf|docx|xlsx|csv|tsv)$/iu.test(name);
23
+ /**
24
+ * A file a documents sync reads the text of: PDF, Word (doc, docx), RTF, OpenDocument (odt, ods, odp), xlsx, pptx,
25
+ * EPUB, HTML, CSV, TSV, plain text and Markdown. Images and scans are kept by name only.
26
+ */
27
+ export const readableFile = ({ name, mime }) => READABLE.has(mime) ||
28
+ /\.(md|markdown|txt|pdf|doc|docx|rtf|odt|ods|odp|xlsx|pptx|epub|html?|xhtml|csv|tsv)$/iu.test(name);
15
29
  /**
16
30
  * The text of a downloaded file through cli-core's readers, or a `validation_error` that says why there is none, in
17
31
  * words a person acts on. `command` names the CLI in the hint for a missing reader.
@@ -35,6 +35,11 @@ export declare const documentIngestion: <M extends SourceFile>(store: Pick<Messa
35
35
  until: () => boolean;
36
36
  }) => Promise<number>;
37
37
  save: (principal: string, content: SourceContent<M>, hash: string) => Promise<string>;
38
+ /**
39
+ * Moves a synced document to the new id its source gave the file, as a replace through a temporary file does, so
40
+ * its tags, the notes about it and its links stay with it. False when the file was never synced.
41
+ */
42
+ rekey: (principal: string, from: string, to: string) => Promise<boolean>;
38
43
  remove: (principal: string, id: string, reason?: SourceRemoval) => Promise<void>;
39
44
  prune: (principal: string, before: string) => Promise<{
40
45
  versions: number;
@@ -1,4 +1,4 @@
1
- import { CliError } from "@wirecat/cli-base";
1
+ import { CliError, isCliError } from "@wirecat/cli-base";
2
2
  import { walkQuery } from "@wirecat/cli-base/query";
3
3
  export const documentIngestion = (store, options) => {
4
4
  const folder = async (principal, create) => {
@@ -101,6 +101,26 @@ export const documentIngestion = (store, options) => {
101
101
  await options.observed?.(principal, content.metadata, note.id);
102
102
  return note.ref;
103
103
  },
104
+ /**
105
+ * Moves a synced document to the new id its source gave the file, as a replace through a temporary file does, so
106
+ * its tags, the notes about it and its links stay with it. False when the file was never synced.
107
+ */
108
+ rekey: async (principal, from, to) => {
109
+ const selected = await folder(principal, false);
110
+ if (!selected)
111
+ return false;
112
+ try {
113
+ const [was, now] = [options.externalId(from), options.externalId(to)];
114
+ const note = await store.notes.renameFileNote(selected.id, was, now, { fold: true });
115
+ await stale(note.ref);
116
+ return true;
117
+ }
118
+ catch (error) {
119
+ if (isCliError(error) && error.code === "not_found")
120
+ return false;
121
+ throw error;
122
+ }
123
+ },
104
124
  remove: async (principal, id, reason) => {
105
125
  const selected = await folder(principal, false);
106
126
  if (selected) {
@@ -228,114 +228,156 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
228
228
  let spent = 0;
229
229
  let listed = 0;
230
230
  let stopped = null;
231
- try {
232
- for (let step = walk.stack.at(-1); step; step = walk.stack.at(-1)) {
233
- if (step.ancestry.includes(step.id))
234
- throw new CliError("invalid_response", "folder traversal contains a cycle");
235
- if (visited.has(step.id)) {
236
- walk.stack.pop();
237
- continue;
238
- }
239
- // One listing at least per call, so a folder with more children than the bound still moves on.
240
- // The run's own signal too: a cooperative sync is not cut from outside, and a CLI may pass no budget.
241
- // The time budget keeps a margin of 5 s or more, so a short run would never list a folder: its first request
242
- // goes ahead while one still fits before the deadline itself.
243
- const taken = options.signal?.aborted
244
- ? "cancelled"
245
- : listed > 0 && spent >= maxEntries
246
- ? "entries"
247
- : budget?.take();
248
- stopped = taken === "deadline" && budget?.first?.() ? null : (taken ?? null);
249
- if (stopped)
250
- break;
251
- if (!step.folder) {
252
- const known = state.folders[step.id];
253
- let root;
254
- try {
255
- root = await source.metadata(step.id, known);
256
- }
257
- catch (error) {
258
- // Without a feed, a folder the last pass held and the provider no longer finds is skipped as unavailable,
259
- // as a round of changes does, so a moved or deleted root does not fail every sync. A source with a feed
260
- // walks in full only on a rescan, where a root it cannot read still fails and keeps what it holds.
261
- if (feed || !known || errorOf(error).code !== "not_found")
262
- throw error;
263
- walk.stack.pop();
264
- visited.add(step.id);
265
- folders[step.id] = { ...known, trashed: true };
266
- spent++;
267
- listed++;
268
- continue;
269
- }
270
- if (!isFolder(root) || root.trashed)
271
- throw new CliError("validation_error", "configured root is not an accessible folder");
272
- container(root);
273
- // Kept on the step, so a call stopped before the listing does not read the root again.
274
- step.folder = root;
275
- stopped = charge();
276
- if (stopped)
277
- break;
278
- }
279
- const folder = step.folder;
280
- let children;
281
- let more;
231
+ // A value that is not a whole number would leave the batch empty and end the walk as if it found nothing.
232
+ const asked = source.parallelListings;
233
+ const width = Number.isInteger(asked) && asked > 1 ? Math.min(asked, 8) : 1;
234
+ // A root read in a listing that then fails is still filed, as the walk saves it on the step.
235
+ const rootsRead = new Map();
236
+ const list = async (step) => {
237
+ if (!step.folder) {
238
+ let root;
282
239
  try {
283
- if (source.childrenPage)
284
- ({ files: children, cursor: more } = await source.childrenPage(folder.id, step.listing, folder));
285
- else
286
- children = await source.children(folder.id, folder);
240
+ root = await source.metadata(step.id, state.folders[step.id]);
287
241
  }
288
242
  catch (error) {
289
- if (errorOf(error).code !== "not_found")
243
+ // Without a feed, a folder the last pass held and the provider no longer finds is skipped as unavailable,
244
+ // as a round of changes does, so a moved or deleted root does not fail every sync. A source with a feed
245
+ // walks in full only on a rescan, where a root it cannot read still fails and keeps what it holds.
246
+ if (feed || !state.folders[step.id] || errorOf(error).code !== "not_found")
290
247
  throw error;
291
- // A later page's 404 can be a cursor the provider no longer knows: the folder is listed again from its first
292
- // page, which tells a gone folder from a stale cursor, and the files already kept are only kept again.
293
- if (step.listing !== undefined) {
294
- delete step.listing;
295
- spent++;
296
- listed++;
297
- continue;
298
- }
299
- // Deleted or unshared since the walk saved it: gone, with what is below it, instead of failing every sync.
300
- // A listing's 404 alone can be passing, so the folder is read again and is gone only when that read is a
301
- // 404 too or finds it trashed; on any doubt the call fails and the next sync lists it again.
302
- if (!(await vanished(folder.id, folder)))
303
- throw error;
304
- walk.stack.pop();
305
- visited.add(folder.id);
306
- folders[folder.id] = { ...folder, trashed: true };
307
- drop(folder.id, "unavailable");
308
- spent++;
309
- listed++;
310
- continue;
248
+ return { kind: "root-gone" };
311
249
  }
312
- spent += 1 + children.length;
313
- listed++;
314
- walk.discovered += children.length;
315
- folders[folder.id] = folder;
316
- const nested = [];
317
- for (const file of children)
318
- if (isFolder(file)) {
319
- container(file);
320
- if (excluded(file))
321
- continue;
322
- if (walked(file.id))
323
- folders[file.id] = file;
324
- else
325
- nested.push({ id: file.id, ancestry: [...step.ancestry, folder.id], folder: file });
326
- }
327
- else if (file.trashed)
328
- trash(file);
250
+ if (!isFolder(root) || root.trashed)
251
+ throw new CliError("validation_error", "configured root is not an accessible folder");
252
+ rootsRead.set(step, root);
253
+ // Kept on the step, so a call stopped before the listing does not read the root again.
254
+ step.folder = root;
255
+ const after = charge();
256
+ if (after)
257
+ return { kind: "root", stopped: after };
258
+ }
259
+ const folder = step.folder;
260
+ try {
261
+ if (!source.childrenPage)
262
+ return { kind: "listed", children: await source.children(folder.id, folder) };
263
+ const page = await source.childrenPage(folder.id, step.listing, folder);
264
+ return { kind: "listed", children: page.files, ...(page.cursor ? { more: page.cursor } : {}) };
265
+ }
266
+ catch (error) {
267
+ if (errorOf(error).code !== "not_found")
268
+ throw error;
269
+ // A later page's 404 can be a cursor the provider no longer knows: the folder is listed again from its first
270
+ // page, which tells a gone folder from a stale cursor, and the files already kept are only kept again.
271
+ if (step.listing !== undefined)
272
+ return { kind: "relist" };
273
+ // Deleted or unshared since the walk saved it: gone, with what is below it, instead of failing every sync.
274
+ // A listing's 404 alone can be passing, so the folder is read again and is gone only when that read is a
275
+ // 404 too or finds it trashed; on any doubt the call fails and the next sync lists it again.
276
+ if (!(await vanished(folder.id, folder)))
277
+ throw error;
278
+ return { kind: "gone" };
279
+ }
280
+ };
281
+ // In the step's own place, so the stack keeps the order a walk one folder at a time has.
282
+ const place = (step, entries) => current.stack.splice(current.stack.indexOf(step), 1, ...entries);
283
+ const apply = (step, result) => {
284
+ if (result.kind === "root") {
285
+ stopped ??= result.stopped;
286
+ return;
287
+ }
288
+ spent++;
289
+ listed++;
290
+ if (result.kind === "relist") {
291
+ delete step.listing;
292
+ return;
293
+ }
294
+ if (result.kind === "root-gone") {
295
+ place(step, []);
296
+ visited.add(step.id);
297
+ folders[step.id] = { ...state.folders[step.id], trashed: true };
298
+ return;
299
+ }
300
+ const folder = step.folder;
301
+ if (result.kind === "gone") {
302
+ place(step, []);
303
+ visited.add(folder.id);
304
+ folders[folder.id] = { ...folder, trashed: true };
305
+ drop(folder.id, "unavailable");
306
+ return;
307
+ }
308
+ const { children, more } = result;
309
+ spent += children.length;
310
+ current.discovered += children.length;
311
+ folders[folder.id] = folder;
312
+ const nested = [];
313
+ for (const file of children)
314
+ if (isFolder(file)) {
315
+ container(file);
316
+ if (excluded(file))
317
+ continue;
318
+ if (walked(file.id))
319
+ folders[file.id] = file;
329
320
  else
330
- keep(file);
331
- walk.stack.pop();
332
- for (const entry of nested.reverse())
333
- walk.stack.push(entry);
334
- // A folder with more pages goes back on top with its cursor, above its child folders.
335
- if (more)
336
- walk.stack.push({ ...step, folder, listing: more });
321
+ nested.push({ id: file.id, ancestry: [...step.ancestry, folder.id], folder: file });
322
+ }
323
+ else if (file.trashed)
324
+ trash(file);
337
325
  else
338
- visited.add(folder.id);
326
+ keep(file);
327
+ // A folder with more pages goes back on top with its cursor, above its child folders.
328
+ place(step, [...nested.reverse(), ...(more ? [{ ...step, folder, listing: more }] : [])]);
329
+ if (!more)
330
+ visited.add(folder.id);
331
+ };
332
+ const done = (step) => {
333
+ if (step.ancestry.includes(step.id))
334
+ throw new CliError("invalid_response", "folder traversal contains a cycle");
335
+ return visited.has(step.id);
336
+ };
337
+ try {
338
+ for (;;) {
339
+ for (let top = current.stack.at(-1); top && done(top); top = current.stack.at(-1))
340
+ current.stack.pop();
341
+ // The folders at the top of the stack, listed together on a source that allows it; each takes its request
342
+ // before it starts, so the budget and the deadline bound the batch as they bound one listing.
343
+ const batch = [];
344
+ for (let at = current.stack.length - 1; at >= 0 && batch.length < width; at--) {
345
+ const step = current.stack[at];
346
+ if (done(step) || batch.some((one) => one.id === step.id))
347
+ continue;
348
+ // One listing at least per call, so a folder with more children than the bound still moves on.
349
+ // The run's own signal too: a cooperative sync is not cut from outside, and a CLI may pass no budget.
350
+ // The time budget keeps a margin of 5 s or more, so a short run would never list a folder: its first
351
+ // request goes ahead while one still fits before the deadline itself.
352
+ const taken = options.signal?.aborted
353
+ ? "cancelled"
354
+ : (listed > 0 || batch.length > 0) && spent >= maxEntries
355
+ ? "entries"
356
+ : budget?.take();
357
+ stopped = taken === "deadline" && budget?.first?.() ? null : (taken ?? null);
358
+ if (stopped)
359
+ break;
360
+ batch.push(step);
361
+ }
362
+ if (!batch.length)
363
+ break;
364
+ const results = await Promise.allSettled(batch.map(list));
365
+ let failure;
366
+ batch.forEach((step, at) => {
367
+ const root = rootsRead.get(step);
368
+ if (root)
369
+ container(root);
370
+ rootsRead.delete(step);
371
+ const result = results[at];
372
+ if (result.status === "fulfilled")
373
+ apply(step, result.value);
374
+ else
375
+ failure ??= { reason: result.reason };
376
+ });
377
+ if (failure)
378
+ throw failure.reason;
379
+ if (stopped)
380
+ break;
339
381
  if (now() - savedAt > SAVE_EVERY_MS)
340
382
  record();
341
383
  }
@@ -24,6 +24,12 @@ export interface GuardedFileWriteResult {
24
24
  sha256: string;
25
25
  };
26
26
  }
27
+ /** The reason of a conflict a target raised for itself, which callers pass on as it is; undefined for the usual one. */
28
+ export declare const ownConflict: (error: {
29
+ details?: {
30
+ reason?: unknown;
31
+ };
32
+ }) => string | undefined;
27
33
  export declare const remoteChanged: (path: string, why: string, reread: string) => CliError;
28
34
  /**
29
35
  * Writes a file only over the content the caller read. Few providers offer a conditional upload, so the current
@@ -1,4 +1,9 @@
1
1
  import { CliError, isCliError } from "@wirecat/cli-base";
2
+ /** The reason of a conflict a target raised for itself, which callers pass on as it is; undefined for the usual one. */
3
+ export const ownConflict = (error) => {
4
+ const reason = error.details?.reason;
5
+ return typeof reason === "string" && reason !== "mirror.remote-changed" ? reason : undefined;
6
+ };
2
7
  export const remoteChanged = (path, why, reread) => new CliError("conflict", `${path} ${why}; nothing was written. Read it again: ${reread}`, {
3
8
  reason: "mirror.remote-changed",
4
9
  });
@@ -23,7 +28,8 @@ export const guardedFileWrite = async (write) => {
23
28
  file = await target.upload(path, from, kept === undefined ? { absent: true } : { sha256: kept }, signal);
24
29
  }
25
30
  catch (error) {
26
- if (isCliError(error) && error.code === "conflict")
31
+ // A target's conflict with its own reason says what it did, which "nothing was written" would hide.
32
+ if (isCliError(error) && error.code === "conflict" && ownConflict(error) === undefined)
27
33
  throw remoteChanged(path, kept === undefined ? "appeared since it was read" : "changed since it was read", reread);
28
34
  throw error;
29
35
  }
@@ -5,6 +5,7 @@ import { CliError } from "@wirecat/cli-base";
5
5
  import { eachMirror, heldCheck } from "../documents/mirrors.js";
6
6
  import { assertNoLink, localTemp, replaceLocal, safePath, skippedName, } from "../documents/push.js";
7
7
  import { excludedBy } from "./exclusions.js";
8
+ import { ownConflict } from "./guarded-write.js";
8
9
  import { listRemote } from "./listing.js";
9
10
  import { ancestors, copyName, freeSpace, gigabytes, linkFree, MAX_FILES, renameLocal, scan, shortOfSpace, spareFor, trashLocal, under, whole, } from "./local-files.js";
10
11
  import { mergeable, mergeText } from "./text-merge.js";
@@ -747,9 +748,7 @@ export const syncFileMirror = async (options) => {
747
748
  break;
748
749
  }
749
750
  if (failure.code === "conflict")
750
- conflict(step, failure.details?.reason === "upload.mismatch"
751
- ? failure.message
752
- : `the ${options.remote} file changed during the sync`);
751
+ conflict(step, ownConflict(failure) !== undefined ? failure.message : `the ${options.remote} file changed during the sync`);
753
752
  else
754
753
  result.errors.push({ path: step.path, code: failure.code, message: failure.message });
755
754
  // Not retried: the next listing shows whether it landed, and adopts it when it did.
@@ -14,12 +14,12 @@ export declare const metadataService: (deps: ServiceDeps) => {
14
14
  dryRun?: boolean;
15
15
  }) => Promise<{
16
16
  items: ({
17
- error?: undefined;
18
17
  chatId: string;
19
18
  tags: import("../domain/channel-tags.js").ChannelTagMatch[];
20
19
  algorithm: string;
21
20
  fetchedAt: string | null;
22
21
  source: string;
22
+ error?: undefined;
23
23
  } | {
24
24
  tags?: undefined;
25
25
  algorithm?: undefined;
@@ -0,0 +1,8 @@
1
+ import type { CacheDatabase } from "../driver.js";
2
+ /**
3
+ * Readies the document at `from` to move to `target`, the path of the id its source gave the file after a replace, so
4
+ * it keeps its id and with it the tags, the notes about it and its links. A sync that ran between the replace and this
5
+ * call took the document out at `from` and filed the file anew at `target`: the new text joins the old document, the
6
+ * new one goes, and the old one is live again. False when nothing was ever at `from`.
7
+ */
8
+ export declare const foldRekeyed: (database: CacheDatabase, folder: number, from: string, target: string, at: number) => boolean;
@@ -0,0 +1,47 @@
1
+ import { keepRevision, logDocumentChange } from "./document-history.js";
2
+ import { deleteDocumentRow } from "./evidence-signature.js";
3
+ const CONTENT = ["title", "body", "front_matter", "content_hash", "metadata", "language"];
4
+ const documentAt = (database, folder, path) => {
5
+ const place = database
6
+ .prepare("SELECT document_id FROM files WHERE account_id = ? AND external_id = ? AND kind <> 'folder'")
7
+ .get(folder, path);
8
+ return place?.document_id != null
9
+ ? database.prepare("SELECT * FROM documents WHERE id = ?").get(Number(place.document_id))
10
+ : database.prepare("SELECT * FROM documents WHERE account_id = ? AND external_id = ?").get(folder, path);
11
+ };
12
+ /**
13
+ * Readies the document at `from` to move to `target`, the path of the id its source gave the file after a replace, so
14
+ * it keeps its id and with it the tags, the notes about it and its links. A sync that ran between the replace and this
15
+ * call took the document out at `from` and filed the file anew at `target`: the new text joins the old document, the
16
+ * new one goes, and the old one is live again. False when nothing was ever at `from`.
17
+ */
18
+ export const foldRekeyed = (database, folder, from, target, at) => {
19
+ const old = documentAt(database, folder, from);
20
+ if (!old)
21
+ return false;
22
+ const id = Number(old.id);
23
+ const filed = documentAt(database, folder, target);
24
+ if (filed && Number(filed.id) !== id) {
25
+ // A catalog entry not read yet has no text; the old document's stays until the next read.
26
+ if (filed.body != null) {
27
+ if ((old.body ?? "") !== "" && old.deleted_at == null)
28
+ keepRevision(database, old, at);
29
+ database
30
+ .prepare(`UPDATE documents SET ${CONTENT.map((column) => `${column} = ?`).join(", ")}, revision = revision + 1, ` +
31
+ "updated_at = ? WHERE id = ?")
32
+ .run(...CONTENT.map((column) => filed[column] ?? null), at, id);
33
+ }
34
+ deleteDocumentRow(database, Number(filed.id), at);
35
+ database
36
+ .prepare("DELETE FROM files WHERE account_id = ? AND external_id = ? AND kind <> 'folder'")
37
+ .run(folder, target);
38
+ }
39
+ if (old.deleted_at != null) {
40
+ database.prepare("UPDATE documents SET deleted_at = NULL, removal = NULL WHERE id = ?").run(id);
41
+ database
42
+ .prepare("UPDATE files SET deleted_at = NULL WHERE account_id = ? AND external_id = ? AND kind <> 'folder'")
43
+ .run(folder, from);
44
+ logDocumentChange(database, id, "restored", at);
45
+ }
46
+ return true;
47
+ };
@@ -137,8 +137,13 @@ export interface NotesStore extends NoteSearch, ImportedDocuments, AddedSources,
137
137
  note: Note;
138
138
  changed: boolean;
139
139
  }>;
140
- /** Moves a file note to a new path in its folder, keeping its id, links and tags; a gone note at `to` is dropped. */
141
- renameFileNote(folderId: string, from: string, to: string): Promise<Note>;
140
+ /**
141
+ * Moves a file note to a new path in its folder, keeping its id, links and tags; a gone note at `to` is dropped.
142
+ * `fold` is for a source that gave the file a new id: see `foldRekeyed`.
143
+ */
144
+ renameFileNote(folderId: string, from: string, to: string, options?: {
145
+ fold?: boolean;
146
+ }): Promise<Note>;
142
147
  /**
143
148
  * Sets the time the source dates each note at these paths (ISO 8601), the note's `modifiedAt`, without counting
144
149
  * as an edit: text, revision and `updatedAt` stay. Answers how many notes it changed.
@@ -13,6 +13,7 @@ import { documentHistoryOver, keepRevision, logDocumentChange, removeDocument }
13
13
  import { encodeDocumentMetadata, languageOf } from "./document-metadata.js";
14
14
  import { deleteDocumentRow, forgetEvidenceToRow } from "./evidence-signature.js";
15
15
  import { fileNoteRow } from "./file-note.js";
16
+ import { foldRekeyed } from "./file-note-rekey.js";
16
17
  import { PREFERRED_FILE, syncFile } from "./files.js";
17
18
  import { importedDocumentWhere } from "./imported-documents.js";
18
19
  import { LINK_KINDS, LINK_ORIGINS, linkKind, RELATION_KINDS } from "./link-kinds.js";
@@ -456,10 +457,12 @@ export const notesStoreOver = (context) => {
456
457
  followPreferred(id, at);
457
458
  return { note: noteAt(id, folder, path), changed: !same };
458
459
  }),
459
- renameFileNote: async (folderId, from, to) => write(database, () => {
460
+ renameFileNote: async (folderId, from, to, options) => write(database, () => {
460
461
  const folder = Number(folderRow(folderId, true).id);
461
462
  const target = textOf(to, "a note's path", 4096);
462
463
  const at = now();
464
+ if (options?.fold)
465
+ foldRekeyed(database, folder, from, target, at);
463
466
  const place = fileAt(folder, from, true);
464
467
  const legacy = database
465
468
  .prepare("SELECT id FROM documents WHERE account_id = ? AND external_id = ? AND deleted_at IS NULL")
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.738.0",
3
+ "version": "0.739.0",
4
4
  "description": "The messenger-neutral half of a messaging CLI: domain model, message locators, rendering, name resolution, the SQLite seam, the command skeleton and shared read commands, the send guard, run records and the message store",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Viacheslav Ptsarev",