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
78const LINEAR_LINK_HINT_PATTERN = new RegExp(
79 `${LINEAR_HOST.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/`,
80 "i",
81);
82
83/** A cheap pre-check, so text without such a link never asks for the bindings. */
84export function mayContainStandaloneIssueLink(text: string): boolean {
85 return LINEAR_LINK_HINT_PATTERN.test(text);
86}
87
88/**
89 * A standalone tracker link resolves through the project bound to its scope, else any bound to
90 * the tracker, and only through an account whose credential reaches the workspace it names: team
91 * keys repeat across workspaces, so a link elsewhere stays an ordinary link.
92 */
93function resolveStandaloneIssueLink<Project extends LinkProject>(
94 url: string,
95 projects: ReadonlyArray<Project>,
96 trackers: IssueTrackerConnectionList | undefined,
97 preferredProjectId: string | undefined,
98): { readonly project: Project; readonly ref: IssueRef } | null {
99 const parsed = trackers === undefined ? null : parseStandaloneIssueLink(url);
100 if (parsed === null || trackers === undefined) return null;
101 const { tracker, link } = parsed;
102 const accounts = new Set(
103 [...trackers.trackers, ...(trackers.accounts ?? [])]
104 .filter(
105 (connection) =>
106 connection.tracker === tracker &&
107 connection.account !== null &&
108 connection.workspace?.toLowerCase() === link.workspace.toLowerCase(),
109 )
110 .map((connection) => connection.accountId ?? null),
111 );
112 if (accounts.size === 0) return null;
113 const bindings = { ...trackers.bindings, ...trackers.accountBindings };
114 const onTracker = projects.flatMap((project) => {
115 const binding = bindings[project.id];
116 return binding?.tracker === tracker && accounts.has(binding.accountId ?? null)
117 ? [{ project, binding }]
118 : [];
119 });
120 const preferFirst = (candidates: typeof onTracker) =>
121 candidates.find((candidate) => candidate.project.id === preferredProjectId) ?? candidates[0];
122 const scope = link.scope.toLowerCase();
123 const boundScope = (candidate: (typeof onTracker)[number]) =>
124 issueTrackerBindingScopes(candidate.binding).find((key) => key.toLowerCase() === scope);
125 const own = preferFirst(onTracker.filter((candidate) => boundScope(candidate) !== undefined));
126 const lender = own ?? preferFirst(onTracker);
127 if (lender === undefined) return null;
128 return {
129 project: lender.project,
130 ref: {
131 projectId: lender.project.id,
132 tracker: lender.binding.tracker,
133 host: link.host,
134 scope: (own && boundScope(own)) ?? link.scope,
135 key: link.key,
136 },
137 };
138}
139
140/**
141 * The reference an issue link resolves to, and the project it is read through: the project whose
142 * tracker binding is that host and scope, else any project on the same tracker and host lending
143 * its credentials for a read-only view. The same rule as the server's `IssueService.resolveUrl`,
144 * applied on the client so a lookalike hostname matches no project and stays an ordinary link.
145 */
146export function resolveIssueLinkTarget<Project extends LinkProject>(input: {
147 readonly url: string;
148 /** The projects of the environment the link is read in. */
149 readonly projects: ReadonlyArray<Project>;
150 readonly preferredProjectId?: string | undefined;
151 /** The environment's standalone trackers and bindings; without them only git-host links resolve. */
152 readonly trackers?: IssueTrackerConnectionList | undefined;
153}): { readonly project: Project; readonly ref: IssueRef } | null {
154 // A link names its server's port; a binding does only when its remote or web URL did.
155 const authority = linkAuthority(input.url);
156 const parsed = parseIssueLink(input.url, authority, input.projects);
157 if (parsed === null)
158 return resolveStandaloneIssueLink(
159 input.url,
160 input.projects,
161 input.trackers,
162 input.preferredProjectId,
163 );
164 const { definition, link } = parsed;
165 const onHost = input.projects.flatMap((project) =>
166 projectIssueBindings(project)
167 .filter(
168 (binding) =>
169 binding.tracker === definition.kind &&
170 (binding.host === link.host || binding.host === authority),
171 )
172 .map((binding) => ({ project, binding })),
173 );
174 const onAuthority = onHost.filter((candidate) => candidate.binding.host === authority);
175 const bound = onAuthority.length > 0 ? onAuthority : onHost;
176 const preferFirst = (candidates: typeof bound) =>
177 candidates.find((candidate) => candidate.project.id === input.preferredProjectId) ??
178 candidates[0];
179 const own =
180 preferFirst(bound.filter((candidate) => candidate.binding.scope === link.scope)) ??
181 preferFirst(bound.filter((candidate) => candidate.binding.scope === link.scopeAlias));
182 const lender = own ?? preferFirst(bound);
183 if (lender === undefined) return null;
184 return {
185 project: lender.project,
186 ref: {
187 projectId: lender.project.id,
188 tracker: IssueTrackerKind.make(lender.binding.tracker),
189 host: lender.binding.host,
190 scope: own === undefined ? link.scope : lender.binding.scope,
191 key: link.key,
192 },
193 };
194}