@wirecat/cli-core 0.691.0 → 0.693.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 (40) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/README.md +141 -203
  3. package/dist/calendar/prepare.d.ts +11 -0
  4. package/dist/cli/bot/api-http.d.ts +4 -1
  5. package/dist/cli/bot/api-http.js +17 -4
  6. package/dist/cli/bot/api-input.d.ts +4 -0
  7. package/dist/cli/bot/api-input.js +9 -0
  8. package/dist/cli/bot/api.d.ts +4 -0
  9. package/dist/cli/bot/api.js +16 -2
  10. package/dist/cli/documents/folders.js +1 -1
  11. package/dist/cli/documents/search.js +3 -3
  12. package/dist/cli/documents/words.d.ts +2 -0
  13. package/dist/cli/documents/words.js +1 -0
  14. package/dist/cli/envelope.d.ts +22 -0
  15. package/dist/cli/index.d.ts +7 -4
  16. package/dist/cli/index.js +7 -4
  17. package/dist/cli/oauth-session.d.ts +60 -0
  18. package/dist/cli/oauth-session.js +224 -0
  19. package/dist/cli/service-api-call.d.ts +27 -0
  20. package/dist/cli/service-api-call.js +32 -0
  21. package/dist/cli/service-api-manifest.d.ts +14 -10
  22. package/dist/cli/service-api-manifest.js +38 -34
  23. package/dist/cli/service-api.d.ts +17 -2
  24. package/dist/cli/service-api.js +42 -24
  25. package/dist/cli/token-session.d.ts +33 -0
  26. package/dist/cli/token-session.js +121 -0
  27. package/dist/crm/index.d.ts +3 -0
  28. package/dist/crm/index.js +3 -0
  29. package/dist/crm/manifest/manifest.d.ts +195 -0
  30. package/dist/crm/manifest/manifest.js +161 -0
  31. package/dist/crm/manifest/map.d.ts +58 -0
  32. package/dist/crm/manifest/map.js +240 -0
  33. package/dist/crm/manifest/paths.d.ts +11 -0
  34. package/dist/crm/manifest/paths.js +161 -0
  35. package/dist/crm/manifest/source.d.ts +18 -0
  36. package/dist/crm/manifest/source.js +385 -0
  37. package/dist/errors/reasons.js +1 -0
  38. package/dist/manifest/index.d.ts +53 -0
  39. package/dist/manifest/index.js +61 -0
  40. package/package.json +8 -3
@@ -1,4 +1,5 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
+ import { signInPlace, signInRequirements, } from "@wirecat/cli-base/codegen";
2
3
  import { apiJson, parseApiJson } from "./bot/api-input.js";
3
4
  /**
4
5
  * The first server the spec names. A variable is filled with its default only when its `enum` lists the choices: a
@@ -19,44 +20,47 @@ export const manifestBaseUrl = (manifest, given) => {
19
20
  throw new CliError("configuration_error", `the api's server ${url} is not https`);
20
21
  return url;
21
22
  };
22
- const BEARER = { name: "authorization", value: (token) => `Bearer ${token}` };
23
- /** The header one scheme signs in with; `undefined` for one the api cannot send (basic, a key in the query). */
24
- const headerOf = (scheme) => {
25
- if (scheme.type === "apiKey")
26
- return scheme.in === "header" && scheme.name
27
- ? { name: scheme.name.toLowerCase(), value: (token) => token }
28
- : undefined;
29
- if (scheme.type === "http") {
30
- if (!scheme.scheme || /^bearer$/i.test(scheme.scheme))
31
- return BEARER;
32
- return /^(basic|digest)$/i.test(scheme.scheme)
33
- ? undefined
34
- : { name: "authorization", value: (token) => `${scheme.scheme} ${token}` };
35
- }
36
- return scheme.type === "oauth2" || scheme.type === "openIdConnect" ? BEARER : undefined;
37
- };
38
23
  /**
39
- * The header that carries the sign-in for one operation, from the first scheme of its requirements the api can send;
40
- * `undefined` for one that needs none (`security: []`, or only `{}`). A manifest without schemes signs in with a bearer
41
- * token, as most services do. An optional sign-in (`[{}, { oauth: [] }]`) still sends the token.
24
+ * Where the sign-in goes for one operation: the first place its requirements' schemes name that a token can be sent
25
+ * to, a header before a key in the query, which a proxy or a server log could keep. `undefined` for a call that needs
26
+ * none: its security, its own or else the document's, is absent, as in a spec that says nothing about sign-in, or
27
+ * empty (`[]`, `[{}]`). An optional sign-in (`[{}, { oauth: [] }]`) still sends the token.
42
28
  */
