html.ts 3.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /**
  2. * Minimal, dependency-free HTML→markdown-ish text conversion for `web_fetch`
  3. * presentation. This is intentionally NOT a full HTML parser: it strips
  4. * script/style/noscript, drops tags, decodes the common named/numeric entities,
  5. * and collapses whitespace into a readable plain-text approximation with a few
  6. * markdown affordances (headings, list bullets, links). A heavier converter can
  7. * replace this without touching the seam or the tool schema.
  8. *
  9. * @module @deepseek-ai/dsh-tool-web/html
  10. */
  11. /** Decode the handful of HTML entities common in textual content. */
  12. function decodeEntities(text: string): string {
  13. return text
  14. .replace(/&(#[xX][0-9a-fA-F]+|#[0-9]+|[a-zA-Z]+);/g, (match, entity: string) => {
  15. if (entity.startsWith('#x') || entity.startsWith('#X')) {
  16. const code = Number.parseInt(entity.slice(2), 16)
  17. return safeFromCodePoint(code, match)
  18. }
  19. if (entity.startsWith('#')) {
  20. const code = Number.parseInt(entity.slice(1), 10)
  21. return safeFromCodePoint(code, match)
  22. }
  23. return NAMED_ENTITIES[entity] ?? match
  24. })
  25. }
  26. const NAMED_ENTITIES: Record<string, string> = {
  27. amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ',
  28. copy: '©', reg: '®', trade: '™', hellip: '…', mdash: '—', ndash: '–',
  29. }
  30. function safeFromCodePoint(code: number, fallback: string): string {
  31. try {
  32. return String.fromCodePoint(code)
  33. } catch {
  34. // An out-of-range code point (RangeError) is the only failure here; keep the
  35. // original entity text rather than throwing out of pure presentation.
  36. return fallback
  37. }
  38. }
  39. /**
  40. * Convert an HTML document to a readable markdown-ish text approximation.
  41. * Best-effort and lossy by design — fidelity is the job of a future heavier
  42. * converter, not this fallback.
  43. *
  44. * @param html - the raw HTML source.
  45. * @returns plain text with markdown headings, list bullets, and links;
  46. * whitespace collapsed to at most one blank line and trimmed.
  47. */
  48. export function htmlToMarkdown(html: string): string {
  49. let text = html
  50. // Drop non-content elements entirely (including their contents).
  51. .replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, '')
  52. .replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi, '')
  53. .replace(/<noscript\b[^>]*>[\s\S]*?<\/noscript>/gi, '')
  54. .replace(/<!--[\s\S]*?-->/g, '')
  55. // Convert links to markdown before stripping tags.
  56. text = text.replace(/<a\b[^>]*\bhref\s*=\s*["']([^"']*)["'][^>]*>([\s\S]*?)<\/a>/gi, (_match, href: string, label: string) => {
  57. const cleanLabel = label.replace(/<[^>]+>/g, '').trim()
  58. return cleanLabel.length > 0 ? `[${cleanLabel}](${href})` : href
  59. })
  60. // Headings → markdown hashes.
  61. text = text.replace(/<h([1-6])\b[^>]*>([\s\S]*?)<\/h\1>/gi, (_match, level: string, body: string) => {
  62. const hashes = '#'.repeat(Number(level))
  63. return `\n\n${hashes} ${body.replace(/<[^>]+>/g, '').trim()}\n\n`
  64. })
  65. // List items → bullets.
  66. text = text.replace(/<li\b[^>]*>([\s\S]*?)<\/li>/gi, (_match, body: string) => `\n- ${body.replace(/<[^>]+>/g, '').trim()}`)
  67. // Block-level breaks become paragraph breaks.
  68. text = text
  69. .replace(/<\/(p|div|section|article|header|footer|tr|table|ul|ol|blockquote)>/gi, '\n\n')
  70. .replace(/<br\s*\/?>/gi, '\n')
  71. // Drop all remaining tags, decode entities, collapse whitespace.
  72. text = text.replace(/<[^>]+>/g, '')
  73. text = decodeEntities(text)
  74. text = text
  75. .replace(/[ \t\f\v]+/g, ' ')
  76. .replace(/ *\n */g, '\n')
  77. .replace(/\n{3,}/g, '\n\n')
  78. .trim()
  79. return text
  80. }