Open History to see the last commit
1import {
2 IssueTrackerKind,
3 issueTrackerBindingScopes,
4 type IssueRef,
5 type IssueTrackerConnectionList,
6 type RepositoryIdentity,
7} from "@t3tools/contracts";
8import {
9 LINEAR_HOST,
10 LINEAR_KIND,
11 parseLinearIssueUrl,
12} from "@t3tools/issue-tracker-linear/shared/issueUrl";
13
14import { sourceControlClients } from "./sourceControlClients.ts";
15import type { EnvironmentProject } from "./state/shell.ts";
16
17type LinkProject = Pick<EnvironmentProject, "id" | "environmentId" | "repositoryIdentity">;
18
19const issueBindingsByRepository = new WeakMap<
20 RepositoryIdentity,
21 ReturnType<typeof sourceControlClients.issueBindings>
22>();
23
24/** The hosts and scopes a project's git-host tracker is bound to, the way the server resolves them. */
25function projectIssueBindings(project: LinkProject) {
26 const identity = project.repositoryIdentity;
27 if (identity == null) return [];
28 const cached = issueBindingsByRepository.get(identity);
29 if (cached !== undefined) return cached;
30 const bindings = sourceControlClients
31 .issueBindings(identity)
32 .map((binding) => ({ ...binding, scope: binding.scope.toLowerCase() }));
33 issueBindingsByRepository.set(identity, bindings);
34 return bindings;
35}
36
37function linkAuthority(url: string): string | null {
38 try {
39 return new URL(url).host.toLowerCase();
40 } catch {
41 return null;
42 }
43}
44
45/** A host whose hostname does not name it, such as GitHub Enterprise Server, is vouched for by a project on it. */
46function parseIssueLink(
47 url: string,
48 authority: string | null,
49 projects: ReadonlyArray<LinkProject>,
50) {
51 const parsed = sourceControlClients.parseIssueUrl(url);
52 if (parsed !== null || authority === null) return parsed;
53 const hostname = new URL(url).hostname.toLowerCase();
54 for (const project of projects) {
55 const bindings = projectIssueBindings(project);
56 if (!bindings.some((binding) => binding.host === hostname || binding.host === authority))
57 continue;
58 const known = sourceControlClients.parseIssueUrl(url, project.repositoryIdentity?.provider);
59 if (known !== null) return known;
60 }
61 return null;
62}
63
64function parseStandaloneIssueLink(url: string) {
65 try {
66 const link = parseLinearIssueUrl(new URL(url));
67 return link === null ? null : { tracker: LINEAR_KIND, link };
68 } catch {
69 return null;
70 }
71}
72
73/** Whether `url` is a standalone tracker's issue link, which only bindings can resolve. */
74export function isStandaloneIssueLink(url: string): boolean {
75 return parseStandaloneIssueLink(url) !== null;
76}
77
78/** A cheap pre-check, so text without such a link never asks for the bindings. */
79export function mayContainStandaloneIssueLink(text: string): boolean {
80 return text.includes(`${LINEAR_HOST}/`);
81}
82
83/**
84 * A standalone tracker link resolves through the project bound to its scope, else any bound to
85 * the tracker, and only when it names the workspace the credential reaches: team keys repeat
86 * across workspaces, so a link elsewhere stays an ordinary link.
87 */
88function resolveStandaloneIssueLink<Project extends LinkProject>(
89 url: string,
90 projects: ReadonlyArray<Project>,
91 trackers: IssueTrackerConnectionList | undefined,
92 preferredProjectId: string | undefined,
93): { readonly project: Project; readonly ref: IssueRef } | null {
94 const parsed = trackers === undefined ? null : parseStandaloneIssueLink(url);
95 if (parsed === null || trackers === undefined) return null;
96 const { tracker, link } = parsed;
97 const workspace = trackers.trackers.find(
98 (connection) => connection.tracker === tracker && connection.account !== null,
99 )?.workspace;
100 if (workspace?.toLowerCase() !== link.workspace.toLowerCase()) return null;
101 const { bindings } = trackers;
102 const onTracker = projects.flatMap((project) => {
103 const binding = bindings[project.id];
104 return binding?.tracker === tracker ? [{ project, binding }] : [];
105 });
106 const preferFirst = (candidates: typeof onTracker) =>
107 candidates.find((candidate) => candidate.project.id === preferredProjectId) ?? candidates[0];
108 const scope = link.scope.toLowerCase();
109 const boundScope = (candidate: (typeof onTracker)[number]) =>
110 issueTrackerBindingScopes(candidate.binding).find((key) => key.toLowerCase() === scope);
111 const own = preferFirst(onTracker.filter((candidate) => boundScope(candidate) !== undefined));
112 const lender = own ?? preferFirst(onTracker);
113 if (lender === undefined) return null;
114 return {
115 project: lender.project,
116 ref: {
117 projectId: lender.project.id,
118 tracker: lender.binding.tracker,
119 host: link.host,
120 scope: (own && boundScope(own)) ?? link.scope,
121 key: link.key,
122 },
123 };
124}
125
126/**
127 * The reference an issue link resolves to, and the project it is read through: the project whose
128 * tracker binding is that host and scope, else any project on the same tracker and host lending
129 * its credentials for a read-only view. The same rule as the server's `IssueService.resolveUrl`,
130 * applied on the client so a lookalike hostname matches no project and stays an ordinary link.
131 */
132export function resolveIssueLinkTarget<Project extends LinkProject>(input: {
133 readonly url: string;
134 /** The projects of the environment the link is read in. */
135 readonly projects: ReadonlyArray<Project>;
136 readonly preferredProjectId?: string | undefined;
137 /** The environment's standalone trackers and bindings; without them only git-host links resolve. */
138 readonly trackers?: IssueTrackerConnectionList | undefined;
139}): { readonly project: Project; readonly ref: IssueRef } | null {
140 // A link names its server's port; a binding does only when its remote or web URL did.
141 const authority = linkAuthority(input.url);
142 const parsed = parseIssueLink(input.url, authority, input.projects);
143 if (parsed === null)
144 return resolveStandaloneIssueLink(
145 input.url,
146 input.projects,
147 input.trackers,
148 input.preferredProjectId,
149 );
150 const { definition, link } = parsed;
151 const onHost = input.projects.flatMap((project) =>
152 projectIssueBindings(project)
153 .filter(
154 (binding) =>
155 binding.tracker === definition.kind &&
156 (binding.host === link.host || binding.host === authority),
157 )
158 .map((binding) => ({ project, binding })),
159 );
160 const onAuthority = onHost.filter((candidate) => candidate.binding.host === authority);
161 const bound = onAuthority.length > 0 ? onAuthority : onHost;
162 const preferFirst = (candidates: typeof bound) =>
163 candidates.find((candidate) => candidate.project.id === input.preferredProjectId) ??
164 candidates[0];
165 const own =
166 preferFirst(bound.filter((candidate) => candidate.binding.scope === link.scope)) ??
167 preferFirst(bound.filter((candidate) => candidate.binding.scope === link.scopeAlias));
168 const lender = own ?? preferFirst(bound);
169 if (lender === undefined) return null;
170 return {
171 project: lender.project,
172 ref: {
173 projectId: lender.project.id,
174 tracker: IssueTrackerKind.make(lender.binding.tracker),
175 host: lender.binding.host,
176 scope: own === undefined ? link.scope : lender.binding.scope,
177 key: link.key,
178 },
179 };
180}