typescriptServiceClient.ts 21.3 KB
Newer Older
I
isidor 已提交
1 2 3 4 5
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

E
Erich Gamma 已提交
6 7 8 9 10 11 12 13 14
'use strict';

import * as cp from 'child_process';
import * as path from 'path';
import * as fs from 'fs';

import * as electron from './utils/electron';
import { Reader } from './utils/wireProtocol';

15
import { workspace, window, Uri, CancellationToken, OutputChannel, Memento, MessageItem }  from 'vscode';
E
Erich Gamma 已提交
16
import * as Proto from './protocol';
17
import { ITypescriptServiceClient, ITypescriptServiceClientHost, APIVersion }  from './typescriptService';
E
Erich Gamma 已提交
18

19
import * as VersionStatus from './utils/versionStatus';
20
import * as is from './utils/is';
E
Erich Gamma 已提交
21

22 23
import TelemetryReporter from 'vscode-extension-telemetry';

D
Dirk Baeumer 已提交
24 25 26
import * as nls from 'vscode-nls';
let localize = nls.loadMessageBundle();

E
Erich Gamma 已提交
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
interface CallbackItem {
	c: (value: any) => void;
	e: (err: any) => void;
	start: number;
}

interface CallbackMap {
	[key: number]: CallbackItem;
}

interface RequestItem {
	request: Proto.Request;
	promise: Promise<any>;
	callbacks: CallbackItem;
}

43 44 45 46 47 48
interface IPackageInfo {
	name: string;
	version: string;
	aiKey: string;
}

49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
enum Trace {
	Off, Messages, Verbose
}

namespace Trace {
	export function fromString(value: string): Trace {
		value = value.toLowerCase();
		switch (value) {
			case 'off':
				return Trace.Off;
			case 'messages':
				return Trace.Messages;
			case 'verbose':
				return Trace.Verbose;
			default:
				return Trace.Off;
		}
	}
}
E
Erich Gamma 已提交
68

69 70 71 72 73 74 75 76 77 78 79 80
enum MessageAction {
	useLocal,
	alwaysUseLocal,
	useBundled,
	doNotCheckAgain
}

interface MyMessageItem extends MessageItem  {
	id: MessageAction;
}


D
Dirk Baeumer 已提交
81
function openUrl(url: string) {
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
	let cmd: string;
	switch (process.platform) {
		case 'darwin':
			cmd = 'open';
			break;
		case 'win32':
			cmd = 'start';
			break;
		default:
			cmd = 'xdg-open';
	}
	return cp.exec(cmd + ' ' + url);
}


97
export default class TypeScriptServiceClient implements ITypescriptServiceClient {
E
Erich Gamma 已提交
98 99

	private host: ITypescriptServiceClientHost;
D
Dirk Baeumer 已提交
100
	private storagePath: string;
101
	private globalState: Memento;
E
Erich Gamma 已提交
102 103 104 105
	private pathSeparator: string;

	private _onReady: { promise: Promise<void>; resolve: () => void; reject: () => void; };
	private tsdk: string;
106
	private _experimentalAutoBuild: boolean;
107
	private trace: Trace;
108
	private _output: OutputChannel;
E
Erich Gamma 已提交
109 110 111 112 113 114 115 116 117 118 119 120 121
	private servicePromise: Promise<cp.ChildProcess>;
	private lastError: Error;
	private reader: Reader<Proto.Response>;
	private sequenceNumber: number;
	private exitRequested: boolean;
	private firstStart: number;
	private lastStart: number;
	private numberRestarts: number;

