|
| 1 | +import babel = require("./babel-core.cts"); |
| 2 | +import convert = require("../convert/index.cts"); |
| 3 | +import astInfo = require("./ast-info.cts"); |
| 4 | +import extractParserOptionsPlugin = require("./extract-parser-options-plugin.cjs"); |
| 5 | + |
| 6 | +import type { InputOptions, ConfigItem } from "@babel/core"; |
| 7 | +import type { AST, ParseResult } from "../types.cts"; |
| 8 | + |
| 9 | +const { getVisitorKeys, getTokLabels } = astInfo; |
| 10 | + |
| 11 | +const ref = {}; |
| 12 | +let extractParserOptionsConfigItem: ConfigItem<any>; |
| 13 | + |
| 14 | +const MULTIPLE_OVERRIDES = /More than one plugin attempted to override parsing/; |
| 15 | + |
| 16 | +export = function maybeParseSync( |
| 17 | + code: string, |
| 18 | + options: InputOptions, |
| 19 | +): { |
| 20 | + ast: AST.Program | null; |
| 21 | + parserOptions: ParseResult | null; |
| 22 | +} { |
| 23 | + if (!extractParserOptionsConfigItem) { |
| 24 | + extractParserOptionsConfigItem = babel.createConfigItemSync( |
| 25 | + [extractParserOptionsPlugin, ref], |
| 26 | + { dirname: __dirname, type: "plugin" }, |
| 27 | + ); |
| 28 | + } |
| 29 | + const { plugins } = options; |
| 30 | + options.plugins = plugins.concat(extractParserOptionsConfigItem); |
| 31 | + |
| 32 | + let ast; |
| 33 | + |
| 34 | + try { |
| 35 | + return { |
| 36 | + parserOptions: babel.parseSync(code, options), |
| 37 | + ast: null, |
| 38 | + }; |
| 39 | + } catch (err) { |
| 40 | + if (!MULTIPLE_OVERRIDES.test(err.message)) { |
| 41 | + throw err; |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + // There was already a parserOverride, so remove our plugin. |
| 46 | + options.plugins = plugins; |
| 47 | + |
| 48 | + try { |
| 49 | + ast = babel.parseSync(code, options); |
| 50 | + } catch (err) { |
| 51 | + throw convert.convertError(err); |
| 52 | + } |
| 53 | + |
| 54 | + return { |
| 55 | + ast: convert.convertFile(ast, code, getTokLabels(), getVisitorKeys()), |
| 56 | + parserOptions: null, |
| 57 | + }; |
| 58 | +}; |
0 commit comments