Untitled conversation
- User
project-root/ ├── cat/ │ ├── bin/ │ │ └── cat.js │ └── src/ │ └── compiler.js | └── component.js | └── page.js ├── index.html ├── package.json └── cat.config.json// cat/src/compiler.js const fs = require('fs-extra'); const path = require('path'); const glob = require('glob'); const { parseComponent, parseScript, generateClassCode, transformMethodBody, generateDOMCode } = require('./component'); const { parsePage, detectLoadRoutes } = require('./page'); const { parseDocument } = require('htmlparser2'); /** * Detect used components in the provided HTML contents by parsing the HTML tags. * @param {Array<string>} htmlContents - Array of HTML file contents. * @param {Set<string>} availableComponents - Set of all available component tag names. * @returns {Set<string>} - Set of used component tag names. */ function detectUsedComponents(htmlContents, availableComponents) { const usedComponents = new Set(); // Regex to match all tags in the HTML const tagRegex = /<\s*([a-zA-Z][a-zA-Z0-9-]*)\b[^>]*>/g; htmlContents.forEach(content => { let match; while ((match = tagRegex.exec(content)) !== null) { let tag = match[1]; if (availableComponents.has(tag)) { usedComponents.add(tag); } } }); return usedComponents; } /** * Generate the registration script for the used components. * @param {Map<string, string>} components - Map of tagName to compiled class code. * @returns {string} - JavaScript code for registering components. */ function generateRegistrationScript(components) { let script = ''; components.forEach((classCode) => { script += ` ${classCode} `; }); return script; } /** * Compiler Function * @param {string} indexPath - Path to the index.html file. * @returns {Promise<string>} - Compiled HTML content with component registrations and page injections. */ async function compile(indexPath) { // Read the index.html content let indexContent = await fs.readFile(indexPath, 'utf-8'); // Define project root const projectRoot = path.dirname(indexPath); // ----------------------- // Step 1: Process Components // ----------------------- // Find all .comp.html files in the project directory const compFiles = glob.sync('**/*.comp.html', { cwd: projectRoot, absolute: true, ignore: ['node_modules/**', 'cat/**'] // Ignore node_modules and cat directory to prevent recursion }); const componentMap = new Map(); // Map of tagName to compiled class code const parsedComponents = new Set(); // To track parsed components // Parse and compile each component file for (const file of compFiles) { try { const { tagName, html, script, style } = await parseComponent(file); if (!parsedComponents.has(tagName)) { // Parse script to extract properties and methods const { properties, methods } = parseScript(script); // Generate class code const classCode = generateClassCode({ tagName, html, style, properties, methods, }); componentMap.set(tagName, classCode); parsedComponents.add(tagName); console.log(`🔍 Parsed and compiled component: <${tagName}> from ${path.relative(projectRoot, file)}`); } else { console.log(`ℹ️ Component <${tagName}> from ${path.relative(projectRoot, file)} has already been parsed.`); } } catch (error) { console.error(`❌ Failed to parse ${file}: ${error.message}`); } } if (componentMap.size === 0) { console.warn('⚠️ No components found to compile.'); } // ----------------------- // Step 2: Process Pages // ----------------------- // Find all .page.html files in the project directory const pageFiles = glob.sync('**/*.page.html', { cwd: projectRoot, absolute: true, ignore: ['node_modules/**', 'cat/**'] }); const routeMap = new Map(); // Map of route to page content for (const file of pageFiles) { try { const { route, content } = await parsePage(file); if (routeMap.has(route)) { console.warn(`⚠️ Duplicate route "${route}" found in ${path.relative(projectRoot, file)}. Overwriting previous route.`); } routeMap.set(route, content); console.log(`📄 Mapped route "${route}" to ${path.relative(projectRoot, file)}`); } catch (error) { console.error(`❌ Failed to parse page ${file}: ${error.message}`); } } if (routeMap.size === 0) { console.warn('⚠️ No pages found to map routes.'); } // ----------------------- // Step 3: Detect Used Components // ----------------------- // Find all .html files in the project directory for usage detection const htmlFiles = glob.sync('**/*.html', { cwd: projectRoot, absolute: true, ignore: ['node_modules/**', 'cat/**'] }); const htmlContents = []; for (const file of htmlFiles) { try { const content = await fs.readFile(file, 'utf-8'); htmlContents.push(content); } catch (error) { console.error(`❌ Failed to read HTML file ${file}: ${error.message}`); } } // Detect which components are used across all HTML files const availableComponents = new Set(componentMap.keys()); const usedComponents = detectUsedComponents(htmlContents, availableComponents); if (usedComponents.size === 0) { console.warn('⚠️ No used components found in HTML files.'); } else { console.log(`📦 Used components: ${[...usedComponents].join(', ')}`); } // ----------------------- // Step 4: Handle <load> Tags and Inject Page Content // ----------------------- // Detect all <load> routes in all HTML files const loadRoutes = detectLoadRoutes(htmlContents); // Prepare a map of route to page content // Verify that each load route exists in the routeMap loadRoutes.forEach(route => { if (!routeMap.has(route)) { console.error(`❌ No page found for route "${route}". Please ensure a .page.html file exists with route="${route}".`); } }); // Now, replace <load route="..."> tags in indexContent with the corresponding page content const loadTagRegex = /<load\s+[^>]*route=["']([^"']+)["'][^>]*>/gi; indexContent = indexContent.replace(loadTagRegex, (match, route) => { if (routeMap.has(route)) { console.log(`🔄 Injecting content for route "${route}"`); return routeMap.get(route); } else { console.warn(`⚠️ No content found for route "${route}". Keeping <load> tag.`); return match; // Keep the <load> tag if no content is found } }); // ----------------------- // Step 5: Generate Registration Script // ----------------------- const registrationScript = generateRegistrationScript( Array.from(usedComponents).reduce((map, tag) => map.set(tag, componentMap.get(tag)), new Map()) ); // ----------------------- // Step 6: Inject Registration Script // ----------------------- if (registrationScript.trim()) { // Inject the registration script before the closing </body> tag const scriptTag = `<script> ${registrationScript} </script> `; if (indexContent.includes('</body>')) { indexContent = indexContent.replace('</body>', `${scriptTag}</body>`); } else { // If no </body> tag, append the script at the end indexContent += `\n${scriptTag}`; } console.log('📝 Injected component registration scripts.'); } // ----------------------- // Step 7: Return Compiled Content // ----------------------- return indexContent; } module.exports = { compile }; - Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.