index.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. function _helperPluginUtils() {
  7. const data = require("@babel/helper-plugin-utils");
  8. _helperPluginUtils = function () {
  9. return data;
  10. };
  11. return data;
  12. }
  13. function _core() {
  14. const data = require("@babel/core");
  15. _core = function () {
  16. return data;
  17. };
  18. return data;
  19. }
  20. var _default = (0, _helperPluginUtils().declare)(api => {
  21. api.assertVersion(7);
  22. return {
  23. name: "transform-new-target",
  24. visitor: {
  25. MetaProperty(path) {
  26. const meta = path.get("meta");
  27. const property = path.get("property");
  28. const {
  29. scope
  30. } = path;
  31. if (meta.isIdentifier({
  32. name: "new"
  33. }) && property.isIdentifier({
  34. name: "target"
  35. })) {
  36. const func = path.findParent(path => {
  37. if (path.isClass()) return true;
  38. if (path.isFunction() && !path.isArrowFunctionExpression()) {
  39. if (path.isClassMethod({
  40. kind: "constructor"
  41. })) {
  42. return false;
  43. }
  44. return true;
  45. }
  46. return false;
  47. });
  48. if (!func) {
  49. throw path.buildCodeFrameError("new.target must be under a (non-arrow) function or a class.");
  50. }
  51. const {
  52. node
  53. } = func;
  54. if (!node.id) {
  55. if (func.isMethod()) {
  56. path.replaceWith(scope.buildUndefinedNode());
  57. return;
  58. }
  59. node.id = scope.generateUidIdentifier("target");
  60. }
  61. const constructor = _core().types.memberExpression(_core().types.thisExpression(), _core().types.identifier("constructor"));
  62. if (func.isClass()) {
  63. path.replaceWith(constructor);
  64. return;
  65. }
  66. path.replaceWith(_core().types.conditionalExpression(_core().types.binaryExpression("instanceof", _core().types.thisExpression(), _core().types.cloneNode(node.id)), constructor, scope.buildUndefinedNode()));
  67. }
  68. }
  69. }
  70. };
  71. });
  72. exports.default = _default;