Open History to see the last commit
1import type {
2 RepositoryIdentity,
3 SourceControlProviderKind,
4 ThreadLinkedPullRequest,
5 ThreadPullRequestKey,
6 ThreadPullRequestLink,
7} from "@t3tools/contracts";
8
9import { pullRequestHostOf } from "@t3tools/contracts";
10import { parseChangeRequestUrl } from "./changeRequestUrl.ts";
11import { canonicalRepositoryKey, sourceControlRepositorySelector } from "./sourceControl.ts";
12
13type ThreadPullRequestKeySource = ThreadPullRequestKey & {
14 readonly authority?: string;
15 readonly url?: string;
16};
17
18/** Normalize stored links, recovering Forgejo HTTP ports from old links' URLs. */
19export function normalizeThreadPullRequestKey(
20 key: ThreadPullRequestKeySource,
21): ThreadPullRequestKey {
22 const parsed = key.url === undefined ? null : parseChangeRequestUrl(key.url);
23 const authority =
24 key.authority ??
25 (parsed?.repository === key.repository.trim().toLowerCase() && parsed.number === key.number
26 ? parsed.authority
27 : undefined);
28 const canonical = canonicalRepositoryKey(
29 `${(authority ?? key.host).trim().toLowerCase()}/${key.repository.trim().toLowerCase()}`,
30 );
31 const separator = canonical.indexOf("/");
32 return {
33 host: canonical.slice(0, separator),
34 repository: canonical.slice(separator + 1),
35 number: key.number,
36 };
37}
38
39/** Legacy Azure selectors omit the organization and project; recover those from the PR URL. */
40export function legacyThreadPullRequestKey(
41 linked: Pick<ThreadLinkedPullRequest, "repository" | "number" | "url">,
42 fallbackHost?: string,
43): ThreadPullRequestKey {
44 const parsed = parseChangeRequestUrl(linked.url);
45 if (parsed !== null && parsed.number === linked.number) {
46 const canonical = canonicalRepositoryKey(`${parsed.host}/${parsed.repository}`);
47 if (parsed.authority !== undefined || canonical.startsWith("dev.azure.com/")) {
48 return normalizeThreadPullRequestKey(parsed);
49 }
50 }
51 let host = fallbackHost;
52 if (host === undefined) {
53 try {
54 host = new URL(linked.url).hostname;
55 } catch {
56 host = "unknown";
57 }
58 }
59 return {
60 host: host.trim().toLowerCase() || "unknown",
61 repository: linked.repository.trim().toLowerCase(),
62 number: linked.number,
63 };
64}
65
66/** Identity comparison for links: host-level, case-insensitive on host and repository. */
67export function threadPullRequestKeysEqual(
68 left: ThreadPullRequestKeySource,
69 right: ThreadPullRequestKeySource,
70): boolean {
71 return threadPullRequestKeyOf(left) === threadPullRequestKeyOf(right);
72}
73
74export function threadPullRequestKeyOf(key: ThreadPullRequestKeySource): string {
75 const normalized = normalizeThreadPullRequestKey(key);
76 return `${normalized.host}/${normalized.repository}#${normalized.number}`;
77}
78
79/** Links a user should see. Tombstoned stack members stay in the array only so the
80 * sync reactor does not re-add them. */
81export function visibleThreadPullRequests(
82 links: ReadonlyArray<ThreadPullRequestLink>,
83): ReadonlyArray<ThreadPullRequestLink> {
84 return links.filter((link) => link.source !== "stack-dismissed");
85}
86
87function isOpen(link: ThreadPullRequestLink): boolean {
88 // Unsynced links are treated as open: they were just linked, and hiding them
89 // behind a terminal PR until the first sync would make the link look lost.
90 return link.snapshot === null || link.snapshot.state === "open";
91}
92
93function latestUpdatedAt(link: ThreadPullRequestLink): number {
94 const value = link.snapshot?.updatedAt ?? link.linkedAt;
95 const ms = Date.parse(value);
96 return Number.isNaN(ms) ? 0 : ms;
97}
98
99/** The single pull request a one-slot surface (sidebar badge, tab icon, copy link) shows. */
100export type ThreadCurrentPullRequest =
101 | { readonly kind: "single"; readonly link: ThreadPullRequestLink }
102 | {
103 readonly kind: "stack";
104 readonly open: ReadonlyArray<ThreadPullRequestLink>;
105 /** Highest layer of the open set; the one "View PR" and copy-link target. */
106 readonly top: ThreadPullRequestLink;
107 };
108
109/**
110 * Prefer open work and the highest open layer within a chain. A completed chain still
111 * points at its top; unrelated terminal links use the most recently updated request.
112 */
113export function resolveThreadCurrentPullRequest(
114 links: ReadonlyArray<ThreadPullRequestLink>,
115): ThreadCurrentPullRequest | null {
116 const visible = visibleThreadPullRequests(links);
117 if (visible.length === 0) return null;
118 const open = visible.filter(isOpen);
119 if (open.length === 1) return { kind: "single", link: open[0]! };
120 const chains = resolveThreadPullRequestChains(visible);
121 if (open.length > 1) {
122 // `.reverse()` on a copy, not `.toReversed()`: this runs on Hermes, which has no ES2023
123 // array methods, and a TypeError here is fatal on every mobile launch that renders a stack.
124 const openChains = chains
125 .map((chain) => [...chain.layers].reverse().filter(isOpen))
126 .filter((layers) => layers.length > 0)
127 .sort(
128 (left, right) =>
129 Math.max(...right.map((link) => Date.parse(link.linkedAt))) -
130 Math.max(...left.map((link) => Date.parse(link.linkedAt))),
131 );
132 const ordered = openChains.flat();
133 return { kind: "stack", open: ordered, top: ordered[0]! };
134 }
135 if (chains.length === 1) {
136 return { kind: "single", link: chains[0]!.layers.at(-1)! };
137 }
138 const terminal = [...visible].sort(
139 (left, right) => latestUpdatedAt(right) - latestUpdatedAt(left),
140 );
141 return { kind: "single", link: terminal[0]! };
142}
143
144/** The one link a legacy `linkedPullRequest` consumer should see, or null. */
145export function resolveThreadCurrentPullRequestLink(
146 links: ReadonlyArray<ThreadPullRequestLink>,
147): ThreadPullRequestLink | null {
148 const current = resolveThreadCurrentPullRequest(links);
149 if (current === null) return null;
150 return current.kind === "single" ? current.link : current.top;
151}
152
153/** Legacy clients can only route links belonging to the thread's own repository. */
154export function legacyLinkedPullRequestOf(
155 links: ReadonlyArray<ThreadPullRequestLink>,
156 projectId: ThreadLinkedPullRequest["projectId"],
157 identity: RepositoryIdentity | null | undefined,
158): ThreadLinkedPullRequest | null {
159 if (!identity) return null;
160 const host = pullRequestHostOf(identity, identity.provider as SourceControlProviderKind);
161 const repository = sourceControlRepositorySelector(identity);
162 if (repository === null) return null;
163 const azureKey =
164 identity.provider === "azure-devops"
165 ? canonicalRepositoryKey(identity.canonicalKey.toLowerCase())
166 : null;
167 const link = resolveThreadCurrentPullRequestLink(
168 links.filter((link) => {
169 if (azureKey !== null) {
170 const key = legacyThreadPullRequestKey(link, link.host);
171 return canonicalRepositoryKey(`${key.host}/${key.repository}`) === azureKey;
172 }
173 const parsed = parseChangeRequestUrl(link.url);
174 if (parsed?.authority !== undefined) {
175 try {
176 const remote = new URL(identity.locator.remoteUrl);
177 if (remote.protocol === "http:" || remote.protocol === "https:") {
178 return (
179 parsed.authority === remote.host && parsed.repository === repository.toLowerCase()
180 );
181 }
182 } catch {
183 // SSH web ports are resolved by the provider's configured login.
184 }
185 return parsed.host === host && parsed.repository === repository.toLowerCase();
186 }
187 return (
188 link.host.toLowerCase() === host.toLowerCase() &&
189 link.repository.toLowerCase() === repository.toLowerCase()
190 );
191 }),
192 );
193 if (link === null) return null;
194 return {
195 projectId,
196 repository: azureKey === null ? link.repository : repository,
197 number: link.number,
198 url: link.url,
199 };
200}
201
202export interface ThreadPullRequestChain {
203 readonly kind: "native" | "derived";
204 /** Bottom to top. */
205 readonly layers: ReadonlyArray<ThreadPullRequestLink>;
206}
207
208/**
209 * Groups a thread's links into stacks. Native stacks come from the host and win; the rest
210 * are chained by matching one link's base branch to another's head branch within the same
211 * repository. A link that chains to nothing is a one-layer chain.
212 */
213export function resolveThreadPullRequestChains(
214 links: ReadonlyArray<ThreadPullRequestLink>,
215): ReadonlyArray<ThreadPullRequestChain> {
216 const visible = visibleThreadPullRequests(links);
217 const chains: Array<ThreadPullRequestChain> = [];
218 const placed = new Set<string>();
219
220 const nativeStacks = new Map<string, Array<ThreadPullRequestLink>>();
221 for (const link of visible) {
222 if (link.stack === null) continue;
223 const key = normalizeThreadPullRequestKey(link);
224 const stackKey = `${key.host}/${key.repository}#stack:${link.stack.id}`;
225 const members = nativeStacks.get(stackKey) ?? [];
226 members.push(link);
227 nativeStacks.set(stackKey, members);
228 }
229 for (const members of nativeStacks.values()) {
230 const order = new Map(members[0]!.stack!.layers.map((layer, index) => [layer.number, index]));
231 members.sort((left, right) => (order.get(left.number) ?? 0) - (order.get(right.number) ?? 0));
232 for (const member of members) placed.add(threadPullRequestKeyOf(member));
233 chains.push({ kind: "native", layers: members });
234 }
235
236 const remaining = visible.filter((link) => !placed.has(threadPullRequestKeyOf(link)));
237 const branchKey = (link: ThreadPullRequestLink, branch: string) => {
238 const key = normalizeThreadPullRequestKey(link);
239 return `${key.host}/${key.repository}:${branch}`;
240 };
241 // Reused head names cannot identify a parent unambiguously.
242 const byHead = new Map<string, ThreadPullRequestLink | null>();
243 for (const link of remaining) {
244 if (link.snapshot === null) continue;
245 const key = branchKey(link, link.snapshot.headBranch);
246 byHead.set(key, byHead.has(key) ? null : link);
247 }
248 const hasChild = new Set<string>();
249 for (const link of remaining) {
250 if (link.snapshot === null) continue;
251 const parent = byHead.get(branchKey(link, link.snapshot.baseBranch));
252 if (parent != null && parent !== link) hasChild.add(threadPullRequestKeyOf(parent));
253 }
254 // Walk from each top (a link nothing builds on) down its base chain.
255 for (const top of remaining) {
256 if (hasChild.has(threadPullRequestKeyOf(top))) continue;
257 const layers: Array<ThreadPullRequestLink> = [];
258 let cursor: ThreadPullRequestLink | undefined = top;
259 while (cursor !== undefined && !placed.has(threadPullRequestKeyOf(cursor))) {
260 placed.add(threadPullRequestKeyOf(cursor));
261 layers.unshift(cursor);
262 cursor =
263 cursor.snapshot === null
264 ? undefined
265 : (byHead.get(branchKey(cursor, cursor.snapshot.baseBranch)) ?? undefined);
266 }
267 if (layers.length > 0) chains.push({ kind: "derived", layers });
268 }
269 // Cycles have no top. Keep those links visible without inventing a stack order.
270 for (const link of remaining) {
271 if (!placed.has(threadPullRequestKeyOf(link))) {
272 chains.push({ kind: "derived", layers: [link] });
273 }
274 }
275 return chains;
276}
277
278export type ThreadPullRequestBadge = {
279 readonly state: "open" | "closed" | "merged" | "draft";
280} & (
281 | {
282 readonly kind: "stack";
283 readonly layers: number;
284 }
285 | { readonly kind: "pull-request"; readonly others: number }
286);
287
288/** Aggregate visible links' state for both stacks and unrelated linked counts. */
289export function resolveThreadPullRequestBadge(
290 pullRequests: ReadonlyArray<ThreadPullRequestLink> | undefined,
291): ThreadPullRequestBadge | null {
292 const visible = visibleThreadPullRequests(pullRequests ?? []);
293 if (visible.length === 0) return null;
294 const states = visible.map((link) => link.snapshot?.state ?? "open");
295 const state = visible.every((link) => link.snapshot?.state === "open" && link.snapshot.isDraft)
296 ? "draft"
297 : states.includes("open")
298 ? "open"
299 : states.every((entry) => entry === "merged")
300 ? "merged"
301 : "closed";
302 const chains = resolveThreadPullRequestChains(visible);
303 if (visible.length > 1 && chains.length === 1) {
304 return { kind: "stack", layers: visible.length, state };
305 }
306 return { kind: "pull-request", others: visible.length - 1, state };
307}
308
309/** Search terms for visible PR links, including the legacy single-link projection. */
310export function threadPullRequestSearchTerms(thread: {
311 readonly pullRequests?: ReadonlyArray<ThreadPullRequestLink> | undefined;
312 readonly linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
313}): string[] {
314 if (thread.pullRequests !== undefined && thread.pullRequests.length > 0) {
315 return visibleThreadPullRequests(thread.pullRequests).flatMap((link) => [
316 `#${link.number}`,
317 `${link.repository}#${link.number}`,
318 link.url,
319 link.snapshot?.title ?? "",
320 ]);
321 }
322 const legacy = thread.linkedPullRequest;
323 return legacy ? [`#${legacy.number}`, `${legacy.repository}#${legacy.number}`, legacy.url] : [];
324}
325
326/** Older V2 event payloads stored one link; an explicit empty array means it was unlinked. */
327export function threadPullRequestsOf(thread: {
328 readonly pullRequests?: ReadonlyArray<ThreadPullRequestLink> | undefined;
329 readonly linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
330}): ReadonlyArray<ThreadPullRequestLink> {
331 if (thread.pullRequests !== undefined) return thread.pullRequests;
332 const linked = thread.linkedPullRequest;
333 return linked == null
334 ? []
335 : [
336 {
337 ...legacyThreadPullRequestKey(linked),
338 url: linked.url,
339 source: "manual",
340 linkedAt: "1970-01-01T00:00:00.000Z",
341 snapshot: null,
342 stack: null,
343 },
344 ];
345}