File size: 16,132 Bytes
3de227d a241775 3de227d 08e03e9 3de227d 08e03e9 3de227d 08e03e9 3de227d 0c69852 3de227d 08e03e9 3de227d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 | /**
* Server-side Markdown renderer for the publisher pipeline.
*
* Walks the same TipTap-JSON document used by `html-renderer.ts` and
* produces a clean Markdown file conforming to the `llms.txt` convention
* (https://llmstxt.org/). The output is meant to be consumed by LLM
* agents and crawlers that struggle with the heavy published HTML
* (theme bootstrap, KaTeX/Mermaid runtimes, inlined CSS, iframe-wrapped
* D3 charts, ...).
*
* Conventions mirror the upstream `research-article-template` Astro
* plugin (`app/plugins/astro/generate-llms-txt.mjs`):
*
* - `<HtmlEmbed src="..." />` -> `*[Interactive visualization: <src>]*`
* - `<Note>...</Note>` -> blockquote
* - `<Quote author=...>` -> blockquote + attribution
* - `<Wide>`/`<FullWidth>` -> unwrap content
* - `<Sidenote>` -> main content + blockquote aside
* - `<Reference caption=...>` -> content + caption
* - `<Accordion title=...>` -> bold title + content
* - `<Mermaid code=...>` -> fenced ```mermaid``` code block
* - `<HfUser username=...>` -> `[@u](https://huggingface.co/u)`
* - `<Citation key=...>` -> `[key]` (or `[N]` for IEEE)
* - `<Footnote content=...>` -> Pandoc `[^N]` reference + footnotes section
* - inline / block math -> `$...$` / `$$...$$`
*
* Output shape:
* # <title>
*
* > <subtitle / description>
*
* - **Authors**: ...
* - **Published**: ...
* - **DOI**: ...
*
* ---
*
* <body markdown>
*
* ## References
* ...
*
* ## Footnotes
* ...
*/
import type { PublishMeta, CitationData } from "./publish-types.js";
type JSONNode = {
type?: string;
attrs?: Record<string, any>;
marks?: Array<{ type: string; attrs?: Record<string, any> }>;
text?: string;
content?: JSONNode[];
};
interface RenderCtx {
citationData?: CitationData;
/** Pre-formatted bibliography (HTML from citation-js) - we strip tags. */
biblioHtml?: string;
/** Footnote texts collected during the walk, emitted at the end. */
footnotes: string[];
/** Emit editable source syntax (`[@key]`, `^[note]`) instead of rendered labels. */
sourceSyntax?: boolean;
}
// ---------------------------------------------------------------------------
// Inline rendering (text + marks + inline atoms)
// ---------------------------------------------------------------------------
function applyMarks(text: string, marks: JSONNode["marks"]): string {
if (!marks?.length) return text;
let out = text;
for (const mark of marks) {
switch (mark.type) {
case "bold":
out = `**${out}**`;
break;
case "italic":
out = `*${out}*`;
break;
case "strike":
out = `~~${out}~~`;
break;
case "code":
out = `\`${out}\``;
break;
case "link": {
const href = mark.attrs?.href || "";
out = href ? `[${out}](${href})` : out;
break;
}
default:
break;
}
}
return out;
}
function getCitationLabel(key: string, ctx: RenderCtx, fallbackLabel?: string): string {
if (!ctx.citationData) return fallbackLabel || `[${key}]`;
const { style, orderedKeys } = ctx.citationData;
if (style === "ieee" || style === "vancouver") {
const idx = orderedKeys.indexOf(key);
if (idx >= 0) return `[${idx + 1}]`;
}
return fallbackLabel || `[${key}]`;
}
function renderInline(nodes: JSONNode[] | undefined, ctx: RenderCtx): string {
if (!nodes) return "";
let out = "";
for (const node of nodes) {
out += renderInlineNode(node, ctx);
}
return out;
}
function renderInlineNode(node: JSONNode, ctx: RenderCtx): string {
switch (node.type) {
case "text":
return applyMarks(node.text || "", node.marks);
case "hardBreak":
return " \n";
case "inlineMath": {
const latex = node.attrs?.latex || "";
return latex ? `$${latex}$` : "";
}
case "citation": {
const key = String(node.attrs?.key || "");
if (!key) return "";
if (ctx.sourceSyntax) return `[@${key}]`;
return getCitationLabel(key, ctx, node.attrs?.label);
}
case "glossary": {
const term = String(node.attrs?.term || "");
return term;
}
case "footnote": {
const content = String(node.attrs?.content || "");
if (ctx.sourceSyntax) return `^[${content}]`;
ctx.footnotes.push(content);
return `[^${ctx.footnotes.length}]`;
}
case "image": {
const src = String(node.attrs?.src || "");
const alt = String(node.attrs?.alt || "");
const title = node.attrs?.title ? ` "${node.attrs.title}"` : "";
return src ? `` : alt;
}
default:
// Unknown inline: fall back to its text content if any.
return renderInline(node.content, ctx);
}
}
// ---------------------------------------------------------------------------
// Block rendering
// ---------------------------------------------------------------------------
function renderBlocks(nodes: JSONNode[] | undefined, ctx: RenderCtx): string {
if (!nodes?.length) return "";
const parts: string[] = [];
for (const node of nodes) {
const rendered = renderBlock(node, ctx);
if (rendered) parts.push(rendered);
}
return parts.join("\n\n");
}
function renderBlock(node: JSONNode, ctx: RenderCtx): string {
switch (node.type) {
case "doc":
return renderBlocks(node.content, ctx);
case "paragraph": {
const inner = renderInline(node.content, ctx).trim();
return inner;
}
case "heading": {
const level = Math.min(Math.max(Number(node.attrs?.level) || 1, 1), 6);
const inner = renderInline(node.content, ctx).trim();
return `${"#".repeat(level)} ${inner}`;
}
case "blockquote": {
const inner = renderBlocks(node.content, ctx);
return inner
.split("\n")
.map((l) => (l.length ? `> ${l}` : ">"))
.join("\n");
}
case "horizontalRule":
return "---";
case "codeBlock": {
const lang = String(node.attrs?.language || node.attrs?.lang || "");
const code = (node.content || [])
.map((c) => c.text || "")
.join("");
return `\`\`\`${lang}\n${code}\n\`\`\``;
}
case "bulletList":
return renderList(node, ctx, "-");
case "orderedList":
return renderList(node, ctx, "1.");
case "listItem": {
// Should normally be reached via renderList, but if encountered
// standalone we just render its blocks.
return renderBlocks(node.content, ctx);
}
case "blockMath": {
const latex = String(node.attrs?.latex || "").trim();
return latex ? `$$\n${latex}\n$$` : "";
}
case "table":
return renderTable(node, ctx);
// --- Custom block components ---
case "accordion": {
const title = String(node.attrs?.title || "Details");
const inner = renderBlocks(node.content, ctx);
return `**${title}**\n\n${inner}`;
}
case "note": {
const inner = renderBlocks(node.content, ctx);
return inner
.split("\n")
.map((l) => (l.length ? `> ${l}` : ">"))
.join("\n");
}
case "quoteBlock": {
const inner = renderBlocks(node.content, ctx);
const author = String(node.attrs?.author || "").trim();
const source = String(node.attrs?.source || "").trim();
const attribution = [author, source].filter(Boolean).join(", ");
const quoted = inner
.split("\n")
.map((l) => (l.length ? `> ${l}` : ">"))
.join("\n");
return attribution ? `${quoted}\n>\n> -- ${attribution}` : quoted;
}
case "wide":
case "fullWidth":
case "stack":
case "stackColumn":
return renderBlocks(node.content, ctx);
case "sidenote": {
const inner = renderBlocks(node.content, ctx);
// No `slot="aside"` in TipTap-JSON: render as a blockquote.
return inner
.split("\n")
.map((l) => (l.length ? `> ${l}` : ">"))
.join("\n");
}
case "reference": {
const inner = renderBlocks(node.content, ctx);
const caption = String(node.attrs?.caption || "").trim();
return caption ? `${inner}\n\n*Figure: ${caption}*` : inner;
}
case "htmlEmbed": {
const src = String(node.attrs?.src || "").trim();
const title = String(node.attrs?.title || "").trim();
const desc = String(node.attrs?.desc || "").trim();
const labelParts = [title, desc].filter(Boolean);
const label = labelParts.length
? labelParts.join(" - ")
: src || "embed";
return `*[Interactive visualization: ${label}]*`;
}
case "iframe": {
const src = String(node.attrs?.src || "").trim();
const title = String(node.attrs?.title || "").trim();
const desc = String(node.attrs?.desc || "").trim();
if (!src) return "";
const label = title || desc || src;
// Surface the URL so LLM agents and crawlers can follow it.
return `*[Embedded page: [${label}](${src})]*`;
}
case "hfUser": {
const username = String(node.attrs?.username || "").trim();
if (!username) return "";
const url =
String(node.attrs?.url || "").trim() ||
`https://huggingface.co/${encodeURIComponent(username)}`;
const name = String(node.attrs?.name || "").trim() || `@${username}`;
return `[${name}](${url})`;
}
case "rawHtml": {
const html = String(node.attrs?.html || "");
return stripHtmlToText(html).trim();
}
case "mermaid": {
const code = String(node.attrs?.code || "").trim();
return code ? `\`\`\`mermaid\n${code}\n\`\`\`` : "";
}
case "bibliography":
// Emitted by `appendBibliographySection` from the post-walk step.
return "";
default:
// Unknown block: fall back to its content, or empty.
return renderBlocks(node.content, ctx);
}
}
function renderList(
node: JSONNode,
ctx: RenderCtx,
marker: string,
): string {
const items = node.content || [];
const lines: string[] = [];
items.forEach((item, idx) => {
const innerBlocks = renderBlocks(item.content, ctx);
const prefix = marker === "1." ? `${idx + 1}.` : marker;
const innerLines = innerBlocks.split("\n");
lines.push(`${prefix} ${innerLines[0] ?? ""}`);
for (let i = 1; i < innerLines.length; i++) {
const indent = " ".repeat(prefix.length + 1);
lines.push(`${indent}${innerLines[i]}`);
}
});
return lines.join("\n");
}
function renderTable(node: JSONNode, ctx: RenderCtx): string {
const rows = node.content || [];
if (!rows.length) return "";
const grid: string[][] = [];
let headerRowIndex = -1;
for (let r = 0; r < rows.length; r++) {
const row = rows[r];
const cells = row.content || [];
const rowText: string[] = [];
let rowIsHeader = false;
for (const cell of cells) {
if (cell.type === "tableHeader") rowIsHeader = true;
const text = renderBlocks(cell.content, ctx)
.replace(/\n+/g, " ")
.replace(/\|/g, "\\|")
.trim();
rowText.push(text);
}
grid.push(rowText);
if (rowIsHeader && headerRowIndex === -1) headerRowIndex = r;
}
const colCount = Math.max(...grid.map((r) => r.length));
for (const row of grid) {
while (row.length < colCount) row.push("");
}
const lines: string[] = [];
if (headerRowIndex === -1) {
// No explicit header row: synthesize one with empty cells so the
// markdown table is still valid.
lines.push(`| ${new Array(colCount).fill(" ").join(" | ")} |`);
lines.push(`| ${new Array(colCount).fill("---").join(" | ")} |`);
for (const row of grid) lines.push(`| ${row.join(" | ")} |`);
} else {
for (let r = 0; r < grid.length; r++) {
lines.push(`| ${grid[r].join(" | ")} |`);
if (r === headerRowIndex) {
lines.push(`| ${new Array(colCount).fill("---").join(" | ")} |`);
}
}
}
return lines.join("\n");
}
// ---------------------------------------------------------------------------
// Header (frontmatter) + bibliography + footnotes
// ---------------------------------------------------------------------------
function buildHeader(meta: PublishMeta): string {
const titleClean = (meta.title || "Untitled")
.replace(/\\n/g, " ")
.replace(/\n/g, " ")
.replace(/\s{2,}/g, " ")
.trim();
const parts = [`# ${titleClean}\n`];
const desc = (meta.description || meta.subtitle || "").trim();
if (desc) parts.push(`> ${desc}\n`);
const metaLines: string[] = [];
const authors = meta.authors.map((a) => a.name).filter(Boolean);
if (authors.length) metaLines.push(`- **Authors**: ${authors.join(", ")}`);
if (meta.date) metaLines.push(`- **Published**: ${meta.date}`);
if (meta.doi) {
const doiUrl = meta.doi.startsWith("http")
? meta.doi
: `https://doi.org/${meta.doi}`;
metaLines.push(`- **DOI**: ${doiUrl}`);
}
if (metaLines.length) parts.push(metaLines.join("\n") + "\n");
parts.push("---\n");
return parts.join("\n");
}
function appendBibliographySection(
ctx: RenderCtx,
): string {
if (!ctx.biblioHtml) return "";
const text = stripHtmlToText(ctx.biblioHtml).trim();
if (!text) return "";
return `## References\n\n${text}`;
}
function appendFootnotesSection(ctx: RenderCtx): string {
if (!ctx.footnotes.length) return "";
const lines = ctx.footnotes.map((content, i) => {
const clean = stripHtmlToText(content).trim().replace(/\n+/g, " ");
return `[^${i + 1}]: ${clean}`;
});
return `## Footnotes\n\n${lines.join("\n\n")}`;
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
/**
* Strip HTML tags while keeping anchor hrefs as Markdown links and emitting
* a blank line between block-level elements. Tuned for citation-js HTML
* output and for `rawHtml` user content - not a general-purpose sanitiser.
*/
export function stripHtmlToText(html: string): string {
if (!html) return "";
let out = html;
out = out.replace(/<a\s+[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi, "[$2]($1)");
out = out.replace(/<br\s*\/?>/gi, "\n");
out = out.replace(
/<\/(p|div|li|tr|h[1-6])>/gi,
"$&\n",
);
out = out.replace(/<[^>]+>/g, "");
out = out
.replace(/ /g, " ")
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, '"')
.replace(/'/g, "'");
return out
.split("\n")
.map((l) => l.trim())
.filter((l, i, arr) => !(l === "" && arr[i - 1] === ""))
.join("\n");
}
// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------
/**
* Render a TipTap-JSON document into an `llms.txt`-compatible Markdown string.
*
* `serverBiblioHtml` is the same HTML produced by `formatBibliographyServer()`
* for the HTML pipeline; we reuse it (stripped to text) so the agent gets the
* same reference list a human would see.
*/
/** Body blocks only (no header, references or footnotes section). */
export function renderBodyMarkdown(
nodes: unknown[],
options: { sourceSyntax?: boolean } = {},
): string {
const ctx: RenderCtx = { footnotes: [], sourceSyntax: options.sourceSyntax };
return renderBlocks(nodes as JSONNode[], ctx).replace(/\n{3,}/g, "\n\n").trim();
}
export function renderArticleMarkdown(
json: Record<string, unknown>,
meta: PublishMeta,
citationData?: CitationData,
serverBiblioHtml?: string,
): string {
const ctx: RenderCtx = {
citationData,
biblioHtml: serverBiblioHtml,
footnotes: [],
};
const body = renderBlocks((json as JSONNode).content, ctx);
const header = buildHeader(meta);
const refs = appendBibliographySection(ctx);
const footnotes = appendFootnotesSection(ctx);
const sections = [header.trimEnd(), body, refs, footnotes]
.filter(Boolean)
.join("\n\n");
return sections.replace(/\n{3,}/g, "\n\n").trim() + "\n";
}
|