	private requestQueue: RequestItem[];
	private pendingResponses: number;
	private callbacks: CallbackMap;

122
	private _packageInfo: IPackageInfo;
123
	private _apiVersion: APIVersion;
124 125
	private telemetryReporter: TelemetryReporter;

126
	constructor(host: ITypescriptServiceClientHost, storagePath: string, globalState: Memento) {
E
Erich Gamma 已提交
127
		this.host = host;
D
Dirk Baeumer 已提交
128
		this.storagePath = storagePath;
129
		this.globalState = globalState;
E
Erich Gamma 已提交
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
		this.pathSeparator = path.sep;

		let p = new Promise<void>((resolve, reject) => {
			this._onReady = { promise: null, resolve, reject };
		});
		this._onReady.promise = p;

		this.servicePromise = null;
		this.lastError = null;
		this.sequenceNumber = 0;
		this.exitRequested = false;
		this.firstStart = Date.now();
		this.numberRestarts = 0;

		this.requestQueue = [];
		this.pendingResponses = 0;
		this.callbacks = Object.create(null);
147 148 149
		const configuration = workspace.getConfiguration();
		this.tsdk = configuration.get<string>('typescript.tsdk', null);
		this._experimentalAutoBuild = configuration.get<boolean>('typescript.tsserver.experimentalAutoBuild', false);
150
		this._apiVersion = APIVersion.v1_x;
151
		this.trace = this.readTrace();
E
Erich Gamma 已提交
152
		workspace.onDidChangeConfiguration(() => {
153
			this.trace = this.readTrace();
E
Erich Gamma 已提交
154 155 156 157 158 159
			let oldTask = this.tsdk;
			this.tsdk = workspace.getConfiguration().get<string>('typescript.tsdk', null);
			if (this.servicePromise === null && oldTask !== this.tsdk) {
				this.startService();
			}
		});
160 161 162
		if (this.packageInfo && this.packageInfo.aiKey) {
			this.telemetryReporter = new TelemetryReporter(this.packageInfo.name, this.packageInfo.version, this.packageInfo.aiKey);
		}
E
Erich Gamma 已提交
163 164 165
		this.startService();
	}

166 167 168 169 170 171 172
	private get output(): OutputChannel {
		if (!this._output) {
			this._output = window.createOutputChannel(localize('channelName', 'TypeScript'));
		}
		return this._output;
	}

173 174 175 176 177 178
	private readTrace(): Trace {
		let result: Trace = Trace.fromString(workspace.getConfiguration().get<string>('typescript.tsserver.trace', 'off'));
		if (result === Trace.Off && !!process.env.TSS_TRACE) {
			result = Trace.Messages;
		}
		return result;
E
Erich Gamma 已提交
179 180
	}

181 182 183 184
	public get experimentalAutoBuild(): boolean {
		return this._experimentalAutoBuild;
	}

185 186 187 188
	public get apiVersion(): APIVersion {
		return this._apiVersion;
	}

189 190
	public onReady(): Promise<void> {
		return this._onReady.promise;
E
Erich Gamma 已提交
191 192
	}

193 194 195 196 197 198 199
	private data2String(data: any): string {
		if (data instanceof Error) {
			if (is.string(data.stack)) {
				return data.stack;
			}
			return (data as Error).message;
		}
200
		if (is.boolean(data.success) && !data.success && is.string(data.message)) {
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
			return data.message;
		}
		if (is.string(data)) {
			return data;
		}
		return data.toString();
	}

	public info(message: string, data?: any): void {
		this.output.appendLine(`[Info  - ${(new Date().toLocaleTimeString())}] ${message}`);
		if (data) {
			this.output.appendLine(this.data2String(data));
		}
	}

	public warn(message: string, data?: any): void {
		this.output.appendLine(`[Warn  - ${(new Date().toLocaleTimeString())}] ${message}`);
		if (data) {
			this.output.appendLine(this.data2String(data));
		}
	}

	public error(message: string, data?: any): void {
224 225 226 227
		// See https://github.com/Microsoft/TypeScript/issues/10496
		if (data && data.message === 'No content available.') {
			return;
		}
228 229 230 231
		this.output.appendLine(`[Error - ${(new Date().toLocaleTimeString())}] ${message}`);
		if (data) {
			this.output.appendLine(this.data2String(data));
		}
232 233
		// VersionStatus.enable(true);
		// this.output.show(true);
234 235 236 237 238 239 240
	}

	private logTrace(message: string, data?: any): void {
		this.output.appendLine(`[Trace - ${(new Date().toLocaleTimeString())}] ${message}`);
		if (data) {
			this.output.appendLine(this.data2String(data));
		}
241
		// this.output.show(true);
242 243
	}

244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
	private get packageInfo(): IPackageInfo {

		if (this._packageInfo !== undefined) {
			return this._packageInfo;
		}
		let packagePath = path.join(__dirname, './../package.json');
		let extensionPackage = require(packagePath);
		if (extensionPackage) {
			this._packageInfo = {
				name: extensionPackage.name,
				version: extensionPackage.version,
				aiKey: extensionPackage.aiKey
			};
		} else {
			this._packageInfo = null;
		}

		return this._packageInfo;
	}

264
	public logTelemetry(eventName: string, properties?: {[prop: string]: string}) {
265 266 267 268 269
		if (this.telemetryReporter) {
			this.telemetryReporter.sendTelemetryEvent(eventName, properties);
		}
	}

E
Erich Gamma 已提交
270 271 272 273 274 275 276 277 278 279 280 281 282
	private service(): Promise<cp.ChildProcess> {
		if (this.servicePromise) {
			return this.servicePromise;
		}
		if (this.lastError) {
			return Promise.reject<cp.ChildProcess>(this.lastError);
		}
		this.startService();
		return this.servicePromise;
	}

