From 4760a5a0a20967c328cb1fe4e3063af80bc4a7e8 Mon Sep 17 00:00:00 2001 From: Kobi Date: Thu, 4 Sep 2025 11:00:59 +0300 Subject: [PATCH] Update eventloop.go to support external Runtime --- eventloop/eventloop.go | 68 +++++++++++++++++++++++++----------------- 1 file changed, 40 insertions(+), 28 deletions(-) diff --git a/eventloop/eventloop.go b/eventloop/eventloop.go index d047816..d232949 100644 --- a/eventloop/eventloop.go +++ b/eventloop/eventloop.go @@ -55,36 +55,41 @@ type EventLoop struct { } func NewEventLoop(opts ...Option) *EventLoop { - vm := goja.New() - - loop := &EventLoop{ - vm: vm, - jobChan: make(chan func()), - wakeupChan: make(chan struct{}, 1), - enableConsole: true, - } - loop.stopCond = sync.NewCond(&loop.stopLock) - - for _, opt := range opts { - opt(loop) - } - if loop.registry == nil { - loop.registry = new(require.Registry) - } - loop.registry.Enable(vm) - if loop.enableConsole { - console.Enable(vm) - } - vm.Set("setTimeout", loop.setTimeout) - vm.Set("setInterval", loop.setInterval) - vm.Set("setImmediate", loop.setImmediate) - vm.Set("clearTimeout", loop.clearTimeout) - vm.Set("clearInterval", loop.clearInterval) - vm.Set("clearImmediate", loop.clearImmediate) - - return loop + loop := &EventLoop{ + jobChan: make(chan func()), + wakeupChan: make(chan struct{}, 1), + enableConsole: true, + } + loop.stopCond = sync.NewCond(&loop.stopLock) + + for _, opt := range opts { + opt(loop) + } + + if loop.vm == nil { + loop.vm = goja.New() + } + + if loop.registry == nil { + loop.registry = new(require.Registry) + } + + loop.registry.Enable(loop.vm) + + if loop.enableConsole { + console.Enable(loop.vm) + } + _ = loop.vm.Set("setTimeout", loop.setTimeout) + _ = loop.vm.Set("setInterval", loop.setInterval) + _ = loop.vm.Set("setImmediate", loop.setImmediate) + _ = loop.vm.Set("clearTimeout", loop.clearTimeout) + _ = loop.vm.Set("clearInterval", loop.clearInterval) + _ = loop.vm.Set("clearImmediate", loop.clearImmediate) + + return loop } + type Option func(*EventLoop) // EnableConsole controls whether the "console" module is loaded into @@ -103,6 +108,13 @@ func WithRegistry(registry *require.Registry) Option { } } +// WithRuntime sets the runtime used by the loop. +func WithRuntime(vm *goja.Runtime) Option { + return func(loop *EventLoop) { + loop.vm = vm + } +} + func (loop *EventLoop) schedule(call goja.FunctionCall, repeating bool) goja.Value { if fn, ok := goja.AssertFunction(call.Argument(0)); ok { delay := call.Argument(1).ToInteger()