@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
@@ -0,0 +1,298 @@
1
+ import { CliError, isCliError } from "@wirecat/cli-base";
2
+ import { serviceApiOwnKeys } from "../../cli/service-api.js";
3
+ import { serviceApiSend } from "../../cli/service-api-call.js";
4
+ import { DEAL_KINDS } from "../../domain/deals.js";
5
+ import { fullName, id, isRaw, text } from "../values.js";
6
+ import { CRM_VERBS } from "../writer.js";
7
+ import { foldFieldName } from "../writes.js";
8
+ import { parseCrmManifest, } from "./manifest.js";
9
+ import { at } from "./map.js";
10
+ import { fill, inputOf } from "./source.js";
11
+ const CALL_OF = {
12
+ create: "create",
13
+ update: "update",
14
+ move: "update",
15
+ close: "update",
16
+ remove: "remove",
17
+ };
18
+ const CLEAR = Symbol("clear");
19
+ const isDealKind = (kind) => DEAL_KINDS.includes(kind);
20
+ const ruleOf = (one, field) => one.fields[field];
21
+ const takes = (kind, one, verb) => verb === "move" || verb === "close"
22
+ ? isDealKind(kind) && one.update !== undefined && typeof ruleOf(one, "stage") === "object"
23
+ : one[CALL_OF[verb]] !== undefined;
24
+ const capabilitiesOf = (manifest) => {
25
+ const written = manifest.kinds.flatMap((kind) => {
26
+ const one = manifest.writes?.[kind];
27
+ return one ? [{ kind, one }] : [];
28
+ });
29
+ if (written.length === 0)
30
+ return undefined;
31
+ return {
32
+ kinds: written.map(({ kind }) => kind),
33
+ verbs: CRM_VERBS.filter((verb) => written.some(({ kind, one }) => takes(kind, one, verb))),
34
+ // No slot sends the operation id, so a repeated write would be made again.
35
+ idempotent: false,
36
+ };
37
+ };
38
+ /** What the manifest's writes take, for `addCrmCommands({ writes })`; none when it describes no writes. */
39
+ export const crmManifestWriteCapabilities = (input, api) => capabilitiesOf(parseCrmManifest(input, api));
40
+ /**
41
+ * The `api` keys each CRM write also checks, those of the operation it sends, so `api.<operation>: deny` stops the
42
+ * write too: for `CrmWrites.alsoChecks` and `crmAlsoChecks`, so `--dry-run` names them.
43
+ */
44
+ export const crmManifestWriteKeys = (input, api, bodyPermissions) => {
45
+ const manifest = parseCrmManifest(input, api);
46
+ const operations = new Map(api.operations.map((one) => [one.id, one]));
47
+ return (kind, verb) => {
48
+ const call = manifest.writes?.[kind]?.[CALL_OF[verb]];
49
+ const operation = call && operations.get(call.operation);
50
+ return operation ? serviceApiOwnKeys(operation, bodyPermissions) : [];
51
+ };
52
+ };
53
+ const refused = (message, param) => new CliError("validation_error", message, { reason: "crm.record-field", sent: false, ...(param ? { param } : {}) });
54
+ /** A merge of the entries rules that share a key give: each object's keys beside the others'. */
55
+ /** Our fields that write one key of the service together, by that key: Attio's name and its parts. */
56
+ const sharedOf = (one) => {
57
+ const by = new Map();
58
+ for (const [field, rule] of Object.entries(one.fields))
59
+ if (typeof rule === "object" && "to" in rule)
60
+ by.set(rule.to, [...(by.get(rule.to) ?? []), field]);
61
+ return [...by.values()].filter((fields) => fields.length > 1);
62
+ };
63
+ const merged = (entries, list) => {
64
+ const given = entries.filter((one) => one !== CLEAR);
65
+ if (given.length === 0)
66
+ return CLEAR;
67
+ if (given.length === 1)
68
+ return given[0];
69
+ const first = (one) => (list && Array.isArray(one) ? one[0] : one);
70
+ const whole = Object.assign({}, ...given.map((one) => (isRaw(first(one)) ? first(one) : {})));
71
+ return list ? [whole] : whole;
72
+ };
73
+ /**
74
+ * A `CrmWriter` from a manifest's `writes`: each of our fields goes to the service by its rule, a field with no rule is
75
+ * refused before anything is sent, and every write is sent once and read back by the entity's `get`, as a sync maps
76
+ * it. A close moves the item to the first stage of its pipeline with that outcome.
77
+ */
78
+ export const crmWriterFromManifest = (input, options) => {
79
+ const manifest = parseCrmManifest(input, options.api);
80
+ const capabilities = capabilitiesOf(manifest);
81
+ if (!capabilities)
82
+ throw new CliError("configuration_error", "source manifest: writes: it describes no writes", {
83
+ reason: "manifest.invalid",
84
+ });
85
+ const { service, send } = options;
86
+ const specOf = (kind, verb) => {
87
+ const one = manifest.writes?.[kind];
88
+ if (!one || !takes(kind, one, verb))
89
+ throw new CliError("validation_error", `${service} takes no ${verb} of a ${kind} here`, {
90
+ reason: "crm.write-unsupported",
91
+ sent: false,
92
+ });
93
+ return one;
94
+ };
95
+ const sent = (call, slots) => send(call.operation, inputOf(call, slots));
96
+ const held = new Map();
97
+ const fixedOf = (rule) => {
98
+ let found = held.get(rule);
99
+ if (!found) {
100
+ found = sent(rule.fixed, {}).then((answer) => text(at(answer, rule.at)));
101
+ found.catch(() => held.delete(rule));
102
+ held.set(rule, found);
103
+ }
104
+ return found;
105
+ };
106
+ const encode = (kind, field, rule, value) => {
107
+ if (value === null)
108
+ return CLEAR;
109
+ const items = (Array.isArray(value) ? value : [value]).map((one) => {
110
+ if (!isRaw(one))
111
+ return one;
112
+ if (one.role !== "contact")
113
+ throw refused(`${service} keeps no role of a ${kind}'s people; give each as a contact`);
114
+ return one.externalId;
115
+ });
116
+ const entries = items.map((one) => {
117
+ const decimals = /\.(\d+)$/.exec(String(one))?.[1]?.length ?? 0;
118
+ if (rule.decimals !== undefined && decimals > rule.decimals)
119
+ throw refused(`${service} keeps a ${kind}'s ${field} to ${rule.decimals} decimal places`, field);
120
+ const given = rule.number ? Number(one) : one;
121
+ return rule.each === undefined ? given : fill(rule.each, { value: given });
122
+ });
123
+ if (rule.list)
124
+ return entries;
125
+ if (entries.length > 1)
126
+ throw refused(`${service} keeps one ${field} of a ${kind}; give one`);
127
+ return entries.length ? entries[0] : CLEAR;
128
+ };
129
+ /** The whole name a service keeps beside its parts, from the parts; or the parts it keeps alone, from the name. */
130
+ const namesOf = (one, given) => {
131
+ const { name, firstName, lastName } = given;
132
+ if (name === undefined && (typeof firstName === "string" || typeof lastName === "string")) {
133
+ const whole = fullName(firstName, lastName);
134
+ return ruleOf(one, "name") && whole ? { ...given, name: whole } : given;
135
+ }
136
+ if (typeof name !== "string" || firstName !== undefined || lastName !== undefined)
137
+ return given;
138
+ if (!ruleOf(one, "firstName"))
139
+ return given;
140
+ const [first, ...rest] = name.trim().split(/\s+/);
141
+ const { name: _, ...parts } = given;
142
+ return {
143
+ ...parts,
144
+ ...(ruleOf(one, "name") ? { name } : {}),
145
+ firstName: first ?? "",
146
+ lastName: rest.join(" ") || null,
147
+ };
148
+ };
149
+ /**
150
+ * The fields an update leaves out of a key it writes with others, from the record as the service holds it: an update
151
+ * replaces the whole value (Attio's name), so a part not sent would be lost. A contact's whole name is not read back
152
+ * when a part is given, nor its parts when the name is: `namesOf` makes them from what was given.
153
+ */
154
+ const completed = async (kind, one, externalId, given) => {
155
+ const person = kind === "person";
156
+ const parts = person && (given.firstName !== undefined || given.lastName !== undefined);
157
+ const whole = person && given.name !== undefined && !parts;
158
+ const missing = sharedOf(one).flatMap((fields) => fields.some((field) => given[field] !== undefined)
159
+ ? fields.filter((field) => given[field] === undefined &&
160
+ !(parts && field === "name") &&
161
+ !(whole && (field === "firstName" || field === "lastName")))
162
+ : []);
163
+ if (missing.length === 0)
164
+ return given;
165
+ const record = (await options.source().record(kind, externalId));
166
+ if (!record)
167
+ throw new CliError("not_found", `${service} has no ${kind} ${externalId}`, { sent: false });
168
+ return {
169
+ ...given,
170
+ ...Object.fromEntries(missing.map((field) => [field, record[field === "owner" ? "assignee" : field] ?? null])),
171
+ };
172
+ };
173
+ /** The object `"{values}"` stands for; a field the manifest has no rule for is refused, with nothing sent. */
174
+ const valuesOf = async (kind, one, written) => {
175
+ const fields = written;
176
+ const given = kind === "person" ? namesOf(one, fields) : fields;
177
+ const parts = new Map();
178
+ const add = (to, list, entry) => parts.set(to, { list, entries: [...(parts.get(to)?.entries ?? []), entry] });
179
+ for (const [field, value] of Object.entries(given)) {
180
+ if (value === undefined || field === "custom")
181
+ continue;
182
+ const rule = ruleOf(one, field);
183
+ if (rule === undefined)
184
+ throw refused(`${service} takes no ${field} of a ${kind} here`, field);
185
+ if (rule === "implied")
186
+ continue;
187
+ if ("fixed" in rule) {
188
+ if (value === null)
189
+ continue;
190
+ const currency = await fixedOf(rule);
191
+ if (currency === null)
192
+ throw refused(`${service} names no ${field} for a ${kind}`, field);
193
+ if (String(value).toUpperCase() !== currency.toUpperCase())
194
+ throw refused(`${service} keeps a ${kind}'s amount in ${currency}; give that ${field} or none`, field);
195
+ continue;
196
+ }
197
+ add(rule.to, rule.list === true, encode(kind, field, rule, value));
198
+ }
199
+ const custom = Object.entries(given.custom ?? {});
200
+ if (custom.length && !one.custom)
201
+ throw refused(`${service} takes no --field of a ${kind} here`, "--field");
202
+ const own = new Set(Object.values(one.fields).flatMap((rule) => typeof rule === "object" && "to" in rule ? [foldFieldName(rule.to)] : []));
203
+ // Only a code the service defines as the account's own: Attio also takes an attribute's id, which could be a stage.
204
+ const source = options.source();
205
+ const defined = custom.length && manifest.fields?.[kind] && source.fields
206
+ ? (await source.fields(kind)).map(({ code }) => code)
207
+ : [];
208
+ for (const [code, value] of custom) {
209
+ if (own.has(foldFieldName(code)))
210
+ throw refused(`${code} is one of ${service}'s own fields; set it with its own option, not --field`, "--field");
211
+ if (!defined.includes(code))
212
+ throw refused(`${service} defines no field ${code} of a ${kind}; fields list names them`, "--field");
213
+ const rule = one.custom;
214
+ add(code, rule.list === true, encode(kind, code, rule, value));
215
+ }
216
+ const clear = one.clear === undefined ? null : one.clear;
217
+ return Object.fromEntries([...parts].map(([to, { list, entries }]) => {
218
+ const value = merged(entries, list);
219
+ return [to, value === CLEAR ? clear : value];
220
+ }));
221
+ };
222
+ /** The write went through: a failed read-back must never read as a failed write, or the owner repeats it. */
223
+ const readBack = async (kind, externalId, written) => {
224
+ try {
225
+ const found = await options.source().record(kind, externalId);
226
+ if (!found)
227
+ throw new CliError("not_found", `${service} has no ${kind} ${externalId}`);
228
+ return found;
229
+ }
230
+ catch (error) {
231
+ throw new CliError("invalid_response", `${service} made the change to ${kind} ${externalId}, but reading it back failed` +
232
+ `${isCliError(error) ? ` (${error.code})` : ""}; run sync to store it — do not write it again`, { operation_id: written.operationId, external_id: externalId, sent: true });
233
+ }
234
+ };
235
+ const update = async (kind, externalId, given, written, verb = "update") => {
236
+ const one = specOf(kind, verb);
237
+ const values = await valuesOf(kind, one, await completed(kind, one, externalId, given));
238
+ if (Object.keys(values).length === 0)
239
+ throw refused("nothing to change: name a field");
240
+ await sent(one.update, { id: externalId, values });
241
+ return readBack(kind, externalId, written);
242
+ };
243
+ /** The item's own pipeline's first stage with that outcome, as HubSpot closes a deal. */
244
+ const closingStage = async (kind, externalId, outcome) => {
245
+ const item = await options.source().record(kind, externalId);
246
+ if (!item)
247
+ throw new CliError("not_found", `${service} has no ${kind} ${externalId}`, { sent: false });
248
+ const pipeline = (await options.source().pipelines(kind)).find((one) => one.externalId === item.pipeline);
249
+ const stage = pipeline?.stages.find((one) => one.outcome === outcome);
250
+ if (!stage)
251
+ throw refused(`the ${kind}'s pipeline ${item.pipeline} has no ${outcome} stage in ${service}`);
252
+ return stage.externalId;
253
+ };
254
+ return {
255
+ provider: manifest.provider,
256
+ capabilities,
257
+ async create(kind, draft, written) {
258
+ const one = specOf(kind, "create");
259
+ const answer = await sent(one.create, { values: await valuesOf(kind, one, draft) });
260
+ const externalId = id(at(answer, one.id));
261
+ if (externalId === null)
262
+ throw new CliError("invalid_response", `${service} answered the new ${kind} without its id; run sync first`, {
263
+ operation_id: written.operationId,
264
+ sent: true,
265
+ });
266
+ return readBack(kind, externalId, written);
267
+ },
268
+ update: (kind, externalId, patch, written) => update(kind, externalId, patch, written),
269
+ move: (kind, externalId, stage, written) => update(kind, externalId, { stage }, written, "move"),
270
+ async close(kind, externalId, outcome, written) {
271
+ const one = specOf(kind, "close");
272
+ if (written.reason !== undefined && ruleOf(one, "reason") === undefined)
273
+ throw refused(`${service} keeps no reason for a close of a ${kind} here`, "--reason");
274
+ const stage = await closingStage(kind, externalId, outcome);
275
+ const reason = written.reason === undefined ? {} : { reason: written.reason };
276
+ return update(kind, externalId, { stage, ...reason }, written, "close");
277
+ },
278
+ async remove(kind, externalId) {
279
+ await sent(specOf(kind, "remove").remove, { id: externalId });
280
+ },
281
+ };
282
+ };
283
+ /**
284
+ * `CrmRun.writes` for a CLI whose writes its manifest describes: the writer over the CLI's fetch and token, and the
285
+ * `api` keys of each operation it sends as `alsoChecks`. The writes' guard asks before each one and journals it.
286
+ */
287
+ export const crmManifestWrites = (input, options) => {
288
+ const { manifest: api, service, source, app, settings, self, env, warn } = options;
289
+ return {
290
+ writer: crmWriterFromManifest(input, { api, service, send: serviceApiSend(options), source }),
291
+ alsoChecks: crmManifestWriteKeys(input, api, options.bodyPermissions),
292
+ app,
293
+ settings,
294
+ ...(self === undefined ? {} : { self }),
295
+ ...(env === undefined ? {} : { env }),
296
+ ...(warn === undefined ? {} : { warn }),
297
+ };
298
+ };
@@ -1,6 +1,6 @@
1
1
  export { ACME_CALENDAR, ACME_MAIL, ACME_NOW, ACME_OPENED, ACME_PORTAL, ACME_TELEGRAM, type AcmeScenario, acmeScenario, } from "./acme-scenario.js";
