forked from getyourguide/vue-class-migrator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmigratorManager.ts
276 lines (246 loc) · 7.77 KB
/
migratorManager.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
import {
ClassDeclaration,
Node,
ObjectLiteralExpression,
OptionalKind,
ParameterDeclarationStructure,
SourceFile,
SyntaxKind,
TypeNode,
} from 'ts-morph';
import { addPropertyObject, getArrayProperty, getObjectProperty } from './utils';
import { ComputedProps, MigratePartProps } from './types/migrator';
import { supportedDecorators } from './config';
import getDefineComponentInit from './migrate-component-decorator';
export default class MigrationManager {
private _clazz: ClassDeclaration;
private _mainObject: ObjectLiteralExpression;
private _outFile: SourceFile;
constructor(props: MigratePartProps) {
this._mainObject = props.mainObject;
this._clazz = props.clazz;
this._outFile = props.outFile;
}
get mainObject(): ObjectLiteralExpression {
return this._mainObject;
}
get clazz(): ClassDeclaration {
return this._clazz;
}
get outFile(): SourceFile {
return this._outFile;
}
addModel(options: {
propName: string,
eventName: string,
}) {
if (this.mainObject.getProperty('model')) {
throw new Error('The component has two models.');
}
const modelObject = getObjectProperty(this.mainObject, 'model');
modelObject
.addPropertyAssignment({
name: 'prop',
initializer: `"${options.propName}"`,
});
modelObject
.addPropertyAssignment({
name: 'event',
initializer: `"${options.eventName}"`,
});
}
addProp(options: {
propName: string;
propNode: Node | undefined;
tsType: TypeNode | undefined;
}): ObjectLiteralExpression {
const propsObject = getObjectProperty(this.mainObject, 'props');
const {
propName, propNode, tsType,
} = options;
let propObject: ObjectLiteralExpression;
if (!propNode) {
propObject = addPropertyObject(propsObject, propName);
propObject
.addPropertyAssignment({
name: 'type',
initializer: this.typeNodeToString(tsType),
});
return propObject;
}
if (
propNode.isKind(SyntaxKind.Identifier) // e.g. String
|| propNode.isKind(SyntaxKind.ArrayLiteralExpression) // e.g. [String, Boolean]
) {
propObject = addPropertyObject(propsObject, propName);
propObject
.addPropertyAssignment({
name: 'type',
initializer: propNode.getText(),
});
return propObject;
}
if (propNode.isKind(SyntaxKind.ObjectLiteralExpression)) {
propObject = addPropertyObject(propsObject, propName, propNode.getText());
if (!propObject.getProperty('type')) {
propObject
.addPropertyAssignment({
name: 'type',
initializer: this.typeNodeToString(tsType),
});
}
return propObject;
}
throw new Error(`Error adding prop ${propName}, Kind: ${propNode.getKindName()}.`);
}
addComputedProp(options: ComputedProps) {
const computedObject = getObjectProperty(this.mainObject, 'computed');
if ('get' in options) {
const syncPropObject = addPropertyObject(computedObject, options.name);
if (options.cache !== undefined) {
syncPropObject.addPropertyAssignment({
name: 'cache',
initializer: `${options.cache}`,
});
}
syncPropObject.addMethod({
name: 'get',
statements: options.get.statements,
returnType: options.get.returnType,
});
if (options.set) {
syncPropObject.addMethod({
name: 'set',
parameters: options.set.parameters,
statements: options.set.statements,
});
}
} else {
computedObject.addMethod({
name: options.name,
returnType: options.returnType,
statements: options.statements,
});
}
}
addMethod(options: {
methodName: string;
parameters: OptionalKind<ParameterDeclarationStructure>[] | undefined;
statements: string;
isAsync?: boolean;
returnType?: string;
}) {
const methodsMainObject = getObjectProperty(this.mainObject, 'methods');
if (methodsMainObject.getProperty(options.methodName)) {
throw new Error(`Duplicated method ${options.methodName}`);
}
methodsMainObject.addMethod({
name: options.methodName,
parameters: options.parameters,
isAsync: options.isAsync,
returnType: options.returnType,
statements: options.statements,
});
}
addWatch(options: {
watchPath: string;
watchOptions: string | undefined;
handlerMethod: string;
}) {
const watchMainObject = getObjectProperty(this.mainObject, 'watch');
const watchPropArray = getArrayProperty(watchMainObject, `"${options.watchPath}"`);
const newWatcher = watchPropArray
.addElement(options.watchOptions ?? '{}')
.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);
newWatcher.addPropertyAssignment({
name: 'handler',
initializer: `"${options.handlerMethod}"`,
});
}
addNamedImport(module: string, namedImport: string) {
const importDeclaration = this._outFile
.getImportDeclaration((imp) => imp.getModuleSpecifierValue() === module);
if (!importDeclaration?.getNamedImports()
.some((imp) => imp.getText() === namedImport)) {
importDeclaration?.addNamedImport('PropType');
}
}
private typeNodeToString(typeNode: TypeNode | undefined): string {
const propertyType = typeNode?.getText() ?? 'any';
const isArray = Node.isArrayTypeNode(typeNode);
const isFunction = Node.isFunctionTypeNode(typeNode);
const propertyConstructorMapping: Record<string, string> = {
string: 'String',
boolean: 'Boolean',
number: 'Number',
};
let fallbackType = 'Object';
fallbackType = isArray ? 'Array' : fallbackType;
fallbackType = isFunction ? 'Function' : fallbackType;
if (!propertyConstructorMapping[propertyType]) {
this.addNamedImport('vue', 'PropType');
return `${fallbackType} as PropType<${propertyType}>`;
}
return propertyConstructorMapping[propertyType];
}
}
export const createMigrationManager = (
sourceFile: SourceFile,
outFile: SourceFile,
): MigrationManager => {
// Do not modify this class.
const sourceFileClass = sourceFile
.getClasses()
.filter((clazz) => clazz.getDecorator('Component'))
.pop();
const outClazz = outFile
.getClasses()
.filter((clazz) => clazz.getDecorator('Component'))
.pop();
if (!sourceFileClass || !outClazz) {
throw new Error('Class implementing the @Component decorator not found.');
}
// Validation
sourceFileClass
.getProperties()
.flatMap((prop) => prop.getDecorators())
.forEach((decorator) => {
if (!supportedDecorators.includes(decorator.getName())) {
throw new Error(`Decorator @${decorator.getName()} not supported`);
}
});
const defineComponentInitObject = getDefineComponentInit(sourceFileClass);
let clazzReplacement: string;
if (!outClazz.getDefaultKeyword()) {
// Non default exported class
clazzReplacement = [
outClazz?.getExportKeyword()?.getText(),
`const ${outClazz.getName()} =`,
`defineComponent(${defineComponentInitObject})`,
]
.filter((s) => s)
.join(' ');
} else {
clazzReplacement = [
outClazz?.getExportKeyword()?.getText(),
outClazz?.getDefaultKeywordOrThrow()?.getText(),
`defineComponent(${defineComponentInitObject})`,
]
.filter((s) => s)
.join(' ');
}
// Main structure
const mainObject = outClazz
.replaceWithText(clazzReplacement)
.getFirstDescendantByKind(SyntaxKind.ObjectLiteralExpression);
if (!mainObject) {
throw new Error('Unable to create defineComponent');
}
const migratePartProps: MigratePartProps = {
clazz: sourceFileClass,
mainObject,
outFile,
sourceFile,
};
return new MigrationManager(migratePartProps);
};