index.js 2.18 KB
Newer Older
Rosanny Sihombing's avatar
Rosanny Sihombing committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _helperPluginUtils = require("@babel/helper-plugin-utils");

var _core = require("@babel/core");

var _default = (0, _helperPluginUtils.declare)(api => {
  api.assertVersion(7);
  return {
    name: "transform-typeof-symbol",
    visitor: {
      Scope({
        scope
      }) {
        if (!scope.getBinding("Symbol")) {
          return;
        }

        scope.rename("Symbol");
      },

      UnaryExpression(path) {
        const {
          node,
          parent
        } = path;
        if (node.operator !== "typeof") return;

        if (path.parentPath.isBinaryExpression() && _core.types.EQUALITY_BINARY_OPERATORS.indexOf(parent.operator) >= 0) {
          const opposite = path.getOpposite();

          if (opposite.isStringLiteral() && opposite.node.value !== "symbol" && opposite.node.value !== "object") {
            return;
          }
        }

        let isUnderHelper = path.findParent(path => {
          if (path.isFunction()) {
            var _path$get;

            return ((_path$get = path.get("body.directives.0")) == null ? void 0 : _path$get.node.value.value) === "@babel/helpers - typeof";
          }
        });
        if (isUnderHelper) return;
        const helper = this.addHelper("typeof");
        isUnderHelper = path.findParent(path => {
          return path.isVariableDeclarator() && path.node.id === helper || path.isFunctionDeclaration() && path.node.id && path.node.id.name === helper.name;
        });

        if (isUnderHelper) {
          return;
        }

        const call = _core.types.callExpression(helper, [node.argument]);

        const arg = path.get("argument");

        if (arg.isIdentifier() && !path.scope.hasBinding(arg.node.name, true)) {
          const unary = _core.types.unaryExpression("typeof", _core.types.cloneNode(node.argument));

          path.replaceWith(_core.types.conditionalExpression(_core.types.binaryExpression("===", unary, _core.types.stringLiteral("undefined")), _core.types.stringLiteral("undefined"), call));
        } else {
          path.replaceWith(call);
        }
      }

    }
  };
});

exports.default = _default;