const TurndownService = require('turndown'); const { marked } = require('marked'); /** * Prepares HTML for document conversion (DOCX). * Because html-to-docx is incredibly unstable with styled HTML tables/divs, * we will use Turndown to extract the raw text/markdown structure, * and then convert it back into safe, barebones HTML for Word. * * @param {string} rawHtml * @returns {string} cleaned HTML */ function prepareHtmlForConversion(rawHtml) { if (!rawHtml || typeof rawHtml !== 'string') return ''; try { // 1. Convert complex AI HTML to simple Markdown const turndownService = new TurndownService({ headingStyle: 'atx', bulletListMarker: '-' }); // Strip out styling blocks before turndown const cleanRaw = rawHtml.replace(/]*>[\s\S]*?<\/style>/gi, '') .replace(/]*>[\s\S]*?<\/script>/gi, ''); const markdown = turndownService.turndown(cleanRaw); // 2. Convert simple Markdown back to guaranteed-safe HTML const safeHtml = marked.parse(markdown); // 3. Wrap in DOCX required skeleton return `${safeHtml}`; } catch (e) { console.warn("Turndown conversion failed, returning fallback:", e); // Absolute fallback const fallbackMsg = "

Resume

Error parsing advanced CV styling. Please use the PDF download.

"; return `${fallbackMsg}`; } } module.exports = { prepareHtmlForConversion };