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