nls.ts 14.6 KB
Newer Older
J
Joao Moreno 已提交
1 2 3 4 5 6
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

import * as ts from 'typescript';
E
Erich Gamma 已提交
7
import * as lazy from 'lazy.js';
8
import { duplex, through } from 'event-stream';
E
Erich Gamma 已提交
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
import File = require('vinyl');
import * as sm from 'source-map';
import assign = require('object-assign');
import path = require('path');

declare class FileSourceMap extends File {
	public sourceMap: sm.RawSourceMap;
}

enum CollectStepResult {
	Yes,
	YesAndRecurse,
	No,
	NoAndRecurse
}

function collect(node: ts.Node, fn: (node: ts.Node) => CollectStepResult): ts.Node[] {
	const result: ts.Node[] = [];

	function loop(node: ts.Node) {
		var stepResult = fn(node);

		if (stepResult === CollectStepResult.Yes || stepResult === CollectStepResult.YesAndRecurse) {
			result.push(node);
		}

		if (stepResult === CollectStepResult.YesAndRecurse || stepResult === CollectStepResult.NoAndRecurse) {
			ts.forEachChild(node, loop);
		}
	}

	loop(node);
	return result;
}

44
function clone<T>(object: T): T {
A
Alex Dima 已提交
45 46 47 48 49 50 51
	var result = <T>{};
	for (var id in object) {
		result[id] = object[id];
	}
	return result;
}

E
Erich Gamma 已提交
52 53 54 55 56 57 58 59 60 61 62
function template(lines: string[]): string {
	let indent = '', wrap = '';

	if (lines.length > 1) {
		indent = '\t';
		wrap = '\n';
	}

	return `/*---------------------------------------------------------
 * Copyright (C) Microsoft Corporation. All rights reserved.
 *--------------------------------------------------------*/
63
define([], [${ wrap + lines.map(l => indent + l).join(',\n') + wrap}]);`;
E
Erich Gamma 已提交
64 65 66 67 68
}

/**
 * Returns a stream containing the patched JavaScript and source maps.
 */
69
function nls(): NodeJS.ReadWriteStream {
E
Erich Gamma 已提交
70 71 72
	var input = through();
	var output = input.pipe(through(function (f: FileSourceMap) {
		if (!f.sourceMap) {
73
			return this.emit('error', new Error(`File ${f.relative} does not have sourcemaps.`));
E
Erich Gamma 已提交
74 75 76 77
		}

		let source = f.sourceMap.sources[0];
		if (!source) {
78
			return this.emit('error', new Error(`File ${f.relative} does not have a source in the source map.`));
E
Erich Gamma 已提交
79 80 81 82 83 84 85 86 87
		}

		const root = f.sourceMap.sourceRoot;
		if (root) {
			source = path.join(root, source);
		}

		const typescript = f.sourceMap.sourcesContent[0];
		if (!typescript) {
88
			return this.emit('error', new Error(`File ${f.relative} does not have the original content in the source map.`));
E
Erich Gamma 已提交
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
		}

		nls.patchFiles(f, typescript).forEach(f => this.emit('data', f));
	}));

	return duplex(input, output);
}

function isImportNode(node: ts.Node): boolean {
	return node.kind === ts.SyntaxKind.ImportDeclaration || node.kind === ts.SyntaxKind.ImportEqualsDeclaration;
}

module nls {

	export interface INlsStringResult {
		javascript: string;
		sourcemap: sm.RawSourceMap;
		nls?: string;
		nlsKeys?: string;
	}

	export interface ISpan {
		start: ts.LineAndCharacter;
		end: ts.LineAndCharacter;
	}

	export interface ILocalizeCall {
		keySpan: ISpan;
		key: string;
		valueSpan: ISpan;
		value: string;
	}

	export interface ILocalizeAnalysisResult {
		localizeCalls: ILocalizeCall[];
		nlsExpressions: ISpan[];
	}

	export interface IPatch {
		span: ISpan;
		content: string;
	}

	export function fileFrom(file: File, contents: string, path: string = file.path) {
		return new File({
			contents: new Buffer(contents),
			base: file.base,
			cwd: file.cwd,
			path: path
		});
	}

	export function mappedPositionFrom(source: string, lc: ts.LineAndCharacter): sm.MappedPosition {
		return { source, line: lc.line + 1, column: lc.character };
	}

	export function lcFrom(position: sm.Position): ts.LineAndCharacter {
		return { line: position.line - 1, character: position.column };
	}

