Open History to see the last commit
1import { sourceControlClients, type ReferenceAutolink } from "./sourceControlClients.ts";
2
3/** `id` is positional on purpose: the same attachment can be embedded twice in one body. */
4export type PullRequestBodySegment =
5 | { readonly id: string; readonly kind: "markdown"; readonly text: string }
6 | {
7 readonly id: string;
8 readonly kind: "attachment";
9 readonly url: string;
10 readonly media: "video" | "image" | "unknown";
11 };
12
13const FENCE_PATTERN = /^\s{0,3}((?:`{3,})|(?:~{3,}))(.*)$/u;
14/**
15 * How far a `<video>` tag may reach for its closing tag. Real embeds are one to three lines,
16 * and the bound keeps an unclosed tag from making each one rescan the rest of the body.
17 */
18const VIDEO_TAG_MAX_LINES = 8;
19
20const INDENTED_CODE_PATTERN = /^(?: {4}|\t)/u;
21const BARE_URL_PATTERN = /^<?(https?:\/\/\S+?)>?$/u;
22const IMAGE_EXTENSION_PATTERN = /\.(?:png|jpe?g|gif|webp|avif|heic|heif|svg)(?:$|[?#])/iu;
23const MARKDOWN_LINK_PATTERN = /^\[[^\]]*\]\((https?:\/\/[^\s)]+)\)$/u;
24const VIDEO_EXTENSION_PATTERN = /\.(?:mp4|webm|mov|m4v|ogv)(?:$|[?#])/iu;
25
26const VIDEO_TAG_SRC_PATTERN = /<(?:video|source)\b[^>]*\bsrc\s*=\s*["']([^"']+)["']/iu;
27
28const STANDALONE_VIDEO_TAG_PATTERN = /^\s*<video\b/iu;
29const VIDEO_TAG_END_PATTERN = /<\/video>\s*$/iu;
30
31function isWebUrl(url: string): boolean {
32 try {
33 const parsed = new URL(url);
34 return parsed.protocol === "https:" || parsed.protocol === "http:";
35 } catch {
36 return false;
37 }
38}
39
40function attachmentFromLine(
41 line: string,
42): { url: string; media: "video" | "image" | "unknown" } | null {
43 const url =
44 BARE_URL_PATTERN.exec(line.trim())?.[1] ?? MARKDOWN_LINK_PATTERN.exec(line.trim())?.[1];
45 if (url === undefined || !isWebUrl(url)) return null;
46 if (VIDEO_EXTENSION_PATTERN.test(url) || sourceControlClients.mediaUrl(url)?.kind === "video") {
47 return { url, media: "video" };
48 }
49 if (IMAGE_EXTENSION_PATTERN.test(url)) return { url, media: "image" };
50 return null;
51}
52
53export function splitPullRequestBody(body: string): ReadonlyArray<PullRequestBodySegment> {
54 const segments: PullRequestBodySegment[] = [];
55 const markdown: string[] = [];
56 let openFence: string | null = null;
57
58 // Blank lines around a run are dropped, but never leading spaces: four of them open an
59 // indented code block, so trimming a run would silently turn code into prose.
60 const flushMarkdown = () => {
61 const text = markdown.join("\n").replace(/^\n+/u, "").replace(/\s+$/u, "");
62 markdown.length = 0;
63 if (text.trim().length > 0) {
64 segments.push({ id: `markdown:${segments.length}`, kind: "markdown", text });
65 }
66 };
67
68 const lines = body.split("\n");
69 for (let index = 0; index < lines.length; index += 1) {
70 const line = lines[index]!;
71 const fenceMatch = FENCE_PATTERN.exec(line);
72 if (fenceMatch !== null) {
73 const fence = fenceMatch[1]!;
74 // A fence closes only on the same marker, at least as long as the one that opened it,
75 // and with nothing after it: `~~~` cannot end a ``` block, and ```` ```ts ```` is an
76 // info string opening a nested fence, not a close.
77 const closes =
78 openFence !== null &&
79 fence[0] === openFence[0] &&
80 fence.length >= openFence.length &&
81 fenceMatch[2]!.trim().length === 0;
82 if (openFence === null) {
83 openFence = fence;
84 } else if (closes) {
85 openFence = null;
86 }
87 markdown.push(line);
88 continue;
89 }
90 if (openFence !== null || INDENTED_CODE_PATTERN.test(line)) {
91 markdown.push(line);
92 continue;
93 }
94
95 const bareAttachment = attachmentFromLine(line);
96 if (bareAttachment !== null) {
97 flushMarkdown();
98 segments.push({ id: `attachment:${segments.length}`, kind: "attachment", ...bareAttachment });
99 continue;
100 }
101
102 if (!STANDALONE_VIDEO_TAG_PATTERN.test(line)) {
103 markdown.push(line);
104 continue;
105 }
106 const lastCandidate = Math.min(index + VIDEO_TAG_MAX_LINES, lines.length) - 1;
107 let cursor = index;
108 while (cursor < lastCandidate && !VIDEO_TAG_END_PATTERN.test(lines[cursor]!)) {
109 cursor += 1;
110 }
111 const source = VIDEO_TAG_END_PATTERN.test(lines[cursor]!)
112 ? VIDEO_TAG_SRC_PATTERN.exec(lines.slice(index, cursor + 1).join("\n"))?.[1]
113 : undefined;
114 if (source !== undefined && isWebUrl(source)) {
115 flushMarkdown();
116 segments.push({
117 id: `attachment:${segments.length}`,
118 kind: "attachment",
119 url: source,
120
121 media: "video",
122 });
123 index = cursor;
124 } else {
125 // Unclosed, or nothing linkable in it: prose. Only this line is consumed, so the
126 // lines that were looked at are still parsed on their own terms.
127 markdown.push(line);
128 }
129 }
130
131 flushMarkdown();
132 return segments;
133}
134
135/**
136 * Finds the references the change request's host links in plain text, resolved against the change
137 * request's repository. Null when the host links none.
138 */
139export function changeRequestReferenceAutolinker(
140 changeRequest: { readonly provider: string; readonly url: string } | null | undefined,
141): ((text: string) => ReadonlyArray<ReferenceAutolink>) | null {
142 if (!changeRequest) return null;
143 const find = sourceControlClients.get(changeRequest.provider).referenceAutolinks;
144 const repositoryUrl = sourceControlClients.parseChangeRequestUrl(changeRequest.url)?.link
145 .repositoryUrl;
146 return find === undefined || repositoryUrl === undefined
147 ? null
148 : (text) => find(text, repositoryUrl);
149}