const { parseDocument } = require('htmlparser2');
const acorn = require('acorn');
/**
* Parser Module
*
* This module parses HTML and JavaScript content into structured formats.
*/
/**
* Parse HTML content into a tree-like structure
* @param {string} htmlContent - Raw HTML content
* @returns {Array} - Parsed HTML structure
*/
function parseHTML(htmlContent) {
const rawParsed = parseDocument(htmlContent, { recognizeSelfClosing: true });
function simplifyNode(node) {
if (node.type === 'tag') {
return {
type: 'tag',
name: node.name,
attributes: node.attribs,
children: node.children.map(simplifyNode).filter(Boolean)
};
} else if (node.type === 'text') {
const content = node.data.trim();
return content ? { type: 'text', content } : null;
}
return null;
}
return rawParsed.children.map(simplifyNode).filter(Boolean);
}
/**
* Parse JavaScript content into an AST
* @param {string} jsContent - Raw JavaScript content
* @returns {Object} - JavaScript AST
*/
function parseJavaScript(jsContent) {
return acorn.parse(jsContent, {
ecmaVersion: 'latest',
sourceType: 'script'
});
}
/**
* Parse both HTML and JavaScript content
* @param {Object} file - Object containing body and script properties
* @returns {Object} - Object with parsed body and script
*/
function parseContent(file) {
const parsedBody = parseHTML(file.body);
const parsedScript = file.script ? (parseJavaScript(file.script)).body : null;
return {
body: parsedBody,
script: parsedScript
};
}
module.exports = { parseContent };
cat\src\slicer.js
javascript
/**
* Slicer Module
*
* This module extracts content from HTML files, slicing it into main, script, and style sections.
*/
/**
* Extract wrappers from content using regex
* @param {string} content - Raw HTML content
* @returns {Array} - Array of wrapper objects
*/
function extractWrappers(content) {
const wrapperRegex = /<(\w+(?:-?\w+)*)>([\s\S]*?)<\/\1>/g;
return Array.from(content.matchAll(wrapperRegex), match => ({
tag: match[1],
content: match[2],
}));
}
/**
* Identify the main wrapper (not script or style)
* @param {Array} wrappers - Array of wrapper objects
* @returns {Object} - The main wrapper object
*/
function identifyMainWrapper(wrappers) {
const mainWrappers = wrappers.filter(w => !['script', 'style'].includes(w.tag.toLowerCase()));
if (mainWrappers.length !== 1) {
throw new Error('Invalid structure. Expected exactly one main wrapper.');
}
return mainWrappers[0];
}
/**
* Slice HTML content into structured parts
* @param {string} file - Raw HTML content to slice
* @returns {Object} - Sliced structure with type, tagName, body, script, and style
*/
function sliceContent(file) {
const wrappers = extractWrappers(file.body);
if (wrappers.length > 3)
throw new Error(`${file.file} :: Invalid structure. Found ${wrappers.length} wrappers, maximum allowed is 3.`);
const mainWrapper = identifyMainWrapper(wrappers);
const scriptWrapper = wrappers.find(w => w.tag.toLowerCase() === 'script');
const styleWrapper = wrappers.find(w => w.tag.toLowerCase() === 'style');
return {
type: file.type,
name: mainWrapper.tag,
body: mainWrapper.content,
script: scriptWrapper ? scriptWrapper.content : null,
style: styleWrapper ? styleWrapper.content : null
};
}
module.exports = { sliceContent };
cat\src\body.js
javascript
/**
* Body Interpreter Module
*
* This module interprets the parsed HTML body, converting custom syntax to JavaScript template literals.
* It also tracks all interpreted variables in a bindings array.
*/
/**
* Convert custom syntax to JavaScript Template Literals and track bindings
* @param {string} content - The content to interpret
* @param {Set} bindingsSet - Set to store unique bindings
* @returns {string} - The interpreted content
*/
function interpretContent(content, bindingsSet) {
return content.replace(/\{([^}]+)\}/g, (match, p1) => {
const trimmed = p1.trim();
bindingsSet.add(trimmed);
return `\${this.${trimmed}}`;
});
}
/**
* Recursively interpret the parsed body and collect bindings
* @param {Array} parsedBody - The parsed HTML body
* @param {Set} bindingsSet - Set to store unique bindings
* @returns {Array} - The interpreted body
*/
function interpretBody(parsedBody, bindingsSet) {
return parsedBody.map(node => {
if (node.type === 'tag') {
return {
...node,
children: interpretBody(node.children, bindingsSet)
};
} else if (node.type === 'text') {
return {
...node,
content: interpretContent(node.content, bindingsSet)
};
}
return node;
});
}
/**
* Main function to interpret the body of a file and collect bindings
* @param {Object} body - The parsed HTML body
* @returns {Object} - Object containing the interpreted body and bindings array
*/
function interpretHTML(body) {
const bindingsSet = new Set();
const interpretedBody = interpretBody(body, bindingsSet);
return {
body: interpretedBody,
bindings: Array.from(bindingsSet)
};
}
module.exports = { interpretHTML };
We need the interpretetScript(file.script) module, inside the file script.js. The module it's going to reconstruct the JavaScript code from the parsed AST format. But, categorizing the code by types:
Variables : All the global variables
Methods: All the methods, written on all the variation for writing a function on JavaScript.
Events: All the events defined in the global scope.
Calls: All the function calls declared on the global scope.
Our module it's going to return the script object.
Certainly! Below is the implementation of the script.js module as per your requirements. This module processes the parsed JavaScript Abstract Syntax Tree (AST) and categorizes the code into Variables, Methods, Events, and Calls. The module reconstructs the JavaScript code by traversing the AST and extracting relevant information for each category.
cat\src\script.js
javascript
/**
* Script Interpreter Module
*
* This module interprets the parsed JavaScript AST, categorizing the code into
* variables, methods, events, and function calls. It reconstructs the JavaScript
* code from the AST and organizes it into a structured `script` object.
*/
const escodegen = require('escodegen');
/**
* Helper function to generate code from AST nodes
* @param {Object} node - AST node
* @returns {string} - Generated JavaScript code as string
*/
function generateCode(node) {
return escodegen.generate(node);
}
/**
* Extract global variable declarations
* @param {Array} astBody - Array of AST nodes from the script
* @returns {Array} - Array of variable declaration strings
*/
function extractVariables(astBody) {
const variables = [];
astBody.forEach(node => {
if (node.type === 'VariableDeclaration' && node.kind === 'var') {
node.declarations.forEach(decl => {
variables.push(generateCode(decl));
});
} else if (node.type === 'VariableDeclaration' && node.kind === 'let') {
node.declarations.forEach(decl => {
variables.push(generateCode(decl));
});
} else if (node.type === 'VariableDeclaration' && node.kind === 'const') {
node.declarations.forEach(decl => {
variables.push(generateCode(decl));
});
}
});
return variables;
}
/**
* Extract global function declarations and function expressions
* @param {Array} astBody - Array of AST nodes from the script
* @returns {Array} - Array of method declaration strings
*/
function extractMethods(astBody) {
const methods = [];
astBody.forEach(node => {
if (node.type === 'FunctionDeclaration') {
methods.push(generateCode(node));
} else if (
node.type === 'VariableDeclaration' &&
node.declarations.some(
decl =>
decl.init &&
(decl.init.type === 'FunctionExpression' ||
decl.init.type === 'ArrowFunctionExpression')
)
) {
node.declarations.forEach(decl => {
if (
decl.init &&
(decl.init.type === 'FunctionExpression' ||
decl.init.type === 'ArrowFunctionExpression')
) {
methods.push(generateCode(decl));
}
});
}
});
return methods;
}
/**
* Extract global event listeners or event-related code
* @param {Array} astBody - Array of AST nodes from the script
* @returns {Array} - Array of event-related strings
*/
function extractEvents(astBody) {
const events = [];
astBody.forEach(node => {
if (
node.type === 'ExpressionStatement' &&
node.expression.type === 'CallExpression'
) {
const callee = node.expression.callee;
// Detect addEventListener or similar event methods
if (
(callee.type === 'MemberExpression' &&
callee.property &&
['addEventListener', 'on'].includes(callee.property.name)) ||
(callee.type === 'Identifier' &&
['addEventListener', 'on'].includes(callee.name))
) {
events.push(generateCode(node));
}
}
});
return events;
}
/**
* Extract global function calls
* @param {Array} astBody - Array of AST nodes from the script
* @returns {Array} - Array of function call strings
*/
function extractCalls(astBody) {
const calls = [];
astBody.forEach(node => {
if (
node.type === 'ExpressionStatement' &&
node.expression.type === 'CallExpression'
) {
calls.push(generateCode(node));
}
});
return calls;
}
/**
* Main function to interpret the script AST and categorize the code
* @param {Array} scriptAST - Parsed JavaScript AST body
* @returns {Object} - Object containing categorized script code
*/
function interpretScript(scriptAST) {
const variables = extractVariables(scriptAST);
const methods = extractMethods(scriptAST);
const events = extractEvents(scriptAST);
const calls = extractCalls(scriptAST);
return {
variables,
methods,
events,
calls
};
}
module.exports = { interpretScript };
Explanation of the script.js Module
Dependencies:
escodegen: This library is used to generate JavaScript code from AST nodes. It helps in reconstructing the code snippets from the AST.
Installation: Ensure that you have escodegen installed in your project. You can install it using:
bash
npm install escodegen
Helper Function:
generateCode(node): Takes an AST node and returns the corresponding JavaScript code as a string using escodegen.
Extraction Functions:
extractVariables(astBody):
Scans through the AST nodes to find global variable declarations (var, let, const).
Extracts and reconstructs each variable declaration.
extractMethods(astBody):
Identifies global function declarations (FunctionDeclaration).
Also captures function expressions and arrow functions assigned to variables.
Reconstructs each method declaration.
extractEvents(astBody):
Looks for event-related method calls such as addEventListener or any method named on.
This can be expanded based on specific event handling patterns in your codebase.
extractCalls(astBody):
Finds all global function calls that are not part of declarations or expressions.
Reconstructs each function call.
Main Function:
interpretScript(scriptAST):
Orchestrates the extraction process by calling the above helper functions.
Aggregates the extracted variables, methods, events, and calls into a single script object.
Returns the structured script object containing categorized code.
Module Export:
Usage in index.js
Given your existing index.js, the interpretScript function will be used as follows:
Error Handling: Depending on the complexity of your scripts, you might need to enhance the extraction functions to handle more edge cases or specific patterns.
Extensibility: The module is designed to be extensible. You can add more categories or refine the existing ones based on your project's requirements.
Dependencies: Ensure all necessary dependencies like escodegen are installed and properly configured in your project.
Feel free to integrate this module into your project and adjust it as needed to fit your specific use cases!