1 import type { DocBlock, DocPage, DocTypeListItem } from "types"
2
3 export type DocPageToMarkdownOptions = {
4 /**
5 * When set, root-relative links (`/references/...`) are rewritten to absolute
6 * URLs, mirroring the `addUrlToRelativeLink` plugin used for MDX pages.
7 */
8 baseUrl?: string
9 }
10
11 /**
12 * Converts a references {@link DocPage} (the JSON doc-model) into clean Markdown
13 * for the `md-content` route (LLM / "copy as markdown" consumption). It is the
14 * doc-model analogue of `getCleanMd`: instead of parsing MDX and stripping
15 * components, it walks the structured blocks and emits plain Markdown.
16 *
17 * Type strings are emitted verbatim (they already contain Markdown code spans /
18 * links), so generics like `Record<string, T>` never need MDX/JSX escaping.
19 */
20 export function docPageToMarkdown(
21 page: DocPage,
22 options: DocPageToMarkdownOptions = {}
23 ): string {
24 const parts: string[] = [`# ${page.title}`]
25
26 for (const block of page.blocks) {
27 const rendered = renderBlock(block)
28 if (rendered.trim().length) {
29 parts.push(rendered.trim())
30 }
31 }
32
33 const content = decodeEntities(parts.join("\n\n"))
34 return options.baseUrl ? absolutizeLinks(content, options.baseUrl) : content
35 }
36
37 /**
38 * Decodes the HTML entities the generator emits for MDX safety (e.g. `&#60;` in
39 * type strings). Plain Markdown doesn't need them, and decoded output reads
40 * better for LLM / copy-as-markdown consumption.
41 */
42 function decodeEntities(text: string): string {
43 return text
44 .replace(/&#60;/g, "<")
45 .replace(/&#62;/g, ">")
46 .replace(/&#123;/g, "{")
47 .replace(/&#125;/g, "}")
48 .replace(/&quot;/g, '"')
49 .replace(/&#39;/g, "'")
50 .replace(/&amp;/g, "&")
51 }
52
53 function renderBlock(block: DocBlock): string {
54 switch (block.kind) {
55 case "markdown":
56 return block.html
57 case "heading":
58 return `${"#".repeat(Math.min(Math.max(block.level, 2), 6))} ${block.text}`
59 case "typeList":
60 return [
61 block.sectionTitle ? `**${block.sectionTitle}**\n` : "",
62 block.types.map((type) => renderTypeItem(type, 0)).join("\n"),
63 ]
64 .filter(Boolean)
65 .join("\n")
66 case "codeTabs":
67 return block.tabs
68 .map((tab) => {
69 const meta = tab.title ? ` title="${tab.title}"` : ""
70 return `**${tab.label}**\n\n\`\`\`${tab.language}${meta}\n${tab.code}\n\`\`\``
71 })
72 .join("\n\n")
73 case "workflowDiagram":
74 // The builder emits a preceding "Steps" heading block, so this renders
75 // only the step list.
76 return block.workflow.steps
77 .map((step) => renderWorkflowStep(step))
78 .join("\n")
79 case "note": {
80 const title = block.title || capitalize(block.variant || "note")
81 const body = block.html
82 .split("\n")
83 .map((line) => `> ${line}`)
84 .join("\n")
85 return `> **${title}**\n>\n${body}`
86 }
87 case "sourceCodeLink":
88 return `[${block.text || "View source code"}](${block.link})`
89 case "linkList":
90 return block.items
91 .map(
92 (item) =>
93 `- [${item.title}](${item.href})${
94 item.description ? ` — ${oneLine(item.description)}` : ""
95 }`
96 )
97 .join("\n")
98 case "workflowEvents":
99 // The builder emits a preceding "Emitted Events" heading block, so this
100 // renders only the event list.
101 return `${block.events
102 .map((event) => {
103 const flags = [
104 event.deprecated ? "deprecated" : "",
105 event.since ? `since v${event.since}` : "",
106 ]
107 .filter(Boolean)
108 .join(", ")
109 const header = `- \`${event.name}\`${flags ? ` (${flags})` : ""}${
110 event.description ? `: ${oneLine(event.description)}` : ""
111 }`
112 const payload = event.payload
113 ? `\n\n \`\`\`ts\n${indent(event.payload, " ")}\n \`\`\``
114 : ""
115 return `${header}${payload}`
116 })
117 .join("\n")}`
118 case "eventsListing":
119 return block.categories
120 .map((category) => {
121 const parts: string[] = []
122 if (block.categories.length > 1 && category.title) {
123 parts.push(`## ${category.title} Events`)
124 }
125 parts.push("### Summary\n")
126 parts.push(
127 [
128 "| Event | Description |",
129 "| --- | --- |",
130 ...category.events.map(
131 (event) =>
132 `| [\`${event.name}\`](#${event.id}) | ${
133 event.description ? oneLine(event.description) : ""
134 } |`
135 ),
136 ].join("\n")
137 )
138 category.events.forEach((event) => {
139 parts.push(`### ${event.name}`)
140 if (event.description) {
141 parts.push(event.description)
142 }
143 if (event.payload) {
144 parts.push(`#### Payload\n\n${event.payload}`)
145 }
146 if (event.workflows?.length) {
147 parts.push("#### Workflows Emitting this Event\n")
148 parts.push(
149 event.workflows
150 .map((workflow) => `- [${workflow.name}](${workflow.href})`)
151 .join("\n")
152 )
153 }
154 })
155 return parts.join("\n\n")
156 })
157 .join("\n\n---\n\n")
158 case "table": {
159 const header = `| ${block.headers.join(" | ")} |`
160 const divider = `| ${block.headers.map(() => "---").join(" | ")} |`
161 const rows = block.rows.map((row) => `| ${row.join(" | ")} |`)
162 return [header, divider, ...rows].join("\n")
163 }
164 case "badges":
165 return ""
166 default:
167 return ""
168 }
169 }
170
171 function renderTypeItem(type: DocTypeListItem, level: number): string {
172 const indentation = " ".repeat(level)
173 const flags = [
174 type.optional ? "optional" : "",
175 type.defaultValue ? `default: ${type.defaultValue}` : "",
176 type.deprecated?.is_deprecated ? "deprecated" : "",
177 ]
178 .filter(Boolean)
179 .join(", ")
180
181 const parts = [`\`${type.name}\``]
182 if (type.type) {
183 parts.push(type.type)
184 }
185 let line = `${indentation}- ${parts.join(": ")}`
186 if (flags) {
187 line += ` (${flags})`
188 }
189 if (type.description) {
190 line += ` — ${oneLine(type.description)}`
191 }
192
193 const children = (type.children || [])
194 .map((child) => renderTypeItem(child, level + 1))
195 .join("\n")
196
197 return children.length ? `${line}\n${children}` : line
198 }
199
200 type WorkflowStepLike = {
201 type: string
202 name?: string
203 description?: string
204 link?: string
205 depth?: number
206 condition?: string
207 steps?: WorkflowStepLike[]
208 }
209
210 function renderWorkflowStep(step: WorkflowStepLike): string {
211 const indentation = " ".repeat(Math.max((step.depth || 1) - 1, 0))
212
213 if (step.type === "when") {
214 const condition = step.condition ? ` (when: ${step.condition})` : ""
215 const nested = (step.steps || [])
216 .map((child) => renderWorkflowStep(child))
217 .join("\n")
218 return `${indentation}- **when**${condition}\n${nested}`
219 }
220
221 const label = step.link ? `[${step.name}](${step.link})` : step.name || ""
222 const desc = step.description ? `: ${oneLine(step.description)}` : ""
223 return `${indentation}- ${label}${desc}`
224 }
225
226 function oneLine(text: string): string {
227 return text.replace(/\s*\n+\s*/g, " ").trim()
228 }
229
230 function indent(text: string, prefix: string): string {
231 return text
232 .split("\n")
233 .map((line) => `${prefix}${line}`)
234 .join("\n")
235 }
236
237 function capitalize(text: string): string {
238 return text.charAt(0).toUpperCase() + text.slice(1)
239 }
240
241 /** Prepends `baseUrl` to root-relative Markdown links (`](/...)`). */
242 function absolutizeLinks(content: string, baseUrl: string): string {
243 const normalizedBase = baseUrl.replace(/\/$/, "")
244 return content.replace(/\]\(\/(?!\/)/g, `](${normalizedBase}/`)
245 }