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

pullRequestMarkdown.ts

547 lines21.1 KB

1import { markdownParagraphLines } from "@t3tools/shared/markdownChunks";
2import { markdownLinkDestinationScanner } from "@t3tools/shared/markdownLinks";
3import * as Effect from "effect/Effect";
4import { Atom } from "effect/reactivity";
5import { GITHUB_EMOJI_ALIASES } from "./githubEmojiAliases.ts";
6import { sourceControlClients } 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 readonly label?: string;
26 }
27 | {
28 readonly id: string;
29 readonly kind: "table";
30 readonly rows: ReadonlyArray<ReadonlyArray<PullRequestBodyTableCell>>;
31 };
32​
33type PullRequestBodyTableCell = {
34 readonly header: boolean;
35 readonly segments: ReadonlyArray<PullRequestBodySegment>;
36};
37​
38// `.` stops at the `\r` of a CRLF body, which is how GitHub stores one written in its web editor.
39// The marker is the whole run, so a line that is no fence is given up on in one pass.
40// A fence may open right after a list marker: `- ```ts` starts code inside the item.
41const FENCE_PATTERN = /^\s{0,3}(?:(?:[-+*]|\d{1,9}[.)]) {1,4})?(`{3,}(?!`)|~{3,}(?!~))(.*)\r?$/u;
42const LIST_ITEM_PATTERN = /^\s{0,3}(?:[-+*]|(\d{1,9})[.)]) /u;
43​
44/** Tabs advance to the next multiple of four, as Markdown measures indentation. */
45function indentColumns(line: string): number {
46 let column = 0;
47 for (const char of /^[ \t]*/u.exec(line)![0]) column += char === "\t" ? 4 - (column % 4) : 1;
48 return column;
50​
51/**
52 * How far a `<video>` tag may reach for its closing tag. Real embeds are one to three lines,
53 * and the bound keeps an unclosed tag from making each one rescan the rest of the body.
54 */
55const VIDEO_TAG_MAX_LINES = 8;
56​
57// A tab after up to three spaces still reaches the fourth column.
58const INDENTED_CODE_PATTERN = /^(?: {4}| {0,3}\t)/u;
59const HTML_COMMENT_START_PATTERN = /^ {0,3}<!--/u;
60const BARE_URL_PATTERN = /^<?(https?:\/\/\S+?)>?$/u;
61const IMAGE_EXTENSION_PATTERN = /\.(?:png|jpe?g|gif|webp|avif|heic|heif|svg)$/iu;
62// A destination unescapes backslashed ASCII punctuation and decodes character references
63// (`&amp;`); a link with a reference stays Markdown so its parser decodes it.
64const MARKDOWN_DESTINATION_TOKEN_PATTERN =
65 /\\([!-/:-@[-`{-~])|&(?:#\d{1,7}|#[xX][\da-fA-F]{1,6}|[A-Za-z][A-Za-z\d]{1,31});/gu;
66const VIDEO_EXTENSION_PATTERN = /\.(?:mp4|webm|mov|m4v|ogv)$/iu;
67​
68// Stops at the next `<`, so matching stays linear in the length of the line.
69const VIDEO_SOURCE_TAG_PATTERN = /<(?:video|source)(?=[\s/>])((?:[^<>"']|"[^"]*"|'[^']*')*)>/giu;
70const HTML_ATTRIBUTE_PATTERN = /([^\s"'=<>/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'<>`]+)))?/gu;
71const HTML_AMPERSAND_REFERENCE_PATTERN = /&(?:amp|AMP|#0*38|#[xX]0*26);/gu;
72​
73function videoTagSource(html: string): string | undefined {
74 for (const tag of html.matchAll(VIDEO_SOURCE_TAG_PATTERN)) {
75 for (const attribute of tag[1]!.matchAll(HTML_ATTRIBUTE_PATTERN)) {
76 if (attribute[1]!.toLowerCase() !== "src") continue;
77 const value = attribute[2] ?? attribute[3] ?? attribute[4];
78 if (value) return value.replace(HTML_AMPERSAND_REFERENCE_PATTERN, "&");
79 }
80 }
81 return undefined;
83​
84const STANDALONE_VIDEO_TAG_PATTERN = /^\s*<video\b/iu;
85const VIDEO_TAG_END_PATTERN = /<\/video>\s*$/iu;
86const VIDEO_TAG_CLOSE_PATTERN = /<\/video>/iu;
87​
88/** Bounded like `VIDEO_TAG_MAX_LINES`; room for a before/after table with several rows. */
89const TABLE_MAX_LINES = 64;
90const TABLE_START_PATTERN = /^\s*<table\b/iu;
91const TABLE_END_PATTERN = /<\/table>\s*$/iu;
92const TABLE_OPEN_PATTERN = /<table\b/giu;
93const TABLE_CLOSE_PATTERN = /<\/table\s*>/giu;
94/**
95 * Quoted attribute values may hold `>`. The alternatives start on disjoint characters and an
96 * unquoted run stops at the next `<`, so a run of unterminated tags stays linear.
97 */
98const TABLE_STRUCTURE_TAG_PATTERN =
99 /<(\/?)(table|thead|tbody|tfoot|tr|td|th)\b((?:[^<>"']|"[^"]*"|'[^']*')*)>/giu;
100/** Rows are laid out independently, so a spanning cell would shift the cells after it. */
101const CELL_SPAN_PATTERN = /\b(?:col|row)span\b/iu;
102​
103function webUrl(url: string): URL | null {
104 try {
105 const parsed = new URL(url);
106 return parsed.protocol === "https:" || parsed.protocol === "http:" ? parsed : null;
107 } catch {
108 return null;
109 }
111​
112/** Index just past the code span opened at `start`, or past the backtick run when none closes it. */
113function codeSpanEnd(text: string, start: number): number {
114 let open = start;
115 while (text[open] === "`") open += 1;
116 for (let index = open; index < text.length;) {
117 if (text[index] !== "`") {
118 index += 1;
119 continue;
120 }
121 let close = index;
122 while (text[close] === "`") close += 1;
123 if (close - index === open - start) return close;
124 index = close;
125 }
126 return open;
128​
129function standaloneMarkdownLink(trimmed: string): { label: string; url: string } | null {
130 if (!trimmed.startsWith("[")) return null;
131 // A label may nest balanced brackets; an escaped `\]` or one inside a code span never closes it.
132 let closeBracket = -1;
133 for (let index = 1, depth = 0; index < trimmed.length && closeBracket < 0; index += 1) {
134 const character = trimmed[index];
135 if (character === "\\") index += 1;
136 else if (character === "`") index = codeSpanEnd(trimmed, index) - 1;
137 else if (character === "[") depth += 1;
138 else if (character === "]" && depth-- === 0) closeBracket = index;
139 }
140 if (closeBracket < 0 || trimmed[closeBracket + 1] !== "(") return null;
141 const destination = markdownLinkDestinationScanner(trimmed)(closeBracket + 1);
142 if (destination === null || destination.end !== trimmed.length) return null;
143 let hasCharacterReference = false;
144 const url = trimmed
145 .slice(destination.hrefStart, destination.hrefEnd)
146 .replace(MARKDOWN_DESTINATION_TOKEN_PATTERN, (token, escaped: string | undefined) => {
147 if (escaped !== undefined) return escaped;
148 hasCharacterReference = true;
149 return token;
150 });
151 return url && !hasCharacterReference ? { label: trimmed.slice(1, closeBracket), url } : null;
153​
154function attachmentFromLine(
155 line: string,
156): Omit<Extract<PullRequestBodySegment, { kind: "attachment" }>, "id" | "kind"> | null {
157 const trimmed = line.trim();
158 const link = standaloneMarkdownLink(trimmed);
159 const url = link?.url ?? BARE_URL_PATTERN.exec(trimmed)?.[1];
160 if (url === undefined) return null;
161 // Only the path names the file: `report?file=demo.mp4` is a page, not a video.
162 const path = webUrl(url)?.pathname;
163 if (path === undefined) return null;
164 const media = VIDEO_EXTENSION_PATTERN.test(path)
165 ? "video"
166 : IMAGE_EXTENSION_PATTERN.test(path)
167 ? "image"
168 : sourceControlClients.mediaUrl(url)?.kind;
169 if (media === undefined) return null;
170 const label = link?.label.trim();
171 return label ? { url, media, label } : { url, media };
173​
174export function makePullRequestMediaKindAtom(
175 fetchMedia: (
176 url: string,
177 options: { headers: Record<string, string>; signal: AbortSignal },
178 ) => Promise<Pick<Response, "ok" | "headers" | "body">>,
179) {
180 return Atom.family((url: string | null) =>
181 Atom.make(
182 Effect.promise(async (signal) => {
183 if (url === null) return null;
184 try {
185 const response = await fetchMedia(url, { headers: { Range: "bytes=0-0" }, signal });
186 void response.body?.cancel().catch(() => undefined);
187 if (!response.ok) return null;
188 const type = response.headers.get("content-type")?.trim().toLowerCase();
189 if (type?.startsWith("image/")) return "image" as const;
190 if (type?.startsWith("video/")) return "video" as const;
191 return null;
192 } catch {
193 return null;
194 }
195 }),
196 ),
197 );
199​
200type TableRows = ReadonlyArray<ReadonlyArray<PullRequestBodyTableCell>>;
201​
202/**
203 * Cells of a table made only of rows and cells, or null when anything else is in it: a caption,
204 * text between cells, a nested table. Cell contents are split on their own, so tables never nest.
205 */
206function tableRows(html: string, htmlOffset: number): TableRows | null {
207 const rows: PullRequestBodyTableCell[][] = [];
208 let row: PullRequestBodyTableCell[] | null = null;
209 let cell: { tag: string; contentStart: number } | null = null;
210 let opened = false;
211 let closed = false;
212 let cursor = 0;
213 for (const match of html.matchAll(TABLE_STRUCTURE_TAG_PATTERN)) {
214 const closing = match[1] === "/";
215 const tag = match[2]!.toLowerCase();
216 if (cell !== null) {
217 if (!closing || tag !== cell.tag) return null;
218 const content = html.slice(cell.contentStart, match.index);
219 // Indented HTML would render as a code block once the cell is markdown on its own.
220 if (content.split("\n").some((line) => INDENTED_CODE_PATTERN.test(line) && line.trim()))
221 return null;
222 row!.push({
223 header: tag === "th",
224 segments: splitBodyAt(content, htmlOffset + cell.contentStart),
225 });
226 cell = null;
227 } else {
228 if (html.slice(cursor, match.index).trim().length > 0) return null;
229 const tableOpen = opened && !closed;
230 if (tag === "table") {
231 if (closing ? !tableOpen || row !== null : opened) return null;
232 opened = true;
233 closed = closing;
234 } else if (tag === "tr") {
235 if (!tableOpen || closing === (row === null)) return null;
236 if (closing) rows.push(row!);
237 row = closing ? null : [];
238 } else if (tag === "td" || tag === "th") {
239 if (closing || row === null || CELL_SPAN_PATTERN.test(match[3]!)) return null;
240 cell = { tag, contentStart: match.index + match[0].length };
241 } else if (!tableOpen || row !== null) {
242 return null;
243 }
244 }
245 cursor = match.index + match[0].length;
246 }
247 if (!closed || html.slice(cursor).trim().length > 0) return null;
248 return rows.filter((cells) => cells.length > 0);
250​
251/**
252 * The table opening at `start`, through its matching close. `end` is the last line looked at
253 * even when the table is not usable, so the caller never re-reads an inner table on its own.
254 */
255function mediaTableAt(
256 lines: ReadonlyArray<string>,
257 start: number,
258 startOffset: number,
259): { end: number; rows: TableRows | null } {
260 const lastCandidate = Math.min(start + TABLE_MAX_LINES, lines.length) - 1;
261 let depth = 0;
262 let end = start;
263 for (; ; end += 1) {
264 const line = lines[end]!;
265 depth +=
266 (line.match(TABLE_OPEN_PATTERN)?.length ?? 0) -
267 (line.match(TABLE_CLOSE_PATTERN)?.length ?? 0);
268 if (depth <= 0 || end === lastCandidate) break;
269 }
270 if (depth !== 0 || !TABLE_END_PATTERN.test(lines[end]!)) return { end, rows: null };
271 // Lifting attachment links out of a table's cells would tear the table apart.
272 const rows = tableRows(lines.slice(start, end + 1).join("\n"), startOffset);
273 const hasMedia = rows?.some((cells) =>
274 cells.some((cell) => cell.segments.some((segment) => segment.kind === "attachment")),
275 );
276 return { end, rows: hasMedia ? rows : null };
278​
279/**
280 * Each markdown segment renders as its own document, so it leads with the body's definitions.
281 * Leading, they win over a later redefinition in the segment, as the first one does in the body.
282 */
283function withDefinitions(
284 segment: PullRequestBodySegment,
285 definitions: string,
286): PullRequestBodySegment {
287 if (segment.kind === "attachment") return segment;
288 if (segment.kind === "table") {
289 return {
290 ...segment,
291 rows: segment.rows.map((cells) =>
292 cells.map((cell) => ({
293 ...cell,
294 segments: cell.segments.map((inner) => withDefinitions(inner, definitions)),
295 })),
296 ),
297 };
298 }
299 if (!segment.text.includes("[")) return segment;
300 const bomLength = segment.sourceOffset === 0 && segment.text.startsWith("\uFEFF") ? 1 : 0;
301 return {
302 ...segment,
303 text: definitions + segment.text.slice(bomLength),
304 sourceOffset: segment.sourceOffset + bomLength - definitions.length,
305 };
307​
308/**
309 * The first definition of each label in a body, each on one line so it stands outside the quote or
310 * list it was written in, as the client's Markdown parser reads them.
311 */
312export type FindReferenceDefinitions = (body: string) => ReadonlyArray<string>;
313​
314/** How much text the body's definitions may add across all the segments that lead with them. */
315const DEFINITIONS_MAX_ADDED_LENGTH = 256 * 1024;
316​
317function segmentsWithReferences(segments: ReadonlyArray<PullRequestBodySegment>): number {
318 let count = 0;
319 for (const segment of segments) {
320 if (segment.kind === "markdown") count += segment.text.includes("[") ? 1 : 0;
321 else if (segment.kind === "table") {
322 for (const cells of segment.rows)
323 for (const cell of cells) count += segmentsWithReferences(cell.segments);
324 }
325 }
326 return count;
328​
329export function splitPullRequestBody(
330 body: string,
331 findDefinitions: FindReferenceDefinitions,
332): ReadonlyArray<PullRequestBodySegment> {
333 const segments = splitBodyAt(body, 0);
334 // One markdown segment is the whole body, which resolves its own references.
335 const whole = segments.length === 1 && segments[0]!.kind === "markdown";
336 if (whole || !body.includes("]:")) return segments;
337 const definitions = findDefinitions(body);
338 if (definitions.length === 0) return segments;
339 const leading = `${definitions.join("\n")}\n\n`;
340 // Past the budget the body renders as one document: its media stays links, its references resolve.
341 if (leading.length * segmentsWithReferences(segments) > DEFINITIONS_MAX_ADDED_LENGTH) {
342 const text = body.replace(/^(?:\r|\n)+/u, "");
343 return [
344 {
345 id: "markdown:0",
346 kind: "markdown",
347 text: text.trimEnd(),
348 sourceOffset: body.length - text.length,
349 },
350 ];
351 }
352 return segments.map((segment) => withDefinitions(segment, leading));
354​
355/** `baseOffset` is where `body` starts in the whole body, so a table cell's edits write back. */
356function splitBodyAt(body: string, baseOffset: number): ReadonlyArray<PullRequestBodySegment> {
357 const segments: PullRequestBodySegment[] = [];
358 const markdown: string[] = [];
359 let markdownStart = 0;
360 let openFence: {
361 readonly marker: string;
362 readonly flushLeft: boolean;
363 /** Columns of a list item the fence opened in; a less indented line ends the item and fence. */
364 readonly itemIndent: number;
365 } | null = null;
366 let openComment = false;
367​
368 // Blank lines around a run are dropped, but never leading spaces: four of them open an
369 // indented code block, so trimming a run would silently turn code into prose.
370 const flushMarkdown = () => {
371 const joined = markdown.join("\n");
372 const text = joined.replace(/^(?:\r?\n)+/u, "");
373 const sourceOffset = markdownStart + joined.length - text.length;
374 markdown.length = 0;
375 if (text.trim().length > 0) {
376 segments.push({
377 id: `markdown:${segments.length}`,
378 kind: "markdown",
379 text: text.trimEnd(),
380 sourceOffset,
381 });
382 }
383 };
384​
385 const lines = body.replace(/\r(?!\n)/gu, "\n").split("\n");
386 let prose: ReadonlySet<number> | undefined;
387 let tableScannedThrough = -1;
388 let lineStart = baseOffset;
389 for (let index = 0; index < lines.length; lineStart += lines[index]!.length + 1, index += 1) {
390 const line = lines[index]!;
391 if (markdown.length === 0) markdownStart = lineStart;
392 if (openComment) {
393 if (line.includes("-->")) {
394 openComment = false;
395 }
396 markdown.push(line);
397 continue;
398 }
399 if (
400 openFence !== null &&
401 openFence.itemIndent > 0 &&
402 line.trim() &&
403 indentColumns(line) < openFence.itemIndent
404 ) {
405 openFence = null;
406 }
407 const fenceMatch = FENCE_PATTERN.exec(line);
408 const ordered =
409 openFence === null && fenceMatch ? LIST_ITEM_PATTERN.exec(line)?.[1] : undefined;
410 if (ordered && ordered !== "1" && (prose ??= markdownParagraphLines(body)).has(index + 1)) {
411 markdown.push(line);
412 continue;
413 }
414 // ```` ```npm test``` ```` is a code span, not an opener that would flip every later fence.
415 // A span that runs past this line is left an opener, so its lines stay out of media.
416 const isInlineCode =
417 openFence === null &&
418 fenceMatch?.[1]![0] === "`" &&
419 (fenceMatch[2]!.match(/`+/gu) ?? []).some((run) => run.length === fenceMatch[1]!.length);
420 // A backtick fence's info string cannot hold a backtick; on a list marker that is item text.
421 const isListText =
422 openFence === null &&
423 fenceMatch?.[1]![0] === "`" &&
424 fenceMatch[2]!.includes("`") &&
425 LIST_ITEM_PATTERN.test(line);
426 if (fenceMatch !== null && !isInlineCode && !isListText) {
427 const fence = fenceMatch[1]!;
428 // A fence closes only on the same marker, at least as long as the one that opened it,
429 // and with nothing after it: `~~~` cannot end a ``` block, and ```` ```ts ```` is an
430 // info string opening a nested fence, not a close. Under a fence opened at the margin, an
431 // indented-code line is content too: a tab-indented ``` there is part of the example.
432 const closes =
433 openFence !== null &&
434 fence[0] === openFence.marker[0] &&
435 fence.length >= openFence.marker.length &&
436 fenceMatch[2]!.trim().length === 0 &&
437 !LIST_ITEM_PATTERN.test(line) &&
438 !(openFence.flushLeft && INDENTED_CODE_PATTERN.test(line)) &&
439 // A closer may sit at most three columns past its list item's content.
440 !(openFence.itemIndent > 0 && indentColumns(line) > openFence.itemIndent + 3);
441 if (openFence === null) {
442 openFence = {
443 marker: fence,
444 flushLeft: line.startsWith(fence),
445 itemIndent: LIST_ITEM_PATTERN.test(line) ? line.indexOf(fence) : 0,
446 };
447 } else if (closes) {
448 openFence = null;
449 }
450 markdown.push(line);
451 continue;
452 }
453 if (openFence !== null || INDENTED_CODE_PATTERN.test(line)) {
454 markdown.push(line);
455 continue;
456 }
457 if (HTML_COMMENT_START_PATTERN.test(line)) {
458 openComment = !line.includes("-->");
459 markdown.push(line);
460 continue;
461 }
462​
463 if (index > tableScannedThrough && TABLE_START_PATTERN.test(line)) {
464 const table = mediaTableAt(lines, index, lineStart);
465 tableScannedThrough = table.end;
466 if (table.rows !== null) {
467 flushMarkdown();
468 segments.push({ id: `table:${segments.length}`, kind: "table", rows: table.rows });
469 for (; index < table.end; index += 1) lineStart += lines[index]!.length + 1;
470 continue;
471 }
472 }
473​
474 const bareAttachment = attachmentFromLine(line);
475 if (bareAttachment !== null) {
476 flushMarkdown();
477 segments.push({ id: `attachment:${segments.length}`, kind: "attachment", ...bareAttachment });
478 continue;
479 }
480​
481 if (!STANDALONE_VIDEO_TAG_PATTERN.test(line)) {
482 markdown.push(line);
483 continue;
484 }
485 const lastCandidate = Math.min(index + VIDEO_TAG_MAX_LINES, lines.length) - 1;
486 let cursor = index;
487 while (cursor < lastCandidate && !VIDEO_TAG_CLOSE_PATTERN.test(lines[cursor]!)) {
488 cursor += 1;
489 }
490 const source = VIDEO_TAG_END_PATTERN.test(lines[cursor]!)
491 ? videoTagSource(lines.slice(index, cursor + 1).join("\n"))
492 : undefined;
493 if (source !== undefined && webUrl(source) !== null) {
494 flushMarkdown();
495 segments.push({
496 id: `attachment:${segments.length}`,
497 kind: "attachment",
498 url: source,
499​
500 media: "video",
501 });
502 for (; index < cursor; index += 1) lineStart += lines[index]!.length + 1;
503 } else {
504 // Unclosed, or nothing linkable in it: prose. Only this line is consumed, so the
505 // lines that were looked at are still parsed on their own terms.
506 markdown.push(line);
507 }
508 }
509​
510 flushMarkdown();
511 return segments;
513let githubEmojiByAlias: ReadonlyMap<string, string> | undefined;
514const githubEmojiAlias = /:([a-z\d_+-]+)(?=:)/gu;
515​
516/** GitHub's `:alias:` emoji in `text`; a colon closes one alias only, so `:tada:tada:` has one. */
517export function githubEmojiAliases(
518 text: string,
519): ReadonlyArray<{ readonly index: number; readonly text: string; readonly emoji: string }> {
520 githubEmojiByAlias ??= new Map(
521 GITHUB_EMOJI_ALIASES.trim()
522 .split("\n")
523 .map((line) => {
524 const space = line.indexOf(" ");
525 return [line.slice(0, space), line.slice(space + 1)] as const;
526 }),
527 );
528 const found: { index: number; text: string; emoji: string }[] = [];
529 let end = 0;
530 for (const match of text.matchAll(githubEmojiAlias)) {
531 const emoji = githubEmojiByAlias.get(match[1]!);
532 if (emoji === undefined || match.index < end) continue;
533 end = match.index + match[0].length + 1;
534 found.push({ index: match.index, text: `${match[0]}:`, emoji });
535 }
536 return found;
538​
539export function expandGithubEmojiAliases(text: string): string {
540 let expanded = "";
541 let start = 0;
542 for (const alias of githubEmojiAliases(text)) {
543 expanded += text.slice(start, alias.index) + alias.emoji;
544 start = alias.index + alias.text.length;
545 }
546 return start === 0 ? text : expanded + text.slice(start);