@wirecat/cli-core 0.723.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 (40) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/dist/cli/documents/history.js +2 -2
  3. package/dist/cli/documents/words.d.ts +1 -1
  4. package/dist/content/writes.d.ts +3 -9
  5. package/dist/content/writes.js +3 -13
  6. package/dist/crm/writes.d.ts +4 -13
  7. package/dist/crm/writes.js +2 -9
  8. package/dist/errors/reasons.js +5 -0
  9. package/dist/sends/profile-writes.d.ts +22 -0
  10. package/dist/sends/profile-writes.js +20 -0
  11. package/dist/services/metadata.d.ts +1 -1
  12. package/dist/tracker/cli/index.d.ts +10 -1
  13. package/dist/tracker/cli/index.js +20 -1
  14. package/dist/tracker/cli/writes.d.ts +27 -0
  15. package/dist/tracker/cli/writes.js +74 -0
  16. package/dist/tracker/index.d.ts +5 -2
  17. package/dist/tracker/index.js +5 -2
  18. package/dist/tracker/manifest/manifest.d.ts +25 -0
  19. package/dist/tracker/manifest/manifest.js +59 -8
  20. package/dist/tracker/manifest/source.d.ts +10 -1
  21. package/dist/tracker/manifest/source.js +12 -9
  22. package/dist/tracker/manifest/writer.d.ts +20 -0
  23. package/dist/tracker/manifest/writer.js +72 -0
  24. package/dist/tracker/sync.d.ts +5 -0
  25. package/dist/tracker/sync.js +12 -0
  26. package/dist/tracker/testing/index.d.ts +3 -1
  27. package/dist/tracker/testing/index.js +3 -1
  28. package/dist/tracker/testing/manifest-fake.d.ts +2 -0
  29. package/dist/tracker/testing/manifest-fake.js +123 -41
  30. package/dist/tracker/testing/manifest-writes.d.ts +16 -0
  31. package/dist/tracker/testing/manifest-writes.js +70 -0
  32. package/dist/tracker/testing/source.d.ts +9 -1
  33. package/dist/tracker/testing/source.js +63 -0
  34. package/dist/tracker/testing/write-contract.d.ts +20 -0
  35. package/dist/tracker/testing/write-contract.js +94 -0
  36. package/dist/tracker/writer.d.ts +57 -0
  37. package/dist/tracker/writer.js +25 -0
  38. package/dist/tracker/writes.d.ts +53 -0
  39. package/dist/tracker/writes.js +226 -0
  40. package/package.json +1 -1
