Open History to see the last commit
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;
28}
29
30export interface ParsedChangeRequestUrl extends ChangeRequestLink {
31 /** The repository's browser URL, without query or hash. */
32 readonly repositoryUrl: string;
33}
34
35export interface CommitLink {
36 readonly host: string;
37 readonly repository: string;
38 readonly sha: string;
39 readonly authority?: string;
40}
41
42export interface CommitUrlInput extends Omit<ChangeRequestUrlInput, "number"> {
43 readonly sha: string;
44}
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;
52}
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;
61}
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;
89}
90
91export interface ChangeRequestCheckoutInput {
92 readonly number: number;
93 readonly headBranch: string;
94 readonly headRepositoryNameWithOwner?: string | null | undefined;
95 readonly repositoryUrl?: string | null | undefined;
96}
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;
108}
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";
118}
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>;
129}
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 }>;
144}
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;
157}
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 );
166}
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;
186}
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;
201}
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 change request URL a `reference` autolink might name, such as a GitHub `#123` written
263 * through the issue route. Only a candidate: the caller must read it as a change request
264 * before treating it as one.
265 */
266 readonly changeRequestUrlFromReferenceAutolink: (url: URL) => string | null;
267 /**
268 * The actions this host can take on a change request, the same list its server provider
269 * declares in `capabilities.actions`.
270 */
271 readonly changeRequestActions: ReadonlySet<PullRequestAction>;
272 readonly checkoutCommand: (changeRequest: ChangeRequestCheckoutInput) => string | null;
273 /**
274 * Matches a shell command that merges or closes a change request with this host's CLI, which
275 * sends T3 no notification of its own. Absent for a host with no such CLI.
276 */
277 readonly changeRequestCloseCommand?: RegExp;
278 /**
279 * Matches a shell command that opens a change request with this host's CLI and prints its URL
280 * on a line of its own. Absent for a host with no such CLI.
281 */
282 readonly changeRequestCreateCommand?: RegExp;
283 readonly authorProfileUrl: (login: string, repositoryUrl: string) => string | null;
284 /**
285 * The references this host's own renderer links in plain text, such as `#12` or a commit SHA,
286 * resolved against `repositoryUrl`, in the order they appear. Absent for a host whose grammar
287 * T3 does not apply.
288 */
289 readonly referenceAutolinks?: (
290 text: string,
291 repositoryUrl: string,
292 ) => ReadonlyArray<ReferenceAutolink>;
293 /** True when the host renders a single newline in change request text as a line break. */
294 readonly hardLineBreaks?: boolean;
295 /** Where the host lists a change request's checks. Absent means the change request's own page. */
296 readonly changeRequestChecksUrl?: (changeRequestUrl: string) => string;
297 /**
298 * The actions a server too old to report `capabilities.actions` could still take on this host's
299 * change requests. Absent means none.
300 */
301 readonly changeRequestActionsWhenUnreported?: ReadonlySet<PullRequestAction>;
302 /**
303 * `host` when the server lists change requests in many repositories on this host with one read,
304 * so a page's size bounds the rows of every repository together. Absent means one read per
305 * repository.
306 */
307 readonly changeRequestListScope?: "host" | "repository";
308 readonly reviewSummaryRequired: (verdict: PullRequestReviewVerdict) => boolean;
309 readonly checkoutCommandArgument: (input: string) => string | null;
310 readonly isChangeRequestReference: (url: string) => boolean;
311 readonly isChangeRequestInRepository: (
312 identity: ChangeRequestProjectIdentity,
313 link: ChangeRequestLink | CommitLink,
314 ) => boolean;
315 readonly canReadChangeRequestOnHost: (
316 identity: ChangeRequestProjectIdentity,
317 link: ChangeRequestLink,
318 ) => boolean;
319 readonly checkoutChangeRequestHost: (identity: ChangeRequestProjectIdentity) => string | null;
320 /**
321 * The ref the target repository publishes change request `number`'s head under, which names the
322 * head even when it lives in a fork. Absent for a host that publishes none.
323 */
324 readonly changeRequestHeadRef?: (number: number) => string;
325 /** Null when this host does not claim the remote. Asked in the registry's recognition order. */
326 readonly recognizeRemote: (remote: GitRemoteHost) => SourceControlProviderInfo | null;
327 /** The host change requests in the project are listed and keyed under. */
328 readonly changeRequestHost?: (identity: ChangeRequestHostIdentity) => string;
329 /**
330 * What the host's tools take to select the project's repository. Absent means the repository
331 * path, `owner/name`.
332 */
333 readonly repositorySelector?: (identity: RepositorySelectorIdentity) => string | null;
334 /**
335 * For a host that spells one repository differently over SSH and on the web: the web spelling
336 * of the `host/path` key `normalizeGitRemoteUrl` made from a remote that names a host. Null when
337 * the key is not this host's. Persisted repository keys are built with it, so its output must
338 * not change.
339 */
340 readonly repositoryKeyFromRemote?: (key: string) => string | null;
341 /**
342 * For a host with more than one spelling of a repository key: the one every spelling compares
343 * equal under. Null when the key is not this host's.
344 */
345 readonly canonicalRepositoryKey?: (key: string) => string | null;
346 /**
347 * Null when `url` is not media this host keeps behind a credential. A client cannot load such
348 * media itself, so it asks the server, whose driver for this host fetches it.
349 */
350 readonly mediaUrl?: (url: URL) => SourceControlMediaUrl | null;
351 readonly settings?: SourceControlHostSettingsSchema;
352}
353
354export type SourceControlHostSettingsSchema = {
355 readonly fields: Readonly<Record<string, Schema.Top>>;
356} & Schema.Decoder<object>;
357
358const FULL_COMMIT_SHA = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/iu;
359
360export function parseCommitPath(url: URL, route: RegExp): CommitLink | null {
361 if (url.protocol !== "https:" && url.protocol !== "http:") return null;
362 const match = route.exec(url.pathname);
363 const repository = match?.[1];
364 const sha = match?.[2];
365 return repository && sha && FULL_COMMIT_SHA.test(sha)
366 ? {
367 host: url.hostname.toLowerCase(),
368 repository: repository.toLowerCase(),
369 sha: sha.toLowerCase(),
370 ...(url.port ? { authority: url.host.toLowerCase() } : {}),
371 }
372 : null;
373}
374
375export function buildCommitUrl(
376 { host, repository, sha, remoteUrl, webUrl }: CommitUrlInput,
377 route: string,
378): string | null {
379 if (!repository || !FULL_COMMIT_SHA.test(sha)) return null;
380 try {
381 const url = new URL(webUrl || `${remoteWebOrigin(host, remoteUrl)}/${repository}`);
382 if (url.protocol !== "http:" && url.protocol !== "https:") return null;
383 url.pathname = changeRequestUrlBelow(url.pathname, `${route}/${sha.toLowerCase()}`);
384 url.username = "";
385 url.password = "";
386 url.search = "";
387 url.hash = "";
388 return url.toString();
389 } catch {
390 return null;
391 }
392}
393
394/**
395 * Reads a change request from `url` with `route`, whose first group is the repository path and
396 * second the number.
397 */
398export function parseChangeRequestPath(url: URL, route: RegExp): ParsedChangeRequestUrl | null {
399 if (url.protocol !== "https:" && url.protocol !== "http:") return null;
400 const match = route.exec(url.pathname);
401 const repository = match?.[1];
402 const number = Number(match?.[2]);
403 return repository && Number.isSafeInteger(number) && number > 0
404 ? {
405 host: url.hostname.toLowerCase(),
406 repository: repository.toLowerCase(),
407 number,
408 repositoryUrl: `${url.origin}/${repository}`,
409 }
410 : null;
411}
412
413export function changeRequestUrlBelow(webUrl: string, route: string): string {
414 return `${webUrl.replace(/\/+$/u, "")}/${route}`;
415}
416
417/** An HTTP remote on `host` names the server's web origin, port included; SSH remotes do not. */
418export function remoteWebOrigin(host: string, remoteUrl: string | undefined): string {
419 try {
420 const remote = new URL(remoteUrl ?? "");
421 if (
422 (remote.protocol === "http:" || remote.protocol === "https:") &&
423 (remote.hostname.toLowerCase() === host.toLowerCase() ||
424 remote.host.toLowerCase() === host.toLowerCase())
425 ) {
426 return remote.origin;
427 }
428 } catch {
429 // SSH remotes do not specify the server's web origin.
430 }
431 return `https://${host}`;
432}
433
434export function defineSourceControl<const Definition extends SourceControlDefinition>(
435 definition: Definition,
436): Definition {
437 return definition;
438}
439
440export function isChangeRequestAuthorityOfProject(
441 identity: ChangeRequestProjectIdentity,
442 link: ChangeRequestLink | CommitLink,
443): boolean {
444 if (link.authority === undefined) return true;
445 try {
446 const remote = new URL(identity.locator.remoteUrl);
447 if (remote.protocol === "http:" || remote.protocol === "https:") {
448 return remote.host.toLowerCase() === link.authority;
449 }
450 } catch {
451 // SSH remotes do not specify the server's HTTP port.
452 }
453 return true;
454}
455
456/** The host of the project's repository key, or `kind` when the key has none. */
457export function projectChangeRequestHost<const Kind extends string | undefined>(
458 identity: ChangeRequestHostIdentity,
459 kind: Kind,
460): string | Kind {
461 const host = identity?.canonicalKey?.split("/")[0]?.trim();
462 return host === undefined || host.length === 0 ? kind : host.toLowerCase();
463}
464
465/** `projectHost` is the project's `changeRequestHost`. */
466export function isChangeRequestOnProjectHost(
467 projectHost: string,
468 identity: ChangeRequestProjectIdentity,
469 link: ChangeRequestLink | CommitLink,
470): boolean {
471 if (!isChangeRequestAuthorityOfProject(identity, link)) return false;
472 return projectHost === link.host.toLowerCase() || projectHost === link.authority;
473}
474
475function projectRepositoryPath(identity: ChangeRequestProjectIdentity): string | null {
476 return (
477 identity.displayName ??
478 (identity.owner && identity.name ? `${identity.owner}/${identity.name}` : null)
479 );
480}
481
482export function isChangeRequestInProjectRepository(
483 projectHost: string,
484 identity: ChangeRequestProjectIdentity,
485 link: ChangeRequestLink | CommitLink,
486): boolean {
487 const repository = projectRepositoryPath(identity);
488 return (
489 repository !== null &&
490 repository.toLowerCase() === link.repository.toLowerCase() &&
491 isChangeRequestOnProjectHost(projectHost, identity, link)
492 );
493}
494
495const SCP_REMOTE = /^[a-zA-Z0-9._-]+@([^:/]+):/;
496
497/** Null when the remote names no host, such as a local path. */
498export function parseGitRemoteHost(remoteUrl: string): GitRemoteHost | null {
499 const trimmed = remoteUrl.trim();
500 if (trimmed.length === 0) return null;
501 let host: string;
502 const scpHost = SCP_REMOTE.exec(trimmed)?.[1] ?? userlessScpRemoteHost(trimmed);
503 if (scpHost) {
504 host = scpHost.toLowerCase();
505 } else {
506 try {
507 const url = new URL(trimmed);
508 host = (url.protocol === "ssh:" ? url.hostname : url.host).toLowerCase();
509 } catch {
510 return null;
511 }
512 }
513 if (host.length === 0) return null;
514 let hostname: string;
515 try {
516 hostname = new URL(`https://${host}`).hostname.toLowerCase();
517 } catch {
518 hostname = host.replace(/:\d+$/u, "").toLowerCase();
519 }
520 return { remoteUrl: trimmed, host, hostname };
521}
522
523/** What a remote on a host no definition claims reads as. */
524export function unknownRemoteProvider(remote: GitRemoteHost): SourceControlProviderInfo {
525 return {
526 kind: SourceControlProviderKind.make("unknown"),
527 name: remote.host,
528 baseUrl: `https://${remote.host}`,
529 };
530}
531
532/** What `definition` alone makes of a remote, for a host's own code that asks only about itself. */
533export function recognizeRemoteWith(
534 definition: Pick<SourceControlDefinition, "recognizeRemote">,
535 remoteUrl: string,
536): SourceControlProviderInfo | null {
537 const remote = parseGitRemoteHost(remoteUrl);
538 return remote === null ? null : definition.recognizeRemote(remote);
539}
540
541function defaultRepositorySelector(
542 identity: RepositorySelectorIdentity | null | undefined,
543): string | null {
544 if (!identity) return null;
545 if (identity.displayName) return identity.displayName;
546 return identity.owner && identity.name ? `${identity.owner}/${identity.name}` : null;
547}
548
549export const UNKNOWN_SOURCE_CONTROL_CLIENT: SourceControlDefinition = {
550 kind: SourceControlProviderKind.make("unknown"),
551 label: "source control",
552 pickerLabel: "source control",
553 icon: null,
554 changeRequest: {
555 shortLabel: "change request",
556 shortLabelWithArticle: "a change request",
557 singular: "change request",
558 plural: "change requests",
559 },
560 repositoryPathHint: "URL",
561 publicHost: null,
562 publishDescription: "Your signed-in server",
563 publishHost: (signedInHost) => signedInHost ?? "your server",
564 newRepositoryOwner: () => null,
565 defaultCloneTransport: "ssh",
566 changeRequestUrl: () => null,
567 parseChangeRequestUrl: () => null,
568 changeRequestUrlFromReferenceAutolink: () => null,
569 changeRequestActions: new Set(),
570 checkoutCommand: () => null,
571 authorProfileUrl: () => null,
572 reviewSummaryRequired: () => false,
573 checkoutCommandArgument: () => null,
574 isChangeRequestReference: () => false,
575 checkoutChangeRequestHost: () => null,
576 recognizeRemote: () => null,
577 isChangeRequestInRepository: (identity, link) =>
578 isChangeRequestInProjectRepository(
579 projectChangeRequestHost(identity, "unknown"),
580 identity,
581 link,
582 ),
583 canReadChangeRequestOnHost: (identity, link) =>
584 isChangeRequestOnProjectHost(projectChangeRequestHost(identity, "unknown"), identity, link),
585};
586
587export interface ParsedChangeRequest {
588 readonly definition: SourceControlDefinition;
589 readonly link: ParsedChangeRequestUrl;
590}
591
592export interface ParsedCommit {
593 readonly definition: SourceControlDefinition;
594 readonly link: CommitLink;
595}
596
597export interface SourceControlMedia extends SourceControlMediaUrl {
598 readonly definition: SourceControlDefinition;
599}
600
601export interface SourceControlDefinitionRegistry {
602 readonly definitions: ReadonlyArray<SourceControlDefinition>;
603 readonly get: (kind: string | null | undefined) => SourceControlDefinition;
604 readonly find: (kind: string) => SourceControlDefinition | undefined;
605 readonly findByPublicHost: (hostname: string) => SourceControlDefinition | undefined;
606 /**
607 * The host whose `publicHost` is `hostname` or a parent domain of it, such as GitHub for
608 * `gist.github.com`: which host a link is on, not one T3 can read from.
609 */
610 readonly findByPublicDomain: (hostname: string) => SourceControlDefinition | undefined;
611 /** The first host, in registry order, that reads `url` as one of its change requests. */
612 readonly parseChangeRequestUrl: (url: string) => ParsedChangeRequest | null;
613 readonly parseCommitUrl: (url: string, kind?: SourceControlProviderKind) => ParsedCommit | null;
614 readonly findByChangeRequestUrl: (url: string) => SourceControlDefinition | undefined;
615 readonly hostLabelForChangeRequestUrl: (url: string) => string;
616 readonly isSameChangeRequest: (left: string, right: string) => boolean;
617 readonly changeRequestUrlFromReferenceAutolink: (url: string) => string | null;
618 /**
619 * The host a remote is on, from the first definition in recognition order that claims it, or an
620 * unknown host. Null when the remote names no host.
621 */
622 readonly recognizeRemote: (remoteUrl: string) => SourceControlProviderInfo | null;
623 /** `normalizeGitRemoteUrl`, in the spelling the remote's host uses on the web. */
624 readonly repositoryKeyFromRemote: (remoteUrl: string) => string;
625 readonly canonicalRepositoryKey: (key: string) => string;
626 /** The host that has more than one spelling of `key`, if any does. */
627 readonly findByRepositoryKey: (key: string) => SourceControlDefinition | undefined;
628 readonly repositorySelector: (
629 identity: RepositorySelectorIdentity | null | undefined,
630 ) => string | null;
631 readonly changeRequestHost: <const Kind extends string | undefined>(
632 identity: ChangeRequestHostIdentity,
633 kind: Kind,
634 ) => string | Kind;
635 /** The first host, in registry order, that keeps `url` behind a credential. */
636 readonly mediaUrl: (url: string) => SourceControlMedia | null;
637}
638
639function httpUrl(value: string): URL | null {
640 try {
641 const url = new URL(value);
642 return url.protocol === "https:" || url.protocol === "http:" ? url : null;
643 } catch {
644 return null;
645 }
646}
647
648function inOrder(
649 definitions: ReadonlyArray<SourceControlDefinition>,
650 firstKinds: ReadonlyArray<SourceControlProviderKind> | undefined,
651): ReadonlyArray<SourceControlDefinition> {
652 const first = (firstKinds ?? []).flatMap(
653 (kind) => definitions.find((definition) => definition.kind === kind) ?? [],
654 );
655 return [...first, ...definitions.filter((definition) => !first.includes(definition))];
656}
657
658/**
659 * `definitions` sets display order and the fallback for repositories with an unknown host.
660 * Claim host-specific URL routes before hosts that accept them on any hostname.
661 * Remote recognition needs a separate order because one hostname can carry several hosts' labels.
662 */
663export function makeSourceControlDefinitionRegistry(
664 definitions: ReadonlyArray<SourceControlDefinition>,
665 options?: {
666 readonly claimChangeRequestUrlsFirst?: ReadonlyArray<SourceControlProviderKind>;
667 readonly recognizeRemotesIn?: ReadonlyArray<SourceControlProviderKind>;
668 },
669): SourceControlDefinitionRegistry {
670 const byKind = new Map<string, SourceControlDefinition>();
671 for (const definition of definitions) {
672 if (byKind.has(definition.kind)) {
673 throw new Error(`Source control host '${definition.kind}' is defined more than once.`);
674 }
675 byKind.set(definition.kind, definition);
676 }
677 const claimOrder = inOrder(definitions, options?.claimChangeRequestUrlsFirst);
678 const recognitionOrder = inOrder(definitions, options?.recognizeRemotesIn);
679 const repositoryKeyOwner = (key: string) => {
680 for (const definition of definitions) {
681 const canonical = definition.canonicalRepositoryKey?.(key);
682 if (canonical != null) return { definition, canonical };
683 }
684 return undefined;
685 };
686 const parseChangeRequestUrl = (value: string): ParsedChangeRequest | null => {
687 const url = httpUrl(value);
688 if (url === null) return null;
689 for (const definition of claimOrder) {
690 const link = definition.parseChangeRequestUrl(url);
691 if (link !== null) return { definition, link };
692 }
693 return null;
694 };
695 return {
696 definitions,
697 get: (kind) =>
698 (kind == null ? definitions[0] : byKind.get(kind)) ?? UNKNOWN_SOURCE_CONTROL_CLIENT,
699 find: (kind) => byKind.get(kind),
700 findByPublicHost: (hostname) => {
701 const host = hostname.toLowerCase();
702 return definitions.find((definition) => definition.publicHost === host);
703 },
704 findByPublicDomain: (hostname) => {
705 const host = hostname.toLowerCase();
706 return definitions.find(
707 (definition) =>
708 definition.publicHost !== null &&
709 (host === definition.publicHost || host.endsWith(`.${definition.publicHost}`)),
710 );
711 },
712 parseChangeRequestUrl,
713 parseCommitUrl: (value, kind) => {
714 const url = httpUrl(value);
715 if (url === null) return null;
716 const preferred = kind === undefined ? undefined : byKind.get(kind);
717 for (const definition of kind === undefined ? claimOrder : preferred ? [preferred] : []) {
718 const link = definition.parseCommitUrl?.(url, preferred !== undefined);
719 if (link != null) return { definition, link };
720 }
721 return null;
722 },
723 findByChangeRequestUrl: (url) => parseChangeRequestUrl(url)?.definition,
724 hostLabelForChangeRequestUrl: (url) =>
725 parseChangeRequestUrl(url)?.definition.label ?? "the host",
726 isSameChangeRequest: (left, right) => {
727 const a = parseChangeRequestUrl(left)?.link;
728 const b = parseChangeRequestUrl(right)?.link;
729 return (
730 a !== undefined &&
731 b !== undefined &&
732 a.host === b.host &&
733 a.repository === b.repository &&
734 a.number === b.number &&
735 a.authority === b.authority
736 );
737 },
738 changeRequestUrlFromReferenceAutolink: (value) => {
739 const url = httpUrl(value);
740 if (url === null) return null;
741 for (const definition of claimOrder) {
742 const candidate = definition.changeRequestUrlFromReferenceAutolink(url);
743 if (candidate !== null) return candidate;
744 }
745 return null;
746 },
747 recognizeRemote: (remoteUrl) => {
748 const remote = parseGitRemoteHost(remoteUrl);
749 if (remote === null) return null;
750 for (const definition of recognitionOrder) {
751 const provider = definition.recognizeRemote(remote);
752 if (provider !== null) return provider;
753 }
754 return unknownRemoteProvider(remote);
755 },
756 repositoryKeyFromRemote: (remoteUrl) => {
757 const key = normalizeGitRemoteUrl(remoteUrl);
758 if (parseGitRemoteRepository(remoteUrl) === null) return key;
759 for (const definition of definitions) {
760 const spelled = definition.repositoryKeyFromRemote?.(key);
761 if (spelled != null) return spelled;
762 }
763 return key;
764 },
765 canonicalRepositoryKey: (key) => repositoryKeyOwner(key)?.canonical ?? key,
766 findByRepositoryKey: (key) => repositoryKeyOwner(key)?.definition,
767 repositorySelector: (identity) =>
768 identity?.provider === undefined
769 ? defaultRepositorySelector(identity)
770 : (byKind.get(identity.provider)?.repositorySelector ?? defaultRepositorySelector)(
771 identity,
772 ),
773 changeRequestHost: (identity, kind) =>
774 (kind === undefined ? undefined : byKind.get(kind)?.changeRequestHost?.(identity)) ??
775 projectChangeRequestHost(identity, kind),
776 mediaUrl: (value) => {
777 const url = httpUrl(value);
778 if (url === null) return null;
779 for (const definition of definitions) {
780 const media = definition.mediaUrl?.(url);
781 if (media != null) return { ...media, definition };
782 }
783 return null;
784 },
785 };
786}
787
788export function readSourceControlHostSettings<S extends SourceControlHostSettingsSchema>(
789 schema: S,
790 saved: unknown,
791): S["Type"] {
792 const decode = Schema.decodeUnknownOption(schema as Schema.Decoder<S["Type"]>);
793 const decoded = decode(saved ?? {});
794 if (decoded._tag === "Some") return decoded.value;
795 const fallback = decode({});
796 if (fallback._tag === "Some") return fallback.value;
797 throw new Error("A source control host settings schema must decode an empty object.");
798}