Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

threadPullRequests.ts

431 lines15.5 KB

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