Open History to see the last commit
1import {
2 findAndReplaceText,
3 type MarkdownNode,
4 type TextMatch,
5} from "~/vendor/mdast-find-and-replace";
6
7/** `id` is positional on purpose: the same attachment can be embedded twice in one body. */
8export type PullRequestBodySegment =
9 | { readonly id: string; readonly kind: "markdown"; readonly text: string }
10 | {
11 readonly id: string;
12 readonly kind: "attachment";
13 readonly url: string;
14 /**
15 * What the reader can be told the upload is. The uuid says nothing on its own — the type
16 * only appears in the signed redirect GitHub answers with — but the shape does: GitHub
17 * writes a dropped image into the body as an `<img>` tag, so a bare attachment link on its
18 * own line is what it does with a video. Anything else keeps the neutral name.
19 */
20 readonly media: "video" | "unknown";
21 };
22
23const FENCE_PATTERN = /^\s{0,3}((?:`{3,})|(?:~{3,}))(.*)$/u;
24/**
25 * How far a `<video>` tag may reach for its closing tag. Real embeds are one to three lines,
26 * and the bound keeps an unclosed tag from making each one rescan the rest of the body.
27 */
28const VIDEO_TAG_MAX_LINES = 8;
29/** Four spaces open an indented code block, so its contents stay verbatim markdown. */
30const INDENTED_CODE_PATTERN = /^(?: {4}|\t)/u;
31const BARE_URL_PATTERN = /^<?(https?:\/\/\S+?)>?$/u;
32const VIDEO_EXTENSION_PATTERN = /\.(?:mp4|webm|mov|m4v|ogv)(?:$|[?#])/iu;
33/** A dropped video becomes a bare asset link; a dropped image becomes an `<img>` tag. */
34const GITHUB_ASSET_PATTERN = /^https:\/\/github\.com\/user-attachments\/assets\/[\w-]+$/iu;
35const VIDEO_TAG_SRC_PATTERN = /<(?:video|source)\b[^>]*\bsrc\s*=\s*["']([^"']+)["']/iu;
36/** Only a tag that owns its line is an embed; inline, it is prose the renderer should keep. */
37const STANDALONE_VIDEO_TAG_PATTERN = /^\s*<video\b/iu;
38const VIDEO_TAG_END_PATTERN = /<\/video>\s*$/iu;
39
40/** Anything else — `javascript:`, `data:`, a relative path — is not an upload to link out to. */
41function isWebUrl(url: string): boolean {
42 try {
43 const parsed = new URL(url);
44 return parsed.protocol === "https:" || parsed.protocol === "http:";
45 } catch {
46 return false;
47 }
48}
49
50function attachmentFromLine(line: string): { url: string; media: "video" | "unknown" } | null {
51 const url = BARE_URL_PATTERN.exec(line.trim())?.[1];
52 if (url === undefined || !isWebUrl(url)) return null;
53 if (VIDEO_EXTENSION_PATTERN.test(url) || GITHUB_ASSET_PATTERN.test(url)) {
54 return { url, media: "video" };
55 }
56 return null;
57}
58
59/**
60 * Splits a pull request body into markdown runs and the uploads embedded in it, which the
61 * markdown renderer drops: `<video>` is not in its sanitizer's schema, and a bare attachment
62 * link arrives as prose. Two shapes are recognised, both of which GitHub produces itself: a
63 * `<video>` (or `<source>`) tag, and a bare link on its own line to a video file or an
64 * uploaded attachment. Fenced code is copied through untouched so a snippet that happens to
65 * contain a link is never lifted out of it.
66 */
67export function splitPullRequestBody(body: string): ReadonlyArray<PullRequestBodySegment> {
68 const segments: PullRequestBodySegment[] = [];
69 const markdown: string[] = [];
70 let openFence: string | null = null;
71
72 // Blank lines around a run are dropped, but never leading spaces: four of them open an
73 // indented code block, so trimming a run would silently turn code into prose.
74 const flushMarkdown = () => {
75 const text = markdown.join("\n").replace(/^\n+/u, "").replace(/\s+$/u, "");
76 markdown.length = 0;
77 if (text.trim().length > 0) {
78 segments.push({ id: `markdown:${segments.length}`, kind: "markdown", text });
79 }
80 };
81
82 const lines = body.split("\n");
83 for (let index = 0; index < lines.length; index += 1) {
84 const line = lines[index]!;
85 const fenceMatch = FENCE_PATTERN.exec(line);
86 if (fenceMatch !== null) {
87 const fence = fenceMatch[1]!;
88 // A fence closes only on the same marker, at least as long as the one that opened it,
89 // and with nothing after it: `~~~` cannot end a ``` block, and ```` ```ts ```` is an
90 // info string opening a nested fence, not a close.
91 const closes =
92 openFence !== null &&
93 fence[0] === openFence[0] &&
94 fence.length >= openFence.length &&
95 fenceMatch[2]!.trim().length === 0;
96 if (openFence === null) {
97 openFence = fence;
98 } else if (closes) {
99 openFence = null;
100 }
101 markdown.push(line);
102 continue;
103 }
104 if (openFence !== null || INDENTED_CODE_PATTERN.test(line)) {
105 markdown.push(line);
106 continue;
107 }
108
109 const bareAttachment = attachmentFromLine(line);
110 if (bareAttachment !== null) {
111 flushMarkdown();
112 segments.push({ id: `attachment:${segments.length}`, kind: "attachment", ...bareAttachment });
113 continue;
114 }
115
116 if (!STANDALONE_VIDEO_TAG_PATTERN.test(line)) {
117 markdown.push(line);
118 continue;
119 }
120 // A tag can span lines, so look ahead for its close — bounded, and without building the
121 // joined text until one is actually found.
122 const lastCandidate = Math.min(index + VIDEO_TAG_MAX_LINES, lines.length) - 1;
123 let cursor = index;
124 while (cursor < lastCandidate && !VIDEO_TAG_END_PATTERN.test(lines[cursor]!)) {
125 cursor += 1;
126 }
127 const source = VIDEO_TAG_END_PATTERN.test(lines[cursor]!)
128 ? VIDEO_TAG_SRC_PATTERN.exec(lines.slice(index, cursor + 1).join("\n"))?.[1]
129 : undefined;
130 if (source !== undefined && isWebUrl(source)) {
131 flushMarkdown();
132 segments.push({
133 id: `attachment:${segments.length}`,
134 kind: "attachment",
135 url: source,
136 // The author wrote the tag, so this one is a video whatever the URL looks like.
137 media: "video",
138 });
139 index = cursor;
140 } else {
141 // Unclosed, or nothing linkable in it: prose. Only this line is consumed, so the
142 // lines that were looked at are still parsed on their own terms.
143 markdown.push(line);
144 }
145 }
146
147 flushMarkdown();
148 return segments;
149}
150
151const AUTOLINK_CANDIDATE_PATTERN = /#[1-9]\d*|[0-9a-f]{40}/giu;
152const AUTOLINK_WORD_CHARACTER_PATTERN = /[A-Za-z0-9_]/u;
153const AUTOLINK_COMMIT_PREFIX_PATTERN = /[\s([{]/u;
154const AUTOLINK_IGNORED_TYPES = new Set(["link", "linkReference"]);
155
156/** GitHub-style same-repository references for pull request prose, never code or authored links. */
157export function remarkPullRequestAutolinks(options: { readonly repositoryUrl: string }) {
158 const repositoryUrl = options.repositoryUrl.replace(/\/+$/u, "");
159 return (tree: MarkdownNode) => {
160 findAndReplaceText(
161 tree,
162 AUTOLINK_CANDIDATE_PATTERN,
163 (matched: string, match: TextMatch) => {
164 const reference = matched.startsWith("#");
165 const before = match.input[match.index - 1];
166 const after = match.input[match.index + matched.length];
167 if (
168 (before !== undefined &&
169 (reference
170 ? AUTOLINK_WORD_CHARACTER_PATTERN.test(before)
171 : !AUTOLINK_COMMIT_PREFIX_PATTERN.test(before))) ||
172 (after !== undefined && AUTOLINK_WORD_CHARACTER_PATTERN.test(after))
173 ) {
174 return false;
175 }
176 return {
177 type: "link",
178 url: reference
179 ? `${repositoryUrl}/issues/${matched.slice(1)}`
180 : `${repositoryUrl}/commit/${matched}`,
181 data: {
182 hProperties: {
183 dataPullRequestAutolink: reference ? "reference" : "commit",
184 },
185 },
186 children: [{ type: "text", value: reference ? matched : matched.slice(0, 7) }],
187 };
188 },
189 AUTOLINK_IGNORED_TYPES,
190 );
191 };
192}