| 1 |
import { types as t } from "@babel/core"; |
| 2 |
|
| 3 |
type DefineMap = { |
| 4 |
_inherits: t.Node[]; |
| 5 |
_key: t.Expression; |
| 6 |
get?: t.Expression; |
| 7 |
set?: t.Expression; |
| 8 |
kind: "get" | "set"; |
| 9 |
}; |
| 10 |
|
| 11 |
export type MutatorMap = Record<string, DefineMap>; |
| 12 |
|
| 13 |
export function pushAccessor( |
| 14 |
mutatorMap: MutatorMap, |
| 15 |
node: t.ObjectMethod & { kind: "get" | "set"; computed: false }, |
| 16 |
) { |
| 17 |
const alias = t.toKeyAlias(node); |
| 18 |
const map = (mutatorMap[alias] ??= { |
| 19 |
_inherits: [], |
| 20 |
_key: node.key, |
| 21 |
} as DefineMap); |
| 22 |
|
| 23 |
map._inherits.push(node); |
| 24 |
|
| 25 |
const value = t.functionExpression( |
| 26 |
null, |
| 27 |
node.params, |
| 28 |
node.body, |
| 29 |
node.generator, |
| 30 |
node.async, |
| 31 |
); |
| 32 |
value.returnType = node.returnType; |
| 33 |
t.inheritsComments(value, node); |
| 34 |
map[node.kind] = value; |
| 35 |
|
| 36 |
return map; |
| 37 |
} |
| 38 |
|
| 39 |
export function toDefineObject(mutatorMap: any) { |
| 40 |
const objExpr = t.objectExpression([]); |
| 41 |
|
| 42 |
Object.keys(mutatorMap).forEach(function (mutatorMapKey) { |
| 43 |
const map = mutatorMap[mutatorMapKey]; |
| 44 |
map.configurable = t.booleanLiteral(true); |
| 45 |
map.enumerable = t.booleanLiteral(true); |
| 46 |
|
| 47 |
const mapNode = t.objectExpression([]); |
| 48 |
|
| 49 |
const propNode = t.objectProperty(map._key, mapNode, map._computed); |
| 50 |
|
| 51 |
Object.keys(map).forEach(function (key) { |
| 52 |
const node = map[key]; |
| 53 |
if (key[0] === "_") return; |
| 54 |
|
| 55 |
const prop = t.objectProperty(t.identifier(key), node); |
| 56 |
t.inheritsComments(prop, node); |
| 57 |
t.removeComments(node); |
| 58 |
|
| 59 |
mapNode.properties.push(prop); |
| 60 |
}); |
| 61 |
|
| 62 |
objExpr.properties.push(propNode); |
| 63 |
}); |
| 64 |
|
| 65 |
return objExpr; |
| 66 |
} |