Open History to see the last commit
1import type {
2 OrchestrationV2AppThread,
3 ThreadLinkedPullRequest,
4 ThreadPullRequestKey,
5 ThreadPullRequestLink,
6} from "@t3tools/contracts";
7
8import { parseChangeRequestUrl } from "./changeRequestUrl.ts";
9import { canonicalRepositoryKey } from "./sourceControl.ts";
10
11type ThreadPullRequestKeySource = ThreadPullRequestKey & {
12 readonly authority?: string;
13 readonly url?: string;
14};
15
16export function normalizeThreadPullRequestKey(
17 key: ThreadPullRequestKeySource,
18): ThreadPullRequestKey {
19 const parsed = key.url === undefined ? null : parseChangeRequestUrl(key.url);
20 const authority =
21 key.authority ??
22 (parsed?.repository === key.repository.trim().toLowerCase() && parsed.number === key.number
23 ? parsed.authority
24 : undefined);
25 const canonical = canonicalRepositoryKey(
26 `${(authority ?? key.host).trim().toLowerCase()}/${key.repository.trim().toLowerCase()}`,
27 );
28 const separator = canonical.indexOf("/");
29 return {
30 host: canonical.slice(0, separator),
31 repository: canonical.slice(separator + 1),
32 number: key.number,
33 };
34}
35
36export function legacyThreadPullRequestKey(
37 linked: Pick<ThreadLinkedPullRequest, "repository" | "number" | "url">,
38 fallbackHost?: string,
39): ThreadPullRequestKey {
40 const parsed = parseChangeRequestUrl(linked.url);
41 if (parsed !== null && parsed.number === linked.number) {
42 const canonical = canonicalRepositoryKey(`${parsed.host}/${parsed.repository}`);
43 if (parsed.authority !== undefined || canonical.startsWith("dev.azure.com/")) {
44 return normalizeThreadPullRequestKey(parsed);
45 }
46 }
47 let host = fallbackHost;
48 if (host === undefined) {
49 try {
50 host = new URL(linked.url).hostname;
51 } catch {
52 host = "unknown";
53 }
54 }
55 return {
56 host: host.trim().toLowerCase() || "unknown",
57 repository: linked.repository.trim().toLowerCase(),
58 number: linked.number,
59 };
60}
61
62export function threadPullRequestKeysEqual(
63 left: ThreadPullRequestKeySource,
64 right: ThreadPullRequestKeySource,
65): boolean {
66 return threadPullRequestKeyOf(left) === threadPullRequestKeyOf(right);
67}
68
69// Clients re-derive chains for every link on each render, and normalizing parses the
70// link's URL. Links are immutable and keep their identity until they change.
71const normalizedKeys = new WeakMap<ThreadPullRequestKeySource, ThreadPullRequestKey>();
72
73function normalizedKeyOf(key: ThreadPullRequestKeySource): ThreadPullRequestKey {
74 let normalized = normalizedKeys.get(key);
75 if (normalized === undefined) {
76 normalized = normalizeThreadPullRequestKey(key);
77 normalizedKeys.set(key, normalized);
78 }
79 return normalized;
80}
81
82export function threadPullRequestKeyOf(key: ThreadPullRequestKeySource): string {
83 const normalized = normalizedKeyOf(key);
84 return `${normalized.host}/${normalized.repository}#${normalized.number}`;
85}
86
87/** Tombstoned stack members stay in the array only so the
88 * sync reactor does not re-add them. */
89export function visibleThreadPullRequests(
90 links: ReadonlyArray<ThreadPullRequestLink>,
91): ReadonlyArray<ThreadPullRequestLink> {
92 return links.filter((link) => link.source !== "stack-dismissed");
93}
94
95function isOpen(link: ThreadPullRequestLink): boolean {
96 return link.snapshot === null || link.snapshot.state === "open";
97}
98
99function latestUpdatedAt(link: ThreadPullRequestLink): number {
100 const value = link.snapshot?.updatedAt ?? link.linkedAt;
101 const ms = Date.parse(value);
102 return Number.isNaN(ms) ? 0 : ms;
103}
104
105export type ThreadCurrentPullRequest =
106 | { readonly kind: "single"; readonly link: ThreadPullRequestLink }
107 | {
108 readonly kind: "stack";
109 readonly open: ReadonlyArray<ThreadPullRequestLink>;
110 readonly top: ThreadPullRequestLink;
111 };
112
113function layersFromTop(chain: ThreadPullRequestChain): Array<ThreadPullRequestLink> {
114 // `.sort()` on a fresh array, not `.toSorted()`: this runs on Hermes, which has no ES2023
115 // array methods, and a TypeError here is fatal on every mobile launch that renders a stack.
116 return chain.layers
117 .map((link, index) => ({ link, index, depth: chain.depths[index]! }))
118 .sort((left, right) => right.depth - left.depth || right.index - left.index)
119 .map((entry) => entry.link);
120}
121
122export function resolveThreadCurrentPullRequest(
123 links: ReadonlyArray<ThreadPullRequestLink>,
124): ThreadCurrentPullRequest | null {
125 const visible = visibleThreadPullRequests(links);
126 if (visible.length === 0) return null;
127 const open = visible.filter(isOpen);
128 if (open.length === 1) return { kind: "single", link: open[0]! };
129 const chains = resolveThreadPullRequestChains(visible);
130 if (open.length > 1) {
131 const openChains = chains
132 .map((chain) => layersFromTop(chain).filter(isOpen))
133 .filter((layers) => layers.length > 0)
134 .sort(
135 (left, right) =>
136 Math.max(...right.map((link) => Date.parse(link.linkedAt))) -
137 Math.max(...left.map((link) => Date.parse(link.linkedAt))),
138 );
139 const ordered = openChains.flat();
140 return { kind: "stack", open: ordered, top: ordered[0]! };
141 }
142 if (chains.length === 1) {
143 return { kind: "single", link: layersFromTop(chains[0]!)[0]! };
144 }
145 const terminal = [...visible].sort(
146 (left, right) => latestUpdatedAt(right) - latestUpdatedAt(left),
147 );
148 return { kind: "single", link: terminal[0]! };
149}
150
151export function resolveThreadCurrentPullRequestLink(
152 links: ReadonlyArray<ThreadPullRequestLink>,
153): ThreadPullRequestLink | null {
154 const current = resolveThreadCurrentPullRequest(links);
155 if (current === null) return null;
156 return current.kind === "single" ? current.link : current.top;
157}
158
159export interface ThreadPullRequestChain {
160 readonly kind: "native" | "derived";
161 readonly layers: ReadonlyArray<ThreadPullRequestLink>;
162 /** One per layer: 0 for the base, parent's depth + 1 above it. Siblings share a depth. */
163 readonly depths: ReadonlyArray<number>;
164}
165
166export function resolveThreadPullRequestChains(
167 links: ReadonlyArray<ThreadPullRequestLink>,
168): ReadonlyArray<ThreadPullRequestChain> {
169 const visible = visibleThreadPullRequests(links);
170 const chains: Array<ThreadPullRequestChain> = [];
171 const placed = new Set<string>();
172
173 const nativeStacks = new Map<string, Array<ThreadPullRequestLink>>();
174 for (const link of visible) {
175 if (link.stack === null) continue;
176 const key = normalizedKeyOf(link);
177 const stackKey = `${key.host}/${key.repository}#stack:${link.stack.id}`;
178 const members = nativeStacks.get(stackKey) ?? [];
179 members.push(link);
180 nativeStacks.set(stackKey, members);
181 }
182 for (const members of nativeStacks.values()) {
183 // Saved snapshots can lag behind newer members of the same stack.
184 const memberNumbers = new Set(members.map((member) => member.number));
185 let layers = members[0]!.stack!.layers;
186 let coverage = layers.filter((layer) => memberNumbers.has(layer.number)).length;
187 for (const member of members.slice(1)) {
188 const candidate = member.stack!.layers;
189 const candidateCoverage = candidate.filter((layer) => memberNumbers.has(layer.number)).length;
190 if (
191 candidateCoverage > coverage ||
192 (candidateCoverage === coverage && candidate.length > layers.length)
193 ) {
194 layers = candidate;
195 coverage = candidateCoverage;
196 }
197 }
198 const order = new Map(layers.map((layer, index) => [layer.number, index]));
199 members.sort(
200 (left, right) =>
201 (order.get(left.number) ?? layers.length) - (order.get(right.number) ?? layers.length),
202 );
203 for (const member of members) placed.add(threadPullRequestKeyOf(member));
204 chains.push({ kind: "native", layers: members, depths: members.map((_, index) => index) });
205 }
206
207 const remaining = visible.filter((link) => !placed.has(threadPullRequestKeyOf(link)));
208 const branchKey = (link: ThreadPullRequestLink, branch: string) => {
209 const key = normalizedKeyOf(link);
210 return `${key.host}/${key.repository}:${branch}`;
211 };
212 const byHead = new Map<string, ThreadPullRequestLink | null>();
213 for (const link of remaining) {
214 if (link.snapshot === null) continue;
215 const key = branchKey(link, link.snapshot.headBranch);
216 byHead.set(key, byHead.has(key) ? null : link);
217 }
218 const parentOf = (link: ThreadPullRequestLink) => {
219 if (link.snapshot === null) return undefined;
220 const parent = byHead.get(branchKey(link, link.snapshot.baseBranch));
221 return parent == null || parent === link ? undefined : parent;
222 };
223 const children = new Map<string, Array<ThreadPullRequestLink>>();
224 for (const link of remaining) {
225 const parent = parentOf(link);
226 if (parent === undefined) continue;
227 const key = threadPullRequestKeyOf(parent);
228 const siblings = children.get(key) ?? [];
229 siblings.push(link);
230 children.set(key, siblings);
231 }
232 for (const base of remaining) {
233 if (parentOf(base) !== undefined) continue;
234 const layers: Array<ThreadPullRequestLink> = [];
235 const depths: Array<number> = [];
236 const pending: Array<{ readonly link: ThreadPullRequestLink; readonly depth: number }> = [
237 { link: base, depth: 0 },
238 ];
239 for (let next = pending.pop(); next !== undefined; next = pending.pop()) {
240 const key = threadPullRequestKeyOf(next.link);
241 // Two links with one identity would otherwise share a child list and expand forever.
242 if (placed.has(key)) continue;
243 placed.add(key);
244 layers.push(next.link);
245 depths.push(next.depth);
246 const below = children.get(key) ?? [];
247 for (let index = below.length - 1; index >= 0; index -= 1) {
248 pending.push({ link: below[index]!, depth: next.depth + 1 });
249 }
250 }
251 if (layers.length > 0) chains.push({ kind: "derived", layers, depths });
252 }
253 for (const link of remaining) {
254 if (!placed.has(threadPullRequestKeyOf(link))) {
255 chains.push({ kind: "derived", layers: [link], depths: [0] });
256 }
257 }
258 return chains;
259}
260
261export type ThreadPullRequestBadge = {
262 readonly state: "open" | "closed" | "merged" | "draft";
263} & (
264 | {
265 readonly kind: "stack";
266 readonly layers: number;
267 }
268 | { readonly kind: "pull-request"; readonly others: number }
269);
270
271export function resolveThreadPullRequestBadge(
272 pullRequests: ReadonlyArray<ThreadPullRequestLink> | undefined,
273): ThreadPullRequestBadge | null {
274 const visible = visibleThreadPullRequests(pullRequests ?? []);
275 if (visible.length === 0) return null;
276 const states = visible.map((link) => link.snapshot?.state ?? "open");
277 const state = visible.every((link) => link.snapshot?.state === "open" && link.snapshot.isDraft)
278 ? "draft"
279 : states.includes("open")
280 ? "open"
281 : states.every((entry) => entry === "merged")
282 ? "merged"
283 : "closed";
284 const chains = resolveThreadPullRequestChains(visible);
285 if (visible.length > 1 && chains.length === 1) {
286 return { kind: "stack", layers: visible.length, state };
287 }
288 return { kind: "pull-request", others: visible.length - 1, state };
289}
290
291export function threadPullRequestSearchTerms(thread: {
292 readonly pullRequests?: ReadonlyArray<ThreadPullRequestLink> | undefined;
293 readonly linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
294 readonly branchPullRequest?: ThreadLinkedPullRequest | null | undefined;
295}): string[] {
296 const branch = thread.branchPullRequest;
297 const terms = branch
298 ? [`#${branch.number}`, `${branch.repository}#${branch.number}`, branch.url]
299 : [];
300 if (thread.pullRequests !== undefined && thread.pullRequests.length > 0) {
301 return terms.concat(
302 visibleThreadPullRequests(thread.pullRequests).flatMap((link) => [
303 `#${link.number}`,
304 `${link.repository}#${link.number}`,
305 link.url,
306 link.snapshot?.title ?? "",
307 ]),
308 );
309 }
310 const legacy = thread.linkedPullRequest;
311 return legacy
312 ? terms.concat([`#${legacy.number}`, `${legacy.repository}#${legacy.number}`, legacy.url])
313 : terms;
314}
315
316/** Older V2 event payloads stored one link; an explicit empty array means it was unlinked. */
317export function threadPullRequestsOf(thread: {
318 readonly pullRequests?: ReadonlyArray<ThreadPullRequestLink> | undefined;
319 readonly linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
320}): ReadonlyArray<ThreadPullRequestLink> {
321 if (thread.pullRequests !== undefined) return thread.pullRequests;
322 const linked = thread.linkedPullRequest;
323 return linked == null
324 ? []
325 : [
326 {
327 ...legacyThreadPullRequestKey(linked),
328 url: linked.url,
329 source: "manual",
330 linkedAt: "1970-01-01T00:00:00.000Z",
331 snapshot: null,
332 stack: null,
333 },
334 ];
335}
336
337export function applyThreadPullRequestLinkUpdate(
338 thread: OrchestrationV2AppThread,
339 updated: ThreadPullRequestLink,
340): OrchestrationV2AppThread {
341 return {
342 ...thread,
343 pullRequests: threadPullRequestsOf(thread).map((link) =>
344 threadPullRequestKeysEqual(link, updated) ? updated : link,
345 ),
346 };
347}
348
349export interface PullRequestListLine {
350 readonly link: ThreadPullRequestLink;
351 readonly depth: number;
352 readonly chainKey: string;
353 readonly stack: { readonly kind: ThreadPullRequestChain["kind"]; readonly size: number } | null;
354}
355
356function chainKeyOf(chain: ThreadPullRequestChain): string {
357 const bottom = chain.layers[0]!;
358 return `${bottom.host}/${bottom.repository}#${bottom.number}`;
359}
360
361export function pullRequestListLines(
362 chains: ReadonlyArray<ThreadPullRequestChain>,
363): ReadonlyArray<PullRequestListLine> {
364 const ordered = [...chains].sort(
365 (left, right) =>
366 Math.max(...right.layers.map(latestUpdatedAt)) -
367 Math.max(...left.layers.map(latestUpdatedAt)),
368 );
369 return ordered.flatMap((chain) => {
370 const chainKey = chainKeyOf(chain);
371 return chain.layers.map((link, index) => ({
372 link,
373 depth: chain.depths[index]!,
374 chainKey,
375 stack:
376 index === 0 && chain.layers.length > 1
377 ? { kind: chain.kind, size: chain.layers.length }
378 : null,
379 }));
380 });
381}