@wirecat/cli-core 0.693.0 → 0.695.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 +59 -0
- package/dist/cli/index.d.ts +1 -1
- package/dist/cli/index.js +1 -1
- package/dist/crm/manifest/paths.d.ts +12 -0
- package/dist/crm/manifest/paths.js +4 -4
- package/dist/crm/testing/index.d.ts +1 -0
- package/dist/crm/testing/index.js +1 -0
- package/dist/crm/testing/manifest-fake.d.ts +47 -0
- package/dist/crm/testing/manifest-fake.js +516 -0
- package/dist/crm/testing/source-contract.d.ts +5 -0
- package/dist/crm/testing/source-contract.js +18 -1
- package/dist/manifest/index.d.ts +15 -1
- package/dist/manifest/index.js +56 -11
- package/dist/search/lucene/plain.js +2 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,65 @@ 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.695.0 — 17.11.2026
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- **`wirecat.config`'s `auth.verify`: the call that checks a token.** For `token` and `oauth2-pkce`, `{ operation, id,
|
|
13
|
+
name? }` names the operation that answers whose the token is and where its answer holds the account's id and name;
|
|
14
|
+
cli-template's `session start` checks a token with it.
|
|
15
|
+
- **`recalledAccount` from `@wirecat/cli-core/cli`**: the account a profile signed in to, as `session start`
|
|
16
|
+
remembered it, for a CLI's own account key (cli-template's CRM wiring from `wirecat.config`).
|
|
17
|
+
- **`crmManifestContract` tests a CRM source from a manifest with no service code.** A CLI made from
|
|
18
|
+
`wirecat.config.ts` runs every `crmSourceContract` case, faults and paging included, in one line
|
|
19
|
+
([CRM.md](docs/dev/CRM.md#a-test-for-a-source-from-a-manifest)). Under it, `crmManifestFake` holds rows sampled
|
|
20
|
+
from each answer's schema, pages them by each operation's own `pagination` and filters change reads by time;
|
|
21
|
+
`crmManifestFixture` gives the source, the rows it holds and the faults `deny`, `change`, `skewed`, `sameToken`. A
|
|
22
|
+
call the manifest never makes, a change read without its since and a read of an unknown id land in `refusals`.
|
|
23
|
+
- **`crmSourceContract` takes `held`, the ids of every row a fixture holds.** A full list must give each of them,
|
|
24
|
+
and a read of changes after `change()` must leave the untouched ones out. Optional: a fixture without it runs as
|
|
25
|
+
before.
|
|
26
|
+
|
|
27
|
+
### Changed — may break callers
|
|
28
|
+
|
|
29
|
+
- **cli-core needs `@wirecat/cli-base` 0.112.0 or later** (peer `>=0.112.0 <1.0.0`), since 0.693.0, for
|
|
30
|
+
`signInRequirements` and `signInPlace`.
|
|
31
|
+
- **`parseCliConfig` refuses a URL that would put a secret, a space or no host into a CLI's files**: `spec.from`,
|
|
32
|
+
`auth.revokeUrl` and a relay redirect take an https URL with a host, and no user name, password, #fragment, or
|
|
33
|
+
key or token in its query. `auth.verify`'s `id` and `name` are dot paths. `hooks` takes a `.ts` or `.js` module
|
|
34
|
+
under `./`. An unknown field reads "not a field of wirecat.config", a missing one "missing".
|
|
35
|
+
|
|
36
|
+
## 0.694.0 — 17.11.2026
|
|
37
|
+
|
|
38
|
+
### Added
|
|
39
|
+
|
|
40
|
+
- **A generated `api` command uploads a file's bytes.** For an operation whose body is an upload, as Petstore 3's
|
|
41
|
+
`application/octet-stream` image, `--body-file <path>` (or `-` for stdin) sends the file as it is, with the
|
|
42
|
+
operation's content type; such a command has no `--body`. A file in the CLI's own folders is refused, as for a JSON
|
|
43
|
+
body. Needs cli-base 0.112.0, whose generator reads such a body.
|
|
44
|
+
- **`serviceApiOperations(manifest)`** lists the operations the `api` group offers and why it leaves out the rest, so
|
|
45
|
+
a CLI's test runs exactly the commands that exist. `sendsBytes(operation)`, `readApiBytes(path)` and
|
|
46
|
+
`unsendableBody(operation)` are exported beside it.
|
|
47
|
+
- **`serviceApiCommand` and `serviceApiCall` take no `token` for a CLI without sign-in.** Left out, no call carries a
|
|
48
|
+
token, whatever the spec says; a CLI made with cli-template's `--sign-in none` passes none.
|
|
49
|
+
|
|
50
|
+
### Changed — may break callers
|
|
51
|
+
|
|
52
|
+
- **A call sends no token where the spec names no sign-in.** The `api` group and `serviceApiCall` now follow cli-base's
|
|
53
|
+
`signInRequirements`: the operation's own `security`, else the document's, and nothing when neither says anything.
|
|
54
|
+
Before, a manifest without `securitySchemes`, or an operation without requirements, got `Authorization: Bearer
|
|
55
|
+
<token>`. A CLI whose spec omits its sign-in now gets the service's refusal (401): generate with `auth`
|
|
56
|
+
(`{ securitySchemes, security, reason }`) to name it. A Discovery manifest gets its OAuth from cli-base 0.112.0's
|
|
57
|
+
generator; regenerate before taking this version.
|
|
58
|
+
- **An operation whose body is neither JSON nor an upload's bytes, such as a multipart form, is no longer offered.**
|
|
59
|
+
It always failed when run; now `api list` leaves it out and `api show <operation>` says why.
|
|
60
|
+
|
|
61
|
+
### Fixed
|
|
62
|
+
|
|
63
|
+
- **A search field whose value starts with a minus reads as that value**: `chat:-1001234567890 budget` searches the
|
|
64
|
+
group with that id, as `chat:"-1001234567890"` did. It was refused as `query.invalid-syntax`, though the CLIs print
|
|
65
|
+
a group's id with its minus. A minus before a bare word still means NOT.
|
|
66
|
+
|
|
8
67
|
## 0.693.0 — 17.11.2026
|
|
9
68
|
|
|
10
69
|
### Added
|
package/dist/cli/index.d.ts
CHANGED
|
@@ -118,7 +118,7 @@ export { readMeetingProjectCandidates } from "./meeting-project-candidates-read.
|
|
|
118
118
|
export { meetingResultItem } from "./meeting-results.js";
|
|
119
119
|
export { type MeetingSeriesInventoryReader, readMeetingSeriesInventory } from "./meeting-series-inventory-read.js";
|
|
120
120
|
export { addMeetingTagsCommand, type MeetingTagsCommandDeps } from "./meeting-tags-command.js";
|
|
121
|
-
export { accountFileFor, profilesHere, rememberAccount } from "./messenger/accounts.js";
|
|
121
|
+
export { accountFileFor, profilesHere, recalledAccount, rememberAccount } from "./messenger/accounts.js";
|
|
122
122
|
export { terminalAsker } from "./messenger/ask.js";
|
|
123
123
|
export type { CompletionOptions } from "./messenger/complete-command.js";
|
|
124
124
|
export { type ConnectOptions, connectFor, type Messenger, type MessengerContext, messengerContext, type ProfileState, type ReadConnection, type StoredMessages, } from "./messenger/context.js";
|
package/dist/cli/index.js
CHANGED
|
@@ -109,7 +109,7 @@ export { readMeetingProjectCandidates } from "./meeting-project-candidates-read.
|
|
|
109
109
|
export { meetingResultItem } from "./meeting-results.js";
|
|
110
110
|
export { readMeetingSeriesInventory } from "./meeting-series-inventory-read.js";
|
|
111
111
|
export { addMeetingTagsCommand } from "./meeting-tags-command.js";
|
|
112
|
-
export { accountFileFor, profilesHere, rememberAccount } from "./messenger/accounts.js";
|
|
112
|
+
export { accountFileFor, profilesHere, recalledAccount, rememberAccount } from "./messenger/accounts.js";
|
|
113
113
|
export { terminalAsker } from "./messenger/ask.js";
|
|
114
114
|
export { connectFor, messengerContext, } from "./messenger/context.js";
|
|
115
115
|
export { DOCTOR_DEEP_OPTION, damageNotes } from "./messenger/doctor-command.js";
|
|
@@ -2,6 +2,18 @@ import type { SchemaNode } from "@wirecat/cli-base/codegen";
|
|
|
2
2
|
import type { ServiceApiManifest } from "../../cli/service-api-manifest.js";
|
|
3
3
|
import type { CrmManifest } from "./manifest.js";
|
|
4
4
|
type Definitions = Readonly<Record<string, SchemaNode>>;
|
|
5
|
+
export declare const resolve: (node: SchemaNode, definitions: Definitions, seen?: Set<string>) => SchemaNode;
|
|
6
|
+
/** The node one step down, `null` when the schema has no such field, `undefined` when the schema cannot say. */
|
|
7
|
+
export declare const step: (node: SchemaNode, key: string, definitions: Definitions) => SchemaNode | null | undefined;
|
|
8
|
+
type Walked = {
|
|
9
|
+
node: SchemaNode | undefined;
|
|
10
|
+
} | {
|
|
11
|
+
missing: string;
|
|
12
|
+
near?: string;
|
|
13
|
+
};
|
|
14
|
+
export declare const walk: (node: SchemaNode, path: string, definitions: Definitions) => Walked;
|
|
15
|
+
/** One item of the list a path ends on; a path that ends on one object is read as a list of it, as the map does. */
|
|
16
|
+
export declare const itemOf: (node: SchemaNode | undefined, definitions: Definitions) => SchemaNode | undefined;
|
|
5
17
|
/**
|
|
6
18
|
* Every path the manifest reads, checked against the schema each operation answers (`definitions` of the generated
|
|
7
19
|
* API): a misspelt or moved field is named with the operation, and the field it likely meant, before a sync runs.
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { editDistance } from "../../search/correct.js";
|
|
2
2
|
import { rulePaths } from "./map.js";
|
|
3
|
-
const resolve = (node, definitions, seen = new Set()) => {
|
|
3
|
+
export const resolve = (node, definitions, seen = new Set()) => {
|
|
4
4
|
if (node.type !== "ref" || seen.has(node.ref))
|
|
5
5
|
return node;
|
|
6
6
|
const found = definitions[node.ref];
|
|
7
7
|
return found ? resolve(found, definitions, new Set([...seen, node.ref])) : { type: "unknown" };
|
|
8
8
|
};
|
|
9
9
|
/** The node one step down, `null` when the schema has no such field, `undefined` when the schema cannot say. */
|
|
10
|
-
const step = (node, key, definitions) => {
|
|
10
|
+
export const step = (node, key, definitions) => {
|
|
11
11
|
const at = resolve(node, definitions);
|
|
12
12
|
switch (at.type) {
|
|
13
13
|
case "object": {
|
|
@@ -43,7 +43,7 @@ const keysOf = (node, definitions) => {
|
|
|
43
43
|
return at.of.flatMap((one) => keysOf(one, definitions));
|
|
44
44
|
return [];
|
|
45
45
|
};
|
|
46
|
-
const walk = (node, path, definitions) => {
|
|
46
|
+
export const walk = (node, path, definitions) => {
|
|
47
47
|
let at = node;
|
|
48
48
|
const segments = path === "." ? [] : path.split(".");
|
|
49
49
|
for (const [place, key] of segments.entries()) {
|
|
@@ -65,7 +65,7 @@ const walk = (node, path, definitions) => {
|
|
|
65
65
|
return { node: at };
|
|
66
66
|
};
|
|
67
67
|
/** One item of the list a path ends on; a path that ends on one object is read as a list of it, as the map does. */
|
|
68
|
-
const itemOf = (node, definitions) => {
|
|
68
|
+
export const itemOf = (node, definitions) => {
|
|
69
69
|
if (node === undefined)
|
|
70
70
|
return undefined;
|
|
71
71
|
const at = resolve(node, definitions);
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export { ACME_CALENDAR, ACME_MAIL, ACME_NOW, ACME_OPENED, ACME_PORTAL, ACME_TELEGRAM, type AcmeScenario, acmeScenario, } from "./acme-scenario.js";
|
|
2
2
|
export { type CrmFilesFixture, crmFilesContract } from "./files-contract.js";
|
|
3
|
+
export { type CrmManifestFake, type CrmManifestFakeOptions, type CrmManifestFixtureOptions, crmManifestContract, crmManifestFake, crmManifestFixture, FAKE_MANIFEST_TOKEN, } from "./manifest-fake.js";
|
|
3
4
|
export { exampleDeal, exampleLead, exampleOrganization, examplePerson, FAKE_CRM_ALIASES, FAKE_FILE_TOKEN, type FakeCrmFile, type FakeCrmSource, type FakeCrmSourceOptions, type FakeCrmWrite, fakeCrmSource, LEAD_PIPELINE, SALES_PIPELINE, SOURCE_FIELD, } from "./source.js";
|
|
4
5
|
export { type CrmSourceFaults, type CrmSourceFixture, crmSourceContract } from "./source-contract.js";
|
|
5
6
|
export { CRM_TRAIT_COMBINATIONS, type CrmSyncFixture, crmSyncContract } from "./sync-contract.js";
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export { ACME_CALENDAR, ACME_MAIL, ACME_NOW, ACME_OPENED, ACME_PORTAL, ACME_TELEGRAM, acmeScenario, } from "./acme-scenario.js";
|
|
2
2
|
export { crmFilesContract } from "./files-contract.js";
|
|
3
|
+
export { crmManifestContract, crmManifestFake, crmManifestFixture, FAKE_MANIFEST_TOKEN, } from "./manifest-fake.js";
|
|
3
4
|
export { exampleDeal, exampleLead, exampleOrganization, examplePerson, FAKE_CRM_ALIASES, FAKE_FILE_TOKEN, fakeCrmSource, LEAD_PIPELINE, SALES_PIPELINE, SOURCE_FIELD, } from "./source.js";
|
|
4
5
|
export { crmSourceContract } from "./source-contract.js";
|
|
5
6
|
export { CRM_TRAIT_COMBINATIONS, crmSyncContract } from "./sync-contract.js";
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { type FakeApi, type SchemaNode } from "@wirecat/cli-base/codegen";
|
|
2
|
+
import { type ServiceApiManifest } from "../../cli/service-api-manifest.js";
|
|
3
|
+
import type { CrmKind } from "../../domain/crm.js";
|
|
4
|
+
import type { ContractCase } from "../../meetings/index.js";
|
|
5
|
+
import { type CrmManifest, type CrmManifestHooks } from "../manifest/manifest.js";
|
|
6
|
+
import { type CrmRaw } from "../values.js";
|
|
7
|
+
import { type CrmSourceFixture } from "./source-contract.js";
|
|
8
|
+
type Definitions = Readonly<Record<string, SchemaNode>>;
|
|
9
|
+
export interface CrmManifestFakeOptions {
|
|
10
|
+
/** The generated API manifest the source manifest names its operations in. */
|
|
11
|
+
api: ServiceApiManifest;
|
|
12
|
+
/** The generated schemas the operations answer by: each row is sampled from them. */
|
|
13
|
+
definitions: Definitions;
|
|
14
|
+
/** In place of the API manifest's first server. */
|
|
15
|
+
baseUrl?: string;
|
|
16
|
+
}
|
|
17
|
+
export interface CrmManifestFake extends FakeApi {
|
|
18
|
+
/** The rows of each kind, as the service holds them; a test may change them. */
|
|
19
|
+
rows: Partial<Record<CrmKind, CrmRaw[]>>;
|
|
20
|
+
/** Makes one row answer `status` to a read by id from now on. */
|
|
21
|
+
deny(kind: CrmKind, id: string, status: number): void;
|
|
22
|
+
/** Moves one row's change time to now, for the next read of changes to list it. */
|
|
23
|
+
touch(kind: CrmKind, id: string): void;
|
|
24
|
+
}
|
|
25
|
+
export declare const FAKE_MANIFEST_TOKEN = "fake-manifest-token";
|
|
26
|
+
/**
|
|
27
|
+
* A CRM service in memory, built from a source manifest and the generated API it names: rows sampled from each
|
|
28
|
+
* operation's answer schema with distinct ids and the values the map reads, paged by each operation's own pagination,
|
|
29
|
+
* read for changes by the time the manifest names. A call no route of the manifest makes is refused and recorded.
|
|
30
|
+
*/
|
|
31
|
+
export declare const crmManifestFake: (input: CrmManifest, options: CrmManifestFakeOptions) => CrmManifestFake;
|
|
32
|
+
export interface CrmManifestFixtureOptions extends CrmManifestFakeOptions {
|
|
33
|
+
hooks?: CrmManifestHooks;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* A `crmSourceContract` fixture for a source built from a manifest, over `crmManifestFake`: the source, the rows it
|
|
37
|
+
* holds, a dead cursor, every fault the manifest allows, and the fake itself, whose `refusals` a test asserts empty.
|
|
38
|
+
*/
|
|
39
|
+
export declare const crmManifestFixture: (manifest: CrmManifest, options: CrmManifestFixtureOptions) => CrmSourceFixture & {
|
|
40
|
+
fake: CrmManifestFake;
|
|
41
|
+
};
|
|
42
|
+
/**
|
|
43
|
+
* `crmSourceContract` over `crmManifestFixture`, each case failing too when the fake refused a call: what a generated
|
|
44
|
+
* test runs, `for (const { name, run } of crmManifestContract(SOURCE, { api, definitions })) it(name, run)`.
|
|
45
|
+
*/
|
|
46
|
+
export declare const crmManifestContract: (manifest: CrmManifest, options: CrmManifestFixtureOptions) => ContractCase[];
|
|
47
|
+
export {};
|
|
@@ -0,0 +1,516 @@
|
|
|
1
|
+
import { fakeApi, sampleOf, } from "@wirecat/cli-base/codegen";
|
|
2
|
+
import { serviceApiCall } from "../../cli/service-api-call.js";
|
|
3
|
+
import { manifestBaseUrl } from "../../cli/service-api-manifest.js";
|
|
4
|
+
import { DEAL_KINDS } from "../../domain/deals.js";
|
|
5
|
+
import { parseCrmManifest, } from "../manifest/manifest.js";
|
|
6
|
+
import { at, convert, evaluate, FIELDS, MISSING } from "../manifest/map.js";
|
|
7
|
+
import { itemOf, resolve, step, walk } from "../manifest/paths.js";
|
|
8
|
+
import { crmSourceFromManifest } from "../manifest/source.js";
|
|
9
|
+
import { id, isRaw } from "../values.js";
|
|
10
|
+
import { crmSourceContract } from "./source-contract.js";
|
|
11
|
+
export const FAKE_MANIFEST_TOKEN = "fake-manifest-token";
|
|
12
|
+
/** Three rows in pages of two: every kind pages at least once, whatever limit the manifest asks for. */
|
|
13
|
+
const ROWS = 3;
|
|
14
|
+
const PAGE = 2;
|
|
15
|
+
const SEEDED = Date.parse("2026-11-01T10:00:00Z");
|
|
16
|
+
/** Where a rule can be written to: the first path it reads, or none for a function or a list it walks. */
|
|
17
|
+
const pathOf = (rule) => {
|
|
18
|
+
if (rule === undefined || typeof rule === "function")
|
|
19
|
+
return undefined;
|
|
20
|
+
if (typeof rule === "string")
|
|
21
|
+
return rule;
|
|
22
|
+
if ("each" in rule || "value" in rule)
|
|
23
|
+
return undefined;
|
|
24
|
+
if ("first" in rule)
|
|
25
|
+
return rule.first[0];
|
|
26
|
+
if ("join" in rule)
|
|
27
|
+
return rule.join[0];
|
|
28
|
+
if ("all" in rule)
|
|
29
|
+
return rule.all[0];
|
|
30
|
+
return rule.path;
|
|
31
|
+
};
|
|
32
|
+
const placeOf = (call, placeholder) => {
|
|
33
|
+
const find = (value, trail) => {
|
|
34
|
+
if (value === placeholder)
|
|
35
|
+
return trail;
|
|
36
|
+
if (!Array.isArray(value) && !isRaw(value))
|
|
37
|
+
return undefined;
|
|
38
|
+
for (const [key, inner] of Object.entries(value)) {
|
|
39
|
+
const found = find(inner, [...trail, key]);
|
|
40
|
+
if (found)
|
|
41
|
+
return found;
|
|
42
|
+
}
|
|
43
|
+
return undefined;
|
|
44
|
+
};
|
|
45
|
+
for (const where of ["path", "query", "body"]) {
|
|
46
|
+
const found = find(call[where], []);
|
|
47
|
+
if (found)
|
|
48
|
+
return { in: where, path: found.join(".") };
|
|
49
|
+
}
|
|
50
|
+
return undefined;
|
|
51
|
+
};
|
|
52
|
+
const readPlace = (call, place) => {
|
|
53
|
+
if (place.in === "body")
|
|
54
|
+
return at(call.body, place.path);
|
|
55
|
+
const found = call[place.in][place.path];
|
|
56
|
+
return Array.isArray(found) ? found.join(",") : found;
|
|
57
|
+
};
|
|
58
|
+
const SINCE = {
|
|
59
|
+
ms: (value) => (/^\d+$/.test(value) ? Number(value) : Number.NaN),
|
|
60
|
+
seconds: (value) => (/^\d+$/.test(value) ? Number(value) * 1000 : Number.NaN),
|
|
61
|
+
iso: (value) => Date.parse(value),
|
|
62
|
+
datetime: (value) => Date.parse(`${value.replace(" ", "T")}Z`),
|
|
63
|
+
};
|
|
64
|
+
/** Every fixed value of a call's template by its dotted path; a placeholder is not fixed. */
|
|
65
|
+
const fixedOf = (value, trail = []) => {
|
|
66
|
+
if (Array.isArray(value) || isRaw(value))
|
|
67
|
+
return Object.entries(value).flatMap(([key, inner]) => fixedOf(inner, [...trail, key]));
|
|
68
|
+
if (!["string", "number", "boolean"].includes(typeof value) || /^\{\w+\}$/.test(String(value)))
|
|
69
|
+
return [];
|
|
70
|
+
return [[trail.join("."), value]];
|
|
71
|
+
};
|
|
72
|
+
const fixedCount = (call) => fixedOf(call.path).length + fixedOf(call.query).length + fixedOf(call.body).length;
|
|
73
|
+
/**
|
|
74
|
+
* A CRM service in memory, built from a source manifest and the generated API it names: rows sampled from each
|
|
75
|
+
* operation's answer schema with distinct ids and the values the map reads, paged by each operation's own pagination,
|
|
76
|
+
* read for changes by the time the manifest names. A call no route of the manifest makes is refused and recorded.
|
|
77
|
+
*/
|
|
78
|
+
export const crmManifestFake = (input, options) => {
|
|
79
|
+
const { api, definitions } = options;
|
|
80
|
+
const manifest = parseCrmManifest(input, api);
|
|
81
|
+
const operations = new Map(api.operations.map((one) => [one.id, one]));
|
|
82
|
+
const own = [];
|
|
83
|
+
const rootOf = (call) => {
|
|
84
|
+
const schema = operations.get(call.operation)?.response?.schema;
|
|
85
|
+
return schema === undefined ? undefined : { type: "ref", ref: schema };
|
|
86
|
+
};
|
|
87
|
+
const itemsOf = (call) => call.items ?? operations.get(call.operation)?.pagination?.items;
|
|
88
|
+
const nodeAt = (node, path) => {
|
|
89
|
+
if (node === undefined)
|
|
90
|
+
return undefined;
|
|
91
|
+
const found = walk(node, path, definitions);
|
|
92
|
+
return "node" in found ? found.node : undefined;
|
|
93
|
+
};
|
|
94
|
+
const rowNodeOf = (call) => {
|
|
95
|
+
const root = rootOf(call);
|
|
96
|
+
const items = itemsOf(call);
|
|
97
|
+
return itemOf(items === undefined ? root : nodeAt(root, items), definitions);
|
|
98
|
+
};
|
|
99
|
+
const sample = (node) => (node === undefined ? undefined : sampleOf(node, definitions));
|
|
100
|
+
const scalarOf = (node) => {
|
|
101
|
+
if (node === undefined)
|
|
102
|
+
return undefined;
|
|
103
|
+
const found = resolve(node, definitions);
|
|
104
|
+
return found.type === "union"
|
|
105
|
+
? scalarOf(found.of.find((one) => resolve(one, definitions).type !== "unknown"))
|
|
106
|
+
: found;
|
|
107
|
+
};
|
|
108
|
+
/** The value as the schema at its place takes it; `undefined` when it cannot. */
|
|
109
|
+
const typed = (node, value) => {
|
|
110
|
+
const found = scalarOf(node);
|
|
111
|
+
const type = found?.type ?? "string";
|
|
112
|
+
if (typeof value === "boolean")
|
|
113
|
+
return type === "boolean" ? value : undefined;
|
|
114
|
+
if (typeof value === "object")
|
|
115
|
+
return type === "integer" || type === "number" ? value.ms : new Date(value.ms).toISOString();
|
|
116
|
+
if (type === "integer" || type === "number")
|
|
117
|
+
return Number.isFinite(Number(value)) ? Number(value) : undefined;
|
|
118
|
+
if (type === "string" && found?.type === "string" && found.enum)
|
|
119
|
+
return undefined;
|
|
120
|
+
return ["string", "unknown"].includes(type) ? String(value) : undefined;
|
|
121
|
+
};
|
|
122
|
+
/** The object a dotted path ends in, with its last key and schema: what is missing is built from the schema's sample. */
|
|
123
|
+
const parentOf = (row, path, node) => {
|
|
124
|
+
const keys = path.split(".");
|
|
125
|
+
const key = keys.pop();
|
|
126
|
+
let here = row;
|
|
127
|
+
let schema = node;
|
|
128
|
+
for (const [place, one] of keys.entries()) {
|
|
129
|
+
const inner = schema === undefined ? undefined : (step(schema, one, definitions) ?? undefined);
|
|
130
|
+
if (typeof here[one] !== "object" || here[one] === null) {
|
|
131
|
+
const made = sample(inner);
|
|
132
|
+
here[one] = typeof made === "object" && made !== null ? made : /^\d+$/.test(keys[place + 1] ?? key) ? [] : {};
|
|
133
|
+
}
|
|
134
|
+
here = here[one];
|
|
135
|
+
schema = inner;
|
|
136
|
+
}
|
|
137
|
+
return { here, key, node: schema === undefined ? undefined : (step(schema, key, definitions) ?? undefined) };
|
|
138
|
+
};
|
|
139
|
+
/** Writes a value as the schema at its place takes it; one it cannot take is left out. */
|
|
140
|
+
const put = (row, path, value, node) => {
|
|
141
|
+
const { here, key, node: inner } = parentOf(row, path, node);
|
|
142
|
+
const written = typed(inner, value);
|
|
143
|
+
if (written !== undefined)
|
|
144
|
+
here[key] = written;
|
|
145
|
+
};
|
|
146
|
+
const putList = (row, path, value, node) => {
|
|
147
|
+
const { here, key } = parentOf(row, path, node);
|
|
148
|
+
here[key] = value;
|
|
149
|
+
};
|
|
150
|
+
/** Drops the next page's token on the last page: the shallowest optional field on its path, else an empty token. */
|
|
151
|
+
const drop = (answer, path, root) => {
|
|
152
|
+
const keys = path.split(".");
|
|
153
|
+
let here = answer;
|
|
154
|
+
let schema = root;
|
|
155
|
+
for (const [place, key] of keys.entries()) {
|
|
156
|
+
if (!isRaw(here))
|
|
157
|
+
return;
|
|
158
|
+
const found = schema === undefined ? undefined : resolve(schema, definitions);
|
|
159
|
+
if (found?.type !== "object" || !found.required.includes(key) || place === keys.length - 1) {
|
|
160
|
+
if (found?.type === "object" && found.required.includes(key))
|
|
161
|
+
here[key] = typed(step(found, key, definitions) ?? undefined, "");
|
|
162
|
+
else
|
|
163
|
+
delete here[key];
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
here = here[key];
|
|
167
|
+
schema = step(found, key, definitions) ?? undefined;
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
const rowOf = (node, rules, types, n, given) => {
|
|
171
|
+
const made = sample(node);
|
|
172
|
+
const row = isRaw(made) ? made : {};
|
|
173
|
+
for (const [field, rule] of Object.entries(rules)) {
|
|
174
|
+
const path = pathOf(rule);
|
|
175
|
+
if (path === undefined)
|
|
176
|
+
continue;
|
|
177
|
+
const mapped = typeof rule === "object" && "map" in rule ? Object.keys(rule.map)[0] : undefined;
|
|
178
|
+
const reverse = typeof rule === "object" && "map" in rule && field in given
|
|
179
|
+
? Object.keys(rule.map).find((key) => String(rule.map[key]) === String(given[field]))
|
|
180
|
+
: undefined;
|
|
181
|
+
const value = reverse !== undefined
|
|
182
|
+
? reverse
|
|
183
|
+
: field in given
|
|
184
|
+
? given[field]
|
|
185
|
+
: mapped !== undefined
|
|
186
|
+
? mapped
|
|
187
|
+
: types[field] === "text"
|
|
188
|
+
? `${field} ${n + 1}`
|
|
189
|
+
: types[field] === "epoch"
|
|
190
|
+
? { ms: SEEDED + (n + 1) * 60_000 }
|
|
191
|
+
: types[field] === "day"
|
|
192
|
+
? `2026-11-0${n + 1}`
|
|
193
|
+
: undefined;
|
|
194
|
+
if (value !== undefined)
|
|
195
|
+
put(row, path, value, node);
|
|
196
|
+
}
|
|
197
|
+
return row;
|
|
198
|
+
};
|
|
199
|
+
const userSpec = manifest.users;
|
|
200
|
+
const users = userSpec
|
|
201
|
+
? Array.from({ length: ROWS }, (_, n) => rowOf(rowNodeOf(userSpec.call), userSpec.map, { name: "text", email: "text" }, n, {
|
|
202
|
+
externalId: String(7001 + n),
|
|
203
|
+
}))
|
|
204
|
+
: [];
|
|
205
|
+
const pipelines = new Map();
|
|
206
|
+
for (const [index, kind] of DEAL_KINDS.entries()) {
|
|
207
|
+
const spec = manifest.pipelines?.[kind];
|
|
208
|
+
if (!spec || !manifest.kinds.includes(kind))
|
|
209
|
+
continue;
|
|
210
|
+
const rule = manifest.entities[kind]?.map.pipeline;
|
|
211
|
+
const id = typeof rule === "object" && "value" in rule ? String(rule.value) : String(9001 + index);
|
|
212
|
+
const node = rowNodeOf(spec.call);
|
|
213
|
+
const stageNode = itemOf(nodeAt(node, spec.stages.each), definitions);
|
|
214
|
+
const outcome = spec.stages.outcome;
|
|
215
|
+
const stages = Array.from({ length: ROWS }, (_, n) => {
|
|
216
|
+
const stage = rowOf(stageNode, spec.stages.map, { name: "text" }, n, {
|
|
217
|
+
externalId: `${id}0${n + 1}`,
|
|
218
|
+
position: n,
|
|
219
|
+
});
|
|
220
|
+
const won = typeof outcome === "object" && "path" in outcome ? [outcome.won?.[0], outcome.lost?.[0]][n - 1] : undefined;
|
|
221
|
+
if (won !== undefined && typeof outcome === "object" && "path" in outcome)
|
|
222
|
+
put(stage, outcome.path, won, stageNode);
|
|
223
|
+
return stage;
|
|
224
|
+
});
|
|
225
|
+
const row = rowOf(node, spec.map, { name: "text" }, 0, { externalId: id });
|
|
226
|
+
putList(row, spec.stages.each, stages, node);
|
|
227
|
+
pipelines.set(kind, { rows: [row], id, stages: stages.map((_, n) => `${id}0${n + 1}`) });
|
|
228
|
+
}
|
|
229
|
+
const rows = {};
|
|
230
|
+
const changeAt = {};
|
|
231
|
+
for (const [index, kind] of manifest.kinds.entries()) {
|
|
232
|
+
const entity = manifest.entities[kind];
|
|
233
|
+
if (!entity)
|
|
234
|
+
continue;
|
|
235
|
+
const map = entity.map;
|
|
236
|
+
const node = rowNodeOf(entity.list);
|
|
237
|
+
const pipeline = pipelines.get(kind);
|
|
238
|
+
const money = pathOf(map.amount) !== undefined && pathOf(map.currency) !== undefined;
|
|
239
|
+
const keyset = entity.changes?.keyset?.field;
|
|
240
|
+
changeAt[kind] = [...new Set([pathOf(map.updatedAt), keyset])].filter(Boolean);
|
|
241
|
+
rows[kind] = Array.from({ length: ROWS }, (_, n) => {
|
|
242
|
+
const time = { ms: SEEDED + (n + 1) * 60_000 };
|
|
243
|
+
const row = rowOf(node, map, FIELDS[kind], n, {
|
|
244
|
+
externalId: String((index + 1) * 1000 + n + 1),
|
|
245
|
+
assignee: "7001",
|
|
246
|
+
...(pipeline ? { pipeline: pipeline.id, stage: pipeline.stages[n % pipeline.stages.length] } : {}),
|
|
247
|
+
...(money ? { amount: "100.50", currency: "EUR" } : { amount: undefined, currency: undefined }),
|
|
248
|
+
});
|
|
249
|
+
if (keyset)
|
|
250
|
+
put(row, keyset, time, node);
|
|
251
|
+
return row;
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
const idOf = (kind, row) => externalIdOf(manifest, kind, row);
|
|
255
|
+
const timeOf = (kind, row) => {
|
|
256
|
+
const path = changeAt[kind]?.[0];
|
|
257
|
+
const found = path === undefined ? null : convert("epoch", at(row, path));
|
|
258
|
+
return typeof found === "number" ? found : null;
|
|
259
|
+
};
|
|
260
|
+
for (const kind of manifest.kinds) {
|
|
261
|
+
if (!manifest.entities[kind]?.changes)
|
|
262
|
+
continue;
|
|
263
|
+
const unread = (rows[kind] ?? []).some((row) => timeOf(kind, row) === null);
|
|
264
|
+
if (!changeAt[kind]?.length || unread)
|
|
265
|
+
throw new Error(`the fake cannot write a change time ${kind} rows read back: map updatedAt or keyset.field to a path`);
|
|
266
|
+
}
|
|
267
|
+
const routes = [];
|
|
268
|
+
for (const kind of manifest.kinds) {
|
|
269
|
+
const entity = manifest.entities[kind];
|
|
270
|
+
if (!entity)
|
|
271
|
+
continue;
|
|
272
|
+
const all = () => rows[kind] ?? [];
|
|
273
|
+
if (entity.changes) {
|
|
274
|
+
const place = placeOf(entity.changes, "{since}");
|
|
275
|
+
routes.push({
|
|
276
|
+
call: entity.changes,
|
|
277
|
+
kind,
|
|
278
|
+
rows: all,
|
|
279
|
+
since: { place, format: entity.changes.since, at: (row) => timeOf(kind, row) },
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
for (const call of [entity.list, entity.ids])
|
|
283
|
+
if (call)
|
|
284
|
+
routes.push({ call, kind, rows: all });
|
|
285
|
+
if (entity.get)
|
|
286
|
+
routes.push({ call: entity.get, kind, rows: all, get: placeOf(entity.get, "{id}") });
|
|
287
|
+
}
|
|
288
|
+
for (const [kind, one] of pipelines) {
|
|
289
|
+
const spec = manifest.pipelines?.[kind];
|
|
290
|
+
if (spec)
|
|
291
|
+
routes.push({ call: spec.call, rows: () => one.rows });
|
|
292
|
+
}
|
|
293
|
+
for (const [kind, spec] of Object.entries(manifest.fields ?? {})) {
|
|
294
|
+
if (!spec)
|
|
295
|
+
continue;
|
|
296
|
+
const node = rowNodeOf(spec.call);
|
|
297
|
+
const { options: _, ...map } = spec.map;
|
|
298
|
+
const fields = Array.from({ length: PAGE }, (_, n) => rowOf(node, map, { code: "text", label: "text" }, n, { code: `${kind}_field_${n + 1}` }));
|
|
299
|
+
routes.push({ call: spec.call, rows: () => fields });
|
|
300
|
+
}
|
|
301
|
+
if (manifest.users)
|
|
302
|
+
routes.push({ call: manifest.users.call, rows: () => users });
|
|
303
|
+
const denied = new Map();
|
|
304
|
+
const refuse = (message, status = 400) => {
|
|
305
|
+
own.push(message);
|
|
306
|
+
return { status, body: { message } };
|
|
307
|
+
};
|
|
308
|
+
const matches = (route, call) => route.call.operation === call.operation &&
|
|
309
|
+
fixedOf(route.call.path).every(([key, value]) => call.path[key] === String(value)) &&
|
|
310
|
+
fixedOf(route.call.query).every(([key, value]) => readPlace(call, { in: "query", path: key }) === String(value)) &&
|
|
311
|
+
fixedOf(route.call.body).every(([key, value]) => at(call.body, key) === value);
|
|
312
|
+
/** The route whose template the call matches most closely; a list wins a tie with a change read. */
|
|
313
|
+
const routeOf = (call) => routes
|
|
314
|
+
.filter((route) => matches(route, call))
|
|
315
|
+
.sort((a, b) => fixedCount(b.call) - fixedCount(a.call) || Number(!!a.since) - Number(!!b.since))[0];
|
|
316
|
+
const page = (route, call, listed) => {
|
|
317
|
+
const operation = operations.get(route.call.operation);
|
|
318
|
+
const pagination = operation?.pagination;
|
|
319
|
+
const root = rootOf(route.call);
|
|
320
|
+
const items = itemsOf(route.call);
|
|
321
|
+
if (items === undefined)
|
|
322
|
+
return { body: listed };
|
|
323
|
+
const made = sample(root);
|
|
324
|
+
const answer = isRaw(made) ? made : {};
|
|
325
|
+
if (!pagination) {
|
|
326
|
+
putList(answer, items, listed, root);
|
|
327
|
+
return { body: answer };
|
|
328
|
+
}
|
|
329
|
+
// The manifest refuses a link-paged read; the check stays for a style cli-base adds later.
|
|
330
|
+
if (pagination.style !== "cursor" && pagination.style !== "offset" && pagination.style !== "page")
|
|
331
|
+
throw new Error(`${route.call.operation}: the fake does not page by ${pagination.style}`);
|
|
332
|
+
const parameter = pagination.style === "cursor"
|
|
333
|
+
? pagination.cursor
|
|
334
|
+
: pagination.style === "offset"
|
|
335
|
+
? pagination.offset
|
|
336
|
+
: pagination.page;
|
|
337
|
+
const sent = readPlace(call, parameter.in === "query" ? { in: "query", path: parameter.name } : { in: "body", path: parameter.name });
|
|
338
|
+
const number = sent === undefined ? undefined : Number(sent);
|
|
339
|
+
if (number !== undefined && !Number.isSafeInteger(number))
|
|
340
|
+
return refuse(`${route.call.operation}: ${parameter.name} ${String(sent)} is not a page this fake gave`);
|
|
341
|
+
const limited = pagination.limit
|
|
342
|
+
? Number(readPlace(call, { in: pagination.limit.in, path: pagination.limit.name }))
|
|
343
|
+
: NaN;
|
|
344
|
+
const size = Number.isSafeInteger(limited) && limited > 0 ? Math.min(limited, PAGE) : PAGE;
|
|
345
|
+
const from = pagination.style === "page" ? ((number ?? 1) - 1) * size : (number ?? 0);
|
|
346
|
+
const chunk = listed.slice(from, from + size);
|
|
347
|
+
const more = from + size < listed.length;
|
|
348
|
+
putList(answer, items, chunk, root);
|
|
349
|
+
if (pagination.style === "cursor") {
|
|
350
|
+
if (more) {
|
|
351
|
+
put(answer, pagination.next, String(from + size), root);
|
|
352
|
+
const written = at(answer, pagination.next);
|
|
353
|
+
if (typeof written !== "string" || written === "")
|
|
354
|
+
throw new Error(`${route.call.operation}: the schema takes no text cursor at ${pagination.next}`);
|
|
355
|
+
}
|
|
356
|
+
else
|
|
357
|
+
drop(answer, pagination.next, root);
|
|
358
|
+
if (pagination.hasMore)
|
|
359
|
+
put(answer, pagination.hasMore, more, root);
|
|
360
|
+
}
|
|
361
|
+
else if (pagination.total)
|
|
362
|
+
put(answer, pagination.total, listed.length, root);
|
|
363
|
+
return { body: answer };
|
|
364
|
+
};
|
|
365
|
+
const answerOf = (call) => {
|
|
366
|
+
const route = routeOf(call);
|
|
367
|
+
if (!route)
|
|
368
|
+
return refuse(`${call.operation ?? call.url.pathname}: no call of the source manifest is this one`, 404);
|
|
369
|
+
const changes = route.since ? route : undefined;
|
|
370
|
+
if (changes?.since && readPlace(call, changes.since.place) === undefined)
|
|
371
|
+
return refuse(`${call.operation}: a read of changes without its since`);
|
|
372
|
+
if (route.get && route.kind) {
|
|
373
|
+
const kind = route.kind;
|
|
374
|
+
const id = String(readPlace(call, route.get) ?? "");
|
|
375
|
+
const status = denied.get(`${kind} ${id}`);
|
|
376
|
+
if (status)
|
|
377
|
+
return { status, body: { message: "denied" } };
|
|
378
|
+
const row = route.rows().find((one) => idOf(kind, one) === id);
|
|
379
|
+
// The contract asks for this id on purpose; any other id the fake lacks is one the source made up.
|
|
380
|
+
if (!row && id.startsWith("contract-missing"))
|
|
381
|
+
return { status: 404, body: { message: "not found" } };
|
|
382
|
+
if (!row)
|
|
383
|
+
return refuse(`${call.operation}: no ${kind} ${id} in the fake`, 404);
|
|
384
|
+
if (route.call.items === undefined)
|
|
385
|
+
return { body: row };
|
|
386
|
+
const root = rootOf(route.call);
|
|
387
|
+
const made = sample(root);
|
|
388
|
+
const answer = isRaw(made) ? made : {};
|
|
389
|
+
putList(answer, route.call.items, row, root);
|
|
390
|
+
return { body: answer };
|
|
391
|
+
}
|
|
392
|
+
if (changes?.since) {
|
|
393
|
+
const { place, format, at: timeAt } = changes.since;
|
|
394
|
+
const from = SINCE[format](String(readPlace(call, place)));
|
|
395
|
+
if (!Number.isFinite(from))
|
|
396
|
+
return refuse(`${call.operation}: since ${String(readPlace(call, place))} is unreadable`);
|
|
397
|
+
const listed = changes
|
|
398
|
+
.rows()
|
|
399
|
+
.filter((row) => (timeAt(row) ?? Number.NEGATIVE_INFINITY) >= from)
|
|
400
|
+
.sort((a, b) => (timeAt(a) ?? 0) - (timeAt(b) ?? 0));
|
|
401
|
+
return page(changes, call, listed);
|
|
402
|
+
}
|
|
403
|
+
return page(route, call, route.rows());
|
|
404
|
+
};
|
|
405
|
+
const fake = fakeApi({
|
|
406
|
+
operations: api.operations,
|
|
407
|
+
definitions,
|
|
408
|
+
baseUrl: options.baseUrl ?? manifestBaseUrl(api),
|
|
409
|
+
token: FAKE_MANIFEST_TOKEN,
|
|
410
|
+
...(api.security ? { security: api.security } : {}),
|
|
411
|
+
...(api.securitySchemes ? { securitySchemes: api.securitySchemes } : {}),
|
|
412
|
+
answers: Object.fromEntries(api.operations.map((one) => [one.id, answerOf])),
|
|
413
|
+
});
|
|
414
|
+
return {
|
|
415
|
+
fetch: fake.fetch,
|
|
416
|
+
calls: fake.calls,
|
|
417
|
+
get refusals() {
|
|
418
|
+
return [...fake.refusals, ...own];
|
|
419
|
+
},
|
|
420
|
+
rows,
|
|
421
|
+
deny: (kind, id, status) => denied.set(`${kind} ${id}`, status),
|
|
422
|
+
touch(kind, id) {
|
|
423
|
+
const row = rows[kind]?.find((one) => idOf(kind, one) === id);
|
|
424
|
+
if (!row)
|
|
425
|
+
throw new Error(`the fake holds no ${kind} ${id}`);
|
|
426
|
+
const node = rowNodeOf(manifest.entities[kind].list);
|
|
427
|
+
const paths = changeAt[kind] ?? [];
|
|
428
|
+
for (const path of paths)
|
|
429
|
+
if (path)
|
|
430
|
+
put(row, path, { ms: Date.now() }, node);
|
|
431
|
+
if (timeOf(kind, row) === null)
|
|
432
|
+
throw new Error(`the fake cannot change the time of ${kind} ${id}`);
|
|
433
|
+
},
|
|
434
|
+
};
|
|
435
|
+
};
|
|
436
|
+
const externalIdOf = (manifest, kind, row) => {
|
|
437
|
+
const rule = manifest.entities[kind]?.map.externalId;
|
|
438
|
+
const found = rule === undefined || row === undefined ? MISSING : evaluate(rule, row);
|
|
439
|
+
return found === MISSING ? null : id(found);
|
|
440
|
+
};
|
|
441
|
+
/**
|
|
442
|
+
* A `crmSourceContract` fixture for a source built from a manifest, over `crmManifestFake`: the source, the rows it
|
|
443
|
+
* holds, a dead cursor, every fault the manifest allows, and the fake itself, whose `refusals` a test asserts empty.
|
|
444
|
+
*/
|
|
445
|
+
export const crmManifestFixture = (manifest, options) => {
|
|
446
|
+
const fake = crmManifestFake(manifest, options);
|
|
447
|
+
const call = serviceApiCall({
|
|
448
|
+
manifest: options.api,
|
|
449
|
+
service: manifest.provider,
|
|
450
|
+
fetch: fake.fetch,
|
|
451
|
+
token: () => FAKE_MANIFEST_TOKEN,
|
|
452
|
+
...(options.baseUrl ? { baseUrl: options.baseUrl } : {}),
|
|
453
|
+
});
|
|
454
|
+
const sourceAt = (now = Date.now) => crmSourceFromManifest(manifest, { api: options.api, call, now, ...(options.hooks ? { hooks: options.hooks } : {}) });
|
|
455
|
+
const source = sourceAt();
|
|
456
|
+
const held = Object.fromEntries(manifest.kinds.map((kind) => [
|
|
457
|
+
kind,
|
|
458
|
+
(fake.rows[kind] ?? []).map((row) => externalIdOf(manifest, kind, row)),
|
|
459
|
+
]));
|
|
460
|
+
const live = ["person", "organization"].find((kind) => manifest.entities[kind]?.get);
|
|
461
|
+
const changed = manifest.kinds.find((kind) => manifest.entities[kind]?.changes);
|
|
462
|
+
const first = (kind) => held[kind]?.[0];
|
|
463
|
+
return {
|
|
464
|
+
source,
|
|
465
|
+
fake,
|
|
466
|
+
held,
|
|
467
|
+
...(source.list ? { live: { person: held.person ?? [], organization: held.organization ?? [] } } : {}),
|
|
468
|
+
deadCursor: { kind: manifest.kinds[0], cursor: "not a time" },
|
|
469
|
+
faults: {
|
|
470
|
+
...(live
|
|
471
|
+
? {
|
|
472
|
+
async deny(status) {
|
|
473
|
+
const id = first(live);
|
|
474
|
+
// A get that reads a wrong id answers null too: the row must read before it is denied.
|
|
475
|
+
if ((await source.get?.(live, id)) == null)
|
|
476
|
+
throw new Error(`get(${live}, ${id}) did not read the row`);
|
|
477
|
+
fake.deny(live, id, status);
|
|
478
|
+
return { kind: live, id };
|
|
479
|
+
},
|
|
480
|
+
}
|
|
481
|
+
: {}),
|
|
482
|
+
skewed: (ms) => sourceAt(() => Date.now() + ms),
|
|
483
|
+
...(changed
|
|
484
|
+
? {
|
|
485
|
+
change: () => {
|
|
486
|
+
const id = first(changed);
|
|
487
|
+
fake.touch(changed, id);
|
|
488
|
+
return { kind: changed, id };
|
|
489
|
+
},
|
|
490
|
+
}
|
|
491
|
+
: {}),
|
|
492
|
+
sameToken: () => sourceAt(),
|
|
493
|
+
},
|
|
494
|
+
};
|
|
495
|
+
};
|
|
496
|
+
/**
|
|
497
|
+
* `crmSourceContract` over `crmManifestFixture`, each case failing too when the fake refused a call: what a generated
|
|
498
|
+
* test runs, `for (const { name, run } of crmManifestContract(SOURCE, { api, definitions })) it(name, run)`.
|
|
499
|
+
*/
|
|
500
|
+
export const crmManifestContract = (manifest, options) => {
|
|
501
|
+
const fakes = [];
|
|
502
|
+
return crmSourceContract(() => {
|
|
503
|
+
const fixture = crmManifestFixture(manifest, options);
|
|
504
|
+
fakes.push(fixture.fake);
|
|
505
|
+
return fixture;
|
|
506
|
+
}).map(({ name, run }) => ({
|
|
507
|
+
name,
|
|
508
|
+
async run() {
|
|
509
|
+
fakes.length = 0;
|
|
510
|
+
await run();
|
|
511
|
+
const refused = fakes.flatMap((fake) => fake.refusals);
|
|
512
|
+
if (refused.length)
|
|
513
|
+
throw new Error(`the fake refused calls the source made:\n${refused.join("\n")}`);
|
|
514
|
+
},
|
|
515
|
+
}));
|
|
516
|
+
};
|
|
@@ -35,6 +35,11 @@ export interface CrmSourceFixture {
|
|
|
35
35
|
* back each of them.
|
|
36
36
|
*/
|
|
37
37
|
live?: Partial<Record<"person" | "organization", readonly string[]>>;
|
|
38
|
+
/**
|
|
39
|
+
* The ids of every row of each kind the fixture holds, each changed before the change feed's overlap: a full list
|
|
40
|
+
* must give back each of them, and a read of changes after `change()` must leave the untouched ones out.
|
|
41
|
+
*/
|
|
42
|
+
held?: Partial<Record<CrmKind, readonly string[]>>;
|
|
38
43
|
/** A cursor the CRM refuses; absent skips that case. */
|
|
39
44
|
deadCursor?: {
|
|
40
45
|
kind: CrmKind;
|
|
@@ -131,6 +131,20 @@ export const crmSourceContract = (make) => {
|
|
|
131
131
|
}
|
|
132
132
|
},
|
|
133
133
|
},
|
|
134
|
+
{
|
|
135
|
+
name: "changes: a full list gives every row the fixture holds, none lost between the CRM's pages",
|
|
136
|
+
async run() {
|
|
137
|
+
const { source, held } = await make();
|
|
138
|
+
if (!held)
|
|
139
|
+
return;
|
|
140
|
+
for (const kind of source.traits.kinds) {
|
|
141
|
+
const ids = held[kind];
|
|
142
|
+
if (!ids)
|
|
143
|
+
continue;
|
|
144
|
+
assert.deepEqual(idsOf((await listAll(source, kind, null)).items).sort(), [...ids].sort(), `${kind}: every row the fixture holds is listed`);
|
|
145
|
+
}
|
|
146
|
+
},
|
|
147
|
+
},
|
|
134
148
|
{
|
|
135
149
|
name: "changes: the cursor a full list gave reads again without failing",
|
|
136
150
|
async run() {
|
|
@@ -239,7 +253,7 @@ const faultCases = (make) => [
|
|
|
239
253
|
if (!first.faults?.skewed || !first.faults.change)
|
|
240
254
|
return;
|
|
241
255
|
for (const ms of [SKEW_MS, -SKEW_MS]) {
|
|
242
|
-
const { faults } = ms === SKEW_MS ? first : await make();
|
|
256
|
+
const { faults, held } = ms === SKEW_MS ? first : await make();
|
|
243
257
|
const source = (await faults?.skewed?.(ms));
|
|
244
258
|
const read = await Promise.all(source.traits.kinds.map(async (kind) => [kind, await listAll(source, kind, null)]));
|
|
245
259
|
const { kind, id } = await faults.change();
|
|
@@ -247,6 +261,9 @@ const faultCases = (make) => [
|
|
|
247
261
|
assert.ok(cursor !== null, `${kind}: a full list gives a cursor for the change to be read after`);
|
|
248
262
|
const { items } = await listAll(source, kind, cursor);
|
|
249
263
|
assert.ok(idsOf(items).includes(id), `${kind} ${id} is in the changes with this computer's clock ${ms / 60_000} min off`);
|
|
264
|
+
const untouched = held?.[kind]?.filter((one) => one !== id) ?? [];
|
|
265
|
+
for (const one of untouched)
|
|
266
|
+
assert.ok(!idsOf(items).includes(one), `${kind} ${one} did not change, yet a read of changes lists it`);
|
|
250
267
|
}
|
|
251
268
|
},
|
|
252
269
|
},
|
package/dist/manifest/index.d.ts
CHANGED
|
@@ -1,15 +1,26 @@
|
|
|
1
1
|
import type { CrmManifest } from "../crm/manifest/manifest.js";
|
|
2
2
|
import type { OAuthProvider } from "../oauth/provider.js";
|
|
3
|
+
/**
|
|
4
|
+
* The operation that answers whose the token is, and where its answer holds the account's id (and a name to show):
|
|
5
|
+
* `{ operation: "getV2Self", id: "workspace_id", name: "workspace_name" }`. `session start` checks a token with it.
|
|
6
|
+
*/
|
|
7
|
+
export interface CliVerify {
|
|
8
|
+
operation: string;
|
|
9
|
+
id: string;
|
|
10
|
+
name?: string;
|
|
11
|
+
}
|
|
3
12
|
export type CliAuth = {
|
|
4
13
|
preset: "none";
|
|
5
14
|
}
|
|
6
15
|
/** A token or key, sent where the spec's `securitySchemes` say: a bearer header, an API key header or query. */
|
|
7
16
|
| {
|
|
8
17
|
preset: "token";
|
|
18
|
+
verify?: CliVerify;
|
|
9
19
|
}
|
|
10
20
|
/** The browser sign-in the spec's authorization code flow declares; the redirect is what the app registered. */
|
|
11
21
|
| {
|
|
12
22
|
preset: "oauth2-pkce";
|
|
23
|
+
verify?: CliVerify;
|
|
13
24
|
scopes: readonly string[];
|
|
14
25
|
scheme?: string;
|
|
15
26
|
redirect?: OAuthProvider["redirect"];
|
|
@@ -49,5 +60,8 @@ export interface CliConfig {
|
|
|
49
60
|
}
|
|
50
61
|
/** Types the config in the editor; it returns what it is given. */
|
|
51
62
|
export declare const defineCli: (config: CliConfig) => CliConfig;
|
|
52
|
-
/**
|
|
63
|
+
/**
|
|
64
|
+
* The config checked against its shape; every error names where it is. A CRM CLI needs its source. `source` comes back
|
|
65
|
+
* unchecked: `parseCrmManifest` checks it against the generated API.
|
|
66
|
+
*/
|
|
53
67
|
export declare const parseCliConfig: (input: unknown) => CliConfig;
|
package/dist/manifest/index.js
CHANGED
|
@@ -1,12 +1,43 @@
|
|
|
1
|
-
import { isAbsolute } from "node:path";
|
|
2
1
|
import { CliError } from "@wirecat/cli-base";
|
|
3
2
|
import * as v from "valibot";
|
|
4
3
|
export const CLI_CATEGORIES = ["messenger", "mail", "notes", "files", "meetings", "calendar", "crm", "other"];
|
|
5
4
|
/** Types the config in the editor; it returns what it is given. */
|
|
6
5
|
export const defineCli = (config) => config;
|
|
7
6
|
const word = v.pipe(v.string(), v.regex(/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/, "lower-case letters and digits, words joined by one dash"));
|
|
8
|
-
|
|
9
|
-
|
|
7
|
+
// A query parameter with such a word in its name holds a secret, which the URL would put into a committed file. Whole
|
|
8
|
+
// words, so `design` or `keyword` stay allowed.
|
|
9
|
+
const SECRET_WORDS = new Set([
|
|
10
|
+
"key",
|
|
11
|
+
"apikey",
|
|
12
|
+
"token",
|
|
13
|
+
"secret",
|
|
14
|
+
"sig",
|
|
15
|
+
"signature",
|
|
16
|
+
"auth",
|
|
17
|
+
"password",
|
|
18
|
+
"pass",
|
|
19
|
+
"passwd",
|
|
20
|
+
"credential",
|
|
21
|
+
"credentials",
|
|
22
|
+
"session",
|
|
23
|
+
"sessionid",
|
|
24
|
+
"jwt",
|
|
25
|
+
"code",
|
|
26
|
+
]);
|
|
27
|
+
const secretName = (name) => name.split(/[_\-.]+|(?<=[a-z0-9])(?=[A-Z])/).some((part) => SECRET_WORDS.has(part.toLowerCase()));
|
|
28
|
+
const urlOf = (text) => (URL.canParse(text) ? new URL(text) : undefined);
|
|
29
|
+
/** An https URL that can be committed: a host, no spaces, no user name or password, no secret in its query. */
|
|
30
|
+
const httpsUrl = v.pipe(v.string(), v.check((text) => !/\s/.test(text), "an https URL without spaces"), v.check((text) => {
|
|
31
|
+
const url = urlOf(text);
|
|
32
|
+
return url?.protocol === "https:" && url.hostname.length > 0;
|
|
33
|
+
}, "a valid https URL with a host"), v.check((text) => {
|
|
34
|
+
const url = urlOf(text);
|
|
35
|
+
return !url?.username && !url?.password;
|
|
36
|
+
}, "an https URL without a user name or password, which would be committed"), v.check((text) => ![...(urlOf(text)?.searchParams.keys() ?? [])].some(secretName), "an https URL without a key or token in its query, which would be committed"),
|
|
37
|
+
// A token handed back in the fragment (OAuth's implicit flow) would be committed too; a description needs none.
|
|
38
|
+
v.check((text) => !urlOf(text)?.hash, "an https URL without a #fragment"));
|
|
39
|
+
const dotPath = v.pipe(v.string(), v.regex(/^[^.\s]+(\.[^.\s]+)*$/, "a dot path into the answer, such as data.id"));
|
|
40
|
+
const verify = v.optional(v.strictObject({ operation: v.pipe(v.string(), v.minLength(1)), id: dotPath, name: v.optional(dotPath) }));
|
|
10
41
|
const schema = v.strictObject({
|
|
11
42
|
identity: v.strictObject({
|
|
12
43
|
command: word,
|
|
@@ -17,38 +48,52 @@ const schema = v.strictObject({
|
|
|
17
48
|
}),
|
|
18
49
|
spec: v.strictObject({
|
|
19
50
|
kind: v.picklist(["openapi", "swagger"]),
|
|
20
|
-
from:
|
|
51
|
+
from: httpsUrl,
|
|
21
52
|
}),
|
|
22
53
|
auth: v.variant("preset", [
|
|
23
54
|
v.strictObject({ preset: v.literal("none") }),
|
|
24
|
-
v.strictObject({ preset: v.literal("token") }),
|
|
55
|
+
v.strictObject({ preset: v.literal("token"), verify }),
|
|
25
56
|
v.strictObject({
|
|
26
57
|
preset: v.literal("oauth2-pkce"),
|
|
58
|
+
verify,
|
|
27
59
|
scopes: v.array(v.string()),
|
|
28
60
|
scheme: v.optional(v.string()),
|
|
29
|
-
revokeUrl: v.optional(
|
|
61
|
+
revokeUrl: v.optional(httpsUrl),
|
|
30
62
|
authorizeParams: v.optional(v.record(v.string(), v.string())),
|
|
31
63
|
rotating: v.optional(v.boolean()),
|
|
32
64
|
redirect: v.optional(v.variant("kind", [
|
|
33
65
|
v.strictObject({ kind: v.literal("loopback"), host: v.optional(v.literal("localhost")) }),
|
|
34
|
-
v.strictObject({ kind: v.literal("relay"), url:
|
|
66
|
+
v.strictObject({ kind: v.literal("relay"), url: httpsUrl }),
|
|
35
67
|
])),
|
|
36
68
|
}),
|
|
37
69
|
]),
|
|
38
70
|
category: v.picklist(CLI_CATEGORIES),
|
|
39
71
|
source: v.optional(v.looseObject({})),
|
|
40
|
-
hooks: v.optional(v.pipe(v.string(), v.
|
|
72
|
+
hooks: v.optional(v.pipe(v.string(), v.regex(/^\.\/([^\s]*\/)?[^/\s.][^/\s]*\.[cm]?[jt]s$/, "a module in the project, such as ./src/hooks.ts"), v.check((text) => !/\.d\.[cm]?ts$/.test(text), "a module, not a .d.ts declaration file"), v.check((text) => !text.split(/[\\/]/).includes(".."), "a module in the project, without .."))),
|
|
41
73
|
});
|
|
42
|
-
/**
|
|
74
|
+
/**
|
|
75
|
+
* The config checked against its shape; every error names where it is. A CRM CLI needs its source. `source` comes back
|
|
76
|
+
* unchecked: `parseCrmManifest` checks it against the generated API.
|
|
77
|
+
*/
|
|
43
78
|
export const parseCliConfig = (input) => {
|
|
44
79
|
const parsed = v.safeParse(schema, input);
|
|
45
80
|
if (!parsed.success) {
|
|
46
81
|
const [issue] = parsed.issues;
|
|
47
|
-
|
|
82
|
+
// valibot's own words for a key: "Invalid key: Expected never but received …". By the issue's shape, so a value
|
|
83
|
+
// that is undefined inside a list or record keeps valibot's words.
|
|
84
|
+
const keyed = issue.type === "strict_object" || issue.type === "variant";
|
|
85
|
+
const message = keyed && issue.expected === "never"
|
|
86
|
+
? "not a field of wirecat.config"
|
|
87
|
+
: keyed && issue.input === undefined
|
|
88
|
+
? "missing"
|
|
89
|
+
: issue.message;
|
|
90
|
+
throw new CliError("configuration_error", `wirecat.config: ${v.getDotPath(issue) ?? "(root)"}: ${message}`, {
|
|
48
91
|
reason: "manifest.invalid",
|
|
49
92
|
});
|
|
50
93
|
}
|
|
51
|
-
|
|
94
|
+
// Typed, not cast: a field CliConfig needs that the schema lacks or types otherwise fails to compile (not the reverse).
|
|
95
|
+
const output = parsed.output;
|
|
96
|
+
const config = output;
|
|
52
97
|
if (config.category !== "crm" && config.source)
|
|
53
98
|
throw new CliError("configuration_error", "wirecat.config: source: only a crm CLI reads a source yet", {
|
|
54
99
|
reason: "manifest.invalid",
|
|
@@ -52,7 +52,8 @@ const literal = (word, keepParens, fields) => {
|
|
|
52
52
|
const prefix = FIELD_PREFIX.exec(word);
|
|
53
53
|
const field = prefix && fields.has(prefix[1] ?? "") ? prefix[0] : "";
|
|
54
54
|
const rest = word.slice(field.length);
|
|
55
|
-
|
|
55
|
+
// After `field:` a minus is part of the value (a group's id is `-100…`); only a bare word's `-` means NOT.
|
|
56
|
+
const opening = keepParens ? ((field ? /^\(*/u : /^[(+-]*/u).exec(rest)?.[0] ?? "") : "";
|
|
56
57
|
const closing = keepParens ? (/\)*$/u.exec(rest.slice(opening.length))?.[0] ?? "") : "";
|
|
57
58
|
const body = rest.slice(opening.length, rest.length - closing.length);
|
|
58
59
|
if (!body)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wirecat/cli-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.695.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",
|