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

pullRequestMarkdown.ts

371 lines14.1 KB

1import type { Root, RootContent } from "mdast";
2import remarkGfm from "remark-gfm";
3import remarkParse from "remark-parse";
4import { unified } from "unified";
5​
6import { sourceControlClients, type ReferenceAutolink } from "./sourceControlClients.ts";
7​
8/** `id` is positional on purpose: the same attachment can be embedded twice in one body. */
9export type PullRequestBodySegment =
10 | {
11 readonly id: string;
12 readonly kind: "markdown";
13 readonly text: string;
14 /**
15 * `sourceOffset + i` is where `text[i]` sits in the body, so an edit can be written back.
16 * Holds past the body's reference definitions, which `text` may lead with.
17 */
18 readonly sourceOffset: number;
19 }
20 | {
21 readonly id: string;
22 readonly kind: "attachment";
23 readonly url: string;
24 readonly media: "video" | "image" | "unknown";
25 }
26 | {
27 readonly id: string;
28 readonly kind: "table";
29 readonly rows: ReadonlyArray<ReadonlyArray<PullRequestBodyTableCell>>;
30 };
31​
32type PullRequestBodyTableCell = {
33 readonly header: boolean;
34 readonly segments: ReadonlyArray<PullRequestBodySegment>;
35};
36​
37// `.` stops at the `\r` of a CRLF body, which is how GitHub stores one written in its web editor.
38const FENCE_PATTERN = /^\s{0,3}((?:`{3,})|(?:~{3,}))(.*)\r?$/u;
39/**
40 * How far a `<video>` tag may reach for its closing tag. Real embeds are one to three lines,
41 * and the bound keeps an unclosed tag from making each one rescan the rest of the body.
42 */
43const VIDEO_TAG_MAX_LINES = 8;
44​
45// A tab after up to three spaces still reaches the fourth column.
46const INDENTED_CODE_PATTERN = /^(?: {4}| {0,3}\t)/u;
47const BARE_URL_PATTERN = /^<?(https?:\/\/\S+?)>?$/u;
48const IMAGE_EXTENSION_PATTERN = /\.(?:png|jpe?g|gif|webp|avif|heic|heif|svg)(?:$|[?#])/iu;
49const MARKDOWN_LINK_PATTERN = /^\[[^\]]*\]\((https?:\/\/[^\s)]+)\)$/u;
50const VIDEO_EXTENSION_PATTERN = /\.(?:mp4|webm|mov|m4v|ogv)(?:$|[?#])/iu;
51​
52const VIDEO_TAG_SRC_PATTERN = /<(?:video|source)\b[^>]*\bsrc\s*=\s*["']([^"']+)["']/iu;
53​
54const STANDALONE_VIDEO_TAG_PATTERN = /^\s*<video\b/iu;
55const VIDEO_TAG_END_PATTERN = /<\/video>\s*$/iu;
56​
57/** Bounded like `VIDEO_TAG_MAX_LINES`; room for a before/after table with several rows. */
58const TABLE_MAX_LINES = 64;
59const TABLE_START_PATTERN = /^\s*<table\b/iu;
60const TABLE_END_PATTERN = /<\/table>\s*$/iu;
61const TABLE_OPEN_PATTERN = /<table\b/giu;
62const TABLE_CLOSE_PATTERN = /<\/table\s*>/giu;
63/**
64 * Quoted attribute values may hold `>`. The alternatives start on disjoint characters and an
65 * unquoted run stops at the next `<`, so a run of unterminated tags stays linear.
66 */
67const TABLE_STRUCTURE_TAG_PATTERN =
68 /<(\/?)(table|thead|tbody|tfoot|tr|td|th)\b((?:[^<>"']|"[^"]*"|'[^']*')*)>/giu;
69/** Rows are laid out independently, so a spanning cell would shift the cells after it. */
70const CELL_SPAN_PATTERN = /\b(?:col|row)span\b/iu;
71​
72function isWebUrl(url: string): boolean {
73 try {
74 const parsed = new URL(url);
75 return parsed.protocol === "https:" || parsed.protocol === "http:";
76 } catch {
77 return false;
78 }
80​
81function attachmentFromLine(
82 line: string,
83): { url: string; media: "video" | "image" | "unknown" } | null {
84 const url =
85 BARE_URL_PATTERN.exec(line.trim())?.[1] ?? MARKDOWN_LINK_PATTERN.exec(line.trim())?.[1];
86 if (url === undefined || !isWebUrl(url)) return null;
87 if (VIDEO_EXTENSION_PATTERN.test(url) || sourceControlClients.mediaUrl(url)?.kind === "video") {
88 return { url, media: "video" };
89 }
90 if (IMAGE_EXTENSION_PATTERN.test(url)) return { url, media: "image" };
91 return null;
93​
94type TableRows = ReadonlyArray<ReadonlyArray<PullRequestBodyTableCell>>;
95​
96/**
97 * Cells of a table made only of rows and cells, or null when anything else is in it: a caption,
98 * text between cells, a nested table. Cell contents are split on their own, so tables never nest.
99 */
100function tableRows(html: string, htmlOffset: number): TableRows | null {
101 const rows: PullRequestBodyTableCell[][] = [];
102 let row: PullRequestBodyTableCell[] | null = null;
103 let cell: { tag: string; contentStart: number } | null = null;
104 let opened = false;
105 let closed = false;
106 let cursor = 0;
107 for (const match of html.matchAll(TABLE_STRUCTURE_TAG_PATTERN)) {
108 const closing = match[1] === "/";
109 const tag = match[2]!.toLowerCase();
110 if (cell !== null) {
111 if (!closing || tag !== cell.tag) return null;
112 const content = html.slice(cell.contentStart, match.index);
113 // Indented HTML would render as a code block once the cell is markdown on its own.
114 if (content.split("\n").some((line) => INDENTED_CODE_PATTERN.test(line) && line.trim()))
115 return null;
116 row!.push({
117 header: tag === "th",
118 segments: splitBodyAt(content, htmlOffset + cell.contentStart),
119 });
120 cell = null;
121 } else {
122 if (html.slice(cursor, match.index).trim().length > 0) return null;
123 const tableOpen = opened && !closed;
124 if (tag === "table") {
125 if (closing ? !tableOpen || row !== null : opened) return null;
126 opened = true;
127 closed = closing;
128 } else if (tag === "tr") {
129 if (!tableOpen || closing === (row === null)) return null;
130 if (closing) rows.push(row!);
131 row = closing ? null : [];
132 } else if (tag === "td" || tag === "th") {
133 if (closing || row === null || CELL_SPAN_PATTERN.test(match[3]!)) return null;
134 cell = { tag, contentStart: match.index + match[0].length };
135 } else if (!tableOpen || row !== null) {
136 return null;
137 }
138 }
139 cursor = match.index + match[0].length;
140 }
141 if (!closed || html.slice(cursor).trim().length > 0) return null;
142 return rows.filter((cells) => cells.length > 0);
144​
145/**
146 * The table opening at `start`, through its matching close. `end` is the last line looked at
147 * even when the table is not usable, so the caller never re-reads an inner table on its own.
148 */
149function mediaTableAt(
150 lines: ReadonlyArray<string>,
151 start: number,
152 startOffset: number,
153): { end: number; rows: TableRows | null } {
154 const lastCandidate = Math.min(start + TABLE_MAX_LINES, lines.length) - 1;
155 let depth = 0;
156 let end = start;
157 for (; ; end += 1) {
158 const line = lines[end]!;
159 depth +=
160 (line.match(TABLE_OPEN_PATTERN)?.length ?? 0) -
161 (line.match(TABLE_CLOSE_PATTERN)?.length ?? 0);
162 if (depth <= 0 || end === lastCandidate) break;
163 }
164 if (depth !== 0 || !TABLE_END_PATTERN.test(lines[end]!)) return { end, rows: null };
165 // Lifting attachment links out of a table's cells would tear the table apart.
166 const rows = tableRows(lines.slice(start, end + 1).join("\n"), startOffset);
167 const hasMedia = rows?.some((cells) =>
168 cells.some((cell) => cell.segments.some((segment) => segment.kind === "attachment")),
169 );
170 return { end, rows: hasMedia ? rows : null };
172​
173const definitionParser = unified().use(remarkParse).use(remarkGfm);
174​
175/**
176 * The first definition of each label in the body, as authored, each joined onto one line so it
177 * stands outside the quote or list it was written in.
178 */
179function referenceDefinitions(body: string): string[] {
180 const definitions = new Map<string, string>();
181 const visit = (node: Root | RootContent, quotes: number) => {
182 if (node.type === "definition" && !definitions.has(node.identifier)) {
183 const wrap = new RegExp(`(?:\\r\\n|\\r|\\n)(?:[ \\t]*>){0,${quotes}}[ \\t]*`, "gu");
184 const source = body.slice(node.position?.start.offset, node.position?.end.offset);
185 definitions.set(node.identifier, source.replace(wrap, " "));
186 }
187 if (!("children" in node)) return;
188 for (const child of node.children) visit(child, quotes + (node.type === "blockquote" ? 1 : 0));
189 };
190 visit(definitionParser.parse(body), 0);
191 return [...definitions.values()];
193​
194/**
195 * Each markdown segment renders as its own document, so it leads with the body's definitions.
196 * Leading, they win over a later redefinition in the segment, as the first one does in the body.
197 */
198function withDefinitions(
199 segment: PullRequestBodySegment,
200 definitions: string,
201): PullRequestBodySegment {
202 if (segment.kind === "attachment") return segment;
203 if (segment.kind === "table") {
204 return {
205 ...segment,
206 rows: segment.rows.map((cells) =>
207 cells.map((cell) => ({
208 ...cell,
209 segments: cell.segments.map((inner) => withDefinitions(inner, definitions)),
210 })),
211 ),
212 };
213 }
214 if (!segment.text.includes("[")) return segment;
215 return {
216 ...segment,
217 text: definitions + segment.text,
218 sourceOffset: segment.sourceOffset - definitions.length,
219 };
221​
222export function splitPullRequestBody(body: string): ReadonlyArray<PullRequestBodySegment> {
223 const segments = splitBodyAt(body, 0);
224 // One markdown segment is the whole body, which resolves its own references.
225 const whole = segments.length === 1 && segments[0]!.kind === "markdown";
226 if (whole || !body.includes("]:")) return segments;
227 const definitions = referenceDefinitions(body);
228 if (definitions.length === 0) return segments;
229 const leading = `${definitions.join("\n")}\n\n`;
230 return segments.map((segment) => withDefinitions(segment, leading));
232​
233/** `baseOffset` is where `body` starts in the whole body, so a table cell's edits write back. */
234function splitBodyAt(body: string, baseOffset: number): ReadonlyArray<PullRequestBodySegment> {
235 const segments: PullRequestBodySegment[] = [];
236 const markdown: string[] = [];
237 let markdownStart = 0;
238 let openFence: string | null = null;
239​
240 // Blank lines around a run are dropped, but never leading spaces: four of them open an
241 // indented code block, so trimming a run would silently turn code into prose.
242 const flushMarkdown = () => {
243 const joined = markdown.join("\n");
244 const text = joined.replace(/^(?:\r?\n)+/u, "");
245 const sourceOffset = markdownStart + joined.length - text.length;
246 markdown.length = 0;
247 if (text.trim().length > 0) {
248 segments.push({
249 id: `markdown:${segments.length}`,
250 kind: "markdown",
251 text: text.replace(/\s+$/u, ""),
252 sourceOffset,
253 });
254 }
255 };
256​
257 const lines = body.split("\n");
258 let tableScannedThrough = -1;
259 let lineStart = baseOffset;
260 for (let index = 0; index < lines.length; lineStart += lines[index]!.length + 1, index += 1) {
261 const line = lines[index]!;
262 if (markdown.length === 0) markdownStart = lineStart;
263 const fenceMatch = FENCE_PATTERN.exec(line);
264 // ```` ```npm test``` ```` is a code span, not an opener that would flip every later fence.
265 // A span that runs past this line is left an opener, so its lines stay out of media.
266 const isInlineCode =
267 openFence === null &&
268 fenceMatch?.[1]![0] === "`" &&
269 (fenceMatch[2]!.match(/`+/gu) ?? []).some((run) => run.length === fenceMatch[1]!.length);
270 if (fenceMatch !== null && !isInlineCode) {
271 const fence = fenceMatch[1]!;
272 // A fence closes only on the same marker, at least as long as the one that opened it,
273 // and with nothing after it: `~~~` cannot end a ``` block, and ```` ```ts ```` is an
274 // info string opening a nested fence, not a close.
275 const closes =
276 openFence !== null &&
277 fence[0] === openFence[0] &&
278 fence.length >= openFence.length &&
279 fenceMatch[2]!.trim().length === 0;
280 if (openFence === null) {
281 openFence = fence;
282 } else if (closes) {
283 openFence = null;
284 }
285 markdown.push(line);
286 continue;
287 }
288 if (openFence !== null || INDENTED_CODE_PATTERN.test(line)) {
289 markdown.push(line);
290 continue;
291 }
292​
293 if (index > tableScannedThrough && TABLE_START_PATTERN.test(line)) {
294 const table = mediaTableAt(lines, index, lineStart);
295 tableScannedThrough = table.end;
296 if (table.rows !== null) {
297 flushMarkdown();
298 segments.push({ id: `table:${segments.length}`, kind: "table", rows: table.rows });
299 for (; index < table.end; index += 1) lineStart += lines[index]!.length + 1;
300 continue;
301 }
302 }
303​
304 const bareAttachment = attachmentFromLine(line);
305 if (bareAttachment !== null) {
306 flushMarkdown();
307 segments.push({ id: `attachment:${segments.length}`, kind: "attachment", ...bareAttachment });
308 continue;
309 }
310​
311 if (!STANDALONE_VIDEO_TAG_PATTERN.test(line)) {
312 markdown.push(line);
313 continue;
314 }
315 const lastCandidate = Math.min(index + VIDEO_TAG_MAX_LINES, lines.length) - 1;
316 let cursor = index;
317 while (cursor < lastCandidate && !VIDEO_TAG_END_PATTERN.test(lines[cursor]!)) {
318 cursor += 1;
319 }
320 const source = VIDEO_TAG_END_PATTERN.test(lines[cursor]!)
321 ? VIDEO_TAG_SRC_PATTERN.exec(lines.slice(index, cursor + 1).join("\n"))?.[1]
322 : undefined;
323 if (source !== undefined && isWebUrl(source)) {
324 flushMarkdown();
325 segments.push({
326 id: `attachment:${segments.length}`,
327 kind: "attachment",
328 url: source,
329​
330 media: "video",
331 });
332 for (; index < cursor; index += 1) lineStart += lines[index]!.length + 1;
333 } else {
334 // Unclosed, or nothing linkable in it: prose. Only this line is consumed, so the
335 // lines that were looked at are still parsed on their own terms.
336 markdown.push(line);
337 }
338 }
339​
340 flushMarkdown();
341 return segments;
343​
344/**
345 * Finds the references the change request's host links in plain text, resolved against the change
346 * request's repository. Null when the host links none.
347 */
348export function changeRequestReferenceAutolinker(
349 changeRequest: { readonly provider: string; readonly url: string } | null | undefined,
350): ((text: string) => ReadonlyArray<ReferenceAutolink>) | null {
351 if (!changeRequest) return null;
352 const find = sourceControlClients.get(changeRequest.provider).referenceAutolinks;
353 const repositoryUrl = sourceControlClients.parseChangeRequestUrl(changeRequest.url)?.link
354 .repositoryUrl;
355 return find === undefined || repositoryUrl === undefined
356 ? null
357 : (text) => find(text, repositoryUrl);
359​
360/**
361 * Forges link uploads root-relative, as GitCafe's `/api/attachments/<id>`. In a change request
362 * body that always means the forge's origin, never a path on the machine rendering it.
363 */
364export function resolveChangeRequestMediaUrl(url: string, changeRequestUrl: string): string {
365 if (!/^\/(?![/\\])/u.test(url)) return url;
366 try {
367 return new URL(url, changeRequestUrl).href;
368 } catch {
369 return url;
370 }