-
Notifications
You must be signed in to change notification settings - Fork 24.8k
/
shared.ts
1321 lines (1146 loc) Β· 52.4 KB
/
shared.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 {createMayBeForwardRefExpression, emitDistinctChangesOnlyDefaultValue, Expression, ExternalExpr, ForwardRefHandling, getSafePropertyAccessString, MaybeForwardRefExpression, ParsedHostBindings, ParseError, parseHostBindings, R3DirectiveMetadata, R3HostDirectiveMetadata, R3InputMetadata, R3QueryMetadata, R3Reference, verifyHostBindings, WrappedNodeExpr} from '@angular/compiler';
import ts from 'typescript';
import {ErrorCode, FatalDiagnosticError, makeRelatedInformation} from '../../../diagnostics';
import {assertSuccessfulReferenceEmit, ImportFlags, Reference, ReferenceEmitter} from '../../../imports';
import {ClassPropertyMapping, DecoratorInputTransform, HostDirectiveMeta, InputMapping, InputOrOutput, isHostDirectiveMetaForGlobalMode} from '../../../metadata';
import {DynamicValue, EnumValue, PartialEvaluator, ResolvedValue, traceDynamicValue} from '../../../partial_evaluator';
import {AmbientImport, ClassDeclaration, ClassMember, ClassMemberKind, Decorator, filterToMembersWithDecorator, isNamedClassDeclaration, ReflectionHost, reflectObjectLiteral} from '../../../reflection';
import {CompilationMode} from '../../../transform';
import {createSourceSpan, createValueHasWrongTypeError, forwardRefResolver, getAngularDecorators, getConstructorDependencies, isAngularDecorator, ReferencesRegistry, toR3Reference, tryUnwrapForwardRef, unwrapConstructorDependencies, unwrapExpression, validateConstructorDependencies, assertLocalCompilationUnresolvedConst, wrapFunctionExpressionsInParens, wrapTypeReference} from '../../common';
import {tryParseSignalInputMapping} from './input_function';
import {tryParseInitializerBasedOutput} from './output_function';
import {tryParseSignalQueryFromInitializer} from './query_functions';
const EMPTY_OBJECT: {[key: string]: string} = {};
type QueryDecoratorName = 'ViewChild'|'ViewChildren'|'ContentChild'|'ContentChildren';
export const queryDecoratorNames: QueryDecoratorName[] =
['ViewChild', 'ViewChildren', 'ContentChild', 'ContentChildren'];
const QUERY_TYPES = new Set<string>(queryDecoratorNames);
/**
* Helper function to extract metadata from a `Directive` or `Component`. `Directive`s without a
* selector are allowed to be used for abstract base classes. These abstract directives should not
* appear in the declarations of an `NgModule` and additional verification is done when processing
* the module.
*/
export function extractDirectiveMetadata(
clazz: ClassDeclaration, decorator: Readonly<Decorator>, reflector: ReflectionHost,
evaluator: PartialEvaluator, refEmitter: ReferenceEmitter,
referencesRegistry: ReferencesRegistry, isCore: boolean, annotateForClosureCompiler: boolean,
compilationMode: CompilationMode, defaultSelector: string|null, useTemplatePipeline: boolean): {
decorator: Map<string, ts.Expression>,
metadata: R3DirectiveMetadata,
inputs: ClassPropertyMapping<InputMapping>,
outputs: ClassPropertyMapping,
isStructural: boolean;
hostDirectives: HostDirectiveMeta[] | null, rawHostDirectives: ts.Expression | null,
}|undefined {
let directive: Map<string, ts.Expression>;
if (decorator.args === null || decorator.args.length === 0) {
directive = new Map<string, ts.Expression>();
} else if (decorator.args.length !== 1) {
throw new FatalDiagnosticError(
ErrorCode.DECORATOR_ARITY_WRONG, decorator.node,
`Incorrect number of arguments to @${decorator.name} decorator`);
} else {
const meta = unwrapExpression(decorator.args[0]);
if (!ts.isObjectLiteralExpression(meta)) {
throw new FatalDiagnosticError(
ErrorCode.DECORATOR_ARG_NOT_LITERAL, meta,
`@${decorator.name} argument must be an object literal`);
}
directive = reflectObjectLiteral(meta);
}
if (directive.has('jit')) {
// The only allowed value is true, so there's no need to expand further.
return undefined;
}
const members = reflector.getMembersOfClass(clazz);
// Precompute a list of ts.ClassElements that have decorators. This includes things like @Input,
// @Output, @HostBinding, etc.
const decoratedElements =
members.filter(member => !member.isStatic && member.decorators !== null);
const coreModule = isCore ? undefined : '@angular/core';
// Construct the map of inputs both from the @Directive/@Component
// decorator, and the decorated fields.
const inputsFromMeta =
parseInputsArray(clazz, directive, evaluator, reflector, refEmitter, compilationMode);
const inputsFromFields = parseInputFields(
clazz, members, evaluator, reflector, refEmitter, isCore, compilationMode, inputsFromMeta,
decorator);
const inputs = ClassPropertyMapping.fromMappedObject({...inputsFromMeta, ...inputsFromFields});
// And outputs.
const outputsFromMeta = parseOutputsArray(directive, evaluator);
const outputsFromFields =
parseOutputFields(clazz, decorator, members, isCore, reflector, evaluator, outputsFromMeta);
const outputs = ClassPropertyMapping.fromMappedObject({...outputsFromMeta, ...outputsFromFields});
// Parse queries of fields.
const {viewQueries, contentQueries} =
parseQueriesOfClassFields(members, reflector, evaluator, isCore);
if (directive.has('queries')) {
const signalQueryFields = new Set(
[...viewQueries, ...contentQueries].filter(q => q.isSignal).map(q => q.propertyName));
const queriesFromDecorator =
extractQueriesFromDecorator(directive.get('queries')!, reflector, evaluator, isCore);
// Checks if the query is already declared/reserved via class members declaration.
// If so, we throw a fatal diagnostic error to prevent this unintentional pattern.
const checkAndUnwrapQuery = (q: {expr: ts.Expression, metadata: R3QueryMetadata}) => {
if (signalQueryFields.has(q.metadata.propertyName)) {
throw new FatalDiagnosticError(
ErrorCode.INITIALIZER_API_DECORATOR_METADATA_COLLISION, q.expr,
`Query is declared multiple times. "@${
decorator.name}" declares a query for the same property.`);
}
return q.metadata;
};
contentQueries.push(...queriesFromDecorator.content.map(q => checkAndUnwrapQuery(q)));
viewQueries.push(...queriesFromDecorator.view.map(q => checkAndUnwrapQuery(q)));
}
// Parse the selector.
let selector = defaultSelector;
if (directive.has('selector')) {
const expr = directive.get('selector')!;
const resolved = evaluator.evaluate(expr);
assertLocalCompilationUnresolvedConst(compilationMode, resolved, null,
'Unresolved identifier found for @Component.selector 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 declarations into a file within the compilation ' +
'unit, 2) Inline the selector');
if (typeof resolved !== 'string') {
throw createValueHasWrongTypeError(expr, resolved, `selector must be a string`);
}
// use default selector in case selector is an empty string
selector = resolved === '' ? defaultSelector : resolved;
if (!selector) {
throw new FatalDiagnosticError(
ErrorCode.DIRECTIVE_MISSING_SELECTOR, expr,
`Directive ${clazz.name.text} has no selector, please add it!`);
}
}
const host = extractHostBindings(decoratedElements, evaluator, coreModule, compilationMode, directive);
const providers: Expression|null = directive.has('providers') ?
new WrappedNodeExpr(
annotateForClosureCompiler ?
wrapFunctionExpressionsInParens(directive.get('providers')!) :
directive.get('providers')!) :
null;
// Determine if `ngOnChanges` is a lifecycle hook defined on the component.
const usesOnChanges = members.some(
member => !member.isStatic && member.kind === ClassMemberKind.Method &&
member.name === 'ngOnChanges');
// Parse exportAs.
let exportAs: string[]|null = null;
if (directive.has('exportAs')) {
const expr = directive.get('exportAs')!;
const resolved = evaluator.evaluate(expr);
if (typeof resolved !== 'string') {
throw createValueHasWrongTypeError(expr, resolved, `exportAs must be a string`);
}
exportAs = resolved.split(',').map(part => part.trim());
}
const rawCtorDeps = getConstructorDependencies(clazz, reflector, isCore);
// Non-abstract directives (those with a selector) require valid constructor dependencies, whereas
// abstract directives are allowed to have invalid dependencies, given that a subclass may call
// the constructor explicitly.
const ctorDeps = selector !== null ? validateConstructorDependencies(clazz, rawCtorDeps) :
unwrapConstructorDependencies(rawCtorDeps);
// Structural directives must have a `TemplateRef` dependency.
const isStructural = ctorDeps !== null && ctorDeps !== 'invalid' &&
ctorDeps.some(
dep => (dep.token instanceof ExternalExpr) &&
dep.token.value.moduleName === '@angular/core' &&
dep.token.value.name === 'TemplateRef');
let isStandalone = false;
if (directive.has('standalone')) {
const expr = directive.get('standalone')!;
const resolved = evaluator.evaluate(expr);
if (typeof resolved !== 'boolean') {
throw createValueHasWrongTypeError(expr, resolved, `standalone flag must be a boolean`);
}
isStandalone = resolved;
}
let isSignal = false;
if (directive.has('signals')) {
const expr = directive.get('signals')!;
const resolved = evaluator.evaluate(expr);
if (typeof resolved !== 'boolean') {
throw createValueHasWrongTypeError(expr, resolved, `signals flag must be a boolean`);
}
isSignal = resolved;
}
// Detect if the component inherits from another class
const usesInheritance = reflector.hasBaseClass(clazz);
const sourceFile = clazz.getSourceFile();
const type = wrapTypeReference(reflector, clazz);
const rawHostDirectives = directive.get('hostDirectives') || null;
const hostDirectives = rawHostDirectives === null ?
null :
extractHostDirectives(rawHostDirectives, evaluator, compilationMode);
if (compilationMode !== CompilationMode.LOCAL && hostDirectives !== null) {
// In global compilation mode where we do type checking, the template type-checker will need to
// import host directive types, so add them as referenced by `clazz`. This will ensure that
// libraries are required to export host directives which are visible from publicly exported
// components.
referencesRegistry.add(clazz, ...hostDirectives.map(hostDir => {
if (!isHostDirectiveMetaForGlobalMode(hostDir)) {
throw new Error('Impossible state');
}
return hostDir.directive;
}));
}
const metadata: R3DirectiveMetadata = {
name: clazz.name.text,
deps: ctorDeps,
host: {
...host,
useTemplatePipeline,
},
lifecycle: {
usesOnChanges,
},
inputs: inputs.toJointMappedObject(toR3InputMetadata),
outputs: outputs.toDirectMappedObject(),
queries: contentQueries,
viewQueries,
selector,
fullInheritance: false,
type,
typeArgumentCount: reflector.getGenericArityOfClass(clazz) || 0,
typeSourceSpan: createSourceSpan(clazz.name),
usesInheritance,
exportAs,
providers,
isStandalone,
isSignal,
hostDirectives:
hostDirectives?.map(hostDir => toHostDirectiveMetadata(hostDir, sourceFile, refEmitter)) ||
null,
};
return {
decorator: directive,
metadata,
inputs,
outputs,
isStructural,
hostDirectives,
rawHostDirectives,
};
}
export function extractDecoratorQueryMetadata(
exprNode: ts.Node, name: string, args: ReadonlyArray<ts.Expression>, propertyName: string,
reflector: ReflectionHost, evaluator: PartialEvaluator): R3QueryMetadata {
if (args.length === 0) {
throw new FatalDiagnosticError(
ErrorCode.DECORATOR_ARITY_WRONG, exprNode, `@${name} must have arguments`);
}
const first = name === 'ViewChild' || name === 'ContentChild';
const forwardReferenceTarget = tryUnwrapForwardRef(args[0], reflector);
const node = forwardReferenceTarget ?? args[0];
const arg = evaluator.evaluate(node);
/** Whether or not this query should collect only static results (see view/api.ts) */
let isStatic: boolean = false;
// Extract the predicate
let predicate: MaybeForwardRefExpression|string[]|null = null;
if (arg instanceof Reference || arg instanceof DynamicValue) {
// References and predicates that could not be evaluated statically are emitted as is.
predicate = createMayBeForwardRefExpression(
new WrappedNodeExpr(node),
forwardReferenceTarget !== null ? ForwardRefHandling.Unwrapped : ForwardRefHandling.None);
} else if (typeof arg === 'string') {
predicate = [arg];
} else if (isStringArrayOrDie(arg, `@${name} predicate`, node)) {
predicate = arg;
} else {
throw createValueHasWrongTypeError(node, arg, `@${name} predicate cannot be interpreted`);
}
// Extract the read and descendants options.
let read: Expression|null = null;
// The default value for descendants is true for every decorator except @ContentChildren.
let descendants: boolean = name !== 'ContentChildren';
let emitDistinctChangesOnly: boolean = emitDistinctChangesOnlyDefaultValue;
if (args.length === 2) {
const optionsExpr = unwrapExpression(args[1]);
if (!ts.isObjectLiteralExpression(optionsExpr)) {
throw new FatalDiagnosticError(
ErrorCode.DECORATOR_ARG_NOT_LITERAL, optionsExpr,
`@${name} options must be an object literal`);
}
const options = reflectObjectLiteral(optionsExpr);
if (options.has('read')) {
read = new WrappedNodeExpr(options.get('read')!);
}
if (options.has('descendants')) {
const descendantsExpr = options.get('descendants')!;
const descendantsValue = evaluator.evaluate(descendantsExpr);
if (typeof descendantsValue !== 'boolean') {
throw createValueHasWrongTypeError(
descendantsExpr, descendantsValue, `@${name} options.descendants must be a boolean`);
}
descendants = descendantsValue;
}
if (options.has('emitDistinctChangesOnly')) {
const emitDistinctChangesOnlyExpr = options.get('emitDistinctChangesOnly')!;
const emitDistinctChangesOnlyValue = evaluator.evaluate(emitDistinctChangesOnlyExpr);
if (typeof emitDistinctChangesOnlyValue !== 'boolean') {
throw createValueHasWrongTypeError(
emitDistinctChangesOnlyExpr, emitDistinctChangesOnlyValue,
`@${name} options.emitDistinctChangesOnly must be a boolean`);
}
emitDistinctChangesOnly = emitDistinctChangesOnlyValue;
}
if (options.has('static')) {
const staticValue = evaluator.evaluate(options.get('static')!);
if (typeof staticValue !== 'boolean') {
throw createValueHasWrongTypeError(
node, staticValue, `@${name} options.static must be a boolean`);
}
isStatic = staticValue;
}
} else if (args.length > 2) {
// Too many arguments.
throw new FatalDiagnosticError(
ErrorCode.DECORATOR_ARITY_WRONG, node, `@${name} has too many arguments`);
}
return {
isSignal: false,
propertyName,
predicate,
first,
descendants,
read,
static: isStatic,
emitDistinctChangesOnly,
};
}
export function extractHostBindings(
members: ClassMember[], evaluator: PartialEvaluator, coreModule: string|undefined, compilationMode: CompilationMode, metadata?: Map<string, ts.Expression>): ParsedHostBindings {
let bindings: ParsedHostBindings;
if (metadata && metadata.has('host')) {
bindings = evaluateHostExpressionBindings(metadata.get('host')!, evaluator);
} else {
bindings = parseHostBindings({});
}
filterToMembersWithDecorator(members, 'HostBinding', coreModule)
.forEach(({member, decorators}) => {
decorators.forEach(decorator => {
let hostPropertyName: string = member.name;
if (decorator.args !== null && decorator.args.length > 0) {
if (decorator.args.length !== 1) {
throw new FatalDiagnosticError(
ErrorCode.DECORATOR_ARITY_WRONG, decorator.node,
`@HostBinding can have at most one argument, got ${
decorator.args.length} argument(s)`);
}
const resolved = evaluator.evaluate(decorator.args[0]);
if (typeof resolved !== 'string') {
throw createValueHasWrongTypeError(
decorator.node, resolved, `@HostBinding's argument must be a string`);
}
hostPropertyName = resolved;
}
// Since this is a decorator, we know that the value is a class member. Always access it
// through `this` so that further down the line it can't be confused for a literal value
// (e.g. if there's a property called `true`). There is no size penalty, because all
// values (except literals) are converted to `ctx.propName` eventually.
bindings.properties[hostPropertyName] = getSafePropertyAccessString('this', member.name);
});
});
filterToMembersWithDecorator(members, 'HostListener', coreModule)
.forEach(({member, decorators}) => {
decorators.forEach(decorator => {
let eventName: string = member.name;
let args: string[] = [];
if (decorator.args !== null && decorator.args.length > 0) {
if (decorator.args.length > 2) {
throw new FatalDiagnosticError(
ErrorCode.DECORATOR_ARITY_WRONG, decorator.args[2],
`@HostListener can have at most two arguments`);
}
const resolved = evaluator.evaluate(decorator.args[0]);
// Specific error for local compilation mode if the event name cannot be resolved
assertLocalCompilationUnresolvedConst(compilationMode, resolved, null,
'Unresolved identifier found for @HostListener\'s event name ' +
'argument! 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 argument');
if (typeof resolved !== 'string') {
throw createValueHasWrongTypeError(
decorator.args[0], resolved,
`@HostListener's event name argument must be a string`);
}
eventName = resolved;
if (decorator.args.length === 2) {
const expression = decorator.args[1];
const resolvedArgs = evaluator.evaluate(decorator.args[1]);
if (!isStringArrayOrDie(resolvedArgs, '@HostListener.args', expression)) {
throw createValueHasWrongTypeError(
decorator.args[1], resolvedArgs,
`@HostListener's second argument must be a string array`);
}
args = resolvedArgs;
}
}
bindings.listeners[eventName] = `${member.name}(${args.join(',')})`;
});
});
return bindings;
}
function extractQueriesFromDecorator(
queryData: ts.Expression, reflector: ReflectionHost, evaluator: PartialEvaluator,
isCore: boolean): {
content: {expr: ts.Expression, metadata: R3QueryMetadata}[],
view: {expr: ts.Expression, metadata: R3QueryMetadata}[],
} {
const content: {expr: ts.Expression, metadata: R3QueryMetadata}[] = [];
const view: {expr: ts.Expression, metadata: R3QueryMetadata}[] = [];
if (!ts.isObjectLiteralExpression(queryData)) {
throw new FatalDiagnosticError(
ErrorCode.VALUE_HAS_WRONG_TYPE, queryData,
'Decorator queries metadata must be an object literal');
}
reflectObjectLiteral(queryData).forEach((queryExpr, propertyName) => {
queryExpr = unwrapExpression(queryExpr);
if (!ts.isNewExpression(queryExpr)) {
throw new FatalDiagnosticError(
ErrorCode.VALUE_HAS_WRONG_TYPE, queryData,
'Decorator query metadata must be an instance of a query type');
}
const queryType = ts.isPropertyAccessExpression(queryExpr.expression) ?
queryExpr.expression.name :
queryExpr.expression;
if (!ts.isIdentifier(queryType)) {
throw new FatalDiagnosticError(
ErrorCode.VALUE_HAS_WRONG_TYPE, queryData,
'Decorator query metadata must be an instance of a query type');
}
const type = reflector.getImportOfIdentifier(queryType);
if (type === null || (!isCore && type.from !== '@angular/core') ||
!QUERY_TYPES.has(type.name)) {
throw new FatalDiagnosticError(
ErrorCode.VALUE_HAS_WRONG_TYPE, queryData,
'Decorator query metadata must be an instance of a query type');
}
const query = extractDecoratorQueryMetadata(
queryExpr, type.name, queryExpr.arguments || [], propertyName, reflector, evaluator);
if (type.name.startsWith('Content')) {
content.push({expr: queryExpr, metadata: query});
} else {
view.push({expr: queryExpr, metadata: query});
}
});
return {content, view};
}
export function parseDirectiveStyles(
directive: Map<string, ts.Expression>, evaluator: PartialEvaluator,
compilationMode: CompilationMode): null|string[] {
const expression = directive.get('styles');
if (!expression) {
return null;
}
const evaluated = evaluator.evaluate(expression);
const value = typeof evaluated === 'string' ? [evaluated] : evaluated;
// Check if the identifier used for @Component.styles cannot be resolved in local compilation mode. if the case, an error specific to this situation is generated.
if (compilationMode === CompilationMode.LOCAL) {
let unresolvedNode: ts.Node|null = null;
if (Array.isArray(value)) {
const entry = value.find(e => e instanceof DynamicValue && e.isFromUnknownIdentifier()) as DynamicValue|undefined;
unresolvedNode = entry?.node ?? null;
} else if (value instanceof DynamicValue && value.isFromUnknownIdentifier()) {
unresolvedNode = value.node;
}
if (unresolvedNode !== null) {
throw new FatalDiagnosticError(
ErrorCode.LOCAL_COMPILATION_UNRESOLVED_CONST,
unresolvedNode,
'Unresolved identifier found for @Component.styles 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 declarations into a file within the compilation ' +
'unit, 2) Inline the styles, 3) Move the styles into separate files and ' +
'include it using @Component.styleUrls');
}
}
if (!isStringArrayOrDie(value, 'styles', expression)) {
throw createValueHasWrongTypeError(
expression, value,
`Failed to resolve @Component.styles to a string or an array of strings`);
}
return value;
}
export function parseFieldStringArrayValue(
directive: Map<string, ts.Expression>, field: string, evaluator: PartialEvaluator): null|
string[] {
if (!directive.has(field)) {
return null;
}
// Resolve the field of interest from the directive metadata to a string[].
const expression = directive.get(field)!;
const value = evaluator.evaluate(expression);
if (!isStringArrayOrDie(value, field, expression)) {
throw createValueHasWrongTypeError(
expression, value, `Failed to resolve @Directive.${field} to a string array`);
}
return value;
}
function isStringArrayOrDie(value: any, name: string, node: ts.Expression): value is string[] {
if (!Array.isArray(value)) {
return false;
}
for (let i = 0; i < value.length; i++) {
if (typeof value[i] !== 'string') {
throw createValueHasWrongTypeError(
node, value[i], `Failed to resolve ${name} at position ${i} to a string`);
}
}
return true;
}
function tryGetQueryFromFieldDecorator(
member: ClassMember, reflector: ReflectionHost, evaluator: PartialEvaluator, isCore: boolean):
{name: QueryDecoratorName, decorator: Decorator, metadata: R3QueryMetadata}|null {
const decorators = member.decorators;
if (decorators === null) {
return null;
}
const queryDecorators = getAngularDecorators(decorators, queryDecoratorNames, isCore);
if (queryDecorators.length === 0) {
return null;
}
if (queryDecorators.length !== 1) {
throw new FatalDiagnosticError(
ErrorCode.DECORATOR_COLLISION, member.node ?? queryDecorators[0].node,
'Cannot combine multiple query decorators.');
}
const decorator = queryDecorators[0];
const node = member.node || decorator.node;
// Throw in case of `@Input() @ContentChild('foo') foo: any`, which is not supported in Ivy
if (decorators.some(v => v.name === 'Input')) {
throw new FatalDiagnosticError(
ErrorCode.DECORATOR_COLLISION, node,
'Cannot combine @Input decorators with query decorators');
}
if (!isPropertyTypeMember(member)) {
throw new FatalDiagnosticError(
ErrorCode.DECORATOR_UNEXPECTED, node, 'Query decorator must go on a property-type member');
}
// Either the decorator was aliased, or is referenced directly with
// the proper query name.
const name = (decorator.import?.name ?? decorator.name) as QueryDecoratorName;
return {
name,
decorator,
metadata: extractDecoratorQueryMetadata(
node, name, decorator.args || [], member.name, reflector, evaluator),
};
}
function isPropertyTypeMember(member: ClassMember): boolean {
return member.kind === ClassMemberKind.Getter || member.kind === ClassMemberKind.Setter ||
member.kind === ClassMemberKind.Property;
}
function parseMappingStringArray(values: string[]) {
return values.reduce((results, value) => {
if (typeof value !== 'string') {
throw new Error('Mapping value must be a string');
}
const [bindingPropertyName, fieldName] = parseMappingString(value);
results[fieldName] = bindingPropertyName;
return results;
}, {} as {[field: string]: string});
}
function parseMappingString(value: string): [bindingPropertyName: string, fieldName: string] {
// Either the value is 'field' or 'field: property'. In the first case, `property` will
// be undefined, in which case the field name should also be used as the property name.
const [fieldName, bindingPropertyName] = value.split(':', 2).map(str => str.trim());
return [bindingPropertyName ?? fieldName, fieldName];
}
/** Parses the `inputs` array of a directive/component decorator. */
function parseInputsArray(
clazz: ClassDeclaration, decoratorMetadata: Map<string, ts.Expression>,
evaluator: PartialEvaluator, reflector: ReflectionHost, refEmitter: ReferenceEmitter,
compilationMode: CompilationMode): Record<string, InputMapping> {
const inputsField = decoratorMetadata.get('inputs');
if (inputsField === undefined) {
return {};
}
const inputs = {} as Record<string, InputMapping>;
const inputsArray = evaluator.evaluate(inputsField);
if (!Array.isArray(inputsArray)) {
throw createValueHasWrongTypeError(
inputsField, inputsArray, `Failed to resolve @Directive.inputs to an array`);
}
for (let i = 0; i < inputsArray.length; i++) {
const value = inputsArray[i];
if (typeof value === 'string') {
// If the value is a string, we treat it as a mapping string.
const [bindingPropertyName, classPropertyName] = parseMappingString(value);
inputs[classPropertyName] = {
bindingPropertyName,
classPropertyName,
required: false,
transform: null,
// Note: Signal inputs are not allowed with the array form.
isSignal: false,
};
} else if (value instanceof Map) {
// If it's a map, we treat it as a config object.
const name = value.get('name');
const alias = value.get('alias');
const required = value.get('required');
let transform: DecoratorInputTransform|null = null;
if (typeof name !== 'string') {
throw createValueHasWrongTypeError(
inputsField, name,
`Value at position ${i} of @Directive.inputs array must have a "name" property`);
}
if (value.has('transform')) {
const transformValue = value.get('transform');
if (!(transformValue instanceof DynamicValue) && !(transformValue instanceof Reference)) {
throw createValueHasWrongTypeError(
inputsField, transformValue,
`Transform of value at position ${i} of @Directive.inputs array must be a function`);
}
transform = parseDecoratorInputTransformFunction(
clazz, name, transformValue, reflector, refEmitter, compilationMode);
}
inputs[name] = {
classPropertyName: name,
bindingPropertyName: typeof alias === 'string' ? alias : name,
required: required === true,
// Note: Signal inputs are not allowed with the array form.
isSignal: false,
transform,
};
} else {
throw createValueHasWrongTypeError(
inputsField, value,
`@Directive.inputs array can only contain strings or object literals`);
}
}
return inputs;
}
/** Attempts to find a given Angular decorator on the class member. */
function tryGetDecoratorOnMember(
member: ClassMember, decoratorName: string, isCore: boolean): Decorator|null {
if (member.decorators === null) {
return null;
}
for (const decorator of member.decorators) {
if (isAngularDecorator(decorator, decoratorName, isCore)) {
return decorator;
}
}
return null;
}
function tryParseInputFieldMapping(
clazz: ClassDeclaration, member: ClassMember, evaluator: PartialEvaluator,
reflector: ReflectionHost, isCore: boolean, refEmitter: ReferenceEmitter,
compilationMode: CompilationMode): InputMapping|null {
const classPropertyName = member.name;
const decorator = tryGetDecoratorOnMember(member, 'Input', isCore);
const signalInputMapping = tryParseSignalInputMapping(member, reflector, isCore);
if (decorator !== null && signalInputMapping !== null) {
throw new FatalDiagnosticError(
ErrorCode.INITIALIZER_API_WITH_DISALLOWED_DECORATOR, decorator.node,
`Using @Input with a signal input is not allowed.`);
}
// Check `@Input` case.
if (decorator !== null) {
if (decorator.args !== null && decorator.args.length > 1) {
throw new FatalDiagnosticError(
ErrorCode.DECORATOR_ARITY_WRONG, decorator.node,
`@${decorator.name} can have at most one argument, got ${
decorator.args.length} argument(s)`);
}
const optionsNode =
decorator.args !== null && decorator.args.length === 1 ? decorator.args[0] : undefined;
const options = optionsNode !== undefined ? evaluator.evaluate(optionsNode) : null;
const required = options instanceof Map ? options.get('required') === true : false;
// To preserve old behavior: Even though TypeScript types ensure proper options are
// passed, we sanity check for unsupported values here again.
if (options !== null && typeof options !== 'string' && !(options instanceof Map)) {
throw createValueHasWrongTypeError(
decorator.node, options,
`@${decorator.name} decorator argument must resolve to a string or an object literal`);
}
let alias: string|null = null;
if (typeof options === 'string') {
alias = options;
} else if (options instanceof Map && typeof options.get('alias') === 'string') {
alias = options.get('alias') as string;
}
const publicInputName = alias ?? classPropertyName;
let transform: DecoratorInputTransform|null = null;
if (options instanceof Map && options.has('transform')) {
const transformValue = options.get('transform');
if (!(transformValue instanceof DynamicValue) && !(transformValue instanceof Reference)) {
throw createValueHasWrongTypeError(
optionsNode!, transformValue, `Input transform must be a function`);
}
transform = parseDecoratorInputTransformFunction(
clazz, classPropertyName, transformValue, reflector, refEmitter, compilationMode);
}
return {
isSignal: false,
classPropertyName,
bindingPropertyName: publicInputName,
transform,
required,
};
}
// Look for signal inputs. e.g. `memberName = input()`
if (signalInputMapping !== null) {
return signalInputMapping;
}
return null;
}
/** Parses the class members that declare inputs (via decorator or initializer). */
function parseInputFields(
clazz: ClassDeclaration, members: ClassMember[], evaluator: PartialEvaluator,
reflector: ReflectionHost, refEmitter: ReferenceEmitter, isCore: boolean,
compilationMode: CompilationMode, inputsFromClassDecorator: Record<string, InputMapping>,
classDecorator: Decorator): Record<string, InputMapping> {
const inputs = {} as Record<string, InputMapping>;
for (const member of members) {
const classPropertyName = member.name;
const inputMapping = tryParseInputFieldMapping(
clazz,
member,
evaluator,
reflector,
isCore,
refEmitter,
compilationMode,
);
if (inputMapping === null) {
continue;
}
if (member.isStatic) {
throw new FatalDiagnosticError(
ErrorCode.INCORRECTLY_DECLARED_ON_STATIC_MEMBER, member.node ?? clazz,
`Input "${member.name}" is incorrectly declared as static member of "${
clazz.name.text}".`);
}
// Validate that signal inputs are not accidentally declared in the `inputs` metadata.
if (inputMapping.isSignal && inputsFromClassDecorator.hasOwnProperty(classPropertyName)) {
throw new FatalDiagnosticError(
ErrorCode.INITIALIZER_API_DECORATOR_METADATA_COLLISION, member.node ?? clazz,
`Input "${member.name}" is also declared as non-signal in @${classDecorator.name}.`);
}
inputs[classPropertyName] = inputMapping;
}
return inputs;
}
/**
* Parses the `transform` function and its type for a decorator `@Input`.
*
* This logic verifies feasibility of extracting the transform write type
* into a different place, so that the input write type can be captured at
* a later point in a static acceptance member.
*
* Note: This is not needed for signal inputs where the transform type is
* automatically captured in the type of the `InputSignal`.
*
*/
export function parseDecoratorInputTransformFunction(
clazz: ClassDeclaration, classPropertyName: string, value: DynamicValue|Reference,
reflector: ReflectionHost, refEmitter: ReferenceEmitter,
compilationMode: CompilationMode): DecoratorInputTransform {
// In local compilation mode we can skip type checking the function args. This is because usually
// the type check is done in a separate build which runs in full compilation mode. So here we skip
// all the diagnostics.
if (compilationMode === CompilationMode.LOCAL) {
const node =
value instanceof Reference ? value.getIdentityIn(clazz.getSourceFile()) : value.node;
// This should never be null since we know the reference originates
// from the same file, but we null check it just in case.
if (node === null) {
throw createValueHasWrongTypeError(
value.node, value, 'Input transform function could not be referenced');
}
return {
node,
type: new Reference(ts.factory.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword))
};
}
const definition = reflector.getDefinitionOfFunction(value.node);
if (definition === null) {
throw createValueHasWrongTypeError(value.node, value, 'Input transform must be a function');
}
if (definition.typeParameters !== null && definition.typeParameters.length > 0) {
throw createValueHasWrongTypeError(
value.node, value, 'Input transform function cannot be generic');
}
if (definition.signatureCount > 1) {
throw createValueHasWrongTypeError(
value.node, value, 'Input transform function cannot have multiple signatures');
}
const members = reflector.getMembersOfClass(clazz);
for (const member of members) {
const conflictingName = `ngAcceptInputType_${classPropertyName}`;
if (member.name === conflictingName && member.isStatic) {
throw new FatalDiagnosticError(
ErrorCode.CONFLICTING_INPUT_TRANSFORM, value.node,
`Class cannot have both a transform function on Input ${
classPropertyName} and a static member called ${conflictingName}`);
}
}
const node = value instanceof Reference ? value.getIdentityIn(clazz.getSourceFile()) : value.node;
// This should never be null since we know the reference originates
// from the same file, but we null check it just in case.
if (node === null) {
throw createValueHasWrongTypeError(
value.node, value, 'Input transform function could not be referenced');
}
// Skip over `this` parameters since they're typing the context, not the actual parameter.
// `this` parameters are guaranteed to be first if they exist, and the only to distinguish them
// is using the name, TS doesn't have a special AST for them.
const firstParam = definition.parameters[0]?.name === 'this' ? definition.parameters[1] :
definition.parameters[0];
// Treat functions with no arguments as `unknown` since returning
// the same value from the transform function is valid.
if (!firstParam) {
return {
node,
type: new Reference(ts.factory.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword))
};
}
// This should be caught by `noImplicitAny` already, but null check it just in case.
if (!firstParam.type) {
throw createValueHasWrongTypeError(
value.node, value, 'Input transform function first parameter must have a type');
}
if (firstParam.node.dotDotDotToken) {
throw createValueHasWrongTypeError(
value.node, value, 'Input transform function first parameter cannot be a spread parameter');
}
assertEmittableInputType(firstParam.type, clazz.getSourceFile(), reflector, refEmitter);
const viaModule = value instanceof Reference ? value.bestGuessOwningModule : null;
return {node, type: new Reference(firstParam.type, viaModule)};
}
/**
* Verifies that a type and all types contained within
* it can be referenced in a specific context file.
*/
function assertEmittableInputType(
type: ts.TypeNode, contextFile: ts.SourceFile, reflector: ReflectionHost,
refEmitter: ReferenceEmitter): void {
(function walk(node: ts.Node) {
if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName)) {
const declaration = reflector.getDeclarationOfIdentifier(node.typeName);
if (declaration !== null) {
// If the type is declared in a different file, we have to check that it can be imported
// into the context file. If they're in the same file, we need to verify that they're
// exported, otherwise TS won't emit it to the .d.ts.
if (declaration.node.getSourceFile() !== contextFile) {
const emittedType = refEmitter.emit(
new Reference(
declaration.node, declaration.viaModule === AmbientImport ? AmbientImport : null),
contextFile,
ImportFlags.NoAliasing | ImportFlags.AllowTypeImports |
ImportFlags.AllowRelativeDtsImports | ImportFlags.AllowAmbientReferences);
assertSuccessfulReferenceEmit(emittedType, node, 'type');
} else if (!reflector.isStaticallyExported(declaration.node)) {
throw new FatalDiagnosticError(
ErrorCode.SYMBOL_NOT_EXPORTED, type,
`Symbol must be exported in order to be used as the type of an Input transform function`,
[makeRelatedInformation(declaration.node, `The symbol is declared here.`)]);
}
}
}
node.forEachChild(walk);
})(type);
}
/**
* Iterates through all specified class members and attempts to detect
* view and content queries defined.
*
* Queries may be either defined via decorators, or through class member
* initializers for signal-based queries.