	export class SingleFileServiceHost implements ts.LanguageServiceHost {

		private file: ts.IScriptSnapshot;
		private lib: ts.IScriptSnapshot;

		constructor(private options: ts.CompilerOptions, private filename: string, contents: string) {
			this.file = ts.ScriptSnapshot.fromString(contents);
			this.lib = ts.ScriptSnapshot.fromString('');
		}

159 160 161 162 163 164
		getCompilationSettings = () => this.options;
		getScriptFileNames = () => [this.filename];
		getScriptVersion = () => '1';
		getScriptSnapshot = (name: string) => name === this.filename ? this.file : this.lib;
		getCurrentDirectory = () => '';
		getDefaultLibFileName = () => 'lib.d.ts';
E
Erich Gamma 已提交
165 166 167 168 169 170 171 172 173 174 175 176 177 178
	}

	function isCallExpressionWithinTextSpanCollectStep(textSpan: ts.TextSpan, node: ts.Node): CollectStepResult {
		if (!ts.textSpanContainsTextSpan({ start: node.pos, length: node.end - node.pos }, textSpan)) {
			return CollectStepResult.No;
		}

		return node.kind === ts.SyntaxKind.CallExpression ? CollectStepResult.YesAndRecurse : CollectStepResult.NoAndRecurse;
	}

	export function analyze(contents: string, options: ts.CompilerOptions = {}): ILocalizeAnalysisResult {
		const filename = 'file.ts';
		const serviceHost = new SingleFileServiceHost(assign(clone(options), { noResolve: true }), filename, contents);
		const service = ts.createLanguageService(serviceHost);
J
Joao Moreno 已提交
179
		const sourceFile = ts.createSourceFile(filename, contents, ts.ScriptTarget.ES5, true);
E
Erich Gamma 已提交
180 181 182 183 184 185 186

		// all imports
		const imports = lazy(collect(sourceFile, n => isImportNode(n) ? CollectStepResult.YesAndRecurse : CollectStepResult.NoAndRecurse));

		// import nls = require('vs/nls');
		const importEqualsDeclarations = imports
			.filter(n => n.kind === ts.SyntaxKind.ImportEqualsDeclaration)
187
			.map(n => <ts.ImportEqualsDeclaration>n)
E
Erich Gamma 已提交
188
			.filter(d => d.moduleReference.kind === ts.SyntaxKind.ExternalModuleReference)
189
			.filter(d => (<ts.ExternalModuleReference>d.moduleReference).expression.getText() === '\'vs/nls\'');
E
Erich Gamma 已提交
190 191 192 193

		// import ... from 'vs/nls';
		const importDeclarations = imports
			.filter(n => n.kind === ts.SyntaxKind.ImportDeclaration)
194
			.map(n => <ts.ImportDeclaration>n)
E
Erich Gamma 已提交
195
			.filter(d => d.moduleSpecifier.kind === ts.SyntaxKind.StringLiteral)
196
			.filter(d => d.moduleSpecifier.getText() === '\'vs/nls\'')
E
Erich Gamma 已提交
197 198 199 200 201 202 203 204 205 206 207 208 209
			.filter(d => !!d.importClause && !!d.importClause.namedBindings);

		const nlsExpressions = importEqualsDeclarations
			.map(d => (<ts.ExternalModuleReference>d.moduleReference).expression)
			.concat(importDeclarations.map(d => d.moduleSpecifier))
			.map<ISpan>(d => ({
				start: ts.getLineAndCharacterOfPosition(sourceFile, d.getStart()),
				end: ts.getLineAndCharacterOfPosition(sourceFile, d.getEnd())
			}));

		// `nls.localize(...)` calls
		const nlsLocalizeCallExpressions = importDeclarations
			.filter(d => d.importClause.namedBindings.kind === ts.SyntaxKind.NamespaceImport)
210
			.map(d => (<ts.NamespaceImport>d.importClause.namedBindings).name)
E
Erich Gamma 已提交
211 212 213 214 215 216 217 218 219 220 221
			.concat(importEqualsDeclarations.map(d => d.name))

			// find read-only references to `nls`
			.map(n => service.getReferencesAtPosition(filename, n.pos + 1))
			.flatten()
			.filter(r => !r.isWriteAccess)

			// find the deepest call expressions AST nodes that contain those references
			.map(r => collect(sourceFile, n => isCallExpressionWithinTextSpanCollectStep(r.textSpan, n)))
			.map(a => lazy(a).last())
			.filter(n => !!n)
222
			.map(n => <ts.CallExpression>n)
E
Erich Gamma 已提交
223 224

			// only `localize` calls
225
			.filter(n => n.expression.kind === ts.SyntaxKind.PropertyAccessExpression && (<ts.PropertyAccessExpression>n.expression).name.getText() === 'localize');
E
Erich Gamma 已提交
226 227 228 229

		// `localize` named imports
		const allLocalizeImportDeclarations = importDeclarations
			.filter(d => d.importClause.namedBindings.kind === ts.SyntaxKind.NamedImports)
230
			.map(d => (<ts.NamedImports>d.importClause.namedBindings).elements)
231
			.flatten();
E
Erich Gamma 已提交
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252

		// `localize` read-only references
		const localizeReferences = allLocalizeImportDeclarations
			.filter(d => d.name.getText() === 'localize')
			.map(n => service.getReferencesAtPosition(filename, n.pos + 1))
			.flatten()
			.filter(r => !r.isWriteAccess);

		// custom named `localize` read-only references
		const namedLocalizeReferences = allLocalizeImportDeclarations
			.filter(d => d.propertyName && d.propertyName.getText() === 'localize')
			.map(n => service.getReferencesAtPosition(filename, n.name.pos + 1))
			.flatten()
			.filter(r => !r.isWriteAccess);

		// find the deepest call expressions AST nodes that contain those references
		const localizeCallExpressions = localizeReferences
			.concat(namedLocalizeReferences)
			.map(r => collect(sourceFile, n => isCallExpressionWithinTextSpanCollectStep(r.textSpan, n)))
			.map(a => lazy(a).last())
			.filter(n => !!n)
253
			.map(n => <ts.CallExpression>n);
E
Erich Gamma 已提交
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

		// collect everything
		const localizeCalls = nlsLocalizeCallExpressions
			.concat(localizeCallExpressions)
			.map(e => e.arguments)
			.filter(a => a.length > 1)
			.sort((a, b) => a[0].getStart() - b[0].getStart())
			.map<ILocalizeCall>(a => ({
				keySpan: { start: ts.getLineAndCharacterOfPosition(sourceFile, a[0].getStart()), end: ts.getLineAndCharacterOfPosition(sourceFile, a[0].getEnd()) },
				key: a[0].getText(),
				valueSpan: { start: ts.getLineAndCharacterOfPosition(sourceFile, a[1].getStart()), end: ts.getLineAndCharacterOfPosition(sourceFile, a[1].getEnd()) },
				value: a[1].getText()
			}));

		return {
			localizeCalls: localizeCalls.toArray(),
			nlsExpressions: nlsExpressions.toArray()
		};
	}

