@nodesecure/js-x-ray
Version:
JavaScript AST XRay analysis
43 lines • 1.31 kB
JavaScript
// Import Node.js Dependencies
import { stripTypeScriptTypes } from "node:module";
// Import Third-party Dependencies
import { parseModule, parse } from "meriyah";
// CONSTANTS
const kParsingOptions = {
next: true,
loc: true,
raw: true,
jsx: true
};
export class JsSourceParser {
static FileExtensions = new Set([
".js",
".cjs",
".mjs",
".jsx"
]);
#stripTypeScriptTypes = false;
constructor(options = {}) {
this.#stripTypeScriptTypes = options.stripTypeScriptTypes ?? false;
}
parse(source) {
const cleanedSource = this.#stripTypeScriptTypes ? stripTypeScriptTypes(source) : source;
try {
const { body } = parseModule(cleanedSource, structuredClone(kParsingOptions));
return body;
}
catch (error) {
const syntaxError = error;
const isIllegalReturn = syntaxError.description.includes("Illegal return statement");
if (isIllegalReturn) {
const { body } = parse(cleanedSource, {
...structuredClone(kParsingOptions),
sourceType: "commonjs"
});
return body;
}
throw error;
}
}
}
//# sourceMappingURL=JsSourceParser.js.map