/
prop-decorator.ts
206 lines (175 loc) · 6.3 KB
/
prop-decorator.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
import * as d from '../../../declarations';
import { augmentDiagnosticWithNode, buildError, buildWarn, catchError, toDashCase } from '@utils';
import {
convertValueToLiteral,
createStaticGetter,
getAttributeTypeInfo,
isMemberPrivate,
resolveType,
serializeSymbol,
typeToString,
validateReferences,
} from '../transform-utils';
import { isDecoratorNamed } from './decorator-utils';
import { validatePublicName } from '../reserved-public-members';
import ts from 'typescript';
export const propDecoratorsToStatic = (
diagnostics: d.Diagnostic[],
decoratedProps: ts.ClassElement[],
typeChecker: ts.TypeChecker,
watchable: Set<string>,
newMembers: ts.ClassElement[],
) => {
const properties = decoratedProps
.filter(ts.isPropertyDeclaration)
.map(prop => parsePropDecorator(diagnostics, typeChecker, prop, watchable))
.filter(prop => prop != null);
if (properties.length > 0) {
newMembers.push(createStaticGetter('properties', ts.createObjectLiteral(properties, true)));
}
};
const parsePropDecorator = (diagnostics: d.Diagnostic[], typeChecker: ts.TypeChecker, prop: ts.PropertyDeclaration, watchable: Set<string>) => {
const propDecorator = prop.decorators.find(isDecoratorNamed('Prop'));
if (propDecorator == null) {
return null;
}
const propName = prop.name.getText();
const propOptions = getPropOptions(propDecorator, diagnostics);
if (isMemberPrivate(prop)) {
const err = buildError(diagnostics);
err.messageText = 'Properties decorated with the @Prop() decorator cannot be "private" nor "protected". More info: https://stenciljs.com/docs/properties';
augmentDiagnosticWithNode(err, prop.modifiers[0]);
}
if (/^on(-|[A-Z])/.test(propName)) {
const warn = buildWarn(diagnostics);
warn.messageText = `The @Prop() name "${propName}" looks like an event. Please use the "@Event()" decorator to expose events instead, not properties or methods.`;
augmentDiagnosticWithNode(warn, prop.name);
} else {
validatePublicName(diagnostics, propName, '@Prop()', 'prop', prop.name);
}
const symbol = typeChecker.getSymbolAtLocation(prop.name);
const type = typeChecker.getTypeAtLocation(prop);
const typeStr = propTypeFromTSType(type);
const propMeta: d.ComponentCompilerStaticProperty = {
type: typeStr,
mutable: !!propOptions.mutable,
complexType: getComplexType(typeChecker, prop, type),
required: prop.exclamationToken !== undefined && propName !== 'mode',
optional: prop.questionToken !== undefined,
docs: serializeSymbol(typeChecker, symbol),
};
validateReferences(diagnostics, propMeta.complexType.references, prop.type);
// prop can have an attribute if type is NOT "unknown"
if (typeStr !== 'unknown') {
propMeta.attribute = getAttributeName(propName, propOptions);
propMeta.reflect = getReflect(diagnostics, propOptions);
}
// extract default value
const initializer = prop.initializer;
if (initializer) {
propMeta.defaultValue = initializer.getText();
}
const staticProp = ts.createPropertyAssignment(ts.createLiteral(propName), convertValueToLiteral(propMeta));
watchable.add(propName);
return staticProp;
};
const getAttributeName = (propName: string, propOptions: d.PropOptions) => {
if (propOptions.attribute === null) {
return undefined;
}
if (typeof propOptions.attribute === 'string' && propOptions.attribute.trim().length > 0) {
return propOptions.attribute.trim().toLowerCase();
}
return toDashCase(propName);
};
const getReflect = (_diagnostics: d.Diagnostic[], propOptions: d.PropOptions) => {
if (typeof propOptions.reflect === 'boolean') {
return propOptions.reflect;
}
if (typeof (propOptions as any).reflectToAttr === 'boolean') {
// const diagnostic = buildWarn(diagnostics);
// diagnostic.messageText = `@Prop option "reflectToAttr" has been depreciated. Please use "reflect" instead.`;
return (propOptions as any).reflectToAttr;
}
return false;
};
const getPropOptions = (propDecorator: ts.Decorator, diagnostics: d.Diagnostic[]) => {
if (propDecorator.expression == null) {
return {};
}
const suppliedOptions = (propDecorator.expression as ts.CallExpression).arguments.map(arg => {
try {
const fnStr = `return ${arg.getText()};`;
return new Function(fnStr)();
} catch (e) {
catchError(diagnostics, e, `parse prop options: ${e}`);
}
});
const propOptions: d.PropOptions = suppliedOptions[0];
return propOptions || {};
};
const getComplexType = (typeChecker: ts.TypeChecker, node: ts.PropertyDeclaration, type: ts.Type): d.ComponentCompilerPropertyComplexType => {
const nodeType = node.type;
return {
original: nodeType ? nodeType.getText() : typeToString(typeChecker, type),
resolved: resolveType(typeChecker, type),
references: getAttributeTypeInfo(node, node.getSourceFile()),
};
};
export const propTypeFromTSType = (type: ts.Type) => {
const isAnyType = checkType(type, isAny);
if (isAnyType) {
return 'any';
}
const isStr = checkType(type, isString);
const isNu = checkType(type, isNumber);
const isBool = checkType(type, isBoolean);
// if type is more than a primitive type at the same time, we mark it as any
if (Number(isStr) + Number(isNu) + Number(isBool) > 1) {
return 'any';
}
// at this point we know the prop's type is NOT the mix of primitive types
if (isStr) {
return 'string';
}
if (isNu) {
return 'number';
}
if (isBool) {
return 'boolean';
}
return 'unknown';
};
const checkType = (type: ts.Type, check: (type: ts.Type) => boolean) => {
if (type.flags & ts.TypeFlags.Union) {
const union = type as ts.UnionType;
if (union.types.some(type => checkType(type, check))) {
return true;
}
}
return check(type);
};
const isBoolean = (t: ts.Type) => {
if (t) {
return !!(t.flags & (ts.TypeFlags.Boolean | ts.TypeFlags.BooleanLike | ts.TypeFlags.BooleanLike));
}
return false;
};
const isNumber = (t: ts.Type) => {
if (t) {
return !!(t.flags & (ts.TypeFlags.Number | ts.TypeFlags.NumberLike | ts.TypeFlags.NumberLiteral));
}
return false;
};
const isString = (t: ts.Type) => {
if (t) {
return !!(t.flags & (ts.TypeFlags.String | ts.TypeFlags.StringLike | ts.TypeFlags.StringLiteral));
}
return false;
};
const isAny = (t: ts.Type) => {
if (t) {
return !!(t.flags & ts.TypeFlags.Any);
}
return false;
};