@wirecat/cli-core 0.647.0 → 0.649.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 (80) hide show
  1. package/CHANGELOG.md +117 -0
  2. package/dist/background/daily-archive-timer.d.ts +1 -1
  3. package/dist/cli/account-remove.d.ts +5 -0
  4. package/dist/cli/account-remove.js +6 -1
  5. package/dist/cli/app-doctor-command.js +15 -57
  6. package/dist/cli/app-store.d.ts +12 -0
  7. package/dist/cli/app-store.js +25 -0
  8. package/dist/cli/commands-command.js +10 -3
  9. package/dist/cli/doctor-reports-command.d.ts +22 -0
  10. package/dist/cli/doctor-reports-command.js +82 -0
  11. package/dist/cli/help/command-help.d.ts +1 -0
  12. package/dist/cli/help/command-help.js +7 -8
  13. package/dist/cli/index.d.ts +3 -1
  14. package/dist/cli/index.js +3 -1
  15. package/dist/cli/messenger/doctor-command.js +21 -64
  16. package/dist/cli/messenger/stats-command.js +1 -1
  17. package/dist/cli/messenger/store-maintenance-command.js +3 -3
  18. package/dist/cli/messenger/tasks-command.js +1 -3
  19. package/dist/cli/permission-keys.js +4 -2
  20. package/dist/cli/program.js +26 -10
  21. package/dist/cli/settings.d.ts +2 -0
  22. package/dist/cli/settings.js +3 -2
  23. package/dist/cli/store-recover.js +2 -2
  24. package/dist/cli/unknown-profile.d.ts +9 -0
  25. package/dist/cli/unknown-profile.js +23 -0
  26. package/dist/crm/cli/search-all.js +4 -4
  27. package/dist/domain/providers.d.ts +4 -1
  28. package/dist/domain/providers.js +9 -2
  29. package/dist/domain/record-types.d.ts +24 -3
  30. package/dist/domain/record-types.js +23 -2
  31. package/dist/domain/records-table.js +4 -3
  32. package/dist/domain/records.d.ts +1 -1
  33. package/dist/domain/records.js +3 -2
  34. package/dist/errors/failures.d.ts +2 -0
  35. package/dist/errors/failures.js +6 -0
  36. package/dist/errors/reasons.js +17 -1
  37. package/dist/index.d.ts +1 -0
  38. package/dist/index.js +1 -0
  39. package/dist/kit/index.d.ts +1 -0
  40. package/dist/kit/index.js +1 -0
  41. package/dist/kit/own-catalogue.d.ts +7 -0
  42. package/dist/kit/own-catalogue.js +21 -0
  43. package/dist/oauth/index.d.ts +2 -2
  44. package/dist/oauth/index.js +2 -1
  45. package/dist/oauth/provider.d.ts +4 -0
  46. package/dist/oauth/provider.js +16 -1
  47. package/dist/oauth/storage.d.ts +5 -0
  48. package/dist/oauth/storage.js +20 -0
  49. package/dist/runs/error-detail.d.ts +1 -1
  50. package/dist/runs/error-detail.js +5 -2
  51. package/dist/runs/events.d.ts +1 -1
  52. package/dist/runs/secrets.d.ts +5 -4
  53. package/dist/runs/secrets.js +8 -4
  54. package/dist/sends/permissions.d.ts +2 -0
  55. package/dist/sends/permissions.js +4 -1
  56. package/dist/services/document-source.js +9 -1
  57. package/dist/services/notes-search.d.ts +10 -5
  58. package/dist/services/notes-search.js +19 -7
  59. package/dist/services/search-all.js +19 -11
  60. package/dist/sftp/index.d.ts +1 -0
  61. package/dist/sftp/index.js +1 -0
  62. package/dist/sftp/session.d.ts +61 -0
  63. package/dist/sftp/session.js +230 -0
  64. package/dist/sftp/ssh2.d.ts +38 -0
  65. package/dist/sftp/ssh2.js +306 -0
  66. package/dist/store/index.d.ts +1 -0
  67. package/dist/store/index.js +1 -0
  68. package/dist/store/sqlite/added-sources.d.ts +38 -0
  69. package/dist/store/sqlite/added-sources.js +80 -50
  70. package/dist/store/sqlite/crm-activities.d.ts +2 -0
  71. package/dist/store/sqlite/crm-activities.js +17 -0
  72. package/dist/store/sqlite/deals.d.ts +4 -3
  73. package/dist/store/sqlite/deals.js +8 -2
  74. package/dist/store/sqlite/open-store.js +14 -1
  75. package/dist/store/sqlite/record-projectors-document.d.ts +12 -0
  76. package/dist/store/sqlite/record-projectors-document.js +81 -0
  77. package/dist/store/sqlite/record-projectors.js +2 -0
  78. package/package.json +14 -4
  79. package/parity.json +2 -11
  80. package/schemas/records-envelope.v1.schema.json +57 -2
