-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathutils.cjs
More file actions
87 lines (67 loc) · 2.16 KB
/
utils.cjs
File metadata and controls
87 lines (67 loc) · 2.16 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
const { types } = require("@babel/core")
module.exports.getDestructredProperties = funcPath => {
const firstParam = funcPath.node.params[0]
const objectPattern = firstParam.type === "AssignmentPattern"
? firstParam.left
: firstParam
return objectPattern.properties
}
const getProgram = path => path.findParent(path => path.isProgram())
module.exports.getProgram = getProgram
const addImportDeclarationToProgram = (types, program, specifier, imported, source) => {
program.node.body.unshift(
types.importDeclaration(
[types.importSpecifier(specifier, types.identifier(imported))],
types.stringLiteral(source)
)
)
}
module.exports.addImportDeclarationToProgram = addImportDeclarationToProgram
module.exports.addStatementToFunction = (funcPath, statement) => {
if (funcPath.node.body.type === 'BlockStatement') {
funcPath.node.body.body.unshift(statement)
} else {
funcPath.node.body = types.blockStatement([
statement,
types.returnStatement(funcPath.node.body)
])
}
}
/**
* Looks for an existing unique import. If none is found, we create a new import and add it
* to the file.
*/
module.exports.getOrCreateUniqueImport = (funcPath, specifier) => {
let uniqueName = lookForUniqueImport(funcPath, specifier)
// If not found, create one
if (!uniqueName) {
const program = getProgram(funcPath)
uniqueName = program.scope.generateUidIdentifier(specifier)
// We mark the identifier as unique so we can find it later
uniqueName.unique = true
addImportDeclarationToProgram(types, program, uniqueName, specifier, "solid-js")
}
return uniqueName
}
/**
* Looks for an existing `mergeProps` import declaration that is marked as unique.
*/
function lookForUniqueImport(funcPath, targetSpecifier) {
const program = getProgram(funcPath)
let mergePropsUniqueName
program.traverse({
ImportDeclaration(path) {
if (path.node.source.value !== "solid-js")
return
for (const specifier of path.node.specifiers)
if (specifier.imported
&& specifier.imported.name === targetSpecifier
&& specifier.local.unique
) {
mergePropsUniqueName = specifier.local
return
}
}
})
return mergePropsUniqueName
}