Open History to see the last commit
1import type { SourceControlMediaUrl } from "@t3tools/source-control-core/shared/definition";
2
3/**
4 * Only hosts where a credential is what decides the answer belong here. `objects.githubusercontent.com`
5 * and the `private-user-images` links GitHub's own HTML carries are already signed and load on their
6 * own, and a token does nothing for them once that signature expires.
7 */
8const WEB_HOSTS = new Set(["github.com", "www.github.com"]);
9const RAW_HOST = "raw.githubusercontent.com";
10const LFS_HOST = "media.githubusercontent.com";
11export const GITHUB_CREDENTIALED_MEDIA_HOSTS: ReadonlySet<string> = new Set([
12 ...WEB_HOSTS,
13 RAW_HOST,
14 LFS_HOST,
15]);
16
17const ATTACHMENT_PATH_PATTERN = /^\/user-attachments\/assets\/[\w-]+$/u;
18const LEGACY_ATTACHMENT_PATH_PATTERN = /^\/[^/]+\/[^/]+\/assets\/\d+\/[\w-]+$/u;
19/** `blob` and `raw` both address file bytes; `raw` is the one the token is honoured on. */
20const REPOSITORY_FILE_PATTERN = /^\/([^/]+)\/([^/]+)\/(?:raw|blob)\/(.*[^/])$/u;
21
22function fileName(fetchUrl: string): string {
23 const segment = new URL(fetchUrl).pathname.split("/").pop() ?? "";
24 let decoded: string;
25 try {
26 decoded = decodeURIComponent(segment);
27 } catch {
28 decoded = segment;
29 }
30 const name = decoded.replace(/[\p{Cc}\\/]/gu, "");
31 return name.length > 0 ? name : "github-media";
32}
33
34function media(fetchUrl: string, kind?: "video"): SourceControlMediaUrl {
35 return { fetchUrl, fileName: fileName(fetchUrl), ...(kind ? { kind } : {}) };
36}
37
38export function gitHubMediaUrl(url: URL): SourceControlMediaUrl | null {
39 if (url.protocol !== "https:") return null;
40 const host = url.hostname.toLowerCase();
41 if (host === RAW_HOST || host === LFS_HOST) {
42 return media(`https://${host}${url.pathname}${url.search}`);
43 }
44 if (!WEB_HOSTS.has(host)) return null;
45 // GitHub links an uploaded video bare, with no extension, and an image as markdown.
46 if (ATTACHMENT_PATH_PATTERN.test(url.pathname)) {
47 return media(`https://github.com${url.pathname}`, "video");
48 }
49 if (LEGACY_ATTACHMENT_PATH_PATTERN.test(url.pathname)) {
50 return media(`https://github.com${url.pathname}`);
51 }
52 const repositoryFile = REPOSITORY_FILE_PATTERN.exec(url.pathname);
53 return repositoryFile
54 ? media(`https://${RAW_HOST}/${repositoryFile[1]}/${repositoryFile[2]}/${repositoryFile[3]}`)
55 : null;
56}