To implement the new feature of passing data through attributes using the reserved prop object and injecting a console log for debugging, we'll update two primary files: scripter.js and component.js. These updates will allow the compiler to detect prop.key usages within both the script and HTML sections of components, and inject a console log displaying the collected keys.
Below are the fully updated versions of the affected files:
cat\src\scripter.js
// cat/src/scripter.js
const acorn = require('acorn'); // Import Acorn for JavaScript parsing
const { parseDocument } = require('htmlparser2');
/**
* Parse the script content to extract properties, methods, and propKeys.
* @param {string} script - The script content.
* @returns {{ properties: Array, methods: Array, propKeys: Set }} - Parsed properties, methods, and propKeys.
*/
function parseScript(script) {
const properties = [];
const methods = [];
const propKeys = new Set();
try {
// Parse the script content into an AST
const ast = acorn.parse(script, { ecmaVersion: 2020, locations: true });
// Recursive function to traverse the AST
function traverse(node, visitor) {
if (Array.isArray(node)) {
node.forEach(child => traverse(child, visitor));
} else if (node && typeof node.type === 'string') {
visitor(node);
for (let key in node) {
if (key === 'parent') continue; // Avoid circular references
const child = node[key];
if (Array.isArray(child)) {
traverse(child, visitor);
} else if (child && typeof child.type === 'string') {
traverse(child, visitor);
}
}
}
}
traverse(ast, node => {
if (node.type === 'VariableDeclaration') {
node.declarations.forEach(declarator => {
if (declarator.id.type === 'Identifier') {
const varName = declarator.id.name;
const varValue = declarator.init
? script.substring(declarator.init.start, declarator.init.end)
: 'undefined';
properties.push({ name: varName, value: varValue });
}
});
} else if (node.type === 'FunctionDeclaration') {
const funcName = node.id.name;
const params = node.params.map(param => {
if (param.type === 'Identifier') {
return param.name;
} else {
return '...args';
}
}).join(', ');
const body = script.substring(node.body.start, node.body.end);
methods.push({ name: funcName, params, body });
} else if (
node.type === 'MemberExpression' &&
node.object.type === 'Identifier' &&
node.object.name === 'prop' &&
node.property.type === 'Identifier'
) {
propKeys.add(node.property.name);
}
});
} catch (error) {
console.error(`Error parsing script: ${error.message}`);
}
return { properties, methods, propKeys };
}
/**
* Transform method body to replace variable references with 'this.' prefix.
* @param {string} body - The method body.
* @param {Array<string>} propNames - The property names to replace.
* @returns {string} - The transformed method body.
*/
function transformMethodBody(body, propNames) {
let transformedBody = body;
propNames.forEach(propName => {
// Replace assignments like 'propName = value;' with 'this.propName = value;'
const assignRegex = new RegExp(`([^\\.\\w$])${propName}\\s*=`, 'g');
transformedBody = transformedBody.replace(assignRegex, `$1this.${propName} =`);
// Replace variable references with 'this.propName'
const varRegex = new RegExp(`([^\\.\\w$])${propName}([^\\w$])`, 'g');
transformedBody = transformedBody.replace(varRegex, `$1this.${propName}$2`);
});
// Ensure braces are correctly balanced and formatted
transformedBody = transformedBody.trim();
// Remove extra outer braces if they exist
if (transformedBody.startsWith('{') && transformedBody.endsWith('}')) {
transformedBody = transformedBody.slice(1, -1).trim();
}
// Properly indent the method body
transformedBody = transformedBody
.split('\n')
.map(line => ' ' + line.trim())
.join('\n');
return transformedBody;
}
/**
* Sanitize a string to be a valid JavaScript variable name.
* @param {string} name - The original name.
* @returns {string} - The sanitized name.
*/
function sanitizeVarName(name) {
// Replace invalid characters with underscores
return name.replace(/[^a-zA-Z0-9_$]/g, '_');
}
/**
* Generate DOM creation code from HTML using htmlparser2.
* @param {string} html - The inner HTML string of the component or page.
* @returns {object} - Object containing generated code, cached nodes, event listeners, and propKeys.
*/
function generateDOMCode(html) {
const dom = parseDocument(html).children; // Array of DOM nodes
let code = '';
let varCounter = 0;
const cachedNodes = {}; // For properties to nodes
const eventListeners = [];
const propKeys = new Set();
function traverse(node, parentVarName) {
if (node.type === 'tag') {
const safeName = sanitizeVarName(node.name);
const varName = safeName + ++varCounter;
// Decide whether to assign to 'this.' or 'const'
let declaration;
if (needsReference(node)) {
declaration = `this.${varName}`;
} else {
declaration = `const ${varName}`;
}
const varReference = declaration.replace(/^const /, '');
if (node.name === 'router') {
// Handle router tag
const nameAttr = node.attribs.name;
code += ` ${declaration} = document.createElement('div');
${varReference}.id = '${nameAttr}';
`;
} else {
code += ` ${declaration} = document.createElement('${node.name}');
`;
}
// Handle attributes
const attribs = node.attribs || {};
for (let [attrName, attrValue] of Object.entries(attribs)) {
if (
attrName === 'class' ||
attrName === 'style' ||
attrName.startsWith('data-') ||
attrName === 'id' ||
attrName === 'src' ||
attrName === 'alt'
) {
// Handle attributes with embedded expressions
const { expression, propNames: exprPropNames } = generateAttributeExpression(attrValue);
code += ` ${varReference}.setAttribute('${attrName}', ${expression});
`;
// Collect propKeys
exprPropNames.forEach(propName => {
propKeys.add(propName);
if (!cachedNodes[propName]) cachedNodes[propName] = [];
cachedNodes[propName].push({
type: 'attribute',
elementVarName: varReference.replace(/^this\./, ''),
attrName: attrName,
expression: `${expression}`,
});
});
} else if (attrName.startsWith('on')) {
// Event listener
const event = attrName.substring(2);
const handlerName = attrValue.replace(/$$$/, '').trim();
eventListeners.push({ elementVarName: varReference.replace(/^this\./, ''), event, handlerName });
} else if (node.name !== 'router' || attrName !== 'name') {
// For other attributes, excluding 'name' attribute of router
code += ` ${varReference}.setAttribute('${attrName}', '${attrValue}');
`;
}
}
// Append to parent
const parentRef = parentVarName ? parentVarName : 'fragment';
code += ` ${parentRef}.appendChild(${varReference});
`;
// Traverse children
if (node.children && node.children.length) {
for (let child of node.children) {
traverse(child, varReference);
}
}
} else if (node.type === 'text') {
const textContent = node.data;
if (textContent.trim()) {
// Handle text nodes with expressions
const { expression, propNames: exprPropNames } = generateTextExpression(textContent);
const varName = 'textNode' + ++varCounter;
// Decide whether to assign to 'this.' or 'const'
let declaration;
if (expression.includes('this.prop.')) {
declaration = `this.${varName}`;
} else {
declaration = `const ${varName}`;
}
const varReference = declaration.replace(/^const /, '');
code += ` ${declaration} = document.createTextNode(${expression});
`;
code += ` ${parentVarName}.appendChild(${varReference});
`;
// Collect propKeys
exprPropNames.forEach(propName => {
propKeys.add(propName);
if (!cachedNodes[propName]) cachedNodes[propName] = [];
cachedNodes[propName].push({
type: 'text',
varName: varReference.replace(/^this\./, ''),
expression: `${expression}`,
});
});
}
}
}
function needsReference(node) {
// Determines if the element needs to be assigned to 'this.'
// Elements that are:
// - Targets of event listeners
// - Contain reactive expressions
// Need to be accessible outside of _buildDOM
if (node.attribs) {
const hasEventListener = Object.keys(node.attribs).some(attr => attr.startsWith('on'));
const hasReactiveAttr = Object.values(node.attribs).some(value => /\{([\w$]+)\}/.test(value));
if (hasEventListener || hasReactiveAttr) {
return true;
}
}
if (node.children && node.children.some(child => child.type === 'text' && /\{([\w$]+)\}/.test(child.data))) {
return true;
}
return false;
}
function generateTextExpression(textContent) {
const exprRegex = /\{([\w$]+)\}/g;
let segments = [];
let propNames = [];
let lastIndex = 0;
let match;
while ((match = exprRegex.exec(textContent)) !== null) {
if (match.index > lastIndex) {
segments.push(JSON.stringify(textContent.slice(lastIndex, match.index)));
}
segments.push(`this.prop.${match[1]}`);
propNames.push(match[1]);
lastIndex = exprRegex.lastIndex;
}
if (lastIndex < textContent.length) {
segments.push(JSON.stringify(textContent.slice(lastIndex)));
}
return {
expression: segments.join(' + '),
propNames,
};
}
function generateAttributeExpression(attrValue) {
const exprRegex = /\{([\w$]+)\}/g;
let segments = [];
let propNames = [];
let lastIndex = 0;
let match;
while ((match = exprRegex.exec(attrValue)) !== null) {
if (match.index > lastIndex) {
segments.push(JSON.stringify(attrValue.slice(lastIndex, match.index)));
}
segments.push(`this.prop.${match[1]}`);
propNames.push(match[1]);
lastIndex = exprRegex.lastIndex;
}
if (lastIndex < attrValue.length) {
segments.push(JSON.stringify(attrValue.slice(lastIndex)));
}
return {
expression: segments.join(' + '),
propNames,
};
}
dom.forEach(node => traverse(node, null));
return { code, cachedNodes, eventListeners, propKeys };
}
/**
* Convert a kebab-case or other tag name to PascalCase for class naming.
* @param {string} tagName - The custom element tag name.
* @returns {string} - PascalCase string.
*/
function toPascalCase(tagName) {
return tagName
.split('-')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join('');
}
/**
* Generate the class code for the component.
* @param {object} component - Component details.
* @returns {string} - The compiled class code.
*/
function generateComponentClassCode({
tagName,
html,
style,
properties,
methods,
scriptPropKeys,
}) {
const className = toPascalCase(tagName);
// Generate DOM code
const { code: domCode, cachedNodes, eventListeners, propKeys: domPropKeys } = generateDOMCode(html);
// Combine propKeys from script and DOM
const combinedPropKeys = new Set([...scriptPropKeys, ...domPropKeys]);
// Assemble the full class code
let classCode = `class ${className} extends HTMLElement {
${generateClassBodyCode({
properties,
methods,
domCode,
cachedNodes,
eventListeners,
propKeys: combinedPropKeys,
isComponent: true, // Components are custom elements
parentClass: 'HTMLElement', // Components extend HTMLElement
tagName, // Pass tagName for console.log
})}
}
customElements.define('${tagName}', ${className});
`;
return classCode;
}
/**
* Generate the class body code for components and pages.
* @param {object} options - Options for class body generation.
* @param {Array} options.properties - Properties extracted from script.
* @param {Array} options.methods - Methods extracted from script.
* @param {string} options.domCode - DOM creation code from HTML.
* @param {object} options.cachedNodes - Nodes cached for property updates.
* @param {Array} options.eventListeners - Event listeners to attach.
* @param {Set} options.propKeys - Set of prop keys used.
* @param {boolean} options.isComponent - Whether it's a component.
* @param {string} options.parentClass - The parent class name.
* @param {string} options.tagName - The tagName of the component.
* @returns {string} - The class body code.
*/
function generateClassBodyCode({ properties, methods, domCode, cachedNodes, eventListeners, propKeys, isComponent, parentClass, tagName }) {
let classBody = '';
// Constructor
classBody += ` constructor() {
`;
// Include super() call if there is a parent class
if (parentClass) {
classBody += `super();
`;
}
// Initialize properties
properties.forEach(prop => {
classBody += ` this._${prop.name} = ${prop.value};
`;
});
// Initialize prop object
if (propKeys.size > 0) {
classBody += `
this.prop = {};
`;
propKeys.forEach(key => {
classBody += ` this.prop.${key} = this.getAttribute('${key}') || '';
`;
}
// Inject console.log for prop keys
classBody += `
console.log('Component <${tagName}> props:', this.prop);
`;
}
// For components, do not build DOM in constructor
if (!isComponent) {
// For pages, build DOM in constructor
classBody += `
this._buildDOM();
`;
}
classBody += ` }
_buildDOM() {
const fragment = document.createDocumentFragment();
`;
// Include DOM creation code
classBody += domCode;
if (isComponent) {
classBody += `
this._fragment = fragment;
}
`;
} else {
classBody += `
this.rootElement = fragment;
}
`;
}
// connectedCallback
classBody += `
connectedCallback() {
`;
if (isComponent) {
classBody += ` this._buildDOM();
this.appendChild(this._fragment);
`;
}
// Attach event listeners
if (eventListeners && eventListeners.length > 0) {
eventListeners.forEach(listener => {
classBody += ` this.${listener.elementVarName}.addEventListener('${listener.event}', this.${listener.handlerName}.bind(this));
`;
});
}
classBody += ` }
disconnectedCallback() {
`;
// Remove event listeners
if (eventListeners && eventListeners.length > 0) {
eventListeners.forEach(listener => {
classBody += ` this.${listener.elementVarName}.removeEventListener('${listener.event}', this.${listener.handlerName}.bind(this));
`;
});
}
classBody += ` }
`;
// Generate getters and setters for cached nodes
Object.keys(cachedNodes).forEach(propName => {
classBody += `
get ${propName}() { return this._${propName}; }
set ${propName}(value) {
if (this._${propName} !== value) {
this._${propName} = value;
`;
cachedNodes[propName].forEach(node => {
if (node.type === 'text') {
classBody += ` this.${node.varName}.textContent = ${node.expression};
`;
} else if (node.type === 'attribute') {
classBody += ` this.${node.elementVarName}.setAttribute('${node.attrName}', ${node.expression});
`;
}
});
classBody += ` }
}
`;
});
// Add getters and setters for prop keys
if (propKeys.size > 0) {
classBody += `
// Getters and setters for prop attributes
`;
propKeys.forEach(key => {
classBody += `
get ${key}() { return this.prop.${key}; }
set ${key}(value) {
if (this.prop.${key} !== value) {
this.prop.${key} = value;
this.setAttribute('${key}', value);
}
}
`;
});
}
// Add methods
methods.forEach(method => {
const transformedBody = transformMethodBody(method.body, properties.map(p => p.name));
classBody += `
${method.name}(${method.params}) {
${transformedBody}
}
`;
});
return classBody;
}
module.exports = {
parseScript,
transformMethodBody,
generateDOMCode,
generateComponentClassCode,
generateClassBodyCode,
};
Changes Made:
-
parseScript Function:
- Prop Key Detection: Enhanced to traverse the AST and identify all
prop.key usages within the script. It collects these keys in the propKeys set.
-
generateDOMCode Function:
- Prop Key Detection in HTML: Modified to detect
{prop.key} patterns within the HTML content and collect these keys in the propKeys set.
-
generateClassBodyCode Function:
- Console Log Injection: Added a
console.log statement in the constructor that logs all collected prop keys for debugging purposes.
-
generateComponentClassCode Function:
- Prop Keys Integration: Combines
propKeys collected from both script and HTML before passing them to generateClassBodyCode.
cat\src\component.js
// cat/src/component.js
const fs = require('fs-extra');
const path = require('path');
const {
parseScript,
generateComponentClassCode,
} = require('./scripter');
/**
* 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 parseComponentFile(filePath) {
const content = await fs.readFile(filePath, 'utf-8');
// Extract the outermost tag name and inner HTML
const componentRegex = /<([\w-]+)>([\s\S]*?)<\/\1>/;
const componentMatch = content.match(componentRegex);
if (!componentMatch) {
throw new Error(
`Invalid component structure in ${path.basename(filePath)}`
);
}
let tagName = componentMatch[1];
let innerContent = componentMatch[2];
// Adjust tagName if it doesn't have a hyphen
if (!tagName.includes('-')) {
tagName = `${tagName}-comp`;
}
// Extract all <script> sections
const scriptRegex = /<script>([\s\S]*?)<\/script>/g;
let scriptContent = '';
let scriptMatch;
while ((scriptMatch = scriptRegex.exec(content)) !== null) {
scriptContent += scriptMatch[1].trim() + '\n';
}
// Extract all <style> sections
const styleRegex = /<style>([\s\S]*?)<\/style>/g;
let styleContent = '';
let styleMatch;
while ((styleMatch = styleRegex.exec(content)) !== null) {
styleContent += styleMatch[1].trim() + '\n';
}
// Remove all <script> and <style> tags from innerContent
innerContent = innerContent
.replace(scriptRegex, '')
.replace(styleRegex, '')
.trim();
return {
tagName,
html: innerContent,
script: scriptContent,
style: styleContent,
};
}
/**
* Convert a kebab-case or other tag name to PascalCase for class naming.
* @param {string} tagName - The custom element tag name.
* @returns {string} - PascalCase string.
*/
function toPascalCase(tagName) {
return tagName
.split('-')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join('');
}
/**
* Generate the class code for the component.
* @param {object} data - Component data.
* @returns {string} - The class code.
*/
function generateComponentClassCode({ tagName, html, style, properties, methods, scriptPropKeys }) {
const className = toPascalCase(tagName);
// Generate class code using scripter.js functions
const classCode = require('./scripter').generateComponentClassCode({
tagName,
html,
style,
properties,
methods,
scriptPropKeys,
});
return classCode;
}
/**
* Parse and compile a component file to generate class code.
* @param {string} filePath - Path to the .comp.html file.
* @returns {Promise<{ tagName: string, classCode: string }>} - Parsed component details and compiled class code.
*/
async function parseComponent(filePath) {
try {
const { tagName, html, script, style } = await parseComponentFile(filePath);
// Parse the script to extract properties, methods, and propKeys
const { properties, methods, propKeys: scriptPropKeys } = parseScript(script);
// Generate class code
const classCode = generateComponentClassCode({
tagName,
html,
style,
properties,
methods,
scriptPropKeys,
});
console.log(
`🔨 Compiled component <${tagName}> from ${path.relative(path.dirname(filePath), filePath)}`
);
return { tagName, classCode };
} catch (error) {
console.error(`❌ Failed to parse component ${filePath}: ${error.message}`);
}
}
module.exports = {
parseComponent: parseComponent,
};
Changes Made:
-
Prop Key Collection:
- Script Parsing: After extracting the script content,
parseScript is invoked to extract properties, methods, and propKeys used within the script.
-
Class Code Generation:
- Prop Keys Integration: The collected
scriptPropKeys are passed to generateComponentClassCode, which combines them with any propKeys detected in the HTML.
- Console Log Injection: The
generateClassBodyCode function now includes a console.log statement within the constructor that logs all collected prop keys for debugging.
-
Logging Enhancements:
- Added a console log statement indicating successful compilation of each component, which helps in tracking the compilation process.
With these updates:
-
Prop Usage Detection: The compiler now accurately detects all usages of prop.key both in the script and within the HTML templates of components.
-
Debugging Support: A console.log statement is injected into the constructor of each component, displaying all collected prop keys. This aids in debugging by allowing developers to verify which properties are being utilized within each component.
These changes ensure that the new attribute-passing feature integrates seamlessly with the existing compiler infrastructure without disrupting other functionalities.