refactor(ivy): extract selector scope logic to a new ngtsc package (#28852)

This commit splits apart selector_scope.ts in ngtsc and extracts the logic
into two separate classes, the LocalModuleScopeRegistry and the
DtsModuleScopeResolver. The logic is cleaned up significantly and new tests
are added to verify behavior.

LocalModuleScopeRegistry implements the NgModule semantics for compilation
scopes, and handles NgModules declared in the current compilation unit.
DtsModuleScopeResolver implements simpler logic for export scopes and
handles NgModules declared in .d.ts files.

This is done in preparation for the addition of re-export logic to solve
StrictDeps issues.

PR Close #28852
This commit is contained in:
Alex Rickabaugh
2019-02-19 12:05:03 -08:00
committed by Ben Lesh
parent fafabc0b92
commit 15c065f9a0
28 changed files with 1105 additions and 830 deletions

View File

@ -0,0 +1,19 @@
package(default_visibility = ["//visibility:public"])
load("//tools:defaults.bzl", "ts_library")
ts_library(
name = "scope",
srcs = glob([
"index.ts",
"src/**/*.ts",
]),
deps = [
"//packages/compiler",
"//packages/compiler-cli/src/ngtsc/imports",
"//packages/compiler-cli/src/ngtsc/reflection",
"//packages/compiler-cli/src/ngtsc/typecheck",
"//packages/compiler-cli/src/ngtsc/util",
"@ngdeps//typescript",
],
)

View File

@ -0,0 +1,12 @@
/**
* @license
* Copyright Google Inc. 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
*/
export {ExportScope, ScopeData, ScopeDirective, ScopePipe} from './src/api';
export {DtsModuleScopeResolver, MetadataDtsModuleScopeResolver} from './src/dependency';
export {LocalModuleScope, LocalModuleScopeRegistry, LocalNgModuleData} from './src/local';
export {extractDirectiveGuards} from './src/util';

View File

@ -0,0 +1,56 @@
/**
* @license
* Copyright Google Inc. 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 * as ts from 'typescript';
import {Reference} from '../../imports';
import {TypeCheckableDirectiveMeta} from '../../typecheck';
/**
* Data for one of a given NgModule's scopes (either compilation scope or export scopes).
*/
export interface ScopeData {
/**
* Directives in the exported scope of the module.
*/
directives: ScopeDirective[];
/**
* Pipes in the exported scope of the module.
*/
pipes: ScopePipe[];
}
/**
* An export scope of an NgModule, containing the directives/pipes it contributes to other NgModules
* which import it.
*/
export interface ExportScope {
/**
* The scope exported by an NgModule, and available for import.
*/
exported: ScopeData;
}
/**
* Metadata for a given directive within an NgModule's scope.
*/
export interface ScopeDirective extends TypeCheckableDirectiveMeta {
/**
* Unparsed selector of the directive.
*/
selector: string;
}
/**
* Metadata for a given pipe within an NgModule's scope.
*/
export interface ScopePipe {
ref: Reference<ts.Declaration>;
name: string;
}

View File

@ -0,0 +1,202 @@
/**
* @license
* Copyright Google Inc. 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 * as ts from 'typescript';
import {Reference} from '../../imports';
import {ReflectionHost} from '../../reflection';
import {ExportScope, ScopeDirective, ScopePipe} from './api';
import {extractDirectiveGuards, extractReferencesFromType, readStringArrayType, readStringMapType, readStringType} from './util';
export interface DtsModuleScopeResolver {
resolve(ref: Reference<ts.ClassDeclaration>): ExportScope|null;
}
/**
* Reads Angular metadata from classes declared in .d.ts files and computes an `ExportScope`.
*
* Given an NgModule declared in a .d.ts file, this resolver can produce a transitive `ExportScope`
* of all of the directives/pipes it exports. It does this by reading metadata off of Ivy static
* fields on directives, components, pipes, and NgModules.
*/
export class MetadataDtsModuleScopeResolver {
/**
* Cache which holds fully resolved scopes for NgModule classes from .d.ts files.
*/
private cache = new Map<ts.ClassDeclaration, ExportScope|null>();
constructor(private checker: ts.TypeChecker, private reflector: ReflectionHost) {}
/**
* Resolve a `Reference`'d NgModule from a .d.ts file and produce a transitive `ExportScope`
* listing the directives and pipes which that NgModule exports to others.
*
* This operation relies on a `Reference` instead of a direct TypeScrpt node as the `Reference`s
* produced depend on how the original NgModule was imported.
*/
resolve(ref: Reference<ts.ClassDeclaration>): ExportScope|null {
const clazz = ref.node;
if (!clazz.getSourceFile().isDeclarationFile) {
throw new Error(
`Debug error: DtsModuleScopeResolver.read(${ref.debugName} from ${clazz.getSourceFile().fileName}), but not a .d.ts file`);
}
if (this.cache.has(clazz)) {
return this.cache.get(clazz) !;
}
// Build up the export scope - those directives and pipes made visible by this module.
const directives: ScopeDirective[] = [];
const pipes: ScopePipe[] = [];
const meta = this.readModuleMetadataFromClass(ref);
if (meta === null) {
this.cache.set(clazz, null);
return null;
}
// Only the 'exports' field of the NgModule's metadata is important. Imports and declarations
// don't affect the export scope.
for (const exportRef of meta.exports) {
// Attempt to process the export as a directive.
const directive = this.readScopeDirectiveFromClassWithDef(exportRef);
if (directive !== null) {
directives.push(directive);
continue;
}
// Attempt to process the export as a pipe.
const pipe = this.readScopePipeFromClassWithDef(exportRef);
if (pipe !== null) {
pipes.push(pipe);
continue;
}
// Attempt to process the export as a module.
const exportScope = this.resolve(exportRef);
if (exportScope !== null) {
// It is a module. Add exported directives and pipes to the current scope.
directives.push(...exportScope.exported.directives);
pipes.push(...exportScope.exported.pipes);
continue;
}
// The export was not a directive, a pipe, or a module. This is an error.
// TODO(alxhub): produce a ts.Diagnostic
throw new Error(`Exported value ${exportRef.debugName} was not a directive, pipe, or module`);
}
return {
exported: {directives, pipes},
};
}
/**
* Read the metadata from a class that has already been compiled somehow (either it's in a .d.ts
* file, or in a .ts file with a handwritten definition).
*
* @param ref `Reference` to the class of interest, with the context of how it was obtained.
*/
private readModuleMetadataFromClass(ref: Reference<ts.Declaration>): RawDependencyMetadata|null {
const clazz = ref.node;
const resolutionContext = clazz.getSourceFile().fileName;
// This operation is explicitly not memoized, as it depends on `ref.ownedByModuleGuess`.
// TODO(alxhub): investigate caching of .d.ts module metadata.
const ngModuleDef = this.reflector.getMembersOfClass(clazz).find(
member => member.name === 'ngModuleDef' && member.isStatic);
if (ngModuleDef === undefined) {
return null;
} else if (
// Validate that the shape of the ngModuleDef type is correct.
ngModuleDef.type === null || !ts.isTypeReferenceNode(ngModuleDef.type) ||
ngModuleDef.type.typeArguments === undefined ||
ngModuleDef.type.typeArguments.length !== 4) {
return null;
}
// Read the ModuleData out of the type arguments.
const [_, declarationMetadata, importMetadata, exportMetadata] = ngModuleDef.type.typeArguments;
return {
declarations: extractReferencesFromType(
this.checker, declarationMetadata, ref.ownedByModuleGuess, resolutionContext),
exports: extractReferencesFromType(
this.checker, exportMetadata, ref.ownedByModuleGuess, resolutionContext),
imports: extractReferencesFromType(
this.checker, importMetadata, ref.ownedByModuleGuess, resolutionContext),
};
}
/**
* Read directive (or component) metadata from a referenced class in a .d.ts file.
*/
private readScopeDirectiveFromClassWithDef(ref: Reference<ts.ClassDeclaration>): ScopeDirective
|null {
const clazz = ref.node;
const def = this.reflector.getMembersOfClass(clazz).find(
field =>
field.isStatic && (field.name === 'ngComponentDef' || field.name === 'ngDirectiveDef'));
if (def === undefined) {
// No definition could be found.
return null;
} else if (
def.type === null || !ts.isTypeReferenceNode(def.type) ||
def.type.typeArguments === undefined || def.type.typeArguments.length < 2) {
// The type metadata was the wrong shape.
return null;
}
const selector = readStringType(def.type.typeArguments[1]);
if (selector === null) {
return null;
}
return {
ref,
name: clazz.name !.text,
isComponent: def.name === 'ngComponentDef', selector,
exportAs: readStringArrayType(def.type.typeArguments[2]),
inputs: readStringMapType(def.type.typeArguments[3]),
outputs: readStringMapType(def.type.typeArguments[4]),
queries: readStringArrayType(def.type.typeArguments[5]),
...extractDirectiveGuards(clazz, this.reflector),
};
}
/**
* Read pipe metadata from a referenced class in a .d.ts file.
*/
private readScopePipeFromClassWithDef(ref: Reference<ts.ClassDeclaration>): ScopePipe|null {
const def = this.reflector.getMembersOfClass(ref.node).find(
field => field.isStatic && field.name === 'ngPipeDef');
if (def === undefined) {
// No definition could be found.
return null;
} else if (
def.type === null || !ts.isTypeReferenceNode(def.type) ||
def.type.typeArguments === undefined || def.type.typeArguments.length < 2) {
// The type metadata was the wrong shape.
return null;
}
const type = def.type.typeArguments[1];
if (!ts.isLiteralTypeNode(type) || !ts.isStringLiteral(type.literal)) {
// The type metadata was the wrong type.
return null;
}
const name = type.literal.text;
return {ref, name};
}
}
/**
* Raw metadata read from the .d.ts info of an ngModuleDef field on a compiled NgModule class.
*/
interface RawDependencyMetadata {
declarations: Reference<ts.ClassDeclaration>[];
imports: Reference<ts.ClassDeclaration>[];
exports: Reference<ts.ClassDeclaration>[];
}

View File

@ -0,0 +1,282 @@
/**
* @license
* Copyright Google Inc. 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 * as ts from 'typescript';
import {Reference} from '../../imports';
import {ExportScope, ScopeData, ScopeDirective, ScopePipe} from './api';
import {DtsModuleScopeResolver} from './dependency';
export interface LocalNgModuleData {
declarations: Reference<ts.Declaration>[];
imports: Reference<ts.Declaration>[];
exports: Reference<ts.Declaration>[];
}
/**
* A scope produced for an NgModule declared locally (in the current program being compiled).
*
* The `LocalModuleScope` contains the compilation scope, the transitive set of directives and pipes
* visible to any component declared in this module. It also contains an `ExportScope`, the
* transitive set of directives and pipes
*/
export interface LocalModuleScope extends ExportScope { compilation: ScopeData; }
/**
* A registry which collects information about NgModules, Directives, Components, and Pipes which
* are local (declared in the ts.Program being compiled), and can produce `LocalModuleScope`s
* which summarize the compilation scope of a component.
*
* This class implements the logic of NgModule declarations, imports, and exports and can produce,
* for a given component, the set of directives and pipes which are "visible" in that component's
* template.
*
* The `LocalModuleScopeRegistry` has two "modes" of operation. During analysis, data for each
* individual NgModule, Directive, Component, and Pipe is added to the registry. No attempt is made
* to traverse or validate the NgModule graph (imports, exports, etc). After analysis, one of
* `getScopeOfModule` or `getScopeForComponent` can be called, which traverses the NgModule graph
* and applies the NgModule logic to generate a `LocalModuleScope`, the full scope for the given
* module or component.
*/
export class LocalModuleScopeRegistry {
/**
* Tracks whether the registry has been asked to produce scopes for a module or component. Once
* this is true, the registry cannot accept registrations of new directives/pipes/modules as it
* would invalidate the cached scope data.
*/
private sealed = false;
/**
* Metadata for each local NgModule registered.
*/
private ngModuleData = new Map<ts.Declaration, LocalNgModuleData>();
/**
* Metadata for each local directive registered.
*/
private directiveData = new Map<ts.Declaration, ScopeDirective>();
/**
* Metadata for each local pipe registered.
*/
private pipeData = new Map<ts.Declaration, ScopePipe>();
/**
* A map of components from the current compilation unit to the NgModule which declared them.
*
* As components and directives are not distinguished at the NgModule level, this map may also
* contain directives. This doesn't cause any problems but isn't useful as there is no concept of
* a directive's compilation scope.
*/
private declarationToModule = new Map<ts.Declaration, ts.Declaration>();
/**
* A cache of calculated `LocalModuleScope`s for each NgModule declared in the current program.
*/
private cache = new Map<ts.Declaration, LocalModuleScope>();
/**
* Tracks whether a given component requires "remote scoping".
*
* Remote scoping is when the set of directives which apply to a given component is set in the
* NgModule's file instead of directly on the ngComponentDef (which is sometimes needed to get
* around cyclic import issues). This is not used in calculation of `LocalModuleScope`s, but is
* tracked here for convenience.
*/
private remoteScoping = new Set<ts.Declaration>();
constructor(private dependencyScopeReader: DtsModuleScopeResolver) {}
/**
* Add an NgModule's data to the registry.
*/
registerNgModule(clazz: ts.Declaration, data: LocalNgModuleData): void {
this.assertCollecting();
this.ngModuleData.set(clazz, data);
for (const decl of data.declarations) {
this.declarationToModule.set(decl.node, clazz);
}
}
registerDirective(directive: ScopeDirective): void {
this.assertCollecting();
this.directiveData.set(directive.ref.node, directive);
}
registerPipe(pipe: ScopePipe): void {
this.assertCollecting();
this.pipeData.set(pipe.ref.node, pipe);
}
getScopeForComponent(clazz: ts.ClassDeclaration): LocalModuleScope|null {
if (!this.declarationToModule.has(clazz)) {
return null;
}
return this.getScopeOfModule(this.declarationToModule.get(clazz) !);
}
/**
* Collects registered data for a module and its directives/pipes and convert it into a full
* `LocalModuleScope`.
*
* This method implements the logic of NgModule imports and exports.
*/
getScopeOfModule(clazz: ts.Declaration): LocalModuleScope|null {
// Seal the registry to protect the integrity of the `LocalModuleScope` cache.
this.sealed = true;
// Look for cached data if available.
if (this.cache.has(clazz)) {
return this.cache.get(clazz) !;
}
// `clazz` should be an NgModule previously added to the registry. If not, a scope for it
// cannot be produced.
if (!this.ngModuleData.has(clazz)) {
return null;
}
const ngModule = this.ngModuleData.get(clazz) !;
// At this point, the goal is to produce two distinct transitive sets:
// - the directives and pipes which are visible to components declared in the NgModule.
// - the directives and pipes which are exported to any NgModules which import this one.
// Directives and pipes in the compilation scope.
const compilationDirectives = new Map<ts.Declaration, ScopeDirective>();
const compilationPipes = new Map<ts.Declaration, ScopePipe>();
// Directives and pipes exported to any importing NgModules.
const exportDirectives = new Map<ts.Declaration, ScopeDirective>();
const exportPipes = new Map<ts.Declaration, ScopePipe>();
// The algorithm is as follows:
// 1) Add directives/pipes declared in the NgModule to the compilation scope.
// 2) Add all of the directives/pipes from each NgModule imported into the current one to the
// compilation scope. At this point, the compilation scope is complete.
// 3) For each entry in the NgModule's exports:
// a) Attempt to resolve it as an NgModule with its own exported directives/pipes. If it is
// one, add them to the export scope of this NgModule.
// b) Otherwise, it should be a class in the compilation scope of this NgModule. If it is,
// add it to the export scope.
// c) If it's neither an NgModule nor a directive/pipe in the compilation scope, then this
// is an error.
// 1) add declarations.
for (const decl of ngModule.declarations) {
if (this.directiveData.has(decl.node)) {
const directive = this.directiveData.get(decl.node) !;
compilationDirectives.set(
decl.node, {...directive, ref: decl as Reference<ts.ClassDeclaration>});
} else if (this.pipeData.has(decl.node)) {
const pipe = this.pipeData.get(decl.node) !;
compilationPipes.set(decl.node, {...pipe, ref: decl});
} else {
// TODO(alxhub): produce a ts.Diagnostic. This can't be an error right now since some
// ngtools tests rely on analysis of broken components.
continue;
}
}
// 2) process imports.
for (const decl of ngModule.imports) {
const importScope = this.getExportedScope(decl);
if (importScope === null) {
// TODO(alxhub): produce a ts.Diagnostic
throw new Error(`Unknown import: ${decl.debugName}`);
}
for (const directive of importScope.exported.directives) {
compilationDirectives.set(directive.ref.node, directive);
}
for (const pipe of importScope.exported.pipes) {
compilationPipes.set(pipe.ref.node, pipe);
}
}
// 3) process exports.
// Exports can contain modules, components, or directives. They're processed differently.
// Modules are straightforward. Directives and pipes from exported modules are added to the
// export maps. Directives/pipes are different - they might be exports of declared types or
// imported types.
for (const decl of ngModule.exports) {
// Attempt to resolve decl as an NgModule.
const importScope = this.getExportedScope(decl);
if (importScope !== null) {
// decl is an NgModule.
for (const directive of importScope.exported.directives) {
exportDirectives.set(directive.ref.node, directive);
}
for (const pipe of importScope.exported.pipes) {
exportPipes.set(pipe.ref.node, pipe);
}
} else if (compilationDirectives.has(decl.node)) {
// decl is a directive or component in the compilation scope of this NgModule.
const directive = compilationDirectives.get(decl.node) !;
exportDirectives.set(decl.node, directive);
} else if (compilationPipes.has(decl.node)) {
// decl is a pipe in the compilation scope of this NgModule.
const pipe = compilationPipes.get(decl.node) !;
exportPipes.set(decl.node, pipe);
} else {
// decl is an unknown export.
// TODO(alxhub): produce a ts.Diagnostic
throw new Error(`Unknown export: ${decl.debugName}`);
}
}
// Finally, produce the `LocalModuleScope` with both the compilation and export scopes.
const scope = {
compilation: {
directives: Array.from(compilationDirectives.values()),
pipes: Array.from(compilationPipes.values()),
},
exported: {
directives: Array.from(exportDirectives.values()),
pipes: Array.from(exportPipes.values()),
},
};
this.cache.set(clazz, scope);
return scope;
}
/**
* Check whether a component requires remote scoping.
*/
getRequiresRemoteScope(node: ts.Declaration): boolean { return this.remoteScoping.has(node); }
/**
* Set a component as requiring remote scoping.
*/
setComponentAsRequiringRemoteScoping(node: ts.Declaration): void { this.remoteScoping.add(node); }
/**
* Look up the `ExportScope` of a given `Reference` to an NgModule.
*
* The NgModule in question may be declared locally in the current ts.Program, or it may be
* declared in a .d.ts file.
*/
private getExportedScope(ref: Reference<ts.Declaration>): ExportScope|null {
if (ref.node.getSourceFile().isDeclarationFile) {
// The NgModule is declared in a .d.ts file. Resolve it with the `DependencyScopeReader`.
if (!ts.isClassDeclaration(ref.node)) {
// TODO(alxhub): produce a ts.Diagnostic
throw new Error(`Reference to an NgModule ${ref.debugName} which isn't a class?`);
}
return this.dependencyScopeReader.resolve(ref as Reference<ts.ClassDeclaration>);
} else {
// The NgModule is declared locally in the current program. Resolve it from the registry.
return this.getScopeOfModule(ref.node);
}
}
private assertCollecting(): void {
if (this.sealed) {
throw new Error(`Assertion: LocalModuleScopeRegistry is not COLLECTING`);
}
}
}

View File

@ -0,0 +1,95 @@
/**
* @license
* Copyright Google Inc. 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 * as ts from 'typescript';
import {Reference} from '../../imports';
import {ClassMemberKind, ReflectionHost, reflectTypeEntityToDeclaration} from '../../reflection';
import {nodeDebugInfo} from '../../util/src/typescript';
export function extractReferencesFromType(
checker: ts.TypeChecker, def: ts.TypeNode, ngModuleImportedFrom: string | null,
resolutionContext: string): Reference<ts.ClassDeclaration>[] {
if (!ts.isTupleTypeNode(def)) {
return [];
}
return def.elementTypes.map(element => {
if (!ts.isTypeQueryNode(element)) {
throw new Error(`Expected TypeQueryNode: ${nodeDebugInfo(element)}`);
}
const type = element.exprName;
const {node, from} = reflectTypeEntityToDeclaration(type, checker);
if (!ts.isClassDeclaration(node)) {
throw new Error(`Expected ClassDeclaration: ${nodeDebugInfo(node)}`);
}
const specifier = (from !== null && !from.startsWith('.') ? from : ngModuleImportedFrom);
if (specifier !== null) {
return new Reference(node, {specifier, resolutionContext});
} else {
return new Reference(node);
}
});
}
export function readStringType(type: ts.TypeNode): string|null {
if (!ts.isLiteralTypeNode(type) || !ts.isStringLiteral(type.literal)) {
return null;
}
return type.literal.text;
}
export function readStringMapType(type: ts.TypeNode): {[key: string]: string} {
if (!ts.isTypeLiteralNode(type)) {
return {};
}
const obj: {[key: string]: string} = {};
type.members.forEach(member => {
if (!ts.isPropertySignature(member) || member.type === undefined || member.name === undefined ||
!ts.isStringLiteral(member.name)) {
return;
}
const value = readStringType(member.type);
if (value === null) {
return null;
}
obj[member.name.text] = value;
});
return obj;
}
export function readStringArrayType(type: ts.TypeNode): string[] {
if (!ts.isTupleTypeNode(type)) {
return [];
}
const res: string[] = [];
type.elementTypes.forEach(el => {
if (!ts.isLiteralTypeNode(el) || !ts.isStringLiteral(el.literal)) {
return;
}
res.push(el.literal.text);
});
return res;
}
export function extractDirectiveGuards(node: ts.Declaration, reflector: ReflectionHost): {
ngTemplateGuards: string[],
hasNgTemplateContextGuard: boolean,
} {
const methods = nodeStaticMethodNames(node, reflector);
const ngTemplateGuards = methods.filter(method => method.startsWith('ngTemplateGuard_'))
.map(method => method.split('_', 2)[1]);
const hasNgTemplateContextGuard = methods.some(name => name === 'ngTemplateContextGuard');
return {hasNgTemplateContextGuard, ngTemplateGuards};
}
function nodeStaticMethodNames(node: ts.Declaration, reflector: ReflectionHost): string[] {
return reflector.getMembersOfClass(node)
.filter(member => member.kind === ClassMemberKind.Method && member.isStatic)
.map(member => member.name);
}

View File

@ -0,0 +1,28 @@
package(default_visibility = ["//visibility:public"])
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library")
ts_library(
name = "test_lib",
testonly = True,
srcs = glob([
"**/*.ts",
]),
deps = [
"//packages:types",
"//packages/compiler-cli/src/ngtsc/imports",
"//packages/compiler-cli/src/ngtsc/reflection",
"//packages/compiler-cli/src/ngtsc/scope",
"//packages/compiler-cli/src/ngtsc/testing",
"@ngdeps//typescript",
],
)
jasmine_node_test(
name = "test",
bootstrap = ["angular/tools/testing/init_node_no_angular_spec.js"],
deps = [
":test_lib",
"//tools/testing:node_no_angular",
],
)

