import DOMPurify from 'dompurify'; import { detectTextDirection, applyTextDirection } from './text-direction'; import { sanitizeHtml } from './email-utils'; /** * Format and standardize email content for display following email industry standards. * This function handles various email content formats and ensures proper display * including support for HTML emails, plain text emails, RTL languages, and email client quirks. */ export function formatEmailContent(email: any): string { if (!email) { console.log('formatEmailContent: No email provided'); return ''; } try { // Get the content in order of preference with proper fallbacks let content = ''; let isHtml = false; let textContent = ''; // Extract content based on standardized property hierarchy if (email.content && typeof email.content === 'object') { isHtml = !!email.content.html; content = email.content.html || ''; textContent = email.content.text || ''; } else if (typeof email.content === 'string') { // Check if the string content is HTML isHtml = email.content.trim().startsWith('<') && (email.content.includes('')); content = email.content; textContent = email.content; } else if (email.html) { isHtml = true; content = email.html; textContent = email.text || ''; } else if (email.text) { isHtml = false; content = ''; textContent = email.text; } else if (email.formattedContent) { // Assume formattedContent is already HTML isHtml = true; content = email.formattedContent; textContent = ''; } // Log what we found for debugging console.log(`Email content detected: isHtml=${isHtml}, contentLength=${content.length}, textLength=${textContent.length}`); // If we have HTML content, sanitize and standardize it if (isHtml && content) { // CRITICAL FIX: Check for browser environment since DOMParser is browser-only const hasHtmlTag = content.includes(' { return `src="data:image/png;base64,${p1.replace(/\s+/g, '')}"`; }); // Use the centralized text direction utility const styledContent = `
${fixedContent}
`; // Apply correct text direction using the centralized utility return applyTextDirection(styledContent, textContent); } // If we only have text content, format it properly else if (textContent) { // Escape HTML characters to prevent XSS const escapedText = textContent .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"') .replace(/'/g, '''); // Format plain text with proper line breaks and paragraphs const formattedText = escapedText .replace(/\r\n|\r|\n/g, '
') // Convert all newlines to
.replace(/((?:
){2,})/g, '

') // Convert multiple newlines to paragraphs .replace(/
<\/p>/g, '

') // Fix any

combinations .replace(/


/g, '

'); // Fix any


combinations const styledPlainText = `

${formattedText}

`; // Apply correct text direction using the centralized utility return applyTextDirection(styledPlainText, textContent); } // Default case: empty or unrecognized content return ''; } catch (error) { console.error('formatEmailContent: Error formatting email content:', error); return ``; } }