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

pullRequestMarkdown.ts

393 lines15.0 KB

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