-
Notifications
You must be signed in to change notification settings - Fork 24.8k
/
handler.ts
288 lines (260 loc) · 13 KB
/
handler.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
/**
* @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 {compileClassMetadata, compileDeclareClassMetadata, compileDeclareDirectiveFromMetadata, compileDirectiveFromMetadata, ConstantPool, FactoryTarget, makeBindingParser, R3ClassMetadata, R3DirectiveMetadata, WrappedNodeExpr} from '@angular/compiler';
import ts from 'typescript';
import {ImportedSymbolsTracker, Reference, ReferenceEmitter} from '../../../imports';
import {extractSemanticTypeParameters, SemanticDepGraphUpdater} from '../../../incremental/semantic_graph';
import {ClassPropertyMapping, DirectiveTypeCheckMeta, extractDirectiveTypeCheckMeta, HostDirectiveMeta, InputMapping, MatchSource, MetadataReader, MetadataRegistry, MetaKind} from '../../../metadata';
import {PartialEvaluator} from '../../../partial_evaluator';
import {PerfEvent, PerfRecorder} from '../../../perf';
import {ClassDeclaration, ClassMember, ClassMemberKind, Decorator, ReflectionHost} from '../../../reflection';
import {LocalModuleScopeRegistry} from '../../../scope';
import {AnalysisOutput, CompilationMode, CompileResult, DecoratorHandler, DetectResult, HandlerPrecedence, ResolveResult} from '../../../transform';
import {compileDeclareFactory, compileInputTransformFields, compileNgFactoryDefField, compileResults, extractClassMetadata, findAngularDecorator, getDirectiveDiagnostics, getProviderDiagnostics, getUndecoratedClassWithAngularFeaturesDiagnostic, InjectableClassRegistry, isAngularDecorator, readBaseClass, ReferencesRegistry, resolveProvidersRequiringFactory, toFactoryMetadata, validateHostDirectives} from '../../common';
import {extractDirectiveMetadata} from './shared';
import {DirectiveSymbol} from './symbol';
const FIELD_DECORATORS = [
'Input', 'Output', 'ViewChild', 'ViewChildren', 'ContentChild', 'ContentChildren', 'HostBinding',
'HostListener'
];
const LIFECYCLE_HOOKS = new Set([
'ngOnChanges', 'ngOnInit', 'ngOnDestroy', 'ngDoCheck', 'ngAfterViewInit', 'ngAfterViewChecked',
'ngAfterContentInit', 'ngAfterContentChecked'
]);
export interface DirectiveHandlerData {
baseClass: Reference<ClassDeclaration>|'dynamic'|null;
typeCheckMeta: DirectiveTypeCheckMeta;
meta: R3DirectiveMetadata;
classMetadata: R3ClassMetadata|null;
providersRequiringFactory: Set<Reference<ClassDeclaration>>|null;
inputs: ClassPropertyMapping<InputMapping>;
outputs: ClassPropertyMapping;
isPoisoned: boolean;
isStructural: boolean;
decorator: ts.Decorator|null;
hostDirectives: HostDirectiveMeta[]|null;
rawHostDirectives: ts.Expression|null;
}
export class DirectiveDecoratorHandler implements
DecoratorHandler<Decorator|null, DirectiveHandlerData, DirectiveSymbol, unknown> {
constructor(
private reflector: ReflectionHost,
private evaluator: PartialEvaluator,
private metaRegistry: MetadataRegistry,
private scopeRegistry: LocalModuleScopeRegistry,
private metaReader: MetadataReader,
private injectableRegistry: InjectableClassRegistry,
private refEmitter: ReferenceEmitter,
private referencesRegistry: ReferencesRegistry,
private isCore: boolean,
private strictCtorDeps: boolean,
private semanticDepGraphUpdater: SemanticDepGraphUpdater|null,
private annotateForClosureCompiler: boolean,
private perf: PerfRecorder,
private importTracker: ImportedSymbolsTracker,
private includeClassMetadata: boolean,
private readonly compilationMode: CompilationMode,
private readonly useTemplatePipeline: boolean,
private readonly generateExtraImportsInLocalMode: boolean,
) {}
readonly precedence = HandlerPrecedence.PRIMARY;
readonly name = 'DirectiveDecoratorHandler';
detect(node: ClassDeclaration, decorators: Decorator[]|null):
DetectResult<Decorator|null>|undefined {
// If a class is undecorated but uses Angular features, we detect it as an
// abstract directive. This is an unsupported pattern as of v10, but we want
// to still detect these patterns so that we can report diagnostics.
if (!decorators) {
const angularField = this.findClassFieldWithAngularFeatures(node);
return angularField ? {trigger: angularField.node, decorator: null, metadata: null} :
undefined;
} else {
const decorator = findAngularDecorator(decorators, 'Directive', this.isCore);
return decorator ? {trigger: decorator.node, decorator, metadata: decorator} : undefined;
}
}
analyze(node: ClassDeclaration, decorator: Readonly<Decorator|null>):
AnalysisOutput<DirectiveHandlerData> {
// Skip processing of the class declaration if compilation of undecorated classes
// with Angular features is disabled. Previously in ngtsc, such classes have always
// been processed, but we want to enforce a consistent decorator mental model.
// See: https://v9.angular.io/guide/migration-undecorated-classes.
if (decorator === null) {
// If compiling @angular/core, skip the diagnostic as core occasionally hand-writes
// definitions.
if (this.isCore) {
return {};
}
return {diagnostics: [getUndecoratedClassWithAngularFeaturesDiagnostic(node)]};
}
this.perf.eventCount(PerfEvent.AnalyzeDirective);
const directiveResult = extractDirectiveMetadata(
node, decorator, this.reflector, this.importTracker, this.evaluator, this.refEmitter,
this.referencesRegistry, this.isCore, this.annotateForClosureCompiler, this.compilationMode,
/* defaultSelector */ null, this.useTemplatePipeline);
if (directiveResult === undefined) {
return {};
}
const analysis = directiveResult.metadata;
let providersRequiringFactory: Set<Reference<ClassDeclaration>>|null = null;
if (directiveResult !== undefined && directiveResult.decorator.has('providers')) {
providersRequiringFactory = resolveProvidersRequiringFactory(
directiveResult.decorator.get('providers')!, this.reflector, this.evaluator);
}
return {
analysis: {
inputs: directiveResult.inputs,
outputs: directiveResult.outputs,
meta: analysis,
hostDirectives: directiveResult.hostDirectives,
rawHostDirectives: directiveResult.rawHostDirectives,
classMetadata: this.includeClassMetadata ?
extractClassMetadata(
node, this.reflector, this.isCore, this.annotateForClosureCompiler) :
null,
baseClass: readBaseClass(node, this.reflector, this.evaluator),
typeCheckMeta: extractDirectiveTypeCheckMeta(node, directiveResult.inputs, this.reflector),
providersRequiringFactory,
isPoisoned: false,
isStructural: directiveResult.isStructural,
decorator: decorator?.node as ts.Decorator | null ?? null,
}
};
}
symbol(node: ClassDeclaration, analysis: Readonly<DirectiveHandlerData>): DirectiveSymbol {
const typeParameters = extractSemanticTypeParameters(node);
return new DirectiveSymbol(
node, analysis.meta.selector, analysis.inputs, analysis.outputs, analysis.meta.exportAs,
analysis.typeCheckMeta, typeParameters);
}
register(node: ClassDeclaration, analysis: Readonly<DirectiveHandlerData>): void {
// Register this directive's information with the `MetadataRegistry`. This ensures that
// the information about the directive is available during the compile() phase.
const ref = new Reference(node);
this.metaRegistry.registerDirectiveMetadata({
kind: MetaKind.Directive,
matchSource: MatchSource.Selector,
ref,
name: node.name.text,
selector: analysis.meta.selector,
exportAs: analysis.meta.exportAs,
inputs: analysis.inputs,
outputs: analysis.outputs,
queries: analysis.meta.queries.map(query => query.propertyName),
isComponent: false,
baseClass: analysis.baseClass,
hostDirectives: analysis.hostDirectives,
...analysis.typeCheckMeta,
isPoisoned: analysis.isPoisoned,
isStructural: analysis.isStructural,
animationTriggerNames: null,
isStandalone: analysis.meta.isStandalone,
isSignal: analysis.meta.isSignal,
imports: null,
deferredImports: null,
schemas: null,
ngContentSelectors: null,
decorator: analysis.decorator,
preserveWhitespaces: false,
// Directives analyzed within our own compilation are not _assumed_ to export providers.
// Instead, we statically analyze their imports to make a direct determination.
assumedToExportProviders: false,
isExplicitlyDeferred: false,
});
this.injectableRegistry.registerInjectable(node, {
ctorDeps: analysis.meta.deps,
});
}
resolve(node: ClassDeclaration, analysis: DirectiveHandlerData, symbol: DirectiveSymbol):
ResolveResult<unknown> {
if (this.compilationMode === CompilationMode.LOCAL) {
return {};
}
if (this.semanticDepGraphUpdater !== null && analysis.baseClass instanceof Reference) {
symbol.baseClass = this.semanticDepGraphUpdater.getSymbol(analysis.baseClass.node);
}
const diagnostics: ts.Diagnostic[] = [];
if (analysis.providersRequiringFactory !== null &&
analysis.meta.providers instanceof WrappedNodeExpr) {
const providerDiagnostics = getProviderDiagnostics(
analysis.providersRequiringFactory, analysis.meta.providers!.node,
this.injectableRegistry);
diagnostics.push(...providerDiagnostics);
}
const directiveDiagnostics = getDirectiveDiagnostics(
node, this.injectableRegistry, this.evaluator, this.reflector, this.scopeRegistry,
this.strictCtorDeps, 'Directive');
if (directiveDiagnostics !== null) {
diagnostics.push(...directiveDiagnostics);
}
const hostDirectivesDiagnotics = analysis.hostDirectives && analysis.rawHostDirectives ?
validateHostDirectives(
analysis.rawHostDirectives, analysis.hostDirectives, this.metaReader) :
null;
if (hostDirectivesDiagnotics !== null) {
diagnostics.push(...hostDirectivesDiagnotics);
}
return {diagnostics: diagnostics.length > 0 ? diagnostics : undefined};
}
compileFull(
node: ClassDeclaration, analysis: Readonly<DirectiveHandlerData>,
resolution: Readonly<unknown>, pool: ConstantPool): CompileResult[] {
const fac = compileNgFactoryDefField(toFactoryMetadata(analysis.meta, FactoryTarget.Directive));
const def = compileDirectiveFromMetadata(analysis.meta, pool, makeBindingParser());
const inputTransformFields = compileInputTransformFields(analysis.inputs);
const classMetadata = analysis.classMetadata !== null ?
compileClassMetadata(analysis.classMetadata).toStmt() :
null;
return compileResults(
fac, def, classMetadata, 'ɵdir', inputTransformFields, null /* deferrableImports */);
}
compilePartial(
node: ClassDeclaration, analysis: Readonly<DirectiveHandlerData>,
resolution: Readonly<unknown>): CompileResult[] {
const fac = compileDeclareFactory(toFactoryMetadata(analysis.meta, FactoryTarget.Directive));
const def = compileDeclareDirectiveFromMetadata(analysis.meta);
const inputTransformFields = compileInputTransformFields(analysis.inputs);
const classMetadata = analysis.classMetadata !== null ?
compileDeclareClassMetadata(analysis.classMetadata).toStmt() :
null;
return compileResults(
fac, def, classMetadata, 'ɵdir', inputTransformFields, null /* deferrableImports */);
}
compileLocal(
node: ClassDeclaration, analysis: Readonly<DirectiveHandlerData>,
resolution: Readonly<unknown>, pool: ConstantPool): CompileResult[] {
const fac = compileNgFactoryDefField(toFactoryMetadata(analysis.meta, FactoryTarget.Directive));
const def = compileDirectiveFromMetadata(analysis.meta, pool, makeBindingParser());
const inputTransformFields = compileInputTransformFields(analysis.inputs);
const classMetadata = analysis.classMetadata !== null ?
compileClassMetadata(analysis.classMetadata).toStmt() :
null;
return compileResults(
fac, def, classMetadata, 'ɵdir', inputTransformFields, null /* deferrableImports */);
}
/**
* Checks if a given class uses Angular features and returns the TypeScript node
* that indicated the usage. Classes are considered using Angular features if they
* contain class members that are either decorated with a known Angular decorator,
* or if they correspond to a known Angular lifecycle hook.
*/
private findClassFieldWithAngularFeatures(node: ClassDeclaration): ClassMember|undefined {
return this.reflector.getMembersOfClass(node).find(member => {
if (!member.isStatic && member.kind === ClassMemberKind.Method &&
LIFECYCLE_HOOKS.has(member.name)) {
return true;
}
if (member.decorators) {
return member.decorators.some(
decorator => FIELD_DECORATORS.some(
decoratorName => isAngularDecorator(decorator, decoratorName, this.isCore)));
}
return false;
});
}
}