// 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
};
}
/**
* Identify reactive expressions within a string.
* @param {string} str - The string to search for expressions.
* @returns {Array<string>} - Array of expression names.
*/
function identifyExpressions(str) {
const exprRegex = /\{([\w$]+)\}/g;
const expressions = [];
let match;
while ((match = exprRegex.exec(str)) !== null) {
expressions.push(match[1]);
}
return expressions;
}
/**
* 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('');
}
/**
* 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 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}
customElements.define('${tagName}', ${toPascalCase(tagName)});
`;
});
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/**'] // 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;
}
// Identify expressions in HTML
const expressions = identifyExpressions(html);
// Parse script to extract properties and methods
const scriptLines = script.split('\n').map(line => line.trim()).filter(line => line);
const properties = [];
const methods = [];
scriptLines.forEach(line => {
// Match variable declarations: let name = 'value';
const varMatch = line.match(/^let\s+([\w$]+)\s*=\s*['"`](.*)['"`];?$/);
if (varMatch) {
properties.push({ name: varMatch[1], value: varMatch[2] });
return;
}
// Match function declarations: function funcName() { ... }
const funcMatch = line.match(/^function\s+([\w$]+)\s*\(([^)]*)\)\s*\{([\s\S]*)\}$/);
if (funcMatch) {
const [, funcName, params, body] = funcMatch;
methods.push({ name: funcName, params, body });
return;
}
});
// Generate class code
const className = toPascalCase(tagName);
let classCode = `class ${className} extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
`;
// Initialize properties
properties.forEach(prop => {
classCode += ` this._${prop.name} = \`${escapeBackticks(prop.value)}\`;\n`;
});
// Build DOM
classCode += `
this._buildDOM();
}
_buildDOM() {
const fragment = document.createDocumentFragment();
`;
// Add styles
if (style) {
classCode += ` const style = document.createElement('style');
style.textContent = \`
${escapeBackticks(style)}
\`;
fragment.appendChild(style);
`;
}
// Parse HTML and generate DOM creation code
const domCode = generateDOMCode(html);
classCode += domCode;
classCode += `
this.shadowRoot.appendChild(fragment);
}
connectedCallback() {
`;
// Attach event listeners
methods.forEach(method => {
// Find event listeners in the DOM (e.g., onclick="methodName")
// This implementation assumes that event listeners are specified with standard DOM event attributes
// e.g., onclick="handleClick"
// Extract all elements with event attributes and attach listeners
});
// Attach event listeners based on methods
// For simplicity, we'll parse the methods and assume that event listeners are defined in the HTML with attributes like onclick="methodName"
// This requires that during DOM generation, we store references to elements that have event listeners
// Assuming that _eventListeners is an array of { element: reference, event: 'click', handler: 'methodName' }
// We'll have to implement this during DOM generation
// For this implementation, let's assume that event listeners are already attached during _buildDOM
// Alternatively, you can enhance the DOM generation to collect event listeners and attach them here
classCode += ` }
disconnectedCallback() {
// Clean up event listeners if necessary
}
`;
// Generate getters and setters for properties
properties.forEach(prop => {
// Getter
classCode += ` get ${prop.name}() {
return this._${prop.name};
}
set ${prop.name}(value) {
if (this._${prop.name} !== value) {
this._${prop.name} = value;
this._update${toPascalCase(prop.name)}();
}
}
`;
// Update method
classCode += ` _update${toPascalCase(prop.name)}() {
if (this._${prop.name}Node) {
this._${prop.name}Node.textContent = \`${escapeBackticks('{')}${prop.name}${escapeBackticks('}')}\`.replace('{${prop.name}}', this._${prop.name});
}
if (this._${prop.name}Attr) {
this._${prop.name}Attr.value = this._${prop.name};
}
}
`;
});
// Add methods
methods.forEach(method => {
classCode += ` ${method.name}(${method.params}) {
${method.body.split('\n').map(line => ' ' + line).join('\n')}
}
`;
});
classCode += `}\n`;
// 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 DOM creation code from HTML.
* This is a simplistic parser and may need enhancements for complex HTML structures.
* @param {string} html - The inner HTML string of the component.
* @returns {string} - JavaScript code for building the DOM.
*/
function generateDOMCode(html) {
// This function parses the HTML and generates JavaScript code using document.createElement
// For demonstration purposes, this is a rudimentary parser and may not handle all HTML features.
// For a more robust solution, consider using an HTML parser library.
// Split the HTML into lines and parse manually
const lines = html.split('\n').map(line => line.trim()).filter(line => line);
let code = '';
// Stack to manage element hierarchy
const stack = [];
lines.forEach(line => {
const openingTagMatch = line.match(/^<([a-zA-Z][\w-]*)([^>]*)>/);
const closingTagMatch = line.match(/^<\/([a-zA-Z][\w-]*)>/);
const selfClosingTagMatch = line.match(/^<([a-zA-Z][\w-]*)([^>]*)\/>/);
if (selfClosingTagMatch) {
const [ , tagName, attrs ] = selfClosingTagMatch;
const varName = generateVarName(tagName);
code += ` const ${varName} = document.createElement('${tagName}');\n`;
// Handle attributes
const attrRegex = /([a-zA-Z-:]+)="([^"]+)"/g;
let attrMatch;
while ((attrMatch = attrRegex.exec(attrs)) !== null) {
const [ , attrName, attrValue ] = attrMatch;
if (attrName.startsWith('on')) {
// Event listener
const event = attrName.substring(2);
const handlerMatch = attrValue.match(/^([a-zA-Z][\w$]*)\((.*)\)$/);
if (handlerMatch) {
const handlerName = handlerMatch[1];
const handlerArgs = handlerMatch[2];
code += ` ${varName}.addEventListener('${event}', this.${handlerName}.bind(this));\n`;
} else {
code += ` ${varName}.addEventListener('${event}', this.${attrValue}.bind(this));\n`;
}
} else {
// Check for reactive expressions in attributes
const exprMatch = attrValue.match(/^\{([\w$]+)\}$/);
if (exprMatch) {
const exprName = exprMatch[1];
code += ` this._${exprName}Attr = ${varName}.setAttribute('${attrName}', \`\${this.${exprName}}\`);\n`;
} else {
code += ` ${varName}.setAttribute('${attrName}', \`${escapeBackticks(attrValue)}\`);\n`;
}
}
}
stack[stack.length - 1].appendChild(varName);
stack.push({ tagName, varName });
stack.pop(); // Self-closing tag, no need to keep in stack
code += ` ${stack[stack.length - 1].varName}.appendChild(${varName});\n`;
} else if (openingTagMatch) {
const [ , tagName, attrs ] = openingTagMatch;
const varName = generateVarName(tagName);
code += ` const ${varName} = document.createElement('${tagName}');\n`;
// Handle attributes
const attrRegex = /([a-zA-Z-:]+)="([^"]+)"/g;
let attrMatch;
while ((attrMatch = attrRegex.exec(attrs)) !== null) {
const [ , attrName, attrValue ] = attrMatch;
if (attrName.startsWith('on')) {
// Event listener
const event = attrName.substring(2);
const handlerMatch = attrValue.match(/^([a-zA-Z][\w$]*)\((.*)\)$/);
if (handlerMatch) {
const handlerName = handlerMatch[1];
const handlerArgs = handlerMatch[2];
code += ` ${varName}.addEventListener('${event}', this.${handlerName}.bind(this));\n`;
} else {
code += ` ${varName}.addEventListener('${event}', this.${attrValue}.bind(this));\n`;
}
} else {
// Check for reactive expressions in attributes
const exprMatch = attrValue.match(/^\{([\w$]+)\}$/);
if (exprMatch) {
const exprName = exprMatch[1];
code += ` this._${exprName}Attr = ${varName}.setAttribute('${attrName}', \`\${this.${exprName}}\`);\n`;
} else {
code += ` ${varName}.setAttribute('${attrName}', \`${escapeBackticks(attrValue)}\`);\n`;
}
}
}
// Handle text content or child elements
// This simplistic parser assumes that text nodes come immediately after the opening tag
// For complex HTML structures, consider using a proper HTML parser
const textMatch = line.match(/^<[\w-]+[^>]*>\s*(.*?)\s*$/);
if (textMatch && textMatch[1]) {
const textContent = textMatch[1];
// Check for reactive expressions in text
const exprMatch = textContent.match(/^\{([\w$]+)\}$/);
if (exprMatch) {
const exprName = exprMatch[1];
code += ` this._${exprName}Node = document.createTextNode(\`\${this.${exprName}}\`);\n`;
code += ` ${varName}.appendChild(this._${exprName}Node);\n`;
} else {
code += ` ${varName}.textContent = \`${escapeBackticks(textContent)}\`;\n`;
}
}
// Append to parent
if (stack.length === 0) {
code += ` fragment.appendChild(${varName});\n`;
} else {
code += ` ${stack[stack.length - 1].varName}.appendChild(${varName});\n`;
}
// Push to stack
stack.push({ tagName, varName });
} else if (closingTagMatch) {
// Pop the last element from the stack
stack.pop();
} else {
// Handle text nodes outside of tags
const textContent = line;
// Check for reactive expressions in text
const exprMatch = textContent.match(/^\{([\w$]+)\}$/);
if (exprMatch) {
const exprName = exprMatch[1];
const varName = generateVarName('text');
code += ` const ${varName} = document.createTextNode(\`\${this.${exprName}}\`);\n`;
code += ` this._${exprName}Node = ${varName};\n`;
if (stack.length === 0) {
code += ` fragment.appendChild(${varName});\n`;
} else {
code += ` ${stack[stack.length - 1].varName}.appendChild(${varName});\n`;
}
} else {
code += ` const textNode = document.createTextNode(\`${escapeBackticks(textContent)}\`);\n`;
if (stack.length === 0) {
code += ` fragment.appendChild(textNode);\n`;
} else {
code += ` ${stack[stack.length - 1].varName}.appendChild(textNode);\n`;
}
}
}
});
return code;
}
/**
* 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 };
Sure! Let's create a sample component named <live-greeting> that includes:
- An
<input> element where users can type their name.
- An
<h1> element that dynamically updates to greet the user based on the input.
- An event listener attached to the
<input> to handle real-time updates.
We'll follow the Cat framework syntax provided and focus on implementing the getters and setters to handle the reactive {expression}.
Component Definition
live-greeting.comp.html
<live-greeting>
<input type="text" placeholder="Enter your name" oninput="updateName(event)" />
<h1>Hello, {name}!</h1>
</live-greeting>
<script>
let name = 'Guest';
function updateName(event) {
name = event.target.value || 'Guest';
}
</script>
<style>
input {
padding: 8px;
font-size: 16px;
}
h1 {
color: #333;
}
</style>
Explanation:
-
HTML Structure:
<input>: Captures user input. The oninput attribute attaches an event listener that triggers the updateName function whenever the input value changes.
<h1>: Displays a greeting message that includes the {name} expression, which should update based on the user's input.
-
Script Section:
- State Variable:
let name = 'Guest'; initializes the name variable with a default value.
- Event Handler: The
updateName function updates the name variable based on the input's current value. If the input is empty, it defaults back to 'Guest'.
-
Style Section:
- Basic styling for the input and heading to enhance the appearance.
Compiled Component
The Cat compiler processes the .comp.html file and generates a JavaScript class that extends HTMLElement. This compiled version includes getters and setters for reactive expressions and attaches event listeners as defined.
LiveGreeting.js
class LiveGreeting extends HTMLElement {
constructor() {
super();
this._name = 'Guest';
// Attach Shadow DOM
this.attachShadow({ mode: 'open' });
this._buildDOM();
}
_buildDOM() {
const fragment = document.createDocumentFragment();
// Create and append styles
const style = document.createElement('style');
style.textContent = `
input {
padding: 8px;
font-size: 16px;
}
h1 {
color: #333;
}
`;
fragment.appendChild(style);
// Create input element
this._input = document.createElement('input');
this._input.setAttribute('type', 'text');
this._input.setAttribute('placeholder', 'Enter your name');
this._input.addEventListener('input', this.updateName.bind(this));
fragment.appendChild(this._input);
// Create h1 element
this._h1 = document.createElement('h1');
this._h1.textContent = `Hello, ${this._name}!`;
fragment.appendChild(this._h1);
this.shadowRoot.appendChild(fragment);
}
connectedCallback() {
// Any additional setup when the element is added to the DOM
}
disconnectedCallback() {
// Clean up event listeners if necessary
this._input.removeEventListener('input', this.updateName.bind(this));
}
// Getter for 'name'
get name() {
return this._name;
}
// Setter for 'name'
set name(value) {
if (this._name !== value) {
this._name = value;
this._updateGreeting();
}
}
// Method to update the 'name' based on input
updateName(event) {
this.name = event.target.value || 'Guest';
}
// Method to update the greeting in the DOM
_updateGreeting() {
this._h1.textContent = `Hello, ${this._name}!`;
}
}
// Define the custom element
customElements.define('live-greeting', LiveGreeting);
Explanation:
-
Class Definition:
LiveGreeting extends HTMLElement, making it a custom web component.
- The constructor initializes the
_name property and attaches the Shadow DOM.
-
Building the DOM:
- The
_buildDOM method creates and appends the necessary elements (<input> and <h1>) and includes the styles.
- Event listeners are attached to handle user interactions.
-
Lifecycle Hooks:
connectedCallback: Invoked when the component is added to the DOM. Placeholder for additional setups if needed.
disconnectedCallback: Cleans up event listeners to prevent memory leaks.
-
Getters and Setters:
- Getter (
get name): Returns the current value of _name.
- Setter (
set name): Updates the _name property and calls _updateGreeting to reflect changes in the DOM.
- This ensures that any change to the
name property automatically updates the <h1> element.
-
Event Handling:
updateName: Bound to the input event of the <input> element. It updates the name property based on user input.
_updateGreeting: Updates the text content of the <h1> element to display the latest greeting.
-
Custom Element Registration:
customElements.define('live-greeting', LiveGreeting); registers the <live-greeting> tag with the browser.
Usage
Once compiled, you can use the <live-greeting> component in your HTML as follows:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Live Greeting Example</title>
</head>
<body>
<live-greeting></live-greeting>
<!-- Include the compiled component script -->
<script src="./path-to-compiled/LiveGreeting.js"></script>
</body>
</html>
How It Works:
-
Initial Load:
- The component displays an input field with the placeholder "Enter your name".
- The
<h1> element shows "Hello, Guest!".
-
User Interaction:
- As the user types into the input field, the
oninput event triggers the updateName method.
- The
name property's setter updates the _name value.
- The setter calls
_updateGreeting, which updates the <h1> element with the new greeting.
-
Reactive Updates:
- Thanks to the getters and setters, any change to the
name property automatically reflects in the DOM without manual intervention.
Summary
This sample demonstrates how to:
This approach ensures a clean separation of concerns, efficient DOM updates, and an intuitive development experience.