2
2
  export { type CrmFilesFixture, crmFilesContract } from "./files-contract.js";
3
- export { type CrmManifestFake, type CrmManifestFakeOptions, type CrmManifestFixtureOptions, crmManifestContract, crmManifestFake, crmManifestFixture, FAKE_MANIFEST_TOKEN, } from "./manifest-fake.js";
3
+ export { type CrmManifestFake, type CrmManifestFakeOptions, type CrmManifestFixtureOptions, crmManifestContract, crmManifestFake, crmManifestFixture, crmManifestWriteContract, crmManifestWriteFixture, FAKE_MANIFEST_TOKEN, } from "./manifest-fake.js";
4
4
  export { exampleDeal, exampleLead, exampleOrganization, examplePerson, FAKE_CRM_ALIASES, FAKE_FILE_TOKEN, type FakeCrmFile, type FakeCrmSource, type FakeCrmSourceOptions, type FakeCrmWrite, fakeCrmSource, LEAD_PIPELINE, SALES_PIPELINE, SOURCE_FIELD, } from "./source.js";
5
5
  export { type CrmSourceFaults, type CrmSourceFixture, crmSourceContract } from "./source-contract.js";
6
6
  export { CRM_TRAIT_COMBINATIONS, type CrmSyncFixture, crmSyncContract } from "./sync-contract.js";
