-
-
Notifications
You must be signed in to change notification settings - Fork 40
/
languageServiceHost.ts
394 lines (349 loc) Β· 11.2 KB
/
languageServiceHost.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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
import type { FileKind, VirtualFile, LanguageContext } from '@volar/language-core';
import type * as ts from 'typescript/lib/tsserverlibrary';
import { posix as path } from 'path';
import { matchFiles } from './typescript/utilities';
import { ServiceEnvironment } from '@volar/language-service';
const fileVersions = new Map<string, { lastVersion: number; snapshotVersions: WeakMap<ts.IScriptSnapshot, number>; }>();
export function createLanguageServiceHost(
ctx: LanguageContext,
ts: typeof import('typescript/lib/tsserverlibrary'),
sys: ts.System & {
version?: number;
},
env: ServiceEnvironment | undefined,
) {
let lastProjectVersion: number | string | undefined;
let tsProjectVersion = 0;
let tsFileNames: string[] = [];
let tsDirectories: Record<string, true> = {};
const _tsHost: ts.LanguageServiceHost = {
...sys,
getCurrentDirectory: () => ctx.host.workspacePath,
getCompilationSettings: () => ctx.host.getCompilationSettings(),
getCancellationToken: ctx.host.getCancellationToken ? () => ctx.host.getCancellationToken!() : undefined,
getLocalizedDiagnosticMessages: ctx.host.getLocalizedDiagnosticMessages ? () => ctx.host.getLocalizedDiagnosticMessages!() : undefined,
getProjectReferences: ctx.host.getProjectReferences ? () => ctx.host.getProjectReferences!() : undefined,
getDefaultLibFileName: (options) => {
try {
return ts.getDefaultLibFilePath(options);
} catch {
// web
return `/node_modules/typescript/lib/${ts.getDefaultLibFileName(options)}`;
}
},
useCaseSensitiveFileNames: () => sys.useCaseSensitiveFileNames,
getNewLine: () => sys.newLine,
readFile: fileName => {
const snapshot = getScriptSnapshot(fileName);
if (snapshot) {
return snapshot.getText(0, snapshot.getLength());
}
},
readDirectory,
getDirectories,
directoryExists,
fileExists,
getProjectVersion: () => {
return tsProjectVersion + ':' + sys.version;
},
getTypeRootsVersion: () => {
return sys.version ?? -1; // TODO: only update for /node_modules changes?
},
getScriptFileNames: () => tsFileNames,
getScriptVersion,
getScriptSnapshot,
getScriptKind(fileName) {
if (ts) {
if (ctx.virtualFiles.hasSource(fileName))
return ts.ScriptKind.Deferred;
switch (path.extname(fileName)) {
case '.js': return ts.ScriptKind.JS;
case '.cjs': return ts.ScriptKind.JS;
case '.mjs': return ts.ScriptKind.JS;
case '.jsx': return ts.ScriptKind.JSX;
case '.ts': return ts.ScriptKind.TS;
case '.cts': return ts.ScriptKind.TS;
case '.mts': return ts.ScriptKind.TS;
case '.tsx': return ts.ScriptKind.TSX;
case '.json': return ts.ScriptKind.JSON;
default: return ts.ScriptKind.Unknown;
}
}
return 0;
},
};
const fsFileSnapshots = new Map<string, [number | undefined, ts.IScriptSnapshot | undefined]>();
if (ctx.host.resolveModuleName) {
// TODO: can this share between monorepo packages?
const moduleCache = ts.createModuleResolutionCache(
_tsHost.getCurrentDirectory(),
_tsHost.useCaseSensitiveFileNames ? s => s : s => s.toLowerCase(),
_tsHost.getCompilationSettings()
);
const watching = !!env?.onDidChangeWatchedFiles?.(() => {
moduleCache.clear();
});
let lastProjectVersion = ctx.host.getProjectVersion();
_tsHost.resolveModuleNameLiterals = (
moduleLiterals,
containingFile,
redirectedReference,
options,
sourceFile
) => {
if (!watching && lastProjectVersion !== ctx.host.getProjectVersion()) {
lastProjectVersion = ctx.host.getProjectVersion();
moduleCache.clear();
}
return moduleLiterals.map((moduleLiteral) => {
let moduleName = moduleLiteral.text;
moduleName = ctx.host.resolveModuleName!(moduleName, sourceFile.impliedNodeFormat);
return ts.resolveModuleName(
moduleName,
containingFile,
options,
_tsHost,
moduleCache,
redirectedReference,
sourceFile.impliedNodeFormat
);
});
};
_tsHost.resolveModuleNames = (
moduleNames,
containingFile,
_reusedNames,
redirectedReference,
options,
sourceFile
) => {
if (!watching && lastProjectVersion !== ctx.host.getProjectVersion()) {
lastProjectVersion = ctx.host.getProjectVersion();
moduleCache.clear();
}
return moduleNames.map((moduleName) => {
moduleName = ctx.host.resolveModuleName!(moduleName, sourceFile?.impliedNodeFormat);
return ts.resolveModuleName(
moduleName,
containingFile,
options,
_tsHost,
moduleCache,
redirectedReference,
sourceFile?.impliedNodeFormat
).resolvedModule;
});
};
}
let oldTsVirtualFileSnapshots = new Set<ts.IScriptSnapshot>();
let oldOtherVirtualFileSnapshots = new Set<ts.IScriptSnapshot>();
return new Proxy(_tsHost, {
get: (target, property: keyof ts.LanguageServiceHost) => {
sync();
return target[property];
},
}) as ts.LanguageServiceHost;
function sync() {
const newProjectVersion = ctx.host.getProjectVersion();
const shouldUpdate = newProjectVersion !== lastProjectVersion;
if (!shouldUpdate)
return;
lastProjectVersion = newProjectVersion;
const newTsVirtualFileSnapshots = new Set<ts.IScriptSnapshot>();
const newOtherVirtualFileSnapshots = new Set<ts.IScriptSnapshot>();
for (const { root } of ctx.virtualFiles.allSources()) {
forEachEmbeddedFile(root, embedded => {
if (embedded.kind === 1 satisfies FileKind.TypeScriptHostFile) {
newTsVirtualFileSnapshots.add(embedded.snapshot);
}
else {
newOtherVirtualFileSnapshots.add(embedded.snapshot);
}
});
}
if (!setEquals(oldTsVirtualFileSnapshots, newTsVirtualFileSnapshots)) {
tsProjectVersion++;
}
else if (setEquals(oldOtherVirtualFileSnapshots, newOtherVirtualFileSnapshots)) {
// no any meta language files update, it mean project version was update by source files this time
tsProjectVersion++;
}
oldTsVirtualFileSnapshots = newTsVirtualFileSnapshots;
oldOtherVirtualFileSnapshots = newOtherVirtualFileSnapshots;
const tsFileNamesSet = new Set<string>();
for (const { root } of ctx.virtualFiles.allSources()) {
forEachEmbeddedFile(root, embedded => {
if (embedded.kind === 1 satisfies FileKind.TypeScriptHostFile) {
tsFileNamesSet.add(embedded.fileName); // virtual .ts
}
});
}
for (const fileName of ctx.host.getScriptFileNames()) {
if (!ctx.virtualFiles.hasSource(fileName)) {
tsFileNamesSet.add(fileName); // .ts
}
}
tsFileNames = [...tsFileNamesSet];
// Update tsDirectories for `directoryExists()`
tsDirectories = {};
for (const fileName of tsFileNames) {
tsDirectories[path.dirname(fileName)] = true;
}
}
function readDirectory(
dirName: string,
extensions?: readonly string[],
excludes?: readonly string[],
includes?: readonly string[],
depth?: number,
): string[] {
let matches = matchFiles(
dirName,
extensions,
excludes,
includes,
sys?.useCaseSensitiveFileNames ?? false,
ctx.host.workspacePath,
depth,
(dirPath) => {
const files: string[] = [];
for (const fileName of tsFileNames) {
if (fileName.toLowerCase().startsWith(dirPath.toLowerCase())) {
const baseName = fileName.substring(dirPath.length);
if (baseName.indexOf('/') === -1) {
files.push(baseName);
}
}
}
return {
files,
directories: getVirtualFileDirectories(dirPath),
};
},
sys?.realpath ? (path => sys.realpath!(path)) : (path => path),
);
matches = matches.map(match => {
const [_, source] = ctx.virtualFiles.getVirtualFile(match);
if (source) {
return source.fileName;
}
return match;
});
return [...new Set([
...matches,
...sys.readDirectory(dirName, extensions, excludes, includes, depth),
])];
}
function getDirectories(dirName: string): string[] {
return [...new Set([
...getVirtualFileDirectories(dirName),
...sys.getDirectories(dirName),
])];
}
function getVirtualFileDirectories(dirName: string): string[] {
const names = new Set<string>();
for (const fileName of tsFileNames) {
if (fileName.toLowerCase().startsWith(dirName.toLowerCase())) {
const path = fileName.substring(dirName.length);
if (path.indexOf('/') >= 0) {
names.add(path.split('/')[0]);
}
}
}
return [...names];
}
function getScriptSnapshot(fileName: string) {
// virtual files
const [virtualFile] = ctx.virtualFiles.getVirtualFile(fileName);
if (virtualFile) {
return virtualFile.snapshot;
}
// root files / opened files
const tsScript = ctx.host.getScriptSnapshot(fileName);
if (tsScript) {
return tsScript;
}
// fs files
const cache = fsFileSnapshots.get(fileName);
const modifiedTime = sys.getModifiedTime?.(fileName)?.valueOf();
if (!cache || cache[0] !== modifiedTime) {
if (sys.fileExists(fileName)) {
const text = sys.readFile(fileName);
const snapshot = text !== undefined ? ts.ScriptSnapshot.fromString(text) : undefined;
fsFileSnapshots.set(fileName, [modifiedTime, snapshot]);
}
else {
fsFileSnapshots.set(fileName, [modifiedTime, undefined]);
}
}
return fsFileSnapshots.get(fileName)?.[1];
}
function getScriptVersion(fileName: string) {
// virtual files / root files / opened files
const [virtualFile] = ctx.virtualFiles.getVirtualFile(fileName);
const snapshot = virtualFile?.snapshot ?? ctx.host.getScriptSnapshot(fileName);
if (snapshot) {
if (!fileVersions.has(fileName)) {
fileVersions.set(fileName, { lastVersion: 0, snapshotVersions: new WeakMap() });
}
const version = fileVersions.get(fileName)!;
if (!version.snapshotVersions.has(snapshot)) {
version.snapshotVersions.set(snapshot, version.lastVersion++);
}
return version.snapshotVersions.get(snapshot)!.toString();
}
// fs files
return sys.getModifiedTime?.(fileName)?.valueOf().toString() ?? '';
}
function directoryExists(dirName: string): boolean {
return tsDirectories[dirName] || sys.directoryExists(dirName);
}
function fileExists(fileName: string) {
// fill external virtual files
const ext = fileName.substring(fileName.lastIndexOf('.'));
if (
ext === '.js'
|| ext === '.ts'
|| ext === '.jsx'
|| ext === '.tsx'
) {
/**
* If try to access a external .vue file that outside of the project,
* the file will not process by language service host,
* so virtual file will not be created.
*
* We try to create virtual file here.
*/
const sourceFileName = fileName.substring(0, fileName.lastIndexOf('.'));
if (!ctx.virtualFiles.hasSource(sourceFileName)) {
const scriptSnapshot = getScriptSnapshot(sourceFileName);
if (scriptSnapshot) {
ctx.virtualFiles.updateSource(sourceFileName, scriptSnapshot, ctx.host.getLanguageId?.(sourceFileName));
}
}
}
// virtual files
if (ctx.virtualFiles.hasVirtualFile(fileName)) {
return true;
}
// root files
if (ctx.host.getScriptSnapshot(fileName)) {
return true;
}
// fs files
return !!sys.fileExists(fileName);
}
}
function setEquals<T>(a: Set<T>, b: Set<T>) {
if (a.size !== b.size) return false;
for (const item of a) {
if (!b.has(item)) return false;
}
return true;
}
function forEachEmbeddedFile(file: VirtualFile, cb: (embedded: VirtualFile) => void) {
cb(file);
for (const embeddedFile of file.embeddedFiles) {
forEachEmbeddedFile(embeddedFile, cb);
}
}