-
Notifications
You must be signed in to change notification settings - Fork 964
Expand file tree
/
Copy pathts-server-client.ts
More file actions
435 lines (392 loc) · 14.8 KB
/
Copy pathts-server-client.ts
File metadata and controls
435 lines (392 loc) · 14.8 KB
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
import fs from 'fs-extra';
import type { Logger } from '@teambit/logger';
import path from 'path';
import type ts from 'typescript/lib/tsserverlibrary';
import { CheckTypes } from '@teambit/watcher';
import type { Position } from 'vscode-languageserver-types';
import commandExists from 'command-exists';
import { findPathToModule } from './modules-resolver';
import { ProcessBasedTsServer } from './process-based-tsserver';
import { CommandTypes, EventName } from './tsp-command-types';
import { getTsserverExecutable } from './utils';
import type { Diagnostic } from './format-diagnostics';
import { formatDiagnostic } from './format-diagnostics';
export type TsserverClientOpts = {
verbose?: boolean; // print tsserver events to the console.
tsServerPath?: string; // if not provided, it'll use findTsserverPath() strategies.
checkTypes?: CheckTypes; // whether errors/warnings are monitored and printed to the console.
printTypeErrors?: boolean; // whether print typescript errors to the console.
aggregateDiagnosticData?: boolean; // whether to aggregate diagnostic data instead of printing them to the console.
/**
* if false, files passed to the constructor are NOT opened during init().
* useful when the caller wants to control opening (e.g. batched open/close in `getDiagnostic`).
* default: true (backward compatible).
*/
openFilesOnInit?: boolean;
};
export type DiagnosticData = {
file: string;
diagnostic: Diagnostic;
formatted: string;
};
export class TsserverClient {
private tsServer: ProcessBasedTsServer | null;
public lastDiagnostics: ts.server.protocol.DiagnosticEventBody[] = [];
private serverRunning = false;
private filesPreOpenedOnInit = false;
public diagnosticData: DiagnosticData[] = [];
constructor(
/**
* absolute root path of the project.
*/
private projectPath: string,
private logger: Logger,
private options: TsserverClientOpts = {},
/**
* provide files if you want to check types on init. (options.checkTypes should be enabled).
* paths should be absolute.
*/
private files: string[] = []
) {}
/**
* start the ts-server and keep its process alive.
* this methods returns pretty fast. if checkTypes is enabled, it runs the process in the background and
* doesn't wait for it.
*/
async init(): Promise<void> {
try {
this.tsServer = new ProcessBasedTsServer({
logger: this.logger,
tsserverPath: this.findTsserverPath(),
logToConsole: this.options.verbose,
onEvent: this.onTsserverEvent.bind(this),
});
// Await the server to be ready before issuing any requests, so a start() failure
// (e.g., tsserver writing to stderr) surfaces here rather than producing a write to a
// broken stdin, and so the inferred-project options below are applied to a live server.
await this.tsServer.start();
this.serverRunning = true;
// TS 6 flipped the `strict` default from false to true for inferred projects.
// Files outside any tsconfig (e.g., components whose env's tsconfig isn't included
// by the workspace config writer) would otherwise get strict-mode errors that didn't
// surface in TS 5. Pin inferred-project options to the TS 5 default to preserve behavior.
await this.setCompilerOptionsForInferredProjects({ strict: false });
const shouldOpenFiles = this.options.openFilesOnInit !== false;
if (this.files.length && shouldOpenFiles) {
const openResults = await Promise.all(
this.files.map((file) => this.open(file).catch((error: unknown) => error))
);
const failedFiles = openResults.filter((result) => result instanceof Error);
if (failedFiles.length > 0) {
this.logger.error('TsserverClient.init failed to open files:', failedFiles);
}
this.filesPreOpenedOnInit = true;
this.checkTypesIfNeeded();
}
this.logger.debug('TsserverClient.init completed');
} catch (err) {
// Rethrow so callers know the server didn't come up. Swallowing here would leave
// `this.tsServer` set but unusable, and subsequent `request()` calls would silently
// return undefined via optional chaining — producing false-clean check-types runs.
this.logger.error('TsserverClient.init failed', err);
this.tsServer = null;
this.serverRunning = false;
throw err;
}
}
private checkTypesIfNeeded(files = this.files) {
if (!this.shouldCheckTypes()) {
return;
}
const start = Date.now();
this.getDiagnostic(files)
.then(() => {
const end = Date.now() - start;
const msg = `completed type checking (${end / 1000} sec)`;
if (this.lastDiagnostics.length) {
this.logger.consoleFailure(`${msg}. found errors in ${this.lastDiagnostics.length} files.`);
} else {
this.logger.consoleSuccess(`${msg}. no errors were found.`);
}
})
.catch((err) => {
const msg = `failed getting the type errors from ts-server`;
this.logger.console(msg);
this.logger.error(msg, err);
});
}
private shouldCheckTypes() {
// this also covers this.options.checkTypes !== CheckTypes.None.
return Boolean(this.options.checkTypes);
}
/**
* if `bit watch` or `bit start` are running in the background, this method is triggered.
*/
async onFileChange(file: string) {
await this.changed(file);
const files = this.options.checkTypes === CheckTypes.ChangedFile ? [file] : undefined;
this.checkTypesIfNeeded(files);
}
killTsServer() {
if (this.tsServer && this.serverRunning) {
this.tsServer.kill();
this.tsServer = null;
this.serverRunning = false;
}
}
isServerRunning() {
return this.serverRunning;
}
/**
* get diagnostic of all files opened in the project.
* there is little to no value of getting diagnostic for a specific file, as
* changing a type in one file may cause errors in different files.
*
* the errors/diagnostic info are sent as events, see this.onTsserverEvent() for more info.
*
* the return value here just shows whether the request was succeeded, it doesn't have any info about whether errors
* were found or not.
*
* @param files files to check
* @param batchSize if provided, files will be processed in batches. when files were not pre-opened
* via init(), each batch is opened, checked, then closed — keeping tsserver memory
* bounded by the batch size to avoid OOM in large workspaces.
*/
async getDiagnostic(files = this.files, batchSize?: number): Promise<any> {
this.lastDiagnostics = [];
if (!batchSize || files.length <= batchSize) {
return this.tsServer?.request(CommandTypes.Geterr, { delay: 0, files });
}
const filesArePreOpened = this.filesPreOpenedOnInit && files.every((f) => this.files.includes(f));
const total = files.length;
try {
for (let i = 0; i < files.length; i += batchSize) {
const batch = files.slice(i, i + batchSize);
const upTo = Math.min(i + batchSize, total);
this.logger.setStatusLine(`type-checking files ${i + 1}-${upTo} of ${total}`);
if (!filesArePreOpened) {
await this.openFiles(batch);
}
try {
await this.tsServer?.request(CommandTypes.Geterr, { delay: 0, files: batch });
} finally {
if (!filesArePreOpened) {
await this.closeFiles(batch).catch((err) => this.logger.error('failed to close batch', err));
}
}
}
} finally {
this.logger.clearStatusLine();
}
}
/**
* open multiple files in a single round-trip. useful when batching to bound tsserver memory.
*/
async openFiles(files: string[]): Promise<void> {
if (!files.length) return;
await this.tsServer?.request(CommandTypes.UpdateOpen, {
openFiles: files.map((file) => ({ file, projectRootPath: this.projectPath })),
});
}
/**
* close multiple files in a single round-trip.
*/
async closeFiles(files: string[]): Promise<void> {
if (!files.length) return;
await this.tsServer?.request(CommandTypes.UpdateOpen, {
closedFiles: files,
});
}
/**
* avoid using this method, it takes longer than `getDiagnostic()` and shows errors from paths outside the project
*/
async getDiagnosticAllProject(requestedByFile: string): Promise<any> {
return this.tsServer?.request(CommandTypes.GeterrForProject, { file: requestedByFile, delay: 0 });
}
/**
* @param file can be absolute or relative to this.projectRoot.
*/
async getQuickInfo(file: string, position: Position): Promise<ts.server.protocol.QuickInfoResponse | undefined> {
const absFile = this.convertFileToAbsoluteIfNeeded(file);
await this.openIfNeeded(absFile);
return this.tsServer?.request(CommandTypes.Quickinfo, {
file: absFile,
line: position.line,
offset: position.character,
});
}
/**
* @param file can be absolute or relative to this.projectRoot.
*/
async getTypeDefinition(
file: string,
position: Position
): Promise<ts.server.protocol.TypeDefinitionResponse | undefined> {
const absFile = this.convertFileToAbsoluteIfNeeded(file);
await this.openIfNeeded(absFile);
return this.tsServer?.request(CommandTypes.TypeDefinition, {
file: absFile,
line: position.line,
offset: position.character,
});
}
async getDefinition(file: string, position: Position) {
const absFile = this.convertFileToAbsoluteIfNeeded(file);
await this.openIfNeeded(absFile);
const response = await this.tsServer?.request(CommandTypes.Definition, {
file: absFile,
line: position.line,
offset: position.character,
});
if (!response?.success) {
// TODO: we need a function to handle responses properly here for all.
this.logger.warn(`For file ${absFile} tsserver failed to request definition info`);
return response;
}
return response;
}
/**
* @param file can be absolute or relative to this.projectRoot.
*/
async getReferences(file: string, position: Position): Promise<ts.server.protocol.ReferencesResponse | undefined> {
const absFile = this.convertFileToAbsoluteIfNeeded(file);
await this.openIfNeeded(absFile);
return this.tsServer?.request(CommandTypes.References, {
file: absFile,
line: position.line,
offset: position.character,
});
}
/**
* @param file can be absolute or relative to this.projectRoot.
*/
async getSignatureHelp(
file: string,
position: Position
): Promise<ts.server.protocol.SignatureHelpResponse | undefined> {
const absFile = this.convertFileToAbsoluteIfNeeded(file);
await this.openIfNeeded(absFile);
return this.tsServer?.request(CommandTypes.SignatureHelp, {
file: absFile,
line: position.line,
offset: position.character,
});
}
private async configure(
configureArgs: ts.server.protocol.ConfigureRequestArguments = {}
): Promise<ts.server.protocol.ConfigureResponse | undefined> {
return this.tsServer?.request(CommandTypes.Configure, configureArgs);
}
private async setCompilerOptionsForInferredProjects(
options: ts.server.protocol.ExternalProjectCompilerOptions
): Promise<void> {
await this.tsServer?.request(CommandTypes.CompilerOptionsForInferredProjects, { options });
}
/**
* ask tsserver to open a file if it was not opened before.
* @param file absolute path of the file
*/
async openIfNeeded(file: string) {
if (this.files.includes(file)) {
return;
}
await this.open(file);
this.files.push(file);
}
private async open(file: string) {
return this.tsServer?.notify(CommandTypes.Open, {
file,
projectRootPath: this.projectPath,
});
}
async close(file: string) {
await this.tsServer?.notify(CommandTypes.Close, {
file,
});
this.files = this.files.filter((openFile) => openFile !== file);
}
/**
* since Bit is not an IDE, it doesn't have the information such as the exact line/offset of the changes.
* as a workaround, to tell tsserver what was changed, we pretend that the entire file was cleared and new text was
* added. this is the only way I could find to tell tsserver about the change. otherwise, tsserver keep assuming that
* the file content remained the same. (closing/re-opening the file doesn't help).
*/
async changed(file: string) {
// tell tsserver that all content was removed
await this.tsServer?.notify(CommandTypes.Change, {
file,
line: 1,
offset: 1,
endLine: 99999,
endOffset: 1,
insertString: '',
});
const content = await fs.readFile(file, 'utf-8');
// tell tsserver that all file content was added
await this.tsServer?.notify(CommandTypes.Change, {
file,
line: 1,
offset: 1,
endLine: 1,
endOffset: 1,
insertString: content,
});
}
protected onTsserverEvent(event: ts.server.protocol.Event): void {
switch (event.event) {
case EventName.semanticDiag:
case EventName.syntaxDiag:
this.publishDiagnostic(event as ts.server.protocol.DiagnosticEvent);
break;
default:
this.logger.debug(`ignored TsServer event: ${event.event}`);
}
}
private convertFileToAbsoluteIfNeeded(filepath: string): string {
if (path.isAbsolute(filepath)) {
return filepath;
}
return path.join(this.projectPath, filepath);
}
private publishDiagnostic(message: ts.server.protocol.DiagnosticEvent) {
if (!message.body?.diagnostics.length || (!this.options.printTypeErrors && !this.options.aggregateDiagnosticData)) {
return;
}
this.lastDiagnostics.push(message.body);
const file = path.relative(this.projectPath, message.body.file);
message.body.diagnostics.forEach((diag) => {
const formatted = formatDiagnostic(diag, file);
if (this.options.printTypeErrors) {
this.logger.console(formatted);
}
if (this.options.aggregateDiagnosticData) {
this.diagnosticData.push({
file,
diagnostic: diag,
formatted,
});
}
});
}
/**
* copied over from https://github.com/typescript-language-server/typescript-language-server/blob/master/src/lsp-server.ts
*/
private findTsserverPath(): string {
if (this.options.tsServerPath) {
return this.options.tsServerPath;
}
const tsServerPath = path.join('typescript', 'lib', 'tsserver.js');
/**
* (1) find it in the bit directory
*/
const bundled = findPathToModule(__dirname, tsServerPath);
if (bundled) {
return bundled;
}
// (2) use globally installed tsserver
if (commandExists.sync(getTsserverExecutable())) {
return getTsserverExecutable();
}
throw new Error(`Couldn't find '${getTsserverExecutable()}' executable or 'tsserver.js' module`);
}
}