forked from documentationjs/documentation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparse_to_ast.js
54 lines (48 loc) · 1.46 KB
/
parse_to_ast.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
const babelParser = require('@babel/parser');
const path = require('path');
const TYPESCRIPT_EXTS = {
'.ts': ['typescript'],
'.tsx': ['typescript', 'jsx']
};
const standardBabelParserPlugins = [
'classProperties',
'classPrivateProperties',
'classPrivateMethods',
'doExpressions',
'exportDefaultFrom',
'exportExtensions',
'functionBind',
'partialApplication',
['pipelineOperator', { proposal: 'minimal' }],
'throwExpressions'
];
module.exports.standardBabelParserPlugins = standardBabelParserPlugins;
function getParserOpts(file) {
return {
allowImportExportEverywhere: true,
sourceType: 'module',
plugins: [
...standardBabelParserPlugins,
['decorators', { decoratorsBeforeExport: false }],
...(TYPESCRIPT_EXTS[path.extname(file || '')] || ['flow', 'jsx'])
]
};
}
/**
* Convert flow comment types into flow annotations so that
* they end up in the final AST. If the source does not contain
* a flow pragma, the code is returned verbatim.
* @param {*} source code with flow type comments
* @returns {string} code with flow annotations
*/
function commentToFlow(source) {
if (!/@flow/.test(source)) return source;
return source
.replace(/\/\*::([^]+?)\*\//g, '$1')
.replace(/\/\*:\s*([^]+?)\s*\*\//g, ':$1');
}
function parseToAst(source, file) {
return babelParser.parse(commentToFlow(source), getParserOpts(file));
}
module.exports.commentToFlow = commentToFlow;
module.exports.parseToAst = parseToAst;