@wirecat/cli-core 0.692.0 → 0.694.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 (38) hide show
  1. package/CHANGELOG.md +85 -0
  2. package/README.md +1 -1
  3. package/dist/background/daily-archive-timer.d.ts +1 -1
  4. package/dist/calendar/prepare.d.ts +11 -0
  5. package/dist/cli/bot/api-http.d.ts +4 -1
  6. package/dist/cli/bot/api-http.js +17 -4
  7. package/dist/cli/bot/api-input.d.ts +4 -0
  8. package/dist/cli/bot/api-input.js +9 -0
  9. package/dist/cli/bot/api.d.ts +4 -0
  10. package/dist/cli/bot/api.js +16 -2
  11. package/dist/cli/documents/words.d.ts +1 -1
  12. package/dist/cli/envelope.d.ts +22 -0
  13. package/dist/cli/index.d.ts +6 -4
  14. package/dist/cli/index.js +6 -4
  15. package/dist/cli/oauth-session.d.ts +60 -0
  16. package/dist/cli/oauth-session.js +224 -0
  17. package/dist/cli/service-api-call.d.ts +2 -1
  18. package/dist/cli/service-api-call.js +4 -6
  19. package/dist/cli/service-api-manifest.d.ts +10 -10
  20. package/dist/cli/service-api-manifest.js +37 -33
  21. package/dist/cli/service-api.d.ts +17 -2
  22. package/dist/cli/service-api.js +42 -24
  23. package/dist/cli/token-session.d.ts +33 -0
  24. package/dist/cli/token-session.js +121 -0
  25. package/dist/crm/index.d.ts +2 -1
  26. package/dist/crm/index.js +1 -0
  27. package/dist/crm/manifest/manifest.d.ts +19 -0
  28. package/dist/crm/manifest/manifest.js +6 -1
  29. package/dist/crm/manifest/map.d.ts +5 -0
  30. package/dist/crm/manifest/map.js +21 -15
  31. package/dist/crm/manifest/paths.d.ts +11 -0
  32. package/dist/crm/manifest/paths.js +161 -0
  33. package/dist/crm/manifest/source.js +105 -34
  34. package/dist/manifest/index.d.ts +53 -0
  35. package/dist/manifest/index.js +61 -0
  36. package/dist/search/lucene/plain.js +2 -1
  37. package/dist/services/metadata.d.ts +1 -1
  38. package/package.json +7 -3
