-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.ts
More file actions
339 lines (290 loc) · 9.33 KB
/
utils.ts
File metadata and controls
339 lines (290 loc) · 9.33 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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
import { extname } from 'node:path'
import { ancestorWalk } from './walk.js'
import type { Node } from 'oxc-parser'
import type { Specifier } from '@knighted/specifier'
import type { IdentMeta, SpannedNode, Scope, CjsExport } from './types.js'
import { scopes as scopeNodes } from './helpers/scope.js'
import { identifier } from './helpers/identifier.js'
type UpdateSrcLang = Parameters<Specifier['updateSrc']>[1]
const getLangFromExt = (filename: string): UpdateSrcLang => {
const ext = extname(filename)
if (ext.endsWith('.js')) {
return 'js'
}
if (ext.endsWith('.ts')) {
return 'ts'
}
if (ext === '.tsx') {
return 'tsx'
}
if (ext === '.jsx') {
return 'jsx'
}
}
const isValidUrl = (url: string) => {
try {
new URL(url)
return true
} catch {
return false
}
}
const exportsRename = '__exports'
const requireMainRgx = /(require\.main\s*===\s*module|module\s*===\s*require\.main)/g
const resolveExportTarget = (node: Node) => {
if (node.type !== 'MemberExpression') return null
const base = node.object
const prop = node.property
if (prop.type !== 'Identifier') return null
if (base.type === 'Identifier' && base.name === 'exports') {
return { key: prop.name, via: 'exports' as const }
}
if (
base.type === 'MemberExpression' &&
base.object.type === 'Identifier' &&
base.object.name === 'module' &&
base.property.type === 'Identifier' &&
base.property.name === 'exports'
) {
return { key: prop.name, via: 'module.exports' as const }
}
if (
base.type === 'Identifier' &&
base.name === 'module' &&
prop.type === 'Identifier' &&
prop.name === 'exports'
) {
return { key: 'default', via: 'module.exports' as const }
}
return null
}
const collectCjsExports = async (ast: Node) => {
const exportsMap = new Map<string, CjsExport>()
const localToExport = new Map<string, Set<string>>()
await ancestorWalk(ast, {
enter(node) {
if (node.type === 'AssignmentExpression') {
const target = resolveExportTarget(node.left)
if (target) {
const entry = exportsMap.get(target.key) ?? {
key: target.key,
writes: [],
via: new Set(),
reassignments: [],
}
entry.via.add(target.via)
entry.writes.push(node)
if (node.right.type === 'Identifier') {
entry.fromIdentifier ??= node.right.name
if (entry.fromIdentifier) {
const set = localToExport.get(entry.fromIdentifier) ?? new Set<string>()
set.add(target.key)
localToExport.set(entry.fromIdentifier, set)
}
}
exportsMap.set(target.key, entry)
return
}
if (node.left.type === 'Identifier') {
const keys = localToExport.get(node.left.name)
if (keys) {
keys.forEach(key => {
const entry = exportsMap.get(key)
if (entry) {
entry.reassignments.push(node)
exportsMap.set(key, entry)
}
})
}
}
}
},
})
return exportsMap
}
const collectScopeIdentifiers = (node: Node, scopes: Scope[]) => {
const { type } = node
switch (type) {
case 'BlockStatement':
case 'ClassBody':
scopes.push({ node, type: 'Block', name: type, idents: new Set<string>() })
break
case 'FunctionDeclaration':
case 'FunctionExpression':
case 'ArrowFunctionExpression':
{
const name = node.id ? node.id.name : 'anonymous'
const scope = { node, name, type: 'Function', idents: new Set<string>() }
node.params
.map(param => {
if (param.type === 'TSParameterProperty') {
return param.parameter
}
if (param.type === 'RestElement') {
return param.argument
}
if (param.type === 'AssignmentPattern') {
return param.left
}
return param
})
.filter(identifier.isNamed)
.forEach(param => {
scope.idents.add(param.name)
})
/**
* If a FunctionExpression has an id, it is a named function expression.
* The function expression name shadows the module scope identifier, so
* we don't want to count reads of module identifers that have the same name.
* They also do not cause a SyntaxError if the function expression name is
* the same as a module scope identifier.
*
* TODO: Is this necessary for FunctionDeclaration?
*/
if (node.type === 'FunctionExpression' && node.id) {
scope.idents.add(node.id.name)
}
// First add the function to any previous scopes
if (scopes.length > 0) {
scopes[scopes.length - 1].idents.add(name)
}
// Then add the function scope to the scopes stack
scopes.push(scope)
}
break
case 'ClassDeclaration':
{
const className = node.id ? node.id.name : 'anonymous'
// First add the class to any previous scopes
if (scopes.length > 0) {
scopes[scopes.length - 1].idents.add(className)
}
// Then add the class to the scopes stack
scopes.push({ node, name: className, type: 'Class', idents: new Set() })
}
break
case 'ClassExpression':
{
}
break
case 'VariableDeclaration':
if (scopes.length > 0) {
const scope = scopes[scopes.length - 1]
node.declarations.forEach(decl => {
if (decl.type === 'VariableDeclarator' && decl.id.type === 'Identifier') {
scope.idents.add(decl.id.name)
}
})
}
break
}
}
/**
* Collects all module scope identifiers in the AST.
*
* Ignores identifiers that are in functions or classes.
* Ignores new scopes for StaticBlock nodes (can only reference static class members).
*
* Special case handling for these which create their own scopes,
* but are also valid module scope identifiers:
* - ClassDeclaration
* - FunctionDeclaration
*
* Special case handling for var inside BlockStatement
* which are also valid module scope identifiers.
*/
const collectModuleIdentifiers = async (ast: Node, hoisting: boolean = true) => {
const identifiers = new Map<string, IdentMeta>()
const globalReads = new Map<string, SpannedNode[]>()
const scopes: Scope[] = []
await ancestorWalk(ast, {
enter(node, ancestors) {
const { type } = node
collectScopeIdentifiers(node, scopes)
// Add module scope identifiers to the registry map
if (type === 'Identifier') {
const { name } = node
const meta = identifiers.get(name) ?? { declare: [], read: [] }
const isDeclaration = identifier.isDeclaration(ancestors)
const inScope = scopes.some(
scope => scope.idents.has(name) || scope.name === name,
)
if (
hoisting &&
!identifier.isDeclaration(ancestors) &&
!identifier.isFunctionExpressionId(ancestors) &&
!identifier.isExportSpecifierAlias(ancestors) &&
!identifier.isClassPropertyKey(ancestors) &&
!identifier.isMethodDefinitionKey(ancestors) &&
!identifier.isMemberKey(ancestors) &&
!identifier.isPropertyKey(ancestors) &&
!identifier.isIife(ancestors) &&
!inScope
) {
if (globalReads.has(name)) {
globalReads.get(name)?.push(node)
} else {
globalReads.set(name, [node])
}
}
if (isDeclaration) {
const isModuleScope = identifier.isModuleScope(ancestors)
const isClassOrFuncDeclaration =
identifier.isClassOrFuncDeclarationId(ancestors)
const isVarDeclarationInGlobalScope =
identifier.isVarDeclarationInGlobalScope(ancestors)
if (
isModuleScope ||
isClassOrFuncDeclaration ||
isVarDeclarationInGlobalScope
) {
meta.declare.push(node)
// Check for hoisted reads
if (hoisting && globalReads.has(name)) {
const reads = globalReads.get(name)
if (reads) {
reads.forEach(read => {
if (!meta.read.includes(read)) {
meta.read.push(read)
}
})
}
}
identifiers.set(name, meta)
}
} else {
if (
identifiers.has(name) &&
!inScope &&
!identifier.isIife(ancestors) &&
!identifier.isFunctionExpressionId(ancestors) &&
!identifier.isExportSpecifierAlias(ancestors) &&
!identifier.isClassPropertyKey(ancestors) &&
!identifier.isMethodDefinitionKey(ancestors) &&
!identifier.isMemberKey(ancestors) &&
!identifier.isPropertyKey(ancestors)
) {
// Closure is referencing module scope identifier
meta.read.push(node)
}
}
}
},
leave(node) {
const { type } = node
if (scopeNodes.includes(type)) {
scopes.pop()
}
},
})
return identifiers
}
export {
getLangFromExt,
isValidUrl,
collectScopeIdentifiers,
collectModuleIdentifiers,
collectCjsExports,
exportsRename,
requireMainRgx,
}