const-enum.js 1.89 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
"use strict";

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

var _enum = require("./enum");

function transpileConstEnum(path, t) {
  const {
    name
  } = path.node.id;
  const parentIsExport = path.parentPath.isExportNamedDeclaration();
  let isExported = parentIsExport;

  if (!isExported && t.isProgram(path.parent)) {
    isExported = path.parent.body.some(stmt => t.isExportNamedDeclaration(stmt) && !stmt.source && stmt.specifiers.some(spec => t.isExportSpecifier(spec) && spec.local.name === name));
  }

  const entries = (0, _enum.translateEnumValues)(path, t);

  if (isExported) {
    const obj = t.objectExpression(entries.map(([name, value]) => t.objectProperty(t.isValidIdentifier(name) ? t.identifier(name) : t.stringLiteral(name), value)));

    if (path.scope.hasOwnBinding(name)) {
      (parentIsExport ? path.parentPath : path).replaceWith(t.expressionStatement(t.callExpression(t.memberExpression(t.identifier("Object"), t.identifier("assign")), [path.node.id, obj])));
    } else {
      path.replaceWith(t.variableDeclaration("var", [t.variableDeclarator(path.node.id, obj)]));
      path.scope.registerDeclaration(path);
    }

    return;
  }

  const entriesMap = new Map(entries);
  path.scope.path.traverse({
    Scope(path) {
      if (path.scope.hasOwnBinding(name)) path.skip();
    },

    MemberExpression(path) {
      if (!t.isIdentifier(path.node.object, {
        name
      })) return;
      let key;

      if (path.node.computed) {
        if (t.isStringLiteral(path.node.property)) {
          key = path.node.property.value;
        } else {
          return;
        }
      } else if (t.isIdentifier(path.node.property)) {
        key = path.node.property.name;
      } else {
        return;
      }

      if (!entriesMap.has(key)) return;
      path.replaceWith(t.cloneNode(entriesMap.get(key)));
    }

  });
  path.remove();
}