-
Notifications
You must be signed in to change notification settings - Fork 24.8k
/
component.ts
830 lines (741 loc) Β· 34.2 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
/**
* @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 {ConstantPool, CssSelector, DEFAULT_INTERPOLATION_CONFIG, DomElementSchemaRegistry, Expression, ExternalExpr, Identifiers, InterpolationConfig, LexerRange, ParseError, ParseSourceFile, ParseTemplateOptions, R3ComponentMetadata, R3FactoryTarget, R3TargetBinder, SchemaMetadata, SelectorMatcher, Statement, TmplAstNode, WrappedNodeExpr, compileComponentFromMetadata, makeBindingParser, parseTemplate} from '@angular/compiler';
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';
import {flattenInheritedDirectiveMetadata} from '../../metadata/src/inheritance';
import {EnumValue, PartialEvaluator} from '../../partial_evaluator';
import {ClassDeclaration, Decorator, ReflectionHost, reflectObjectLiteral} from '../../reflection';
import {ComponentScopeReader, LocalModuleScopeRegistry} from '../../scope';
import {AnalysisOutput, CompileResult, DecoratorHandler, DetectResult, HandlerFlags, HandlerPrecedence, ResolveResult} from '../../transform';
import {TemplateSourceMapping, TypeCheckContext} from '../../typecheck';
import {NoopResourceDependencyRecorder, ResourceDependencyRecorder} from '../../util/src/resource_recorder';
import {tsSourceMapBug29300Fixed} from '../../util/src/ts_source_map_bug_29300';
import {ResourceLoader} from './api';
import {extractDirectiveMetadata, parseFieldArrayValue} from './directive';
import {compileNgFactoryDefField} from './factory';
import {generateSetClassMetadataCall} from './metadata';
import {findAngularDecorator, isAngularCoreReference, isExpressionForwardReference, readBaseClass, unwrapExpression} from './util';
const EMPTY_MAP = new Map<string, Expression>();
const EMPTY_ARRAY: any[] = [];
export interface ComponentHandlerData {
meta: R3ComponentMetadata;
parsedTemplate: ParsedTemplate;
templateSourceMapping: TemplateSourceMapping;
metadataStmt: Statement|null;
parseTemplate: (options?: ParseTemplateOptions) => ParsedTemplate;
}
/**
* `DecoratorHandler` which handles the `@Component` annotation.
*/
export class ComponentDecoratorHandler implements
DecoratorHandler<ComponentHandlerData, Decorator> {
constructor(
private reflector: ReflectionHost, private evaluator: PartialEvaluator,
private metaRegistry: MetadataRegistry, private metaReader: MetadataReader,
private scopeReader: ComponentScopeReader, private scopeRegistry: LocalModuleScopeRegistry,
private isCore: boolean, private resourceLoader: ResourceLoader, private rootDirs: string[],
private defaultPreserveWhitespaces: boolean, private i18nUseExternalIds: boolean,
private i18nLegacyMessageIdFormat: string, private moduleResolver: ModuleResolver,
private cycleAnalyzer: CycleAnalyzer, private refEmitter: ReferenceEmitter,
private defaultImportRecorder: DefaultImportRecorder,
private resourceDependencies:
ResourceDependencyRecorder = new NoopResourceDependencyRecorder()) {}
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<ts.Declaration, PreanalyzedTemplate>();
readonly precedence = HandlerPrecedence.PRIMARY;
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,
metadata: decorator,
};
} else {
return undefined;
}
}
preanalyze(node: ClassDeclaration, decorator: 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;
// Convert a styleUrl string into a Promise to preload it.
const resolveStyleUrl = (styleUrl: string): Promise<void> => {
const resourceUrl = this.resourceLoader.resolve(styleUrl, containingFile);
const promise = this.resourceLoader.preload(resourceUrl);
return promise || Promise.resolve();
};
// 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 => {
if (template === null) {
return undefined;
} else {
return Promise.all(template.styleUrls.map(resolveStyleUrl)).then(() => undefined);
}
});
// Extract all the styleUrls in the decorator.
const styleUrls = this._extractStyleUrls(component, []);
if (styleUrls === null) {
// A fast path exists if there are no styleUrls, to just wait for
// templateAndTemplateStyleResources.
return templateAndTemplateStyleResources;
} else {
// Wait for both the template and all styleUrl resources to resolve.
return Promise.all([templateAndTemplateStyleResources, ...styleUrls.map(resolveStyleUrl)])
.then(() => undefined);
}
}
analyze(node: ClassDeclaration, decorator: Decorator, flags: HandlerFlags = HandlerFlags.NONE):
AnalysisOutput<ComponentHandlerData> {
const containingFile = node.getSourceFile().fileName;
this.literalCache.delete(decorator);
// @Component inherits @Directive, so begin by extracting the @Directive metadata and building
// on it.
const directiveResult = extractDirectiveMetadata(
node, decorator, this.reflector, this.evaluator, this.defaultImportRecorder, this.isCore,
flags, 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} = directiveResult;
// 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) !;
const viewProviders: Expression|null = component.has('viewProviders') ?
new WrappedNodeExpr(component.get('viewProviders') !) :
null;
// 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 parseTemplate: (options?: ParseTemplateOptions) => ParsedTemplate;
// Track the origin of the template to determine how the ParseSourceSpans should be interpreted.
let templateSourceMapping: TemplateSourceMapping;
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);
parseTemplate = preanalyzed.parseTemplate;
templateSourceMapping = preanalyzed.templateSourceMapping;
} else {
// The template was not already parsed. Either there's a templateUrl, or an inline template.
if (component.has('templateUrl')) {
const templateUrlExpr = component.get('templateUrl') !;
const templateUrl = this.evaluator.evaluate(templateUrlExpr);
if (typeof templateUrl !== 'string') {
throw new FatalDiagnosticError(
ErrorCode.VALUE_HAS_WRONG_TYPE, templateUrlExpr, 'templateUrl must be a string');
}
const resourceUrl = this.resourceLoader.resolve(templateUrl, containingFile);
const external =
this._extractExternalTemplate(node, component, templateUrlExpr, resourceUrl);
parseTemplate = external.parseTemplate;
templateSourceMapping = external.templateSourceMapping;
} else {
// Expect an inline template to be present.
const inline = this._extractInlineTemplate(node, decorator, component, containingFile);
parseTemplate = inline.parseTemplate;
templateSourceMapping = inline.templateSourceMapping;
}
}
const template = parseTemplate();
if (template.errors !== undefined) {
throw new Error(
`Errors parsing template: ${template.errors.map(e => e.toString()).join(', ')}`);
}
// 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({
ref,
name: node.name.text,
selector: metadata.selector,
exportAs: metadata.exportAs,
inputs: metadata.inputs,
outputs: metadata.outputs,
queries: metadata.queries.map(query => query.propertyName),
isComponent: true, ...extractDirectiveGuards(node, this.reflector),
baseClass: readBaseClass(node, this.reflector, this.evaluator),
});
// 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[]|null = null;
const styleUrls = this._extractStyleUrls(component, template.styleUrls);
if (styleUrls !== null) {
if (styles === null) {
styles = [];
}
for (const styleUrl of styleUrls) {
const resourceUrl = this.resourceLoader.resolve(styleUrl, containingFile);
const resourceStr = this.resourceLoader.load(resourceUrl);
styles.push(resourceStr);
this.resourceDependencies.recordResourceDependency(node.getSourceFile(), resourceUrl);
}
}
if (component.has('styles')) {
const litStyles = parseFieldArrayValue(component, 'styles', this.evaluator);
if (litStyles !== null) {
if (styles === null) {
styles = litStyles;
} else {
styles.push(...litStyles);
}
}
}
if (template.styles.length > 0) {
if (styles === null) {
styles = template.styles;
} else {
styles.push(...template.styles);
}
}
const encapsulation: number =
this._resolveEnumValue(component, 'encapsulation', 'ViewEncapsulation') || 0;
const changeDetection: number|null =
this._resolveEnumValue(component, 'changeDetection', 'ChangeDetectionStrategy');
let animations: Expression|null = null;
if (component.has('animations')) {
animations = new WrappedNodeExpr(component.get('animations') !);
}
const output = {
analysis: {
meta: {
...metadata,
template,
encapsulation,
interpolation: template.interpolation,
styles: 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.
pipes: EMPTY_MAP,
directives: EMPTY_ARRAY,
wrapDirectivesAndPipesInClosure: false, //
animations,
viewProviders,
i18nUseExternalIds: this.i18nUseExternalIds, relativeContextFilePath
},
metadataStmt: generateSetClassMetadataCall(
node, this.reflector, this.defaultImportRecorder, this.isCore),
parsedTemplate: template, parseTemplate, templateSourceMapping,
},
typeCheck: true,
};
if (changeDetection !== null) {
(output.analysis.meta as R3ComponentMetadata).changeDetection = changeDetection;
}
return output;
}
index(context: IndexingContext, node: ClassDeclaration, analysis: ComponentHandlerData) {
// The component template may have been previously parsed without preserving whitespace or with
// `leadingTriviaChar`s, both of which may manipulate the AST into a form not representative of
// the source code, making it unsuitable for indexing. The template is reparsed with preserving
// options to remedy this.
const template = analysis.parseTemplate({
preserveWhitespaces: true,
leadingTriviaChars: [],
});
const scope = this.scopeReader.getScopeForComponent(node);
const selector = analysis.meta.selector;
const matcher = new SelectorMatcher<DirectiveMeta>();
if (scope !== 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: template.nodes});
context.addComponent({
declaration: node,
selector,
boundTemplate,
templateMeta: {
isInline: template.isInline,
file: template.file,
},
});
}
typeCheck(ctx: TypeCheckContext, node: ClassDeclaration, meta: ComponentHandlerData): void {
if (!ts.isClassDeclaration(node)) {
return;
}
// There are issues with parsing the template under certain configurations (namely with
// `preserveWhitespaces: false`) which cause inaccurate positional information within the
// template AST, particularly within interpolation expressions.
//
// To work around this, the template is re-parsed with settings that guarantee the spans are as
// accurate as possible. This is only a temporary solution until the whitespace removal step can
// be rewritten as a transform against the expression AST instead of against the HTML AST.
//
// TODO(alxhub): remove this when whitespace removal no longer corrupts span information.
const template = meta.parseTemplate({
preserveWhitespaces: true,
leadingTriviaChars: [],
});
const matcher = new SelectorMatcher<DirectiveMeta>();
const pipes = new Map<string, Reference<ClassDeclaration<ts.ClassDeclaration>>>();
let schemas: SchemaMetadata[] = [];
const scope = this.scopeReader.getScopeForComponent(node);
if (scope !== null) {
for (const meta of scope.compilation.directives) {
if (meta.selector !== null) {
const extMeta = flattenInheritedDirectiveMetadata(this.metaReader, meta.ref);
matcher.addSelectables(CssSelector.parse(meta.selector), extMeta);
}
}
for (const {name, ref} of scope.compilation.pipes) {
if (!ts.isClassDeclaration(ref.node)) {
throw new Error(
`Unexpected non-class declaration ${ts.SyntaxKind[ref.node.kind]} for pipe ${ref.debugName}`);
}
pipes.set(name, ref as Reference<ClassDeclaration<ts.ClassDeclaration>>);
}
schemas = scope.schemas;
}
const bound = new R3TargetBinder(matcher).bind({template: template.nodes});
ctx.addTemplate(
new Reference(node), bound, pipes, schemas, meta.templateSourceMapping, template.file);
}
resolve(node: ClassDeclaration, analysis: ComponentHandlerData): ResolveResult {
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;
if (scope !== null) {
// 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.
const matcher = new SelectorMatcher<DirectiveMeta&{expression: Expression}>();
const directives: {selector: string, expression: Expression}[] = [];
for (const dir of scope.compilation.directives) {
const {ref, selector} = dir;
if (selector !== null) {
const expression = this.refEmitter.emit(ref, context);
directives.push({selector, expression});
matcher.addSelectables(CssSelector.parse(selector), {...dir, expression});
}
}
const pipes = new Map<string, Expression>();
for (const pipe of scope.compilation.pipes) {
pipes.set(pipe.name, this.refEmitter.emit(pipe.ref, context));
}
// Next, the component template AST is bound using the R3TargetBinder. This produces an
// 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.
const usedDirectives = bound.getUsedDirectives();
const usedPipes = bound.getUsedPipes().map(name => pipes.get(name) !);
// 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 cycleDetected =
usedDirectives.some(dir => this._isCyclicImport(dir.expression, context)) ||
usedPipes.some(pipe => this._isCyclicImport(pipe, context));
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 {expression} of usedDirectives) {
this._recordSyntheticImport(expression, context);
}
for (const pipe of usedPipes) {
this._recordSyntheticImport(pipe, 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.expression, node.name, context)) ||
usedPipes.some(pipe => isExpressionForwardReference(pipe, node.name, context));
// Actual compilation still uses the full scope, not the narrowed scope determined by
// R3TargetBinder. This is a hedge against potential issues with the R3TargetBinder - right
// now the TemplateDefinitionBuilder is the "source of truth" for which directives/pipes are
// actually used (though the two should agree perfectly).
//
// TODO(alxhub): switch TemplateDefinitionBuilder over to using R3TargetBinder directly.
metadata.directives = directives;
metadata.pipes = pipes;
metadata.wrapDirectivesAndPipesInClosure = wrapDirectivesAndPipesInClosure;
} else {
// 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.setComponentAsRequiringRemoteScoping(node);
}
}
return {};
}
compile(node: ClassDeclaration, analysis: ComponentHandlerData, pool: ConstantPool):
CompileResult[] {
const meta = analysis.meta;
const res = compileComponentFromMetadata(meta, pool, makeBindingParser());
const factoryRes = compileNgFactoryDefField(
{...meta, injectFn: Identifiers.directiveInject, target: R3FactoryTarget.Component});
if (analysis.metadataStmt !== null) {
factoryRes.statements.push(analysis.metadataStmt);
}
return [
factoryRes, {
name: 'Ι΅cmp',
initializer: res.expression,
statements: [],
type: res.type,
}
];
}
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 new FatalDiagnosticError(
ErrorCode.VALUE_HAS_WRONG_TYPE, expr,
`${field} must be a member of ${enumSymbolName} enum from @angular/core`);
}
}
return resolved;
}
private _extractStyleUrls(component: Map<string, ts.Expression>, extraUrls: string[]):
string[]|null {
if (!component.has('styleUrls')) {
return extraUrls.length > 0 ? extraUrls : null;
}
const styleUrlsExpr = component.get('styleUrls') !;
const styleUrls = this.evaluator.evaluate(styleUrlsExpr);
if (!Array.isArray(styleUrls) || !styleUrls.every(url => typeof url === 'string')) {
throw new FatalDiagnosticError(
ErrorCode.VALUE_HAS_WRONG_TYPE, styleUrlsExpr, 'styleUrls must be an array of strings');
}
styleUrls.push(...extraUrls);
return styleUrls as string[];
}
private _preloadAndParseTemplate(
node: ClassDeclaration, decorator: Decorator, component: Map<string, ts.Expression>,
containingFile: string): Promise<ParsedTemplate|null> {
if (component.has('templateUrl')) {
// Extract the templateUrl and preload it.
const templateUrlExpr = component.get('templateUrl') !;
const templateUrl = this.evaluator.evaluate(templateUrlExpr);
if (typeof templateUrl !== 'string') {
throw new FatalDiagnosticError(
ErrorCode.VALUE_HAS_WRONG_TYPE, templateUrlExpr, 'templateUrl must be a string');
}
const resourceUrl = this.resourceLoader.resolve(templateUrl, containingFile);
const templatePromise = this.resourceLoader.preload(resourceUrl);
// If the preload worked, then actually load and parse the template, and wait for any style
// URLs to resolve.
if (templatePromise !== undefined) {
return templatePromise.then(() => {
const {parseTemplate, templateSourceMapping} =
this._extractExternalTemplate(node, component, templateUrlExpr, resourceUrl);
const template = parseTemplate();
this.preanalyzeTemplateCache.set(
node, {...template, parseTemplate, templateSourceMapping});
return template;
});
} else {
return Promise.resolve(null);
}
} else {
const {parseTemplate, templateSourceMapping} =
this._extractInlineTemplate(node, decorator, component, containingFile);
const template = parseTemplate();
this.preanalyzeTemplateCache.set(node, {...template, parseTemplate, templateSourceMapping});
return Promise.resolve(template);
}
}
private _extractExternalTemplate(
node: ClassDeclaration, component: Map<string, ts.Expression>, templateUrlExpr: ts.Expression,
resourceUrl: string): {
parseTemplate: (options?: ParseTemplateOptions) => ParsedTemplate;
templateSourceMapping: TemplateSourceMapping
} {
const templateStr = this.resourceLoader.load(resourceUrl);
this.resourceDependencies.recordResourceDependency(node.getSourceFile(), resourceUrl);
const parseTemplate = (options?: ParseTemplateOptions) => this._parseTemplate(
component, templateStr, sourceMapUrl(resourceUrl),
/* templateRange */ undefined,
/* escapedString */ false, options);
const templateSourceMapping: TemplateSourceMapping = {
type: 'external',
componentClass: node,
node: templateUrlExpr,
template: templateStr,
templateUrl: resourceUrl,
};
return {parseTemplate, templateSourceMapping};
}
private _extractInlineTemplate(
node: ClassDeclaration, decorator: Decorator, component: Map<string, ts.Expression>,
containingFile: string): {
parseTemplate: (options?: ParseTemplateOptions) => ParsedTemplate;
templateSourceMapping: TemplateSourceMapping
} {
if (!component.has('template')) {
throw new FatalDiagnosticError(
ErrorCode.COMPONENT_MISSING_TEMPLATE, Decorator.nodeForError(decorator),
'component is missing a template');
}
const templateExpr = component.get('template') !;
let templateStr: string;
let templateUrl: string = '';
let templateRange: LexerRange|undefined = undefined;
let templateSourceMapping: TemplateSourceMapping;
let escapedString = false;
// We only support SourceMaps for inline templates that are simple string literals.
if (ts.isStringLiteral(templateExpr) || ts.isNoSubstitutionTemplateLiteral(templateExpr)) {
// the start and end of the `templateExpr` node includes the quotation marks, which we
// must
// strip
templateRange = getTemplateRange(templateExpr);
templateStr = templateExpr.getSourceFile().text;
templateUrl = containingFile;
escapedString = true;
templateSourceMapping = {
type: 'direct',
node: templateExpr as(ts.StringLiteral | ts.NoSubstitutionTemplateLiteral),
};
} else {
const resolvedTemplate = this.evaluator.evaluate(templateExpr);
if (typeof resolvedTemplate !== 'string') {
throw new FatalDiagnosticError(
ErrorCode.VALUE_HAS_WRONG_TYPE, templateExpr, 'template must be a string');
}
templateStr = resolvedTemplate;
templateSourceMapping = {
type: 'indirect',
node: templateExpr,
componentClass: node,
template: templateStr,
};
}
const parseTemplate = (options?: ParseTemplateOptions) => this._parseTemplate(
component, templateStr, templateUrl, templateRange, escapedString, options);
return {parseTemplate, templateSourceMapping};
}
private _parseTemplate(
component: Map<string, ts.Expression>, templateStr: string, templateUrl: string,
templateRange: LexerRange|undefined, escapedString: boolean,
options: ParseTemplateOptions = {}): ParsedTemplate {
let preserveWhitespaces: boolean = this.defaultPreserveWhitespaces;
if (component.has('preserveWhitespaces')) {
const expr = component.get('preserveWhitespaces') !;
const value = this.evaluator.evaluate(expr);
if (typeof value !== 'boolean') {
throw new FatalDiagnosticError(
ErrorCode.VALUE_HAS_WRONG_TYPE, expr, 'preserveWhitespaces must be a boolean');
}
preserveWhitespaces = value;
}
let interpolation: InterpolationConfig = DEFAULT_INTERPOLATION_CONFIG;
if (component.has('interpolation')) {
const expr = component.get('interpolation') !;
const value = this.evaluator.evaluate(expr);
if (!Array.isArray(value) || value.length !== 2 ||
!value.every(element => typeof element === 'string')) {
throw new FatalDiagnosticError(
ErrorCode.VALUE_HAS_WRONG_TYPE, expr,
'interpolation must be an array with 2 elements of string type');
}
interpolation = InterpolationConfig.fromArray(value as[string, string]);
}
return {
interpolation,
...parseTemplate(templateStr, templateUrl, {
preserveWhitespaces,
interpolationConfig: interpolation,
range: templateRange, escapedString,
i18nLegacyMessageIdFormat: this.i18nLegacyMessageIdFormat, ...options,
}),
template: templateStr, templateUrl,
isInline: component.has('template'),
file: new ParseSourceFile(templateStr, templateUrl),
};
}
private _expressionToImportedFile(expr: Expression, origin: ts.SourceFile): ts.SourceFile|null {
if (!(expr instanceof ExternalExpr)) {
return null;
}
// Figure out what file is being imported.
return this.moduleResolver.resolveModuleName(expr.value.moduleName !, origin);
}
private _isCyclicImport(expr: Expression, origin: ts.SourceFile): boolean {
const imported = this._expressionToImportedFile(expr, origin);
if (imported === null) {
return false;
}
// Check whether the import is legal.
return this.cycleAnalyzer.wouldCreateCycle(origin, imported);
}
private _recordSyntheticImport(expr: Expression, origin: ts.SourceFile): void {
const imported = this._expressionToImportedFile(expr, origin);
if (imported === null) {
return;
}
this.cycleAnalyzer.recordSyntheticImport(origin, imported);
}
}
function getTemplateRange(templateExpr: ts.Expression) {
const startPos = templateExpr.getStart() + 1;
const {line, character} =
ts.getLineAndCharacterOfPosition(templateExpr.getSourceFile(), startPos);
return {
startPos,
startLine: line,
startCol: character,
endPos: templateExpr.getEnd() - 1,
};
}
function sourceMapUrl(resourceUrl: string): string {
if (!tsSourceMapBug29300Fixed()) {
// By removing the template URL we are telling the translator not to try to
// map the external source file to the generated code, since the version
// of TS that is running does not support it.
return '';
} else {
return resourceUrl;
}
}
/**
* Information about the template which was extracted during parsing.
*
* This contains the actual parsed template as well as any metadata collected during its parsing,
* some of which might be useful for re-parsing the template with different options.
*/
export interface ParsedTemplate {
/**
* The `InterpolationConfig` specified by the user.
*/
interpolation: InterpolationConfig;
/**
* A full path to the file which contains the template.
*
* This can be either the original .ts file if the template is inline, or the .html file if an
* external file was used.
*/
templateUrl: string;
/**
* The string contents of the template.
*
* This is the "logical" template string, after expansion of any escaped characters (for inline
* templates). This may differ from the actual template bytes as they appear in the .ts file.
*/
template: string;
/**
* Any errors from parsing the template the first time.
*/
errors?: ParseError[]|undefined;
/**
* The actual parsed template nodes.
*/
nodes: TmplAstNode[];
/**
* Any styleUrls extracted from the metadata.
*/
styleUrls: string[];
/**
* Any inline styles extracted from the metadata.
*/
styles: string[];
/**
* Whether the template was inline.
*/
isInline: boolean;
/**
* The `ParseSourceFile` for the template.
*/
file: ParseSourceFile;
}
interface PreanalyzedTemplate extends ParsedTemplate {
parseTemplate: (options?: ParseTemplateOptions) => ParsedTemplate;
templateSourceMapping: TemplateSourceMapping;
}