schema

package
v0.89.0 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: Apache-2.0 Imports: 20 Imported by: 2 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package schema provides the `@schema NAME { Field Type `json:"..." default:"..." validate:"..."` ... }` directive. The declaration lands in meta["schemas"]. Pipeline headers can use `:schema=NAME` for one shared request/response contract, or `:request-schema=NAME` (`:in-schema=NAME`) and `:response-schema=NAME` (`:out-schema=NAME`) for separate boundaries. Prefixing a selected name with `!` rejects undeclared fields at that boundary. Requests receive defaults before validation; response schemas are validated without defaults and must not declare any `default` tags. Such declarations fail before execution. Extra fields remain allowed unless the corresponding boundary is strict. All boundaries also accept `=[]Type`, including shared `:schema` shorthand, validating array shape and each item against a declared schema or supported scalar type. Request object items receive defaults; response items do not.

Typical use:

@schema TestUser {
  Name string `json:"name" default:"guest" validate:"required"`
}
@pipeline greet
  :schema=TestUser
  runtime.noop
@end

ApplyDefaults returns a new effective payload map, and schema validation passes that map to the pipeline's first action. NormalizeObject exposes encoding/json-compatible object normalization for Go values. Response boundaries validate this normalized view but return the original result, preserving typed values for callers and later composition.

Index

Constants

View Source
const (
	SchemaModifierName         = "schema"
	RequestSchemaModifierName  = "request-schema"
	ResponseSchemaModifierName = "response-schema"
	InSchemaModifierName       = "in-schema"
	OutSchemaModifierName      = "out-schema"
)
View Source
const ID = "schema"

Variables

View Source
var Directive = compiler.Directive{
	Name:        "schema",
	Example:     `@schema Plan { Summary string }`,
	Handler:     handleDirective,
	OpaqueBlock: true,
}

Directive parses `@schema NAME { ... }` into a Schema appended to meta["schemas"]. Duplicate names are a compile error.

View Source
var EnumDirective = compiler.Directive{
	Name:        "enum",
	Example:     "@enum OrderStatus { pending, paid = \"settled\" }",
	Handler:     handleEnumDirective,
	OpaqueBlock: true,
}

EnumDirective parses @enum declarations and exposes their wire strings to the current source's expression environment.

View Source
var InSchemaModifier = compiler.String(InSchemaModifierName,
	func(b *action.Builder[any, any], name string) *action.Builder[any, any] {
		return b.Tag("request-schema:" + name)
	})
View Source
var OutSchemaModifier = compiler.String(OutSchemaModifierName,
	func(b *action.Builder[any, any], name string) *action.Builder[any, any] {
		return b.Tag("response-schema:" + name)
	})
View Source
var RequestSchemaModifier = compiler.String(RequestSchemaModifierName,
	func(b *action.Builder[any, any], name string) *action.Builder[any, any] {
		return b.Tag("request-schema:" + name)
	})
View Source
var ResponseSchemaModifier = compiler.String(ResponseSchemaModifierName,
	func(b *action.Builder[any, any], name string) *action.Builder[any, any] {
		return b.Tag("response-schema:" + name)
	})
View Source
var SchemaModifier = compiler.String(SchemaModifierName,
	func(b *action.Builder[any, any], name string) *action.Builder[any, any] {
		return b.Tag("schema:" + name)
	})

SchemaModifier attaches schema metadata to an atom. Pipeline headers use schema selections at the request and response boundaries.

View Source
var ValidateAction = action.New("schema.validate", func(ctx context.Context, req ValidateRequest) (any, error) {
	if req.Name == "" {
		return nil, xerr.BadRequest("schema.validate: schema name is required (use ( name: \"SchemaName\" ))")
	}

	schemas, _ := schemasContextKey.From(ctx)
	targetSchema, ok := schemas[req.Name]
	if !ok {
		return nil, xerr.NotFound("schema.validate: schema '" + req.Name + "' not registered in workflow")
	}

	targetPayload := req.Payload
	if targetPayload == nil {
		targetPayload, _ = rootInputKey.From(ctx)
	}

	if targetPayload == nil {
		return nil, xerr.BadRequest("schema.validate: no payload available to validate")
	}

	effective, err := ApplyDefaultsAndValidate(ctx, targetSchema, targetPayload)
	if err != nil {
		return nil, err
	}

	return effective, nil
}).Description("Validate payload against a declared @schema").
	Tag("schema", "validation").
	Build()

Functions

func ApplyDefaults added in v0.30.2

func ApplyDefaults(schema Schema, payload any) (map[string]any, error)

ApplyDefaults returns a copy of payload with each missing field filled from its schema field's `default` tag. Explicitly supplied values, including nil, are preserved. The input map is never modified.

Scalar defaults are parsed according to the declared field type. Slice, map, and struct defaults use JSON values, for example `default:"[1,2]"` or `default:"{\"enabled\":true}"`.

func ApplyDefaultsAndValidate added in v0.30.3

func ApplyDefaultsAndValidate(ctx context.Context, schema Schema, payload any) (map[string]any, error)

