Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
projectdiscovery
GitHub Repository: projectdiscovery/nuclei
Path: blob/dev/pkg/js/devtools/tsgen/astutil.go
2070 views
1
package tsgen
2
3
import (
4
"fmt"
5
"go/ast"
6
"strings"
7
)
8
9
// isExported checks if the given name is exported
10
func isExported(name string) bool {
11
return ast.IsExported(name)
12
}
13
14
// exprToString converts an expression to a string
15
func exprToString(expr ast.Expr) string {
16
switch t := expr.(type) {
17
case *ast.Ident:
18
return toTsTypes(t.Name)
19
case *ast.SelectorExpr:
20
return exprToString(t.X) + "." + t.Sel.Name
21
case *ast.StarExpr:
22
return exprToString(t.X)
23
case *ast.ArrayType:
24
return toTsTypes("[]" + exprToString(t.Elt))
25
case *ast.InterfaceType:
26
return "interface{}"
27
case *ast.MapType:
28
return "Record<" + toTsTypes(exprToString(t.Key)) + ", " + toTsTypes(exprToString(t.Value)) + ">"
29
// Add more cases to handle other types
30
default:
31
return fmt.Sprintf("%T", expr)
32
}
33
}
34
35
// toTsTypes converts Go types to TypeScript types
36
func toTsTypes(t string) string {
37
if strings.Contains(t, "interface{}") {
38
return "any"
39
}
40
if strings.HasPrefix(t, "map[") {
41
return convertMaptoRecord(t)
42
}
43
switch t {
44
case "string":
45
return "string"
46
case "int", "int8", "int16", "int32", "int64", "uint", "uint8", "uint16", "uint32", "uint64":
47
return "number"
48
case "float32", "float64":
49
return "number"
50
case "bool":
51
return "boolean"
52
case "[]byte":
53
return "Uint8Array"
54
case "interface{}":
55
return "any"
56
case "time.Duration":
57
return "number"
58
case "time.Time":
59
return "Date"
60
default:
61
if strings.HasPrefix(t, "[]") {
62
return toTsTypes(strings.TrimPrefix(t, "[]")) + "[]"
63
}
64
return t
65
}
66
}
67
68
func TsDefaultValue(t string) string {
69
switch t {
70
case "string":
71
return `""`
72
case "number":
73
return `0`
74
case "boolean":
75
return `false`
76
case "Uint8Array":
77
return `new Uint8Array(8)`
78
case "any":
79
return `undefined`
80
case "interface{}":
81
return `undefined`
82
default:
83
if strings.Contains(t, "[]") {
84
return `[]`
85
}
86
return "new " + t + "()"
87
}
88
}
89
90
// Ternary is a ternary operator for strings
91
func Ternary(condition bool, trueVal, falseVal string) string {
92
if condition {
93
return trueVal
94
}
95
return falseVal
96
}
97
98
// checkCanFail checks if a function can fail
99
func checkCanFail(fn *ast.FuncDecl) bool {
100
if fn.Type.Results != nil {
101
for _, result := range fn.Type.Results.List {
102
// Check if any of the return types is an error
103
if ident, ok := result.Type.(*ast.Ident); ok && ident.Name == "error" {
104
return true
105
}
106
}
107
}
108
return false
109
}
110
111