agentsqripts
Version:
Comprehensive static code analysis toolkit for identifying technical debt, security vulnerabilities, performance issues, and code quality problems
41 lines (36 loc) • 1.12 kB
JavaScript
/**
* @file AST parsing utility for code analysis
* @description Single responsibility: Parse JavaScript code into AST for analysis
*/
const acorn = require('acorn');
/**
* Parse JavaScript code into an Abstract Syntax Tree
* @param {string} code - JavaScript code to parse
* @param {Object} options - Parsing options
* @returns {Object} AST representation of the code
*/
function parseCode(code, options = {}) {
if (typeof code !== 'string') {
throw new TypeError('Code must be a string');
}
const defaultOptions = {
ecmaVersion: 2020,
sourceType: 'module',
allowReturnOutsideFunction: true,
...options
};
try {
return acorn.parse(code, defaultOptions);
} catch (error) {
// Try with script mode if module fails
if (defaultOptions.sourceType === 'module') {
try {
return acorn.parse(code, { ...defaultOptions, sourceType: 'script' });
} catch (scriptError) {
throw new Error(`Failed to parse code: ${error.message}`);
}
}
throw new Error(`Failed to parse code: ${error.message}`);
}
}
module.exports = parseCode;