The best way to control Claude Code, Codex and more from any computer or phone

main
ts 971 lines 38.7 KB
Raw
1 import {
2 type PullRequestAction,
3 type PullRequestReviewVerdict,
4 type RepositoryIdentity,
5 secretSetting,
6 SettingsSecretValue,
7 SourceControlProviderKind,
8 type SourceControlProviderInfo,
9 TrimmedNonEmptyString,
10 TrimmedString,
11 } from "@t3tools/contracts";
12 import {
13 canonicalRepositoryPath,
14 normalizeGitRemoteUrl,
15 parseGitRemoteRepository,
16 } from "@t3tools/shared/git";
17 import { userlessScpRemoteHost } from "@t3tools/shared/sourceControl";
18 import * as Effect from "effect/Effect";
19 import * as Schema from "effect/Schema";
20 import * as SchemaTransformation from "effect/SchemaTransformation";
21
22 /**
23 * The two strings are what `changeRequestHost` and the project's `repositoryIdentity` produce
24 * from a git remote — lower case, no port, the full path below the host — because links are
25 * matched against those. `authority` keeps the port for hosts whose identity includes it.
26 */
27 export interface ChangeRequestLink {
28 readonly host: string;
29 readonly repository: string;
30 readonly number: number;
31 readonly authority?: string;
32 }
33
34 /**
35 * An issue as a URL names it: the host it is served from, the container the tracker addresses
36 * it by, and its native key there. Written like a project's own binding, lower case, because
37 * links are matched against those.
38 */
39 export interface IssueLink {
40 readonly host: string;
41 readonly scope: string;
42 /** An equivalent binding scope when the provider allows another spelling in URLs. */
43 readonly scopeAlias?: string;
44 readonly key: string;
45 }
46
47 export interface ParsedChangeRequestUrl extends ChangeRequestLink {
48 /** The repository's browser URL, without query or hash. */
49 readonly repositoryUrl: string;
50 }
51
52 export interface CommitLink {
53 readonly host: string;
54 readonly repository: string;
55 readonly sha: string;
56 readonly authority?: string;
57 }
58
59 export interface CommitUrlInput extends Omit<ChangeRequestUrlInput, "number"> {
60 readonly sha: string;
61 }
62
63 export interface ChangeRequestTerminology {
64 readonly shortLabel: string;
65 /** Spelled out because the article follows how the label is said: "an MR". */
66 readonly shortLabelWithArticle: string;
67 readonly singular: string;
68 readonly plural: string;
69 }
70
71 export interface ChangeRequestUrlInput {
72 readonly host: string;
73 readonly repository: string;
74 readonly number: number;
75 readonly remoteUrl?: string | undefined;
76 /** The repository's browser URL; when given, the result is this plus the host's route. */
77 readonly webUrl?: string | undefined;
78 }
79
80 export type ChangeRequestProjectIdentity = Pick<
81 RepositoryIdentity,
82 "canonicalKey" | "locator" | "webUrl" | "displayName" | "owner" | "name"
83 >;
84
85 export type ChangeRequestHostIdentity =
86 | {
87 readonly canonicalKey?: string | undefined;
88 readonly locator?: { readonly remoteUrl: string } | undefined;
89 readonly webUrl?: string | undefined;
90 }
91 | null
92 | undefined;
93
94 export type RepositorySelectorIdentity = Pick<
95 RepositoryIdentity,
96 "provider" | "displayName" | "owner" | "name"
97 >;
98
99 export type IssueScopeIdentity = RepositorySelectorIdentity &
100 Partial<Pick<RepositoryIdentity, "canonicalKey">>;
101
102 /** A git-host tracker a project's issues are read from and filed in. */
103 export interface IssueBinding {
104 readonly tracker: SourceControlProviderKind;
105 readonly host: string;
106 readonly scope: string;
107 }
108
109 /** A git remote's host, as `recognizeRemote` reads it. */
110 export interface GitRemoteHost {
111 /** Trimmed. */
112 readonly remoteUrl: string;
113 /** Lower case. Keeps the port of an HTTP remote, never an SSH one. */
114 readonly host: string;
115 /** `host` without its port. */
116 readonly hostname: string;
117 }
118
119 export interface ChangeRequestCheckoutInput {
120 readonly number: number;
121 readonly headBranch: string;
122 readonly headRepositoryNameWithOwner?: string | null | undefined;
123 readonly repositoryUrl?: string | null | undefined;
124 }
125
126 /** Media a host serves only to a request carrying a credential, as `mediaUrl` reads it. */
127 export interface SourceControlMediaUrl {
128 /** The canonical URL to fetch, the same for every spelling of one file. */
129 readonly fetchUrl: string;
130 /** A file name for the media, safe to put in a path or a download. */
131 readonly fileName: string;
132 /** Set when the URL alone says what the media is, as an extensionless upload can. */
133 readonly kind?: "image" | "video";
134 /** Set when the bytes behind `fetchUrl` can never change, so a client may cache them by it. */
135 readonly immutable?: true;
136 }
137
138 export interface ReferenceAutolink {
139 /** Where `text` starts in the string that was searched. */
140 readonly index: number;
141 readonly text: string;
142 /** What to show for the link, which can be shorter than `text`, as for a commit SHA. */
143 readonly label: string;
144 readonly url: string;
145 readonly kind: "reference" | "commit" | "mention";
146 }
147
148 /**
149 * A host's mark as data, so web and mobile draw the same artwork without React in the host's
150 * package. Paths only: a circle or rectangle is written as a path.
151 */
152 export interface SourceControlIcon {
153 readonly viewBox: string;
154 /** Always in user space, as `gradientUnits="userSpaceOnUse"`. */
155 readonly gradients?: ReadonlyArray<SourceControlIconGradient>;
156 readonly paths: ReadonlyArray<SourceControlIconPath>;
157 }
158
159 export interface SourceControlIconGradient {
160 /** Unique within the icon; renderers make it unique on the page. */
161 readonly id: string;
162 readonly x1: number;
163 readonly y1: number;
164 readonly x2: number;
165 readonly y2: number;
166 readonly transform?: string;
167 readonly stops: ReadonlyArray<{
168 readonly offset: number;
169 readonly color: string;
170 readonly opacity?: number;
171 }>;
172 }
173
174 /** A colour, `currentColor` for a mark drawn in the text colour, or one of the icon's gradients. */
175 export type SourceControlIconPaint = string | { readonly gradient: string };
176
177 export interface SourceControlIconPath {
178 readonly d: string;
179 /** Absent means unfilled. */
180 readonly fill?: SourceControlIconPaint;
181 readonly fillRule?: "evenodd" | "nonzero";
182 readonly fillOpacity?: number;
183 readonly stroke?: string;
184 readonly strokeWidth?: number;
185 }
186
187 /** Whether the mark is drawn in the text colour alone, so a client may tint it. */
188 export function isMonochromeSourceControlIcon(icon: SourceControlIcon): boolean {
189 return icon.paths.every(
190 (path) =>
191 (path.fill === undefined || path.fill === "currentColor") &&
192 (path.stroke === undefined || path.stroke === "currentColor"),
193 );
194 }
195
196 /**
197 * For a host whose server signs in per hostname, with a saved token or one of a CLI's logins.
198 * Its `settings` include `hostCredentialSettingsFields`, and clients show controls for those
199 * instead of the generic settings form.
200 */
201 export interface SourceControlHostCredentials {
202 /** The command name, as `gh`. */
203 readonly cliName: string;
204 /** The CLI's product name, as `GitHub CLI`. */
205 readonly cliLabel: string;
206 readonly loginCommand: string;
207 /** The variable the server reads a token from, which a saved token takes precedence over. */
208 readonly tokenEnvVar: string;
209 /** What a token must be granted, completing "Give it …". */
210 readonly tokenAccess: string;
211 readonly newTokenUrl: (host: string) => string;
212 /** Signing in through the forge's own app instead of a token or CLI login. */
213 readonly appSignIn?: SourceControlAppSignIn;
214 }
215
216 /**
217 * A forge app the server signs in to with a device code, on the hosts it is registered on. The
218 * session it keeps is the `signIns` setting, which takes precedence over everything but a saved
219 * token.
220 */
221 export interface SourceControlAppSignIn {
222 /** The app's name on the forge, as the consent screen shows it. */
223 readonly appName: string;
224 readonly hosts: ReadonlyArray<string>;
225 /** Where an account or organization installs the app so it can reach its repositories. */
226 readonly installUrl: string;
227 /** Where the user revokes the app's access entirely. */
228 readonly revokeUrl: string;
229 }
230
231 export const SourceControlHostName = TrimmedNonEmptyString.pipe(
232 Schema.decodeTo(Schema.String, SchemaTransformation.toLowerCase()),
233 );
234
235 export const HostAccountChoice = Schema.Struct({
236 account: Schema.optionalKey(TrimmedNonEmptyString),
237 enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
238 });
239 export type HostAccountChoice = typeof HostAccountChoice.Type;
240
241 /** Per-hostname settings of a host with `credentials`, keyed by lower-case hostname. */
242 export const hostCredentialSettingsFields = {
243 hosts: Schema.Record(SourceControlHostName, HostAccountChoice).pipe(
244 Schema.withDecodingDefault(Effect.succeed({})),
245 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
246 ),
247 tokens: Schema.Record(SourceControlHostName, SettingsSecretValue).pipe(
248 Schema.withDecodingDefault(Effect.succeed({})),
249 secretSetting,
250 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
251 ),
252 /** The serialized session of an `appSignIn`, owned by the server's driver. */
253 signIns: Schema.Record(SourceControlHostName, TrimmedString).pipe(
254 Schema.withDecodingDefault(Effect.succeed({})),
255 secretSetting,
256 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
257 ),
258 };
259
260 export const HostCredentialSettings = Schema.Struct(hostCredentialSettingsFields);
261 export type HostCredentialSettings = typeof HostCredentialSettings.Type;
262
263 /**
264 * What the server and every client know about a forge. It is plain data and pure functions so
265 * one copy serves both sides; a lint rule keeps UI runtimes out of `shared/`.
266 */
267 export interface SourceControlDefinition {
268 readonly kind: SourceControlProviderKind;
269 readonly label: string;
270 readonly pickerLabel: string;
271 /** Null for a host without a mark of its own; clients draw a generic change request glyph. */
272 readonly icon: SourceControlIcon | null;
273 /** Further words settings search finds this host by, besides its label. */
274 readonly searchKeywords?: ReadonlyArray<string>;
275 readonly credentials?: SourceControlHostCredentials;
276 readonly changeRequest: ChangeRequestTerminology;
277 readonly repositoryPathHint: string;
278 readonly publicHost: string | null;
279 readonly publishDescription: string;
280 readonly publishHost: (signedInHost: string | null) => string;
281 readonly newRepositoryOwner: (account: string | null) => { readonly owner: string | null } | null;
282 readonly defaultCloneTransport: "https" | "ssh";
283 readonly changeRequestUrl: (input: ChangeRequestUrlInput) => string | null;
284 readonly commitUrl?: (input: CommitUrlInput) => string | null;
285 /** `known` is set when the caller already knows this host serves the URL's repository. */
286 readonly parseCommitUrl?: (url: URL, known: boolean) => CommitLink | null;
287 /** Null when the URL is not one of this host's change requests. */
288 readonly parseChangeRequestUrl: (url: URL) => ParsedChangeRequestUrl | null;
289 /**
290 * Null when the URL is not one of this host's issues. Absent for a host with none. `known` is
291 * set when the caller already knows this host serves the URL's repository.
292 */
293 readonly parseIssueUrl?: (url: URL, known: boolean) => IssueLink | null;
294 /**
295 * The repository URL when `url` is a page inside one of this host's repositories. `known` is set
296 * when the caller already knows this host serves the URL's repository. Off a known host, return
297 * `url.href` when the path may already be a clone URL, so no rewrite happens.
298 */
299 readonly repositoryUrlFromPage?: (url: URL, known: boolean) => string | null;
300 /**
301 * The change request URL a `reference` autolink might name, such as a GitHub `#123` written
302 * through the issue route. Only a candidate: the caller must read it as a change request
303 * before treating it as one.
304 */
305 readonly changeRequestUrlFromReferenceAutolink: (url: URL) => string | null;
306 /**
307 * The actions this host can take on a change request, the same list its server provider
308 * declares in `capabilities.actions`.
309 */
310 readonly changeRequestActions: ReadonlySet<PullRequestAction>;
311 readonly checkoutCommand: (changeRequest: ChangeRequestCheckoutInput) => string | null;
312 /**
313 * Matches a shell command that merges or closes a change request with this host's CLI, which
314 * sends T3 no notification of its own. Absent for a host with no such CLI.
315 */
316 readonly changeRequestCloseCommand?: RegExp;
317 /**
318 * Matches a shell command that opens a change request with this host's CLI and prints its URL
319 * on a line of its own. Absent for a host with no such CLI.
320 */
321 readonly changeRequestCreateCommand?: RegExp;
322 readonly authorProfileUrl: (login: string, repositoryUrl: string) => string | null;
323 /**
324 * The references this host's own renderer links in plain text, such as `#12` or a commit SHA,
325 * resolved against `repositoryUrl`, in the order they appear. Absent for a host whose grammar
326 * T3 does not apply.
327 */
328 readonly referenceAutolinks?: (
329 text: string,
330 repositoryUrl: string,
331 ) => ReadonlyArray<ReferenceAutolink>;
332 /** True when the host renders a single newline in change request text as a line break. */
333 readonly hardLineBreaks?: boolean;
334 /** Where the host lists a change request's checks. Absent means the change request's own page. */
335 readonly changeRequestChecksUrl?: (changeRequestUrl: string) => string;
336 /**
337 * The actions a server too old to report `capabilities.actions` could still take on this host's
338 * change requests. Absent means none.
339 */
340 readonly changeRequestActionsWhenUnreported?: ReadonlySet<PullRequestAction>;
341 /**
342 * `host` when the server lists change requests in many repositories on this host with one read,
343 * so a page's size bounds the rows of every repository together. Absent means one read per
344 * repository.
345 */
346 readonly changeRequestListScope?: "host" | "repository";
347 readonly reviewSummaryRequired: (verdict: PullRequestReviewVerdict) => boolean;
348 readonly checkoutCommandArgument: (input: string) => string | null;
349 readonly isChangeRequestReference: (url: string) => boolean;
350 readonly isChangeRequestInRepository: (
351 identity: ChangeRequestProjectIdentity,
352 link: ChangeRequestLink | CommitLink,
353 ) => boolean;
354 readonly canReadChangeRequestOnHost: (
355 identity: ChangeRequestProjectIdentity,
356 link: ChangeRequestLink,
357 ) => boolean;
358 readonly checkoutChangeRequestHost: (identity: ChangeRequestProjectIdentity) => string | null;
359 /**
360 * The ref the target repository publishes change request `number`'s head under, which names the
361 * head even when it lives in a fork. Absent for a host that publishes none.
362 */
363 readonly changeRequestHeadRef?: (number: number) => string;
364 /** Null when this host does not claim the remote. Asked in the registry's recognition order. */
365 readonly recognizeRemote: (remote: GitRemoteHost) => SourceControlProviderInfo | null;
366 /** The host change requests in the project are listed and keyed under. */
367 readonly changeRequestHost?: (identity: ChangeRequestHostIdentity) => string;
368 /**
369 * What the host's tools take to select the project's repository. Absent means the repository
370 * path, `owner/name`.
371 */
372 readonly repositorySelector?: (identity: RepositorySelectorIdentity) => string | null;
373 /**
374 * The container the project's issues live in, where that is not its repository: Azure DevOps
375 * keeps work items per project. Null when the repository cannot be placed.
376 */
377 readonly issueScope?: (identity: IssueScopeIdentity) => string | null;
378 /**
379 * The key of a remote's lower case `host/path`, `.git` suffix kept, for a host that spells it
380 * apart from `normalizeGitRemoteUrl`: over SSH and the web, or with `.git` as part of the name.
381 * Null when the key is not this host's. Persisted keys are built with it: output must not change.
382 */
383 readonly repositoryKeyFromRemote?: (key: string) => string | null;
384 /**
385 * For a host with more than one spelling of a repository key: the one every spelling compares
386 * equal under. Null when the key is not this host's.
387 */
388 readonly canonicalRepositoryKey?: (key: string) => string | null;
389 /**
390 * Null when `url` is not media this host keeps behind a credential. A client cannot load such
391 * media itself, so it asks the server, whose driver for this host fetches it.
392 */
393 readonly mediaUrl?: (url: URL) => SourceControlMediaUrl | null;
394 /**
395 * A URL `mediaUrl` claims for the bytes of `path` at full commit `sha` in the repository at
396 * `repositoryUrl`. Null or absent when the host cannot serve one.
397 */
398 readonly rawFileUrl?: (input: {
399 readonly repositoryUrl: string;
400 readonly sha: string;
401 readonly path: string;
402 }) => string | null;
403 readonly settings?: SourceControlHostSettingsSchema;
404 }
405
406 export type SourceControlHostSettingsSchema = {
407 readonly fields: Readonly<Record<string, Schema.Top>>;
408 } & Schema.Decoder<object>;
409
410 const FULL_COMMIT_SHA = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/iu;
411
412 export function parseCommitPath(url: URL, route: RegExp): CommitLink | null {
413 if (url.protocol !== "https:" && url.protocol !== "http:") return null;
414 const match = route.exec(url.pathname);
415 const repository = match?.[1];
416 const sha = match?.[2];
417 return repository && sha && FULL_COMMIT_SHA.test(sha)
418 ? {
419 host: url.hostname.toLowerCase(),
420 repository: canonicalRepositoryPath(repository),
421 sha: sha.toLowerCase(),
422 ...(url.port ? { authority: url.host.toLowerCase() } : {}),
423 }
424 : null;
425 }
426
427 export function buildCommitUrl(
428 { host, repository, sha, remoteUrl, webUrl }: CommitUrlInput,
429 route: string,
430 ): string | null {
431 if (!repository || !FULL_COMMIT_SHA.test(sha)) return null;
432 try {
433 const url = new URL(webUrl || `${remoteWebOrigin(host, remoteUrl)}/${repository}`);
434 if (url.protocol !== "http:" && url.protocol !== "https:") return null;
435 url.pathname = changeRequestUrlBelow(url.pathname, `${route}/${sha.toLowerCase()}`);
436 url.username = "";
437 url.password = "";
438 url.search = "";
439 url.hash = "";
440 return url.toString();
441 } catch {
442 return null;
443 }
444 }
445
446 /**
447 * Reads a change request from `url` with `route`, whose first group is the repository path and
448 * second the number.
449 */
450 export function parseChangeRequestPath(url: URL, route: RegExp): ParsedChangeRequestUrl | null {
451 if (url.protocol !== "https:" && url.protocol !== "http:") return null;
452 const match = route.exec(url.pathname);
453 const repository = match?.[1];
454 const number = Number(match?.[2]);
455 return repository && Number.isSafeInteger(number) && number > 0
456 ? {
457 host: url.hostname.toLowerCase(),
458 repository: canonicalRepositoryPath(repository),
459 number,
460 repositoryUrl: `${url.origin}/${repository}`,
461 }
462 : null;
463 }
464
465 /** Reads an issue from `url` with `route`, whose groups are the scope and the issue number. */
466 export function parseIssuePath(url: URL, route: RegExp): IssueLink | null {
467 if (url.protocol !== "https:" && url.protocol !== "http:") return null;
468 const match = route.exec(url.pathname);
469 const scope = match?.[1];
470 const number = Number(match?.[2]);
471 return scope && Number.isSafeInteger(number) && number > 0
472 ? { host: url.hostname.toLowerCase(), scope: scope.toLowerCase(), key: String(number) }
473 : null;
474 }
475
476 /** Reads a repository page from `url` with `route`, whose first group is the repository path. */
477 export function repositoryUrlFromPagePath(url: URL, route: RegExp): string | null {
478 const repository = route.exec(url.pathname)?.[1];
479 if (!repository) return null;
480 // Keeps the credentials and port a private clone relies on.
481 const repositoryUrl = new URL(url);
482 repositoryUrl.pathname = `/${repository}`;
483 repositoryUrl.search = "";
484 repositoryUrl.hash = "";
485 return repositoryUrl.href;
486 }
487
488 export function changeRequestUrlBelow(webUrl: string, route: string): string {
489 return `${webUrl.replace(/\/+$/u, "")}/${route}`;
490 }
491
492 /** An HTTP remote on `host` names the server's web origin, port included; SSH remotes do not. */
493 export function remoteWebOrigin(host: string, remoteUrl: string | undefined): string {
494 try {
495 const remote = new URL(remoteUrl ?? "");
496 if (
497 (remote.protocol === "http:" || remote.protocol === "https:") &&
498 (remote.hostname.toLowerCase() === host.toLowerCase() ||
499 remote.host.toLowerCase() === host.toLowerCase())
500 ) {
501 return remote.origin;
502 }
503 } catch {
504 // SSH remotes do not specify the server's web origin.
505 }
506 return `https://${host}`;
507 }
508
509 export function defineSourceControl<const Definition extends SourceControlDefinition>(
510 definition: Definition,
511 ): Definition {
512 return definition;
513 }
514
515 export function isChangeRequestAuthorityOfProject(
516 identity: ChangeRequestProjectIdentity,
517 link: ChangeRequestLink | CommitLink,
518 ): boolean {
519 if (link.authority === undefined) return true;
520 try {
521 const remote = new URL(identity.locator.remoteUrl);
522 if (remote.protocol === "http:" || remote.protocol === "https:") {
523 return remote.host.toLowerCase() === link.authority;
524 }
525 } catch {
526 // SSH remotes do not specify the server's HTTP port.
527 }
528 return true;
529 }
530
531 /** The host of the project's repository key, or `kind` when the key has none. */
532 export function projectChangeRequestHost<const Kind extends string | undefined>(
533 identity: ChangeRequestHostIdentity,
534 kind: Kind,
535 ): string | Kind {
536 const host = identity?.canonicalKey?.split("/")[0]?.trim();
537 return host === undefined || host.length === 0 ? kind : host.toLowerCase();
538 }
539
540 /** `projectHost` is the project's `changeRequestHost`. */
541 export function isChangeRequestOnProjectHost(
542 projectHost: string,
543 identity: ChangeRequestProjectIdentity,
544 link: ChangeRequestLink | CommitLink,
545 ): boolean {
546 if (!isChangeRequestAuthorityOfProject(identity, link)) return false;
547 return projectHost === link.host.toLowerCase() || projectHost === link.authority;
548 }
549
550 function projectRepositoryPath(identity: ChangeRequestProjectIdentity): string | null {
551 return (
552 identity.displayName ??
553 (identity.owner && identity.name ? `${identity.owner}/${identity.name}` : null)
554 );
555 }
556
557 export function isChangeRequestInProjectRepository(
558 projectHost: string,
559 identity: ChangeRequestProjectIdentity,
560 link: ChangeRequestLink | CommitLink,
561 ): boolean {
562 const repository = projectRepositoryPath(identity);
563 return (
564 repository !== null &&
565 canonicalRepositoryPath(repository) === canonicalRepositoryPath(link.repository) &&
566 isChangeRequestOnProjectHost(projectHost, identity, link)
567 );
568 }
569
570 const SCP_REMOTE = /^[a-zA-Z0-9._-]+@([^:/]+):/;
571
572 /** Null when the remote names no host, such as a local path. */
573 export function parseGitRemoteHost(remoteUrl: string): GitRemoteHost | null {
574 const trimmed = remoteUrl.trim();
575 if (trimmed.length === 0) return null;
576 let host: string;
577 const scpHost = SCP_REMOTE.exec(trimmed)?.[1] ?? userlessScpRemoteHost(trimmed);
578 if (scpHost) {
579 host = scpHost.toLowerCase();
580 } else {
581 try {
582 const url = new URL(trimmed);
583 host = (url.protocol === "ssh:" ? url.hostname : url.host).toLowerCase();
584 } catch {
585 return null;
586 }
587 }
588 if (host.length === 0) return null;
589 let hostname: string;
590 try {
591 hostname = new URL(`https://${host}`).hostname.toLowerCase();
592 } catch {
593 hostname = host.replace(/:\d+$/u, "").toLowerCase();
594 }
595 return { remoteUrl: trimmed, host, hostname };
596 }
597
598 /** What a remote on a host no definition claims reads as. */
599 export function unknownRemoteProvider(remote: GitRemoteHost): SourceControlProviderInfo {
600 return {
601 kind: SourceControlProviderKind.make("unknown"),
602 name: remote.host,
603 baseUrl: `https://${remote.host}`,
604 };
605 }
606
607 /** What `definition` alone makes of a remote, for a host's own code that asks only about itself. */
608 export function recognizeRemoteWith(
609 definition: Pick<SourceControlDefinition, "recognizeRemote">,
610 remoteUrl: string,
611 ): SourceControlProviderInfo | null {
612 const remote = parseGitRemoteHost(remoteUrl);
613 return remote === null ? null : definition.recognizeRemote(remote);
614 }
615
616 function defaultRepositorySelector(
617 identity: RepositorySelectorIdentity | null | undefined,
618 ): string | null {
619 if (!identity) return null;
620 if (identity.displayName) return identity.displayName;
621 return identity.owner && identity.name ? `${identity.owner}/${identity.name}` : null;
622 }
623
624 export const UNKNOWN_SOURCE_CONTROL_CLIENT: SourceControlDefinition = {
625 kind: SourceControlProviderKind.make("unknown"),
626 label: "source control",
627 pickerLabel: "source control",
628 icon: null,
629 changeRequest: {
630 shortLabel: "change request",
631 shortLabelWithArticle: "a change request",
632 singular: "change request",
633 plural: "change requests",
634 },
635 repositoryPathHint: "URL",
636 publicHost: null,
637 publishDescription: "Your signed-in server",
638 publishHost: (signedInHost) => signedInHost ?? "your server",
639 newRepositoryOwner: () => null,
640 defaultCloneTransport: "ssh",
641 changeRequestUrl: () => null,
642 parseChangeRequestUrl: () => null,
643 changeRequestUrlFromReferenceAutolink: () => null,
644 changeRequestActions: new Set(),
645 checkoutCommand: () => null,
646 authorProfileUrl: () => null,
647 reviewSummaryRequired: () => false,
648 checkoutCommandArgument: () => null,
649 isChangeRequestReference: () => false,
650 checkoutChangeRequestHost: () => null,
651 recognizeRemote: () => null,
652 isChangeRequestInRepository: (identity, link) =>
653 isChangeRequestInProjectRepository(
654 projectChangeRequestHost(identity, "unknown"),
655 identity,
656 link,
657 ),
658 canReadChangeRequestOnHost: (identity, link) =>
659 isChangeRequestOnProjectHost(projectChangeRequestHost(identity, "unknown"), identity, link),
660 };
661
662 export interface ParsedChangeRequest {
663 readonly definition: SourceControlDefinition;
664 readonly link: ParsedChangeRequestUrl;
665 }
666
667 export interface ParsedCommit {
668 readonly definition: SourceControlDefinition;
669 readonly link: CommitLink;
670 }
671
672 export interface SourceControlMedia extends SourceControlMediaUrl {
673 readonly definition: SourceControlDefinition;
674 }
675
676 export interface SourceControlDefinitionRegistry {
677 readonly definitions: ReadonlyArray<SourceControlDefinition>;
678 readonly get: (kind: string | null | undefined) => SourceControlDefinition;
679 readonly find: (kind: string) => SourceControlDefinition | undefined;
680 readonly findByPublicHost: (hostname: string) => SourceControlDefinition | undefined;
681 /**
682 * The host whose `publicHost` is `hostname` or a parent domain of it, such as GitHub for
683 * `gist.github.com`: which host a link is on, not one T3 can read from.
684 */
685 readonly findByPublicDomain: (hostname: string) => SourceControlDefinition | undefined;
686 /** The first host, in registry order, that reads `url` as one of its change requests. */
687 readonly parseChangeRequestUrl: (url: string) => ParsedChangeRequest | null;
688 /** The first host, in registry order, that reads `url` as one of its issues, or `kind` alone. */
689 readonly parseIssueUrl: (
690 url: string,
691 kind?: SourceControlProviderKind,
692 ) => { readonly definition: SourceControlDefinition; readonly link: IssueLink } | null;
693 readonly parseCommitUrl: (url: string, kind?: SourceControlProviderKind) => ParsedCommit | null;
694 readonly findByChangeRequestUrl: (url: string) => SourceControlDefinition | undefined;
695 readonly hostLabelForChangeRequestUrl: (url: string) => string;
696 readonly isSameChangeRequest: (left: string, right: string) => boolean;
697 readonly changeRequestUrlFromReferenceAutolink: (url: string) => string | null;
698 /** The repository a page URL copied from a browser is in, such as a branch or file view. */
699 readonly repositoryUrlFromPage: (url: string) => string | null;
700 /**
701 * The host a remote is on, from the first definition in recognition order that claims it, or an
702 * unknown host. Null when the remote names no host.
703 */
704 readonly recognizeRemote: (remoteUrl: string) => SourceControlProviderInfo | null;
705 /** `normalizeGitRemoteUrl`, in the spelling the remote's host uses on the web. */
706 readonly repositoryKeyFromRemote: (remoteUrl: string) => string;
707 readonly canonicalRepositoryKey: (key: string) => string;
708 /** The host that has more than one spelling of `key`, if any does. */
709 readonly findByRepositoryKey: (key: string) => SourceControlDefinition | undefined;
710 readonly repositorySelector: (
711 identity: RepositorySelectorIdentity | null | undefined,
712 ) => string | null;
713 /** Where the project's issues live: the host's `issueScope`, else its repository. */
714 readonly issueScope: (identity: IssueScopeIdentity | null | undefined) => string | null;
715 /**
716 * Every repository whose issues are the project's own: its primary one, then the fork its
717 * `origin` remote names when that is on the same host. Empty for a project with no host.
718 */
719 readonly issueBindings: (
720 identity: RepositoryIdentity | null | undefined,
721 ) => ReadonlyArray<IssueBinding>;
722 readonly changeRequestHost: <const Kind extends string | undefined>(
723 identity: ChangeRequestHostIdentity,
724 kind: Kind,
725 ) => string | Kind;
726 /** The first host, in registry order, that keeps `url` behind a credential. */
727 readonly mediaUrl: (url: string) => SourceControlMedia | null;
728 }
729
730 function httpUrl(value: string): URL | null {
731 try {
732 const url = new URL(value);
733 return url.protocol === "https:" || url.protocol === "http:" ? url : null;
734 } catch {
735 return null;
736 }
737 }
738
739 function inOrder(
740 definitions: ReadonlyArray<SourceControlDefinition>,
741 firstKinds: ReadonlyArray<SourceControlProviderKind> | undefined,
742 ): ReadonlyArray<SourceControlDefinition> {
743 const first = (firstKinds ?? []).flatMap(
744 (kind) => definitions.find((definition) => definition.kind === kind) ?? [],
745 );
746 return [...first, ...definitions.filter((definition) => !first.includes(definition))];
747 }
748
749 /**
750 * `definitions` sets display order and the fallback for repositories with an unknown host.
751 * Claim host-specific URL routes before hosts that accept them on any hostname.
752 * Remote recognition needs a separate order because one hostname can carry several hosts' labels.
753 */
754 export function makeSourceControlDefinitionRegistry(
755 definitions: ReadonlyArray<SourceControlDefinition>,
756 options?: {
757 readonly claimChangeRequestUrlsFirst?: ReadonlyArray<SourceControlProviderKind>;
758 readonly recognizeRemotesIn?: ReadonlyArray<SourceControlProviderKind>;
759 },
760 ): SourceControlDefinitionRegistry {
761 const byKind = new Map<string, SourceControlDefinition>();
762 for (const definition of definitions) {
763 if (byKind.has(definition.kind)) {
764 throw new Error(`Source control host '${definition.kind}' is defined more than once.`);
765 }
766 byKind.set(definition.kind, definition);
767 }
768 const claimOrder = inOrder(definitions, options?.claimChangeRequestUrlsFirst);
769 const recognitionOrder = inOrder(definitions, options?.recognizeRemotesIn);
770 // Keys persisted before paths had one spelling still compare equal.
771 const canonicalKeyPath = (key: string) => {
772 const slash = key.indexOf("/");
773 return slash < 0
774 ? key
775 : `${key.slice(0, slash)}/${canonicalRepositoryPath(key.slice(slash + 1))}`;
776 };
777 const repositoryKeyOwner = (written: string) => {
778 const key = canonicalKeyPath(written);
779 for (const definition of definitions) {
780 const canonical = definition.canonicalRepositoryKey?.(key);
781 if (canonical != null) return { definition, canonical };
782 }
783 return undefined;
784 };
785 const remoteOwner = (remote: GitRemoteHost) =>
786 recognitionOrder.find((definition) => definition.recognizeRemote(remote) !== null);
787 const repositorySelector = (identity: RepositorySelectorIdentity | null | undefined) =>
788 identity?.provider === undefined
789 ? defaultRepositorySelector(identity)
790 : (byKind.get(identity.provider)?.repositorySelector ?? defaultRepositorySelector)(identity);
791 const parseChangeRequestUrl = (value: string): ParsedChangeRequest | null => {
792 const url = httpUrl(value);
793 if (url === null) return null;
794 for (const definition of claimOrder) {
795 const link = definition.parseChangeRequestUrl(url);
796 if (link !== null) return { definition, link };
797 }
798 return null;
799 };
800 const issueScope = (identity: IssueScopeIdentity | null | undefined) => {
801 const scopeOf =
802 identity?.provider === undefined ? undefined : byKind.get(identity.provider)?.issueScope;
803 return scopeOf === undefined || identity == null
804 ? repositorySelector(identity)
805 : scopeOf(identity);
806 };
807 const changeRequestHost = <const Kind extends string | undefined>(
808 identity: ChangeRequestHostIdentity,
809 kind: Kind,
810 ): string | Kind =>
811 (kind === undefined ? undefined : byKind.get(kind)?.changeRequestHost?.(identity)) ??
812 projectChangeRequestHost(identity, kind);
813 const issueBindings = (identity: RepositoryIdentity | null | undefined) => {
814 const tracker = identity?.provider;
815 if (!identity || tracker === undefined || tracker === "unknown") return [];
816 const scope = issueScope(identity);
817 if (scope === null) return [];
818 const host = changeRequestHost(identity, tracker);
819 const primary = { tracker, host, scope };
820 const origin = identity.origin;
821 // The origin keeps no provider or web URL, so it is read only on the primary's server. Keys
822 // drop schemes and ports, so an HTTP origin must match the primary's remote, its web address
823 // when the remote is SSH, else the issue host.
824 const originUrl = origin?.remoteUrl === undefined ? null : httpUrl(origin.remoteUrl);
825 const primaryUrl =
826 (identity.locator?.remoteUrl === undefined ? null : httpUrl(identity.locator.remoteUrl)) ??
827 (identity.webUrl === undefined ? null : httpUrl(identity.webUrl));
828 if (
829 origin === undefined ||
830 projectChangeRequestHost(origin, undefined) !==
831 projectChangeRequestHost(identity, undefined) ||
832 (originUrl !== null &&
833 (primaryUrl === null ? originUrl.host !== host : originUrl.origin !== primaryUrl.origin))
834 )
835 return [primary];
836 const originScope = issueScope({
837 provider: tracker,
838 canonicalKey: origin.canonicalKey,
839 displayName: origin.displayName ?? origin.canonicalKey.split("/").slice(1).join("/"),
840 });
841 if (originScope === null || originScope.toLowerCase() === scope.toLowerCase()) return [primary];
842 return [primary, { tracker, host, scope: originScope }];
843 };
844 return {
845 definitions,
846 get: (kind) =>
847 (kind == null ? definitions[0] : byKind.get(kind)) ?? UNKNOWN_SOURCE_CONTROL_CLIENT,
848 find: (kind) => byKind.get(kind),
849 findByPublicHost: (hostname) => {
850 const host = hostname.toLowerCase();
851 return definitions.find((definition) => definition.publicHost === host);
852 },
853 findByPublicDomain: (hostname) => {
854 const host = hostname.toLowerCase();
855 return definitions.find(
856 (definition) =>
857 definition.publicHost !== null &&
858 (host === definition.publicHost || host.endsWith(`.${definition.publicHost}`)),
859 );
860 },
861 parseChangeRequestUrl,
862 parseIssueUrl: (value, kind) => {
863 const url = httpUrl(value);
864 if (url === null) return null;
865 const preferred = kind === undefined ? undefined : byKind.get(kind);
866 for (const definition of kind === undefined ? claimOrder : preferred ? [preferred] : []) {
867 const link = definition.parseIssueUrl?.(url, preferred !== undefined) ?? null;
868 if (link !== null) return { definition, link };
869 }
870 return null;
871 },
872 parseCommitUrl: (value, kind) => {
873 const url = httpUrl(value);
874 if (url === null) return null;
875 const preferred = kind === undefined ? undefined : byKind.get(kind);
876 for (const definition of kind === undefined ? claimOrder : preferred ? [preferred] : []) {
877 const link = definition.parseCommitUrl?.(url, preferred !== undefined);
878 if (link != null) return { definition, link };
879 }
880 return null;
881 },
882 findByChangeRequestUrl: (url) => parseChangeRequestUrl(url)?.definition,
883 hostLabelForChangeRequestUrl: (url) =>
884 parseChangeRequestUrl(url)?.definition.label ?? "the host",
885 isSameChangeRequest: (left, right) => {
886 const a = parseChangeRequestUrl(left)?.link;
887 const b = parseChangeRequestUrl(right)?.link;
888 return (
889 a !== undefined &&
890 b !== undefined &&
891 a.host === b.host &&
892 a.repository === b.repository &&
893 a.number === b.number &&
894 a.authority === b.authority
895 );
896 },
897 changeRequestUrlFromReferenceAutolink: (value) => {
898 const url = httpUrl(value);
899 if (url === null) return null;
900 for (const definition of claimOrder) {
901 const candidate = definition.changeRequestUrlFromReferenceAutolink(url);
902 if (candidate !== null) return candidate;
903 }
904 return null;
905 },
906 repositoryUrlFromPage: (value) => {
907 const url = httpUrl(value);
908 if (url === null) return null;
909 // A recognized host's paths are its own, so another host's any-host route never rewrites them.
910 const remote = parseGitRemoteHost(value);
911 const owner = remote === null ? undefined : remoteOwner(remote);
912 if (owner) return owner.repositoryUrlFromPage?.(url, true) ?? null;
913 // Elsewhere a path ending in `.git` is already a clone URL, whatever routes it contains.
914 if (url.pathname.replace(/\/$/u, "").endsWith(".git")) return null;
915 // On an unrecognized host, only rewrite when every route that matches agrees. A route that
916 // answers with the page itself says it may already be the clone URL.
917 const [repositoryUrl, ...others] = new Set(
918 claimOrder.flatMap((definition) => definition.repositoryUrlFromPage?.(url, false) ?? []),
919 );
920 return repositoryUrl !== undefined && repositoryUrl !== url.href && others.length === 0
921 ? repositoryUrl
922 : null;
923 },
924 recognizeRemote: (remoteUrl) => {
925 const remote = parseGitRemoteHost(remoteUrl);
926 if (remote === null) return null;
927 for (const definition of recognitionOrder) {
928 const provider = definition.recognizeRemote(remote);
929 if (provider !== null) return provider;
930 }
931 return unknownRemoteProvider(remote);
932 },
933 repositoryKeyFromRemote: (remoteUrl) => {
934 const key = normalizeGitRemoteUrl(remoteUrl);
935 const written = parseGitRemoteRepository(remoteUrl, { keepGitSuffix: true });
936 if (written === null) return key;
937 for (const definition of definitions) {
938 const spelled = definition.repositoryKeyFromRemote?.(`${written.host}/${written.path}`);
939 if (spelled != null) return spelled;
940 }
941 return key;
942 },
943 canonicalRepositoryKey: (key) => repositoryKeyOwner(key)?.canonical ?? canonicalKeyPath(key),
944 findByRepositoryKey: (key) => repositoryKeyOwner(key)?.definition,
945 repositorySelector,
946 issueScope,
947 issueBindings,
948 changeRequestHost,
949 mediaUrl: (value) => {
950 const url = httpUrl(value);
951 if (url === null) return null;
952 for (const definition of definitions) {
953 const media = definition.mediaUrl?.(url);
954 if (media != null) return { ...media, definition };
955 }
956 return null;
957 },
958 };
959 }
960
961 export function readSourceControlHostSettings<S extends SourceControlHostSettingsSchema>(
962 schema: S,
963 saved: unknown,
964 ): S["Type"] {
965 const decode = Schema.decodeUnknownOption(schema as Schema.Decoder<S["Type"]>);
966 const decoded = decode(saved ?? {});
967 if (decoded._tag === "Some") return decoded.value;
968 const fallback = decode({});
969 if (fallback._tag === "Some") return fallback.value;
970 throw new Error("A source control host settings schema must decode an empty object.");
971 }