	private startService(resendModels: boolean = false): void {
		let modulePath = path.join(__dirname, '..', 'server', 'typescript', 'lib', 'tsserver.js');
283
		let checkGlobalVersion = true;
D
Dirk Baeumer 已提交
284
		let showVersionStatusItem = false;
D
Dirk Baeumer 已提交
285

E
Erich Gamma 已提交
286
		if (this.tsdk) {
287
			checkGlobalVersion = false;
E
Erich Gamma 已提交
288 289 290 291 292 293
			if ((<any>path).isAbsolute(this.tsdk)) {
				modulePath = path.join(this.tsdk, 'tsserver.js');
			} else if (workspace.rootPath) {
				modulePath = path.join(workspace.rootPath, this.tsdk, 'tsserver.js');
			}
		}
294 295 296
		let versionCheckPromise: Thenable<string> = Promise.resolve(modulePath);
		const doLocalVersionCheckKey: string = 'doLocalVersionCheck';

297
		if (!this.tsdk && workspace.rootPath) {
298 299 300 301 302 303 304 305 306
			let localModulePath = path.join(workspace.rootPath, 'node_modules', 'typescript', 'lib', 'tsserver.js');
			if (fs.existsSync(localModulePath)) {
				let localVersion = this.getTypeScriptVersion(localModulePath);
				let shippedVersion = this.getTypeScriptVersion(modulePath);
				if (localVersion && localVersion !== shippedVersion) {
					checkGlobalVersion = false;
					versionCheckPromise = window.showInformationMessage<MyMessageItem>(
						localize(
							'localTSFound',
307
							'The workspace folder contains TypeScript version {0}. Do you want to use this version instead of the bundled version {1}?',
308 309
							localVersion, shippedVersion
						),
310
						{
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
							title: localize('use', 'Use {0}', localVersion),
							id: MessageAction.useLocal
						},
						{
							title: localize('useBundled', 'Use {0}', shippedVersion),
							id: MessageAction.useBundled,
						},
						{
							title: localize('useAlways', /*'Always use {0}'*/ 'More Information', localVersion),
							id: MessageAction.alwaysUseLocal
						},
						{
							title: localize('doNotCheckAgain', 'Don\'t Check Again'),
							id: MessageAction.doNotCheckAgain,
							isCloseAffordance: true
326
						}
327 328 329 330 331 332
					).then((selected) => {
						if (!selected) {
							return modulePath;
						}
						switch(selected.id) {
							case MessageAction.useLocal:
D
Dirk Baeumer 已提交
333
								showVersionStatusItem = true;
334 335 336
								return localModulePath;
							case MessageAction.alwaysUseLocal:
								window.showInformationMessage(localize('continueWithVersion', 'Continuing with version {0}', shippedVersion));
D
Dirk Baeumer 已提交
337
								openUrl('http://go.microsoft.com/fwlink/?LinkId=826239');
338 339 340 341 342 343 344 345 346 347 348
								return modulePath;
							case MessageAction.useBundled:
								return modulePath;
							case MessageAction.doNotCheckAgain:
								this.globalState.update(doLocalVersionCheckKey, false);
								return modulePath;
							default:
								return modulePath;
						}
					});
				}
349 350
			} else {
				this.informAboutTS20();
351
			}
E
Erich Gamma 已提交
352
		}
353 354 355 356 357 358
		versionCheckPromise.then((modulePath) => {
			this.info(`Using tsserver from location: ${modulePath}`);
			if (!fs.existsSync(modulePath)) {
				window.showErrorMessage(localize('noServerFound', 'The path {0} doesn\'t point to a valid tsserver install. TypeScript language features will be disabled.', path.dirname(modulePath)));
				return;
			}
359

360 361 362 363 364 365 366 367 368 369 370
			let version = this.getTypeScriptVersion(modulePath);
			if (!version) {
				version = workspace.getConfiguration().get<string>('typescript.tsdk_version', undefined);
			}
			if (version) {
				this._apiVersion = APIVersion.fromString(version);
			}


			const label = version || localize('versionNumber.custom' ,'custom');
			const tooltip = modulePath;
D
Dirk Baeumer 已提交
371
			VersionStatus.enable(!!this.tsdk || showVersionStatusItem);
372 373 374 375 376 377 378 379 380 381 382 383
			VersionStatus.setInfo(label, tooltip);

			const doGlobalVersionCheckKey: string = 'doGlobalVersionCheck';
			if (checkGlobalVersion && this.globalState.get(doGlobalVersionCheckKey, true)) {
				let tscVersion: string = undefined;
				try {
					let out = cp.execSync('tsc --version', { encoding: 'utf8' });
					if (out) {
						let matches = out.trim().match(/Version\s*(.*)$/);
						if (matches && matches.length === 2) {
							tscVersion = matches[1];
						}
E
Erich Gamma 已提交
384
					}
385
				} catch (error) {
E
Erich Gamma 已提交
386
				}
387
				if (tscVersion && tscVersion !== version) {
388
					window.showInformationMessage<MyMessageItem>(
389
						localize('versionMismatch', 'A version mismatch between the globally installed tsc compiler ({0}) and VS Code\'s language service ({1}) has been detected. This might result in inconsistent compile errors.', tscVersion, version),
390
						{
R
Rob Lourens 已提交
391
							title: localize('moreInformation', 'More Information'),
392 393 394 395 396 397
							id: 1
						},
						{
							title: localize('doNotCheckAgain', 'Don\'t Check Again'),
							id: 2,
							isCloseAffordance: true
398
						}
399 400 401 402 403 404
					).then((selected) => {
						if (!selected) {
							return;
						}
						switch (selected.id) {
							case 1:
D
Dirk Baeumer 已提交
405
								openUrl('http://go.microsoft.com/fwlink/?LinkId=826239');
406 407 408 409 410
								break;
							case 2:
								this.globalState.update(doGlobalVersionCheckKey, false);
								break;
						}
E
Erich Gamma 已提交
411
					});
412
				}
E
Erich Gamma 已提交
413
			}
414 415 416 417

			this.servicePromise = new Promise<cp.ChildProcess>((resolve, reject) => {
				try {
					let options: electron.IForkOptions = {
418
						execArgv: [`--debug-brk=5859`]
419
					};
420 421 422
					if (workspace.rootPath) {
						options.cwd = fs.realpathSync(workspace.rootPath);
					}
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
					let value = process.env.TSS_DEBUG;
					if (value) {
						let port = parseInt(value);
						if (!isNaN(port)) {
							this.info(`TSServer started in debug mode using port ${port}`);
							options.execArgv = [`--debug=${port}`];
						}
					}
					electron.fork(modulePath, [], options, (err: any, childProcess: cp.ChildProcess) => {
						if (err) {
							this.lastError = err;
							this.error('Starting TSServer failed with error.', err);
							window.showErrorMessage(localize('serverCouldNotBeStarted', 'TypeScript language server couldn\'t be started. Error message is: {0}', err.message || err));
							this.logTelemetry('error', {message: err.message});
							return;
						}
						this.lastStart = Date.now();
						childProcess.on('error', (err: Error) => {
							this.lastError = err;
							this.error('TSServer errored with error.', err);
							this.serviceExited(false);
						});
						childProcess.on('exit', (code: any) => {
							this.error(`TSServer exited with code: ${code ? code : 'unknown'}`);
							this.serviceExited(true);
						});
						this.reader = new Reader<Proto.Response>(childProcess.stdout, (msg) => {
							this.dispatchMessage(msg);
						});
						this._onReady.resolve();
						resolve(childProcess);
					});
				} catch (error) {
					reject(error);
				}
			});
			this.serviceStarted(resendModels);
E
Erich Gamma 已提交
460 461 462
		});
	}

463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
	private informAboutTS20(): void {
		const informAboutTS20: string = 'informAboutTS20';
		if (!this.globalState.get(informAboutTS20, false)) {
			window.showInformationMessage(
				localize(
					'tsversion20',
					'VS Code version 1.6 ships with TypeScript version 2.0.x. If you have to use a previous version of typescript set the \'typescript.tsdk\' option.'
				),
				{
					title: localize('moreInformation', 'More Information'),
					id: 1
				}
			).then((selected) => {
				this.globalState.update(informAboutTS20, true);
				if (selected && selected.id === 1) {
					openUrl('https://go.microsoft.com/fwlink/?LinkID=533483#vscode');
				}
			});
		}
	}

E
Erich Gamma 已提交
484
	private serviceStarted(resendModels: boolean): void {
485
		if (this._experimentalAutoBuild && this.storagePath) {
D
Dirk Baeumer 已提交
486 487 488 489
			try {
				fs.mkdirSync(this.storagePath);
			} catch(error) {
			}
490 491 492 493
			this.execute('configure', {
				autoBuild: true,
				metaDataDirectory: this.storagePath
			});
D
Dirk Baeumer 已提交
494
		}
E
Erich Gamma 已提交
495 496 497 498 499
		if (resendModels) {
			this.host.populateService();
		}
	}

500
	private getTypeScriptVersion(serverPath: string): string {
501 502
		let p = serverPath.split(path.sep);
		if (p.length <= 2) {
503
			return undefined;
504 505 506 507 508
		}
		let p2 = p.slice(0, -2);
		let modulePath = p2.join(path.sep);
		let fileName = path.join(modulePath, 'package.json');
		if (!fs.existsSync(fileName)) {
509
			return undefined;
510 511
		}
		let contents = fs.readFileSync(fileName).toString();
512
		let desc = null;
513 514 515
		try {
			desc = JSON.parse(contents);
		} catch(err) {
516
			return undefined;
517 518
		}
		if (!desc.version) {
519
			return undefined;
520
		}
521
		return desc.version;
522 523
	}

E
Erich Gamma 已提交
524 525 526 527 528 529 530 531 532 533 534 535
	private serviceExited(restart: boolean): void {
		this.servicePromise = null;
		Object.keys(this.callbacks).forEach((key) => {
			this.callbacks[parseInt(key)].e(new Error('Service died.'));
		});
		this.callbacks = Object.create(null);
		if (!this.exitRequested && restart) {
			let diff = Date.now() - this.lastStart;
			this.numberRestarts++;
			let startService = true;
			if (this.numberRestarts > 5) {
				if (diff < 60 * 1000 /* 1 Minutes */) {
P
Paul van Brenk 已提交
536
					window.showWarningMessage(localize('serverDied','The TypeScript language service died unexpectedly 5 times in the last 5 Minutes. Please consider to open a bug report.'));
E
Erich Gamma 已提交
537 538
				} else if (diff < 2 * 1000 /* 2 seconds */) {
					startService = false;
P
Paul van Brenk 已提交
539
					window.showErrorMessage(localize('serverDiedAfterStart', 'The TypeScript language service died 5 times right after it got started. The service will not be restarted. Please open a bug report.'));
540
					this.logTelemetry('serviceExited');
E
Erich Gamma 已提交
541 542 543 544 545 546 547 548 549 550 551 552 553 554
				}
			}
			if (startService) {
				this.startService(true);
			}
		}
	}

