/
project.ts
288 lines (260 loc) · 9.23 KB
/
project.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
import * as shared from '@volar/shared';
import * as vue from '@volar/vue-language-service';
import type * as ts from 'typescript/lib/tsserverlibrary';
import type { TextDocument } from 'vscode-languageserver-textdocument';
import * as vscode from 'vscode-languageserver';
import type { createLsConfigs } from './configHost';
import * as path from 'upath';
import { getDocumentSafely } from './utils';
import { LanguageConfigs, loadCustomPlugins, RuntimeEnvironment } from './common';
import { tsShared } from '@volar/vue-typescript';
export interface Project extends ReturnType<typeof createProject> { }
export const fileRenamings = new Set<Promise<void>>();
export const renameFileContentCache = new Map<string, string>();
export async function createProject(
runtimeEnv: RuntimeEnvironment,
languageConfigs: LanguageConfigs,
ts: typeof import('typescript/lib/tsserverlibrary'),
options: shared.ServerInitializationOptions,
rootPath: string,
tsConfig: string | ts.CompilerOptions,
tsLocalized: ts.MapLike<string> | undefined,
documents: vscode.TextDocuments<TextDocument>,
connection: vscode.Connection,
lsConfigs: ReturnType<typeof createLsConfigs> | undefined,
) {
await Promise.all([...fileRenamings]);
const projectSys: typeof ts.sys = {
...ts.sys,
readFile: (path, encoding) => ts.sys.readFile(resolveAbsolutePath(path), encoding),
writeFile: (path, content) => ts.sys.writeFile(resolveAbsolutePath(path), content),
directoryExists: path => {
if (path === '') {
// fix https://github.com/johnsoncodehk/volar/issues/679
return ts.sys.directoryExists(path);
}
return ts.sys.directoryExists(resolveAbsolutePath(path));
},
getDirectories: path => ts.sys.getDirectories(resolveAbsolutePath(path)),
readDirectory: (path, extensions, exclude, include, depth) => ts.sys.readDirectory(resolveAbsolutePath(path), extensions, exclude, include, depth),
realpath: ts.sys.realpath ? path => {
const resolvedPath = resolveAbsolutePath(path);
const realPath = ts.sys.realpath!(resolvedPath);
if (realPath === resolvedPath) {
// rollback if failed
return path;
}
return realPath;
} : undefined,
fileExists: path => ts.sys.fileExists(resolveAbsolutePath(path)),
getCurrentDirectory: () => rootPath,
};
let typeRootVersion = 0;
let projectVersion = 0;
let vueLs: vue.LanguageService | undefined;
let parsedCommandLine = createParsedCommandLine();
const scripts = shared.createPathMap<{
version: number,
fileName: string,
snapshot: ts.IScriptSnapshot | undefined,
snapshotVersion: number | undefined,
}>();
const languageServiceHost = createLanguageServiceHost();
return {
onWorkspaceFilesChanged,
onDocumentUpdated,
getLanguageService,
getLanguageServiceDontCreate: () => vueLs,
getParsedCommandLine: () => parsedCommandLine,
dispose,
};
function resolveAbsolutePath(_path: string) {
const relativePath = path.relative(ts.sys.getCurrentDirectory(), rootPath);
if (relativePath === '') {
return _path;
}
if (_path === '') {
return relativePath;
}
return _path;
}
function getLanguageService() {
if (!vueLs) {
vueLs = languageConfigs.createLanguageService(
{ typescript: ts },
languageServiceHost,
runtimeEnv.fileSystemProvide,
(uri) => {
const protocol = uri.substring(0, uri.indexOf(':'));
const builtInHandler = runtimeEnv.schemaRequestHandlers[protocol];
if (builtInHandler) {
return builtInHandler(uri);
}
if (typeof options === 'object' && options.languageFeatures?.schemaRequestService) {
return connection.sendRequest(shared.GetDocumentContentRequest.type, { uri }).then(responseText => {
return responseText;
}, error => {
return Promise.reject(error.message);
});
}
else {
return Promise.reject('clientHandledGetDocumentContentRequest is false');
}
},
lsConfigs,
loadCustomPlugins(languageServiceHost.getCurrentDirectory()),
options.languageFeatures?.completion ? async (uri) => {
if (options.languageFeatures?.completion?.getDocumentNameCasesRequest) {
const res = await connection.sendRequest(shared.GetDocumentNameCasesRequest.type, { uri });
return {
tag: res.tagNameCase,
attr: res.attrNameCase,
};
}
return {
tag: options.languageFeatures!.completion!.defaultTagNameCase,
attr: options.languageFeatures!.completion!.defaultAttrNameCase,
};
} : undefined,
);
}
return vueLs;
}
async function onWorkspaceFilesChanged(changes: vscode.FileEvent[]) {
await Promise.all([...fileRenamings]);
for (const change of changes) {
const script = scripts.uriGet(change.uri);
if (script && (change.type === vscode.FileChangeType.Changed || change.type === vscode.FileChangeType.Created)) {
if (script.version >= 0) {
script.version = -1;
}
else {
script.version--;
}
}
else if (script && change.type === vscode.FileChangeType.Deleted) {
scripts.uriDelete(change.uri);
}
projectVersion++;
}
const creates = changes.filter(change => change.type === vscode.FileChangeType.Created);
const deletes = changes.filter(change => change.type === vscode.FileChangeType.Deleted);
if (creates.length || deletes.length) {
parsedCommandLine = createParsedCommandLine();
typeRootVersion++; // TODO: check changed in node_modules?
}
}
async function onDocumentUpdated(document: TextDocument) {
await Promise.all([...fileRenamings]);
const script = scripts.uriGet(document.uri);
if (script) {
script.version = document.version;
}
projectVersion++;
}
function createLanguageServiceHost() {
const host: vue.LanguageServiceHost = {
// ts
getNewLine: () => projectSys.newLine,
useCaseSensitiveFileNames: () => projectSys.useCaseSensitiveFileNames,
readFile: projectSys.readFile,
writeFile: projectSys.writeFile,
directoryExists: projectSys.directoryExists,
getDirectories: projectSys.getDirectories,
readDirectory: projectSys.readDirectory,
realpath: projectSys.realpath,
fileExists: projectSys.fileExists,
getCurrentDirectory: projectSys.getCurrentDirectory,
getProjectReferences: () => parsedCommandLine.projectReferences, // if circular, broken with provide `getParsedCommandLine: () => parsedCommandLine`
// custom
getDefaultLibFileName: options => ts.getDefaultLibFilePath(options), // TODO: vscode option for ts lib
getProjectVersion: () => projectVersion.toString(),
getTypeRootsVersion: () => typeRootVersion,
getScriptFileNames: () => {
const fileNames = new Set(parsedCommandLine.fileNames);
for (const script of scripts.values()) {
fileNames.add(script.fileName);
}
return [...fileNames];
},
getCompilationSettings: () => parsedCommandLine.options,
getVueCompilationSettings: () => parsedCommandLine.vueOptions,
getScriptVersion,
getScriptSnapshot,
};
if (tsLocalized) {
host.getLocalizedDiagnosticMessages = () => tsLocalized;
}
return host;
function getScriptVersion(fileName: string) {
return scripts.fsPathGet(fileName)?.version.toString() ?? '';
}
function getScriptSnapshot(fileName: string) {
const script = scripts.fsPathGet(fileName);
if (script && script.snapshotVersion === script.version) {
return script.snapshot;
}
const text = getScriptText(documents, fileName, projectSys);
if (text !== undefined) {
const snapshot = ts.ScriptSnapshot.fromString(text);
if (script) {
script.snapshot = snapshot;
script.snapshotVersion = script.version;
}
else {
scripts.fsPathSet(fileName, {
version: -1,
fileName: fileName,
snapshot: snapshot,
snapshotVersion: -1,
});
}
return snapshot;
}
}
}
function dispose() {
vueLs?.dispose();
scripts.clear();
}
function createParsedCommandLine(): ReturnType<typeof tsShared.createParsedCommandLine> {
const parseConfigHost: ts.ParseConfigHost = {
useCaseSensitiveFileNames: projectSys.useCaseSensitiveFileNames,
readDirectory: (path, extensions, exclude, include, depth) => {
const exts = [...extensions, ...languageConfigs.definitelyExts];
for (const passiveExt of languageConfigs.indeterminateExts) {
if (include.some(i => i.endsWith(passiveExt))) {
exts.push(passiveExt);
}
}
return projectSys.readDirectory(path, exts, exclude, include, depth);
},
fileExists: projectSys.fileExists,
readFile: projectSys.readFile,
};
if (typeof tsConfig === 'string') {
return tsShared.createParsedCommandLine(ts, parseConfigHost, tsConfig);
}
else {
const content = ts.parseJsonConfigFileContent({}, parseConfigHost, rootPath, tsConfig, 'tsconfig.json');
content.options.outDir = undefined; // TODO: patching ts server broke with outDir + rootDir + composite/incremental
content.fileNames = content.fileNames.map(shared.normalizeFileName);
return { ...content, vueOptions: {} };
}
}
}
export function getScriptText(
documents: vscode.TextDocuments<TextDocument>,
fileName: string,
sys: typeof import('typescript/lib/tsserverlibrary')['sys'],
) {
const uri = shared.fsPathToUri(fileName);
const doc = getDocumentSafely(documents, uri);
if (doc) {
return doc.getText();
}
if (sys.fileExists(fileName)) {
return sys.readFile(fileName, 'utf8');
}
return renameFileContentCache.get(shared.fsPathToUri(fileName));
}