	export class TextModel {

		private lines: string[];
		private lineEndings: string[];

		constructor(contents: string) {
			const regex = /\r\n|\r|\n/g;
			let index = 0;
			let match: RegExpExecArray;

			this.lines = [];
			this.lineEndings = [];

			while (match = regex.exec(contents)) {
				this.lines.push(contents.substring(index, match.index));
				this.lineEndings.push(match[0]);
				index = regex.lastIndex;
			}

			if (contents.length > 0) {
				this.lines.push(contents.substring(index, contents.length));
				this.lineEndings.push('');
			}
		}

		public get(index: number): string {
			return this.lines[index];
		}

		public set(index: number, line: string): void {
			this.lines[index] = line;
		}

		public get lineCount(): number {
			return this.lines.length;
		}

		/**
		 * Applies patch(es) to the model.
		 * Multiple patches must be ordered.
		 * Does not support patches spanning multiple lines.
		 */
		public apply(patch: IPatch): void {
			const startLineNumber = patch.span.start.line;
			const endLineNumber = patch.span.end.line;

			const startLine = this.lines[startLineNumber] || '';
			const endLine = this.lines[endLineNumber] || '';

			this.lines[startLineNumber] = [
				startLine.substring(0, patch.span.start.character),
				patch.content,
				endLine.substring(patch.span.end.character)
			].join('');

			for (let i = startLineNumber + 1; i <= endLineNumber; i++) {
				this.lines[i] = '';
			}
		}

		public toString(): string {
			return lazy(this.lines).zip(this.lineEndings)
				.flatten().toArray().join('');
		}
	}

