html.ts 3.3 KB

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