UNPKG

2.38 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.default = parser;
7
8function _parser() {
9 const data = require("@babel/parser");
10
11 _parser = function () {
12 return data;
13 };
14
15 return data;
16}
17
18function _codeFrame() {
19 const data = require("@babel/code-frame");
20
21 _codeFrame = function () {
22 return data;
23 };
24
25 return data;
26}
27
28var _missingPluginHelper = _interopRequireDefault(require("./util/missing-plugin-helper"));
29
30function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
31
32function* parser(pluginPasses, {
33 parserOpts,
34 highlightCode = true,
35 filename = "unknown"
36}, code) {
37 try {
38 const results = [];
39
40 for (const plugins of pluginPasses) {
41 for (const plugin of plugins) {
42 const {
43 parserOverride
44 } = plugin;
45
46 if (parserOverride) {
47 const ast = parserOverride(code, parserOpts, _parser().parse);
48 if (ast !== undefined) results.push(ast);
49 }
50 }
51 }
52
53 if (results.length === 0) {
54 return (0, _parser().parse)(code, parserOpts);
55 } else if (results.length === 1) {
56 yield* [];
57
58 if (typeof results[0].then === "function") {
59 throw new Error(`You appear to be using an async parser plugin, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, you may need to upgrade ` + `your @babel/core version.`);
60 }
61
62 return results[0];
63 }
64
65 throw new Error("More than one plugin attempted to override parsing.");
66 } catch (err) {
67 if (err.code === "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED") {
68 err.message += "\nConsider renaming the file to '.mjs', or setting sourceType:module " + "or sourceType:unambiguous in your Babel config for this file.";
69 }
70
71 const {
72 loc,
73 missingPlugin
74 } = err;
75
76 if (loc) {
77 const codeFrame = (0, _codeFrame().codeFrameColumns)(code, {
78 start: {
79 line: loc.line,
80 column: loc.column + 1
81 }
82 }, {
83 highlightCode
84 });
85
86 if (missingPlugin) {
87 err.message = `${filename}: ` + (0, _missingPluginHelper.default)(missingPlugin[0], loc, codeFrame);
88 } else {
89 err.message = `${filename}: ${err.message}\n\n` + codeFrame;
90 }
91
92 err.code = "BABEL_PARSE_ERROR";
93 }
94
95 throw err;
96 }
97}
\No newline at end of file