	public asAbsolutePath(resource: Uri): string {
		if (resource.scheme !== 'file') {
			return null;
		}
		let result = resource.fsPath;
		// Both \ and / must be escaped in regular expressions
555
		return result ? fs.realpathSync(result.replace(new RegExp('\\' + this.pathSeparator, 'g'), '/')) : null;
E
Erich Gamma 已提交
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
	}

	public asUrl(filepath: string): Uri {
		return Uri.file(filepath);
	}

	public execute(command: string, args: any, expectsResultOrToken?: boolean | CancellationToken, token?: CancellationToken): Promise<any> {
		let expectsResult = true;
		if (typeof expectsResultOrToken === 'boolean') {
			expectsResult = expectsResultOrToken;
		} else {
			token = expectsResultOrToken;
		}

		let request: Proto.Request = {
			seq: this.sequenceNumber++,
			type: 'request',
			command: command,
			arguments: args
		};
		let requestInfo: RequestItem = {
			request: request,
			promise: null,
			callbacks: null
		};
		let result: Promise<any> = null;
		if (expectsResult) {
			result = new Promise<any>((resolve, reject) => {
				requestInfo.callbacks = { c: resolve, e: reject, start: Date.now() };
				if (token) {
					token.onCancellationRequested(() => {
						this.tryCancelRequest(request.seq);
588
						resolve(undefined);
E
Erich Gamma 已提交
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
					});
				}
			});
		}
		requestInfo.promise = result;
		this.requestQueue.push(requestInfo);
		this.sendNextRequests();

		return result;
	}

