@wirecat/cli-core 0.720.0 → 0.722.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 (85) hide show
  1. package/CHANGELOG.md +106 -0
  2. package/dist/cli/config-command.js +8 -2
  3. package/dist/cli/config-issues.d.ts +3 -1
  4. package/dist/cli/config-issues.js +9 -2
  5. package/dist/cli/documents/file-conflicts.d.ts +25 -0
  6. package/dist/cli/documents/file-conflicts.js +102 -0
  7. package/dist/cli/documents/file-edit.d.ts +29 -0
  8. package/dist/cli/documents/file-edit.js +352 -0
  9. package/dist/cli/documents/file-update.d.ts +43 -0
  10. package/dist/cli/documents/file-update.js +95 -0
  11. package/dist/cli/documents/history.d.ts +34 -0
  12. package/dist/cli/documents/history.js +89 -0
  13. package/dist/cli/documents/index.d.ts +9 -2
  14. package/dist/cli/documents/index.js +9 -2
  15. package/dist/cli/documents/library.js +10 -0
  16. package/dist/cli/messenger/lacks.d.ts +2 -1
  17. package/dist/cli/messenger/lacks.js +14 -1
  18. package/dist/cli/permission-keys.d.ts +6 -0
  19. package/dist/cli/permission-keys.js +15 -3
  20. package/dist/cli/service-api.d.ts +1 -1
  21. package/dist/cli/service-api.js +16 -34
  22. package/dist/cli/token-session.d.ts +2 -1
  23. package/dist/cli/token-session.js +2 -2
  24. package/dist/crm/cli/account.d.ts +60 -0
  25. package/dist/crm/cli/account.js +147 -0
  26. package/dist/crm/cli/files.js +2 -1
  27. package/dist/crm/cli/index.d.ts +3 -0
  28. package/dist/crm/cli/index.js +4 -0
  29. package/dist/crm/foreign-contacts.js +2 -1
  30. package/dist/crm/state-folders.d.ts +5 -0
  31. package/dist/crm/state-folders.js +2 -0
  32. package/dist/documents/file-mirror-model.d.ts +18 -1
  33. package/dist/documents/index.d.ts +7 -4
  34. package/dist/documents/index.js +4 -1
  35. package/dist/documents/model.d.ts +16 -1
  36. package/dist/errors/reasons.d.ts +1 -1
  37. package/dist/errors/reasons.js +15 -0
  38. package/dist/services/documents/block-diff.d.ts +13 -3
  39. package/dist/services/documents/block-diff.js +13 -7
  40. package/dist/services/documents/ingestion.d.ts +21 -2
  41. package/dist/services/documents/ingestion.js +29 -2
  42. package/dist/services/documents/plan.js +16 -7
  43. package/dist/services/documents/ports.d.ts +2 -0
  44. package/dist/services/documents/sync.d.ts +1 -0
  45. package/dist/services/documents/sync.js +9 -4
  46. package/dist/services/files/conflicts.d.ts +78 -0
  47. package/dist/services/files/conflicts.js +183 -0
  48. package/dist/services/files/guarded-write.d.ts +34 -0
  49. package/dist/services/files/guarded-write.js +42 -0
  50. package/dist/services/files/listing.d.ts +8 -0
  51. package/dist/services/files/listing.js +1 -1
  52. package/dist/services/files/local-files.d.ts +54 -0
  53. package/dist/services/files/local-files.js +143 -0
  54. package/dist/services/files/mirror-state.d.ts +14 -0
  55. package/dist/services/files/mirror-state.js +65 -0
  56. package/dist/services/files/mirror.d.ts +8 -15
  57. package/dist/services/files/mirror.js +164 -205
  58. package/dist/services/files/text-merge.d.ts +27 -0
  59. package/dist/services/files/text-merge.js +134 -0
  60. package/dist/services/files/versions.d.ts +36 -9
  61. package/dist/services/files/versions.js +40 -12
  62. package/dist/services/metadata.d.ts +1 -1
  63. package/dist/store/index.d.ts +2 -0
  64. package/dist/store/index.js +1 -0
  65. package/dist/store/sqlite/account-purge.js +3 -0
  66. package/dist/store/sqlite/crm-stage-entries.js +4 -1
  67. package/dist/store/sqlite/document-history.d.ts +84 -0
  68. package/dist/store/sqlite/document-history.js +158 -0
  69. package/dist/store/sqlite/erase-plan.d.ts +19 -0
  70. package/dist/store/sqlite/erase-plan.js +74 -0
  71. package/dist/store/sqlite/manifest.js +2 -0
  72. package/dist/store/sqlite/messages.js +2 -1
  73. package/dist/store/sqlite/migrations.generated.js +17 -0
  74. package/dist/store/sqlite/notes.d.ts +9 -10
  75. package/dist/store/sqlite/notes.js +33 -21
  76. package/dist/store/sqlite/organization-erase.d.ts +29 -0
  77. package/dist/store/sqlite/organization-erase.js +83 -0
  78. package/dist/store/sqlite/organizations.d.ts +10 -1
  79. package/dist/store/sqlite/organizations.js +6 -1
  80. package/dist/store/sqlite/person-erase.js +4 -45
  81. package/dist/store/sqlite/schema/document-changes.d.ts +136 -0
  82. package/dist/store/sqlite/schema/document-changes.js +11 -0
  83. package/dist/store/sqlite/schema.d.ts +65 -0
  84. package/dist/store/sqlite/schema.js +5 -0
  85. package/package.json +3 -3
@@ -1,13 +1,18 @@
1
1
  import { addDocumentCatalogCommands } from "./catalog.js";
2
2
  import { addLocalDocumentCommands } from "./documents.js";
3
3
  import { addDocumentFolderCommands } from "./folders.js";
4
+ import { addDocumentHistoryCommands } from "./history.js";
4
5
  import { addDocumentKnowledgeCommands } from "./knowledge.js";
