import MarkdownIt from "markdown-it"; import { type Html, trusted } from "./html.ts"; import { pathUrl } from "./layout.ts"; /** Where a Markdown file lives, so its relative links and images can point at the repo's raw files. */ export type MarkdownBase = { repo: string; dir: string; at: string | null }; const SCHEME = /^([a-z][a-z0-9+.-]*):/i; const ALLOWED_SCHEMES = ["http", "https", "mailto"]; // ยง25: raw HTML is off, so markdown-it's own escaping is the whole sanitizer. const md = new MarkdownIt({ html: false, linkify: true }); md.validateLink = (url) => { const scheme = SCHEME.exec(url.trim()); return !scheme || ALLOWED_SCHEMES.includes((scheme[1] as string).toLowerCase()); }; md.core.ruler.push("kepr_raw_links", (state) => { const base = state.env as MarkdownBase; const visit = (tokens: typeof state.tokens) => { for (const token of tokens) { const attr = token.type === "link_open" ? "href" : token.type === "image" ? "src" : null; const url = attr && token.attrGet(attr); if (attr && typeof url === "string") token.attrSet(attr, rawUrl(url, base)); if (token.children) visit(token.children); } }; visit(state.tokens); }); function rawUrl(url: string, base: MarkdownBase): string { if (SCHEME.test(url) || url.startsWith("#") || url.startsWith("//")) return url; // A leading `/` means the repo root, as it does on a code host. const resolved = new URL(url, `http://repo/${base.dir ? `${pathUrl(base.dir)}/` : ""}`); const at = base.at ? `?at=${base.at}` : ""; return `/${base.repo}/raw${resolved.pathname}${at}${resolved.hash}`; } export function renderMarkdown(source: string, base: MarkdownBase): Html { return trusted(md.render(source, base)); } /** * A paragraph of Markdown source (the README's first paragraph, found as the Atlas finds it) as * inline markup, and as plain text for link previews. */ export function renderParagraph(source: string, base: MarkdownBase): { html: Html; text: string } { const children = md.parseInline(source, base)[0]?.children ?? []; const text = children .map((token) => token.type === "text" || token.type === "code_inline" ? token.content : token.type === "softbreak" ? " " : "", ) .join(""); return { html: trusted(md.renderer.renderInline(children, md.options, base)), text }; } /** One line of Markdown with links and images flattened away, for a row that is itself a link. */ export function renderLine(source: string, base: MarkdownBase): Html { const tokens = md.parseInline(source, base)[0]?.children ?? []; const kept = tokens.filter((token) => !/^(link_open|link_close|image)$/.test(token.type)); return trusted(md.renderer.renderInline(kept, md.options, base)); }