{"modulePath":"github.com/daveshanley/vacuum","version":"v0.43.0","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package eventloop\n\nPackage eventloop provides an event loop implementation for running asynchronous JavaScript code with Goja. It enables async/await and Promise support in custom JavaScript functions by processing the microtask queue.\n\nThe design is inspired by Grafana k6's event loop implementation and goja\\_nodejs.\n\n## Variables\n\n```go\nvar (\n\t// ErrLoopAlreadyRunning is returned when Run is called on an already running loop\n\tErrLoopAlreadyRunning = errors.New(\"event loop already running\")\n\n\t// ErrLoopNotRunning is returned when trying to queue work on a stopped loop\n\tErrLoopNotRunning = errors.New(\"event loop not running\")\n\n\t// ErrPromiseRejected is returned when a Promise is rejected\n\tErrPromiseRejected = errors.New(\"promise rejected\")\n\n\t// ErrPromiseTimeout is returned when a Promise doesn't resolve within timeout\n\tErrPromiseTimeout = errors.New(\"promise did not resolve within timeout\")\n)\n```\n\n## Functions\n\n```go\nfunc ExtractPromiseValue(value goja.Value) (interface{}, error)\n```\nExtractPromiseValue extracts the resolved value from a Promise. If the value is not a Promise, returns the value directly. Returns an error if the Promise was rejected or is still pending.\n\n```go\nfunc GetPromise(value goja.Value) *goja.Promise\n```\nGetPromise extracts a \\*goja.Promise from a goja.Value Returns nil if the value is not a Promise\n\n```go\nfunc IsPromise(value goja.Value) bool\n```\nIsPromise checks if a goja.Value is a Promise\n\n## Types\n\n```go\ntype EventLoop struct {\n\t// contains filtered or unexported fields\n}\n```\nEventLoop manages asynchronous JavaScript execution by processing a job queue and handling Promise microtasks.\n\n```go\nfunc New(vm *goja.Runtime) *EventLoop\n```\nNew creates a new EventLoop wrapping the given Goja runtime. The runtime should not be used directly while the event loop is running.\n\n```go\nfunc (e *EventLoop) AwaitPromise(ctx context.Context, value goja.Value) PromiseResult\n```\nAwaitPromise waits for a Promise to resolve or reject. It processes the event loop until the Promise settles or the context is cancelled.\n\nIf the value is not a Promise, it returns immediately with the value.\n\n```go\nfunc (e *EventLoop) ClearTimeout(t *Timer)\n```\nClearTimeout cancels a pending timeout created with SetTimeout\n\n```go\nfunc (e *EventLoop) Context() context.Context\n```\nContext returns the active invocation context. Call it only from the VM owner.\n\n```go\nfunc (e *EventLoop) EnqueueJob(fn func())\n```\nEnqueueJob adds a job to the queue. Thread-safe: can be called from any goroutine.\n\n```go\nfunc (e *EventLoop) NewPromise() (*goja.Promise, func(interface{}), func(interface{}))\n```\nNewPromise creates a new Promise and returns resolve/reject functions. This is a convenience wrapper around goja.Runtime.NewPromise().\n\n```go\nfunc (e *EventLoop) RegisterCallback() func(func())\n```\nRegisterCallback returns a function that will queue work on the event loop. This is the k6-style pattern for async operations.\n\nWhen called, it increments the pending operation counter to prevent the loop from exiting. The returned function should be called with the callback to execute when the async operation completes.\n\n```go\nfunc (e *EventLoop) RegisterFetch(config *fetch.FetchConfig)\n```\nRegisterFetch registers the fetch() function in the JavaScript runtime. If config is nil, secure defaults are used (HTTPS only, no private networks).\n\n```go\nfunc (e *EventLoop) Run(ctx context.Context, fn func(*goja.Runtime) (goja.Value, error)) (goja.Value, error)\n```\nRun executes the provided function and processes the event loop until all pending work completes or the context is cancelled.\n\nThe function fn is called with the Goja runtime and should return the result of the JavaScript execution (which may be a Promise).\n\nRun blocks until:\n\n  - All pending jobs are processed, and no more work is queued\n  - The context is cancelled (timeout or explicit cancellation)\n  - An error occurs during execution\n\n```go\nfunc (e *EventLoop) RunOnLoop(fn func()) bool\n```\nRunOnLoop queues a function to be executed on the event loop. This is thread-safe and can be called from any goroutine. Returns false if the loop is not running.\n\n```go\nfunc (e *EventLoop) Runtime() *goja.Runtime\n```\nRuntime returns the underlying Goja runtime. Should only be used when the loop is not running.\n\n```go\nfunc (e *EventLoop) SetTimeout(fn func(), delay time.Duration) *Timer\n```\nSetTimeout schedules a Go function to be called after the specified delay. Returns a Timer that can be used with ClearTimeout.\n\n```go\nfunc (e *EventLoop) WrapGoFunctionAsync(name string, fn func(call goja.FunctionCall, enqueue func(func())) goja.Value)\n```\nWrapGoFunctionAsync wraps a Go function as an async JavaScript function. The Go function receives the event loop's RegisterCallback function to properly signal async completion.\n\nExample usage:\n\n\tloop.WrapGoFunctionAsync(\"fetchData\", func(call goja.FunctionCall, enqueue func(func())) goja.Value {\n\t    url := call.Argument(0).String()\n\t    promise, resolve, reject := loop.vm.NewPromise()\n\n\t    go func() {\n\t        result, err := http.Get(url)\n\t        enqueue(func() {\n\t            if err != nil {\n\t                reject(loop.vm.NewGoError(err))\n\t            } else {\n\t                resolve(loop.vm.ToValue(result))\n\t            }\n\t        })\n\t    }()\n\n\t    return loop.vm.ToValue(promise)\n\t})\n\n```go\ntype PromiseResult struct {\n\tState PromiseState\n\tValue goja.Value\n\tError error\n}\n```\nPromiseResult holds the result of awaiting a Promise\n\n```go\ntype PromiseState int\n```\nPromiseState represents the state of a Promise\n\n```go\nconst (\n\tPromiseStatePending PromiseState = iota\n\tPromiseStateFulfilled\n\tPromiseStateRejected\n)\n```\n\n```go\ntype Timer struct {\n\t// contains filtered or unexported fields\n}\n```\nTimer represents a scheduled timeout or interval\n\n","path":"github.com/daveshanley/vacuum/plugin/javascript/eventloop","name":"eventloop","synopsis":"Package eventloop provides an event loop implementation for running asynchronous JavaScript code with Goja.","isRedistributable":true}
