index.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. var _default = (0, _helperPluginUtils.declare)(api => {
  9. api.assertVersion(7);
  10. return {
  11. name: "transform-new-target",
  12. visitor: {
  13. MetaProperty(path) {
  14. const meta = path.get("meta");
  15. const property = path.get("property");
  16. const {
  17. scope
  18. } = path;
  19. if (meta.isIdentifier({
  20. name: "new"
  21. }) && property.isIdentifier({
  22. name: "target"
  23. })) {
  24. const func = path.findParent(path => {
  25. if (path.isClass()) return true;
  26. if (path.isFunction() && !path.isArrowFunctionExpression()) {
  27. if (path.isClassMethod({
  28. kind: "constructor"
  29. })) {
  30. return false;
  31. }
  32. return true;
  33. }
  34. return false;
  35. });
  36. if (!func) {
  37. throw path.buildCodeFrameError("new.target must be under a (non-arrow) function or a class.");
  38. }
  39. const {
  40. node
  41. } = func;
  42. if (_core.types.isMethod(node)) {
  43. path.replaceWith(scope.buildUndefinedNode());
  44. return;
  45. }
  46. const constructor = _core.types.memberExpression(_core.types.thisExpression(), _core.types.identifier("constructor"));
  47. if (func.isClass()) {
  48. path.replaceWith(constructor);
  49. return;
  50. }
  51. if (!node.id) {
  52. node.id = scope.generateUidIdentifier("target");
  53. } else {
  54. let scope = path.scope;
  55. const name = node.id.name;
  56. while (scope !== func.parentPath.scope) {
  57. if (scope.hasOwnBinding(name) && !scope.bindingIdentifierEquals(name, node.id)) {
  58. scope.rename(name);
  59. }
  60. scope = scope.parent;
  61. }
  62. }
  63. path.replaceWith(_core.types.conditionalExpression(_core.types.binaryExpression("instanceof", _core.types.thisExpression(), _core.types.cloneNode(node.id)), constructor, scope.buildUndefinedNode()));
  64. }
  65. }
  66. }
  67. };
  68. });
  69. exports.default = _default;