-
-
Notifications
You must be signed in to change notification settings - Fork 431
/
servicesHost.ts
244 lines (199 loc) · 9.17 KB
/
servicesHost.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
import * as typescript from 'typescript';
import * as path from 'path';
import * as semver from 'semver';
import * as constants from './constants';
import * as logger from './logger';
import { makeResolver } from './resolver';
import { appendSuffixesIfMatch, readFile } from './utils';
import {
ModuleResolutionHost,
ResolvedModule,
ResolveSync,
TSInstance,
Webpack
} from './interfaces';
/**
* Create the TypeScript language service
*/
export function makeServicesHost(
scriptRegex: RegExp,
log: logger.Logger,
loader: Webpack,
instance: TSInstance,
appendTsSuffixTo: RegExp[],
appendTsxSuffixTo: RegExp[]
) {
const { compiler, compilerOptions, files } = instance;
const newLine =
compilerOptions.newLine === constants.CarriageReturnLineFeedCode ? constants.CarriageReturnLineFeed :
compilerOptions.newLine === constants.LineFeedCode ? constants.LineFeed :
constants.EOL;
// make a (sync) resolver that follows webpack's rules
const resolveSync = makeResolver(loader.options);
const readFileWithFallback = compiler.sys === undefined || compiler.sys.readFile === undefined
? readFile
: (path: string, encoding?: string | undefined): string | undefined => compiler.sys.readFile(path, encoding) || readFile(path, encoding);
const fileExists = compiler.sys === undefined || compiler.sys.fileExists === undefined
? (path: string) => readFile(path) !== undefined
: (path: string) => compiler.sys.fileExists(path) || readFile(path) !== undefined;
const moduleResolutionHost: ModuleResolutionHost = {
fileExists,
readFile: readFileWithFallback
};
// loader.context seems to work fine on Linux / Mac regardless causes problems for @types resolution on Windows for TypeScript < 2.3
const getCurrentDirectory = (compiler!.version && semver.gte(compiler!.version, '2.3.0'))
? () => loader.context
: () => process.cwd();
const resolutionStrategy = (compiler!.version && semver.gte(compiler!.version, '2.4.0'))
? resolutionStrategyTS24AndAbove
: resolutionStrategyTS23AndBelow;
const servicesHost: typescript.LanguageServiceHost = {
getProjectVersion: () => `${instance.version}`,
getScriptFileNames: () => Object.keys(files).filter(filePath => filePath.match(scriptRegex)),
getScriptVersion: (fileName: string) => {
fileName = path.normalize(fileName);
const file = files[fileName];
return file === undefined ? '' : file.version.toString();
},
getScriptSnapshot: (fileName: string) => {
// This is called any time TypeScript needs a file's text
// We either load from memory or from disk
fileName = path.normalize(fileName);
let file = files[fileName];
if (file === undefined) {
const text = readFile(fileName);
if (text === undefined) { return undefined; }
file = files[fileName] = { version: 0, text };
}
return compiler.ScriptSnapshot.fromString(file.text);
},
/**
* getDirectories is also required for full import and type reference completions.
* Without it defined, certain completions will not be provided
*/
getDirectories: compiler.sys ? compiler.sys.getDirectories : undefined,
/**
* For @types expansion, these two functions are needed.
*/
directoryExists: compiler.sys ? compiler.sys.directoryExists : undefined,
useCaseSensitiveFileNames: compiler.sys
? () => compiler.sys.useCaseSensitiveFileNames
: undefined,
// The following three methods are necessary for @types resolution from TS 2.4.1 onwards see: https://github.com/Microsoft/TypeScript/issues/16772
fileExists: compiler.sys ? compiler.sys.fileExists : undefined,
readFile: compiler.sys ? compiler.sys.readFile : undefined,
readDirectory: compiler.sys ? compiler.sys.readDirectory : undefined,
getCurrentDirectory,
getCompilationSettings: () => compilerOptions,
getDefaultLibFileName: (options: typescript.CompilerOptions) => compiler.getDefaultLibFilePath(options),
getNewLine: () => newLine,
log: log.log,
/* Unclear if this is useful
resolveTypeReferenceDirectives: (typeDirectiveNames: string[], containingFile: string) =>
typeDirectiveNames.map(directive =>
compiler.resolveTypeReferenceDirective(directive, containingFile, compilerOptions, moduleResolutionHost).resolvedTypeReferenceDirective),
*/
resolveModuleNames: (moduleNames: string[], containingFile: string) =>
resolveModuleNames(
resolveSync, moduleResolutionHost, appendTsSuffixTo, appendTsxSuffixTo, scriptRegex, instance,
moduleNames, containingFile, resolutionStrategy),
getCustomTransformers: () => instance.transformers
};
return servicesHost;
}
function resolveModuleNames(
resolveSync: ResolveSync,
moduleResolutionHost: ModuleResolutionHost,
appendTsSuffixTo: RegExp[],
appendTsxSuffixTo: RegExp[],
scriptRegex: RegExp,
instance: TSInstance,
moduleNames: string[],
containingFile: string,
resolutionStrategy: ResolutionStrategy
) {
const resolvedModules = moduleNames.map(moduleName =>
resolveModuleName(resolveSync, moduleResolutionHost, appendTsSuffixTo, appendTsxSuffixTo, scriptRegex, instance,
moduleName, containingFile, resolutionStrategy));
populateDependencyGraphs(resolvedModules, instance, containingFile);
return resolvedModules;
}
function isJsImplementationOfTypings(
resolvedModule: ResolvedModule,
tsResolution: ResolvedModule
) {
return resolvedModule.resolvedFileName.endsWith('js') &&
/\.d\.ts$/.test(tsResolution.resolvedFileName);
}
type ResolutionStrategy = (resolutionResult: ResolvedModule | undefined, tsResolutionResult: ResolvedModule) => ResolvedModule;
function resolveModuleName(
resolveSync: ResolveSync,
moduleResolutionHost: ModuleResolutionHost,
appendTsSuffixTo: RegExp[],
appendTsxSuffixTo: RegExp[],
scriptRegex: RegExp,
instance: TSInstance,
moduleName: string,
containingFile: string,
resolutionStrategy: ResolutionStrategy
) {
const { compiler, compilerOptions } = instance;
let resolutionResult: ResolvedModule;
try {
const originalFileName = resolveSync(undefined, path.normalize(path.dirname(containingFile)), moduleName);
const resolvedFileName = appendTsSuffixTo.length > 0 || appendTsxSuffixTo.length > 0
? appendSuffixesIfMatch({
'.ts': appendTsSuffixTo,
'.tsx': appendTsxSuffixTo,
}, originalFileName)
: originalFileName;
if (resolvedFileName.match(scriptRegex)) {
resolutionResult = { resolvedFileName, originalFileName };
}
} catch (e) { }
const tsResolution = compiler.resolveModuleName(moduleName, containingFile, compilerOptions, moduleResolutionHost);
if (tsResolution.resolvedModule !== undefined) {
const resolvedFileName = path.normalize(tsResolution.resolvedModule.resolvedFileName);
const tsResolutionResult: ResolvedModule = {
originalFileName: resolvedFileName,
resolvedFileName,
isExternalLibraryImport: tsResolution.resolvedModule.isExternalLibraryImport
};
return resolutionStrategy(resolutionResult!, tsResolutionResult);
}
return resolutionResult!;
}
function resolutionStrategyTS23AndBelow(resolutionResult: ResolvedModule | undefined, tsResolutionResult: ResolvedModule): ResolvedModule {
if (resolutionResult! !== undefined) {
if (resolutionResult!.resolvedFileName === tsResolutionResult.resolvedFileName ||
isJsImplementationOfTypings(resolutionResult!, tsResolutionResult)) {
resolutionResult!.isExternalLibraryImport = tsResolutionResult.isExternalLibraryImport;
}
} else {
return tsResolutionResult;
}
return resolutionResult!;
}
function resolutionStrategyTS24AndAbove(resolutionResult: ResolvedModule | undefined, tsResolutionResult: ResolvedModule): ResolvedModule {
return (resolutionResult! === undefined ||
resolutionResult!.resolvedFileName === tsResolutionResult.resolvedFileName ||
isJsImplementationOfTypings(resolutionResult!, tsResolutionResult)
)
? tsResolutionResult
: resolutionResult!;
}
function populateDependencyGraphs(
resolvedModules: ResolvedModule[],
instance: TSInstance,
containingFile: string
) {
resolvedModules = resolvedModules
.filter(mod => mod !== null && mod !== undefined);
instance.dependencyGraph[path.normalize(containingFile)] = resolvedModules;
resolvedModules.forEach(resolvedModule => {
if (instance.reverseDependencyGraph[resolvedModule.resolvedFileName] === undefined) {
instance.reverseDependencyGraph[resolvedModule.resolvedFileName] = {};
}
instance.reverseDependencyGraph[resolvedModule.resolvedFileName]![path.normalize(containingFile)] = true;
});
}