	private sendNextRequests(): void {
		while (this.pendingResponses === 0 && this.requestQueue.length > 0) {
			this.sendRequest(this.requestQueue.shift());
		}
	}

	private sendRequest(requestItem: RequestItem): void {
		let serverRequest = requestItem.request;
608
		this.traceRequest(serverRequest, !!requestItem.callbacks);
E
Erich Gamma 已提交
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
		if (requestItem.callbacks) {
			this.callbacks[serverRequest.seq] = requestItem.callbacks;
			this.pendingResponses++;
		}
		this.service().then((childProcess) => {
			childProcess.stdin.write(JSON.stringify(serverRequest) + '\r\n', 'utf8');
		}).catch(err => {
			let callback = this.callbacks[serverRequest.seq];
			if (callback) {
				callback.e(err);
				delete this.callbacks[serverRequest.seq];
				this.pendingResponses--;
			}
		});
	}

	private tryCancelRequest(seq: number): boolean {
		for (let i = 0; i < this.requestQueue.length; i++) {
			if (this.requestQueue[i].request.seq === seq) {
				this.requestQueue.splice(i, 1);
629
				if (this.trace !== Trace.Off) {
630
					this.logTrace(`TypeScript Service: canceled request with sequence number ${seq}`);
E
Erich Gamma 已提交
631 632 633 634
				}
				return true;
			}
		}
635
		if (this.trace !== Trace.Off) {
636
			this.logTrace(`TypeScript Service: tried to cancel request with sequence number ${seq}. But request got already delivered.`);
E
Erich Gamma 已提交
637 638 639 640 641 642 643 644 645 646
		}
		return false;
	}

