@wirecat/cli-core 0.722.0 → 0.724.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 (56) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/dist/cli/documents/history.js +2 -2
  3. package/dist/cli/documents/words.d.ts +1 -1
  4. package/dist/cli/service-api-call.d.ts +6 -0
  5. package/dist/cli/service-api-call.js +21 -9
  6. package/dist/cli/service-api.d.ts +5 -0
  7. package/dist/cli/service-api.js +11 -0
  8. package/dist/content/writes.d.ts +3 -9
  9. package/dist/content/writes.js +3 -13
  10. package/dist/crm/index.d.ts +3 -2
  11. package/dist/crm/index.js +1 -0
  12. package/dist/crm/manifest/manifest.d.ts +60 -1
  13. package/dist/crm/manifest/manifest.js +88 -0
  14. package/dist/crm/manifest/source.d.ts +22 -3
  15. package/dist/crm/manifest/source.js +10 -3
  16. package/dist/crm/manifest/writer.d.ts +39 -0
  17. package/dist/crm/manifest/writer.js +298 -0
  18. package/dist/crm/testing/index.d.ts +1 -1
  19. package/dist/crm/testing/index.js +1 -1
  20. package/dist/crm/testing/manifest-fake.d.ts +14 -0
  21. package/dist/crm/testing/manifest-fake.js +252 -27
  22. package/dist/crm/writes.d.ts +4 -13
  23. package/dist/crm/writes.js +2 -9
  24. package/dist/errors/reasons.js +5 -0
  25. package/dist/ports/wirecat-tools.js +7 -0
  26. package/dist/sends/profile-writes.d.ts +22 -0
  27. package/dist/sends/profile-writes.js +20 -0
  28. package/dist/tracker/cli/index.d.ts +10 -1
  29. package/dist/tracker/cli/index.js +20 -1
  30. package/dist/tracker/cli/writes.d.ts +27 -0
  31. package/dist/tracker/cli/writes.js +74 -0
  32. package/dist/tracker/index.d.ts +5 -2
  33. package/dist/tracker/index.js +5 -2
  34. package/dist/tracker/manifest/manifest.d.ts +25 -0
  35. package/dist/tracker/manifest/manifest.js +59 -8
  36. package/dist/tracker/manifest/source.d.ts +10 -1
  37. package/dist/tracker/manifest/source.js +12 -9
  38. package/dist/tracker/manifest/writer.d.ts +20 -0
  39. package/dist/tracker/manifest/writer.js +72 -0
  40. package/dist/tracker/sync.d.ts +5 -0
  41. package/dist/tracker/sync.js +12 -0
  42. package/dist/tracker/testing/index.d.ts +3 -1
  43. package/dist/tracker/testing/index.js +3 -1
  44. package/dist/tracker/testing/manifest-fake.d.ts +2 -0
  45. package/dist/tracker/testing/manifest-fake.js +123 -41
  46. package/dist/tracker/testing/manifest-writes.d.ts +16 -0
  47. package/dist/tracker/testing/manifest-writes.js +70 -0
  48. package/dist/tracker/testing/source.d.ts +9 -1
  49. package/dist/tracker/testing/source.js +63 -0
  50. package/dist/tracker/testing/write-contract.d.ts +20 -0
  51. package/dist/tracker/testing/write-contract.js +94 -0
  52. package/dist/tracker/writer.d.ts +57 -0
  53. package/dist/tracker/writer.js +25 -0
  54. package/dist/tracker/writes.d.ts +53 -0
  55. package/dist/tracker/writes.js +226 -0
  56. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -5,6 +5,60 @@ 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.724.0 — 23.11.2026