@@ -0,0 +1,121 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { annotate } from "@wirecat/cli-base/commands";
3
+ import { Command } from "commander";
4
+ import { readSecret } from "../terminal/prompt.js";
5
+ import { baseContext, environmentOf, outputFor, secretInputOf } from "./context.js";
6
+ import { refuseOffline } from "./early-refusal.js";
7
+ import { FETCH, LOCAL_READ, LOCAL_WRITE, logsInOrOut, REMOTE_READ, refuseUnderReadOnly } from "./effects.js";
8
+ import { itemOf, listOf, renderAnswer } from "./envelope.js";
9
+ import { profilesHere, rememberAccount } from "./messenger/accounts.js";
10
+ import { commandWords, profileFree, refuseCommandName, rootOf } from "./profile.js";
11
+ import { ProfileTokenStore } from "./profile-token.js";
12
+ export const storageOf = (raw) => {
13
+ if (raw === "keyring" || raw === "file")
14
+ return raw;
15
+ throw new CliError("validation_error", `--credential-storage takes keyring or file; got ${raw}`);
16
+ };
17
+ /**
18
+ * `session start | status | end | list` for a service signed in with one token (WC-ACCT-12): the token is asked hidden
19
+ * or read from stdin, checked with the service, and only then kept in the keyring or a private file.
20
+ */
21
+ export const tokenSessionCommand = (options) => {
22
+ const { app, service } = options;
23
+ const word = options.token ?? "API token";
24
+ const contextOf = (command) => {
25
+ const base = baseContext(command, options.resolveSettings);
26
+ const tokens = new ProfileTokenStore({
27
+ app,
28
+ env: base.env,
29
+ ...(base.keyring ? { keyring: base.keyring } : {}),
30
+ warn: base.renderer.warn,
31
+ });
32
+ return { ...base, profile: base.settings.profile, tokens };
33
+ };
34
+ const answer = (command, item) => renderAnswer(command, outputFor(command), itemOf(item));
35
+ const start = logsInOrOut(annotate(new Command("start"), {
36
+ effects: FETCH,
37
+ lifetime: "interactive",
38
+ mcp: false,
39
+ examples: [
40
+ `${app.command} personal session start`,
41
+ `${app.command} personal session start --credential-storage file`,
42
+ ],
43
+ }))
44
+ .summary(`sign in to ${service} with its ${word}`)
45
+ .description(`sign this profile in: the ${service} ${word} is asked hidden or read from stdin, never taken as an argument, ` +
46
+ `checked with ${service}, and only then kept in the keyring, or in a private file` +
47
+ (options.about ? `. ${options.about}` : ""))
48
+ .option("--credential-storage <storage>", "where the token is kept: keyring, which falls back to a private file by itself, or file", storageOf, "keyring")
49
+ .action(async function (args) {
50
+ const { env, profile, tokens, run } = contextOf(this);
51
+ refuseCommandName(profile, commandWords(rootOf(this)), app.command);
52
+ refuseOffline(this, service);
53
+ // A secret is never an argument: it would land in shell history and in the run record (WC-SECR-5).
54
+ const token = (await readSecret(`${service} ${word}: `, secretInputOf(this))).trim();
55
+ if (!token)
56
+ throw new CliError("validation_error", "no token was given");
57
+ const { id, account } = await run((events) => options.verify(this, token, events));
58
+ (options.claim ?? ((at, name, key) => rememberAccount(app, name, key, at)))(env, profile, id, tokens);
59
+ const storedIn = tokens.write(profile, token, args.credentialStorage);
60
+ answer(this, { profile, state: "saved", stored_in: storedIn, verified: true, ...account });
61
+ });
62
+ const status = annotate(new Command("status"), {
63
+ effects: REMOTE_READ,
64
+ examples: [`${app.command} personal session status`, `${app.command} personal session status --check --json`],
65
+ })
66
+ .summary("show where this profile's token comes from; never the token")
67
+ .description(`show where this profile's token comes from: ${app.envPrefix}_TOKEN, the keyring or a file, never the token; ` +
68
+ `--check asks ${service} whose token it is`)
69
+ .option("--check", `ask ${service} whether the token still works, and whose it is`)
70
+ .action(async function (args) {
71
+ const { profile, tokens, run } = contextOf(this);
72
+ const saved = tokens.read(profile);
73
+ const state = { profile, state: saved ? "saved" : "missing", token_from: saved?.source ?? null };
74
+ if (!args.check || !saved)
75
+ return answer(this, { ...state, verified: false });
76
+ refuseOffline(this, service);
77
+ const { account } = await run((events) => options.verify(this, saved.secret, events));
78
+ answer(this, { ...state, verified: true, ...account });
79
+ });
80
+ const end = logsInOrOut(annotate(new Command("end"), {
81
+ effects: LOCAL_WRITE,
82
+ mcp: false,
83
+ examples: [`${app.command} personal session end`],
84
+ }))
85
+ .summary("forget this profile's token on this computer")
86
+ .description(`forget this profile's token on this computer; the token itself stays valid in ${service}` +
87
+ (options.endNote ? `. ${options.endNote}` : ""))
88
+ .action(function () {
89
+ refuseUnderReadOnly(this, "session end");
90
+ const { profile, tokens } = contextOf(this);
91
+ answer(this, { profile, ended: tokens.remove(profile) });
92
+ });
93
+ const list = profileFree(annotate(new Command("list"), {
94
+ effects: LOCAL_READ,
95
+ examples: [`${app.command} session list`, `${app.command} session list --json`],
96
+ }))
97
+ .summary("list the profiles here and whether each is signed in")
98
+ .description("list the profiles on this computer and whether each has a token; picks none")
99
+ .action(function () {
100
+ const environment = environmentOf(this);
101
+ const env = environment.env ?? process.env;
102
+ const { configuredProfiles } = options.resolveSettings({}, { env, needsProfile: false });
103
+ const tokens = new ProfileTokenStore({
104
+ app,
105
+ env,
106
+ ...(environment.keyring ? { keyring: environment.keyring } : {}),
107
+ warn: outputFor(this).renderer.warn,
108
+ });
109
+ const items = profilesHere(app, configuredProfiles, env).map((profile) => {
110
+ const saved = tokens.read(profile);
111
+ return { profile, signed_in: saved !== undefined, token_from: saved?.source ?? null };
112
+ });
113
+ renderAnswer(this, outputFor(this), listOf("session list", { items, limit: Math.max(1, items.length), has_more: false }));
114
+ });
115
+ return annotate(new Command("session"), { effects: LOCAL_READ })
116
+ .description(`keep this profile's ${service} token in the OS keyring`)
117
+ .addCommand(start)
118
+ .addCommand(status)
119
+ .addCommand(end)
120
+ .addCommand(list);
121
+ };
@@ -1,7 +1,8 @@
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 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 CrmManifest, type CrmManifestEntity, type CrmManifestFields, type CrmManifestHooks, type CrmManifestPipelines, type CrmOperationCall, type CrmRule, parseCrmManifest, } from "./manifest/manifest.js";
5
+ export { crmManifestProblems } from "./manifest/paths.js";
5
6
  export { type CrmManifestSourceOptions, crmSourceFromManifest } from "./manifest/source.js";
