console.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. package console
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/xml"
  6. "sync"
  7. "time"
  8. sLog "github.com/sagernet/sing-box/log"
  9. "github.com/sagernet/sing-box/script/jsc"
  10. "github.com/sagernet/sing-box/script/modules/boxctx"
  11. F "github.com/sagernet/sing/common/format"
  12. "github.com/sagernet/sing/common/logger"
  13. "github.com/dop251/goja"
  14. )
  15. type Console struct {
  16. class jsc.Class[*Module, *Console]
  17. access sync.Mutex
  18. countMap map[string]int
  19. timeMap map[string]time.Time
  20. }
  21. func NewConsole(class jsc.Class[*Module, *Console]) goja.Value {
  22. return class.New(&Console{
  23. class: class,
  24. countMap: make(map[string]int),
  25. timeMap: make(map[string]time.Time),
  26. })
  27. }
  28. func createConsole(m *Module) jsc.Class[*Module, *Console] {
  29. class := jsc.NewClass[*Module, *Console](m)
  30. class.DefineMethod("assert", (*Console).assert)
  31. class.DefineMethod("clear", (*Console).clear)
  32. class.DefineMethod("count", (*Console).count)
  33. class.DefineMethod("countReset", (*Console).countReset)
  34. class.DefineMethod("debug", (*Console).debug)
  35. class.DefineMethod("dir", (*Console).dir)
  36. class.DefineMethod("dirxml", (*Console).dirxml)
  37. class.DefineMethod("error", (*Console).error)
  38. class.DefineMethod("group", (*Console).stub)
  39. class.DefineMethod("groupCollapsed", (*Console).stub)
  40. class.DefineMethod("groupEnd", (*Console).stub)
  41. class.DefineMethod("info", (*Console).info)
  42. class.DefineMethod("log", (*Console)._log)
  43. class.DefineMethod("profile", (*Console).stub)
  44. class.DefineMethod("profileEnd", (*Console).profileEnd)
  45. class.DefineMethod("table", (*Console).table)
  46. class.DefineMethod("time", (*Console).time)
  47. class.DefineMethod("timeEnd", (*Console).timeEnd)
  48. class.DefineMethod("timeLog", (*Console).timeLog)
  49. class.DefineMethod("timeStamp", (*Console).stub)
  50. class.DefineMethod("trace", (*Console).trace)
  51. class.DefineMethod("warn", (*Console).warn)
  52. return class
  53. }
  54. func (c *Console) stub(call goja.FunctionCall) any {
  55. return goja.Undefined()
  56. }
  57. func (c *Console) assert(call goja.FunctionCall) any {
  58. assertion := call.Argument(0).ToBoolean()
  59. if !assertion {
  60. return c.log(logger.ContextLogger.ErrorContext, call.Arguments[1:])
  61. }
  62. return goja.Undefined()
  63. }
  64. func (c *Console) clear(call goja.FunctionCall) any {
  65. return nil
  66. }
  67. func (c *Console) count(call goja.FunctionCall) any {
  68. label := jsc.AssertString(c.class.Runtime(), call.Argument(0), "label", true)
  69. if label == "" {
  70. label = "default"
  71. }
  72. c.access.Lock()
  73. newValue := c.countMap[label] + 1
  74. c.countMap[label] = newValue
  75. c.access.Unlock()
  76. writeLog(c.class.Runtime(), logger.ContextLogger.InfoContext, F.ToString(label, ": ", newValue))
  77. return goja.Undefined()
  78. }
  79. func (c *Console) countReset(call goja.FunctionCall) any {
  80. label := jsc.AssertString(c.class.Runtime(), call.Argument(0), "label", true)
  81. if label == "" {
  82. label = "default"
  83. }
  84. c.access.Lock()
  85. delete(c.countMap, label)
  86. c.access.Unlock()
  87. return goja.Undefined()
  88. }
  89. func (c *Console) log(logFunc func(logger.ContextLogger, context.Context, ...any), args []goja.Value) any {
  90. var buffer bytes.Buffer
  91. var formatString string
  92. if len(args) > 0 {
  93. formatString = args[0].String()
  94. }
  95. format(c.class.Runtime(), &buffer, formatString, args[1:]...)
  96. writeLog(c.class.Runtime(), logFunc, buffer.String())
  97. return goja.Undefined()
  98. }
  99. func (c *Console) debug(call goja.FunctionCall) any {
  100. return c.log(logger.ContextLogger.DebugContext, call.Arguments)
  101. }
  102. func (c *Console) dir(call goja.FunctionCall) any {
  103. object := jsc.AssertObject(c.class.Runtime(), call.Argument(0), "object", false)
  104. var buffer bytes.Buffer
  105. for _, key := range object.Keys() {
  106. value := object.Get(key)
  107. buffer.WriteString(key)
  108. buffer.WriteString(": ")
  109. buffer.WriteString(value.String())
  110. buffer.WriteString("\n")
  111. }
  112. writeLog(c.class.Runtime(), logger.ContextLogger.InfoContext, buffer.String())
  113. return goja.Undefined()
  114. }
  115. func (c *Console) dirxml(call goja.FunctionCall) any {
  116. var buffer bytes.Buffer
  117. encoder := xml.NewEncoder(&buffer)
  118. encoder.Indent("", " ")
  119. encoder.Encode(call.Argument(0).Export())
  120. writeLog(c.class.Runtime(), logger.ContextLogger.InfoContext, buffer.String())
  121. return goja.Undefined()
  122. }
  123. func (c *Console) error(call goja.FunctionCall) any {
  124. return c.log(logger.ContextLogger.ErrorContext, call.Arguments)
  125. }
  126. func (c *Console) info(call goja.FunctionCall) any {
  127. return c.log(logger.ContextLogger.InfoContext, call.Arguments)
  128. }
  129. func (c *Console) _log(call goja.FunctionCall) any {
  130. return c.log(logger.ContextLogger.InfoContext, call.Arguments)
  131. }
  132. func (c *Console) profileEnd(call goja.FunctionCall) any {
  133. return goja.Undefined()
  134. }
  135. func (c *Console) table(call goja.FunctionCall) any {
  136. return c.dir(call)
  137. }
  138. func (c *Console) time(call goja.FunctionCall) any {
  139. label := jsc.AssertString(c.class.Runtime(), call.Argument(0), "label", true)
  140. if label == "" {
  141. label = "default"
  142. }
  143. c.access.Lock()
  144. c.timeMap[label] = time.Now()
  145. c.access.Unlock()
  146. return goja.Undefined()
  147. }
  148. func (c *Console) timeEnd(call goja.FunctionCall) any {
  149. label := jsc.AssertString(c.class.Runtime(), call.Argument(0), "label", true)
  150. if label == "" {
  151. label = "default"
  152. }
  153. c.access.Lock()
  154. startTime, ok := c.timeMap[label]
  155. if !ok {
  156. c.access.Unlock()
  157. return goja.Undefined()
  158. }
  159. delete(c.timeMap, label)
  160. c.access.Unlock()
  161. writeLog(c.class.Runtime(), logger.ContextLogger.InfoContext, F.ToString(label, ": ", time.Since(startTime).String(), " - - timer ended"))
  162. return goja.Undefined()
  163. }
  164. func (c *Console) timeLog(call goja.FunctionCall) any {
  165. label := jsc.AssertString(c.class.Runtime(), call.Argument(0), "label", true)
  166. if label == "" {
  167. label = "default"
  168. }
  169. c.access.Lock()
  170. startTime, ok := c.timeMap[label]
  171. c.access.Unlock()
  172. if !ok {
  173. writeLog(c.class.Runtime(), logger.ContextLogger.ErrorContext, F.ToString("Timer \"", label, "\" doesn't exist."))
  174. return goja.Undefined()
  175. }
  176. writeLog(c.class.Runtime(), logger.ContextLogger.InfoContext, F.ToString(label, ": ", time.Since(startTime)))
  177. return goja.Undefined()
  178. }
  179. func (c *Console) trace(call goja.FunctionCall) any {
  180. return c.log(logger.ContextLogger.TraceContext, call.Arguments)
  181. }
  182. func (c *Console) warn(call goja.FunctionCall) any {
  183. return c.log(logger.ContextLogger.WarnContext, call.Arguments)
  184. }
  185. func writeLog(runtime *goja.Runtime, logFunc func(logger.ContextLogger, context.Context, ...any), message string) {
  186. var (
  187. ctx context.Context
  188. sLogger logger.ContextLogger
  189. )
  190. boxCtx := boxctx.FromRuntime(runtime)
  191. if boxCtx != nil {
  192. ctx = boxCtx.Context
  193. sLogger = boxCtx.Logger
  194. } else {
  195. ctx = context.Background()
  196. sLogger = sLog.StdLogger()
  197. }
  198. logFunc(sLogger, ctx, message)
  199. }
  200. func format(runtime *goja.Runtime, b *bytes.Buffer, f string, args ...goja.Value) {
  201. pct := false
  202. argNum := 0
  203. for _, chr := range f {
  204. if pct {
  205. if argNum < len(args) {
  206. if format1(runtime, chr, args[argNum], b) {
  207. argNum++
  208. }
  209. } else {
  210. b.WriteByte('%')
  211. b.WriteRune(chr)
  212. }
  213. pct = false
  214. } else {
  215. if chr == '%' {
  216. pct = true
  217. } else {
  218. b.WriteRune(chr)
  219. }
  220. }
  221. }
  222. for _, arg := range args[argNum:] {
  223. b.WriteByte(' ')
  224. b.WriteString(arg.String())
  225. }
  226. }
  227. func format1(runtime *goja.Runtime, f rune, val goja.Value, w *bytes.Buffer) bool {
  228. switch f {
  229. case 's':
  230. w.WriteString(val.String())
  231. case 'd':
  232. w.WriteString(val.ToNumber().String())
  233. case 'j':
  234. if json, ok := runtime.Get("JSON").(*goja.Object); ok {
  235. if stringify, ok := goja.AssertFunction(json.Get("stringify")); ok {
  236. res, err := stringify(json, val)
  237. if err != nil {
  238. panic(err)
  239. }
  240. w.WriteString(res.String())
  241. }
  242. }
  243. case '%':
  244. w.WriteByte('%')
  245. return false
  246. default:
  247. w.WriteByte('%')
  248. w.WriteRune(f)
  249. return false
  250. }
  251. return true
  252. }