-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
createIsolatedProgram.ts
84 lines (75 loc) · 2.04 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
import debug from 'debug';
import * as ts from 'typescript';
import type { ParseSettings } from '../parseSettings';
import { getScriptKind } from './getScriptKind';
import type { ASTAndProgram } from './shared';
import { createDefaultCompilerOptionsFromExtra } 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(parseSettings: ParseSettings): ASTAndProgram {
log(
'Getting isolated program in %s mode for: %s',
parseSettings.jsx ? 'TSX' : 'TS',
parseSettings.filePath,
);
const compilerHost: ts.CompilerHost = {
fileExists() {
return true;
},
getCanonicalFileName() {
return parseSettings.filePath;
},
getCurrentDirectory() {
return '';
},
getDirectories() {
return [];
},
getDefaultLibFileName() {
return 'lib.d.ts';
},
// TODO: Support Windows CRLF
getNewLine() {
return '\n';
},
getSourceFile(filename: string) {
return ts.createSourceFile(
filename,
parseSettings.codeFullText,
ts.ScriptTarget.Latest,
/* setParentNodes */ true,
getScriptKind(parseSettings.filePath, parseSettings.jsx),
);
},
readFile() {
return undefined;
},
useCaseSensitiveFileNames() {
return true;
},
writeFile() {
return null;
},
};
const program = ts.createProgram(
[parseSettings.filePath],
{
noResolve: true,
target: ts.ScriptTarget.Latest,
jsx: parseSettings.jsx ? ts.JsxEmit.Preserve : undefined,
...createDefaultCompilerOptionsFromExtra(parseSettings),
},
compilerHost,
);
const ast = program.getSourceFile(parseSettings.filePath);
if (!ast) {
throw new Error(
'Expected an ast to be returned for the single-file isolated program.',
);
}
return { ast, program };
}
export { createIsolatedProgram };