@wirecat/cli-core 0.722.0 → 0.723.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/dist/cli/service-api-call.d.ts +6 -0
- package/dist/cli/service-api-call.js +21 -9
- package/dist/cli/service-api.d.ts +5 -0
- package/dist/cli/service-api.js +11 -0
- package/dist/crm/index.d.ts +3 -2
- package/dist/crm/index.js +1 -0
- package/dist/crm/manifest/manifest.d.ts +60 -1
- package/dist/crm/manifest/manifest.js +88 -0
- package/dist/crm/manifest/source.d.ts +22 -3
- package/dist/crm/manifest/source.js +10 -3
- package/dist/crm/manifest/writer.d.ts +39 -0
- package/dist/crm/manifest/writer.js +298 -0
- package/dist/crm/testing/index.d.ts +1 -1
- package/dist/crm/testing/index.js +1 -1
- package/dist/crm/testing/manifest-fake.d.ts +14 -0
- package/dist/crm/testing/manifest-fake.js +252 -27
- package/dist/ports/wirecat-tools.js +7 -0
- package/dist/services/metadata.d.ts +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,26 @@ Notable changes to `@wirecat/cli-core` (`@wirecat/cli-messaging` up to 0.261.0,
|
|
|
5
5
|
minor version may break callers, and says how under "Changed — may break callers". `pnpm docs:check` checks the
|
|
6
6
|
shape of this file.
|
|
7
7
|
|
|
8
|
+
## 0.723.0 — 23.11.2026
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- **`knowledge.eraseOrganization` deletes an organization and what memo knows of it alone.** The tags, links,
|
|
13
|
+
aliases and mentions that name it go, and so does which identities it held. A deal, lead, project, account, fact or
|
|
14
|
+
note that names it stays and loses the name. `apply: false` answers what would go and changes nothing. Owner only;
|
|
15
|
+
refused for one of the owner's own companies (`organization.own`), and while an invoice, order, subscription or a
|
|
16
|
+
row it wrote still names it (`organization.erase-blocked`). It shares `ErasePlan` with `people.erase`: both read
|
|
17
|
+
the store's own pointers and foreign keys, so the plan shown and the delete run read one list.
|
|
18
|
+
|
|
19
|
+
### Fixed
|
|
20
|
+
|
|
21
|
+
- **Removing an import's account now takes the organizations only its records made**, as it does for people. One
|
|
22
|
+
that another source, a deal or the owner still names stays.
|
|
23
|
+
- **A deal or lead that enters a stage in the same second its `stage-tasks` rules were set now opens its task.** A
|
|
24
|
+
CRM's stage history keeps whole seconds, so such a move read as made before the rules and opened none; the rules
|
|
25
|
+
now count from the start of the second they were set. Bitrix24's live check hit it when it set the rules and moved
|
|
26
|
+
a deal within a second.
|
|
27
|
+
|
|
8
28
|
## 0.722.0 — 23.11.2026
|
|
9
29
|
|
|
10
30
|
### Added
|
|
@@ -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
|
-
|
|
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
|
/**
|
package/dist/cli/service-api.js
CHANGED
|
@@ -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];
|
package/dist/crm/index.d.ts
CHANGED
|
@@ -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
|
|
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 {
|
|
4
|
-
import {
|
|
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) =>
|
|
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
|
|
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;
|
|
@@ -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 {};
|
|
@@ -1,18 +1,22 @@
|
|
|
1
1
|
import { fakeApi, sampleOf, } from "@wirecat/cli-base/codegen";
|
|
2
|
-
import { serviceApiCall } from "../../cli/service-api-call.js";
|
|
2
|
+
import { serviceApiCall, serviceApiSend } from "../../cli/service-api-call.js";
|
|
3
3
|
import { manifestBaseUrl } from "../../cli/service-api-manifest.js";
|
|
4
4
|
import { DEAL_KINDS } from "../../domain/deals.js";
|
|
5
|
-
import { parseCrmManifest, } from "../manifest/manifest.js";
|
|
6
|
-
import { at, convert, evaluate, FIELDS, MISSING } from "../manifest/map.js";
|
|
5
|
+
import { CRM_LIST_FIELDS, parseCrmManifest, } from "../manifest/manifest.js";
|
|
6
|
+
import { at, convert, evaluate, FIELDS, MISSING, mapRecord } from "../manifest/map.js";
|
|
7
7
|
import { itemOf, resolve, step, walk } from "../manifest/paths.js";
|
|
8
8
|
import { crmSourceFromManifest } from "../manifest/source.js";
|
|
9
|
+
import { crmWriterFromManifest } from "../manifest/writer.js";
|
|
9
10
|
import { id, isRaw } from "../values.js";
|
|
10
11
|
import { crmSourceContract } from "./source-contract.js";
|
|
12
|
+
import { crmWriteContract } from "./write-contract.js";
|
|
11
13
|
export const FAKE_MANIFEST_TOKEN = "fake-manifest-token";
|
|
12
14
|
/** Three rows in pages of two: every kind pages at least once, whatever limit the manifest asks for. */
|
|
13
15
|
const ROWS = 3;
|
|
14
16
|
const PAGE = 2;
|
|
15
17
|
const SEEDED = Date.parse("2026-11-01T10:00:00Z");
|
|
18
|
+
/** The currency of every amount, and what a fixed currency reads. */
|
|
19
|
+
const CURRENCY = "EUR";
|
|
16
20
|
/** Where a rule can be written to: the first path it reads, or none for a function or a list it walks. */
|
|
17
21
|
const pathOf = (rule) => {
|
|
18
22
|
if (rule === undefined || typeof rule === "function")
|
|
@@ -29,26 +33,58 @@ const pathOf = (rule) => {
|
|
|
29
33
|
return rule.all[0];
|
|
30
34
|
return rule.path;
|
|
31
35
|
};
|
|
32
|
-
const
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
if (!Array.isArray(value) && !isRaw(value))
|
|
37
|
-
return undefined;
|
|
38
|
-
for (const [key, inner] of Object.entries(value)) {
|
|
39
|
-
const found = find(inner, [...trail, key]);
|
|
40
|
-
if (found)
|
|
41
|
-
return found;
|
|
42
|
-
}
|
|
36
|
+
const trailOf = (value, placeholder, trail = []) => {
|
|
37
|
+
if (value === placeholder)
|
|
38
|
+
return trail;
|
|
39
|
+
if (!Array.isArray(value) && !isRaw(value))
|
|
43
40
|
return undefined;
|
|
44
|
-
|
|
41
|
+
for (const [key, inner] of Object.entries(value)) {
|
|
42
|
+
const found = trailOf(inner, placeholder, [...trail, key]);
|
|
43
|
+
if (found)
|
|
44
|
+
return found;
|
|
45
|
+
}
|
|
46
|
+
return undefined;
|
|
47
|
+
};
|
|
48
|
+
const placeOf = (call, placeholder) => {
|
|
45
49
|
for (const where of ["path", "query", "body"]) {
|
|
46
|
-
const found =
|
|
50
|
+
const found = trailOf(call[where], placeholder);
|
|
47
51
|
if (found)
|
|
48
|
-
return { in: where, path: found.join(".") };
|
|
52
|
+
return { in: where, path: found.length ? found.join(".") : "." };
|
|
49
53
|
}
|
|
50
54
|
return undefined;
|
|
51
55
|
};
|
|
56
|
+
/**
|
|
57
|
+
* Our fields, in the names a read maps, that a write's values give: each rule read backwards, `"{value}"` in its
|
|
58
|
+
* `each` the place of ours. A value the service clears with is a cleared field.
|
|
59
|
+
*/
|
|
60
|
+
const givenOf = (spec, values) => {
|
|
61
|
+
const given = {};
|
|
62
|
+
if (!isRaw(values))
|
|
63
|
+
return given;
|
|
64
|
+
const clear = JSON.stringify(spec.clear === undefined ? null : spec.clear);
|
|
65
|
+
for (const [field, rule] of Object.entries(spec.fields)) {
|
|
66
|
+
if (typeof rule !== "object" || !("to" in rule) || !(rule.to in values))
|
|
67
|
+
continue;
|
|
68
|
+
const name = field === "owner" ? "assignee" : field;
|
|
69
|
+
const list = CRM_LIST_FIELDS.includes(field);
|
|
70
|
+
const raw = values[rule.to];
|
|
71
|
+
if (JSON.stringify(raw) === clear) {
|
|
72
|
+
given[name] = list ? [] : null;
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
const trail = rule.each === undefined ? [] : (trailOf(rule.each, "{value}") ?? []);
|
|
76
|
+
const found = (rule.list ? (Array.isArray(raw) ? raw : []) : [raw])
|
|
77
|
+
.map((one) => (trail.length ? at(one, trail.join(".")) : one))
|
|
78
|
+
.filter((one) => one !== undefined && one !== null)
|
|
79
|
+
.map(String);
|
|
80
|
+
if (list)
|
|
81
|
+
given[name] = field === "people" ? found.map((one) => ({ externalId: one, role: "contact" })) : found;
|
|
82
|
+
// A key several rules write together is replaced whole: a part it leaves out is gone.
|
|
83
|
+
else
|
|
84
|
+
given[name] = found[0] ?? null;
|
|
85
|
+
}
|
|
86
|
+
return given;
|
|
87
|
+
};
|
|
52
88
|
const readPlace = (call, place) => {
|
|
53
89
|
if (place.in === "body")
|
|
54
90
|
return at(call.body, place.path);
|
|
@@ -288,15 +324,19 @@ export const crmManifestFake = (input, options) => {
|
|
|
288
324
|
const index = manifest.kinds.indexOf(kind);
|
|
289
325
|
return index < 0 ? undefined : String((index + 1) * 1000 + n + 1);
|
|
290
326
|
};
|
|
291
|
-
/** A
|
|
292
|
-
const
|
|
293
|
-
if (typeof rule !== "object" || !("each" in rule)
|
|
327
|
+
/** A list a rule walks, one entry for each value: a deal's people, a contact's e-mails. */
|
|
328
|
+
const putEach = (row, rule, node, values) => {
|
|
329
|
+
if (typeof rule !== "object" || !("each" in rule))
|
|
294
330
|
return;
|
|
331
|
+
const inner = "id" in rule ? rule.id : rule.value;
|
|
295
332
|
const entry = itemOf(nodeAt(node, rule.each), definitions);
|
|
296
|
-
const
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
333
|
+
const items = values.map((value) => {
|
|
334
|
+
const made = sample(entry && narrowed(entry, inner.split("."), value));
|
|
335
|
+
const item = isRaw(made) ? made : {};
|
|
336
|
+
put(item, inner, value, entry);
|
|
337
|
+
return item;
|
|
338
|
+
});
|
|
339
|
+
putList(row, rule.each, items, node);
|
|
300
340
|
};
|
|
301
341
|
const rows = {};
|
|
302
342
|
const changeAt = {};
|
|
@@ -316,12 +356,12 @@ export const crmManifestFake = (input, options) => {
|
|
|
316
356
|
externalId: String((index + 1) * 1000 + n + 1),
|
|
317
357
|
assignee: "7001",
|
|
318
358
|
...(pipeline ? { pipeline: pipeline.id, stage: pipeline.stages[n % pipeline.stages.length] } : {}),
|
|
319
|
-
...(money ? { amount: "100.50", currency:
|
|
359
|
+
...(money ? { amount: "100.50", currency: CURRENCY } : { amount: undefined, currency: undefined }),
|
|
320
360
|
...(pipeline && idAt("organization", n) ? { organization: idAt("organization", n) } : {}),
|
|
321
361
|
});
|
|
322
362
|
const person = idAt("person", n);
|
|
323
363
|
if (pipeline && person)
|
|
324
|
-
|
|
364
|
+
putEach(row, map.people, node, [person]);
|
|
325
365
|
if (keyset)
|
|
326
366
|
put(row, keyset, time, node);
|
|
327
367
|
return row;
|
|
@@ -384,7 +424,111 @@ export const crmManifestFake = (input, options) => {
|
|
|
384
424
|
}
|
|
385
425
|
if (manifest.users)
|
|
386
426
|
routes.push({ call: manifest.users.call, rows: () => users });
|
|
427
|
+
for (const kind of manifest.kinds) {
|
|
428
|
+
const spec = manifest.writes?.[kind];
|
|
429
|
+
if (!spec)
|
|
430
|
+
continue;
|
|
431
|
+
for (const verb of ["create", "update", "remove"]) {
|
|
432
|
+
const call = spec[verb];
|
|
433
|
+
if (!call)
|
|
434
|
+
continue;
|
|
435
|
+
const id = placeOf(call, "{id}");
|
|
436
|
+
const values = placeOf(call, "{values}");
|
|
437
|
+
routes.push({
|
|
438
|
+
call,
|
|
439
|
+
kind,
|
|
440
|
+
rows: () => rows[kind] ?? [],
|
|
441
|
+
write: { verb, spec, ...(id ? { id } : {}), ...(values ? { values } : {}) },
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
const currency = spec.fields.currency;
|
|
445
|
+
if (typeof currency === "object" && "fixed" in currency)
|
|
446
|
+
routes.push({ call: currency.fixed, rows: () => [], fixed: currency.at });
|
|
447
|
+
}
|
|
387
448
|
const denied = new Map();
|
|
449
|
+
let writes = 0;
|
|
450
|
+
let made = 0;
|
|
451
|
+
let lose = false;
|
|
452
|
+
/** A record, in the names a read maps, as a row the read maps back: what it does not name stays out. */
|
|
453
|
+
const rowFor = (kind, fields) => {
|
|
454
|
+
const entity = manifest.entities[kind];
|
|
455
|
+
const map = entity.map;
|
|
456
|
+
const node = rowNodeOf(entity.list);
|
|
457
|
+
const scalar = (field, value) => {
|
|
458
|
+
if (typeof value === "number" && FIELDS[kind][field] === "epoch")
|
|
459
|
+
return { ms: value };
|
|
460
|
+
return ["string", "number", "boolean"].includes(typeof value) ? value : undefined;
|
|
461
|
+
};
|
|
462
|
+
const given = Object.fromEntries(Object.keys(map).flatMap((field) => {
|
|
463
|
+
const value = scalar(field, fields[field]);
|
|
464
|
+
return value === undefined ? [] : [[field, value]];
|
|
465
|
+
}));
|
|
466
|
+
// Only the rules with a value shape the sample: one without would sample a value where the record has none.
|
|
467
|
+
const rules = Object.fromEntries(Object.entries(map).filter(([field]) => field in given || field === "pipeline"));
|
|
468
|
+
const row = rowOf(node, rules, FIELDS[kind], 0, given);
|
|
469
|
+
for (const [field, value] of Object.entries(fields)) {
|
|
470
|
+
if (!Array.isArray(value))
|
|
471
|
+
continue;
|
|
472
|
+
const ids = value.map((one) => (isRaw(one) ? String(one.externalId) : String(one)));
|
|
473
|
+
const rule = map[field];
|
|
474
|
+
const path = pathOf(rule);
|
|
475
|
+
if (typeof rule === "object" && "each" in rule)
|
|
476
|
+
putEach(row, rule, node, ids);
|
|
477
|
+
else if (path !== undefined && ids[0] !== undefined)
|
|
478
|
+
put(row, path, ids[0], node);
|
|
479
|
+
}
|
|
480
|
+
return row;
|
|
481
|
+
};
|
|
482
|
+
/** A create, update or remove of one record, as the service would make it, answered as its schema says. */
|
|
483
|
+
const written = (route, call) => {
|
|
484
|
+
writes += 1;
|
|
485
|
+
const { kind, write } = route;
|
|
486
|
+
const list = rows[kind] ?? [];
|
|
487
|
+
rows[kind] = list;
|
|
488
|
+
const root = rootOf(route.call);
|
|
489
|
+
const sampled = sample(root);
|
|
490
|
+
const answer = isRaw(sampled) ? sampled : {};
|
|
491
|
+
const externalId = write.verb === "create"
|
|
492
|
+
? String((manifest.kinds.indexOf(kind) + 1) * 1000 + 500 + ++made)
|
|
493
|
+
: String(readPlace(call, write.id) ?? "");
|
|
494
|
+
const place = list.findIndex((one) => idOf(kind, one) === externalId);
|
|
495
|
+
if (write.verb !== "create" && place < 0)
|
|
496
|
+
return refuse(`${call.operation}: no ${kind} ${externalId} in the fake`, 404);
|
|
497
|
+
if (write.verb === "remove") {
|
|
498
|
+
list.splice(place, 1);
|
|
499
|
+
return { body: answer };
|
|
500
|
+
}
|
|
501
|
+
const entity = manifest.entities[kind];
|
|
502
|
+
const before = place < 0 ? {} : (mapRecord(kind, entity, list[place]) ?? {});
|
|
503
|
+
const values = write.values ? readPlace(call, write.values) : undefined;
|
|
504
|
+
const known = [
|
|
505
|
+
...Object.values(write.spec.fields).flatMap((rule) => typeof rule === "object" && "to" in rule ? [rule.to] : []),
|
|
506
|
+
...(manifest.fields?.[kind] ? Array.from({ length: PAGE }, (_, n) => `${kind}_field_${n + 1}`) : []),
|
|
507
|
+
];
|
|
508
|
+
const unknown = Object.keys(isRaw(values) ? values : {}).filter((key) => !known.includes(key));
|
|
509
|
+
if (unknown.length)
|
|
510
|
+
return refuse(`${call.operation}: ${kind} has no field ${unknown.join(", ")} in the fake`);
|
|
511
|
+
const given = givenOf(write.spec, values);
|
|
512
|
+
const pipeline = pipelines.get(kind);
|
|
513
|
+
const fields = {
|
|
514
|
+
...(pipeline ? { pipeline: pipeline.id } : {}),
|
|
515
|
+
...before,
|
|
516
|
+
...given,
|
|
517
|
+
externalId,
|
|
518
|
+
updatedAt: Date.now(),
|
|
519
|
+
};
|
|
520
|
+
const currency = write.spec.fields.currency;
|
|
521
|
+
if (typeof currency === "object" && "fixed" in currency && fields.amount != null)
|
|
522
|
+
fields.currency = CURRENCY;
|
|
523
|
+
const row = rowFor(kind, fields);
|
|
524
|
+
if (place < 0)
|
|
525
|
+
list.push(row);
|
|
526
|
+
else
|
|
527
|
+
list[place] = row;
|
|
528
|
+
if (write.verb === "create" && write.spec.id)
|
|
529
|
+
putList(answer, write.spec.id, externalId, root);
|
|
530
|
+
return { body: answer };
|
|
531
|
+
};
|
|
388
532
|
const refuse = (message, status = 400) => {
|
|
389
533
|
own.push(message);
|
|
390
534
|
return { status, body: { message } };
|
|
@@ -464,6 +608,15 @@ export const crmManifestFake = (input, options) => {
|
|
|
464
608
|
const route = routeOf(call);
|
|
465
609
|
if (!route)
|
|
466
610
|
return refuse(`${call.operation ?? call.url.pathname}: no call of the source manifest is this one`, 404);
|
|
611
|
+
if (route.write && route.kind)
|
|
612
|
+
return written({ ...route, kind: route.kind, write: route.write }, call);
|
|
613
|
+
if (route.fixed !== undefined) {
|
|
614
|
+
const root = rootOf(route.call);
|
|
615
|
+
const sampled = sample(root);
|
|
616
|
+
const answer = isRaw(sampled) ? sampled : {};
|
|
617
|
+
putList(answer, route.fixed, CURRENCY, root);
|
|
618
|
+
return { body: answer };
|
|
619
|
+
}
|
|
467
620
|
const changes = route.since ? route : undefined;
|
|
468
621
|
if (changes?.since && readPlace(call, changes.since.place) === undefined)
|
|
469
622
|
return refuse(`${call.operation}: a read of changes without its since`);
|
|
@@ -514,7 +667,15 @@ export const crmManifestFake = (input, options) => {
|
|
|
514
667
|
answers: Object.fromEntries(api.operations.map((one) => [one.id, answerOf])),
|
|
515
668
|
});
|
|
516
669
|
return {
|
|
517
|
-
|
|
670
|
+
async fetch(input, init) {
|
|
671
|
+
const before = writes;
|
|
672
|
+
const answer = await fake.fetch(input, init);
|
|
673
|
+
if (lose && writes > before) {
|
|
674
|
+
lose = false;
|
|
675
|
+
throw new TypeError("fetch failed");
|
|
676
|
+
}
|
|
677
|
+
return answer;
|
|
678
|
+
},
|
|
518
679
|
calls: fake.calls,
|
|
519
680
|
get refusals() {
|
|
520
681
|
return [...fake.refusals, ...own];
|
|
@@ -533,6 +694,10 @@ export const crmManifestFake = (input, options) => {
|
|
|
533
694
|
if (timeOf(kind, row) === null)
|
|
534
695
|
throw new Error(`the fake cannot change the time of ${kind} ${id}`);
|
|
535
696
|
},
|
|
697
|
+
loseNextAnswer: () => {
|
|
698
|
+
lose = true;
|
|
699
|
+
},
|
|
700
|
+
requests: () => writes,
|
|
536
701
|
};
|
|
537
702
|
};
|
|
538
703
|
const externalIdOf = (manifest, kind, row) => {
|
|
@@ -616,3 +781,63 @@ export const crmManifestContract = (manifest, options) => {
|
|
|
616
781
|
},
|
|
617
782
|
}));
|
|
618
783
|
};
|
|
784
|
+
/**
|
|
785
|
+
* A `crmWriteContract` fixture for a writer built from a manifest's `writes`, over `crmManifestFake`: the writer, the
|
|
786
|
+
* first pipeline of the deal kind it writes, the service's own names of stage and owner, and the fake.
|
|
787
|
+
*/
|
|
788
|
+
export const crmManifestWriteFixture = async (manifest, options) => {
|
|
789
|
+
const fake = crmManifestFake(manifest, options);
|
|
790
|
+
const sending = {
|
|
791
|
+
manifest: options.api,
|
|
792
|
+
service: manifest.provider,
|
|
793
|
+
fetch: fake.fetch,
|
|
794
|
+
token: () => FAKE_MANIFEST_TOKEN,
|
|
795
|
+
...(options.baseUrl ? { baseUrl: options.baseUrl } : {}),
|
|
796
|
+
};
|
|
797
|
+
const source = crmSourceFromManifest(manifest, {
|
|
798
|
+
api: options.api,
|
|
799
|
+
call: serviceApiCall(sending),
|
|
800
|
+
...(options.hooks ? { hooks: options.hooks } : {}),
|
|
801
|
+
});
|
|
802
|
+
const writer = crmWriterFromManifest(manifest, {
|
|
803
|
+
api: options.api,
|
|
804
|
+
service: manifest.provider,
|
|
805
|
+
send: serviceApiSend(sending),
|
|
806
|
+
source: () => source,
|
|
807
|
+
});
|
|
808
|
+
const kind = DEAL_KINDS.find((one) => writer.capabilities.kinds.includes(one));
|
|
809
|
+
if (!kind)
|
|
810
|
+
throw new Error("the manifest writes no deal or lead, and the write contract needs one");
|
|
811
|
+
const [pipeline] = await source.pipelines(kind);
|
|
812
|
+
if (!pipeline)
|
|
813
|
+
throw new Error(`the fake holds no ${kind} pipeline`);
|
|
814
|
+
const fields = (manifest.writes?.[kind]?.fields ?? {});
|
|
815
|
+
const aliases = [fields.stage, fields.owner].flatMap((rule) => isRaw(rule) && typeof rule.to === "string" ? [rule.to] : []);
|
|
816
|
+
return {
|
|
817
|
+
writer,
|
|
818
|
+
kind,
|
|
819
|
+
pipeline,
|
|
820
|
+
aliases,
|
|
821
|
+
loseNextAnswer: fake.loseNextAnswer,
|
|
822
|
+
requests: fake.requests,
|
|
823
|
+
fake,
|
|
824
|
+
};
|
|
825
|
+
};
|
|
826
|
+
/** `crmWriteContract` over `crmManifestWriteFixture`, each case failing too when the fake refused a call. */
|
|
827
|
+
export const crmManifestWriteContract = (manifest, options) => {
|
|
828
|
+
const fakes = [];
|
|
829
|
+
return crmWriteContract(async () => {
|
|
830
|
+
const fixture = await crmManifestWriteFixture(manifest, options);
|
|
831
|
+
fakes.push(fixture.fake);
|
|
832
|
+
return fixture;
|
|
833
|
+
}).map(({ name, run }) => ({
|
|
834
|
+
name,
|
|
835
|
+
async run() {
|
|
836
|
+
fakes.length = 0;
|
|
837
|
+
await run();
|
|
838
|
+
const refused = fakes.flatMap((fake) => fake.refusals);
|
|
839
|
+
if (refused.length)
|
|
840
|
+
throw new Error(`the fake refused calls the writer made:\n${refused.join("\n")}`);
|
|
841
|
+
},
|
|
842
|
+
}));
|
|
843
|
+
};
|
|
@@ -71,6 +71,13 @@ export const WIRECAT_TOOLS = [
|
|
|
71
71
|
package: "@wirecat/amo-cli",
|
|
72
72
|
does: "amoCRM and Kommo: deals, contacts and companies, searchable with your other WireCat data",
|
|
73
73
|
},
|
|
74
|
+
{
|
|
75
|
+
command: "attio",
|
|
76
|
+
appName: "attio-cli",
|
|
77
|
+
envPrefix: "WCATTIO",
|
|
78
|
+
package: "@wirecat/attio-cli",
|
|
79
|
+
does: "Attio CRM: deals, people and companies, searchable with your other WireCat data",
|
|
80
|
+
},
|
|
74
81
|
{
|
|
75
82
|
command: "pbx",
|
|
76
83
|
appName: "asterisk-cli",
|
|
@@ -14,12 +14,12 @@ export declare const metadataService: (deps: ServiceDeps) => {
|
|
|
14
14
|
dryRun?: boolean;
|
|
15
15
|
}) => Promise<{
|
|
16
16
|
items: ({
|
|
17
|
+
error?: undefined;
|
|
17
18
|
chatId: string;
|
|
18
19
|
tags: import("../domain/channel-tags.js").ChannelTagMatch[];
|
|
19
20
|
algorithm: string;
|
|
20
21
|
fetchedAt: string | null;
|
|
21
22
|
source: string;
|
|
22
|
-
error?: undefined;
|
|
23
23
|
} | {
|
|
24
24
|
tags?: undefined;
|
|
25
25
|
algorithm?: undefined;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wirecat/cli-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.723.0",
|
|
4
4
|
"description": "The messenger-neutral half of a messaging CLI: domain model, message locators, rendering, name resolution, the SQLite seam, the command skeleton and shared read commands, the send guard, run records and the message store",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "Viacheslav Ptsarev",
|