@@ -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>;
@@ -0,0 +1,226 @@
1
+ import { CliError, isCliError } from "@wirecat/cli-base";
2
+ import { foldName } from "../resolve.js";
3
+ import { guardedWrite } from "../sends/guarded.js";
4
+ import { askedKeys, profileWriteGuard } from "../sends/profile-writes.js";
5
+ import { newOperationId } from "../sends/send-id.js";
6
+ import { trackerSelfOf } from "./sync.js";
7
+ import { TRACKER_ASSIGN_OTHERS_KEY, TRACKER_WRITE_DEFAULTS, TRACKER_WRITE_KEYS, } from "./writer.js";
8
+ const PAGE = 500;
9
+ const PRIORITIES = { none: 0, urgent: 1, high: 2, medium: 3, low: 4 };
10
+ const PLURALS = { team: "teams", user: "users", state: "states", label: "labels", project: "projects" };
11
+ const invalid = (message, param, details = {}) => new CliError("validation_error", message, { reason: "tracker.field", ...(param ? { param } : {}), ...details });
12
+ const supported = (writer, write) => {
13
+ if (!writer.writes.includes(write))
14
+ throw new CliError("validation_error", `this tracker takes no issues ${write}`, {
15
+ reason: "tracker.write-unsupported",
16
+ sent: false,
17
+ });
18
+ };
19
+ const namesOf = (kind, record) => {
20
+ const { name } = record;
21
+ if (kind === "team")
22
+ return [name, record.key ?? ""];
23
+ if (kind === "user")
24
+ return [name, record.email ?? ""];
25
+ return [name];
26
+ };
27
+ /** Every live row of the kind, page by page: a uniqueness check over a capped page could miss the second match. */
28
+ const allOf = async (context, kind, parent) => {
29
+ const all = [];
30
+ for (let offset = 0;; offset += PAGE) {
31
+ const page = await context.store.tracker.list(context.account, kind, {
32
+ limit: PAGE,
33
+ offset,
34
+ ...(parent === undefined ? {} : { parent }),
35
+ });
36
+ for (const item of page.items)
37
+ all.push(item);
38
+ if (!page.hasMore)
39
+ return all;
40
+ }
41
+ };
42
+ /** A team's states are its own; its labels are its own and the workspace's, which belong to no team. */
43
+ const withinTeam = (kind, item, team) => {
44
+ if (team === undefined || (kind !== "state" && kind !== "label"))
45
+ return true;
46
+ const owner = item.record.team ?? null;
47
+ return owner === team || (kind === "label" && owner === null);
48
+ };
49
+ /**
50
+ * A record of this account's copy by the tracker's id, or by a name only one of them has, in any letter case. A state
51
+ * or a label is looked for among the issue's team's. Anything else is refused before a write is sent: a reference the
52
+ * copy does not hold would reach the tracker as typed.
53
+ */
54
+ const referenceOf = async (context, kind, given, param, team) => {
55
+ const byId = await context.store.tracker.get(context.account, kind, given);
56
+ if (byId && byId.deletedAt === null && withinTeam(kind, byId, team))
57
+ return given;
58
+ const want = foldName(given.trim());
59
+ const found = (await allOf(context, kind, kind === "state" ? team : undefined)).filter((one) => withinTeam(kind, one, team) && namesOf(kind, one.record).some((name) => name && foldName(name) === want));
60
+ if (found.length === 1)
61
+ return found[0].record.externalId;
62
+ const candidates = found.map((one) => ({ id: one.record.externalId, name: one.record.name }));
63
+ const scoped = (kind === "state" || kind === "label") && team ? " for the issue's team" : "";
64
+ throw invalid(found.length
65
+ ? `${found.length} ${PLURALS[kind]} are named ${given}${scoped}; name one by its id`
66
+ : `no ${kind} ${given} in the copy${scoped}; see ${PLURALS[kind]} list, or run sync`, param, { reason: "tracker.reference", ...(candidates.length ? { candidates } : {}) });
67
+ };
68
+ /** The team a new issue goes to: the one named, or the copy's only team; several and none named is refused. */
69
+ const teamOf = async (context, given) => {
70
+ if (given !== undefined)
71
+ return referenceOf(context, "team", given, "--team");
72
+ const all = await allOf(context, "team");
73
+ if (all.length === 1)
74
+ return all[0].record.externalId;
75
+ // Sent without a team, the issue would be refused by the tracker or land where the owner did not choose.
76
+ if (all.length === 0)
77
+ throw invalid("the copy holds no team for a new issue; run sync, then try again", "--team", {
78
+ reason: "tracker.team-required",
79
+ });
80
+ throw invalid(`this tracker has ${all.length} teams; name one with --team: ` +
81
+ all.map(({ record }) => `${record.name} (${record.key ?? record.externalId})`).join(", "), "--team", { reason: "tracker.team-required", allowed: all.map(({ record }) => record.externalId) });
82
+ };
83
+ /** An issue of this account's copy by its key (`ENG-12`, any case) or id. */
84
+ export const trackerIssueOf = async (context, reference, param = "<issue>") => {
85
+ const found = (await context.store.tracker.get(context.account, "issue", reference)) ??
86
+ (await context.store.tracker.issueByKey(context.account, reference));
87
+ if (!found || found.deletedAt !== null)
88
+ throw new CliError("not_found", `no issue ${reference} in the copy; run sync, then try again`, { param });
89
+ return found;
90
+ };
91
+ /** An empty value clears it, as for every other field: 0 is the tracker's "no priority". */
92
+ const priorityOf = (typed) => {
93
+ if (typed.trim() === "")
94
+ return 0;
95
+ const word = PRIORITIES[typed.trim().toLowerCase()];
96
+ const number = word ?? Number(typed);
97
+ if (!Number.isInteger(number) || number < 0 || number > 4)
98
+ throw invalid("--priority is 0 to 4, or none, urgent, high, medium, low", "--priority");
99
+ return number;
100
+ };
101
+ /** Typed fields into the port's, each reference resolved in the copy; `team` is the issue's, for its states. */
102
+ const fieldsOf = async (context, input, team, self) => {
103
+ const fields = {};
104
+ const cleared = (value) => value.trim() === "";
105
+ if (input.title !== undefined) {
106
+ if (cleared(input.title))
107
+ throw invalid("a title is never empty", "--title");
108
+ fields.title = input.title.trim();
109
+ }
110
+ if (input.description !== undefined)
111
+ fields.description = cleared(input.description) ? null : input.description;
112
+ if (team !== undefined && input.team !== undefined)
113
+ fields.team = team;
114
+ if (input.state !== undefined) {
115
+ if (cleared(input.state))
116
+ throw invalid("every issue is in a state; name one", "--state");
117
+ fields.state = await referenceOf(context, "state", input.state, "--state", team);
118
+ }
119
+ if (input.assignee !== undefined)
120
+ fields.assignee = cleared(input.assignee) ? null : await referenceOf(context, "user", input.assignee, "--assignee");
121
+ if (input.priority !== undefined)
122
+ fields.priority = priorityOf(input.priority);
123
+ if (input.labels !== undefined)
124
+ fields.labels =
125
+ input.labels.length === 1 && cleared(input.labels[0])
126
+ ? []
127
+ : await Promise.all(input.labels.map((one) => referenceOf(context, "label", one, "--label", team)));
128
+ if (input.project !== undefined)
129
+ fields.project = cleared(input.project) ? null : await referenceOf(context, "project", input.project, "--project");
130
+ if (input.parent !== undefined) {
131
+ fields.parent = cleared(input.parent)
132
+ ? null
133
+ : (await trackerIssueOf(context, input.parent, "--parent")).record.externalId;
134
+ if (fields.parent !== null && fields.parent === self)
135
+ throw invalid("an issue is not its own parent", "--parent");
136
+ }
137
+ return fields;
138
+ };
139
+ /**
140
+ * Checked and journaled once. A write the tracker made whose answer then held no record is journaled as sent, and the
141
+ * failure answered after; a lost answer is `outcome_unknown`, and the owner syncs before writing again.
142
+ */
143
+ const written = async (context, write, operationId, act, extra = []) => {
144
+ const key = TRACKER_WRITE_KEYS[write];
145
+ try {
146
+ const confirmed = askedKeys(context.writes, TRACKER_WRITE_DEFAULTS, [key, ...extra]);
147
+ const done = await guardedWrite(profileWriteGuard(context.writes, context.ask, TRACKER_WRITE_DEFAULTS, extra), { chatId: null, kind: "edit", key, operationId }, async () => {
148
+ try {
149
+ return { record: await act({ operationId, confirmed }), unread: null };
150
+ }
151
+ catch (error) {
152
+ if (isCliError(error) && error.details.sent === true)
153
+ return { record: null, unread: error };
154
+ throw error;
155
+ }
156
+ });
157
+ if (done.unread)
158
+ throw new CliError(done.unread.code, `${done.unread.message} — sync to store it, do not write it again`, {
159
+ ...done.unread.details,
160
+ operation_id: operationId,
161
+ });
162
+ return done.record;
163
+ }
164
+ catch (error) {
165
+ if (!isCliError(error) || error.code !== "outcome_unknown")
166
+ throw error;
167
+ throw new CliError("outcome_unknown", `${error.message} — sync and look at the tracker before writing again: a repeat may write it twice`, { ...error.details, operation_id: operationId });
168
+ }
169
+ };
170
+ /** The tracker's answer into the copy, as a sync saves it; a failure names the record, which the tracker has written. */
171
+ const kept = async (context, kind, record, operationId) => {
172
+ try {
173
+ await context.store.tracker.save(context.account, kind, [record], context.now?.() ?? Date.now());
174
+ const found = await context.store.tracker.get(context.account, kind, record.externalId);
175
+ if (!found)
176
+ throw new Error("it is not found after the save");
177
+ return found;
178
+ }
179
+ catch (error) {
180
+ throw new CliError("invalid_response", `the tracker wrote ${kind} ${record.externalId}, but the local store did not keep it ` +
181
+ `(${error instanceof Error ? error.message : String(error)}); sync to store it — do not write it again`, { operation_id: operationId, external_id: record.externalId, sent: true });
182
+ }
183
+ };
184
+ /** An assignee other than the sign-in's own user checks `issues.assign-others` too (WC-PERM-22). */
185
+ const assignKeys = async (context, fields) => {
186
+ if (fields.assignee == null)
187
+ return [];
188
+ const self = await trackerSelfOf(context.store, context.account, context.source?.());
189
+ return fields.assignee === self ? [] : [TRACKER_ASSIGN_OTHERS_KEY];
190
+ };
191
+ /** A new issue in the tracker, through the guarded path; the tracker's answer is stored as a sync stores it. */
192
+ export const createTrackerIssue = async (context, input) => {
193
+ const { writer } = context.writes;
194
+ supported(writer, "create");
195
+ if (input.title === undefined)
196
+ throw invalid("a new issue needs --title", "--title");
197
+ const team = await teamOf(context, input.team);
198
+ const fields = await fieldsOf(context, { ...input, team }, team);
199
+ const operationId = newOperationId();
200
+ const issue = await written(context, "create", operationId, (options) => writer.createIssue({ ...fields, title: fields.title }, options), await assignKeys(context, fields));
201
+ return { operationId, issue: await kept(context, "issue", issue, operationId) };
202
+ };
203
+ /** A change to an issue by its key or id; what is left out keeps its value. */
204
+ export const updateTrackerIssue = async (context, reference, input) => {
205
+ const { writer } = context.writes;
206
+ supported(writer, "update");
207
+ const copy = await trackerIssueOf(context, reference);
208
+ const team = input.team === undefined ? (copy.record.team ?? undefined) : await teamOf(context, input.team);
209
+ const fields = await fieldsOf(context, input, team, copy.record.externalId);
210
+ if (Object.keys(fields).length === 0)
211
+ throw invalid("nothing to change: name a field");
212
+ const operationId = newOperationId();
213
+ const issue = await written(context, "update", operationId, (options) => writer.updateIssue(copy.record.externalId, fields, options), await assignKeys(context, fields));
214
+ return { operationId, issue: await kept(context, "issue", issue, operationId) };
215
+ };
216
+ /** A comment on an issue by its key or id, in the owner's words. */
217
+ export const commentTrackerIssue = async (context, reference, body) => {
218
+ const { writer } = context.writes;
219
+ supported(writer, "comment");
220
+ if (body.trim() === "")
221
+ throw invalid("a comment is never empty", "--body");
222
+ const copy = await trackerIssueOf(context, reference);
223
+ const operationId = newOperationId();
224
+ const comment = await written(context, "comment", operationId, (options) => writer.comment(copy.record.externalId, body, options));
225
+ return { operationId, comment: await kept(context, "comment", comment, operationId) };
226
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.723.0",
3
+ "version": "0.724.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",