@wirecat/cli-core 0.735.0 → 0.736.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 (59) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/dist/background/daily-archive-timer.d.ts +1 -1
  3. package/dist/background/report/messages.d.ts +4 -0
  4. package/dist/background/report/messages.js +2 -0
  5. package/dist/background/report/templates/schedule-failed.email.en.liquid +2 -1
  6. package/dist/background/report/templates/schedule-failed.email.ru.liquid +2 -1
  7. package/dist/background/report/templates/schedule-failed.sample.json +2 -1
  8. package/dist/background/report/templates/schedule-failed.telegram.en.liquid +2 -1
  9. package/dist/background/report/templates/schedule-failed.telegram.ru.liquid +2 -1
  10. package/dist/background/report/templates/schedule-failed.text.en.liquid +2 -1
  11. package/dist/background/report/templates/schedule-failed.text.ru.liquid +2 -1
  12. package/dist/background/schedules.js +11 -7
  13. package/dist/cli/documents/file-edit.d.ts +4 -4
  14. package/dist/cli/documents/file-edit.js +69 -5
  15. package/dist/cli/enrichment-consents-command.js +2 -1
  16. package/dist/cli/messenger/catch-up-answers.js +1 -0
  17. package/dist/cli/messenger/download-command.js +3 -0
  18. package/dist/cli/messenger/inbox.js +4 -1
  19. package/dist/cli/messenger/review.js +4 -1
  20. package/dist/cli/messenger/search-answers.js +1 -0
  21. package/dist/cli/schedule/schedule-command.js +10 -1
  22. package/dist/cli/search-harder-consents-command.js +2 -1
  23. package/dist/cli/templates-command.js +7 -6
  24. package/dist/crm/cli/records.js +16 -1
  25. package/dist/domain/models.d.ts +4 -0
  26. package/dist/domain/providers.d.ts +7 -0
  27. package/dist/domain/providers.js +15 -2
  28. package/dist/entities/hit.d.ts +2 -0
  29. package/dist/entities/hit.js +2 -0
  30. package/dist/entities/index.d.ts +1 -0
  31. package/dist/errors/reasons.js +9 -2
  32. package/dist/office/create.d.ts +34 -0
  33. package/dist/office/create.js +216 -0
  34. package/dist/office/index.d.ts +1 -0
  35. package/dist/office/index.js +1 -0
  36. package/dist/office/package.d.ts +1 -0
  37. package/dist/office/package.js +1 -1
  38. package/dist/ports/messenger.d.ts +5 -2
  39. package/dist/search/word-match.d.ts +16 -0
  40. package/dist/search/word-match.js +28 -0
  41. package/dist/sends/upload.d.ts +3 -0
  42. package/dist/sends/upload.js +2 -2
  43. package/dist/services/documents/ingestion.js +4 -2
  44. package/dist/services/file-download.js +4 -2
  45. package/dist/services/inbox.js +5 -2
  46. package/dist/services/metadata.d.ts +1 -1
  47. package/dist/services/search-all.d.ts +2 -0
  48. package/dist/services/search-all.js +47 -17
  49. package/dist/store/sqlite/crm-rows.d.ts +4 -0
  50. package/dist/store/sqlite/crm-rows.js +30 -0
  51. package/dist/store/sqlite/crm.d.ts +2 -0
  52. package/dist/store/sqlite/crm.js +3 -10
  53. package/dist/store/sqlite/deals.js +1 -24
  54. package/dist/store/sqlite/tracker-chunks.d.ts +24 -8
  55. package/dist/store/sqlite/tracker-chunks.js +137 -38
  56. package/dist/store/sqlite/tracker.d.ts +5 -0
  57. package/dist/store/sqlite/tracker.js +118 -17
  58. package/dist/tracker/cli/index.js +1 -1
  59. package/package.json +1 -1