View File

@ -0,0 +1,144 @@
/**
* @license
* Copyright Google Inc. 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 * as ts from 'typescript';
import {Reference} from '../../imports';
import {TypeScriptReflectionHost} from '../../reflection';
import {makeProgram} from '../../testing/in_memory_typescript';
import {ExportScope} from '../src/api';
import {MetadataDtsModuleScopeResolver} from '../src/dependency';
const MODULE_FROM_NODE_MODULES_PATH = /.*node_modules\/(\w+)\/index\.d\.ts$/;
/**
* Simple metadata types are added to the top of each testing file, for convenience.
*/
const PROLOG = `
export declare type ModuleMeta<A, B, C, D> = never;
export declare type ComponentMeta<A, B, C, D, E, F> = never;
export declare type DirectiveMeta<A, B, C, D, E, F> = never;
export declare type PipeMeta<A, B> = never;
`;
/**
* Construct the testing environment with a given set of absolute modules and their contents.
*
* This returns both the `MetadataDtsModuleScopeResolver` and a `refs` object which can be
* destructured to retrieve references to specific declared classes.
*/
function makeTestEnv(modules: {[module: string]: string}): {
refs: {[name: string]: Reference<ts.ClassDeclaration>},
resolver: MetadataDtsModuleScopeResolver,
} {
// Map the modules object to an array of files for `makeProgram`.
const files = Object.keys(modules).map(moduleName => {
return {
name: `node_modules/${moduleName}/index.d.ts`,
contents: PROLOG + (modules as any)[moduleName],
};
});
const {program} = makeProgram(files);
const checker = program.getTypeChecker();
const resolver =
new MetadataDtsModuleScopeResolver(checker, new TypeScriptReflectionHost(checker));
// Resolver for the refs object.
const get = (target: {}, name: string): Reference<ts.ClassDeclaration> => {
for (const sf of program.getSourceFiles()) {
const symbol = checker.getSymbolAtLocation(sf) !;
const exportedSymbol = symbol.exports !.get(name as ts.__String);
if (exportedSymbol !== undefined) {
const decl = exportedSymbol.valueDeclaration as ts.ClassDeclaration;
const specifier = MODULE_FROM_NODE_MODULES_PATH.exec(sf.fileName) ![1];
return new Reference(decl, {specifier, resolutionContext: sf.fileName});
}
}
throw new Error('Class not found: ' + name);
};
return {
resolver,
refs: new Proxy({}, {get}),
};
}
describe('MetadataDtsModuleScopeResolver', () => {
it('should produce an accurate scope for a basic NgModule', () => {
const {resolver, refs} = makeTestEnv({
'test': `
export declare class Dir {
static ngDirectiveDef: DirectiveMeta<Dir, '[dir]', ['exportAs'], {'input': 'input2'},
{'output': 'output2'}, ['query']>;
}
export declare class Module {
static ngModuleDef: ModuleMeta<Module, [typeof Dir], never, [typeof Dir]>;
}
`
});
const {Dir, Module} = refs;
const scope = resolver.resolve(Module) !;
expect(scopeToRefs(scope)).toEqual([Dir]);
});
it('should produce an accurate scope when a module is exported', () => {
const {resolver, refs} = makeTestEnv({
'test': `
export declare class Dir {
static ngDirectiveDef: DirectiveMeta<Dir, '[dir]', never, never, never, never>;
}
export declare class ModuleA {
static ngModuleDef: ModuleMeta<ModuleA, [typeof Dir], never, [typeof Dir]>;
}
export declare class ModuleB {
static ngModuleDef: ModuleMeta<ModuleB, never, never, [typeof ModuleA]>;
}
`
});
const {Dir, ModuleB} = refs;
const scope = resolver.resolve(ModuleB) !;
expect(scopeToRefs(scope)).toEqual([Dir]);
});
it('should resolve correctly across modules', () => {
const {resolver, refs} = makeTestEnv({
'declaration': `
export declare class Dir {
static ngDirectiveDef: DirectiveMeta<Dir, '[dir]', never, never, never, never>;
}
export declare class ModuleA {
static ngModuleDef: ModuleMeta<ModuleA, [typeof Dir], never, [typeof Dir]>;
}
`,
'exported': `
import * as d from 'declaration';
export declare class ModuleB {
static ngModuleDef: ModuleMeta<ModuleB, never, never, [typeof d.ModuleA]>;
}
`
});
const {Dir, ModuleB} = refs;
const scope = resolver.resolve(ModuleB) !;
expect(scopeToRefs(scope)).toEqual([Dir]);
// Explicitly verify that the directive has the correct owning module.
expect(scope.exported.directives[0].ref.ownedByModuleGuess).toBe('declaration');
});
});
function scopeToRefs(scope: ExportScope): Reference<ts.Declaration>[] {
const directives = scope.exported.directives.map(dir => dir.ref);
const pipes = scope.exported.pipes.map(pipe => pipe.ref);
return [...directives, ...pipes].sort((a, b) => a.debugName !.localeCompare(b.debugName !));
}

