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

openPullRequestLink.ts

368 lines14.8 KB

1import type {
2 EnvironmentId,
3 LocalApi,
4 RepositoryIdentity,
5 ScopedThreadRef,
6 ThreadLinkedPullRequest,
7} from "@t3tools/contracts";
8import { useNavigate } from "@tanstack/react-router";
9import * as Schema from "effect/Schema";
10import { type MouseEvent, useCallback } from "react";
11​
12import { pullRequestHostOf, type SourceControlProviderKind } from "@t3tools/contracts";
13​
14import { stackedThreadToast, toastManager } from "../components/ui/toast";
15import { readLocalApi } from "../localApi";
16import { useRightPanelStore } from "../rightPanelStore";
17import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
18​
19import { useProjects, useServerConfigs } from "../state/entities";
20import { usePrimaryEnvironmentId } from "../state/environments";
21​
22export class PullRequestLinkOpenError extends Schema.TaggedErrorClass<PullRequestLinkOpenError>()(
23 "PullRequestLinkOpenError",
24 {
25 targetOrigin: Schema.NullOr(Schema.String),
26 cause: Schema.Defect(),
27 },
28) {
29 static fromCause(targetUrl: string, cause: unknown): PullRequestLinkOpenError {
30 let targetOrigin: string | null = null;
31 try {
32 targetOrigin = new URL(targetUrl).origin;
33 } catch {
34 // Keep malformed URLs out of diagnostics while preserving the open failure below.
35 }
36 return new PullRequestLinkOpenError({ targetOrigin, cause });
37 }
38​
39 override get message(): string {
40 return this.targetOrigin === null
41 ? "Unable to open pull request link."
42 : `Unable to open pull request link at ${this.targetOrigin}.`;
43 }
45​
46export async function openPullRequestLink(
47 shell: Pick<LocalApi["shell"], "openExternal">,
48 targetUrl: string,
49): Promise<void> {
50 try {
51 await shell.openExternal(targetUrl);
52 } catch (cause) {
53 throw PullRequestLinkOpenError.fromCause(targetUrl, cause);
54 }
56​
57/** Builds a GitHub URL that remains available when the pull request API cannot be read. */
58export function gitHubPullRequestBrowserUrl(
59 identity: RepositoryIdentity | null | undefined,
60 repository: string,
61 number: number,
62): string | null {
63 if (identity?.provider !== "github" || !Number.isSafeInteger(number) || number < 1) return null;
64 const repositoryPath = repository.split("/");
65 if (
66 repositoryPath.length !== 2 ||
67 repositoryPath.some((segment) => segment.length === 0 || segment === "." || segment === "..")
68 ) {
69 return null;
70 }
71​
72 let origin: string | null = null;
73 try {
74 const remoteUrl = new URL(identity.locator.remoteUrl.trim());
75 if (remoteUrl.protocol === "http:" || remoteUrl.protocol === "https:") {
76 origin = remoteUrl.origin;
77 }
78 } catch {
79 // SCP-style remotes are read from their normalized identity below.
80 }
81 const hostname = identity.canonicalKey.split("/")[0];
82 if (origin === null && !hostname) return null;
83​
84 try {
85 const url = new URL(origin ?? `https://${hostname}`);
86 url.pathname = `/${repositoryPath.join("/")}/pull/${number}`;
87 return url.toString();
88 } catch {
89 return null;
90 }
92​
93/**
94 * A change request the page can open, named the way the page names one: the host below which the
95 * repository is addressed, the repository path as that host writes it, and the number.
96 *
97 * The two strings are what `pullRequestHostOf` and the project's `repositoryIdentity` produce
98 * from a git remote — lower case, no port, the full path below the host — because the page matches
99 * a link against those. Anything else opens nothing.
100 */
101export interface ChangeRequestLink {
102 readonly host: string;
103 readonly repository: string;
104 readonly number: number;
106​
107/** The host itself, one of its subdomains, or an install named after the provider. */
108function isHostOf(hostname: string, apex: string, label?: string): boolean {
109 if (hostname === apex || hostname.endsWith(`.${apex}`)) return true;
110 return label !== undefined && hostname.startsWith(`${label}.`);
112​
113/**
114 * The repository and number behind a change request URL on a host the page can read, or null for
115 * anything else — an issue, a commit, a repository root, a host this cannot tell apart from an
116 * ordinary link. Null means the system browser, so a doubtful match is worse than no match: it
117 * takes the reader out of their browser and into a page that cannot find the change request.
118 *
119 * Each host is recognised by the path shape it alone uses, guarded by a hostname it could
120 * plausibly be served from, since self-hosted installs are named whatever their admin chose:
121 * GitLab's `/-/` marker is unique enough to trust on any hostname, while `/pull/` is generic
122 * enough that it is only believed from a GitHub-ish host.
123 */
124export function parseChangeRequestUrl(targetUrl: string): ChangeRequestLink | null {
125 let url: URL;
126 try {
127 url = new URL(targetUrl);
128 } catch {
129 return null;
130 }
131 // `javascript:`, `mailto:` and friends have no host to speak of and nothing to open.
132 if (url.protocol !== "https:" && url.protocol !== "http:") return null;
133 // Nothing here tries to tell a lookalike hostname from a real one — `github.com.evil.test`,
134 // `github.com-evil.test` and the rest are an open set, and blocking spellings of it costs real
135 // hosts (`gitlab.com.br` is a registrable domain, not a disguise). What a claim is worth is
136 // decided where it is used: only a link matching a repository this workspace has checked out
137 // opens the page, and everything else stays the ordinary link it was.
138 const host = url.hostname.toLowerCase();
139​
140 // GitHub, and any Enterprise install: /{owner}/{repo}/pull/{n}
141 if (isHostOf(host, "github.com", "github")) {
142 const match = /^\/([^/]+\/[^/]+)\/pull\/(\d+)(?:\/|$)/u.exec(url.pathname);
143 return claim(host, match);
144 }
145 // GitLab, self-hosted included: /{group}/[{subgroup}/...]{repo}/-/merge_requests/{n}. The `/-/`
146 // separator is GitLab's own, so the hostname is not asked about.
147 const gitlab = /^\/([^/]+(?:\/[^/]+)+)\/-\/merge_requests\/(\d+)(?:\/|$)/u.exec(url.pathname);
148 if (gitlab) return claim(host, gitlab);
149 // Bitbucket Cloud: /{workspace}/{repo}/pull-requests/{n}
150 if (isHostOf(host, "bitbucket.org", "bitbucket")) {
151 const match = /^\/([^/]+\/[^/]+)\/pull-requests\/(\d+)(?:\/|$)/u.exec(url.pathname);
152 return claim(host, match);
153 }
154 // Azure DevOps, both the current host and the per-organisation one it replaced. `_git` is part
155 // of the repository path there, as it is in the remote URL the identity is read from.
156 if (isHostOf(host, "dev.azure.com") || host.endsWith(".visualstudio.com")) {
157 const match = /^\/((?:[^/]+\/)*_git\/[^/]+)\/pullrequest\/(\d+)(?:\/|$)/u.exec(url.pathname);
158 return claim(host, match);
159 }
160 return null;
162​
163/** Match a stored PR without requiring its project to remain available. */
164export function matchesLinkedPullRequestUrl(
165 linkedPullRequest: ThreadLinkedPullRequest,
166 targetUrl: string,
167): boolean {
168 const linked = parseChangeRequestUrl(linkedPullRequest.url);
169 const target = parseChangeRequestUrl(targetUrl);
170 return (
171 linked !== null &&
172 target !== null &&
173 linked.host === target.host &&
174 linked.repository === target.repository &&
175 linked.number === target.number
176 );
178​
179/** The repository root behind a recognised change-request URL, without PR-specific state. */
180export function changeRequestRepositoryUrl(targetUrl: string): string | null {
181 const changeRequest = parseChangeRequestUrl(targetUrl);
182 if (changeRequest === null) return null;
183 const url = new URL(targetUrl);
184 const repositoryPath =
185 /^(.*?)\/-\/merge_requests\/\d+(?:\/|$)/iu.exec(url.pathname)?.[1] ??
186 /^(.*?)(?:\/pull\/\d+|\/-\/merge_requests\/\d+|\/pull-requests\/\d+|\/pullrequest\/\d+)(?:\/|$)/iu.exec(
187 url.pathname,
188 )?.[1];
189 if (!repositoryPath) return null;
190 url.pathname = repositoryPath;
191 url.search = "";
192 url.hash = "";
193 return url.toString();
195​
196function claim(host: string, match: RegExpExecArray | null): ChangeRequestLink | null {
197 const repository = match?.[1];
198 const number = Number(match?.[2]);
199 return repository && Number.isSafeInteger(number) && number > 0
200 ? { host, repository: repository.toLowerCase(), number }
201 : null;
203​
204/**
205 * Returns a click handler that opens a pull request URL in the system browser.
206 *
207 * Stops event propagation/default so activating the link does not also trigger
208 * an enclosing row or trigger (e.g. opening the branch dropdown), and surfaces a
209 * toast when the local API is unavailable or the open fails.
210 */
211/**
212 * The project a link belongs to, or nothing. Matched the way the server matches: the repository
213 * identity is the full path below the host where one was recorded — which is what nested GitLab
214 * groups and Azure project paths need — and the host is the first segment of the canonical
215 * remote, so github.com and an Enterprise install stay apart.
216 */
217export function findProjectForChangeRequest(
218 projects: ReadonlyArray<EnvironmentProject>,
219 link: ChangeRequestLink,
220): EnvironmentProject | undefined {
221 return projects.find((project) => {
222 const identity = project.repositoryIdentity;
223 if (!identity) return false;
224 const kind = identity.provider as SourceControlProviderKind | undefined;
225 if (kind === undefined) return false;
226 const repository =
227 identity.displayName ??
228 (identity.owner && identity.name ? `${identity.owner}/${identity.name}` : null);
229 return (
230 repository !== null &&
231 repository.toLowerCase() === link.repository.toLowerCase() &&
232 pullRequestHostOf(identity, kind) === link.host.toLowerCase()
233 );
234 });
236​
237/**
238 * Opens a change request link on the page, and says whether it did. Anything else — another
239 * organisation's repository, a host nothing here is checked out from, a link that merely looks
240 * like one — is left alone for the caller to handle as the ordinary link it is.
241 *
242 * Resolving the project here rather than on the page is what makes recognising a URL safe: a
243 * lookalike hostname matches no project and stays a link, and the page is handed the project
244 * rather than a host to narrow its whole list by.
245 *
246 * Given a thread, the link opens beside it in the right panel instead of taking the whole app to
247 * the pull requests page: a reader following a link the agent wrote is reading the thread, and
248 * should still be reading it afterwards. Any change request opens there, not only the thread's
249 * own, since the panel is told which one to show.
250 */
251export function shouldOpenPullRequestExternally(
252 event: Pick<MouseEvent<HTMLElement>, "metaKey" | "ctrlKey">,
253): boolean {
254 return event.metaKey || event.ctrlKey;
256​
257export function useOpenChangeRequestLink(
258 threadRef?: ScopedThreadRef,
259): (
260 event: Pick<
261 MouseEvent<HTMLElement>,
262 "preventDefault" | "stopPropagation" | "metaKey" | "ctrlKey"
263 >,
264 targetUrl: string,
265 targetThreadRef?: ScopedThreadRef,
266) => boolean {
267 const navigate = useNavigate();
268 const allProjects = useProjects();
269 const serverConfigs = useServerConfigs();
270 const primaryEnvironmentId = usePrimaryEnvironmentId();
271 return useCallback(
272 (event, targetUrl, targetThreadRef) => {
273 if (shouldOpenPullRequestExternally(event)) return false;
274 const resolvedThreadRef = targetThreadRef ?? threadRef;
275 const parsed = parseChangeRequestUrl(targetUrl);
276 if (parsed === null) return false;
277 const reads = (environmentId: string) =>
278 serverConfigs.get(environmentId as EnvironmentId)?.environment.capabilities.pullRequests ===
279 true;
280 // Beside a thread the panel reads on that thread's environment, so a project from another
281 // one could not be read there whatever its remote says: two environments can hold the same
282 // repository, and handing the panel the wrong one's id opens a surface that never loads.
283 //
284 // The page has no such tie — it lists every server at once — so the link is resolved
285 // against all of them, the primary first where two hold the same repository.
286 const projects = resolvedThreadRef
287 ? allProjects.filter((project) => project.environmentId === resolvedThreadRef.environmentId)
288 : allProjects
289 .filter((project) => reads(project.environmentId))
290 .toSorted(
291 (left, right) =>
292 Number(right.environmentId === primaryEnvironmentId) -
293 Number(left.environmentId === primaryEnvironmentId),
294 );
295 const project = findProjectForChangeRequest(projects, parsed);
296 if (project === undefined || !reads(project.environmentId)) return false;
297 event.preventDefault();
298 event.stopPropagation();
299 if (resolvedThreadRef) {
300 useRightPanelStore.getState().openPullRequest(resolvedThreadRef, {
301 projectId: project.id,
302 // The identity's own spelling, not the one read out of the URL: the panel asks the
303 // provider for this repository, while matching a link only ever compares lower case.
304 repository: project.repositoryIdentity?.displayName ?? parsed.repository,
305 number: parsed.number,
306 });
307 return true;
308 }
309 void navigate({
310 to: "/pull-requests",
311 search: {
312 involvement: "all",
313 // Every state, so the pull request being opened is also in the list behind it whether
314 // it is open, merged or closed.
315 state: "all",
316 repository: parsed.repository,
317 number: parsed.number,
318 selectedProjectId: project.id,
319 // Named so the page opens the right one of two servers holding this project.
320 selectedEnvironmentId: project.environmentId,
321 },
322 });
323 return true;
324 },
325 [allProjects, navigate, primaryEnvironmentId, serverConfigs, threadRef],
326 );
328​
329export function useOpenPrLink(threadRef?: ScopedThreadRef) {
330 const openChangeRequest = useOpenChangeRequestLink(threadRef);
331 return useCallback(
332 (event: MouseEvent<HTMLElement>, prUrl: string, targetThreadRef?: ScopedThreadRef) => {
333 event.stopPropagation();
334 const openInBrowser = shouldOpenPullRequestExternally(event);
335 const isAnchor =
336 event.currentTarget instanceof HTMLAnchorElement && event.currentTarget.href.length > 0;
337 // A real link already knows how to cmd/ctrl+click. Leave its default
338 // action alone so the browser (or Electron's window-open handler) opens
339 // the host. Buttons have no href, so they still go through openExternal.
340 if (openInBrowser && isAnchor) return false;
341​
342 event.preventDefault();
343 if (!openInBrowser && openChangeRequest(event, prUrl, targetThreadRef)) return true;
344​
345 const api = readLocalApi();
346 if (!api) {
347 toastManager.add({
348 type: "error",
349 title: "Link opening is unavailable.",
350 });
351 return false;
352 }
353​
354 void openPullRequestLink(api.shell, prUrl).catch((error) => {
355 console.error(error);
356 toastManager.add(
357 stackedThreadToast({
358 type: "error",
359 title: "Unable to open pull request link",
360 description: error instanceof Error ? error.message : "An error occurred.",
361 }),
362 );
363 });
364 return false;
365 },
366 [openChangeRequest],
367 );