Debian Codegraph @

packages/babel-plugin-transform-async-to-generator/src/index.ts

raw
1 import { declare } from "@babel/helper-plugin-utils";
2 import remapAsyncToGenerator from "@babel/helper-remap-async-to-generator";
3 import { addNamed } from "@babel/helper-module-imports";
4 import { types as t } from "@babel/core";
5
6 export interface Options {
7 method?: string;
8 module?: string;
9 }
10
11 type State = {
12 methodWrapper?: t.Identifier | t.SequenceExpression;
13 };
14
15 export default declare<State>((api, options: Options) => {
16 api.assertVersion(7);
17
18 const { method, module } = options;
19 // Todo(BABEL 8): Consider default it to false
20 const noNewArrows = api.assumption("noNewArrows") ?? true;
21 const ignoreFunctionLength = api.assumption("ignoreFunctionLength") ?? false;
22
23 if (method && module) {
24 return {
25 name: "transform-async-to-generator",
26
27 visitor: {
28 Function(path, state) {
29 if (!path.node.async || path.node.generator) return;
30
31 let wrapAsync = state.methodWrapper;
32 if (wrapAsync) {
33 wrapAsync = t.cloneNode(wrapAsync);
34 } else {
35 wrapAsync = state.methodWrapper = addNamed(path, method, module);
36 }
37
38 remapAsyncToGenerator(
39 path,
40 { wrapAsync },
41 noNewArrows,
42 ignoreFunctionLength,
43 );
44 },
45 },
46 };
47 }
48
49 return {
50 name: "transform-async-to-generator",
51
52 visitor: {
53 Function(path, state) {
54 if (!path.node.async || path.node.generator) return;
55
56 remapAsyncToGenerator(
57 path,
58 { wrapAsync: state.addHelper("asyncToGenerator") },
59 noNewArrows,
60 ignoreFunctionLength,
61 );
62 },
63 },
64 };
65 });