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

definition.ts

838 lines32.8 KB

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