index.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = _default;
  6. var _t = require("@babel/types");
  7. const {
  8. assignmentExpression,
  9. cloneNode,
  10. isIdentifier,
  11. isLiteral,
  12. isMemberExpression,
  13. isPrivateName,
  14. isPureish,
  15. isSuper,
  16. memberExpression,
  17. toComputedKey
  18. } = _t;
  19. function getObjRef(node, nodes, scope) {
  20. let ref;
  21. if (isIdentifier(node)) {
  22. if (scope.hasBinding(node.name)) {
  23. return node;
  24. } else {
  25. ref = node;
  26. }
  27. } else if (isMemberExpression(node)) {
  28. ref = node.object;
  29. if (isSuper(ref) || isIdentifier(ref) && scope.hasBinding(ref.name)) {
  30. return ref;
  31. }
  32. } else {
  33. throw new Error(`We can't explode this node type ${node["type"]}`);
  34. }
  35. const temp = scope.generateUidIdentifierBasedOnNode(ref);
  36. scope.push({
  37. id: temp
  38. });
  39. nodes.push(assignmentExpression("=", cloneNode(temp), cloneNode(ref)));
  40. return temp;
  41. }
  42. function getPropRef(node, nodes, scope) {
  43. const prop = node.property;
  44. if (isPrivateName(prop)) {
  45. throw new Error("We can't generate property ref for private name, please install `@babel/plugin-proposal-class-properties`");
  46. }
  47. const key = toComputedKey(node, prop);
  48. if (isLiteral(key) && isPureish(key)) return key;
  49. const temp = scope.generateUidIdentifierBasedOnNode(prop);
  50. scope.push({
  51. id: temp
  52. });
  53. nodes.push(assignmentExpression("=", cloneNode(temp), cloneNode(prop)));
  54. return temp;
  55. }
  56. function _default(node, nodes, file, scope, allowedSingleIdent) {
  57. let obj;
  58. if (isIdentifier(node) && allowedSingleIdent) {
  59. obj = node;
  60. } else {
  61. obj = getObjRef(node, nodes, scope);
  62. }
  63. let ref, uid;
  64. if (isIdentifier(node)) {
  65. ref = cloneNode(node);
  66. uid = obj;
  67. } else {
  68. const prop = getPropRef(node, nodes, scope);
  69. const computed = node.computed || isLiteral(prop);
  70. uid = memberExpression(cloneNode(obj), cloneNode(prop), computed);
  71. ref = memberExpression(cloneNode(obj), cloneNode(prop), computed);
  72. }
  73. return {
  74. uid: uid,
  75. ref: ref
  76. };
  77. }