@@ -1,6 +1,6 @@
1
1
  export { ACME_CALENDAR, ACME_MAIL, ACME_NOW, ACME_OPENED, ACME_PORTAL, ACME_TELEGRAM, acmeScenario, } from "./acme-scenario.js";
2
2
  export { crmFilesContract } from "./files-contract.js";
3
- export { crmManifestContract, crmManifestFake, crmManifestFixture, FAKE_MANIFEST_TOKEN, } from "./manifest-fake.js";
3
+ export { crmManifestContract, crmManifestFake, crmManifestFixture, crmManifestWriteContract, crmManifestWriteFixture, FAKE_MANIFEST_TOKEN, } from "./manifest-fake.js";
4
4
  export { exampleDeal, exampleLead, exampleOrganization, examplePerson, FAKE_CRM_ALIASES, FAKE_FILE_TOKEN, fakeCrmSource, LEAD_PIPELINE, SALES_PIPELINE, SOURCE_FIELD, } from "./source.js";
5
5
  export { crmSourceContract } from "./source-contract.js";
6
6
  export { CRM_TRAIT_COMBINATIONS, crmSyncContract } from "./sync-contract.js";
@@ -5,6 +5,7 @@ import type { ContractCase } from "../../meetings/index.js";
5
5
  import { type CrmManifest, type CrmManifestHooks } from "../manifest/manifest.js";