6
7
  export { type ProviderCallOptions, providerCall } from "./provider-call.js";
7
8
  export { type CrmConditionHooks, type CrmQueryField, conditionsOf, customConditions, customNames, filterableFields, selectedCodes, wantedCodes, withCustomFields, } from "./query.js";
package/dist/crm/index.js CHANGED
@@ -2,6 +2,7 @@ export { fetchCrmFile } from "./file-fetch.js";
2
2
  export { crmFileId, LINK_REMOVED, parseCrmFileId, withoutFileLinks } from "./files.js";
3
3
  export { DAILY_FOREIGN_CONTACTS, foreignContacts, foreignContactsPathFor, refuseForeignClientReads, } from "./foreign-contacts.js";
4
4
  export { parseCrmManifest, } from "./manifest/manifest.js";
5
+ export { crmManifestProblems } from "./manifest/paths.js";
5
6
  export { crmSourceFromManifest } from "./manifest/source.js";
6
7
  export { providerCall } from "./provider-call.js";
7
8
  export { conditionsOf, customConditions, customNames, filterableFields, selectedCodes, wantedCodes, withCustomFields, } from "./query.js";
@@ -72,6 +72,8 @@ export interface CrmManifestEntity<K extends CrmKind = CrmKind> {
72
72
  select?: {
73
73
  from: string;
74
74
  also?: readonly string[];
75
+ /** The longest `{select}` the service takes, in characters joined by commas; the rest is a gap. */
76
+ max?: number;
75
77
  };
76
78
  map: {
77
79
  readonly [F in keyof CrmRecords[K]]?: CrmRule;
@@ -84,6 +86,14 @@ export interface CrmManifestEntity<K extends CrmKind = CrmKind> {
84
86
  from: string;
85
87
  split?: string;
86
88
  };
89
+ /**
90
+ * A kind the plan or the sign-in may not have (HubSpot's leads): the service refusing it is a gap with this text and
91
+ * scope, and the other kinds still sync.
92
+ */
93
+ optional?: {
94
+ message: string;
95
+ scope?: string;
96
+ };
87
97
  }
88
98
  export interface CrmManifestPipelines {
89
99
  call: CrmOperationCall;
@@ -166,6 +176,15 @@ export interface CrmManifestHooks {
166
176
  after?: {
167
177
  readonly [K in CrmKind]?: CrmAfterHook<K>;
168
178
  };
179
+ /**
180
+ * Reads more for a whole page before the map, in one batch request: what an answer leaves out and another operation
181
+ * gives (HubSpot's associations, which a search does not answer).
182
+ */
183
+ enrich?: {
184
+ readonly [K in CrmKind]?: (rows: CrmRaw[], service: {
185
+ call: ServiceApiCall;
186
+ }) => Promise<CrmRaw[]>;
187
+ };
169
188
  /** Adds or replaces source methods (`self`, `activities`, a live `list`); `base` is what the manifest built. */
170
189
  extend?: (base: CrmSource) => Partial<CrmSource>;
171
190
  }
@@ -34,9 +34,14 @@ const entity = v.strictObject({
34
34
  })),
35
35
  ids: v.optional(call),
36
36
  get: v.optional(call),
37
- select: v.optional(v.strictObject({ from: path, also: v.optional(v.array(v.string())) })),
37
+ select: v.optional(v.strictObject({
38
+ from: path,
39
+ also: v.optional(v.array(v.string())),
40
+ max: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1))),
41
+ })),
38
42
  map: v.record(v.string(), rule),
