package gojs
import (
"context"
"reflect"
"github.com/Mzack9999/goja"
"github.com/projectdiscovery/utils/errkit"
)
var (
ErrInvalidFuncOpts = errkit.New("invalid function options")
ErrNilRuntime = errkit.New("runtime is nil")
)
type FuncOpts struct {
Name string
Signatures []string
Description string
FuncDecl interface{}
}
func (f *FuncOpts) valid() bool {
return f.Name != "" && f.FuncDecl != nil && len(f.Signatures) > 0 && f.Description != ""
}
func wrapWithContext(runtime *goja.Runtime, fn interface{}) interface{} {
fnType := reflect.TypeOf(fn)
if fnType.Kind() != reflect.Func {
return fn
}
if fnType.NumIn() == 0 || fnType.In(0) != reflect.TypeFor[context.Context]() {
return fn
}
inTypes := make([]reflect.Type, fnType.NumIn())
for i := 0; i < fnType.NumIn(); i++ {
inTypes[i] = fnType.In(i)
}
outTypes := make([]reflect.Type, fnType.NumOut())
for i := 0; i < fnType.NumOut(); i++ {
outTypes[i] = fnType.Out(i)
}
newFnType := reflect.FuncOf(inTypes, outTypes, fnType.IsVariadic())
newFn := reflect.MakeFunc(newFnType, func(args []reflect.Value) []reflect.Value {
var ctx context.Context
if ctxVal := runtime.Get("context"); ctxVal != nil {
if ctxObj, ok := ctxVal.Export().(context.Context); ok {
ctx = ctxObj
}
}
if ctx == nil {
ctx = context.Background()
}
if execID := runtime.Get("executionId"); execID != nil {
ctx = context.WithValue(ctx, "executionId", execID.String())
}
args[0] = reflect.ValueOf(ctx)
return reflect.ValueOf(fn).Call(args)
})
return newFn.Interface()
}
func RegisterFuncWithSignature(runtime *goja.Runtime, opts FuncOpts) error {
if runtime == nil {
return ErrNilRuntime
}
if !opts.valid() {
return errkit.Newf("invalid function options: name: %s, signatures: %v, description: %s", opts.Name, opts.Signatures, opts.Description)
}
return runtime.Set(opts.Name, opts.FuncDecl )
}