This repository was archived by the owner on Jan 19, 2019. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 75
/
Copy pathast-converter.js
82 lines (69 loc) · 2.3 KB
/
ast-converter.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/**
* @fileoverview Converts TypeScript AST into ESTree format.
* @author Nicholas C. Zakas
* @author James Henry <https://github.com/JamesHenry>
* @copyright jQuery Foundation and other contributors, https://jquery.org/
* MIT License
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const convert = require("./convert"),
convertComments = require("./convert-comments").convertComments,
nodeUtils = require("./node-utils");
//------------------------------------------------------------------------------
// Private
//------------------------------------------------------------------------------
/**
* Extends and formats a given error object
* @param {Object} error the error object
* @returns {Object} converted error object
*/
function convertError(error) {
const loc = error.file.getLineAndCharacterOfPosition(error.start);
return {
index: error.start,
lineNumber: loc.line + 1,
column: loc.character,
message: error.message || error.messageText
};
}
//------------------------------------------------------------------------------
// Public
//------------------------------------------------------------------------------
module.exports = (ast, extra) => {
/**
* The TypeScript compiler produced fundamental parse errors when parsing the
* source.
*/
if (ast.parseDiagnostics.length) {
throw convertError(ast.parseDiagnostics[0]);
}
/**
* Recursively convert the TypeScript AST into an ESTree-compatible AST
*/
const estree = convert({
node: ast,
parent: null,
ast,
additionalOptions: {
errorOnUnknownASTType: extra.errorOnUnknownASTType || false,
useJSXTextNode: extra.useJSXTextNode || false,
parseForESLint: extra.parseForESLint
}
});
/**
* Optionally convert and include all tokens in the AST
*/
if (extra.tokens) {
estree.tokens = nodeUtils.convertTokens(ast);
}
/**
* Optionally convert and include all comments in the AST
*/
if (extra.comment) {
estree.comments = convertComments(ast, extra.code);
}
return estree;
};