ApplyDefaultsAndValidate returns the effective payload after applying missing defaults and validating the declared fields. Explicit input values, including typed slice values, are preserved.

func Bundle

func Bundle(_ map[string]string) compiler.Bundle

func IsArrayItemType added in v0.76.0

func IsArrayItemType(meta map[string]any, name string) bool

IsArrayItemType reports whether name is a declared schema or supported scalar type that can be selected as an element type for a schema-boundary array.

func IsScalarTypeName added in v0.76.0

func IsScalarTypeName(name string) bool

IsScalarTypeName reports whether name is one of the scalar types supported by schema fields.

func Library added in v0.12.0

func Library() action.Library

func NormalizeArray added in v0.76.0

func NormalizeArray(value any) ([]any, error)

NormalizeArray returns the JSON-visible elements of value as generic values. It follows encoding/json semantics and restores native time.Duration values for schema validation. The input is not modified.

func NormalizeObject added in v0.40.0

func NormalizeObject(value any) (map[string]any, error)

NormalizeObject returns the JSON-visible fields of value as a generic object. It follows encoding/json semantics for field visibility, json tags, embedded fields, pointers, custom marshalers, and omitempty. Nested objects become map[string]any, arrays become []any, and JSON numbers become float64. Native time.Duration values are restored in the decoded view so duration schemas can validate them without a JSON-number round trip.

A nil value, nil pointer, or value that encodes as a non-object is rejected. The input is not modified. Use the returned view for inspection or validation; retain the original value when typed output must be preserved.

func SplitFields added in v0.17.0

func SplitFields(s Schema) (payload, config []string)

func ToJSONSchema added in v0.22.0

func ToJSONSchema(s Schema) map[string]any

func Validate

func Validate(ctx context.Context, schema Schema, payload any) error

Validate applies missing defaults and checks payload against the declared schema.

For every field that is present, the check proceeds in two stages:

  1. Go-kind check (checkFieldKind): the payload value's kind must match the schema field's declared type.
  2. Tag check (validation.Var): when the field carries a `validate:"..."` tag beyond bare "required", the value is validated against the tag expression using the same validator/v10 instance that powers validation.Struct.

The presence check for validate:"required" is handled inline, so a missing field reports as "is required" without invoking the validator. An empty string for a required field is also reported as "is required" because validator/v10 treats empty as the zero value.

ctx is threaded from the caller so context-aware custom rules registered via validation.RegisterCustom see the live context, and so a canceled invocation aborts validation promptly.

func ValidateScalarValue added in v0.76.0

func ValidateScalarValue(typeName string, value any) error

checkFieldKind compares the runtime kind of value against the schema field's declared Go kind. Each mismatch produces a ValidationDetail whose Value reads "must be X (got Y)".

func ValidateWithoutDefaults added in v0.40.0

func ValidateWithoutDefaults(ctx context.Context, schema Schema, payload any) error

ValidateWithoutDefaults checks a payload against a schema without adding default values or changing the payload. Unknown fields are left untouched.

func WithContextSchemas added in v0.12.0

func WithContextSchemas(ctx context.Context, schemas []Schema) context.Context

Types

type Enum added in v0.85.0

type Enum struct {
	Name    string
	Members []EnumMember
}

Enum is a file-local set of wire strings. Its name is qualified by an @include alias when exposed to another source module.

func EnumsFromMap added in v0.85.0

func EnumsFromMap(meta map[string]any) []Enum

func VisibleEnumsFromMeta added in v0.85.0

func VisibleEnumsFromMeta(meta map[string]any) []Enum

VisibleEnumsFromMeta returns local enums and explicitly imported enums, qualified by each module's @include alias.

type EnumMember added in v0.85.0

type EnumMember struct {
	Name  string
	Value string
}

EnumMember is one named member of a file-local closed enum.

type Field

type Field struct {
	Name            string
	JSONName        string
	Type            string
	Kind            Kind
	ElemType        string
	Pointer         bool
	Slice           bool
	Map             bool
	Tags            map[string]string
	Embed           string
	EnumType        string
	EnumValues      []string
	TypedDefault    any
	HasTypedDefault bool
	NestedSchema    *Schema `json:"-"`
	Position        compiler.Position
}

type Kind

type Kind uint8
const (
	KindString Kind = iota
	KindInt
	KindFloat
	KindBool
	KindDuration
	KindAny
	KindStruct
	KindSecret
)

type Schema

type Schema struct {
	Name   string
	Fields []Field
}

func ByName

func ByName(meta map[string]any, name string) (Schema, bool)

func SchemasFromMap

func SchemasFromMap(meta map[string]any) []Schema

func VisibleSchemasFromMeta added in v0.53.0

func VisibleSchemasFromMeta(meta map[string]any) []Schema

VisibleSchemasFromMeta returns local schemas plus schemas from explicitly included modules, qualified by each include alias. It does not merge imported schemas into the local declaration set; callers must use the qualified name (for example, memory.ChatTurn) to select an imported schema.

type ValidateRequest added in v0.12.0

type ValidateRequest struct {
	Name    string `json:"name"              validate:"required"`
	Payload any    `json:"payload,omitempty"`
}

Jump to

Keyboard shortcuts

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