import { ProjectFile } from '../types'; export interface ParsedFile { name: string; language: ProjectFile['language']; content: string; } /** * Infer file language from extension or block language tag */ export function inferLanguage(nameOrLang: string): ProjectFile['language'] { const lower = nameOrLang.toLowerCase(); if (lower.endsWith('.html') || lower === 'html') return 'html'; if (lower.endsWith('.css') || lower === 'css') return 'css'; if (lower.endsWith('.js') || lower.endsWith('.jsx') || lower === 'javascript' || lower === 'js') return 'javascript'; if (lower.endsWith('.ts') || lower.endsWith('.tsx') || lower === 'typescript' || lower === 'ts') return 'typescript'; if (lower.endsWith('.json') || lower === 'json') return 'json'; return 'markdown'; } /** * Robust line-by-line markdown code block extractor */ export function parseMarkdownCodeFiles(markdown: string): ParsedFile[] { const files: ParsedFile[] = []; const lines = markdown.split('\n'); let insideBlock = false; let currentLang = ''; let currentFilename = ''; let currentContent: string[] = []; let lastHeading = ''; for (let i = 0; i < lines.length; i++) { const line = lines[i]; const trimmed = line.trim(); // Check for headings like "# index.html" or "### style.css" const headingMatch = trimmed.match(/^#{1,6}\s+([a-zA-Z0-9_\-\.\/]+\.[a-zA-Z0-9]+)\s*$/i); if (headingMatch && !insideBlock) { lastHeading = headingMatch[1].trim(); continue; } if (trimmed.startsWith('```')) { if (!insideBlock) { // Opening fence insideBlock = true; currentContent = []; const headerInfo = trimmed.replace(/^```/, '').trim(); // Extract language and potential filename from headerInfo // Examples: // "html " // "css /* file: style.css */" // "javascript // file: app.js" // "html index.html" // "html" let lang = ''; let detectedFilename = ''; // Clean out comment delimiters const cleaned = headerInfo .replace(/|\/\*|\*\/|\/\/|#/g, '') .replace(/file\s*:\s*/i, '') .trim(); const parts = cleaned.split(/\s+/).filter(Boolean); if (parts.length >= 2) { lang = parts[0]; detectedFilename = parts[1]; } else if (parts.length === 1) { if (parts[0].includes('.')) { detectedFilename = parts[0]; lang = inferLanguage(parts[0]); } else { lang = parts[0]; } } if (!detectedFilename && lastHeading) { detectedFilename = lastHeading; } currentLang = lang || 'html'; currentFilename = detectedFilename; lastHeading = ''; // Consume heading } else { // Closing fence insideBlock = false; const rawBody = currentContent.join('\n').trim(); if (rawBody) { let finalName = currentFilename; if (!finalName) { if (currentLang === 'html' || rawBody.includes('(); for (const f of files) { fileMap.set(f.name, f); } return Array.from(fileMap.values()); } /** * Combines project files into a runnable standalone HTML string with console bridge */ export function assemblePreviewHtml(files: ProjectFile[]): string { const htmlFile = files.find(f => f.name.endsWith('.html')) || { content: 'Preview
' }; const cssFiles = files.filter(f => f.name.endsWith('.css')); const jsFiles = files.filter(f => f.name.endsWith('.js') || f.name.endsWith('.jsx')); let htmlContent = htmlFile.content; // Strip relative local script tags (e.g. ) and local css links htmlContent = htmlContent.replace(/<\/script>/gi, ''); htmlContent = htmlContent.replace(/]*href=["'](?:\.\/|\/)?(?!https?:\/\/)(?:[a-zA-Z0-9_\-\.\/]+\.css)["'][^>]*>/gi, ''); // Virtual Console interceptor script const consoleBridgeScript = ` `; // Concatenate all CSS const combinedCss = cssFiles.map(f => `\n/* ${f.name} */\n${f.content}`).join('\n'); const styleBlock = combinedCss ? `` : ''; // Concatenate all JS const combinedJs = jsFiles.map(f => `\n// ${f.name}\ntry {\n${f.content}\n} catch(err) { console.error(err); }`).join('\n'); const scriptBlock = combinedJs ? `` : ''; // Inject into HTML if (htmlContent.includes('')) { htmlContent = htmlContent.replace('', `${consoleBridgeScript}\n${styleBlock}\n`); } else { htmlContent = `${consoleBridgeScript}\n${styleBlock}\n${htmlContent}`; } if (htmlContent.includes('')) { htmlContent = htmlContent.replace('', `${scriptBlock}\n`); } else { htmlContent = `${htmlContent}\n${scriptBlock}`; } return htmlContent; }