@wirecat/cli-core 0.694.0 → 0.696.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 +58 -0
- package/dist/cli/bot/api.js +10 -1
- package/dist/cli/index.d.ts +3 -3
- package/dist/cli/index.js +3 -3
- package/dist/cli/profile-token.d.ts +10 -2
- package/dist/cli/profile-token.js +19 -3
- package/dist/cli/service-api-call.d.ts +2 -0
- package/dist/cli/service-api-call.js +1 -1
- package/dist/cli/service-api-manifest.d.ts +9 -3
- package/dist/cli/service-api-manifest.js +63 -7
- package/dist/cli/service-api.d.ts +5 -0
- package/dist/cli/service-api.js +7 -4
- package/dist/cli/token-session.d.ts +27 -1
- package/dist/cli/token-session.js +52 -13
- 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/package.json +1 -1
|
@@ -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;
|