forked from mskelton/ratchet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
transform.ts
437 lines (373 loc) · 12 KB
/
transform.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
import type { NodePath } from "ast-types/lib/node-path.js"
import type {
API,
Collection,
CommentBlock,
CommentLine,
FileInfo,
Identifier,
JSCodeshift,
Literal,
Options,
TSAnyKeyword,
TSFunctionType,
} from "jscodeshift"
let j: JSCodeshift
let options: {
declarationStyle: "interface" | "type"
preservePropTypes: "none" | "unconverted" | "all"
}
function reactType(type: string) {
return j.tsQualifiedName(j.identifier("React"), j.identifier(type))
}
type TSType = {
comments: (CommentLine | CommentBlock)[]
key: Identifier | Literal
required: boolean
type: TSAnyKeyword | TSFunctionType
}
function createPropertySignature({ comments, key, required, type }: TSType) {
if (type.type === "TSFunctionType") {
return j.tsMethodSignature.from({
comments,
key,
optional: !required,
parameters: type.parameters,
typeAnnotation: type.typeAnnotation,
})
}
return j.tsPropertySignature.from({
comments,
key,
optional: !required,
typeAnnotation: j.tsTypeAnnotation(type),
})
}
function isCustomValidator(path: NodePath) {
return (
path.get("type").value === "FunctionExpression" ||
path.get("type").value === "ArrowFunctionExpression"
)
}
const resolveRequired = (path: NodePath) =>
isRequired(path) ? path.get("object") : path
function getTSType(path: NodePath) {
const { value: name } =
path.get("type").value === "MemberExpression"
? path.get("property", "name")
: path.get("callee", "property", "name")
switch (name) {
case "func": {
const restElement = j.restElement.from({
argument: j.identifier("args"),
typeAnnotation: j.tsTypeAnnotation(j.tsArrayType(j.tsUnknownKeyword())),
})
return j.tsFunctionType.from({
parameters: [restElement],
typeAnnotation: j.tsTypeAnnotation(j.tsUnknownKeyword()),
})
}
case "arrayOf": {
const type = path.get("arguments", 0)
return isCustomValidator(type)
? j.tsUnknownKeyword()
: j.tsArrayType(getTSType(resolveRequired(type)))
}
case "objectOf": {
const type = path.get("arguments", 0)
return isCustomValidator(type)
? j.tsUnknownKeyword()
: j.tsTypeReference(
j.identifier("Record"),
j.tsTypeParameterInstantiation([
j.tsStringKeyword(),
getTSType(resolveRequired(type)),
])
)
}
case "oneOf": {
const arg = path.get("arguments", 0)
return arg.get("type").value !== "ArrayExpression"
? j.tsArrayType(j.tsUnknownKeyword())
: j.tsUnionType(
arg.get("elements").value.map(({ type, value }) => {
switch (type) {
case "StringLiteral":
return j.tsLiteralType(j.stringLiteral(value))
case "NumericLiteral":
return j.tsLiteralType(j.numericLiteral(value))
case "BooleanLiteral":
return j.tsLiteralType(j.booleanLiteral(value))
default:
return j.tsUnknownKeyword()
}
})
)
}
case "oneOfType":
return j.tsUnionType(path.get("arguments", 0, "elements").map(getTSType))
case "instanceOf":
return j.tsTypeReference(
j.identifier(path.get("arguments", 0, "name").value)
)
case "shape":
case "exact":
return j.tsTypeLiteral(
path
.get("arguments", 0, "properties")
.map(mapType)
.map(createPropertySignature)
)
}
const map = {
any: j.tsAnyKeyword(),
array: j.tsArrayType(j.tsUnknownKeyword()),
bool: j.tsBooleanKeyword(),
element: j.tsTypeReference(reactType("ReactElement")),
elementType: j.tsTypeReference(reactType("ElementType")),
node: j.tsTypeReference(reactType("ReactNode")),
number: j.tsNumberKeyword(),
object: j.tsObjectKeyword(),
string: j.tsStringKeyword(),
symbol: j.tsSymbolKeyword(),
}
return map[name] || j.tsUnknownKeyword()
}
const isRequired = (path: NodePath) =>
path.get("type").value === "MemberExpression" &&
path.get("property", "name").value === "isRequired"
function mapType(path: NodePath): TSType {
const required = isRequired(path.get("value"))
const key = path.get("key").value
const comments = path.get("leadingComments").value
const type = getTSType(
required ? path.get("value", "object") : path.get("value")
)
// If all types should be removed or the type was able to be converted,
// we remove the type.
if (options.preservePropTypes !== "all" && type.type !== "TSUnknownKeyword") {
path.replace()
}
return {
comments: comments ?? [],
key,
required,
type,
}
}
type CollectedTypes = {
component: string
types: TSType[]
}[]
function getTSTypes(
source: Collection,
getComponentName: (path: NodePath) => string
) {
const collected = [] as CollectedTypes
const propertyTypes = ["Property", "ObjectProperty", "ObjectMethod"]
source
.filter((path) => path.value)
.forEach((path) => {
collected.push({
component: getComponentName(path),
types: path
.filter(({ value }) => propertyTypes.includes(value.type), null)
.map(mapType, null),
})
})
return collected
}
function getFunctionParent(path: NodePath) {
return path.parent.get("type").value === "Program"
? path
: getFunctionParent(path.parent)
}
function getComponentName(path: NodePath) {
const root =
path.get("type").value === "ArrowFunctionExpression" ? path.parent : path
return root.get("id", "name").value ?? root.parent.get("id", "name").value
}
function createTypeDeclaration(path: NodePath, componentTypes: CollectedTypes) {
const componentName = getComponentName(path)
const types = componentTypes.find((t) => t.component === componentName)
const typeName = `${componentName}Props`
// If the component doesn't have propTypes, ignore it
if (!types) return
// Add the TS types before the function/class
getFunctionParent(path).insertBefore(
options.declarationStyle === "type"
? j.tsTypeAliasDeclaration(
j.identifier(typeName),
j.tsTypeLiteral(types.types.map(createPropertySignature))
)
: j.tsInterfaceDeclaration(
j.identifier(typeName),
j.tsInterfaceBody(types.types.map(createPropertySignature))
)
)
return typeName
}
/**
* If forwardRef is being used, declare the props.
* Otherwise, return false
*/
function addForwardRefTypes(path: NodePath, typeName: string): boolean {
// for `React.forwardRef()`
if (path.node.callee?.property?.name === "forwardRef") {
path.node.callee.property.name = `forwardRef<HTMLElement, ${typeName}>`
return true
}
// if calling `forwardRef()` directly
if (path.node.callee?.name === "forwardRef") {
path.node.callee.name = `forwardRef<HTMLElement, ${typeName}>`
return true
}
return false
}
function addFunctionTSTypes(
source: Collection,
componentTypes: CollectedTypes
) {
source.forEach((path) => {
const typeName = createTypeDeclaration(path, componentTypes)
if (!typeName) return
// add forwardRef types if present
if (addForwardRefTypes(path.parentPath, typeName)) return
// Function components & Class Components
// Add the TS types to the props param
path.get("params", 0).value.typeAnnotation = j.tsTypeReference(
// For some reason, jscodeshift isn't adding the colon so we have to do
// that ourselves.
j.identifier(`: ${typeName}`)
)
})
}
function addClassTSTypes(source: Collection, componentTypes: CollectedTypes) {
source.find(j.ClassDeclaration).forEach((path) => {
const typeName = createTypeDeclaration(path, componentTypes)
if (!typeName) return
// Add the TS types to the React.Component super class
path.value.superTypeParameters = j.tsTypeParameterInstantiation([
j.tsTypeReference(j.identifier(typeName)),
])
})
}
function collectPropTypes(source: Collection) {
return source
.find(j.AssignmentExpression)
.filter(
(path) => path.get("left", "property", "name").value === "propTypes"
)
.map((path) => path.get("right", "properties"))
}
function collectStaticPropTypes(source: Collection) {
return source
.find(j.ClassProperty)
.filter((path) => !!path.value.static)
.filter((path) => path.get("key", "name").value === "propTypes")
.map((path) => path.get("value", "properties"))
}
function cleanup(
source: Collection,
propTypes: Collection,
staticPropTypes: Collection
) {
propTypes.forEach((path) => {
if (!path.parent.get("right", "properties", "length").value) {
path.parent.prune()
}
})
staticPropTypes.forEach((path) => {
if (!path.parent.get("value", "properties", "length").value) {
path.parent.prune()
}
})
const propTypesUsages = source
.find(j.MemberExpression)
.filter((path) => path.get("object", "name").value === "PropTypes")
// We can remove the import without caring about the preserve-prop-types
// option since the criteria for removal is that no PropTypes.* member
// expressions exist.
if (propTypesUsages.length === 0) {
source
.find(j.ImportDeclaration)
.filter((path) => path.value.source.value === "prop-types")
.remove()
}
}
const isOnlyWhitespace = (str: string) => !/\S/.test(str)
/**
* Guess the tab width of the file. This file is a modified version of recast's
* built-in tab width guessing with a modification to better handle files with
* block comments.
* @see https://github.com/benjamn/recast/blob/8cc1f42408c41b5616d82574f5552c2da3e11cf7/lib/lines.ts#L280-L314
*/
function guessTabWidth(source: string) {
const lines = source.split("\n")
const counts: number[] = []
let lastIndent = 0
for (const line of lines) {
// Whitespace-only lines don't tell us much about the likely tab width
if (isOnlyWhitespace(line)) {
continue
}
// Calculate the indentation of the line excluding lines starting with an
// asterisk. This is because these lines are often part of block comments
// which are indented an extra space which throws off our tab width guessing.
const indent = line.match(/^(\s*)/)
? line.trim().startsWith("*")
? lastIndent
: RegExp.$1.length
: 0
const diff = Math.abs(indent - lastIndent)
counts[diff] = ~~counts[diff] + 1
lastIndent = indent
}
let maxCount = -1
let result = 2
// Loop through the counts array to find the most common tab width in the file
for (let tabWidth = 1; tabWidth < counts.length; tabWidth++) {
if (counts[tabWidth] && counts[tabWidth] > maxCount) {
maxCount = counts[tabWidth]
result = tabWidth
}
}
return result
}
// Use the TSX to allow parsing of TypeScript code that still contains prop
// types. Though not typical, this exists in the wild.
export const parser = "tsx"
export default function (file: FileInfo, api: API, opts: Options) {
j = api.jscodeshift
const source = j(file.source)
// Parse the CLI options
options = {
declarationStyle: opts["declaration-style"] || "interface",
preservePropTypes:
opts["preserve-prop-types"] === true
? "all"
: opts["preserve-prop-types"] || "none",
}
const propTypes = collectPropTypes(source)
const tsTypes = getTSTypes(
propTypes,
(path) => path.parent.get("left", "object", "name").value
)
const staticPropTypes = collectStaticPropTypes(source)
const staticTSTypes = getTSTypes(
staticPropTypes,
(path) => path.parent.parent.parent.value.id.name
)
addFunctionTSTypes(source.find(j.FunctionDeclaration), tsTypes)
addFunctionTSTypes(source.find(j.FunctionExpression), tsTypes)
addFunctionTSTypes(source.find(j.ArrowFunctionExpression), tsTypes)
addClassTSTypes(source, tsTypes)
addClassTSTypes(source, staticTSTypes)
if (options.preservePropTypes === "none") {
propTypes.remove()
staticPropTypes.remove()
}
// Remove empty propTypes expressions and imports
cleanup(source, propTypes, staticPropTypes)
return source.toSource({ tabWidth: guessTabWidth(file.source) })
}