-
Notifications
You must be signed in to change notification settings - Fork 24.8k
/
resources.ts
757 lines (694 loc) Β· 24.9 KB
/
resources.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
/**
* @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 {
DEFAULT_INTERPOLATION_CONFIG,
InterpolationConfig,
LexerRange,
ParsedTemplate,
ParseSourceFile,
parseTemplate,
TmplAstNode,
} from '@angular/compiler';
import ts from 'typescript';
import {ErrorCode, FatalDiagnosticError} from '../../../diagnostics';
import {absoluteFrom} from '../../../file_system';
import {DependencyTracker} from '../../../incremental/api';
import {Resource} from '../../../metadata';
import {DynamicValue, PartialEvaluator, traceDynamicValue} from '../../../partial_evaluator';
import {ClassDeclaration, DeclarationNode, Decorator} from '../../../reflection';
import {CompilationMode} from '../../../transform';
import {TemplateSourceMapping} from '../../../typecheck/api';
import {
createValueHasWrongTypeError,
isStringArray,
ResourceLoader,
assertLocalCompilationUnresolvedConst,
} from '../../common';
/**
* 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,
}
/**
* 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 ParsedComponentTemplate extends ParsedTemplate {
/**
* The template AST, parsed in a manner which preserves source map information for diagnostics.
*
* Not useful for emit.
*/
diagNodes: TmplAstNode[];
/**
* The `ParseSourceFile` for the template.
*/
file: ParseSourceFile;
}
export interface ParsedTemplateWithSource extends ParsedComponentTemplate {
/** The string contents of the template. */
content: string;
sourceMapping: TemplateSourceMapping;
declaration: TemplateDeclaration;
}
/**
* Common fields extracted from the declaration of a template.
*/
interface CommonTemplateDeclaration {
preserveWhitespaces: boolean;
interpolationConfig: InterpolationConfig;
templateUrl: string;
resolvedTemplateUrl: string;
}
/**
* Information extracted from the declaration of an inline template.
*/
export interface InlineTemplateDeclaration extends CommonTemplateDeclaration {
isInline: true;
expression: ts.Expression;
}
/**
* Information extracted from the declaration of an external template.
*/
export interface ExternalTemplateDeclaration extends CommonTemplateDeclaration {
isInline: false;
templateUrlExpression: ts.Expression;
}
/**
* The declaration of a template extracted from a component decorator.
*
* This data is extracted and stored separately to facilitate re-interpreting the template
* declaration whenever the compiler is notified of a change to a template file. With this
* information, `ComponentDecoratorHandler` is able to re-read the template and update the component
* record without needing to parse the original decorator again.
*/
export type TemplateDeclaration = InlineTemplateDeclaration | ExternalTemplateDeclaration;
/** Determines the node to use for debugging purposes for the given TemplateDeclaration. */
export function getTemplateDeclarationNodeForError(declaration: TemplateDeclaration): ts.Node {
return declaration.isInline ? declaration.expression : declaration.templateUrlExpression;
}
export interface ExtractTemplateOptions {
usePoisonedData: boolean;
enableI18nLegacyMessageIdFormat: boolean;
i18nNormalizeLineEndingsInICUs: boolean;
enableBlockSyntax: boolean;
}
export function extractTemplate(
node: ClassDeclaration,
template: TemplateDeclaration,
evaluator: PartialEvaluator,
depTracker: DependencyTracker | null,
resourceLoader: ResourceLoader,
options: ExtractTemplateOptions,
compilationMode: CompilationMode,
): ParsedTemplateWithSource {
if (template.isInline) {
let sourceStr: string;
let sourceParseRange: LexerRange | null = null;
let templateContent: string;
let sourceMapping: TemplateSourceMapping;
let escapedString = false;
let sourceMapUrl: string | null;
// We only support SourceMaps for inline templates that are simple string literals.
if (
ts.isStringLiteral(template.expression) ||
ts.isNoSubstitutionTemplateLiteral(template.expression)
) {
// the start and end of the `templateExpr` node includes the quotation marks, which we must
// strip
sourceParseRange = getTemplateRange(template.expression);
sourceStr = template.expression.getSourceFile().text;
templateContent = template.expression.text;
escapedString = true;
sourceMapping = {
type: 'direct',
node: template.expression,
};
sourceMapUrl = template.resolvedTemplateUrl;
} else {
const resolvedTemplate = evaluator.evaluate(template.expression);
// The identifier used for @Component.template cannot be resolved in local compilation mode. An error specific to this situation is generated.
assertLocalCompilationUnresolvedConst(
compilationMode,
resolvedTemplate,
template.expression,
'Unresolved identifier found for @Component.template field! ' +
'Did you import this identifier from a file outside of the compilation unit? ' +
'This is not allowed when Angular compiler runs in local mode. ' +
'Possible solutions: 1) Move the declaration into a file within the ' +
'compilation unit, 2) Inline the template, 3) Move the template into ' +
'a separate .html file and include it using @Component.templateUrl',
);
if (typeof resolvedTemplate !== 'string') {
throw createValueHasWrongTypeError(
template.expression,
resolvedTemplate,
'template must be a string',
);
}
// We do not parse the template directly from the source file using a lexer range, so
// the template source and content are set to the statically resolved template.
sourceStr = resolvedTemplate;
templateContent = resolvedTemplate;
sourceMapping = {
type: 'indirect',
node: template.expression,
componentClass: node,
template: templateContent,
};
// Indirect templates cannot be mapped to a particular byte range of any input file, since
// they're computed by expressions that may span many files. Don't attempt to map them back
// to a given file.
sourceMapUrl = null;
}
return {
...parseExtractedTemplate(
template,
sourceStr,
sourceParseRange,
escapedString,
sourceMapUrl,
options,
),
content: templateContent,
sourceMapping,
declaration: template,
};
} else {
const templateContent = resourceLoader.load(template.resolvedTemplateUrl);
if (depTracker !== null) {
depTracker.addResourceDependency(
node.getSourceFile(),
absoluteFrom(template.resolvedTemplateUrl),
);
}
return {
...parseExtractedTemplate(
template,
/* sourceStr */ templateContent,
/* sourceParseRange */ null,
/* escapedString */ false,
/* sourceMapUrl */ template.resolvedTemplateUrl,
options,
),
content: templateContent,
sourceMapping: {
type: 'external',
componentClass: node,
node: template.templateUrlExpression,
template: templateContent,
templateUrl: template.resolvedTemplateUrl,
},
declaration: template,
};
}
}
function parseExtractedTemplate(
template: TemplateDeclaration,
sourceStr: string,
sourceParseRange: LexerRange | null,
escapedString: boolean,
sourceMapUrl: string | null,
options: ExtractTemplateOptions,
): ParsedComponentTemplate {
// We always normalize line endings if the template has been escaped (i.e. is inline).
const i18nNormalizeLineEndingsInICUs = escapedString || options.i18nNormalizeLineEndingsInICUs;
const parsedTemplate = parseTemplate(sourceStr, sourceMapUrl ?? '', {
preserveWhitespaces: template.preserveWhitespaces,
interpolationConfig: template.interpolationConfig,
range: sourceParseRange ?? undefined,
escapedString,
enableI18nLegacyMessageIdFormat: options.enableI18nLegacyMessageIdFormat,
i18nNormalizeLineEndingsInICUs,
alwaysAttemptHtmlToR3AstConversion: options.usePoisonedData,
enableBlockSyntax: options.enableBlockSyntax,
});
// Unfortunately, the primary parse of the template above may not contain accurate source map
// information. If used directly, it would result in incorrect code locations in template
// errors, etc. There are three main problems:
//
// 1. `preserveWhitespaces: false` annihilates the correctness of template source mapping, as
// the whitespace transformation changes the contents of HTML text nodes before they're
// parsed into Angular expressions.
// 2. `preserveLineEndings: false` causes growing misalignments in templates that use '\r\n'
// line endings, by normalizing them to '\n'.
// 3. By default, the template parser strips leading trivia characters (like spaces, tabs, and
// newlines). This also destroys source mapping information.
//
// In order to guarantee the correctness of diagnostics, templates are parsed a second time
// with the above options set to preserve source mappings.
const {nodes: diagNodes} = parseTemplate(sourceStr, sourceMapUrl ?? '', {
preserveWhitespaces: true,
preserveLineEndings: true,
interpolationConfig: template.interpolationConfig,
range: sourceParseRange ?? undefined,
escapedString,
enableI18nLegacyMessageIdFormat: options.enableI18nLegacyMessageIdFormat,
i18nNormalizeLineEndingsInICUs,
leadingTriviaChars: [],
alwaysAttemptHtmlToR3AstConversion: options.usePoisonedData,
enableBlockSyntax: options.enableBlockSyntax,
});
return {
...parsedTemplate,
diagNodes,
file: new ParseSourceFile(sourceStr, sourceMapUrl ?? ''),
};
}
export function parseTemplateDeclaration(
node: ClassDeclaration,
decorator: Decorator,
component: Map<string, ts.Expression>,
containingFile: string,
evaluator: PartialEvaluator,
depTracker: DependencyTracker | null,
resourceLoader: ResourceLoader,
defaultPreserveWhitespaces: boolean,
): TemplateDeclaration {
let preserveWhitespaces: boolean = defaultPreserveWhitespaces;
if (component.has('preserveWhitespaces')) {
const expr = component.get('preserveWhitespaces')!;
const value = evaluator.evaluate(expr);
if (typeof value !== 'boolean') {
throw createValueHasWrongTypeError(expr, value, 'preserveWhitespaces must be a boolean');
}
preserveWhitespaces = value;
}
let interpolationConfig = DEFAULT_INTERPOLATION_CONFIG;
if (component.has('interpolation')) {
const expr = component.get('interpolation')!;
const value = evaluator.evaluate(expr);
if (
!Array.isArray(value) ||
value.length !== 2 ||
!value.every((element) => typeof element === 'string')
) {
throw createValueHasWrongTypeError(
expr,
value,
'interpolation must be an array with 2 elements of string type',
);
}
interpolationConfig = InterpolationConfig.fromArray(value as [string, string]);
}
if (component.has('templateUrl')) {
const templateUrlExpr = component.get('templateUrl')!;
const templateUrl = evaluator.evaluate(templateUrlExpr);
if (typeof templateUrl !== 'string') {
throw createValueHasWrongTypeError(
templateUrlExpr,
templateUrl,
'templateUrl must be a string',
);
}
try {
const resourceUrl = resourceLoader.resolve(templateUrl, containingFile);
return {
isInline: false,
interpolationConfig,
preserveWhitespaces,
templateUrl,
templateUrlExpression: templateUrlExpr,
resolvedTemplateUrl: resourceUrl,
};
} catch (e) {
if (depTracker !== null) {
// The analysis of this file cannot be re-used if the template URL could
// not be resolved. Future builds should re-analyze and re-attempt resolution.
depTracker.recordDependencyAnalysisFailure(node.getSourceFile());
}
throw makeResourceNotFoundError(
templateUrl,
templateUrlExpr,
ResourceTypeForDiagnostics.Template,
);
}
} else if (component.has('template')) {
return {
isInline: true,
interpolationConfig,
preserveWhitespaces,
expression: component.get('template')!,
templateUrl: containingFile,
resolvedTemplateUrl: containingFile,
};
} else {
throw new FatalDiagnosticError(
ErrorCode.COMPONENT_MISSING_TEMPLATE,
decorator.node,
'component is missing a template',
);
}
}
export function preloadAndParseTemplate(
evaluator: PartialEvaluator,
resourceLoader: ResourceLoader,
depTracker: DependencyTracker | null,
preanalyzeTemplateCache: Map<DeclarationNode, ParsedTemplateWithSource>,
node: ClassDeclaration,
decorator: Decorator,
component: Map<string, ts.Expression>,
containingFile: string,
defaultPreserveWhitespaces: boolean,
options: ExtractTemplateOptions,
compilationMode: CompilationMode,
): Promise<ParsedTemplateWithSource | null> {
if (component.has('templateUrl')) {
// Extract the templateUrl and preload it.
const templateUrlExpr = component.get('templateUrl')!;
const templateUrl = evaluator.evaluate(templateUrlExpr);
if (typeof templateUrl !== 'string') {
throw createValueHasWrongTypeError(
templateUrlExpr,
templateUrl,
'templateUrl must be a string',
);
}
try {
const resourceUrl = resourceLoader.resolve(templateUrl, containingFile);
const templatePromise = resourceLoader.preload(resourceUrl, {
type: 'template',
containingFile,
});
// 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 templateDecl = parseTemplateDeclaration(
node,
decorator,
component,
containingFile,
evaluator,
depTracker,
resourceLoader,
defaultPreserveWhitespaces,
);
const template = extractTemplate(
node,
templateDecl,
evaluator,
depTracker,
resourceLoader,
options,
compilationMode,
);
preanalyzeTemplateCache.set(node, template);
return template;
});
} else {
return Promise.resolve(null);
}
} catch (e) {
if (depTracker !== null) {
// The analysis of this file cannot be re-used if the template URL could
// not be resolved. Future builds should re-analyze and re-attempt resolution.
depTracker.recordDependencyAnalysisFailure(node.getSourceFile());
}
throw makeResourceNotFoundError(
templateUrl,
templateUrlExpr,
ResourceTypeForDiagnostics.Template,
);
}
} else {
const templateDecl = parseTemplateDeclaration(
node,
decorator,
component,
containingFile,
evaluator,
depTracker,
resourceLoader,
defaultPreserveWhitespaces,
);
const template = extractTemplate(
node,
templateDecl,
evaluator,
depTracker,
resourceLoader,
options,
compilationMode,
);
preanalyzeTemplateCache.set(node, template);
return Promise.resolve(template);
}
}
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,
};
}
export function makeResourceNotFoundError(
file: string,
nodeForError: ts.Node,
resourceType: ResourceTypeForDiagnostics,
): FatalDiagnosticError {
let errorText: string;
switch (resourceType) {
case ResourceTypeForDiagnostics.Template:
errorText = `Could not find template file '${file}'.`;
break;
case ResourceTypeForDiagnostics.StylesheetFromTemplate:
errorText = `Could not find stylesheet file '${file}' linked from the template.`;
break;
case ResourceTypeForDiagnostics.StylesheetFromDecorator:
errorText = `Could not find stylesheet file '${file}'.`;
break;
}
return new FatalDiagnosticError(ErrorCode.COMPONENT_RESOURCE_NOT_FOUND, nodeForError, errorText);
}
/**
* Transforms the given decorator to inline external resources. i.e. if the decorator
* resolves to `@Component`, the `templateUrl` and `styleUrls` metadata fields will be
* transformed to their semantically-equivalent inline variants.
*
* This method is used for serializing decorators into the class metadata. The emitted
* class metadata should not refer to external resources as this would be inconsistent
* with the component definitions/declarations which already inline external resources.
*
* Additionally, the references to external resources would require libraries to ship
* external resources exclusively for the class metadata.
*/
export function transformDecoratorResources(
dec: Decorator,
component: Map<string, ts.Expression>,
styles: string[],
template: ParsedTemplateWithSource,
): Decorator {
if (dec.name !== 'Component') {
return dec;
}
// If no external resources are referenced, preserve the original decorator
// for the best source map experience when the decorator is emitted in TS.
if (
!component.has('templateUrl') &&
!component.has('styleUrls') &&
!component.has('styleUrl') &&
!component.has('styles')
) {
return dec;
}
const metadata = new Map(component);
// Set the `template` property if the `templateUrl` property is set.
if (metadata.has('templateUrl')) {
metadata.delete('templateUrl');
metadata.set('template', ts.factory.createStringLiteral(template.content));
}
if (metadata.has('styleUrls') || metadata.has('styleUrl') || metadata.has('styles')) {
metadata.delete('styles');
metadata.delete('styleUrls');
metadata.delete('styleUrl');
if (styles.length > 0) {
const styleNodes = styles.reduce((result, style) => {
if (style.trim().length > 0) {
result.push(ts.factory.createStringLiteral(style));
}
return result;
}, [] as ts.StringLiteral[]);
if (styleNodes.length > 0) {
metadata.set('styles', ts.factory.createArrayLiteralExpression(styleNodes));
}
}
}
// Convert the metadata to TypeScript AST object literal element nodes.
const newMetadataFields: ts.ObjectLiteralElementLike[] = [];
for (const [name, value] of metadata.entries()) {
newMetadataFields.push(ts.factory.createPropertyAssignment(name, value));
}
// Return the original decorator with the overridden metadata argument.
return {...dec, args: [ts.factory.createObjectLiteralExpression(newMetadataFields)]};
}
export function extractComponentStyleUrls(
evaluator: PartialEvaluator,
component: Map<string, ts.Expression>,
): StyleUrlMeta[] {
const styleUrlsExpr = component.get('styleUrls');
const styleUrlExpr = component.get('styleUrl');
if (styleUrlsExpr !== undefined && styleUrlExpr !== undefined) {
throw new FatalDiagnosticError(
ErrorCode.COMPONENT_INVALID_STYLE_URLS,
styleUrlExpr,
'@Component cannot define both `styleUrl` and `styleUrls`. ' +
'Use `styleUrl` if the component has one stylesheet, or `styleUrls` if it has multiple',
);
}
if (styleUrlsExpr !== undefined) {
return extractStyleUrlsFromExpression(evaluator, component.get('styleUrls')!);
}
if (styleUrlExpr !== undefined) {
const styleUrl = evaluator.evaluate(styleUrlExpr);
if (typeof styleUrl !== 'string') {
throw createValueHasWrongTypeError(styleUrlExpr, styleUrl, 'styleUrl must be a string');
}
return [
{
url: styleUrl,
source: ResourceTypeForDiagnostics.StylesheetFromDecorator,
nodeForError: styleUrlExpr,
},
];
}
return [];
}
function extractStyleUrlsFromExpression(
evaluator: PartialEvaluator,
styleUrlsExpr: ts.Expression,
): StyleUrlMeta[] {
const styleUrls: StyleUrlMeta[] = [];
if (ts.isArrayLiteralExpression(styleUrlsExpr)) {
for (const styleUrlExpr of styleUrlsExpr.elements) {
if (ts.isSpreadElement(styleUrlExpr)) {
styleUrls.push(...extractStyleUrlsFromExpression(evaluator, styleUrlExpr.expression));
} else {
const styleUrl = 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 = evaluator.evaluate(styleUrlsExpr);
if (!isStringArray(evaluatedStyleUrls)) {
throw createValueHasWrongTypeError(
styleUrlsExpr,
evaluatedStyleUrls,
'styleUrls must be an array of strings',
);
}
for (const styleUrl of evaluatedStyleUrls) {
styleUrls.push({
url: styleUrl,
source: ResourceTypeForDiagnostics.StylesheetFromDecorator,
nodeForError: styleUrlsExpr,
});
}
}
return styleUrls;
}
export function extractStyleResources(
resourceLoader: ResourceLoader,
component: Map<string, ts.Expression>,
containingFile: string,
): ReadonlySet<Resource> {
const styles = new Set<Resource>();
function stringLiteralElements(array: ts.ArrayLiteralExpression): ts.StringLiteralLike[] {
return array.elements.filter((e): e is ts.StringLiteralLike => ts.isStringLiteralLike(e));
}
// If styleUrls is a literal array, process each resource url individually and register ones that
// are string literals. If `styleUrl` is specified, register a single stylesheet. Note that
// `styleUrl` and `styleUrls` are mutually-exclusive. This is validated in
// `extractComponentStyleUrls`.
const styleUrlExpr = component.get('styleUrl');
const styleUrlsExpr = component.get('styleUrls');
if (styleUrlsExpr !== undefined && ts.isArrayLiteralExpression(styleUrlsExpr)) {
for (const expression of stringLiteralElements(styleUrlsExpr)) {
const resource = stringLiteralUrlToResource(resourceLoader, expression, containingFile);
if (resource !== null) {
styles.add(resource);
}
}
} else if (styleUrlExpr !== undefined && ts.isStringLiteralLike(styleUrlExpr)) {
const resource = stringLiteralUrlToResource(resourceLoader, styleUrlExpr, containingFile);
if (resource !== null) {
styles.add(resource);
}
}
const stylesExpr = component.get('styles');
if (stylesExpr !== undefined) {
if (ts.isArrayLiteralExpression(stylesExpr)) {
for (const expression of stringLiteralElements(stylesExpr)) {
styles.add({path: null, expression});
}
} else if (ts.isStringLiteralLike(stylesExpr)) {
styles.add({path: null, expression: stylesExpr});
}
}
return styles;
}
function stringLiteralUrlToResource(
resourceLoader: ResourceLoader,
expression: ts.StringLiteralLike,
containingFile: string,
): Resource | null {
try {
const resourceUrl = resourceLoader.resolve(expression.text, containingFile);
return {path: absoluteFrom(resourceUrl), expression};
} catch {
// Errors in style resource extraction do not need to be handled here. We will produce
// diagnostics for each one that fails in the analysis, after we evaluate the `styleUrls`
// expression to determine _all_ style resources, not just the string literals.
return null;
}
}
export function _extractTemplateStyleUrls(template: ParsedTemplateWithSource): StyleUrlMeta[] {
if (template.styleUrls === null) {
return [];
}
const nodeForError = getTemplateDeclarationNodeForError(template.declaration);
return template.styleUrls.map((url) => ({
url,
source: ResourceTypeForDiagnostics.StylesheetFromTemplate,
nodeForError,
}));
}