9
+
10
+ ### Added
11
+
12
+ - **CRM writes described by a source manifest.** `writes.<kind>` names a service's create, update and remove calls
13
+ and how each of our fields is sent (`to`, `each`, `list`, `number`, `decimals`, `implied`, a fixed currency,
14
+ `clear`), so a CRM CLI built from `wirecat.config.ts` gets `deals create|update|move|close|delete` and
15
+ `people create|update` with no writer of its own. A field with no rule, and a `--field` code the service does not
16
+ define, are refused before anything is sent. `crmManifestWrites` builds
17
+ `CrmRun.writes` over the CLI's fetch and token, and each write also checks its operation's `api` keys;
18
+ `crmManifestWriteCapabilities` and `crmManifestWriteKeys` give `addCrmCommands` and `crmAlsoChecks` the same.
19
+ `crmManifestWriteContract` runs `crmWriteContract` against `crmManifestFake`, which now answers writes, with
20
+ `loseNextAnswer()` and `requests()` ([CRM.md](docs/dev/CRM.md#writes-from-a-manifest)).
21
+ - **`crmSourceFromManifest` reads one record of any kind**: `record(kind, id)` by the entity's `get`, as a writer's
22
+ read-back.
23
+ - **attio in "Works with".** `WIRECAT_TOOLS` lists `attio` (`@wirecat/attio-cli`) beside the other CRM CLIs.
24
+ - **A tracker CLI creates, changes and comments on issues with its own commands.** `addTrackerCommands({ writes })`
25
+ mounts `issues create`, `issues update <issue>` and `issues comment <issue>`: a team, state, label, project or user
26
+ is named by its id or by a name only one row of the copy has (a label among the issue's team's and the workspace's),
27
+ an empty value clears a field, and a reference the copy does not hold is refused before anything is sent. Each write
28
+ passes the profile's guard on `issues.create`, `issues.update` or `issues.comment`, is journaled with the
29
+ `operation_id` it answers, previews under `--dry-run`, and stores the tracker's answer as a sync does, so
30
+ `issues show` has it at once. An `--assignee` other than the sign-in's own user also checks `issues.assign-others`,
31
+ denied by default as `crm.assign-others` is. A manifest's `writes` section maps each write to a mutation (Linear's
32
+ `issueCreate`, `issueUpdate`, `commentCreate`); `trackerWriterFromManifest` sends it through `serviceApiWriter`, so
33
+ the operation's own `api.*` key still applies. `trackerWriteContract` and `trackerManifestWriteContract` check a
34
+ writer, over a fake that answers the mutations strictly by the schema ([TRACKER.md](docs/dev/TRACKER.md#writes)).
35
+
36
+ ### Fixed
37
+
38
+ - **`changes` takes `--since <time>` and `--until <time>`**, the vocabulary's value name, where it said `<when>`. With
39
+ cli-base 0.129.0, which adds the `changes` view, `--since` and `--event`, the shared history commands pass
40
+ `cli-dev lint` in a documents CLI with no override. The flags take the same values as before.
41
+
42
+ ## 0.723.0 — 23.11.2026
43
+
44
+ ### Added
45
+
46
+ - **`knowledge.eraseOrganization` deletes an organization and what memo knows of it alone.** The tags, links,
47
+ aliases and mentions that name it go, and so does which identities it held. A deal, lead, project, account, fact or
48
+ note that names it stays and loses the name. `apply: false` answers what would go and changes nothing. Owner only;
49
+ refused for one of the owner's own companies (`organization.own`), and while an invoice, order, subscription or a
50
+ row it wrote still names it (`organization.erase-blocked`). It shares `ErasePlan` with `people.erase`: both read
51
+ the store's own pointers and foreign keys, so the plan shown and the delete run read one list.
52
+
53
+ ### Fixed
54
+
55
+ - **Removing an import's account now takes the organizations only its records made**, as it does for people. One
56
+ that another source, a deal or the owner still names stays.
57
+ - **A deal or lead that enters a stage in the same second its `stage-tasks` rules were set now opens its task.** A
58
+ CRM's stage history keeps whole seconds, so such a move read as made before the rules and opened none; the rules
59
+ now count from the start of the second they were set. Bitrix24's live check hit it when it set the rules and moved
60
+ a deal within a second.
61
+
8
62
  ## 0.722.0 — 23.11.2026
9
63
 
10
64
  ### Added
@@ -55,8 +55,8 @@ const addDocumentHistoryCommandsDefinition = (program, helpers) => {
55
55
  helpers.output(itemOf(await history.versions(ref)));
56
56
  }));
57
57
  return examples(annotate(program.command("changes"), { effects: LOCAL_READ }).description("list the documents the sync added, changed, removed or brought back, newest first"), [`${prefix} changes`, `${prefix} changes --since 7d --event deleted,unavailable`])
58
- .option("--since <when>", "from this time: an ISO 8601 time, today, yesterday, or 30m, 2h, 1d ago", "1d")
59
- .option("--until <when>", "up to this time, in the same forms")
58
+ .option("--since <time>", "from this time: an ISO 8601 time, today, yesterday, or 30m, 2h, 1d ago", "1d")
59
+ .option("--until <time>", "up to this time, in the same forms")
60
60
  .option(`--event <events>`, `only these, comma separated: ${DOCUMENT_EVENTS.join(", ")}`, eventList)
61
61
  .option("--limit <n>", "how many changes to return", positive, 50)
62
62
  .option("--page <n>", "which page to return", positive, 1)
@@ -58,8 +58,8 @@ export interface CopyAge {
58
58
  }
59
59
  export declare const ageOf: (lastSync: string | undefined, now?: number) => CopyAge;
60
60
  export declare const staleCopy: (provider: string, lastSync: string | undefined, now?: number) => {
61
- next?: undefined;
62
61
  missing?: undefined;
62
+ next?: undefined;
63
63
  meta?: undefined;
64
64
  } | {
65
65
  missing: {
@@ -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,19 +1,13 @@
1
1
  import type { ContentPost } from "../domain/content.js";
2
- import type { AppIdentity } from "../ports/app.js";
3
- import type { Warn } from "../runs/events.js";
4
- import { type Asker, type GuardSettings } from "../sends/guard.js";
2
+ import type { Asker } from "../sends/guard.js";
3
+ import { type ProfileWrites } from "../sends/profile-writes.js";
5
4
  import type { MessageStore } from "../store/store.js";
6
5
  import type { AccountKey } from "../store/types.js";
7
6
  import type { ContentSource } from "./source.js";
8
7
  import { type ContentDraft, type ContentFields, type ContentWriter } from "./writer.js";
9
8
  /** What a CLI hands the content writes for one profile. */
10
- export interface ContentWrites {
9
+ export interface ContentWrites extends ProfileWrites {
11
10
  writer: ContentWriter;
12
- app: AppIdentity;
13
- /** The profile's levels, read on every write so a config change applies at once. */
14
- settings: () => Omit<GuardSettings, "sendsPerHour"> & Partial<Pick<GuardSettings, "sendsPerHour">>;
15
- env?: NodeJS.ProcessEnv;
16
- warn?: Warn;
17
11
  }
18
12
  export interface ContentWriteContext {
19
13
  store: MessageStore;
@@ -1,24 +1,14 @@
1
1
  import { CliError, isCliError } from "@wirecat/cli-base";
2
- import { guardFor } from "../sends/guard.js";
3
2
  import { guardedWrite } from "../sends/guarded.js";
4
- import { keyedGuard } from "../sends/keyed-guard.js";
5
- import { DEFAULT_PERMISSIONS, levelFor } from "../sends/permissions.js";
3
+ import { askedKeys, profileWriteGuard } from "../sends/profile-writes.js";
6
4
  import { newOperationId } from "../sends/send-id.js";
7
5
  import { CONTENT_WRITE_DEFAULTS, contentConflict, POSTS_DELETE_FORCE_KEY, POSTS_PUBLISH_KEY, } from "./writer.js";
8
6
  const PUBLIC = new Set(["published", "scheduled"]);
9
- const guardOf = (context, extra) => {
10
- const settings = context.writes.settings();
11
- const defaults = { ...DEFAULT_PERMISSIONS, ...CONTENT_WRITE_DEFAULTS, ...settings.permissionDefaults };
12
- return keyedGuard((ask) => guardFor(context.writes.app, { ...settings, sendsPerHour: Number.MAX_SAFE_INTEGER, permissionDefaults: defaults }, context.writes.warn ?? (() => { }), context.writes.env, ask), context.ask, (key) => levelFor(settings.permissions, key, defaults).level, extra);
13
- };
7
+ const guardOf = (context, extra) => profileWriteGuard(context.writes, context.ask, CONTENT_WRITE_DEFAULTS, extra);
14
8
  /** Checked and journaled once; a lost answer is `outcome_unknown`, and the owner syncs before writing again. */
15
9
  const written = async (context, key, extra, operationId, act) => {
16
10
  try {
17
- // The keys the owner was asked about here (an `ask` level) need not be asked again by a writer's own call; a key
18
- // allowed here was asked about by nobody, so it confirms nothing.
19
- const settings = context.writes.settings();
20
- const defaults = { ...DEFAULT_PERMISSIONS, ...CONTENT_WRITE_DEFAULTS, ...settings.permissionDefaults };
21
- const asked = [key, ...extra].filter((one) => levelFor(settings.permissions, one, defaults).level === "ask");
11
+ const asked = askedKeys(context.writes, CONTENT_WRITE_DEFAULTS, [key, ...extra]);
22
12
  return await guardedWrite(guardOf(context, extra), { chatId: null, kind: "edit", key, operationId }, () => act(asked));
23
13
  }
24
14
  catch (error) {
@@ -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";
@@ -4,7 +4,8 @@ import type { ServiceApiManifest } from "../../cli/service-api-manifest.js";
4
4
  import { type CrmKind, type CrmRecords } from "../../domain/crm.js";
5
5
  import { type DealKind, type StageOutcome } from "../../domain/deals.js";
6
6
  import type { CrmSource } from "../source.js";
7
- import type { CrmRaw } from "../values.js";
7
+ import { type CrmRaw } from "../values.js";
8
+ import type { CrmWriteFields } from "../writer.js";
8
9
  /**
9
10
  * Where one of our fields comes from in a row the service answered. A path is dotted (`properties.firstname`); the
10
11
  * engine converts the value by the field it fills (an id to a string, a time to epoch ms, a day to `YYYY-MM-DD`).
@@ -170,6 +171,61 @@ export interface CrmManifestFields {
170
171
  is: unknown;
171
172
  } | ((raw: CrmRaw) => boolean);
172
173
  }
174
+ /**
175
+ * How one of our fields is written under the call's `"{values}"`: at `to`, in the shape `each` gives one value, where
176
+ * `"{value}"` stands for ours. Rules that share a `to` merge into one entry, as Attio's personal name takes the first
177
+ * and last name together.
178
+ */
179
+ export interface CrmWriteRule {
180
+ to: string;
181
+ /** Absent, the value itself. */
182
+ each?: unknown;
183
+ /** The service takes a list even for one value (Attio); without it, a list of more than one is refused. */
184
+ list?: true;
185
+ /** A decimal string goes as a number: an amount. */
186
+ number?: true;
187
+ /** The most decimal places the service keeps; more is refused (Attio's currency takes 4). */
188
+ decimals?: number;
189
+ }
190
+ /** A value the service keeps elsewhere (Attio's currency is the attribute's): read once, and another one is refused. */
191
+ export interface CrmFixedValue {
192
+ fixed: CrmOperationCall;
193
+ /** Where the value is in the answer. */
194
+ at: string;
195
+ }
196
+ /** The fields a write of each kind may name, as `CrmWriteFields` has them; `custom` has its own rule. */
197
+ export declare const CRM_WRITE_FIELDS: {
198
+ readonly [K in CrmKind]: readonly string[];
199
+ };
200
+ /** The fields that take a list: each value goes through `each`. */
201
+ export declare const CRM_LIST_FIELDS: readonly string[];
202
+ /**
203
+ * Writes of one kind. A field with no rule is refused before anything is sent. The item is read back by the
204
+ * entity's `get` after each write, so the store keeps what the service holds.
205
+ */
206
+ export interface CrmManifestWrite<K extends CrmKind = CrmKind> {
207
+ /** Its body holds `"{values}"` where the object of values goes. */
208
+ create?: CrmOperationCall;
209
+ /** `"{id}"` in its path, `"{values}"` in its body. Only the fields given are sent. */
210
+ update?: CrmOperationCall;
211
+ /** `"{id}"` in its path; a deal or lead only. */
212
+ remove?: CrmOperationCall;
213
+ /** Where the new record's id is in the create's answer: `data.id.record_id`. */
214
+ id?: string;
215
+ /**
216
+ * Our fields by the names `CrmWriteFields` gives them, and `reason` for a close's reason. `implied`: the field is
217
+ * not sent, as Attio's one pipeline follows from the stage. `currency` may be a fixed value.
218
+ */
219
+ fields: {
220
+ readonly [F in Exclude<keyof CrmWriteFields[K], "custom" | "currency"> | "reason"]?: CrmWriteRule | "implied";
221
+ } & {
222
+ readonly currency?: CrmWriteRule | CrmFixedValue;
223
+ };
224
+ /** The account's own fields, each written at its code; absent, `--field` is refused. */
225
+ custom?: Omit<CrmWriteRule, "to">;
226
+ /** What clears a field: Attio `[]`, HubSpot `""`. Default `null`. */
227
+ clear?: unknown;
228
+ }
173
229
  /** A CRM account described as data: what to call for each kind and where each of our fields is in the answer. */
174
230
  export interface CrmManifest {
175
231
  /** The registry name: `hubspot`, `pipedrive`. */
@@ -197,6 +253,9 @@ export interface CrmManifest {
197
253
  active?: CrmRule;
198
254
  };
199
255
  };
256
+ writes?: {
257
+ readonly [K in CrmKind]?: CrmManifestWrite<K>;
258
+ };
200
259
  }
201
260
  /** Corrects one record after the map; `call` reads more from the service, spent from the run's budget. */
202
261
  export type CrmAfterHook<K extends CrmKind> = (record: CrmRecords[K], raw: CrmRaw, service: {
@@ -3,7 +3,17 @@ import * as v from "valibot";
3
3
  import { CRM_KINDS } from "../../domain/crm.js";
4
4
  import { DEAL_KINDS, STAGE_OUTCOMES } from "../../domain/deals.js";
5
5
  import { editDistance } from "../../search/correct.js";
6
+ import { isRaw } from "../values.js";
6
7
  import { FIELDS } from "./map.js";
8
+ /** The fields a write of each kind may name, as `CrmWriteFields` has them; `custom` has its own rule. */
9
+ export const CRM_WRITE_FIELDS = {
10
+ deal: ["title", "pipeline", "stage", "amount", "currency", "closeDate", "organization", "people", "owner", "reason"],
11
+ lead: ["title", "pipeline", "stage", "amount", "currency", "closeDate", "organization", "people", "owner", "reason"],
12
+ person: ["name", "firstName", "lastName", "position", "emails", "phones", "owner"],
13
+ organization: ["name", "emails", "phones", "owner"],
14
+ };
15
+ /** The fields that take a list: each value goes through `each`. */
16
+ export const CRM_LIST_FIELDS = ["emails", "phones", "people"];
7
17
  const path = v.pipe(v.string(), v.regex(/^[^.\s]+(\.[^.\s]+)*$/, "a dotted path such as properties.name"));
8
18
  const paths = v.pipe(v.array(path), v.minLength(1));
9
19
  export const crmRuleSchema = v.union([
@@ -77,6 +87,22 @@ const fields = v.strictObject({
77
87
  keep: v.optional(v.union([v.strictObject({ path, is: v.unknown() }), v.function()])),
78
88
  });
79
89
  const kind = v.picklist(CRM_KINDS);
90
+ const writeShape = {
91
+ each: v.optional(v.unknown()),
92
+ list: v.optional(v.literal(true)),
93
+ number: v.optional(v.literal(true)),
94
+ decimals: v.optional(v.pipe(v.number(), v.integer(), v.minValue(0))),
95
+ };
96
+ const writeRule = v.strictObject({ to: v.pipe(v.string(), v.minLength(1)), ...writeShape });
97
+ const write = v.strictObject({
98
+ create: v.optional(call),
99
+ update: v.optional(call),
100
+ remove: v.optional(call),
101
+ id: v.optional(path),
102
+ fields: v.record(v.string(), v.union([writeRule, v.literal("implied"), v.strictObject({ fixed: call, at: path })])),
103
+ custom: v.optional(v.strictObject(writeShape)),
104
+ clear: v.optional(v.unknown()),
105
+ });
80
106
  const schema = v.strictObject({
81
107
  provider: v.pipe(v.string(), v.regex(/^[a-z][a-z0-9-]*$/, "a registry name such as hubspot")),
82
108
  kinds: v.pipe(v.array(kind), v.minLength(1)),
@@ -94,6 +120,7 @@ const schema = v.strictObject({
94
120
  active: v.optional(rule),
95
121
  }),
96
122
  })),
123
+ writes: v.optional(v.record(kind, v.optional(write))),
97
124
  });
98
125
  const invalid = (where, message) => new CliError("configuration_error", `source manifest: ${where}: ${message}`, { reason: "manifest.invalid" });
99
126
  /** The known name a typo most likely meant: at most two edits away, else none. */
@@ -191,5 +218,66 @@ export const parseCrmManifest = (input, api) => {
191
218
  checkCall(`fields.${kind}.call`, one.call, true);
192
219
  if (manifest.users)
193
220
  checkCall("users.call", manifest.users.call, true);
221
+ for (const [kind, one] of Object.entries(manifest.writes ?? {}))
222
+ if (one)
223
+ checkWrite(kind, one, manifest, { operations, known, checkCall });
194
224
  return manifest;
195
225
  };
226
+ const checkWrite = (kind, one, manifest, { operations, known, checkCall, }) => {
227
+ const where = `writes.${kind}`;
228
+ if (!manifest.kinds.includes(kind))
229
+ throw invalid(where, `${kind} is not in kinds`);
230
+ if (!manifest.entities[kind]?.get)
231
+ throw invalid(where, `each write is read back by entities.${kind}.get, and it has none`);
232
+ if (!one.create && !one.update && !one.remove)
233
+ throw invalid(where, "names no create, update or remove");
234
+ if (one.remove && !DEAL_KINDS.includes(kind))
235
+ throw invalid(`${where}.remove`, "only a deal or a lead is removed");
236
+ if (one.create && one.id === undefined)
237
+ throw invalid(`${where}.id`, "a create says where the new record's id is");
238
+ for (const verb of ["create", "update", "remove"]) {
239
+ const sent = one[verb];
240
+ if (!sent)
241
+ continue;
242
+ const operation = operations.get(sent.operation);
243
+ if (!operation) {
244
+ const near = nearest(sent.operation, known);
245
+ throw invalid(`${where}.${verb}.operation`, `no operation ${sent.operation} in the API${near ? `; did you mean ${near}?` : ""}`);
246
+ }
247
+ if (operation.effect === "read")
248
+ throw invalid(`${where}.${verb}.operation`, `${sent.operation} is a read`);
249
+ if (verb !== "create" && !hasPlaceholder([sent.path, sent.query, sent.body], "{id}"))
250
+ throw invalid(`${where}.${verb}`, 'no "{id}" in its path, query or body');
251
+ if (verb !== "remove" && !hasPlaceholder(sent.body, "{values}"))
252
+ throw invalid(`${where}.${verb}`, 'no "{values}" in its body');
253
+ }
254
+ const fields = CRM_WRITE_FIELDS[kind];
255
+ const shared = new Map();
256
+ for (const [field, rule] of Object.entries(one.fields)) {
257
+ if (!fields.includes(field)) {
258
+ const near = nearest(field, fields);
259
+ throw invalid(`${where}.fields.${field}`, `a ${kind} writes no such field${near ? `; did you mean ${near}?` : ""}`);
260
+ }
261
+ if (rule === "implied") {
262
+ if (field !== "pipeline")
263
+ throw invalid(`${where}.fields.${field}`, "only a pipeline follows from the stage");
264
+ continue;
265
+ }
266
+ if ("fixed" in rule) {
267
+ if (field !== "currency")
268
+ throw invalid(`${where}.fields.${field}`, "only a currency is a fixed value");
269
+ checkCall(`${where}.fields.${field}.fixed`, rule.fixed, false);
270
+ continue;
271
+ }
272
+ if (rule.each !== undefined && !hasPlaceholder(rule.each, "{value}"))
273
+ throw invalid(`${where}.fields.${field}.each`, 'no "{value}" in it');
274
+ shared.set(rule.to, [...(shared.get(rule.to) ?? []), field]);
275
+ }
276
+ for (const [to, named] of shared) {
277
+ const rules = named.map((field) => one.fields[field]);
278
+ if (named.length > 1 && !named.every((field, n) => !CRM_LIST_FIELDS.includes(field) && isRaw(rules[n]?.each)))
279
+ throw invalid(`${where}.fields`, `${named.join(", ")} share ${to}: only single values in objects merge`);
280
+ }
281
+ if (one.custom?.each !== undefined && !hasPlaceholder(one.custom.each, "{value}"))
282
+ throw invalid(`${where}.custom.each`, 'no "{value}" in it');
283
+ };
@@ -1,7 +1,9 @@
1
+ import type { ApiCommandInput } from "../../cli/bot/api.js";
1
2
  import type { ServiceApiCall } from "../../cli/service-api-call.js";
2
3
  import { type ServiceApiManifest } from "../../cli/service-api-manifest.js";
3
- import type { CrmSource } from "../source.js";
4
- import { type CrmManifestHooks } from "./manifest.js";
4
+ import type { CrmKind, CrmRecords } from "../../domain/crm.js";
5
+ import type { CrmCallContext, CrmSource } from "../source.js";
6
+ import { type CrmManifestHooks, type CrmOperationCall } from "./manifest.js";
5
7
  export interface CrmManifestSourceOptions {
6
8
  /** The generated API manifest the operations are named in: their paths, paging and sign-in. */
7
9
  api: ServiceApiManifest;
@@ -10,9 +12,26 @@ export interface CrmManifestSourceOptions {
10
12
  now?: () => number;
11
13
  hooks?: CrmManifestHooks;
12
14
  }
15
+ export interface Slots {
16
+ since?: string;
17
+ select?: readonly string[];
18
+ id?: string;
19
+ query?: string;
20
+ /** A write's values, put in whole: what they hold is never filled. */
21
+ values?: Readonly<Record<string, unknown>>;
22
+ /** One value in a write rule's `each`. */
23
+ value?: unknown;
24
+ }
25
+ /** Fills each `"{slot}"` by its name in `Slots`; an empty select drops the parameter it stands for. */
26
+ export declare const fill: (value: unknown, slots: Slots) => unknown;
27
+ export declare const inputOf: (call: CrmOperationCall, slots: Slots) => ApiCommandInput;
28
+ /** A source from a manifest also reads one record of any kind by its entity's `get`: a writer's read-back. */
29
+ export interface CrmManifestSource extends CrmSource {
30
+ record<K extends CrmKind>(kind: K, externalId: string, context?: CrmCallContext): Promise<CrmRecords[K] | null>;
31
+ }
13
32
  /**
14
33
  * A `CrmSource` read from a manifest: every kind listed and read for changes by the operations it names, paged by each
15
34
  * operation's own `pagination`, each row mapped onto the shared schema. Deletions are found by a pass over every id.
16
35
  * What the manifest cannot say comes from `hooks`.
17
36
  */
18
- export declare const crmSourceFromManifest: (input: unknown, options: CrmManifestSourceOptions) => CrmSource;
37
+ export declare const crmSourceFromManifest: (input: unknown, options: CrmManifestSourceOptions) => CrmManifestSource;
@@ -12,8 +12,12 @@ const MOST_PAGES = 500;
12
12
  /** Contacts or companies a deal names, read one by one, per page of a sync round. */
13
13
  const LINKED_PAGE = 50;
14
14
  const DROP = Symbol("drop");
15
- /** Fills `"{since}"`, `"{select}"`, `"{id}"` and `"{query}"`; an empty select drops the parameter it stands for. */
16
- const fill = (value, slots) => {
15
+ /** Fills each `"{slot}"` by its name in `Slots`; an empty select drops the parameter it stands for. */
16
+ export const fill = (value, slots) => {
17
+ if (value === "{values}")
18
+ return slots.values ?? DROP;
19
+ if (value === "{value}")
20
+ return slots.value ?? DROP;
17
21
  if (value === "{since}")
18
22
  return slots.since ?? DROP;
19
23
  if (value === "{select}")
@@ -31,7 +35,7 @@ const fill = (value, slots) => {
31
35
  }));
32
36
  return value;
33
37
  };
34
- const inputOf = (call, slots) => {
38
+ export const inputOf = (call, slots) => {
35
39
  const path = fill(call.path ?? {}, slots);
36
40
  const query = fill(call.query ?? {}, slots);
37
41
  const body = call.body === undefined ? undefined : fill(call.body, slots);
@@ -413,6 +417,9 @@ export const crmSourceFromManifest = (input, options) => {
413
417
  async get(kind, externalId, context) {
414
418
  return readOne(kind, externalId, metered(context), context);
415
419
  },
420
+ async record(kind, externalId, context) {
421
+ return readOne(kind, externalId, metered(context), context);
422
+ },
416
423
  ...(manifest.fields
417
424
  ? { fields: (kind, context) => fieldsOf(kind, metered(context), context) }
418
425
  : {}),
@@ -0,0 +1,39 @@
1
+ import { type ServiceApiPermissionsInput } from "../../cli/service-api.js";
2
+ import { type ServiceApiCall, type ServiceApiCallOptions } from "../../cli/service-api-call.js";
3
+ import type { ServiceApiManifest } from "../../cli/service-api-manifest.js";
4
+ import type { CrmKind } from "../../domain/crm.js";
5
+ import type { PermissionKey } from "../../sends/permissions.js";
6
+ import { type CrmVerb, type CrmWriteCapabilities, type CrmWriter } from "../writer.js";
7
+ import { type CrmWrites } from "../writes.js";
8
+ import { type CrmManifestSource } from "./source.js";
9
+ export interface CrmManifestWriterOptions {
10
+ api: ServiceApiManifest;
11
+ /** The service's name in messages: "Attio". */
12
+ service: string;
13
+ /** Sends one operation with no guard of its own (`serviceApiSend`): `crm/writes.ts` guards every writer call. */
14
+ send: ServiceApiCall;
15
+ /** The source over the same manifest: the read-back after each write, and the pipelines a close looks in. */
16
+ source: () => CrmManifestSource;
17
+ }
18
+ /** What the manifest's writes take, for `addCrmCommands({ writes })`; none when it describes no writes. */
19
+ export declare const crmManifestWriteCapabilities: (input: unknown, api: ServiceApiManifest) => CrmWriteCapabilities | undefined;
20
+ /**
21
+ * The `api` keys each CRM write also checks, those of the operation it sends, so `api.<operation>: deny` stops the
22
+ * write too: for `CrmWrites.alsoChecks` and `crmAlsoChecks`, so `--dry-run` names them.
23
+ */
24
+ export declare const crmManifestWriteKeys: (input: unknown, api: ServiceApiManifest, bodyPermissions?: ServiceApiPermissionsInput["bodyPermissions"]) => ((kind: CrmKind, verb: CrmVerb) => PermissionKey[]);
25
+ /**
26
+ * A `CrmWriter` from a manifest's `writes`: each of our fields goes to the service by its rule, a field with no rule is
27
+ * refused before anything is sent, and every write is sent once and read back by the entity's `get`, as a sync maps
28
+ * it. A close moves the item to the first stage of its pipeline with that outcome.
29
+ */
30
+ export declare const crmWriterFromManifest: (input: unknown, options: CrmManifestWriterOptions) => CrmWriter;
31
+ export interface CrmManifestWritesOptions extends ServiceApiCallOptions, Pick<ServiceApiPermissionsInput, "bodyPermissions">, Omit<CrmWrites, "writer" | "alsoChecks"> {
32
+ /** The CLI's source over the same manifest (`crmSourceFromManifest`). */
33
+ source: () => CrmManifestSource;
34
+ }
35
+ /**
36
+ * `CrmRun.writes` for a CLI whose writes its manifest describes: the writer over the CLI's fetch and token, and the
37
+ * `api` keys of each operation it sends as `alsoChecks`. The writes' guard asks before each one and journals it.
38
+ */
39
+ export declare const crmManifestWrites: (input: unknown, options: CrmManifestWritesOptions) => CrmWrites;