43
- export const authHeader = (manifest, operation) => {
44
- const requirements = operation.security ?? manifest.security;
45
- if (requirements?.every((one) => Object.keys(one).length === 0))
29
+ const authOf = (manifest, operation) => {
30
+ const requirements = signInRequirements(operation, manifest.security);
31
+ if (!requirements)
46
32
  return undefined;
47
- if (!manifest.securitySchemes)
48
- return BEARER;
49
- const names = (requirements ?? []).flatMap((one) => Object.keys(one));
50
- for (const name of names) {
51
- const scheme = manifest.securitySchemes[name];
52
- const auth = scheme && headerOf(scheme);
53
- if (auth)
54
- return auth;
55
- }
56
- if (names.length === 0)
57
- return BEARER;
33
+ const names = requirements.flatMap((one) => Object.keys(one));
34
+ const sendable = names.flatMap((name) => {
35
+ const scheme = manifest.securitySchemes?.[name];
36
+ const place = scheme && signInPlace(scheme);
37
+ return place ? [place] : [];
38
+ });
39
+ const auth = sendable.find((one) => one.in === "header") ?? sendable[0];
40
+ if (auth)
41
+ return auth;
58
42
  throw new CliError("configuration_error", `${operation.command} signs in by ${names.join(" or ")}, which the api cannot send`);
59
43
  };
44
+ /**
45
+ * Signs one request for its operation. Set the final URL first: a key in the query goes into it. Anything but the
46
+ * standard sign-in header, or a key in the query, never follows a redirect, even to the same host: another host would
47
+ * get the key. The URL then holds the key, so a fetch wrapper must not log it. Without `token`, for a CLI that never
48
+ * signs in, nothing is added.
49
+ */
50
+ export const signRequest = async (manifest, operation, request, token) => {
51
+ if (!token)
52
+ return;
53
+ const auth = authOf(manifest, operation);
54
+ if (!auth)
55
+ return;
56
+ const value = auth.value(await token());
57
+ if (auth.in === "query")
58
+ request.url.searchParams.set(auth.name, value);
59
+ else
60
+ request.headers.set(auth.name, value);
61
+ if (auth.in === "query" || auth.name !== "authorization")
62
+ request.redirect = "manual";
63
+ };
60
64
  const at = (value, path) => path
61
65
  .split(".")
62
66
  .reduce((inner, key) => (inner && typeof inner === "object" ? inner[key] : undefined), value);
@@ -69,7 +73,7 @@ export const parameterValue = (input, parameter) => parameter.in === "query"
69
73
  : input.body === undefined
70
74
  ? undefined
71
75
  : parseApiJson(input.body)?.[parameter.name];
72
- const withValue = (input, parameter, value) => {
76
+ export const withValue = (input, parameter, value) => {
73
77
  if (parameter.in === "query")
74
78
  return { ...input, query: { ...input.query, [parameter.name]: String(value) } };
75
79
  const body = input.body === undefined ? {} : parseApiJson(input.body);
@@ -32,8 +32,11 @@ export interface ServiceApiOptions extends ServiceApiPermissionsInput {
32
32
  baseUrl?: string;
33
33
  /** The host-checked fetch with the CLI's pace and its retry of reads (cli-base `retrying` over `hostFetch`). */
34
34
  fetch: (command: Command) => FetchLike;
35
- /** The profile's token, sent in the header the operation's security scheme names. Read before any guard asks. */
36
- token: (command: Command) => string | Promise<string>;
35
+ /**
36
+ * The profile's token, sent where the operation's security scheme names. Read before any guard asks. Left out, for a
37
+ * CLI without sign-in, no call carries one.
38
+ */
39
+ token?: (command: Command) => string | Promise<string>;
37
40
  /** Headers beside the sign-in, such as the API version. */
38
41
  headers?: (command: Command, operation: ManifestOperation) => Record<string, string>;
39
42
  /** Loaded only once an operation is about to check its input: a large spec is megabytes of code. */
@@ -49,6 +52,18 @@ export interface ServiceApiOptions extends ServiceApiPermissionsInput {
49
52
  shown?: Readonly<Record<string, unknown>>;
50
53
  failure?: (status: number, answer: unknown, operation: ManifestOperation) => CliError | undefined;
51
54
  }
55
+ /**
56
+ * The operations the `api` group offers, and why it leaves out the rest: one that answers with a credential needs a
57
+ * bot's `--store-token`, as a service CLI signs in through `session`; a body other than JSON or an upload's bytes (a
58
+ * multipart form) the generated command cannot send.
59
+ */
60
+ export declare const serviceApiOperations: (manifest: ServiceApiManifest) => {
61
+ offered: readonly ManifestOperation[];
62
+ left: readonly {
63
+ id: string;
64
+ reason: string;
65
+ }[];
66
+ };
52
67
  /** The keys one call checks beside `api.<operation>`: the manifest's that apply, and the CLI's from the body. */
53
68
  export declare const serviceApiKeys: (input: ServiceApiPermissionsInput, operation: ManifestOperation, call: ApiCommandInput) => PermissionKey[];
54
69
  /**
@@ -8,14 +8,29 @@ import { levelFor } from "../sends/permissions.js";
8
8
  import { newOperationId } from "../sends/send-id.js";
9
9
  import { refusedPlace } from "../sends/upload.js";
10
10
  import { generatedApiCommand } from "./bot/api.js";
11
- import { httpApiRequest, httpApiSend } from "./bot/api-http.js";
12
- import { checkApiBody, checkApiParameter, parseApiJson, readApiBody } from "./bot/api-input.js";
11
+ import { httpApiRequest, httpApiSend, unsendableBody } from "./bot/api-http.js";
12
+ import { checkApiBody, checkApiParameter, parseApiJson, readApiBody, readApiBytes } from "./bot/api-input.js";
13
13
  import { baseContext, outputFor } from "./context.js";
14
14
  import { NO_EFFECTS } from "./effects.js";
15
15
  import { itemOf, listOf, renderAnswer } from "./envelope.js";
16
16
  import { queryTerms, termField, withQuery } from "./list-query.js";
17
17
  import { terminalAsker } from "./messenger/ask.js";
18
- import { authHeader, manifestBaseUrl, nextPage, parameterValue, } from "./service-api-manifest.js";
18
+ import { manifestBaseUrl, nextPage, parameterValue, signRequest, } from "./service-api-manifest.js";
19
+ /**
20
+ * The operations the `api` group offers, and why it leaves out the rest: one that answers with a credential needs a
21
+ * bot's `--store-token`, as a service CLI signs in through `session`; a body other than JSON or an upload's bytes (a
22
+ * multipart form) the generated command cannot send.
23
+ */
24
+ export const serviceApiOperations = (manifest) => {
25
+ const reasonOf = (operation) => operation.response?.sensitive ? "it returns a credential, which is never printed" : unsendableBody(operation);
26
+ return {
27
+ offered: manifest.operations.filter((operation) => reasonOf(operation) === undefined),
28
+ left: manifest.operations.flatMap((operation) => {
29
+ const reason = reasonOf(operation);
30
+ return reason ? [{ id: operation.id, reason }] : [];
31
+ }),
32
+ };
33
+ };
19
34
  /** How far `--all` reads: a service that never stops paging must not run a command forever. */
20
35
  const MOST_PAGES = 500;
21
36
  const isObject = (value) => !!value && typeof value === "object" && !Array.isArray(value);
@@ -90,8 +105,7 @@ const API_QUERY = {
90
105
  */
91
106
  export const serviceApiCommand = (options) => {
92
107
  const { app, configuration, manifest } = options;
93
- // A credential-returning operation needs a bot's `--store-token`; a service CLI signs in through `session` instead.
94
- const operations = manifest.operations.filter((operation) => !operation.response?.sensitive);
108
+ const { offered: operations, left } = serviceApiOperations(manifest);
95
109
  const baseUrl = manifestBaseUrl(manifest, options.baseUrl);
96
110
  const base = new URL(baseUrl);
97
111
  const own = serviceApiPermissions(options);
@@ -121,21 +135,15 @@ export const serviceApiCommand = (options) => {
121
135
  const found = operations.find((operation) => operation.command === name || operation.id === name);
122
136
  if (found)
123
137
  return found;
124
- const left = options.excluded?.find((one) => one.id === name) ??
125
- (manifest.operations.some((one) => one.command === name || one.id === name)
126
- ? { reason: "it returns a credential, which is never printed" }
127
- : undefined);
128
- throw new CliError("not_found", left
129
- ? `${name} is not offered: ${left.reason}`
138
+ const id = manifest.operations.find((one) => one.command === name || one.id === name)?.id ?? name;
139
+ const why = options.excluded?.find((one) => one.id === name) ?? left.find((one) => one.id === id);
140
+ throw new CliError("not_found", why
141
+ ? `${name} is not offered: ${why.reason}`
130
142
  : `no ${options.service} API operation ${name}; see ${app.command} api list`);
131
143
  };
132
144
  const signed = async (command, operation, request) => {
133
- const auth = authHeader(manifest, operation);
134
- if (auth)
135
- request.headers.set(auth.name, auth.value(await options.token(command)));
136
- // A redirect to another host drops only the standard sign-in headers; an API key header would go along.
137
- if (auth && auth.name !== "authorization")
138
- request.redirect = "manual";
145
+ const { token } = options;
146
+ await signRequest(manifest, operation, request, token && (() => token(command)));
139
147
  for (const [name, value] of Object.entries(options.headers?.(command, operation) ?? {}))
140
148
  request.headers.set(name, value);
141
149
  return request;
@@ -170,9 +178,11 @@ export const serviceApiCommand = (options) => {
170
178
  for (let page = 0;; page++) {
171
179
  if (page >= MOST_PAGES)
172
180
  throw new CliError("validation_error", `${operation.command} has more than ${MOST_PAGES} pages; narrow it with its own flags, or page it yourself`);
173
- const request = await signed(command, operation, httpApiRequest(operation, call, baseUrl));
181
+ const unsigned = httpApiRequest(operation, call, baseUrl);
182
+ // A next link replaces the URL, so the request is signed after: a key in the query goes into the link.
174
183
  if (url !== undefined)
175
- request.url = url;
184
+ unsigned.url = new URL(url);
185
+ const request = await signed(command, operation, unsigned);
176
186
  const key = `${request.url.href} ${request.body ?? ""}`;
177
187
  if (asked.has(key))
178
188
  throw new CliError("invalid_response", `${options.service} gave the same next page twice; nothing more read`);
@@ -193,18 +203,26 @@ export const serviceApiCommand = (options) => {
193
203
  });
194
204
  renderAnswer(command, outputFor(command), listOf(`api ${operation.command}`, { items, limit: items.length, has_more: false }));
195
205
  };
206
+ const refuseOwnFiles = (command, path) => {
207
+ if (path === "-")
208
+ return;
209
+ const { env } = baseContext(command, configuration.resolveSettings);
210
+ if (refusedPlace(path, app, env))
211
+ throw new CliError("validation_error", `--body-file may not read ${path}: it holds sign-ins or state`);
212
+ };
196
213
  const generated = generatedApiCommand({
197
214
  operations,
198
215
  checkParameter: (name, schema, raw) => checkApiParameter(name, schema, raw, loaded()),
199
216
  checkBody: (operation, text) => checkApiBody(operation, text, loaded()),
200
217
  readBody: (command, body) => {
201
- if (body.bodyFile !== undefined && body.bodyFile !== "-") {
202
- const { env } = baseContext(command, configuration.resolveSettings);
203
- if (refusedPlace(body.bodyFile, app, env))
204
- throw new CliError("validation_error", `--body-file may not read ${body.bodyFile}: it holds sign-ins or state`);
205
- }
218
+ if (body.bodyFile !== undefined)
219
+ refuseOwnFiles(command, body.bodyFile);
206
220
  return readApiBody(body);
207
221
  },
222
+ readBytes: (command, path) => {
223
+ refuseOwnFiles(command, path);
224
+ return readApiBytes(path);
225
+ },
208
226
  execute: async (command, operation, input) => {
209
227
  const extra = serviceApiKeys(options, operation, input);
210
228
  if (operation.pagination && command.opts().all === true) {
@@ -0,0 +1,33 @@
1
+ import { Command } from "commander";
2
+ import type { AppIdentity } from "../ports/app.js";
3
+ import type { EventSink } from "../runs/events.js";
4
+ import { ProfileTokenStore, type TokenStorage } from "./profile-token.js";
5
+ import type { GlobalFlags, ResolveOptions, Settings } from "./settings.js";
6
+ export interface TokenSessionOptions {
7
+ app: AppIdentity;
8
+ /** The service's name, as the owner knows it: "Notion". */
9
+ service: string;
10
+ resolveSettings: (flags: GlobalFlags, options?: ResolveOptions) => Settings;
11
+ /**
12
+ * Asks the service whose the token is. `id` names the account, so one profile stays one account; `account` is what
13
+ * `session start` and `session status --check` show.
14
+ */
15
+ verify: (command: Command, token: string, events: EventSink) => Promise<{
16
+ id: string;
17
+ account: Readonly<Record<string, unknown>>;
18
+ }>;
19
+ /** Keeps the account a profile signed in to; by default only remembers it. A CLI that refuses a taken one says so. */
20
+ claim?: (env: NodeJS.ProcessEnv, profile: string, id: string, tokens: ProfileTokenStore) => void;
21
+ /** What the token is, for the prompt and help: "API token" when not given. */
22
+ token?: string;
23
+ /** One sentence more for `session start --help`: which token, and what it can see. */
24
+ about?: string;
25
+ /** One sentence more for `session end --help`, such as what of the service's own tools it leaves alone. */
26
+ endNote?: string;
27
+ }
28
+ export declare const storageOf: (raw: string) => TokenStorage;
29
+ /**
30
+ * `session start | status | end | list` for a service signed in with one token (WC-ACCT-12): the token is asked hidden
31
+ * or read from stdin, checked with the service, and only then kept in the keyring or a private file.
32
+ */
33
+ export declare const tokenSessionCommand: (options: TokenSessionOptions) => Command;
@@ -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,6 +1,9 @@
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";
5
+ export { crmManifestProblems } from "./manifest/paths.js";
6
+ export { type CrmManifestSourceOptions, crmSourceFromManifest } from "./manifest/source.js";
4
7
  export { type ProviderCallOptions, providerCall } from "./provider-call.js";
5
8
  export { type CrmConditionHooks, type CrmQueryField, conditionsOf, customConditions, customNames, filterableFields, selectedCodes, wantedCodes, withCustomFields, } from "./query.js";
6
9
  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
@@ -1,6 +1,9 @@
1
1
  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
+ export { parseCrmManifest, } from "./manifest/manifest.js";
5
+ export { crmManifestProblems } from "./manifest/paths.js";
6
+ export { crmSourceFromManifest } from "./manifest/source.js";
4
7
  export { providerCall } from "./provider-call.js";
5
8
  export { conditionsOf, customConditions, customNames, filterableFields, selectedCodes, wantedCodes, withCustomFields, } from "./query.js";
6
9
  export { CRM_FILE_SOURCES, } from "./source.js";
@@ -0,0 +1,195 @@
1
+ import type { ServiceApiCall } from "../../cli/service-api-call.js";
2
+ import type { ServiceApiManifest } from "../../cli/service-api-manifest.js";
3
+ import { type CrmKind, type CrmRecords } from "../../domain/crm.js";
4
+ import { type DealKind, type StageOutcome } from "../../domain/deals.js";
5
+ import type { CrmSource } from "../source.js";
6
+ import type { CrmRaw } from "../values.js";
7
+ /**
8
+ * Where one of our fields comes from in a row the service answered. A path is dotted (`properties.firstname`); the
9
+ * 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`).
10
+ */
11
+ export type CrmRule = string | {
12
+ first: readonly string[];
13
+ } | {
14
+ join: readonly string[];
15
+ } | {
16
+ all: readonly string[];
17
+ split?: string;
18
+ } | {
19
+ path: string;
20
+ split?: string;
21
+ } | {
22
+ path: string;
23
+ map: Readonly<Record<string, unknown>>;
24
+ } | {
25
+ each: string;
26
+ id: string;
27
+ primary?: string;
28
+ } | {
29
+ each: string;
30
+ value: string;
31
+ } | {
32
+ value: unknown;
33
+ } | ((raw: CrmRaw) => unknown);
34
+ /**
35
+ * One request to the service: an operation of the generated API manifest by its id, with fixed parameters. A string
36
+ * value `"{since}"`, `"{select}"` or `"{id}"` anywhere in `path`, `query` or `body` is filled in by the engine; an empty
37
+ * `"{select}"` leaves the parameter out.
38
+ */
39
+ export interface CrmOperationCall {
40
+ operation: string;
41
+ path?: Readonly<Record<string, string>>;
42
+ query?: Readonly<Record<string, string | number | boolean>>;
43
+ body?: unknown;
44
+ /** Where the answer's rows are when the operation has no `pagination`; absent, the answer itself is the list. */
45
+ items?: string;
46
+ }
47
+ export interface CrmChangesCall extends CrmOperationCall {
48
+ /** How `{since}` is written: epoch ms or seconds as digits, ISO, or `YYYY-MM-DD HH:MM:SS` in UTC. */
49
+ since: "ms" | "seconds" | "iso" | "datetime";
50
+ /**
51
+ * The answer is sorted by `field`, a time, ascending: pages go on from the last row's time, so a row that changes
52
+ * mid-round moves nothing under the next page. Past `cap` rows at one time the round answers `reset`.
53
+ */
54
+ keyset?: {
55
+ field: string;
56
+ cap?: number;
57
+ };
58
+ }
59
+ export interface CrmManifestEntity<K extends CrmKind = CrmKind> {
60
+ /** Every row of the kind, page by page by the operation's own `pagination`. */
61
+ list: CrmOperationCall;
62
+ /** Rows changed since `{since}`, the last cursor less the overlap; absent, every sync lists in full. */
63
+ changes?: CrmChangesCall;
64
+ /** Every id, to find deletions; absent, `list` with an empty `{select}`. */
65
+ ids?: CrmOperationCall;
66
+ /** One row by `{id}`, for a live read of a contact or company; a 403 or 404 is no row. */
67
+ get?: CrmOperationCall;
68
+ /**
69
+ * The service names the fields a read returns (HubSpot `properties=`, Bitrix24 `select`): `{select}` becomes the
70
+ * names under `from` that `map` reads, the custom field codes, and `also`.
71
+ */
72
+ select?: {
73
+ from: string;
74
+ also?: readonly string[];
75
+ /** The longest `{select}` the service takes, in characters joined by commas; the rest is a gap. */
76
+ max?: number;
77
+ };
78
+ map: {
79
+ readonly [F in keyof CrmRecords[K]]?: CrmRule;
80
+ } & {
81
+ amount?: CrmRule;
82
+ currency?: CrmRule;
83
+ };
84
+ /** The account's own fields' values, by the codes `fields` lists, under this object of the row. */
85
+ custom?: {
86
+ from: string;
87
+ split?: string;
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
+ };
97
+ }
98
+ export interface CrmManifestPipelines {
99
+ call: CrmOperationCall;
100
+ map: {
101
+ externalId: CrmRule;
102
+ name: CrmRule;
103
+ };
104
+ stages: {
105
+ each: string;
106
+ map: {
107
+ externalId: CrmRule;
108
+ name: CrmRule;
109
+ position?: CrmRule;
110
+ };
111
+ /** Which stages are won or lost by one field; any other is open. A rule a field cannot say is a function. */
112
+ outcome: {
113
+ path: string;
114
+ won?: readonly string[];
115
+ lost?: readonly string[];
116
+ } | {
117
+ value: StageOutcome;
118
+ } | ((stage: CrmRaw, pipeline: CrmRaw) => StageOutcome);
119
+ };
120
+ }
121
+ export interface CrmManifestFields {
122
+ call: CrmOperationCall;
123
+ map: {
124
+ code: CrmRule;
125
+ label?: CrmRule;
126
+ type?: CrmRule;
127
+ multiple?: CrmRule;
128
+ filterable?: CrmRule;
129
+ options?: {
130
+ each: string;
131
+ id: string;
132
+ label: string;
133
+ } | ((raw: CrmRaw) => {
134
+ id: string;
135
+ label: string;
136
+ }[] | undefined);
137
+ };
138
+ /** Which listed fields are the account's own, not the service's built-in ones the map already reads. */
139
+ keep?: (raw: CrmRaw) => boolean;
140
+ }
141
+ /** A CRM account described as data: what to call for each kind and where each of our fields is in the answer. */
142
+ export interface CrmManifest {
143
+ /** The registry name: `hubspot`, `pipedrive`. */
144
+ provider: string;
145
+ /** Contacts and companies before the items on them. */
146
+ kinds: readonly CrmKind[];
147
+ /** Re-read before the last cursor: rows saved while the round ran, and a clock running ahead. Default 10 min. */
148
+ overlapMs?: number;
149
+ entities: {
150
+ readonly [K in CrmKind]?: CrmManifestEntity<K>;
151
+ };
152
+ pipelines?: {
153
+ readonly [K in DealKind]?: CrmManifestPipelines;
154
+ };
155
+ fields?: {
156
+ readonly [K in CrmKind]?: CrmManifestFields;
157
+ };
158
+ users?: {
159
+ call: CrmOperationCall;
160
+ map: {
161
+ externalId: CrmRule;
162
+ name?: CrmRule;
163
+ email?: CrmRule;
164
+ position?: CrmRule;
165
+ active?: CrmRule;
166
+ };
167
+ };
168
+ }
169
+ /** Corrects one record after the map; `call` reads more from the service, spent from the run's budget. */
170
+ export type CrmAfterHook<K extends CrmKind> = (record: CrmRecords[K], raw: CrmRaw, service: {
171
+ call: ServiceApiCall;
172
+ }) => CrmRecords[K] | Promise<CrmRecords[K]>;
173
+ /** Code a service needs beyond what the manifest says. */
174
+ export interface CrmManifestHooks {
175
+ /** Corrects one record after the map, such as a default the account keeps elsewhere. */
176
+ after?: {
177
+ readonly [K in CrmKind]?: CrmAfterHook<K>;
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
+ };
188
+ /** Adds or replaces source methods (`self`, `activities`, a live `list`); `base` is what the manifest built. */
189
+ extend?: (base: CrmSource) => Partial<CrmSource>;
190
+ }
191
+ /**
192
+ * The manifest checked against its shape and the generated API: each operation exists, a list pages or says where its
193
+ * rows are, a change call places `{since}`, a deal or lead kind has pipelines. Every error names where it is.
194
+ */
195
+ export declare const parseCrmManifest: (input: unknown, api: ServiceApiManifest) => CrmManifest;