-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtopLevelAwait.js
More file actions
160 lines (142 loc) · 5.84 KB
/
topLevelAwait.js
File metadata and controls
160 lines (142 loc) · 5.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
/* Babel plugin: transform-top-level-await
* ------------------------------------------------------------------
* Enables use of true "top-level await" in environments that execute
* code as CommonJS (e.g. Node.js REPL, scripts evaluated with `vm`).
*
* The plugin transforms code containing top-level await by:
* 1. Detecting top-level await and illegal top-level return statements
* 2. Preserving statements before the first top-level await
* 3. Wrapping remaining code in an async IIFE while maintaining proper
* variable scoping and declaration behavior
*
* Key behaviours:
* 1. Abort when the source does NOT contain a top-level `await` or
* when it DOES contain an illegal top-level `return`.
* 2. Preserve statements before the first top-level await without modification
* 3. Hoist all variable declarations as `let` declarations, so the bindings
* stay visible after evaluation.
* 4. Rewrite top-level variable declarations into assignment
* expressions executed *inside* the async IIFE.
* 5. Ensure the last expression's value is exposed by returning the value,
* except when it is an assignment expression.
*/
module.exports = function topLevelAwait({ types: t }) {
return {
name: 'transform-top-level-await',
visitor: {
Program: {
enter(programPath) {
const { node } = programPath
// 1. Detect presence of top-level await and illegal top-level return.
let containsTopLevelAwait = false
let hasIllegalReturn = false
programPath.traverse({
AwaitExpression(path) {
if (!path.findParent((p) => p.isFunction())) {
containsTopLevelAwait = true
path.stop()
}
},
ReturnStatement(path) {
if (!path.findParent((p) => p.isFunction())) {
hasIllegalReturn = true
path.stop()
}
},
})
if (hasIllegalReturn) {
throw programPath.buildCodeFrameError(
'Illegal top-level return in module using top-level await.'
)
}
// Abort early if there is no top-level await – nothing to transform.
if (!containsTopLevelAwait) return
// 2. Identify index of first statement that contains top-level await.
const bodyPaths = programPath.get('body')
let firstAwaitIdx = -1
for (let i = 0; i < bodyPaths.length && firstAwaitIdx === -1; i++) {
const stmtPath = bodyPaths[i]
stmtPath.traverse({
AwaitExpression(path) {
if (!path.findParent((p) => p.isFunction())) {
firstAwaitIdx = i
path.stop()
}
},
})
}
// If somehow none found (shouldn't get here), bail.
if (firstAwaitIdx === -1) return
// 2. Preserve statements before the first await.
const prefixStmts = node.body.slice(0, firstAwaitIdx)
const transformStmts = node.body.slice(firstAwaitIdx)
// 3. Prepare hoisting containers and IIFE body collector.
const letDeclarators = []
const iifeBody = []
// Helper to collect binding identifiers from any pattern.
const collectIds = (pattern) =>
Object.values(t.getBindingIdentifiers(pattern))
// 4. Transform statements that need to be inside the IIFE.
transformStmts.forEach((stmt) => {
if (t.isVariableDeclaration(stmt)) {
stmt.declarations.forEach((decl) => {
// Collect ids for hoisting.
const ids = collectIds(decl.id)
ids.forEach((id) => {
letDeclarators.push(
t.variableDeclarator(t.identifier(id.name))
)
})
// Build assignment expression for inside the IIFE.
const assignment = t.expressionStatement(
t.assignmentExpression(
'=',
decl.id,
decl.init || t.identifier('undefined')
)
)
iifeBody.push(assignment)
})
} else if (t.isClassDeclaration(stmt) && stmt.id) {
// Hoist class declarations as `let` and assign inside IIFE.
letDeclarators.push(
t.variableDeclarator(t.identifier(stmt.id.name))
)
const assignClass = t.expressionStatement(
t.assignmentExpression('=', stmt.id, t.toExpression(stmt))
)
iifeBody.push(assignClass)
} else {
// Other statements are pushed unmodified.
iifeBody.push(stmt)
}
})
// 5. Ensure last expression value is returned (unless it is an assignment).
if (iifeBody.length) {
const last = iifeBody[iifeBody.length - 1]
if (
t.isExpressionStatement(last) &&
!t.isAssignmentExpression(last.expression)
) {
iifeBody[iifeBody.length - 1] = t.returnStatement(last.expression)
}
}
// Compose hoisted declarations.
const hoisted = []
if (letDeclarators.length) {
hoisted.push(t.variableDeclaration('let', letDeclarators))
}
// 3. Wrap remaining logic inside an async IIFE.
const asyncIIFECall = t.expressionStatement(
t.callExpression(
t.arrowFunctionExpression([], t.blockStatement(iifeBody), true),
[]
)
)
// Replace program body in-place (prefix + transform result).
programPath.node.body = [...prefixStmts, ...hoisted, asyncIIFECall]
},
},
},
}
}