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

threadPullRequests.ts

413 lines14.8 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 const order = new Map(members[0]!.stack!.layers.map((layer, index) => [layer.number, index]));
234 members.sort((left, right) => (order.get(left.number) ?? 0) - (order.get(right.number) ?? 0));
235 for (const member of members) placed.add(threadPullRequestKeyOf(member));
236 chains.push({ kind: "native", layers: members, depths: members.map((_, index) => index) });
237 }
238​
239 const remaining = visible.filter((link) => !placed.has(threadPullRequestKeyOf(link)));
240 const branchKey = (link: ThreadPullRequestLink, branch: string) => {
241 const key = normalizedKeyOf(link);
242 return `${key.host}/${key.repository}:${branch}`;
243 };
244 const byHead = new Map<string, ThreadPullRequestLink | null>();
245 for (const link of remaining) {
246 if (link.snapshot === null) continue;
247 const key = branchKey(link, link.snapshot.headBranch);
248 byHead.set(key, byHead.has(key) ? null : link);
249 }
250 const parentOf = (link: ThreadPullRequestLink) => {
251 if (link.snapshot === null) return undefined;
252 const parent = byHead.get(branchKey(link, link.snapshot.baseBranch));
253 return parent == null || parent === link ? undefined : parent;
254 };
255 const children = new Map<string, Array<ThreadPullRequestLink>>();
256 for (const link of remaining) {
257 const parent = parentOf(link);
258 if (parent === undefined) continue;
259 const key = threadPullRequestKeyOf(parent);
260 const siblings = children.get(key) ?? [];
261 siblings.push(link);
262 children.set(key, siblings);
263 }
264 for (const base of remaining) {
265 if (parentOf(base) !== undefined) continue;
266 const layers: Array<ThreadPullRequestLink> = [];
267 const depths: Array<number> = [];
268 const pending: Array<{ readonly link: ThreadPullRequestLink; readonly depth: number }> = [
269 { link: base, depth: 0 },
270 ];
271 for (let next = pending.pop(); next !== undefined; next = pending.pop()) {
272 const key = threadPullRequestKeyOf(next.link);
273 // Two links with one identity would otherwise share a child list and expand forever.
274 if (placed.has(key)) continue;
275 placed.add(key);
276 layers.push(next.link);
277 depths.push(next.depth);
278 const below = children.get(key) ?? [];
279 for (let index = below.length - 1; index >= 0; index -= 1) {
280 pending.push({ link: below[index]!, depth: next.depth + 1 });
281 }
282 }
283 if (layers.length > 0) chains.push({ kind: "derived", layers, depths });
284 }
285 for (const link of remaining) {
286 if (!placed.has(threadPullRequestKeyOf(link))) {
287 chains.push({ kind: "derived", layers: [link], depths: [0] });
288 }
289 }
290 return chains;
292​
293export type ThreadPullRequestBadge = {
294 readonly state: "open" | "closed" | "merged" | "draft";
295} & (
296 | {
297 readonly kind: "stack";
298 readonly layers: number;
299 }
300 | { readonly kind: "pull-request"; readonly others: number }
301);
302​
303export function resolveThreadPullRequestBadge(
304 pullRequests: ReadonlyArray<ThreadPullRequestLink> | undefined,
305): ThreadPullRequestBadge | null {
306 const visible = visibleThreadPullRequests(pullRequests ?? []);
307 if (visible.length === 0) return null;
308 const states = visible.map((link) => link.snapshot?.state ?? "open");
309 const state = visible.every((link) => link.snapshot?.state === "open" && link.snapshot.isDraft)
310 ? "draft"
311 : states.includes("open")
312 ? "open"
313 : states.every((entry) => entry === "merged")
314 ? "merged"
315 : "closed";
316 const chains = resolveThreadPullRequestChains(visible);
317 if (visible.length > 1 && chains.length === 1) {
318 return { kind: "stack", layers: visible.length, state };
319 }
320 return { kind: "pull-request", others: visible.length - 1, state };
322​
323export function threadPullRequestSearchTerms(thread: {
324 readonly pullRequests?: ReadonlyArray<ThreadPullRequestLink> | undefined;
325 readonly linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
326 readonly branchPullRequest?: ThreadLinkedPullRequest | null | undefined;
327}): string[] {
328 const branch = thread.branchPullRequest;
329 const terms = branch
330 ? [`#${branch.number}`, `${branch.repository}#${branch.number}`, branch.url]
331 : [];
332 if (thread.pullRequests !== undefined && thread.pullRequests.length > 0) {
333 return terms.concat(
334 visibleThreadPullRequests(thread.pullRequests).flatMap((link) => [
335 `#${link.number}`,
336 `${link.repository}#${link.number}`,
337 link.url,
338 link.snapshot?.title ?? "",
339 ]),
340 );
341 }
342 const legacy = thread.linkedPullRequest;
343 return legacy
344 ? terms.concat([`#${legacy.number}`, `${legacy.repository}#${legacy.number}`, legacy.url])
345 : terms;
347​
348/** Older V2 event payloads stored one link; an explicit empty array means it was unlinked. */
349export function threadPullRequestsOf(thread: {
350 readonly pullRequests?: ReadonlyArray<ThreadPullRequestLink> | undefined;
351 readonly linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
352}): ReadonlyArray<ThreadPullRequestLink> {
353 if (thread.pullRequests !== undefined) return thread.pullRequests;
354 const linked = thread.linkedPullRequest;
355 return linked == null
356 ? []
357 : [
358 {
359 ...legacyThreadPullRequestKey(linked),
360 url: linked.url,
361 source: "manual",
362 linkedAt: "1970-01-01T00:00:00.000Z",
363 snapshot: null,
364 stack: null,
365 },
366 ];
368​
369export function applyThreadPullRequestLinkUpdate(
370 thread: OrchestrationV2AppThread,
371 updated: ThreadPullRequestLink,
372): OrchestrationV2AppThread {
373 return {
374 ...thread,
375 pullRequests: threadPullRequestsOf(thread).map((link) =>
376 threadPullRequestKeysEqual(link, updated) ? updated : link,
377 ),
378 };
380​
381export interface PullRequestListLine {
382 readonly link: ThreadPullRequestLink;
383 readonly depth: number;
384 readonly chainKey: string;
385 readonly stack: { readonly kind: ThreadPullRequestChain["kind"]; readonly size: number } | null;
387​
388function chainKeyOf(chain: ThreadPullRequestChain): string {
389 const bottom = chain.layers[0]!;
390 return `${bottom.host}/${bottom.repository}#${bottom.number}`;
392​
393export function pullRequestListLines(
394 chains: ReadonlyArray<ThreadPullRequestChain>,
395): ReadonlyArray<PullRequestListLine> {
396 const ordered = [...chains].sort(
397 (left, right) =>
398 Math.max(...right.layers.map(latestUpdatedAt)) -
399 Math.max(...left.layers.map(latestUpdatedAt)),
400 );
401 return ordered.flatMap((chain) => {
402 const chainKey = chainKeyOf(chain);
403 return chain.layers.map((link, index) => ({
404 link,
405 depth: chain.depths[index]!,
406 chainKey,
407 stack:
408 index === 0 && chain.layers.length > 1
409 ? { kind: chain.kind, size: chain.layers.length }
410 : null,
411 }));
412 });