/
component.ts
1489 lines (1332 loc) · 61.9 KB
/
component.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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @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, compileComponentFromMetadata, compileDeclareClassMetadata, compileDeclareComponentFromMetadata, ConstantPool, CssSelector, DeclarationListEmitMode, DeclareComponentTemplateInfo, DEFAULT_INTERPOLATION_CONFIG, DomElementSchemaRegistry, Expression, ExternalExpr, FactoryTarget, InterpolationConfig, LexerRange, makeBindingParser, ParsedTemplate, ParseSourceFile, parseTemplate, R3ClassMetadata, R3ComponentMetadata, R3TargetBinder, R3UsedDirectiveMetadata, SelectorMatcher, Statement, TmplAstNode, WrappedNodeExpr} from '@angular/compiler';
import {ViewEncapsulation} from '@angular/compiler/src/core';
import * as ts from 'typescript';
import {Cycle, CycleAnalyzer, CycleHandlingStrategy} from '../../cycles';
import {ErrorCode, FatalDiagnosticError, makeDiagnostic, makeRelatedInformation} from '../../diagnostics';
import {absoluteFrom, relative} from '../../file_system';
import {ImportedFile, ModuleResolver, Reference, ReferenceEmitter} from '../../imports';
import {DependencyTracker} from '../../incremental/api';
import {extractSemanticTypeParameters, isArrayEqual, isReferenceEqual, SemanticDepGraphUpdater, SemanticReference, SemanticSymbol} from '../../incremental/semantic_graph';
import {IndexingContext} from '../../indexer';
import {ClassPropertyMapping, ComponentResources, DirectiveMeta, DirectiveTypeCheckMeta, extractDirectiveTypeCheckMeta, InjectableClassRegistry, MetadataReader, MetadataRegistry, MetaType, Resource, ResourceRegistry} from '../../metadata';
import {EnumValue, PartialEvaluator, ResolvedValue} from '../../partial_evaluator';
import {PerfEvent, PerfRecorder} from '../../perf';
import {ClassDeclaration, DeclarationNode, Decorator, ReflectionHost, reflectObjectLiteral} from '../../reflection';
import {ComponentScopeReader, LocalModuleScopeRegistry, TypeCheckScopeRegistry} from '../../scope';
import {AnalysisOutput, CompileResult, DecoratorHandler, DetectResult, HandlerFlags, HandlerPrecedence, ResolveResult} from '../../transform';
import {TemplateSourceMapping, TypeCheckContext} from '../../typecheck/api';
import {ExtendedTemplateChecker} from '../../typecheck/extended/api';
import {SubsetOfKeys} from '../../util/src/typescript';
import {Xi18nContext} from '../../xi18n';
import {ResourceLoader} from './api';
import {createValueHasWrongTypeError, getDirectiveDiagnostics, getProviderDiagnostics} from './diagnostics';
import {DirectiveSymbol, extractDirectiveMetadata, parseFieldArrayValue} from './directive';
import {compileDeclareFactory, compileNgFactoryDefField} from './factory';
import {extractClassMetadata} from './metadata';
import {NgModuleSymbol} from './ng_module';
import {compileResults, findAngularDecorator, isAngularCoreReference, isExpressionForwardReference, readBaseClass, resolveProvidersRequiringFactory, toFactoryMetadata, unwrapExpression, wrapFunctionExpressionsInParens} from './util';
const EMPTY_MAP = new Map<string, Expression>();
const EMPTY_ARRAY: any[] = [];
/**
* These fields of `R3ComponentMetadata` are updated in the `resolve` phase.
*
* The `keyof R3ComponentMetadata &` condition ensures that only fields of `R3ComponentMetadata` can
* be included here.
*/
export type ComponentMetadataResolvedFields =
SubsetOfKeys<R3ComponentMetadata, 'directives'|'pipes'|'declarationListEmitMode'>;
export interface ComponentAnalysisData {
/**
* `meta` includes those fields of `R3ComponentMetadata` which are calculated at `analyze` time
* (not during resolve).
*/
meta: Omit<R3ComponentMetadata, ComponentMetadataResolvedFields>;
baseClass: Reference<ClassDeclaration>|'dynamic'|null;
typeCheckMeta: DirectiveTypeCheckMeta;
template: ParsedTemplateWithSource;
classMetadata: R3ClassMetadata|null;
inputs: ClassPropertyMapping;
outputs: ClassPropertyMapping;
/**
* Providers extracted from the `providers` field of the component annotation which will require
* an Angular factory definition at runtime.
*/
providersRequiringFactory: Set<Reference<ClassDeclaration>>|null;
/**
* Providers extracted from the `viewProviders` field of the component annotation which will
* require an Angular factory definition at runtime.
*/
viewProvidersRequiringFactory: Set<Reference<ClassDeclaration>>|null;
resources: ComponentResources;
/**
* `styleUrls` extracted from the decorator, if present.
*/
styleUrls: StyleUrlMeta[]|null;
/**
* Inline stylesheets extracted from the decorator, if present.
*/
inlineStyles: string[]|null;
isPoisoned: boolean;
}
export type ComponentResolutionData = Pick<R3ComponentMetadata, ComponentMetadataResolvedFields>;
/**
* The literal style url extracted from the decorator, along with metadata for diagnostics.
*/
export interface StyleUrlMeta {
url: string;
nodeForError: ts.Node;
source: ResourceTypeForDiagnostics.StylesheetFromTemplate|
ResourceTypeForDiagnostics.StylesheetFromDecorator;
}
/**
* Information about the origin of a resource in the application code. This is used for creating
* diagnostics, so we can point to the root cause of an error in the application code.
*
* A template resource comes from the `templateUrl` property on the component decorator.
*
* Stylesheets resources can come from either the `styleUrls` property on the component decorator,
* or from inline `style` tags and style links on the external template.
*/
export const enum ResourceTypeForDiagnostics {
Template,
StylesheetFromTemplate,
StylesheetFromDecorator,
}
/**
* Represents an Angular component.
*/
export class ComponentSymbol extends DirectiveSymbol {
usedDirectives: SemanticReference[] = [];
usedPipes: SemanticReference[] = [];
isRemotelyScoped = false;
override isEmitAffected(previousSymbol: SemanticSymbol, publicApiAffected: Set<SemanticSymbol>):
boolean {
if (!(previousSymbol instanceof ComponentSymbol)) {
return true;
}
// Create an equality function that considers symbols equal if they represent the same
// declaration, but only if the symbol in the current compilation does not have its public API
// affected.
const isSymbolUnaffected = (current: SemanticReference, previous: SemanticReference) =>
isReferenceEqual(current, previous) && !publicApiAffected.has(current.symbol);
// The emit of a component is affected if either of the following is true:
// 1. The component used to be remotely scoped but no longer is, or vice versa.
// 2. The list of used directives has changed or any of those directives have had their public
// API changed. If the used directives have been reordered but not otherwise affected then
// the component must still be re-emitted, as this may affect directive instantiation order.
// 3. The list of used pipes has changed, or any of those pipes have had their public API
// changed.
return this.isRemotelyScoped !== previousSymbol.isRemotelyScoped ||
!isArrayEqual(this.usedDirectives, previousSymbol.usedDirectives, isSymbolUnaffected) ||
!isArrayEqual(this.usedPipes, previousSymbol.usedPipes, isSymbolUnaffected);
}
override isTypeCheckBlockAffected(
previousSymbol: SemanticSymbol, typeCheckApiAffected: Set<SemanticSymbol>): boolean {
if (!(previousSymbol instanceof ComponentSymbol)) {
return true;
}
// To verify that a used directive is not affected we need to verify that its full inheritance
// chain is not present in `typeCheckApiAffected`.
const isInheritanceChainAffected = (symbol: SemanticSymbol): boolean => {
let currentSymbol: SemanticSymbol|null = symbol;
while (currentSymbol instanceof DirectiveSymbol) {
if (typeCheckApiAffected.has(currentSymbol)) {
return true;
}
currentSymbol = currentSymbol.baseClass;
}
return false;
};
// Create an equality function that considers directives equal if they represent the same
// declaration and if the symbol and all symbols it inherits from in the current compilation
// do not have their type-check API affected.
const isDirectiveUnaffected = (current: SemanticReference, previous: SemanticReference) =>
isReferenceEqual(current, previous) && !isInheritanceChainAffected(current.symbol);
// Create an equality function that considers pipes equal if they represent the same
// declaration and if the symbol in the current compilation does not have its type-check
// API affected.
const isPipeUnaffected = (current: SemanticReference, previous: SemanticReference) =>
isReferenceEqual(current, previous) && !typeCheckApiAffected.has(current.symbol);
// The emit of a type-check block of a component is affected if either of the following is true:
// 1. The list of used directives has changed or any of those directives have had their
// type-check API changed.
// 2. The list of used pipes has changed, or any of those pipes have had their type-check API
// changed.
return !isArrayEqual(
this.usedDirectives, previousSymbol.usedDirectives, isDirectiveUnaffected) ||
!isArrayEqual(this.usedPipes, previousSymbol.usedPipes, isPipeUnaffected);
}
}
/**
* `DecoratorHandler` which handles the `@Component` annotation.
*/
export class ComponentDecoratorHandler implements
DecoratorHandler<Decorator, ComponentAnalysisData, ComponentSymbol, ComponentResolutionData> {
constructor(
private reflector: ReflectionHost, private evaluator: PartialEvaluator,
private metaRegistry: MetadataRegistry, private metaReader: MetadataReader,
private scopeReader: ComponentScopeReader, private scopeRegistry: LocalModuleScopeRegistry,
private typeCheckScopeRegistry: TypeCheckScopeRegistry,
private resourceRegistry: ResourceRegistry, private isCore: boolean,
private resourceLoader: ResourceLoader, private rootDirs: ReadonlyArray<string>,
private defaultPreserveWhitespaces: boolean, private i18nUseExternalIds: boolean,
private enableI18nLegacyMessageIdFormat: boolean, private usePoisonedData: boolean,
private i18nNormalizeLineEndingsInICUs: boolean|undefined,
private moduleResolver: ModuleResolver, private cycleAnalyzer: CycleAnalyzer,
private cycleHandlingStrategy: CycleHandlingStrategy, private refEmitter: ReferenceEmitter,
private depTracker: DependencyTracker|null,
private injectableRegistry: InjectableClassRegistry,
private semanticDepGraphUpdater: SemanticDepGraphUpdater|null,
private annotateForClosureCompiler: boolean, private perf: PerfRecorder) {}
private literalCache = new Map<Decorator, ts.ObjectLiteralExpression>();
private elementSchemaRegistry = new DomElementSchemaRegistry();
/**
* During the asynchronous preanalyze phase, it's necessary to parse the template to extract
* any potential <link> tags which might need to be loaded. This cache ensures that work is not
* thrown away, and the parsed template is reused during the analyze phase.
*/
private preanalyzeTemplateCache = new Map<DeclarationNode, ParsedTemplateWithSource>();
private preanalyzeStylesCache = new Map<DeclarationNode, string[]|null>();
readonly precedence = HandlerPrecedence.PRIMARY;
readonly name = ComponentDecoratorHandler.name;
detect(node: ClassDeclaration, decorators: Decorator[]|null): DetectResult<Decorator>|undefined {
if (!decorators) {
return undefined;
}
const decorator = findAngularDecorator(decorators, 'Component', this.isCore);
if (decorator !== undefined) {
return {
trigger: decorator.node,
decorator,
metadata: decorator,
};
} else {
return undefined;
}
}
preanalyze(node: ClassDeclaration, decorator: Readonly<Decorator>): Promise<void>|undefined {
// In preanalyze, resource URLs associated with the component are asynchronously preloaded via
// the resourceLoader. This is the only time async operations are allowed for a component.
// These resources are:
//
// - the templateUrl, if there is one
// - any styleUrls if present
// - any stylesheets referenced from <link> tags in the template itself
//
// As a result of the last one, the template must be parsed as part of preanalysis to extract
// <link> tags, which may involve waiting for the templateUrl to be resolved first.
// If preloading isn't possible, then skip this step.
if (!this.resourceLoader.canPreload) {
return undefined;
}
const meta = this._resolveLiteral(decorator);
const component = reflectObjectLiteral(meta);
const containingFile = node.getSourceFile().fileName;
const resolveStyleUrl = (styleUrl: string): Promise<void>|undefined => {
try {
const resourceUrl = this.resourceLoader.resolve(styleUrl, containingFile);
return this.resourceLoader.preload(resourceUrl, {type: 'style', containingFile});
} catch {
// Don't worry about failures to preload. We can handle this problem during analysis by
// producing a diagnostic.
return undefined;
}
};
// A Promise that waits for the template and all <link>ed styles within it to be preloaded.
const templateAndTemplateStyleResources =
this._preloadAndParseTemplate(node, decorator, component, containingFile)
.then((template: ParsedTemplateWithSource|null): Promise<void>|undefined => {
if (template === null) {
return undefined;
}
return Promise.all(template.styleUrls.map(styleUrl => resolveStyleUrl(styleUrl)))
.then(() => undefined);
});
// Extract all the styleUrls in the decorator.
const componentStyleUrls = this._extractComponentStyleUrls(component);
// Extract inline styles, process, and cache for use in synchronous analyze phase
let inlineStyles;
if (component.has('styles')) {
const litStyles = parseFieldArrayValue(component, 'styles', this.evaluator);
if (litStyles === null) {
this.preanalyzeStylesCache.set(node, null);
} else {
inlineStyles = Promise
.all(litStyles.map(
style => this.resourceLoader.preprocessInline(
style, {type: 'style', containingFile})))
.then(styles => {
this.preanalyzeStylesCache.set(node, styles);
});
}
} else {
this.preanalyzeStylesCache.set(node, null);
}
// Wait for both the template and all styleUrl resources to resolve.
return Promise
.all([
templateAndTemplateStyleResources, inlineStyles,
...componentStyleUrls.map(styleUrl => resolveStyleUrl(styleUrl.url))
])
.then(() => undefined);
}
analyze(
node: ClassDeclaration, decorator: Readonly<Decorator>,
flags: HandlerFlags = HandlerFlags.NONE): AnalysisOutput<ComponentAnalysisData> {
this.perf.eventCount(PerfEvent.AnalyzeComponent);
const containingFile = node.getSourceFile().fileName;
this.literalCache.delete(decorator);
let diagnostics: ts.Diagnostic[]|undefined;
let isPoisoned = false;
// @Component inherits @Directive, so begin by extracting the @Directive metadata and building
// on it.
const directiveResult = extractDirectiveMetadata(
node, decorator, this.reflector, this.evaluator, this.isCore, flags,
this.annotateForClosureCompiler,
this.elementSchemaRegistry.getDefaultComponentElementName());
if (directiveResult === undefined) {
// `extractDirectiveMetadata` returns undefined when the @Directive has `jit: true`. In this
// case, compilation of the decorator is skipped. Returning an empty object signifies
// that no analysis was produced.
return {};
}
// Next, read the `@Component`-specific fields.
const {decorator: component, metadata, inputs, outputs} = directiveResult;
const encapsulation: number =
this._resolveEnumValue(component, 'encapsulation', 'ViewEncapsulation') ??
ViewEncapsulation.Emulated;
const changeDetection: number|null =
this._resolveEnumValue(component, 'changeDetection', 'ChangeDetectionStrategy');
let animations: Expression|null = null;
if (component.has('animations')) {
animations = new WrappedNodeExpr(component.get('animations')!);
}
// 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 = relative(absoluteFrom(rootDir), absoluteFrom(containingFile));
if (previous === undefined || candidate.length < previous.length) {
return candidate;
} else {
return previous;
}
}, undefined)!;
// Note that we could technically combine the `viewProvidersRequiringFactory` and
// `providersRequiringFactory` into a single set, but we keep the separate so that
// we can distinguish where an error is coming from when logging the diagnostics in `resolve`.
let viewProvidersRequiringFactory: Set<Reference<ClassDeclaration>>|null = null;
let providersRequiringFactory: Set<Reference<ClassDeclaration>>|null = null;
let wrappedViewProviders: Expression|null = null;
if (component.has('viewProviders')) {
const viewProviders = component.get('viewProviders')!;
viewProvidersRequiringFactory =
resolveProvidersRequiringFactory(viewProviders, this.reflector, this.evaluator);
wrappedViewProviders = new WrappedNodeExpr(
this.annotateForClosureCompiler ? wrapFunctionExpressionsInParens(viewProviders) :
viewProviders);
}
if (component.has('providers')) {
providersRequiringFactory = resolveProvidersRequiringFactory(
component.get('providers')!, this.reflector, this.evaluator);
}
// Parse the template.
// If a preanalyze phase was executed, the template may already exist in parsed form, so check
// the preanalyzeTemplateCache.
// Extract a closure of the template parsing code so that it can be reparsed with different
// options if needed, like in the indexing pipeline.
let template: ParsedTemplateWithSource;
if (this.preanalyzeTemplateCache.has(node)) {
// The template was parsed in preanalyze. Use it and delete it to save memory.
const preanalyzed = this.preanalyzeTemplateCache.get(node)!;
this.preanalyzeTemplateCache.delete(node);
template = preanalyzed;
} else {
const templateDecl = this.parseTemplateDeclaration(decorator, component, containingFile);
template = this.extractTemplate(node, templateDecl);
}
const templateResource =
template.declaration.isInline ? {path: null, expression: component.get('template')!} : {
path: absoluteFrom(template.declaration.resolvedTemplateUrl),
expression: template.sourceMapping.node
};
// Figure out the set of styles. The ordering here is important: external resources (styleUrls)
// precede inline styles, and styles defined in the template override styles defined in the
// component.
let styles: string[] = [];
const styleResources = this._extractStyleResources(component, containingFile);
const styleUrls: StyleUrlMeta[] = [
...this._extractComponentStyleUrls(component), ...this._extractTemplateStyleUrls(template)
];
for (const styleUrl of styleUrls) {
try {
const resourceUrl = this.resourceLoader.resolve(styleUrl.url, containingFile);
const resourceStr = this.resourceLoader.load(resourceUrl);
styles.push(resourceStr);
if (this.depTracker !== null) {
this.depTracker.addResourceDependency(node.getSourceFile(), absoluteFrom(resourceUrl));
}
} catch {
if (diagnostics === undefined) {
diagnostics = [];
}
const resourceType =
styleUrl.source === ResourceTypeForDiagnostics.StylesheetFromDecorator ?
ResourceTypeForDiagnostics.StylesheetFromDecorator :
ResourceTypeForDiagnostics.StylesheetFromTemplate;
diagnostics.push(
this.makeResourceNotFoundError(styleUrl.url, styleUrl.nodeForError, resourceType)
.toDiagnostic());
}
}
if (encapsulation === ViewEncapsulation.ShadowDom && metadata.selector !== null) {
const selectorError = checkCustomElementSelectorForErrors(metadata.selector);
if (selectorError !== null) {
if (diagnostics === undefined) {
diagnostics = [];
}
diagnostics.push(makeDiagnostic(
ErrorCode.COMPONENT_INVALID_SHADOW_DOM_SELECTOR, component.get('selector')!,
selectorError));
}
}
// If inline styles were preprocessed use those
let inlineStyles: string[]|null = null;
if (this.preanalyzeStylesCache.has(node)) {
inlineStyles = this.preanalyzeStylesCache.get(node)!;
this.preanalyzeStylesCache.delete(node);
if (inlineStyles !== null) {
styles.push(...inlineStyles);
}
} else {
// Preprocessing is only supported asynchronously
// If no style cache entry is present asynchronous preanalyze was not executed.
// This protects against accidental differences in resource contents when preanalysis
// is not used with a provided transformResource hook on the ResourceHost.
if (this.resourceLoader.canPreprocess) {
throw new Error('Inline resource processing requires asynchronous preanalyze.');
}
if (component.has('styles')) {
const litStyles = parseFieldArrayValue(component, 'styles', this.evaluator);
if (litStyles !== null) {
inlineStyles = [...litStyles];
styles.push(...litStyles);
}
}
}
if (template.styles.length > 0) {
styles.push(...template.styles);
}
const output: AnalysisOutput<ComponentAnalysisData> = {
analysis: {
baseClass: readBaseClass(node, this.reflector, this.evaluator),
inputs,
outputs,
meta: {
...metadata,
template: {
nodes: template.nodes,
ngContentSelectors: template.ngContentSelectors,
},
encapsulation,
interpolation: template.interpolationConfig ?? DEFAULT_INTERPOLATION_CONFIG,
styles,
// These will be replaced during the compilation step, after all `NgModule`s have been
// analyzed and the full compilation scope for the component can be realized.
animations,
viewProviders: wrappedViewProviders,
i18nUseExternalIds: this.i18nUseExternalIds,
relativeContextFilePath,
},
typeCheckMeta: extractDirectiveTypeCheckMeta(node, inputs, this.reflector),
classMetadata: extractClassMetadata(
node, this.reflector, this.isCore, this.annotateForClosureCompiler),
template,
providersRequiringFactory,
viewProvidersRequiringFactory,
inlineStyles,
styleUrls,
resources: {
styles: styleResources,
template: templateResource,
},
isPoisoned,
},
diagnostics,
};
if (changeDetection !== null) {
output.analysis!.meta.changeDetection = changeDetection;
}
return output;
}
symbol(node: ClassDeclaration, analysis: Readonly<ComponentAnalysisData>): ComponentSymbol {
const typeParameters = extractSemanticTypeParameters(node);
return new ComponentSymbol(
node, analysis.meta.selector, analysis.inputs, analysis.outputs, analysis.meta.exportAs,
analysis.typeCheckMeta, typeParameters);
}
register(node: ClassDeclaration, analysis: ComponentAnalysisData): void {
// Register this component's information with the `MetadataRegistry`. This ensures that
// the information about the component is available during the compile() phase.
const ref = new Reference(node);
this.metaRegistry.registerDirectiveMetadata({
type: MetaType.Directive,
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: true,
baseClass: analysis.baseClass,
...analysis.typeCheckMeta,
isPoisoned: analysis.isPoisoned,
isStructural: false,
});
this.resourceRegistry.registerResources(analysis.resources, node);
this.injectableRegistry.registerInjectable(node);
}
index(
context: IndexingContext, node: ClassDeclaration, analysis: Readonly<ComponentAnalysisData>) {
if (analysis.isPoisoned && !this.usePoisonedData) {
return null;
}
const scope = this.scopeReader.getScopeForComponent(node);
const selector = analysis.meta.selector;
const matcher = new SelectorMatcher<DirectiveMeta>();
if (scope !== null) {
if ((scope.compilation.isPoisoned || scope.exported.isPoisoned) && !this.usePoisonedData) {
// Don't bother indexing components which had erroneous scopes, unless specifically
// requested.
return null;
}
for (const directive of scope.compilation.directives) {
if (directive.selector !== null) {
matcher.addSelectables(CssSelector.parse(directive.selector), directive);
}
}
}
const binder = new R3TargetBinder(matcher);
const boundTemplate = binder.bind({template: analysis.template.diagNodes});
context.addComponent({
declaration: node,
selector,
boundTemplate,
templateMeta: {
isInline: analysis.template.declaration.isInline,
file: analysis.template.file,
},
});
}
typeCheck(ctx: TypeCheckContext, node: ClassDeclaration, meta: Readonly<ComponentAnalysisData>):
void {
if (this.typeCheckScopeRegistry === null || !ts.isClassDeclaration(node)) {
return;
}
if (meta.isPoisoned && !this.usePoisonedData) {
return;
}
const scope = this.typeCheckScopeRegistry.getTypeCheckScope(node);
if (scope.isPoisoned && !this.usePoisonedData) {
// Don't type-check components that had errors in their scopes, unless requested.
return;
}
const binder = new R3TargetBinder(scope.matcher);
ctx.addTemplate(
new Reference(node), binder, meta.template.diagNodes, scope.pipes, scope.schemas,
meta.template.sourceMapping, meta.template.file, meta.template.errors);
}
extendedTemplateCheck(
component: ts.ClassDeclaration,
extendedTemplateChecker: ExtendedTemplateChecker): ts.Diagnostic[] {
return extendedTemplateChecker.getDiagnosticsForComponent(component);
}
resolve(
node: ClassDeclaration, analysis: Readonly<ComponentAnalysisData>,
symbol: ComponentSymbol): ResolveResult<ComponentResolutionData> {
if (this.semanticDepGraphUpdater !== null && analysis.baseClass instanceof Reference) {
symbol.baseClass = this.semanticDepGraphUpdater.getSymbol(analysis.baseClass.node);
}
if (analysis.isPoisoned && !this.usePoisonedData) {
return {};
}
const context = node.getSourceFile();
// Check whether this component was registered with an NgModule. If so, it should be compiled
// under that module's compilation scope.
const scope = this.scopeReader.getScopeForComponent(node);
let metadata = analysis.meta as Readonly<R3ComponentMetadata>;
const data: ComponentResolutionData = {
directives: EMPTY_ARRAY,
pipes: EMPTY_MAP,
declarationListEmitMode: DeclarationListEmitMode.Direct,
};
if (scope !== null && (!scope.compilation.isPoisoned || this.usePoisonedData)) {
// Replace the empty components and directives from the analyze() step with a fully expanded
// scope. This is possible now because during resolve() the whole compilation unit has been
// fully analyzed.
//
// First it needs to be determined if actually importing the directives/pipes used in the
// template would create a cycle. Currently ngtsc refuses to generate cycles, so an option
// known as "remote scoping" is used if a cycle would be created. In remote scoping, the
// module file sets the directives/pipes on the ɵcmp of the component, without
// requiring new imports (but also in a way that breaks tree shaking).
//
// Determining this is challenging, because the TemplateDefinitionBuilder is responsible for
// matching directives and pipes in the template; however, that doesn't run until the actual
// compile() step. It's not possible to run template compilation sooner as it requires the
// ConstantPool for the overall file being compiled (which isn't available until the
// transform step).
//
// Instead, directives/pipes are matched independently here, using the R3TargetBinder. This
// is an alternative implementation of template matching which is used for template
// type-checking and will eventually replace matching in the TemplateDefinitionBuilder.
// Set up the R3TargetBinder, as well as a 'directives' array and a 'pipes' map that are
// later fed to the TemplateDefinitionBuilder. First, a SelectorMatcher is constructed to
// match directives that are in scope.
type MatchedDirective = DirectiveMeta&{selector: string};
const matcher = new SelectorMatcher<MatchedDirective>();
for (const dir of scope.compilation.directives) {
if (dir.selector !== null) {
matcher.addSelectables(CssSelector.parse(dir.selector), dir as MatchedDirective);
}
}
const pipes = new Map<string, Reference<ClassDeclaration>>();
for (const pipe of scope.compilation.pipes) {
pipes.set(pipe.name, pipe.ref);
}
// Next, the component template AST is bound using the R3TargetBinder. This produces a
// BoundTarget, which is similar to a ts.TypeChecker.
const binder = new R3TargetBinder(matcher);
const bound = binder.bind({template: metadata.template.nodes});
// The BoundTarget knows which directives and pipes matched the template.
type UsedDirective =
R3UsedDirectiveMetadata&{ref: Reference<ClassDeclaration>, importedFile: ImportedFile};
const usedDirectives: UsedDirective[] = bound.getUsedDirectives().map(directive => {
const type = this.refEmitter.emit(directive.ref, context);
return {
ref: directive.ref,
type: type.expression,
importedFile: type.importedFile,
selector: directive.selector,
inputs: directive.inputs.propertyNames,
outputs: directive.outputs.propertyNames,
exportAs: directive.exportAs,
isComponent: directive.isComponent,
};
});
type UsedPipe = {
ref: Reference<ClassDeclaration>,
pipeName: string,
expression: Expression,
importedFile: ImportedFile,
};
const usedPipes: UsedPipe[] = [];
for (const pipeName of bound.getUsedPipes()) {
if (!pipes.has(pipeName)) {
continue;
}
const pipe = pipes.get(pipeName)!;
const type = this.refEmitter.emit(pipe, context);
usedPipes.push({
ref: pipe,
pipeName,
expression: type.expression,
importedFile: type.importedFile,
});
}
if (this.semanticDepGraphUpdater !== null) {
symbol.usedDirectives = usedDirectives.map(
dir => this.semanticDepGraphUpdater!.getSemanticReference(dir.ref.node, dir.type));
symbol.usedPipes = usedPipes.map(
pipe =>
this.semanticDepGraphUpdater!.getSemanticReference(pipe.ref.node, pipe.expression));
}
// Scan through the directives/pipes actually used in the template and check whether any
// import which needs to be generated would create a cycle.
const cyclesFromDirectives = new Map<UsedDirective, Cycle>();
for (const usedDirective of usedDirectives) {
const cycle =
this._checkForCyclicImport(usedDirective.importedFile, usedDirective.type, context);
if (cycle !== null) {
cyclesFromDirectives.set(usedDirective, cycle);
}
}
const cyclesFromPipes = new Map<UsedPipe, Cycle>();
for (const usedPipe of usedPipes) {
const cycle =
this._checkForCyclicImport(usedPipe.importedFile, usedPipe.expression, context);
if (cycle !== null) {
cyclesFromPipes.set(usedPipe, cycle);
}
}
const cycleDetected = cyclesFromDirectives.size !== 0 || cyclesFromPipes.size !== 0;
if (!cycleDetected) {
// No cycle was detected. Record the imports that need to be created in the cycle detector
// so that future cyclic import checks consider their production.
for (const {type, importedFile} of usedDirectives) {
this._recordSyntheticImport(importedFile, type, context);
}
for (const {expression, importedFile} of usedPipes) {
this._recordSyntheticImport(importedFile, expression, context);
}
// Check whether the directive/pipe arrays in ɵcmp need to be wrapped in closures.
// This is required if any directive/pipe reference is to a declaration in the same file
// but declared after this component.
const wrapDirectivesAndPipesInClosure =
usedDirectives.some(
dir => isExpressionForwardReference(dir.type, node.name, context)) ||
usedPipes.some(
pipe => isExpressionForwardReference(pipe.expression, node.name, context));
data.directives = usedDirectives;
data.pipes = new Map(usedPipes.map(pipe => [pipe.pipeName, pipe.expression]));
data.declarationListEmitMode = wrapDirectivesAndPipesInClosure ?
DeclarationListEmitMode.Closure :
DeclarationListEmitMode.Direct;
} else {
if (this.cycleHandlingStrategy === CycleHandlingStrategy.UseRemoteScoping) {
// Declaring the directiveDefs/pipeDefs arrays directly would require imports that would
// create a cycle. Instead, mark this component as requiring remote scoping, so that the
// NgModule file will take care of setting the directives for the component.
this.scopeRegistry.setComponentRemoteScope(
node, usedDirectives.map(dir => dir.ref), usedPipes.map(pipe => pipe.ref));
symbol.isRemotelyScoped = true;
// If a semantic graph is being tracked, record the fact that this component is remotely
// scoped with the declaring NgModule symbol as the NgModule's emit becomes dependent on
// the directive/pipe usages of this component.
if (this.semanticDepGraphUpdater !== null) {
const moduleSymbol = this.semanticDepGraphUpdater.getSymbol(scope.ngModule);
if (!(moduleSymbol instanceof NgModuleSymbol)) {
throw new Error(
`AssertionError: Expected ${scope.ngModule.name} to be an NgModuleSymbol.`);
}
moduleSymbol.addRemotelyScopedComponent(
symbol, symbol.usedDirectives, symbol.usedPipes);
}
} else {
// We are not able to handle this cycle so throw an error.
const relatedMessages: ts.DiagnosticRelatedInformation[] = [];
for (const [dir, cycle] of cyclesFromDirectives) {
relatedMessages.push(
makeCyclicImportInfo(dir.ref, dir.isComponent ? 'component' : 'directive', cycle));
}
for (const [pipe, cycle] of cyclesFromPipes) {
relatedMessages.push(makeCyclicImportInfo(pipe.ref, 'pipe', cycle));
}
throw new FatalDiagnosticError(
ErrorCode.IMPORT_CYCLE_DETECTED, node,
'One or more import cycles would need to be created to compile this component, ' +
'which is not supported by the current compiler configuration.',
relatedMessages);
}
}
}
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);
}
if (analysis.viewProvidersRequiringFactory !== null &&
analysis.meta.viewProviders instanceof WrappedNodeExpr) {
const viewProviderDiagnostics = getProviderDiagnostics(
analysis.viewProvidersRequiringFactory, analysis.meta.viewProviders!.node,
this.injectableRegistry);
diagnostics.push(...viewProviderDiagnostics);
}
const directiveDiagnostics = getDirectiveDiagnostics(
node, this.metaReader, this.evaluator, this.reflector, this.scopeRegistry, 'Component');
if (directiveDiagnostics !== null) {
diagnostics.push(...directiveDiagnostics);
}
if (diagnostics.length > 0) {
return {diagnostics};
}
return {data};
}
xi18n(ctx: Xi18nContext, node: ClassDeclaration, analysis: Readonly<ComponentAnalysisData>):
void {
ctx.updateFromTemplate(
analysis.template.content, analysis.template.declaration.resolvedTemplateUrl,
analysis.template.interpolationConfig ?? DEFAULT_INTERPOLATION_CONFIG);
}
updateResources(node: ClassDeclaration, analysis: ComponentAnalysisData): void {
const containingFile = node.getSourceFile().fileName;
// If the template is external, re-parse it.
const templateDecl = analysis.template.declaration;
if (!templateDecl.isInline) {
analysis.template = this.extractTemplate(node, templateDecl);
}
// Update any external stylesheets and rebuild the combined 'styles' list.
// TODO(alxhub): write tests for styles when the primary compiler uses the updateResources path
let styles: string[] = [];
if (analysis.styleUrls !== null) {
for (const styleUrl of analysis.styleUrls) {
try {
const resolvedStyleUrl = this.resourceLoader.resolve(styleUrl.url, containingFile);
const styleText = this.resourceLoader.load(resolvedStyleUrl);
styles.push(styleText);
} catch (e) {
// Resource resolve failures should already be in the diagnostics list from the analyze
// stage. We do not need to do anything with them when updating resources.
}
}
}
if (analysis.inlineStyles !== null) {
for (const styleText of analysis.inlineStyles) {
styles.push(styleText);
}
}
for (const styleText of analysis.template.styles) {
styles.push(styleText);
}
analysis.meta.styles = styles;
}
compileFull(
node: ClassDeclaration, analysis: Readonly<ComponentAnalysisData>,
resolution: Readonly<ComponentResolutionData>, pool: ConstantPool): CompileResult[] {
if (analysis.template.errors !== null && analysis.template.errors.length > 0) {
return [];
}
const meta: R3ComponentMetadata = {...analysis.meta, ...resolution};
const fac = compileNgFactoryDefField(toFactoryMetadata(meta, FactoryTarget.Component));
const def = compileComponentFromMetadata(meta, pool, makeBindingParser());
const classMetadata = analysis.classMetadata !== null ?
compileClassMetadata(analysis.classMetadata).toStmt() :
null;
return compileResults(fac, def, classMetadata, 'ɵcmp');
}
compilePartial(
node: ClassDeclaration, analysis: Readonly<ComponentAnalysisData>,
resolution: Readonly<ComponentResolutionData>): CompileResult[] {
if (analysis.template.errors !== null && analysis.template.errors.length > 0) {
return [];
}
const templateInfo: DeclareComponentTemplateInfo = {
content: analysis.template.content,
sourceUrl: analysis.template.declaration.resolvedTemplateUrl,
isInline: analysis.template.declaration.isInline,
inlineTemplateLiteralExpression: analysis.template.sourceMapping.type === 'direct' ?
new WrappedNodeExpr(analysis.template.sourceMapping.node) :
null,
};
const meta: R3ComponentMetadata = {...analysis.meta, ...resolution};
const fac = compileDeclareFactory(toFactoryMetadata(meta, FactoryTarget.Component));
const def = compileDeclareComponentFromMetadata(meta, analysis.template, templateInfo);
const classMetadata = analysis.classMetadata !== null ?
compileDeclareClassMetadata(analysis.classMetadata).toStmt() :
null;
return compileResults(fac, def, classMetadata, 'ɵcmp');
}
private _resolveLiteral(decorator: Decorator): ts.ObjectLiteralExpression {
if (this.literalCache.has(decorator)) {
return this.literalCache.get(decorator)!;
}
if (decorator.args === null || decorator.args.length !== 1) {
throw new FatalDiagnosticError(
ErrorCode.DECORATOR_ARITY_WRONG, Decorator.nodeForError(decorator),
`Incorrect number of arguments to @Component decorator`);
}
const meta = unwrapExpression(decorator.args[0]);
if (!ts.isObjectLiteralExpression(meta)) {
throw new FatalDiagnosticError(
ErrorCode.DECORATOR_ARG_NOT_LITERAL, meta, `Decorator argument must be literal.`);
}
this.literalCache.set(decorator, meta);
return meta;
}
private _resolveEnumValue(
component: Map<string, ts.Expression>, field: string, enumSymbolName: string): number|null {
let resolved: number|null = null;
if (component.has(field)) {
const expr = component.get(field)!;
const value = this.evaluator.evaluate(expr) as any;
if (value instanceof EnumValue && isAngularCoreReference(value.enumRef, enumSymbolName)) {
resolved = value.resolved as number;
} else {
throw createValueHasWrongTypeError(
expr, value, `${field} must be a member of ${enumSymbolName} enum from @angular/core`);
}
}
return resolved;
}
private _extractComponentStyleUrls(
component: Map<string, ts.Expression>,
): StyleUrlMeta[] {
if (!component.has('styleUrls')) {
return [];
}
return this._extractStyleUrlsFromExpression(component.get('styleUrls')!);
}
private _extractStyleUrlsFromExpression(styleUrlsExpr: ts.Expression): StyleUrlMeta[] {
const styleUrls: StyleUrlMeta[] = [];
if (ts.isArrayLiteralExpression(styleUrlsExpr)) {
for (const styleUrlExpr of styleUrlsExpr.elements) {
if (ts.isSpreadElement(styleUrlExpr)) {
styleUrls.push(...this._extractStyleUrlsFromExpression(styleUrlExpr.expression));
} else {
const styleUrl = this.evaluator.evaluate(styleUrlExpr);
if (typeof styleUrl !== 'string') {
throw createValueHasWrongTypeError(styleUrlExpr, styleUrl, 'styleUrl must be a string');
}
styleUrls.push({
url: styleUrl,
source: ResourceTypeForDiagnostics.StylesheetFromDecorator,
nodeForError: styleUrlExpr,
});
}
}
} else {
const evaluatedStyleUrls = this.evaluator.evaluate(styleUrlsExpr);
if (!isStringArray(evaluatedStyleUrls)) {
throw createValueHasWrongTypeError(