@wirecat/cli-core 0.669.0 → 0.670.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 (54) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/dist/background/daily-archive-timer.d.ts +1 -1
  3. package/dist/calendar/mcp/index.d.ts +12 -12
  4. package/dist/cli/documents/words.d.ts +1 -1
  5. package/dist/cli/store-settings.js +5 -3
  6. package/dist/crm/cli/csv.d.ts +1 -1
  7. package/dist/crm/cli/csv.js +2 -2
  8. package/dist/crm/cli/index.d.ts +11 -1
  9. package/dist/crm/cli/index.js +11 -5
  10. package/dist/crm/cli/records.d.ts +94 -0
  11. package/dist/crm/cli/records.js +412 -0
  12. package/dist/crm/foreign-contacts.d.ts +34 -0
  13. package/dist/crm/foreign-contacts.js +104 -0
  14. package/dist/crm/index.d.ts +9 -3
  15. package/dist/crm/index.js +7 -1
  16. package/dist/crm/provider-call.d.ts +23 -0
  17. package/dist/crm/provider-call.js +49 -0
  18. package/dist/crm/query.d.ts +32 -0
  19. package/dist/crm/query.js +122 -0
  20. package/dist/crm/source.d.ts +41 -4
  21. package/dist/crm/sync.d.ts +1 -1
  22. package/dist/crm/sync.js +13 -7
  23. package/dist/crm/testing/source-contract.d.ts +5 -0
  24. package/dist/crm/testing/source-contract.js +39 -0
  25. package/dist/crm/testing/source.d.ts +9 -3
  26. package/dist/crm/testing/source.js +109 -10
  27. package/dist/crm/testing/write-contract.d.ts +2 -2
  28. package/dist/crm/testing/write-contract.js +41 -2
  29. package/dist/crm/values.d.ts +33 -0
  30. package/dist/crm/values.js +75 -0
  31. package/dist/crm/walk.d.ts +18 -0
  32. package/dist/crm/walk.js +23 -0
  33. package/dist/crm/writer.d.ts +41 -6
  34. package/dist/crm/writer.js +16 -10
  35. package/dist/crm/writes.d.ts +38 -2
  36. package/dist/crm/writes.js +163 -9
  37. package/dist/domain/crm.d.ts +41 -5
  38. package/dist/entities/deal.d.ts +8 -2
  39. package/dist/entities/deal.js +4 -1
  40. package/dist/errors/reasons.js +23 -2
  41. package/dist/oauth/index.d.ts +1 -1
  42. package/dist/oauth/index.js +1 -1
  43. package/dist/oauth/keeper.js +4 -0
  44. package/dist/oauth/storage.d.ts +21 -0
  45. package/dist/oauth/storage.js +32 -1
  46. package/dist/store/sqlite/crm-contacts.d.ts +5 -4
  47. package/dist/store/sqlite/crm-contacts.js +8 -4
  48. package/dist/store/sqlite/crm-rows.d.ts +1 -0
  49. package/dist/store/sqlite/crm-rows.js +37 -7
  50. package/dist/store/sqlite/crm-settings.d.ts +2 -2
  51. package/dist/store/sqlite/crm-settings.js +4 -3
  52. package/dist/store/sqlite/crm.d.ts +5 -3
  53. package/dist/store/sqlite/crm.js +20 -3
  54. package/package.json +1 -1
