codex

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 21, 2026 License: MIT Imports: 8 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrMissingField = errors.New("missing required field")

ErrMissingField is returned when a required struct field is absent from the input. Use errors.Is to check for this sentinel.

Functions

func Downcast

func Downcast[A any, B any](v B) (A, error)

Downcast attempts to cast a value of type B to type A. Useful for tagged unions where variants share a common interface.

func Must

func Must[T any](v T, err error) T

Must returns v if err is nil, and panics with err otherwise.

It follows the same convention as template.Must and regexp.MustCompile: use it to wrap any (T, error) call where failure is a programming error, not a recoverable runtime condition.

Typical uses include package-level validated constants and test data setup:

var defaultEmail = codex.Must(emailCodec.New(Email("noreply@example.com")))
got := codex.Must(emailCodec.Decode("user@example.com"))

Types

type Codec

type Codec[T any] struct {
	Encode func(T) (any, error)
	Decode func(any) (T, error)
	Schema schema.Schema
}

Codec encodes values of type T to an intermediate representation, decodes that representation back to T, and describes the schema.

func Bool

func Bool() Codec[bool]

Bool returns a Codec for the bool type.

func Bytes

func Bytes() Codec[[]byte]

Bytes returns a Codec for []byte using base64 standard encoding. Encoded values are strings; schema format is "byte".

func Date

func Date() Codec[time.Time]

Date returns a Codec for time.Time using date-only encoding (2006-01-02). The time component is ignored on encode. Decoded values have time set to midnight UTC. Schema format is "date".

func Float64

func Float64() Codec[float64]

Float64 returns a Codec for the float64 type.

func Int

func Int() Codec[int]

Int returns a Codec for the int type.

func Int64

func Int64() Codec[int64]

Int64 returns a Codec for the int64 type.

func MapCodecSafe

func MapCodecSafe[A, B any](
	c Codec[A],
	to func(A) B,
	from func(B) (A, error),
) Codec[B]

MapCodecSafe creates a new Codec[B] from Codec[A] using two mapping functions. from is the encode direction and must always succeed. to is the decode direction and may fail.

func MapCodecValidated

func MapCodecValidated[A, B any](
	ca Codec[A],
	cb Codec[B],
	to func(A) (B, error),
	from func(B) (A, error),
) Codec[B]

MapCodecValidated creates a Codec[B] from Codec[A] and Codec[B] using two fallible mapping functions.

Both directions may return an error. After mapping to B in the decode direction, cb.Validate is called to enforce all Refine constraints defined on cb. The resulting codec carries cb's schema.

Use MapCodecValidated when the mapping itself can fail and the target type B has its own validation constraints expressed via Refine. For a simpler case where only the encode direction can fail and no post-mapping validation is needed, use MapCodecSafe.

func Nullable

func Nullable[T any](inner Codec[T]) Codec[*T]

Nullable wraps inner to produce a Codec[*T] that treats nil as JSON null. The generated schema inherits all fields from inner and sets Nullable to true.

func Refine

func Refine[T any](c Codec[T], constraints ...Constraint[T]) Codec[T]

Refine applies multiple constraints to a codec.

func SliceOf

func SliceOf[T any](elem Codec[T]) Codec[[]T]

SliceOf returns a Codec for a slice of T, using elem to encode/decode each element.

func String

func String() Codec[string]

String returns a Codec for the string type.

func StringMap

func StringMap[V any](value Codec[V]) Codec[map[string]V]

StringMap returns a Codec for map[string]V, using value to encode/decode each entry. The generated schema is an object with additionalProperties set to the value codec's schema.

func Struct

func Struct[T any](fields ...fieldCodec[T]) Codec[T]

Struct builds a Codec[T] by composing field codecs. Schema is built eagerly.

func TaggedUnion

func TaggedUnion[T any](
	tag string,
	variants map[string]Codec[T],
	selectVariant func(T) (string, error),
) Codec[T]

TaggedUnion builds a Codec[T] for a discriminated union identified by a tag field.

func Time

func Time() Codec[time.Time]

Time returns a Codec for time.Time using RFC 3339 (ISO 8601) encoding. Values are normalized to UTC on encode. Schema format is "date-time".

func (Codec[T]) New

func (c Codec[T]) New(v T) (T, error)

New validates v and returns it if all constraints pass.

It is a single-call smart constructor: call New to create a validated instance of T without separating construction from validation. On success it returns (v, nil); on failure it returns (zero, err) where err contains the first constraint that failed.

New delegates to Validate internally, so the same Refine constraints and encode-direction checks apply.

func (Codec[T]) Refine

func (c Codec[T]) Refine(cons Constraint[T]) Codec[T]

Refine wraps the codec with a single constraint checked during Decode. If cons.Schema is non-nil, it is applied to the codec's schema.

func (Codec[T]) Validate

func (c Codec[T]) Validate(v T) error

It encodes v to the intermediate representation and decodes it back, running all Refine constraints defined on the codec. This reuses the exact same constraint logic as Decode — builtin constraints (via validate.*) and any self-defined Constraint[T] values work without modification.

The encode direction is intentionally unconstrained (you constructed the value yourself). Call Validate explicitly when you want bidirectional enforcement.

func (Codec[T]) WithDescription

func (c Codec[T]) WithDescription(desc string) Codec[T]

WithDescription returns a new Codec with Schema.Description set to desc.

func (Codec[T]) WithTitle

