| 1 | import { declare } from "@babel/helper-plugin-utils"; |
| 2 | import { types as t } from "@babel/core"; |
| 3 | import type { NodePath } from "@babel/traverse"; |
| 4 | |
| 5 | export default declare(api => { |
| 6 | api.assertVersion(7); |
| 7 | |
| 8 | function transformStatementList(paths: NodePath<t.Statement>[]) { |
| 9 | for (const path of paths) { |
| 10 | if (!path.isFunctionDeclaration()) continue; |
| 11 | const func = path.node; |
| 12 | const declar = t.variableDeclaration("let", [ |
| 13 | t.variableDeclarator(func.id, t.toExpression(func)), |
| 14 | ]); |
| 15 | |
| 16 | // hoist it up above everything else |
| 17 | // @ts-expect-error todo(flow->ts): avoid mutations |
| 18 | declar._blockHoist = 2; |
| 19 | |
| 20 | // todo: name this |
| 21 | func.id = null; |
| 22 | |
| 23 | path.replaceWith(declar); |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | return { |
| 28 | name: "transform-block-scoped-functions", |
| 29 | |
| 30 | visitor: { |
| 31 | BlockStatement(path) { |
| 32 | const { node, parent } = path; |
| 33 | if ( |
| 34 | t.isFunction(parent, { body: node }) || |
| 35 | t.isExportDeclaration(parent) |
| 36 | ) { |
| 37 | return; |
| 38 | } |
| 39 | |
| 40 | transformStatementList(path.get("body")); |
| 41 | }, |
| 42 | |
| 43 | SwitchCase(path) { |
| 44 | transformStatementList(path.get("consequent")); |
| 45 | }, |
| 46 | }, |
| 47 | }; |
| 48 | }); |