@@ -0,0 +1,412 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { annotate } from "@wirecat/cli-base/commands";
3
+ import { defineQuery, queryFieldsOf } from "@wirecat/cli-base/query";
4
+ import { isoTime } from "@wirecat/cli-base/standards";
5
+ import { InvalidArgumentError } from "commander";
6
+ import * as v from "valibot";
7
+ import { answerEntity } from "../../cli/answer-entity.js";
8
+ import { REMOTE_READ, REMOTE_WRITE } from "../../cli/effects.js";
9
+ import { itemOf, listOf } from "../../cli/envelope.js";
10
+ import { commandPath, listQuery, nativeTerms, searchText, typedQuery, withQuery } from "../../cli/list-query.js";
11
+ import { terminalAsker } from "../../cli/messenger/ask.js";
12
+ import { foldName } from "../../resolve.js";
13
+ import { foreignContacts, foreignContactsPathFor } from "../foreign-contacts.js";
14
+ import { conditionsOf, customConditions, customNames, filterableFields, selectedCodes, wantedCodes, withCustomFields, } from "../query.js";
15
+ import { createCrmRecord, fieldPairsOf, RECORD_ID, updateCrmRecord, } from "../writes.js";
16
+ import { csvFormatOption, renderCsv } from "./csv.js";
17
+ const time = v.nullable(isoTime);
18
+ const metadata = v.optional(v.record(v.string(), v.strictObject({
19
+ label: v.nullable(v.string()),
20
+ value: v.unknown(),
21
+ option_id: v.optional(v.union([v.string(), v.array(v.string())])),
22
+ })));
23
+ const untrusted = v.array(v.string());
24
+ /** A phone or an address and its kind as the CRM names it (`WORK`, `MOB`), null when it names none. */
25
+ const contacts = v.optional(v.array(v.strictObject({ value: v.string(), type: v.nullable(v.string()) })));
26
+ /** A CRM contact as the CRM holds it now. `emails` and `phones` are left out where the sign-in may not see them. */
27
+ export const crmPersonSchema = v.strictObject({
28
+ id: v.string(),
29
+ name: v.nullable(v.string()),
30
+ first_name: v.nullable(v.string()),
31
+ last_name: v.nullable(v.string()),
32
+ position: v.nullable(v.string()),
33
+ organization_ids: v.array(v.string()),
34
+ emails: contacts,
35
+ phones: contacts,
36
+ assigned_to: v.nullable(v.string()),
37
+ created_at: time,
38
+ updated_at: time,
39
+ url: v.nullable(v.string()),
40
+ provider_metadata: metadata,
41
+ untrusted,
42
+ });
43
+ /** A CRM company as the CRM holds it now. */
44
+ export const crmOrganizationSchema = v.strictObject({
45
+ id: v.string(),
46
+ name: v.nullable(v.string()),
47
+ type: v.nullable(v.string()),
48
+ own: v.boolean(),
49
+ person_ids: v.array(v.string()),
50
+ emails: contacts,
51
+ phones: contacts,
52
+ assigned_to: v.nullable(v.string()),
53
+ created_at: time,
54
+ updated_at: time,
55
+ url: v.nullable(v.string()),
56
+ provider_metadata: metadata,
57
+ untrusted,
58
+ });
59
+ /** A user of the CRM account: someone of the owner's own company. */
60
+ export const crmUserSchema = v.strictObject({
61
+ id: v.string(),
62
+ name: v.nullable(v.string()),
63
+ email: v.nullable(v.string()),
64
+ position: v.nullable(v.string()),
65
+ active: v.boolean(),
66
+ department_ids: v.array(v.string()),
67
+ untrusted,
68
+ });
69
+ const PERSON_UNTRUSTED = ["name", "first_name", "last_name", "position", "emails", "phones", "provider_metadata"];
70
+ const ORGANIZATION_UNTRUSTED = ["name", "type", "emails", "phones", "provider_metadata"];
71
+ const USER_UNTRUSTED = ["name", "email", "position"];
72
+ const iso = (ms) => (ms == null ? null : new Date(ms).toISOString());
73
+ /** The primary value first, each once; absent when the CRM said neither. */
74
+ const both = (first, all) => first == null && all === undefined ? undefined : [...new Set([...(first ? [first] : []), ...(all ?? [])])];
75
+ const shared = (record) => {
76
+ const typed = (values) => values?.map((value) => ({ value, type: record.contactTypes?.[value] ?? null }));
77
+ const emails = typed(both(record.email, record.emails));
78
+ const phones = typed(both(record.phone, record.phones));
79
+ return {
80
+ ...(emails ? { emails } : {}),
81
+ ...(phones ? { phones } : {}),
82
+ assigned_to: record.assignee ?? null,
83
+ created_at: iso(record.createdAt),
84
+ updated_at: iso(record.updatedAt),
85
+ url: record.url ?? null,
86
+ ...(record.metadata ? { provider_metadata: record.metadata } : {}),
87
+ };
88
+ };
89
+ export const crmPersonOf = (person) => ({
90
+ id: person.externalId,
91
+ name: person.name,
92
+ first_name: person.firstName ?? null,
93
+ last_name: person.lastName ?? null,
94
+ position: person.position ?? null,
95
+ organization_ids: (person.organizations ?? []).map(({ externalId }) => externalId),
96
+ ...shared(person),
97
+ untrusted: PERSON_UNTRUSTED,
98
+ });
99
+ export const crmOrganizationOf = (organization) => ({
100
+ id: organization.externalId,
101
+ name: organization.name,
102
+ type: organization.type ?? null,
103
+ own: organization.own === true,
104
+ person_ids: organization.people ?? [],
105
+ ...shared(organization),
106
+ untrusted: ORGANIZATION_UNTRUSTED,
107
+ });
108
+ export const crmUserOf = (user) => ({
109
+ id: user.externalId,
110
+ name: user.name,
111
+ email: user.email ?? null,
112
+ position: user.position ?? null,
113
+ active: user.active !== false,
114
+ department_ids: user.departments ?? [],
115
+ untrusted: USER_UNTRUSTED,
116
+ });
117
+ const RECORD_FIELDS = {
118
+ person: {
119
+ assigned_to: { field: "assigned_to", kind: "id" },
120
+ created_at: { field: "created_at", kind: "time" },
121
+ updated_at: { field: "updated_at", kind: "time" },
122
+ },
123
+ organization: {
124
+ type: { field: "type", kind: "text" },
125
+ assigned_to: { field: "assigned_to", kind: "id" },
126
+ created_at: { field: "created_at", kind: "time" },
127
+ updated_at: { field: "updated_at", kind: "time" },
128
+ },
129
+ };
130
+ const nativeQuery = (entity, schema, native) => defineQuery({
131
+ entity,
132
+ backend: "native",
133
+ fields: queryFieldsOf(schema, {
134
+ exclude: ["provider_metadata", "url", "untrusted"],
135
+ native,
136
+ text: ["name"],
137
+ examples: { name: "name:anna*" },
138
+ }),
139
+ });
140
+ export const CRM_PEOPLE_QUERY = nativeQuery("crm_person", crmPersonSchema, [
141
+ "name",
142
+ ...Object.keys(RECORD_FIELDS.person),
143
+ ]);
144
+ export const CRM_ORGANIZATIONS_QUERY = nativeQuery("crm_organization", crmOrganizationSchema, [
145
+ "name",
146
+ ...Object.keys(RECORD_FIELDS.organization),
147
+ ]);
148
+ export const CRM_USERS_QUERY = nativeQuery("crm_user", crmUserSchema, ["name", "active"]);
149
+ const CUSTOM_HELP = `
150
+ The CRM's own fields, as \`fields list\` prints them:
151
+ <code or label>:<value> a field the CRM can filter by; a list field takes its option's label or id.
152
+ A label with spaces: lead_source:web, or Lead\\ source:web
153
+ --json=id,name,provider_metadata.<code> keeps that field of each item; provider_metadata keeps them all`;
154
+ const NOUNS = {
155
+ person: {
156
+ kind: "person",
157
+ noun: "people",
158
+ entity: "crm_person",
159
+ schema: crmPersonSchema,
160
+ query: CRM_PEOPLE_QUERY,
161
+ what: "contacts",
162
+ of: (record) => crmPersonOf(record),
163
+ },
164
+ organization: {
165
+ kind: "organization",
166
+ noun: "organizations",
167
+ entity: "crm_organization",
168
+ schema: crmOrganizationSchema,
169
+ query: CRM_ORGANIZATIONS_QUERY,
170
+ what: "companies",
171
+ of: (record) => crmOrganizationOf(record),
172
+ },
173
+ };
174
+ /** The most rows a live page asks for: amoCRM's own largest page. */
175
+ const MOST = 250;
176
+ /** A whole number from 1 to `most`, as `--limit` and `--page` take it. */
177
+ export const integer = (most) => (value) => {
178
+ if (!/^[1-9]\d*$/.test(value) || Number(value) > most)
179
+ throw new InvalidArgumentError(`expected 1 to ${most}`);
180
+ return Number(value);
181
+ };
182
+ const sourceWith = (run, method, what) => {
183
+ const source = run.source();
184
+ if (!source[method])
185
+ throw new CliError("configuration_error", `this CRM does not read its ${what} live`);
186
+ return source;
187
+ };
188
+ /** `people`, `organizations` and `users`: read live from the CRM, so `--offline` is refused (NEED-2661). */
189
+ export const addCrmRecordCommands = (program, options) => {
190
+ const { within, example } = options;
191
+ const quotaOf = (run) => foreignContacts(run.source(), async () => {
192
+ const self = run.source().self;
193
+ return foreignContactsPathFor(options.app, run.account, run.env, self ? String(await self()) : undefined);
194
+ }, { now: options.now });
195
+ // The definitions a sync stored, which a list reads without a request; read live only before the first sync.
196
+ const liveFields = async (run, kind) => {
197
+ const stored = await run.store.crm.fields(run.account, kind);
198
+ return stored.length ? stored : ((await run.source().fields?.(kind)) ?? []);
199
+ };
200
+ const records = (noun) => {
201
+ const group = annotate(program.command(noun.noun), { effects: REMOTE_READ }).description(`the CRM's ${noun.what}, read live: the copy holds only your own`);
202
+ example(withQuery(answerEntity(annotate(group.command("list"), { effects: REMOTE_READ, offline: false }), noun.entity, noun.schema), noun.query)
203
+ .description(`${noun.what} in the CRM, newest first; another client is found here, never in the copy`)
204
+ .option("--limit <n>", `${noun.what} per page, 1–${MOST}`, integer(MOST), 50)
205
+ .option("--page <n>", "which page, starting at 1", integer(1_000_000), 1)
206
+ .addOption(csvFormatOption())
207
+ .addHelpText("after", CUSTOM_HELP), `${noun.noun} list`, `${noun.noun} list name:anna* --json`, `${noun.noun} list --format csv > ${noun.noun}.csv`).action(async (words, opts, command) => {
208
+ const csv = opts.format === "csv";
209
+ const path = commandPath(command);
210
+ const text = typedQuery(words);
211
+ const names = customNames(text, noun.query, path, "name");
212
+ const columns = command.optsWithGlobals().fields;
213
+ const wanted = csv && columns === undefined ? "all" : wantedCodes(columns);
214
+ const read = async (run) => {
215
+ const source = sourceWith(run, "list", noun.what);
216
+ const fields = names.length || wanted !== undefined || csv ? await liveFields(run, noun.kind) : [];
217
+ const chosen = filterableFields(fields, names);
218
+ selectedCodes(fields, wanted);
219
+ const terms = nativeTerms(listQuery(text, withCustomFields(noun.query, chosen), path, { defaultField: "name" }), path);
220
+ const custom = customConditions(terms, chosen);
221
+ const name = searchText(terms.get("name"));
222
+ terms.delete("name");
223
+ const page = await source.list(noun.kind, {
224
+ conditions: [...conditionsOf(terms, RECORD_FIELDS[noun.kind]), ...custom],
225
+ ...(name ? { text: name } : {}),
226
+ limit: opts.limit,
227
+ page: opts.page,
228
+ });
229
+ const shown = await quotaOf(run).strip(noun.kind, page.items);
230
+ return { items: shown.map(noun.of), fields, hasMore: page.hasMore };
231
+ };
232
+ if (csv)
233
+ return renderCsv(command, options.open, async (run) => ({ ...(await read(run)), page: opts.page }), [
234
+ ...Object.keys(noun.schema.entries).filter((key) => key !== "provider_metadata" && key !== "untrusted"),
235
+ "provider_metadata",
236
+ ]);
237
+ await within(command, async (run) => {
238
+ const found = await read(run);
239
+ return listOf(path, {
240
+ items: found.items,
241
+ limit: opts.limit,
242
+ page: opts.page,
243
+ has_more: found.hasMore,
244
+ ...(words.length ? { args: { query: words } } : {}),
245
+ });
246
+ });
247
+ });
248
+ example(answerEntity(annotate(group.command("show"), { effects: REMOTE_READ, offline: false }), noun.entity, noun.schema)
249
+ .description(`one of the CRM's ${noun.what}, read live, with its phones and e-mails; one that is not your client ` +
250
+ "counts toward the day's limit when the CRM sets one")
251
+ .argument(`<${noun.kind}>`, `the CRM's id of the ${noun.kind}, as list prints it, or its exact name`), `${noun.noun} show 42`, `${noun.noun} show "Anna Example" --json`).action(async (given, _opts, command) => {
252
+ await within(command, async (run) => {
253
+ const found = await recordNamed(run, noun, given);
254
+ await quotaOf(run).spend(noun.kind, found);
255
+ return itemOf(noun.of(found));
256
+ });
257
+ });
258
+ addRecordWrites(group, noun, options);
259
+ };
260
+ for (const kind of ["person", "organization"])
261
+ if (options.live.includes(kind))
262
+ records(NOUNS[kind]);
263
+ if (options.live.includes("user"))
264
+ users(program, options);
265
+ };
266
+ /** By the CRM's id first; else the one record whose whole name is the given one, folded. */
267
+ const recordNamed = async (run, noun, given) => {
268
+ const id = given.trim();
269
+ const byId = RECORD_ID.test(id) ? await sourceWith(run, "get", noun.what).get(noun.kind, id) : null;
270
+ if (byId)
271
+ return byId;
272
+ const want = foldName(id);
273
+ const page = await sourceWith(run, "list", noun.what).list(noun.kind, { conditions: [], text: id, limit: MOST });
274
+ const named = page.items.filter((one) => foldName(one.name ?? "") === want);
275
+ const [only] = named;
276
+ if (named.length > 1)
277
+ throw new CliError("validation_error", `${named.length} ${noun.what} are named ${id}; name one by its id`, {
278
+ reason: "crm.record-ambiguous",
279
+ candidates: named.map((one) => ({ id: one.externalId, name: one.name })),
280
+ });
281
+ if (!only)
282
+ throw new CliError("not_found", `the CRM has no ${noun.kind} ${id}, or this sign-in cannot see it`);
283
+ return only;
284
+ };
285
+ const matches = (user, terms) => {
286
+ const name = terms.get("name");
287
+ if (name) {
288
+ const want = foldName(searchText(name) ?? "");
289
+ if (!foldName(user.name ?? "").includes(want))
290
+ return false;
291
+ }
292
+ const active = terms.get("active");
293
+ return !active || String(user.active !== false) === active.value.toLowerCase();
294
+ };
295
+ const runUsers = new WeakMap();
296
+ /** The CRM's users, read once a run. */
297
+ const usersOf = (run) => {
298
+ let found = runUsers.get(run);
299
+ if (!found) {
300
+ found = sourceWith(run, "users", "users").users();
301
+ runUsers.set(run, found);
302
+ }
303
+ return found;
304
+ };
305
+ const users = (program, { within, example }) => {
306
+ const group = annotate(program.command("users"), { effects: REMOTE_READ }).description("the CRM account's users: the people of your own company who own deals");
307
+ example(withQuery(answerEntity(annotate(group.command("list"), { effects: REMOTE_READ, offline: false }), "crm_user", crmUserSchema), CRM_USERS_QUERY)
308
+ .description("the CRM's users, read live, in the CRM's order")
309
+ .option("--limit <n>", `users per page, 1–${MOST}`, integer(MOST), 50)
310
+ .option("--page <n>", "which page, starting at 1", integer(1_000_000), 1), "users list", "users list active:true --json").action(async (words, opts, command) => {
311
+ const path = commandPath(command);
312
+ const terms = nativeTerms(listQuery(typedQuery(words), CRM_USERS_QUERY, path, { defaultField: "name" }), path);
313
+ await within(command, async (run) => {
314
+ const all = (await usersOf(run)).filter((user) => matches(user, terms));
315
+ const offset = (opts.page - 1) * opts.limit;
316
+ return listOf(path, {
317
+ items: all.slice(offset, offset + opts.limit).map(crmUserOf),
318
+ limit: opts.limit,
319
+ page: opts.page,
320
+ has_more: all.length > offset + opts.limit,
321
+ ...(words.length ? { args: { query: words } } : {}),
322
+ });
323
+ });
324
+ });
325
+ example(answerEntity(annotate(group.command("show"), { effects: REMOTE_READ, offline: false }), "crm_user", crmUserSchema)
326
+ .description("one of the CRM's users, read live")
327
+ .argument("<user>", "the CRM's id of the user, as list prints it"), "users show 7").action(async (id, _opts, command) => {
328
+ if (!RECORD_ID.test(id))
329
+ throw new CliError("validation_error", "name the user by the CRM's id, as users list prints it", {
330
+ reason: "ref.malformed",
331
+ });
332
+ await within(command, async (run) => {
333
+ const found = (await usersOf(run)).find((user) => user.externalId === id);
334
+ if (!found)
335
+ throw new CliError("not_found", `the CRM has no user ${id}`);
336
+ return itemOf(crmUserOf(found));
337
+ });
338
+ });
339
+ };
340
+ const crmRecordWrite = v.strictObject({
341
+ operation_id: v.string(),
342
+ stored: v.boolean(),
343
+ person: v.optional(crmPersonSchema),
344
+ organization: v.optional(crmOrganizationSchema),
345
+ untrusted,
346
+ });
347
+ /** `create` and `update` of contacts and companies, through the same guarded path as `deals create`. */
348
+ const addRecordWrites = (group, noun, { within, example, writes }) => {
349
+ if (!writes?.kinds.includes(noun.kind))
350
+ return;
351
+ const person = noun.kind === "person";
352
+ const fields = (command) => {
353
+ command.option("--name <name>", person ? "the whole name" : "the company's name");
354
+ if (person)
355
+ command
356
+ .option("--first-name <name>", "the first name; empty clears it")
357
+ .option("--last-name <name>", "the last name; empty clears it")
358
+ .option("--position <title>", "the job title; empty clears it");
359
+ command
360
+ .option("--owner <user>", "the CRM user it is assigned to; anyone but the sign-in's own user checks crm.assign-others")
361
+ .option("--field <key=value>", "one of the CRM's own fields, by its code or label as `fields list` prints them, and its value; a list " +
362
+ "field takes its option's label or id; repeat it for more fields, or for each value of a multiple field; " +
363
+ "an empty value clears it", (value, previous = []) => {
364
+ if (value.indexOf("=") < 1)
365
+ throw new CliError("validation_error", "--field takes <key>=<value>");
366
+ return [...previous, value];
367
+ }, []);
368
+ if (writes.idempotent)
369
+ command.option("--operation-id <id>", "the operation_id a write that ended in outcome_unknown named: the CRM answers the repeat from its record");
370
+ return command;
371
+ };
372
+ const inputOf = ({ field, operationId: _id, ...rest }) => ({
373
+ ...Object.fromEntries(Object.entries(rest).filter(([, value]) => value !== undefined)),
374
+ ...(field?.length ? { custom: fieldPairsOf(field) } : {}),
375
+ });
376
+ const contextOf = (run, command) => {
377
+ if (!run.writes)
378
+ throw new CliError("configuration_error", "this profile cannot write to its CRM");
379
+ return {
380
+ store: run.store,
381
+ account: run.account,
382
+ writes: run.writes(),
383
+ ask: terminalAsker(command),
384
+ source: run.source,
385
+ names: { id: "--operation-id" },
386
+ };
387
+ };
388
+ const answered = ({ operationId, record, stored }) => itemOf({
389
+ operation_id: operationId,
390
+ stored,
391
+ [noun.kind]: noun.of(record),
392
+ untrusted: (person ? PERSON_UNTRUSTED : ORGANIZATION_UNTRUSTED).map((one) => `${noun.kind}.${one}`),
393
+ });
394
+ const command = (name, description) => answerEntity(annotate(group.command(name), { effects: REMOTE_WRITE, offline: false }), "crm_record_write", crmRecordWrite).description(description);
395
+ if (writes.verbs.includes("create"))
396
+ example(fields(command("create", `make a ${noun.kind} in the CRM, then store the CRM's copy of it`)), person
397
+ ? `${noun.noun} create --first-name Anna --last-name Example --position Buyer`
398
+ : `${noun.noun} create --name "Example LLC"`).action(async (opts, leaf) => {
399
+ await within(leaf, async (run) => {
400
+ const done = await createCrmRecord(contextOf(run, leaf), noun.kind, inputOf(opts), idOf(opts));
401
+ return answered(done);
402
+ });
403
+ });
404
+ if (writes.verbs.includes("update"))
405
+ example(fields(command("update", `change a ${noun.kind} in the CRM; what is left out keeps its value; the CRM's copy is stored again`).argument(`<${noun.kind}>`, `the CRM's id of the ${noun.kind}, as list prints it`)), person ? `${noun.noun} update 42 --position Buyer` : `${noun.noun} update 9 --name "Example Ltd"`).action(async (id, opts, leaf) => {
406
+ await within(leaf, async (run) => {
407
+ const done = await updateCrmRecord(contextOf(run, leaf), noun.kind, id, inputOf(opts), idOf(opts));
408
+ return answered(done);
409
+ });
410
+ });
411
+ };
412
+ const idOf = (opts) => opts.operationId === undefined ? {} : { operationId: opts.operationId };
@@ -0,0 +1,34 @@
1
+ import type { CrmOrganization, CrmPerson } from "../domain/crm.js";
2
+ import type { AppIdentity } from "../ports/app.js";
3
+ import type { AccountKey } from "../store/types.js";
4
+ import type { CrmLiveKind, CrmSource } from "./source.js";
5
+ /** The owner's rule (NEED-2487): a user sees at most this many other contacts' or companies' details a UTC day. */
6
+ export declare const DAILY_FOREIGN_CONTACTS = 100;
7
+ type Live = CrmPerson | CrmOrganization;
8
+ /** Where the day's count of one CRM user is kept: the CLI's state folder, a file per account and user. */
9
+ export declare const foreignContactsPathFor: (app: AppIdentity, account: AccountKey, env?: NodeJS.ProcessEnv, user?: string) => string;
10
+ export interface ForeignContacts {
11
+ /** Phones and e-mails kept only on the sign-in's own clients; an administrator's list comes back as it was. */
12
+ strip<T extends Live>(kind: CrmLiveKind, records: T[]): Promise<T[]>;
13
+ /** Whether the sign-in may see this record whole: its own client, or an administrator's or unlimited CRM's. */
14
+ own(kind: CrmLiveKind, record: Live): Promise<boolean>;
15
+ /** One record shown whole: a foreign one spends one of the day's slots, the same one again that day is free. */
16
+ spend(kind: CrmLiveKind, record: Live): Promise<void>;
17
+ }
18
+ /**
19
+ * The shared rule over one source, for anyone but the CRM's administrator. A source without `isAdmin` is not
20
+ * limited. The count is read and written under a file lock, so two runs never both take the day's last slot.
21
+ */
22
+ export declare const foreignContacts: (source: CrmSource,
23
+ /** The day's count file; a caller that only strips, such as a write, passes none and spends nothing. */
24
+ file: (() => string | Promise<string>) | undefined, options?: {
25
+ now?: () => number;
26
+ lockWaitMs?: number;
27
+ }) => ForeignContacts;
28
+ /**
29
+ * `api call` of a method that returns contacts or companies or their contact data: only the CRM's administrator
30
+ * makes it (NEED-2488), since one raw list would hand over the whole client base past the day's limit. The CLI knows
31
+ * its methods and says which read clients; a source without `isAdmin` is not limited.
32
+ */
33
+ export declare const refuseForeignClientReads: (source: CrmSource, readsClients: boolean, method: string) => Promise<void>;
34
+ export {};
@@ -0,0 +1,104 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { CliError, resolvePaths, writeSecurely } from "@wirecat/cli-base";
4
+ import { withFileLockAsync } from "../sends/file-lock.js";
5
+ /** The owner's rule (NEED-2487): a user sees at most this many other contacts' or companies' details a UTC day. */
6
+ export const DAILY_FOREIGN_CONTACTS = 100;
7
+ /** Where the day's count of one CRM user is kept: the CLI's state folder, a file per account and user. */
8
+ 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`);
9
+ const shownIn = (file, day) => {
10
+ try {
11
+ const found = JSON.parse(readFileSync(file, "utf8"));
12
+ return found.day === day && Array.isArray(found.seen) ? { day, seen: found.seen.map(String) } : { day, seen: [] };
13
+ }
14
+ catch {
15
+ return { day, seen: [] };
16
+ }
17
+ };
18
+ /**
19
+ * A foreign record without its phones and e-mails. A custom value goes too when its field holds a phone or an e-mail
20
+ * (`CrmField.holds`) or repeats one of the record's own; with no definitions every custom value goes, since nothing
21
+ * then says which fields hold contact data.
22
+ */
23
+ const stripped = (record, fields) => {
24
+ const { phones, emails, email, phone, contactTypes: _types, ...rest } = record;
25
+ const own = new Set([...(phones ?? []), ...(emails ?? []), email, phone].filter((one) => !!one));
26
+ const holding = new Set(fields.filter((field) => field.holds).map((field) => field.code));
27
+ const repeats = (value) => (Array.isArray(value) ? value : [value]).some((one) => typeof one === "string" && own.has(one.trim()));
28
+ const metadata = rest.metadata;
29
+ if (metadata)
30
+ rest.metadata = fields.length
31
+ ? Object.fromEntries(Object.entries(metadata).filter(([code, one]) => !holding.has(code) && !repeats(one.value)))
32
+ : {};
33
+ return rest;
34
+ };
35
+ /**
36
+ * The shared rule over one source, for anyone but the CRM's administrator. A source without `isAdmin` is not
37
+ * limited. The count is read and written under a file lock, so two runs never both take the day's last slot.
38
+ */
39
+ export const foreignContacts = (source,
40
+ /** The day's count file; a caller that only strips, such as a write, passes none and spends nothing. */
41
+ file, options = {}) => {
42
+ let admin;
43
+ // Read from the CRM, not the copy: the store does not keep `holds` (no column for it yet).
44
+ const definitions = {};
45
+ const limited = async () => {
46
+ if (!source.isAdmin)
47
+ return false;
48
+ admin ??= source.isAdmin();
49
+ return !(await admin);
50
+ };
51
+ const own = async (kind, records) => {
52
+ const self = source.self ? String(await source.self()) : undefined;
53
+ const mine = new Set(records.filter((one) => self && one.assignee === self).map((one) => one.externalId));
54
+ const rest = records.filter((one) => !mine.has(one.externalId)).map((one) => one.externalId);
55
+ if (rest.length && source.ownClients)
56
+ for (const id of await source.ownClients(kind, rest))
57
+ mine.add(id);
58
+ return mine;
59
+ };
60
+ return {
61
+ async strip(kind, records) {
62
+ if (!(await limited()) || records.length === 0)
63
+ return records;
64
+ const mine = await own(kind, records);
65
+ if (records.every((one) => mine.has(one.externalId)))
66
+ return records;
67
+ definitions[kind] ??= Promise.resolve(source.fields?.(kind)).then((found) => found ?? []);
68
+ const fields = await definitions[kind];
69
+ return records.map((one) => (mine.has(one.externalId) ? one : stripped(one, fields)));
70
+ },
71
+ async own(kind, record) {
72
+ return !(await limited()) || (await own(kind, [record])).has(record.externalId);
73
+ },
74
+ async spend(kind, record) {
75
+ if (!(await limited()) || (await own(kind, [record])).has(record.externalId))
76
+ return;
77
+ const key = `${kind}:${record.externalId}`;
78
+ if (!file)
79
+ throw new Error("foreignContacts: spend needs the count file");
80
+ const path = await file();
81
+ const day = new Date(options.now?.() ?? Date.now()).toISOString().slice(0, 10);
82
+ await withFileLockAsync(path, "the day's count of foreign contacts", () => {
83
+ const shown = shownIn(path, day);
84
+ if (shown.seen.includes(key))
85
+ return;
86
+ if (shown.seen.length >= DAILY_FOREIGN_CONTACTS)
87
+ throw new CliError("permission_error", `${DAILY_FOREIGN_CONTACTS} contacts and companies that are not your clients were shown today, the ` +
88
+ "most a day; your own clients are not counted, and the CRM's administrator has no limit", { reason: "crm.foreign-contacts-spent", limit: DAILY_FOREIGN_CONTACTS });
89
+ writeSecurely(path, JSON.stringify({ day, seen: [...shown.seen, key] }), 0o600);
90
+ }, options.lockWaitMs);
91
+ },
92
+ };
93
+ };
94
+ /**
95
+ * `api call` of a method that returns contacts or companies or their contact data: only the CRM's administrator
96
+ * makes it (NEED-2488), since one raw list would hand over the whole client base past the day's limit. The CLI knows
97
+ * its methods and says which read clients; a source without `isAdmin` is not limited.
98
+ */
99
+ export const refuseForeignClientReads = async (source, readsClients, method) => {
100
+ if (!readsClients || !source.isAdmin || (await source.isAdmin()))
101
+ return;
102
+ throw new CliError("permission_error", `${method} reads contacts or companies, which only the CRM's administrator reads through api call: your ` +
103
+ `clients come with sync, and another one with people show or organizations show, ${DAILY_FOREIGN_CONTACTS} a day`, { reason: "crm.client-reads-admin-only", sent: false });
104
+ };
@@ -1,4 +1,10 @@
1
- export type { CrmCallContext, CrmChanges, CrmGap, CrmIdPage, CrmPage, CrmSource, CrmSourceTraits, } from "./source.js";
1
+ export { DAILY_FOREIGN_CONTACTS, type ForeignContacts, foreignContacts, foreignContactsPathFor, refuseForeignClientReads, } from "./foreign-contacts.js";
2
+ export { type ProviderCallOptions, providerCall } from "./provider-call.js";
3
+ export { type CrmConditionHooks, type CrmQueryField, conditionsOf, customConditions, customNames, filterableFields, selectedCodes, wantedCodes, withCustomFields, } from "./query.js";
4
+ export type { CrmCallContext, CrmChanges, CrmCondition, CrmGap, CrmIdPage, CrmLiveKind, CrmLiveQuery, CrmPage, CrmSource, CrmSourceTraits, } from "./source.js";
2
5
  export { type CrmCursor, type CrmSyncIssue, type CrmSyncOptions, type CrmSyncReport, type CrmSyncResult, crmGapsOf, crmStatus, cursorName, parseCrmCursor, syncCrm, } from "./sync.js";
