56 lines
1.2 KiB
TypeScript
56 lines
1.2 KiB
TypeScript
import MarkdownIt from 'markdown-it'
|
|
import type Token from 'markdown-it/lib/token.mjs'
|
|
|
|
const md = new MarkdownIt({
|
|
html: true,
|
|
linkify: true,
|
|
typographer: true,
|
|
breaks: true
|
|
})
|
|
|
|
type AstNode = {
|
|
type: string
|
|
tag?: string
|
|
nesting?: number
|
|
level?: number
|
|
content?: string
|
|
markup?: string
|
|
info?: string
|
|
block?: boolean
|
|
hidden?: boolean
|
|
map?: number[] | null
|
|
attrs?: Record<string, string>
|
|
children?: AstNode[]
|
|
}
|
|
|
|
function tokenToAstNode(token: Token): AstNode {
|
|
return {
|
|
type: token.type,
|
|
tag: token.tag || undefined,
|
|
nesting: token.nesting,
|
|
level: token.level,
|
|
content: token.content || undefined,
|
|
markup: token.markup || undefined,
|
|
info: token.info || undefined,
|
|
block: token.block,
|
|
hidden: token.hidden,
|
|
map: token.map || null,
|
|
attrs: token.attrs ? Object.fromEntries(token.attrs) : undefined,
|
|
children: token.children?.map(tokenToAstNode)
|
|
}
|
|
}
|
|
|
|
export function markdownToAstString(markdown: string): string {
|
|
if (!markdown.trim()) {
|
|
return ''
|
|
}
|
|
|
|
const tokens = md.parse(markdown, {})
|
|
const ast = {
|
|
type: 'root',
|
|
children: tokens.map(tokenToAstNode)
|
|
}
|
|
|
|
return JSON.stringify(ast, null, 2)
|
|
}
|