5
6
  import { addDocumentMirrorCommands } from "./mirrors.js";
6
7
  import { addDocumentSearchCommand } from "./search.js";
7
8
  import { addDocumentSyncCommands } from "./sync.js";
8
9
  export { addDocumentCatalogCommands, CATALOG_FIELDS, catalogId, catalogOutput, catalogSource, catalogTree, } from "./catalog.js";
9
10
  export { addLocalDocumentCommands } from "./documents.js";
11
+ export { fileConflictsCommand } from "./file-conflicts.js";
12
+ export { addFileEditCommands } from "./file-edit.js";
13
+ export { addFileUpdateCommand } from "./file-update.js";
10
14
  export { addDocumentFolderCommands } from "./folders.js";
15
+ export { addDocumentHistoryCommands, DOCUMENT_HISTORY_SETTINGS, keepVersionsForDays, } from "./history.js";
11
16
  export { addDocumentKnowledgeCommands, } from "./knowledge.js";
12
17
  export { addDocumentMirrorCommands } from "./mirrors.js";
13
18
  export { documentQueries, FACT_QUERY, factItem, folderRow, IDENTITY_ROLES, identityRow, linkRow, MEMORY_QUERY, MEMORY_SEARCH_QUERY, memoryItem, memorySearch, mirrorRow, tagRow, } from "./queries.js";
@@ -15,14 +20,16 @@ export { addDocumentSearchCommand } from "./search.js";
15
20
  export { addDocumentSyncCommands } from "./sync.js";
16
21
  export { ageOf, staleCopy } from "./words.js";
17
22
  /**
18
- * `folders`, `sync`, `status`, `documents list|show|export|context`, `search`, `catalog`, the knowledge groups and,
19
- * when given, `mirrors`, in that order. Answers the `documents` group, for the CLI's live subcommands.
23
+ * `folders`, `sync`, `status`, `documents list|show|export|context`, when given `documents history` and `changes`,
24
+ * `search`, `catalog`, the knowledge groups and, when given, `mirrors`, in that order. Answers the `documents` group, for the CLI's live subcommands.
20
25
  */
