This repository has been archived by the owner on Nov 1, 2020. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
methods.ts
89 lines (71 loc) · 2.69 KB
/
methods.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
import { types } from '@babel/core'
import { getSetupMethod } from '../../ast-utilities'
export function addMethods(ast: types.File, section: types.ObjectProperty) {
const setupMethodBody = getSetupMethod(ast).body.body
const MethodsProps = section.value as types.ObjectExpression
const properties = MethodsProps.properties
const toExportList = []
for (let i = 0; i < properties.length; i += 1) {
const property = properties[i]
if (types.isObjectMethod(property)) {
const key = property.key as types.Identifier
const MethodsStatement = types.variableDeclaration('const', [
types.variableDeclarator(
types.identifier(key.name),
types.arrowFunctionExpression(property.params, property.body)
)
])
toExportList.push(key.name)
setupMethodBody.splice(-1, 0, MethodsStatement)
continue
}
if (types.isObjectProperty(property)) {
const key = property.key as types.Identifier
const value = property.value
if (types.isArrowFunctionExpression(value)) {
const MethodsStatement = types.variableDeclaration('const', [
types.variableDeclarator(types.identifier(key.name), value)
])
toExportList.push(key.name)
setupMethodBody.splice(-1, 0, MethodsStatement)
}
if (types.isFunctionExpression(value)) {
const MethodsStatement = types.variableDeclaration('const', [
types.variableDeclarator(
types.identifier(key.name),
types.arrowFunctionExpression(value.params, value.body, value.async)
)
])
toExportList.push(key.name)
setupMethodBody.splice(-1, 0, MethodsStatement)
}
}
if (types.isSpreadElement(property)) {
const argument = property.argument as types.ArrayExpression
const values = argument.elements as types.FunctionExpression[]
values.forEach(value => {
const key = value.id as types.Identifier
const MethodsStatement = types.variableDeclaration('const', [
types.variableDeclarator(
types.identifier(key.name),
types.arrowFunctionExpression(value.params, value.body, value.async)
)
])
toExportList.push(key.name)
setupMethodBody.splice(-1, 0, MethodsStatement)
})
}
}
// export computed properties
const returnStatement = setupMethodBody.slice(-1)[0] as types.ReturnStatement
const argument = returnStatement.argument as types.ObjectExpression
toExportList.forEach(exportItem => {
argument.properties.push(
types.objectProperty(
types.identifier(exportItem),
types.identifier(exportItem)
)
)
})
// TODO: update method calls
}