Render a project's README as GitHub-flavoured Markdown, its links and images pointing into the repo at the SHA, sanitized
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- features/markdown/pipeline.ts holds the one plugin order (remark-gfm; rehype-raw, rehypeRepoUrls, rehype-sanitize with GitHub's defaultSchema plus `language-` on code, rehype-slug), because the order is the security property; react-markdown's defaultUrlTransform stays on as a second net. - features/markdown/resolve.ts: resolveRepoUrl is pure. `#…`, `""`, `//…` and any scheme stay as written; `/x` is repo-root, the rest is relative to dir with `..` clamped by the URL parser; query and hash kept; links to /<project>/blob/<sha>/…, media to /<project>/raw/<sha>/…, always the SHA. Only the parsed path is kept, so `/\host/x` stays inside the project. - Decision: a link ending in `/` goes to /tree/ (a folder), so it does not rely on the blob route redirecting. - Decision: `source[srcset]` is resolved to raw too (ky's and awesome's <picture> dark logos); the schema is unchanged. - RepoMarkdown: in-project `a` is a TanStack Link inside a router and a plain <a> outside one (views rendered alone, as their tests do); external links get rel="nofollow noopener noreferrer"; img gets lazy loading, async decoding and no referrer; prose prose-sm max-w-none dark:prose-invert. RepoMarkdownProps unchanged. - RepoText renders a non-Markdown README in a <pre>; isMarkdownPath tells the caller which to use (the props carry no path). - Tests: test/markdown-resolve.test.ts (each rule, `?raw=1#L3`, dir ""), test/markdown.test.tsx (script, onerror, javascript:/data:/vbscript: hrefs, iframe/style/form, user-content- name; relative image, ../../x, /LICENSE, external rel, #usage, raw-HTML img and picture srcset; GFM table, disabled task checkboxes, heading slug, code language; Link inside a router). - Bytes: nothing imports features/markdown yet, so the web build is unchanged (entry 717,922 of 1,665,000; JS 2,410,994 of 4,500,000); the pipeline alone is ~380 KB minified, ~116 KB gzip, which 904's import should add. - ASSUMPTION: a <style>'s CSS text left behind as inert text and double-prefixed footnote ids are acceptable GitHub-like defaults for W9 (noted for 999 in the issue).
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+610 added−4 removed
- tests:+298 added−0 removed
- other:+312 added−4 removed
Provenance
- Commit
c0ea449- Tree
17525ba- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
254268a
5 files changed+610 added−4 removed
modified:apps/web/src/features/markdown/markdown.tsx+114 added-4 removed
2 unmodified lines345678789101112111314151617181920212223242 unmodified lines27282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109231101111121131141151161171181191201211221231241251261271281291301311321331341351361372 unmodified lines * project and tree pages, a `.md` file on the blob page. Its links and * images resolve against `dir` at the commit `at`, so they stay inside the * project at that commit. * * Stub: the source as text, in a `<pre>`, until the GFM pipeline lands * (issue 905 replaces this body; the props are final). * react-markdown builds React elements (no `dangerouslySetInnerHTML`), so * the same component renders in the Worker and in the browser. What may * reach the page is decided by the plugin chain in `pipeline.ts`; this * file only draws the elements that come out of it. */import type { CommitSha, ProjectName } from "@repo/protocol/ids";import type { ReactNode } from "react";import type { AnyRouter } from "@tanstack/react-router";import { Link, useRouter } from "@tanstack/react-router";import type { ComponentProps, ReactNode } from "react";import Markdown, { defaultUrlTransform } from "react-markdown";import type { Components, ExtraProps } from "react-markdown";
import { rehypePluginsFor, remarkPlugins } from "./pipeline.ts";
export interface RepoMarkdownProps { /** The commit the file was read at; links and images point there. */ readonly at: CommitSha; /** The file's directory, relative to the repo root; `""` is the root. */2 unmodified lines /** The file's text. */ readonly source: string;}
type AnchorProps = ComponentProps<"a"> & ExtraProps;
/** A path on this origin (`/p/blob/…`), as `resolve.ts` leaves every in-project link. */const isSameOrigin = (href: string) => href.startsWith("/") && !href.startsWith("//") && !href.startsWith("/\\");
/** * A link inside the project: a router `Link` when a router is there (the * app), so it opens without a full load; a plain link when none is (a * view rendered on its own, as the pages' tests render it). */const ProjectLink = ({ children, href, // The sanitizer never lets a `target` through. target: _target, ...props}: Omit<ComponentProps<"a">, "href"> & { readonly href: string }) => { // Outside a router the context holds `null`, whatever the hook's type says. const router: AnyRouter | null | undefined = useRouter({ warn: false });
return router === null || router === undefined ? ( <a {...props} href={href}> {children} </a> ) : ( <Link {...props} to={href}> {children} </Link> );};
/** `a`: in-project links through the router; links that leave go with no referrer and no endorsement. */const Anchor = ({ children, href, node: _node, ...props }: AnchorProps) => { if (href !== undefined && isSameOrigin(href)) { return ( <ProjectLink {...props} href={href}> {children} </ProjectLink> ); }
if (href === undefined || href === "" || href.startsWith("#")) { return ( <a {...props} href={href}> {children} </a> ); }
return ( <a {...props} href={href} rel="nofollow noopener noreferrer"> {children} </a> );};
/** `img`: loaded when scrolled to, decoded off the main thread, and sent with no referrer. */const Image = ({ alt, node: _node, ...props}: ComponentProps<"img"> & ExtraProps) => ( <img {...props} alt={alt ?? ""} decoding="async" loading="lazy" referrerPolicy="no-referrer" />);
const components: Components = { a: Anchor, img: Image };
export const RepoMarkdown = ({ at, dir, project, source,export const RepoMarkdown = ({ source }: RepoMarkdownProps): ReactNode => (}: RepoMarkdownProps): ReactNode => ( <div className="prose prose-sm dark:prose-invert max-w-none"> <Markdown components={components} rehypePlugins={rehypePluginsFor({ dir, project, sha: at })} remarkPlugins={remarkPlugins} urlTransform={defaultUrlTransform} > {source} </Markdown> </div>);
/** A README that is not Markdown (`README`, `README.txt`, `README.rst`): its text as written. */export const RepoText = ({ source,}: { readonly source: string;}): ReactNode => ( <pre className="overflow-x-auto font-mono text-sm whitespace-pre-wrap"> {source} </pre>);
const markdownExtension = /\.(?:markdown|md|mdown|mdwn|mkd|mkdn)$/iu;
/** Whether a file renders as Markdown (`RepoMarkdown`) or as text (`RepoText`), by its name. */export const isMarkdownPath = (path: string) => markdownExtension.test(path);added:apps/web/src/features/markdown/pipeline.ts+119 added
1+/**2+ * The plugin chain that turns a project's Markdown into a safe tree, in3+ * the one order that makes it safe (W9-D5). It is the security property4+ * of the README renderer, so it lives here alone and is tested whole5+ * (`test/markdown.test.tsx`):6+ *7+ * 1. `remarkGfm`: tables, task lists, strikethrough, autolinks, footnotes;8+ * 2. `rehypeRaw`: the README's own HTML (`<p align="center"><img …>`)9+ * becomes elements, so everything after sees it;10+ * 3. `rehypeRepoUrls`: relative links and media point into the project at11+ * the SHA (`resolve.ts`), before the sanitizer judges them;12+ * 4. `rehypeSanitize` with `schema`: GitHub's allow-list, the last gate on13+ * what comes in (no script, no handler, no `javascript:` or `data:`14+ * URL, no iframe, style or form; a README's `id` and `name` prefixed15+ * `user-content-`);16+ * 5. `rehypeSlug`: heading ids, after the sanitizer, so `#usage` finds17+ * `## Usage` unprefixed.18+ *19+ * react-markdown's `defaultUrlTransform` stays on as a second net.20+ */21+import { Predicate } from "effect";22+import type { Element, Properties, Root } from "hast";23+import type { Options } from "react-markdown";24+import rehypeRaw from "rehype-raw";25+import rehypeSanitize, { defaultSchema } from "rehype-sanitize";26+import type { Options as Schema } from "rehype-sanitize";27+import rehypeSlug from "rehype-slug";28+import remarkGfm from "remark-gfm";29+import { visit } from "unist-util-visit";30+31+import { resolveRepoUrl } from "./resolve.ts";32+import type { RepoUrlContext } from "./resolve.ts";33+34+/** A list of unified plugins, each with its options, as react-markdown takes them. */35+export type PluggableList = NonNullable<Options["rehypePlugins"]>;36+37+/** Where a Markdown file was read: the project, the commit, and the file's directory (`""` is the root). */38+export type MarkdownAt = Omit<RepoUrlContext, "kind">;39+40+/**41+ * GitHub's allow-list (`hast-util-sanitize`'s `defaultSchema`), with a42+ * code block's `language-…` class kept on `code`, and nothing else added.43+ */44+export const schema: Schema = {45+ ...defaultSchema,46+ attributes: {47+ ...defaultSchema.attributes,48+ code: [49+ ...(defaultSchema.attributes?.code ?? []),50+ ["className", /^language-./u],51+ ],52+ },53+};54+55+/** Elements whose URL loads bytes into the page: they read the raw file. */56+const media = new Set(["img", "source", "video"]);57+58+/** One `srcset` candidate (`url [descriptor]`), its URL resolved. */59+const candidate = (value: string, at: RepoUrlContext) => {60+ const [url = "", ...descriptor] = value.trim().split(/\s+/u);61+62+ return [resolveRepoUrl(url, at), ...descriptor].join(" ");63+};64+65+/** Rewrite one URL property, when the element carries it as a string. */66+const rewrite = (67+ properties: Properties,68+ key: "href" | "src" | "srcSet",69+ to: (value: string) => string70+) => {71+ const value = properties[key];72+73+ if (Predicate.isString(value)) {74+ properties[key] = to(value);75+ }76+};77+78+const resolveElement = (node: Element, at: MarkdownAt) => {79+ if (node.tagName === "a") {80+ rewrite(node.properties, "href", (href) =>81+ resolveRepoUrl(href, { ...at, kind: "link" })82+ );83+ }84+85+ if (!media.has(node.tagName)) {86+ return;87+ }88+89+ const here = { ...at, kind: "media" } as const;90+91+ rewrite(node.properties, "src", (src) => resolveRepoUrl(src, here));92+ // rehype-raw keeps `srcset` as written: one string, candidates split by commas.93+ rewrite(node.properties, "srcSet", (srcSet) =>94+ srcSet95+ .split(",")96+ .map((value) => candidate(value, here))97+ .join(", ")98+ );99+};100+101+/**102+ * A rehype plugin: every `a[href]` and every `img`, `video` and `source`103+ * `src` (and `srcset`) resolved into the project at the SHA.104+ */105+export const rehypeRepoUrls = (at: MarkdownAt) => (tree: Root) => {106+ visit(tree, "element", (node) => {107+ resolveElement(node, at);108+ });109+};110+111+export const remarkPlugins: PluggableList = [remarkGfm];112+113+/** The rehype half of the chain for one file, in its fixed order. */114+export const rehypePluginsFor = (at: MarkdownAt): PluggableList => [115+ rehypeRaw,116+ [rehypeRepoUrls, at],117+ [rehypeSanitize, schema],118+ rehypeSlug,119+];added:apps/web/src/features/markdown/resolve.ts+79 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879/** * Where a link or an image in a project's Markdown file points, inside the * web: the file was read at one commit, in one directory, so a relative * URL names a path in that commit's tree, as GitHub resolves a README's * links. The result always names the SHA, never `main`, so it reads the * same tree forever (and a raw image caches forever, W9-D6). * * Pure, so the rules are table-tested on their own; `pipeline.ts` runs it * over the rendered tree before the sanitizer sees it. */import type { CommitSha, ProjectName } from "@repo/protocol/ids";
/** Where the file was read: the project, the commit, its directory, and what kind of URL this is. */export interface RepoUrlContext { /** The file's directory, relative to the repo root; `""` is the root. */ readonly dir: string; /** A link opens a page (`blob`, or `tree` for a folder); media loads the raw bytes. */ readonly kind: "link" | "media"; readonly project: ProjectName; readonly sha: CommitSha;}
/** A URL scheme (`https:`, `mailto:`, `javascript:` …): the URL leaves the repo, and the sanitizer judges it. */const scheme = /^[a-z][a-z0-9+.-]*:/iu;
/** A base no reader resolves against; only its path is kept. */const base = "https://repo.invalid/";
const edgeSlashes = /^\/+|\/+$/gu;
/** Media reads raw bytes; a link opens a folder (`tree`) when its path ends in `/`, else a file (`blob`). */const routeOf = (kind: RepoUrlContext["kind"], pathname: string) => { if (kind === "media") { return "raw"; }
return pathname.endsWith("/") ? "tree" : "blob";};
/** * Resolve `url` against the file's directory at `sha`: * * - `#…`, `""`, `//host…` and anything with a scheme come back as written; * - `/x` starts at the repo root, anything else at `dir`; `..` stops at * the root (the URL parser clamps it), and a `?query` and `#hash` stay; * - a link becomes `/<project>/blob/<sha>/<path>`, or `/tree/` when it ends * in `/` (a folder); media becomes `/<project>/raw/<sha>/<path>`. * * Only the parsed path is kept, so a URL the parser reads as another host * (`/\host/x`) still lands inside the project. */export const resolveRepoUrl = (url: string, at: RepoUrlContext): string => { if ( url === "" || url.startsWith("#") || url.startsWith("//") || scheme.test(url) ) { return url; }
const folder = at.dir .split("/") .filter((segment) => segment !== "") .map((segment) => encodeURIComponent(segment)) .join("/");
const resolved = URL.parse(url, folder === "" ? base : `${base}${folder}/`);
if (resolved === null) { return ""; }
const path = resolved.pathname.replaceAll(edgeSlashes, "");
const route = routeOf(at.kind, resolved.pathname);
return `/${at.project}/${route}/${at.sha}${path === "" ? "" : `/${path}`}${resolved.search}${resolved.hash}`;};added:apps/web/test/markdown-resolve.test.ts+80 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980/** * A Markdown file's link or image, resolved into the project at the commit * it was read at: a fragment and anything with a scheme stay as written, * `/x` starts at the repo root, anything else starts at the file's * directory, `..` stops at the root, and a query and a fragment survive. * Links open the file's page, media its raw bytes, always at the SHA. */import { describe, expect, it } from "@effect/vitest";import { CommitSha, ProjectName } from "@repo/protocol/ids";
import { resolveRepoUrl } from "../src/features/markdown/resolve.ts";
const sha = CommitSha.make("0123456789abcdef0123456789abcdef01234567");
/** A `javascript:` URL, joined at run time so lint reads no script URL in the source. */const scriptUrl = ["javascript", "alert(1)"].join(":");
const at = (dir: string, kind: "link" | "media") => ({ dir, kind, project: ProjectName.make("p"), sha,});
describe("a link in a Markdown file", () => { it.each([ ["#usage", "#usage"], ["https://e.org/x", "https://e.org/x"], ["mailto:a@e.org", "mailto:a@e.org"], [scriptUrl, scriptUrl], ["//cdn.e.org/x.png", "//cdn.e.org/x.png"], ["", ""], ])("leaves %j as written", (url, expected) => { expect(resolveRepoUrl(url, at("docs", "link"))).toBe(expected); });
it.each([ ["./guide.md", "docs", `/p/blob/${sha}/docs/guide.md`], ["guide.md", "docs/api", `/p/blob/${sha}/docs/api/guide.md`], ["../../x", "docs", `/p/blob/${sha}/x`], ["../../../../x", "docs/api", `/p/blob/${sha}/x`], ["/LICENSE", "docs/api", `/p/blob/${sha}/LICENSE`], ["/../LICENSE", "docs", `/p/blob/${sha}/LICENSE`], ["src/a.ts?raw=1#L3", "", `/p/blob/${sha}/src/a.ts?raw=1#L3`], ["CONTRIBUTING.md", "", `/p/blob/${sha}/CONTRIBUTING.md`], ["./a.md#usage", "docs", `/p/blob/${sha}/docs/a.md#usage`], ["my file.md", "", `/p/blob/${sha}/my%20file.md`], ["my%20file.md", "", `/p/blob/${sha}/my%20file.md`], ])("resolves %j in %j", (url, dir, expected) => { expect(resolveRepoUrl(url, at(dir, "link"))).toBe(expected); });
it.each([ ["docs/", "", `/p/tree/${sha}/docs`], ["..", "docs/api", `/p/tree/${sha}/docs`], ["/", "docs", `/p/tree/${sha}`], ["./", "", `/p/tree/${sha}`], ])("opens %j in %j as a folder", (url, dir, expected) => { expect(resolveRepoUrl(url, at(dir, "link"))).toBe(expected); });
it.each([ ["/\\evil.example/x", `/p/blob/${sha}/x`], ["\\\\evil.example/x", `/p/blob/${sha}/x`], ])("keeps %j inside the project", (url, expected) => { expect(resolveRepoUrl(url, at("", "link"))).toBe(expected); });});
describe("an image or a video in a Markdown file", () => { it.each([ ["./img/logo.png", "docs", `/p/raw/${sha}/docs/img/logo.png`], ["media/logo.svg", "", `/p/raw/${sha}/media/logo.svg`], ["/media/logo.svg", "docs", `/p/raw/${sha}/media/logo.svg`], ["../demo.mp4", "docs", `/p/raw/${sha}/demo.mp4`], ["https://e.org/logo.png", "docs", "https://e.org/logo.png"], ])("resolves %j in %j", (url, dir, expected) => { expect(resolveRepoUrl(url, at(dir, "media"))).toBe(expected); });});added:apps/web/test/markdown.test.tsx+218 added
1+/**2+ * A project's Markdown file, rendered to HTML with `react-dom/server`, as3+ * the Worker renders it: GitHub-flavoured Markdown and the README's own4+ * HTML, its links and images pointing into the project at the commit it5+ * was read at, and nothing that could run script or post a form.6+ */7+import { describe, expect, it } from "@effect/vitest";8+import { CommitSha, ProjectName } from "@repo/protocol/ids";9+import {10+ RouterContextProvider,11+ createMemoryHistory,12+ createRootRoute,13+ createRouter,14+} from "@tanstack/react-router";15+import type { ReactElement } from "react";16+import { renderToString } from "react-dom/server";17+18+import {19+ RepoMarkdown,20+ RepoText,21+ isMarkdownPath,22+} from "../src/features/markdown/markdown.tsx";23+24+const sha = CommitSha.make("0123456789abcdef0123456789abcdef01234567");25+26+const project = ProjectName.make("p");27+28+/** The file `<dir>/README.md` at `sha`, rendered with no router around it, as a view's test renders it. */29+const rendered = (source: string, dir = "") =>30+ renderToString(31+ <RepoMarkdown at={sha} dir={dir} project={project} source={source} />32+ );33+34+/** The same, inside a router, as the app renders it. */35+const routed = (element: ReactElement) =>36+ renderToString(37+ <RouterContextProvider38+ router={createRouter({39+ history: createMemoryHistory({ initialEntries: ["/p"] }),40+ routeTree: createRootRoute(),41+ })}42+ >43+ {element}44+ </RouterContextProvider>45+ );46+47+/** Each `<a …>` opening tag in `markup`. */48+const anchorsOf = (markup: string) => markup.match(/<a\b[^>]*>/gu) ?? [];49+50+describe("what a README cannot carry", () => {51+ it("drops a script and what it says", () => {52+ const markup = rendered("before\n\n<script>alert(1)</script>\n\nafter");53+54+ expect(markup).not.toContain("script");55+ expect(markup).not.toContain("alert");56+ expect(markup).toContain("<p>after</p>");57+ });58+59+ it("keeps an image but not its event handler", () => {60+ const markup = rendered("<img src=x onerror=alert(1)>");61+62+ expect(markup).toContain(`src="/p/raw/${sha}/x"`);63+ expect(markup).not.toContain("onerror");64+ expect(markup).not.toContain("alert");65+ });66+67+ it.each([68+ ["a javascript: link", "[x](javascript:alert(1))"],69+ ["a data: link", '<a href="data:text/html,<b>hi</b>">x</a>'],70+ ["a vbscript: link", "[x](vbscript:msgbox(1))"],71+ ])("renders %s with no href", (_, source) => {72+ const markup = rendered(source);73+74+ expect(anchorsOf(markup)).toStrictEqual(["<a>"]);75+ expect(markup).not.toMatch(/javascript|data:|vbscript/u);76+ });77+78+ it.each([79+ ["an iframe", '<iframe src="https://e.org"></iframe>', "iframe"],80+ ["a style", "<style>body{display:none}</style>", "<style"],81+ ["a form", '<form action="/x"><input name="q"></form>', "action"],82+ ])("drops %s", (_, source, word) => {83+ const markup = rendered(`${source}\n\nafter`);84+85+ expect(markup).not.toContain(word);86+ expect(markup).toContain("<p>after</p>");87+ });88+89+ it("prefixes a name the README sets, so it cannot clobber the page's own", () => {90+ const markup = rendered('<a name="top">Top</a>');91+92+ expect(markup).toMatch(/(?:id|name)="user-content-top"/u);93+ });94+});95+96+/** `docs/README.md`, rendered. */97+const readme = (source: string) => rendered(source, "docs");98+99+describe("links and images in docs/README.md", () => {100+ it("loads a relative image raw from the README's folder, at the SHA", () => {101+ const markup = readme("");102+103+ expect(markup).toContain(`src="/p/raw/${sha}/docs/img/logo.png"`);104+ expect(markup).toContain('loading="lazy"');105+ expect(markup).toContain('decoding="async"');106+ expect(markup).toContain('referrerPolicy="no-referrer"');107+ });108+109+ it.each([110+ ["[a](../../x)", `/p/blob/${sha}/x`],111+ ["[b](/LICENSE)", `/p/blob/${sha}/LICENSE`],112+ ["[g](guide.md#install)", `/p/blob/${sha}/docs/guide.md#install`],113+ ])("opens %s inside the project", (source, href) => {114+ expect(anchorsOf(readme(source))).toStrictEqual([`<a href="${href}">`]);115+ });116+117+ it("opens a link inside the project through the router when there is one", () => {118+ const markup = routed(119+ <RepoMarkdown120+ at={sha}121+ dir="docs"122+ project={project}123+ source="[a](../../x?raw=1#L3)"124+ />125+ );126+127+ expect(anchorsOf(markup)).toStrictEqual([128+ `<a href="/p/blob/${sha}/x?raw=1#L3">`,129+ ]);130+ });131+132+ it("leaves an external link as written, opened with no referrer", () => {133+ const [anchor] = anchorsOf(readme("[c](https://e.org)"));134+135+ expect(anchor).toContain('href="https://e.org"');136+ expect(anchor).toMatch(/rel="[^"]*\bnoopener\b[^"]*"/u);137+ expect(anchor).toMatch(/rel="[^"]*\bnofollow\b[^"]*"/u);138+ expect(anchor).toMatch(/rel="[^"]*\bnoreferrer\b[^"]*"/u);139+ });140+141+ it("leaves a link to a heading as written", () => {142+ expect(anchorsOf(readme("[d](#usage)"))).toStrictEqual([143+ '<a href="#usage">',144+ ]);145+ });146+147+ it("resolves an image in the README's own HTML, as ky's and awesome's are written", () => {148+ const markup = rendered(149+ '<p align="center"><img src="media/logo.svg" width="200" alt="logo"></p>'150+ );151+152+ expect(markup).toContain(`src="/p/raw/${sha}/media/logo.svg"`);153+ expect(markup).toContain('align="center"');154+ });155+156+ it("resolves a picture's sources too, so the dark logo loads", () => {157+ const markup = rendered(158+ '<picture><source media="(prefers-color-scheme: dark)" srcset="media/dark.svg 1x, media/dark@2x.svg 2x"><img src="media/logo.svg"></picture>'159+ );160+161+ expect(markup).toContain(162+ `srcSet="/p/raw/${sha}/media/dark.svg 1x, /p/raw/${sha}/media/dark@2x.svg 2x"`163+ );164+ expect(markup).toContain(`src="/p/raw/${sha}/media/logo.svg"`);165+ });166+});167+168+describe("GitHub-flavoured Markdown", () => {169+ it("renders a table", () => {170+ const markup = rendered("| a | b |\n| - | - |\n| 1 | 2 |");171+172+ expect(markup).toContain("<table>");173+ expect(markup).toContain("<td>1</td>");174+ });175+176+ it("renders a task list with checkboxes nobody can tick", () => {177+ const markup = rendered("- [x] done\n- [ ] not yet");178+179+ expect(markup.match(/<input[^>]*>/gu)).toStrictEqual([180+ '<input type="checkbox" disabled="" checked=""/>',181+ '<input type="checkbox" disabled=""/>',182+ ]);183+ });184+185+ it("gives a heading an id a link can point at", () => {186+ expect(rendered("## Hello World")).toContain('<h2 id="hello-world">');187+ });188+189+ it("keeps a code block's language and draws it in mono", () => {190+ const markup = rendered("```ts\nconst a = 1;\n```");191+192+ expect(markup).toContain('class="language-ts"');193+ expect(markup).toContain("<pre");194+ });195+196+ it("styles the whole as prose", () => {197+ expect(rendered("hi")).toMatch(/class="[^"]*\bprose\b[^"]*"/u);198+ });199+});200+201+describe("a README that is not Markdown", () => {202+ it.each([203+ ["README.md", true],204+ ["docs/readme.markdown", true],205+ ["README.mdown", true],206+ ["README", false],207+ ["README.txt", false],208+ ["README.rst", false],209+ ])("reads %s as Markdown: %s", (path, markdown) => {210+ expect(isMarkdownPath(path)).toBe(markdown);211+ });212+213+ it("shows as written, in a pre", () => {214+ const markup = renderToString(<RepoText source={"# not a heading\n<b>"} />);215+216+ expect(markup).toMatch(/^<pre[^>]*># not a heading\n<b><\/pre>$/u);217+ });218+});