typescriptServiceClient.ts 22.9 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
enum MessageAction {
	useLocal,
	useBundled,
D
Dirk Baeumer 已提交
72 73
	neverCheckLocalVersion,
	close
74 75 76 77 78 79 80
}

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');
			}
		}
D
Dirk Baeumer 已提交
294 295
		const tsConfig = workspace.getConfiguration('typescript');
		const checkWorkspaceVersionKey = 'check.workspaceVersion';
296
		let versionCheckPromise: Thenable<string> = Promise.resolve(modulePath);
D
Dirk Baeumer 已提交
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318

		if (!workspace.rootPath) {
			versionCheckPromise = this.informAboutTS20(modulePath);
		} else {
			if (!this.tsdk && tsConfig.get(checkWorkspaceVersionKey, true)) {
				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',
								'The workspace folder contains TypeScript version {0}. Do you want to use this version instead of the bundled version {1}?',
								localVersion, shippedVersion
							),
							{
								title: localize('use', 'Use Workspace ({0})', localVersion),
								id: MessageAction.useLocal
							},
							{
319 320 321 322
								title: localize({
									key: 'useBundled',
									comment: ["Bundled has the meaning of packaged with VS Code itself."]
								}, 'Use Bundled ({0})', shippedVersion),
D
Dirk Baeumer 已提交
323 324 325 326
								id: MessageAction.useBundled,
							},
							{
								title: localize('neverCheckLocalVesion', 'Never Check for Workspace Version'),
327
								id: MessageAction.neverCheckLocalVersion
D
Dirk Baeumer 已提交
328 329 330 331 332
							},
							{
								title: localize('close', 'Close'),
								id: MessageAction.close,
								isCloseAffordance: true
D
Dirk Baeumer 已提交
333 334
							}
						).then((selected) => {
D
Dirk Baeumer 已提交
335
							if (!selected || selected.id === MessageAction.close) {
336
								return modulePath;
D
Dirk Baeumer 已提交
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
							}
							switch(selected.id) {
								case MessageAction.useLocal:
									let pathValue = './node_modules/typescript/lib';
									tsConfig.update('tsdk', pathValue, false);
									window.showInformationMessage(localize('updatedtsdk', 'Updated workspace setting \'typescript.tsdk\' to {0}', pathValue));
									showVersionStatusItem = true;
									return localModulePath;
								case MessageAction.useBundled:
									tsConfig.update(checkWorkspaceVersionKey, false, false);
									window.showInformationMessage(localize('updateLocalWorkspaceCheck', 'Updated workspace setting \'typescript.check.workspaceVersion\' to false'));
									return modulePath;
								case MessageAction.neverCheckLocalVersion:
									window.showInformationMessage(localize('updateGlobalWorkspaceCheck', 'Updated user setting \'typescript.check.workspaceVersion\' to false'));
									tsConfig.update(checkWorkspaceVersionKey, false, true);
									return modulePath;
								default:
									return modulePath;
							}
						});
					}
				} else {
					versionCheckPromise = this.informAboutTS20(modulePath);
360 361
				}
			}
E
Erich Gamma 已提交
362
		}
D
Dirk Baeumer 已提交
363

364 365 366 367 368 369
		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;
			}
370

371 372 373 374 375 376 377 378 379 380 381
			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 已提交
382
			VersionStatus.enable(!!this.tsdk || showVersionStatusItem);
383 384 385
			VersionStatus.setInfo(label, tooltip);

			const doGlobalVersionCheckKey: string = 'doGlobalVersionCheck';
D
Dirk Baeumer 已提交
386 387 388 389
			const globalStateValue = this.globalState.get(doGlobalVersionCheckKey, true);
			const checkTscVersion = 'check.tscVersion';
			if (!globalStateValue) {
				tsConfig.update(checkTscVersion, false, true);
390
				this.globalState.update(doGlobalVersionCheckKey, true);
D
Dirk Baeumer 已提交
391 392
			}
			if (checkGlobalVersion && tsConfig.get(checkTscVersion)) {
393 394 395 396 397 398 399 400
				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 已提交
401
					}
402
				} catch (error) {
E
Erich Gamma 已提交
403
				}
