import DOMPurify from 'dompurify'
import MarkdownIt from 'markdown-it'

const md = new MarkdownIt({
  html: false,
  linkify: true,
  breaks: true,
})

/**
 * 将 Markdown 转为可安全 `v-html` 的 HTML。
 */
export function renderMarkdown(source: string): string {
  const raw = md.render(source || '')
  return DOMPurify.sanitize(raw, {
    ADD_ATTR: ['target'],
    ALLOWED_TAGS: [
      'p',
      'br',
      'strong',
      'em',
      'u',
      's',
      'blockquote',
      'code',
      'pre',
      'ul',
      'ol',
      'li',
      'a',
      'h1',
      'h2',
      'h3',
      'h4',
      'hr',
    ],
  })
}
