Open History to see the last commit
1import type {
2 EnvironmentId,
3 IssueListCursors,
4 IssueListEntry,
5 IssueListProjectError,
6 IssueListResult,
7 IssueListSort,
8 IssueScopeRef,
9 IssueTrackerSummary,
10 SourceControlProviderKind,
11} from "@t3tools/contracts";
12
13import { mergeIssueListPage } from "./state/issues.ts";
14import { sourceControlClients } from "./sourceControlClients.ts";
15import type { EnvironmentProject } from "./state/shell.ts";
16
17export interface EnvironmentIssueEntry extends IssueListEntry {
18 readonly environmentId: EnvironmentId;
19}
20
21/** Rows from every environment that answered, with any continuation pages laid over them. */
22export interface HeldIssuePage {
23 readonly answer: IssueListResult;
24 readonly entries: ReadonlyArray<IssueListEntry>;
25 readonly errors: ReadonlyArray<IssueListProjectError>;
26 /** What continuations reported, each beside the cursors it was asked to carry on. */
27 readonly moreErrors: ReadonlyArray<{
28 readonly asked: ReadonlyArray<string>;
29 readonly errors: ReadonlyArray<IssueListProjectError>;
30 }>;
31 readonly nextCursors: IssueListCursors;
32 /** Why the last "Load more" failed, until a retry succeeds or a new first page arrives. */
33 readonly moreFailure: string | null;
34}
35
36export function issueTrackerKey(tracker: Pick<IssueTrackerSummary, "tracker" | "host">): string {
37 return `${tracker.tracker} ${tracker.host.toLowerCase()}`;
38}
39
40/** Continuations are laid over the first page they continue; a new first page forgets them. */
41export function holdIssuePages(
42 answers: ReadonlyArray<readonly [EnvironmentId, IssueListResult]>,
43 pages: ReadonlyMap<EnvironmentId, HeldIssuePage>,
44): ReadonlyMap<EnvironmentId, HeldIssuePage> {
45 const next = new Map<EnvironmentId, HeldIssuePage>();
46 for (const [environmentId, answer] of answers) {
47 const previous = pages.get(environmentId);
48 next.set(
49 environmentId,
50 previous?.answer === answer
51 ? previous
52 : {
53 answer,
54 entries: answer.entries,
55 errors: answer.errors,
56 moreErrors: [],
57 nextCursors: answer.nextCursors,
58 moreFailure: null,
59 },
60 );
61 }
62 return next;
63}
64
65/** The cursors of one tracker host, so its "Load more" leaves the other trackers where they are. */
66export function issueCursorsForHost(cursors: IssueListCursors, host: string): IssueListCursors {
67 return Object.fromEntries(Object.entries(cursors).filter(([key]) => key.startsWith(`${host} `)));
68}
69
70/**
71 * Lays the next page over the rows held; a failure keeps them and says why. `asked` is the
72 * cursors the page was asked to carry on: only those move, and what an earlier continuation
73 * reported for any of them is replaced, so a retry that works takes its error away.
74 */
75export function continueIssuePage(
76 page: HeldIssuePage,
77 next: IssueListResult | { readonly failure: string },
78 asked: IssueListCursors = page.nextCursors,
79): HeldIssuePage {
80 if ("failure" in next) return { ...page, moreFailure: next.failure };
81 const moreErrors = page.moreErrors.filter((more) => !more.asked.some((key) => key in asked));
82 if (next.errors.length > 0) moreErrors.push({ asked: Object.keys(asked), errors: next.errors });
83 return {
84 answer: page.answer,
85 entries: mergeIssueListPage(page.entries, next.entries),
86 errors: [...page.answer.errors, ...moreErrors.flatMap((more) => more.errors)],
87 moreErrors,
88 nextCursors: {
89 ...Object.fromEntries(Object.entries(page.nextCursors).filter(([key]) => !(key in asked))),
90 ...next.nextCursors,
91 },
92 moreFailure: null,
93 };
94}
95
96/** Newest first by the date the trackers were asked to sort on, so merged rows keep that order. */
97export function issueOrder(sort: IssueListSort) {
98 const date = (issue: IssueListEntry) =>
99 Date.parse(sort === "created" ? issue.createdAt : issue.updatedAt);
100 return (left: IssueListEntry, right: IssueListEntry) => date(right) - date(left);
101}
102
103export function groupIssues(
104 held: ReadonlyMap<EnvironmentId, HeldIssuePage>,
105 query: string,
106 projects: ReadonlyArray<EnvironmentProject>,
107 sort: IssueListSort = "updated",
108) {
109 const byTracker = new Map<
110 string,
111 {
112 tracker: IssueTrackerSummary;
113 rows: EnvironmentIssueEntry[];
114 errors: Array<{ projectTitle: string; message: string; environmentId: EnvironmentId }>;
115 more: EnvironmentId[];
116 }
117 >();
118 const listed = new Set<string>();
119 const needle = query.toLowerCase();
120 for (const [environmentId, page] of held) {
121 for (const tracker of page.answer.trackers) {
122 const key = issueTrackerKey(tracker);
123 if (!byTracker.has(key)) byTracker.set(key, { tracker, rows: [], errors: [], more: [] });
124 const group = byTracker.get(key)!;
125 if (!group.tracker.configured && tracker.configured) group.tracker = tracker;
126 if (Object.keys(page.nextCursors).some((c) => c.startsWith(`${tracker.host} `)))
127 group.more.push(environmentId);
128 }
129 for (const entry of page.entries) {
130 const key = issueTrackerKey(entry);
131 const group = byTracker.get(key);
132 if (!group) continue;
133 // A tracker that cannot search is narrowed here instead.
134 if (
135 needle.length > 0 &&
136 group.tracker.capabilities?.search !== true &&
137 !entry.title.toLowerCase().includes(needle) &&
138 !entry.displayKey.toLowerCase().includes(needle)
139 )
140 continue;
141 // Environments holding the same repository answer the same issue; the first one keeps it.
142 if (listed.has(entry.url)) continue;
143 listed.add(entry.url);
144 group.rows.push({ ...entry, environmentId });
145 }
146 for (const error of page.errors) {
147 const project = projects.find(
148 (p) => p.environmentId === environmentId && p.id === error.projectId,
149 );
150 const kind = project?.repositoryIdentity?.provider as SourceControlProviderKind | undefined;
151 const host = kind
152 ? sourceControlClients.changeRequestHost(project?.repositoryIdentity, kind)
153 : null;
154 const group =
155 (host ? byTracker.get(`${kind} ${host.toLowerCase()}`) : undefined) ??
156 [...byTracker.values()][0];
157 group?.errors.push({ ...error, environmentId });
158 }
159 }
160 for (const group of byTracker.values()) group.rows.sort(issueOrder(sort));
161 return [...byTracker.values()].sort((a, b) =>
162 issueTrackerKey(a.tracker).localeCompare(issueTrackerKey(b.tracker)),
163 );
164}
165
166/** The scopes whose labels and people a list filter offers, each reached through one project. */
167export function issueFilterScopes(
168 held: ReadonlyMap<EnvironmentId, HeldIssuePage>,
169 projects: ReadonlyArray<EnvironmentProject>,
170) {
171 const scopes: Array<{ readonly environmentId: EnvironmentId; readonly input: IssueScopeRef }> =
172 [];
173 // A repository's scope is the same scope on every server. A bound tracker's scope is not: two
174 // accounts, or two servers, may both have an ENG team, so those are deduplicated per server only.
175 const fromRepository = new Set<IssueScopeRef>();
176 for (const [environmentId, page] of held) {
177 for (const project of projects) {
178 if (project.environmentId !== environmentId) continue;
179 for (const { tracker: kind, host, scope } of sourceControlClients.issueBindings(
180 project.repositoryIdentity,
181 )) {
182 const tracker = page.answer.trackers.find(
183 (t) => String(t.tracker) === kind && t.host.toLowerCase() === host.toLowerCase(),
184 );
185 if (!tracker?.configured || tracker.capabilities === null) continue;
186 if (
187 scopes.some(
188 (s) => s.input.scope.toLowerCase() === scope.toLowerCase() && s.input.host === host,
189 )
190 )
191 continue;
192 const input = { projectId: project.id, tracker: tracker.tracker, host, scope };
193 fromRepository.add(input);
194 scopes.push({ environmentId, input });
195 }
196 }
197 // A tracker bound in settings (a Linear team) is no repository's; the answer names its scope,
198 // matched or not. Older servers do not, so their rows stand in.
199 const covered: ReadonlyArray<IssueScopeRef> =
200 page.answer.scopes ??
201 page.entries.map(({ projectId, tracker, host, scope }) => ({
202 projectId,
203 tracker,
204 host,
205 scope,
206 }));
207 for (const input of covered) {
208 const host = input.host?.toLowerCase();
209 const tracker = page.answer.trackers.find(
210 (t) => t.tracker === input.tracker && t.host.toLowerCase() === host,
211 );
212 if (!tracker?.configured) continue;
213 if (!tracker.capabilities?.labels && !tracker.capabilities?.assignees) continue;
214 // An answer names each scope once per account; rows standing in for one repeat.
215 if (
216 scopes.some(
217 (s) =>
218 (fromRepository.has(s.input) ||
219 (page.answer.scopes === undefined && s.environmentId === environmentId)) &&
220 s.input.scope.toLowerCase() === input.scope.toLowerCase() &&
221 s.input.host?.toLowerCase() === host,
222 )
223 )
224 continue;
225 scopes.push({ environmentId, input });
226 }
227 }
228 return scopes;
229}