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

pullRequestMarkdown.test.ts

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