@@ -10,6 +10,61 @@ import { documentOf, folderOf, insertLink, keepRevision, pathParts, requiredThin
10
10
  import { oneOf, textOf } from "./text-input.js";
11
11
  import { write } from "./transaction.js";
12
12
  export const ADDED_KINDS = ["text", "file", "page"];
13
+ const TEXT_COLUMNS = "kind = ?, title = ?, file_name = ?, extension = ?, url = ?, mime = ?, size = ?, content_hash = ?, body = ?, " +
14
+ "extraction = ?, metadata = ?, language = ?";
15
+ const textValues = (document) => [
16
+ document.kind,
17
+ document.title,
18
+ document.fileName,
19
+ document.extension,
20
+ document.url,
21
+ document.mime,
22
+ document.size,
23
+ document.hash,
24
+ document.text,
25
+ document.extraction,
26
+ document.metadata,
27
+ document.language,
28
+ ];
29
+ /**
30
+ * The writes of a document in a given account: the added sources' (`added:owner`) and a records import's (the
31
+ * envelope's own account) go through the same columns.
32
+ */
33
+ export const documentWritesOver = ({ database }) => ({
34
+ insert: (accountId, externalId, document, kept, at) => Number(database
35
+ .prepare("INSERT INTO documents (account_id, external_id, kind, title, file_name, extension, url, mime, size, " +
36
+ "content_hash, body, extraction, metadata, language, storage, local_path, revision, created_at, updated_at) " +
37
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?) RETURNING id")
38
+ .get(accountId, externalId, ...textValues(document), kept.storage, kept.localPath, at, at)?.id),
39
+ /** Its next revision, the text before kept; `revised: false` changes what describes it and keeps the revision. */
40
+ update: (row, document, at, revised = true) => {
41
+ if (revised)
42
+ keepRevision(database, row, at);
43
+ database
44
+ .prepare(`UPDATE documents SET ${TEXT_COLUMNS}, revision = revision + ?, updated_at = ? WHERE id = ?`)
45
+ .run(...textValues(document), revised ? 1 : 0, at, Number(row.id));
46
+ },
47
+ /** A removed document back, as written now. */
48
+ revive: (id, document, kept, at) => {
49
+ database
50
+ .prepare(`UPDATE documents SET ${TEXT_COLUMNS}, storage = ?, local_path = ?, updated_at = ?, deleted_at = NULL WHERE id = ?`)
51
+ .run(...textValues(document), kept.storage, kept.localPath, at, id);
52
+ },
53
+ /** Its `files` row, named as its source names it, not by a hash or a key. */
54
+ place: (id, at, name) => {
55
+ syncFile(database, at, id);
56
+ database
57
+ .prepare("UPDATE files SET name = ?, path = ?, path_folded = ? WHERE document_id = ? AND kind <> 'folder'")
58
+ .run(name, name, fold(name), id);
59
+ },
60
+ /** Its text goes, its row stays as deleted: what a folder file's removal does. */
61
+ remove: (id, at) => {
62
+ database
63
+ .prepare("UPDATE files SET deleted_at = ?, updated_at = ? WHERE document_id = ? AND deleted_at IS NULL")
64
+ .run(at, at, id);
65
+ database.prepare("UPDATE documents SET deleted_at = ?, body = '' WHERE id = ?").run(at, id);
66
+ },
67
+ });
13
68
  const sha256 = (value) => createHash("sha256").update(value).digest("hex");
14
69
  // `sha256:` is the content's own name, so no key may take it.
15
70
  const SOURCE_KEY = /^(?!sha256:)[a-z][a-z0-9-]{0,39}:[A-Za-z0-9._~-]{1,200}$/;
@@ -66,8 +121,23 @@ const checked = (input) => {
66
121
  extension: fileName === null ? null : pathParts(fileName).extension,
67
122
  };
68
123
  };
