Spaces:
No application file
No application file
Download src/utils/codeParser.ts from usrrootkali/Awakened_RiShre: direct link, hf CLI and curl.
- Browser
- Download file 7.35 kB
-
https://huggingface.co/spaces/usrrootkali/Awakened_RiShre/resolve/main/src/utils/codeParser.ts
- Command line
-
hf download hf://spaces/usrrootkali/Awakened_RiShre/src/utils/codeParser.ts
-
curl -L -o codeParser.ts https://huggingface.co/spaces/usrrootkali/Awakened_RiShre/resolve/main/src/utils/codeParser.ts
7.35 kB
| 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 <!-- file: index.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('<!DOCTYPE') || rawBody.includes('<html')) { | |
| finalName = 'index.html'; | |
| } else if (currentLang === 'css') { | |
| finalName = 'style.css'; | |
| } else if (currentLang === 'javascript' || currentLang === 'js') { | |
| finalName = 'app.js'; | |
| } else { | |
| finalName = `file_${files.length + 1}.${currentLang || 'txt'}`; | |
| } | |
| } | |
| files.push({ | |
| name: finalName, | |
| language: inferLanguage(finalName || currentLang), | |
| content: rawBody, | |
| }); | |
| } | |
| currentLang = ''; | |
| currentFilename = ''; | |
| currentContent = []; | |
| } | |
| } else if (insideBlock) { | |
| currentContent.push(line); | |
| } | |
| } | |
| // Deduplicate by filename (latest occurrence wins) | |
| const fileMap = new Map<string, ParsedFile>(); | |
| 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: '<!DOCTYPE html><html><head><title>Preview</title></head><body><div id="root"></div></body></html>' | |
| }; | |
| 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. <script src="app.js"></script>) and local css links | |
| htmlContent = htmlContent.replace(/<script\s+src=["'](?:\.\/|\/)?(?!https?:\/\/)(?:[a-zA-Z0-9_\-\.\/]+\.js)["']\s*><\/script>/gi, ''); | |
| htmlContent = htmlContent.replace(/<link\s+[^>]*href=["'](?:\.\/|\/)?(?!https?:\/\/)(?:[a-zA-Z0-9_\-\.\/]+\.css)["'][^>]*>/gi, ''); | |
| // Virtual Console interceptor script | |
| const consoleBridgeScript = ` | |
| <script> | |
| (function() { | |
| const emitLog = (type, args) => { | |
| try { | |
| const serialized = Array.from(args).map(arg => { | |
| if (typeof arg === 'object' && arg !== null) { | |
| try { return JSON.stringify(arg); } catch (e) { return String(arg); } | |
| } | |
| return String(arg); | |
| }).join(' '); | |
| window.parent.postMessage({ | |
| type: 'RISHRE_CONSOLE_EVENT', | |
| payload: { | |
| type, | |
| message: serialized, | |
| timestamp: Date.now() | |
| } | |
| }, '*'); | |
| } catch (e) {} | |
| }; | |
| const _log = console.log; | |
| const _warn = console.warn; | |
| const _error = console.error; | |
| const _info = console.info; | |
| console.log = function(...args) { _log.apply(console, args); emitLog('log', args); }; | |
| console.info = function(...args) { _info.apply(console, args); emitLog('info', args); }; | |
| console.warn = function(...args) { _warn.apply(console, args); emitLog('warn', args); }; | |
| console.error = function(...args) { _error.apply(console, args); emitLog('error', args); }; | |
| window.addEventListener('error', function(e) { | |
| emitLog('error', [e.message + ' at ' + (e.filename || 'script') + ':' + e.lineno]); | |
| }); | |
| window.addEventListener('unhandledrejection', function(e) { | |
| emitLog('error', ['Unhandled Promise Rejection: ' + (e.reason ? (e.reason.message || e.reason) : 'Unknown')]); | |
| }); | |
| })(); | |
| </script> | |
| `; | |
| // Concatenate all CSS | |
| const combinedCss = cssFiles.map(f => `\n/* ${f.name} */\n${f.content}`).join('\n'); | |
| const styleBlock = combinedCss ? `<style id="rishre-styles">${combinedCss}</style>` : ''; | |
| // 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 ? `<script id="rishre-scripts">${combinedJs}</script>` : ''; | |
| // Inject into HTML | |
| if (htmlContent.includes('</head>')) { | |
| htmlContent = htmlContent.replace('</head>', `${consoleBridgeScript}\n${styleBlock}\n</head>`); | |
| } else { | |
| htmlContent = `${consoleBridgeScript}\n${styleBlock}\n${htmlContent}`; | |
| } | |
| if (htmlContent.includes('</body>')) { | |
| htmlContent = htmlContent.replace('</body>', `${scriptBlock}\n</body>`); | |
| } else { | |
| htmlContent = `${htmlContent}\n${scriptBlock}`; | |
| } | |
| return htmlContent; | |
| } | |