@wirecat/cli-core 0.721.0 → 0.723.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 (48) hide show
  1. package/CHANGELOG.md +90 -0
  2. package/dist/background/daily-archive-timer.d.ts +1 -1
  3. package/dist/cli/messenger/lacks.d.ts +2 -1
  4. package/dist/cli/messenger/lacks.js +14 -1
  5. package/dist/cli/service-api-call.d.ts +6 -0
  6. package/dist/cli/service-api-call.js +21 -9
  7. package/dist/cli/service-api.d.ts +5 -0
  8. package/dist/cli/service-api.js +11 -0
  9. package/dist/cli/token-session.d.ts +2 -1
  10. package/dist/cli/token-session.js +2 -2
  11. package/dist/crm/cli/account.d.ts +60 -0
  12. package/dist/crm/cli/account.js +147 -0
  13. package/dist/crm/cli/files.js +2 -1
  14. package/dist/crm/cli/index.d.ts +3 -0
  15. package/dist/crm/cli/index.js +4 -0
  16. package/dist/crm/foreign-contacts.js +2 -1
  17. package/dist/crm/index.d.ts +3 -2
  18. package/dist/crm/index.js +1 -0
  19. package/dist/crm/manifest/manifest.d.ts +60 -1
  20. package/dist/crm/manifest/manifest.js +88 -0
  21. package/dist/crm/manifest/source.d.ts +22 -3
  22. package/dist/crm/manifest/source.js +10 -3
  23. package/dist/crm/manifest/writer.d.ts +39 -0
  24. package/dist/crm/manifest/writer.js +298 -0
  25. package/dist/crm/state-folders.d.ts +5 -0
  26. package/dist/crm/state-folders.js +2 -0
  27. package/dist/crm/testing/index.d.ts +1 -1
  28. package/dist/crm/testing/index.js +1 -1
  29. package/dist/crm/testing/manifest-fake.d.ts +14 -0
  30. package/dist/crm/testing/manifest-fake.js +252 -27
  31. package/dist/errors/reasons.d.ts +1 -1
  32. package/dist/errors/reasons.js +11 -0
  33. package/dist/ports/wirecat-tools.js +7 -0
  34. package/dist/services/files/mirror.d.ts +5 -2
  35. package/dist/services/files/mirror.js +1 -1
  36. package/dist/services/metadata.d.ts +1 -1
  37. package/dist/store/index.d.ts +1 -0
  38. package/dist/store/sqlite/account-purge.js +3 -0
  39. package/dist/store/sqlite/crm-stage-entries.js +4 -1
  40. package/dist/store/sqlite/erase-plan.d.ts +19 -0
  41. package/dist/store/sqlite/erase-plan.js +74 -0
  42. package/dist/store/sqlite/messages.js +2 -1
  43. package/dist/store/sqlite/organization-erase.d.ts +29 -0
  44. package/dist/store/sqlite/organization-erase.js +83 -0
  45. package/dist/store/sqlite/organizations.d.ts +10 -1
  46. package/dist/store/sqlite/organizations.js +6 -1
  47. package/dist/store/sqlite/person-erase.js +4 -45
  48. package/package.json +2 -2
