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

pullRequestMarkdown.test.ts

419 lines16.5 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("keeps a video tag that shares its line with prose as markdown", () => {
144 const body = 'Before <video src="https://example.com/a.mp4"></video> after';
145 expect(split(body)).toEqual([
146 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
147 ]);
148 });
149​
150 it("treats an info-string fence as a nested opener, not a close", () => {
151 const body = "```\n```javascript\nhttps://example.com/demo.mp4\n```";
152 expect(split(body)).toEqual([
153 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
154 ]);
155 });
156​
157 it("does not open a fence on a line of inline triple-backtick code", () => {
158 const code = "```\nhttps://example.com/b.png\n```";
159 expect(
160 split(`\`\`\`npm test\`\`\` passes.\n\nhttps://example.com/demo.mp4\n\n${code}`),
161 ).toEqual([
162 { id: "markdown:0", kind: "markdown", text: "```npm test``` passes.", sourceOffset: 0 },
163 {
164 id: "attachment:1",
165 kind: "attachment",
166 url: "https://example.com/demo.mp4",
167 media: "video",
168 },
169 { id: "markdown:2", kind: "markdown", text: code, sourceOffset: 54 },
170 ]);
171 const multilineSpan = "```foo`\nhttps://example.com/demo.mp4\nbar```";
172 expect(split(multilineSpan)).toEqual([
173 { id: "markdown:0", kind: "markdown", text: multilineSpan, sourceOffset: 0 },
174 ]);
175 });
176​
177 it("leaves an indented code line alone even when it is only a video link", () => {
178 const body = " https://example.com/demo.mp4";
179 expect(split(body)).toEqual([
180 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
181 ]);
182 });
183​
184 it("leaves an unclosed video tag as prose without eating the rest of the body", () => {
185 const body = ['<video src="https://example.com/a.mp4">', "still prose", "more prose"].join(
186 "\n",
187 );
188 expect(split(body)).toEqual([
189 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
190 ]);
191 });
192​
193 it("refuses a non-http source rather than making a link out of it", () => {
194 const body = '<video src="javascript:alert(1)"></video>';
195 expect(split(body)).toEqual([
196 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
197 ]);
198 });
199});
200​
201describe("reference links around lifted media", () => {
202 const recording =
203 "https://github.com/user-attachments/assets/2f8c1a90-1b2c-4d5e-8f90-abcdef123456";
204 const parser = unified().use(remarkParse).use(remarkGfm);
205 const prose = (segments: ReadonlyArray<PullRequestBodySegment>): string[] =>
206 segments.flatMap((segment) =>
207 segment.kind === "markdown"
208 ? [segment.text]
209 : segment.kind === "table"
210 ? segment.rows.flat().flatMap((cell) => prose(cell.segments))
211 : [],
212 );
213 // Each segment renders as its own document; the first definition of a label wins, as in mdast-util-to-hast.
214 const referenceLinks = (body: string) =>
215 prose(split(body)).flatMap((text) => {
216 const definitions = new Map<string, string>();
217 const references: Array<{ identifier: string; text: string }> = [];
218 const visit = (node: Root | RootContent) => {
219 if (node.type === "definition" && !definitions.has(node.identifier)) {
220 definitions.set(node.identifier, node.url);
221 }
222 if (node.type === "linkReference") {
223 references.push({
224 identifier: node.identifier,
225 text: node.children.map((child) => ("value" in child ? child.value : "")).join(""),
226 });
227 }
228 if ("children" in node) node.children.forEach(visit);
229 };
230 visit(parser.parse(text));
231 return references.map((reference) => [reference.text, definitions.get(reference.identifier)]);
232 });
233​
234 it.each([
235 [
236 "use, then media, then definition",
237 `See [the docs][guide].\n\n${recording}\n\n[guide]: https://example.com/docs`,
238 ],
239 [
240 "definition, then media, then use",
241 `[guide]: https://example.com/docs\n\n${recording}\n\nSee [the docs][guide].`,
242 ],
243 ...["\n", "\r\n", "\r"].map((lineEnding) => [
244 `a definition wrapped over quoted lines with ${JSON.stringify(lineEnding)}`,
245 `> [guide]:${lineEnding}> https://example.com/docs${lineEnding}> "The guide"\n\n${recording}\n\nSee [the docs][guide].`,
246 ]),
247 [
248 "a use inside a media table cell",
249 `<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`,
250 ],
251 ])("resolves a reference defined across a video: %s", (_case, body) => {
252 expect(referenceLinks(body)).toEqual([["the docs", "https://example.com/docs"]]);
253 });
254​
255 it("keeps the body's first definition of a label, wherever the media falls", () => {
256 expect(
257 referenceLinks(
258 `[guide]: https://example.com/first\n\n${recording}\n\nSee [the docs][guide].\n\n[GUIDE]: https://example.com/second`,
259 ),
260 ).toEqual([["the docs", "https://example.com/first"]]);
261 });
262​
263 it("leaves a definition shown in code as code", () => {
264 expect(
265 referenceLinks(
266 `\`\`\`md\n[guide]: https://example.com/docs\n\`\`\`\n\n${recording}\n\nSee [the docs][guide].`,
267 ),
268 ).toEqual([]);
269 });
270​
271 it("still writes a task tick back to its place in the body", () => {
272 const body = `[guide]: https://example.com/docs\n\n${recording}\n\n- [ ] Read [the docs][guide]`;
273 const segment = split(body).at(-1)!;
274 if (segment.kind !== "markdown") throw new Error("expected prose last");
275 const marker = segment.text.indexOf("[ ]");
276 expect(body.slice(segment.sourceOffset + marker)).toBe("[ ] Read [the docs][guide]");
277 });
278});
279​
280describe("media on custom hosts", () => {
281 it.each([
282 ["https://drop.example.com/capture.PNG?token=abc#preview", "image"],
283 ["[Recording](https://drop.example.com/recording.mov)", "video"],
284 ["<https://drop.example.com/shot.webp>", "image"],
285 ])("recognizes %s without a request", (body, media) => {
286 expect(split(body)).toEqual([expect.objectContaining({ kind: "attachment", media })]);
287 });
288​
289 it("keeps inline links and media examples in code as prose", () => {
290 const body =
291 "See [recording](https://drop.example.com/a.mp4) for context.\n\n```md\nhttps://drop.example.com/a.png\n```";
292 expect(split(body)).toEqual([
293 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
294 ]);
295 });
296});
297​
298describe("media tables", () => {
299 const before = "https://github.com/user-attachments/assets/c69c7c1c-ef2f-47dd-97e8-fe42e40712eb";
300 const after = "https://github.com/user-attachments/assets/1867b6ec-4f88-4248-b2df-6b0f9808105b";
301 const video = "https://example.com/a.mp4";
302​
303 it("keeps GitHub's before/after video table together, splitting each cell on its own", () => {
304 const segments = split(
305 `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`,
306 );
307 expect(segments.map((segment) => segment.kind)).toEqual(["markdown", "table", "markdown"]);
308 expect(segments[0]).toMatchObject({ text: "Intro" });
309 expect(segments[2]).toMatchObject({ text: "Outro" });
310 const table = segments[1]!;
311 if (table.kind !== "table") throw new Error("expected a table segment");
312 expect(
313 table.rows.map((row) =>
314 row.map((cell) =>
315 cell.segments.map((segment) =>
316 segment.kind === "attachment" ? `attachment:${segment.url}` : segment,
317 ),
318 ),
319 ),
320 ).toEqual([
321 [
322 [{ id: "markdown:0", kind: "markdown", text: "Before", sourceOffset: 23 }],
323 [{ id: "markdown:0", kind: "markdown", text: "After", sourceOffset: 38 }],
324 ],
325 [[`attachment:${before}`], [`attachment:${after}`]],
326 ]);
327 });
328​
329 it("keeps a quoted `>` inside a cell's attributes out of its text", () => {
330 const [table] = split(
331 `<table>\n<tr><td title="Before > after">Caption</td><td>\n\n${video}\n\n</td></tr>\n</table>`,
332 );
333 expect(table).toMatchObject({
334 kind: "table",
335 rows: [[{ segments: [{ kind: "markdown", text: "Caption" }] }, {}]],
336 });
337 });
338​
339 it("leaves a table without media links as markdown", () => {
340 const body = "<table>\n<tr><td>a</td><td>b</td></tr>\n</table>";
341 expect(split(body)).toEqual([
342 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
343 ]);
344 });
345​
346 it.each([
347 ["a caption", "<table>\n<caption>Before upgrading</caption>\n<tr><td>", "</td></tr>\n</table>"],
348 ["text outside cells", "<table>\nBefore upgrading\n<tr><td>", "</td></tr>\n</table>"],
349 [
350 "text inside a row but outside cells",
351 "<table>\n<tr>Before upgrading<td>",
352 "</td></tr>\n</table>",
353 ],
354 [
355 "a table nested in another",
356 "<table>\n<tr><td>\n<table>\n<tr><td>",
357 "</td></tr>\n</table>\n</td></tr>\n</table>",
358 ],
359 ["an unclosed table", "<table>\n<tr><td>", ""],
360 ["a spanning cell", '<table>\n<tr><td colspan="2">', "</td></tr>\n</table>"],
361 [
362 "an indented cell",
363 "<table>\n <tr>\n <th>\n Before\n </th>\n </tr>\n <tr><td>",
364 "</td></tr>\n</table>",
365 ],
366 [
367 "a cell indented by a space and a tab",
368 "<table>\n<tr><td>\n \tBefore\n</td><td>",
369 "</td></tr>\n</table>",
370 ],
371 ])("splits a media table with %s line by line, as before", (_name, open, close) => {
372 const body = `${open}\n\n${video}\n\n${close}`;
373 expect(split(body)).toEqual([
374 { id: "markdown:0", kind: "markdown", text: open, sourceOffset: 0 },
375 { id: "attachment:1", kind: "attachment", url: video, media: "video" },
376 ...(close
377 ? [
378 {
379 id: "markdown:2",
380 kind: "markdown",
381 text: close,
382 sourceOffset: body.length - close.length,
383 },
384 ]
385 : []),
386 ]);
387 });
388});
389​
390describe("change request reference autolinks", () => {
391 const urls = (provider: string, url: string, text: string) =>
392 changeRequestReferenceAutolinker({ provider, url })?.(text).map((link) => link.url) ?? null;
393​
394 it("links references against the change request's own repository", () => {
395 expect(urls("github", "https://ghe.example.com/acme/web/pull/7", "Fixes #5")).toEqual([
396 "https://ghe.example.com/acme/web/issues/5",
397 ]);
398 });
399​
400 // regression: the mobile review guide linked every host's `#5` with GitHub's grammar
401 it("links nothing on a host whose grammar is not applied", () => {
402 expect(urls("forgejo", "https://codeberg.org/acme/web/pulls/7", "#5")).toBeNull();
403 });
404});
405​
406describe("change request media urls", () => {
407 // regression: GitCafe's `/api/attachments/<id>` uploads rendered as missing local files
408 it.each([
409 ["/api/attachments/attach_1", "https://git.cafe/api/attachments/attach_1"],
410 ["//cdn.example.com/a.png", "//cdn.example.com/a.png"],
411 ["/\\evil.example.com/a.png", "/\\evil.example.com/a.png"],
412 ["https://example.com/a.png", "https://example.com/a.png"],
413 ["docs/a.png", "docs/a.png"],
414 ])("resolves %s against the forge", (url, expected) => {
415 expect(resolveChangeRequestMediaUrl(url, "https://git.cafe/pingdotgg/t3code/pulls/31251")).toBe(
416 expected,
417 );
418 });
419});