	private dispatchMessage(message: Proto.Message): void {
		try {
			if (message.type === 'response') {
				let response: Proto.Response = <Proto.Response>message;
				let p = this.callbacks[response.request_seq];
				if (p) {
647
					this.traceResponse(response, p.start);
E
Erich Gamma 已提交
648 649 650 651 652
					delete this.callbacks[response.request_seq];
					this.pendingResponses--;
					if (response.success) {
						p.c(response);
					} else {
653 654 655 656 657
						this.logTelemetry('requestFailed', {
							id: response.request_seq.toString(),
							command: response.command,
							message: response.message ? response.message : 'No detailed message provided'
						});
E
Erich Gamma 已提交
658 659 660 661 662
						p.e(response);
					}
				}
			} else if (message.type === 'event') {
				let event: Proto.Event = <Proto.Event>message;
663
				this.traceEvent(event);
E
Erich Gamma 已提交
664
				if (event.event === 'syntaxDiag') {
665 666 667 668 669
					this.host.syntaxDiagnosticsReceived(event as Proto.DiagnosticEvent);
				} else if (event.event === 'semanticDiag') {
					this.host.semanticDiagnosticsReceived(event as Proto.DiagnosticEvent);
				} else if (event.event === 'configFileDiag') {
					this.host.configFileDiagnosticsReceived(event as Proto.ConfigFileDiagnosticEvent);
E
Erich Gamma 已提交
670 671 672 673 674 675 676 677
				}
			} else {
				throw new Error('Unknown message type ' + message.type + ' recevied');
			}
		} finally {
			this.sendNextRequests();
		}
	}
678 679 680 681 682

	private traceRequest(request: Proto.Request, responseExpected: boolean): void {
		if (this.trace === Trace.Off) {
			return;
		}
683
		let data: string = undefined;
684
		if (this.trace === Trace.Verbose && request.arguments) {
685
			data = `Arguments: ${JSON.stringify(request.arguments, null, 4)}`;
686
		}
687
		this.logTrace(`Sending request: ${request.command} (${request.seq}). Response expected: ${responseExpected ? 'yes' : 'no'}. Current queue length: ${this.requestQueue.length}`, data);
688 689 690 691 692 693
	}

	private traceResponse(response: Proto.Response, startTime: number): void {
		if (this.trace === Trace.Off) {
			return;
		}
694
		let data: string = undefined;
695
		if (this.trace === Trace.Verbose && response.body) {
696
			data = `Result: ${JSON.stringify(response.body, null, 4)}`;
697
		}
698
		this.logTrace(`Response received: ${response.command} (${response.request_seq}). Request took ${Date.now() - startTime} ms. Success: ${response.success} ${!response.success ? '. Message: ' + response.message : ''}`, data);
699 700 701 702 703 704
	}

	private traceEvent(event: Proto.Event): void {
		if (this.trace === Trace.Off) {
			return;
		}
705
		let data: string = undefined;
706
		if (this.trace === Trace.Verbose && event.body) {
707
			data = `Data: ${JSON.stringify(event.body, null, 4)}`;
708
		}
709
		this.logTrace(`Event received: ${event.event} (${event.seq}).`, data);
710
	}
E
Erich Gamma 已提交
711
}