1 | /**
|
2 | * @fileoverview Converts TypeScript AST into ESTree format.
|
3 | * @author Nicholas C. Zakas
|
4 | * @author James Henry <https://github.com/JamesHenry>
|
5 | * @copyright jQuery Foundation and other contributors, https://jquery.org/
|
6 | * MIT License
|
7 | */
|
8 |
|
9 | ;
|
10 |
|
11 | //------------------------------------------------------------------------------
|
12 | // Requirements
|
13 | //------------------------------------------------------------------------------
|
14 |
|
15 | const convert = require("./convert"),
|
16 | convertComments = require("./convert-comments").convertComments,
|
17 | nodeUtils = require("./node-utils");
|
18 |
|
19 | //------------------------------------------------------------------------------
|
20 | // Private
|
21 | //------------------------------------------------------------------------------
|
22 |
|
23 | /**
|
24 | * Extends and formats a given error object
|
25 | * @param {Object} error the error object
|
26 | * @returns {Object} converted error object
|
27 | */
|
28 | function convertError(error) {
|
29 | const loc = error.file.getLineAndCharacterOfPosition(error.start);
|
30 | return {
|
31 | index: error.start,
|
32 | lineNumber: loc.line + 1,
|
33 | column: loc.character,
|
34 | message: error.message || error.messageText
|
35 | };
|
36 | }
|
37 |
|
38 | //------------------------------------------------------------------------------
|
39 | // Public
|
40 | //------------------------------------------------------------------------------
|
41 |
|
42 | module.exports = (ast, extra) => {
|
43 |
|
44 | /**
|
45 | * The TypeScript compiler produced fundamental parse errors when parsing the
|
46 | * source.
|
47 | */
|
48 | if (ast.parseDiagnostics.length) {
|
49 | throw convertError(ast.parseDiagnostics[0]);
|
50 | }
|
51 |
|
52 | /**
|
53 | * Recursively convert the TypeScript AST into an ESTree-compatible AST
|
54 | */
|
55 | const estree = convert({
|
56 | node: ast,
|
57 | parent: null,
|
58 | ast,
|
59 | additionalOptions: {
|
60 | errorOnUnknownASTType: extra.errorOnUnknownASTType || false,
|
61 | useJSXTextNode: extra.useJSXTextNode || false,
|
62 | parseForESLint: extra.parseForESLint
|
63 | }
|
64 | });
|
65 |
|
66 | /**
|
67 | * Optionally convert and include all tokens in the AST
|
68 | */
|
69 | if (extra.tokens) {
|
70 | estree.tokens = nodeUtils.convertTokens(ast);
|
71 | }
|
72 |
|
73 | /**
|
74 | * Optionally convert and include all comments in the AST
|
75 | */
|
76 | if (extra.comment) {
|
77 | estree.comments = convertComments(ast, extra.code);
|
78 | }
|
79 |
|
80 | return estree;
|
81 |
|
82 | };
|