404
				if (tscVersion && tscVersion !== version) {
405
					window.showInformationMessage<MyMessageItem>(
406
						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),
407
						{
R
Rob Lourens 已提交
408
							title: localize('moreInformation', 'More Information'),
409 410 411 412
							id: 1
						},
						{
							title: localize('doNotCheckAgain', 'Don\'t Check Again'),
413
							id: 2
D
Dirk Baeumer 已提交
414 415 416 417 418
						},
						{
							title: localize('close', 'Close'),
							id: 3,
							isCloseAffordance: true
419
						}
420
					).then((selected) => {
D
Dirk Baeumer 已提交
421
						if (!selected || selected.id === 3) {
422 423 424 425
							return;
						}
						switch (selected.id) {
							case 1:
D
Dirk Baeumer 已提交
426
								openUrl('http://go.microsoft.com/fwlink/?LinkId=826239');
427 428
								break;
							case 2:
D
Dirk Baeumer 已提交
429 430
								tsConfig.update(checkTscVersion, false, true);
								window.showInformationMessage(localize('updateTscCheck', 'Updated user setting \'typescript.check.tscVersion\' to false'));
431 432 433
								this.globalState.update(doGlobalVersionCheckKey, false);
								break;
						}
E
Erich Gamma 已提交
434
					});
435
				}
E
Erich Gamma 已提交
436
			}
437 438 439 440

			this.servicePromise = new Promise<cp.ChildProcess>((resolve, reject) => {
				try {
					let options: electron.IForkOptions = {
D
Dirk Baeumer 已提交
441
						execArgv: [] // [`--debug-brk=5859`]
442
					};
443 444 445 446 447 448
					try {
						if (workspace.rootPath) {
							options.cwd = fs.realpathSync(workspace.rootPath);
						}
					} catch (error) {
						options.cwd = workspace.rootPath;
449
					}
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
					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 已提交
487 488 489
		});
	}

D
Dirk Baeumer 已提交
490
	private informAboutTS20(modulePath: string): Thenable<string> {
491 492
		const informAboutTS20: string = 'informAboutTS20';
		if (!this.globalState.get(informAboutTS20, false)) {
D
Dirk Baeumer 已提交
493
			return window.showInformationMessage(
494 495
				localize(
					'tsversion20',
D
Dirk Baeumer 已提交
496
					'VS Code 1.6 ships with TypeScript version 2.0.3. If you want to use a previous version of TypeScript set the \'typescript.tsdk\' option.'
497 498 499 500 501 502 503 504 505 506
				),
				{
					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');
				}
D
Dirk Baeumer 已提交
507
				return modulePath;
508
			});
D
Dirk Baeumer 已提交
509 510
		} else {
			return Promise.resolve(modulePath);
511 512 513
		}
	}

E
Erich Gamma 已提交
514
	private serviceStarted(resendModels: boolean): void {
515
		if (this._experimentalAutoBuild && this.storagePath) {
D
Dirk Baeumer 已提交
516 517 518 519
			try {
				fs.mkdirSync(this.storagePath);
			} catch(error) {
			}
520 521 522 523
			this.execute('configure', {
				autoBuild: true,
				metaDataDirectory: this.storagePath
			});
D
Dirk Baeumer 已提交
524
		}
E
Erich Gamma 已提交
525 526 527 528 529
		if (resendModels) {
			this.host.populateService();
		}
	}

530
	private getTypeScriptVersion(serverPath: string): string {
531 532
		let p = serverPath.split(path.sep);
		if (p.length <= 2) {
533
			return undefined;
534 535 536 537 538
		}
		let p2 = p.slice(0, -2);
		let modulePath = p2.join(path.sep);
		let fileName = path.join(modulePath, 'package.json');
		if (!fs.existsSync(fileName)) {
539
			return undefined;
540 541
		}
		let contents = fs.readFileSync(fileName).toString();
542
		let desc = null;
543 544 545
		try {
			desc = JSON.parse(contents);
		} catch(err) {
546
			return undefined;
547 548
		}
		if (!desc.version) {
549
			return undefined;
550
		}
551
		return desc.version;
552 553
	}

E
Erich Gamma 已提交
554 555 556 557 558 559 560 561 562 563 564 565
	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 已提交
566
					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 已提交
