index.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. var _helperPluginUtils = require("@babel/helper-plugin-utils");
  7. var _core = require("@babel/core");
  8. function getName(key) {
  9. if (_core.types.isIdentifier(key)) {
  10. return key.name;
  11. }
  12. return key.value.toString();
  13. }
  14. var _default = (0, _helperPluginUtils.declare)(api => {
  15. api.assertVersion(7);
  16. return {
  17. name: "transform-duplicate-keys",
  18. visitor: {
  19. ObjectExpression(path) {
  20. const {
  21. node
  22. } = path;
  23. const plainProps = node.properties.filter(prop => !_core.types.isSpreadElement(prop) && !prop.computed);
  24. const alreadySeenData = Object.create(null);
  25. const alreadySeenGetters = Object.create(null);
  26. const alreadySeenSetters = Object.create(null);
  27. for (const prop of plainProps) {
  28. const name = getName(prop.key);
  29. let isDuplicate = false;
  30. switch (prop.kind) {
  31. case "get":
  32. if (alreadySeenData[name] || alreadySeenGetters[name]) {
  33. isDuplicate = true;
  34. }
  35. alreadySeenGetters[name] = true;
  36. break;
  37. case "set":
  38. if (alreadySeenData[name] || alreadySeenSetters[name]) {
  39. isDuplicate = true;
  40. }
  41. alreadySeenSetters[name] = true;
  42. break;
  43. default:
  44. if (alreadySeenData[name] || alreadySeenGetters[name] || alreadySeenSetters[name]) {
  45. isDuplicate = true;
  46. }
  47. alreadySeenData[name] = true;
  48. }
  49. if (isDuplicate) {
  50. prop.computed = true;
  51. prop.key = _core.types.stringLiteral(name);
  52. }
  53. }
  54. }
  55. }
  56. };
  57. });
  58. exports.default = _default;