refactor(ivy): implement a virtual file-system layer in ngtsc + ngcc (#30921)
To improve cross platform support, all file access (and path manipulation) is now done through a well known interface (`FileSystem`). For testing a number of `MockFileSystem` implementations are provided. These provide an in-memory file-system which emulates operating systems like OS/X, Unix and Windows. The current file system is always available via the static method, `FileSystem.getFileSystem()`. This is also used by a number of static methods on `AbsoluteFsPath` and `PathSegment`, to avoid having to pass `FileSystem` objects around all the time. The result of this is that one must be careful to ensure that the file-system has been initialized before using any of these static methods. To prevent this happening accidentally the current file system always starts out as an instance of `InvalidFileSystem`, which will throw an error if any of its methods are called. You can set the current file-system by calling `FileSystem.setFileSystem()`. During testing you can call the helper function `initMockFileSystem(os)` which takes a string name of the OS to emulate, and will also monkey-patch aspects of the TypeScript library to ensure that TS is also using the current file-system. Finally there is the `NgtscCompilerHost` to be used for any TypeScript compilation, which uses a given file-system. All tests that interact with the file-system should be tested against each of the mock file-systems. A series of helpers have been provided to support such tests: * `runInEachFileSystem()` - wrap your tests in this helper to run all the wrapped tests in each of the mock file-systems. * `addTestFilesToFileSystem()` - use this to add files and their contents to the mock file system for testing. * `loadTestFilesFromDisk()` - use this to load a mirror image of files on disk into the in-memory mock file-system. * `loadFakeCore()` - use this to load a fake version of `@angular/core` into the mock file-system. All ngcc and ngtsc source and tests now use this virtual file-system setup. PR Close #30921
This commit is contained in:

committed by
Kara Erickson

parent
1e7e065423
commit
7186f9c016
@ -11,6 +11,7 @@ ts_library(
|
||||
"//packages/compiler",
|
||||
"//packages/compiler-cli/src/ngtsc/cycles",
|
||||
"//packages/compiler-cli/src/ngtsc/diagnostics",
|
||||
"//packages/compiler-cli/src/ngtsc/file_system",
|
||||
"//packages/compiler-cli/src/ngtsc/imports",
|
||||
"//packages/compiler-cli/src/ngtsc/indexer",
|
||||
"//packages/compiler-cli/src/ngtsc/metadata",
|
||||
|
@ -7,11 +7,11 @@
|
||||
*/
|
||||
|
||||
import {ConstantPool, CssSelector, DEFAULT_INTERPOLATION_CONFIG, DomElementSchemaRegistry, Expression, ExternalExpr, InterpolationConfig, LexerRange, ParseError, ParseSourceFile, ParseTemplateOptions, R3ComponentMetadata, R3TargetBinder, SelectorMatcher, Statement, TmplAstNode, WrappedNodeExpr, compileComponentFromMetadata, makeBindingParser, parseTemplate} from '@angular/compiler';
|
||||
import * as path from 'path';
|
||||
import * as ts from 'typescript';
|
||||
|
||||
import {CycleAnalyzer} from '../../cycles';
|
||||
import {ErrorCode, FatalDiagnosticError} from '../../diagnostics';
|
||||
import {absoluteFrom, relative} from '../../file_system';
|
||||
import {DefaultImportRecorder, ModuleResolver, Reference, ReferenceEmitter} from '../../imports';
|
||||
import {IndexingContext} from '../../indexer';
|
||||
import {DirectiveMeta, MetadataReader, MetadataRegistry, extractDirectiveGuards} from '../../metadata';
|
||||
@ -156,7 +156,7 @@ export class ComponentDecoratorHandler implements
|
||||
// Go through the root directories for this project, and select the one with the smallest
|
||||
// relative path representation.
|
||||
const relativeContextFilePath = this.rootDirs.reduce<string|undefined>((previous, rootDir) => {
|
||||
const candidate = path.posix.relative(rootDir, containingFile);
|
||||
const candidate = relative(absoluteFrom(rootDir), absoluteFrom(containingFile));
|
||||
if (previous === undefined || candidate.length < previous.length) {
|
||||
return candidate;
|
||||
} else {
|
||||
@ -205,7 +205,7 @@ export class ComponentDecoratorHandler implements
|
||||
/* escapedString */ false, options);
|
||||
} else {
|
||||
// Expect an inline template to be present.
|
||||
const inlineTemplate = this._extractInlineTemplate(component, relativeContextFilePath);
|
||||
const inlineTemplate = this._extractInlineTemplate(component, containingFile);
|
||||
if (inlineTemplate === null) {
|
||||
throw new FatalDiagnosticError(
|
||||
ErrorCode.COMPONENT_MISSING_TEMPLATE, decorator.node,
|
||||
@ -583,8 +583,7 @@ export class ComponentDecoratorHandler implements
|
||||
}
|
||||
}
|
||||
|
||||
private _extractInlineTemplate(
|
||||
component: Map<string, ts.Expression>, relativeContextFilePath: string): {
|
||||
private _extractInlineTemplate(component: Map<string, ts.Expression>, containingFile: string): {
|
||||
templateStr: string,
|
||||
templateUrl: string,
|
||||
templateRange: LexerRange|undefined,
|
||||
@ -606,7 +605,7 @@ export class ComponentDecoratorHandler implements
|
||||
// strip
|
||||
templateRange = getTemplateRange(templateExpr);
|
||||
templateStr = templateExpr.getSourceFile().text;
|
||||
templateUrl = relativeContextFilePath;
|
||||
templateUrl = containingFile;
|
||||
escapedString = true;
|
||||
} else {
|
||||
const resolvedTemplate = this.evaluator.evaluate(templateExpr);
|
||||
|
@ -8,7 +8,6 @@
|
||||
|
||||
import * as ts from 'typescript';
|
||||
import {Reference} from '../../imports';
|
||||
import {Declaration} from '../../reflection';
|
||||
|
||||
/**
|
||||
* Implement this interface if you want DecoratorHandlers to register
|
||||
|
@ -14,15 +14,15 @@ ts_library(
|
||||
"//packages/compiler-cli/src/ngtsc/annotations",
|
||||
"//packages/compiler-cli/src/ngtsc/cycles",
|
||||
"//packages/compiler-cli/src/ngtsc/diagnostics",
|
||||
"//packages/compiler-cli/src/ngtsc/file_system",
|
||||
"//packages/compiler-cli/src/ngtsc/file_system/testing",
|
||||
"//packages/compiler-cli/src/ngtsc/imports",
|
||||
"//packages/compiler-cli/src/ngtsc/metadata",
|
||||
"//packages/compiler-cli/src/ngtsc/partial_evaluator",
|
||||
"//packages/compiler-cli/src/ngtsc/path",
|
||||
"//packages/compiler-cli/src/ngtsc/reflection",
|
||||
"//packages/compiler-cli/src/ngtsc/scope",
|
||||
"//packages/compiler-cli/src/ngtsc/testing",
|
||||
"//packages/compiler-cli/src/ngtsc/translator",
|
||||
"//packages/compiler-cli/src/ngtsc/util",
|
||||
"@npm//typescript",
|
||||
],
|
||||
)
|
||||
|
@ -7,12 +7,14 @@
|
||||
*/
|
||||
import {CycleAnalyzer, ImportGraph} from '../../cycles';
|
||||
import {ErrorCode, FatalDiagnosticError} from '../../diagnostics';
|
||||
import {absoluteFrom} from '../../file_system';
|
||||
import {runInEachFileSystem} from '../../file_system/testing';
|
||||
import {ModuleResolver, NOOP_DEFAULT_IMPORT_RECORDER, ReferenceEmitter} from '../../imports';
|
||||
import {CompoundMetadataReader, DtsMetadataReader, LocalMetadataRegistry} from '../../metadata';
|
||||
import {PartialEvaluator} from '../../partial_evaluator';
|
||||
import {TypeScriptReflectionHost, isNamedClassDeclaration} from '../../reflection';
|
||||
import {LocalModuleScopeRegistry, MetadataDtsModuleScopeResolver} from '../../scope';
|
||||
import {getDeclaration, makeProgram} from '../../testing/in_memory_typescript';
|
||||
import {getDeclaration, makeProgram} from '../../testing';
|
||||
import {ResourceLoader} from '../src/api';
|
||||
import {ComponentDecoratorHandler} from '../src/component';
|
||||
|
||||
@ -22,62 +24,64 @@ export class NoopResourceLoader implements ResourceLoader {
|
||||
load(): string { throw new Error('Not implemented'); }
|
||||
preload(): Promise<void>|undefined { throw new Error('Not implemented'); }
|
||||
}
|
||||
runInEachFileSystem(() => {
|
||||
describe('ComponentDecoratorHandler', () => {
|
||||
let _: typeof absoluteFrom;
|
||||
beforeEach(() => _ = absoluteFrom);
|
||||
|
||||
describe('ComponentDecoratorHandler', () => {
|
||||
it('should produce a diagnostic when @Component has non-literal argument', () => {
|
||||
const {program, options, host} = makeProgram([
|
||||
{
|
||||
name: 'node_modules/@angular/core/index.d.ts',
|
||||
contents: 'export const Component: any;',
|
||||
},
|
||||
{
|
||||
name: 'entry.ts',
|
||||
contents: `
|
||||
it('should produce a diagnostic when @Component has non-literal argument', () => {
|
||||
const {program, options, host} = makeProgram([
|
||||
{
|
||||
name: _('/node_modules/@angular/core/index.d.ts'),
|
||||
contents: 'export const Component: any;',
|
||||
},
|
||||
{
|
||||
name: _('/entry.ts'),
|
||||
contents: `
|
||||
import {Component} from '@angular/core';
|
||||
|
||||
const TEST = '';
|
||||
@Component(TEST) class TestCmp {}
|
||||
`
|
||||
},
|
||||
]);
|
||||
const checker = program.getTypeChecker();
|
||||
const reflectionHost = new TypeScriptReflectionHost(checker);
|
||||
const evaluator = new PartialEvaluator(reflectionHost, checker);
|
||||
const moduleResolver = new ModuleResolver(program, options, host);
|
||||
const importGraph = new ImportGraph(moduleResolver);
|
||||
const cycleAnalyzer = new CycleAnalyzer(importGraph);
|
||||
const metaRegistry = new LocalMetadataRegistry();
|
||||
const dtsReader = new DtsMetadataReader(checker, reflectionHost);
|
||||
const scopeRegistry = new LocalModuleScopeRegistry(
|
||||
metaRegistry, new MetadataDtsModuleScopeResolver(dtsReader, null), new ReferenceEmitter([]),
|
||||
null);
|
||||
const metaReader = new CompoundMetadataReader([metaRegistry, dtsReader]);
|
||||
const refEmitter = new ReferenceEmitter([]);
|
||||
},
|
||||
]);
|
||||
const checker = program.getTypeChecker();
|
||||
const reflectionHost = new TypeScriptReflectionHost(checker);
|
||||
const evaluator = new PartialEvaluator(reflectionHost, checker);
|
||||
const moduleResolver = new ModuleResolver(program, options, host);
|
||||
const importGraph = new ImportGraph(moduleResolver);
|
||||
const cycleAnalyzer = new CycleAnalyzer(importGraph);
|
||||
const metaRegistry = new LocalMetadataRegistry();
|
||||
const dtsReader = new DtsMetadataReader(checker, reflectionHost);
|
||||
const scopeRegistry = new LocalModuleScopeRegistry(
|
||||
metaRegistry, new MetadataDtsModuleScopeResolver(dtsReader, null),
|
||||
new ReferenceEmitter([]), null);
|
||||
const metaReader = new CompoundMetadataReader([metaRegistry, dtsReader]);
|
||||
const refEmitter = new ReferenceEmitter([]);
|
||||
|
||||
const handler = new ComponentDecoratorHandler(
|
||||
reflectionHost, evaluator, metaRegistry, metaReader, scopeRegistry, false,
|
||||
new NoopResourceLoader(), [''], false, true, moduleResolver, cycleAnalyzer, refEmitter,
|
||||
NOOP_DEFAULT_IMPORT_RECORDER);
|
||||
const TestCmp = getDeclaration(program, 'entry.ts', 'TestCmp', isNamedClassDeclaration);
|
||||
const detected = handler.detect(TestCmp, reflectionHost.getDecoratorsOfDeclaration(TestCmp));
|
||||
if (detected === undefined) {
|
||||
return fail('Failed to recognize @Component');
|
||||
}
|
||||
try {
|
||||
handler.analyze(TestCmp, detected.metadata);
|
||||
return fail('Analysis should have failed');
|
||||
} catch (err) {
|
||||
if (!(err instanceof FatalDiagnosticError)) {
|
||||
return fail('Error should be a FatalDiagnosticError');
|
||||
const handler = new ComponentDecoratorHandler(
|
||||
reflectionHost, evaluator, metaRegistry, metaReader, scopeRegistry, false,
|
||||
new NoopResourceLoader(), [''], false, true, moduleResolver, cycleAnalyzer, refEmitter,
|
||||
NOOP_DEFAULT_IMPORT_RECORDER);
|
||||
const TestCmp = getDeclaration(program, _('/entry.ts'), 'TestCmp', isNamedClassDeclaration);
|
||||
const detected = handler.detect(TestCmp, reflectionHost.getDecoratorsOfDeclaration(TestCmp));
|
||||
if (detected === undefined) {
|
||||
return fail('Failed to recognize @Component');
|
||||
}
|
||||
const diag = err.toDiagnostic();
|
||||
expect(diag.code).toEqual(ivyCode(ErrorCode.DECORATOR_ARG_NOT_LITERAL));
|
||||
expect(diag.file.fileName.endsWith('entry.ts')).toBe(true);
|
||||
expect(diag.start).toBe(detected.metadata.args ![0].getStart());
|
||||
}
|
||||
try {
|
||||
handler.analyze(TestCmp, detected.metadata);
|
||||
return fail('Analysis should have failed');
|
||||
} catch (err) {
|
||||
if (!(err instanceof FatalDiagnosticError)) {
|
||||
return fail('Error should be a FatalDiagnosticError');
|
||||
}
|
||||
const diag = err.toDiagnostic();
|
||||
expect(diag.code).toEqual(ivyCode(ErrorCode.DECORATOR_ARG_NOT_LITERAL));
|
||||
expect(diag.file.fileName.endsWith('entry.ts')).toBe(true);
|
||||
expect(diag.start).toBe(detected.metadata.args ![0].getStart());
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
function ivyCode(code: ErrorCode): number {
|
||||
return Number('-99' + code.valueOf());
|
||||
}
|
||||
function ivyCode(code: ErrorCode): number { return Number('-99' + code.valueOf()); }
|
||||
});
|
||||
|
@ -5,25 +5,30 @@
|
||||
* 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 {absoluteFrom} from '../../file_system';
|
||||
import {runInEachFileSystem} from '../../file_system/testing';
|
||||
import {NOOP_DEFAULT_IMPORT_RECORDER, ReferenceEmitter} from '../../imports';
|
||||
import {DtsMetadataReader, LocalMetadataRegistry} from '../../metadata';
|
||||
import {PartialEvaluator} from '../../partial_evaluator';
|
||||
import {ClassDeclaration, TypeScriptReflectionHost, isNamedClassDeclaration} from '../../reflection';
|
||||
import {LocalModuleScopeRegistry, MetadataDtsModuleScopeResolver} from '../../scope';
|
||||
import {getDeclaration, makeProgram} from '../../testing/in_memory_typescript';
|
||||
import {getDeclaration, makeProgram} from '../../testing';
|
||||
import {DirectiveDecoratorHandler} from '../src/directive';
|
||||
|
||||
runInEachFileSystem(() => {
|
||||
describe('DirectiveDecoratorHandler', () => {
|
||||
let _: typeof absoluteFrom;
|
||||
beforeEach(() => _ = absoluteFrom);
|
||||
|
||||
describe('DirectiveDecoratorHandler', () => {
|
||||
it('should use the `ReflectionHost` to detect class inheritance', () => {
|
||||
const {program} = makeProgram([
|
||||
{
|
||||
name: 'node_modules/@angular/core/index.d.ts',
|
||||
contents: 'export const Directive: any;',
|
||||
},
|
||||
{
|
||||
name: 'entry.ts',
|
||||
contents: `
|
||||
it('should use the `ReflectionHost` to detect class inheritance', () => {
|
||||
const {program} = makeProgram([
|
||||
{
|
||||
name: _('/node_modules/@angular/core/index.d.ts'),
|
||||
contents: 'export const Directive: any;',
|
||||
},
|
||||
{
|
||||
name: _('/entry.ts'),
|
||||
contents: `
|
||||
import {Directive} from '@angular/core';
|
||||
|
||||
@Directive({selector: 'test-dir-1'})
|
||||
@ -32,51 +37,53 @@ describe('DirectiveDecoratorHandler', () => {
|
||||
@Directive({selector: 'test-dir-2'})
|
||||
export class TestDir2 {}
|
||||
`,
|
||||
},
|
||||
]);
|
||||
},
|
||||
]);
|
||||
|
||||
const checker = program.getTypeChecker();
|
||||
const reflectionHost = new TestReflectionHost(checker);
|
||||
const evaluator = new PartialEvaluator(reflectionHost, checker);
|
||||
const metaReader = new LocalMetadataRegistry();
|
||||
const dtsReader = new DtsMetadataReader(checker, reflectionHost);
|
||||
const scopeRegistry = new LocalModuleScopeRegistry(
|
||||
metaReader, new MetadataDtsModuleScopeResolver(dtsReader, null), new ReferenceEmitter([]),
|
||||
null);
|
||||
const handler = new DirectiveDecoratorHandler(
|
||||
reflectionHost, evaluator, scopeRegistry, NOOP_DEFAULT_IMPORT_RECORDER, false);
|
||||
const checker = program.getTypeChecker();
|
||||
const reflectionHost = new TestReflectionHost(checker);
|
||||
const evaluator = new PartialEvaluator(reflectionHost, checker);
|
||||
const metaReader = new LocalMetadataRegistry();
|
||||
const dtsReader = new DtsMetadataReader(checker, reflectionHost);
|
||||
const scopeRegistry = new LocalModuleScopeRegistry(
|
||||
metaReader, new MetadataDtsModuleScopeResolver(dtsReader, null), new ReferenceEmitter([]),
|
||||
null);
|
||||
const handler = new DirectiveDecoratorHandler(
|
||||
reflectionHost, evaluator, scopeRegistry, NOOP_DEFAULT_IMPORT_RECORDER, false);
|
||||
|
||||
const analyzeDirective = (dirName: string) => {
|
||||
const DirNode = getDeclaration(program, 'entry.ts', dirName, isNamedClassDeclaration);
|
||||
const analyzeDirective = (dirName: string) => {
|
||||
const DirNode = getDeclaration(program, _('/entry.ts'), dirName, isNamedClassDeclaration);
|
||||
|
||||
const detected = handler.detect(DirNode, reflectionHost.getDecoratorsOfDeclaration(DirNode));
|
||||
if (detected === undefined) {
|
||||
throw new Error(`Failed to recognize @Directive (${dirName}).`);
|
||||
}
|
||||
const detected =
|
||||
handler.detect(DirNode, reflectionHost.getDecoratorsOfDeclaration(DirNode));
|
||||
if (detected === undefined) {
|
||||
throw new Error(`Failed to recognize @Directive (${dirName}).`);
|
||||
}
|
||||
|
||||
const {analysis} = handler.analyze(DirNode, detected.metadata);
|
||||
if (analysis === undefined) {
|
||||
throw new Error(`Failed to analyze @Directive (${dirName}).`);
|
||||
}
|
||||
const {analysis} = handler.analyze(DirNode, detected.metadata);
|
||||
if (analysis === undefined) {
|
||||
throw new Error(`Failed to analyze @Directive (${dirName}).`);
|
||||
}
|
||||
|
||||
return analysis;
|
||||
};
|
||||
return analysis;
|
||||
};
|
||||
|
||||
// By default, `TestReflectionHost#hasBaseClass()` returns `false`.
|
||||
const analysis1 = analyzeDirective('TestDir1');
|
||||
expect(analysis1.meta.usesInheritance).toBe(false);
|
||||
// By default, `TestReflectionHost#hasBaseClass()` returns `false`.
|
||||
const analysis1 = analyzeDirective('TestDir1');
|
||||
expect(analysis1.meta.usesInheritance).toBe(false);
|
||||
|
||||
// Tweak `TestReflectionHost#hasBaseClass()` to return true.
|
||||
reflectionHost.hasBaseClassReturnValue = true;
|
||||
// Tweak `TestReflectionHost#hasBaseClass()` to return true.
|
||||
reflectionHost.hasBaseClassReturnValue = true;
|
||||
|
||||
const analysis2 = analyzeDirective('TestDir2');
|
||||
expect(analysis2.meta.usesInheritance).toBe(true);
|
||||
const analysis2 = analyzeDirective('TestDir2');
|
||||
expect(analysis2.meta.usesInheritance).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// Helpers
|
||||
class TestReflectionHost extends TypeScriptReflectionHost {
|
||||
hasBaseClassReturnValue = false;
|
||||
|
||||
hasBaseClass(clazz: ClassDeclaration): boolean { return this.hasBaseClassReturnValue; }
|
||||
}
|
||||
});
|
||||
|
||||
// Helpers
|
||||
class TestReflectionHost extends TypeScriptReflectionHost {
|
||||
hasBaseClassReturnValue = false;
|
||||
|
||||
hasBaseClass(clazz: ClassDeclaration): boolean { return this.hasBaseClassReturnValue; }
|
||||
}
|
||||
|
@ -5,53 +5,44 @@
|
||||
* 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 * as ts from 'typescript';
|
||||
|
||||
import {absoluteFrom, getSourceFileOrError} from '../../file_system';
|
||||
import {TestFile, runInEachFileSystem} from '../../file_system/testing';
|
||||
import {NOOP_DEFAULT_IMPORT_RECORDER, NoopImportRewriter} from '../../imports';
|
||||
import {TypeScriptReflectionHost} from '../../reflection';
|
||||
import {getDeclaration, makeProgram} from '../../testing/in_memory_typescript';
|
||||
import {getDeclaration, makeProgram} from '../../testing';
|
||||
import {ImportManager, translateStatement} from '../../translator';
|
||||
import {generateSetClassMetadataCall} from '../src/metadata';
|
||||
|
||||
const CORE = {
|
||||
name: 'node_modules/@angular/core/index.d.ts',
|
||||
contents: `
|
||||
export declare function Input(...args: any[]): any;
|
||||
export declare function Inject(...args: any[]): any;
|
||||
export declare function Component(...args: any[]): any;
|
||||
export declare class Injector {}
|
||||
`
|
||||
};
|
||||
|
||||
describe('ngtsc setClassMetadata converter', () => {
|
||||
it('should convert decorated class metadata', () => {
|
||||
const res = compileAndPrint(`
|
||||
runInEachFileSystem(() => {
|
||||
describe('ngtsc setClassMetadata converter', () => {
|
||||
it('should convert decorated class metadata', () => {
|
||||
const res = compileAndPrint(`
|
||||
import {Component} from '@angular/core';
|
||||
|
||||
|
||||
@Component('metadata') class Target {}
|
||||
`);
|
||||
expect(res).toEqual(
|
||||
`/*@__PURE__*/ i0.ɵsetClassMetadata(Target, [{ type: Component, args: ['metadata'] }], null, null);`);
|
||||
});
|
||||
expect(res).toEqual(
|
||||
`/*@__PURE__*/ i0.ɵsetClassMetadata(Target, [{ type: Component, args: ['metadata'] }], null, null);`);
|
||||
});
|
||||
|
||||
it('should convert decorated class constructor parameter metadata', () => {
|
||||
const res = compileAndPrint(`
|
||||
it('should convert decorated class constructor parameter metadata', () => {
|
||||
const res = compileAndPrint(`
|
||||
import {Component, Inject, Injector} from '@angular/core';
|
||||
const FOO = 'foo';
|
||||
|
||||
|
||||
@Component('metadata') class Target {
|
||||
constructor(@Inject(FOO) foo: any, bar: Injector) {}
|
||||
}
|
||||
`);
|
||||
expect(res).toContain(
|
||||
`function () { return [{ type: undefined, decorators: [{ type: Inject, args: [FOO] }] }, { type: i0.Injector }]; }, null);`);
|
||||
});
|
||||
expect(res).toContain(
|
||||
`function () { return [{ type: undefined, decorators: [{ type: Inject, args: [FOO] }] }, { type: i0.Injector }]; }, null);`);
|
||||
});
|
||||
|
||||
it('should convert decorated field metadata', () => {
|
||||
const res = compileAndPrint(`
|
||||
it('should convert decorated field metadata', () => {
|
||||
const res = compileAndPrint(`
|
||||
import {Component, Input} from '@angular/core';
|
||||
|
||||
|
||||
@Component('metadata') class Target {
|
||||
@Input() foo: string;
|
||||
|
||||
@ -60,35 +51,47 @@ describe('ngtsc setClassMetadata converter', () => {
|
||||
notDecorated: string;
|
||||
}
|
||||
`);
|
||||
expect(res).toContain(`{ foo: [{ type: Input }], bar: [{ type: Input, args: ['value'] }] })`);
|
||||
});
|
||||
expect(res).toContain(`{ foo: [{ type: Input }], bar: [{ type: Input, args: ['value'] }] })`);
|
||||
});
|
||||
|
||||
it('should not convert non-angular decorators to metadata', () => {
|
||||
const res = compileAndPrint(`
|
||||
it('should not convert non-angular decorators to metadata', () => {
|
||||
const res = compileAndPrint(`
|
||||
declare function NotAComponent(...args: any[]): any;
|
||||
|
||||
|
||||
@NotAComponent('metadata') class Target {}
|
||||
`);
|
||||
expect(res).toBe('');
|
||||
expect(res).toBe('');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
function compileAndPrint(contents: string): string {
|
||||
const {program} = makeProgram([
|
||||
CORE, {
|
||||
name: 'index.ts',
|
||||
contents,
|
||||
function compileAndPrint(contents: string): string {
|
||||
const _ = absoluteFrom;
|
||||
const CORE: TestFile = {
|
||||
name: _('/node_modules/@angular/core/index.d.ts'),
|
||||
contents: `
|
||||
export declare function Input(...args: any[]): any;
|
||||
export declare function Inject(...args: any[]): any;
|
||||
export declare function Component(...args: any[]): any;
|
||||
export declare class Injector {}
|
||||
`
|
||||
};
|
||||
|
||||
const {program} = makeProgram([
|
||||
CORE, {
|
||||
name: _('/index.ts'),
|
||||
contents,
|
||||
}
|
||||
]);
|
||||
const host = new TypeScriptReflectionHost(program.getTypeChecker());
|
||||
const target = getDeclaration(program, _('/index.ts'), 'Target', ts.isClassDeclaration);
|
||||
const call = generateSetClassMetadataCall(target, host, NOOP_DEFAULT_IMPORT_RECORDER, false);
|
||||
if (call === null) {
|
||||
return '';
|
||||
}
|
||||
]);
|
||||
const host = new TypeScriptReflectionHost(program.getTypeChecker());
|
||||
const target = getDeclaration(program, 'index.ts', 'Target', ts.isClassDeclaration);
|
||||
const call = generateSetClassMetadataCall(target, host, NOOP_DEFAULT_IMPORT_RECORDER, false);
|
||||
if (call === null) {
|
||||
return '';
|
||||
const sf = getSourceFileOrError(program, _('/index.ts'));
|
||||
const im = new ImportManager(new NoopImportRewriter(), 'i');
|
||||
const tsStatement = translateStatement(call, im, NOOP_DEFAULT_IMPORT_RECORDER);
|
||||
const res = ts.createPrinter().printNode(ts.EmitHint.Unspecified, tsStatement, sf);
|
||||
return res.replace(/\s+/g, ' ');
|
||||
}
|
||||
const sf = program.getSourceFile('index.ts') !;
|
||||
const im = new ImportManager(new NoopImportRewriter(), 'i');
|
||||
const tsStatement = translateStatement(call, im, NOOP_DEFAULT_IMPORT_RECORDER);
|
||||
const res = ts.createPrinter().printNode(ts.EmitHint.Unspecified, tsStatement, sf);
|
||||
return res.replace(/\s+/g, ' ');
|
||||
}
|
||||
});
|
||||
|
@ -5,34 +5,36 @@
|
||||
* 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 {WrappedNodeExpr} from '@angular/compiler';
|
||||
import {R3Reference} from '@angular/compiler/src/compiler';
|
||||
import * as ts from 'typescript';
|
||||
|
||||
import {absoluteFrom} from '../../file_system';
|
||||
import {runInEachFileSystem} from '../../file_system/testing';
|
||||
import {LocalIdentifierStrategy, NOOP_DEFAULT_IMPORT_RECORDER, ReferenceEmitter} from '../../imports';
|
||||
import {DtsMetadataReader, LocalMetadataRegistry} from '../../metadata';
|
||||
import {PartialEvaluator} from '../../partial_evaluator';
|
||||
import {TypeScriptReflectionHost, isNamedClassDeclaration} from '../../reflection';
|
||||
import {LocalModuleScopeRegistry, MetadataDtsModuleScopeResolver} from '../../scope';
|
||||
import {getDeclaration, makeProgram} from '../../testing/in_memory_typescript';
|
||||
import {getDeclaration, makeProgram} from '../../testing';
|
||||
import {NgModuleDecoratorHandler} from '../src/ng_module';
|
||||
import {NoopReferencesRegistry} from '../src/references_registry';
|
||||
|
||||
describe('NgModuleDecoratorHandler', () => {
|
||||
it('should resolve forwardRef', () => {
|
||||
const {program} = makeProgram([
|
||||
{
|
||||
name: 'node_modules/@angular/core/index.d.ts',
|
||||
contents: `
|
||||
runInEachFileSystem(() => {
|
||||
describe('NgModuleDecoratorHandler', () => {
|
||||
it('should resolve forwardRef', () => {
|
||||
const _ = absoluteFrom;
|
||||
const {program} = makeProgram([
|
||||
{
|
||||
name: _('/node_modules/@angular/core/index.d.ts'),
|
||||
contents: `
|
||||
export const Component: any;
|
||||
export const NgModule: any;
|
||||
export declare function forwardRef(fn: () => any): any;
|
||||
`,
|
||||
},
|
||||
{
|
||||
name: 'entry.ts',
|
||||
contents: `
|
||||
},
|
||||
{
|
||||
name: _('/entry.ts'),
|
||||
contents: `
|
||||
import {Component, forwardRef, NgModule} from '@angular/core';
|
||||
|
||||
@Component({
|
||||
@ -50,37 +52,38 @@ describe('NgModuleDecoratorHandler', () => {
|
||||
})
|
||||
export class TestModule {}
|
||||
`
|
||||
},
|
||||
]);
|
||||
const checker = program.getTypeChecker();
|
||||
const reflectionHost = new TypeScriptReflectionHost(checker);
|
||||
const evaluator = new PartialEvaluator(reflectionHost, checker);
|
||||
const referencesRegistry = new NoopReferencesRegistry();
|
||||
const metaRegistry = new LocalMetadataRegistry();
|
||||
const dtsReader = new DtsMetadataReader(checker, reflectionHost);
|
||||
const scopeRegistry = new LocalModuleScopeRegistry(
|
||||
metaRegistry, new MetadataDtsModuleScopeResolver(dtsReader, null), new ReferenceEmitter([]),
|
||||
null);
|
||||
const refEmitter = new ReferenceEmitter([new LocalIdentifierStrategy()]);
|
||||
},
|
||||
]);
|
||||
const checker = program.getTypeChecker();
|
||||
const reflectionHost = new TypeScriptReflectionHost(checker);
|
||||
const evaluator = new PartialEvaluator(reflectionHost, checker);
|
||||
const referencesRegistry = new NoopReferencesRegistry();
|
||||
const metaRegistry = new LocalMetadataRegistry();
|
||||
const dtsReader = new DtsMetadataReader(checker, reflectionHost);
|
||||
const scopeRegistry = new LocalModuleScopeRegistry(
|
||||
metaRegistry, new MetadataDtsModuleScopeResolver(dtsReader, null),
|
||||
new ReferenceEmitter([]), null);
|
||||
const refEmitter = new ReferenceEmitter([new LocalIdentifierStrategy()]);
|
||||
|
||||
const handler = new NgModuleDecoratorHandler(
|
||||
reflectionHost, evaluator, metaRegistry, scopeRegistry, referencesRegistry, false, null,
|
||||
refEmitter, NOOP_DEFAULT_IMPORT_RECORDER);
|
||||
const TestModule = getDeclaration(program, 'entry.ts', 'TestModule', isNamedClassDeclaration);
|
||||
const detected =
|
||||
handler.detect(TestModule, reflectionHost.getDecoratorsOfDeclaration(TestModule));
|
||||
if (detected === undefined) {
|
||||
return fail('Failed to recognize @NgModule');
|
||||
}
|
||||
const moduleDef = handler.analyze(TestModule, detected.metadata).analysis !.ngModuleDef;
|
||||
const handler = new NgModuleDecoratorHandler(
|
||||
reflectionHost, evaluator, metaRegistry, scopeRegistry, referencesRegistry, false, null,
|
||||
refEmitter, NOOP_DEFAULT_IMPORT_RECORDER);
|
||||
const TestModule =
|
||||
getDeclaration(program, _('/entry.ts'), 'TestModule', isNamedClassDeclaration);
|
||||
const detected =
|
||||
handler.detect(TestModule, reflectionHost.getDecoratorsOfDeclaration(TestModule));
|
||||
if (detected === undefined) {
|
||||
return fail('Failed to recognize @NgModule');
|
||||
}
|
||||
const moduleDef = handler.analyze(TestModule, detected.metadata).analysis !.ngModuleDef;
|
||||
|
||||
expect(getReferenceIdentifierTexts(moduleDef.declarations)).toEqual(['TestComp']);
|
||||
expect(getReferenceIdentifierTexts(moduleDef.exports)).toEqual(['TestComp']);
|
||||
expect(getReferenceIdentifierTexts(moduleDef.imports)).toEqual(['TestModuleDependency']);
|
||||
expect(getReferenceIdentifierTexts(moduleDef.declarations)).toEqual(['TestComp']);
|
||||
expect(getReferenceIdentifierTexts(moduleDef.exports)).toEqual(['TestComp']);
|
||||
expect(getReferenceIdentifierTexts(moduleDef.imports)).toEqual(['TestModuleDependency']);
|
||||
|
||||
function getReferenceIdentifierTexts(references: R3Reference[]) {
|
||||
return references.map(ref => (ref.value as WrappedNodeExpr<ts.Identifier>).node.text);
|
||||
}
|
||||
function getReferenceIdentifierTexts(references: R3Reference[]) {
|
||||
return references.map(ref => (ref.value as WrappedNodeExpr<ts.Identifier>).node.text);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
});
|
||||
|
Reference in New Issue
Block a user