From 1d33fabf9306ac7d892acd15c7c5e148443e805a Mon Sep 17 00:00:00 2001 From: Dmitri Aleksandrov Date: Mon, 19 Oct 2026 11:22:54 +0300 Subject: [PATCH 1/2] feat(huma): the rules of valigo in the OpenAPI document OpenAPI returns the OpenAPI document of the api with the constraints of the validator in the schemas of the request bodies and their nested structs: maxLength, format, enum, items, the required properties... A keyword with another value than the one of huma goes to allOf. The schemas of huma, which it validates the requests by, are not changed. --- huma/openapi.go | 129 +++++++++++++++++++++++++++++++++++++++++ huma/openapi_test.go | 133 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 262 insertions(+) create mode 100644 huma/openapi.go create mode 100644 huma/openapi_test.go diff --git a/huma/openapi.go b/huma/openapi.go new file mode 100644 index 0000000..60e1a34 --- /dev/null +++ b/huma/openapi.go @@ -0,0 +1,129 @@ +package huma + +import ( + "encoding/json" + "reflect" + "slices" + "strings" + + dhuma "github.com/danielgtaylor/huma/v2" + "github.com/insei/fmap/v3" + + "github.com/insei/valigo" + "github.com/insei/valigo/shared" +) + +// schemasPrefix is the prefix of the references of the schemas of the registry of huma by default. +const schemasPrefix = "#/components/schemas/" + +// OpenAPI returns the OpenAPI document of the api as JSON values with the rules of the validator in the schemas +// of the request bodies and their nested structs: maxLength of MaxRunes, minimum of Min, the required properties..., +// see Validator.Constraints. Serve it instead of the document of huma, so the clients see the rules of valigo. +// +// The schemas of huma, which huma validates the requests by, are not changed, the validation stays by valigo +// with translated messages. The parameters keep the schemas of huma. +func OpenAPI(api dhuma.API, v *valigo.Validator) (map[string]any, error) { + oapi := api.OpenAPI() + data, err := json.Marshal(oapi) + if err != nil { + return nil, err + } + var doc map[string]any + _ = json.Unmarshal(data, &doc) // the JSON of json.Marshal + byStruct := map[reflect.Type][]shared.Constraint{} + for _, c := range v.Constraints() { + if owner, ok := ownerOf(c); ok { + byStruct[owner] = append(byStruct[owner], c) + } + } + components, _ := doc["components"].(map[string]any) + schemas, _ := components["schemas"].(map[string]any) + for name, s := range schemas { + constraints := byStruct[oapi.Components.Schemas.TypeFromRef(schemasPrefix+name)] + for _, c := range constraints { + apply(s.(map[string]any), c) + } + } + return doc, nil +} + +// ownerOf returns the struct type of the schema the field of the constraint is a property of: +// the configured struct or the nested struct of the field, the embedded structs without a JSON name are flattened. +func ownerOf(c shared.Constraint) (reflect.Type, bool) { + if _, ok := propertyName(c.Field); !ok { + return nil, false + } + owner := c.Field.GetParent() + for owner != nil && owner.GetAnonymous() && jsonName(owner) == "" { + owner = owner.GetParent() + } + if owner == nil { + return c.Struct, true + } + return owner.GetDereferencedType(), true +} + +func jsonName(f fmap.Field) string { + name, _, _ := strings.Cut(f.GetTag().Get("json"), ",") + return name +} + +// propertyName returns the name of the property of the field in the schema of its struct, false for skipped fields. +func propertyName(f fmap.Field) (string, bool) { + name := jsonName(f) + if name == "-" { + return "", false + } + if name == "" { + name = f.GetName() + } + return name, true +} + +// apply adds the constraint to the schema of the struct of its field. +func apply(schema map[string]any, c shared.Constraint) { + name, _ := propertyName(c.Field) + properties, _ := schema["properties"].(map[string]any) + target, ok := properties[name].(map[string]any) + if !ok { + return + } + if c.Keyword == shared.KeywordRequired && len(c.Path) == 0 { + required, _ := schema["required"].([]any) + if !slices.Contains(required, any(name)) { + schema["required"] = append(required, name) + } + return + } + if c.Keyword == shared.KeywordRequired { + // the elements of a slice and the values of a map can't be required + return + } + for _, keyword := range c.Path { + next, ok := target[keyword].(map[string]any) + if !ok { + // additionalProperties: true, or no propertyNames yet + next = map[string]any{} + target[keyword] = next + } + target = next + } + value := normalize(c.Value) + existing, ok := target[c.Keyword] + switch { + case !ok: + target[c.Keyword] = value + case !reflect.DeepEqual(existing, value): + // e.g. two patterns or maxLength of huma and of valigo: the value must satisfy both + allOf, _ := target["allOf"].([]any) + target["allOf"] = append(allOf, map[string]any{c.Keyword: value}) + } +} + +// normalize converts the value to the JSON values of the document, e.g. ints to float64 and named strings to strings. +func normalize(v any) any { + data, _ := json.Marshal(v) // the values of the constraints are JSON values + var result any + _ = json.Unmarshal(data, &result) + return result +} diff --git a/huma/openapi_test.go b/huma/openapi_test.go new file mode 100644 index 0000000..2cb5af8 --- /dev/null +++ b/huma/openapi_test.go @@ -0,0 +1,133 @@ +package huma_test + +import ( + "context" + "testing" + + dhuma "github.com/danielgtaylor/huma/v2" + "github.com/danielgtaylor/huma/v2/humatest" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/insei/valigo" + "github.com/insei/valigo/eq" + vhuma "github.com/insei/valigo/huma" + "github.com/insei/valigo/num" + "github.com/insei/valigo/shared" + "github.com/insei/valigo/str" +) + +type Item struct { + Title string `json:"title"` +} + +type Base struct { + Version int `json:"version"` +} + +type CreateItemInput struct { + Limit int `query:"limit"` + Body struct { + Base + Name string `json:"name" maxLength:"10"` + Code string `json:"code,omitempty" pattern:"^[A-Z]+$"` + Kind string `json:"kind,omitempty"` + Tags []string `json:"tags"` + Labels map[string]int `json:"labels,omitempty"` + Flags map[string]string `json:"flags,omitempty"` + Item *Item `json:"item,omitempty"` + Secret string `json:"-"` + Hidden string `json:"hidden,omitempty" hidden:"true"` + Comment string + } +} + +func newOpenAPI(t *testing.T) map[string]any { + t.Helper() + v := valigo.New() + valigo.Configure[CreateItemInput](v, func(b valigo.Configurator[CreateItemInput], i *CreateItemInput) { + b.Field(&i.Limit).As(num.Of).Max(100) + b.Field(&i.Body.Version).As(num.Of).Min(1) + b.Field(&i.Body.Name).As(str.Of).Required().MaxRunes(10).MaxLen(40) + b.Field(&i.Body.Code).As(str.Of).Required().Prefix("A") + b.Field(&i.Body.Kind).As(eq.Of).OneOf("a", "b") + b.Slice(&i.Body.Tags).As(str.Slice).MaxLen(3).Each(func(tag *str.BaseConfigurator) { tag.Required().MaxRunes(16) }) + b.Map(&i.Body.Labels).EachValue(func(v *shared.Field[int]) { v.As(num.Of).Min(1) }) + b.Map(&i.Body.Flags).EachKey(func(k *shared.Field[string]) { k.As(str.Of).Hostname() }) + b.Field(&i.Body.Secret).As(str.Of).Required() + b.Field(&i.Body.Hidden).As(str.Of).MaxRunes(1) + b.Field(&i.Body.Comment).As(str.Of).MaxRunes(200) + }) + valigo.Configure[Item](v, func(b valigo.Configurator[Item], i *Item) { + b.Field(&i.Title).As(str.Of).MinRunes(2) + }) + _, api := humatest.New(t) + dhuma.Post(api, "/items", func(context.Context, *CreateItemInput) (*struct{}, error) { return nil, nil }) + doc, err := vhuma.OpenAPI(api, v) + require.NoError(t, err) + return doc +} + +func schemaOf(t *testing.T, doc map[string]any, name string) map[string]any { + t.Helper() + s, ok := doc["components"].(map[string]any)["schemas"].(map[string]any)[name].(map[string]any) + require.True(t, ok, name) + return s +} + +func TestOpenAPI(t *testing.T) { + doc := newOpenAPI(t) + body := schemaOf(t, doc, "CreateItemInputBody") + props := body["properties"].(map[string]any) + + assert.Equal(t, map[string]any{"type": "integer", "format": "int64", "minimum": 1.0}, props["version"], "the embedded struct is flattened") + assert.Equal(t, map[string]any{"type": "string", "minLength": 1.0, "maxLength": 10.0, "allOf": []any{map[string]any{"maxLength": 40.0}}}, props["name"], + "the same value is kept once, another one is in allOf") + assert.Equal(t, map[string]any{"type": "string", "minLength": 1.0, "pattern": "^[A-Z]+$", "allOf": []any{map[string]any{"pattern": "^A"}}}, props["code"]) + assert.Equal(t, []any{"a", "b"}, props["kind"].(map[string]any)["enum"]) + tags := props["tags"].(map[string]any) + assert.Equal(t, 3.0, tags["maxItems"]) + assert.Equal(t, map[string]any{"type": "string", "minLength": 1.0, "maxLength": 16.0}, tags["items"], "elements aren't required") + assert.Equal(t, 1.0, props["labels"].(map[string]any)["additionalProperties"].(map[string]any)["minimum"]) + assert.Equal(t, map[string]any{"format": "hostname"}, props["flags"].(map[string]any)["propertyNames"]) + assert.Equal(t, 200.0, props["Comment"].(map[string]any)["maxLength"]) + assert.NotContains(t, props, "Secret") + assert.NotContains(t, props, "hidden", "a hidden property isn't added") + + required := body["required"].([]any) + assert.Contains(t, required, "code", "Required adds the omitempty field to the required properties") + assert.Equal(t, 1, countOf(required, "name"), "a required property isn't repeated") + assert.NotContains(t, required, "Secret") + + assert.Equal(t, 2.0, schemaOf(t, doc, "Item")["properties"].(map[string]any)["title"].(map[string]any)["minLength"], "the rules of a nested struct type") + + params := doc["paths"].(map[string]any)["/items"].(map[string]any)["post"].(map[string]any)["parameters"].([]any) + assert.NotContains(t, params[0].(map[string]any)["schema"], "maximum", "the parameters keep the schemas of huma") +} + +func TestOpenAPIDoesntChangeHuma(t *testing.T) { + v := valigo.New() + valigo.Configure[Item](v, func(b valigo.Configurator[Item], i *Item) { b.Field(&i.Title).As(str.Of).MaxRunes(2) }) + _, api := humatest.New(t) + dhuma.Post(api, "/items", func(context.Context, *struct{ Body Item }) (*struct{}, error) { return nil, nil }) + _, err := vhuma.OpenAPI(api, v) + require.NoError(t, err) + assert.Nil(t, api.OpenAPI().Components.Schemas.Map()["Item"].Properties["title"].MaxLength) +} + +func TestOpenAPIError(t *testing.T) { + _, api := humatest.New(t) + api.OpenAPI().Extensions = map[string]any{"x-bad": func() {}} + _, err := vhuma.OpenAPI(api, valigo.New()) + assert.Error(t, err) +} + +func countOf(values []any, v any) int { + n := 0 + for _, x := range values { + if x == v { + n++ + } + } + return n +} From dfcc7d2936545661deddef78d2326f1c09221ffd Mon Sep 17 00:00:00 2001 From: Dmitri Aleksandrov Date: Mon, 19 Oct 2026 11:22:54 +0300 Subject: [PATCH 2/2] docs: describe JSON Schema of the rules and the OpenAPI document of huma --- README.md | 1 + docs/features/huma.md | 105 ++++++++++++++++++++++++++++++++++++++++ docs/features/index.md | 3 +- docs/features/schema.md | 46 ++++++++++++++++++ mkdocs.yml | 4 +- skills/valigo/SKILL.md | 4 ++ 6 files changed, 161 insertions(+), 2 deletions(-) create mode 100644 docs/features/schema.md diff --git a/README.md b/README.md index f9797b2..696e9d1 100644 --- a/README.md +++ b/README.md @@ -78,6 +78,7 @@ and a conversion that doesn't fit the field doesn't compile: * Every error has the translated message, the location (`Tags[1]`, `address.city` with JSON paths), the value, a stable `Code` and named `Params` * Messages in English, German, Spanish, French and Russian with plural forms, the language of every request from the context, an `Accept-Language` middleware * `problem`: the errors as `application/problem+json` of RFC 9457 with JSON pointers +* The rules as the keywords of JSON Schema, `vhuma.OpenAPI` puts them into the OpenAPI document of huma: the clients see `maxLength`, `format`, `enum` of the rules * `github.com/insei/valigo/huma`, `github.com/insei/valigo/gin`, `github.com/insei/valigo/echo`: the rules of valigo in [huma](https://huma.rocks), [gin](https://gin-gonic.com) and [echo](https://echo.labstack.com) # Performance diff --git a/docs/features/huma.md b/docs/features/huma.md index b4bdb17..d21dca2 100644 --- a/docs/features/huma.md +++ b/docs/features/huma.md @@ -99,3 +99,108 @@ query.limit - Не может быть больше 100 body.email - Должно быть электронным адресом body.tags[1] - Должно содержать только латинские буквы и цифры ``` + +## The rules in the OpenAPI document + +`vhuma.OpenAPI(api, v)` returns the OpenAPI document of the api with the rules of valigo in the schemas of the request bodies and their nested structs, by [JSON Schema](schema.md): `maxLength` of `MaxRunes`, `format: email` of `Email`, `items` of `Each`, the required properties of `Required`. Serve it, so the clients and the generators of SDKs see the rules: + +```go +mux.HandleFunc("GET /openapi.json", func(w http.ResponseWriter, r *http.Request) { + doc, err := vhuma.OpenAPI(api, validator) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + _ = json.NewEncoder(w).Encode(doc) +}) +``` + +with `config.OpenAPIPath = ""` instead of the document of huma, or under another path. + +- The schemas of huma are not changed: huma validates the requests by its tags, the rules of valigo are checked in `Resolve` with translated messages, without the duplicates of huma. +- A keyword with another value than the one of the tags of huma, e.g. two `maxLength`, is added to `allOf`: the value must satisfy both. +- The parameters keep the schemas of huma: an operation of huma doesn't know its input type. +- The schemas are found by the registry of huma with the prefix `#/components/schemas/`, the default one. + +```go +package main + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + + "github.com/danielgtaylor/huma/v2" + "github.com/danielgtaylor/huma/v2/adapters/humago" + "github.com/insei/valigo" + vhuma "github.com/insei/valigo/huma" + "github.com/insei/valigo/str" +) + +type CreateUserInput struct { + Body struct { + Name string `json:"name"` + Email string `json:"email,omitempty"` + Tags []string `json:"tags,omitempty"` + } +} + +func main() { + validator := valigo.New(valigo.WithFieldLocationNamingFn(vhuma.Location)) + valigo.Configure[CreateUserInput](validator, func(b valigo.Configurator[CreateUserInput], i *CreateUserInput) { + b.Field(&i.Body.Name).As(str.Of).MaxRunes(64) + b.Field(&i.Body.Email).As(str.Of).Required().Email() + b.Slice(&i.Body.Tags).As(str.Slice).MaxLen(5).Each(func(tag *str.BaseConfigurator) { tag.Alphanumeric() }) + }) + + api := humago.New(http.NewServeMux(), huma.DefaultConfig("Users", "1.0.0")) + huma.Post(api, "/users", func(context.Context, *CreateUserInput) (*struct{}, error) { return nil, nil }) + + doc, err := vhuma.OpenAPI(api, validator) + if err != nil { + panic(err) + } + body := doc["components"].(map[string]any)["schemas"].(map[string]any)["CreateUserInputBody"].(map[string]any) + delete(body["properties"].(map[string]any), "$schema") // the property of huma for the link to the schema + out, _ := json.MarshalIndent(body, "", " ") + fmt.Println(string(out)) +} +``` + +Output: + +```text +{ + "additionalProperties": false, + "properties": { + "email": { + "format": "email", + "minLength": 1, + "type": "string" + }, + "name": { + "maxLength": 64, + "type": "string" + }, + "tags": { + "items": { + "pattern": "^[a-zA-Z0-9]+$", + "type": "string" + }, + "maxItems": 5, + "type": [ + "array", + "null" + ] + } + }, + "required": [ + "name", + "email" + ], + "type": "object" +} +``` + +`email` is `omitempty` for huma, `Required` of valigo makes it required in the document; `tags` has the rules of its elements in `items`. diff --git a/docs/features/index.md b/docs/features/index.md index 6587f4e..88af6de 100644 --- a/docs/features/index.md +++ b/docs/features/index.md @@ -45,6 +45,7 @@ The separate modules for the frameworks. | Page | What's inside | |---|---| -| [huma](huma.md) | `github.com/insei/valigo/huma`: the rules in the `Resolve` of huma inputs with the locations of huma | +| [JSON Schema](schema.md) | the rules as the keywords of JSON Schema for the generators of API schemas, `Constraints` | +| [huma](huma.md) | `github.com/insei/valigo/huma`: the rules in the `Resolve` of huma inputs with the locations of huma and in its OpenAPI document | | [gin](gin.md) | `github.com/insei/valigo/gin`: the `binding.StructValidator` of gin and validation with the language of the request | | [echo](echo.md) | `github.com/insei/valigo/echo`: the `echo.Validator` and validation with the language of the request | diff --git a/docs/features/schema.md b/docs/features/schema.md new file mode 100644 index 0000000..a973238 --- /dev/null +++ b/docs/features/schema.md @@ -0,0 +1,46 @@ +# JSON Schema + +The rules that JSON Schema can express are described by its keywords, so the generators of the schemas of an API can show them to the clients: [huma](huma.md#the-rules-in-the-openapi-document) puts them into its OpenAPI document. `v.Constraints()` returns them for other generators. + +```go +for _, c := range v.Constraints() { + fmt.Println(c.Struct, c.Field.GetStructPath(), c.Path, c.Keyword, c.Value) +} +``` + +Every `shared.Constraint` has the configured struct, the field, the path from the schema of the field to the constrained value — `[items]` for the elements of a slice, `[additionalProperties]` for the values of a map, `[propertyNames]` for its keys — the keyword and its value. The keyword `required` means the field is in the required properties of its object. + +| Rules | Keywords | +|---|---| +| `str`: `Required` | `required`, `minLength: 1` | +| `str`: `MinRunes`, `MaxRunes`, `MaxLen` | `minLength`, `maxLength` | +| `str`: `Regexp`, `Prefix`, `Suffix`, `Contains`, `Alphanumeric`, `Semver`, `E164`, `HexColor` | `pattern` | +| `str`: `Email`, `URL`, `IPv4`, `IPv6`, `Hostname`, `UUID` | `format`: `email`, `uri`, `ipv4`, `ipv6`, `hostname`, `uuid` | +| `str`: `Datetime(time.RFC3339)`, `Datetime(time.DateOnly)` | `format`: `date-time`, `date` | +| `str`: `Base64`, `Base64URL` | `contentEncoding` | +| `str`, `num`, `uuid`: `AnyOf`; `eq`: `OneOf` | `enum` | +| `eq`: `Equal` | `const` | +| `num`: `Min`, `Max`, `AnyOfInterval`, `Latitude`, `Longitude` | `minimum`, `maximum` | +| `num`, `eq`, `uuid`: `Required` | `required` | +| slices: `Required`, `MinLen`, `MaxLen`, `Unique`, `Each` | `required` and `minItems: 1`, `minItems`, `maxItems`, `uniqueItems`, `items` | +| maps: `Required`, `MinLen`, `MaxLen`, `EachKey`, `EachValue` | `required` and `minProperties: 1`, `minProperties`, `maxProperties`, `propertyNames`, `additionalProperties` | + +The schema describes the rules, valigo validates the values: the descriptions are chosen not to be stricter than the rules, so a value valid for valigo is valid for the schema. The formats are annotations of JSON Schema, the validators that check them can differ in details. + +- `MinLen` of strings counts bytes, `minLength` counts characters: it isn't described. `MaxLen` is `maxLength`, a string of `n` bytes has no more than `n` characters. +- The rules under `When` of the struct and of fields aren't described, they don't apply to every value. +- After `Trim` and other `Modify` rules only `Required` is described: the schema describes the value of the request, the rules check the modified one. +- Rules on other fields, custom rules and the formats without a keyword of JSON Schema aren't described. + +## Your conversions + +A [conversion](conversions.md#your-types) describes its rules by `Schema` of the field, `Schema` of a slice configurator describes the rules of the slice: + +```go +// Percent checks that the number is in [0, 100]. +func (c *RatioConfigurator) Percent() *RatioConfigurator { + c.f.Schema("minimum", 0).Schema("maximum", 100) + c.f.CheckMsg(func(v Ratio) bool { return v >= 0 && v <= 100 }, shared.M("ratio.percent", percentKey)) + return c +} +``` diff --git a/mkdocs.yml b/mkdocs.yml index 30f3daa..3c882b4 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -97,6 +97,7 @@ nav: - Translations: features/translations.md - HTTP problem details: features/problem.md - Integrations: + - JSON Schema: features/schema.md - huma: features/huma.md - gin: features/gin.md - echo: features/echo.md @@ -147,7 +148,8 @@ plugins: - features/translations.md: locales, plural forms, languages from the context - features/problem.md: problem details of RFC 9457 Integrations: - - features/huma.md: huma inputs + - features/schema.md: the rules as the keywords of JSON Schema, Validator.Constraints + - features/huma.md: huma inputs, the rules in the OpenAPI document - features/gin.md: gin binding - features/echo.md: echo validator Architecture: diff --git a/skills/valigo/SKILL.md b/skills/valigo/SKILL.md index edc086a..9c5f209 100644 --- a/skills/valigo/SKILL.md +++ b/skills/valigo/SKILL.md @@ -178,6 +178,10 @@ func main() { `valigo.New(valigo.WithErrorsTransformer(problem.Transformer()))` makes `Validate` return one `*problem.Details` of RFC 9457, write it by `problem.From(errs).Write(w)`: 422, `application/problem+json`, `errors` with `detail`, `pointer` (`#/tags/1`), `location`, `code`, `params`. Options: `problem.WithType`, `WithTitle`, `WithStatus`, `WithDetail`. +## JSON Schema + +`v.Constraints()` returns the unconditional rules as JSON Schema keywords (`shared.Constraint`: Struct, Field, Path `items`/`additionalProperties`/`propertyNames`, Keyword, Value); rules under `When` aren't described, after `Trim`/`Modify` only `required`. `vhuma.OpenAPI(api, v)` returns the huma document with them in the body schemas (huma's own schemas stay unchanged). Own conversions describe rules by `f.Schema("minimum", 0)`. + ## gin The module `github.com/insei/valigo/gin` (`vgin`): `binding.Validator = vgin.New(v)` makes `c.ShouldBindJSON` validate by valigo (messages in the default language, gin passes no request), `vgin.Validate(c, v, &req)` validates with the languages of `Accept-Language`; the error is `shared.Errors`, get it by `errors.As`.