UNPKG

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