@wirecat/cli-core 0.698.0 → 0.700.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 CHANGED
@@ -5,6 +5,54 @@ 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.700.0 — 18.11.2026
9
+
10
+ ### Added
11
+
12
+ - **`htmlToMarkdown` and `markdownToHtml` in `@wirecat/cli-core/documents`**, for the content category: a blog keeps
13
+ HTML (WordPress, Ghost), and a CLI shows and takes Markdown. WordPress block comments and Ghost card comments go,
14
+ and so do scripts, styles, frames, event attributes, raw HTML from Markdown, and links and images whose scheme is
15
+ not http(s), mailto or tel: a post body is untrusted. Tested on one post as WordPress 6.9 stores and renders it and
16
+ as Ghost 6.78 renders it; Markdown that went through HTML once comes back the same. The converters are unified's
17
+ `hast-util-from-html`, `hast-util-to-mdast`, `mdast-util-to-hast` and `hast-util-to-html`, loaded on first use.
18
+ - **A CRM source from a manifest reads a pipeline answered as a flat list of stages** (`stages.each: "."`, grouped by
19
+ `stages.pipeline` or one pipeline), and a hook `pipelines.<kind>.outcome` decides a stage's outcome the data cannot
20
+ say. Attio's deal stages and Pipedrive's `/stages` answer this way.
21
+ - **`custom.typed` reads the account's own fields from typed entries with their history**, as Attio keeps them: the
22
+ current entry's value by its type (`TYPED_VALUE_PATHS`, overridable), a multiple field or several current entries as a list.
23
+ `fields.keep` takes `{ path, is }`, so a config file can say which fields are the account's own.
24
+ - **`entities.person.search` and `entities.organization.search` give a manifest source a live `list`**, for `people
25
+ list` and `organizations list`: words through the search call's `"{query}"`, none through `list`. A condition it
26
+ cannot send is refused, not dropped; a live list pages by offset, so a cursor-paged search is refused.
27
+ - `hooks.extend` gets the service's `call` as its second argument.
28
+ - **The `api` group checks a key by a field's value, as WordPress publishes by `status: "publish"`.** A manifest
29
+ permission with `values` (cli-base's `permissions.valueKeys`) applies when the call's JSON body or its query holds
30
+ one of those values: `{ key: "posts.publish", values: { status: ["publish", "future"] } }` asks for
31
+ `posts.publish` before `api post-wp-v2-posts --body '{"status":"publish"}'` and lets a draft through. Both places
32
+ count, because WordPress reads the same parameter from either. So a profile that denies publishing also stops an
33
+ agent that publishes through the raw `api` group. `--dry-run` and discovery show the key with
34
+ `with status publish or future`.
35
+
36
+ ### Changed — may break callers
37
+
38
+ - **cli-core needs `@wirecat/cli-base` 0.118.0**, which carries the manifest's `values` and WordPress's
39
+ `wpJsonToOpenApi`. A CLI that pins an older cli-base raises it with this cli-core.
40
+
41
+ ### Fixed
42
+
43
+ - `crmManifestFake` matches a call whatever page size and offset the source asked for, a live list setting its own, and writes a stage's won or lost flag as a boolean or a word, as its schema takes it.
44
+
45
+ ## 0.699.0 — 18.11.2026
46
+
47
+ ### Added
48
+
49
+ - **`manifestVerify` and `hostsFetch` in `@wirecat/cli-core/cli`**, so a CLI made from `wirecat.config.ts` keeps no
50
+ token check of its own. `manifestVerify` is `tokenSessionCommand`'s `verify` from the config's `auth.verify`: it sends
51
+ the one operation, refuses a token the answer does not call `active` (Attio answers a revoked key with 200), names a
52
+ missing id as the service's error, and keeps the id and the name when it is text. `hostsFetch(hosts, fetch)` reaches
53
+ only the CLI's hosts, over a test's fake when one is given.
54
+ - **`ProfileTokenStore` takes `keyring: undefined`**, so a CLI passes `baseContext`'s keyring as it is.
55
+
8
56
  ## 0.698.0 — 18.11.2026
9
57
 
10
58
  ### Added
@@ -58,8 +58,8 @@ export interface CopyAge {
58
58
  }
59
59
  export declare const ageOf: (lastSync: string | undefined, now?: number) => CopyAge;
60
60
  export declare const staleCopy: (provider: string, lastSync: string | undefined, now?: number) => {
61
- missing?: undefined;
62
61
  next?: undefined;
62
+ missing?: undefined;
63
63
  meta?: undefined;
64
64
  } | {
65
65
  missing: {
@@ -154,7 +154,7 @@ export { HARNESSES, type Harness, harnessesOn, harnessInfo, harnessOfArgv, isHar
154
154
  export { type AgentScheduleSpec, agentSchedule, backfillScheduleRun, pauseSchedule, removeSchedule, runScheduleNow, SCHEDULE_SETTINGS, type ScheduleHost, type ScheduleLimits, type ScheduleSite, scheduleLimitsOf, scheduleState, slotsOfAt, writeSchedule, } from "./schedule/schedule-command.js";
155
155
  export { deniedKinds, deniedKindsOf, type LeftOut, type SearchedKind } from "./search-left-out.js";
156
156
  export { type BodyPermission, type ServiceApiOptions, type ServiceApiPermissionsInput, serviceApiKeys, serviceApiOperations, serviceApiPermissions, } from "./service-api.js";
157
- export { type ServiceApiCall, type ServiceApiCallOptions, serviceApiCall } from "./service-api-call.js";
157
+ export { hostsFetch, type ServiceApiCall, type ServiceApiCallOptions, serviceApiCall } from "./service-api-call.js";
158
158
  export { manifestBaseUrl, type ServiceApiManifest, signRequest, siteValue } from "./service-api-manifest.js";
159
159
  export { type DeclaredSetting, type SettingRow, settingRows, withSettingDefaults } from "./setting-defaults.js";
160
160
  export { type Config, type Configuration, count, first, flag, fromFile, type GlobalFlags, NONE_NAMED, namedProfile, type ProfileKind, plain, type ResolveOptions, type Settings, type SettingsExtension, type SettingsExtensionContext, type Source, settingsFor, } from "./settings.js";
@@ -167,5 +167,5 @@ export { type StoreInfo, sharedStoreCommand, storeInfo, storeInfoCommand } from
167
167
  export { type RecoveryCheck, type RecoveryRun, recoveryNotes, storeRecoverCommand, storeRecoveryCheck, storeRecoveryRun, } from "./store-recover.js";
168
168
  export { changeStoreSetting, isStoreSetting, STORE_SETTINGS, storeSettings } from "./store-settings.js";
169
169
  export type { TemplatesOptions } from "./templates-command.js";
170
- export { signedInSite, type TokenSessionOptions, tokenSessionCommand } from "./token-session.js";
170
+ export { type ManifestVerifyOptions, manifestVerify, signedInSite, type TokenSessionOptions, tokenSessionCommand, } from "./token-session.js";
171
171
  export { restartServers, type UpgradeContext } from "./upgrade-command.js";
package/dist/cli/index.js CHANGED
@@ -143,7 +143,7 @@ export { HARNESSES, harnessesOn, harnessInfo, harnessOfArgv, isHarness, reportsC
143
143
  export { agentSchedule, backfillScheduleRun, pauseSchedule, removeSchedule, runScheduleNow, SCHEDULE_SETTINGS, scheduleLimitsOf, scheduleState, slotsOfAt, writeSchedule, } from "./schedule/schedule-command.js";
144
144
  export { deniedKinds, deniedKindsOf } from "./search-left-out.js";
145
145
  export { serviceApiKeys, serviceApiOperations, serviceApiPermissions, } from "./service-api.js";
146
- export { serviceApiCall } from "./service-api-call.js";
146
+ export { hostsFetch, serviceApiCall } from "./service-api-call.js";
147
147
  export { manifestBaseUrl, signRequest, siteValue } from "./service-api-manifest.js";
148
148
  export { settingRows, withSettingDefaults } from "./setting-defaults.js";
149
149
  export { count, first, flag, fromFile, NONE_NAMED, namedProfile, plain, settingsFor, } from "./settings.js";
@@ -155,5 +155,5 @@ export { runnable, withSafety } from "./steps.js";
155
155
  export { sharedStoreCommand, storeInfo, storeInfoCommand } from "./store-info.js";
156
156
  export { recoveryNotes, storeRecoverCommand, storeRecoveryCheck, storeRecoveryRun, } from "./store-recover.js";
157
157
  export { changeStoreSetting, isStoreSetting, STORE_SETTINGS, storeSettings } from "./store-settings.js";
158
- export { signedInSite, tokenSessionCommand } from "./token-session.js";
158
+ export { manifestVerify, signedInSite, tokenSessionCommand, } from "./token-session.js";
159
159
  export { restartServers } from "./upgrade-command.js";
@@ -4,7 +4,7 @@ export type TokenStorage = "keyring" | "file";
4
4
  export interface ProfileTokenStoreOptions {
5
5
  app: AppIdentity;
6
6
  env?: NodeJS.ProcessEnv;
7
- keyring?: KeyringStore;
7
+ keyring?: KeyringStore | undefined;
8
8
  /** Where the one warning about an unreachable keyring goes; stderr when left out. */
9
9
  warn?: (message: string) => void;
10
10
  }
@@ -1,5 +1,5 @@
1
1
  import type { ManifestOperation } from "@wirecat/cli-base/codegen";
2
- import type { FetchLike } from "@wirecat/cli-base/http";
2
+ import { type FetchLike } from "@wirecat/cli-base/http";
3
3
  import type { ApiCommandInput } from "./bot/api.js";
4
4
  import { type HttpApiSendOptions } from "./bot/api-http.js";
5
5
  import { type ServiceApiManifest } from "./service-api-manifest.js";
@@ -21,6 +21,11 @@ export interface ServiceApiCallOptions {
21
21
  headers?: (operation: ManifestOperation) => Record<string, string>;
22
22
  failure?: HttpApiSendOptions["failure"];
23
23
  }
24
+ /**
25
+ * A fetch that reaches only `hosts` (WC-CMD-32), over the fetch a test gives in its environment, or the network when
26
+ * none: a CLI passes `environment.fetch` as it is.
27
+ */
28
+ export declare const hostsFetch: (hosts: readonly string[], fetch: FetchLike | undefined) => FetchLike;
24
29
  /**
25
30
  * The `api` group's request path for code that is not a command, such as a source read from a manifest: the same
26
31
  * request building, sign-in header, redirect rule, run record and refusals as `serviceApiCommand`, without a guard. It
@@ -1,7 +1,13 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
+ import { hostFetch } from "@wirecat/cli-base/http";
2
3
  import { Command } from "commander";
3
4
  import { httpApiRequest, httpApiSend } from "./bot/api-http.js";
4
5
  import { manifestBaseUrl, signRequest } from "./service-api-manifest.js";
6
+ /**
7
+ * A fetch that reaches only `hosts` (WC-CMD-32), over the fetch a test gives in its environment, or the network when
8
+ * none: a CLI passes `environment.fetch` as it is.
9
+ */
10
+ export const hostsFetch = (hosts, fetch) => hostFetch({ hosts, ...(fetch ? { fetch } : {}) });
5
11
  // The run record and the fetch are the only things httpApiSend asks a command for, and a sync has no command of its own.
6
12
  const NO_COMMAND = new Command("source");
7
13
  /**
@@ -39,12 +39,24 @@ const permissionsOf = (operation) => operation.permissions ?? [];
39
39
  /** By its method too: an override may have marked a DELETE as a plain write. */
40
40
  const destructive = (operation) => operation.effect === "destructive" || (operation.binding.kind === "http" && operation.binding.method === "DELETE");
41
41
  const flagsOf = ({ body = [], query = [] }) => [...body, ...query];
42
+ const valuesOf = ({ values = {} }) => Object.entries(values);
43
+ /** Always, unless its flags or values name when; `with status publish or future`, `with archived set`. */
44
+ const whenOf = (permission) => {
45
+ const flags = flagsOf(permission);
46
+ const values = valuesOf(permission).map(([field, listed]) => `${field} ${listed.join(" or ")}`);
47
+ if (flags.length === 0 && values.length === 0)
48
+ return undefined;
49
+ return `with ${[...(flags.length > 0 ? [`${flags.join(" or ")} set`] : []), ...values].join(" or ")}`;
50
+ };
51
+ /** A body field or query parameter holding one of the values: WordPress publishes from either. */
52
+ const holds = (value, listed) => typeof value === "string" && listed.includes(value);
42
53
  /** A flag counts unless it is absent or plainly false: a service may read `1` or `True` as true. */
43
54
  const set = (value) => value !== undefined && value !== null && value !== false && value !== "false";
44
- /** Whether a manifest key applies to this call: always, or when one of its flags is set. */
45
- const applies = (permission, body, input) => flagsOf(permission).length === 0 ||
55
+ /** Whether a manifest key applies to this call: always, or when one of its flags is set or a field holds a value. */
56
+ const applies = (permission, body, input) => whenOf(permission) === undefined ||
46
57
  (permission.body ?? []).some((field) => isObject(body) && set(body[field])) ||
47
- (permission.query ?? []).some((name) => set(input.query[name]));
58
+ (permission.query ?? []).some((name) => set(input.query[name])) ||
59
+ valuesOf(permission).some(([field, listed]) => (isObject(body) && holds(body[field], listed)) || holds(input.query[field], listed));
48
60
  /** The keys one call checks beside `api.<operation>`: the manifest's that apply, and the CLI's from the body. */
49
61
  export const serviceApiKeys = (input, operation, call) => {
50
62
  const body = call.body?.trim() ? parseApiJson(call.body) : undefined;
@@ -66,9 +78,10 @@ export const serviceApiPermissions = (input) => {
66
78
  const checks = new Map();
67
79
  for (const operation of input.manifest.operations)
68
80
  checks.set(operation.command, [
69
- ...permissionsOf(operation).map((permission) => flagsOf(permission).length === 0
70
- ? permission.key
71
- : { key: permission.key, when: `with ${flagsOf(permission).join(" or ")} set` }),
81
+ ...permissionsOf(operation).map((permission) => {
82
+ const when = whenOf(permission);
83
+ return when === undefined ? permission.key : { key: permission.key, when };
84
+ }),
72
85
  ...(input.bodyPermissions?.[operation.command] ?? []).map(({ key, when }) => ({ key, when })),
73
86
  ]);
74
87
  const keys = [...new Set([...checks.values()].flat().map((one) => (typeof one === "string" ? one : one.key)))];
@@ -1,7 +1,10 @@
1
+ import type { FetchLike } from "@wirecat/cli-base/http";
1
2
  import { Command } from "commander";
3
+ import type { CliVerify } from "../manifest/index.js";
2
4
  import type { AppIdentity } from "../ports/app.js";
3
5
  import type { EventSink } from "../runs/events.js";
4
6
  import { ProfileTokenStore, type TokenStorage } from "./profile-token.js";
7
+ import { type ServiceApiManifest } from "./service-api-manifest.js";
5
8
  import type { GlobalFlags, ResolveOptions, Settings } from "./settings.js";
6
9
  export interface TokenSessionOptions {
7
10
  app: AppIdentity;
@@ -43,6 +46,20 @@ export interface TokenSessionOptions {
43
46
  /** One sentence more for `session end --help`, such as what of the service's own tools it leaves alone. */
44
47
  endNote?: string;
45
48
  }
49
+ export interface ManifestVerifyOptions {
50
+ manifest: ServiceApiManifest;
51
+ /** The service's name in messages: "Attio". */
52
+ service: string;
53
+ /** The config's `auth.verify`: the operation, where its answer holds the id and a name, and whether it is live. */
54
+ verify: CliVerify;
55
+ /** The command's host-checked fetch, such as `hostsFetch(hosts, environment.fetch)`. */
56
+ fetch: (command: Command) => FetchLike;
57
+ }
58
+ /**
59
+ * `verify` for `tokenSessionCommand` from a config's `auth.verify`: the one operation is sent with the token, a token the
60
+ * answer does not call active is refused, and the account is the id and name the answer holds.
61
+ */
62
+ export declare const manifestVerify: ({ manifest, service, verify, fetch }: ManifestVerifyOptions) => TokenSessionOptions["verify"];
46
63
  export declare const storageOf: (raw: string) => TokenStorage;
47
64
  /**
48
65
  * `session start | status | end | list` for a service signed in with one token (WC-ACCT-12): the token is asked hidden
@@ -1,6 +1,7 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { annotate } from "@wirecat/cli-base/commands";
3
3
  import { Command } from "commander";
4
+ import { at as valueAt } from "../crm/manifest/map.js";
4
5
  import { readSecret } from "../terminal/prompt.js";
5
6
  import { baseContext, environmentOf, outputFor, secretInputOf } from "./context.js";
6
7
  import { refuseOffline } from "./early-refusal.js";
@@ -9,7 +10,26 @@ import { itemOf, listOf, renderAnswer } from "./envelope.js";
9
10
  import { profilesHere, rememberAccount } from "./messenger/accounts.js";
10
11
  import { commandWords, profileFree, refuseCommandName, rootOf } from "./profile.js";
11
12
  import { ProfileTokenStore } from "./profile-token.js";
13
+ import { serviceApiCall } from "./service-api-call.js";
12
14
  import { siteValue } from "./service-api-manifest.js";
15
+ /**
16
+ * `verify` for `tokenSessionCommand` from a config's `auth.verify`: the one operation is sent with the token, a token the
17
+ * answer does not call active is refused, and the account is the id and name the answer holds.
18
+ */
19
+ export const manifestVerify = ({ manifest, service, verify, fetch }) => async (command, token) => {
20
+ const call = serviceApiCall({ manifest, service, fetch: fetch(command), token: () => token });
21
+ const answer = await call(verify.operation, { path: {}, query: {}, headers: {}, fields: {} });
22
+ // A service such as Attio answers a revoked key with 200 and `active: false`, not with 401.
23
+ if (verify.active !== undefined && valueAt(answer, verify.active) !== true)
24
+ throw new CliError("authentication_error", `${service} does not accept this token; sign in again`);
25
+ const id = valueAt(answer, verify.id);
26
+ if (typeof id !== "string" && typeof id !== "number")
27
+ throw new CliError("provider_error", `${service} answered ${verify.operation} without ${verify.id}`, {
28
+ reason: "verify.no-id",
29
+ });
30
+ const name = verify.name === undefined ? undefined : valueAt(answer, verify.name);
31
+ return { id: String(id), account: { id: String(id), ...(typeof name === "string" ? { name } : {}) } };
32
+ };
13
33
  export const storageOf = (raw) => {
14
34
  if (raw === "keyring" || raw === "file")
15
35
  return raw;
@@ -66,6 +66,11 @@ export interface CrmManifestEntity<K extends CrmKind = CrmKind> {
66
66
  ids?: CrmOperationCall;
67
67
  /** One row by `{id}`, for a live read of a contact or company; a 403 or 404 is no row. */
68
68
  get?: CrmOperationCall;
69
+ /**
70
+ * Contacts or companies whose name holds `{query}`, for a live `people list` and `organizations list`; a list with no
71
+ * words reads `list`. Both page by the operation's own `pagination`. Absent, the source has no live list.
72
+ */
73
+ search?: CrmOperationCall;
69
74
  /**
70
75
  * The service names the fields a read returns (HubSpot `properties=`, Bitrix24 `select`): `{select}` becomes the
71
76
  * names under `from` that `map` reads, the custom field codes, and `also`.
@@ -86,6 +91,7 @@ export interface CrmManifestEntity<K extends CrmKind = CrmKind> {
86
91
  custom?: {
87
92
  from: string;
88
93
  split?: string;
94
+ typed?: CrmTypedValues;
89
95
  };
90
96
  /**
91
97
  * 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
@@ -96,14 +102,30 @@ export interface CrmManifestEntity<K extends CrmKind = CrmKind> {
96
102
  scope?: string;
97
103
  };
98
104
  }
105
+ /**
106
+ * Values kept as a list of typed entries, each naming its type (Attio's `values.<slug>`): the entry's type picks where
107
+ * its value is, and a replaced entry, one with a time at `current`, is skipped.
108
+ */
109
+ export interface CrmTypedValues {
110
+ /** Where an entry names its type: `attribute_type`. */
111
+ by: string;
112
+ /** A time an entry was replaced at; an entry with one is history, not the value. */
113
+ current?: string;
114
+ /** Where the value is for each type, over `TYPED_VALUE_PATHS`. */
115
+ paths?: Readonly<Record<string, string>>;
116
+ }
99
117
  export interface CrmManifestPipelines {
100
118
  call: CrmOperationCall;
119
+ /** Read from the pipeline's row, or from its first stage when the call answers stages (`stages.each` is `.`). */
101
120
  map: {
102
121
  externalId: CrmRule;
103
122
  name: CrmRule;
104
123
  };
105
124
  stages: {
125
+ /** The stages in a pipeline's row; `.` when the call answers the stages themselves, one row each. */
106
126
  each: string;
127
+ /** With `each` `.`: the stage's pipeline, by which the stages are grouped; absent, they are all one pipeline. */
128
+ pipeline?: string;
107
129
  map: {
108
130
  externalId: CrmRule;
109
131
  name: CrmRule;
@@ -137,7 +159,10 @@ export interface CrmManifestFields {
137
159
  }[] | undefined);
138
160
  };
139
161
  /** Which listed fields are the account's own, not the service's built-in ones the map already reads. */
140
- keep?: (raw: CrmRaw) => boolean;
162
+ keep?: {
163
+ path: string;
164
+ is: unknown;
165
+ } | ((raw: CrmRaw) => boolean);
141
166
  }
142
167
  /** A CRM account described as data: what to call for each kind and where each of our fields is in the answer. */
143
168
  export interface CrmManifest {
@@ -186,8 +211,16 @@ export interface CrmManifestHooks {
186
211
  call: ServiceApiCall;
187
212
  }) => Promise<CrmRaw[]>;
188
213
  };
214
+ /** The outcome of a stage the data cannot say (Attio names a lost stage only by its title); `found` is the data's. */
215
+ pipelines?: {
216
+ readonly [K in DealKind]?: {
217
+ outcome?: (stage: CrmRaw, pipeline: CrmRaw, found: StageOutcome) => StageOutcome;
218
+ };
219
+ };
189
220
  /** Adds or replaces source methods (`self`, `activities`, a live `list`); `base` is what the manifest built. */
190
- extend?: (base: CrmSource) => Partial<CrmSource>;
221
+ extend?: (base: CrmSource, service: {
222
+ call: ServiceApiCall;
223
+ }) => Partial<CrmSource>;
191
224
  }
192
225
  export declare const crmRuleSchema: v.GenericSchema<CrmRule>;
193
226
  /**
@@ -35,20 +35,26 @@ const entity = v.strictObject({
35
35
  })),
36
36
  ids: v.optional(call),
37
37
  get: v.optional(call),
38
+ search: v.optional(call),
38
39
  select: v.optional(v.strictObject({
39
40
  from: path,
40
41
  also: v.optional(v.array(v.string())),
41
42
  max: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1))),
42
43
  })),
43
44
  map: v.record(v.string(), rule),
44
- custom: v.optional(v.strictObject({ from: path, split: v.optional(v.string()) })),
45
+ custom: v.optional(v.strictObject({
46
+ from: path,
47
+ split: v.optional(v.string()),
48
+ typed: v.optional(v.strictObject({ by: path, current: v.optional(path), paths: v.optional(v.record(v.string(), path)) })),
49
+ })),
45
50
  optional: v.optional(v.strictObject({ message: v.pipe(v.string(), v.minLength(1)), scope: v.optional(v.string()) })),
46
51
  });
47
52
  const pipelines = v.strictObject({
48
53
  call,
49
54
  map: v.strictObject({ externalId: rule, name: rule }),
50
55
  stages: v.strictObject({
51
- each: path,
56
+ each: v.union([v.literal("."), path]),
57
+ pipeline: v.optional(path),
52
58
  map: v.strictObject({ externalId: rule, name: rule, position: v.optional(rule) }),
53
59
  outcome: v.union([
54
60
  v.strictObject({ path, won: v.optional(v.array(v.string())), lost: v.optional(v.array(v.string())) }),
@@ -67,7 +73,7 @@ const fields = v.strictObject({
67
73
  filterable: v.optional(rule),
68
74
  options: v.optional(v.union([v.strictObject({ each: path, id: path, label: path }), v.function()])),
69
75
  }),
70
- keep: v.optional(v.function()),
76
+ keep: v.optional(v.union([v.strictObject({ path, is: v.unknown() }), v.function()])),
71
77
  });
72
78
  const kind = v.picklist(CRM_KINDS);
73
79
  const schema = v.strictObject({
@@ -138,6 +144,21 @@ export const parseCrmManifest = (input, api) => {
138
144
  if (!hasPlaceholder([one.get.path, one.get.query, one.get.body], "{id}"))
139
145
  throw invalid(`entities.${kind}.get`, 'no "{id}" in its path, query or body');
140
146
  }
147
+ if (one.search) {
148
+ if (kind !== "person" && kind !== "organization")
149
+ throw invalid(`entities.${kind}.search`, "only contacts and companies are read live");
150
+ checkCall(`entities.${kind}.search`, one.search, true);
151
+ for (const [name, live] of [
152
+ ["search", one.search],
153
+ ["list", one.list],
154
+ ]) {
155
+ const style = operations.get(live.operation)?.pagination?.style;
156
+ if (style !== undefined && style !== "offset")
157
+ throw invalid(`entities.${kind}.${name}`, `a live list pages by offset or not at all, not by ${style}`);
158
+ }
159
+ if (!hasPlaceholder([one.search.path, one.search.query, one.search.body], "{query}"))
160
+ throw invalid(`entities.${kind}.search`, 'no "{query}" in its path, query or body');
161
+ }
141
162
  if (one.map.externalId === undefined)
142
163
  throw invalid(`entities.${kind}.map.externalId`, "every kind maps its id");
143
164
  const fields = [...Object.keys(FIELDS[kind]), "amount", "currency"];
@@ -152,6 +173,8 @@ export const parseCrmManifest = (input, api) => {
152
173
  if (!one)
153
174
  throw invalid(`pipelines.${kind}`, `${kind} is in kinds, and every deal or lead stands in a pipeline`);
154
175
  checkCall(`pipelines.${kind}.call`, one.call, true);
176
+ if (one.stages.pipeline !== undefined && one.stages.each !== ".")
177
+ throw invalid(`pipelines.${kind}.stages.pipeline`, 'groups stages only when the call answers them: each "."');
155
178
  }
156
179
  for (const [kind, one] of Object.entries(manifest.fields ?? {}))
157
180
  if (one)
@@ -1,6 +1,6 @@
1
1
  import type { CrmField, CrmKind, CrmRecords } from "../../domain/crm.js";
2
2
  import { type CrmRaw, id, number, text } from "../values.js";
3
- import type { CrmRule } from "./manifest.js";
3
+ import type { CrmRule, CrmTypedValues } from "./manifest.js";
4
4
  /** The service sent nothing at this path: the field is left out, so the stored copy keeps what it held. */
5
5
  export declare const MISSING: unique symbol;
6
6
  type Read = unknown | typeof MISSING;
@@ -44,11 +44,14 @@ export declare const FIELDS: {
44
44
  export declare const convert: (conversion: Conversion, value: unknown) => unknown;
45
45
  /** Our fields from the rules, each converted by `types`; a rule whose path is missing gives no key. */
46
46
  export declare const mapFields: (rules: Readonly<Record<string, CrmRule | undefined>>, types: Readonly<Record<string, Conversion>>, raw: CrmRaw) => Record<string, unknown>;
47
+ /** Where a typed entry keeps its value, by its type, as Attio names them; a manifest's `typed.paths` adds or replaces. */
48
+ export declare const TYPED_VALUE_PATHS: Readonly<Record<string, string>>;
47
49
  export interface RecordRules {
48
50
  map: Readonly<Record<string, CrmRule | undefined>>;
49
51
  custom?: {
50
52
  from: string;
51
53
  split?: string;
54
+ typed?: CrmTypedValues;
52
55
  };
53
56
  }
54
57
  /** One row as our record of the kind, or null for a row without an id. */
@@ -178,6 +178,39 @@ export const mapFields = (rules, types, raw) => {
178
178
  }
179
179
  return out;
180
180
  };
181
+ /** Where a typed entry keeps its value, by its type, as Attio names them; a manifest's `typed.paths` adds or replaces. */
182
+ export const TYPED_VALUE_PATHS = {
183
+ text: "value",
184
+ number: "value",
185
+ checkbox: "value",
186
+ date: "value",
187
+ timestamp: "value",
188
+ rating: "value",
189
+ currency: "currency_value",
190
+ status: "status.title",
191
+ select: "option.title",
192
+ "record-reference": "target_record_id",
193
+ "actor-reference": "referenced_actor_id",
194
+ domain: "domain",
195
+ "email-address": "email_address",
196
+ "phone-number": "phone_number",
197
+ "personal-name": "full_name",
198
+ interaction: "interacted_at",
199
+ };
200
+ /** The current entries' values: one alone is the value, several a list, none no value. */
201
+ const typedOf = (entries, typed) => {
202
+ const values = listOf(entries).flatMap((entry) => {
203
+ if (!isRaw(entry))
204
+ return [];
205
+ if (typed.current !== undefined && at(entry, typed.current) != null)
206
+ return [];
207
+ const type = text(at(entry, typed.by));
208
+ const path = type === null ? undefined : (typed.paths?.[type] ?? TYPED_VALUE_PATHS[type]);
209
+ const value = path === undefined ? null : at(entry, path);
210
+ return value === null || value === undefined || value === "" ? [] : [value];
211
+ });
212
+ return values.length > 1 ? values : (values[0] ?? null);
213
+ };
181
214
  /** The account's own fields' values under `from`, labelled by their definitions. */
182
215
  const customOf = (raw, custom, defined) => {
183
216
  const under = at(raw, custom.from);
@@ -185,7 +218,12 @@ const customOf = (raw, custom, defined) => {
185
218
  return undefined;
186
219
  const values = {};
187
220
  for (const field of defined) {
188
- const value = under[field.code];
221
+ const typed = custom.typed ? typedOf(under[field.code], custom.typed) : undefined;
222
+ const value = !custom.typed
223
+ ? under[field.code]
224
+ : field.multiple && typed !== null && !Array.isArray(typed)
225
+ ? [typed]
226
+ : typed;
189
227
  if (value === null || value === undefined || value === "")
190
228
  continue;
191
229
  values[field.code] = field.multiple && custom.split && typeof value === "string" ? value.split(custom.split) : value;
@@ -133,19 +133,22 @@ export const crmManifestProblems = (manifest, api, definitions) => {
133
133
  ...entity.map,
134
134
  ...(entity.custom ? { "(custom)": entity.custom.from } : {}),
135
135
  };
136
- for (const call of [entity.list, entity.changes, entity.get])
136
+ for (const call of [entity.list, entity.changes, entity.get, entity.search])
137
137
  if (call)
138
138
  check(`entities.${kind}.map`, call, rules);
139
139
  }
140
140
  for (const [kind, pipelines] of Object.entries(manifest.pipelines ?? {})) {
141
141
  if (!pipelines)
142
142
  continue;
143
- check(`pipelines.${kind}.map`, pipelines.call, { ...pipelines.map, "(stages)": pipelines.stages.each });
144
- const { outcome } = pipelines.stages;
143
+ const { outcome, each, pipeline } = pipelines.stages;
144
+ // A call that answers stages has one row per stage: the pipeline's map and the stage's read the same row.
145
+ const flat = each === ".";
146
+ check(`pipelines.${kind}.map`, pipelines.call, flat ? pipelines.map : { ...pipelines.map, "(stages)": each });
145
147
  check(`pipelines.${kind}.stages.map`, pipelines.call, {
146
148
  ...pipelines.stages.map,
147
149
  ...(typeof outcome === "object" && "path" in outcome ? { outcome: outcome.path } : {}),
148
- }, pipelines.stages.each);
150
+ ...(pipeline ? { "(pipeline)": pipeline } : {}),
151
+ }, flat ? undefined : each);
149
152
  }
150
153
  for (const [kind, fields] of Object.entries(manifest.fields ?? {})) {
151
154
  if (!fields)
@@ -1,13 +1,16 @@
1
1
  import { CliError, isCliError } from "@wirecat/cli-base";
2
2
  import { nextPage, parameterValue, withValue } from "../../cli/service-api-manifest.js";
3
3
  import { id, isRaw, number, rawsOf, text } from "../values.js";
4
+ import { crmWindowOf, walk } from "../walk.js";
4
5
  import { parseCrmManifest, } from "./manifest.js";
5
6
  import { at, convert, evaluate, MISSING, mapFields, mapRecord, selectedOf } from "./map.js";
6
7
  const OVERLAP_MS = 10 * 60_000;
8
+ /** The most rows a live list asks for in one request. */
9
+ const MOST_LIVE = 100;
7
10
  /** How far one read of every page goes: a service that never stops paging must not hold a sync forever. */
8
11
  const MOST_PAGES = 500;
9
12
  const DROP = Symbol("drop");
10
- /** Fills `"{since}"`, `"{select}"` and `"{id}"`; an empty select drops the parameter it stands for. */
13
+ /** Fills `"{since}"`, `"{select}"`, `"{id}"` and `"{query}"`; an empty select drops the parameter it stands for. */
11
14
  const fill = (value, slots) => {
12
15
  if (value === "{since}")
13
16
  return slots.since ?? DROP;
@@ -15,6 +18,8 @@ const fill = (value, slots) => {
15
18
  return slots.select?.length ? [...slots.select] : DROP;
16
19
  if (value === "{id}")
17
20
  return slots.id ?? DROP;
21
+ if (value === "{query}")
22
+ return slots.query ?? DROP;
18
23
  if (Array.isArray(value))
19
24
  return value.map((one) => fill(one, slots)).filter((one) => one !== DROP);
20
25
  if (isRaw(value))
@@ -252,6 +257,43 @@ export const crmSourceFromManifest = (input, options) => {
252
257
  });
253
258
  return next === undefined ? { items, hasMore: false } : { items, hasMore: true, nextCursor: next };
254
259
  };
260
+ const live = ["person", "organization"].filter((kind) => manifest.entities[kind]?.search);
261
+ /**
262
+ * A live page of contacts or companies, newest first as the service sorts them: words read `search`, none `list`.
263
+ * Only the words narrow it; a condition the manifest cannot send is refused rather than left out of the answer.
264
+ */
265
+ async function readLive(kind, query, context) {
266
+ const entity = entityOf(kind);
267
+ if (!entity.search)
268
+ throw new CliError("validation_error", `${manifest.provider} reads no ${kind} live`, {
269
+ reason: "query.unsupported-field",
270
+ });
271
+ if (query.conditions.length)
272
+ throw new CliError("validation_error", `${manifest.provider} narrows a live list only by words in the name, not by ${query.conditions.map(({ field }) => field).join(", ")}`, { reason: "query.unsupported-field" });
273
+ const words = query.text?.trim() || undefined;
274
+ const call = words ? entity.search : entity.list;
275
+ const send = metered(context);
276
+ const defined = entity.custom ? await fieldsOf(kind, send, context) : [];
277
+ const slots = { select: selectOf(kind, defined, context), ...(words ? { query: words } : {}) };
278
+ const pagination = operations.get(call.operation)?.pagination;
279
+ const largest = pagination?.style === "offset" ? MOST_LIVE : query.limit + 1;
280
+ const page = await walk(crmWindowOf(query), largest, async (offset, size) => {
281
+ let request = inputOf(call, slots);
282
+ if (pagination?.style === "offset") {
283
+ request = withValue(request, pagination.offset, offset);
284
+ if (pagination.limit)
285
+ request = withValue(request, pagination.limit, size);
286
+ }
287
+ const answer = await send(call.operation, request);
288
+ const items = call.items ?? (pagination && "items" in pagination ? pagination.items : undefined);
289
+ const rows = rawsOf(items === undefined ? answer : at(answer, items));
290
+ const all = pagination?.style === "offset" ? rows : rows.slice(offset, offset + size);
291
+ // A short page is not the last: a service may cap a page below the size asked for; only an empty one ends it.
292
+ // That costs one request past the last row, which losing the rows past a cap would not repay.
293
+ return { rows: all, more: pagination?.style === "offset" ? rows.length > 0 : rows.length > offset + size };
294
+ });
295
+ return { ...page, items: await mapped(kind, page.items, defined, send) };
296
+ }
255
297
  const base = {
256
298
  provider: manifest.provider,
257
299
  traits: { kinds: manifest.kinds, removedInChanges: false },
@@ -259,9 +301,10 @@ export const crmSourceFromManifest = (input, options) => {
259
301
  const spec = manifest.pipelines?.[kind];
260
302
  if (!spec)
261
303
  return [];
304
+ const outcome = hooks.pipelines?.[kind]?.outcome;
262
305
  try {
263
306
  const rows = await readAll(spec.call, metered(context));
264
- return rows.flatMap((raw) => toPipeline(spec, raw) ?? []);
307
+ return groupsOf(spec, rows).flatMap(({ raw, stages }) => toPipeline(spec, raw, stages, outcome) ?? []);
265
308
  }
266
309
  catch (error) {
267
310
  if (optionalRefused(kind, error, context))
@@ -290,6 +333,7 @@ export const crmSourceFromManifest = (input, options) => {
290
333
  throw error;
291
334
  }
292
335
  },
336
+ ...(live.length ? { list: readLive } : {}),
293
337
  async get(kind, externalId, context) {
294
338
  const entity = entityOf(kind);
295
339
  if (!entity.get)
@@ -325,26 +369,42 @@ export const crmSourceFromManifest = (input, options) => {
325
369
  }
326
370
  : {}),
327
371
  };
328
- return { ...base, ...hooks.extend?.(base) };
372
+ return { ...base, ...hooks.extend?.(base, { call: options.call }) };
329
373
  };
330
374
  const outcomeOf = (spec, stage, pipeline) => {
331
375
  if (typeof spec === "function")
332
376
  return spec(stage, pipeline);
333
377
  if ("value" in spec)
334
378
  return spec.value;
335
- const found = text(at(stage, spec.path)) ?? "";
379
+ const value = at(stage, spec.path);
380
+ const found = typeof value === "boolean" ? String(value) : (text(value) ?? "");
336
381
  if (spec.won?.includes(found))
337
382
  return "won";
338
383
  return spec.lost?.includes(found) ? "lost" : "open";
339
384
  };
340
- const toPipeline = (spec, raw) => {
385
+ /**
386
+ * Each pipeline's row and its stages. A call that answers stages (`each` `.`) is grouped by `stages.pipeline`, or is
387
+ * one pipeline; its first stage is the row the pipeline's own map reads.
388
+ */
389
+ const groupsOf = (spec, rows) => {
390
+ if (spec.stages.each !== ".")
391
+ return rows.map((raw) => ({ raw, stages: rawsOf(at(raw, spec.stages.each)) }));
392
+ const by = spec.stages.pipeline;
393
+ const groups = new Map();
394
+ for (const row of rows) {
395
+ const key = by === undefined ? "" : (id(at(row, by)) ?? "");
396
+ groups.set(key, [...(groups.get(key) ?? []), row]);
397
+ }
398
+ return [...groups.values()].map((stages) => ({ raw: stages[0], stages }));
399
+ };
400
+ const toPipeline = (spec, raw, stages, hook) => {
341
401
  const { externalId, name } = mapFields(spec.map, { externalId: "id", name: "text" }, raw);
342
402
  if (typeof externalId !== "string")
343
403
  return null;
344
404
  return {
345
405
  externalId,
346
406
  name: typeof name === "string" ? name : externalId,
347
- stages: rawsOf(at(raw, spec.stages.each)).flatMap((stage, place) => {
407
+ stages: stages.flatMap((stage, place) => {
348
408
  const found = mapFields(spec.stages.map, { externalId: "id", name: "text", position: "text" }, stage);
349
409
  if (typeof found.externalId !== "string")
350
410
  return [];
@@ -353,14 +413,16 @@ const toPipeline = (spec, raw) => {
353
413
  externalId: found.externalId,
354
414
  name: typeof found.name === "string" ? found.name : found.externalId,
355
415
  position: number(found.position) ?? place,
356
- outcome: outcomeOf(spec.stages.outcome, stage, raw),
416
+ outcome: hook
417
+ ? hook(stage, raw, outcomeOf(spec.stages.outcome, stage, raw))
418
+ : outcomeOf(spec.stages.outcome, stage, raw),
357
419
  },
358
420
  ];
359
421
  }),
360
422
  };
361
423
  };
362
424
  const toField = (spec, raw) => {
363
- if (spec.keep && !spec.keep(raw))
425
+ if (spec.keep && !(typeof spec.keep === "function" ? spec.keep(raw) : at(raw, spec.keep.path) === spec.keep.is))
364
426
  return null;
365
427
  const { options: optionsRule, ...rules } = spec.map;
366
428
  const found = mapFields(rules, { code: "text", label: "text", type: "text", multiple: "bool", filterable: "bool" }, raw);
@@ -61,6 +61,13 @@ const SINCE = {
61
61
  iso: (value) => Date.parse(value),
62
62
  datetime: (value) => Date.parse(`${value.replace(" ", "T")}Z`),
63
63
  };
64
+ const pageParameter = (pagination) => pagination.style === "cursor"
65
+ ? pagination.cursor
66
+ : pagination.style === "offset"
67
+ ? pagination.offset
68
+ : pagination.style === "page"
69
+ ? pagination.page
70
+ : undefined;
64
71
  /** Every fixed value of a call's template by its dotted path; a placeholder is not fixed. */
65
72
  const fixedOf = (value, trail = []) => {
66
73
  if (Array.isArray(value) || isRaw(value))
@@ -69,7 +76,9 @@ const fixedOf = (value, trail = []) => {
69
76
  return [];
70
77
  return [[trail.join("."), value]];
71
78
  };
72
- const fixedCount = (call) => fixedOf(call.path).length + fixedOf(call.query).length + fixedOf(call.body).length;
79
+ const fixedCount = (call, paging) => fixedOf(call.path).length +
80
+ fixedOf(call.query).filter(([key]) => !paging("query", key)).length +
81
+ fixedOf(call.body).filter(([key]) => !paging("body", key)).length;
73
82
  /**
74
83
  * A CRM service in memory, built from a source manifest and the generated API it names: rows sampled from each
75
84
  * operation's answer schema with distinct ids and the values the map reads, paged by each operation's own pagination,
@@ -109,8 +118,9 @@ export const crmManifestFake = (input, options) => {
109
118
  const typed = (node, value) => {
110
119
  const found = scalarOf(node);
111
120
  const type = found?.type ?? "string";
121
+ // A place whose schema the walk cannot name keeps a flag a flag: the strict fake still checks it.
112
122
  if (typeof value === "boolean")
113
- return type === "boolean" ? value : undefined;
123
+ return type === "boolean" || found === undefined ? value : undefined;
114
124
  if (typeof value === "object")
115
125
  return type === "integer" || type === "number" ? value.ms : new Date(value.ms).toISOString();
116
126
  if (type === "integer" || type === "number")
@@ -123,24 +133,29 @@ export const crmManifestFake = (input, options) => {
123
133
  * The schema with each union on the way to `keys` cut to the branch that has the rest of the path: a sample of the
124
134
  * first branch of Attio's seventeen value types would carry another type's fields, and the strict fake refuses it.
125
135
  */
126
- const narrowed = (node, keys) => {
136
+ const narrowed = (node, keys, value) => {
127
137
  if (keys.length === 0)
128
138
  return node;
129
139
  const found = resolve(node, definitions);
130
140
  const [key, ...rest] = keys;
131
- const fits = (one) => "node" in walk(one, keys.join("."), definitions);
141
+ // A branch fits when it has the path, and, with a value to write, takes it there: Attio's `value` is text in one
142
+ // branch and a flag in another.
143
+ const fits = (one) => {
144
+ const leaf = walk(one, keys.join("."), definitions);
145
+ return "node" in leaf && (value === undefined || typed(leaf.node, value) !== undefined);
146
+ };
132
147
  switch (found.type) {
133
148
  case "union": {
134
- const branch = found.of.find(fits);
135
- return branch ? narrowed(branch, keys) : node;
149
+ const branch = found.of.find(fits) ?? found.of.find((one) => "node" in walk(one, keys.join("."), definitions));
150
+ return branch ? narrowed(branch, keys, value) : node;
136
151
  }
137
152
  case "allOf":
138
- return { ...found, of: found.of.map((one) => (fits(one) ? narrowed(one, keys) : one)) };
153
+ return { ...found, of: found.of.map((one) => (fits(one) ? narrowed(one, keys, value) : one)) };
139
154
  case "array":
140
- return /^\d+$/.test(key) ? { ...found, items: narrowed(found.items, rest) } : node;
155
+ return /^\d+$/.test(key) ? { ...found, items: narrowed(found.items, rest, value) } : node;
141
156
  case "object": {
142
157
  const inner = found.properties[key] ?? found.additionalProperties;
143
- return inner ? { ...found, properties: { ...found.properties, [key]: narrowed(inner, rest) } } : node;
158
+ return inner ? { ...found, properties: { ...found.properties, [key]: narrowed(inner, rest, value) } } : node;
144
159
  }
145
160
  default:
146
161
  return node;
@@ -195,34 +210,35 @@ export const crmManifestFake = (input, options) => {
195
210
  }
196
211
  };
197
212
  const rowOf = (node, rules, types, n, given) => {
198
- // Sampled already cut to the branches the rules write into, so a list the first sample holds has the right type.
199
- const paths = Object.values(rules).flatMap((rule) => pathOf(rule) ?? []);
200
- const made = sample(node && paths.reduce((cut, path) => narrowed(cut, path.split(".")), node));
201
- const row = isRaw(made) ? made : {};
202
- for (const [field, rule] of Object.entries(rules)) {
203
- const path = pathOf(rule);
204
- if (path === undefined)
205
- continue;
213
+ const sampledValue = (field, rule) => {
206
214
  const mapped = typeof rule === "object" && "map" in rule ? Object.keys(rule.map)[0] : undefined;
207
215
  const reverse = typeof rule === "object" && "map" in rule && field in given
208
216
  ? Object.keys(rule.map).find((key) => String(rule.map[key]) === String(given[field]))
209
217
  : undefined;
210
- const value = reverse !== undefined
211
- ? reverse
212
- : field in given
213
- ? given[field]
214
- : mapped !== undefined
215
- ? mapped
216
- : types[field] === "text"
217
- ? `${field} ${n + 1}`
218
- : types[field] === "epoch"
219
- ? { ms: SEEDED + (n + 1) * 60_000 }
220
- : types[field] === "day"
221
- ? `2026-11-0${n + 1}`
222
- : undefined;
218
+ if (reverse !== undefined)
219
+ return reverse;
220
+ if (field in given)
221
+ return given[field];
222
+ if (mapped !== undefined)
223
+ return mapped;
224
+ if (types[field] === "text")
225
+ return `${field} ${n + 1}`;
226
+ if (types[field] === "epoch")
227
+ return { ms: SEEDED + (n + 1) * 60_000 };
228
+ return types[field] === "day" ? `2026-11-0${n + 1}` : undefined;
229
+ };
230
+ const writes = Object.entries(rules).flatMap(([field, rule]) => {
231
+ const path = pathOf(rule);
232
+ return path === undefined ? [] : [{ path, value: sampledValue(field, rule) }];
233
+ });
234
+ // Sampled from the schema cut to the branches the rules write into, each one that takes its value: Attio's
235
+ // `value` is text in one branch and a flag in another, and a list the first sample holds must have the right type.
236
+ const cut = node && writes.reduce((one, { path, value }) => narrowed(one, path.split("."), value), node);
237
+ const made = sample(cut);
238
+ const row = isRaw(made) ? made : {};
239
+ for (const { path, value } of writes)
223
240
  if (value !== undefined)
224
- put(row, path, value, node);
225
- }
241
+ put(row, path, value, cut);
226
242
  return row;
227
243
  };
228
244
  const userSpec = manifest.users;
@@ -239,7 +255,8 @@ export const crmManifestFake = (input, options) => {
239
255
  const rule = manifest.entities[kind]?.map.pipeline;
240
256
  const id = typeof rule === "object" && "value" in rule ? String(rule.value) : String(9001 + index);
241
257
  const node = rowNodeOf(spec.call);
242
- const stageNode = itemOf(nodeAt(node, spec.stages.each), definitions);
258
+ const flat = spec.stages.each === ".";
259
+ const stageNode = flat ? node : itemOf(nodeAt(node, spec.stages.each), definitions);
243
260
  const outcome = spec.stages.outcome;
244
261
  const stages = Array.from({ length: ROWS }, (_, n) => {
245
262
  const stage = rowOf(stageNode, spec.stages.map, { name: "text" }, n, {
@@ -248,12 +265,24 @@ export const crmManifestFake = (input, options) => {
248
265
  });
249
266
  const won = typeof outcome === "object" && "path" in outcome ? [outcome.won?.[0], outcome.lost?.[0]][n - 1] : undefined;
250
267
  if (won !== undefined && typeof outcome === "object" && "path" in outcome)
251
- put(stage, outcome.path, won, stageNode);
268
+ for (const value of won === "true" || won === "false" ? [won === "true", won] : [won]) {
269
+ // A flag the schema keeps as a boolean takes one; a text field the word.
270
+ put(stage, outcome.path, value, stageNode);
271
+ if (at(stage, outcome.path) === value)
272
+ break;
273
+ }
274
+ if (flat && spec.stages.pipeline)
275
+ put(stage, spec.stages.pipeline, id, stageNode);
252
276
  return stage;
253
277
  });
278
+ const ids = stages.map((_, n) => `${id}0${n + 1}`);
279
+ if (flat) {
280
+ pipelines.set(kind, { rows: stages, id, stages: ids });
281
+ continue;
282
+ }
254
283
  const row = rowOf(node, spec.map, { name: "text" }, 0, { externalId: id });
255
284
  putList(row, spec.stages.each, stages, node);
256
- pipelines.set(kind, { rows: [row], id, stages: stages.map((_, n) => `${id}0${n + 1}`) });
285
+ pipelines.set(kind, { rows: [row], id, stages: ids });
257
286
  }
258
287
  const rows = {};
259
288
  const changeAt = {};
@@ -313,6 +342,8 @@ export const crmManifestFake = (input, options) => {
313
342
  routes.push({ call, kind, rows: all });
314
343
  if (entity.get)
315
344
  routes.push({ call: entity.get, kind, rows: all, get: placeOf(entity.get, "{id}") });
345
+ if (entity.search)
346
+ routes.push({ call: entity.search, kind, rows: all, query: placeOf(entity.search, "{query}") });
316
347
  }
317
348
  for (const [kind, one] of pipelines) {
318
349
  const spec = manifest.pipelines?.[kind];
@@ -324,7 +355,13 @@ export const crmManifestFake = (input, options) => {
324
355
  continue;
325
356
  const node = rowNodeOf(spec.call);
326
357
  const { options: _, ...map } = spec.map;
327
- const fields = Array.from({ length: PAGE }, (_, n) => rowOf(node, map, { code: "text", label: "text" }, n, { code: `${kind}_field_${n + 1}` }));
358
+ const keep = typeof spec.keep === "object" ? spec.keep : undefined;
359
+ const fields = Array.from({ length: PAGE }, (_, n) => {
360
+ const field = rowOf(node, map, { code: "text", label: "text" }, n, { code: `${kind}_field_${n + 1}` });
361
+ if (keep && typeof keep.is !== "object")
362
+ putList(field, keep.path, keep.is, node);
363
+ return field;
364
+ });
328
365
  routes.push({ call: spec.call, rows: () => fields });
329
366
  }
330
367
  if (manifest.users)
@@ -334,14 +371,28 @@ export const crmManifestFake = (input, options) => {
334
371
  own.push(message);
335
372
  return { status, body: { message } };
336
373
  };
374
+ /** A page's size and place are the engine's to set: a live list asks for its own, whatever the template says. */
375
+ const paging = (operation, where, key) => {
376
+ const pagination = operations.get(operation)?.pagination;
377
+ if (!pagination)
378
+ return false;
379
+ const parameters = [pageParameter(pagination), "limit" in pagination ? pagination.limit : undefined];
380
+ return parameters.some((one) => one?.in === where && one.name === key);
381
+ };
337
382
  const matches = (route, call) => route.call.operation === call.operation &&
338
383
  fixedOf(route.call.path).every(([key, value]) => call.path[key] === String(value)) &&
339
- fixedOf(route.call.query).every(([key, value]) => readPlace(call, { in: "query", path: key }) === String(value)) &&
340
- fixedOf(route.call.body).every(([key, value]) => at(call.body, key) === value);
341
- /** The route whose template the call matches most closely; a list wins a tie with a change read. */
384
+ fixedOf(route.call.query).every(([key, value]) => paging(route.call.operation, "query", key) || readPlace(call, { in: "query", path: key }) === String(value)) &&
385
+ fixedOf(route.call.body).every(([key, value]) => paging(route.call.operation, "body", key) || at(call.body, key) === value);
386
+ /**
387
+ * The route whose template the call matches most closely; a list wins a tie with a change read, and a search a tie
388
+ * with a list only when its words were sent.
389
+ */
342
390
  const routeOf = (call) => routes
343
- .filter((route) => matches(route, call))
344
- .sort((a, b) => fixedCount(b.call) - fixedCount(a.call) || Number(!!a.since) - Number(!!b.since))[0];
391
+ .filter((route) => matches(route, call) && (!route.query || readPlace(call, route.query) !== undefined))
392
+ .sort((a, b) => fixedCount(b.call, (where, key) => paging(b.call.operation, where, key)) -
393
+ fixedCount(a.call, (where, key) => paging(a.call.operation, where, key)) ||
394
+ Number(!!b.query) - Number(!!a.query) ||
395
+ Number(!!a.since) - Number(!!b.since))[0];
345
396
  const page = (route, call, listed) => {
346
397
  const operation = operations.get(route.call.operation);
347
398
  const pagination = operation?.pagination;
@@ -429,6 +480,10 @@ export const crmManifestFake = (input, options) => {
429
480
  .sort((a, b) => (timeAt(a) ?? 0) - (timeAt(b) ?? 0));
430
481
  return page(changes, call, listed);
431
482
  }
483
+ if (route.query) {
484
+ const words = String(readPlace(call, route.query)).toLowerCase();
485
+ return page(route, call, route.rows().filter((row) => JSON.stringify(row).toLowerCase().includes(words)));
486
+ }
432
487
  return page(route, call, route.rows());
433
488
  };
434
489
  const fake = fakeApi({
@@ -0,0 +1,11 @@
1
+ /**
2
+ * HTML as Markdown (CommonMark + GFM tables): a WordPress post's `content.rendered` or its raw `content` with block
3
+ * comments, a Ghost post's `html`. Comments, scripts, styles, frames and event attributes are dropped, and so are links
4
+ * and images with a scheme other than http(s), mailto and tel.
5
+ */
6
+ export declare const htmlToMarkdown: (html: string) => Promise<string>;
7
+ /**
8
+ * Markdown (CommonMark + GFM) as HTML for a service that stores HTML, such as WordPress or Ghost. Raw HTML in the
9
+ * Markdown is not passed through, and links and images with an unsafe scheme are dropped, as `htmlToMarkdown` does.
10
+ */
11
+ export declare const markdownToHtml: (markdown: string) => Promise<string>;
@@ -0,0 +1,81 @@
1
+ // Loaded on first use, as markdown-blocks.ts loads its parser: most commands never convert a body.
2
+ let converters;
3
+ const loaded = () => (converters ??= importAll());
4
+ const importAll = async () => {
5
+ const [fromHtml, toMdast, toMarkdown, fromMarkdown, gfmMdast, gfmMicromark, toHast, toHtml] = await Promise.all([
6
+ import("hast-util-from-html"),
7
+ import("hast-util-to-mdast"),
8
+ import("mdast-util-to-markdown"),
9
+ import("mdast-util-from-markdown"),
10
+ import("mdast-util-gfm"),
11
+ import("micromark-extension-gfm"),
12
+ import("mdast-util-to-hast"),
13
+ import("hast-util-to-html"),
14
+ ]);
15
+ return {
16
+ fromHtml: fromHtml.fromHtml,
17
+ toMdast: toMdast.toMdast,
18
+ toMarkdown: toMarkdown.toMarkdown,
19
+ fromMarkdown: fromMarkdown.fromMarkdown,
20
+ gfmToMarkdown: gfmMdast.gfmToMarkdown,
21
+ gfmFromMarkdown: gfmMdast.gfmFromMarkdown,
22
+ gfm: gfmMicromark.gfm,
23
+ toHast: toHast.toHast,
24
+ toHtml: toHtml.toHtml,
25
+ };
26
+ };
27
+ // A post body is untrusted: a link or image that runs code or reads a file must not survive into what a CLI shows
28
+ // or writes back. A URL with no scheme (relative, `#anchor`) stays.
29
+ const SAFE_URL = /^(?:https?:|mailto:|tel:|[^:]*$|[^:]*[/?#])/i;
30
+ const unsafe = (url) => !SAFE_URL.test(url.trim());
31
+ // The first definition of a label wins in CommonMark: dropping only an unsafe first one would hand its references to
32
+ // a later definition the author never meant.
33
+ const unsafeLabels = (node, first = new Map()) => {
34
+ if (node.type === "definition" && !first.has(node.identifier))
35
+ first.set(node.identifier, unsafe(node.url));
36
+ if ("children" in node)
37
+ for (const child of node.children)
38
+ unsafeLabels(child, first);
39
+ return first;
40
+ };
41
+ const safeChildren = (node, labels) => {
42
+ node.children = node.children.flatMap((child) => {
43
+ // Raw HTML, including the comments WordPress and Ghost wrap their blocks and cards in.
44
+ if (child.type === "html")
45
+ return [];
46
+ if (child.type === "definition" && (unsafe(child.url) || labels.get(child.identifier)))
47
+ return [];
48
+ if (child.type === "link" && unsafe(child.url)) {
49
+ safeChildren(child, labels);
50
+ return child.children;
51
+ }
52
+ if (child.type === "image" && unsafe(child.url))
53
+ return child.alt ? [{ type: "text", value: child.alt }] : [];
54
+ if ("children" in child)
55
+ safeChildren(child, labels);
56
+ return [child];
57
+ });
58
+ };
59
+ const makeSafe = (tree) => {
60
+ safeChildren(tree, unsafeLabels(tree));
61
+ return tree;
62
+ };
63
+ /**
64
+ * HTML as Markdown (CommonMark + GFM tables): a WordPress post's `content.rendered` or its raw `content` with block
65
+ * comments, a Ghost post's `html`. Comments, scripts, styles, frames and event attributes are dropped, and so are links
66
+ * and images with a scheme other than http(s), mailto and tel.
67
+ */
68
+ export const htmlToMarkdown = async (html) => {
69
+ const { fromHtml, toMdast, toMarkdown, gfmToMarkdown } = await loaded();
70
+ const tree = makeSafe(toMdast(fromHtml(html, { fragment: true })));
71
+ return toMarkdown(tree, { extensions: [gfmToMarkdown()] });
72
+ };
73
+ /**
74
+ * Markdown (CommonMark + GFM) as HTML for a service that stores HTML, such as WordPress or Ghost. Raw HTML in the
75
+ * Markdown is not passed through, and links and images with an unsafe scheme are dropped, as `htmlToMarkdown` does.
76
+ */
77
+ export const markdownToHtml = async (markdown) => {
78
+ const { fromMarkdown, gfmFromMarkdown, gfm, toHast, toHtml } = await loaded();
79
+ const tree = makeSafe(fromMarkdown(markdown, { extensions: [gfm()], mdastExtensions: [gfmFromMarkdown()] }));
80
+ return toHtml(toHast(tree));
81
+ };
@@ -12,6 +12,7 @@ export { type PushConflict, type PushOptions, type PushResult, planPush, pushDoc
12
12
  export { type SyncResult, syncDocuments } from "../services/documents/sync.js";
13
13
  export { type Block, blockKey, blockShape, type Inline, type ListKind, normalizeInlines } from "./blocks.js";
14
14
  export { catalogFiles } from "./catalog.js";
15
+ export { htmlToMarkdown, markdownToHtml } from "./html-markdown.js";
15
16
  export { markdownBlocks, type PlacedBlock, placedMarkdownBlocks } from "./markdown-blocks.js";
16
17
  export type { DocumentSource, FeedlessDocumentSource, IndexedSource, PictureWriter, SourceChange, SourceContent, SourceFile, SourceIndex, SourceSkip, SourceState, SourceStatePort, SourceWalk, SourceWork, TabText, } from "./model.js";
17
18
  export { feedOf } from "./model.js";
@@ -11,6 +11,7 @@ export { planPush, pushDocuments, scanLocal, } from "../services/documents/push.
11
11
  export { syncDocuments } from "../services/documents/sync.js";
12
12
  export { blockKey, blockShape, normalizeInlines } from "./blocks.js";
13
13
  export { catalogFiles } from "./catalog.js";
14
+ export { htmlToMarkdown, markdownToHtml } from "./html-markdown.js";
14
15
  export { markdownBlocks, placedMarkdownBlocks } from "./markdown-blocks.js";
15
16
  export { feedOf } from "./model.js";
16
17
  export { inScope, within } from "./scope.js";
@@ -63,6 +63,7 @@ const PROVIDER_API = [
63
63
  validation("api.unknown-method", "the provider has no method by this name"),
64
64
  ["api.disabled", "configuration_error", "the provider's API is turned off for this OAuth project"],
65
65
  ["manifest.invalid", "configuration_error", "the source manifest does not match its shape or the generated API"],
66
+ ["verify.no-id", "provider_error", "the answer to the sign-in check holds no account id where auth.verify says"],
66
67
  ["provider.usage-limit", "rate_limited", "the account's usage limit at the provider is reached; wait, do not retry"],
67
68
  ["access.denied", "permission_error", "the provider refused this account access to the item"],
68
69
  ["item.not-found", "not_found", "the provider has no item by this id, or this account cannot see it"],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.698.0",
3
+ "version": "0.700.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",
@@ -277,6 +277,9 @@
277
277
  "disposable-email-domains-js": "1.26.0",
278
278
  "echarts": "6.1.0",
279
279
  "fflate": "0.8.3",
280
+ "hast-util-from-html": "2.1.0",
281
+ "hast-util-to-html": "9.0.6",
282
+ "hast-util-to-mdast": "10.1.3",
280
283
  "iconv-lite": "0.7.3",
281
284
  "image-size": "2.0.4",
282
285
  "linkedom": "0.18.14",
@@ -285,6 +288,8 @@
285
288
  "mammoth": "1.13.0",
286
289
  "mdast-util-from-markdown": "2.1.0",
287
290
  "mdast-util-gfm": "3.1.0",
291
+ "mdast-util-to-hast": "13.2.2",
292
+ "mdast-util-to-markdown": "2.2.0",
288
293
  "micromark-extension-gfm": "3.0.0",
289
294
  "mpg123-decoder": "1.0.3",
290
295
  "ogg-opus-decoder": "1.7.5",
@@ -313,7 +318,7 @@
313
318
  "@types/pngjs": "6.0.5",
314
319
  "@types/ssh2": "1.15.5",
315
320
  "@vitest/coverage-v8": "^5.0.5",
316
- "@wirecat/cli-base": "0.117.0",
321
+ "@wirecat/cli-base": "0.118.0",
317
322
  "@wirecat/cli-core-legacy-tags": "npm:@wirecat/cli-core@0.414.0",
318
323
  "ajv": "8.17.1",
319
324
  "commander": "15.0.0",
@@ -337,7 +342,7 @@
337
342
  },
338
343
  "peerDependencies": {
339
344
  "@napi-rs/canvas": ">=0.1.69 <2",
340
- "@wirecat/cli-base": ">=0.117.0 <1.0.0",
345
+ "@wirecat/cli-base": ">=0.118.0 <1.0.0",
341
346
  "commander": ">=15",
342
347
  "mysql2": "^3.24.6",
343
348
  "pg": "^8.23.1",