UNPKG

@nodesecure/js-x-ray

Version:
43 lines 1.31 kB
// 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