/
test_utils.ts
477 lines (432 loc) · 15.4 KB
/
test_utils.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
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
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
470
471
472
473
474
475
476
477
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {CompileNgModuleMetadata, NgAnalyzedModules} from '@angular/compiler';
import {setup} from '@angular/compiler-cli/test/test_support';
import * as fs from 'fs';
import * as path from 'path';
import * as ts from 'typescript';
import {Span} from '../src/types';
const angularts = /@angular\/(\w|\/|-)+\.tsx?$/;
const rxjsts = /rxjs\/(\w|\/)+\.tsx?$/;
const rxjsmetadata = /rxjs\/(\w|\/)+\.metadata\.json?$/;
const tsxfile = /\.tsx$/;
/* The missing cache does two things. First it improves performance of the
tests as it reduces the number of OS calls made during testing. Also it
improves debugging experience as fewer exceptions are raised to allow you
to use stopping on all exceptions. */
const missingCache = new Set<string>([
'/node_modules/@angular/core.d.ts',
'/node_modules/@angular/animations.d.ts',
'/node_modules/@angular/platform-browser/animations.d.ts',
'/node_modules/@angular/common.d.ts',
'/node_modules/@angular/forms.d.ts',
'/node_modules/@angular/core/src/di/provider.metadata.json',
'/node_modules/@angular/core/src/change_detection/pipe_transform.metadata.json',
'/node_modules/@angular/core/src/reflection/types.metadata.json',
'/node_modules/@angular/core/src/reflection/platform_reflection_capabilities.metadata.json',
'/node_modules/@angular/forms/src/directives/form_interface.metadata.json',
]);
function isFile(path: string) {
return fs.statSync(path).isFile();
}
/**
* Return a Map with key = directory / file path, value = file content.
* [
* /app => [[directory]]
* /app/main.ts => ...
* /app/app.component.ts => ...
* /app/expression-cases.ts => ...
* /app/ng-for-cases.ts => ...
* /app/ng-if-cases.ts => ...
* /app/parsing-cases.ts => ...
* /app/test.css => ...
* /app/test.ng => ...
* ]
*/
function loadTourOfHeroes(): ReadonlyMap<string, string> {
const {TEST_SRCDIR} = process.env;
const root =
path.join(TEST_SRCDIR!, 'angular', 'packages', 'language-service', 'test', 'project');
const dirs = [root];
const files = new Map<string, string>();
while (dirs.length) {
const dirPath = dirs.pop()!;
for (const filePath of fs.readdirSync(dirPath)) {
const absPath = path.join(dirPath, filePath);
if (isFile(absPath)) {
const key = path.join('/', path.relative(root, absPath));
const value = fs.readFileSync(absPath, 'utf8');
files.set(key, value);
} else {
const key = path.join('/', path.relative(root, absPath));
files.set(key, '[[directory]]');
dirs.push(absPath);
}
}
}
return files;
}
const TOH = loadTourOfHeroes();
const COMPILER_OPTIONS: Readonly<ts.CompilerOptions> = {
target: ts.ScriptTarget.ES5,
module: ts.ModuleKind.CommonJS,
moduleResolution: ts.ModuleResolutionKind.NodeJs,
emitDecoratorMetadata: true,
experimentalDecorators: true,
removeComments: false,
noImplicitAny: false,
lib: ['lib.es2015.d.ts', 'lib.dom.d.ts'],
strict: true,
};
export class MockTypescriptHost implements ts.LanguageServiceHost {
private readonly angularPath: string;
private readonly nodeModulesPath: string;
private readonly scriptVersion = new Map<string, number>();
private readonly overrides = new Map<string, string>();
private projectVersion = 0;
private options: ts.CompilerOptions;
private readonly overrideDirectory = new Set<string>();
private readonly existsCache = new Map<string, boolean>();
private readonly fileCache = new Map<string, string|undefined>();
errors: string[] = [];
constructor(
private readonly scriptNames: string[],
private readonly node_modules: string = 'node_modules',
private readonly myPath: typeof path = path) {
const support = setup();
this.nodeModulesPath = path.posix.join(support.basePath, 'node_modules');
this.angularPath = path.posix.join(this.nodeModulesPath, '@angular');
this.options = COMPILER_OPTIONS;
}
override(fileName: string, content: string) {
this.scriptVersion.set(fileName, (this.scriptVersion.get(fileName) || 0) + 1);
this.projectVersion++;
if (content) {
this.overrides.set(fileName, content);
this.overrideDirectory.add(path.dirname(fileName));
} else {
this.overrides.delete(fileName);
}
return content;
}
/**
* Override the inline template in `fileName`.
* @param fileName path to component that has inline template
* @param content new template
*
* @return the new content of the file
*/
overrideInlineTemplate(fileName: string, content: string): string {
const originalContent = this.getRawFileContent(fileName)!;
const newContent =
originalContent.replace(/template: `([\s\S]+?)`/, `template: \`${content}\``);
return this.override(fileName, newContent);
}
addScript(fileName: string, content: string) {
if (this.scriptVersion.has(fileName)) {
throw new Error(`${fileName} is already in the root files.`);
}
this.scriptVersion.set(fileName, 0);
this.projectVersion++;
this.overrides.set(fileName, content);
this.overrideDirectory.add(path.dirname(fileName));
this.scriptNames.push(fileName);
}
overrideOptions(options: Partial<ts.CompilerOptions>) {
this.options = {...this.options, ...options};
this.projectVersion++;
}
getCompilationSettings(): ts.CompilerOptions {
return {...this.options};
}
getProjectVersion(): string {
return this.projectVersion.toString();
}
getScriptFileNames(): string[] {
return this.scriptNames;
}
getScriptVersion(fileName: string): string {
return (this.scriptVersion.get(fileName) || 0).toString();
}
getScriptSnapshot(fileName: string): ts.IScriptSnapshot|undefined {
const content = this.readFile(fileName);
if (content) return ts.ScriptSnapshot.fromString(content);
return undefined;
}
getCurrentDirectory(): string {
return '/';
}
getDefaultLibFileName(options: ts.CompilerOptions): string {
return 'lib.d.ts';
}
directoryExists(directoryName: string): boolean {
if (this.overrideDirectory.has(directoryName)) return true;
const effectiveName = this.getEffectiveName(directoryName);
if (effectiveName === directoryName) {
return TOH.get(directoryName) === '[[directory]]';
}
if (effectiveName === '/' + this.node_modules) {
return true;
}
return this.pathExists(effectiveName);
}
fileExists(fileName: string): boolean {
return this.getRawFileContent(fileName) != null;
}
readFile(fileName: string): string|undefined {
const content = this.getRawFileContent(fileName);
if (content) {
return removeReferenceMarkers(removeLocationMarkers(content));
}
}
/**
* Reset the project to its original state, effectively removing all overrides.
*/
reset() {
// project version and script version must be monotonically increasing,
// they must not be reset to zero.
this.projectVersion++;
for (const fileName of this.overrides.keys()) {
const version = this.scriptVersion.get(fileName);
if (version === undefined) {
throw new Error(`No prior version found for ${fileName}`);
}
this.scriptVersion.set(fileName, version + 1);
}
// Remove overrides from scriptNames
let length = 0;
for (let i = 0; i < this.scriptNames.length; ++i) {
const fileName = this.scriptNames[i];
if (!this.overrides.has(fileName)) {
this.scriptNames[length++] = fileName;
}
}
this.scriptNames.splice(length);
this.overrides.clear();
this.overrideDirectory.clear();
this.options = COMPILER_OPTIONS;
}
private getRawFileContent(fileName: string): string|undefined {
if (this.overrides.has(fileName)) {
return this.overrides.get(fileName);
}
let basename = path.basename(fileName);
if (/^lib.*\.d\.ts$/.test(basename)) {
let libPath = ts.getDefaultLibFilePath(this.getCompilationSettings());
return fs.readFileSync(this.myPath.join(path.dirname(libPath), basename), 'utf8');
}
if (missingCache.has(fileName)) {
return undefined;
}
const effectiveName = this.getEffectiveName(fileName);
if (effectiveName === fileName) {
return TOH.get(fileName);
}
if (!fileName.match(angularts) && !fileName.match(rxjsts) && !fileName.match(rxjsmetadata) &&
!fileName.match(tsxfile)) {
if (this.fileCache.has(effectiveName)) {
return this.fileCache.get(effectiveName);
} else if (this.pathExists(effectiveName)) {
const content = fs.readFileSync(effectiveName, 'utf8');
this.fileCache.set(effectiveName, content);
return content;
} else {
missingCache.add(fileName);
}
}
}
private pathExists(path: string): boolean {
if (this.existsCache.has(path)) {
return this.existsCache.get(path)!;
}
const exists = fs.existsSync(path);
this.existsCache.set(path, exists);
return exists;
}
private getEffectiveName(name: string): string {
const node_modules = this.node_modules;
const at_angular = '/@angular';
if (name.startsWith('/' + node_modules)) {
if (this.nodeModulesPath && !name.startsWith('/' + node_modules + at_angular)) {
const result =
this.myPath.posix.join(this.nodeModulesPath, name.substr(node_modules.length + 1));
if (!name.match(rxjsts) && this.pathExists(result)) {
return result;
}
}
if (name.startsWith('/' + node_modules + at_angular)) {
return this.myPath.posix.join(
this.angularPath, name.substr(node_modules.length + at_angular.length + 1));
}
}
return name;
}
/**
* Append a snippet of code to `app.component.ts` and return the file name.
* There must not be any name collision with existing code.
* @param code Snippet of code
*/
addCode(code: string) {
const fileName = '/app/app.component.ts';
const originalContent = this.readFile(fileName);
const newContent = originalContent + code;
this.override(fileName, newContent);
return fileName;
}
/**
* Returns the definition marker `ᐱselectorᐱ` for the specified 'selector'.
* Asserts that marker exists.
* @param fileName name of the file
* @param selector name of the marker
*/
getDefinitionMarkerFor(fileName: string, selector: string): ts.TextSpan {
const content = this.getRawFileContent(fileName);
if (!content) {
throw new Error(`File does not exist: ${fileName}`);
}
const markers = getReferenceMarkers(content);
const definitions = markers.definitions[selector];
if (!definitions || !definitions.length) {
throw new Error(`Failed to find marker '${selector}' in ${fileName}`);
}
if (definitions.length > 1) {
throw new Error(`Multiple positions found for '${selector}' in ${fileName}`);
}
const {start, end} = definitions[0];
if (start > end) {
throw new Error(`Marker '${selector}' in ${fileName} is invalid: ${start} > ${end}`);
}
return {
start,
length: end - start,
};
}
/**
* Returns the reference marker `«selector»` for the specified 'selector'.
* Asserts that marker exists.
* @param fileName name of the file
* @param selector name of the marker
*/
getReferenceMarkerFor(fileName: string, selector: string): ts.TextSpan {
const content = this.getRawFileContent(fileName);
if (!content) {
throw new Error(`File does not exist: ${fileName}`);
}
const markers = getReferenceMarkers(content);
const references = markers.references[selector];
if (!references || !references.length) {
throw new Error(`Failed to find marker '${selector}' in ${fileName}`);
}
if (references.length > 1) {
throw new Error(`Multiple positions found for '${selector}' in ${fileName}`);
}
const {start, end} = references[0];
if (start > end) {
throw new Error(`Marker '${selector}' in ${fileName} is invalid: ${start} > ${end}`);
}
return {
start,
length: end - start,
};
}
/**
* Returns the location marker `~{selector}` or the marker pair
* `~{start-selector}` and `~{end-selector}` for the specified 'selector'.
* Asserts that marker exists.
* @param fileName name of the file
* @param selector name of the marker
*/
getLocationMarkerFor(fileName: string, selector: string): ts.TextSpan {
const content = this.getRawFileContent(fileName);
if (!content) {
throw new Error(`File does not exist: ${fileName}`);
}
const markers = getLocationMarkers(content);
// Look for just the selector itself
const position = markers[selector];
if (position !== undefined) {
return {
start: position,
length: 0,
};
}
// Look for start and end markers for the selector
const start = markers[`start-${selector}`];
const end = markers[`end-${selector}`];
if (start !== undefined && end !== undefined) {
return {
start,
length: end - start,
};
}
throw new Error(`Failed to find marker '${selector}' in ${fileName}`);
}
error(msg: string) {
this.errors.push(msg);
}
}
const locationMarker = /\~\{(\w+(-\w+)*)\}/g;
function removeLocationMarkers(value: string): string {
return value.replace(locationMarker, '');
}
function getLocationMarkers(value: string): {[name: string]: number} {
value = removeReferenceMarkers(value);
let result: {[name: string]: number} = {};
let adjustment = 0;
value.replace(locationMarker, (match: string, name: string, _: any, index: number): string => {
result[name] = index - adjustment;
adjustment += match.length;
return '';
});
return result;
}
const referenceMarker = /«(((\w|\-)+)|([^ᐱ]*ᐱ(\w+)ᐱ.[^»]*))»/g;
export type ReferenceMarkers = {
[name: string]: Span[]
};
export interface ReferenceResult {
text: string;
definitions: ReferenceMarkers;
references: ReferenceMarkers;
}
function getReferenceMarkers(value: string): ReferenceResult {
const references: ReferenceMarkers = {};
const definitions: ReferenceMarkers = {};
value = removeLocationMarkers(value);
let adjustment = 0;
const text = value.replace(
referenceMarker,
(match: string, text: string, reference: string, _: string, definition: string,
definitionName: string, index: number): string => {
const result = reference ? text : text.replace(/ᐱ/g, '');
const span: Span = {start: index - adjustment, end: index - adjustment + result.length};
const markers = reference ? references : definitions;
const name = reference || definitionName;
(markers[name] = (markers[name] || [])).push(span);
adjustment += match.length - result.length;
return result;
});
return {text, definitions, references};
}
function removeReferenceMarkers(value: string): string {
return value.replace(referenceMarker, (match, text) => text.replace(/ᐱ/g, ''));
}
/**
* Find the StaticSymbol that has the specified `directiveName` and return its
* Angular metadata, if any.
* @param ngModules analyzed modules
* @param directiveName
*/
export function findDirectiveMetadataByName(
ngModules: NgAnalyzedModules, directiveName: string): CompileNgModuleMetadata|undefined {
for (const [key, value] of ngModules.ngModuleByPipeOrDirective) {
if (key.name === directiveName) {
return value;
}
}
}