3
- export { CRM_ASSIGN_OTHERS_KEY, CRM_VERBS, CRM_WRITE_DEFAULTS, CRM_WRITE_KEYS, type CrmDraft, type CrmFields, type CrmVerb, type CrmWriteCapabilities, type CrmWriteOptions, type CrmWriter, crmAlsoChecks, } from "./writer.js";
4
- export { type CrmFieldsInput, type CrmWriteContext, type CrmWrites, type CrmWritten, closeCrmItem, createCrmItem, fieldNamed, fieldPairsOf, foldFieldName, moveCrmItem, type NamedField, optionOf, removeCrmItem, unknownField, updateCrmItem, } from "./writes.js";
6
+ /** An adapter's readers of a CRM's raw JSON: `crmValues.text(raw.name)`, `crmValues.time(raw.created_at)`. */
7
+ export * as crmValues from "./values.js";
8
+ export { type CrmRows, type CrmWindow, crmWindowOf, walk } from "./walk.js";
9
+ export { CRM_ASSIGN_OTHERS_KEY, CRM_VERBS, CRM_WRITE_DEFAULTS, CRM_WRITE_KEYS, type CrmDraft, type CrmDrafts, type CrmFields, type CrmOrganizationFields, type CrmPersonFields, type CrmVerb, type CrmWriteCapabilities, type CrmWriteFields, type CrmWriteOptions, type CrmWriter, crmAlsoChecks, } from "./writer.js";
10
+ export { type CrmFieldsInput, type CrmRecordInput, type CrmRecordKind, type CrmRecordWritten, type CrmWriteContext, type CrmWrites, type CrmWritten, closeCrmItem, createCrmItem, createCrmRecord, crmCustomValues, fieldNamed, fieldPairsOf, foldFieldName, moveCrmItem, type NamedField, optionOf, removeCrmItem, unknownField, updateCrmItem, updateCrmRecord, } from "./writes.js";
package/dist/crm/index.js CHANGED
@@ -1,3 +1,9 @@
1
+ export { DAILY_FOREIGN_CONTACTS, foreignContacts, foreignContactsPathFor, refuseForeignClientReads, } from "./foreign-contacts.js";
2
+ export { providerCall } from "./provider-call.js";
3
+ export { conditionsOf, customConditions, customNames, filterableFields, selectedCodes, wantedCodes, withCustomFields, } from "./query.js";
1
4
  export { crmGapsOf, crmStatus, cursorName, parseCrmCursor, syncCrm, } from "./sync.js";
