/
createIsolatedProgram.ts
85 lines (77 loc) · 1.84 KB
/
createIsolatedProgram.ts
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
83
84
85
import debug from 'debug';
import * as ts from 'typescript';
import { Extra } from '../parser-options';
import {
ASTAndProgram,
createDefaultCompilerOptionsFromExtra,
getScriptKind,
} from './shared';
const log = debug('typescript-eslint:typescript-estree:createIsolatedProgram');
/**
* @param code The code of the file being linted
* @returns Returns a new source file and program corresponding to the linted code
*/
function createIsolatedProgram(code: string, extra: Extra): ASTAndProgram {
log(
'Getting isolated program in %s mode for: %s',
extra.jsx ? 'TSX' : 'TS',
extra.filePath,
);
const compilerHost: ts.CompilerHost = {
fileExists() {
return true;
},
getCanonicalFileName() {
return extra.filePath;
},
getCurrentDirectory() {
return '';
},
getDirectories() {
return [];
},
getDefaultLibFileName() {
return 'lib.d.ts';
},
// TODO: Support Windows CRLF
getNewLine() {
return '\n';
},
getSourceFile(filename: string) {
return ts.createSourceFile(
filename,
code,
ts.ScriptTarget.Latest,
true,
getScriptKind(extra, filename),
);
},
readFile() {
return undefined;
},
useCaseSensitiveFileNames() {
return true;
},
writeFile() {
return null;
},
};
const program = ts.createProgram(
[extra.filePath],
{
noResolve: true,
target: ts.ScriptTarget.Latest,
jsx: extra.jsx ? ts.JsxEmit.Preserve : undefined,
...createDefaultCompilerOptionsFromExtra(extra),
},
compilerHost,
);
const ast = program.getSourceFile(extra.filePath);
if (!ast) {
throw new Error(
'Expected an ast to be returned for the single-file isolated program.',
);
}
return { ast, program };
}
export { createIsolatedProgram };