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