Follow the task requirements exactly, the compiled output must be exact, don't change anything and make sure of not breaking the other features of the compiler.
Avoid any type of .replace method, instead direct done manipulation based on the context, weather it's an attribute, text node, etc...
Stick to the defined task, don't lose the point.
javascript
// cat/src/compiler.js
const fs = require('fs-extra');
const path = require('path');
const glob = require('glob');
/**
* Parse a component file to extract tagName, HTML, script, and style sections.
* @param {string} filePath - Path to the .comp.html file.
* @returns {Promise<{ tagName: string, html: string, script: string, style: string }>} - Component details.
*/
async function parseComponent(filePath) {
const content = await fs.readFile(filePath, 'utf-8');
// Extract the outermost tag name
const tagRegex = /<\s*([\w-]+)(\s+[^>]*)?>/i;
const tagMatch = content.match(tagRegex);
if (!tagMatch) {
throw new Error(`No valid root tag found in ${path.basename(filePath)}`);
}
let tagName = tagMatch[1];
// Ensure the tag name contains a hyphen
if (!tagName.includes('-')) {
tagName = `${tagName}-cat`;
}
// Extract HTML content inside the root tag
const htmlRegex = new RegExp(`<${tagMatch[1]}[^>]*>([\\s\\S]*?)<\\/${tagMatch[1]}>`, 'i');
const htmlMatch = content.match(htmlRegex);
const htmlContent = htmlMatch ? htmlMatch[1].trim() : '';
// Extract <script> section
const scriptRegex = /<script[^>]*>([\s\S]*?)<\/script>/i;
const scriptMatch = content.match(scriptRegex);
const scriptContent = scriptMatch ? scriptMatch[1].trim() : '';
// Extract <style> section
const styleRegex = /<style[^>]*>([\s\S]*?)<\/style>/i;
const styleMatch = content.match(styleRegex);
const styleContent = styleMatch ? styleMatch[1].trim() : '';
return {
tagName,
html: htmlContent,
script: scriptContent,
style: styleContent
};
}
/**
* Escape backticks in templates to avoid breaking template literals.
* @param {string} str - The template string.
* @returns {string} - Escaped string.
*/
function escapeBackticks(str) {
return str.replace(/`/g, '\\`');
}
/**
* Generate the class name in PascalCase from a tag name.
* @param {string} tagName - The custom element tag name.
* @returns {string} - PascalCase class name.
*/
function toPascalCase(tagName) {
return tagName
.split('-')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join('');
}
/**
* 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/**'] // Adjust ignore patterns as needed
});
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)) {
console.log(`ℹ️ Component <${tagName}> from ${path.relative(projectRoot, file)} has already been parsed.`);
continue;
}
// Parse script to extract properties and methods
const properties = [];
const methods = [];
// Parse variable declarations
const variableRegex = /let\s+([\w$]+)\s*=\s*(.*?);/g;
let variableMatch;
while ((variableMatch = variableRegex.exec(script)) !== null) {
const varName = variableMatch[1];
const varValue = variableMatch[2].trim();
properties.push({ name: varName, value: varValue });
}
// Parse function declarations
const functionRegex = /function\s+([\w$]+)\s*\(([^)]*)\)\s*\{([\s\S]*?)\n?\}/g;
let functionMatch;
while ((functionMatch = functionRegex.exec(script)) !== null) {
const funcName = functionMatch[1];
const funcParams = functionMatch[2];
const funcBody = functionMatch[3];
methods.push({ name: funcName, params: funcParams, body: funcBody.trim() });
}
// Generate class code
const className = toPascalCase(tagName);
let classCode = `class ${className} extends HTMLElement {
constructor() {
super();
`;
// Initialize properties
properties.forEach(prop => {
classCode += ` this._${prop.name} = ${prop.value};\n`;
});
classCode += `
this.attachShadow({ mode: 'open' });
this._buildDOM();
}
_buildDOM() {
const fragment = document.createDocumentFragment();
`;
// Add styles
if (style) {
classCode += ` const style = document.createElement('style');
style.textContent = \`
${escapeBackticks(style)}
\`;
fragment.appendChild(style);
`;
}
// Generate DOM code
const { domCode, bindings, eventListeners } = generateDOMCode(html);
classCode += domCode;
classCode += `
this.shadowRoot.appendChild(fragment);
}
connectedCallback() {
`;
// Attach event listeners
eventListeners.forEach(listener => {
classCode += ` this.${listener.elementVar}.addEventListener('${listener.eventType}', this.${listener.handlerName}.bind(this));
`;
});
classCode += ` }
disconnectedCallback() {
`;
// Remove event listeners
eventListeners.forEach(listener => {
classCode += ` this.${listener.elementVar}.removeEventListener('${listener.eventType}', this.${listener.handlerName}.bind(this));
`;
});
classCode += ` }
`;
// Generate getters and setters
properties.forEach(prop => {
classCode += `
get ${prop.name}() { return this._${prop.name}; }
set ${prop.name}(value) {
if (this._${prop.name} !== value) {
this._${prop.name} = value;
`;
// Update bindings
if (bindings[prop.name]) {
bindings[prop.name].forEach(binding => {
if (binding.type === 'text') {
classCode += ` this.${binding.nodeVar}.textContent = ${binding.expression.replace(/\bthis\._${prop.name}\b/g, 'value')};
`;
} else if (binding.type === 'attribute') {
classCode += ` this.${binding.nodeVar}.setAttribute('${binding.attrName}', ${binding.expression.replace(/\bthis\._${prop.name}\b/g, 'value')});
`;
}
});
}
classCode += ` }
}
`;
});
// Add methods
methods.forEach(method => {
classCode += `
${method.name}(${method.params}) {
${method.body.split('\n').map(line => ' ' + line).join('\n')}
}
`;
});
classCode += `}
customElements.define('${tagName}', ${className});
`;
// Store the compiled class code
componentMap.set(tagName, classCode);
parsedComponents.add(tagName);
console.log(`🔍 Parsed and compiled component: <${tagName}> from ${path.relative(projectRoot, file)}`);
} catch (error) {
console.error(`❌ Failed to parse ${file}: ${error.message}`);
}
}
if (componentMap.size === 0) {
console.warn('⚠️ No components found to compile.');
}
// -----------------------
// Step 2: 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 3: Generate Registration Script
// -----------------------
const registrationScript = generateRegistrationScript(
Array.from(usedComponents).reduce((map, tag) => map.set(tag, componentMap.get(tag)), new Map())
);
// -----------------------
// Step 4: 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 5: Handle <load> Tags and Inject Page Content
// -----------------------
// Find and replace <load route="..."> tags with corresponding page content
const loadTagRegex = /<load\s+[^>]*route=["']([^"']+)["'][^>]*>/gi;
// Process <load> tags in the index.html
indexContent = indexContent.replace(loadTagRegex, (match, route) => {
// Path to the page content
const pageFilePath = path.join(projectRoot, `${route}.page.html`);
if (fs.existsSync(pageFilePath)) {
const pageContent = fs.readFileSync(pageFilePath, 'utf-8');
console.log(`🔄 Injected content for route "${route}"`);
return pageContent;
} else {
console.error(`❌ No page found for route "${route}".`);
return match; // Keep the <load> tag if no content is found
}
});
// -----------------------
// Step 6: Return Compiled Content
// -----------------------
return indexContent;
}
/**
* 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 tag doesn't contain '-', append '-cat'
if (!tag.includes('-')) {
tag = `${tag}-cat`;
}
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, tagName) => {
script += `
${classCode}
`;
});
return script;
}
/**
* Generate DOM creation code from HTML and collect bindings.
* @param {string} html - The inner HTML string of the component.
* @returns {{ domCode: string, bindings: object, eventListeners: Array }} - JavaScript code for building the DOM, property bindings, and event listeners.
*/
function generateDOMCode(html) {
const tree = parseHTML(html);
let code = '';
const nodeReferences = {}; // Map from variable names to nodes
let variableCounter = {}; // For unique variable names
const bindings = {}; // propertyName => array of bindings
const eventListeners = []; // Array of event listener info
function traverse(node, parentVarName) {
if (node.type === 'element') {
const varName = generateVarName(node.tagName);
code += ` this.${varName} = document.createElement('${node.tagName}');
`;
// Set attributes
for (let [attrName, attrValue] of Object.entries(node.attributes)) {
if (attrName.startsWith('on')) {
// Event listener
const eventType = attrName.slice(2);
const handlerMatch = attrValue.match(/^([a-zA-Z_][\w$]*)\((.*)\)$/);
let handlerName = attrValue;
if (handlerMatch) {
handlerName = handlerMatch[1];
}
eventListeners.push({ elementVar: varName, eventType, handlerName });
} else {
const exprRegex = /\{([\w$]+)\}/g;
if (exprRegex.test(attrValue)) {
let replacedValue = attrValue.replace(exprRegex, '${this._$1}');
code += ` this.${varName}.setAttribute('${attrName}', \`${escapeBackticks(replacedValue)}\`);
`;
// Record bindings for each property
let match;
while ((match = exprRegex.exec(attrValue)) !== null) {
const propName = match[1];
bindings[propName] = bindings[propName] || [];
bindings[propName].push({
type: 'attribute',
nodeVar: varName,
attrName,
expression: `\`${escapeBackticks(replacedValue)}\``
});
}
} else {
code += ` this.${varName}.setAttribute('${attrName}', \`${escapeBackticks(attrValue)}\`);
`;
}
}
}
if (parentVarName) {
code += ` this.${parentVarName}.appendChild(this.${varName});
`;
} else {
code += ` fragment.appendChild(this.${varName});
`;
}
// Traverse children
if (node.children && node.children.length > 0) {
node.children.forEach(childNode => {
traverse(childNode, varName);
});
}
} else if (node.type === 'text') {
const exprRegex = /\{([\w$]+)\}/g;
if (exprRegex.test(node.content)) {
let replacedText = node.content.replace(exprRegex, '${this._$1}');
const textNodeVar = generateVarName('textNode');
code += ` this.${textNodeVar} = document.createTextNode(\`${escapeBackticks(replacedText)}\`);
this.${parentVarName}.appendChild(this.${textNodeVar});
`;
// Record bindings for each property
let match;
while ((match = exprRegex.exec(node.content)) !== null) {
const propName = match[1];
bindings[propName] = bindings[propName] || [];
bindings[propName].push({
type: 'text',
nodeVar: textNodeVar,
expression: `\`${escapeBackticks(replacedText)}\``
});
}
} else {
code += ` this.${parentVarName}.appendChild(document.createTextNode(\`${escapeBackticks(node.content)}\`));
`;
}
}
}
// Start traversal from root
tree.children.forEach(node => {
traverse(node, null);
});
return { domCode: code, bindings, eventListeners };
}
/**
* Simple HTML parser to convert HTML string into a DOM-like tree structure.
* @param {string} html - The HTML string to parse.
* @returns {object} - The parsed tree.
*/
function parseHTML(html) {
let index = 0;
let root = { type: 'root', children: [] };
let currentParent = root;
const stack = [root];
const tagRegex = /<\/?[^>]+>/g;
let lastIndex = 0;
let match;
while ((match = tagRegex.exec(html)) !== null) {
if (match.index > lastIndex) {
// Text node between last tag and this tag
const textContent = html.slice(lastIndex, match.index).trim();
if (textContent) {
currentParent.children.push({ type: 'text', content: textContent });
}
}
const tagString = match[0];
if (tagString.startsWith('</')) {
// Closing tag
const tagNameMatch = tagString.match(/^<\/\s*([\w-]+)/);
if (tagNameMatch) {
const tagName = tagNameMatch[1];
if (currentParent.tagName === tagName) {
stack.pop();
currentParent = stack[stack.length - 1];
} else {
// Mismatched tag, error
throw new Error(`Mismatched closing tag: ${tagString}`);
}
}
} else {
// Opening tag or self-closing tag
const isSelfClosing = tagString.endsWith('/>');
const tagNameMatch = tagString.match(/^<\s*([\w-]+)/);
if (tagNameMatch) {
const tagName = tagNameMatch[1];
const attributes = {};
const attrRegex = /([\w:-]+)=["']([^"']+)["']/g;
let attrMatch;
while ((attrMatch = attrRegex.exec(tagString)) !== null) {
attributes[attrMatch[1]] = attrMatch[2];
}
const elementNode = { type: 'element', tagName, attributes, children: [] };
currentParent.children.push(elementNode);
if (!isSelfClosing && !tagString.endsWith('/>')) {
// Not self-closing, push to stack
stack.push(elementNode);
currentParent = elementNode;
}
}
}
lastIndex = tagRegex.lastIndex;
}
// Remaining text after the last tag
if (lastIndex < html.length) {
const textContent = html.slice(lastIndex).trim();
if (textContent) {
currentParent.children.push({ type: 'text', content: textContent });
}
}
return root;
}
/**
* Generate a unique variable name based on the tag name.
* @param {string} tagName - The tag name of the element.
* @returns {string} - A unique variable name.
*/
function generateVarName(tagName) {
// Simple counter-based variable name generation
if (!generateVarName.counter) {
generateVarName.counter = {};
}
if (!generateVarName.counter[tagName]) {
generateVarName.counter[tagName] = 1;
} else {
generateVarName.counter[tagName]++;
}
return `${tagName.replace(/-/g, '_')}_${generateVarName.counter[tagName]}`;
}
module.exports = { compile };