func (c Codec[T]) WithTitle(title string) Codec[T]

WithTitle returns a new Codec with Schema.Title set to title.

type Constraint

type Constraint[T any] struct {
	Name    string
	Check   func(T) bool
	Message func(T) string
	Schema  func(schema.Schema) schema.Schema // optional: mutates schema when Refine is applied
}

Constraint is a named validation predicate applied during decoding.

The optional Schema field annotates the codec's schema when the constraint is applied via Refine. Set it to propagate constraint metadata (e.g. minimum length, numeric bounds) into the schema for renderers such as render/openapi. Leaving Schema nil is a no-op and keeps all existing constraints unchanged.

type ConstraintError

type ConstraintError struct {
	Name    string // constraint identifier
	Message string // human-readable failure description
}

ConstraintError is returned when a Refine constraint check fails during Decode. Name identifies the constraint (e.g. "minLen(3)"); Message describes the failure.

func (ConstraintError) Error

func (e ConstraintError) Error() string

func (ConstraintError) LogValue

func (e ConstraintError) LogValue() slog.Value

LogValue implements slog.LogValuer for structured logging.

type ElementError

type ElementError struct {
	Index int
	Err   error
}

ElementError wraps a decode error at a specific slice index.

func (ElementError) Error

func (e ElementError) Error() string

func (ElementError) LogValue

func (e ElementError) LogValue() slog.Value

LogValue implements slog.LogValuer for structured logging.

func (ElementError) Unwrap

func (e ElementError) Unwrap() error

type Field

type Field[T any, F any] struct {
	Name     string
	Codec    Codec[F]
	Get      func(T) F
	Set      func(*T, F)
	Required bool
}

Field describes a single struct field and its codec.

func OptionalField

func OptionalField[T, F any](name string, codec Codec[F], get func(T) F, set func(*T, F)) Field[T, F]

OptionalField is a shorthand for Field with Required set to false. The intent is explicit at the call site — no boolean flag needed.

func RequiredField

func RequiredField[T, F any](name string, codec Codec[F], get func(T) F, set func(*T, F)) Field[T, F]

RequiredField is a shorthand for Field with Required set to true. The intent is explicit at the call site — no boolean flag needed.

type KeyError

type KeyError struct {
	Key string
	Err error
}

KeyError wraps a decode error at a specific map key.

func (KeyError) Error

func (e KeyError) Error() string

func (KeyError) LogValue

func (e KeyError) LogValue() slog.Value

LogValue implements slog.LogValuer for structured logging.

func (KeyError) Unwrap

func (e KeyError) Unwrap() error

type TypeMismatchError

type TypeMismatchError struct {
	Expected string // e.g. "object", "array", "string"
	Got      string // e.g. "int", "bool"
}

TypeMismatchError is returned when a codec receives a value of an unexpected type. Expected names the required type; Got names the actual type received.

func (TypeMismatchError) Error

func (e TypeMismatchError) Error() string

func (TypeMismatchError) LogValue

func (e TypeMismatchError) LogValue() slog.Value

LogValue implements slog.LogValuer for structured logging.

type UnknownVariantError

type UnknownVariantError struct {
	Tag     string // discriminator field name
	Variant string // unrecognised tag value
}

UnknownVariantError is returned when a tagged union receives a tag value that does not match any registered variant. Tag is the discriminator field name; Variant is the unrecognised tag value.

func (UnknownVariantError) Error

func (e UnknownVariantError) Error() string

func (UnknownVariantError) LogValue

func (e UnknownVariantError) LogValue() slog.Value

LogValue implements slog.LogValuer for structured logging.

type ValidationError

type ValidationError struct {
	Field string // name of the field that failed
	Err   error  // underlying constraint or missing-field error
}

ValidationError is a single field-level validation failure returned from struct Decode.

func (ValidationError) Error

func (e ValidationError) Error() string

func (ValidationError) LogValue

func (e ValidationError) LogValue() slog.Value

LogValue implements slog.LogValuer for structured logging.

func (ValidationError) Unwrap

func (e ValidationError) Unwrap() error

type ValidationErrors

type ValidationErrors []ValidationError

ValidationErrors is a collection of field-level validation errors. It implements the error interface; callers can use errors.As to extract it. Unwrap returns the individual errors as a []error slice for errors.Is/As traversal.

func (ValidationErrors) Error

func (ve ValidationErrors) Error() string

func (ValidationErrors) LogValue

func (ve ValidationErrors) LogValue() slog.Value

LogValue implements slog.LogValuer for structured logging. Each field name is the slog key; its value is the underlying error (which invokes LogValue on types like ConstraintError, preserving nested structure).

func (ValidationErrors) Unwrap

func (ve ValidationErrors) Unwrap() []error

Unwrap returns the individual ValidationError values as a []error slice, enabling errors.Is and errors.As to traverse the full list.

type VariantError

type VariantError struct {
	Tag     string // discriminator field name
	Variant string // matched variant value
	Err     error  // underlying encode or decode failure
}

VariantError is returned when a known tagged-union variant fails to encode or decode. Tag is the discriminator field name; Variant is the matched variant value. Err is always non-nil; use UnknownVariantError for unrecognised tag values.

func (VariantError) Error

func (e VariantError) Error() string

func (VariantError) LogValue

func (e VariantError) LogValue() slog.Value

LogValue implements slog.LogValuer for structured logging.

func (VariantError) Unwrap

func (e VariantError) Unwrap() error

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL