@wirecat/cli-core 0.722.0 → 0.724.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/dist/cli/documents/history.js +2 -2
  3. package/dist/cli/documents/words.d.ts +1 -1
  4. package/dist/cli/service-api-call.d.ts +6 -0
  5. package/dist/cli/service-api-call.js +21 -9
  6. package/dist/cli/service-api.d.ts +5 -0
  7. package/dist/cli/service-api.js +11 -0
  8. package/dist/content/writes.d.ts +3 -9
  9. package/dist/content/writes.js +3 -13
  10. package/dist/crm/index.d.ts +3 -2
  11. package/dist/crm/index.js +1 -0
  12. package/dist/crm/manifest/manifest.d.ts +60 -1
  13. package/dist/crm/manifest/manifest.js +88 -0
  14. package/dist/crm/manifest/source.d.ts +22 -3
  15. package/dist/crm/manifest/source.js +10 -3
  16. package/dist/crm/manifest/writer.d.ts +39 -0
  17. package/dist/crm/manifest/writer.js +298 -0
  18. package/dist/crm/testing/index.d.ts +1 -1
  19. package/dist/crm/testing/index.js +1 -1
  20. package/dist/crm/testing/manifest-fake.d.ts +14 -0
  21. package/dist/crm/testing/manifest-fake.js +252 -27
  22. package/dist/crm/writes.d.ts +4 -13
  23. package/dist/crm/writes.js +2 -9
  24. package/dist/errors/reasons.js +5 -0
  25. package/dist/ports/wirecat-tools.js +7 -0
  26. package/dist/sends/profile-writes.d.ts +22 -0
  27. package/dist/sends/profile-writes.js +20 -0
  28. package/dist/tracker/cli/index.d.ts +10 -1
  29. package/dist/tracker/cli/index.js +20 -1
  30. package/dist/tracker/cli/writes.d.ts +27 -0
  31. package/dist/tracker/cli/writes.js +74 -0
  32. package/dist/tracker/index.d.ts +5 -2
  33. package/dist/tracker/index.js +5 -2
  34. package/dist/tracker/manifest/manifest.d.ts +25 -0
  35. package/dist/tracker/manifest/manifest.js +59 -8
  36. package/dist/tracker/manifest/source.d.ts +10 -1
  37. package/dist/tracker/manifest/source.js +12 -9
  38. package/dist/tracker/manifest/writer.d.ts +20 -0
  39. package/dist/tracker/manifest/writer.js +72 -0
  40. package/dist/tracker/sync.d.ts +5 -0
  41. package/dist/tracker/sync.js +12 -0
  42. package/dist/tracker/testing/index.d.ts +3 -1
  43. package/dist/tracker/testing/index.js +3 -1
  44. package/dist/tracker/testing/manifest-fake.d.ts +2 -0
  45. package/dist/tracker/testing/manifest-fake.js +123 -41
  46. package/dist/tracker/testing/manifest-writes.d.ts +16 -0
  47. package/dist/tracker/testing/manifest-writes.js +70 -0
  48. package/dist/tracker/testing/source.d.ts +9 -1
  49. package/dist/tracker/testing/source.js +63 -0
  50. package/dist/tracker/testing/write-contract.d.ts +20 -0
  51. package/dist/tracker/testing/write-contract.js +94 -0
  52. package/dist/tracker/writer.d.ts +57 -0
  53. package/dist/tracker/writer.js +25 -0
  54. package/dist/tracker/writes.d.ts +53 -0
  55. package/dist/tracker/writes.js +226 -0
  56. package/package.json +1 -1
@@ -6,7 +6,7 @@ import { at, evaluate, MISSING, rulePaths } from "../../crm/manifest/map.js";
6
6
  import { resolve, step } from "../../crm/manifest/paths.js";
7
7
  import { FAKE_MANIFEST_TOKEN } from "../../crm/testing/index.js";
8
8
  import { STATE_TYPES } from "../../domain/tracker.js";
9
- import { parseTrackerManifest, rowSelection, selectionOf, } from "../manifest/manifest.js";
9
+ import { parseTrackerManifest, rowSelection, selectionOf, TRACKER_WRITE_FIELDS, } from "../manifest/manifest.js";
10
10
  import { TRACKER_FIELDS } from "../manifest/map.js";
11
11
  import { trackerSourceFromManifest } from "../manifest/source.js";
12
12
  import { trackerSourceContract } from "./source-contract.js";
@@ -167,39 +167,49 @@ export const trackerManifestFake = (input, options) => {
167
167
  const rule = manifest.entities[kind]?.map[field];
168
168
  return typeof rule === "string" ? rule : typeof rule === "object" && "path" in rule ? rule.path : undefined;
169
169
  };
170
+ const writeCalls = (kind) => {
171
+ const one = manifest.writes?.[kind];
172
+ return [one?.create, one?.update].filter((call) => call !== undefined);
173
+ };
170
174
  const items = new Map();
175
+ const selections = new Map();
171
176
  const rows = {};
177
+ const seed = (kind, n) => {
178
+ const entity = manifest.entities[kind];
179
+ const item = items.get(kind);
180
+ const made = item ? sampled(item, selections.get(kind) ?? {}) : {};
181
+ const row = crmValues.isRaw(made) ? made : {};
182
+ for (const [field, rule] of Object.entries(entity.map)) {
183
+ if (typeof rule === "function" || (typeof rule === "object" && "value" in rule && !("each" in rule)))
184
+ continue;
185
+ const [first, inside] = rulePaths(rule);
186
+ if (!first)
187
+ continue;
188
+ if (inside?.inside !== undefined) {
189
+ const one = {};
190
+ put(one, inside.path, pointed(field));
191
+ put(row, first.path, [one]);
192
+ }
193
+ else if (typeof rule === "object" && "map" in rule)
194
+ put(row, first.path, Object.keys(rule.map)[0] ?? null);
195
+ else
196
+ write(row, item, first.path, sampleValue(kind, field, n));
197
+ }
198
+ return row;
199
+ };
172
200
  for (const kind of manifest.kinds) {
173
201
  const entity = manifest.entities[kind];
174
202
  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);
203
+ // A written row is answered within the write's selection too, so the rows hold what it reads.
204
+ const selection = [
205
+ ...calls.map((call) => rowSelection(selectionOf(call, api) ?? {}, itemsOf(call)) ?? {}),
206
+ ...writeCalls(kind).map((call) => rowSelection(selectionOf(call, api) ?? {}, call.items) ?? {}),
207
+ ].reduce((all, one) => merge(all, one), {});
208
+ selections.set(kind, selection);
209
+ items.set(kind, nodeAt(responseOf(entity.list), itemsOf(entity.list)));
180
210
  if (entity.changes && timePath(kind, "updatedAt") === undefined)
181
211
  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
- });
212
+ rows[kind] = Array.from({ length: ROWS }, (_, n) => seed(kind, n));
203
213
  }
