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

definition.ts

794 lines30.4 KB

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