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

pullRequestMarkdown.test.ts

383 lines15.1 KB

1import type { Root, RootContent } from "mdast";
2import remarkGfm from "remark-gfm";
3import remarkParse from "remark-parse";
4import { unified } from "unified";
5import { describe, expect, it } from "vite-plus/test";
6​
7import {
8 changeRequestReferenceAutolinker,
9 resolveChangeRequestMediaUrl,
10 splitPullRequestBody,
11 type PullRequestBodySegment,
12} from "./pullRequestMarkdown.ts";
13​
14describe("pull request body segmentation", () => {
15 // GitHub writes a dropped image into the body as an `<img>` tag, so a bare attachment link on
16 // its own line is the shape it uses for a video — every one sampled in the wild was one.
17 it("lifts a dropped video out and keeps the prose around it", () => {
18 expect(
19 splitPullRequestBody(
20 "Before\n\nhttps://github.com/user-attachments/assets/2f8c1a90-1b2c-4d5e-8f90-abcdef123456\n\nAfter",
21 ),
22 ).toEqual([
23 { id: "markdown:0", kind: "markdown", text: "Before", sourceOffset: 0 },
24 {
25 id: "attachment:1",
26 kind: "attachment",
27 url: "https://github.com/user-attachments/assets/2f8c1a90-1b2c-4d5e-8f90-abcdef123456",
28 media: "video",
29 },
30 { id: "markdown:2", kind: "markdown", text: "After", sourceOffset: 89 },
31 ]);
32 });
33​
34 it("places each prose run at its offset in the body, including inside a media table", () => {
35 const body =
36 '\n\n- [ ] Before\r\n\nhttps://example.com/shot.png\n\n\n<video controls>\n <source src="https://example.com/a.mp4">\n</video>\n - [ ] code\n- [x] After\n\r\n<table>\r\n<tr><td>\r\n\r\n- [ ] In a cell\r\n\r\n</td><td>\r\n\r\nhttps://example.com/b.mp4\r\n\r\n</td></tr>\r\n</table>\r\n- [ ] Last\n';
37 type Prose = Extract<PullRequestBodySegment, { kind: "markdown" }>;
38 const prose = (segments: ReadonlyArray<PullRequestBodySegment>): Prose[] =>
39 segments.flatMap((segment) =>
40 segment.kind === "markdown"
41 ? [segment]
42 : segment.kind === "table"
43 ? segment.rows.flat().flatMap((cell) => prose(cell.segments))
44 : [],
45 );
46 const runs = prose(splitPullRequestBody(body));
47 expect(runs.map((segment) => segment.text)).toEqual([
48 "- [ ] Before",
49 " - [ ] code\n- [x] After",
50 "- [ ] In a cell",
51 "- [ ] Last",
52 ]);
53 for (const segment of runs) {
54 expect(body.slice(segment.sourceOffset, segment.sourceOffset + segment.text.length)).toBe(
55 segment.text,
56 );
57 }
58 });
59​
60 it("reads the source out of a video tag, including a multi-line one", () => {
61 expect(
62 splitPullRequestBody(
63 '<video controls>\n <source src="https://example.com/a.webm">\n</video>',
64 ),
65 ).toEqual([
66 {
67 id: "attachment:0",
68 kind: "attachment",
69 url: "https://example.com/a.webm",
70 media: "video",
71 },
72 ]);
73 });
74​
75 it("leaves the img tag GitHub writes for a dropped image as markdown", () => {
76 const body =
77 '<img width="1414" alt="image" src="https://github.com/user-attachments/assets/7195f963-51a9-4331-be74-3e06be760422" />';
78 expect(splitPullRequestBody(body)).toEqual([
79 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
80 ]);
81 });
82​
83 it("leaves an ordinary link alone, whether it is bare or written as markdown", () => {
84 const body = "https://example.com/page\n\n[the docs](https://example.com/docs)";
85 expect(splitPullRequestBody(body)).toEqual([
86 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
87 ]);
88 });
89​
90 it("never lifts a link inside fenced code out of it", () => {
91 const body = "```\nhttps://example.com/demo.mp4\n```";
92 expect(splitPullRequestBody(body)).toEqual([
93 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
94 ]);
95 });
96​
97 // GitHub keeps CRLF in a body written in its web editor.
98 it("recognizes fences in a body with CRLF line endings", () => {
99 const body = "```\r\nhttps://example.com/demo.mp4\r\n```";
100 expect(splitPullRequestBody(body)).toEqual([
101 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
102 ]);
103 });
104​
105 it("closes a CRLF fence, so a video after it still lifts out", () => {
106 const code = '```html\r\n<video src="https://example.com/example.mp4"></video>\r\n```';
107 expect(splitPullRequestBody(`${code}\r\n\r\nhttps://example.com/demo.mp4\r\n`)).toEqual([
108 { id: "markdown:0", kind: "markdown", text: code, sourceOffset: 0 },
109 {
110 id: "attachment:1",
111 kind: "attachment",
112 url: "https://example.com/demo.mp4",
113 media: "video",
114 },
115 ]);
116 });
117​
118 it("does not let a different fence marker close an open fence", () => {
119 const body = "```\n~~~\nhttps://example.com/demo.mp4\n```";
120 expect(splitPullRequestBody(body)).toEqual([
121 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
122 ]);
123 });
124​
125 it("keeps a video tag that shares its line with prose as markdown", () => {
126 const body = 'Before <video src="https://example.com/a.mp4"></video> after';
127 expect(splitPullRequestBody(body)).toEqual([
128 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
129 ]);
130 });
131​
132 it("treats an info-string fence as a nested opener, not a close", () => {
133 const body = "```\n```javascript\nhttps://example.com/demo.mp4\n```";
134 expect(splitPullRequestBody(body)).toEqual([
135 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
136 ]);
137 });
138​
139 it("leaves an indented code line alone even when it is only a video link", () => {
140 const body = " https://example.com/demo.mp4";
141 expect(splitPullRequestBody(body)).toEqual([
142 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
143 ]);
144 });
145​
146 it("leaves an unclosed video tag as prose without eating the rest of the body", () => {
147 const body = ['<video src="https://example.com/a.mp4">', "still prose", "more prose"].join(
148 "\n",
149 );
150 expect(splitPullRequestBody(body)).toEqual([
151 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
152 ]);
153 });
154​
155 it("refuses a non-http source rather than making a link out of it", () => {
156 const body = '<video src="javascript:alert(1)"></video>';
157 expect(splitPullRequestBody(body)).toEqual([
158 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
159 ]);
160 });
161});
162​
163describe("reference links around lifted media", () => {
164 const recording =
165 "https://github.com/user-attachments/assets/2f8c1a90-1b2c-4d5e-8f90-abcdef123456";
166 const parser = unified().use(remarkParse).use(remarkGfm);
167 const prose = (segments: ReadonlyArray<PullRequestBodySegment>): string[] =>
168 segments.flatMap((segment) =>
169 segment.kind === "markdown"
170 ? [segment.text]
171 : segment.kind === "table"
172 ? segment.rows.flat().flatMap((cell) => prose(cell.segments))
173 : [],
174 );
175 // Each segment renders as its own document; the first definition of a label wins, as in mdast-util-to-hast.
176 const referenceLinks = (body: string) =>
177 prose(splitPullRequestBody(body)).flatMap((text) => {
178 const definitions = new Map<string, string>();
179 const references: Array<{ identifier: string; text: string }> = [];
180 const visit = (node: Root | RootContent) => {
181 if (node.type === "definition" && !definitions.has(node.identifier)) {
182 definitions.set(node.identifier, node.url);
183 }
184 if (node.type === "linkReference") {
185 references.push({
186 identifier: node.identifier,
187 text: node.children.map((child) => ("value" in child ? child.value : "")).join(""),
188 });
189 }
190 if ("children" in node) node.children.forEach(visit);
191 };
192 visit(parser.parse(text));
193 return references.map((reference) => [reference.text, definitions.get(reference.identifier)]);
194 });
195​
196 it.each([
197 [
198 "use, then media, then definition",
199 `See [the docs][guide].\n\n${recording}\n\n[guide]: https://example.com/docs`,
200 ],
201 [
202 "definition, then media, then use",
203 `[guide]: https://example.com/docs\n\n${recording}\n\nSee [the docs][guide].`,
204 ],
205 ...["\n", "\r\n", "\r"].map((lineEnding) => [
206 `a definition wrapped over quoted lines with ${JSON.stringify(lineEnding)}`,
207 `> [guide]:${lineEnding}> https://example.com/docs${lineEnding}> "The guide"\n\n${recording}\n\nSee [the docs][guide].`,
208 ]),
209 [
210 "a use inside a media table cell",
211 `<table><tr><td>\n\nSee [the docs][guide].\n\n</td><td>\n\n${recording}\n\n</td></tr></table>\n\n[guide]: https://example.com/docs`,
212 ],
213 ])("resolves a reference defined across a video: %s", (_case, body) => {
214 expect(referenceLinks(body)).toEqual([["the docs", "https://example.com/docs"]]);
215 });
216​
217 it("keeps the body's first definition of a label, wherever the media falls", () => {
218 expect(
219 referenceLinks(
220 `[guide]: https://example.com/first\n\n${recording}\n\nSee [the docs][guide].\n\n[GUIDE]: https://example.com/second`,
221 ),
222 ).toEqual([["the docs", "https://example.com/first"]]);
223 });
224​
225 it("leaves a definition shown in code as code", () => {
226 expect(
227 referenceLinks(
228 `\`\`\`md\n[guide]: https://example.com/docs\n\`\`\`\n\n${recording}\n\nSee [the docs][guide].`,
229 ),
230 ).toEqual([]);
231 });
232​
233 it("still writes a task tick back to its place in the body", () => {
234 const body = `[guide]: https://example.com/docs\n\n${recording}\n\n- [ ] Read [the docs][guide]`;
235 const segment = splitPullRequestBody(body).at(-1)!;
236 if (segment.kind !== "markdown") throw new Error("expected prose last");
237 const marker = segment.text.indexOf("[ ]");
238 expect(body.slice(segment.sourceOffset + marker)).toBe("[ ] Read [the docs][guide]");
239 });
240});
241​
242describe("media on custom hosts", () => {
243 it.each([
244 ["https://drop.example.com/capture.PNG?token=abc#preview", "image"],
245 ["[Recording](https://drop.example.com/recording.mov)", "video"],
246 ["<https://drop.example.com/shot.webp>", "image"],
247 ])("recognizes %s without a request", (body, media) => {
248 expect(splitPullRequestBody(body)).toEqual([
249 expect.objectContaining({ kind: "attachment", media }),
250 ]);
251 });
252​
253 it("keeps inline links and media examples in code as prose", () => {
254 const body =
255 "See [recording](https://drop.example.com/a.mp4) for context.\n\n```md\nhttps://drop.example.com/a.png\n```";
256 expect(splitPullRequestBody(body)).toEqual([
257 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
258 ]);
259 });
260});
261​
262describe("media tables", () => {
263 const before = "https://github.com/user-attachments/assets/c69c7c1c-ef2f-47dd-97e8-fe42e40712eb";
264 const after = "https://github.com/user-attachments/assets/1867b6ec-4f88-4248-b2df-6b0f9808105b";
265 const video = "https://example.com/a.mp4";
266​
267 it("keeps GitHub's before/after video table together, splitting each cell on its own", () => {
268 const segments = splitPullRequestBody(
269 `Intro\n\n<table>\n<tr><th>Before</th><th>After</th></tr>\n<tr>\n<td>\n\n${before}\n\n</td>\n<td>\n\n${after}\n\n</td>\n</tr>\n</table>\n\nOutro`,
270 );
271 expect(segments.map((segment) => segment.kind)).toEqual(["markdown", "table", "markdown"]);
272 expect(segments[0]).toMatchObject({ text: "Intro" });
273 expect(segments[2]).toMatchObject({ text: "Outro" });
274 const table = segments[1]!;
275 if (table.kind !== "table") throw new Error("expected a table segment");
276 expect(
277 table.rows.map((row) =>
278 row.map((cell) =>
279 cell.segments.map((segment) =>
280 segment.kind === "attachment" ? `attachment:${segment.url}` : segment,
281 ),
282 ),
283 ),
284 ).toEqual([
285 [
286 [{ id: "markdown:0", kind: "markdown", text: "Before", sourceOffset: 23 }],
287 [{ id: "markdown:0", kind: "markdown", text: "After", sourceOffset: 38 }],
288 ],
289 [[`attachment:${before}`], [`attachment:${after}`]],
290 ]);
291 });
292​
293 it("keeps a quoted `>` inside a cell's attributes out of its text", () => {
294 const [table] = splitPullRequestBody(
295 `<table>\n<tr><td title="Before > after">Caption</td><td>\n\n${video}\n\n</td></tr>\n</table>`,
296 );
297 expect(table).toMatchObject({
298 kind: "table",
299 rows: [[{ segments: [{ kind: "markdown", text: "Caption" }] }, {}]],
300 });
301 });
302​
303 it("leaves a table without media links as markdown", () => {
304 const body = "<table>\n<tr><td>a</td><td>b</td></tr>\n</table>";
305 expect(splitPullRequestBody(body)).toEqual([
306 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
307 ]);
308 });
309​
310 it.each([
311 ["a caption", "<table>\n<caption>Before upgrading</caption>\n<tr><td>", "</td></tr>\n</table>"],
312 ["text outside cells", "<table>\nBefore upgrading\n<tr><td>", "</td></tr>\n</table>"],
313 [
314 "text inside a row but outside cells",
315 "<table>\n<tr>Before upgrading<td>",
316 "</td></tr>\n</table>",
317 ],
318 [
319 "a table nested in another",
320 "<table>\n<tr><td>\n<table>\n<tr><td>",
321 "</td></tr>\n</table>\n</td></tr>\n</table>",
322 ],
323 ["an unclosed table", "<table>\n<tr><td>", ""],
324 ["a spanning cell", '<table>\n<tr><td colspan="2">', "</td></tr>\n</table>"],
325 [
326 "an indented cell",
327 "<table>\n <tr>\n <th>\n Before\n </th>\n </tr>\n <tr><td>",
328 "</td></tr>\n</table>",
329 ],
330 [
331 "a cell indented by a space and a tab",
332 "<table>\n<tr><td>\n \tBefore\n</td><td>",
333 "</td></tr>\n</table>",
334 ],
335 ])("splits a media table with %s line by line, as before", (_name, open, close) => {
336 const body = `${open}\n\n${video}\n\n${close}`;
337 expect(splitPullRequestBody(body)).toEqual([
338 { id: "markdown:0", kind: "markdown", text: open, sourceOffset: 0 },
339 { id: "attachment:1", kind: "attachment", url: video, media: "video" },
340 ...(close
341 ? [
342 {
343 id: "markdown:2",
344 kind: "markdown",
345 text: close,
346 sourceOffset: body.length - close.length,
347 },
348 ]
349 : []),
350 ]);
351 });
352});
353​
354describe("change request reference autolinks", () => {
355 const urls = (provider: string, url: string, text: string) =>
356 changeRequestReferenceAutolinker({ provider, url })?.(text).map((link) => link.url) ?? null;
357​
358 it("links references against the change request's own repository", () => {
359 expect(urls("github", "https://ghe.example.com/acme/web/pull/7", "Fixes #5")).toEqual([
360 "https://ghe.example.com/acme/web/issues/5",
361 ]);
362 });
363​
364 // regression: the mobile review guide linked every host's `#5` with GitHub's grammar
365 it("links nothing on a host whose grammar is not applied", () => {
366 expect(urls("forgejo", "https://codeberg.org/acme/web/pulls/7", "#5")).toBeNull();
367 });
368});
369​
370describe("change request media urls", () => {
371 // regression: GitCafe's `/api/attachments/<id>` uploads rendered as missing local files
372 it.each([
373 ["/api/attachments/attach_1", "https://git.cafe/api/attachments/attach_1"],
374 ["//cdn.example.com/a.png", "//cdn.example.com/a.png"],
375 ["/\\evil.example.com/a.png", "/\\evil.example.com/a.png"],
376 ["https://example.com/a.png", "https://example.com/a.png"],
377 ["docs/a.png", "docs/a.png"],
378 ])("resolves %s against the forge", (url, expected) => {
379 expect(resolveChangeRequestMediaUrl(url, "https://git.cafe/pingdotgg/t3code/pulls/31251")).toBe(
380 expected,
381 );
382 });
383});