-
Notifications
You must be signed in to change notification settings - Fork 0
/
typescript.go
executable file
·70 lines (64 loc) · 1.89 KB
/
typescript.go
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
package typescript
import (
_ "embed"
"encoding/base64"
"encoding/json"
"fmt"
"github.com/clarkmcc/go-typescript/utils"
"github.com/davidforest123/goutil/basic/gerrors"
"github.com/davidforest123/goutil/container/grand"
"github.com/dop251/goja"
"strings"
)
//go:embed typescript_source/v4.7.2.js
var tsSrcV4x7x2 string
var (
allTs = map[string]*goja.Program{}
latestTsVer = "4.7.2"
)
func init() {
programV4x7x2, err := goja.Compile("", tsSrcV4x7x2, true)
if err != nil {
panic(fmt.Errorf("compiling registered source for tag '%s': %w", "4.7.2", err))
}
allTs["4.7.2"] = programV4x7x2
}
func TranspileToJavaScript(ts string, tsVer string) (string, error) {
if tsVer == "" {
tsVer = latestTsVer
}
tsProg, exist := allTs[tsVer]
if !exist {
return "", gerrors.New("typescript version %s not found", tsVer)
}
if tsProg == nil {
return "", gerrors.New("typescript program %s is nil", tsVer)
}
rt := goja.New()
_, err := rt.RunProgram(tsProg)
if err != nil {
return "", fmt.Errorf("running typescript compiler: %w", err)
}
compileOptions := map[string]interface{}{
"module": "none",
}
optionBytes, err := json.Marshal(compileOptions)
if err != nil {
return "", fmt.Errorf("marshalling compile options: %w", err)
}
decoderName := grand.RandomString(24)
rt.Set(decoderName, utils.ErrorWrapper(rt, func(call goja.FunctionCall) (interface{}, error) {
bs, err := base64.StdEncoding.DecodeString(call.Argument(0).String())
if err != nil {
return nil, err
}
return string(bs), nil
}))
transpileCmd := fmt.Sprintf("ts.transpile(%s('%s'), %s, /*fileName*/ undefined, /*diagnostics*/ undefined, /*moduleName*/ \"%s\")",
decoderName, base64.StdEncoding.EncodeToString([]byte(ts)), optionBytes, "default")
value, err := rt.RunString(transpileCmd)
if err != nil {
return "", fmt.Errorf("running compiler: %w", err)
}
return strings.TrimSuffix(value.String(), "\r\n"), nil
}