1 | const babylon = require('@babel/parser');
|
2 | const {omit, collectAllNodes} = require('./annotation-utils');
|
3 | const omitFields = {
|
4 | loc: true,
|
5 | start: true,
|
6 | end: true,
|
7 | optional: true,
|
8 | variance: true,
|
9 | exact: true,
|
10 | static: true
|
11 | };
|
12 |
|
13 | function extractTypes(source) {
|
14 | const ast = babylon.parse(source, {plugins: ['flow']});
|
15 | const types = collectAllNodes(ast, node => node.type === 'TypeAlias').reduce((acc, node) => {
|
16 | acc[node.id.name] = omit(node.right, omitFields);
|
17 | return acc;
|
18 | }, {});
|
19 | const expr = collectAllNodes(
|
20 | ast,
|
21 | node =>
|
22 | node.type === 'FunctionDeclaration' &&
|
23 | node.returnType &&
|
24 | node.returnType.typeAnnotation &&
|
25 | node.id.name.indexOf('annotate_') === 0
|
26 | ).reduce((acc, node) => {
|
27 | acc[node.id.name.replace('annotate_', '')] = omit(node.returnType.typeAnnotation, omitFields);
|
28 | return acc;
|
29 | }, {});
|
30 | return {expr, types};
|
31 | }
|
32 |
|
33 | module.exports = {extractTypes};
|