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

threadPullRequests.ts

366 lines13.3 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​
72export function threadPullRequestKeyOf(key: ThreadPullRequestKeySource): string {
73 const normalized = normalizeThreadPullRequestKey(key);
74 return `${normalized.host}/${normalized.repository}#${normalized.number}`;
76​
77/** Tombstoned stack members stay in the array only so the
78 * sync reactor does not re-add them. */
79export function visibleThreadPullRequests(
80 links: ReadonlyArray<ThreadPullRequestLink>,
81): ReadonlyArray<ThreadPullRequestLink> {
82 return links.filter((link) => link.source !== "stack-dismissed");
84​
85function isOpen(link: ThreadPullRequestLink): boolean {
86 return link.snapshot === null || link.snapshot.state === "open";
88​
89function latestUpdatedAt(link: ThreadPullRequestLink): number {
90 const value = link.snapshot?.updatedAt ?? link.linkedAt;
91 const ms = Date.parse(value);
92 return Number.isNaN(ms) ? 0 : ms;
94​
95export type ThreadCurrentPullRequest =
96 | { readonly kind: "single"; readonly link: ThreadPullRequestLink }
97 | {
98 readonly kind: "stack";
99 readonly open: ReadonlyArray<ThreadPullRequestLink>;
100 readonly top: ThreadPullRequestLink;
101 };
102​
103function layersFromTop(chain: ThreadPullRequestChain): Array<ThreadPullRequestLink> {
104 // `.sort()` on a fresh array, not `.toSorted()`: this runs on Hermes, which has no ES2023
105 // array methods, and a TypeError here is fatal on every mobile launch that renders a stack.
106 return chain.layers
107 .map((link, index) => ({ link, index, depth: chain.depths[index]! }))
108 .sort((left, right) => right.depth - left.depth || right.index - left.index)
109 .map((entry) => entry.link);
111​
112export function resolveThreadCurrentPullRequest(
113 links: ReadonlyArray<ThreadPullRequestLink>,
114): ThreadCurrentPullRequest | null {
115 const visible = visibleThreadPullRequests(links);
116 if (visible.length === 0) return null;
117 const open = visible.filter(isOpen);
118 if (open.length === 1) return { kind: "single", link: open[0]! };
119 const chains = resolveThreadPullRequestChains(visible);
120 if (open.length > 1) {
121 const openChains = chains
122 .map((chain) => layersFromTop(chain).filter(isOpen))
123 .filter((layers) => layers.length > 0)
124 .sort(
125 (left, right) =>
126 Math.max(...right.map((link) => Date.parse(link.linkedAt))) -
127 Math.max(...left.map((link) => Date.parse(link.linkedAt))),
128 );
129 const ordered = openChains.flat();
130 return { kind: "stack", open: ordered, top: ordered[0]! };
131 }
132 if (chains.length === 1) {
133 return { kind: "single", link: layersFromTop(chains[0]!)[0]! };
134 }
135 const terminal = [...visible].sort(
136 (left, right) => latestUpdatedAt(right) - latestUpdatedAt(left),
137 );
138 return { kind: "single", link: terminal[0]! };
140​
141export function resolveThreadCurrentPullRequestLink(
142 links: ReadonlyArray<ThreadPullRequestLink>,
143): ThreadPullRequestLink | null {
144 const current = resolveThreadCurrentPullRequest(links);
145 if (current === null) return null;
146 return current.kind === "single" ? current.link : current.top;
148​
149export function legacyLinkedPullRequestOf(
150 links: ReadonlyArray<ThreadPullRequestLink>,
151 projectId: ThreadLinkedPullRequest["projectId"],
152 identity: RepositoryIdentity | null | undefined,
153): ThreadLinkedPullRequest | null {
154 if (!identity) return null;
155 const host = pullRequestHostOf(identity, identity.provider as SourceControlProviderKind);
156 if (typeof host !== "string") return null;
157 const repository = sourceControlRepositorySelector(identity);
158 if (repository === null) return null;
159 const azureKey =
160 identity.provider === "azure-devops"
161 ? canonicalRepositoryKey(identity.canonicalKey.toLowerCase())
162 : null;
163 const link = resolveThreadCurrentPullRequestLink(
164 links.filter((link) => {
165 if (azureKey !== null) {
166 const key = legacyThreadPullRequestKey(link, link.host);
167 return canonicalRepositoryKey(`${key.host}/${key.repository}`) === azureKey;
168 }
169 const parsed = parseChangeRequestUrl(link.url);
170 if (parsed?.authority !== undefined) {
171 try {
172 const remote = new URL(identity.locator.remoteUrl);
173 if (remote.protocol === "http:" || remote.protocol === "https:") {
174 return (
175 parsed.authority === remote.host && parsed.repository === repository.toLowerCase()
176 );
177 }
178 } catch {}
179 return parsed.host === host && parsed.repository === repository.toLowerCase();
180 }
181 return (
182 link.host.toLowerCase() === host.toLowerCase() &&
183 link.repository.toLowerCase() === repository.toLowerCase()
184 );
185 }),
186 );
187 if (link === null) return null;
188 return {
189 projectId,
190 repository: azureKey === null ? link.repository : repository,
191 number: link.number,
192 url: link.url,
193 };
195​
196export interface ThreadPullRequestChain {
197 readonly kind: "native" | "derived";
198 readonly layers: ReadonlyArray<ThreadPullRequestLink>;
199 /** One per layer: 0 for the base, parent's depth + 1 above it. Siblings share a depth. */
200 readonly depths: ReadonlyArray<number>;
202​
203export function resolveThreadPullRequestChains(
204 links: ReadonlyArray<ThreadPullRequestLink>,
205): ReadonlyArray<ThreadPullRequestChain> {
206 const visible = visibleThreadPullRequests(links);
207 const chains: Array<ThreadPullRequestChain> = [];
208 const placed = new Set<string>();
209​
210 const nativeStacks = new Map<string, Array<ThreadPullRequestLink>>();
211 for (const link of visible) {
212 if (link.stack === null) continue;
213 const key = normalizeThreadPullRequestKey(link);
214 const stackKey = `${key.host}/${key.repository}#stack:${link.stack.id}`;
215 const members = nativeStacks.get(stackKey) ?? [];
216 members.push(link);
217 nativeStacks.set(stackKey, members);
218 }
219 for (const members of nativeStacks.values()) {
220 const order = new Map(members[0]!.stack!.layers.map((layer, index) => [layer.number, index]));
221 members.sort((left, right) => (order.get(left.number) ?? 0) - (order.get(right.number) ?? 0));
222 for (const member of members) placed.add(threadPullRequestKeyOf(member));
223 chains.push({ kind: "native", layers: members, depths: members.map((_, index) => index) });
224 }
225​
226 const remaining = visible.filter((link) => !placed.has(threadPullRequestKeyOf(link)));
227 const branchKey = (link: ThreadPullRequestLink, branch: string) => {
228 const key = normalizeThreadPullRequestKey(link);
229 return `${key.host}/${key.repository}:${branch}`;
230 };
231 const byHead = new Map<string, ThreadPullRequestLink | null>();
232 for (const link of remaining) {
233 if (link.snapshot === null) continue;
234 const key = branchKey(link, link.snapshot.headBranch);
235 byHead.set(key, byHead.has(key) ? null : link);
236 }
237 const parentOf = (link: ThreadPullRequestLink) => {
238 if (link.snapshot === null) return undefined;
239 const parent = byHead.get(branchKey(link, link.snapshot.baseBranch));
240 return parent == null || parent === link ? undefined : parent;
241 };
242 const children = new Map<string, Array<ThreadPullRequestLink>>();
243 for (const link of remaining) {
244 const parent = parentOf(link);
245 if (parent === undefined) continue;
246 const key = threadPullRequestKeyOf(parent);
247 const siblings = children.get(key) ?? [];
248 siblings.push(link);
249 children.set(key, siblings);
250 }
251 for (const base of remaining) {
252 if (parentOf(base) !== undefined) continue;
253 const layers: Array<ThreadPullRequestLink> = [];
254 const depths: Array<number> = [];
255 const pending: Array<{ readonly link: ThreadPullRequestLink; readonly depth: number }> = [
256 { link: base, depth: 0 },
257 ];
258 for (let next = pending.pop(); next !== undefined; next = pending.pop()) {
259 const key = threadPullRequestKeyOf(next.link);
260 // Two links with one identity would otherwise share a child list and expand forever.
261 if (placed.has(key)) continue;
262 placed.add(key);
263 layers.push(next.link);
264 depths.push(next.depth);
265 const below = children.get(key) ?? [];
266 for (let index = below.length - 1; index >= 0; index -= 1) {
267 pending.push({ link: below[index]!, depth: next.depth + 1 });
268 }
269 }
270 if (layers.length > 0) chains.push({ kind: "derived", layers, depths });
271 }
272 for (const link of remaining) {
273 if (!placed.has(threadPullRequestKeyOf(link))) {
274 chains.push({ kind: "derived", layers: [link], depths: [0] });
275 }
276 }
277 return chains;
279​
280export type ThreadPullRequestBadge = {
281 readonly state: "open" | "closed" | "merged" | "draft";
282} & (
283 | {
284 readonly kind: "stack";
285 readonly layers: number;
286 }
287 | { readonly kind: "pull-request"; readonly others: number }
288);
289​
290export function resolveThreadPullRequestBadge(
291 pullRequests: ReadonlyArray<ThreadPullRequestLink> | undefined,
292): ThreadPullRequestBadge | null {
293 const visible = visibleThreadPullRequests(pullRequests ?? []);
294 if (visible.length === 0) return null;
295 const states = visible.map((link) => link.snapshot?.state ?? "open");
296 const state = visible.every((link) => link.snapshot?.state === "open" && link.snapshot.isDraft)
297 ? "draft"
298 : states.includes("open")
299 ? "open"
300 : states.every((entry) => entry === "merged")
301 ? "merged"
302 : "closed";
303 const chains = resolveThreadPullRequestChains(visible);
304 if (visible.length > 1 && chains.length === 1) {
305 return { kind: "stack", layers: visible.length, state };
306 }
307 return { kind: "pull-request", others: visible.length - 1, state };
309​
310export function threadPullRequestSearchTerms(thread: {
311 readonly pullRequests?: ReadonlyArray<ThreadPullRequestLink> | undefined;
312 readonly linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
313 readonly branchPullRequest?: ThreadLinkedPullRequest | null | undefined;
314}): string[] {
315 const branch = thread.branchPullRequest;
316 const terms = branch
317 ? [`#${branch.number}`, `${branch.repository}#${branch.number}`, branch.url]
318 : [];
319 if (thread.pullRequests !== undefined && thread.pullRequests.length > 0) {
320 return terms.concat(
321 visibleThreadPullRequests(thread.pullRequests).flatMap((link) => [
322 `#${link.number}`,
323 `${link.repository}#${link.number}`,
324 link.url,
325 link.snapshot?.title ?? "",
326 ]),
327 );
328 }
329 const legacy = thread.linkedPullRequest;
330 return legacy
331 ? terms.concat([`#${legacy.number}`, `${legacy.repository}#${legacy.number}`, legacy.url])
332 : terms;
334​
335/** Older V2 event payloads stored one link; an explicit empty array means it was unlinked. */
336export function threadPullRequestsOf(thread: {
337 readonly pullRequests?: ReadonlyArray<ThreadPullRequestLink> | undefined;
338 readonly linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
339}): ReadonlyArray<ThreadPullRequestLink> {
340 if (thread.pullRequests !== undefined) return thread.pullRequests;
341 const linked = thread.linkedPullRequest;
342 return linked == null
343 ? []
344 : [
345 {
346 ...legacyThreadPullRequestKey(linked),
347 url: linked.url,
348 source: "manual",
349 linkedAt: "1970-01-01T00:00:00.000Z",
350 snapshot: null,
351 stack: null,
352 },
353 ];
355​
356export function applyThreadPullRequestLinkUpdate(
357 thread: OrchestrationV2AppThread,
358 updated: ThreadPullRequestLink,
359): OrchestrationV2AppThread {
360 return {
361 ...thread,
362 pullRequests: threadPullRequestsOf(thread).map((link) =>
363 threadPullRequestKeysEqual(link, updated) ? updated : link,
364 ),
365 };