ai_old/js/console.go
Star 767d87ac3e update throw exception
add util.load and util.save
2024-09-24 13:34:32 +08:00

82 lines
2.0 KiB
Go

package js
import (
"apigo.cc/ai/ai/goja"
"fmt"
"github.com/ssgo/u"
"strings"
)
func RequireConsole() map[string]any {
return map[string]any{
"print": func(args goja.FunctionCall) goja.Value {
consolePrint(args, "print", nil)
return nil
},
"println": func(args goja.FunctionCall) goja.Value {
consolePrint(args, "log", nil)
return nil
},
"log": func(args goja.FunctionCall) goja.Value {
consolePrint(args, "log", nil)
return nil
},
"info": func(args goja.FunctionCall) goja.Value {
consolePrint(args, "info", nil)
return nil
},
"warn": func(args goja.FunctionCall, vm *goja.Runtime) goja.Value {
consolePrint(args, "warn", vm)
return nil
},
"error": func(args goja.FunctionCall, vm *goja.Runtime) goja.Value {
consolePrint(args, "error", vm)
return nil
},
"debug": func(args goja.FunctionCall, vm *goja.Runtime) goja.Value {
consolePrint(args, "debug", vm)
return nil
},
"input": func(args goja.FunctionCall, vm *goja.Runtime) goja.Value {
consolePrint(args, "print", nil)
line := ""
_, _ = fmt.Scanln(&line)
return vm.ToValue(line)
},
}
}
func consolePrint(args goja.FunctionCall, typ string, vm *goja.Runtime) {
arr := make([]any, len(args.Arguments))
textColor := u.TextNone
switch typ {
case "info":
textColor = u.TextCyan
case "warn":
textColor = u.TextYellow
case "error":
textColor = u.TextRed
}
for i, arg := range args.Arguments {
if textColor != u.TextNone {
arr[i] = u.Color(u.StringP(arg.Export()), textColor, u.BgNone)
} else {
arr[i] = u.StringP(arg.Export())
}
}
if (typ == "warn" || typ == "error" || typ == "debug") && vm != nil {
callStacks := make([]string, 0)
for _, stack := range vm.CaptureCallStack(0, nil) {
callStacks = append(callStacks, u.Color(" "+stack.Position().String(), textColor, u.BgNone))
}
fmt.Println(arr...)
fmt.Println(strings.Join(callStacks, "\n"))
} else if typ == "print" {
fmt.Print(arr...)
} else {
fmt.Println(arr...)
}
}