runtime.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. //go:build with_script
  2. package script
  3. import (
  4. "context"
  5. "github.com/sagernet/sing-box/script/modules/boxctx"
  6. "github.com/sagernet/sing-box/script/modules/console"
  7. "github.com/sagernet/sing-box/script/modules/eventloop"
  8. "github.com/sagernet/sing-box/script/modules/require"
  9. "github.com/sagernet/sing-box/script/modules/surge"
  10. "github.com/sagernet/sing-box/script/modules/url"
  11. E "github.com/sagernet/sing/common/exceptions"
  12. "github.com/sagernet/sing/common/logger"
  13. "github.com/sagernet/sing/common/ntp"
  14. "github.com/dop251/goja"
  15. "github.com/dop251/goja/parser"
  16. )
  17. func NewRuntime(ctx context.Context, cancel context.CancelCauseFunc) *goja.Runtime {
  18. vm := goja.New()
  19. if timeFunc := ntp.TimeFuncFromContext(ctx); timeFunc != nil {
  20. vm.SetTimeSource(timeFunc)
  21. }
  22. vm.SetParserOptions(parser.WithDisableSourceMaps)
  23. registry := require.NewRegistry(require.WithLoader(func(path string) ([]byte, error) {
  24. return nil, E.New("unsupported usage")
  25. }))
  26. registry.Enable(vm)
  27. registry.RegisterNodeModule(console.ModuleName, console.Require)
  28. registry.RegisterNodeModule(url.ModuleName, url.Require)
  29. registry.RegisterNativeModule(boxctx.ModuleName, boxctx.Require)
  30. registry.RegisterNativeModule(surge.ModuleName, surge.Require)
  31. console.Enable(vm)
  32. url.Enable(vm)
  33. eventloop.Enable(vm, cancel)
  34. return vm
  35. }
  36. func SetModules(runtime *goja.Runtime, ctx context.Context, logger logger.ContextLogger, errorHandler func(error), tag string) {
  37. boxctx.Enable(runtime, &boxctx.Context{
  38. Context: ctx,
  39. Logger: logger,
  40. Tag: tag,
  41. ErrorHandler: errorHandler,
  42. })
  43. }