@@ -500,6 +500,8 @@ export interface Inbox {
500
500
  skipped: Pick<Chat, "id" | "title" | "lastMessageAt">[];
501
501
  /** The messenger could not list every chat, so one it left out may have more. */
502
502
  partial: boolean;
503
+ /** What the messenger said it did not look at and why, such as chats it cannot count. */
504
+ left?: string[];
503
505
  /** Muted or archived chats with something waiting, left out because nothing in them is for the owner. */
504
506
  quiet: number;
505
507
  /** `new` only: each chat read, and the time its next check starts from. */
@@ -523,6 +525,8 @@ export interface Review {
523
525
  chats: ReviewChat[];
524
526
  skipped: Pick<Chat, "id" | "title" | "lastMessageAt">[];
525
527
  partial: boolean;
528
+ /** What the messenger said it did not look at and why. */
529
+ left?: string[];
526
530
  /** Muted or archived chats that changed, left out because nothing in them is for the owner. */
527
531
  quiet: number;
528
532
  /** `--unanswered`: only questions still open after this many hours are in `chats`. */
@@ -22,6 +22,11 @@ export interface ProviderEntry {
22
22
  command?: string;
23
23
  /** The read command, after `<command> <profile>`, that opens a ref of each kind: `{ chat: "messages list" }`. */
24
24
  opens?: Partial<Record<RefKindName, string>>;
25
+ /**
26
+ * A tracker whose item ids name one item across every account of the provider, as Linear's do: two sign-ins'
27
+ * copies of an id are one item, and `search all` shows it once.
28
+ */
29
+ globalItemIds?: boolean;
25
30
  }
26
31
  /** What a CRM CLI's entry gives as `opens`: the read commands `addCrmCommands` mounts. */
27
32
  export declare const CRM_OPENS: {
@@ -101,6 +106,8 @@ export declare const kindsIn: (provider: Provider) => readonly Kind[];
101
106
  * as the first entry of its name, and never dropped once given. Answers the flag to store.
102
107
  */
103
108
  export declare const importedOf: (entry: ProviderEntry, held: ProviderEntry | undefined) => boolean;
109
+ /** Whether a tracker's item ids name one item across all its accounts, so their copies are one item. */
110
+ export declare const hasGlobalItemIds: (provider: Provider) => boolean;
104
111
  /** Whether a provider's accounts hold only what imports wrote: the one place a records import writes messages and events. */
105
112
  export declare const isImportedProvider: (provider: Provider) => boolean;
106
113
  /**
@@ -24,7 +24,14 @@ export const PROVIDERS = [
24
24
  { name: "google-drive", kind: "documents", aliases: [] },
25
25
  // Seeded: linear-cli registers no entry, and without one its accounts would count as a messenger's. One sign-in holds
26
26
  // the issues and the documents, so the account is a tracker's and a documents account at once.
27
- { name: "linear", kind: "tracker", kinds: ["tracker", "documents"], aliases: [], command: "linear" },
27
+ {
28
+ name: "linear",
29
+ kind: "tracker",
30
+ kinds: ["tracker", "documents"],
31
+ aliases: [],
32
+ command: "linear",
33
+ globalItemIds: true,
34
+ },
28
35
  // Its meetings come from the notes Telemost mails (`keeper@telemost.yandex.ru`), read by a mail rule.
29
36
  { name: "telemost", kind: "meetings", aliases: [] },
30
37
  // A phone export's records: its SMS and its calls in the one account the import names.
@@ -109,7 +116,7 @@ const opensOf = (value, named) => {
109
116
  export const providerEntryOf = (value) => {
110
117
  if (typeof value !== "object" || value === null || Array.isArray(value))
111
118
  return invalid("a provider entry is an object");
112
- const { name, kind, kinds, aliases = [], command, opens, imported } = value;
119
+ const { name, kind, kinds, aliases = [], command, opens, imported, globalItemIds } = value;
113
120
  const named = wordOf(name, "a provider's name");
114
121
  const isKindWord = (one) => typeof one === "string" && KINDS.includes(one);
115
122
  const given = kinds === undefined ? [kind] : Array.isArray(kinds) && kinds.length > 0 ? kinds : [undefined];
@@ -123,6 +130,8 @@ export const providerEntryOf = (value) => {
123
130
  invalid(`provider ${named}'s aliases are a list`);
124
131
  if (imported !== undefined && typeof imported !== "boolean")
125
132
  invalid(`provider ${named}'s imported is true or false`);
133
+ if (globalItemIds !== undefined && typeof globalItemIds !== "boolean")
134
+ invalid(`provider ${named}'s globalItemIds is true or false`);
126
135
  return {
127
136
  name: named,
128
137
  kind: list[0],
@@ -131,6 +140,7 @@ export const providerEntryOf = (value) => {
131
140
  aliases: [...new Set(aliases.map((alias) => wordOf(alias, `an alias of ${named}`)))],
132
141
  ...(command === undefined ? {} : { command: wordOf(command, `the command of ${named}`) }),
133
142
  ...(opens === undefined ? {} : { opens: opensOf(opens, named) }),
143
+ ...(globalItemIds === true ? { globalItemIds: true } : {}),
134
144
  };
135
145
  };
136
146
  export const kindsOfEntry = (entry) => entry.kinds ?? [entry.kind];
@@ -156,6 +166,7 @@ const joined = (known, entry) => {
156
166
  aliases: [...new Set([...same.aliases, ...entry.aliases])],
157
167
  ...(entry.command ? { command: entry.command } : {}),
158
168
  ...(entry.opens ? { opens: { ...same.opens, ...entry.opens } } : {}),
169
+ ...(entry.globalItemIds ? { globalItemIds: true } : {}),
159
170
  }
160
171
  : entry;
161
172
  const others = known.filter((one) => one !== same);
@@ -236,6 +247,8 @@ export const importedOf = (entry, held) => {
236
247
  invalid(`provider ${entry.name} was registered without imported: an entry cannot make it import-only later`);
237
248
  return held.imported === true;
238
249
  };
250
+ /** Whether a tracker's item ids name one item across all its accounts, so their copies are one item. */
251
+ export const hasGlobalItemIds = (provider) => registry.find(({ name }) => name === provider)?.globalItemIds === true;
239
252
  /** Whether a provider's accounts hold only what imports wrote: the one place a records import writes messages and events. */
240
253
  export const isImportedProvider = (provider) => registry.find(({ name }) => name === provider)?.imported === true;
241
254
  /**
@@ -11,6 +11,8 @@ export declare const hit: v.StrictObjectSchema<{
11
11
  readonly url: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
12
12
  /** The account it was found in; a note's folder id, or `internal` for a note written in memo. */
13
13
  readonly account: v.StringSchema<undefined>;
14
+ /** A tracker hit that more than one sign-in holds: every account it was found in, `account` first. */
15
+ readonly accounts: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
14
16
  /** The chat, the mail thread's subject, the note's, the event's or the meeting's title. */
15
17
  readonly title: v.NullableSchema<v.StringSchema<undefined>, undefined>;
16
18
  /** Null for a meeting whose start is unknown. */
@@ -28,6 +28,8 @@ export const hit = v.strictObject({
28
28
  url: v.optional(text),
29
29
  /** The account it was found in; a note's folder id, or `internal` for a note written in memo. */
30
30
  account: text,
31
+ /** A tracker hit that more than one sign-in holds: every account it was found in, `account` first. */
32
+ accounts: v.optional(v.array(text)),
31
33
  /** The chat, the mail thread's subject, the note's, the event's or the meeting's title. */
32
34
  title: v.nullable(text),
33
35
  /** Null for a meeting whose start is unknown. */
@@ -4331,6 +4331,7 @@ export declare const ENTITIES: {
4331
4331
  readonly provider: v.StringSchema<undefined>;
4332
4332
  readonly url: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
4333
4333
  readonly account: v.StringSchema<undefined>;
4334
+ readonly accounts: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
4334
4335
  readonly title: v.NullableSchema<v.StringSchema<undefined>, undefined>;
4335
4336
  readonly timestamp: v.NullableSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.IsoTimestampAction<string, "an ISO 8601 time in UTC">, v.EndsWithAction<string, "Z", "an ISO 8601 time in UTC, ending in `Z`">]>, undefined>;
4336
4337
  readonly excerpt: v.StringSchema<undefined>;
@@ -123,11 +123,11 @@ const SQL = [
123
123
  ["db.timeout", "timeout", "the database server did not answer in time"],
124
124
  ["db.failed", "provider_error", "the database server failed the query"],
125
125
  ];
126
- /** In-place Office edits (`./office`, `files sheets|documents update`); the names are documented in office.md. */
126
+ /** Office files edited and created (`./office`, `files sheets|documents`); the names are documented in office.md. */
127
127
  const OFFICE = [
128
128
  ["office.wrong-format", "the file is not the Office format the command edits, or its parts cannot be read"],
129
129
  ["office.invalid-cell", "a cell is not an address like B7"],
130
- ["office.invalid-value", "a cell value cannot be written: a number must be finite"],
130
+ ["office.invalid-value", "a value cannot be written: an infinite number, a cell text too long, an unknown style"],
131
131
  ["office.no-sheet", "the workbook has no such sheet, or several when none is named"],
132
132
  ["office.duplicate-edit", "the same cell or paragraph is changed twice in one call"],
133
133
  ["office.formula-cell", "the cell holds a formula; --replace writes the value over it"],
@@ -143,8 +143,10 @@ const OFFICE = [
143
143
  ["office.section-break", "the paragraph ends a section; deleting it would merge two sections"],
144
144
  ["office.bookmark", "the paragraph holds a bookmark a cross-reference may point at"],
145
145
  ["office.last-paragraph", "the delete would leave the document or a table cell without a paragraph"],
146
+ ["office.invalid-sheet-name", "a new sheet's name is empty, too long, repeated or holds a character Excel refuses"],
146
147
  ].map(([reason, message]) => validation(reason, message));
147
148
  const OTHERS = [
149
+ ["office.file-exists", "conflict", "a file is there already; create never replaces one, update changes it"],
148
150
  validation("doctor.report-exists", "the report's file exists; a problem report never overwrites a file"),
149
151
  validation("usage.unknown-command", "no command by this name; the CLI's help lists them"),
150
152
  validation("usage.unknown-option", "the command takes no option by this name; its help lists them"),
@@ -226,6 +228,11 @@ const OTHERS = [
226
228
  "nothing holds this agent to the CLI's commands, so no schedule starts it",
227
229
  ],
228
230
  ["read-only.output-outside", "permission_error", "a read-only process writes files only inside its working folder"],
231
+ [
232
+ "schedule.outside-folder",
233
+ "permission_error",
234
+ "schedule exec runs only a schedule file in the tool's own schedules folder",
235
+ ],
229
236
  [
230
237
  "agent.refused",
231
238
  "permission_error",
@@ -0,0 +1,34 @@
1
+ import type { CellValue } from "./xlsx.js";
2
+ export interface NewSheet {
3
+ /** 1 to 31 characters, none of `[]:*?/\`, not starting or ending with `'`; unique in the workbook, ignoring case. */
4
+ readonly name: string;
5
+ /** Rows from A1 down; `null` leaves a cell empty. */
6
+ readonly rows: readonly (readonly CellValue[])[];
7
+ }
8
+ export interface CreateXlsxOptions {
9
+ readonly sheets: readonly NewSheet[];
10
+ /** The first row of every sheet in bold. */
11
+ readonly boldHeader?: boolean;
12
+ }
13
+ /**
14
+ * 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.
16
+ */
17
+ export declare const createXlsx: (options: CreateXlsxOptions) => Uint8Array;
18
+ export declare const NEW_PARAGRAPH_STYLES: readonly ["Title", "Heading1", "Heading2", "Heading3", "Normal", "ListBullet"];
19
+ export type NewParagraphStyle = (typeof NEW_PARAGRAPH_STYLES)[number];
20
+ export interface NewParagraph {
21
+ /** A tab is `\t`, a line break `\n`. */
22
+ readonly text: string;
23
+ /** `Normal` when absent. */
24
+ readonly style?: NewParagraphStyle;
25
+ }
26
+ export interface CreateDocxOptions {
27
+ readonly paragraphs: readonly NewParagraph[];
28
+ }
29
+ /**
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.
33
+ */
34
+ export declare const createDocx: (options: CreateDocxOptions) => Uint8Array;
@@ -0,0 +1,216 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { strToU8, zipSync } from "fflate";
3
+ import { columnName } from "../attachments/sheets.js";
4
+ import { escapeAttribute } from "./package.js";
5
+ import { escapeText } from "./xml.js";
6
+ const MAX_ROW = 1_048_576;
7
+ const MAX_COLUMN = 16_384;
8
+ const MAX_CELL_TEXT = 32_767;
9
+ const XML = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n';
10
+ const CONTENT_TYPES = "http://schemas.openxmlformats.org/package/2006/content-types";
11
+ const PACKAGE_REL = "http://schemas.openxmlformats.org/package/2006/relationships";
12
+ const OFFICE_REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
13
+ const SHEET_NS = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
14
+ const WORD_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
15
+ const OPENXML = "application/vnd.openxmlformats-officedocument";
16
+ const refuse = (message, reason) => new CliError("validation_error", message, { reason });
17
+ const packed = (parts) => zipSync(Object.fromEntries(Object.entries(parts).map(([path, text]) => [path, strToU8(XML + text)])), {
18
+ level: 6,
19
+ // fflate stores the time with local getters: a date made here from local fields is the same in every time zone.
20
+ mtime: new Date(1980, 0, 1),
21
+ });
22
+ const contentTypes = (overrides) => `<Types xmlns="${CONTENT_TYPES}">` +
23
+ `<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>` +
24
+ `<Default Extension="xml" ContentType="application/xml"/>` +
25
+ Object.entries(overrides)
26
+ .map(([part, type]) => `<Override PartName="/${part}" ContentType="${OPENXML}.${type}"/>`)
27
+ .join("") +
28
+ "</Types>";
29
+ const relationships = (entries) => `<Relationships xmlns="${PACKAGE_REL}">` +
30
+ entries
31
+ .map(([type, target], index) => `<Relationship Id="rId${index + 1}" Type="${OFFICE_REL}/${type}" Target="${target}"/>`)
32
+ .join("") +
33
+ "</Relationships>";
34
+ const checkSheetNames = (sheets) => {
35
+ if (!sheets.length)
36
+ throw refuse("a workbook needs at least one sheet", "office.invalid-sheet-name");
37
+ const seen = new Set();
38
+ for (const { name } of sheets) {
39
+ if (!name || name.length > 31 || /[[\]:*?/\\]/u.test(name) || name.startsWith("'") || name.endsWith("'"))
40
+ throw refuse(`"${name}" cannot name a sheet: 1 to 31 characters, none of [ ] : * ? / \\, not starting or ending with '`, "office.invalid-sheet-name");
41
+ escapeText(name);
42
+ const folded = name.toLocaleLowerCase("en");
43
+ if (seen.has(folded))
44
+ throw refuse(`two sheets are named "${name}"`, "office.invalid-sheet-name");
45
+ seen.add(folded);
46
+ }
47
+ };
48
+ class SharedStrings {
49
+ indexes = new Map();
50
+ count = 0;
51
+ index(text) {
52
+ this.count++;
53
+ const known = this.indexes.get(text);
54
+ if (known !== undefined)
55
+ return known;
56
+ this.indexes.set(text, this.indexes.size);
57
+ return this.indexes.size - 1;
58
+ }
59
+ get size() {
60
+ return this.indexes.size;
61
+ }
62
+ xml() {
63
+ const items = [...this.indexes.keys()].map((text) => `<si><t xml:space="preserve">${escapeText(text)}</t></si>`);
64
+ return `<sst xmlns="${SHEET_NS}" count="${this.count}" uniqueCount="${this.size}">${items.join("")}</sst>`;
65
+ }
66
+ }
67
+ const cellXml = (address, value, style, strings) => {
68
+ if (typeof value === "boolean")
69
+ return `<c r="${address}"${style} t="b"><v>${value ? 1 : 0}</v></c>`;
70
+ if (typeof value === "number") {
71
+ if (!Number.isFinite(value))
72
+ throw refuse(`${address}: a cell number must be finite`, "office.invalid-value");
73
+ return `<c r="${address}"${style}><v>${String(value)}</v></c>`;
74
+ }
75
+ if (value.length > MAX_CELL_TEXT)
76
+ throw refuse(`${address}: a cell holds at most 32,767 characters`, "office.invalid-value");
77
+ return `<c r="${address}"${style} t="s"><v>${strings.index(value)}</v></c>`;
78
+ };
79
+ const worksheetXml = (sheet, strings, boldHeader) => {
80
+ if (sheet.rows.length > MAX_ROW)
81
+ throw refuse(`sheet "${sheet.name}" has more than 1,048,576 rows`, "office.invalid-cell");
82
+ let right = 0;
83
+ let bottom = 0;
84
+ const rows = sheet.rows.flatMap((values, down) => {
85
+ if (values.length > MAX_COLUMN)
86
+ 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) => {
89
+ if (value === null)
90
+ return [];
91
+ right = Math.max(right, across + 1);
92
+ return [cellXml(`${columnName(across + 1)}${down + 1}`, value, style, strings)];
93
+ });
94
+ if (!cells.length)
95
+ return [];
96
+ bottom = down + 1;
97
+ return [`<row r="${down + 1}">${cells.join("")}</row>`];
98
+ });
99
+ const dimension = bottom ? `A1:${columnName(right)}${bottom}` : "A1";
100
+ const data = rows.length ? `<sheetData>${rows.join("")}</sheetData>` : "<sheetData/>";
101
+ return `<worksheet xmlns="${SHEET_NS}" xmlns:r="${OFFICE_REL}"><dimension ref="${dimension}"/>${data}</worksheet>`;
102
+ };
103
+ // Excel repairs a workbook whose styles lack the two default fills or a border; font 1 and format 1 are the bold header.
104
+ const STYLES = `<styleSheet xmlns="${SHEET_NS}">` +
105
+ '<fonts count="2"><font><sz val="11"/><name val="Calibri"/><family val="2"/></font>' +
106
+ '<font><b/><sz val="11"/><name val="Calibri"/><family val="2"/></font></fonts>' +
107
+ '<fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills>' +
108
+ '<borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders>' +
109
+ '<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>' +
110
+ '<cellXfs count="2"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>' +
111
+ '<xf numFmtId="0" fontId="1" fillId="0" borderId="0" xfId="0" applyFont="1"/></cellXfs>' +
112
+ '<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles>' +
113
+ "</styleSheet>";
114
+ /**
115
+ * 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.
117
+ */
118
+ export const createXlsx = (options) => {
119
+ const { sheets, boldHeader = false } = options;
120
+ checkSheetNames(sheets);
121
+ const strings = new SharedStrings();
122
+ const parts = {};
123
+ const types = { "xl/workbook.xml": "spreadsheetml.sheet.main+xml" };
124
+ sheets.forEach((sheet, index) => {
125
+ parts[`xl/worksheets/sheet${index + 1}.xml`] = worksheetXml(sheet, strings, boldHeader);
126
+ types[`xl/worksheets/sheet${index + 1}.xml`] = "spreadsheetml.worksheet+xml";
127
+ });
128
+ types["xl/styles.xml"] = "spreadsheetml.styles+xml";
129
+ const links = [
130
+ ...sheets.map((_, index) => ["worksheet", `worksheets/sheet${index + 1}.xml`]),
131
+ ["styles", "styles.xml"],
132
+ ];
133
+ if (strings.size) {
134
+ types["xl/sharedStrings.xml"] = "spreadsheetml.sharedStrings+xml";
135
+ links.push(["sharedStrings", "sharedStrings.xml"]);
136
+ }
137
+ const listed = sheets
138
+ .map((sheet, index) => `<sheet name="${escapeAttribute(sheet.name)}" sheetId="${index + 1}" r:id="rId${index + 1}"/>`)
139
+ .join("");
140
+ return packed({
141
+ "[Content_Types].xml": contentTypes(types),
142
+ "_rels/.rels": relationships([["officeDocument", "xl/workbook.xml"]]),
143
+ "xl/workbook.xml": `<workbook xmlns="${SHEET_NS}" xmlns:r="${OFFICE_REL}"><sheets>${listed}</sheets></workbook>`,
144
+ "xl/_rels/workbook.xml.rels": relationships(links),
145
+ "xl/styles.xml": STYLES,
146
+ ...(strings.size ? { "xl/sharedStrings.xml": strings.xml() } : {}),
147
+ ...parts,
148
+ });
149
+ };
150
+ export const NEW_PARAGRAPH_STYLES = ["Title", "Heading1", "Heading2", "Heading3", "Normal", "ListBullet"];
151
+ const heading = (level, size, before) => `<w:style w:type="paragraph" w:styleId="Heading${level}"><w:name w:val="heading ${level}"/>` +
152
+ '<w:basedOn w:val="Normal"/><w:next w:val="Normal"/><w:uiPriority w:val="9"/><w:qFormat/>' +
153
+ `<w:pPr><w:keepNext/><w:keepLines/><w:spacing w:before="${before}" w:after="80"/><w:outlineLvl w:val="${level - 1}"/></w:pPr>` +
154
+ `<w:rPr><w:b/><w:bCs/><w:sz w:val="${size}"/><w:szCs w:val="${size}"/></w:rPr></w:style>`;
155
+ // Word's built-in names ("heading 1", "List Bullet"), so Word, LibreOffice and mammoth know the styles as their own.
156
+ const WORD_STYLES = `<w:styles xmlns:w="${WORD_NS}">` +
157
+ "<w:docDefaults><w:rPrDefault><w:rPr>" +
158
+ '<w:rFonts w:ascii="Calibri" w:eastAsia="Calibri" w:hAnsi="Calibri" w:cs="Calibri"/>' +
159
+ '<w:sz w:val="22"/><w:szCs w:val="22"/></w:rPr></w:rPrDefault>' +
160
+ '<w:pPrDefault><w:pPr><w:spacing w:after="160" w:line="259" w:lineRule="auto"/></w:pPr></w:pPrDefault>' +
161
+ "</w:docDefaults>" +
162
+ '<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/><w:qFormat/></w:style>' +
163
+ '<w:style w:type="paragraph" w:styleId="Title"><w:name w:val="Title"/><w:basedOn w:val="Normal"/>' +
164
+ '<w:next w:val="Normal"/><w:uiPriority w:val="10"/><w:qFormat/><w:pPr><w:spacing w:after="80"/></w:pPr>' +
165
+ '<w:rPr><w:sz w:val="56"/><w:szCs w:val="56"/></w:rPr></w:style>' +
166
+ heading(1, 40, 360) +
167
+ heading(2, 32, 160) +
168
+ heading(3, 28, 160) +
169
+ '<w:style w:type="paragraph" w:styleId="ListBullet"><w:name w:val="List Bullet"/><w:basedOn w:val="Normal"/>' +
170
+ '<w:uiPriority w:val="99"/><w:pPr><w:numPr><w:numId w:val="1"/></w:numPr><w:contextualSpacing/></w:pPr></w:style>' +
171
+ "</w:styles>";
172
+ const NUMBERING = `<w:numbering xmlns:w="${WORD_NS}"><w:abstractNum w:abstractNumId="0">` +
173
+ '<w:multiLevelType w:val="singleLevel"/><w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="bullet"/>' +
174
+ '<w:lvlText w:val="•"/><w:lvlJc w:val="left"/><w:pPr><w:ind w:left="720" w:hanging="360"/></w:pPr></w:lvl>' +
175
+ '</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>`;
183
+ const content = text
184
+ .replace(/\r\n?/gu, "\n")
185
+ .split(/(\n|\t)/u)
186
+ .filter((piece) => piece !== "")
187
+ .map((piece) => piece === "\n" ? "<w:br/>" : piece === "\t" ? "<w:tab/>" : `<w:t xml:space="preserve">${escapeText(piece)}</w:t>`)
188
+ .join("");
189
+ return `<w:p>${properties}${content ? `<w:r>${content}</w:r>` : ""}</w:p>`;
190
+ };
191
+ /**
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.
195
+ */
196
+ 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/>";
199
+ 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
+ 'w:header="708" w:footer="708" w:gutter="0"/></w:sectPr>';
201
+ return packed({
202
+ "[Content_Types].xml": contentTypes({
203
+ "word/document.xml": "wordprocessingml.document.main+xml",
204
+ "word/styles.xml": "wordprocessingml.styles+xml",
205
+ "word/numbering.xml": "wordprocessingml.numbering+xml",
206
+ }),
207
+ "_rels/.rels": relationships([["officeDocument", "word/document.xml"]]),
208
+ "word/document.xml": `<w:document xmlns:w="${WORD_NS}" xmlns:r="${OFFICE_REL}"><w:body>${body}${section}</w:body></w:document>`,
209
+ "word/_rels/document.xml.rels": relationships([
210
+ ["styles", "styles.xml"],
211
+ ["numbering", "numbering.xml"],
212
+ ]),
213
+ "word/styles.xml": WORD_STYLES,
214
+ "word/numbering.xml": NUMBERING,
215
+ });
216
+ };
@@ -1,2 +1,3 @@
1
+ export { type CreateDocxOptions, type CreateXlsxOptions, createDocx, createXlsx, NEW_PARAGRAPH_STYLES, type NewParagraph, type NewParagraphStyle, type NewSheet, } from "./create.js";
1
2
  export { type DocxEdit, type DocxParagraph, type EditDocxResult, editDocxParagraphs, readDocxParagraphs, } from "./docx.js";
2
3
  export { type CellType, type CellValue, type EditXlsxOptions, type EditXlsxResult, editXlsxCells, type ReadXlsxOptions, readXlsxCells, type XlsxCell, type XlsxEdit, type XlsxSheet, } from "./xlsx.js";
@@ -1,2 +1,3 @@
1
+ export { createDocx, createXlsx, NEW_PARAGRAPH_STYLES, } from "./create.js";
1
2
  export { editDocxParagraphs, readDocxParagraphs, } from "./docx.js";
2
3
  export { editXlsxCells, readXlsxCells, } from "./xlsx.js";
@@ -30,6 +30,7 @@ export declare class OfficePackage {
30
30
  /** The new file: changed parts recompressed, every other entry copied as it was. */
31
31
  build(): Uint8Array<ArrayBuffer>;
32
32
  }
33
+ export declare const escapeAttribute: (value: string) => string;
33
34
  /** A start tag with one attribute set (added at the end when it was not there). */
34
35
  export declare const withAttribute: (tag: string, name: string, value: string) => string;
35
36
  export declare const withoutAttribute: (tag: string, name: string) => string;
@@ -80,7 +80,7 @@ export class OfficePackage {
80
80
  return this.changed.size ? rewriteZip(this.bytes, this.changed) : this.bytes.slice();
81
81
  }
82
82
  }
83
- const escapeAttribute = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll('"', "&quot;");
83
+ export const escapeAttribute = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll('"', "&quot;");
84
84
  /** A start tag with one attribute set (added at the end when it was not there). */
85
85
  export const withAttribute = (tag, name, value) => {
86
86
  const pattern = new RegExp(`(\\s)${name}\\s*=\\s*(?:"[^"]*"|'[^']*')`);
@@ -301,9 +301,12 @@ export interface UnreadChats {
301
301
  /**
302
302
  * The chats `inbox` and `review` look at, with `unreadCount`, `unreadMentions`, `muted` and `lastMessageAt` filled
303
303
  * where `chats` leaves them out because each costs a request, as Slack's do. `chats` stays one cheap list for every
304
- * other command. `hasMore` when it stopped short, so the answer says it may have missed one.
304
+ * other command. `hasMore` when it stopped short, so the answer says it may have missed one. `left` says, in the
305
+ * owner's words, what it did not look at and why, such as chats it cannot count; the answer names each in `missing`.
305
306
  */
306
- unreadChats(): Promise<Page<Chat>>;
307
+ unreadChats(): Promise<Page<Chat> & {
308
+ left?: string[];
309
+ }>;
307
310
  }
308
311
  export interface ThreadReplies {
309
312
  /**
@@ -0,0 +1,16 @@
1
+ export declare const stemsOf: (token: string) => string[];
2
+ export type StoredWord = {
3
+ token: string;
4
+ literal: string;
5
+ };
6
+ export type Probe = {
7
+ literal: string;
8
+ stems: string[];
9
+ };
10
+ /** One word of a query clause, with the corrections that may stand for it. */
11
+ export type QueryWord = Probe[];
12
+ export declare const probeOf: (token: string) => Probe;
13
+ export declare const tokensOf: (text: string) => string[];
14
+ export declare const wordMatches: (probe: Probe, word: StoredWord, exact: boolean) => boolean;
15
+ /** A clause of several words, `КТП-630` or an e-mail, matches only where they follow each other. */
16
+ export declare const clauseIn: (clause: QueryWord[], words: StoredWord[], exact: boolean) => boolean;
@@ -0,0 +1,28 @@
1
+ import { fold } from "../store/normalize.js";
2
+ import { createStemmer, DEFAULT_STEMMERS, START_LETTERS } from "./stem.js";
3
+ /**
4
+ * Word matching over text read into memory, for the stores that keep no stem index: a query word matches a stored word
5
+ * that is the same, one it begins (`START_LETTERS` letters or more; shorter words only as whole words: «с» or "a"
6
+ * begins half the words of any title), or one of the same stem by the default Snowball stemmers.
7
+ */
8
+ const TOKEN = /[\p{L}\p{N}\p{M}]+/gu;
9
+ const stemmer = createStemmer(DEFAULT_STEMMERS, { cacheLimit: 20_000 });
10
+ export const stemsOf = (token) => stemmer.stemSequences(token).flat();
11
+ export const probeOf = (token) => ({ literal: fold(token), stems: stemsOf(token) });
12
+ export const tokensOf = (text) => text.normalize("NFC").toLowerCase().match(TOKEN) ?? [];
13
+ export const wordMatches = (probe, word, exact) => {
14
+ if (word.literal === probe.literal)
15
+ return true;
16
+ if (exact)
17
+ return false;
18
+ if (probe.literal.length >= START_LETTERS && word.literal.startsWith(probe.literal))
19
+ return true;
20
+ // A stem begins its word, so a word that does not start like the stem needs no stemming.
21
+ return (probe.stems.some((stem) => word.literal.startsWith(stem.slice(0, 3))) &&
22
+ stemsOf(word.token).some((stem) => probe.stems.includes(stem)));
23
+ };
24
+ /** A clause of several words, `КТП-630` or an e-mail, matches only where they follow each other. */
25
+ export const clauseIn = (clause, words, exact) => words.some((_, at) => clause.every((alternatives, offset) => {
26
+ const word = words[at + offset];
27
+ return word !== undefined && alternatives.some((probe) => wordMatches(probe, word, exact));
28
+ }));
@@ -9,6 +9,8 @@ export declare const uploadBlob: (source: UploadSource, type?: string) => Promis
9
9
  export declare const uploadBytes: (source: UploadSource) => Promise<Uint8Array>;
10
10
  /** `[".jpg", ".jpeg"]` as help says it: ".jpg or .jpeg". */
11
11
  export declare const typesText: (types: readonly string[]) => string;
12
+ /** Where `path` really is: its nearest existing ancestor's real path, as a write may create the rest under a symlink. */
13
+ export declare const realPathOf: (path: string) => string;
12
14
  /**
13
15
  * Refuses a file or folder a read-only process would write outside its scheduled run's work folder. The run names
14
16
  * that empty folder in `<PREFIX>_WORK_FOLDER` on the agent it starts, and it is read from there, so neither a `cd` nor
@@ -21,6 +23,7 @@ export declare const refuseLockedOutput: (path: string, app: AppIdentity, env: N
21
23
  * ordinary hidden developer folders.
22
24
  */
23
25
  export declare const refusedPlace: (path: string, app: AppIdentity, env: NodeJS.ProcessEnv, platform?: NodeJS.Platform) => boolean;
26
+ export declare const inside: (path: string, dir: string) => boolean;
24
27
  export declare const readUpload: (kind: UploadKind, path: string, { app, env, anyFile, photoTypes, }: {
25
28
  app: AppIdentity;
26
29
  env?: NodeJS.ProcessEnv;
@@ -124,7 +124,7 @@ const WIRECAT_APPS = [
124
124
  const SYSTEM_ROOTS = ["/proc", "/sys", "/dev"];
125
125
  const systemPlace = (path, platform) => platform !== "win32" && SYSTEM_ROOTS.some((root) => inside(path, root));
126
126
  /** Where `path` really is: its nearest existing ancestor's real path, as a write may create the rest under a symlink. */
127
- const realPathOf = (path) => {
127
+ export const realPathOf = (path) => {
128
128
  let ancestor = resolve(path);
129
129
  for (;;) {
130
130
  try {
@@ -187,7 +187,7 @@ export const refusedPlace = (path, app, env, platform = process.platform) => {
187
187
  own.some((dir) => inside(fold(candidate), fold(dir))) ||
188
188
  [store, `${store}-wal`, `${store}-shm`].some((file) => same(candidate, file)));
189
189
  };
190
- const inside = (path, dir) => {
190
+ export const inside = (path, dir) => {
191
191
  const way = relative(resolve(dir), path);
192
192
  return way === "" || (!way.startsWith("..") && !isAbsolute(way));
193
193
  };
@@ -121,11 +121,13 @@ export const documentIngestion = (store, options) => {
121
121
  history: {
122
122
  /** `id` is the source's id, or a `document:<n>` ref; a removed document is found too. */
123
123
  reference: async (principal, id) => {
124
- if (/^document:\d+$/.test(id))
125
- return id;
126
124
  const selected = await folder(principal, false);
127
125
  if (!selected)
128
126
  return undefined;
127
+ if (/^document:\d+$/.test(id)) {
128
+ const path = await store.notes.documentHistory(id).then((found) => found.path, () => undefined);
129
+ return path !== undefined && (await store.notes.documentAt(selected.id, path)) === id ? id : undefined;
130
+ }
129
131
  for (const path of both(id)) {
130
132
  const found = await store.notes.documentAt(selected.id, path);
131
133
  if (found)
@@ -102,9 +102,11 @@ export { safeName };
102
102
  */
103
103
  export const save = async (file, directory, fallbackName, { unique = false } = {}) => {
104
104
  const own = safeName(file.name);
105
+ // The fallback is made from the provider's message id, which is no safer than the sender's own name.
106
+ const fallback = safeName(fallbackName) ?? "file";
105
107
  const fileName = () => {
106
108
  const extension = EXTENSIONS[file.mime ?? ""] ?? BY_KIND[file.kind];
107
- return own ?? (extension ? `${fallbackName}.${extension}` : fallbackName);
109
+ return own ?? (extension ? `${fallback}.${extension}` : fallback);
108
110
  };
109
111
  const partial = join(directory, `.${fileName()}.${process.pid}.part`);
110
112
  let bytes = 0;
@@ -118,7 +120,7 @@ export const save = async (file, directory, fallbackName, { unique = false } = {
118
120
  await pipeline(Readable.from(file.bytes()), counting, createWriteStream(partial, { flags: "wx", mode: 0o600 }));
119
121
  // Lazy HTTP downloads learn MIME while reading bytes.
120
122
  const name = fileName();
121
- const names = unique && own ? [name, `${fallbackName}-${own}`] : [name];
123
+ const names = unique && own ? [name, `${fallback}-${own}`] : [name];
122
124
  for (const candidate of names) {
123
125
  const path = resolve(join(directory, candidate));
124
126
  const taken = await link(partial, path).then(() => false, (error) => {
@@ -27,7 +27,8 @@ export const heard = (chats, all) => all
27
27
  * typed title; MAX answers from the chats its login sent. `hasMore` is the messenger saying it could
28
28
  * not list them all.
29
29
  */
30
- const everyChat = (adapter) => (adapter.unreadChats ? adapter.unreadChats() : adapter.chats({ offset: 0 }));
30
+ const everyChat = (adapter) => adapter.unreadChats ? adapter.unreadChats() : adapter.chats({ offset: 0 });
31
+ const leftOf = (page) => (page.left?.length ? { left: page.left } : {});
31
32
  /**
32
33
  * The stored chats and messages, read as the messenger would answer. Saving a message does not move
33
34
  * its chat's last message time, so the newest stored message does — a chat that only `watch` heard
@@ -99,7 +100,7 @@ export const unreadIn = async (adapter, { limit, all = false, kinds }) => {
99
100
  if (theirs.length > 0)
100
101
  chats.push({ id, title, kind, unreadCount, messages: theirs, more: count > limit });
101
102
  }
102
- return { mode: "unread", chats, skipped, partial: page.hasMore, quiet };
103
+ return { mode: "unread", chats, skipped, partial: page.hasMore, ...leftOf(page), quiet };
103
104
  };
104
105
  /**
105
106
  * Other people's messages in every chat that changed after its own point — `points` — or after
@@ -144,6 +145,7 @@ export const newIn = async (adapter, { since, points, limit, all = false, kinds,
144
145
  chats,
145
146
  skipped,
146
147
  partial: page.hasMore,
148
+ ...leftOf(page),
147
149
  quiet,
148
150
  checked,
149
151
  };
@@ -206,6 +208,7 @@ export const reviewIn = async (adapter, { since, points, chat, kinds, all = fals
206
208
  chats,
207
209
  skipped,
208
210
  partial,
211
+ ...leftOf(page),
209
212
  quiet,
210
213
  ...(points === undefined ? {} : { checked }),
211
214
  };