index.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. var _helperPluginUtils = require("@babel/helper-plugin-utils");
  7. var _pluginSyntaxFunctionSent = require("@babel/plugin-syntax-function-sent");
  8. var _helperWrapFunction = require("@babel/helper-wrap-function");
  9. var _core = require("@babel/core");
  10. var _default = (0, _helperPluginUtils.declare)(api => {
  11. api.assertVersion(7);
  12. const isFunctionSent = node => _core.types.isIdentifier(node.meta, {
  13. name: "function"
  14. }) && _core.types.isIdentifier(node.property, {
  15. name: "sent"
  16. });
  17. const hasBeenReplaced = (node, sentId) => _core.types.isAssignmentExpression(node) && _core.types.isIdentifier(node.left, {
  18. name: sentId
  19. });
  20. const yieldVisitor = {
  21. Function(path) {
  22. path.skip();
  23. },
  24. YieldExpression(path) {
  25. if (!hasBeenReplaced(path.parent, this.sentId)) {
  26. path.replaceWith(_core.types.assignmentExpression("=", _core.types.identifier(this.sentId), path.node));
  27. }
  28. },
  29. MetaProperty(path) {
  30. if (isFunctionSent(path.node)) {
  31. path.replaceWith(_core.types.identifier(this.sentId));
  32. }
  33. }
  34. };
  35. return {
  36. name: "proposal-function-sent",
  37. inherits: _pluginSyntaxFunctionSent.default,
  38. visitor: {
  39. MetaProperty(path, state) {
  40. if (!isFunctionSent(path.node)) return;
  41. const fnPath = path.getFunctionParent();
  42. if (!fnPath.node.generator) {
  43. throw new Error("Parent generator function not found");
  44. }
  45. const sentId = path.scope.generateUid("function.sent");
  46. fnPath.traverse(yieldVisitor, {
  47. sentId
  48. });
  49. fnPath.node.body.body.unshift(_core.types.variableDeclaration("let", [_core.types.variableDeclarator(_core.types.identifier(sentId), _core.types.yieldExpression())]));
  50. (0, _helperWrapFunction.default)(fnPath, state.addHelper("skipFirstGeneratorNext"));
  51. }
  52. }
  53. };
  54. });
  55. exports.default = _default;