module.go 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package surge
  2. import (
  3. "github.com/sagernet/sing-box/script/jsc"
  4. "github.com/sagernet/sing-box/script/modules/require"
  5. "github.com/sagernet/sing/common"
  6. "github.com/dop251/goja"
  7. )
  8. const ModuleName = "surge"
  9. type Module struct {
  10. runtime *goja.Runtime
  11. classScript jsc.Class[*Module, *Script]
  12. classEnvironment jsc.Class[*Module, *Environment]
  13. classPersistentStore jsc.Class[*Module, *PersistentStore]
  14. classHTTP jsc.Class[*Module, *HTTP]
  15. classUtils jsc.Class[*Module, *Utils]
  16. classNotification jsc.Class[*Module, *Notification]
  17. }
  18. func Require(runtime *goja.Runtime, module *goja.Object) {
  19. m := &Module{
  20. runtime: runtime,
  21. }
  22. m.classScript = createScript(m)
  23. m.classEnvironment = createEnvironment(m)
  24. m.classPersistentStore = createPersistentStore(m)
  25. m.classHTTP = createHTTP(m)
  26. m.classUtils = createUtils(m)
  27. m.classNotification = createNotification(m)
  28. exports := module.Get("exports").(*goja.Object)
  29. exports.Set("Script", m.classScript.ToValue())
  30. exports.Set("Environment", m.classEnvironment.ToValue())
  31. exports.Set("PersistentStore", m.classPersistentStore.ToValue())
  32. exports.Set("HTTP", m.classHTTP.ToValue())
  33. exports.Set("Utils", m.classUtils.ToValue())
  34. exports.Set("Notification", m.classNotification.ToValue())
  35. }
  36. func Enable(runtime *goja.Runtime, scriptType string, args []string) {
  37. exports := require.Require(runtime, ModuleName).ToObject(runtime)
  38. classScript := jsc.GetClass[*Module, *Script](runtime, exports, "Script")
  39. classEnvironment := jsc.GetClass[*Module, *Environment](runtime, exports, "Environment")
  40. classPersistentStore := jsc.GetClass[*Module, *PersistentStore](runtime, exports, "PersistentStore")
  41. classHTTP := jsc.GetClass[*Module, *HTTP](runtime, exports, "HTTP")
  42. classUtils := jsc.GetClass[*Module, *Utils](runtime, exports, "Utils")
  43. classNotification := jsc.GetClass[*Module, *Notification](runtime, exports, "Notification")
  44. runtime.Set("$script", classScript.New(&Script{class: classScript, ScriptType: scriptType}))
  45. runtime.Set("$environment", classEnvironment.New(&Environment{class: classEnvironment}))
  46. runtime.Set("$persistentStore", newPersistentStore(classPersistentStore))
  47. runtime.Set("$http", classHTTP.New(newHTTP(classHTTP, goja.ConstructorCall{})))
  48. runtime.Set("$utils", classUtils.New(&Utils{class: classUtils}))
  49. runtime.Set("$notification", newNotification(classNotification))
  50. runtime.Set("$argument", runtime.NewArray(common.Map(args, func(it string) any {
  51. return it
  52. })...))
  53. }
  54. func (m *Module) Runtime() *goja.Runtime {
  55. return m.runtime
  56. }