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

definition.ts

191 lines7.4 KB

1import { makeProviderSettingsSchema, SourceControlProviderKind } from "@t3tools/contracts";
2import {
3 buildCommitUrl,
4 changeRequestUrlBelow,
5 defineSourceControl,
6 hostCredentialSettingsFields,
7 isChangeRequestInProjectRepository,
8 isChangeRequestOnProjectHost,
9 parseChangeRequestPath,
10 parseCommitPath,
11 parseIssuePath,
12 projectChangeRequestHost,
13 repositoryUrlFromPagePath,
14 type SourceControlMediaUrl,
15} from "@t3tools/source-control-core/shared/definition";
16​
17import { icon } from "./icon.ts";
18​
19export const TANSTACK_SOURCE_HOST = "source.tanstack.com";
20​
21/** Web pages name the owner with a leading `@`, as `/@TanStack/router`; clone URLs may omit it. */
22const CHANGE_REQUEST_PATH = /^\/(?:@|%40)?([^/@%]+\/[^/]+)\/pull\/(\d+)(?:\/|$)/u;
23const ISSUE_PATH = /^\/(?:@|%40)?([^/@%]+\/[^/]+)\/issues\/(\d+)(?:\/|$)/u;
24const COMMIT_PATH = /^\/(?:@|%40)?([^/@%]+\/[^/]+)\/commit\/([0-9a-f]+)\/?$/iu;
25const REPOSITORY_PAGE_PATH = /^\/(@[^/@]+\/[^/]+)\/(?:tree|blob)\/[^/]/u;
26/** `https://<host>/<owner>/<repo>/assets/<path>`; the web also spells the owner `@owner`. */
27const ASSET_PATH = /^\/(?:@|%40)?([\w.-]+)\/([\w.-]+)\/assets\/([^?#]*[^/])$/u;
28const PINNED_VERSION = /^\d+$/u;
29const CHECKOUT_COMMAND = /^src\s+pr\s+checkout\s+(.+)$/iu;
30​
31const KIND = SourceControlProviderKind.make("tanstack-source");
32​
33const isTanStackSourceHost = (hostname: string) => hostname.toLowerCase() === TANSTACK_SOURCE_HOST;
34​
35function parseChangeRequestUrl(url: URL) {
36 const link = isTanStackSourceHost(url.hostname)
37 ? parseChangeRequestPath(url, CHANGE_REQUEST_PATH)
38 : null;
39 return link === null
40 ? null
41 : { ...link, repositoryUrl: `${url.origin}/@${CHANGE_REQUEST_PATH.exec(url.pathname)![1]}` };
43​
44/**
45 * `owner/name` as the API names it. The web spells it `@owner/name`, and a client without this
46 * definition percent-encodes that as `%40owner/name`.
47 */
48export const withoutOwnerMark = (repository: string) => repository.replace(/^(?:@|%40)/iu, "");
49​
50/** Links stored with the web's spelling compare equal to the project's own key. */
51function canonicalRepositoryKey(key: string): string | null {
52 const slash = key.indexOf("/");
53 return slash > 0 && isTanStackSourceHost(key.slice(0, slash))
54 ? `${TANSTACK_SOURCE_HOST}/${withoutOwnerMark(key.slice(slash + 1))}`
55 : null;
57​
58/** Keys drop the owner's `@`, so a project's repository is `owner/name` as the API names it. */
59function repositoryKeyFromRemote(key: string): string | null {
60 // Remote parsing spells the `@` percent-encoded.
61 const match = /^source\.tanstack\.com\/(?:@|%40)([^/@%]+\/[^/]+)$/u.exec(key);
62 return match?.[1] === undefined
63 ? null
64 : `${TANSTACK_SOURCE_HOST}/${match[1].replace(/\.git$/u, "")}`;
66​
67/**
68 * Assets of a private repository answer 404 to a request without the reader's token, so every
69 * asset goes through the server, which also loads public ones without a sign-in.
70 */
71function tanStackSourceMediaUrl(url: URL): SourceControlMediaUrl | null {
72 if (url.protocol !== "https:" || url.port !== "" || !isTanStackSourceHost(url.hostname)) {
73 return null;
74 }
75 const match = ASSET_PATH.exec(url.pathname);
76 const [, owner, name, path] = match ?? [];
77 if (owner === undefined || name === undefined || path === undefined) return null;
78 if ([owner, name].some((segment) => segment === "." || segment === "..")) return null;
79 const version = url.searchParams.get("v");
80 const pinned = version !== null && PINNED_VERSION.test(version);
81 const fetchUrl = `https://${TANSTACK_SOURCE_HOST}/${owner}/${name}/assets/${path}${pinned ? `?v=${version}` : ""}`;
82 let fileName: string;
83 try {
84 fileName = decodeURIComponent(path.split("/").pop() ?? "");
85 } catch {
86 fileName = path.split("/").pop() ?? "";
87 }
88 fileName = fileName.replace(/[\p{Cc}\\/]/gu, "");
89 // Not `immutable`, even when pinned: a private asset must not outlive the reader's access in
90 // a persistent client cache.
91 return { fetchUrl, fileName: fileName.length > 0 ? fileName : "source-asset" };
93​
94export const settings = makeProviderSettingsSchema(hostCredentialSettingsFields);
95export type TanStackSourceSettings = typeof settings.Type;
96​
97export const definition = defineSourceControl({
98 kind: KIND,
99 label: "TanStack Source",
100 pickerLabel: "TanStack Source",
101 icon,
102 searchKeywords: ["tanstack", "src"],
103 credentials: {
104 cliName: "src",
105 cliLabel: "TanStack Source CLI",
106 loginCommand: "src auth login --web",
107 tokenEnvVar: "SRC_TOKEN",
108 tokenAccess: "read and write access to repositories, issues and pull requests",
109 newTokenUrl: (host) => `https://${host}/settings/tokens`,
110 },
111 changeRequest: {
112 shortLabel: "PR",
113 shortLabelWithArticle: "a PR",
114 singular: "pull request",
115 plural: "pull requests",
116 },
117 repositoryPathHint: "owner/repo",
118 publicHost: TANSTACK_SOURCE_HOST,
119 publishDescription: TANSTACK_SOURCE_HOST,
120 publishHost: () => TANSTACK_SOURCE_HOST,
121 newRepositoryOwner: (account) => ({ owner: account }),
122 defaultCloneTransport: "https",
123 changeRequestUrl: ({ host, repository, number, webUrl }) =>
124 !Number.isSafeInteger(number) || number < 1
125 ? null
126 : webUrl
127 ? changeRequestUrlBelow(webUrl, `pull/${number}`)
128 : `https://${host}/@${withoutOwnerMark(repository)}/pull/${number}`,
129 parseChangeRequestUrl,
130 commitUrl: (input) =>
131 buildCommitUrl(
132 input.webUrl
133 ? input
134 : { ...input, webUrl: `https://${input.host}/@${withoutOwnerMark(input.repository)}` },
135 "commit",
136 ),
137 parseIssueUrl: (url) =>
138 isTanStackSourceHost(url.hostname) ? parseIssuePath(url, ISSUE_PATH) : null,
139 parseCommitUrl: (url) =>
140 isTanStackSourceHost(url.hostname) ? parseCommitPath(url, COMMIT_PATH) : null,
141 repositoryUrlFromPage: (url) => {
142 if (!isTanStackSourceHost(url.hostname)) return null;
143 const page = new URL(url);
144 page.pathname = page.pathname.replace(/^\/%40/iu, "/@");
145 return repositoryUrlFromPagePath(page, REPOSITORY_PAGE_PATH);
146 },
147 changeRequestUrlFromReferenceAutolink: () => null,
148 changeRequestActions: new Set([
149 "merge",
150 "ready",
151 "draft",
152 "close",
153 "reopen",
154 "update-branch",
155 "enable-auto-merge",
156 "disable-auto-merge",
157 "revert",
158 ] as const),
159 checkoutCommand: ({ number }) => `src pr checkout ${number}`,
160 changeRequestCloseCommand: /\bsrc\s+pr\s+(?:merge|close)\b/u,
161 changeRequestCreateCommand: /\bsrc\s+pr\s+(?:create|new)\b/u,
162 authorProfileUrl: ({ login }) =>
163 login.endsWith("[bot]")
164 ? null
165 : `https://${TANSTACK_SOURCE_HOST}/@${encodeURIComponent(login)}`,
166 reviewSummaryRequired: () => false,
167 checkoutCommandArgument: (input) => CHECKOUT_COMMAND.exec(input)?.[1]?.trim() ?? null,
168 isChangeRequestReference: (url) => parsePullRequestUrl(url) !== null,
169 checkoutChangeRequestHost: () => null,
170 changeRequestHeadRef: (number) => `refs/pull/${number}/head`,
171 repositoryKeyFromRemote,
172 canonicalRepositoryKey,
173 mediaUrl: tanStackSourceMediaUrl,
174 recognizeRemote: ({ hostname }) =>
175 isTanStackSourceHost(hostname)
176 ? { kind: KIND, name: "TanStack Source", baseUrl: `https://${TANSTACK_SOURCE_HOST}` }
177 : null,
178 isChangeRequestInRepository: (identity, link) =>
179 isChangeRequestInProjectRepository(projectChangeRequestHost(identity, KIND), identity, link),
180 canReadChangeRequestOnHost: (identity, link) =>
181 isChangeRequestOnProjectHost(projectChangeRequestHost(identity, KIND), identity, link),
182 settings,
183});
184​
185export function parsePullRequestUrl(value: string) {
186 try {
187 return parseChangeRequestUrl(new URL(value));
188 } catch {
189 return null;
190 }