Open History to see the last commit
1import { describe, expect, it, vi } from "@effect/vitest";
2import * as Effect from "effect/Effect";
3import { AtomRegistry } from "effect/reactivity";
4import type { Root, RootContent } from "mdast";
5import remarkGfm from "remark-gfm";
6import remarkParse from "remark-parse";
7import { unified } from "unified";
8
9import {
10 makePullRequestMediaKindAtom,
11 splitPullRequestBody,
12 type PullRequestBodySegment,
13} from "./pullRequestMarkdown.ts";
14import {
15 changeRequestReferenceAutolinker,
16 resolveChangeRequestMediaUrl,
17} from "./pullRequestReferences.ts";
18
19const definitionParser = unified().use(remarkParse).use(remarkGfm);
20
21// The finder a client passes: each first definition, joined onto one line out of its quote.
22const split = (body: string) =>
23 splitPullRequestBody(body, (markdown) => {
24 const definitions = new Map<string, string>();
25 const visit = (node: Root | RootContent, quotes: number) => {
26 if (node.type === "definition" && !definitions.has(node.identifier)) {
27 const wrap = new RegExp(`(?:\\r\\n|\\r|\\n)(?:[ \\t]*>){0,${quotes}}[ \\t]*`, "gu");
28 const source = markdown.slice(node.position?.start.offset, node.position?.end.offset);
29 definitions.set(node.identifier, source.replace(wrap, " "));
30 }
31 if ("children" in node) {
32 for (const child of node.children)
33 visit(child, quotes + (node.type === "blockquote" ? 1 : 0));
34 }
35 };
36 visit(definitionParser.parse(markdown), 0);
37 return [...definitions.values()];
38 });
39
40describe("pull request body segmentation", () => {
41 it("lifts a GitHub upload without guessing its type and keeps the prose around it", () => {
42 expect(
43 split(
44 "Before\n\nhttps://github.com/user-attachments/assets/2f8c1a90-1b2c-4d5e-8f90-abcdef123456\n\nAfter",
45 ),
46 ).toEqual([
47 { id: "markdown:0", kind: "markdown", text: "Before", sourceOffset: 0 },
48 {
49 id: "attachment:1",
50 kind: "attachment",
51 url: "https://github.com/user-attachments/assets/2f8c1a90-1b2c-4d5e-8f90-abcdef123456",
52 media: "unknown",
53 },
54 { id: "markdown:2", kind: "markdown", text: "After", sourceOffset: 89 },
55 ]);
56 });
57
58 it("leaves the type of a linked GitHub upload unresolved", () => {
59 const upload =
60 "https://github.com/user-attachments/assets/f619ea9d-112c-400b-b1db-8c8d5d2357cc";
61 expect(split(`[Native iPhone caption playback](${upload})`)).toEqual([
62 {
63 id: "attachment:0",
64 kind: "attachment",
65 url: upload,
66 media: "unknown",
67 label: "Native iPhone caption playback",
68 },
69 ]);
70 });
71
72 it("places each prose run at its offset in the body, including inside a media table", () => {
73 const body =
74 '\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';
75 type Prose = Extract<PullRequestBodySegment, { kind: "markdown" }>;
76 const prose = (segments: ReadonlyArray<PullRequestBodySegment>): Prose[] =>
77 segments.flatMap((segment) =>
78 segment.kind === "markdown"
79 ? [segment]
80 : segment.kind === "table"
81 ? segment.rows.flat().flatMap((cell) => prose(cell.segments))
82 : [],
83 );
84 const runs = prose(split(body));
85 expect(runs.map((segment) => segment.text)).toEqual([
86 "- [ ] Before",
87 " - [ ] code\n- [x] After",
88 "- [ ] In a cell",
89 "- [ ] Last",
90 ]);
91 for (const segment of runs) {
92 expect(body.slice(segment.sourceOffset, segment.sourceOffset + segment.text.length)).toBe(
93 segment.text,
94 );
95 }
96 });
97
98 it("reads the source out of a video tag, including a multi-line one", () => {
99 expect(
100 split('<video controls>\n <source src="https://example.com/a.webm">\n</video>'),
101 ).toEqual([
102 {
103 id: "attachment:0",
104 kind: "attachment",
105 url: "https://example.com/a.webm",
106 media: "video",
107 },
108 ]);
109 for (const body of [
110 '<video src="https://example.org/right.mp4" data-src="https://example.org/wrong.mp4"></video>',
111 '<video data-src="https://example.org/wrong.mp4" src="https://example.org/right.mp4"></video>',
112 ]) {
113 expect(split(body)).toEqual([
114 {
115 id: "attachment:0",
116 kind: "attachment",
117 url: "https://example.org/right.mp4",
118 media: "video",
119 },
120 ]);
121 }
122 expect(split("<video src=https://example.org/demo.mp4?token=abc></video>")).toEqual([
123 {
124 id: "attachment:0",
125 kind: "attachment",
126 url: "https://example.org/demo.mp4?token=abc",
127 media: "video",
128 },
129 ]);
130 for (const [body, url] of [
131 [
132 '<video src="https://example.org/a.mp4?x=1&y=2"></video>',
133 "https://example.org/a.mp4?x=1&y=2",
134 ],
135 [
136 '<video><source src="https://example.org/a.mp4?x=1&y=2&z=3"></video>',
137 "https://example.org/a.mp4?x=1&y=2&z=3",
138 ],
139 [
140 '<video src="https://example.org/a.mp4?x=1&amp;y=2"></video>',
141 "https://example.org/a.mp4?x=1&y=2",
142 ],
143 ] as const) {
144 expect(split(body)).toEqual([
145 {
146 id: "attachment:0",
147 kind: "attachment",
148 url,
149 media: "video",
150 },
151 ]);
152 }
153 const dataSrcOnly = '<video data-src="https://example.org/wrong.mp4"></video>';
154 expect(split(dataSrcOnly)).toEqual([
155 { id: "markdown:0", kind: "markdown", text: dataSrcOnly, sourceOffset: 0 },
156 ]);
157 });
158
159 it("leaves the img tag GitHub writes for a dropped image as markdown", () => {
160 const body =
161 '<img width="1414" alt="image" src="https://github.com/user-attachments/assets/7195f963-51a9-4331-be74-3e06be760422" />';
162 expect(split(body)).toEqual([
163 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
164 ]);
165 });
166
167 it("leaves an ordinary link alone, whether it is bare or written as markdown", () => {
168 const body = "https://example.com/page\n\n[the docs](https://example.com/docs)";
169 expect(split(body)).toEqual([
170 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
171 ]);
172 });
173
174 it("never lifts a link inside fenced code out of it", () => {
175 const body = "```\nhttps://example.com/demo.mp4\n```";
176 expect(split(body)).toEqual([
177 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
178 ]);
179 });
180
181 // GitHub keeps CRLF in a body written in its web editor.
182 it("recognizes fences in a body with CRLF line endings", () => {
183 const body = "```\r\nhttps://example.com/demo.mp4\r\n```";
184 expect(split(body)).toEqual([
185 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
186 ]);
187 });
188
189 it("closes a CRLF fence, so a video after it still lifts out", () => {
190 const code = '```html\r\n<video src="https://example.com/example.mp4"></video>\r\n```';
191 expect(split(`${code}\r\n\r\nhttps://example.com/demo.mp4\r\n`)).toEqual([
192 { id: "markdown:0", kind: "markdown", text: code, sourceOffset: 0 },
193 {
194 id: "attachment:1",
195 kind: "attachment",
196 url: "https://example.com/demo.mp4",
197 media: "video",
198 },
199 ]);
200 });
201
202 it("splits a lone-CR body into lines, so a video after its fence still lifts out", () => {
203 const crLines = ["```text", "https://example.com/sample.mp4", "```"];
204 const crBody = [...crLines, "", "https://example.com/actual.mp4", "", "- [ ] Done"].join("\r");
205 expect(split(crBody)).toEqual([
206 { id: "markdown:0", kind: "markdown", text: crLines.join("\n"), sourceOffset: 0 },
207 {
208 id: "attachment:1",
209 kind: "attachment",
210 url: "https://example.com/actual.mp4",
211 media: "video",
212 },
213 {
214 id: "markdown:2",
215 kind: "markdown",
216 text: "- [ ] Done",
217 sourceOffset: crBody.indexOf("- [ ] Done"),
218 },
219 ]);
220 });
221
222 it("keeps a fence opened on a list marker in the list, closing it on its close or dedent", () => {
223 const actual = {
224 id: "attachment:1",
225 kind: "attachment",
226 url: "https://example.com/actual.mp4",
227 media: "video",
228 };
229 const listCode = "- ```text\n https://example.com/sample.mp4\n ```";
230 expect(split(`${listCode}\n\nhttps://example.com/actual.mp4`)).toEqual([
231 { id: "markdown:0", kind: "markdown", text: listCode, sourceOffset: 0 },
232 actual,
233 ]);
234 const unclosed = "1. ```text\n https://example.com/sample.mp4";
235 expect(split(`${unclosed}\nhttps://example.com/actual.mp4`)).toEqual([
236 { id: "markdown:0", kind: "markdown", text: unclosed, sourceOffset: 0 },
237 actual,
238 ]);
239 const tabbed = "- ```text\n\tcode()\n https://example.com/sample.mp4\n ```";
240 expect(split(`${tabbed}\n\nhttps://example.com/actual.mp4`)).toEqual([
241 { id: "markdown:0", kind: "markdown", text: tabbed, sourceOffset: 0 },
242 actual,
243 ]);
244 const deepCloser = "- ```text\n\t\t```\n https://example.com/sample.mp4\n ```";
245 expect(split(`${deepCloser}\n\nhttps://example.com/actual.mp4`)).toEqual([
246 { id: "markdown:0", kind: "markdown", text: deepCloser, sourceOffset: 0 },
247 actual,
248 ]);
249 expect(split("- ```js`x\n\n https://example.com/actual.mp4")).toEqual([
250 { id: "markdown:0", kind: "markdown", text: "- ```js`x", sourceOffset: 0 },
251 actual,
252 ]);
253 const shown = "```markdown\n- ```\nhttps://example.com/sample.mp4\n```";
254 expect(split(`${shown}\n\nhttps://example.com/actual.mp4`)).toEqual([
255 { id: "markdown:0", kind: "markdown", text: shown, sourceOffset: 0 },
256 actual,
257 ]);
258 });
259
260 it.each([
261 ["list marker", "\t- ~~~", " "],
262 ["no list marker", "\t~~~", ""],
263 ["complete example", "Intro\n\n\t- ~~~\n\t https://example.com/a.mp4\n\t ~~~", ""],
264 ["BOM before prose", "\uFEFFIntro\n\n\t- ~~~", " "],
265 ["BOM before example", "\uFEFF\t~~~", ""],
266 ["BOM before a large example", `\uFEFF\t~~~\n\t${"a".repeat(17_000)}`, ""],
267 ["a long setext heading", `${"a".repeat(17_000)}\n===\n\t~~~`, ""],
268 ["a long closed HTML comment", `<!--\n${"a".repeat(17_000)}\n-->\n\t~~~`, ""],
269 ["long description before example", `${"Release notes.\n\n".repeat(1100)}\t~~~`, ""],
270 ["long CRLF description", `${"Release notes.\r\n\r\n".repeat(1000)} \t- \`\`\``, " "],
271 ["a single long paragraph", `${"a".repeat(17_000)}\n\n\t~~~`, ""],
272 ["a large closed fence", `\`\`\`\n${"a".repeat(17_000)}\n\`\`\`\n\n\t~~~`, ""],
273 [
274 "an example immediately after a large fence",
275 `\`\`\`\n${"a".repeat(17_000)}\n\`\`\`\n\t~~~`,
276 "",
277 ],
278 [
279 "two large examples",
280 [1, 2].map(() => `\t~~~\n\t${"a".repeat(8500)}`).join("\n\nIntro\n\n"),
281 "",
282 ],
283 ["a long list with a dedented example", `${"100. Item\n".repeat(1700)}\n\t~~~`, ""],
284 ])("lifts a video after a tab-indented example with %s", (_, code, indent) => {
285 const segments = splitPullRequestBody(
286 `${code}\n\n${indent}https://example.com/demo.mp4`,
287 () => [],
288 );
289 expect(segments.map((segment) => segment.kind)).toEqual(["markdown", "attachment"]);
290 expect(segments[0]).toMatchObject({ text: code });
291 expect(segments[1]).toMatchObject({ url: "https://example.com/demo.mp4", media: "video" });
292 });
293
294 it.each([
295 ["ordered parent", "1. Step\n\t- ```sh\n\t run\n\t ```"],
296 ["bullet parent", "- List\n\t- ~~~\n\t code\n\t ~~~"],
297 ["blank after parent", "- List\n\n\t- ~~~\n\t code\n\t ~~~"],
298 ])("lifts a video after a real tab-indented nested list fence (%s)", (_, code) => {
299 const segments = splitPullRequestBody(`${code}\n\nhttps://example.com/demo.mp4`, () => []);
300 expect(segments.map((segment) => segment.kind)).toEqual(["markdown", "attachment"]);
301 expect(segments[0]).toMatchObject({ text: code });
302 expect(segments[1]).toMatchObject({ url: "https://example.com/demo.mp4", media: "video" });
303 });
304
305 it("only lets a list starting at 1 open a fence inside prose", () => {
306 const splitSegments = (body: string) => splitPullRequestBody(body, () => []);
307 const body = "Intro\n2. ~~~\n https://example.com/demo.mp4";
308 for (const candidate of [
309 body,
310 "Release notes.\n\n".repeat(1100) + body,
311 body.replace("Intro", "a".repeat(17_000)),
312 "a".repeat(17_000) + "\n\n" + "Intro\n2. ~~~\n\n".repeat(32) + body,
313 ]) {
314 const segments = splitSegments(candidate);
315 expect(segments.map((segment) => segment.kind)).toEqual(["markdown", "attachment"]);
316 expect(segments[1]).toMatchObject({ url: "https://example.com/demo.mp4", media: "video" });
317 }
318 for (const code of [
319 body.replace("2.", "1."),
320 body.replace("Intro\n", "Intro\n\n"),
321 body.replace("Intro", "# Intro"),
322 body.replace("Intro", "1. Item\ncontinuation"),
323 body.replace("Intro", "| Header |\n| --- |\n| Value |"),
324 ]) {
325 expect(splitSegments(code)).toEqual([
326 { id: "markdown:0", kind: "markdown", text: code, sourceOffset: 0 },
327 ]);
328 }
329 });
330
331 it("does not let a different fence marker close an open fence", () => {
332 const body = "```\n~~~\nhttps://example.com/demo.mp4\n```";
333 expect(split(body)).toEqual([
334 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
335 ]);
336 });
337
338 it("does not close a fence opened at the margin on a tab-indented marker", () => {
339 const code = "```\n\t```\nhttps://example.com/sample.mp4\n```";
340 expect(split(`${code}\n\nhttps://example.com/demo.mp4`)).toEqual([
341 { id: "markdown:0", kind: "markdown", text: code, sourceOffset: 0 },
342 {
343 id: "attachment:1",
344 kind: "attachment",
345 url: "https://example.com/demo.mp4",
346 media: "video",
347 },
348 ]);
349 const listCode = "- List\n\n\t```md\n https://example.com/sample.mp4\n\t```";
350 expect(split(`${listCode}\n\nhttps://example.com/demo.mp4`)).toEqual([
351 { id: "markdown:0", kind: "markdown", text: listCode, sourceOffset: 0 },
352 {
353 id: "attachment:1",
354 kind: "attachment",
355 url: "https://example.com/demo.mp4",
356 media: "video",
357 },
358 ]);
359 });
360
361 it("keeps a video tag that shares its line with prose as markdown", () => {
362 const body = 'Before <video src="https://example.com/a.mp4"></video> after';
363 expect(split(body)).toEqual([
364 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
365 ]);
366 const captioned = '<video src="https://example.com/a.mp4"></video> Before the fix\n\nIt opens.';
367 expect(split(`${captioned}\n\n<video src="https://example.com/b.mp4"></video>`)).toEqual([
368 { id: "markdown:0", kind: "markdown", text: captioned, sourceOffset: 0 },
369 { id: "attachment:1", kind: "attachment", url: "https://example.com/b.mp4", media: "video" },
370 ]);
371 });
372
373 it("treats an info-string fence as a nested opener, not a close", () => {
374 const body = "```\n```javascript\nhttps://example.com/demo.mp4\n```";
375 expect(split(body)).toEqual([
376 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
377 ]);
378 });
379
380 it("does not open a fence on a line of inline triple-backtick code", () => {
381 const code = "```\nhttps://example.com/b.png\n```";
382 expect(
383 split(`\`\`\`npm test\`\`\` passes.\n\nhttps://example.com/demo.mp4\n\n${code}`),
384 ).toEqual([
385 { id: "markdown:0", kind: "markdown", text: "```npm test``` passes.", sourceOffset: 0 },
386 {
387 id: "attachment:1",
388 kind: "attachment",
389 url: "https://example.com/demo.mp4",
390 media: "video",
391 },
392 { id: "markdown:2", kind: "markdown", text: code, sourceOffset: 54 },
393 ]);
394 const multilineSpan = "```foo`\nhttps://example.com/demo.mp4\nbar```";
395 expect(split(multilineSpan)).toEqual([
396 { id: "markdown:0", kind: "markdown", text: multilineSpan, sourceOffset: 0 },
397 ]);
398 });
399
400 it("leaves an indented code line alone even when it is only a video link", () => {
401 const body = " https://example.com/demo.mp4";
402 expect(split(body)).toEqual([
403 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
404 ]);
405 });
406
407 it("never lifts media out of an HTML comment, while lifting media after it", () => {
408 const visible = {
409 id: "attachment:1",
410 kind: "attachment",
411 url: "https://example.org/visible.mp4",
412 media: "video",
413 };
414 // A fence inside a comment is hidden too, so it must not open a code block.
415 const comment = [
416 "<!--",
417 "https://example.org/hidden.mp4",
418 '<video src="https://example.org/hidden-tag.mp4"></video>',
419 "```",
420 "-->",
421 ].join("\n");
422 for (const hidden of [comment, "<!-- template hint -->"]) {
423 expect(split(`${hidden}\n\nhttps://example.org/visible.mp4`)).toEqual([
424 { id: "markdown:0", kind: "markdown", text: hidden, sourceOffset: 0 },
425 visible,
426 ]);
427 }
428 });
429
430 it("leaves an unclosed video tag as prose without eating the rest of the body", () => {
431 const body = ['<video src="https://example.com/a.mp4">', "still prose", "more prose"].join(
432 "\n",
433 );
434 expect(split(body)).toEqual([
435 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
436 ]);
437 });
438
439 it.each([
440 ["a whitespace run inside a line", `a${" ".repeat(1_000_000)}b`],
441 ["a run of unclosed video tags", `${"<video ".repeat(150_000)}</video>`],
442 ["a run of backticks before a line separator", `${"`".repeat(100_000)}\u2028x`],
443 ])("splits %s in one pass", (_case, body) => {
444 expect(split(body)).toEqual([
445 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
446 ]);
447 });
448
449 it("refuses a non-http source rather than making a link out of it", () => {
450 const body = '<video src="javascript:alert(1)"></video>';
451 expect(split(body)).toEqual([
452 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
453 ]);
454 });
455});
456
457describe("extensionless pull request media", () => {
458 it.effect.each([
459 [206, "image/png", "image"],
460 [206, "video/mp4", "video"],
461 [200, "text/html", null],
462 [404, "image/png", null],
463 ] as const)("classifies HTTP %i with Content-Type %s", ([status, contentType, kind]) =>
464 Effect.gen(function* () {
465 const cancel = vi.fn();
466 const fetchMedia = vi.fn(
467 async () =>
468 new Response(new ReadableStream({ cancel }), {
469 status,
470 headers: { "content-type": contentType },
471 }),
472 );
473 const url = "https://environment.test/api/assets/signed/upload";
474 const registry = AtomRegistry.make();
475 yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
476 const atom = makePullRequestMediaKindAtom(fetchMedia)(url);
477 expect(yield* AtomRegistry.getResult(registry, atom)).toBe(kind);
478 expect(fetchMedia).toHaveBeenCalledWith(
479 url,
480 expect.objectContaining({
481 headers: { Range: "bytes=0-0" },
482 }),
483 );
484 expect(cancel).toHaveBeenCalledOnce();
485 }),
486 );
487});
488
489describe("reference links around lifted media", () => {
490 const recording =
491 "https://github.com/user-attachments/assets/2f8c1a90-1b2c-4d5e-8f90-abcdef123456";
492 const parser = unified().use(remarkParse).use(remarkGfm);
493 const prose = (segments: ReadonlyArray<PullRequestBodySegment>): string[] =>
494 segments.flatMap((segment) =>
495 segment.kind === "markdown"
496 ? [segment.text]
497 : segment.kind === "table"
498 ? segment.rows.flat().flatMap((cell) => prose(cell.segments))
499 : [],
500 );
501 // Each segment renders as its own document; the first definition of a label wins, as in mdast-util-to-hast.
502 const referenceLinks = (body: string) =>
503 prose(split(body)).flatMap((text) => {
504 const definitions = new Map<string, string>();
505 const references: Array<{ identifier: string; text: string }> = [];
506 const visit = (node: Root | RootContent) => {
507 if (node.type === "definition" && !definitions.has(node.identifier)) {
508 definitions.set(node.identifier, node.url);
509 }
510 if (node.type === "linkReference") {
511 references.push({
512 identifier: node.identifier,
513 text: node.children.map((child) => ("value" in child ? child.value : "")).join(""),
514 });
515 }
516 if ("children" in node) node.children.forEach(visit);
517 };
518 visit(parser.parse(text));
519 return references.map((reference) => [reference.text, definitions.get(reference.identifier)]);
520 });
521
522 it.each([
523 [
524 "use, then media, then definition",
525 `See [the docs][guide].\n\n${recording}\n\n[guide]: https://example.com/docs`,
526 ],
527 [
528 "definition, then media, then use",
529 `[guide]: https://example.com/docs\n\n${recording}\n\nSee [the docs][guide].`,
530 ],
531 ...["\n", "\r\n", "\r"].map((lineEnding) => [
532 `a definition wrapped over quoted lines with ${JSON.stringify(lineEnding)}`,
533 `> [guide]:${lineEnding}> https://example.com/docs${lineEnding}> "The guide"\n\n${recording}\n\nSee [the docs][guide].`,
534 ]),
535 [
536 "a use inside a media table cell",
537 `<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`,
538 ],
539 ])("resolves a reference defined across a video: %s", (_case, body) => {
540 expect(referenceLinks(body)).toEqual([["the docs", "https://example.com/docs"]]);
541 });
542
543 it("keeps the body's first definition of a label, wherever the media falls", () => {
544 expect(
545 referenceLinks(
546 `[guide]: https://example.com/first\n\n${recording}\n\nSee [the docs][guide].\n\n[GUIDE]: https://example.com/second`,
547 ),
548 ).toEqual([["the docs", "https://example.com/first"]]);
549 });
550
551 it("renders the body whole when its definitions would be repeated past the budget", () => {
552 const definitions = Array.from(
553 { length: 400 },
554 (_, index) => `[d${index}]: https://example.com/${"x".repeat(60)}${index}`,
555 ).join("\n");
556 const uses = Array.from({ length: 1200 }, () => `[use][d1]\n${recording}`).join("\n");
557 const body = `\n${definitions}\n\n${uses}\n`;
558 expect(split(body)).toEqual([
559 { id: "markdown:0", kind: "markdown", text: body.trim(), sourceOffset: 1 },
560 ]);
561 });
562
563 it("leaves a definition shown in code as code", () => {
564 expect(
565 referenceLinks(
566 `\`\`\`md\n[guide]: https://example.com/docs\n\`\`\`\n\n${recording}\n\nSee [the docs][guide].`,
567 ),
568 ).toEqual([]);
569 });
570
571 it("still writes a task tick back to its place in the body", () => {
572 const body = `[guide]: https://example.com/docs\n\n${recording}\n\n- [ ] Read [the docs][guide]`;
573 const segment = split(body).at(-1)!;
574 if (segment.kind !== "markdown") throw new Error("expected prose last");
575 const marker = segment.text.indexOf("[ ]");
576 expect(body.slice(segment.sourceOffset + marker)).toBe("[ ] Read [the docs][guide]");
577 });
578
579 it.each([
580 ["\uFEFF", "", 0],
581 ["intro\n\n\uFEFF", "intro\n\n\uFEFF", 0],
582 [`${recording}\n\n\uFEFF`, "\uFEFF", 1],
583 ])("preserves BOM meaning and task offsets after prefix %j", (prefix, kept, pick) => {
584 const definition = "[guide]: https://example.com/docs";
585 const task = "- [ ] Read [guide]";
586 const body = `${prefix}${task}\n\n${recording}\n\n${definition}`;
587 const segment = splitPullRequestBody(body, () => [definition])[pick]!;
588 if (segment.kind !== "markdown") throw new Error("expected prose");
589 expect(segment.text).toBe(`${definition}\n\n${kept}${task}`);
590 expect(segment.sourceOffset + segment.text.indexOf("[ ]")).toBe(body.indexOf("[ ]"));
591 });
592});
593
594describe("media on custom hosts", () => {
595 it.each([
596 [
597 "https://drop.example.com/capture.PNG?token=abc#preview",
598 "https://drop.example.com/capture.PNG?token=abc#preview",
599 "image",
600 undefined,
601 ],
602 [
603 "[Recording](https://drop.example.com/recording.mov)",
604 "https://drop.example.com/recording.mov",
605 "video",
606 "Recording",
607 ],
608 ["[Demo](https://example.com/demo(1).mp4)", "https://example.com/demo(1).mp4", "video", "Demo"],
609 [
610 "[Demo [v2]](https://example.com/demo.mp4)",
611 "https://example.com/demo.mp4",
612 "video",
613 "Demo [v2]",
614 ],
615 ["[`[`](https://example.com/demo.mp4)", "https://example.com/demo.mp4", "video", "`[`"],
616 [
617 "[Demo](https://example.com/demo\\(1\\).mp4)",
618 "https://example.com/demo(1).mp4",
619 "video",
620 "Demo",
621 ],
622 [
623 "[Demo](https://example.com/demo(1).mp4?a=1\\&b=2)",
624 "https://example.com/demo(1).mp4?a=1&b=2",
625 "video",
626 "Demo",
627 ],
628 [
629 "[Screenshot](https://drop.example.com/shot.webp)",
630 "https://drop.example.com/shot.webp",
631 "image",
632 "Screenshot",
633 ],
634 [
635 "<https://drop.example.com/shot.webp>",
636 "https://drop.example.com/shot.webp",
637 "image",
638 undefined,
639 ],
640 ])("recognizes %s without a request and preserves its label", (body, url, media, label) => {
641 const segments = split(body);
642 expect(segments).toEqual([expect.objectContaining({ kind: "attachment", url, media })]);
643 const [segment] = segments;
644 expect(segment?.kind === "attachment" ? segment.label : null).toBe(label);
645 });
646
647 it.each([
648 "[Open report](https://example.com/report?file=demo.mp4)",
649 "https://example.com/report#demo.png",
650 "[Demo](https://example.com/demo(1).mp4) trailing",
651 "[Demo](https://example.com/demo(1.mp4)",
652 "[Demo](https://example.com/demo(1).mp4?a=1&b=2)",
653 ])("keeps %s a link when not a standalone media link", (body) => {
654 expect(split(body)).toEqual([
655 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
656 ]);
657 });
658
659 it("keeps inline links and media examples in code as prose", () => {
660 const body =
661 "See [recording](https://drop.example.com/a.mp4) for context.\n\n```md\nhttps://drop.example.com/a.png\n```";
662 expect(split(body)).toEqual([
663 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
664 ]);
665 });
666});
667
668describe("media tables", () => {
669 const before = "https://github.com/user-attachments/assets/c69c7c1c-ef2f-47dd-97e8-fe42e40712eb";
670 const after = "https://github.com/user-attachments/assets/1867b6ec-4f88-4248-b2df-6b0f9808105b";
671 const video = "https://example.com/a.mp4";
672
673 it("keeps GitHub's before/after video table together, splitting each cell on its own", () => {
674 const segments = split(
675 `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`,
676 );
677 expect(segments.map((segment) => segment.kind)).toEqual(["markdown", "table", "markdown"]);
678 expect(segments[0]).toMatchObject({ text: "Intro" });
679 expect(segments[2]).toMatchObject({ text: "Outro" });
680 const table = segments[1]!;
681 if (table.kind !== "table") throw new Error("expected a table segment");
682 expect(
683 table.rows.map((row) =>
684 row.map((cell) =>
685 cell.segments.map((segment) =>
686 segment.kind === "attachment" ? `attachment:${segment.url}` : segment,
687 ),
688 ),
689 ),
690 ).toEqual([
691 [
692 [{ id: "markdown:0", kind: "markdown", text: "Before", sourceOffset: 23 }],
693 [{ id: "markdown:0", kind: "markdown", text: "After", sourceOffset: 38 }],
694 ],
695 [[`attachment:${before}`], [`attachment:${after}`]],
696 ]);
697 });
698
699 it("keeps a quoted `>` inside a cell's attributes out of its text", () => {
700 const [table] = split(
701 `<table>\n<tr><td title="Before > after">Caption</td><td>\n\n${video}\n\n</td></tr>\n</table>`,
702 );
703 expect(table).toMatchObject({
704 kind: "table",
705 rows: [[{ segments: [{ kind: "markdown", text: "Caption" }] }, {}]],
706 });
707 });
708
709 it("leaves a table without media links as markdown", () => {
710 const body = "<table>\n<tr><td>a</td><td>b</td></tr>\n</table>";
711 expect(split(body)).toEqual([
712 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
713 ]);
714 });
715
716 it.each([
717 ["a caption", "<table>\n<caption>Before upgrading</caption>\n<tr><td>", "</td></tr>\n</table>"],
718 ["text outside cells", "<table>\nBefore upgrading\n<tr><td>", "</td></tr>\n</table>"],
719 [
720 "text inside a row but outside cells",
721 "<table>\n<tr>Before upgrading<td>",
722 "</td></tr>\n</table>",
723 ],
724 [
725 "a table nested in another",
726 "<table>\n<tr><td>\n<table>\n<tr><td>",
727 "</td></tr>\n</table>\n</td></tr>\n</table>",
728 ],
729 ["an unclosed table", "<table>\n<tr><td>", ""],
730 ["a spanning cell", '<table>\n<tr><td colspan="2">', "</td></tr>\n</table>"],
731 [
732 "an indented cell",
733 "<table>\n <tr>\n <th>\n Before\n </th>\n </tr>\n <tr><td>",
734 "</td></tr>\n</table>",
735 ],
736 [
737 "a cell indented by a space and a tab",
738 "<table>\n<tr><td>\n \tBefore\n</td><td>",
739 "</td></tr>\n</table>",
740 ],
741 ])("splits a media table with %s line by line, as before", (_name, open, close) => {
742 const body = `${open}\n\n${video}\n\n${close}`;
743 expect(split(body)).toEqual([
744 { id: "markdown:0", kind: "markdown", text: open, sourceOffset: 0 },
745 { id: "attachment:1", kind: "attachment", url: video, media: "video" },
746 ...(close
747 ? [
748 {
749 id: "markdown:2",
750 kind: "markdown",
751 text: close,
752 sourceOffset: body.length - close.length,
753 },
754 ]
755 : []),
756 ]);
757 });
758});
759
760describe("change request reference autolinks", () => {
761 const urls = (provider: string, url: string, text: string) =>
762 changeRequestReferenceAutolinker({ provider, url })?.(text).map((link) => link.url) ?? null;
763
764 it("links references against the change request's own repository", () => {
765 expect(urls("github", "https://ghe.example.com/acme/web/pull/7", "Fixes #5")).toEqual([
766 "https://ghe.example.com/acme/web/issues/5",
767 ]);
768 });
769
770 // regression: the mobile review guide linked every host's `#5` with GitHub's grammar
771 it("links nothing on a host whose grammar is not applied", () => {
772 expect(urls("forgejo", "https://codeberg.org/acme/web/pulls/7", "#5")).toBeNull();
773 });
774});
775
776describe("change request media urls", () => {
777 // regression: GitCafe's `/api/attachments/<id>` uploads rendered as missing local files
778 it.each([
779 ["/api/attachments/attach_1", "https://git.cafe/api/attachments/attach_1"],
780 ["//cdn.example.com/a.png", "//cdn.example.com/a.png"],
781 ["/\\evil.example.com/a.png", "/\\evil.example.com/a.png"],
782 ["https://example.com/a.png", "https://example.com/a.png"],
783 ["docs/a.png", "docs/a.png"],
784 ])("resolves %s against the forge", (url, expected) => {
785 expect(resolveChangeRequestMediaUrl(url, "https://git.cafe/pingdotgg/t3code/pulls/31251")).toBe(
786 expected,
787 );
788 });
789});