5
+ /** An adapter's readers of a CRM's raw JSON: `crmValues.text(raw.name)`, `crmValues.time(raw.created_at)`. */
6
+ export * as crmValues from "./values.js";
7
+ export { crmWindowOf, walk } from "./walk.js";
2
8
  export { CRM_ASSIGN_OTHERS_KEY, CRM_VERBS, CRM_WRITE_DEFAULTS, CRM_WRITE_KEYS, crmAlsoChecks, } from "./writer.js";
3
- export { closeCrmItem, createCrmItem, fieldNamed, fieldPairsOf, foldFieldName, moveCrmItem, optionOf, removeCrmItem, unknownField, updateCrmItem, } from "./writes.js";
9
+ export { closeCrmItem, createCrmItem, createCrmRecord, crmCustomValues, fieldNamed, fieldPairsOf, foldFieldName, moveCrmItem, optionOf, removeCrmItem, unknownField, updateCrmItem, updateCrmRecord, } from "./writes.js";
@@ -0,0 +1,23 @@
1
+ import { type Pacer, type TurnOptions } from "../sends/pace.js";
2
+ export interface ProviderCallOptions<T> {
3
+ /** A write is tried again only on `rate_limited`, which a CRM answers before doing anything. */
4
+ write: boolean;
5
+ /** One HTTP exchange; it throws a cli-base `CliError` with a reason. */
6
+ send: () => Promise<T>;
7
+ /** The profile's shared pace (`@wirecat/cli-core/sends`): each attempt waits its turn, and a refused rate holds it. */
8
+ pace?: {
9
+ pacer: Pacer;
10
+ } & TurnOptions;
11
+ /** One token refresh on `oauth.expired`; false gives up. A refused token did nothing, so a write goes again too. */
12
+ refresh?: () => Promise<boolean>;
13
+ /** Attempts after the first; 3 when absent. */
14
+ retries?: number;
15
+ /** Waits between attempts; a test or a cancellable run passes its own. */
16
+ sleep?: (ms: number) => Promise<void>;
17
+ random?: () => number;
18
+ }
19
+ /**
20
+ * One call to a CRM: paced, reads tried again on a retryable failure or a refused rate, a write only on a refused
21
+ * rate. A write that got no answer is `outcome_unknown` and is never sent again: a CRM may have carried it out.
22
+ */
23
+ export declare const providerCall: <T>(options: ProviderCallOptions<T>) => Promise<T>;
@@ -0,0 +1,49 @@
1
+ import { backoffMs, CliError, isCliError, realSleep } from "@wirecat/cli-base";
2
+ import { waitForTurn } from "../sends/pace.js";
3
+ const RETRY = { retries: 3, baseDelayMs: 1_000, maxDelayMs: 10_000, maxRetryAfterMs: 30_000 };
4
+ /**
5
+ * A write cut off by these, or answered with a body nobody can read, may have reached the CRM: only a refusal says it
6
+ * did not. A cancel while waiting for the turn is thrown before the try and stays `cancelled`.
7
+ */
8
+ const UNANSWERED = new Set(["timeout", "network_error", "provider_unavailable", "cancelled", "invalid_response"]);
9
+ const unanswered = (error) => !isCliError(error) || (UNANSWERED.has(error.code) && error.details.sent !== false);
10
+ /**
11
+ * One call to a CRM: paced, reads tried again on a retryable failure or a refused rate, a write only on a refused
12
+ * rate. A write that got no answer is `outcome_unknown` and is never sent again: a CRM may have carried it out.
13
+ */
14
+ export const providerCall = async (options) => {
15
+ const retries = options.retries ?? RETRY.retries;
16
+ const sleep = options.sleep ?? ((ms) => realSleep(ms));
17
+ let refreshed = false;
18
+ for (let attempt = 1;; attempt++) {
19
+ if (options.pace)
20
+ await waitForTurn(options.pace.pacer, options.pace);
21
+ try {
22
+ return await options.send();
23
+ }
24
+ catch (error) {
25
+ if (!refreshed &&
26
+ options.refresh &&
27
+ isCliError(error) &&
28
+ error.code === "authentication_error" &&
29
+ error.details.reason === "oauth.expired") {
30
+ refreshed = true;
31
+ if (await options.refresh())
32
+ continue;
33
+ throw error;
34
+ }
35
+ if (options.write && unanswered(error))
36
+ throw new CliError("outcome_unknown", `${error instanceof Error ? error.message : String(error)}; the CRM may or may not have carried it out`, { ...(isCliError(error) ? error.details : {}), retryable: false });
37
+ if (!isCliError(error))
38
+ throw error;
39
+ const asked = error.details.retry_after_ms;
40
+ const wait = typeof asked === "number" ? asked : backoffMs(attempt, RETRY, options.random ?? Math.random);
41
+ const again = error.code === "rate_limited" || (!options.write && error.details.retryable === true);
42
+ if (!again || wait > RETRY.maxRetryAfterMs || attempt > retries)
43
+ throw error;
44
+ if (error.code === "rate_limited")
45
+ await options.pace?.pacer.holdFor(wait);
46
+ await sleep(wait);
47
+ }
48
+ }
49
+ };