204
214
  const filterProblem = (kind, call, place) => {
205
215
  const filter = fixedOf(call.variables?.[FILTER] ?? {});
@@ -331,6 +341,76 @@ export const trackerManifestFake = (input, options) => {
331
341
  put(body, self.path, pointed("assignee"));
332
342
  return { data: project(body, selection) };
333
343
  };
344
+ /** One of our fields onto a row where the map reads it: a list of ids under its `each`, a cleared link as null. */
345
+ const assign = (kind, row, field, value) => {
346
+ const rule = manifest.entities[kind]?.map[field];
347
+ const [first, inside] = rulePaths(rule);
348
+ if (!first)
349
+ return;
350
+ if (inside?.inside !== undefined && Array.isArray(value))
351
+ put(row, first.path, value.map((id) => {
352
+ const one = {};
353
+ put(one, inside.path, id);
354
+ return one;
355
+ }));
356
+ else if (value === null && TRACKER_FIELDS[kind][field] === "id" && first.path.includes("."))
357
+ put(row, first.path.slice(0, first.path.lastIndexOf(".")), null);
358
+ else
359
+ write(row, items.get(kind), first.path, value);
360
+ };
361
+ const writeRoutes = Object.keys(manifest.writes ?? {}).flatMap((kind) => {
362
+ const one = manifest.writes?.[kind];
363
+ return ["create", "update"].flatMap((verb) => {
364
+ const call = one?.[verb];
365
+ return call ? [{ kind, verb, call, fields: one.fields }] : [];
366
+ });
367
+ });
368
+ /**
369
+ * A create adds a row, an update changes the row its `"{id}"` names; each answers the row within the call's
370
+ * selection. The variables were checked against the schema first, as the tracker checks them.
371
+ */
372
+ const answerWrite = (call) => {
373
+ const route = writeRoutes.find((one) => one.call.operation === call.operation);
374
+ if (!route)
375
+ return refuse(`${call.operation}: no write of the source manifest sends it`);
376
+ const { kind } = route;
377
+ const values = at(call.variables, placeOf(route.call.variables, "{values}"));
378
+ if (!crmValues.isRaw(values))
379
+ return refuse(`${call.operation}: no "{values}" object in its variables`);
380
+ const named = new Set(Object.values(route.fields).map(({ to }) => to.split(".")[0]));
381
+ const stray = Object.keys(values).find((key) => !named.has(key));
382
+ if (stray)
383
+ return refuse(`${call.operation}: ${stray} is not a field the manifest writes`);
384
+ let row;
385
+ if (route.verb === "create") {
386
+ row = seed(kind, rows[kind]?.length ?? 0);
387
+ // What the tracker sets itself (the key, the creator, the times) keeps its sample; the rest is what was sent.
388
+ for (const field of TRACKER_WRITE_FIELDS[kind])
389
+ assign(kind, row, field, field === "labels" ? [] : null);
390
+ rows[kind] ??= [];
391
+ rows[kind].push(row);
392
+ }
393
+ else {
394
+ const id = at(call.variables, placeOf(route.call.variables, "{id}"));
395
+ row = rows[kind]?.find((one) => externalIdOf(manifest, kind, one) === id);
396
+ // The tracker's own refusal, not the fake's: an issue deleted since the last sync.
397
+ if (!row)
398
+ return { errors: [{ message: `Entity not found: ${String(id)}`, extensions: { code: "INVALID_INPUT" } }] };
399
+ }
400
+ for (const [field, rule] of Object.entries(route.fields)) {
401
+ const value = at(values, rule.to);
402
+ if (value !== undefined)
403
+ assign(kind, row, field, value);
404
+ }
405
+ stamp(kind, row, "updatedAt");
406
+ const selection = call.selection ?? {};
407
+ const made = sampled(responseOf(route.call), selection);
408
+ const body = crmValues.isRaw(made) ? made : {};
409
+ if (route.call.items === undefined)
410
+ return { data: project(row, selection) };
411
+ put(body, route.call.items, project(row, rowSelection(selection, route.call.items) ?? true));
412
+ return { data: project(body, selection) };
413
+ };
334
414
  const scheme = Object.values(api.securitySchemes ?? {})[0];
335
415
  const fake = graphqlFake({
336
416
  operations: api.operations,
@@ -346,6 +426,7 @@ export const trackerManifestFake = (input, options) => {
346
426
  answers: {
347
427
  ...Object.fromEntries(routes.map((route) => [route.call.operation, answer])),
348
428
  ...(manifest.self ? { [manifest.self.call.operation]: answerSelf } : {}),
429
+ ...Object.fromEntries(writeRoutes.map((route) => [route.call.operation, answerWrite])),
349
430
  },
350
431
  });
351
432
  return {
@@ -442,21 +523,22 @@ export const trackerManifestFixture = (manifest, options) => {
442
523
  */
443
524
  export const trackerManifestContract = (manifest, options) => {
444
525
  const fakes = [];
445
- return trackerSourceContract(() => {
526
+ return failingOnRefusals(trackerSourceContract(() => {
446
527
  const fixture = trackerManifestFixture(manifest, options);
447
528
  fakes.push(fixture.fake);
448
529
  return fixture;
449
- }).map(({ name, run }) => ({
450
- name,
451
- async run() {
452
- fakes.length = 0;
453
- const failed = await run().then(() => undefined, (error) => error);
454
- // A refused call fails the source too; the refusal says why, its error only that the tracker said no.
455
- const refused = fakes.flatMap((fake) => fake.refusals);
456
- if (refused.length)
457
- throw new Error(`the fake refused calls the source made:\n${refused.join("\n")}`, { cause: failed });
458
- if (failed)
459
- throw failed;
460
- },
461
- }));
530
+ }), fakes);
462
531
  };
532
+ /** Each case failing too when a fake it built refused a call: the refusal says why, the error only that it was refused. */
533
+ export const failingOnRefusals = (cases, fakes) => cases.map(({ name, run }) => ({
534
+ name,
535
+ async run() {
536
+ fakes.length = 0;
537
+ const failed = await run().then(() => undefined, (error) => error);
538
+ const refused = fakes.flatMap((fake) => fake.refusals);
539
+ if (refused.length)
540
+ throw new Error(`the fake refused calls the source made:\n${refused.join("\n")}`, { cause: failed });
541
+ if (failed)
542
+ throw failed;
543
+ },
544
+ }));
@@ -0,0 +1,16 @@
1
+ import type { ContractCase } from "../../meetings/index.js";
2
+ import { type TrackerManifestFake, type TrackerManifestFakeOptions } from "./manifest-fake.js";
3
+ import { type TrackerWriteFixture } from "./write-contract.js";
4
+ /**
5
+ * A `trackerWriteContract` fixture for a writer built from a manifest's `writes`, over `trackerManifestFake`: the
6
+ * variables of each write are checked against the generated schema (an unknown field, a missing required one), and
7
+ * the fake's `refusals` say why.
8
+ */
9
+ export declare const trackerManifestWriteFixture: (manifest: unknown, options: TrackerManifestFakeOptions) => TrackerWriteFixture & {
10
+ fake: TrackerManifestFake;
11
+ };
12
+ /**
13
+ * `trackerWriteContract` over `trackerManifestWriteFixture`, each case failing too when the fake refused a call: what
14
+ * a generated test runs, `for (const { name, run } of trackerManifestWriteContract(SOURCE, { api, definitions }))`.
15
+ */
16
+ export declare const trackerManifestWriteContract: (manifest: unknown, options: TrackerManifestFakeOptions) => ContractCase[];
@@ -0,0 +1,70 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { Command } from "commander";
3
+ import { serviceApiCall } from "../../cli/service-api-call.js";
4
+ import { crmValues } from "../../crm/index.js";
5
+ import { FAKE_MANIFEST_TOKEN } from "../../crm/testing/index.js";
6
+ import { parseTrackerManifest } from "../manifest/manifest.js";
7
+ import { trackerWriterFromManifest } from "../manifest/writer.js";
8
+ import { failingOnRefusals, trackerManifestFake, } from "./manifest-fake.js";
9
+ import { trackerWriteContract } from "./write-contract.js";
10
+ /**
11
+ * A `trackerWriteContract` fixture for a writer built from a manifest's `writes`, over `trackerManifestFake`: the
12
+ * variables of each write are checked against the generated schema (an unknown field, a missing required one), and
13
+ * the fake's `refusals` say why.
14
+ */
15
+ export const trackerManifestWriteFixture = (manifest, options) => {
16
+ const fake = trackerManifestFake(manifest, options);
17
+ const parsed = parseTrackerManifest(manifest, options.api);
18
+ // serviceApiCall sends reads only; through it a write is built and signed as the CLI's serviceApiWriter builds it,
19
+ // without the profile's guard, which the tracker writes hold above the writer.
20
+ const call = serviceApiCall({
21
+ manifest: { ...options.api, operations: options.api.operations.map((one) => ({ ...one, effect: "read" })) },
22
+ service: parsed.provider,
23
+ fetch: fake.fetch,
24
+ token: () => FAKE_MANIFEST_TOKEN,
25
+ ...(options.baseUrl ? { baseUrl: options.baseUrl } : {}),
26
+ });
27
+ const writeOperations = new Set(Object.values(parsed.writes ?? {}).flatMap((one) => [one?.create, one?.update].flatMap((sent) => (sent ? [sent.operation] : []))));
28
+ let lose = false;
29
+ const write = async (_command, operation, input) => {
30
+ const result = await call(operation, input);
31
+ if (lose) {
32
+ lose = false;
33
+ throw new CliError("outcome_unknown", "the connection dropped after the tracker got the write");
34
+ }
35
+ return { operation_id: `fake-${fake.calls.length}`, result };
36
+ };
37
+ const idOf = (kind) => {
38
+ const row = fake.rows[kind]?.[0];
39
+ const rule = parsed.entities[kind]?.map.externalId;
40
+ const id = row && typeof rule === "string" ? crmValues.id(row[rule]) : null;
41
+ if (id === null)
42
+ throw new Error(`the fake holds no ${kind} to write with`);
43
+ return id;
44
+ };
45
+ return {
46
+ writer: trackerWriterFromManifest(manifest, { api: options.api, write, command: new Command("fake") }),
47
+ fake,
48
+ team: idOf("team"),
49
+ state: idOf("state"),
50
+ user: idOf("user"),
51
+ label: idOf("label"),
52
+ project: idOf("project"),
53
+ loseNextAnswer: () => {
54
+ lose = true;
55
+ },
56
+ requests: () => fake.calls.filter((one) => one.operation && writeOperations.has(one.operation)).length,
57
+ };
58
+ };
59
+ /**
60
+ * `trackerWriteContract` over `trackerManifestWriteFixture`, each case failing too when the fake refused a call: what
61
+ * a generated test runs, `for (const { name, run } of trackerManifestWriteContract(SOURCE, { api, definitions }))`.
62
+ */
63
+ export const trackerManifestWriteContract = (manifest, options) => {
64
+ const fakes = [];
65
+ return failingOnRefusals(trackerWriteContract(() => {
66
+ const fixture = trackerManifestWriteFixture(manifest, options);
67
+ fakes.push(fixture.fake);
68
+ return fixture;
69
+ }), fakes);
70
+ };
@@ -1,5 +1,6 @@
1
1
  import type { TrackerKind, TrackerRecords } from "../../domain/tracker.js";
2
2
  import type { TrackerSource } from "../source.js";
3
+ import { type TrackerWrite, type TrackerWriter } from "../writer.js";
3
4
  export type FakeTrackerRows = {
4
5
  [K in TrackerKind]?: TrackerRecords[K][];
5
6
  };
@@ -14,7 +15,14 @@ export interface FakeTrackerSourceOptions {
14
15
  /** The signed-in user's id, which `self()` answers; absent, the tracker cannot say. */
15
16
  self?: string;
16
17
  }
17
- export interface FakeTrackerSource extends TrackerSource {
18
+ export interface FakeTrackerSource extends TrackerSource, TrackerWriter {
19
+ /** Each write that reached the tracker, in order. */
20
+ sent: {
21
+ write: TrackerWrite;
22
+ id: string;
23
+ }[];
24
+ /** The next write is made, and its answer lost, as a dropped connection does. */
25
+ loseNextAnswer(): void;
18
26
  /** Changes one row on the tracker's side: it gets a new `updatedAt`. */
19
27
  touch(kind: TrackerKind, externalId: string): void;
20
28
  archive(kind: TrackerKind, externalId: string): void;
@@ -1,4 +1,5 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
+ import { TRACKER_WRITES } from "../writer.js";
2
3
  const OVERLAP_MS = 10 * 60_000;
3
4
  /**
4
5
  * A tracker in memory, read the way a GraphQL tracker is: changes by `updatedAt` from the cursor less an overlap, pages
@@ -18,6 +19,22 @@ export const fakeTrackerSource = (options) => {
18
19
  return found;
19
20
  };
20
21
  const self = options.self;
22
+ const sent = [];
23
+ let lose = false;
24
+ const made = (write, id) => {
25
+ sent.push({ write, id });
26
+ if (!lose)
27
+ return;
28
+ lose = false;
29
+ throw new CliError("outcome_unknown", "the connection dropped after the tracker got the write");
30
+ };
31
+ const apply = (issue, fields) => {
32
+ for (const [field, value] of Object.entries(fields))
33
+ if (value !== undefined)
34
+ Object.assign(issue, { [field]: value });
35
+ issue.updatedAt = clock();
36
+ return { ...issue };
37
+ };
21
38
  const make = (skew) => ({
22
39
  provider: options.provider ?? "fake-tracker",
23
40
  traits: { kinds: Object.keys(rows).filter((kind) => listOf(kind).length > 0) },
@@ -64,6 +81,52 @@ export const fakeTrackerSource = (options) => {
64
81
  list?.splice(at, 1);
65
82
  },
66
83
  skewed: (ms) => make(ms),
84
+ sent,
85
+ loseNextAnswer() {
86
+ lose = true;
87
+ },
88
+ writes: TRACKER_WRITES,
89
+ async createIssue(draft) {
90
+ rows.issue ??= [];
91
+ const issues = rows.issue;
92
+ const team = (rows.team ?? []).find((one) => one.externalId === draft.team);
93
+ const number = issues.length + 1;
94
+ const issue = {
95
+ externalId: `issue-${number}`,
96
+ key: `${team?.key ?? "ISS"}-${number}`,
97
+ labels: [],
98
+ creator: self ?? null,
99
+ createdAt: clock(),
100
+ title: draft.title,
101
+ };
102
+ issues.push(issue);
103
+ const answer = apply(issue, draft);
104
+ made("create", issue.externalId);
105
+ return answer;
106
+ },
107
+ async updateIssue(externalId, patch) {
108
+ const found = (rows.issue ?? []).find((one) => one.externalId === externalId);
109
+ if (!found)
110
+ throw new CliError("not_found", `the fake tracker has no issue ${externalId}`);
111
+ const answer = apply(found, patch);
112
+ made("update", externalId);
113
+ return answer;
114
+ },
115
+ async comment(issue, body) {
116
+ rows.comment ??= [];
117
+ const comments = rows.comment;
118
+ const comment = {
119
+ externalId: `comment-${comments.length + 1}`,
120
+ issue,
121
+ body,
122
+ author: self ?? null,
123
+ createdAt: clock(),
124
+ updatedAt: clock(),
125
+ };
126
+ comments.push(comment);
127
+ made("comment", comment.externalId);
128
+ return { ...comment };
129
+ },
67
130
  });
68
131
  return make(options.skew ?? 0);
69
132
  };
@@ -0,0 +1,20 @@
1
+ import type { ContractCase } from "../../meetings/index.js";
2
+ import { type TrackerWriter } from "../writer.js";
3
+ /**
4
+ * One adapter over recorded or faked responses, fresh for each case, and ids of what it holds: a team, a state of that
5
+ * team, a user, a label and a project, as a sync stored them.
6
+ */
7
+ export interface TrackerWriteFixture {
8
+ writer: TrackerWriter;
9
+ team: string;
10
+ state: string;
11
+ user: string;
12
+ label: string;
13
+ project: string;
14
+ /** Makes the next write's answer lost after the tracker got it, as a dropped connection does. */
15
+ loseNextAnswer: () => void;
16
+ /** How many write requests reached the tracker so far. */
17
+ requests: () => number;
18
+ }
19
+ /** What every tracker adapter's write side does, whatever the tracker: run each case in the adapter's tests. */
20
+ export declare const trackerWriteContract: (make: () => TrackerWriteFixture | Promise<TrackerWriteFixture>) => ContractCase[];
@@ -0,0 +1,94 @@
1
+ import assert from "node:assert/strict";
2
+ import { isCliError } from "@wirecat/cli-base";
3
+ import { TRACKER_WRITES } from "../writer.js";
4
+ let operations = 0;
5
+ const operation = () => {
6
+ operations += 1;
7
+ return { operationId: `contract-${Date.now()}-${operations}` };
8
+ };
9
+ /** What every tracker adapter's write side does, whatever the tracker: run each case in the adapter's tests. */
10
+ export const trackerWriteContract = (make) => {
11
+ const created = async () => {
12
+ const fixture = await make();
13
+ const issue = await fixture.writer.createIssue({
14
+ title: "Example contract issue",
15
+ description: "Example: written by the contract",
16
+ team: fixture.team,
17
+ state: fixture.state,
18
+ assignee: fixture.user,
19
+ priority: 2,
20
+ labels: [fixture.label],
21
+ project: fixture.project,
22
+ }, operation());
23
+ return { ...fixture, issue };
24
+ };
25
+ return [
26
+ {
27
+ name: "writes: known writes, at least one",
28
+ async run() {
29
+ const { writer } = await make();
30
+ assert.ok(writer.writes.length > 0 && writer.writes.every((one) => TRACKER_WRITES.includes(one)));
31
+ },
32
+ },
33
+ {
34
+ name: "create answers the whole issue with its new id, in the fields it was given",
35
+ async run() {
36
+ const { issue, team, state, user, label, project } = await created();
37
+ assert.ok(issue.externalId, "an id");
38
+ assert.equal(issue.title, "Example contract issue");
39
+ assert.equal(issue.description, "Example: written by the contract");
40
+ assert.equal(issue.team, team);
41
+ assert.equal(issue.state, state);
42
+ assert.equal(issue.assignee, user);
43
+ assert.equal(issue.priority, 2);
44
+ assert.deepEqual(issue.labels, [label]);
45
+ assert.equal(issue.project, project);
46
+ },
47
+ },
48
+ {
49
+ name: "update of one field answers the whole issue, every other field as it was",
50
+ async run() {
51
+ const { writer, issue } = await created();
52
+ const changed = await writer.updateIssue(issue.externalId, { title: "Example renamed" }, operation());
53
+ assert.equal(changed.externalId, issue.externalId);
54
+ assert.equal(changed.title, "Example renamed");
55
+ for (const field of ["description", "team", "state", "assignee", "priority", "project"])
56
+ assert.deepEqual(changed[field] ?? null, issue[field] ?? null, `${field} kept`);
57
+ assert.deepEqual(changed.labels ?? [], issue.labels ?? [], "labels kept");
58
+ },
59
+ },
60
+ {
61
+ name: "an update clears the assignee, the project and the labels",
62
+ async run() {
63
+ const { writer, issue } = await created();
64
+ const cleared = await writer.updateIssue(issue.externalId, { assignee: null, project: null, labels: [] }, operation());
65
+ assert.equal(cleared.assignee ?? null, null);
66
+ assert.equal(cleared.project ?? null, null);
67
+ assert.deepEqual(cleared.labels ?? [], []);
68
+ },
69
+ },
70
+ {
71
+ name: "comment answers the comment on the issue, and text that looks like a slot goes out as written",
72
+ async run() {
73
+ const { writer, issue } = await created();
74
+ // A manifest's variables hold "{id}" and "{values}": the owner's text must never be filled as one.
75
+ const renamed = await writer.updateIssue(issue.externalId, { title: "{id}" }, operation());
76
+ assert.equal(renamed.title, "{id}");
77
+ const comment = await writer.comment(issue.externalId, "{values}", operation());
78
+ assert.ok(comment.externalId, "an id");
79
+ assert.equal(comment.issue, issue.externalId);
80
+ assert.equal(comment.body, "{values}");
81
+ },
82
+ },
83
+ {
84
+ name: "a lost answer is outcome_unknown, and the write reached the tracker once",
85
+ async run() {
86
+ const { writer, issue, loseNextAnswer, requests } = await created();
87
+ const before = requests();
88
+ loseNextAnswer();
89
+ await assert.rejects(writer.updateIssue(issue.externalId, { title: "Example lost" }, operation()), (error) => isCliError(error) && error.code === "outcome_unknown");
90
+ assert.equal(requests(), before + 1);
91
+ },
92
+ },
93
+ ];
94
+ };
@@ -0,0 +1,57 @@
1
+ import type { ConditionalKey } from "../cli/permission-keys.js";
2
+ import type { TrackerComment, TrackerIssue } from "../domain/tracker.js";
3
+ import type { Level, PermissionKey } from "../sends/permissions.js";
4
+ export declare const TRACKER_WRITES: readonly ["create", "update", "comment"];
5
+ export type TrackerWrite = (typeof TRACKER_WRITES)[number];
6
+ /** An issue's fields in `TrackerIssue`'s names, each a reference by the tracker's own id; `null` clears one. */
7
+ export interface TrackerIssueFields {
8
+ title?: string;
9
+ description?: string | null;
10
+ team?: string;
11
+ state?: string | null;
12
+ assignee?: string | null;
13
+ /** 0 is none, then 1 the most urgent, as `TrackerIssue` keeps it. */
14
+ priority?: number | null;
15
+ /** Replaces the whole list. */
16
+ labels?: string[];
17
+ project?: string | null;
18
+ parent?: string | null;
19
+ }
20
+ export type TrackerIssueDraft = TrackerIssueFields & {
21
+ title: string;
22
+ };
23
+ export interface TrackerWriteOptions {
24
+ /** Journaled before the call. */
25
+ operationId: string;
26
+ /**
27
+ * The keys the owner was asked about for this write, those at level `ask`: a writer over the `api` group does not
28
+ * ask them again.
29
+ */
30
+ confirmed?: readonly PermissionKey[];
31
+ }
32
+ /**
33
+ * Writes to one tracker account. Each answers the whole record as the tracker holds it after the write, which the store
34
+ * saves as a sync would. None of them retries: a write whose answer was lost throws `outcome_unknown`.
35
+ */
36
+ export interface TrackerWriter {
37
+ readonly provider: string;
38
+ /** What this tracker takes: `issues create`, `issues update` and `issues comment` are mounted for these. */
39
+ readonly writes: readonly TrackerWrite[];
40
+ createIssue(draft: TrackerIssueDraft, options: TrackerWriteOptions): Promise<TrackerIssue>;
41
+ updateIssue(externalId: string, patch: TrackerIssueFields, options: TrackerWriteOptions): Promise<TrackerIssue>;
42
+ /** A comment on the issue by its tracker id; the body is the owner's text, sent as typed. */
43
+ comment(issue: string, body: string, options: TrackerWriteOptions): Promise<TrackerComment>;
44
+ }
45
+ /** Each write's key: its command path. */
46
+ export declare const TRACKER_WRITE_KEYS: Readonly<Record<TrackerWrite, PermissionKey>>;
47
+ /** Giving an issue to a tracker user other than the one the sign-in acts as, as `crm.assign-others` for a CRM. */
48
+ export declare const TRACKER_ASSIGN_OTHERS_KEY: PermissionKey;
49
+ /** The keys the tracker writes check beyond their command paths, for a CLI's `commandPermissions({ extra })`. */
50
+ export declare const TRACKER_WRITE_EXTRA_KEYS: readonly PermissionKey[];
51
+ /** Built in, and only ever tightening (WC-PERM-7): an issue is not given to somebody else until the owner allows it. */
52
+ export declare const TRACKER_WRITE_DEFAULTS: Readonly<Record<PermissionKey, Level>>;
53
+ /**
54
+ * Every key a tracker write command may check beyond its own path, for `commandPermissions({ alsoChecks })`, so its
55
+ * `--dry-run` names each: `also` adds the CLI's own, such as the `api.*` key of the mutation it sends.
56
+ */
57
+ export declare const trackerAlsoChecks: (also?: (write: TrackerWrite) => readonly PermissionKey[]) => (path: readonly string[]) => readonly (PermissionKey | ConditionalKey)[];
@@ -0,0 +1,25 @@
1
+ export const TRACKER_WRITES = ["create", "update", "comment"];
2
+ /** Each write's key: its command path. */
3
+ export const TRACKER_WRITE_KEYS = {
4
+ create: "issues.create",
5
+ update: "issues.update",
6
+ comment: "issues.comment",
7
+ };
8
+ /** Giving an issue to a tracker user other than the one the sign-in acts as, as `crm.assign-others` for a CRM. */
9
+ export const TRACKER_ASSIGN_OTHERS_KEY = "issues.assign-others";
10
+ /** The keys the tracker writes check beyond their command paths, for a CLI's `commandPermissions({ extra })`. */
11
+ export const TRACKER_WRITE_EXTRA_KEYS = [TRACKER_ASSIGN_OTHERS_KEY];
12
+ /** Built in, and only ever tightening (WC-PERM-7): an issue is not given to somebody else until the owner allows it. */
13
+ export const TRACKER_WRITE_DEFAULTS = { [TRACKER_ASSIGN_OTHERS_KEY]: "deny" };
14
+ /**
15
+ * Every key a tracker write command may check beyond its own path, for `commandPermissions({ alsoChecks })`, so its
16
+ * `--dry-run` names each: `also` adds the CLI's own, such as the `api.*` key of the mutation it sends.
17
+ */
18
+ export const trackerAlsoChecks = (also) => (path) => {
19
+ const [noun, command] = path;
20
+ const write = TRACKER_WRITES.find((one) => one === command);
21
+ if (path.length !== 2 || noun !== "issues" || write === undefined)
22
+ return [];
23
+ const assign = { key: TRACKER_ASSIGN_OTHERS_KEY, when: "--assignee other than the sign-in's user" };
24
+ return [...(write === "comment" ? [] : [assign]), ...(also?.(write) ?? [])];
25
+ };
@@ -0,0 +1,53 @@
1
+ import type { Asker } from "../sends/guard.js";
2
+ import { type ProfileWrites } from "../sends/profile-writes.js";
3
+ import type { TrackerItem } from "../store/sqlite/tracker.js";
4
+ import type { MessageStore } from "../store/store.js";
5
+ import type { AccountKey } from "../store/types.js";
6
+ import type { TrackerSource } from "./source.js";
7
+ import { type TrackerWriter } from "./writer.js";
8
+ /** What a CLI hands the tracker writes for one profile. */
9
+ export interface TrackerWrites extends ProfileWrites {
10
+ writer: TrackerWriter;
11
+ }
12
+ export interface TrackerWriteContext {
13
+ store: MessageStore;
14
+ account: AccountKey;
15
+ writes: TrackerWrites;
16
+ /** A terminal's question, or an agent's go-ahead. */
17
+ ask: Asker;
18
+ /** Names the sign-in's own user when no sync has kept it yet; left out, every assignee is somebody else. */
19
+ source?: () => TrackerSource;
20
+ now?: () => number;
21
+ }
22
+ /**
23
+ * An issue's fields as typed: a team by its id, key or name, a state, label or project by its id or name, a user by
24
+ * its id, name or e-mail, a parent by its key or id. An empty value clears a field; one empty `labels` clears the list.
25
+ */
26
+ export interface TrackerIssueInput {
27
+ title?: string;
28
+ description?: string;
29
+ team?: string;
30
+ state?: string;
31
+ assignee?: string;
32
+ /** 0 to 4, or none, urgent, high, medium, low. */
33
+ priority?: string;
34
+ labels?: readonly string[];
35
+ project?: string;
36
+ parent?: string;
37
+ }
38
+ export interface TrackerIssueWritten {
39
+ operationId: string;
40
+ issue: TrackerItem<"issue">;
41
+ }
42
+ export interface TrackerCommentWritten {
43
+ operationId: string;
44
+ comment: TrackerItem<"comment">;
45
+ }
46
+ /** An issue of this account's copy by its key (`ENG-12`, any case) or id. */
47
+ export declare const trackerIssueOf: (context: Pick<TrackerWriteContext, "store" | "account">, reference: string, param?: string) => Promise<TrackerItem<"issue">>;
48
+ /** A new issue in the tracker, through the guarded path; the tracker's answer is stored as a sync stores it. */
49
+ export declare const createTrackerIssue: (context: TrackerWriteContext, input: TrackerIssueInput) => Promise<TrackerIssueWritten>;
50
+ /** A change to an issue by its key or id; what is left out keeps its value. */
51
+ export declare const updateTrackerIssue: (context: TrackerWriteContext, reference: string, input: TrackerIssueInput) => Promise<TrackerIssueWritten>;
52
+ /** A comment on an issue by its key or id, in the owner's words. */
53
+ export declare const commentTrackerIssue: (context: TrackerWriteContext, reference: string, body: string) => Promise<TrackerCommentWritten>;