-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhtml-to-markdown.ts
More file actions
47 lines (40 loc) · 1.24 KB
/
html-to-markdown.ts
File metadata and controls
47 lines (40 loc) · 1.24 KB
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
import TurndownService from "turndown";
import { gfm } from "turndown-plugin-gfm";
import type { AnchorIndex } from "./types";
/** Result of converting HTML to Markdown. */
export interface HtmlToMarkdownResult {
markdown: string;
anchorIndex: AnchorIndex;
}
const turndown = new TurndownService({
headingStyle: "atx",
codeBlockStyle: "fenced",
bulletListMarker: "-",
});
turndown.use(gfm);
turndown.addRule("pythonSig", {
filter: (node) => node.nodeName === "DT" && node.classList?.contains("sig"),
replacement: (content) => `\n**${content.trim()}**\n`,
});
turndown.remove(["script", "style", "nav", "footer", "header"]);
/**
* Converts HTML documentation to Markdown format.
* Strips comments and unwanted elements, normalizes whitespace,
* and formats Python function signatures as bold text.
* @param html - Raw HTML content from DevDocs.
* @returns Markdown content and anchor index for navigation.
*/
export function htmlToMarkdown(html: string): HtmlToMarkdownResult {
const cleanHtml = html.replace(/<!--[\s\S]*?-->/g, "");
const markdown = turndown
.turndown(cleanHtml)
.replace(/\n{3,}/g, "\n\n")
.trim();
return {
markdown,
anchorIndex: {
anchors: [],
totalLength: markdown.length,
},
};
}