package/CHANGELOG.md CHANGED
@@ -5,6 +5,96 @@ Notable changes to `@wirecat/cli-core` (`@wirecat/cli-messaging` up to 0.261.0,
5
5
  minor version may break callers, and says how under "Changed — may break callers". `pnpm docs:check` checks the
6
6
  shape of this file.
7
7
 
8
+ ## 0.723.0 — 23.11.2026
9
+
10
+ ### Added
11
+
12
+ - **`knowledge.eraseOrganization` deletes an organization and what memo knows of it alone.** The tags, links,
13
+ aliases and mentions that name it go, and so does which identities it held. A deal, lead, project, account, fact or
14
+ note that names it stays and loses the name. `apply: false` answers what would go and changes nothing. Owner only;
15
+ refused for one of the owner's own companies (`organization.own`), and while an invoice, order, subscription or a
16
+ row it wrote still names it (`organization.erase-blocked`). It shares `ErasePlan` with `people.erase`: both read
17
+ the store's own pointers and foreign keys, so the plan shown and the delete run read one list.
18
+
19
+ ### Fixed
20
+
21
+ - **Removing an import's account now takes the organizations only its records made**, as it does for people. One
22
+ that another source, a deal or the owner still names stays.
23
+ - **A deal or lead that enters a stage in the same second its `stage-tasks` rules were set now opens its task.** A
24
+ CRM's stage history keeps whole seconds, so such a move read as made before the rules and opened none; the rules
25
+ now count from the start of the second they were set. Bitrix24's live check hit it when it set the rules and moved
26
+ a deal within a second.
27
+
28
+ ## 0.722.0 — 23.11.2026
29
+
30
+ ### Added
31
+
32
+ - **`account remove` for every CRM CLI, with its guard.** `addCrmCommands({ account })` mounts cli-core's
33
+ `account remove`, which refuses `--delete-data` while another profile here holds the same account, whose one copy
34
+ the store shares (`account-remove.account-shared`); `--dry-run` warns instead. `refuseTakenCrmAccount` and
35
+ `crmAccountClaim` (the `claim` of `tokenSessionCommand`) refuse a sign-in to an account and user another profile is
36
+ signed in to (`session.duplicate`), and a profile named `files` or `foreign-contacts`, the folders every account
37
+ shares (`profile.reserved`). A `held` hook says which account a profile holds; unset, it is the account
38
+ `session start` remembered. bitrix24-cli, amo-cli and hubspot-cli can drop their own copies
39
+ ([CRM.md](docs/dev/CRM.md#one-account-one-profile)).
40
+ - **`tokenSessionCommand`'s `claim` gets the run's keyring** as its fifth argument, so a check of the other profiles'
41
+ sign-ins reads the same keyring a test hands in.
42
+ - **Earlier versions of every synced document, and a change log (store version 72).** The store keeps a document's
43
+ text, title and front matter before each change and before each removal, so a deleted page's last text is never
44
+ lost. `documents history <document>` lists the versions and `--revision <n>` shows one. `changes --since 1d` lists
45
+ what was added, changed, deleted, no longer visible, left the synced folders or came back, with titles. Both are
46
+ local reads, so agents get them over MCP too. `documentLibraryCommands` mounts them, and `addDocumentCommands` does
47
+ when the CLI gives `history`. A CLI with its own `documents` group calls `addDocumentHistoryCommands`
48
+ ([DOCUMENTS.md](docs/dev/DOCUMENTS.md#history-and-the-change-log)).
49
+ - **`keep_versions_for_days`, 365 by default.** A sync that completes its pass drops older versions and change log
50
+ rows of that account. A CLI adds `DOCUMENT_HISTORY_SETTINGS` to `settingsFor` and passes `keepVersionsForDays` to
51
+ `syncDocuments`. Without it the sync keeps one year.
52
+ - **A source can say a document is no longer visible rather than deleted.** A change takes `gone: "deleted"` or
53
+ `gone: "unavailable"`, and `SourceIndex.remove` and `deleteFileNotes` take the reason.
54
+ - **Office files edited in place, and earlier versions put back.** `addFileEditCommands` mounts under a CLI's files
55
+ group `sheets show|update` for .xlsx cells, `documents show|update` for .docx paragraphs, `history` for what this
56
+ profile's writes replaced, and `restore <path> [version]`, besides `update`. A show gives the file's sha256; every
57
+ edit and restore takes it as `--expected-fingerprint` and writes through `guardedFileWrite`, so a change made
58
+ meanwhile is a conflict with nothing uploaded and the replaced content is kept. The Office editors' refusals pass
59
+ through with their reasons ([DOCUMENTS.md](docs/dev/DOCUMENTS.md#edit-office-files-in-place)).
60
+
61
+ ### Changed — may break callers
62
+
63
+ - **A file mirror's guard on mass replacements names the count to allow.** A sync stopped before more than 50
64
+ replacements now says to pass `--allow-replacements <count>` with the count filled in, where its default hint said
65
+ `--replace`; `allowReplacements` already took a count. A CLI that offers neither option and relied on the default
66
+ hint should add `--allow-replacements <count>`. One that keeps its `--replace` switch passes
67
+ `allowReplacements: Number.POSITIVE_INFINITY` and its own `allowReplacements` hint, as before
68
+ ([DOCUMENTS.md](docs/dev/DOCUMENTS.md#plain-files-both-ways)).
69
+ - **Uses `@wirecat/cli-base` 0.127.0**, whose vocabulary has `mirrors`, `conflicts`, `--keep <side>`,
70
+ `--allow-deletions <count>`, `--allow-replacements <count>` and `--repin`: the mirror's conflict commands pass
71
+ `cli-dev lint` with no override for them.
72
+ - **`files update` refuses a .pdf, .docx or .xlsx** (`file.not-plain-text`): a read gives their extracted text, which
73
+ would replace the whole document. A CLI leaves the sha256 out of a truncated or extracted text read
74
+ ([DOCUMENTS.md](docs/dev/DOCUMENTS.md#write-one-file-at-the-hash-read)).
75
+
76
+ ### Fixed
77
+
78
+ - **Only a direct signal deletes a synced document's text.** A removal from a change feed without `gone`, a 404 or a
79
+ refusal when the content is read, and a file a finished walk did not find now mark the document no longer visible.
80
+ It leaves lists and search but keeps its text, and comes back as it was. Before, its text was blanked. The trash or
81
+ `gone: "deleted"` still deletes. A file that left the scope because the owner changed the chosen folders is marked
82
+ unsynced.
83
+ - **A messenger's `never` hides ten more commands, and a group left empty.** `messages forward`, `contacts block`
84
+ and `unblock`, `chats links show` and `reset`, `chats requests list`, `confirm` and `reject`, and `chats admins add`
85
+ and `remove` now refuse before connecting when their one method is in `lacks` or `never`, and `never` hides them
86
+ from help, `commands` and MCP. A group whose every command is hidden, such as `account sessions` or `chats folders`,
87
+ is hidden too, so a messenger can put those methods in `never` instead of `lacks`.
88
+ - **A server search no longer erases what the store knew about a message.** A hit is a partial copy: saved over a
89
+ held message, it now adds to its provider metadata instead of replacing it, so a Slack thread root found by
90
+ `search.messages` keeps the reply count a sync saved. A fetch from history still replaces the metadata.
91
+ - **A file mirror no longer merges edits to neighbouring lines.** Two changes with no unchanged line between them,
92
+ one on each side, are now a conflict, as in Git's merge. They used to be combined silently. This includes an
93
+ insertion right after the other side's edit, and edits to neighbouring Markdown blocks such as two list items.
94
+ Changes with at least one unchanged line between them still merge, and a checklist tick still merges with a text
95
+ edit. Document push keeps merging neighbouring blocks as before
96
+ ([DOCUMENTS.md](docs/dev/DOCUMENTS.md#plain-files-both-ways)).
97
+
8
98
  ## 0.721.0 — 23.11.2026
9
99
 
10
100
  ### Added
@@ -24,12 +24,12 @@ export interface DailyArchiveTimerInput {
24
24
  }
25
25
  export declare const dailyArchiveTimer: (input: DailyArchiveTimerInput) => DailyArchiveTimer;
26
26
  export declare const manageDailyArchiveTimer: (plan: DailyArchiveTimer, action: "install" | "start" | "stop" | "status" | "uninstall", system: Pick<ServerSystem, "platform" | "run">, env: NodeJS.ProcessEnv, signal?: AbortSignal) => Promise<{
27
- action?: undefined;
28
27
  name: string;
29
28
  installed: boolean;
30
29
  active: boolean;
31
30
  servicePath: string;
32
31
  timerPath: string;
32
+ action?: undefined;
33
33
  } | {
34
34
  active?: undefined;
35
35
  name: string;
@@ -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()]);
@@ -43,3 +43,9 @@ credentialScope?: string) => FetchLike;
43
43
  export declare const serviceApiCall: (options: ServiceApiCallOptions) => ServiceApiCall & {
44
44
  withHeaders: ServiceApiCallWithHeaders;
45
45
  };
46
+ /**
47
+ * `serviceApiCall` that sends writes too, with no guard of its own: only for a writer that cli-core's CRM writes
48
+ * wrap in theirs (`crm/writes.ts`), which checks the operation's `api` keys. Never exported from the package: a CLI
49
+ * that sends a write itself goes through `serviceApiWriter`. A write is sent once; a lost answer is `outcome_unknown`.
50
+ */
51
+ export declare const serviceApiSend: (options: ServiceApiCallOptions) => ServiceApiCall;
@@ -12,13 +12,7 @@ export const hostsFetch = (hosts, fetch,
12
12
  credentialScope) => hostFetch({ hosts, ...(fetch ? { fetch } : {}), ...(credentialScope ? { credentialScope } : {}) });
13
13
  // The run record and the fetch are the only things httpApiSend asks a command for, and a sync has no command of its own.
14
14
  const NO_COMMAND = new Command("source");
15
- /**
16
- * The `api` group's request path for code that is not a command, such as a source read from a manifest: the same
17
- * request building, sign-in header, redirect rule, run record and refusals as `serviceApiCommand`, without a guard. It
18
- * sends reads only; a write goes through `serviceApiWriter` or the `api` group, where the profile's guard asks. A
19
- * request is sent only under the server's address, path included: a site at `host/blog` never signs `host/other`.
20
- */
21
- export const serviceApiCall = (options) => {
15
+ const sender = (options, writes) => {
22
16
  const baseUrl = manifestBaseUrl(options.manifest, options.baseUrl, options.serverVariables);
23
17
  const operations = new Map(options.manifest.operations.map((one) => [one.id, one]));
24
18
  const exchange = httpApiExchange({
@@ -27,11 +21,11 @@ export const serviceApiCall = (options) => {
27
21
  failure: options.failure,
28
22
  failedAnswer: options.failedAnswer,
29
23
  });
30
- const withHeaders = async (id, input) => {
24
+ return async (id, input) => {
31
25
  const operation = operations.get(id);
32
26
  if (!operation)
33
27
  throw new CliError("configuration_error", `no ${options.service} API operation ${id}`);
34
- if (operation.effect !== "read")
28
+ if (!writes && operation.effect !== "read")
35
29
  throw new CliError("configuration_error", `${operation.command} is not a read; a source only reads`);
36
30
  const request = httpApiRequest(operation, input, baseUrl);
37
31
  if (!underBase(request.url, baseUrl))
@@ -47,7 +41,25 @@ export const serviceApiCall = (options) => {
47
41
  const { answer, headers } = await exchange(NO_COMMAND, operation, request);
48
42
  return { body: answer, headers };
49
43
  };
44
+ };
45
+ /**
46
+ * The `api` group's request path for code that is not a command, such as a source read from a manifest: the same
47
+ * request building, sign-in header, redirect rule, run record and refusals as `serviceApiCommand`, without a guard. It
48
+ * sends reads only; a write goes through `serviceApiWriter` or the `api` group, where the profile's guard asks. A
49
+ * request is sent only under the server's address, path included: a site at `host/blog` never signs `host/other`.
50
+ */
51
+ export const serviceApiCall = (options) => {
52
+ const withHeaders = sender(options, false);
50
53
  return Object.assign(async (id, input) => (await withHeaders(id, input)).body, {
51
54
  withHeaders,
52
55
  });
53
56
  };
57
+ /**
58
+ * `serviceApiCall` that sends writes too, with no guard of its own: only for a writer that cli-core's CRM writes
59
+ * wrap in theirs (`crm/writes.ts`), which checks the operation's `api` keys. Never exported from the package: a CLI
60
+ * that sends a write itself goes through `serviceApiWriter`. A write is sent once; a lost answer is `outcome_unknown`.
61
+ */
62
+ export const serviceApiSend = (options) => {
63
+ const withHeaders = sender(options, true);
64
+ return async (id, input) => (await withHeaders(id, input)).body;
65
+ };
@@ -76,6 +76,11 @@ export declare const serviceApiOperations: (manifest: ServiceApiManifest) => {
76
76
  reason: string;
77
77
  }[];
78
78
  };
79
+ /**
80
+ * Every key a call of the operation may check: `api.<operation>`, the manifest's and the CLI's body keys, each whatever
81
+ * the body holds. For a writer that sends the operation outside the `api` group, so its door is never wider.
82
+ */
83
+ export declare const serviceApiOwnKeys: (operation: ManifestOperation, bodyPermissions?: ServiceApiPermissionsInput["bodyPermissions"]) => PermissionKey[];
79
84
  /** The keys one call checks beside `api.<operation>`: the manifest's that apply, and the CLI's from the body. */
80
85
  export declare const serviceApiKeys: (input: ServiceApiPermissionsInput, operation: ManifestOperation, call: ApiCommandInput) => PermissionKey[];
81
86
  /**
@@ -47,6 +47,17 @@ const formerKeyOf = (operation) => {
47
47
  return former === keyOf(operation) ? undefined : former;
48
48
  };
49
49
  const permissionsOf = (operation) => operation.permissions ?? [];
50
+ /**
51
+ * Every key a call of the operation may check: `api.<operation>`, the manifest's and the CLI's body keys, each whatever
52
+ * the body holds. For a writer that sends the operation outside the `api` group, so its door is never wider.
53
+ */
54
+ export const serviceApiOwnKeys = (operation, bodyPermissions) => [
55
+ ...new Set([
56
+ keyOf(operation),
57
+ ...permissionsOf(operation).map(({ key }) => key),
58
+ ...(bodyPermissions?.[operation.command] ?? []).map(({ key }) => key),
59
+ ]),
60
+ ];
50
61
  /** By its method too: an override may have marked a DELETE as a plain write. */
51
62
  const destructive = (operation) => operation.effect === "destructive" || (operation.binding.kind === "http" && operation.binding.method === "DELETE");
52
63
  const flagsOf = ({ body = [], query = [] }) => [...body, ...query];
@@ -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));
@@ -2,13 +2,14 @@ import { readFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { CliError, resolvePaths, writeSecurely } from "@wirecat/cli-base";
4
4
  import { withFileLockAsync } from "../sends/file-lock.js";
5
+ import { CRM_SHARED_FOLDERS } from "./state-folders.js";
5
6
  /**
6
7
  * The owner's rule (NEED-2487, NEED-2703 B): a user sees at most this many other people's records a UTC day: a
7
8
  * contact's or company's details, or a deal's, lead's, contact's or company's files.
8
9
  */
9
10
  export const DAILY_FOREIGN_CONTACTS = 100;
10
11
  /** Where the day's count of one CRM user is kept: the CLI's state folder, a file per account and user. */
11
- export const foreignContactsPathFor = (app, account, env = process.env, user) => join(resolvePaths({ appName: app.appName, prefix: app.envPrefix, env }).state, "crm", "foreign-contacts", `${[account.provider, account.account, ...(user ? [user] : [])].join("-").replace(/[^\w.-]+/gu, "_")}.json`);
12
+ export const foreignContactsPathFor = (app, account, env = process.env, user) => join(resolvePaths({ appName: app.appName, prefix: app.envPrefix, env }).state, "crm", CRM_SHARED_FOLDERS.foreignContacts, `${[account.provider, account.account, ...(user ? [user] : [])].join("-").replace(/[^\w.-]+/gu, "_")}.json`);
12
13
  const shownIn = (file, day) => {
13
14
  try {
14
15
  const found = JSON.parse(readFileSync(file, "utf8"));
@@ -1,9 +1,10 @@
1
1
  export { type CrmFileFetchOptions, fetchCrmFile } from "./file-fetch.js";
2
2
  export { crmFileId, LINK_REMOVED, parseCrmFileId, withoutFileLinks } from "./files.js";
3
3
  export { DAILY_FOREIGN_CONTACTS, type ForeignContacts, foreignContacts, foreignContactsPathFor, refuseForeignClientReads, } from "./foreign-contacts.js";
4
- export { type CrmAfterHook, type CrmChangesCall, type CrmManifest, type CrmManifestEntity, type CrmManifestFields, type CrmManifestHooks, type CrmManifestPipelines, type CrmOperationCall, type CrmRule, parseCrmManifest, } from "./manifest/manifest.js";
4
+ export { type CrmAfterHook, type CrmChangesCall, type CrmFixedValue, type CrmManifest, type CrmManifestEntity, type CrmManifestFields, type CrmManifestHooks, type CrmManifestPipelines, type CrmManifestWrite, type CrmOperationCall, type CrmRule, type CrmWriteRule, parseCrmManifest, } from "./manifest/manifest.js";
5
5
  export { crmManifestProblems } from "./manifest/paths.js";
6
- export { type CrmManifestSourceOptions, crmSourceFromManifest } from "./manifest/source.js";
6
+ export { type CrmManifestSource, type CrmManifestSourceOptions, crmSourceFromManifest } from "./manifest/source.js";
7
+ export { type CrmManifestWritesOptions, crmManifestWriteCapabilities, crmManifestWriteKeys, crmManifestWrites, } from "./manifest/writer.js";
7
8
  export { type ProviderCallOptions, providerCall } from "./provider-call.js";
8
9
  export { type CrmConditionHooks, type CrmQueryField, conditionsOf, customConditions, customNames, filterableFields, selectedCodes, wantedCodes, withCustomFields, } from "./query.js";
9
10
  export { CRM_FILE_SOURCES, type CrmCallContext, type CrmChanges, type CrmCondition, type CrmFile, type CrmFileOwner, type CrmFileSourceKind, type CrmFiles, type CrmGap, type CrmIdPage, type CrmLiveKind, type CrmLiveQuery, type CrmOpenableFile, type CrmPage, type CrmSource, type CrmSourceTraits, } from "./source.js";
package/dist/crm/index.js CHANGED
@@ -4,6 +4,7 @@ export { DAILY_FOREIGN_CONTACTS, foreignContacts, foreignContactsPathFor, refuse
4
4
  export { parseCrmManifest, } from "./manifest/manifest.js";
5
5
  export { crmManifestProblems } from "./manifest/paths.js";
6
6
  export { crmSourceFromManifest } from "./manifest/source.js";
7
+ export { crmManifestWriteCapabilities, crmManifestWriteKeys, crmManifestWrites, } from "./manifest/writer.js";
7
8
  export { providerCall } from "./provider-call.js";
8
9
  export { conditionsOf, customConditions, customNames, filterableFields, selectedCodes, wantedCodes, withCustomFields, } from "./query.js";
9
10
  export { CRM_FILE_SOURCES, } from "./source.js";