124
+ const documentTextOf = (source, input) => ({
125
+ kind: source.kind,
126
+ title: source.title,
127
+ fileName: source.fileName,
128
+ extension: source.extension,
129
+ url: source.url,
130
+ mime: input.mime ?? null,
131
+ size: input.size ?? input.bytes?.byteLength ?? null,
132
+ hash: source.hash,
133
+ text: source.text,
134
+ extraction: source.read === "extracted" ? "text" : "none",
135
+ metadata: encodeDocumentMetadata(input.metadata, input.sections),
136
+ language: languageOf(input.metadata),
137
+ });
69
138
  export const addedSourcesOver = (context) => {
70
139
  const { database, now } = context;
140
+ const writes = documentWritesOver(context);
71
141
  const accountRow = () => database.prepare("SELECT * FROM accounts WHERE provider = ? AND external_id = ?").get(ADDED_PROVIDER, ADDED_ACCOUNT);
72
142
  const documentAt = (id) => documentOf(database.prepare("SELECT * FROM documents WHERE id = ?").get(id));
73
143
  const ownRow = (externalId) => {
@@ -122,13 +192,6 @@ export const addedSourcesOver = (context) => {
122
192
  .get(JSON.stringify(hashes));
123
193
  return row ? Number(row.id) : undefined;
124
194
  };
125
- /** Its `files` row is named as the owner named the source, not by its hash. */
126
- const placeFile = (id, at, name) => {
127
- syncFile(database, at, id);
128
- database
129
- .prepare("UPDATE files SET name = ?, path = ?, path_folded = ? WHERE document_id = ? AND kind <> 'folder'")
130
- .run(name, name, fold(name), id);
131
- };
132
195
  return {
133
196
  addedAccount: async () => {
134
197
  const row = accountRow();
@@ -177,11 +240,7 @@ export const addedSourcesOver = (context) => {
177
240
  .get(id, ADDED_PROVIDER);
178
241
  if (!row)
179
242
  throw new CliError("not_found", `no live added source ${reference} in the local store`);
180
- const at = now();
181
- database
182
- .prepare("UPDATE files SET deleted_at = ?, updated_at = ? WHERE document_id = ? AND deleted_at IS NULL")
183
- .run(at, at, id);
184
- database.prepare("UPDATE documents SET deleted_at = ?, body = '' WHERE id = ?").run(at, id);
243
+ writes.remove(id, now());
185
244
  return {
186
245
  ref: `document:${id}`,
187
246
  removed: true,
@@ -191,7 +250,8 @@ export const addedSourcesOver = (context) => {
191
250
  },
192
251
  saveAddedSource: async (input) => {
193
252
  const source = checked(input);
194
- const metadata = encodeDocumentMetadata(input.metadata, input.sections);
253
+ const document = documentTextOf(source, input);
254
+ const kept = { storage: source.copy === null ? "text" : "copy", localPath: source.copy };
195
255
  const subjects = input.subjects ?? [];
196
256
  return write(database, () => {
197
257
  const at = now();
@@ -200,24 +260,18 @@ export const addedSourcesOver = (context) => {
200
260
  const id = Number(own.id);
201
261
  const revised = input.sourceKey !== undefined && own.content_hash !== source.hash;
202
262
  if (revised) {
203
- keepRevision(database, own, at);
204
- database
205
- .prepare("UPDATE documents SET kind = ?, title = ?, file_name = ?, extension = ?, url = ?, mime = ?, size = ?, " +
206
- "content_hash = ?, body = ?, extraction = ?, metadata = ?, language = ?, revision = revision + 1, " +
207
- "updated_at = ? WHERE id = ?")
208
- .run(source.kind, source.title, source.fileName, source.extension, source.url, input.mime ?? null, input.size ?? input.bytes?.byteLength ?? null, source.hash, source.text, source.read === "extracted" ? "text" : "none", metadata, languageOf(input.metadata), at, id);
209
- placeFile(id, at, source.fileName ?? source.title ?? source.externalId);
263
+ writes.update(own, document, at);
264
+ writes.place(id, at, source.fileName ?? source.title ?? source.externalId);
210
265
  }
211
266
  if (source.copy !== null && own.storage !== "copy")
212
267
  database
213
268
  .prepare("UPDATE documents SET storage = 'copy', local_path = ?, updated_at = ? WHERE id = ?")
214
269
  .run(source.copy, at, id);
215
- const kept = source.copy !== null || own.storage === "copy" ? "copy" : "text";
216
270
  return {
217
271
  note: documentAt(id),
218
272
  created: false,
219
273
  duplicateOf: null,
220
- kept,
274
+ kept: source.copy !== null || own.storage === "copy" ? "copy" : "text",
221
275
  changed: revised,
222
276
  subjects: about(id, subjects, input.by),
223
277
  };
@@ -228,30 +282,10 @@ export const addedSourcesOver = (context) => {
228
282
  const note = documentAt(duplicate);
229
283
  return { note, created: false, duplicateOf: note.ref, kept: null, changed: false, subjects: linked };
230
284
  }
231
- const values = [
232
- source.kind,
233
- source.title,
234
- source.fileName,
235
- source.extension,
236
- source.url,
237
- source.copy === null ? "text" : "copy",
238
- source.copy,
239
- input.mime ?? null,
240
- input.size ?? input.bytes?.byteLength ?? null,
241
- source.hash,
242
- source.text,
243
- source.read === "extracted" ? "text" : "none",
244
- metadata,
245
- languageOf(input.metadata),
246
- ];
247
285
  let id;
248
286
  if (own) {
249
287
  id = Number(own.id);
250
- database
251
- .prepare("UPDATE documents SET kind = ?, title = ?, file_name = ?, extension = ?, url = ?, storage = ?, local_path = ?, " +
252
- "mime = ?, size = ?, content_hash = ?, body = ?, extraction = ?, metadata = ?, language = ?, " +
253
- "updated_at = ?, deleted_at = NULL WHERE id = ?")
254
- .run(...values, at, id);
288
+ writes.revive(id, document, kept, at);
255
289
  }
256
290
  else {
257
291
  const holder = accountRow()?.id ??
@@ -259,18 +293,14 @@ export const addedSourcesOver = (context) => {
259
293
  .prepare("INSERT INTO accounts (provider, external_id, name, settings, created_at, updated_at) " +
260
294
  "VALUES (?, ?, NULL, ?, ?, ?) RETURNING id")
261
295
  .get(ADDED_PROVIDER, ADDED_ACCOUNT, JSON.stringify({ format: "markdown" }), at, at)?.id;
262
- id = Number(database
263
- .prepare("INSERT INTO documents (account_id, external_id, kind, title, file_name, extension, url, storage, local_path, " +
264
- "mime, size, content_hash, body, extraction, metadata, language, revision, created_at, updated_at) " +
265
- "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?) RETURNING id")
266
- .get(Number(holder), source.externalId, ...values, at, at)?.id);
296
+ id = writes.insert(Number(holder), source.externalId, document, kept, at);
267
297
  }
268
- placeFile(id, at, source.fileName ?? source.title ?? source.externalId);
298
+ writes.place(id, at, source.fileName ?? source.title ?? source.externalId);
269
299
  return {
270
300
  note: documentAt(id),
271
301
  created: !own,
272
302
  duplicateOf: null,
273
- kept: source.copy === null ? "text" : "copy",
303
+ kept: kept.storage,
274
304
  changed: true,
275
305
  subjects: about(id, subjects, input.by),
276
306
  };
@@ -16,6 +16,8 @@ export interface StoredActivity {
16
16
  createdAt: number;
17
17
  updatedAt: number;
18
18
  }
19
+ /** The subjects and texts of the activities on each deal or lead of a kind, by `<account id>\u0000<external id>`. */
20
+ export declare const activityTexts: (database: StoreContext["database"], kind: DealKind) => Map<string, string[]>;
19
21
  export interface CrmActivitiesSaved {
20
22
  saved: number;
21
23
  /** On no deal or lead this copy keeps, so not stored. */
@@ -6,6 +6,23 @@ export const ACTIVITY_RECORD = "crm.activity";
6
6
  /** A CRM's text field holds what people typed or pasted, a whole e-mail thread too. */
7
7
  const MOST_BODY = 20_000;
8
8
  const MOST_SUBJECT = 500;
9
+ /** The subjects and texts of the activities on each deal or lead of a kind, by `<account id>\u0000<external id>`. */
10
+ export const activityTexts = (database, kind) => {
11
+ const found = new Map();
12
+ for (const row of database
13
+ .prepare("SELECT r.account_id, rr.target_external_id, json_extract(r.fields, '$.subject') AS subject, " +
14
+ "json_extract(r.fields, '$.body') AS body FROM records r JOIN record_relations rr ON rr.record_id = r.id " +
15
+ "WHERE r.type = ? AND r.deleted_at IS NULL AND rr.role = 'on' AND rr.target_type = ?")
16
+ .all(ACTIVITY_RECORD, kind)) {
17
+ const key = `${row.account_id}\u0000${row.target_external_id}`;
18
+ const texts = found.get(key) ?? [];
19
+ found.set(key, texts);
20
+ for (const text of [row.subject, row.body])
21
+ if (typeof text === "string" && text)
22
+ texts.push(text);
23
+ }
24
+ return found;
25
+ };
9
26
  export const crmActivitiesOver = (context) => {
10
27
  const { database, now } = context;
11
28
  const kept = (accountId, kind, externalId) => database
@@ -182,8 +182,8 @@ export interface DealSearch {
182
182
  limit?: number;
183
183
  offset?: number;
184
184
  }
185
- /** Where a deal's or a lead's words are searched: its title, its company, the people on it. */
186
- export type DealPart = "title" | "company" | "contact";
185
+ /** Where a deal's or a lead's words are searched: its title, its company, the people on it, its CRM activities. */
186
+ export type DealPart = "title" | "company" | "contact" | "activity";
187
187
  export interface FoundDeal extends Deal {
188
188
  /** Where the query's words were found, in the order of `DealPart`. */
189
189
  matched: DealPart[];
@@ -228,7 +228,8 @@ export interface DealsStore {
228
228
  stages(reference: string): Promise<StageChange[]>;
229
229
  list(filter?: DealFilter): Promise<ListResult<Deal>>;
230
230
  /**
231
- * Deals and leads together, by the words of their title, company and contacts: a query word matches a stored word
231
+ * Deals and leads together, by the words of their title, company, contacts and the subjects and texts of their CRM
232
+ * activities (calls, e-mails, meetings, tasks): a query word matches a stored word
232
233
  * it begins or one of the same stem. The most words matched first, then the latest changed. When nothing matches,
233
234
  * a misspelt word is corrected to the stored words nearest to it, once.
234
235
  */
@@ -7,6 +7,7 @@ import { createStemmer, DEFAULT_STEMMERS } from "../../search/stem.js";
7
7
  import { fold } from "../normalize.js";
8
8
  import { proposedBySql } from "./actors.js";
9
9
  import { suggestBaseStages } from "./base-suggest.js";
10
+ import { activityTexts } from "./crm-activities.js";
10
11
  import { crmAccountPrefix } from "./crm-rows.js";
11
12
  import { linkKind } from "./link-kinds.js";
12
13
  import { authorActor, authorOf, evidenceOf, linkEvidence, projectId, projectOf } from "./memories.js";
@@ -48,7 +49,7 @@ const providerMetadataOf = (metadata) => {
48
49
  }
49
50
  };
50
51
  const accountOf = (provider, external) => provider == null ? null : { provider: String(provider), account: String(external) };
51
- const DEAL_PARTS = ["title", "company", "contact"];
52
+ const DEAL_PARTS = ["title", "company", "contact", "activity"];
52
53
  const TOKEN = /[\p{L}\p{N}\p{M}]+/gu;
53
54
  /** A query word shorter than this matches only a whole word: «с» or "a" begins half the words of any title. */
54
55
  const SHORTEST_BEGINNING = 4;
@@ -497,8 +498,9 @@ export const dealOperationsOver = (context) => {
497
498
  for (const phone of phones)
498
499
  texts.add(phone.replace(/\D/g, ""));
499
500
  }
501
+ const activities = activityTexts(database, kind);
500
502
  return database
501
- .prepare(`SELECT d.id, d.title, d.updated_at, a.provider, a.external_id AS account, o.name AS company, ` +
503
+ .prepare(`SELECT d.id, d.account_id, d.external_id, d.title, d.updated_at, a.provider, a.external_id AS account, o.name AS company, ` +
502
504
  "CASE WHEN json_valid(d.metadata) THEN json_extract(d.metadata, '$.company_name') END AS own_company, " +
503
505
  "CASE WHEN json_valid(d.metadata) THEN json_extract(d.metadata, '$.contact_name') END AS own_contact " +
504
506
  `FROM ${TABLES[kind]} d LEFT JOIN accounts a ON a.id = d.account_id ` +
@@ -516,6 +518,10 @@ export const dealOperationsOver = (context) => {
516
518
  ...[row.own_contact, ...(contacts.get(Number(row.id)) ?? [])]
517
519
  .filter((text) => typeof text === "string")
518
520
  .map((text) => ({ part: "contact", words: wordsOf(text) })),
521
+ ...(activities.get(`${row.account_id}\u0000${row.external_id}`) ?? []).map((text) => ({
522
+ part: "activity",
523
+ words: wordsOf(text),
524
+ })),
519
525
  ],
520
526
  }));
521
527
  });
@@ -1,6 +1,7 @@
1
1
  import { accessSync, constants, existsSync, mkdirSync, statSync, writeFileSync } from "node:fs";
2
2
  import { dirname } from "node:path";
3
3
  import { CliError } from "@wirecat/cli-base";
4
+ import { sqliteCode } from "../../errors/failures.js";
4
5
  import { DEFAULT_DECISION_POLICY } from "../decisions.js";
5
6
  import { noteShmWithoutWal, watchJournal } from "../journal.js";
6
7
  import { refuseDamagedStore } from "../marks.js";
@@ -71,6 +72,16 @@ const openReadable = async (file, options) => {
71
72
  throw error;
72
73
  }
73
74
  };
75
+ const SQLITE_CANTOPEN = 14;
76
+ /** A store path SQLite cannot open, such as a folder, is the owner's setting to fix, not a bug (BUG-753). */
77
+ const unopenable = (error, file) => {
78
+ const cannot = sqliteCode(error) === SQLITE_CANTOPEN ||
79
+ (error instanceof Error && /unable to open database file/.test(error.message));
80
+ if (!cannot)
81
+ return error;
82
+ const message = `the store at ${file} cannot be opened: it is a folder, or this user may not open it`;
83
+ return new CliError("configuration_error", message, { reason: "store.unopenable", path: file });
84
+ };
74
85
  export const openStoreContext = async (options = {}) => {
75
86
  const { path, env, now = Date.now, command, version, warn = (line) => process.stderr.write(`${line}\n`), readOnly = false, decisions = DEFAULT_DECISION_POLICY, } = options;
76
87
  if (typeof readOnly !== "boolean")
@@ -87,7 +98,9 @@ export const openStoreContext = async (options = {}) => {
87
98
  refuseDamagedStore(file, command);
88
99
  noteShmWithoutWal(file, command ?? "unknown");
89
100
  }
90
- const opened = readOnly ? await openReadable(file, options) : await openSqlite(file, { readOnly });
101
+ const opened = await (readOnly ? openReadable(file, options) : openSqlite(file, { readOnly })).catch((error) => {
102
+ throw unopenable(error, file);
103
+ });
91
104
  const database = opened.database;
92
105
  try {
93
106
  if (!readOnly) {
@@ -0,0 +1,12 @@
1
+ import { type Projection, type ProjectionTools } from "./record-projection.js";
2
+ /** A document of the envelope's own account under the record's external id: changed text is its next revision. */
3
+ declare const saveDocument: (projection: Projection, { context }: ProjectionTools) => string;
4
+ export declare const DOCUMENT_PROJECTORS: {
5
+ readonly document: {
6
+ readonly create: typeof saveDocument;
7
+ readonly update: (_ref: string, projection: Projection, tools: ProjectionTools) => true;
8
+ readonly remove: (ref: string, { context }: ProjectionTools) => void;
9
+ readonly restore: (_ref: string, projection: Projection, tools: ProjectionTools) => void;
10
+ };
11
+ };
12
+ export {};
@@ -0,0 +1,81 @@
1
+ import { documentWritesOver } from "./added-sources.js";
2
+ import { linkKind } from "./link-kinds.js";
3
+ import { requiredThing } from "./notes.js";
4
+ import { given } from "./record-projection.js";
5
+ const TEXT_ONLY = { storage: "text", localPath: null };
6
+ const textOf = ({ fields, externalId }) => {
7
+ const text = String(fields.text ?? "");
8
+ return {
9
+ kind: "text",
10
+ title: given(fields, "title") ?? externalId.slice(0, 500),
11
+ fileName: null,
12
+ extension: null,
13
+ url: given(fields, "url") ?? null,
14
+ mime: null,
15
+ size: null,
16
+ hash: null,
17
+ text,
18
+ extraction: text ? "text" : "none",
19
+ metadata: null,
20
+ language: null,
21
+ };
22
+ };
23
+ const momentOf = (fields, name) => {
24
+ const at = Date.parse(given(fields, name) ?? "");
25
+ return Number.isNaN(at) ? null : at;
26
+ };
27
+ /** The import's own `about` links, written again from the record each time; the owner's stay as they are. */
28
+ const relinkAbout = ({ database, now }, id, subjects) => {
29
+ database
30
+ .prepare(`DELETE FROM links WHERE from_type = 'document' AND from_id = ? AND kind = ${linkKind("about")} AND source = 'import'`)
31
+ .run(id);
32
+ const at = now();
33
+ for (const subject of subjects) {
34
+ const thing = requiredThing(database, subject, "a subject");
35
+ database
36
+ .prepare(`INSERT OR IGNORE INTO links (from_type, from_id, to_type, to_id, kind, source, confirmed, created_at, author,
37
+ updated_at) VALUES ('document', ?, ?, ?, ${linkKind("about")}, 'import', 1, ?, 'import', ?)`)
38
+ .run(id, thing.type, thing.id, at, at);
39
+ }
40
+ };
41
+ /** A document of the envelope's own account under the record's external id: changed text is its next revision. */
42
+ const saveDocument = (projection, { context }) => {
43
+ const { database } = context;
44
+ const writes = documentWritesOver(context);
45
+ const document = textOf(projection);
46
+ const at = context.now();
47
+ const own = database
48
+ .prepare("SELECT * FROM documents WHERE account_id = ? AND external_id = ?")
49
+ .get(projection.accountId, projection.externalId);
50
+ let id;
51
+ if (own === undefined)
52
+ id = writes.insert(projection.accountId, projection.externalId, document, TEXT_ONLY, at);
53
+ else {
54
+ id = Number(own.id);
55
+ if (own.deleted_at != null)
56
+ writes.revive(id, document, TEXT_ONLY, at);
57
+ else
58
+ writes.update(own, document, at, String(own.body ?? "") !== document.text);
59
+ }
60
+ database
61
+ .prepare("UPDATE documents SET external_created_at = ?, external_updated_at = ? WHERE id = ?")
62
+ .run(momentOf(projection.fields, "created_at"), momentOf(projection.fields, "updated_at"), id);
63
+ writes.place(id, at, document.title ?? projection.externalId);
64
+ relinkAbout(context, id, projection.related.get("about") ?? []);
65
+ return `document:${id}`;
66
+ };
67
+ export const DOCUMENT_PROJECTORS = {
68
+ document: {
69
+ create: saveDocument,
70
+ update: (_ref, projection, tools) => {
71
+ saveDocument(projection, tools);
72
+ return true;
73
+ },
74
+ remove: (ref, { context }) => {
75
+ documentWritesOver(context).remove(requiredThing(context.database, ref).id, context.now());
76
+ },
77
+ restore: (_ref, projection, tools) => {
78
+ saveDocument(projection, tools);
79
+ },
80
+ },
81
+ };
@@ -1,4 +1,5 @@
1
1
  import { DIRECT_PROJECTORS } from "./record-projectors-direct.js";
2
+ import { DOCUMENT_PROJECTORS } from "./record-projectors-document.js";
2
3
  import { MONEY_PROJECTORS } from "./record-projectors-money.js";
3
4
  import { PHONE_PROJECTORS } from "./record-projectors-phone.js";
4
5
  /** One projector per registered type; `null` for the types whose entity is matched or made from identifiers. */
@@ -6,6 +7,7 @@ export const RECORD_PROJECTORS = {
6
7
  ...MONEY_PROJECTORS,
7
8
  ...DIRECT_PROJECTORS,
8
9
  ...PHONE_PROJECTORS,
10
+ ...DOCUMENT_PROJECTORS,
9
11
  person: null,
10
12
  organization: null,
11
13
  project: null,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.647.0",
3
+ "version": "0.649.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",
@@ -183,6 +183,10 @@
183
183
  "types": "./dist/update/index.d.ts",
184
184
  "default": "./dist/update/index.js"
185
185
  },
186
+ "./sftp": {
187
+ "types": "./dist/sftp/index.d.ts",
188
+ "default": "./dist/sftp/index.js"
189
+ },
186
190
  "./oauth": {
187
191
  "types": "./dist/oauth/index.d.ts",
188
192
  "default": "./dist/oauth/index.js"
@@ -277,8 +281,9 @@
277
281
  "@types/mdast": "4.0.4",
278
282
  "@types/node": "^22.20.5",
279
283
  "@types/pngjs": "6.0.5",
284
+ "@types/ssh2": "1.15.5",
280
285
  "@vitest/coverage-v8": "^5.0.5",
281
- "@wirecat/cli-base": "0.97.0",
286
+ "@wirecat/cli-base": "0.98.0",
282
287
  "@wirecat/cli-core-legacy-tags": "npm:@wirecat/cli-core@0.414.0",
283
288
  "ajv": "8.17.1",
284
289
  "commander": "15.0.0",
@@ -291,6 +296,7 @@
291
296
  "libphonenumber-js": "1.13.15",
292
297
  "markdownlint-cli2": "0.24.0",
293
298
  "pngjs": "7.0.0",
299
+ "ssh2": "1.17.0",
294
300
  "typescript": "^7.0.2",
295
301
  "vitest": "^5.0.5"
296
302
  },
@@ -299,8 +305,9 @@
299
305
  },
300
306
  "peerDependencies": {
301
307
  "@napi-rs/canvas": ">=0.1.69 <2",
302
- "@wirecat/cli-base": ">=0.80.7 <1.0.0",
303
- "commander": ">=15"
308
+ "@wirecat/cli-base": ">=0.98.0 <1.0.0",
309
+ "commander": ">=15",
310
+ "ssh2": "^1.17.0"
304
311
  },
305
312
  "bin": {
306
313
  "cli-core-parity": "dist/parity/bin.js"
@@ -308,6 +315,9 @@
308
315
  "peerDependenciesMeta": {
309
316
  "@napi-rs/canvas": {
310
317
  "optional": true
318
+ },
319
+ "ssh2": {
320
+ "optional": true
311
321
  }
312
322
  }
313
323
  }
package/parity.json CHANGED
@@ -3199,16 +3199,10 @@
3199
3199
  "in": "all"
3200
3200
  },
3201
3201
  "flood": {
3202
- "in": ["max", "tg"],
3203
- "planned": {
3204
- "wa": "wa backlog: mount the shared flood command"
3205
- }
3202
+ "in": "all"
3206
3203
  },
3207
3204
  "flood clear": {
3208
- "in": ["max", "tg"],
3209
- "planned": {
3210
- "wa": "wa backlog: mount the shared flood command"
3211
- }
3205
+ "in": "all"
3212
3206
  },
3213
3207
  "guide": {
3214
3208
  "in": ["max", "tg"],
@@ -4798,9 +4792,6 @@
4798
4792
  "--by": {
4799
4793
  "in": "all"
4800
4794
  },
4801
- "--chat": {
4802
- "in": "all"
4803
- },
4804
4795
  "--timezone": {
4805
4796
  "in": "all"
4806
4797
  },
@@ -74,7 +74,7 @@
74
74
  },
75
75
  "type": {
76
76
  "type": "string",
77
- "pattern": "^(invoice|payment|person|organization|project|order|product|contract|subscription|wallet|transaction|deal|lead|message|event|pipeline|custom:[a-z0-9][a-z0-9_-]{0,62})$"
77
+ "pattern": "^(invoice|payment|person|organization|project|order|product|contract|subscription|wallet|transaction|deal|lead|message|event|document|pipeline|custom:[a-z0-9][a-z0-9_-]{0,62})$"
78
78
  },
79
79
  "external_id": {
80
80
  "type": "string",
@@ -357,6 +357,23 @@
357
357
  }
358
358
  }
359
359
  },
360
+ {
361
+ "if": {
362
+ "properties": {
363
+ "type": {
364
+ "const": "document"
365
+ }
366
+ },
367
+ "required": ["type"]
368
+ },
369
+ "then": {
370
+ "properties": {
371
+ "fields": {
372
+ "$ref": "#/$defs/fields-document"
373
+ }
374
+ }
375
+ }
376
+ },
360
377
  {
361
378
  "if": {
362
379
  "properties": {
@@ -395,7 +412,7 @@
395
412
  },
396
413
  "type": {
397
414
  "type": "string",
398
- "pattern": "^(invoice|payment|person|organization|project|order|product|contract|subscription|wallet|transaction|deal|lead|message|event|pipeline|custom:[a-z0-9][a-z0-9_-]{0,62})$"
415
+ "pattern": "^(invoice|payment|person|organization|project|order|product|contract|subscription|wallet|transaction|deal|lead|message|event|document|pipeline|custom:[a-z0-9][a-z0-9_-]{0,62})$"
399
416
  },
400
417
  "external_id": {
401
418
  "type": "string",
@@ -1215,6 +1232,44 @@
1215
1232
  "required": ["kind", "direction", "phone", "started_at"],
1216
1233
  "additionalProperties": true
1217
1234
  },
1235
+ "fields-document": {
1236
+ "type": "object",
1237
+ "properties": {
1238
+ "title": {
1239
+ "type": ["string", "null"],
1240
+ "minLength": 1,
1241
+ "maxLength": 500,
1242
+ "description": "What the document is called; its external id when left out"
1243
+ },
1244
+ "text": {
1245
+ "type": "string",
1246
+ "maxLength": 1000000,
1247
+ "description": "The text search reads"
1248
+ },
1249
+ "created_at": {
1250
+ "type": ["string", "null"],
1251
+ "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}(:[0-9]{2}(\\.[0-9]{1,9})?)?(Z|[+-][0-9]{2}:[0-9]{2})$",
1252
+ "description": "When the source made it"
1253
+ },
1254
+ "updated_at": {
1255
+ "type": ["string", "null"],
1256
+ "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}(:[0-9]{2}(\\.[0-9]{1,9})?)?(Z|[+-][0-9]{2}:[0-9]{2})$",
1257
+ "description": "When the source last changed it: what date: reads"
1258
+ },
1259
+ "url": {
1260
+ "type": ["string", "null"],
1261
+ "minLength": 1,
1262
+ "maxLength": 4096,
1263
+ "description": "Where the original is"
1264
+ },
1265
+ "metadata": {
1266
+ "type": ["object", "null"],
1267
+ "description": "Anything else the source knows about it, kept as sent"
1268
+ }
1269
+ },
1270
+ "required": ["text"],
1271
+ "additionalProperties": true
1272
+ },
1218
1273
  "fields-pipeline": {
1219
1274
  "type": "object",
1220
1275
  "properties": {