From 98d210f7f93da1e4a837d19945fd56f769d0b856 Mon Sep 17 00:00:00 2001 From: WithoutPants <53250216+WithoutPants@users.noreply.github.com> Date: Thu, 23 May 2024 11:28:15 +1000 Subject: [PATCH] Fix inconsistent field names in javascript plugin hooks (#4869) --- pkg/javascript/vm.go | 22 +++++++++++++++++++++- pkg/plugin/js.go | 2 ++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/pkg/javascript/vm.go b/pkg/javascript/vm.go index cf75028df..ce84b820d 100644 --- a/pkg/javascript/vm.go +++ b/pkg/javascript/vm.go @@ -4,6 +4,7 @@ import ( "fmt" "net/http" "os" + "reflect" "github.com/dop251/goja" ) @@ -16,8 +17,27 @@ type VM struct { GQLHandler http.Handler } +// optionalFieldNameMapper wraps a goja.FieldNameMapper and returns the field name if the wrapped mapper returns an empty string. +type optionalFieldNameMapper struct { + mapper goja.FieldNameMapper +} + +func (tfm optionalFieldNameMapper) FieldName(t reflect.Type, f reflect.StructField) string { + if ret := tfm.mapper.FieldName(t, f); ret != "" { + return ret + } + + return f.Name +} + +func (tfm optionalFieldNameMapper) MethodName(t reflect.Type, m reflect.Method) string { + return tfm.mapper.MethodName(t, m) +} + func NewVM() *VM { - return &VM{Runtime: goja.New()} + r := goja.New() + r.SetFieldNameMapper(optionalFieldNameMapper{goja.TagFieldNameMapper("json", true)}) + return &VM{Runtime: r} } type APIAdder interface { diff --git a/pkg/plugin/js.go b/pkg/plugin/js.go index 8bfa3c87f..f011e250f 100644 --- a/pkg/plugin/js.go +++ b/pkg/plugin/js.go @@ -57,6 +57,8 @@ func (t *jsPluginTask) makeOutput(o goja.Value) { func (t *jsPluginTask) initVM() error { // converting the Args field to map[string]interface{} is required, otherwise // it gets converted to an empty object + // ideally this should have included json tags with the correct casing but changing + // it now will result in a breaking change type pluginInput struct { // Server details to connect to the stash server. ServerConnection common.StashServerConnection