index.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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 _helperRemapAsyncToGenerator = require("@babel/helper-remap-async-to-generator");
  8. var _pluginSyntaxAsyncGenerators = require("@babel/plugin-syntax-async-generators");
  9. var _core = require("@babel/core");
  10. var _forAwait = require("./for-await");
  11. var _helperEnvironmentVisitor = require("@babel/helper-environment-visitor");
  12. var _default = (0, _helperPluginUtils.declare)(api => {
  13. api.assertVersion(7);
  14. const yieldStarVisitor = _core.traverse.visitors.merge([{
  15. ArrowFunctionExpression(path) {
  16. path.skip();
  17. },
  18. YieldExpression({
  19. node
  20. }, state) {
  21. if (!node.delegate) return;
  22. const callee = state.addHelper("asyncGeneratorDelegate");
  23. node.argument = _core.types.callExpression(callee, [_core.types.callExpression(state.addHelper("asyncIterator"), [node.argument]), state.addHelper("awaitAsyncGenerator")]);
  24. }
  25. }, _helperEnvironmentVisitor.default]);
  26. const forAwaitVisitor = _core.traverse.visitors.merge([{
  27. ArrowFunctionExpression(path) {
  28. path.skip();
  29. },
  30. ForOfStatement(path, {
  31. file
  32. }) {
  33. const {
  34. node
  35. } = path;
  36. if (!node.await) return;
  37. const build = (0, _forAwait.default)(path, {
  38. getAsyncIterator: file.addHelper("asyncIterator")
  39. });
  40. const {
  41. declar,
  42. loop
  43. } = build;
  44. const block = loop.body;
  45. path.ensureBlock();
  46. if (declar) {
  47. block.body.push(declar);
  48. }
  49. block.body.push(...path.node.body.body);
  50. _core.types.inherits(loop, node);
  51. _core.types.inherits(loop.body, node.body);
  52. if (build.replaceParent) {
  53. path.parentPath.replaceWithMultiple(build.node);
  54. } else {
  55. path.replaceWithMultiple(build.node);
  56. }
  57. }
  58. }, _helperEnvironmentVisitor.default]);
  59. const visitor = {
  60. Function(path, state) {
  61. if (!path.node.async) return;
  62. path.traverse(forAwaitVisitor, state);
  63. if (!path.node.generator) return;
  64. path.traverse(yieldStarVisitor, state);
  65. (0, _helperRemapAsyncToGenerator.default)(path, {
  66. wrapAsync: state.addHelper("wrapAsyncGenerator"),
  67. wrapAwait: state.addHelper("awaitAsyncGenerator")
  68. });
  69. }
  70. };
  71. return {
  72. name: "proposal-async-generator-functions",
  73. inherits: _pluginSyntaxAsyncGenerators.default,
  74. visitor: {
  75. Program(path, state) {
  76. path.traverse(visitor, state);
  77. }
  78. }
  79. };
  80. });
  81. exports.default = _default;