6
6
  import { type CrmRaw } from "../values.js";
7
7
  import { type CrmSourceFixture } from "./source-contract.js";
8
+ import { type CrmWriteFixture } from "./write-contract.js";
8
9
  type Definitions = Readonly<Record<string, SchemaNode>>;
9
10
  export interface CrmManifestFakeOptions {
10
11
  /** The generated API manifest the source manifest names its operations in. */
@@ -21,6 +22,10 @@ export interface CrmManifestFake extends FakeApi {
21
22
  deny(kind: CrmKind, id: string, status: number): void;
22
23
  /** Moves one row's change time to now, for the next read of changes to list it. */
23
24
  touch(kind: CrmKind, id: string): void;
25
+ /** Makes the next write's answer lost after the service made the change, as a dropped connection does. */
26
+ loseNextAnswer(): void;
27
+ /** How many write requests reached the service so far. */
28
+ requests(): number;
24
29
  }
25
30
  export declare const FAKE_MANIFEST_TOKEN = "fake-manifest-token";
26
31
  /**
@@ -44,4 +49,13 @@ export declare const crmManifestFixture: (manifest: CrmManifest, options: CrmMan
44
49
  * test runs, `for (const { name, run } of crmManifestContract(SOURCE, { api, definitions })) it(name, run)`.
45
50
  */
46
51
  export declare const crmManifestContract: (manifest: CrmManifest, options: CrmManifestFixtureOptions) => ContractCase[];
52
+ /**
53
+ * A `crmWriteContract` fixture for a writer built from a manifest's `writes`, over `crmManifestFake`: the writer, the
54
+ * first pipeline of the deal kind it writes, the service's own names of stage and owner, and the fake.
55
+ */
56
+ export declare const crmManifestWriteFixture: (manifest: CrmManifest, options: CrmManifestFixtureOptions) => Promise<CrmWriteFixture & {
57
+ fake: CrmManifestFake;
58
+ }>;
59
+ /** `crmWriteContract` over `crmManifestWriteFixture`, each case failing too when the fake refused a call. */
60
+ export declare const crmManifestWriteContract: (manifest: CrmManifest, options: CrmManifestFixtureOptions) => ContractCase[];
47
61
  export {};