Debian Codegraph @

packages/babel-plugin-transform-duplicate-keys/src/index.ts

raw
1 import { declare } from "@babel/helper-plugin-utils";
2 import { types as t } from "@babel/core";
3
4 function getName(
5 key: t.Identifier | t.StringLiteral | t.NumericLiteral | t.BigIntLiteral,
6 ) {
7 if (t.isIdentifier(key)) {
8 return key.name;
9 }
10 return key.value.toString();
11 }
12
13 export default declare(api => {
14 api.assertVersion(7);
15
16 return {
17 name: "transform-duplicate-keys",
18
19 visitor: {
20 ObjectExpression(path) {
21 const { node } = path;
22 const plainProps = node.properties.filter(
23 prop => !t.isSpreadElement(prop) && !prop.computed,
24 ) as (t.ObjectMethod | t.ObjectProperty)[];
25
26 // A property is a duplicate key if:
27 // * the property is a data property, and is preceded by a data,
28 // getter, or setter property of the same name.
29 // * the property is a getter property, and is preceded by a data or
30 // getter property of the same name.
31 // * the property is a setter property, and is preceded by a data or
32 // setter property of the same name.
33
34 const alreadySeenData = Object.create(null);
35 const alreadySeenGetters = Object.create(null);
36 const alreadySeenSetters = Object.create(null);
37
38 for (const prop of plainProps) {
39 const name = getName(
40 // prop must be non-computed
41 prop.key as
42 | t.Identifier
43 | t.StringLiteral
44 | t.NumericLiteral
45 | t.BigIntLiteral,
46 );
47 let isDuplicate = false;
48 // @ts-expect-error prop.kind is not defined in ObjectProperty
49 switch (prop.kind) {
50 case "get":
51 if (alreadySeenData[name] || alreadySeenGetters[name]) {
52 isDuplicate = true;
53 }
54 alreadySeenGetters[name] = true;
55 break;
56 case "set":
57 if (alreadySeenData[name] || alreadySeenSetters[name]) {
58 isDuplicate = true;
59 }
60 alreadySeenSetters[name] = true;
61 break;
62 default:
63 if (
64 alreadySeenData[name] ||
65 alreadySeenGetters[name] ||
66 alreadySeenSetters[name]
67 ) {
68 isDuplicate = true;
69 }
70 alreadySeenData[name] = true;
71 }
72
73 if (isDuplicate) {
74 // Rely on the computed properties transform to split the property
75 // assignment out of the object literal.
76 prop.computed = true;
77 prop.key = t.stringLiteral(name);
78 }
79 }
80 },
81 },
82 };
83 });