	export function patchJavascript(patches: IPatch[], contents: string, moduleId: string): string {
		const model = new nls.TextModel(contents);

		// patch the localize calls
		lazy(patches).reverse().each(p => model.apply(p));

		// patch the 'vs/nls' imports
		const firstLine = model.get(0);
348
		const patchedFirstLine = firstLine.replace(/(['"])vs\/nls\1/g, `$1vs/nls!${moduleId}$1`);
E
Erich Gamma 已提交
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
		model.set(0, patchedFirstLine);

		return model.toString();
	}

	export function patchSourcemap(patches: IPatch[], rsm: sm.RawSourceMap, smc: sm.SourceMapConsumer): sm.RawSourceMap {
		const smg = new sm.SourceMapGenerator({
			file: rsm.file,
			sourceRoot: rsm.sourceRoot
		});

		patches = patches.reverse();
		let currentLine = -1;
		let currentLineDiff = 0;
		let source = null;

		smc.eachMapping(m => {
			const patch = patches[patches.length - 1];
			const original = { line: m.originalLine, column: m.originalColumn };
			const generated = { line: m.generatedLine, column: m.generatedColumn };

			if (currentLine !== generated.line) {
				currentLineDiff = 0;
			}

			currentLine = generated.line;
			generated.column += currentLineDiff;

			if (patch && m.generatedLine - 1 === patch.span.end.line && m.generatedColumn === patch.span.end.character) {
				const originalLength = patch.span.end.character - patch.span.start.character;
				const modifiedLength = patch.content.length;
				const lengthDiff = modifiedLength - originalLength;
				currentLineDiff += lengthDiff;
				generated.column += lengthDiff;

				patches.pop();
			}

			source = rsm.sourceRoot ? path.relative(rsm.sourceRoot, m.source) : m.source;
			source = source.replace(/\\/g, '/');
389
			smg.addMapping({ source, name: m.name, original, generated });
E
Erich Gamma 已提交
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
		}, null, sm.SourceMapConsumer.GENERATED_ORDER);

		if (source) {
			smg.setSourceContent(source, smc.sourceContentFor(source));
		}

		return JSON.parse(smg.toString());
	}

	export function patch(moduleId: string, typescript: string, javascript: string, sourcemap: sm.RawSourceMap): INlsStringResult {
		const { localizeCalls, nlsExpressions } = analyze(typescript);

		if (localizeCalls.length === 0) {
			return { javascript, sourcemap };
		}

		const nlsKeys = template(localizeCalls.map(lc => lc.key));
		const nls = template(localizeCalls.map(lc => lc.value));
		const smc = new sm.SourceMapConsumer(sourcemap);
		const positionFrom = mappedPositionFrom.bind(null, sourcemap.sources[0]);
		let i = 0;

		// build patches
		const patches = lazy(localizeCalls)
			.map(lc => ([
				{ range: lc.keySpan, content: '' + (i++) },
				{ range: lc.valueSpan, content: 'null' }
			]))
			.flatten()
			.map<IPatch>(c => {
				const start = lcFrom(smc.generatedPositionFor(positionFrom(c.range.start)));
				const end = lcFrom(smc.generatedPositionFor(positionFrom(c.range.end)));
				return { span: { start, end }, content: c.content };
			})
			.toArray();

		javascript = patchJavascript(patches, javascript, moduleId);

		// since imports are not within the sourcemap information,
		// we must do this MacGyver style
		if (nlsExpressions.length) {
			javascript = javascript.replace(/^define\(.*$/m, line => {
432
				return line.replace(/(['"])vs\/nls\1/g, `$1vs/nls!${moduleId}$1`);
E
Erich Gamma 已提交
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 460 461 462 463 464 465 466 467 468 469
			});
		}

		sourcemap = patchSourcemap(patches, sourcemap, smc);

		return { javascript, sourcemap, nlsKeys, nls };
	}

	export function patchFiles(javascriptFile: File, typescript: string): File[] {
		// hack?
		const moduleId = javascriptFile.relative
			.replace(/\.js$/, '')
			.replace(/\\/g, '/');

		const { javascript, sourcemap, nlsKeys, nls } = patch(
			moduleId,
			typescript,
			javascriptFile.contents.toString(),
			(<any>javascriptFile).sourceMap
		);

		const result: File[] = [fileFrom(javascriptFile, javascript)];
		(<any>result[0]).sourceMap = sourcemap;

		if (nlsKeys) {
			result.push(fileFrom(javascriptFile, nlsKeys, javascriptFile.path.replace(/\.js$/, '.nls.keys.js')));
		}

		if (nls) {
			result.push(fileFrom(javascriptFile, nls, javascriptFile.path.replace(/\.js$/, '.nls.js')));
		}

		return result;
	}
}

export = nls;