39
43
  custom: v.optional(v.strictObject({ from: path, split: v.optional(v.string()) })),
44
+ optional: v.optional(v.strictObject({ message: v.pipe(v.string(), v.minLength(1)), scope: v.optional(v.string()) })),
40
45
  });
41
46
  const pipelines = v.strictObject({
42
47
  call,
@@ -48,6 +48,11 @@ export interface RecordRules {
48
48
  }
49
49
  /** One row as our record of the kind, or null for a row without an id. */
50
50
  export declare const mapRecord: <K extends CrmKind>(kind: K, rules: RecordRules, raw: CrmRaw, defined?: readonly CrmField[]) => CrmRecords[K] | null;
51
+ /** Each path a rule reads; `inside` is the list an `each` reads its `id` or `value` from, item by item. */
52
+ export declare const rulePaths: (rule: CrmRule | undefined) => {
53
+ path: string;
54
+ inside?: string;
55
+ }[];
51
56
  /** The names under `from` that the rules read: what a service that names its returned fields is asked for. */
52
57
  export declare const selectedOf: (rules: Readonly<Record<string, CrmRule | undefined>>, from: string) => string[];
53
58
  export {};
@@ -210,24 +210,30 @@ export const mapRecord = (kind, rules, raw, defined = []) => {
210
210
  out.metadata = metadata;
211
211
  return out;
212
212
  };
213
+ /** Each path a rule reads; `inside` is the list an `each` reads its `id` or `value` from, item by item. */
214
+ export const rulePaths = (rule) => {
215
+ if (rule === undefined || typeof rule === "function")
216
+ return [];
217
+ if (typeof rule === "string")
218
+ return [{ path: rule }];
219
+ if ("first" in rule)
220
+ return rule.first.map((path) => ({ path }));
221
+ if ("join" in rule)
222
+ return rule.join.map((path) => ({ path }));
223
+ if ("all" in rule)
224
+ return rule.all.map((path) => ({ path }));
225
+ if ("each" in rule)
226
+ return [
227
+ { path: rule.each },
228
+ { path: "id" in rule ? rule.id : rule.value, inside: rule.each },
229
+ ...("primary" in rule && rule.primary ? [{ path: rule.primary }] : []),
230
+ ];
231
+ return "path" in rule ? [{ path: rule.path }] : [];
232
+ };
213
233
  /** The names under `from` that the rules read: what a service that names its returned fields is asked for. */
214
234
  export const selectedOf = (rules, from) => {
215
235
  const prefix = `${from}.`;
216
- const paths = Object.values(rules).flatMap((rule) => {
217
- if (rule === undefined || typeof rule === "function")
218
- return [];
219
- if (typeof rule === "string")
220
- return [rule];
221
- if ("first" in rule)
222
- return [...rule.first];
223
- if ("join" in rule)
224
- return [...rule.join];
225
- if ("all" in rule)
226
- return [...rule.all];
227
- if ("each" in rule)
228
- return [rule.each, ...("primary" in rule && rule.primary ? [rule.primary] : [])];
229
- return "path" in rule ? [rule.path] : [];
230
- });
236
+ const paths = Object.values(rules).flatMap((rule) => rulePaths(rule).flatMap(({ path, inside }) => (inside === undefined ? [path] : [])));
231
237
  return [
232
238
  ...new Set(paths.filter((one) => one.startsWith(prefix)).map((one) => one.slice(prefix.length).split(".")[0] ?? "")),
233
239
  ].filter(Boolean);
@@ -0,0 +1,11 @@
1
+ import type { SchemaNode } from "@wirecat/cli-base/codegen";
2
+ import type { ServiceApiManifest } from "../../cli/service-api-manifest.js";
3
+ import type { CrmManifest } from "./manifest.js";
4
+ type Definitions = Readonly<Record<string, SchemaNode>>;
5
+ /**
6
+ * Every path the manifest reads, checked against the schema each operation answers (`definitions` of the generated
7
+ * API): a misspelt or moved field is named with the operation, and the field it likely meant, before a sync runs.
8
+ * A part of a schema that says nothing (`unknown`, an open object) passes. Empty when all hold.
9
+ */
10
+ export declare const crmManifestProblems: (manifest: CrmManifest, api: ServiceApiManifest, definitions: Definitions) => string[];
11
+ export {};
@@ -0,0 +1,161 @@
1
+ import { editDistance } from "../../search/correct.js";
2
+ import { rulePaths } from "./map.js";
3
+ const resolve = (node, definitions, seen = new Set()) => {
4
+ if (node.type !== "ref" || seen.has(node.ref))
5
+ return node;
6
+ const found = definitions[node.ref];
7
+ return found ? resolve(found, definitions, new Set([...seen, node.ref])) : { type: "unknown" };
8
+ };
9
+ /** The node one step down, `null` when the schema has no such field, `undefined` when the schema cannot say. */
10
+ const step = (node, key, definitions) => {
11
+ const at = resolve(node, definitions);
12
+ switch (at.type) {
13
+ case "object": {
14
+ const found = at.properties[key] ?? at.additionalProperties;
15
+ if (found)
16
+ return found;
17
+ // An object the spec leaves open ("any object") comes out of the adapter with no fields at all.
18
+ return Object.keys(at.properties).length === 0 ? undefined : null;
19
+ }
20
+ case "array":
21
+ return /^\d+$/.test(key) ? at.items : null;
22
+ case "allOf":
23
+ case "union": {
24
+ const found = at.of.map((one) => step(one, key, definitions));
25
+ if (found.includes(undefined))
26
+ return undefined;
27
+ const matched = found.filter((one) => one !== null);
28
+ if (matched.length === 0)
29
+ return null;
30
+ return matched.length === 1 ? matched[0] : { type: "union", of: matched };
31
+ }
32
+ case "unknown":
33
+ return undefined;
34
+ default:
35
+ return null;
36
+ }
37
+ };
38
+ const keysOf = (node, definitions) => {
39
+ const at = resolve(node, definitions);
40
+ if (at.type === "object")
41
+ return Object.keys(at.properties);
42
+ if (at.type === "allOf" || at.type === "union")
43
+ return at.of.flatMap((one) => keysOf(one, definitions));
44
+ return [];
45
+ };
46
+ const walk = (node, path, definitions) => {
47
+ let at = node;
48
+ const segments = path === "." ? [] : path.split(".");
49
+ for (const [place, key] of segments.entries()) {
50
+ if (at === undefined)
51
+ return { node: undefined };
52
+ const next = step(at, key, definitions);
53
+ if (next === null) {
54
+ const near = keysOf(at, definitions)
55
+ .map((one) => ({ one, edits: editDistance(key, one, 2) }))
56
+ .filter(({ edits }) => edits <= 2)
57
+ .sort((a, b) => a.edits - b.edits)[0]?.one;
58
+ return {
59
+ missing: segments.slice(0, place + 1).join("."),
60
+ ...(near ? { near: [...segments.slice(0, place), near].join(".") } : {}),
61
+ };
62
+ }
63
+ at = next;
64
+ }
65
+ return { node: at };
66
+ };
67
+ /** One item of the list a path ends on; a path that ends on one object is read as a list of it, as the map does. */
68
+ const itemOf = (node, definitions) => {
69
+ if (node === undefined)
70
+ return undefined;
71
+ const at = resolve(node, definitions);
72
+ return at.type === "array" ? at.items : at;
73
+ };
74
+ const missingText = (found, operation) => `${found.missing} is not in what ${operation} answers${found.near ? `; did you mean ${found.near}?` : ""}`;
75
+ /**
76
+ * Every path the manifest reads, checked against the schema each operation answers (`definitions` of the generated
77
+ * API): a misspelt or moved field is named with the operation, and the field it likely meant, before a sync runs.
78
+ * A part of a schema that says nothing (`unknown`, an open object) passes. Empty when all hold.
79
+ */
80
+ export const crmManifestProblems = (manifest, api, definitions) => {
81
+ const operations = new Map(api.operations.map((one) => [one.id, one]));
82
+ const problems = [];
83
+ const problem = (where, text) => problems.push(`source manifest: ${where}: ${text}`);
84
+ /** The schema of one row the call answers: its response, down `items`, one item of the list. */
85
+ const rowOf = (where, operation, call) => {
86
+ const schema = operation.response?.schema;
87
+ if (!schema)
88
+ return undefined;
89
+ const root = { type: "ref", ref: schema };
90
+ const items = call.items ?? operation.pagination?.items;
91
+ if (items === undefined)
92
+ return itemOf(root, definitions);
93
+ const found = walk(root, items, definitions);
94
+ if ("missing" in found) {
95
+ problem(`${where}.items`, missingText(found, call.operation));
96
+ return undefined;
97
+ }
98
+ return itemOf(found.node, definitions);
99
+ };
100
+ const check = (where, call, rules, inside) => {
101
+ const operation = operations.get(call.operation);
102
+ if (!operation)
103
+ return problem(where, `no operation ${call.operation} in the API`);
104
+ let row = rowOf(where, operation, call);
105
+ if (row === undefined)
106
+ return;
107
+ if (inside !== undefined) {
108
+ const list = walk(row, inside, definitions);
109
+ if ("missing" in list)
110
+ return problem(where, missingText(list, call.operation));
111
+ row = itemOf(list.node, definitions);
112
+ if (row === undefined)
113
+ return;
114
+ }
115
+ for (const [field, rule] of Object.entries(rules))
116
+ for (const { path, inside: list } of rulePaths(rule)) {
117
+ let from = row;
118
+ if (list !== undefined) {
119
+ const found = walk(row, list, definitions);
120
+ from = "node" in found ? itemOf(found.node, definitions) : undefined;
121
+ if (from === undefined)
122
+ continue;
123
+ }
124
+ const found = walk(from, path, definitions);
125
+ if ("missing" in found)
126
+ problem(`${where}.${field}`, missingText(found, call.operation));
127
+ }
128
+ };
129
+ for (const [kind, entity] of Object.entries(manifest.entities)) {
130
+ if (!entity)
131
+ continue;
132
+ const rules = {
133
+ ...entity.map,
134
+ ...(entity.custom ? { "(custom)": entity.custom.from } : {}),
135
+ };
136
+ for (const call of [entity.list, entity.changes, entity.get])
137
+ if (call)
138
+ check(`entities.${kind}.map`, call, rules);
139
+ }
140
+ for (const [kind, pipelines] of Object.entries(manifest.pipelines ?? {})) {
141
+ if (!pipelines)
142
+ continue;
143
+ check(`pipelines.${kind}.map`, pipelines.call, { ...pipelines.map, "(stages)": pipelines.stages.each });
144
+ const { outcome } = pipelines.stages;
145
+ check(`pipelines.${kind}.stages.map`, pipelines.call, {
146
+ ...pipelines.stages.map,
147
+ ...(typeof outcome === "object" && "path" in outcome ? { outcome: outcome.path } : {}),
148
+ }, pipelines.stages.each);
149
+ }
150
+ for (const [kind, fields] of Object.entries(manifest.fields ?? {})) {
151
+ if (!fields)
152
+ continue;
153
+ const { options, ...map } = fields.map;
154
+ check(`fields.${kind}.map`, fields.call, map);
155
+ if (options && typeof options === "object")
156
+ check(`fields.${kind}.map.options`, fields.call, { id: options.id, label: options.label }, options.each);
157
+ }
158
+ if (manifest.users)
159
+ check("users.map", manifest.users.call, manifest.users.map);
160
+ return problems;
161
+ };
@@ -127,7 +127,7 @@ export const crmSourceFromManifest = (input, options) => {
127
127
  .then((rows) => rows.flatMap((raw) => toField(spec, raw) ?? []))
128
128
  .catch((error) => {
129
129
  if (isCliError(error) && error.code === "permission_error") {
130
- context?.gap({
130
+ gap(context, {
131
131
  kind,
132
132
  message: `the service refused the ${kind} field definitions: no custom values are read`,
133
133
  });
@@ -140,18 +140,61 @@ export const crmSourceFromManifest = (input, options) => {
140
140
  }
141
141
  return found;
142
142
  };
143
- const selectOf = (kind, defined) => {
143
+ /** Each gap once per call: a round of a hundred pages would otherwise store the same gap a hundred times. */
144
+ const said = new WeakMap();
145
+ const gap = (context, one) => {
146
+ if (!context)
147
+ return;
148
+ const seen = said.get(context) ?? new Set();
149
+ said.set(context, seen);
150
+ const key = `${one.kind} ${one.message}`;
151
+ if (seen.has(key))
152
+ return;
153
+ seen.add(key);
154
+ context.gap(one);
155
+ };
156
+ /**
157
+ * The names `{select}` asks for: every mapped one, then the account's own while they fit `max` (a request line past
158
+ * about 8 KB is refused); the call says how many it left out.
159
+ */
160
+ const selectOf = (kind, defined, context) => {
144
161
  const entity = entityOf(kind);
145
162
  if (!entity.select)
146
163
  return [];
164
+ const own = [...new Set([...selectedOf(entity.map, entity.select.from), ...(entity.select.also ?? [])])];
147
165
  const custom = entity.custom?.from === entity.select.from ? defined.map(({ code }) => code) : [];
148
- return [...new Set([...selectedOf(entity.map, entity.select.from), ...custom, ...(entity.select.also ?? [])])];
166
+ const { max } = entity.select;
167
+ if (max === undefined)
168
+ return [...new Set([...own, ...custom])];
169
+ const kept = [...own];
170
+ let length = own.join(",").length;
171
+ for (const name of custom)
172
+ if (!kept.includes(name) && length + name.length + 1 <= max) {
173
+ kept.push(name);
174
+ length += name.length + 1;
175
+ }
176
+ const left = custom.filter((name) => !kept.includes(name)).length;
177
+ if (left)
178
+ gap(context, {
179
+ kind,
180
+ message: `${left} of the account's own ${kind} fields do not fit one request and were not read`,
181
+ });
182
+ return kept;
183
+ };
184
+ /** A refusal of a kind the manifest marks optional is a gap; the other kinds still sync. */
185
+ const optionalRefused = (kind, error, context) => {
186
+ const optional = manifest.entities[kind]?.optional;
187
+ if (!optional || !isCliError(error) || error.code !== "permission_error")
188
+ return false;
189
+ gap(context, { kind, message: optional.message, ...(optional.scope ? { scope: optional.scope } : {}) });
190
+ return true;
149
191
  };
150
192
  const mapped = async (kind, rows, defined, send) => {
151
193
  const entity = entityOf(kind);
152
194
  const after = hooks.after?.[kind];
195
+ const enrich = hooks.enrich?.[kind];
153
196
  const records = [];
154
- for (const raw of rows) {
197
+ for (const raw of enrich && rows.length ? await enrich([...rows], { call: send }) : rows) {
155
198
  const record = mapRecord(kind, entity, raw, defined);
156
199
  if (record !== null)
157
200
  records.push(after ? await after(record, raw, { call: send }) : record);
@@ -178,6 +221,37 @@ export const crmSourceFromManifest = (input, options) => {
178
221
  return { reset: true };
179
222
  return { rows, next: `${spot.from}.${spot.offset}` };
180
223
  };
224
+ const readChanges = async (kind, cursor, page, context) => {
225
+ const entity = entityOf(kind);
226
+ const since = cursor === null ? null : Date.parse(cursor);
227
+ if (since !== null && Number.isNaN(since))
228
+ return { reset: true };
229
+ const { token, started } = pageOf(page, now());
230
+ const send = metered(context);
231
+ const defined = entity.custom ? await fieldsOf(kind, send, context) : [];
232
+ const changes = since !== null ? entity.changes : undefined;
233
+ const slots = { select: selectOf(kind, defined, context) };
234
+ const read = changes?.keyset && since !== null
235
+ ? await keysetPage({ ...changes, keyset: changes.keyset }, slots, since - overlap, token, send)
236
+ : await readPage(changes ?? entity.list, changes && since !== null ? { ...slots, since: SINCE[changes.since](since - overlap) } : slots, token, send);
237
+ if ("reset" in read)
238
+ return { reset: true };
239
+ const { rows, next } = read;
240
+ const items = await mapped(kind, rows, defined, send);
241
+ return next === undefined
242
+ ? { items, hasMore: false, cursor: new Date(started).toISOString() }
243
+ : { items, hasMore: true, nextCursor: `${next}@${started}` };
244
+ };
245
+ const readIds = async (kind, page, context) => {
246
+ const entity = entityOf(kind);
247
+ const { rows, next } = await readPage(entity.ids ?? entity.list, {}, page, metered(context));
248
+ const items = rows.flatMap((raw) => {
249
+ const found = evaluate(entity.map.externalId, raw);
250
+ const externalId = found === MISSING ? null : id(found);
251
+ return externalId === null ? [] : [externalId];
252
+ });
253
+ return next === undefined ? { items, hasMore: false } : { items, hasMore: true, nextCursor: next };
254
+ };
181
255
  const base = {
182
256
  provider: manifest.provider,
183
257
  traits: { kinds: manifest.kinds, removedInChanges: false },
@@ -185,39 +259,36 @@ export const crmSourceFromManifest = (input, options) => {
185
259
  const spec = manifest.pipelines?.[kind];
186
260
  if (!spec)
187
261
  return [];
188
- const rows = await readAll(spec.call, metered(context));
189
- return rows.flatMap((raw) => toPipeline(spec, raw) ?? []);
262
+ try {
263
+ const rows = await readAll(spec.call, metered(context));
264
+ return rows.flatMap((raw) => toPipeline(spec, raw) ?? []);
265
+ }
266
+ catch (error) {
267
+ if (optionalRefused(kind, error, context))
268
+ return [];
269
+ throw error;
270
+ }
190
271
  },
191
272
  async changes(kind, cursor, page, context) {
192
- const entity = entityOf(kind);
193
- const since = cursor === null ? null : Date.parse(cursor);
194
- if (since !== null && Number.isNaN(since))
195
- return { reset: true };
196
- const { token, started } = pageOf(page, now());
197
- const send = metered(context);
198
- const defined = entity.custom ? await fieldsOf(kind, send, context) : [];
199
- const changes = since !== null ? entity.changes : undefined;
200
- const slots = { select: selectOf(kind, defined) };
201
- const read = changes?.keyset && since !== null
202
- ? await keysetPage({ ...changes, keyset: changes.keyset }, slots, since - overlap, token, send)
203
- : await readPage(changes ?? entity.list, changes && since !== null ? { ...slots, since: SINCE[changes.since](since - overlap) } : slots, token, send);
204
- if ("reset" in read)
205
- return { reset: true };
206
- const { rows, next } = read;
207
- const items = await mapped(kind, rows, defined, send);
208
- return next === undefined
209
- ? { items, hasMore: false, cursor: new Date(started).toISOString() }
210
- : { items, hasMore: true, nextCursor: `${next}@${started}` };
273
+ try {
274
+ return await readChanges(kind, cursor, page, context);
275
+ }
276
+ catch (error) {
277
+ if (optionalRefused(kind, error, context))
278
+ return { items: [], hasMore: false, cursor: null };
279
+ throw error;
280
+ }
211
281
  },
212
282
  async ids(kind, page, context) {
213
- const entity = entityOf(kind);
214
- const { rows, next } = await readPage(entity.ids ?? entity.list, {}, page, metered(context));
215
- const items = rows.flatMap((raw) => {
216
- const found = evaluate(entity.map.externalId, raw);
217
- const externalId = found === MISSING ? null : id(found);
218
- return externalId === null ? [] : [externalId];
219
- });
220
- return next === undefined ? { items, hasMore: false } : { items, hasMore: true, nextCursor: next };
283
+ try {
284
+ return await readIds(kind, page, context);
285
+ }
286
+ catch (error) {
287
+ // Refused part way through a pass, the ids read so far would mark every unread row deleted.
288
+ if (page === undefined && optionalRefused(kind, error, context))
289
+ return { items: [], hasMore: false };
290
+ throw error;
291
+ }
221
292
  },
222
293
  async get(kind, externalId, context) {
223
294
  const entity = entityOf(kind);
@@ -227,7 +298,7 @@ export const crmSourceFromManifest = (input, options) => {
227
298
  const defined = entity.custom ? await fieldsOf(kind, send, context) : [];
228
299
  let answer;
229
300
  try {
230
- answer = await send(entity.get.operation, inputOf(entity.get, { id: externalId, select: selectOf(kind, defined) }));
301
+ answer = await send(entity.get.operation, inputOf(entity.get, { id: externalId, select: selectOf(kind, defined, context) }));
231
302
  }
232
303
  catch (error) {
233
304
  if (unseen(error))