View File

@ -0,0 +1,159 @@
/**
* @license
* Copyright Google Inc. 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 * as ts from 'typescript';
import {Reference} from '../../imports';
import {ScopeData, ScopeDirective, ScopePipe} from '../src/api';
import {DtsModuleScopeResolver} from '../src/dependency';
import {LocalModuleScopeRegistry} from '../src/local';
function registerFakeRefs(registry: LocalModuleScopeRegistry):
{[name: string]: Reference<ts.ClassDeclaration>} {
const get = (target: {}, name: string): Reference<ts.ClassDeclaration> => {
const sf = ts.createSourceFile(
name + '.ts', `export class ${name} {}`, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
const clazz = sf.statements[0] as ts.ClassDeclaration;
const ref = new Reference(clazz);
if (name.startsWith('Dir') || name.startsWith('Cmp')) {
registry.registerDirective(fakeDirective(ref));
} else if (name.startsWith('Pipe')) {
registry.registerPipe(fakePipe(ref));
}
return ref;
};
return new Proxy({}, {get});
}
describe('LocalModuleScopeRegistry', () => {
let registry !: LocalModuleScopeRegistry;
beforeEach(() => { registry = new LocalModuleScopeRegistry(new MockDtsModuleScopeResolver()); });
it('should produce an accurate LocalModuleScope for a basic NgModule', () => {
const {Dir1, Dir2, Pipe1, Module} = registerFakeRefs(registry);
registry.registerNgModule(Module.node, {
imports: [],
declarations: [Dir1, Dir2, Pipe1],
exports: [Dir1, Pipe1],
});
const scope = registry.getScopeOfModule(Module.node) !;
expect(scopeToRefs(scope.compilation)).toEqual([Dir1, Dir2, Pipe1]);
expect(scopeToRefs(scope.exported)).toEqual([Dir1, Pipe1]);
});
it('should produce accurate LocalModuleScopes for a complex module chain', () => {
const {DirA, DirB, DirCI, DirCE, ModuleA, ModuleB, ModuleC} = registerFakeRefs(registry);
registry.registerNgModule(
ModuleA.node, {imports: [ModuleB], declarations: [DirA], exports: []});
registry.registerNgModule(
ModuleB.node, {exports: [ModuleC, DirB], declarations: [DirB], imports: []});
registry.registerNgModule(
ModuleC.node, {declarations: [DirCI, DirCE], exports: [DirCE], imports: []});
const scopeA = registry.getScopeOfModule(ModuleA.node) !;
expect(scopeToRefs(scopeA.compilation)).toEqual([DirA, DirB, DirCE]);
expect(scopeToRefs(scopeA.exported)).toEqual([]);
});
it('should not treat exported modules as imported', () => {
const {Dir, ModuleA, ModuleB} = registerFakeRefs(registry);
registry.registerNgModule(ModuleA.node, {exports: [ModuleB], imports: [], declarations: []});
registry.registerNgModule(ModuleB.node, {declarations: [Dir], exports: [Dir], imports: []});
const scopeA = registry.getScopeOfModule(ModuleA.node) !;
expect(scopeToRefs(scopeA.compilation)).toEqual([]);
expect(scopeToRefs(scopeA.exported)).toEqual([Dir]);
});
it('should deduplicate declarations and exports', () => {
const {DirA, ModuleA, DirB, ModuleB, ModuleC} = registerFakeRefs(registry);
registry.registerNgModule(ModuleA.node, {
declarations: [DirA, DirA],
imports: [ModuleB, ModuleC],
exports: [DirA, DirA, DirB, ModuleB],
});
registry.registerNgModule(ModuleB.node, {declarations: [DirB], imports: [], exports: [DirB]});
registry.registerNgModule(ModuleC.node, {declarations: [], imports: [], exports: [ModuleB]});
const scope = registry.getScopeOfModule(ModuleA.node) !;
expect(scopeToRefs(scope.compilation)).toEqual([DirA, DirB]);
expect(scopeToRefs(scope.exported)).toEqual([DirA, DirB]);
});
it('should preserve reference identities in module metadata', () => {
const {Dir, Module} = registerFakeRefs(registry);
const idSf = ts.createSourceFile('id.ts', 'var id;', ts.ScriptTarget.Latest, true);
// Create a new Reference to Dir, with a special `ts.Identifier`, and register the directive
// using it. This emulates what happens when an NgModule declares a Directive.
const idVar = idSf.statements[0] as ts.VariableStatement;
const id = idVar.declarationList.declarations[0].name as ts.Identifier;
const DirInModule = new Reference(Dir.node);
DirInModule.addIdentifier(id);
registry.registerNgModule(Module.node, {exports: [], imports: [], declarations: [DirInModule]});
const scope = registry.getScopeOfModule(Module.node) !;
expect(scope.compilation.directives[0].ref.getIdentityIn(idSf)).toBe(id);
});
it('should allow directly exporting a directive that\'s not imported', () => {
const {Dir, ModuleA, ModuleB} = registerFakeRefs(registry);
registry.registerNgModule(ModuleA.node, {exports: [Dir], imports: [ModuleB], declarations: []});
registry.registerNgModule(ModuleB.node, {declarations: [Dir], exports: [Dir], imports: []});
const scopeA = registry.getScopeOfModule(ModuleA.node) !;
expect(scopeToRefs(scopeA.exported)).toEqual([Dir]);
});
it('should not allow directly exporting a directive that\'s not imported', () => {
const {Dir, ModuleA, ModuleB} = registerFakeRefs(registry);
registry.registerNgModule(ModuleA.node, {exports: [Dir], imports: [], declarations: []});
registry.registerNgModule(ModuleB.node, {declarations: [Dir], exports: [Dir], imports: []});
expect(() => registry.getScopeOfModule(ModuleA.node)).toThrow();
});
});
function fakeDirective(ref: Reference<ts.ClassDeclaration>): ScopeDirective {
const name = ref.debugName !;
return {
ref,
name,
selector: `[${ref.debugName}]`,
isComponent: name.startsWith('Cmp'),
inputs: {},
outputs: {},
exportAs: null,
queries: [],
hasNgTemplateContextGuard: false,
ngTemplateGuards: [],
};
}
function fakePipe(ref: Reference<ts.ClassDeclaration>): ScopePipe {
const name = ref.debugName !;
return {ref, name};
}
class MockDtsModuleScopeResolver implements DtsModuleScopeResolver {
resolve(ref: Reference<ts.ClassDeclaration>): null { return null; }
}
function scopeToRefs(scopeData: ScopeData): Reference<ts.Declaration>[] {
const directives = scopeData.directives.map(dir => dir.ref);
const pipes = scopeData.pipes.map(pipe => pipe.ref);
return [...directives, ...pipes].sort((a, b) => a.debugName !.localeCompare(b.debugName !));
}