21
26
  export const addDocumentCommands = (program, options) => {
22
27
  const shared = { words: options.words, output: options.output };
23
28
  addDocumentFolderCommands(program, { ...shared, ...options.folders });
24
29
  addDocumentSyncCommands(program, { ...shared, ...options.sync });
25
30
  const documents = addLocalDocumentCommands(program, { ...shared, ...options.documents });
31
+ if (options.history)
32
+ addDocumentHistoryCommands(program, { ...shared, ...options.history });
26
33
  addDocumentSearchCommand(program, { ...shared, ...options.search });
27
34
  addDocumentCatalogCommands(program, { ...shared, ...options.catalog });
28
35
  addDocumentKnowledgeCommands(program, { ...shared, ...options.knowledge });
@@ -22,6 +22,7 @@ import { ProfileTokenStore } from "../profile-token.js";
22
22
  import { addDocumentCatalogCommands } from "./catalog.js";
23
23
  import { addLocalDocumentCommands } from "./documents.js";
24
24
  import { addDocumentFolderCommands } from "./folders.js";
25
+ import { addDocumentHistoryCommands, keepVersionsForDays } from "./history.js";
25
26
  import { addDocumentKnowledgeCommands } from "./knowledge.js";
26
27
  import { factItem, memoryItem } from "./queries.js";
27
28
  import { addDocumentSearchCommand } from "./search.js";
@@ -351,6 +352,7 @@ export const documentLibraryCommands = (options) => {
351
352
  errorOf,
352
353
  assertHeld,
353
354
  storeVersion: app.version,
355
+ keepVersionsForDays: keepVersionsForDays(context().settings),
354
356
  ...(environmentOf(command()).signal ? { signal: environmentOf(command()).signal } : {}),
355
357
  ...(rescan ? { rescan } : {}),
356
358
  ...(budget ? { budget } : {}),
@@ -421,6 +423,13 @@ export const documentLibraryCommands = (options) => {
421
423
  },
422
424
  lastSync: () => files().state("").read().lastSync,
423
425
  },
426
+ history: {
427
+ run: (fn) => {
428
+ const account = principal();
429
+ return withStore(false, (store) => fn(options.ingestion(store).history, account));
430
+ },
431
+ id: (input) => options.idOf(input),
432
+ },
424
433
  search: {
425
434
  search: (query, searchOptions) => {
426
435
  const account = principal();
@@ -509,6 +518,7 @@ export const documentLibraryCommands = (options) => {
509
518
  addDocumentFolderCommands(holder, { ...shared, ...groups.folders });
510
519
  addDocumentSyncCommands(holder, { ...shared, ...groups.sync });
511
520
  addLocalDocumentCommands(holder, { ...shared, ...groups.documents });
521
+ addDocumentHistoryCommands(holder, { ...shared, ...groups.history });
512
522
  addDocumentSearchCommand(holder, { ...shared, ...groups.search });
513
523
  addDocumentCatalogCommands(holder, { ...shared, ...groups.catalog });
514
524
  addDocumentKnowledgeCommands(holder, { ...shared, ...groups.knowledge });
@@ -20,7 +20,8 @@ export declare const lackedNeed: (messenger: Lacking | undefined, path: string)
20
20
  export declare const refuseLacking: (messenger: Lacking | undefined, path: readonly string[]) => void;
21
21
  /**
22
22
  * Hides under `group` each command whose one method this messenger can `never` have, from help, `commands` and MCP;
23
- * typed anyway, it still refuses. A method it only `lacks` keeps its command in sight, since it may come.
23
+ * typed anyway, it still refuses. A group left with nothing in sight is hidden too, since an empty group lists
24
+ * nothing to run. A method it only `lacks` keeps its command in sight, since it may come.
24
25
  */
25
26
  export declare const hideNever: <T extends Command>(messenger: Lacking, group: T) => T;
26
27
  export {};
@@ -15,10 +15,20 @@ export const COMMAND_NEEDS = {
15
15
  "chats folders create": ["createFolder", "create a folder"],
16
16
  "chats folders update": ["updateFolder", "change a folder"],
17
17
  "chats folders delete": ["deleteFolder", "delete a folder"],
18
+ "chats links show": ["group", "read a group"],
19
+ "chats links reset": ["resetInviteLink", "replace an invite link"],
20
+ "chats requests list": ["joinRequests", "read join requests"],
21
+ "chats requests confirm": ["answerJoinRequest", "answer join requests"],
22
+ "chats requests reject": ["answerJoinRequest", "answer join requests"],
23
+ "chats admins add": ["addAdmin", "make someone an admin"],
24
+ "chats admins remove": ["removeAdmin", "take admin rights back"],
18
25
  "contacts add": ["addContact", "add a contact"],
19
26
  "contacts remove": ["removeContact", "remove a contact"],
20
27
  "contacts rename": ["renameContact", "rename a contact"],
21
28
  "contacts import": ["importContacts", "import contacts"],
29
+ "contacts block": ["block", "block a person"],
30
+ "contacts unblock": ["unblock", "unblock a person"],
31
+ "messages forward": ["forward", "forward a message"],
22
32
  "messages comments": ["comments", "read comments on a channel post"],
23
33
  "messages pin": ["pin", "pin a message"],
24
34
  "messages unpin": ["unpin", "unpin a message"],
@@ -47,7 +57,8 @@ export const refuseLacking = (messenger, path) => {
47
57
  };
48
58
  /**
49
59
  * Hides under `group` each command whose one method this messenger can `never` have, from help, `commands` and MCP;
50
- * typed anyway, it still refuses. A method it only `lacks` keeps its command in sight, since it may come.
60
+ * typed anyway, it still refuses. A group left with nothing in sight is hidden too, since an empty group lists
61
+ * nothing to run. A method it only `lacks` keeps its command in sight, since it may come.
51
62
  */
52
63
  export const hideNever = (messenger, group) => {
53
64
  const walk = (command, path) => {
@@ -57,6 +68,8 @@ export const hideNever = (messenger, group) => {
57
68
  if (need && messenger.never?.includes(need[0]))
58
69
  child._hidden = true;
59
70
  walk(child, at);
71
+ if (child.commands.length > 0 && child.commands.every((one) => one._hidden))
72
+ child._hidden = true;
60
73
  }
61
74
  };
62
75
  walk(group, [group.name()]);
@@ -35,6 +35,12 @@ export declare const commandPermissions: ({ keyOf, extra, defaults, alsoChecks,
35
35
  * parents. A key outside it is a typo that would otherwise do nothing (BUG-137).
36
36
  */
37
37
  export declare const knownPermissionKeys: (command: Command, keyOf?: PermissionKeySource, extra?: readonly PermissionKey[]) => Set<PermissionKey>;
38
+ /**
39
+ * Old keys of commands that moved, on the group that moved them (the generated `api` group, `api.contacts-list` →
40
+ * `api.contacts.list`): such a key is still refused like any unknown one (WC-CMD-8), and the refusal names the new key.
41
+ */
42
+ export declare const markRenamedPermissionKeys: (command: Command, renamed: ReadonlyMap<PermissionKey, PermissionKey>) => void;
43
+ export declare const renamedPermissionKeys: (command: Command) => Map<PermissionKey, PermissionKey>;
38
44
  /** The known keys one level under the unknown key's parent, to name in the refusal. */
39
45
  export declare const knownBeside: (key: PermissionKey, known: ReadonlySet<PermissionKey>) => PermissionKey[];
40
46
  export declare const unknownPermissionKeys: (levels: Readonly<Record<PermissionKey, unknown>>, known: ReadonlySet<PermissionKey>) => PermissionKey[];
@@ -67,6 +67,16 @@ export const knownPermissionKeys = (command, keyOf = (one) => keyForCommand(path
67
67
  add(key);
68
68
  return known;
69
69
  };
70
+ const RENAMED = new WeakMap();
71
+ /**
72
+ * Old keys of commands that moved, on the group that moved them (the generated `api` group, `api.contacts-list` →
73
+ * `api.contacts.list`): such a key is still refused like any unknown one (WC-CMD-8), and the refusal names the new key.
74
+ */
75
+ export const markRenamedPermissionKeys = (command, renamed) => {
76
+ if (renamed.size > 0)
77
+ RENAMED.set(command, renamed);
78
+ };
79
+ export const renamedPermissionKeys = (command) => new Map(everyCommand(rootOf(command)).flatMap((one) => [...(RENAMED.get(one) ?? [])]));
70
80
  /** The known keys one level under the unknown key's parent, to name in the refusal. */
71
81
  export const knownBeside = (key, known) => {
72
82
  const parent = key.split(".").slice(0, -1).join(".");
@@ -82,7 +92,7 @@ export const unknownPermissionIssues = (command, settings, tool, keyOf) => {
82
92
  Object.keys(settings.permissions)
83
93
  .filter((key) => key !== CEILING_KEY && settings.permissionSources[key] !== "flag")
84
94
  .map((key) => ({ key, at: ["profiles", settings.profile, "permissions", key] }));
85
- return permissionIssues(saved, knownPermissionKeys(command, keyOf), { file: settings.configPath, tool }).map(publicIssue);
95
+ return permissionIssues(saved, knownPermissionKeys(command, keyOf), { file: settings.configPath, tool }, renamedPermissionKeys(command)).map(publicIssue);
86
96
  };
87
97
  /**
88
98
  * A saved key no command checks would do nothing, so the command refuses to run and names the unset that removes
@@ -94,6 +104,8 @@ export const refuseUnknownPermissionKeys = (command, settings, tool, keyOf) => {
94
104
  throw new CliError("configuration_error", issueMessage(issues), { permission: issues[0]?.key });
95
105
  const flagged = Object.keys(settings.permissions).filter((key) => settings.permissionSources[key] === "flag");
96
106
  const [key] = unknownPermissionKeys(Object.fromEntries(flagged.map((one) => [one, true])), knownPermissionKeys(command, keyOf));
97
- if (key !== undefined)
98
- throw new CliError("validation_error", `--permission ${key} names no command`, { permission: key });
107
+ if (key === undefined)
108
+ return;
109
+ const now = renamedPermissionKeys(command).get(key);
110
+ throw new CliError("validation_error", `--permission ${key} names no command${now === undefined ? "" : `: its command moved, so use ${now}`}`, { permission: key });
99
111
  };
@@ -6,7 +6,7 @@ import type * as v from "valibot";
6
6
  import type { AppIdentity } from "../ports/app.js";
7
7
  import type { Level, PermissionKey } from "../sends/permissions.js";
8
8
  import { type ApiCommandInput } from "./bot/api.js";
9
- import type { ConditionalKey } from "./permission-keys.js";
9
+ import { type ConditionalKey } from "./permission-keys.js";
10
10
  import { type ServiceApiManifest } from "./service-api-manifest.js";
11
11
  import type { Configuration } from "./settings.js";
12
12
  /** A key a call's body implies in a way no flag names, as notion's `agent-batch` with an action `delete`. */
@@ -15,6 +15,7 @@ import { NO_EFFECTS } from "./effects.js";
15
15
  import { itemOf, listOf, renderAnswer } from "./envelope.js";
16
16
  import { queryTerms, termField, withQuery } from "./list-query.js";
17
17
  import { terminalAsker } from "./messenger/ask.js";
18
+ import { markRenamedPermissionKeys } from "./permission-keys.js";
18
19
  import { manifestBaseUrl, nextPage, parameterValue, signRequest, underBase, } from "./service-api-manifest.js";
19
20
  /**
20
21
  * The operations the `api` group offers, and why it leaves out the rest: one that answers with a credential needs a
@@ -38,9 +39,8 @@ const keyOf = (operation) => ["api", ...apiPathOf(operation)].join(".");
38
39
  /** `contacts list`: what follows `api` on the command line. */
39
40
  const pathOf = (operation) => apiPathOf(operation).join(" ");
40
41
  /**
41
- * The key a grouped operation had while `api` was flat, `api.contacts-list`. A profile that still names it keeps its
42
- * hold on that one command: checked beside the new key, it only ever tightens. A group never takes an old command's
43
- * name (the generator refuses it), so the old key never reaches past its command.
42
+ * The key a grouped operation had while `api` was flat, `api.contacts-list`. It checks nothing now: a config that still
43
+ * names it is refused as an unknown key, and the refusal names the new key (WC-CMD-8).
44
44
  */
45
45
  const formerKeyOf = (operation) => {
46
46
  const former = `api.${operation.command}`;
@@ -100,27 +100,18 @@ export const serviceApiKeys = (input, operation, call) => {
100
100
  */
101
101
  export const serviceApiPermissions = (input) => {
102
102
  const checks = new Map();
103
- const former = [];
104
103
  for (const operation of input.manifest.operations) {
105
- const old = formerKeyOf(operation);
106
- if (old)
107
- former.push(old);
108
104
  checks.set(pathOf(operation), [
109
105
  ...permissionsOf(operation).map((permission) => {
110
106
  const when = whenOf(permission);
111
107
  return when === undefined ? permission.key : { key: permission.key, when };
112
108
  }),
113
109
  ...(input.bodyPermissions?.[operation.command] ?? []).map(({ key, when }) => ({ key, when })),
114
- ...(old ? [{ key: old, when: "while a profile still names this old key" }] : []),
115
110
  ]);
116
111
  }
117
- const keys = [
118
- ...new Set([...checks.values()]
119
- .flat()
120
- .flatMap((one) => (typeof one === "string" ? [one] : former.includes(one.key) ? [] : [one.key]))),
121
- ];
112
+ const keys = [...new Set([...checks.values()].flat().map((one) => (typeof one === "string" ? one : one.key)))];
122
113
  return {
123
- extra: [...keys, ...former],
114
+ extra: keys,
124
115
  alsoChecks: (path) => (path[0] === "api" ? (checks.get(path.slice(1).join(" ")) ?? []) : []),
125
116
  defaults: {
126
117
  ...Object.fromEntries(keys.map((key) => [key, "ask"])),
@@ -252,22 +243,10 @@ const serviceApiCore = (options) => {
252
243
  throw error;
253
244
  }
254
245
  };
255
- /** The old flat key, when the profile names it: on a read only its refusal or its question applies. */
256
- const formerKeys = (command, operation) => {
257
- const former = formerKeyOf(operation);
258
- if (!former)
259
- return [];
260
- const { settings, renderer } = baseContext(command, configuration.resolveSettings);
261
- const level = settings.permissions[former];
262
- if (level === undefined)
263
- return [];
264
- renderer.warn(`permissions name ${former}, the old key of api ${pathOf(operation)}: rename it to ${keyOf(operation)}`);
265
- return operation.effect === "read" && level !== "deny" && level !== "ask" ? [] : [former];
266
- };
267
246
  /**
268
247
  * The refusal `execute` would give, before the body is read: a `deny` stops a call whatever its input, and a missing
269
- * body must not answer `validation_error` in its place. Only the keys known without the body; the rest, and an old
270
- * flat key (which warns), wait for `execute`.
248
+ * body must not answer `validation_error` in its place. Only the keys known without the body; the rest wait for
249
+ * `execute`.
271
250
  */
272
251
  const refuseBeforeBody = (command, operation) => {
273
252
  const extra = permissionsOf(operation)
@@ -283,7 +262,6 @@ const serviceApiCore = (options) => {
283
262
  baseUrlOf,
284
263
  defaults,
285
264
  exchange,
286
- formerKeys,
287
265
  operationOf,
288
266
  readsFreely,
289
267
  refuseBeforeBody,
@@ -292,8 +270,8 @@ const serviceApiCore = (options) => {
292
270
  };
293
271
  };
294
272
  export const serviceApiCommand = (options) => {
295
- const { app, configuration } = options;
296
- const { operations, baseUrlOf, exchange, formerKeys, operationOf, readsFreely, refuseBeforeBody, signed, write } = serviceApiCore(options);
273
+ const { app, configuration, manifest } = options;
274
+ const { operations, baseUrlOf, exchange, operationOf, readsFreely, refuseBeforeBody, signed, write } = serviceApiCore(options);
297
275
  const send = async (command, operation, request) => (await exchange(command, operation, request)).answer;
298
276
  let schemas;
299
277
  const loaded = () => {
@@ -374,7 +352,7 @@ export const serviceApiCommand = (options) => {
374
352
  command.hook("preAction", load);
375
353
  },
376
354
  execute: async (command, operation, input) => {
377
- const extra = [...serviceApiKeys(options, operation, input), ...formerKeys(command, operation)];
355
+ const extra = serviceApiKeys(options, operation, input);
378
356
  const read = readsFreely(command, operation, extra);
379
357
  if (operation.pagination && command.opts().all === true) {
380
358
  if (!read)
@@ -422,6 +400,10 @@ export const serviceApiCommand = (options) => {
422
400
  group.addCommand(list).addCommand(show);
423
401
  for (const child of [...generated.commands])
424
402
  group.addCommand(child);
403
+ markRenamedPermissionKeys(group, new Map(manifest.operations.flatMap((operation) => {
404
+ const former = formerKeyOf(operation);
405
+ return former ? [[former, keyOf(operation)]] : [];
406
+ })));
425
407
  return group;
426
408
  };
427
409
  // Code may pass a number, a boolean or a list where a person types text; the check reads the text it stands for.
@@ -442,7 +424,7 @@ const writerBody = (operation, input, schemas) => {
442
424
  * can be asked. A read that no key guards goes through `serviceApiCall`.
443
425
  */
444
426
  export const serviceApiWriter = (options) => {
445
- const { baseUrlOf, formerKeys, operationOf, signed, write } = serviceApiCore(options);
427
+ const { baseUrlOf, operationOf, signed, write } = serviceApiCore(options);
446
428
  return async (command, name, input, { confirmed } = {}) => {
447
429
  const operation = operationOf(name);
448
430
  // The api group offers only declared parameters; code must not reach further, as WordPress's `_method` turns a
@@ -468,6 +450,6 @@ export const serviceApiWriter = (options) => {
468
450
  throw new CliError("validation_error", problem);
469
451
  }
470
452
  const request = await signed(command, operation, httpApiRequest(operation, writerBody(operation, input, schemas), baseUrlOf(command)));
471
- return write(command, operation, [...extra, ...formerKeys(command, operation)], request, confirmed);
453
+ return write(command, operation, extra, request, confirmed);
472
454
  };
473
455
  };
@@ -1,3 +1,4 @@
1
+ import { type KeyringStore } from "@wirecat/cli-base";
1
2
  import type { FetchLike } from "@wirecat/cli-base/http";
2
3
  import { Command } from "commander";
3
4
  import type { CliVerify } from "../manifest/index.js";
@@ -41,7 +42,7 @@ export interface TokenSessionOptions {
41
42
  * Keeps the account a profile signed in to; by default only remembers it. A CLI that refuses a taken one says so.
42
43
  * With `site`, `id` is `<site>:<id>`, the site as `--site` was cleaned.
43
44
  */
44
- claim?: (env: NodeJS.ProcessEnv, profile: string, id: string, tokens: ProfileTokenStore) => void;
45
+ claim?: (env: NodeJS.ProcessEnv, profile: string, id: string, tokens: ProfileTokenStore, keyring: KeyringStore | undefined) => void;
45
46
  /** What the token is, for the prompt and help: "API token" when not given. */
46
47
  token?: string;
47
48
  /** One sentence more for `session start --help`: which token, and what it can see. */
@@ -79,7 +79,7 @@ export const tokenSessionCommand = (options) => {
79
79
  if (options.site)
80
80
  start.option("--site <address>", `the ${service} site, as https://${options.site.example} or ${options.site.example}`);
81
81
  start.action(async function (args) {
82
- const { env, profile, tokens, run, renderer } = contextOf(this);
82
+ const { env, profile, tokens, run, renderer, keyring } = contextOf(this);
83
83
  refuseCommandName(profile, commandWords(rootOf(this)), app.command);
84
84
  if (options.site && args.site === undefined)
85
85
  throw new CliError("validation_error", `give the ${service} site: --site ${options.site.example}`);
@@ -102,7 +102,7 @@ export const tokenSessionCommand = (options) => {
102
102
  throw new CliError("validation_error", `no ${word} was given`);
103
103
  const token = login === undefined ? secret : `${login}:${secret}`;
104
104
  const { id, account } = await run((events) => options.verify(this, token, events, site));
105
- (options.claim ?? ((at, name, key) => rememberAccount(app, name, key, at)))(env, profile, siteAccount(site, id), tokens);
105
+ (options.claim ?? ((at, name, key) => rememberAccount(app, name, key, at)))(env, profile, siteAccount(site, id), tokens, keyring);
106
106
  const storedIn = tokens.write(profile, token, args.credentialStorage, site === undefined ? {} : { site });
107
107
  answer(this, { profile, state: "saved", stored_in: storedIn, verified: true, ...siteOf(site), ...account });
108
108
  });
@@ -0,0 +1,60 @@
1
+ import { type KeyringStore } from "@wirecat/cli-base";
2
+ import { Command } from "commander";
3
+ import { ProfileTokenStore } from "../../cli/profile-token.js";
4
+ import type { GlobalFlags, ResolveOptions, Settings } from "../../cli/settings.js";
5
+ import type { TokenSessionOptions } from "../../cli/token-session.js";
6
+ import type { AppIdentity } from "../../ports/app.js";
7
+ export interface CrmAccountContext {
8
+ env: NodeJS.ProcessEnv;
9
+ /** The run's keyring; `undefined` is the system one. */
10
+ keyring?: KeyringStore;
11
+ }
12
+ /** The CRM account a profile holds: `account` as the store names it, `user` where one account has several users. */
13
+ export interface CrmHeld {
14
+ account: string;
15
+ user?: string;
16
+ /** A sign-in is saved for the profile here. False: only what `session start` remembered outlives `session end`. */
17
+ signedIn: boolean;
18
+ }
19
+ /** `addCrmCommands`'s `account`: mounts `account remove`, which refuses `--delete-data` on an account others read. */
20
+ export interface CrmAccountOptions {
21
+ /** The store's provider name for the CRM, the `provider` of the account's `AccountKey`. */
22
+ provider: string;
23
+ /** The CRM's name, as the owner knows it: "HubSpot". */
24
+ service: string;
25
+ /**
26
+ * What a profile holds, from its saved sign-in or else from what `session start` remembered. Unset: the account
27
+ * `rememberAccount` recorded, signed in while a token is saved in the profile's entry. A CLI whose remembered
28
+ * account is not the store's name for it (bitrix24's and amo's `<host>:<userId>`) passes its own.
29
+ */
30
+ held?: (profile: string, context: CrmAccountContext) => CrmHeld | undefined;
31
+ /** What `account remove` says the sign-out removed, when the CRM keeps more than a token valid. */
32
+ signedOut?: (profile: string) => string;
33
+ /** Unset: the one `run()` set. `crmAccountClaim` needs it to see the profiles the configuration names. */
34
+ resolveSettings?: (flags: GlobalFlags, options?: ResolveOptions) => Settings;
35
+ }
36
+ type Tokens = Pick<ProfileTokenStore, "read">;
37
+ export interface CrmSignIn extends CrmAccountContext {
38
+ /** The profile signing in. */
39
+ profile: string;
40
+ /** The profiles the configuration names; those `session start` remembered are added. */
41
+ profiles?: readonly string[];
42
+ /** The run's token store, whose warnings go where the run's do. Unset: one that keeps them quiet. */
43
+ tokens?: Tokens;
44
+ }
45
+ /**
46
+ * Refuses a sign-in to an account and user another profile here is signed in to: two profiles would sync the same
47
+ * copy twice and split its permissions. A profile that ended its session no longer holds the account.
48
+ */
49
+ export declare const refuseTakenCrmAccount: (app: AppIdentity, options: CrmAccountOptions, { profile, profiles, tokens, ...context }: CrmSignIn, at: {
50
+ account: string;
51
+ user?: string;
52
+ }) => void;
53
+ /** `claim` for `tokenSessionCommand`: refuses an account another profile is signed in to, then remembers it. */
54
+ export declare const crmAccountClaim: (app: AppIdentity, options: CrmAccountOptions) => NonNullable<TokenSessionOptions["claim"]>;
55
+ /**
56
+ * `account remove` of a CRM CLI: cli-core's own, which refuses `--delete-data` while another profile here reads the
57
+ * same account, whose one copy the store shares. Under `--dry-run` it warns instead.
58
+ */
59
+ export declare const crmAccountCommand: (app: AppIdentity, options: CrmAccountOptions) => Command;
60
+ export {};
@@ -0,0 +1,147 @@
1
+ import { join } from "node:path";
2
+ import { CliError, resolvePaths } from "@wirecat/cli-base";
3
+ import { annotate } from "@wirecat/cli-base/commands";
4
+ import { Command } from "commander";
5
+ import { accountRemoveCommand } from "../../cli/account-remove.js";
6
+ import { baseContext, environmentOf } from "../../cli/context.js";
7
+ import { LOCAL_READ, LOCAL_WRITE } from "../../cli/effects.js";
8
+ import { profilesHere, recalledAccount, rememberAccount } from "../../cli/messenger/accounts.js";
9
+ import { ProfileTokenStore } from "../../cli/profile-token.js";
10
+ import { oauthAccount } from "../../oauth/storage.js";
11
+ import { CRM_SHARED_FOLDERS } from "../state-folders.js";
12
+ const SHARED = new Set(Object.values(CRM_SHARED_FOLDERS));
13
+ // A folder named Files is the folder files on macOS and Windows.
14
+ const isShared = (profile) => SHARED.has(profile.toLowerCase());
15
+ /** The account alone, which the delete guard needs: the default reads no keyring, so it cannot fail. */
16
+ const accountBy = (app, options) => (profile, context) => options.held
17
+ ? options.held(profile, context)?.account
18
+ : recalledAccount(app, options.provider, profile, context.env)?.account;
19
+ const signedInBy = (app, options, tokens) => (profile, context) => {
20
+ try {
21
+ if (options.held)
22
+ return options.held(profile, context);
23
+ const account = recalledAccount(app, options.provider, profile, context.env)?.account;
24
+ if (account === undefined)
25
+ return undefined;
26
+ const saved = (tokens ?? new ProfileTokenStore({ app, ...context, warn: () => { } })).read(profile);
27
+ // `<PREFIX>_TOKEN` is every profile's at once, so it is no profile's own sign-in.
28
+ return { account, signedIn: saved !== undefined && saved.source !== "environment" };
29
+ }
30
+ catch {
31
+ // A keyring that does not answer for one profile must not stop another profile's sign-in.
32
+ return undefined;
33
+ }
34
+ };
35
+ const also = (names) => `${names.join(", ")} also read${names.length === 1 ? "s" : ""}`;
36
+ /**
37
+ * Refuses a sign-in to an account and user another profile here is signed in to: two profiles would sync the same
38
+ * copy twice and split its permissions. A profile that ended its session no longer holds the account.
39
+ */
40
+ export const refuseTakenCrmAccount = (app, options, { profile, profiles = [], tokens, ...context }, at) => {
41
+ if (isShared(profile))
42
+ throw new CliError("validation_error", `"${profile}" names a folder every account shares, where this profile's own files would land. Pick another ` +
43
+ `name than ${Object.values(CRM_SHARED_FOLDERS).join(" or ")}`, { reason: "profile.reserved", profile });
44
+ const held = signedInBy(app, options, tokens);
45
+ const other = profilesHere(app, profiles, context.env).find((one) => {
46
+ if (one === profile)
47
+ return false;
48
+ const found = held(one, context);
49
+ return found?.signedIn === true && found.account === at.account && found.user === at.user;
50
+ });
51
+ if (!other)
52
+ return;
53
+ const command = app.command;
54
+ throw new CliError("conflict", `profile ${other} already signs in to ${options.service} account ${at.account}` +
55
+ `${at.user === undefined ? "" : ` as user ${at.user}`}. Use \`${command} ${other}\`, ` +
56
+ // Another user's token on the account is a second sign-in only where the account has users.
57
+ (at.user === undefined ? "" : `sign it in again with \`${command} ${other} session start\`, `) +
58
+ `or end it with \`${command} ${other} session end\` first`, { reason: "session.duplicate", profile: other, account: at.account });
59
+ };
60
+ /** `claim` for `tokenSessionCommand`: refuses an account another profile is signed in to, then remembers it. */
61
+ export const crmAccountClaim = (app, options) => (env, profile, id, tokens, keyring) => {
62
+ const profiles = options.resolveSettings?.({}, { env, needsProfile: false }).configuredProfiles ?? [];
63
+ refuseTakenCrmAccount(app, options, { env, profile, profiles, tokens, ...(keyring ? { keyring } : {}) }, { account: id });
64
+ rememberAccount(app, profile, id, env);
65
+ };
66
+ /** The store keeps one copy per account, so deleting one profile's data deletes every profile's on that account. */
67
+ const refuseSharedDelete = (app, options, command) => {
68
+ const given = command.opts();
69
+ if (given.deleteData !== true)
70
+ return;
71
+ const resolveSettings = options.resolveSettings ?? environmentOf(command).resolveSettings;
72
+ if (!resolveSettings)
73
+ return;
74
+ const { env, keyring, settings, renderer } = baseContext(command, resolveSettings);
75
+ const context = { env, ...(keyring ? { keyring } : {}) };
76
+ const accountOf = accountBy(app, options);
77
+ const read = (profile) => {
78
+ try {
79
+ return accountOf(profile, context);
80
+ }
81
+ catch {
82
+ throw new CliError("conflict", `${app.command} could not tell which ${options.service} account ${profile} holds, so --delete-data could ` +
83
+ `delete a copy ${profile} still reads. Fix ${profile}'s sign-in, or use --keep-data`, { reason: "account-remove.account-unknown", profile });
84
+ }
85
+ };
86
+ const own = read(settings.profile);
87
+ if (own === undefined)
88
+ return;
89
+ const sharing = settings.profilesHere.filter((one) => one !== settings.profile && read(one) === own);
90
+ if (sharing.length === 0)
91
+ return;
92
+ if (given.dryRun === true) {
93
+ renderer.warn(`without --dry-run this refuses: ${also(sharing)} ${options.service} account ${own}`);
94
+ return;
95
+ }
96
+ const names = sharing.join(", ");
97
+ throw new CliError("conflict", `${also(sharing)} ${options.service} account ${own}, and the store keeps one copy of an account: ` +
98
+ `--delete-data would delete their deals, contacts and companies too. Use --keep-data, or remove ${names} first`, { reason: "account-remove.account-shared", profiles: sharing, account: own });
99
+ };
100
+ const removalOf = (app, options) => {
101
+ const accountOf = accountBy(app, options);
102
+ const folders = (env) => resolvePaths({ appName: app.appName, prefix: app.envPrefix, env });
103
+ return {
104
+ // A CRM's API token has no call that revokes it; the CRM's own settings do.
105
+ signOut: async (profile) => ({
106
+ revoked: null,
107
+ removed: [
108
+ options.signedOut?.(profile) ??
109
+ `the sign-in of ${profile} (the token stays valid in ${options.service} until you delete it there)`,
110
+ ],
111
+ }),
112
+ account: (profile, context) => {
113
+ try {
114
+ const account = accountOf(profile, context);
115
+ return account === undefined ? undefined : { provider: options.provider, account };
116
+ }
117
+ catch {
118
+ // --delete-data was refused before this; --keep-data only names the account it keeps.
119
+ return undefined;
120
+ }
121
+ },
122
+ secrets: (profile, { env, keyring }) => [
123
+ {
124
+ credentials: {
125
+ configDir: folders(env).config,
126
+ service: app.appName,
127
+ envVar: `${app.envPrefix}_TOKEN`,
128
+ env,
129
+ ...(keyring ? { keyring } : {}),
130
+ },
131
+ // An OAuth sign-in's entry; removing a missing one is fine.
132
+ accounts: [`token:${profile}`, oauthAccount(options.provider, profile)],
133
+ },
134
+ ],
135
+ // A profile named after a folder every account shares has no folder of its own there.
136
+ stateFiles: (profile, { env }) => (isShared(profile) ? [] : [join(folders(env).state, "crm", profile)]),
137
+ };
138
+ };
139
+ /**
140
+ * `account remove` of a CRM CLI: cli-core's own, which refuses `--delete-data` while another profile here reads the
141
+ * same account, whose one copy the store shares. Under `--dry-run` it warns instead.
142
+ */
143
+ export const crmAccountCommand = (app, options) => annotate(new Command("account"), { effects: LOCAL_READ })
144
+ .description("this profile on this computer")
145
+ .addCommand(annotate(accountRemoveCommand(app, removalOf(app, options), {
146
+ ...(options.resolveSettings ? { resolveSettings: options.resolveSettings } : {}),
147
+ }), { effects: LOCAL_WRITE }).hook("preAction", (_, action) => refuseSharedDelete(app, options, action)));
@@ -18,6 +18,7 @@ import { safeName } from "../../files/safe-name.js";
18
18
  import { crmIdentityId } from "../../store/sqlite/crm-rows.js";
19
19
  import { parseCrmFileId } from "../files.js";
20
20
  import { foreignContacts, foreignContactsPathFor } from "../foreign-contacts.js";
21
+ import { CRM_SHARED_FOLDERS } from "../state-folders.js";
21
22
  import { integer } from "./records.js";
22
23
  const MB = 1024 * 1024;
23
24
  const PAGE = 500;
@@ -72,7 +73,7 @@ const OWNER_FLAGS = [
72
73
  const iso = (ms) => (ms === null ? null : new Date(ms).toISOString());
73
74
  const segment = (text) => text.replace(/[^\w.-]+/gu, "_");
74
75
  /** The account's own folder of downloads: what the disk cap counts and drops. */
75
- const accountFolder = (app, run) => join(resolvePaths({ appName: app.appName, prefix: app.envPrefix, env: run.env ?? process.env }).state, "crm", "files", segment(`${run.account.provider}-${run.account.account}`));
76
+ const accountFolder = (app, run) => join(resolvePaths({ appName: app.appName, prefix: app.envPrefix, env: run.env ?? process.env }).state, "crm", CRM_SHARED_FOLDERS.files, segment(`${run.account.provider}-${run.account.account}`));
76
77
  /** Each folder from `top` down to `folder` is the OS user's alone, whatever the umask or an earlier run left. */
77
78
  const ownFolder = (top, folder) => {
78
79
  mkdirSync(folder, { recursive: true, mode: 0o700 });
@@ -6,7 +6,9 @@ import type { AccountKey } from "../../store/types.js";
6
6
  import type { CrmSource } from "../source.js";
7
7
  import type { CrmWriteCapabilities } from "../writer.js";
8
8
  import { type CrmWrites } from "../writes.js";
9
+ import { type CrmAccountOptions } from "./account.js";
9
10
  import { type CrmLiveRecord } from "./records.js";
11
+ export * from "./account.js";
10
12
  export { type CsvField, type CsvPage, csvColumnPaths, csvFormatOption, DEAL_CSV_COLUMNS, printCsv, refuseCsvConflict, } from "./csv.js";
11
13
  export { CRM_ORGANIZATIONS_QUERY, CRM_PEOPLE_QUERY, CRM_USERS_QUERY, type CrmLiveRecord, crmOrganizationOf, crmOrganizationSchema, crmPersonOf, crmPersonSchema, crmUserOf, crmUserSchema, } from "./records.js";
12
14
  export { type CrmStoreOptions, openCrmStore } from "./store.js";
@@ -59,6 +61,7 @@ export interface CrmCommandOptions {
59
61
  activities?: boolean;
60
62
  files?: boolean;
61
63
  now?: () => number;
64
+ account?: CrmAccountOptions;
62
65
  }
63
66
  /** What `deals list` and `leads list` narrow by, the same in memo and every CRM CLI (WC-OUT-11). */
64
67
  export declare const DEALS_QUERY: {
@@ -25,12 +25,14 @@ import { openStageTasks } from "../stage-tasks.js";
25
25
  import { crmStatus, syncRecorded } from "../sync.js";
26
26
  import { ownerOf, shortened, viewerOf, withReadableDeal } from "../viewer.js";
27
27
  import { closeCrmItem, createCrmItem, fieldPairsOf, moveCrmItem, pipelineOf, removeCrmItem, updateCrmItem, } from "../writes.js";
28
+ import { crmAccountCommand } from "./account.js";
28
29
  import { addCrmChangeCommands } from "./changes.js";
29
30
  import { csvFormatOption, renderCsv } from "./csv.js";
30
31
  import { addCrmFileCommands } from "./files.js";
31
32
  import { pipelineView } from "./pipeline-view.js";
32
33
  import { addCrmRecordCommands, integer } from "./records.js";
33
34
  import { addCrmSearchAll } from "./search-all.js";
35
+ export * from "./account.js";
34
36
  export { csvColumnPaths, csvFormatOption, DEAL_CSV_COLUMNS, printCsv, refuseCsvConflict, } from "./csv.js";
35
37
  export { CRM_ORGANIZATIONS_QUERY, CRM_PEOPLE_QUERY, CRM_USERS_QUERY, crmOrganizationOf, crmOrganizationSchema, crmPersonOf, crmPersonSchema, crmUserOf, crmUserSchema, } from "./records.js";
36
38
  export { openCrmStore } from "./store.js";
@@ -681,6 +683,8 @@ const addCrmCommandsDefinition = (program, options) => {
681
683
  const search = program.commands.find((one) => one.name() === "search") ??
682
684
  annotate(program.command("search"), { effects: NO_EFFECTS }).description("search what the local store holds");
683
685
  addCrmSearchAll(search, { within, app: options.app, example, viewerOf, leads: hasLeads });
686
+ if (options.account)
687
+ program.addCommand(crmAccountCommand(options.app, options.account));
684
688
  };
685
689
  // honoursDryRun: a host program other than `run` would otherwise let a write through under --dry-run.
686
690
  export const addCrmCommands = honoursDryRun(sharedCommand(addCrmCommandsDefinition));