@wirecat/cli-core 0.700.0 → 0.702.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,40 @@ 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.702.0 — 18.11.2026
9
+
10
+ ### Added
11
+
12
+ - **A source manifest's `linked: true` on contacts or companies copies only the ones a deal names**, each read by its
13
+ `get`, as bitrix24-cli's sync does; the rest stay in the service and are read live. Their ids are the deals' links,
14
+ so one no deal names any more leaves the copy at the next full round. Attio's contacts and companies grow from the
15
+ owner's mail, and a full copy held thousands nobody sells to.
16
+
17
+ ### Fixed
18
+
19
+ - **An optional kind the service answers with 404 is a gap too**, not only a 403. Attio's Deals object is off until an
20
+ admin turns it on, and its records query answers 404: the sync failed instead of naming the gap.
21
+
22
+ ## 0.701.0 — 18.11.2026
23
+
24
+ ### Added
25
+
26
+ - **`trackerManifestContract`, `trackerManifestFixture` and `trackerManifestFake` in `@wirecat/cli-core/tracker/testing`
27
+ run `trackerSourceContract` over a tracker source built from a manifest**, with no code for the service: a CLI made
28
+ from `wirecat.config.ts` (linear-cli first) checks its tracker in one line,
29
+ `for (const { name, run } of trackerManifestContract(SOURCE, { api, definitions })) it(name, run)`. The fake is
30
+ cli-base's strict `graphqlFake` with three rows of each kind behind it, written where the map reads them and linked
31
+ across kinds, paged by the Relay cursor, read for changes by the since, archived rows hidden unless asked for. The
32
+ fixture brings the held ids, a dead cursor and the faults `skewed`, `change`, `archive` and `remove`
33
+ ([TRACKER.md](docs/dev/TRACKER.md#the-contract-kit)).
34
+
35
+ ### Fixed
36
+
37
+ - **A conversation rebuild no longer spends minutes dropping the old build's vectors.** For each old chunk text the
38
+ check for a current chunk with the same text read every conversation chunk in the store, and the delete that follows
39
+ read the whole vector key; both now use their index. A rebuild of a forum of about 112,000 messages took 889 s and now
40
+ takes 52 s, on the same store and load.
41
+
8
42
  ## 0.700.0 — 18.11.2026
9
43
 
10
44
  ### Added
@@ -94,13 +94,19 @@ export interface CrmManifestEntity<K extends CrmKind = CrmKind> {
94
94
  typed?: CrmTypedValues;
95
95
  };
96
96
  /**
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
98
- * scope, and the other kinds still sync.
97
+ * A kind the plan or the sign-in may not have (HubSpot's leads, Attio's Deals object when it is off): the service
98
+ * refusing it, or answering that it is not there, is a gap with this text and scope, and the other kinds still sync.
99
99
  */
100
100
  optional?: {
101
101
  message: string;
102
102
  scope?: string;
103
103
  };
104
+ /**
105
+ * Contacts or companies: the sync copies only the ones a deal names, each read by `get`, as Bitrix24's does; the
106
+ * rest stay in the service and are read live. For a service whose own contacts and companies grow from mail
107
+ * (Attio), where a full copy would hold thousands nobody sells to.
108
+ */
109
+ linked?: true;
104
110
  }
105
111
  /**
106
112
  * Values kept as a list of typed entries, each naming its type (Attio's `values.<slug>`): the entry's type picks where
@@ -48,6 +48,7 @@ const entity = v.strictObject({
48
48
  typed: v.optional(v.strictObject({ by: path, current: v.optional(path), paths: v.optional(v.record(v.string(), path)) })),
49
49
  })),
50
50
  optional: v.optional(v.strictObject({ message: v.pipe(v.string(), v.minLength(1)), scope: v.optional(v.string()) })),
51
+ linked: v.optional(v.literal(true)),
51
52
  });
52
53
  const pipelines = v.strictObject({
53
54
  call,
@@ -159,6 +160,15 @@ export const parseCrmManifest = (input, api) => {
159
160
  if (!hasPlaceholder([one.search.path, one.search.query, one.search.body], "{query}"))
160
161
  throw invalid(`entities.${kind}.search`, 'no "{query}" in its path, query or body');
161
162
  }
163
+ if (one.linked) {
164
+ if (kind !== "person" && kind !== "organization")
165
+ throw invalid(`entities.${kind}.linked`, "only contacts and companies are copied as a deal names them");
166
+ if (!one.get)
167
+ throw invalid(`entities.${kind}.linked`, "each one is read by its get, and this kind has none");
168
+ const link = kind === "person" ? "people" : "organization";
169
+ if (!manifest.kinds.includes("deal") || manifest.entities.deal?.map[link] === undefined)
170
+ throw invalid(`entities.${kind}.linked`, `no deal entity maps ${link}`);
171
+ }
162
172
  if (one.map.externalId === undefined)
163
173
  throw invalid(`entities.${kind}.map.externalId`, "every kind maps its id");
164
174
  const fields = [...Object.keys(FIELDS[kind]), "amount", "currency"];
@@ -9,6 +9,8 @@ const OVERLAP_MS = 10 * 60_000;
9
9
  const MOST_LIVE = 100;
10
10
  /** How far one read of every page goes: a service that never stops paging must not hold a sync forever. */
11
11
  const MOST_PAGES = 500;
12
+ /** Contacts or companies a deal names, read one by one, per page of a sync round. */
13
+ const LINKED_PAGE = 50;
12
14
  const DROP = Symbol("drop");
13
15
  /** Fills `"{since}"`, `"{select}"`, `"{id}"` and `"{query}"`; an empty select drops the parameter it stands for. */
14
16
  const fill = (value, slots) => {
@@ -189,7 +191,7 @@ export const crmSourceFromManifest = (input, options) => {
189
191
  /** A refusal of a kind the manifest marks optional is a gap; the other kinds still sync. */
190
192
  const optionalRefused = (kind, error, context) => {
191
193
  const optional = manifest.entities[kind]?.optional;
192
- if (!optional || !isCliError(error) || error.code !== "permission_error")
194
+ if (!optional || !unseen(error))
193
195
  return false;
194
196
  gap(context, { kind, message: optional.message, ...(optional.scope ? { scope: optional.scope } : {}) });
195
197
  return true;
@@ -228,6 +230,8 @@ export const crmSourceFromManifest = (input, options) => {
228
230
  };
229
231
  const readChanges = async (kind, cursor, page, context) => {
230
232
  const entity = entityOf(kind);
233
+ if (entity.linked && (kind === "person" || kind === "organization"))
234
+ return (await readLinked(kind, page, context));
231
235
  const since = cursor === null ? null : Date.parse(cursor);
232
236
  if (since !== null && Number.isNaN(since))
233
237
  return { reset: true };
@@ -247,8 +251,80 @@ export const crmSourceFromManifest = (input, options) => {
247
251
  ? { items, hasMore: false, cursor: new Date(started).toISOString() }
248
252
  : { items, hasMore: true, nextCursor: `${next}@${started}` };
249
253
  };
254
+ const readOne = async (kind, externalId, send, context) => {
255
+ const entity = entityOf(kind);
256
+ if (!entity.get)
257
+ return null;
258
+ const defined = entity.custom ? await fieldsOf(kind, send, context) : [];
259
+ let answer;
260
+ try {
261
+ answer = await send(entity.get.operation, inputOf(entity.get, { id: externalId, select: selectOf(kind, defined, context) }));
262
+ }
263
+ catch (error) {
264
+ if (unseen(error))
265
+ return null;
266
+ throw error;
267
+ }
268
+ const raw = entity.get.items === undefined ? answer : at(answer, entity.get.items);
269
+ return isRaw(raw) ? ((await mapped(kind, [raw], defined, send))[0] ?? null) : null;
270
+ };
271
+ /** The contacts and companies the deals name, from one pass over the deals; deals the service refuses name none. */
272
+ const linkedOf = async (send, context) => {
273
+ const deal = entityOf("deal");
274
+ const found = { person: new Set(), organization: new Set() };
275
+ let rows;
276
+ try {
277
+ rows = await readAll(deal.list, send);
278
+ }
279
+ catch (error) {
280
+ if (!optionalRefused("deal", error, context))
281
+ throw error;
282
+ rows = [];
283
+ }
284
+ for (const raw of rows) {
285
+ const record = mapRecord("deal", deal, raw, []);
286
+ if (record?.organization)
287
+ found.organization.add(record.organization);
288
+ for (const one of record?.people ?? [])
289
+ found.person.add(one.externalId);
290
+ }
291
+ return { person: [...found.person].sort(), organization: [...found.organization].sort() };
292
+ };
293
+ /** One pass per round: every page of the round reads the same list, so no id is skipped or read twice. */
294
+ let round;
295
+ const linkedRound = (started, send, context) => {
296
+ if (round?.started !== started) {
297
+ const ids = linkedOf(send, context);
298
+ ids.catch(() => {
299
+ if (round?.ids === ids)
300
+ round = undefined;
301
+ });
302
+ round = { started, ids };
303
+ }
304
+ return round.ids;
305
+ };
306
+ const readLinked = async (kind, page, context) => {
307
+ const { token, started } = pageOf(page, now());
308
+ const from = token === undefined ? 0 : Number(token);
309
+ if (!Number.isSafeInteger(from) || from < 0)
310
+ return { reset: true };
311
+ const send = metered(context);
312
+ const ids = (await linkedRound(started, send, context))[kind];
313
+ const items = [];
314
+ for (const externalId of ids.slice(from, from + LINKED_PAGE)) {
315
+ const one = await readOne(kind, externalId, send, context);
316
+ if (one)
317
+ items.push(one);
318
+ }
319
+ const next = from + LINKED_PAGE;
320
+ return next < ids.length
321
+ ? { items, hasMore: true, nextCursor: `${next}@${started}` }
322
+ : { items, hasMore: false, cursor: new Date(started).toISOString() };
323
+ };
250
324
  const readIds = async (kind, page, context) => {
251
325
  const entity = entityOf(kind);
326
+ if (entity.linked && (kind === "person" || kind === "organization"))
327
+ return { items: (await linkedOf(metered(context), context))[kind], hasMore: false };
252
328
  const { rows, next } = await readPage(entity.ids ?? entity.list, {}, page, metered(context));
253
329
  const items = rows.flatMap((raw) => {
254
330
  const found = evaluate(entity.map.externalId, raw);
@@ -335,22 +411,7 @@ export const crmSourceFromManifest = (input, options) => {
335
411
  },
336
412
  ...(live.length ? { list: readLive } : {}),
337
413
  async get(kind, externalId, context) {
338
- const entity = entityOf(kind);
339
- if (!entity.get)
340
- return null;
341
- const send = metered(context);
342
- const defined = entity.custom ? await fieldsOf(kind, send, context) : [];
343
- let answer;
344
- try {
345
- answer = await send(entity.get.operation, inputOf(entity.get, { id: externalId, select: selectOf(kind, defined, context) }));
346
- }
347
- catch (error) {
348
- if (unseen(error))
349
- return null;
350
- throw error;
351
- }
352
- const raw = entity.get.items === undefined ? answer : at(answer, entity.get.items);
353
- return isRaw(raw) ? ((await mapped(kind, [raw], defined, send))[0] ?? null) : null;
414
+ return readOne(kind, externalId, metered(context), context);
354
415
  },
355
416
  ...(manifest.fields
356
417
  ? { fields: (kind, context) => fieldsOf(kind, metered(context), context) }
@@ -56,14 +56,19 @@ export const chunkFreshness = ({ orm }, { conversationPk, firstMessagePk, lastMe
56
56
  */
57
57
  export const purgeVectorHashes = (context, hashes) => {
58
58
  const { orm } = context;
59
- for (const hash of new Set(hashes)) {
59
+ const unique = new Set(hashes);
60
+ if (unique.size === 0)
61
+ return;
62
+ const models = orm.all(sql `SELECT DISTINCT model FROM embeddings`).map(({ model }) => model);
63
+ for (const hash of unique) {
60
64
  let offset = 0;
61
65
  let valid = false;
62
66
  for (;;) {
67
+ // `+` keeps SQLite on the hash index: by chunk type it read every conversation chunk for each hash.
63
68
  const candidates = orm.all(sql `SELECT k.chunkable_id AS conversation, r.first_message_id AS first,
64
69
  r.last_message_id AS last, r.text_start AS start, r.text_end AS end
65
70
  FROM chunks k JOIN chunk_messages r ON r.chunk_id = k.id
66
- JOIN conversations c ON k.chunkable_type = 'conversation' AND c.id = k.chunkable_id
71
+ JOIN conversations c ON +k.chunkable_type = 'conversation' AND c.id = k.chunkable_id
67
72
  JOIN conversation_state s ON s.chat_id = c.chat_id AND s.current_build = c.build
68
73
  WHERE k.content_hash = ${hash} ORDER BY k.chunkable_id, k.position LIMIT 100 OFFSET ${offset}`);
69
74
  valid = candidates.some(({ conversation, first, last, start, end }) => {
@@ -78,9 +83,11 @@ export const purgeVectorHashes = (context, hashes) => {
78
83
  break;
79
84
  }
80
85
  }
86
+ // By the full key, model first: by hash alone each delete read the whole key.
81
87
  if (!valid)
82
- orm.run(sql `DELETE FROM embeddings WHERE content_hash = ${hash}
83
- AND NOT EXISTS (SELECT 1 FROM chunks WHERE content_hash = ${hash} AND chunkable_type <> 'conversation')`);
88
+ for (const model of models)
89
+ orm.run(sql `DELETE FROM embeddings WHERE model = ${model} AND content_hash = ${hash}
90
+ AND NOT EXISTS (SELECT 1 FROM chunks WHERE content_hash = ${hash} AND chunkable_type <> 'conversation')`);
84
91
  }
85
92
  };
86
93
  export const purgeVectorsOf = (context, messagePk) => {
@@ -68,6 +68,8 @@ export interface TrackerManifestHooks {
68
68
  }
69
69
  /** The selection a call sends, as a tree: its own, else the operation's default; none for an operation over HTTP. */
70
70
  export declare const selectionOf: (one: TrackerOperationCall, api: ServiceApiManifest) => Selection | undefined;
71
+ /** The selection of one row: under the operation's `items` (a connection's `nodes`) or the call's own. */
72
+ export declare const rowSelection: (tree: Selection, items: string | undefined) => Selection | undefined;
71
73
  /**
72
74
  * The manifest checked against its shape and the generated API: each operation exists and reads, a list pages or
73
75
  * says where its rows are, a change call places `{since}`, and over GraphQL every path the map reads is selected, so
@@ -55,7 +55,7 @@ const selects = (tree, steps) => {
55
55
  return found === true ? rest.every((step) => /^\d+$/.test(step)) : selects(found, rest);
56
56
  };
57
57
  /** The selection of one row: under the operation's `items` (a connection's `nodes`) or the call's own. */
58
- const rowSelection = (tree, items) => {
58
+ export const rowSelection = (tree, items) => {
59
59
  let inside = tree;
60
60
  for (const step of items?.split(".") ?? [])
61
61
  inside = inside === true ? undefined : inside?.[step];
@@ -1,2 +1,3 @@
1
+ export { type TrackerManifestFake, type TrackerManifestFakeOptions, type TrackerManifestFixtureOptions, trackerManifestContract, trackerManifestFake, trackerManifestFixture, } from "./manifest-fake.js";
1
2
  export { exampleTrackerRows, type FakeTrackerRows, type FakeTrackerSource, type FakeTrackerSourceOptions, fakeTrackerSource, } from "./source.js";
2
3
  export { type TrackerSourceFaults, type TrackerSourceFixture, trackerSourceContract, } from "./source-contract.js";
@@ -1,2 +1,3 @@
1
+ export { trackerManifestContract, trackerManifestFake, trackerManifestFixture, } from "./manifest-fake.js";
1
2
  export { exampleTrackerRows, fakeTrackerSource, } from "./source.js";
2
3
  export { trackerSourceContract, } from "./source-contract.js";
@@ -0,0 +1,51 @@
1
+ import { type GraphqlFake, type SchemaNode } from "@wirecat/cli-base/codegen";
2
+ import { type ServiceApiManifest } from "../../cli/service-api-manifest.js";
3
+ import { crmValues } from "../../crm/index.js";
4
+ import { type TrackerKind } from "../../domain/tracker.js";
5
+ import type { ContractCase } from "../../meetings/index.js";
6
+ import { type TrackerManifestHooks } from "../manifest/manifest.js";
7
+ import { type TrackerSourceFixture } from "./source-contract.js";
8
+ type Definitions = Readonly<Record<string, SchemaNode>>;
9
+ export interface TrackerManifestFakeOptions {
10
+ /** The generated API manifest the source manifest names its operations in. */
11
+ api: ServiceApiManifest;
12
+ /** The generated schemas: rows are sampled from them, and every call and answer is checked against them. */
13
+ definitions: Definitions;
14
+ /** In place of the API manifest's first server. */
15
+ baseUrl?: string;
16
+ }
17
+ export interface TrackerManifestFake extends GraphqlFake {
18
+ /** The rows of each kind as the tracker holds them, every field any call of the kind selects; a test may change them. */
19
+ rows: Partial<Record<TrackerKind, crmValues.CrmRaw[]>>;
20
+ /** Moves one row's change time to now, for the next read of changes to list it. */
21
+ touch(kind: TrackerKind, id: string): void;
22
+ /** Archives one row now: listed only to a call that asks for archived rows, and read as changed. */
23
+ archive(kind: TrackerKind, id: string): void;
24
+ /** Deletes one row outright. */
25
+ remove(kind: TrackerKind, id: string): void;
26
+ }
27
+ /**
28
+ * A GraphQL tracker in memory, built from a source manifest and the generated API it names: cli-base's strict
29
+ * `graphqlFake` with three rows of each kind behind it. Each row holds the values the map reads where it reads them,
30
+ * links to rows of the kinds it points at, and is answered within each call's selection, Relay-paged two a page. A
31
+ * change read keeps the rows changed at or after its since, oldest first. A cursor the fake never gave, an unreadable
32
+ * since and a call no route of the manifest makes are refused and recorded.
33
+ */
34
+ export declare const trackerManifestFake: (input: unknown, options: TrackerManifestFakeOptions) => TrackerManifestFake;
35
+ export interface TrackerManifestFixtureOptions extends TrackerManifestFakeOptions {
36
+ hooks?: TrackerManifestHooks;
37
+ }
38
+ /**
39
+ * A `trackerSourceContract` fixture for a source built from a manifest, over `trackerManifestFake`: the source, the
40
+ * rows it holds, a dead cursor, the faults the manifest allows, and the fake itself, whose `refusals` a test asserts
41
+ * empty.
42
+ */
43
+ export declare const trackerManifestFixture: (manifest: unknown, options: TrackerManifestFixtureOptions) => TrackerSourceFixture & {
44
+ fake: TrackerManifestFake;
45
+ };
46
+ /**
47
+ * `trackerSourceContract` over `trackerManifestFixture`, each case failing too when the fake refused a call: what a
48
+ * generated test runs, `for (const { name, run } of trackerManifestContract(SOURCE, { api, definitions })) it(name, run)`.
49
+ */
50
+ export declare const trackerManifestContract: (manifest: unknown, options: TrackerManifestFixtureOptions) => ContractCase[];
51
+ export {};
@@ -0,0 +1,450 @@
1
+ import { graphqlFake, 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 { crmValues } from "../../crm/index.js";
5
+ import { at, evaluate, MISSING, rulePaths } from "../../crm/manifest/map.js";
6
+ import { resolve, step } from "../../crm/manifest/paths.js";
7
+ import { FAKE_MANIFEST_TOKEN } from "../../crm/testing/index.js";
8
+ import { STATE_TYPES } from "../../domain/tracker.js";
9
+ import { parseTrackerManifest, rowSelection, selectionOf, } from "../manifest/manifest.js";
10
+ import { TRACKER_FIELDS } from "../manifest/map.js";
11
+ import { trackerSourceFromManifest } from "../manifest/source.js";
12
+ import { trackerSourceContract } from "./source-contract.js";
13
+ /** Three rows in pages of two: every kind pages at least once, whatever `first` the manifest asks for. */
14
+ const ROWS = 3;
15
+ const PAGE = 2;
16
+ const SEEDED = Date.parse("2026-11-01T10:00:00Z");
17
+ /** Linear's argument; a call to an operation that takes it and leaves it unset sees no archived row. */
18
+ const ARCHIVED = "includeArchived";
19
+ const CURSOR = /^fake-page-(\d+)$/;
20
+ /** The kind an id field points at: an issue's assignee is a user, its labels are labels. */
21
+ const TARGETS = {
22
+ team: "team",
23
+ teams: "team",
24
+ state: "state",
25
+ label: "label",
26
+ labels: "label",
27
+ project: "project",
28
+ lead: "user",
29
+ assignee: "user",
30
+ creator: "user",
31
+ author: "user",
32
+ issue: "issue",
33
+ parent: "issue",
34
+ };
35
+ const SINCE = {
36
+ iso: (value) => Date.parse(value),
37
+ ms: (value) => (/^\d+$/.test(value) ? Number(value) : Number.NaN),
38
+ seconds: (value) => (/^\d+$/.test(value) ? Number(value) * 1000 : Number.NaN),
39
+ };
40
+ const idOf = (kind, n) => `${kind}-${n + 1}`;
41
+ const merge = (a, b) => Object.fromEntries([...new Set([...Object.keys(a), ...Object.keys(b)])].map((key) => {
42
+ const [x, y] = [a[key], b[key]];
43
+ if (x === undefined || x === true)
44
+ return [key, y ?? x ?? true];
45
+ return [key, y === undefined || y === true ? x : merge(x, y)];
46
+ }));
47
+ const project = (value, selection) => {
48
+ if (selection === true || value === null || value === undefined)
49
+ return value ?? null;
50
+ if (Array.isArray(value))
51
+ return value.map((one) => project(one, selection));
52
+ return Object.fromEntries(Object.entries(selection).map(([field, inner]) => [field, project(value[field], inner)]));
53
+ };
54
+ const fixedOf = (value, trail = []) => crmValues.isRaw(value)
55
+ ? Object.entries(value).flatMap(([key, inner]) => fixedOf(inner, [...trail, key]))
56
+ : /^\{\w+\}$/.test(String(value))
57
+ ? []
58
+ : [[trail.join("."), value]];
59
+ const placeOf = (value, placeholder, trail = []) => {
60
+ if (value === placeholder)
61
+ return trail.join(".");
62
+ if (!crmValues.isRaw(value))
63
+ return undefined;
64
+ for (const [key, inner] of Object.entries(value)) {
65
+ const found = placeOf(inner, placeholder, [...trail, key]);
66
+ if (found !== undefined)
67
+ return found;
68
+ }
69
+ return undefined;
70
+ };
71
+ const put = (row, path, value) => {
72
+ const keys = path.split(".");
73
+ const last = keys.pop();
74
+ let here = row;
75
+ for (const key of keys) {
76
+ if (!crmValues.isRaw(here[key]))
77
+ here[key] = {};
78
+ here = here[key];
79
+ }
80
+ here[last] = value;
81
+ };
82
+ /** The only filter the fake applies: a since on the change time. Any other would pass rows the tracker drops. */
83
+ const FILTER = "filter";
84
+ /**
85
+ * A GraphQL tracker in memory, built from a source manifest and the generated API it names: cli-base's strict
86
+ * `graphqlFake` with three rows of each kind behind it. Each row holds the values the map reads where it reads them,
87
+ * links to rows of the kinds it points at, and is answered within each call's selection, Relay-paged two a page. A
88
+ * change read keeps the rows changed at or after its since, oldest first. A cursor the fake never gave, an unreadable
89
+ * since and a call no route of the manifest makes are refused and recorded.
90
+ */
91
+ export const trackerManifestFake = (input, options) => {
92
+ const { api, definitions } = options;
93
+ const manifest = parseTrackerManifest(input, api);
94
+ const operations = new Map(api.operations.map((one) => [one.id, one]));
95
+ const own = [];
96
+ const operationOf = (call) => {
97
+ const found = operations.get(call.operation);
98
+ if (found?.binding.kind !== "graphql")
99
+ throw new Error(`${call.operation}: the tracker fake answers GraphQL operations only`);
100
+ return found;
101
+ };
102
+ const itemsOf = (call) => call.items ?? operationOf(call).pagination?.items;
103
+ const responseOf = (call) => {
104
+ const schema = operationOf(call).response?.schema;
105
+ return schema === undefined ? { type: "unknown" } : { type: "ref", ref: schema };
106
+ };
107
+ const nodeAt = (node, path) => (path?.split(".") ?? []).reduce((inner, key) => {
108
+ const found = inner && step(inner, key, definitions);
109
+ const resolved = found ? resolve(found, definitions) : undefined;
110
+ return resolved?.type === "array" ? resolved.items : (found ?? undefined);
111
+ }, node);
112
+ const sampled = (node, selection) => {
113
+ if (selection === true)
114
+ return sampleOf(node, definitions);
115
+ const found = resolve(node, definitions);
116
+ if (found.type === "array")
117
+ return [sampled(found.items, selection)];
118
+ return Object.fromEntries(Object.entries(selection).map(([name, inner]) => [
119
+ name,
120
+ sampled(step(found, name, definitions) ?? { type: "unknown" }, inner),
121
+ ]));
122
+ };
123
+ /** A value as the schema at its place takes it: a time as ISO text or epoch ms; `undefined` when it cannot. */
124
+ const typed = (node, value) => {
125
+ const found = node && resolve(node, definitions);
126
+ if (value === null)
127
+ return found === undefined || node?.nullable || found.nullable ? null : undefined;
128
+ // A text the schema keeps as an enum (Linear's project status type) is one of its values.
129
+ if (typeof value === "string" && found?.type === "string" && found.enum && !found.enum.includes(value))
130
+ return found.enum[0];
131
+ if (typeof value !== "object")
132
+ return value;
133
+ return found?.type === "integer" || found?.type === "number" ? value.ms : new Date(value.ms).toISOString();
134
+ };
135
+ const write = (row, item, path, value) => {
136
+ const written = typed(nodeAt(item, path), value);
137
+ if (written !== undefined)
138
+ put(row, path, written);
139
+ };
140
+ const pointed = (field) => {
141
+ const target = TARGETS[field];
142
+ return target && manifest.kinds.includes(target) ? idOf(target, 0) : `${field}-1`;
143
+ };
144
+ const sampleValue = (kind, field, n) => {
145
+ const type = TRACKER_FIELDS[kind][field];
146
+ if (field === "externalId")
147
+ return idOf(kind, n);
148
+ // A state of a type outside STATE_TYPES is dropped by the map, and its issues with it.
149
+ if (kind === "state" && field === "type")
150
+ return STATE_TYPES[n % STATE_TYPES.length];
151
+ switch (type) {
152
+ case "epoch":
153
+ return field === "createdAt" || field === "updatedAt" ? { ms: SEEDED + n * 60_000 } : null;
154
+ case "id":
155
+ return pointed(field);
156
+ case "number":
157
+ return n + 1;
158
+ case "bool":
159
+ return true;
160
+ case "day":
161
+ return `2026-11-0${n + 1}`;
162
+ default:
163
+ return `${field} ${n + 1}`;
164
+ }
165
+ };
166
+ const timePath = (kind, field) => {
167
+ const rule = manifest.entities[kind]?.map[field];
168
+ return typeof rule === "string" ? rule : typeof rule === "object" && "path" in rule ? rule.path : undefined;
169
+ };
170
+ const items = new Map();
171
+ const rows = {};
172
+ for (const kind of manifest.kinds) {
173
+ const entity = manifest.entities[kind];
174
+ const calls = [entity.list, entity.changes, entity.ids].filter((one) => one !== undefined);
175
+ const selection = calls
176
+ .map((call) => rowSelection(selectionOf(call, api) ?? {}, itemsOf(call)) ?? {})
177
+ .reduce((all, one) => merge(all, one), {});
178
+ const item = nodeAt(responseOf(entity.list), itemsOf(entity.list));
179
+ items.set(kind, item);
180
+ if (entity.changes && timePath(kind, "updatedAt") === undefined)
181
+ throw new Error(`${kind}: map updatedAt to a path, so the fake can read a change time`);
182
+ rows[kind] = Array.from({ length: ROWS }, (_, n) => {
183
+ const made = item ? sampled(item, selection) : {};
184
+ const row = crmValues.isRaw(made) ? made : {};
185
+ for (const [field, rule] of Object.entries(entity.map)) {
186
+ if (typeof rule === "function" || (typeof rule === "object" && "value" in rule && !("each" in rule)))
187
+ continue;
188
+ const [first, inside] = rulePaths(rule);
189
+ if (!first)
190
+ continue;
191
+ if (inside?.inside !== undefined) {
192
+ const one = {};
193
+ put(one, inside.path, pointed(field));
194
+ put(row, first.path, [one]);
195
+ }
196
+ else if (typeof rule === "object" && "map" in rule)
197
+ put(row, first.path, Object.keys(rule.map)[0] ?? null);
198
+ else
199
+ write(row, item, first.path, sampleValue(kind, field, n));
200
+ }
201
+ return row;
202
+ });
203
+ }
204
+ const filterProblem = (kind, call, place) => {
205
+ const filter = fixedOf(call.variables?.[FILTER] ?? {});
206
+ if (filter.length > 0)
207
+ return `${call.operation}: the fake cannot apply ${FILTER}.${filter[0]?.[0]}, so it would list rows the tracker drops`;
208
+ if (place === undefined)
209
+ return undefined;
210
+ const time = timePath(kind, "updatedAt");
211
+ const ends = [`${time}.gte`, `${time}.gt`];
212
+ if (!ends.some((end) => place === end || place.endsWith(`.${end}`)))
213
+ return `${call.operation}: {since} at ${place} is not ${time}.gte or ${time}.gt, the change time the map reads`;
214
+ return undefined;
215
+ };
216
+ const routes = manifest.kinds.flatMap((kind) => {
217
+ const entity = manifest.entities[kind];
218
+ const plain = (call) => {
219
+ const problem = call.variables && FILTER in call.variables
220
+ ? `${call.operation}: a list or id read with a ${FILTER} leaves rows out, and sync would mark them deleted`
221
+ : undefined;
222
+ return { kind, call, ...(problem ? { problem } : {}) };
223
+ };
224
+ const changes = entity.changes;
225
+ const place = changes && placeOf(changes.variables, "{since}");
226
+ const problem = changes && filterProblem(kind, changes, place);
227
+ return [
228
+ plain(entity.list),
229
+ ...(entity.ids ? [plain(entity.ids)] : []),
230
+ ...(changes && place
231
+ ? [
232
+ {
233
+ kind,
234
+ call: changes,
235
+ since: { place, format: changes.since, after: place.endsWith(".gt") },
236
+ ...(problem ? { problem } : {}),
237
+ },
238
+ ]
239
+ : []),
240
+ ];
241
+ });
242
+ /** A page's size and place are the engine's to set, whatever the template says. */
243
+ const paging = (operation, key) => {
244
+ const pagination = operations.get(operation)?.pagination;
245
+ return pagination?.style === "cursor" && [pagination.cursor.name, pagination.limit?.name].includes(key);
246
+ };
247
+ const fixed = (route) => fixedOf(route.call.variables ?? {}).filter(([key]) => !paging(route.call.operation, key));
248
+ const matches = (route, call) => route.call.operation === call.operation &&
249
+ fixed(route).every(([key, value]) => JSON.stringify(at(call.variables, key)) === JSON.stringify(value)) &&
250
+ (!route.since || at(call.variables, route.since.place) !== undefined);
251
+ /** A change read wins over a list when its since was sent; else the route that fixes the most values. */
252
+ const routeOf = (call) => routes
253
+ .filter((route) => matches(route, call))
254
+ .sort((a, b) => Number(!!b.since) - Number(!!a.since) || fixed(b).length - fixed(a).length)[0];
255
+ const find = (kind, id) => {
256
+ const found = rows[kind]?.find((row) => externalIdOf(manifest, kind, row) === id);
257
+ if (!found)
258
+ throw new Error(`the fake holds no ${kind} ${id}`);
259
+ return found;
260
+ };
261
+ const timeOf = (kind, row, field) => {
262
+ const path = timePath(kind, field);
263
+ const value = path === undefined ? null : at(row, path);
264
+ return typeof value === "number" ? value : typeof value === "string" ? Date.parse(value) : null;
265
+ };
266
+ const stamp = (kind, row, field) => {
267
+ const path = timePath(kind, field);
268
+ if (path === undefined)
269
+ throw new Error(`${kind}: map ${field} to a path, so the fake can write it`);
270
+ write(row, items.get(kind), path, { ms: Date.now() });
271
+ };
272
+ const refuse = (message) => {
273
+ own.push(message);
274
+ return { status: 400, errors: [{ message, extensions: { code: "FAKE_REFUSED" } }] };
275
+ };
276
+ const answer = (call) => {
277
+ const route = routeOf(call);
278
+ if (!route)
279
+ return refuse(`${call.operation}: no call of the source manifest sends these variables`);
280
+ if (route.problem)
281
+ return refuse(route.problem);
282
+ const { kind } = route;
283
+ const operation = operationOf(route.call);
284
+ const hidesArchived = operation.binding.kind === "graphql" && ARCHIVED in operation.binding.variables;
285
+ let listed = (rows[kind] ?? []).filter((row) => !hidesArchived || call.variables[ARCHIVED] === true || !Number.isFinite(timeOf(kind, row, "archivedAt") ?? NaN));
286
+ if (route.since) {
287
+ const sent = String(at(call.variables, route.since.place));
288
+ const from = SINCE[route.since.format](sent);
289
+ if (!Number.isFinite(from))
290
+ return refuse(`${call.operation}: since ${sent} is unreadable`);
291
+ listed = listed
292
+ .filter((row) => {
293
+ const time = timeOf(kind, row, "updatedAt") ?? Number.NEGATIVE_INFINITY;
294
+ return route.since?.after ? time > from : time >= from;
295
+ })
296
+ .sort((a, b) => (timeOf(kind, a, "updatedAt") ?? 0) - (timeOf(kind, b, "updatedAt") ?? 0));
297
+ }
298
+ const selection = call.selection ?? {};
299
+ const where = itemsOf(route.call);
300
+ const inner = rowSelection(selection, where) ?? true;
301
+ const pagination = operation.pagination;
302
+ if (where === undefined)
303
+ return { data: listed.map((row) => project(row, inner)) };
304
+ const made = sampled(responseOf(route.call), selection);
305
+ const body = crmValues.isRaw(made) ? made : {};
306
+ if (pagination && pagination.style !== "cursor")
307
+ throw new Error(`${call.operation}: the tracker fake pages by a cursor only, not by ${pagination.style}`);
308
+ if (!pagination) {
309
+ put(body, where, listed.map((row) => project(row, inner)));
310
+ return { data: project(body, selection) };
311
+ }
312
+ const sent = call.variables[pagination.cursor.name];
313
+ const offset = sent === undefined || sent === null ? 0 : Number(CURSOR.exec(String(sent))?.[1] ?? Number.NaN);
314
+ if (!Number.isSafeInteger(offset))
315
+ return refuse(`${call.operation}: ${String(sent)} is not a cursor this fake gave`);
316
+ const limit = pagination.limit ? Number(call.variables[pagination.limit.name]) : Number.NaN;
317
+ const size = Number.isSafeInteger(limit) && limit > 0 ? Math.min(limit, PAGE) : PAGE;
318
+ const more = offset + size < listed.length;
319
+ put(body, where, listed.slice(offset, offset + size).map((row) => project(row, inner)));
320
+ put(body, pagination.next, more ? `fake-page-${offset + size}` : null);
321
+ if (pagination.hasMore)
322
+ put(body, pagination.hasMore, more);
323
+ return { data: project(body, selection) };
324
+ };
325
+ const scheme = Object.values(api.securitySchemes ?? {})[0];
326
+ const fake = graphqlFake({
327
+ operations: api.operations,
328
+ definitions,
329
+ url: options.baseUrl ?? manifestBaseUrl(api),
330
+ ...(scheme
331
+ ? {
332
+ auth: scheme.type === "apiKey" && scheme.in === "header" && scheme.name
333
+ ? { header: scheme.name, value: FAKE_MANIFEST_TOKEN }
334
+ : { header: "Authorization", value: `Bearer ${FAKE_MANIFEST_TOKEN}` },
335
+ }
336
+ : {}),
337
+ answers: Object.fromEntries(routes.map((route) => [route.call.operation, answer])),
338
+ });
339
+ return {
340
+ // An answer of the fake's own that breaks the schema throws inside fetch, which the source reports as a network
341
+ // error; the refusal names it.
342
+ fetch: (input, init) => fake.fetch(input, init).catch((error) => {
343
+ own.push(error instanceof Error ? error.message : String(error));
344
+ throw error;
345
+ }),
346
+ calls: fake.calls,
347
+ get refusals() {
348
+ return [...fake.refusals, ...own];
349
+ },
350
+ rows,
351
+ touch: (kind, id) => stamp(kind, find(kind, id), "updatedAt"),
352
+ archive(kind, id) {
353
+ const row = find(kind, id);
354
+ stamp(kind, row, "archivedAt");
355
+ stamp(kind, row, "updatedAt");
356
+ },
357
+ remove(kind, id) {
358
+ const row = find(kind, id);
359
+ rows[kind]?.splice(rows[kind].indexOf(row), 1);
360
+ },
361
+ };
362
+ };
363
+ const externalIdOf = (manifest, kind, row) => {
364
+ const rule = manifest.entities[kind]?.map.externalId;
365
+ const found = rule === undefined ? MISSING : evaluate(rule, row);
366
+ return found === MISSING ? null : crmValues.id(found);
367
+ };
368
+ /**
369
+ * A `trackerSourceContract` fixture for a source built from a manifest, over `trackerManifestFake`: the source, the
370
+ * rows it holds, a dead cursor, the faults the manifest allows, and the fake itself, whose `refusals` a test asserts
371
+ * empty.
372
+ */
373
+ export const trackerManifestFixture = (manifest, options) => {
374
+ const fake = trackerManifestFake(manifest, options);
375
+ const parsed = parseTrackerManifest(manifest, options.api);
376
+ const call = serviceApiCall({
377
+ manifest: options.api,
378
+ service: parsed.provider,
379
+ fetch: fake.fetch,
380
+ token: () => FAKE_MANIFEST_TOKEN,
381
+ ...(options.baseUrl ? { baseUrl: options.baseUrl } : {}),
382
+ });
383
+ const sourceAt = (now = Date.now) => trackerSourceFromManifest(manifest, {
384
+ api: options.api,
385
+ call,
386
+ now,
387
+ ...(options.hooks ? { hooks: options.hooks } : {}),
388
+ });
389
+ const held = Object.fromEntries(parsed.kinds.map((kind) => [kind, (fake.rows[kind] ?? []).map((row) => externalIdOf(parsed, kind, row))]));
390
+ // An issue first: the kind a tracker's changes matter most for. Its last row is the one archived or removed, which
391
+ // no other row points at.
392
+ const changed = ["issue", ...[...parsed.kinds].reverse()].find((kind) => parsed.kinds.includes(kind) && parsed.entities[kind]?.changes);
393
+ const archivable = changed && parsed.entities[changed]?.map.archivedAt !== undefined;
394
+ const first = (kind) => held[kind]?.[0];
395
+ const last = (kind) => held[kind]?.at(-1);
396
+ return {
397
+ source: sourceAt(),
398
+ fake,
399
+ held,
400
+ deadCursor: { kind: parsed.kinds[0], cursor: "not a time" },
401
+ faults: {
402
+ remove: () => {
403
+ const kind = changed ?? parsed.kinds.at(-1);
404
+ fake.remove(kind, last(kind));
405
+ return { kind, id: last(kind) };
406
+ },
407
+ ...(changed
408
+ ? {
409
+ skewed: (ms) => sourceAt(() => Date.now() + ms),
410
+ change: () => {
411
+ fake.touch(changed, first(changed));
412
+ return { kind: changed, id: first(changed) };
413
+ },
414
+ }
415
+ : {}),
416
+ ...(changed && archivable
417
+ ? {
418
+ archive: () => {
419
+ fake.archive(changed, last(changed));
420
+ return { kind: changed, id: last(changed) };
421
+ },
422
+ }
423
+ : {}),
424
+ },
425
+ };
426
+ };
427
+ /**
428
+ * `trackerSourceContract` over `trackerManifestFixture`, each case failing too when the fake refused a call: what a
429
+ * generated test runs, `for (const { name, run } of trackerManifestContract(SOURCE, { api, definitions })) it(name, run)`.
430
+ */
431
+ export const trackerManifestContract = (manifest, options) => {
432
+ const fakes = [];
433
+ return trackerSourceContract(() => {
434
+ const fixture = trackerManifestFixture(manifest, options);
435
+ fakes.push(fixture.fake);
436
+ return fixture;
437
+ }).map(({ name, run }) => ({
438
+ name,
439
+ async run() {
440
+ fakes.length = 0;
441
+ const failed = await run().then(() => undefined, (error) => error);
442
+ // A refused call fails the source too; the refusal says why, its error only that the tracker said no.
443
+ const refused = fakes.flatMap((fake) => fake.refusals);
444
+ if (refused.length)
445
+ throw new Error(`the fake refused calls the source made:\n${refused.join("\n")}`, { cause: failed });
446
+ if (failed)
447
+ throw failed;
448
+ },
449
+ }));
450
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.700.0",
3
+ "version": "0.702.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",