567 568
				} else if (diff < 2 * 1000 /* 2 seconds */) {
					startService = false;
P
Paul van Brenk 已提交
569
					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.'));
570
					this.logTelemetry('serviceExited');
E
Erich Gamma 已提交
571 572 573 574 575 576 577 578 579 580 581 582 583
				}
			}
			if (startService) {
				this.startService(true);
			}
		}
	}

	public asAbsolutePath(resource: Uri): string {
		if (resource.scheme !== 'file') {
			return null;
		}
		let result = resource.fsPath;
584 585 586
		if (!result) {
			return null;
		}
E
Erich Gamma 已提交
587
		// Both \ and / must be escaped in regular expressions
588 589 590 591 592 593 594
		result = result.replace(new RegExp('\\' + this.pathSeparator, 'g'), '/');
		try {
			result = fs.realpathSync(result);
		} catch (error) {
			// Do nothing. Keep original path.
		}
		return result;
E
Erich Gamma 已提交
595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
	}

	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);
627
						resolve(undefined);
E
Erich Gamma 已提交
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
					});
				}
			});
		}
		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;
647
		this.traceRequest(serverRequest, !!requestItem.callbacks);
E
Erich Gamma 已提交
648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
		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);
668
				if (this.trace !== Trace.Off) {
669
					this.logTrace(`TypeScript Service: canceled request with sequence number ${seq}`);
E
Erich Gamma 已提交
670 671 672 673
				}
				return true;
			}
		}
674
		if (this.trace !== Trace.Off) {
675
			this.logTrace(`TypeScript Service: tried to cancel request with sequence number ${seq}. But request got already delivered.`);
E
Erich Gamma 已提交
676 677 678 679 680 681 682 683 684 685
		}
		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) {
686
					this.traceResponse(response, p.start);
E
Erich Gamma 已提交
687 688 689 690 691
					delete this.callbacks[response.request_seq];
					this.pendingResponses--;
					if (response.success) {
						p.c(response);
					} else {
692 693 694 695 696
						this.logTelemetry('requestFailed', {
							id: response.request_seq.toString(),
							command: response.command,
							message: response.message ? response.message : 'No detailed message provided'
						});
E
Erich Gamma 已提交
697 698 699 700 701
						p.e(response);
					}
				}
			} else if (message.type === 'event') {
				let event: Proto.Event = <Proto.Event>message;
702
				this.traceEvent(event);
E
Erich Gamma 已提交
703
				if (event.event === 'syntaxDiag') {
704 705 706 707 708
					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 已提交
709 710 711 712 713 714 715 716
				}
			} else {
				throw new Error('Unknown message type ' + message.type + ' recevied');
			}
		} finally {
			this.sendNextRequests();
		}
	}
717 718 719 720 721

	private traceRequest(request: Proto.Request, responseExpected: boolean): void {
		if (this.trace === Trace.Off) {
			return;
		}
722
		let data: string = undefined;
723
		if (this.trace === Trace.Verbose && request.arguments) {
724
			data = `Arguments: ${JSON.stringify(request.arguments, null, 4)}`;
725
		}
726
		this.logTrace(`Sending request: ${request.command} (${request.seq}). Response expected: ${responseExpected ? 'yes' : 'no'}. Current queue length: ${this.requestQueue.length}`, data);
727 728 729 730 731 732
	}

	private traceResponse(response: Proto.Response, startTime: number): void {
		if (this.trace === Trace.Off) {
			return;
		}
733
		let data: string = undefined;
734
		if (this.trace === Trace.Verbose && response.body) {
735
			data = `Result: ${JSON.stringify(response.body, null, 4)}`;
736
		}
737
		this.logTrace(`Response received: ${response.command} (${response.request_seq}). Request took ${Date.now() - startTime} ms. Success: ${response.success} ${!response.success ? '. Message: ' + response.message : ''}`, data);
738 739 740 741 742 743
	}

	private traceEvent(event: Proto.Event): void {
		if (this.trace === Trace.Off) {
			return;
		}
744
		let data: string = undefined;
745
		if (this.trace === Trace.Verbose && event.body) {
746
			data = `Data: ${JSON.stringify(event.body, null, 4)}`;
747
		}
748
		this.logTrace(`Event received: ${event.event} (${event.seq}).`, data);
749
	}
E
Erich Gamma 已提交
750
}