diff --git a/quickgo/js/globals.go b/quickgo/js/globals.go index 9e883a7..0c200aa 100644 --- a/quickgo/js/globals.go +++ b/quickgo/js/globals.go @@ -1,11 +1,35 @@ package js -import "fmt" +import ( + "encoding/base64" + "encoding/json" + "fmt" +) + +var PanicOnError = false func logConsole(args ...any) { fmt.Println(args...) } +func Console() *JSConsole { + return &JSConsole{ + Debug: logConsole, + Log: logConsole, + Info: logConsole, + Warn: logConsole, + Error: logConsole, + } +} + +func JSON() *_json { + return &_json{} +} + +func Base64() *_base64 { + return &_base64{} +} + type JSConsole struct { Debug func(...any) `json:"debug"` Log func(...any) `json:"log"` @@ -14,12 +38,46 @@ type JSConsole struct { Error func(...any) `json:"error"` } -func Console() *JSConsole { - return &JSConsole{ - Debug: logConsole, - Log: logConsole, - Info: logConsole, - Warn: logConsole, - Error: logConsole, +type _json struct{} + +func (j *_json) Encode(v any) string { + data, err := json.Marshal(v) + must(err) + return string(data) +} + +func (j *_json) DecodeObject(s string) any { + var v = make(map[string]any) + json.Unmarshal([]byte(s), &v) + return v +} + +func (j *_json) DecodeArray(s string) []any { + var v = make([]any, 0) + json.Unmarshal([]byte(s), &v) + return v +} + +type _base64 struct{} + +func (b *_base64) Encode(data string) string { + return base64.StdEncoding.EncodeToString([]byte(data)) +} + +func (b *_base64) Decode(data string) any { + var arr, err = base64.StdEncoding.DecodeString(data) + if must(err) { + return nil + } + return string(arr) +} + +func must(err error) bool { + if err != nil { + if PanicOnError { + panic(err) + } + return true } + return false } diff --git a/quickgo/js/js.go b/quickgo/js/js.go index 0ebcf11..ed0659a 100644 --- a/quickgo/js/js.go +++ b/quickgo/js/js.go @@ -68,6 +68,9 @@ func (s *Command) Run(scriptSource string) (err error) { goja.TagFieldNameMapper("json", true), ) + vm.Set("json", JSON()) + vm.Set("base64", Base64()) + for k, v := range s._Globals { err = vm.Set(k, v) if err != nil { diff --git a/quickgo/quickgo_commands.go b/quickgo/quickgo_commands.go index b3e5b72..67df10b 100644 --- a/quickgo/quickgo_commands.go +++ b/quickgo/quickgo_commands.go @@ -97,9 +97,15 @@ func (a *App) ExecJS(targetDir string, scriptName string, args map[string]any) ( return errors.Wrapf(err, "failed to read script %s", script) } - var projectName string + var ( + projectName string + projectPath string + ) if a.ProjectConfig != nil { projectName = a.ProjectConfig.Name + projectPath = getTargetDirectory( + projectName, + ) } cmd = js.NewScript( @@ -111,9 +117,7 @@ func (a *App) ExecJS(targetDir string, scriptName string, args map[string]any) ( "config": a.Config, "environ": args, "projectName": projectName, - "projectPath": GetProjectDirectoryPath( - a.ProjectConfig.Name, true, - ), + "projectPath": projectPath, }, "os": map[string]any{ "args": os.Args,