expr

package
v1.10.0-alpha.6 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2026 License: MIT Imports: 43 Imported by: 16

Documentation

Overview

Package expr defines expressions and data types used by the DSL and the code generators. The expressions implement the Preparer, Validator, and Finalizer interfaces. The code generators use the finalized expressions to generate the final output.

The data types defined in the expr package are primitive types corresponding to scalar values (bool, string, integers, and numbers), array types which represent a collection of items, map types which represent maps of key/value pairs, and object types describing data structures with fields. The package also defines user types which can also be a result types. A result type is a user type used to describe response messages rendered using a view.

This file wires Loom's core expressions into the Meta DSL extension points.

The `dsl.Meta` and `dsl.RemoveMeta` helpers operate on the expression returned by `eval.Current()`. Most expressions that accept metadata store it in a `MetaExpr` field. By implementing the `MetaAdder` / `MetaDeleter` interfaces on those expressions, the DSL implementation stays small and does not need to enumerate all supported expression types.

Index

Constants

View Source
const (
	// FormatDate describes RFC3339 date values.
	FormatDate ValidationFormat = "date"

	// FormatDateTime describes RFC3339 date time values.
	FormatDateTime ValidationFormat = "date-time"

	// FormatUUID describes RFC4122 UUID values.
	FormatUUID = "uuid"

	// FormatEmail describes RFC5322 email addresses.
	FormatEmail = "email"

	// FormatHostname describes ASCII Internet hostnames with RFC1035 size limits
	// and RFC1123 letters/digits at label boundaries. A terminal root dot is allowed.
	FormatHostname = "hostname"

	// FormatIPv4 describes RFC2373 IPv4 address values.
	FormatIPv4 = "ipv4"

	// FormatIPv6 describes RFC2373 IPv6 address values.
	FormatIPv6 = "ipv6"

	// FormatIP describes RFC2373 IPv4 or IPv6 address values.
	FormatIP = "ip"

	// FormatURI describes absolute RFC3986 URI values with a scheme.
	FormatURI = "uri"

	// FormatURIReference describes RFC3986 URI-reference values.
	FormatURIReference = "uri-reference"

	// FormatMAC describes IEEE 802 MAC-48, EUI-48 or EUI-64 MAC address values.
	FormatMAC = "mac"

	// FormatCIDR describes RFC4632 and RFC4291 CIDR notation IP address values.
	FormatCIDR = "cidr"

	// FormatRegexp describes regular expression syntax accepted by RE2.
	FormatRegexp = "regexp"

	// FormatJSON describes JSON text.
	FormatJSON = "json"

	// FormatRFC1123 describes RFC1123 date time values.
	FormatRFC1123 = "rfc1123"
)
View Source
const (
	StatusContinue           = 100 // RFC 7231, 6.2.1
	StatusSwitchingProtocols = 101 // RFC 7231, 6.2.2
	StatusProcessing         = 102 // RFC 2518, 10.1

	StatusOK                   = 200 // RFC 7231, 6.3.1
	StatusCreated              = 201 // RFC 7231, 6.3.2
	StatusAccepted             = 202 // RFC 7231, 6.3.3
	StatusNonAuthoritativeInfo = 203 // RFC 7231, 6.3.4
	StatusNoContent            = 204 // RFC 7231, 6.3.5
	StatusResetContent         = 205 // RFC 7231, 6.3.6
	StatusPartialContent       = 206 // RFC 7233, 4.1
	StatusMultiStatus          = 207 // RFC 4918, 11.1
	StatusAlreadyReported      = 208 // RFC 5842, 7.1
	StatusIMUsed               = 226 // RFC 3229, 10.4.1

	StatusMultipleChoices  = 300 // RFC 7231, 6.4.1
	StatusMovedPermanently = 301 // RFC 7231, 6.4.2
	StatusFound            = 302 // RFC 7231, 6.4.3
	StatusSeeOther         = 303 // RFC 7231, 6.4.4
	StatusNotModified      = 304 // RFC 7232, 4.1
	StatusUseProxy         = 305 // RFC 7231, 6.4.5

	StatusTemporaryRedirect = 307 // RFC 7231, 6.4.7
	StatusPermanentRedirect = 308 // RFC 7538, 3

	StatusBadRequest                   = 400 // RFC 7231, 6.5.1
	StatusUnauthorized                 = 401 // RFC 7235, 3.1
	StatusPaymentRequired              = 402 // RFC 7231, 6.5.2
	StatusForbidden                    = 403 // RFC 7231, 6.5.3
	StatusNotFound                     = 404 // RFC 7231, 6.5.4
	StatusMethodNotAllowed             = 405 // RFC 7231, 6.5.5
	StatusNotAcceptable                = 406 // RFC 7231, 6.5.6
	StatusProxyAuthRequired            = 407 // RFC 7235, 3.2
	StatusRequestTimeout               = 408 // RFC 7231, 6.5.7
	StatusConflict                     = 409 // RFC 7231, 6.5.8
	StatusGone                         = 410 // RFC 7231, 6.5.9
	StatusLengthRequired               = 411 // RFC 7231, 6.5.10
	StatusPreconditionFailed           = 412 // RFC 7232, 4.2
	StatusRequestEntityTooLarge        = 413 // RFC 7231, 6.5.11
	StatusRequestURITooLong            = 414 // RFC 7231, 6.5.12
	StatusUnsupportedMediaType         = 415 // RFC 7231, 6.5.13
	StatusRequestedRangeNotSatisfiable = 416 // RFC 7233, 4.4
	StatusExpectationFailed            = 417 // RFC 7231, 6.5.14
	StatusTeapot                       = 418 // RFC 7168, 2.3.3
	StatusUnprocessableEntity          = 422 // RFC 4918, 11.2
	StatusLocked                       = 423 // RFC 4918, 11.3
	StatusFailedDependency             = 424 // RFC 4918, 11.4
	StatusUpgradeRequired              = 426 // RFC 7231, 6.5.15
	StatusPreconditionRequired         = 428 // RFC 6585, 3
	StatusTooManyRequests              = 429 // RFC 6585, 4
	StatusRequestHeaderFieldsTooLarge  = 431 // RFC 6585, 5
	StatusUnavailableForLegalReasons   = 451 // RFC 7725, 3

	StatusInternalServerError           = 500 // RFC 7231, 6.6.1
	StatusNotImplemented                = 501 // RFC 7231, 6.6.2
	StatusBadGateway                    = 502 // RFC 7231, 6.6.3
	StatusServiceUnavailable            = 503 // RFC 7231, 6.6.4
	StatusGatewayTimeout                = 504 // RFC 7231, 6.6.5
	StatusHTTPVersionNotSupported       = 505 // RFC 7231, 6.6.6
	StatusVariantAlsoNegotiates         = 506 // RFC 2295, 8.1
	StatusInsufficientStorage           = 507 // RFC 4918, 11.5
	StatusLoopDetected                  = 508 // RFC 5842, 7.2
	StatusNotExtended                   = 510 // RFC 2774, 7
	StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6
)
View Source
const (
	RPCParseError     = -32700 // JSON-RPC 2.0, 5.1
	RPCInvalidRequest = -32600
	RPCMethodNotFound = -32601
	RPCInvalidParams  = -32602
	RPCInternalError  = -32603
)
View Source
const (
	// DefaultView is the name of the default result type view.
	DefaultView = "default"

	// ViewMetaKey is the key used to store the view name in the attribute meta.
	ViewMetaKey = "view"
)
View Source
const (
	// Boolean is the type for a JSON boolean.
	Boolean = Primitive(BooleanKind)

	// Int is the type for a signed integer.
	Int = Primitive(IntKind)

	// Int32 is the type for a signed 32-bit integer.
	Int32 = Primitive(Int32Kind)

	// Int64 is the type for a signed 64-bit integer.
	Int64 = Primitive(Int64Kind)

	// UInt is the type for an unsigned integer.
	UInt = Primitive(UIntKind)

	// UInt32 is the type for an unsigned 32-bit integer.
	UInt32 = Primitive(UInt32Kind)

	// UInt64 is the type for an unsigned 64-bit integer.
	UInt64 = Primitive(UInt64Kind)

	// Float32 is the type for a 32-bit floating number.
	Float32 = Primitive(Float32Kind)

	// Float64 is the type for a 64-bit floating number.
	Float64 = Primitive(Float64Kind)

	// String is the type for a JSON string.
	String = Primitive(StringKind)

	// Bytes is the type for binary data.
	Bytes = Primitive(BytesKind)

	// Any is the type for an arbitrary JSON value (any in Go).
	Any = Primitive(AnyKind)
)
View Source
const DefaultProtoc = "protoc"

DefaultProtoc is the default command to be invoked for generating code from protobuf schemas.

Variables

View Source
var (
	// ProblemResultIdentifier is the standards-first result type identifier used
	// for RFC 9457-style problem responses.
	ProblemResultIdentifier = "application/problem+json"

	// ErrorResultIdentifier is the result type identifier used for default HTTP
	// error responses. It intentionally matches ProblemResultIdentifier so the
	// framework defaults to RFC 9457 problem documents.
	ErrorResultIdentifier = ProblemResultIdentifier

	// ErrorResult is the built-in result type for error responses.
	ErrorResult = &ResultTypeExpr{
		UserTypeExpr: &UserTypeExpr{
			AttributeExpr: &AttributeExpr{
				Type:        problemResultType,
				Description: "Problem response result type",
				Validation:  &ValidationExpr{Required: []string{"type", "title", "status", "detail", "instance", "code"}},
			},
			TypeName: "problem",
		},
		Identifier: ErrorResultIdentifier,
		Views:      []*ViewExpr{problemResultView},
	}

	// ProblemResult is the built-in result type for problem-document error
	// responses.
	ProblemResult = ErrorResult
)
View Source
var Empty = &UserTypeExpr{
	TypeName: "Empty",
	AttributeExpr: &AttributeExpr{
		Description: "Empty represents empty values",
		Type:        &Object{},
	},
}

Empty represents empty values.

View Source
var (
	// ErrValuePlanAssociationNotFound reports that a valid occurrence and target
	// node have no captured association in this plan. Callers that search exact
	// captured ancestry may continue only for this error.
	ErrValuePlanAssociationNotFound = errors.New("value plan association not found")
)
View Source
var GeneratedResultTypes = defaultRuntime.GeneratedResultTypes

GeneratedResultTypes records the generated result types and is a DSL root evaluated after Root.

View Source
var HTTPWildcardRegex = regexp.MustCompile(`/{\*?([a-zA-Z0-9_]+)}`)

HTTPWildcardRegex is the regular expression used to capture path parameters.

View Source
var Root = defaultRuntime.Root

Root is the root object built by the DSL.

Functions

func AllowsNull added in v1.8.0

func AllowsNull(attribute *AttributeExpr) bool

AllowsNull reports whether an attribute occurrence accepts an explicit null value. Any is intrinsically null-admitting, and nullable named types carry their nullability to each occurrence.

func ArrayElementsAllowNull added in v1.9.0

func ArrayElementsAllowNull(array *Array) bool

ArrayElementsAllowNull reports whether an array accepts explicit null elements. ArrayOfRequired overrides the element type's intrinsic nullability.

func AttributeName

func AttributeName(key string) string

AttributeName returns the attribute name of the object key: the part of key that precedes the transport element name suffix, such as "n" for "n:m", or key when it has no suffix.

func AuthorizationValues added in v1.9.0

func AuthorizationValues(att *AttributeExpr) ([]string, error)

AuthorizationValues returns the finite authored values of a selector.

func CanonicalIdentifier

func CanonicalIdentifier(identifier string) string

CanonicalIdentifier returns the result type identifier sans suffix which is what the DSL uses to store and lookup result types.

func CanonicalizeExample

func CanonicalizeExample(att *AttributeExpr, example any) any

CanonicalizeExample normalizes example values to their canonical JSON shape: objects use the JSON field names of the HTTP and JSON-RPC bodies, which name a field declared as "n:m" after its element name "m", Loom unions use their discriminator/value shape, and map keys become JSON object member names, so that the key true becomes "true" and the key 12 becomes "12".

func ContainsNonNullableCollectionElement added in v1.9.0

func ContainsNonNullableCollectionElement(attribute *AttributeExpr) bool

ContainsNonNullableCollectionElement reports whether an attribute contains an array element or map value contract that rejects null.

func CreateTempFile

func CreateTempFile(t *testing.T, content string) string

CreateTempFile creates a temporary file and writes the given content. It is used only for testing.

func DerivedUnionTypeName

func DerivedUnionTypeName(names []string) string

DerivedUnionTypeName returns the deterministic type name for a derived union given the already-derived variant names.

func DerivedUnionVariantNames

func DerivedUnionVariantNames(types []DataType) []string

DerivedUnionVariantNames returns deterministic discriminator names for the given union variant data types.

func DupKeeping

func DupKeeping(d DataType, keep []UserType) (DataType, []*AttributeExpr)

DupKeeping creates a copy of the given data type like Dup, except that it keeps the references to the user types in keep instead of copying them. It also returns the attributes of the copy that reference a kept user type. Use it to copy a type that references user types whose DSL is still running, so that the copy does not snapshot their incomplete definitions.

func ElementName

func ElementName(key string) string

ElementName returns the transport element name of the object key: the suffix of key, such as "m" for "n:m", or key when it has no suffix. HTTP and JSON-RPC bodies name the field after it.

func Equal

func Equal(dt, dt2 DataType) bool

Equal compares the types recursively and returns true if they are equal. Two types are equal if:

  • both types have the same kind
  • primitive types have the same name
  • array types have elements whose types are equal
  • map types have keys and elements whose types are equal
  • union types have the same type name, tagging, and variant names, and the variant types are equal
  • user and result types have the same nullability and their underlying types are equal, whatever their names
  • objects have the same attribute names and the attribute types are equal
  • attributes being compared have the same nullability

Equal ignores type names, struct field tags, and validations. Recursive types are compared coinductively, so a type that references itself is never equal to a finite type.

Note: calling Equal is not equivalent to evaluating dt.Hash() == dt2.Hash() as the former may return true for two user types with different names and thus with different hash values.

func ExtractHTTPWildcards

func ExtractHTTPWildcards(path string) []string

ExtractHTTPWildcards returns the names of the wildcards that appear in a HTTP path.

func Hash

func Hash(dt DataType, ignoreFields, ignoreNames, ignoreTags bool) string

Hash returns a hash value for the given data type. The hash of a primitive type is its name. When ignoreFields is true, two types have the same hash if:

  • both types have the same kind
  • array types have elements whose types have the same hash
  • map types have keys and elements whose types have the same hash
  • union types have the same name and variants whose types have the same hash
  • user types have the same name
  • object attributes have the same "struct:field:xxx" tags if ignoreTags is false

When ignoreFields is false, two types have the same hash if their unfoldings are identical: user types are compared by their attribute types instead of only by name, and their names are compared too unless ignoreNames is true. Recursive types are handled exactly, so a type that references itself never has the same hash as a finite type. Hash results are deterministic.

func InlineJSONSchema

func InlineJSONSchema(attr *AttributeExpr) ([]byte, error)

InlineJSONSchema returns a compact JSON Schema for the given Loom attribute. The schema is fully resolved and does not include $ref references. Object properties use the JSON field names of the HTTP and JSON-RPC bodies, which name a field declared as "n:m" after its element name "m".

func IsAlias

func IsAlias(dt DataType) bool

IsAlias returns true if the data type is a user type backed by a primitive type (so call aliased type).

func IsAny added in v1.9.0

func IsAny(dataType DataType) bool

IsAny reports whether a data type resolves to Any through named types.

func IsArray

func IsArray(dt DataType) bool

IsArray returns true if the data type is an array.

func IsDefaultErrorResult added in v1.0.9

func IsDefaultErrorResult(dt DataType) bool

IsDefaultErrorResult returns true when dt is one of the built-in problem document result types used for default HTTP error contracts.

func IsMap

func IsMap(dt DataType) bool

IsMap returns true if the data type is a map.

func IsNullable added in v1.8.0

func IsNullable(attribute *AttributeExpr) bool

IsNullable reports whether nullability is explicitly declared on an attribute occurrence or inherited from a named type.

func IsObject

func IsObject(dt DataType) bool

IsObject returns true if the data type is an object.

func IsPrimitive

func IsPrimitive(dt DataType) bool

IsPrimitive returns true if the data type is a primitive type.

func IsUnion

func IsUnion(dt DataType) bool

IsUnion returns true if the data type is a map.

func JSONFieldName added in v1.9.0

func JSONFieldName(name string, attribute *AttributeExpr) string

JSONFieldName returns the effective JSON member name for an object field.

func MapValuesAllowNull added in v1.9.0

func MapValuesAllowNull(mapping *Map) bool

MapValuesAllowNull reports whether a map accepts explicit null values.

func NewLength

func NewLength(a *AttributeExpr, r *ExampleGenerator) int

NewLength returns an int that validates the generator attribute length validations if any.

func PrepareValidateFinalize

func PrepareValidateFinalize(root *RootExpr) error

PrepareValidateFinalize runs prepare, validate, and finalize on the given root using an isolated evaluation context and temporary Root binding.

func QualifiedTypeName

func QualifiedTypeName(t DataType) string

QualifiedTypeName returns the qualified type name for the given data type. The qualified type name includes the name of the type of the elements of array or map types. This is useful in reporting types in error messages, examples of qualified type names:

"array<string>"
"map<string, string>"
"map<string, array<int32>>"

func RegisterDefaultRoots added in v1.0.8

func RegisterDefaultRoots() error

RegisterDefaultRoots registers the process-default runtime roots with the current evaluation context.

func RemovePkgPath

func RemovePkgPath(attr *AttributeExpr)

RemovePkgPath traverses the given data type and removes the "struct:pkg:path" metadata from all the user type attributes.

func RunInvalidDSL

func RunInvalidDSL(t *testing.T, dsl func()) error

RunInvalidDSL returns the error resulting from running the given DSL. It is used only in tests.

func TaggedAttribute

func TaggedAttribute(a *AttributeExpr, tag string) string

TaggedAttribute returns the name of the child attribute of a with the given tag if a is an object.

func Title

func Title(s string) string

Title returns the string with the first character of each word in upper case.

func UnionVariantPublicName

func UnionVariantPublicName(dt DataType) string

UnionVariantPublicName returns the stable public-facing name for the union variant data type. A user type renamed for a transport body, possibly more than once, keeps the name it had before its first rename.

func UnionVariantTag

func UnionVariantTag(nat *NamedAttributeExpr) string

UnionVariantTag returns the wire discriminator value for a union branch. It prefers explicit metadata and falls back to the attribute name of the branch, without its element name suffix.

func UniqueStableNames

func UniqueStableNames(bases, stableKeys []string, suffix func(base string, ordinal int) string) []string

UniqueStableNames deduplicates base names using the corresponding stable keys to produce deterministic suffix assignment across runs.

func WalkMappedAttr

func WalkMappedAttr(ma *MappedAttributeExpr, it MappedAttributeWalker) error

WalkMappedAttr iterates over the mapped attributes. It calls the given function giving each attribute as it iterates. WalkMappedAttr stops if there is no more attribute to iterate over or if the iterator function returns an error in which case it returns the error.

Types

type APIExpr

type APIExpr struct {
	// DSLFunc contains the DSL used to initialize the expression.
	eval.DSLFunc
	// Name of API
	Name string
	// Title of API
	Title string
	// Description of API
	Description string
	// Version is the version of the API described by this DSL.
	Version string
	// Servers lists the API hosts.
	Servers []*ServerExpr
	// TermsOfService describes or links to the service terms of API.
	TermsOfService string
	// Contact provides the API users with contact information.
	Contact *ContactExpr
	// License describes the API license.
	License *LicenseExpr
	// Docs points to the API external documentation.
	Docs *DocsExpr
	// Meta is a list of key/value pairs.
	Meta MetaExpr
	// Requirements contains the security requirements that apply to
	// all the API service methods. One requirement is composed of
	// potentially multiple schemes. Incoming requests must validate
	// at least one requirement to be authorized.
	Requirements []*SecurityExpr
	// SessionAuths contains the multi-transport session auth contracts that
	// apply to all API service methods.
	SessionAuths []*SessionAuthExpr
	// ClientInterceptors is the list of API client interceptors.
	ClientInterceptors []*InterceptorExpr
	// ServerInterceptors is the list of API server interceptors.
	ServerInterceptors []*InterceptorExpr
	// StrictAuthorization requires every method to declare access or an exemption.
	StrictAuthorization bool
	// HTTP contains the HTTP specific API level expressions.
	HTTP *HTTPExpr
	// GRPC contains the gRPC specific API level expressions.
	GRPC *GRPCExpr
	// JSONRPC contains the JSON-RPC specific API level expressions.
	JSONRPC *JSONRPCExpr

	// random generator used to build examples for the API types.
	ExampleGenerator *ExampleGenerator
}

APIExpr contains the global properties for an API expression.

func NewAPIExpr

func NewAPIExpr(name string, dsl func()) *APIExpr

NewAPIExpr initializes an API expression.

func (*APIExpr) AddMeta

func (a *APIExpr) AddMeta(name string, value ...string)

AddMeta appends metadata values to the API expression.

func (*APIExpr) DefaultServer

func (a *APIExpr) DefaultServer() *ServerExpr

DefaultServer returns a server expression that describes a server which exposes all the services in the design and listens on localhost port 80 for HTTP requests and port 8080 for gRPC requests.

func (*APIExpr) DeleteMeta

func (a *APIExpr) DeleteMeta(name string)

DeleteMeta removes a metadata entry from the API expression.

func (*APIExpr) EvalName

func (a *APIExpr) EvalName() string

EvalName is the qualified name of the expression.

func (*APIExpr) Finalize

func (a *APIExpr) Finalize()

Finalize makes sure that the API name is initialized and there is at least one server definition (if none exists, it creates a default server). If API name is empty, it sets the name of the first service definition as API name.

func (*APIExpr) Hash

func (a *APIExpr) Hash() string

Hash returns a unique hash value for a.

func (*APIExpr) Schemes

func (a *APIExpr) Schemes() []string

Schemes returns the list of transport schemes used by all the API servers. The possible values for the elements of the returned slice are "http", "https", "grpc" and "grpcs".

func (*APIExpr) Validate added in v1.8.0

func (a *APIExpr) Validate() error

Validate checks API-level metadata constraints.

type Array

type Array struct {
	ElemType         *AttributeExpr
	NonNullableElems bool
}

Array is the type used to describe field arrays or repeated fields.

func AsArray

func AsArray(dt DataType) *Array

AsArray returns the type underlying array if any, nil otherwise.

func (*Array) Example

func (a *Array) Example(r *ExampleGenerator) any

Example generates a pseudo-random array value using the given random generator.

func (*Array) Hash

func (a *Array) Hash() string

Hash returns a unique hash value for a.

func (*Array) IsCompatible

func (a *Array) IsCompatible(val any) bool

IsCompatible returns true if val is compatible with p.

func (*Array) Kind

func (*Array) Kind() Kind

Kind implements DataKind.

func (*Array) MakeSlice

func (a *Array) MakeSlice(s []any) any

MakeSlice examines the key type from the Array and create a slice with builtin type if possible. The idea is to avoid generating []any and produce more precise types.

func (*Array) Name

func (*Array) Name() string

Name returns the type name.

type ArrayVal

type ArrayVal []any

ArrayVal is the type used to set the default value for arrays.

func (ArrayVal) ToSlice

func (a ArrayVal) ToSlice() []any

ToSlice converts an ArrayVal into a slice.

type AttributeExpr

type AttributeExpr struct {
	// DSLFunc contains the DSL used to initialize the expression.
	eval.DSLFunc
	// Attribute type
	Type DataType
	// Base types if any
	Bases []DataType
	// Attribute reference types if any
	References []DataType
	// Optional description
	Description string
	// Title is the optional JSON Schema title for this attribute.
	Title string
	// Docs points to external documentation
	Docs *DocsExpr
	// Optional validations
	Validation *ValidationExpr
	// Meta is a list of key/value pairs
	Meta MetaExpr
	// Optional member default value
	DefaultValue any
	// Nullable reports whether the attribute occurrence accepts an explicit
	// null value independently of whether its parent requires the field.
	Nullable bool
	// UserExample set in DSL or computed in Finalize
	UserExamples []*ExampleExpr
	// contains filtered or unexported fields
}

AttributeExpr defines an object field with optional description, default value and validations.

func DupAtt

func DupAtt(att *AttributeExpr) *AttributeExpr

DupAtt creates a copy of the given attribute.

func UnionToObject

func UnionToObject(att *AttributeExpr) *AttributeExpr

UnionToObject returns an object adequate to serialize the given union type in HTTP requests and responses. The object has two fields for the discriminator and value, with names determined by the union's Meta tags (defaulting to "Type" and "Value"). The discriminator field indicates the name of the union type, and the value field contains the JSON encoded union value.

func UnwrapInlineHTTPBody

func UnwrapInlineHTTPBody(att *AttributeExpr) *AttributeExpr

UnwrapInlineHTTPBody returns the inline object request body defined with the Body DSL when att is the user type that wraps it for Go code generation, and att otherwise. The result is a shallow copy of att that keeps its meta, validation and examples. Generators that document the HTTP contract, such as OpenAPI, use it so that the wrapper never becomes a named schema.

func (*AttributeExpr) AddMeta

func (a *AttributeExpr) AddMeta(name string, vals ...string)

AddMeta adds values to the meta field of the attribute.

func (*AttributeExpr) AllRequired

func (a *AttributeExpr) AllRequired() []string

AllRequired returns the list of all required fields from the underlying object. This method recurses if the type is itself an attribute (i.e. a UserType). Before finalization it also resolves required fields inherited from Reference and Extend, restricted to fields selected by a reference.

func (*AttributeExpr) Debug

func (a *AttributeExpr) Debug(prefix string)

Debug dumps the attribute to STDOUT in a Loom developer friendly way.

func (*AttributeExpr) Delete

func (a *AttributeExpr) Delete(name string)

Delete removes an attribute with the given name. It does nothing if the attribute expression is not an object type.

func (*AttributeExpr) DeleteMeta

func (a *AttributeExpr) DeleteMeta(name string)

DeleteMeta removes the metadata entry with the given name.

func (*AttributeExpr) EvalName

func (a *AttributeExpr) EvalName() string

EvalName returns the name used by the DSL evaluation.

func (*AttributeExpr) Example

func (a *AttributeExpr) Example(r *ExampleGenerator) any

Example returns the example set on the attribute at design time. If there isn't such a value then Example computes a random value for the attribute using the given random value producer.

func (*AttributeExpr) ExtractUserExamples

func (a *AttributeExpr) ExtractUserExamples() []*ExampleExpr

ExtractUserExamples return the examples defined in the design directly on the attribute or on its type.

func (*AttributeExpr) FieldTag

func (a *AttributeExpr) FieldTag() (tag string, found bool)

FieldTag returns the field tag if the attribute is a field.

func (*AttributeExpr) Finalize

func (a *AttributeExpr) Finalize()

Finalize merges base and reference type attributes and finalizes the Type attribute.

func (*AttributeExpr) Find

func (a *AttributeExpr) Find(name string) *AttributeExpr

Find finds a child attribute with the given name in the attribute and its bases and references. If the parent attribute is not an object, it returns nil.

func (*AttributeExpr) FindAttribute

func (a *AttributeExpr) FindAttribute(name string) (string, *AttributeExpr)

FindAttribute finds a child attribute by attribute name in the attribute and its bases and references, as Find does. The attribute name of an object key is the part that precedes its element name suffix (AttributeName), so FindAttribute("n") and FindAttribute("n:x") both find a child declared as "n", "n:m" or "n:x". A child whose key is name takes precedence. It returns the object key and the child, or an empty string and nil when the attribute is not an object or has no such child.

func (*AttributeExpr) GetDefault

func (a *AttributeExpr) GetDefault(attName string) any

GetDefault gets the default value for the child attribute with the given name. Before design finalization it follows named-type ancestry without validating the complete value graph. It returns nil if the child attribute does not exist or if the child attribute does not have a default value.

func (*AttributeExpr) HasDefaultValue

func (a *AttributeExpr) HasDefaultValue(attName string) bool

HasDefaultValue returns true if the attribute with the given name has a default value.

func (*AttributeExpr) HasTag

func (a *AttributeExpr) HasTag(tag string) bool

HasTag returns true if the attribute is an object that has an attribute with the given tag.

func (*AttributeExpr) HasTagPrefix

func (a *AttributeExpr) HasTagPrefix(prefix string) bool

HasTagPrefix returns true if the attribute is an object that has an attribute with the given tag prefix.

func (*AttributeExpr) Inherit

func (a *AttributeExpr) Inherit(parent *AttributeExpr)

Inherit merges the properties of existing target type attributes with the argument's. The algorithm is recursive so that child attributes are also merged.

func (*AttributeExpr) IsPrimitivePointer

func (a *AttributeExpr) IsPrimitivePointer(attName string, useDefault bool) bool

IsPrimitivePointer returns true if the field generated for the given attribute should be a pointer to a primitive type. The receiver attribute must be an object.

If useDefault is true and the attribute has a default value then IsPrimitivePointer returns false. This makes it possible to differentiate between request types where attributes with default values should not be generated using a pointer value and response types where they should.

DefaultValue UseDefault Pointer (assuming all other conditions are true)
Yes          True       False
Yes          False      True
No           True       True
No           False      True

func (*AttributeExpr) IsRequired

func (a *AttributeExpr) IsRequired(attName string) bool

IsRequired returns true if the given string matches the name of a required attribute, false otherwise. This method only applies to attributes of type Object.

func (*AttributeExpr) IsRequiredNoDefault

func (a *AttributeExpr) IsRequiredNoDefault(attName string) bool

IsRequiredNoDefault returns true if the given string matches the name of a required attribute and the attribute has no default value, false otherwise. This method only applies to attributes of type Object.

func (*AttributeExpr) IsSupportedValidationFormat

func (*AttributeExpr) IsSupportedValidationFormat(vf ValidationFormat) bool

IsSupportedValidationFormat checks if the validation format is supported by Loom.

func (*AttributeExpr) Merge

func (a *AttributeExpr) Merge(other *AttributeExpr)

Merge merges other's attributes into a overriding attributes of a with attributes of other with identical names.

This only applies to attributes of type Object and Merge panics if the argument or the target is not of type Object.

func (*AttributeExpr) Prepare

func (a *AttributeExpr) Prepare()

Prepare resolves any deferred named type references before validation.

func (*AttributeExpr) SetDefault

func (a *AttributeExpr) SetDefault(def any)

SetDefault sets the default for the attribute. It also converts HashVal and ArrayVal to map and slice respectively.

func (*AttributeExpr) SetTitle added in v1.8.0

func (a *AttributeExpr) SetTitle(title string)

SetTitle sets the JSON Schema title for the attribute.

func (*AttributeExpr) UnionFieldTags

func (a *AttributeExpr) UnionFieldTags() []string

UnionFieldTags returns the field tags of the branches of the union attribute a in declaration order, or nil if a is not a union. A branch keeps the tag set with Field in a OneOf block. A branch without a tag takes the field tag of a plus its position when a has a numeric one, so that Field(n, "name", OneOf(A, B)) numbers the branches n and n+1. The tag of a branch that has neither is empty.

func (*AttributeExpr) Validate

func (a *AttributeExpr) Validate(ctx string, parent eval.Expression) *eval.ValidationErrors

Validate tests whether the attribute required fields exist. Since attributes are unaware of their context, additional context information can be provided to be used in error messages. The parent definition context is automatically added to error messages.

type AuthorizationBindingExpr added in v1.9.0

type AuthorizationBindingExpr struct {
	// Input is a top-level field of the requirement input.
	Input string
	// Payload is a dot-separated path, with union paths resolved in their case.
	Payload string
}

AuthorizationBindingExpr connects an input field to a payload path.

type AuthorizationCaseExpr added in v1.9.0

type AuthorizationCaseExpr struct {
	// Value is the authored enum value or union branch name.
	Value string
	// Authorization contains this case's requirements or exemption.
	Authorization *MethodAuthorizationExpr
}

AuthorizationCaseExpr classifies one enum value or union branch name.

type AuthorizationExpr added in v1.9.0

type AuthorizationExpr struct {
	// Name identifies the requirement independently of service method names.
	Name string
	// Input defines the typed values passed to the application evaluator.
	Input *AttributeExpr
}

AuthorizationExpr declares an application-owned decision with a stable name and a concrete named object input, or Empty for a context-only check.

func (*AuthorizationExpr) EvalName added in v1.9.0

func (a *AuthorizationExpr) EvalName() string

EvalName returns the requirement's diagnostic identity.

type AuthorizationPathStep added in v1.9.0

type AuthorizationPathStep struct {
	// Name is an object field or a selected union branch name.
	Name string
	// Parent owns the field and its requiredness.
	Parent *AttributeExpr
	// Attribute is the selected field or branch type.
	Attribute *AttributeExpr
	// Union indicates selection of the active union branch.
	Union bool
}

AuthorizationPathStep describes one validated access along a payload path.

func AuthorizationPath added in v1.9.0

func AuthorizationPath(payload *AttributeExpr, path, selector, branch string) ([]*AuthorizationPathStep, error)

AuthorizationPath resolves a payload path without reflection. Within a union case, traversing selector selects branch before continuing into its fields. Empty paths select the entire payload; this is useful for a root union.

type AuthorizationUseExpr added in v1.9.0

type AuthorizationUseExpr struct {
	// Requirement is the registered application decision.
	Requirement *AuthorizationExpr
	// Bindings connect named input fields to typed payload paths.
	Bindings []*AuthorizationBindingExpr
}

AuthorizationUseExpr binds a named requirement to a method payload.

func (*AuthorizationUseExpr) EvalName added in v1.9.0

func (a *AuthorizationUseExpr) EvalName() string

EvalName returns the binding scope's diagnostic identity.

type CompositeExpr

type CompositeExpr interface {
	// Attribute returns the composite expression embedded attribute.
	Attribute() *AttributeExpr
}

CompositeExpr defines a generic composite expression that contains an attribute. This makes it possible for plugins to use attributes in their own data structures.

type ContactExpr

type ContactExpr struct {
	// Name of the contact person/organization
	Name string `json:"name,omitempty"`
	// Email address of the contact person/organization
	Email string `json:"email,omitempty"`
	// URL pointing to the contact information
	URL string `json:"url,omitempty"`
}

ContactExpr contains the API contact information.

func (*ContactExpr) EvalName

func (c *ContactExpr) EvalName() string

EvalName is the qualified name of the expression.

type CookieSameSiteValue

type CookieSameSiteValue string

CookieSameSiteValue is the type used to enumerate the possible cookie SameSite values.

const (
	CookieSameSiteStrict  CookieSameSiteValue = "strict"
	CookieSameSiteLax     CookieSameSiteValue = "lax"
	CookieSameSiteNone    CookieSameSiteValue = "none"
	CookieSameSiteDefault CookieSameSiteValue = "default"
)

type DataType

type DataType interface {
	// Kind of data type, one of the Kind enum.
	Kind() Kind
	// Name returns the type name.
	Name() string
	// IsCompatible checks whether val has a Go type that is compatible with the data
	// type.
	IsCompatible(any) bool
	// Example generates a pseudo-random value using the given random generator.
	Example(*ExampleGenerator) any
	// Hash returns a unique hash value for the instance of the type.
	Hash() string
}

DataType is the common interface to all types.

func Dup

func Dup(d DataType) DataType

Dup creates a copy the given data type.

type DescriptionHolder

type DescriptionHolder interface {
	SetDescription(string)
}

DescriptionHolder is an interface that allows expression types to receive a description. Types implementing this interface can use the Description() DSL function to set a description.

type DeterministicRandomizer

type DeterministicRandomizer struct{}

DeterministicRandomizer returns hard-coded values, removing all randomness from example generation

func (DeterministicRandomizer) ArrayLength

func (DeterministicRandomizer) ArrayLength() int

func (DeterministicRandomizer) Bool

func (DeterministicRandomizer) Characters

func (DeterministicRandomizer) Characters(n int) string

func (DeterministicRandomizer) Email

func (DeterministicRandomizer) Float32

func (DeterministicRandomizer) Float32() float32

func (DeterministicRandomizer) Float64

func (DeterministicRandomizer) Float64() float64

func (DeterministicRandomizer) Hostname

func (DeterministicRandomizer) Hostname() string

func (DeterministicRandomizer) IPv4Address

func (DeterministicRandomizer) IPv4Address() net.IP

func (DeterministicRandomizer) IPv6Address

func (DeterministicRandomizer) IPv6Address() net.IP

func (DeterministicRandomizer) Int

func (DeterministicRandomizer) Int32

func (DeterministicRandomizer) Int64

func (DeterministicRandomizer) Name

func (DeterministicRandomizer) String

func (DeterministicRandomizer) UInt

func (DeterministicRandomizer) UInt32

func (DeterministicRandomizer) UInt64

func (DeterministicRandomizer) URL

func (DeterministicRandomizer) UUID

type DocsExpr

type DocsExpr struct {
	// Description of documentation.
	Description string `json:"description,omitempty"`
	// URL to documentation.
	URL string `json:"url,omitempty"`
}

DocsExpr points to external documentation.

func (*DocsExpr) EvalName

func (d *DocsExpr) EvalName() string

EvalName is the qualified name of the expression.

type EffectiveConstraintSource

type EffectiveConstraintSource struct {
	// Occurrence identifies the finalized attribute occurrence that authored
	// the constraint.
	Occurrence ValueIdentity
	// Declaration names the authored declaration for diagnostics and audits.
	Declaration string
}

EffectiveConstraintSource identifies the occurrence and named declaration that authored an effective enum, default, or required constraint.

type EffectiveConstraints

type EffectiveConstraints struct {
	// contains filtered or unexported fields
}

EffectiveConstraints is an immutable snapshot of the constraints that apply to one finalized attribute occurrence and its named-type ancestry.

func EffectiveConstraintsFor

func EffectiveConstraintsFor(attribute *AttributeExpr) (EffectiveConstraints, error)

EffectiveConstraintsFor builds the immutable effective constraints for an attribute through the same finalized occurrence lifecycle used by values.

func (EffectiveConstraints) Default

func (c EffectiveConstraints) Default() (any, bool)

Default returns the effective default and whether one was authored. Built-in values are detached; opaque custom values remain borrowed.

func (EffectiveConstraints) DefaultSource

DefaultSource returns the declaration provenance of the effective default.

func (EffectiveConstraints) EnumCandidates

func (c EffectiveConstraints) EnumCandidates() (values []any, present bool)

EnumCandidates returns the detached finite candidates from the first effective enum predicate that satisfy the complete contract, preserving their authored order. Present distinguishes no enum predicate from a present empty domain. Validation retains every unfiltered enum clause. Built-in values are detached while opaque custom values remain borrowed.

func (EffectiveConstraints) EnumSource

EnumSource returns the declaration provenance of the effective enum.

func (EffectiveConstraints) LowerBound

LowerBound returns the effective lowered numeric minimum.

func (EffectiveConstraints) Required

func (c EffectiveConstraints) Required() []EffectiveRequired

Required returns detached required-field identities in deterministic current-to-base declaration order.

func (EffectiveConstraints) UpperBound

UpperBound returns the effective lowered numeric maximum.

func (EffectiveConstraints) Validation

Validation returns the complete effective validation snapshot.

type EffectiveNumericBound

type EffectiveNumericBound struct {
	// Value is the lowered endpoint value.
	Value float64
	// Exclusive reports whether values equal to the endpoint are excluded.
	Exclusive bool
	// Present reports whether an endpoint was authored.
	Present bool
	// Provenance identifies the declaration that supplied the tight endpoint.
	Provenance EffectiveConstraintSource
}

EffectiveNumericBound is one lowered numeric endpoint and its authored declaration provenance. Present distinguishes an absent endpoint from zero.

type EffectiveRequired

type EffectiveRequired struct {
	// Name is the finalized design field name.
	Name string
	// WireName is the finalized serialized field name.
	WireName string
	// Member identifies the finalized object member.
	Member ValueIdentity
	// Provenance identifies the declaration that made the member required.
	Provenance EffectiveConstraintSource
}

EffectiveRequired identifies one required field after resolving all authored names against the finalized object occurrence.

type EffectiveValidation

type EffectiveValidation struct {
	// contains filtered or unexported fields
}

EffectiveValidation is the complete immutable validation snapshot for one finalized occurrence.

func (EffectiveValidation) Clauses

Clauses returns detached pattern and format predicates in derived-to-base order. Exact kind-and-value duplicates retain the first, most-derived declaration provenance.

func (EffectiveValidation) Lowered

func (v EffectiveValidation) Lowered() *ValidationExpr

Lowered returns a detached ValidationExpr that preserves every predicate. Authored Values, Pattern, and Format are cleared. Selected enum membership is stored in EnumClauses, and each string predicate kind is stored in derived-to-base order in PatternClauses or FormatClauses. This distinguishes a materialized inherited enum from a newly authored enum. Interleaving between string predicate kinds and declaration provenance remain available only through Clauses. Re-querying a lowered physical attribute derives new physical provenance. Built-in enum values are detached while opaque custom values remain borrowed.

type EffectiveValidationClause

type EffectiveValidationClause struct {
	// Kind identifies whether Value is a pattern or format predicate.
	Kind EffectiveValidationClauseKind
	// Value is the authored pattern or format name.
	Value string
	// Provenance identifies the declaration that authored the predicate.
	Provenance EffectiveConstraintSource
}

EffectiveValidationClause is one conjoined string predicate and its declaration provenance.

type EffectiveValidationClauseKind

type EffectiveValidationClauseKind uint8

EffectiveValidationClauseKind identifies a conjoined string predicate.

const (
	// EffectivePatternClause identifies a regular-expression pattern predicate.
	EffectivePatternClause EffectiveValidationClauseKind = iota + 1
	// EffectiveFormatClause identifies a named string-format predicate.
	EffectiveFormatClause
)

type ErrorExpr

type ErrorExpr struct {
	// AttributeExpr is the underlying attribute.
	*AttributeExpr
	// Name is the unique name of the error.
	Name string
	// Remedy is the optional structured remediation guidance for the error.
	Remedy *ErrorRemedyExpr
}

ErrorExpr defines an error response. It consists of a named attribute.

func (*ErrorExpr) Finalize

func (e *ErrorExpr) Finalize()

Finalize makes sure the error type is a user type since it has to generate a Go error. Note: this may produce a user type with an attribute that is not an object!

func (*ErrorExpr) Validate

func (e *ErrorExpr) Validate() error

Validate checks the error type and custom error-name metadata.

type ErrorRemedyExpr

type ErrorRemedyExpr struct {
	// Code is the stable remediation code consumers may use to classify the
	// failure.
	Code string
	// SafeMessage is the safe, user-facing message to surface without leaking
	// internal details.
	SafeMessage string
	// RetryHint is concise guidance on how to correct the request or retry the
	// operation.
	RetryHint string
}

ErrorRemedyExpr describes machine-consumable remediation guidance for an API error.

func (*ErrorRemedyExpr) EvalName

func (*ErrorRemedyExpr) EvalName() string

EvalName returns the generic expression name used in validation errors.

func (*ErrorRemedyExpr) Validate

func (r *ErrorRemedyExpr) Validate() *eval.ValidationErrors

Validate checks that a remedy, when declared, contains at least one field.

type ExampleEntry

type ExampleEntry struct {
	// contains filtered or unexported fields
}

ExampleEntry describes one captured source in the selected authored group. Its value remains opaque; callers resolve Source against their retained effective occurrence rather than inferring an owner from authored provenance.

func (ExampleEntry) Description

func (e ExampleEntry) Description() string

Description returns the authored long description.

func (ExampleEntry) Meta

func (e ExampleEntry) Meta() MetaExpr

Meta returns detached design-time metadata for this entry.

func (ExampleEntry) Source

func (e ExampleEntry) Source() ValueSource

Source returns the opaque captured value source for this group entry.

func (ExampleEntry) Summary

func (e ExampleEntry) Summary() string

Summary returns the authored short summary.

type ExampleExpr

type ExampleExpr struct {
	// Summary is the example short summary.
	Summary string
	// Description is an optional long description.
	Description string
	// Meta holds design-time metadata attached to the example.
	Meta MetaExpr
	// Value is the example value.
	Value any
	// ExplicitNull distinguishes an authored null example from a missing
	// example value.
	ExplicitNull bool
	// contains filtered or unexported fields
}

ExampleExpr represents an example.

func (*ExampleExpr) AddMeta added in v1.0.9

func (e *ExampleExpr) AddMeta(name string, value ...string)

AddMeta appends metadata values to example expression.

func (*ExampleExpr) DeleteMeta added in v1.0.9

func (e *ExampleExpr) DeleteMeta(name string)

DeleteMeta removes metadata entry from example expression.

func (*ExampleExpr) EvalName

func (a *ExampleExpr) EvalName() string

EvalName returns the name used by the DSL evaluation.

type ExampleGenerator

type ExampleGenerator struct {
	Randomizer
	// contains filtered or unexported fields
}

ExampleGenerator memoizes examples by type identity while drawing values from Randomizer. Transport wrappers have a separate identity namespace.

func NewRandom

func NewRandom(seed string) *ExampleGenerator

NewRandom returns a random value generator seeded from the given string value, using the faker library to generate random but realistic values.

func (*ExampleGenerator) HaveSeen

func (r *ExampleGenerator) HaveSeen(typeID string, val *any)

HaveSeen stores the value for an authored type ID, for reuse later.

func (*ExampleGenerator) PreviouslySeen

func (r *ExampleGenerator) PreviouslySeen(typeID string) (*any, bool)

PreviouslySeen returns the previously seen value for an authored type ID.

type ExamplePolicy

type ExamplePolicy struct {
	// Reachable indicates that the target consumes this occurrence.
	Reachable bool
	// SuppressGenerated disables synthesis when no authored source exists.
	SuppressGenerated bool
}

ExamplePolicy applies reachability before source use. SuppressGenerated suppresses synthesis only; it preserves the authored-example exception.

type ExampleSelection

type ExampleSelection struct {
	// contains filtered or unexported fields
}

ExampleSelection preserves the source and occurrence chosen before resolution. Only an absent selection is eligible for synthesis.

func (ExampleSelection) Entries

func (s ExampleSelection) Entries() []ExampleEntry

Entries returns the selected authored group in declaration order. The result is empty for excluded, suppressed and absent selections. Editing the returned slice or metadata cannot alter the captured selection.

func (ExampleSelection) Source

func (s ExampleSelection) Source() (ValueSource, bool)

Source returns the supplied source only for an authored selection.

func (ExampleSelection) State

func (s ExampleSelection) State() ExampleState

State returns the result of source selection, without interpreting source data.

type ExampleState

type ExampleState uint8

ExampleState describes source selection without resolving or generating data.

const (
	// ExampleExcluded is unreachable and cannot use authored or synthesized data.
	ExampleExcluded ExampleState = iota + 1
	// ExampleSuppressed has no authored source and disables synthesis.
	ExampleSuppressed
	// ExampleAbsent has no authored source and may attempt synthesis.
	ExampleAbsent
	// ExampleSelected identifies a supplied source, including invalid data or null.
	ExampleSelected
)

type FakerRandomizer

type FakerRandomizer struct {
	Seed string
	// contains filtered or unexported fields
}

FakerRandomizer implements the Random interface, using the Faker library.

func (*FakerRandomizer) ArrayLength

func (r *FakerRandomizer) ArrayLength() int

func (*FakerRandomizer) Bool

func (r *FakerRandomizer) Bool() bool

func (*FakerRandomizer) Characters

func (r *FakerRandomizer) Characters(n int) string

func (*FakerRandomizer) Email

func (r *FakerRandomizer) Email() string

func (*FakerRandomizer) Float32

func (r *FakerRandomizer) Float32() float32

func (*FakerRandomizer) Float64

func (r *FakerRandomizer) Float64() float64

func (*FakerRandomizer) Hostname

func (r *FakerRandomizer) Hostname() string

func (*FakerRandomizer) IPv4Address

func (r *FakerRandomizer) IPv4Address() net.IP

func (*FakerRandomizer) IPv6Address

func (r *FakerRandomizer) IPv6Address() net.IP

func (*FakerRandomizer) Int

func (r *FakerRandomizer) Int() int

func (*FakerRandomizer) Int32

func (r *FakerRandomizer) Int32() int32

func (*FakerRandomizer) Int64

func (r *FakerRandomizer) Int64() int64

func (*FakerRandomizer) Name

func (r *FakerRandomizer) Name() string

func (*FakerRandomizer) String

func (r *FakerRandomizer) String() string

func (*FakerRandomizer) UInt

func (r *FakerRandomizer) UInt() uint

func (*FakerRandomizer) UInt32

func (r *FakerRandomizer) UInt32() uint32

func (*FakerRandomizer) UInt64

func (r *FakerRandomizer) UInt64() uint64

func (*FakerRandomizer) URL

func (r *FakerRandomizer) URL() string

func (*FakerRandomizer) UUID

func (r *FakerRandomizer) UUID() string

type FlowExpr

type FlowExpr struct {
	// Kind is the kind of flow.
	Kind FlowKind
	// AuthorizationURL to be used for implicit or authorizationCode
	// flows.
	AuthorizationURL string
	// TokenURL to be used for password, clientCredentials or
	// authorizationCode flows.
	TokenURL string
	// RefreshURL to be used for obtaining refresh token.
	RefreshURL string
	// DeviceAuthorizationURL starts a device authorization flow.
	DeviceAuthorizationURL string
}

FlowExpr describes a specific OAuth2 flow.

func (*FlowExpr) EvalName

func (f *FlowExpr) EvalName() string

EvalName returns the name of the expression used in error messages.

func (*FlowExpr) Type

func (f *FlowExpr) Type() string

Type returns the grant type of the OAuth2 grant.

func (*FlowExpr) Validate

func (f *FlowExpr) Validate() *eval.ValidationErrors

Validate ensures that TokenURL and AuthorizationURL are valid URLs.

type FlowKind

type FlowKind int

FlowKind is a type of OAuth2 flow.

const (
	// AuthorizationCodeFlowKind identifies a OAuth2 authorization code
	// flow.
	AuthorizationCodeFlowKind FlowKind = iota + 1
	// ImplicitFlowKind identifiers a OAuth2 implicit flow.
	ImplicitFlowKind
	// PasswordFlowKind identifies a Resource Owner Password flow.
	PasswordFlowKind
	// ClientCredentialsFlowKind identifies a OAuth Client Credentials flow.
	ClientCredentialsFlowKind
	// DeviceAuthorizationFlowKind identifies an OAuth 2 device authorization flow.
	DeviceAuthorizationFlowKind
)

type GRPCEndpointExpr

type GRPCEndpointExpr struct {
	eval.DSLFunc
	// MethodExpr is the underlying method expression.
	MethodExpr *MethodExpr
	// Service is the parent service.
	Service *GRPCServiceExpr
	// Request is the message passed to the gRPC method.
	Request *AttributeExpr
	// StreamingRequest is the message passed to the gRPC method through a
	// stream.
	StreamingRequest *AttributeExpr
	// Responses is the success gRPC response from the method.
	Response *GRPCResponseExpr
	// GRPCErrors is the list of all the possible error gRPC responses.
	GRPCErrors []*GRPCErrorExpr
	// Metadata is the metadata to be sent in a gRPC request.
	Metadata *MappedAttributeExpr
	// Requirements is the list of security requirements for the gRPC endpoint.
	Requirements []*SecurityExpr
	// Meta is a set of key/value pairs with semantic that is
	// specific to each generator, see dsl.Meta.
	Meta MetaExpr
}

GRPCEndpointExpr describes a gRPC endpoint. It embeds a MethodExpr and adds gRPC specific properties.

func (*GRPCEndpointExpr) Description

func (e *GRPCEndpointExpr) Description() string

Description of gRPC endpoint

func (*GRPCEndpointExpr) EvalName

func (e *GRPCEndpointExpr) EvalName() string

EvalName returns the generic expression name used in error messages.

func (*GRPCEndpointExpr) Finalize

func (e *GRPCEndpointExpr) Finalize()

Finalize ensures the request and response attributes are initialized.

func (*GRPCEndpointExpr) Name

func (e *GRPCEndpointExpr) Name() string

Name of gRPC endpoint

func (*GRPCEndpointExpr) Prepare

func (e *GRPCEndpointExpr) Prepare()

Prepare initializes the Request and Response if nil.

func (*GRPCEndpointExpr) Validate

func (e *GRPCEndpointExpr) Validate() error

Validate validates the endpoint expression by checking if the request and responses contains the "rpc:tag" in the meta. It also makes sure that there is only one response per status code.

type GRPCErrorExpr

type GRPCErrorExpr struct {
	// ErrorExpr is the underlying Loom design error expression.
	*ErrorExpr
	// Name of error to match it up with the appropriate ErrorExpr.
	Name string
	// Response is the corresponding gRPC response.
	Response *GRPCResponseExpr
}

GRPCErrorExpr defines a gRPC error response including its name, status, and result type.

func (*GRPCErrorExpr) Dup

func (e *GRPCErrorExpr) Dup() *GRPCErrorExpr

Dup creates a copy of the error expression.

func (*GRPCErrorExpr) EvalName

func (e *GRPCErrorExpr) EvalName() string

EvalName returns the generic definition name used in error messages.

func (*GRPCErrorExpr) Finalize

func (e *GRPCErrorExpr) Finalize(a *GRPCEndpointExpr)

Finalize looks up the corresponding method error expression.

func (*GRPCErrorExpr) Validate

func (e *GRPCErrorExpr) Validate() *eval.ValidationErrors

Validate makes sure there is a error expression that matches the gRPC error expression.

type GRPCExpr

type GRPCExpr struct {
	// Services contains the gRPC services created by the DSL.
	Services []*GRPCServiceExpr
	// Errors lists the error gRPC error responses defined globally.
	Errors []*GRPCErrorExpr
}

GRPCExpr contains the API level gRPC specific expressions.

func (*GRPCExpr) EvalName

func (*GRPCExpr) EvalName() string

EvalName returns the name printed in case of evaluation error.

func (*GRPCExpr) Prepare

func (g *GRPCExpr) Prepare()

Prepare initializes the error responses.

func (*GRPCExpr) Service

func (g *GRPCExpr) Service(name string) *GRPCServiceExpr

Service returns the service with the given name if any.

func (*GRPCExpr) ServiceFor

func (g *GRPCExpr) ServiceFor(s *ServiceExpr) *GRPCServiceExpr

ServiceFor creates a new or returns the existing service definition for the given service.

type GRPCResponseExpr

type GRPCResponseExpr struct {
	// gRPC status code
	StatusCode int
	// Response description
	Description string
	// Response Message if any
	Message *AttributeExpr
	// Parent expression, one of EndpointExpr, ServiceExpr or
	// RootExpr.
	Parent eval.Expression
	// Headers is the header metadata to be sent in the gRPC response.
	Headers *MappedAttributeExpr
	// Trailers is the trailer metadata to be sent in the gRPC response.
	Trailers *MappedAttributeExpr
	// Meta is a list of key/value pairs.
	Meta MetaExpr
}

GRPCResponseExpr defines a gRPC response including its status code, result type, and metadata.

func (*GRPCResponseExpr) Dup

Dup creates a copy of the response expression.

func (*GRPCResponseExpr) EvalName

func (r *GRPCResponseExpr) EvalName() string

EvalName returns the generic definition name used in error messages.

func (*GRPCResponseExpr) Finalize

func (r *GRPCResponseExpr) Finalize(a *GRPCEndpointExpr, svcAtt *AttributeExpr)

Finalize ensures that the response message type is set. If Message DSL is used to set the response message then the message type is set by mapping the attributes to the method Result expression. If no response message set explicitly, the message is set from the method Result expression.

func (*GRPCResponseExpr) Prepare

func (r *GRPCResponseExpr) Prepare()

Prepare makes sure the response message and metadata are initialized.

func (*GRPCResponseExpr) Validate

Validate checks that the response definition is consistent: its status is set and the result type definition if any is valid.

type GRPCServiceExpr

type GRPCServiceExpr struct {
	eval.DSLFunc
	// ServiceExpr is the service expression that backs this service.
	ServiceExpr *ServiceExpr
	// Name of parent service if any
	ParentName string
	// ProtoPkg is the name of the generated protobuf package.
	ProtoPkg string
	// GRPCEndpoints is the list of service endpoints.
	GRPCEndpoints []*GRPCEndpointExpr
	// GRPCErrors lists gRPC errors that apply to all endpoints.
	GRPCErrors []*GRPCErrorExpr
	// Meta is a set of key/value pairs with semantic that is
	// specific to each generator.
	Meta MetaExpr
}

GRPCServiceExpr describes a gRPC service.

func (*GRPCServiceExpr) Description

func (svc *GRPCServiceExpr) Description() string

Description of service (service)

func (*GRPCServiceExpr) Endpoint

func (svc *GRPCServiceExpr) Endpoint(name string) *GRPCEndpointExpr

Endpoint returns the service endpoint with the given name or nil if there isn't one.

func (*GRPCServiceExpr) EndpointFor

func (svc *GRPCServiceExpr) EndpointFor(name string, m *MethodExpr) *GRPCEndpointExpr

EndpointFor builds the endpoint for the given method.

func (*GRPCServiceExpr) Error

func (svc *GRPCServiceExpr) Error(name string) *ErrorExpr

Error returns the error with the given name.

func (*GRPCServiceExpr) EvalName

func (svc *GRPCServiceExpr) EvalName() string

EvalName returns the generic definition name used in error messages.

func (*GRPCServiceExpr) GRPCError

func (svc *GRPCServiceExpr) GRPCError(name string) *GRPCErrorExpr

GRPCError returns the service gRPC error with given name if any.

func (*GRPCServiceExpr) Name

func (svc *GRPCServiceExpr) Name() string

Name of service (service)

func (*GRPCServiceExpr) Prepare

func (svc *GRPCServiceExpr) Prepare()

Prepare initializes the error responses.

func (*GRPCServiceExpr) Validate

func (svc *GRPCServiceExpr) Validate() error

Validate makes sure the service is valid.

type HTTPCORSExpr added in v1.3.0

type HTTPCORSExpr struct {
	Origins []*HTTPCORSOriginExpr
	Runtime bool
}

HTTPCORSExpr describes the CORS policy for an API or HTTP service.

func (*HTTPCORSExpr) Dup added in v1.3.0

func (c *HTTPCORSExpr) Dup() *HTTPCORSExpr

Dup returns a deep copy of c.

func (*HTTPCORSExpr) EvalName added in v1.3.0

func (*HTTPCORSExpr) EvalName() string

EvalName returns the expression name used in validation errors.

func (*HTTPCORSExpr) Validate added in v1.3.0

func (c *HTTPCORSExpr) Validate() *eval.ValidationErrors

Validate validates the CORS policy.

type HTTPCORSOriginExpr added in v1.3.0

type HTTPCORSOriginExpr struct {
	Pattern     string
	Regex       bool
	Methods     []string
	Headers     []string
	Expose      []string
	MaxAge      int
	Credentials bool
}

HTTPCORSOriginExpr describes one allowed CORS origin and its response policy. Pattern is either an exact origin, "*", or a regular expression.

func (*HTTPCORSOriginExpr) EvalName added in v1.3.0

func (o *HTTPCORSOriginExpr) EvalName() string

EvalName returns the expression name used in validation errors.

type HTTPEndpointExpr

type HTTPEndpointExpr struct {
	eval.DSLFunc
	// MethodExpr is the underlying method expression.
	MethodExpr *MethodExpr
	// Service is the parent service.
	Service *HTTPServiceExpr
	// Endpoint routes
	Routes []*RouteExpr
	// MapQueryParams - when not nil - indicates that the HTTP
	// request query string parameters are used to build a map.
	//    - If the value is the empty string then the map is stored
	//      in the method payload (which must be of type Map)
	//    - If the value is a non-empty string then the map is
	//      stored in the payload attribute with the corresponding
	//      name (which must of be of type Map)
	MapQueryParams *string
	// Params defines the HTTP request path and query parameters.
	Params *MappedAttributeExpr
	// Headers defines the HTTP request headers.
	Headers *MappedAttributeExpr
	// Cookies defines the HTTP request cookies.
	Cookies *MappedAttributeExpr
	// Body describes the HTTP request body.
	Body *AttributeExpr
	// OpenAPIRequestBody describes a documentation-only request body.
	OpenAPIRequestBody *AttributeExpr
	// OpenAPIRequestBodyContentTypes are the documented request media types.
	OpenAPIRequestBodyContentTypes []string
	// OpenAPIRequestBodyRequired records whether the documented body is required.
	OpenAPIRequestBodyRequired bool
	// StreamingBody describes the body transferred through the websocket
	// stream.
	StreamingBody *AttributeExpr
	// PayloadIDAttribute is the name of the JSON-RPC request ID
	// payload attribute.
	PayloadIDAttribute string
	// ResultIDAttribute is the name of the JSON-RPC result ID
	// result attribute.
	ResultIDAttribute string
	// SkipRequestBodyEncodeDecode indicates that the service method accepts
	// a reader and that the client provides a reader to stream the request
	// body.
	SkipRequestBodyEncodeDecode bool
	// SkipResponseBodyEncodeDecode indicates that the service method
	// returns a reader and that the client accepts a reader to stream the
	// response body.
	SkipResponseBodyEncodeDecode bool
	// FileResponse indicates that the endpoint result includes seekable
	// content served with net/http ServeContent semantics.
	FileResponse bool
	// Responses is the list of all the possible success HTTP
	// responses.
	Responses []*HTTPResponseExpr
	// HTTPErrors is the list of all the possible error HTTP
	// responses.
	HTTPErrors []*HTTPErrorExpr
	// Requirements contains the security requirements for the HTTP endpoint.
	Requirements []*SecurityExpr
	// MultipartRequest indicates that the request content type for
	// the endpoint is a multipart type.
	MultipartRequest bool
	// FormRequest indicates that the request content type for
	// the endpoint is application/x-www-form-urlencoded.
	FormRequest bool
	// OptionalRequestBody indicates that the endpoint accepts an empty
	// request body in addition to a typed JSON request body.
	OptionalRequestBody bool
	// Redirect defines a redirect for the endpoint.
	Redirect *HTTPRedirectExpr
	// SSE defines the Server-Sent Events configuration for this endpoint if it's
	// a streaming endpoint. If nil, the endpoint uses WebSockets by default or
	// inherits the service-level SSE configuration if defined.
	SSE *HTTPSSEExpr
	// Meta is a set of key/value pairs with semantic that is
	// specific to each generator, see dsl.Meta.
	Meta MetaExpr
	// contains filtered or unexported fields
}

HTTPEndpointExpr describes a HTTP endpoint. It embeds a MethodExpr and adds HTTP specific properties.

It defines both an HTTP endpoint and the shape of HTTP requests and responses made to that endpoint. The shape of requests is defined via "parameters", there are path parameters (i.e. portions of the URL that define parameter values), query string parameters and a payload parameter (request body).

func (*HTTPEndpointExpr) AddMeta

func (e *HTTPEndpointExpr) AddMeta(name string, value ...string)

AddMeta appends metadata values to the HTTP endpoint expression.

func (*HTTPEndpointExpr) DeleteMeta

func (e *HTTPEndpointExpr) DeleteMeta(name string)

DeleteMeta removes a metadata entry from the HTTP endpoint expression.

func (*HTTPEndpointExpr) Description

func (e *HTTPEndpointExpr) Description() string

Description of HTTP endpoint

func (*HTTPEndpointExpr) EvalName

func (e *HTTPEndpointExpr) EvalName() string

EvalName returns the generic expression name used in error messages.

func (*HTTPEndpointExpr) Finalize

func (e *HTTPEndpointExpr) Finalize()

Finalize is run post DSL execution. It merges response definitions, creates implicit endpoint parameters and initializes querystring parameters. It also flattens the error responses and makes sure the error types are all user types so that the response encoding code can properly use the type to infer the response that it needs to build.

func (*HTTPEndpointExpr) HasAbsoluteRoutes

func (e *HTTPEndpointExpr) HasAbsoluteRoutes() bool

HasAbsoluteRoutes returns true if all the endpoint routes are absolute.

func (*HTTPEndpointExpr) IsJSONRPC

func (e *HTTPEndpointExpr) IsJSONRPC() bool

IsJSONRPC returns true if the endpoint is a JSON-RPC endpoint.

func (*HTTPEndpointExpr) Name

func (e *HTTPEndpointExpr) Name() string

Name of HTTP endpoint

func (*HTTPEndpointExpr) PathParams

func (e *HTTPEndpointExpr) PathParams() *MappedAttributeExpr

PathParams computes a mapped attribute containing the subset of e.Params that describe path parameters. A route wildcard names the transport element of a param: the route "/{k}" matches Param("key:k"), the path parameter of the key attribute.

func (*HTTPEndpointExpr) Prepare

func (e *HTTPEndpointExpr) Prepare()

Prepare computes the request path and query string parameters as well as the headers and body taking into account the inherited values from the service.

func (*HTTPEndpointExpr) QueryParams

func (e *HTTPEndpointExpr) QueryParams() *MappedAttributeExpr

QueryParams computes a mapped attribute containing the subset of e.Params that describe query parameters: the params whose transport element no route wildcard names.

func (*HTTPEndpointExpr) Validate

func (e *HTTPEndpointExpr) Validate() error

Validate validates the endpoint expression.

type HTTPErrorExpr

type HTTPErrorExpr struct {
	// ErrorExpr is the underlying Loom design error expression.
	*ErrorExpr
	// Name of error, we need a separate copy of the name to match it
	// up with the appropriate ErrorExpr.
	Name string
	// Response is the corresponding HTTP response.
	Response *HTTPResponseExpr
}

HTTPErrorExpr defines a HTTP error response including its name, status, headers and result type.

func (*HTTPErrorExpr) Dup

func (e *HTTPErrorExpr) Dup() *HTTPErrorExpr

Dup creates a copy of the error expression.

func (*HTTPErrorExpr) EvalName

func (e *HTTPErrorExpr) EvalName() string

EvalName returns the generic definition name used in error messages.

func (*HTTPErrorExpr) Finalize

func (e *HTTPErrorExpr) Finalize(a *HTTPEndpointExpr)

Finalize looks up the corresponding method error expression.

func (*HTTPErrorExpr) Validate

func (e *HTTPErrorExpr) Validate() *eval.ValidationErrors

Validate makes sure there is a error expression that matches the HTTP error expression.

type HTTPExpr

type HTTPExpr struct {
	// Path is the common request path prefix to all the service
	// HTTP endpoints.
	Path string
	// Params defines the HTTP request path and query parameters
	// common to all the API endpoints.
	Params *MappedAttributeExpr
	// Headers defines the HTTP request headers common to to all
	// the API endpoints.
	Headers *MappedAttributeExpr
	// Cookies defines the HTTP request cookies common to to all
	// the API endpoints.
	Cookies *MappedAttributeExpr
	// Consumes lists the mime types supported by the API
	// controllers.
	Consumes []string
	// Produces lists the mime types generated by the API
	// controllers.
	Produces []string
	// Services contains the services created by the DSL.
	Services []*HTTPServiceExpr
	// Errors lists the error HTTP responses.
	Errors []*HTTPErrorExpr
	// SSE contains the Server-Sent Events configuration for all
	// streaming endpoints in the API.
	SSE *HTTPSSEExpr
	// CORS contains the API-level Cross-Origin Resource Sharing policy.
	CORS *HTTPCORSExpr
}

HTTPExpr contains the API level HTTP specific expressions.

func (*HTTPExpr) EvalName

func (*HTTPExpr) EvalName() string

EvalName returns the name printed in case of evaluation error.

func (*HTTPExpr) Finalize

func (h *HTTPExpr) Finalize()

Finalize initializes Consumes and Produces with defaults if not set.

func (*HTTPExpr) Service

func (h *HTTPExpr) Service(name string) *HTTPServiceExpr

Service returns the service with the given name if any.

func (*HTTPExpr) ServiceFor

func (h *HTTPExpr) ServiceFor(s *ServiceExpr, root *HTTPExpr) *HTTPServiceExpr

ServiceFor creates a new or returns the existing service definition for the given service.

func (*HTTPExpr) Validate added in v1.3.0

func (h *HTTPExpr) Validate() error

Validate validates the API-level HTTP expression.

type HTTPFileServerExpr

type HTTPFileServerExpr struct {
	// Service is the parent service.
	Service *HTTPServiceExpr
	// Description for docs
	Description string
	// Docs points to the service external documentation
	Docs *DocsExpr
	// FilePath is the file path to the static asset(s)
	FilePath string
	// RequestPaths is the list of HTTP paths that serve the assets.
	RequestPaths []string
	// Redirect defines a redirect for the endpoint.
	Redirect *HTTPRedirectExpr
	// Meta is a list of key/value pairs
	Meta MetaExpr
}

HTTPFileServerExpr defines an endpoint that serves static assets through HTTP.

func (*HTTPFileServerExpr) AddMeta

func (f *HTTPFileServerExpr) AddMeta(name string, value ...string)

AddMeta appends metadata values to the HTTP file server expression.

func (*HTTPFileServerExpr) DeleteMeta

func (f *HTTPFileServerExpr) DeleteMeta(name string)

DeleteMeta removes a metadata entry from the HTTP file server expression.

func (*HTTPFileServerExpr) EvalName

func (f *HTTPFileServerExpr) EvalName() string

EvalName returns the generic definition name used in error messages.

func (*HTTPFileServerExpr) Finalize

func (f *HTTPFileServerExpr) Finalize()

Finalize normalizes the request path.

func (*HTTPFileServerExpr) IsDir

func (f *HTTPFileServerExpr) IsDir() bool

IsDir reports whether the request path uses a wildcard and therefore needs directory-style route mounting. The configured target may resolve to either a directory or a single file at runtime.

func (*HTTPFileServerExpr) Validate

func (f *HTTPFileServerExpr) Validate() error

Validate makes sure every full request path is one the muxer can register: a "{*name}" catch-all must terminate it, no wildcard may repeat, and no bare "*" may appear outside the "{*name}" syntax.

type HTTPRedirectExpr

type HTTPRedirectExpr struct {
	// URL is the URL that is being redirected to.
	URL string
	// StatusCode is the HTTP status code.
	StatusCode int
	// Parent expression, one of HTTPEndpointExpr or HTTPFileServerExpr.
	Parent eval.Expression
}

HTTPRedirectExpr defines an endpoint that replies to the request with a redirect.

func (*HTTPRedirectExpr) EvalName

func (r *HTTPRedirectExpr) EvalName() string

EvalName returns the generic definition name used in error messages.

type HTTPResponseCookieExpr

type HTTPResponseCookieExpr struct {
	// MappedAttributeExpr contains the mapped result attribute for the cookie
	// value.
	*MappedAttributeExpr
	// Path defines the cookie Path attribute.
	Path string
	// Domain defines the cookie Domain attribute.
	Domain string
	// MaxAge defines the cookie Max-Age attribute.
	MaxAge string
	// Secure indicates whether the cookie should include the Secure flag.
	Secure bool
	// HTTPOnly indicates whether the cookie should include the HttpOnly flag.
	HTTPOnly bool
	// SameSite defines the cookie SameSite attribute.
	SameSite CookieSameSiteValue
}

HTTPResponseCookieExpr describes a single HTTP response cookie.

func NewHTTPResponseCookieExpr

func NewHTTPResponseCookieExpr() *HTTPResponseCookieExpr

NewHTTPResponseCookieExpr creates an empty HTTP response cookie expression.

func (*HTTPResponseCookieExpr) Attribute

func (c *HTTPResponseCookieExpr) Attribute() *AttributeExpr

Attribute returns the mapped cookie attribute.

func (*HTTPResponseCookieExpr) AttributeName

func (c *HTTPResponseCookieExpr) AttributeName() string

AttributeName returns the mapped result attribute name.

func (*HTTPResponseCookieExpr) Dup

Dup creates a copy of the response cookie expression.

func (*HTTPResponseCookieExpr) HTTPName

func (c *HTTPResponseCookieExpr) HTTPName() string

HTTPName returns the cookie name written on the wire.

func (*HTTPResponseCookieExpr) IsEmpty

func (c *HTTPResponseCookieExpr) IsEmpty() bool

IsEmpty returns true if the cookie contains no mapped attribute.

type HTTPResponseExpr

type HTTPResponseExpr struct {
	// HTTP status
	StatusCode int
	// Response description
	Description string
	// Headers describe the HTTP response headers.
	Headers *MappedAttributeExpr
	// Cookies describe the HTTP response cookies.
	Cookies []*HTTPResponseCookieExpr
	// Response body if any
	Body *AttributeExpr
	// OpenAPIBody describes a documentation-only response body used by
	// OpenAPI generation when runtime response encoding/decoding is skipped.
	OpenAPIBody *AttributeExpr
	// Response Content-Type header value
	ContentType string
	// Tag the value a field of the result must have for this
	// response to be used.
	Tag [2]string
	// Parent expression, one of EndpointExpr, ServiceExpr or
	// RootExpr.
	Parent eval.Expression
	// ErrorName identifies the error whose response DSL is executing. It is
	// empty for successful responses.
	ErrorName string
	// Meta is a list of key/value pairs
	Meta MetaExpr
	// Links describes the OpenAPI links emitted for this response.
	Links []*HTTPResponseLinkExpr
	// contains filtered or unexported fields
}

HTTPResponseExpr defines a HTTP response including its status code, headers and result type.

func (*HTTPResponseExpr) AddCookie

func (r *HTTPResponseExpr) AddCookie(cookie *HTTPResponseCookieExpr)

AddCookie appends a response cookie to the response and marks it active for subsequent cookie attribute setters.

func (*HTTPResponseExpr) AddMeta

func (r *HTTPResponseExpr) AddMeta(name string, value ...string)

AddMeta appends metadata values to the HTTP response expression.

func (*HTTPResponseExpr) CurrentCookie

func (r *HTTPResponseExpr) CurrentCookie() *HTTPResponseCookieExpr

CurrentCookie returns the cookie currently configured by the DSL.

func (*HTTPResponseExpr) DeleteMeta

func (r *HTTPResponseExpr) DeleteMeta(name string)

DeleteMeta removes a metadata entry from the HTTP response expression.

func (*HTTPResponseExpr) Dup

Dup creates a copy of the response expression.

func (*HTTPResponseExpr) EvalName

func (r *HTTPResponseExpr) EvalName() string

EvalName returns the generic definition name used in error messages.

func (*HTTPResponseExpr) Finalize

func (r *HTTPResponseExpr) Finalize(a *HTTPEndpointExpr, svcAtt *AttributeExpr)

Finalize sets the response result type from its type if the type is a result type and no result type is already specified.

func (*HTTPResponseExpr) Prepare

func (r *HTTPResponseExpr) Prepare()

Prepare makes sure the response is initialized even if not done explicitly by

func (*HTTPResponseExpr) Validate

Validate checks that the response definition is consistent: its status is set and the result type definition if any is valid.

type HTTPResponseLinkExpr

type HTTPResponseLinkExpr struct {
	// Name is the published OpenAPI link key.
	Name string
	// Description is the optional human-readable link description.
	Description string
	// Operation is the target operation name. It may be either "method" for a
	// method in the current service or "service.method" for an explicit target.
	Operation string
	// OperationRef is the explicit OpenAPI operationRef target.
	OperationRef string
	// Parameters maps target parameter names to OpenAPI runtime expressions.
	Parameters map[string]string
	// RequestBody is the optional OpenAPI runtime expression used to build the
	// target request body.
	RequestBody string
}

HTTPResponseLinkExpr describes an OpenAPI response link.

func (*HTTPResponseLinkExpr) EvalName

func (l *HTTPResponseLinkExpr) EvalName() string

EvalName returns the generic definition name used in error messages.

func (*HTTPResponseLinkExpr) Validate

Validate validates the response link definition.

type HTTPSSEExpr

type HTTPSSEExpr struct {
	// RequestIDField is the name of the attribute in the Payload type
	// that provides the Last-Event-ID request header value.
	// If empty, no Last-Event-ID request header is included in the request.
	RequestIDField string
	// NotificationMethod is the JSON-RPC method used for intermediate SSE
	// notifications. If empty, code generation uses a namespaced default.
	NotificationMethod string
	// DataField is the name of the attribute in the StreamingResult type
	// that provides the data field for a Server-Sent Event.
	// If empty, the entire StreamingResult is used as the data field.
	DataField string
	// IDField is the name of the attribute in the StreamingResult type
	// that provides the id field for a Server-Sent Event.
	// If empty, no id field is included in the event.
	IDField string
	// EventField is the name of the attribute in the StreamingResult type
	// that provides the event field (event type) for a Server-Sent Event.
	// If empty, no event field is included in the event.
	EventField string
	// RetryField is the name of the attribute in the StreamingResult type
	// that provides the retry field for a Server-Sent Event.
	// If empty, no retry field is included in the event.
	RetryField string
	// Projections map SSE event discriminator values to result views.
	Projections []*SSEProjectionExpr
}

HTTPSSEExpr describes a Server-Sent Events configuration for a HTTP endpoint. It defines how a streaming endpoint should use the Server-Sent Events protocol instead of WebSockets.

func (*HTTPSSEExpr) EvalName

func (e *HTTPSSEExpr) EvalName() string

EvalName returns the generic expression name used in error messages.

func (*HTTPSSEExpr) Validate

func (e *HTTPSSEExpr) Validate(method *MethodExpr) error

Validate validates the Server-Sent Events expression against a specific result type.

type HTTPServiceExpr

type HTTPServiceExpr struct {
	eval.DSLFunc
	// Root is the root HTTP expression.
	Root *HTTPExpr
	// ServiceExpr is the service expression that backs this
	// service.
	ServiceExpr *ServiceExpr
	// Common URL prefixes to all service endpoint HTTP requests
	Paths []string
	// Params defines the HTTP request path and query parameters
	// common to all the service endpoints.
	Params *MappedAttributeExpr
	// Headers defines the HTTP request headers common to all the
	// service endpoints.
	Headers *MappedAttributeExpr
	// Cookies defines the HTTP request cookies common to all the
	// service endpoints.
	Cookies *MappedAttributeExpr
	// Name of parent service if any
	ParentName string
	// Endpoint with canonical service path
	CanonicalEndpointName string
	// HTTPEndpoints is the list of service endpoints.
	HTTPEndpoints []*HTTPEndpointExpr
	// HTTPErrors lists HTTP errors that apply to all endpoints.
	HTTPErrors []*HTTPErrorExpr
	// FileServers is the list of static asset serving endpoints
	FileServers []*HTTPFileServerExpr
	// SSE defines the Server-Sent Events configuration for all streaming endpoints
	// in this service. If nil, streaming endpoints use WebSockets by default.
	SSE *HTTPSSEExpr
	// CORS defines the service-level Cross-Origin Resource Sharing policy.
	// If nil, the API-level CORS policy applies.
	CORS *HTTPCORSExpr
	// JSONRPCRoute is the route used for all JSON-RPC endpoints in this service.
	// Only applicable to JSON-RPC services.
	JSONRPCRoute *RouteExpr
	// Meta is a set of key/value pairs with semantic that is
	// specific to each generator.
	Meta MetaExpr
}

HTTPServiceExpr describes a HTTP service. It defines both a result type and a set of endpoints that can be executed through HTTP requests. HTTPServiceExpr embeds a ServiceExpr and adds HTTP specific properties.

func NewJSONRPCHTTPService

func NewJSONRPCHTTPService(service *ServiceExpr, routePath string) *HTTPServiceExpr

NewJSONRPCHTTPService builds an HTTP service expression for a synthesized JSON-RPC service. The returned service uses a single POST route for all methods and pre-initializes endpoint body and mapped attributes so transport analyzers can consume it directly.

func (*HTTPServiceExpr) AddMeta

func (s *HTTPServiceExpr) AddMeta(name string, value ...string)

AddMeta appends metadata values to the HTTP service expression.

func (*HTTPServiceExpr) CanonicalEndpoint

func (svc *HTTPServiceExpr) CanonicalEndpoint() *HTTPEndpointExpr

CanonicalEndpoint returns the canonical endpoint of the service if any. The canonical endpoint is used to compute hrefs to services.

func (*HTTPServiceExpr) DeleteMeta

func (s *HTTPServiceExpr) DeleteMeta(name string)

DeleteMeta removes a metadata entry from the HTTP service expression.

func (*HTTPServiceExpr) Description

func (svc *HTTPServiceExpr) Description() string

Description of service (service)

func (*HTTPServiceExpr) Endpoint

func (svc *HTTPServiceExpr) Endpoint(name string) *HTTPEndpointExpr

Endpoint returns the service endpoint with the given name or nil if there isn't one.

func (*HTTPServiceExpr) EndpointFor

func (svc *HTTPServiceExpr) EndpointFor(m *MethodExpr) *HTTPEndpointExpr

EndpointFor builds the endpoint for the given method.

func (*HTTPServiceExpr) Error

func (svc *HTTPServiceExpr) Error(name string) *ErrorExpr

Error returns the error with the given name.

func (*HTTPServiceExpr) EvalName

func (svc *HTTPServiceExpr) EvalName() string

EvalName returns the generic definition name used in error messages.

func (*HTTPServiceExpr) Finalize

func (svc *HTTPServiceExpr) Finalize()

Finalize initializes the path if no path is set in design.

func (*HTTPServiceExpr) FullPaths

func (svc *HTTPServiceExpr) FullPaths() []string

FullPaths computes the base paths to the service endpoints concatenating the API and parent service base paths as needed.

func (*HTTPServiceExpr) HTTPError

func (svc *HTTPServiceExpr) HTTPError(name string) *HTTPErrorExpr

HTTPError returns the service HTTP error with given name if any.

func (*HTTPServiceExpr) Name

func (svc *HTTPServiceExpr) Name() string

Name of service (service)

func (*HTTPServiceExpr) Parent

func (svc *HTTPServiceExpr) Parent() *HTTPServiceExpr

Parent returns the parent service if any, nil otherwise.

func (*HTTPServiceExpr) Prepare

func (svc *HTTPServiceExpr) Prepare()

Prepare initializes the error responses.

func (*HTTPServiceExpr) Validate

func (svc *HTTPServiceExpr) Validate() error

Validate makes sure the service is valid.

type HostExpr

type HostExpr struct {
	// Name of host
	Name string
	// Name of server that uses host.
	ServerName string
	// Description of host
	Description string
	// URIs to host if any, may contain parameter elements using
	// the "{param}" syntax.
	URIs []URIExpr
	// Variables defines the URI variables if any.
	Variables *AttributeExpr
	// Meta is a set of key/value pairs.
	Meta MetaExpr
}

HostExpr describes a server host.

func (*HostExpr) AddMeta

func (h *HostExpr) AddMeta(name string, value ...string)

AddMeta appends metadata values to the host expression.

func (*HostExpr) Attribute

func (h *HostExpr) Attribute() *AttributeExpr

Attribute returns the variables attribute.

func (*HostExpr) DeleteMeta

func (h *HostExpr) DeleteMeta(name string)

DeleteMeta removes a metadata entry from the host expression.

func (*HostExpr) EvalName

func (h *HostExpr) EvalName() string

EvalName returns the name returned in error messages.

func (*HostExpr) Finalize

func (h *HostExpr) Finalize()

Finalize makes sure Variables is set.

func (*HostExpr) HasGRPCScheme

func (h *HostExpr) HasGRPCScheme() bool

HasGRPCScheme returns true if at least one of the URIs in the host expression define "grpc" or "grpcs" scheme.

func (*HostExpr) HasHTTPScheme

func (h *HostExpr) HasHTTPScheme() bool

HasHTTPScheme returns true if at least one of the URIs in the host expression define "http" or "https" scheme.

func (*HostExpr) Schemes

func (h *HostExpr) Schemes() []string

Schemes returns the list of transport schemes defined for the host. The possible values for the elements of the returned slice are "http", "https", "grpc" and "grpcs".

func (*HostExpr) URIString

func (h *HostExpr) URIString(u URIExpr) (string, error)

URIString returns a valid URI string by substituting the parameters with their default value if present or the first item in their enum. It returns an error if the given URI expression is not found in the host URIs.

func (*HostExpr) Validate

func (h *HostExpr) Validate() error

Validate validates the host.

type InlineDiscriminator added in v1.0.11

type InlineDiscriminator struct {
	PropertyName string `json:"propertyName,omitempty"`
}

InlineDiscriminator mirrors the JSON Schema/OpenAPI discriminator object.

type InlineSchema

type InlineSchema struct {
	Type        string                   `json:"type,omitempty"`
	Title       string                   `json:"title,omitempty"`
	Description string                   `json:"description,omitempty"`
	Examples    []any                    `json:"examples,omitempty"`
	Required    []string                 `json:"required,omitempty"`
	Properties  map[string]*InlineSchema `json:"properties,omitempty"`
	OneOf       []*InlineSchema          `json:"oneOf,omitempty"`
	AnyOf       []*InlineSchema          `json:"anyOf,omitempty"`
	AllOf       []*InlineSchema          `json:"allOf,omitempty"`
	// Not rejects values accepted by the nested schema, including not:{} for an empty range.
	Not *InlineSchema `json:"not,omitzero"`
	// ContentEncoding names the string representation; validation remains explicit.
	ContentEncoding      string               `json:"contentEncoding,omitempty"`
	Discriminator        *InlineDiscriminator `json:"discriminator,omitempty"`
	Items                *InlineSchema        `json:"items,omitempty"`
	AdditionalProperties any                  `json:"additionalProperties,omitempty"`
	Enum                 []any                `json:"enum,omitempty"`
	Default              any                  `json:"default,omitempty"`
	Minimum              any                  `json:"minimum,omitempty"`
	Maximum              any                  `json:"maximum,omitempty"`
	ExclusiveMinimum     any                  `json:"exclusiveMinimum,omitempty"`
	ExclusiveMaximum     any                  `json:"exclusiveMaximum,omitempty"`
	MinLength            *int                 `json:"minLength,omitempty"`
	MaxLength            *int                 `json:"maxLength,omitempty"`
	Pattern              string               `json:"pattern,omitempty"`
	Format               string               `json:"format,omitempty"`
	MinItems             *int                 `json:"minItems,omitempty"`
	MaxItems             *int                 `json:"maxItems,omitempty"`
}

InlineSchema represents a fully inlined JSON Schema document derived from a Loom attribute. It avoids $ref indirections so machine consumers can consume standalone payload and result contracts directly.

type InterceptorExpr

type InterceptorExpr struct {
	// Name is the name of the interceptor
	Name string
	// Description is the optional description of the interceptor
	Description string
	// ReadPayload lists the payload attribute names read by the interceptor
	ReadPayload *AttributeExpr
	// WritePayload lists the payload attribute names written by the interceptor
	WritePayload *AttributeExpr
	// ReadResult lists the result attribute names read by the interceptor
	ReadResult *AttributeExpr
	// WriteResult lists the result attribute names written by the interceptor
	WriteResult *AttributeExpr
	// ReadStreamingPayload lists the streaming payload attribute names read by the interceptor
	ReadStreamingPayload *AttributeExpr
	// WriteStreamingPayload lists the streaming payload attribute names written by the interceptor
	WriteStreamingPayload *AttributeExpr
	// ReadStreamingResult lists the streaming result attribute names read by the interceptor
	ReadStreamingResult *AttributeExpr
	// WriteStreamingResult lists the streaming result attribute names written by the interceptor
	WriteStreamingResult *AttributeExpr
}

InterceptorExpr describes an interceptor definition in the design. Interceptors are used to inject user code into the request/response processing pipeline. There are four kinds of interceptors, in order of execution:

  • client-side payload: executes after the payload is encoded and before the request is sent to the server
  • server-side request: executes after the request is decoded and before the payload is sent to the service
  • server-side result: executes after the service returns a result and before the response is encoded
  • client-side response: executes after the response is decoded and before the result is sent to the client

func (*InterceptorExpr) EvalName

func (i *InterceptorExpr) EvalName() string

EvalName returns the generic expression name used in error messages.

type JSONRPCExpr

type JSONRPCExpr struct {
	HTTPExpr
}

JSONRPCExpr contains the API level JSON-RPC specific expressions.

func (*JSONRPCExpr) EvalName

func (*JSONRPCExpr) EvalName() string

EvalName returns the name printed in case of evaluation error.

func (*JSONRPCExpr) Prepare

func (j *JSONRPCExpr) Prepare()

Prepare copies shared HTTP API constructs over to the JSON-RPC API.

type Kind

type Kind uint

A Kind defines the conceptual type that a DataType represents.

const (
	// BooleanKind represents a boolean.
	BooleanKind Kind = iota + 1
	// IntKind represents a signed integer.
	IntKind
	// Int32Kind represents a signed 32-bit integer.
	Int32Kind
	// Int64Kind represents a signed 64-bit integer.
	Int64Kind
	// UIntKind represents an unsigned integer.
	UIntKind
	// UInt32Kind represents an unsigned 32-bit integer.
	UInt32Kind
	// UInt64Kind represents an unsigned 64-bit integer.
	UInt64Kind
	// Float32Kind represents a 32-bit floating number.
	Float32Kind
	// Float64Kind represents a 64-bit floating number.
	Float64Kind
	// StringKind represents a string.
	StringKind
	// BytesKind represent a series of bytes (binary data).
	BytesKind
	// ArrayKind represents an array of types.
	ArrayKind
	// ObjectKind represents an object.
	ObjectKind
	// MapKind represents a dictionary.
	MapKind
	// UnionKind represents a union type.
	UnionKind
	// UserTypeKind represents a user defined type.
	UserTypeKind
	// ResultTypeKind represents a user defined result type.
	ResultTypeKind
	// AnyKind represents an unknown type.
	AnyKind
)

type LicenseExpr

type LicenseExpr struct {
	// Name of license used for the API
	Name string `json:"name,omitempty"`
	// URL to the license used for the API
	URL string `json:"url,omitempty"`
}

LicenseExpr contains the license information for the API.

func (*LicenseExpr) EvalName

func (l *LicenseExpr) EvalName() string

EvalName is the qualified name of the expression.

type Map

type Map struct {
	KeyType  *AttributeExpr
	ElemType *AttributeExpr
}

Map is the type used to describe maps of fields.

func AsMap

func AsMap(dt DataType) *Map

AsMap returns the type underlying map if any, nil otherwise.

func (*Map) Example

func (m *Map) Example(r *ExampleGenerator) any

Example returns a random example value.

func (*Map) Hash

func (m *Map) Hash() string

Hash returns a unique hash value for m.

func (*Map) IsCompatible

func (m *Map) IsCompatible(val any) bool

IsCompatible returns true if o describes the (Go) type of val.

func (*Map) Kind

func (*Map) Kind() Kind

Kind implements DataKind.

func (*Map) MakeMap

func (m *Map) MakeMap(raw map[any]any) any

MakeMap examines the key type from a Map and create a map with builtin type if possible. The idea is to avoid generating map[any]any, which cannot be handled by json.Marshal.

func (*Map) Name

func (*Map) Name() string

Name returns the type name.

type MapVal

type MapVal map[any]any

MapVal is the type used to set the default value for maps.

func (MapVal) ToMap

func (m MapVal) ToMap() map[any]any

ToMap converts a MapVal to a map.

type MappedAttributeExpr

type MappedAttributeExpr struct {
	*AttributeExpr
	// contains filtered or unexported fields
}

MappedAttributeExpr is an attribute expression of type object that map the object keys to external names (e.g. HTTP header names).

func DupMappedAtt

func DupMappedAtt(ma *MappedAttributeExpr) *MappedAttributeExpr

DupMappedAtt creates a deep copy of ma.

func NewEmptyMappedAttributeExpr

func NewEmptyMappedAttributeExpr() *MappedAttributeExpr

NewEmptyMappedAttributeExpr creates an empty mapped attribute expression.

func NewMappedAttributeExpr

func NewMappedAttributeExpr(att *AttributeExpr) *MappedAttributeExpr

NewMappedAttributeExpr instantiates a mapped attribute expression for the given attribute. The type of att must be Object.

func (*MappedAttributeExpr) Attribute

func (ma *MappedAttributeExpr) Attribute() *AttributeExpr

Attribute returns the original attribute using "att:elem" format for the keys and for the names of the required attributes.

func (*MappedAttributeExpr) Delete

func (ma *MappedAttributeExpr) Delete(attName string)

Delete removes a child attribute given its name.

func (*MappedAttributeExpr) ElemName

func (ma *MappedAttributeExpr) ElemName(keyName string) string

ElemName returns the transport element name of the given object key. It returns keyName if it's a key of the mapped attribute object type. It panics if there is no mapping and keyName is not a key.

func (*MappedAttributeExpr) FindKey

func (ma *MappedAttributeExpr) FindKey(keyName string) (string, bool)

FindKey finds the given key in the mapped attribute expression. If key is found, it returns the transport element name of the key and true. Otherwise, it returns an empty string and false.

func (*MappedAttributeExpr) IsEmpty

func (ma *MappedAttributeExpr) IsEmpty() bool

IsEmpty returns true if the mapped attribute contains no key.

func (*MappedAttributeExpr) KeyName

func (ma *MappedAttributeExpr) KeyName(elemName string) string

KeyName returns the object key of the given transport element name. It returns elemName if it's a key of the mapped attribute object type. It panics if there is no mapping and elemName is not a key.

func (*MappedAttributeExpr) Map

func (ma *MappedAttributeExpr) Map(elemName, attName string)

Map records the element name of one of the child attributes. Map panics if attName is not the name of a child attribute.

func (*MappedAttributeExpr) Merge

func (ma *MappedAttributeExpr) Merge(other *MappedAttributeExpr)

Merge merges other's attributes into a overriding attributes of a with attributes of other with identical names.

func (*MappedAttributeExpr) Remap

func (ma *MappedAttributeExpr) Remap()

Remap recomputes the name mappings from the inner attribute. Use this if the underlying attribute is modified after the mapped attribute has been initially created. The keys of the mapped object and the names of its required attributes are the attribute names, without the element name suffix: a required attribute listed as "n:m" is listed as "n".

type MappedAttributeWalker

type MappedAttributeWalker func(name, elem string, a *AttributeExpr) error

MappedAttributeWalker is the type of functions given to WalkMappedAttr.

name is the name of the attribute elem the name of the corresponding transport element a is the corresponding attribute expression

type MetaAdder

type MetaAdder interface {
	// AddMeta appends the given values to the metadata entry identified by name.
	AddMeta(name string, value ...string)
}

MetaAdder is implemented by expressions that can receive design-time metadata.

Loom's standard DSL helper `Meta(name, value...)` attaches metadata to the current expression. Most Loom core expressions store metadata directly in a `MetaExpr` field. Third-party DSLs (and plugins) may add new expression types that also want to support `Meta` without Loom needing to know about those concrete types.

An expression that implements MetaAdder opts into Loom's `Meta` DSL by providing an AddMeta implementation that:

  • appends values to the existing entry for the given name, and
  • preserves existing metadata for other names.

Callers should treat metadata keys and values as opaque strings; their interpretation is application-specific.

type MetaDeleter

type MetaDeleter interface {
	// DeleteMeta removes the metadata entry identified by name.
	DeleteMeta(name string)
}

MetaDeleter is implemented by expressions that can remove design-time metadata.

Loom's standard DSL helper `RemoveMeta(name)` removes the metadata entry with the given name from the current expression.

Implementations should be a no-op when no metadata is present.

type MetaExpr

type MetaExpr map[string][]string

MetaExpr is a set of key/value pairs

func (MetaExpr) Dup

func (m MetaExpr) Dup() MetaExpr

Dup creates a new map from the given expression.

func (MetaExpr) Last

func (m MetaExpr) Last(key string) (string, bool)

Last returns the last value for a specific key, if the key exists and has values; otherwise returns an empty string, with the "ok" flag set to false.

func (MetaExpr) Merge

func (m MetaExpr) Merge(src MetaExpr)

Merge merges src meta expression with m. If meta has intersecting set of keys on both m and src, then the values for those keys in src is appended to the values of the keys in m if not already existing.

type MethodAuthorizationExpr added in v1.9.0

type MethodAuthorizationExpr struct {
	// Requirements must all succeed before the operation can execute.
	Requirements []*AuthorizationUseExpr
	// Exemption explains why no additional authorization check is required.
	Exemption string
	// VariantSelection distinguishes a selector (including a root selector) from direct requirements.
	VariantSelection bool
	// Selector is a dot-separated payload path to a string enum or union.
	Selector string
	// Cases classify every declared selector value.
	Cases []*AuthorizationCaseExpr
}

MethodAuthorizationExpr describes either conjunctive requirements, an explicit exemption, or exhaustive cases selected from a payload field.

func (*MethodAuthorizationExpr) EvalName added in v1.9.0

func (*MethodAuthorizationExpr) EvalName() string

EvalName returns the classification's diagnostic identity.

type MethodExpr

type MethodExpr struct {
	// DSLFunc contains the DSL used to initialize the expression.
	eval.DSLFunc
	// Name of method.
	Name string
	// Description of method for consumption by humans.
	Description string
	// Docs points to the method external documentation if any.
	Docs *DocsExpr
	// Payload attribute
	Payload *AttributeExpr
	// Result attribute
	Result *AttributeExpr
	// Errors lists the error responses.
	Errors []*ErrorExpr
	// Requirements contains the security requirements for the
	// method. One requirement is composed of potentially multiple
	// schemes. Incoming requests must validate at least one
	// requirement to be authorized.
	Requirements []*SecurityExpr
	// SessionAuths contains the multi-transport session auth contracts that
	// apply to the method.
	SessionAuths []*SessionAuthExpr
	// ClientInterceptors is the list of client interceptors.
	ClientInterceptors []*InterceptorExpr
	// ServerInterceptors is the list of server interceptors.
	ServerInterceptors []*InterceptorExpr
	// Authorization classifies access independently of credential security.
	Authorization *MethodAuthorizationExpr
	// Service that owns method.
	Service *ServiceExpr
	// Meta is an arbitrary set of key/value pairs, see dsl.Meta
	Meta MetaExpr
	// Stream is the kind of stream (none, payload, result, or both)
	// the method defines.
	Stream StreamKind
	// StreamingPayload is the payload sent across the stream.
	StreamingPayload *AttributeExpr
	// StreamingResult is the result sent across the stream when using SSE.
	// When both Result and StreamingResult are defined with different types,
	// the method supports content negotiation between standard HTTP responses
	// (using Result) and SSE streams (using StreamingResult).
	StreamingResult *AttributeExpr
}

MethodExpr defines a single method.

func (*MethodExpr) AddMeta

func (m *MethodExpr) AddMeta(name string, value ...string)

AddMeta appends metadata values to the method expression.

func (*MethodExpr) DeleteMeta

func (m *MethodExpr) DeleteMeta(name string)

DeleteMeta removes a metadata entry from the method expression.

func (*MethodExpr) EffectiveRequirements added in v1.0.6

func (m *MethodExpr) EffectiveRequirements() []*SecurityExpr

EffectiveRequirements returns the method security requirements after applying no-security overrides, inherited service/API requirements, and derived session-auth transports.

func (*MethodExpr) EffectiveSessionAuths added in v1.0.6

func (m *MethodExpr) EffectiveSessionAuths() []*SessionAuthExpr

EffectiveSessionAuths returns the session auth contracts that apply to the method after honoring no-security overrides and inherited service/API session-auth declarations.

func (*MethodExpr) Error

func (m *MethodExpr) Error(name string) *ErrorExpr

Error returns the error with the given name. It looks up recursively in the endpoint then the service and finally the root expression.

func (*MethodExpr) EvalName

func (m *MethodExpr) EvalName() string

EvalName returns the generic expression name used in error messages.

func (*MethodExpr) Finalize

func (m *MethodExpr) Finalize()

Finalize makes sure the method payload and result types are set. It also projects the result if it is a result type and a view is explicitly set in the design or a result type having at most one view.

func (*MethodExpr) HasMixedResults

func (m *MethodExpr) HasMixedResults() bool

HasMixedResults returns true if the method has both Result and StreamingResult defined with different types, indicating support for content negotiation.

func (*MethodExpr) IsPayloadStreaming

func (m *MethodExpr) IsPayloadStreaming() bool

IsPayloadStreaming determines whether the method streams payload.

func (*MethodExpr) IsResultStreaming

func (m *MethodExpr) IsResultStreaming() bool

IsResultStreaming determines whether the method streams payload.

func (*MethodExpr) IsStreaming

func (m *MethodExpr) IsStreaming() bool

IsStreaming determines whether the method streams payload or result.

func (*MethodExpr) Prepare

func (m *MethodExpr) Prepare()

Prepare makes sure the payload and result types are initialized (to the Empty type if nil) and merges the method interceptors with the API and service level interceptors.

func (*MethodExpr) Validate

func (m *MethodExpr) Validate() error

Validate validates the method payloads, results, errors, security requirements, and interceptors.

type NamedAttributeExpr

type NamedAttributeExpr struct {
	// Name of attribute
	Name string
	// Attribute
	Attribute *AttributeExpr
}

NamedAttributeExpr describes object attributes together with their names.

type Object

type Object []*NamedAttributeExpr

Object is the type used to describe composite data structures. Note: not a map because order matters.

func AsObject

func AsObject(dt DataType) *Object

AsObject returns the type underlying object if any, nil otherwise.

func (*Object) Attribute

func (o *Object) Attribute(name string) *AttributeExpr

Attribute returns the attribute with the given name if any, nil otherwise.

func (*Object) Delete

func (o *Object) Delete(n string)

Delete creates a new object with the same named attributes as o but without the named attribute n if any.

func (*Object) Example

func (o *Object) Example(r *ExampleGenerator) any

Example returns a random value of the object.

func (*Object) Hash

func (o *Object) Hash() string

Hash returns a unique hash value for o.

func (*Object) IsCompatible

func (*Object) IsCompatible(val any) bool

IsCompatible returns true if o describes the (Go) type of val.

func (*Object) Kind

func (*Object) Kind() Kind

Kind implements DataKind.

func (*Object) Merge

func (o *Object) Merge(other *Object) *Object

Merge creates a new object consisting of the named attributes of o appended with duplicates of the named attributes of other. Named attributes of o that have an identical name to named attributes of other get overridden.

func (*Object) Name

func (*Object) Name() string

Name returns the type name.

func (*Object) Rename

func (o *Object) Rename(n, m string)

Rename changes the name of the named attribute n to m. Rename does nothing if o does not have an attribute named n.

func (*Object) Set

func (o *Object) Set(n string, att *AttributeExpr)

Set replaces the object named attribute n if any - creates a new object by appending to the slice of named attributes otherwise. The resulting object is returned in both cases.

type Primitive

type Primitive Kind

Primitive is the type for null, boolean, integer, number, string, and time.

func (Primitive) Example

func (p Primitive) Example(r *ExampleGenerator) any

Example generates a pseudo-random primitive value using the given random generator.

func (Primitive) Hash

func (p Primitive) Hash() string

Hash returns a unique hash value for p.

func (Primitive) IsCompatible

func (p Primitive) IsCompatible(val any) bool

IsCompatible returns true if val is compatible with p.

func (Primitive) Kind

func (p Primitive) Kind() Kind

Kind implements DataKind.

func (Primitive) Name

func (p Primitive) Name() string

Name returns the type name appropriate for logging.

type ProjectionOutcome

type ProjectionOutcome uint8

ProjectionOutcome describes whether one target can represent the retained semantic value. Rejection never authorizes branch reselection or synthesis.

const (
	// ProjectionEmitted contains one checked target representation.
	ProjectionEmitted ProjectionOutcome = iota + 1
	// ProjectionIncomplete lacks a retained required wire member.
	ProjectionIncomplete
	// ProjectionUnsupported requires a codec outside builtin JSON interpretation.
	ProjectionUnsupported
	// ProjectionInvalidPlan has incompatible ownership or target structure.
	ProjectionInvalidPlan
	// ProjectionUnrepresentable fails schema, decoding or semantic preservation.
	ProjectionUnrepresentable
	// ProjectionSuppressed does not attempt materialization or synthesis.
	ProjectionSuppressed
)

type ProjectionResult

type ProjectionResult struct {
	// contains filtered or unexported fields
}

ProjectionResult owns canonical JSON bytes or a target-specific diagnostic.

func (ProjectionResult) Diagnostics

func (r ProjectionResult) Diagnostics() []ValueDiagnostic

Diagnostics returns owned diagnostic records and paths.

func (ProjectionResult) Err

func (r ProjectionResult) Err() error

Err reports an authored custom materialization error when one occurred.

func (ProjectionResult) JSON

func (r ProjectionResult) JSON() ([]byte, bool)

JSON returns copied canonical bytes only when the target emitted a value.

func (ProjectionResult) Outcome

func (r ProjectionResult) Outcome() ProjectionOutcome

Outcome returns the target projection result.

type Randomizer

type Randomizer interface {
	// ArrayLength decides how long an example array will be
	ArrayLength() int
	// Int generates an integer example
	Int() int
	// Int32 generates an int32 example
	Int32() int32
	// Int64 generates an int64 example
	Int64() int64
	// String generates a string example
	String() string
	// Bool generates a bool example
	Bool() bool
	// Float32 generates a float32 example
	Float32() float32
	// Float64 generates a float64 example
	Float64() float64
	// UInt generates a uint example
	UInt() uint
	// UInt32 generates a uint example
	UInt32() uint32
	// UInt64 generates a uint example
	UInt64() uint64
	// Name generates a human name example
	Name() string
	// Email generates an example email address
	Email() string
	// Hostname generates an example hostname
	Hostname() string
	// IPv4Address generates an example IPv4 address
	IPv4Address() net.IP
	// IPv6Address generates an example IPv6 address
	IPv6Address() net.IP
	// URL generates an example URL
	URL() string
	// Characters generates a n-character string example
	Characters(n int) string
	// UUID generates a random v4 UUID
	UUID() string
}

Randomizer generates consistent random values of different types given a seed.

The random values should be consistent in that given the same seed the same random values get generated.

Setting the randomizer to nil disables example generation.

func NewDeterministicRandomizer

func NewDeterministicRandomizer() Randomizer

NewDeterministicRandomizer builds a Randomizer that will return hard-coded values, removing all randomness from example generation.

func NewFakerRandomizer

func NewFakerRandomizer(seed string) Randomizer

NewFakerRandomizer creates a randomizer that uses the faker library to generate fake but reasonable values.

type ResolvedEntry

type ResolvedEntry struct {
	// Key is a scalar semantic key.
	Key ResolvedValue
	// Value is the entry's semantic value.
	Value ResolvedValue
}

ResolvedEntry preserves typed map keys before target spelling and insertion.

type ResolvedField

type ResolvedField struct {
	// Member identifies the declared occurrence edge, or is zero for extras.
	Member ValueIdentity
	// Name is the authored member name, not a transport rename.
	Name string
	// Value retains absent and null states as distinct semantic nodes.
	Value ResolvedValue
}

ResolvedField carries a declared member identity or, for an additional object field, a zero Member with its authored Name.

type ResolvedValue

type ResolvedValue struct {
	// contains filtered or unexported fields
}

ResolvedValue is an immutable semantic node. Accessors return copied containers and preserve selected branches instead of guessing from wire data.

func (ResolvedValue) Any

func (v ResolvedValue) Any() (ResolvedValue, bool)

Any returns the retained builtin payload of an Any node.

func (ResolvedValue) Elements

func (v ResolvedValue) Elements() []ResolvedValue

Elements returns copied handles in array order.

func (ResolvedValue) Entries

func (v ResolvedValue) Entries() []ResolvedEntry

Entries returns copied typed map entries.

func (ResolvedValue) Fields

func (v ResolvedValue) Fields() []ResolvedField

Fields returns copied declared-field and additional-field records.

func (ResolvedValue) ID

ID returns this node's opaque identity, or zero for an absent handle.

func (ResolvedValue) Kind

func (v ResolvedValue) Kind() ValueKind

Kind returns the semantic shape, or zero for a zero handle.

func (ResolvedValue) OccurrenceID

func (v ResolvedValue) OccurrenceID() ValueIdentity

OccurrenceID identifies the semantic occurrence, independently of its target.

func (ResolvedValue) Presence

func (v ResolvedValue) Presence() ValuePresence

Presence returns the node's presence; the zero handle is absent.

func (ResolvedValue) RawAny

func (v ResolvedValue) RawAny() (any, bool)

RawAny returns an owned copy of the finite builtin host snapshot retained by an Any value. Concrete container and nested scalar types are preserved. This is source host meaning, not projected JSON or a fallback for other kinds; no custom materializer is invoked. Non-Any values return false.

func (ResolvedValue) Scalar

func (v ResolvedValue) Scalar() (any, bool)

Scalar returns a scalar copy, preserving its concrete numeric or byte type.

func (ResolvedValue) SourceID

func (v ResolvedValue) SourceID() ValueIdentity

SourceID identifies the source from which this node was resolved.

func (ResolvedValue) Union

Union returns the selected occurrence, branch and payload without reselection.

type ResultTypeExpr

type ResultTypeExpr struct {
	// A result type is a user type
	*UserTypeExpr
	// Identifier is the RFC 6838 result type media type identifier.
	Identifier string
	// Views list the supported views indexed by name.
	Views []*ViewExpr
}

ResultTypeExpr is a user type which describes views used to render responses.

func GeneratedResultType

func GeneratedResultType(id string) *ResultTypeExpr

GeneratedResultType returns the generated result type expression with the given id, nil if there isn't one.

func NewResultTypeExpr

func NewResultTypeExpr(name, identifier string, fn func()) *ResultTypeExpr

NewResultTypeExpr creates a result type definition but does not execute the DSL.

func Project

func Project(rt *ResultTypeExpr, view string) (*ResultTypeExpr, error)

Project creates a ResultTypeExpr containing the fields defined in the view expression of m named after the view argument.

The resulting result type defines a default view. The result type identifier is computed by adding a parameter called "view" to the original identifier. The value of the "view" parameter is the name of the view.

Project returns an error if the view does not exist for the given result type or any result type that makes up its attributes recursively. Note that individual attributes may use a different view. In this case Project uses that view and returns an error if it isn't defined on the attribute type.

func (*ResultTypeExpr) Dup

func (rt *ResultTypeExpr) Dup(att *AttributeExpr) UserType

Dup creates a copy of the result type given a deep copy of its attribute. Views keep independent metadata, validation and requiredness overrides while sharing field types whose DSL may still be awaiting evaluation.

func (*ResultTypeExpr) Finalize

func (rt *ResultTypeExpr) Finalize()

Finalize builds the default view if not explicitly defined and finalizes the underlying UserTypeExpr.

func (*ResultTypeExpr) HasMultipleViews

func (rt *ResultTypeExpr) HasMultipleViews() bool

HasMultipleViews returns true if the result type has more than one view.

func (*ResultTypeExpr) ID

func (rt *ResultTypeExpr) ID() string

ID returns the identifier of the result type.

func (*ResultTypeExpr) Kind

func (*ResultTypeExpr) Kind() Kind

Kind implements DataKind.

func (*ResultTypeExpr) Name

func (rt *ResultTypeExpr) Name() string

Name returns the result type name.

func (*ResultTypeExpr) View

func (rt *ResultTypeExpr) View(name string) *ViewExpr

View returns the view with the given name.

func (*ResultTypeExpr) ViewHasAttribute

func (rt *ResultTypeExpr) ViewHasAttribute(view, attr string) bool

ViewHasAttribute returns true if the result type view has the given attribute.

type ResultTypesRoot

type ResultTypesRoot []*ResultTypeExpr

ResultTypesRoot is a DSL root that records the result types generated by the DSL.

func (*ResultTypesRoot) Append

Append adds the given type to the generated result types if not already added. It returns the type that was added or already present.

func (*ResultTypesRoot) DependsOn

func (*ResultTypesRoot) DependsOn() []eval.Root

DependsOn ensures that Root executes first.

func (*ResultTypesRoot) EvalName

func (*ResultTypesRoot) EvalName() string

EvalName is the name of the expression used by eval.

func (*ResultTypesRoot) Packages

func (*ResultTypesRoot) Packages() []string

Packages returns the Go import path to this and the dsl packages.

func (*ResultTypesRoot) WalkSets

func (r *ResultTypesRoot) WalkSets(w eval.SetWalker)

WalkSets returns the generated result types for evaluation.

type RootExpr

type RootExpr struct {
	// API contains the API expression built by the DSL.
	API *APIExpr
	// Services contains the list of services exposed by the API.
	Services []*ServiceExpr
	// Interceptors contains the list of interceptors.
	Interceptors []*InterceptorExpr
	// Authorizations contains named application access requirements.
	Authorizations []*AuthorizationExpr
	// Errors contains the list of errors returned by all the API
	// methods.
	Errors []*ErrorExpr
	// Types contains the user types described in the DSL.
	Types []UserType
	// ResultTypes contains the result types generated during DSL
	// execution.
	ResultTypes []*ResultTypeExpr
	// Conversions list the user type to external type mappings.
	Conversions []*TypeMap
	// Creations list the external type to user type mappings.
	Creations []*TypeMap
	// Schemes list the registered security schemes.
	Schemes []*SchemeExpr
	// SessionAuths list the registered multi-transport session auth contracts.
	SessionAuths []*SessionAuthExpr
	// contains filtered or unexported fields
}

RootExpr is the struct built by the DSL on process start.

func RunDSL

func RunDSL(t *testing.T, dsl func()) *RootExpr

RunDSL returns the DSL root resulting from running the given DSL. Used only in tests.

func SetupTestDSL added in v1.0.8

func SetupTestDSL(t *testing.T) *RootExpr

SetupTestDSL resets the global expression state for testing and initializes a default API. This function should be called before running any DSL that modifies the global Root or GeneratedResultTypes variables.

Usage in tests:

func TestMyDSL(t *testing.T) {
    // Option 1: Use expr.RunDSL which calls SetupTestDSL automatically
    root := expr.RunDSL(t, func() {
        Service("my-service", func() { /* ... */ })
    })

    // Option 2: Call SetupTestDSL manually when running DSL directly
    expr.SetupTestDSL(t)
    eval.Execute(myDSL, nil)
    eval.RunDSL()
}

Note: RunDSL and RunInvalidDSL automatically call SetupTestDSL, so you only need to call it manually when executing DSL code directly.

func (*RootExpr) DependsOn

func (*RootExpr) DependsOn() []eval.Root

DependsOn returns nil, the core DSL has no dependency.

func (*RootExpr) Error

func (r *RootExpr) Error(name string) *ErrorExpr

Error returns the error with the given name.

func (*RootExpr) EvalName

func (*RootExpr) EvalName() string

EvalName is the name of the DSL.

func (*RootExpr) Finalize

func (r *RootExpr) Finalize()

Finalize establishes stable service ordering and finalizes the server expressions. Go may initialize independent package variables in a dependency-derived order, so declaration registration order is not a durable code-generation contract.

func (*RootExpr) NewUnionBranch

func (r *RootExpr) NewUnionBranch(name string, attribute *AttributeExpr) *UserTypeExpr

NewUnionBranch constructs an automatically named branch type. Its private identity keeps distinct definitions separate during DSL copies. Prepare assigns stable names before transport preparation; copies of one definition receive the same name. Callers must retain the returned type in the design.

func (*RootExpr) Packages

func (*RootExpr) Packages() []string

Packages returns the Go import path to this and the dsl packages.

func (*RootExpr) Prepare

func (r *RootExpr) Prepare()

Prepare gives automatically promoted union branches stable, distinct names before identity-based transport preparation and validation run.

func (*RootExpr) Service

func (r *RootExpr) Service(name string) *ServiceExpr

Service returns the service with the given name.

func (*RootExpr) UserType

func (r *RootExpr) UserType(name string) UserType

UserType returns the user type expression with the given name if found, nil otherwise.

func (*RootExpr) Validate

func (r *RootExpr) Validate() error

Validate makes sure the root expression is valid for code generation.

func (*RootExpr) WalkSets

func (r *RootExpr) WalkSets(walk eval.SetWalker)

WalkSets returns the expressions in order of evaluation.

type RouteExpr

type RouteExpr struct {
	// Method is the HTTP method, e.g. "GET", "POST", etc.
	Method string
	// Path is the URL path e.g. "/tasks/{id}"
	Path string
	// Endpoint is the endpoint this route applies to.
	Endpoint *HTTPEndpointExpr
	// Meta is an arbitrary set of key/value pairs, see
	// dsl.Meta
	Meta MetaExpr
}

RouteExpr represents an endpoint route (HTTP endpoint).

func (*RouteExpr) AddMeta

func (r *RouteExpr) AddMeta(name string, value ...string)

AddMeta appends metadata values to the route expression.

func (*RouteExpr) DeleteMeta

func (r *RouteExpr) DeleteMeta(name string)

DeleteMeta removes a metadata entry from the route expression.

func (*RouteExpr) EvalName

func (r *RouteExpr) EvalName() string

EvalName returns the generic definition name used in error messages.

func (*RouteExpr) FullPaths

func (r *RouteExpr) FullPaths() []string

FullPaths returns the endpoint full paths computed by concatenating the service base paths with the route specific path.

func (*RouteExpr) IsAbsolute

func (r *RouteExpr) IsAbsolute() bool

IsAbsolute returns true if the endpoint path should not be concatenated to the service and API base paths.

func (*RouteExpr) Params

func (r *RouteExpr) Params() []string

Params returns all the route parameters across all the base paths. For example for the route "GET /foo/{foo_id}" Params returns []string{"foo_id"}. A route parameter is the transport element name of a param, such as "k" for Param("key:k").

func (*RouteExpr) Validate

func (r *RouteExpr) Validate() *eval.ValidationErrors

Validate validates a route expression by ensuring that the route parameters can be inferred from the method payload and there is no duplicate parameters in an absolute route.

type Runtime added in v1.0.8

type Runtime struct {
	Root                 *RootExpr
	GeneratedResultTypes *ResultTypesRoot
	Validated            map[*AttributeExpr]bool
}

Runtime owns the root expressions that back one Loom DSL session.

func DefaultRuntime added in v1.0.8

func DefaultRuntime() *Runtime

DefaultRuntime returns the process-default DSL runtime.

func NewRuntime added in v1.0.8

func NewRuntime() *Runtime

NewRuntime creates a fresh DSL runtime.

func (*Runtime) EvalRoots added in v1.0.8

func (r *Runtime) EvalRoots() []eval.Root

EvalRoots returns the runtime roots in evaluation order.

func (*Runtime) RegisterRoots added in v1.0.8

func (r *Runtime) RegisterRoots(ctx *eval.DSLContext) error

RegisterRoots registers the runtime roots with the given context.

type SSEProjectionExpr added in v1.6.0

type SSEProjectionExpr struct {
	// EventType is the value written to the SSE event field.
	EventType string
	// View is the result view used for the JSON event data.
	View string
}

SSEProjectionExpr maps an SSE event discriminator to a result view.

type SchemeExpr

type SchemeExpr struct {
	// Kind is the sort of security scheme this object represents.
	Kind SchemeKind
	// SchemeName is the name of the security scheme, e.g. "googAuth",
	// "my_big_token", "jwt".
	SchemeName string
	// Description describes the security scheme e.g. "Google OAuth2"
	Description string
	// In determines the location of the API key, one of "header" or
	// "query".
	In string
	// Name refers to a header or parameter name, based on In's
	// value.
	Name string
	// Scopes lists the Basic, APIKey, JWT or OAuth2 scopes.
	Scopes []*ScopeExpr
	// Flows determine the oauth2 flows supported by this scheme.
	Flows []*FlowExpr
	// Meta is a list of key/value pairs
	Meta MetaExpr
}

SchemeExpr defines a security scheme used to authenticate against the method being designed.

func DupScheme

func DupScheme(sch *SchemeExpr) *SchemeExpr

DupScheme creates a copy of the given scheme expression.

func (*SchemeExpr) AddMeta added in v1.8.0

func (s *SchemeExpr) AddMeta(name string, value ...string)

AddMeta appends metadata values to the security scheme expression.

func (*SchemeExpr) DeleteMeta added in v1.8.0

func (s *SchemeExpr) DeleteMeta(name string)

DeleteMeta removes a metadata entry from the security scheme expression.

func (*SchemeExpr) EvalName

func (s *SchemeExpr) EvalName() string

EvalName returns the generic definition name used in error messages.

func (*SchemeExpr) Hash

func (s *SchemeExpr) Hash() string

Hash returns a unique hash value for s.

func (*SchemeExpr) Type

func (s *SchemeExpr) Type() string

Type returns the type of the scheme.

func (*SchemeExpr) Validate

func (s *SchemeExpr) Validate() *eval.ValidationErrors

Validate ensures that the method payload contains attributes required by the scheme.

type SchemeKind

type SchemeKind int

SchemeKind is a type of security scheme.

const (
	// OAuth2Kind identifies a "OAuth2" security scheme.
	OAuth2Kind SchemeKind = iota + 1
	// BasicAuthKind means "basic" security scheme.
	BasicAuthKind
	// APIKeyKind means "apiKey" security scheme.
	APIKeyKind
	// JWTKind means an "JWT" security scheme, with support for
	// TokenPath and Scopes.
	JWTKind
	// NoKind means to have no security for this endpoint.
	NoKind
)

func (SchemeKind) String

func (k SchemeKind) String() string

type ScopeExpr

type ScopeExpr struct {
	// Name of the scope.
	Name string
	// Description is the description of the scope.
	Description string
}

ScopeExpr defines a security scope.

type SecurityExpr

type SecurityExpr struct {
	// Schemes is the list of security schemes used for this
	// requirement.
	Schemes []*SchemeExpr
	// Scopes list the required scopes if any.
	Scopes []string
}

SecurityExpr defines a security requirement.

func DupRequirement

func DupRequirement(req *SecurityExpr) *SecurityExpr

DupRequirement creates a copy of the given security requirement.

func (*SecurityExpr) EvalName

func (s *SecurityExpr) EvalName() string

EvalName returns the generic definition name used in error messages.

type SecurityHolder

type SecurityHolder interface {
	AddSecurityRequirement(*SecurityExpr)
}

SecurityHolder is an interface that allows expression types to receive security requirements. Types implementing this interface can use the Security() DSL function to add security schemes.

type ServerExpr

type ServerExpr struct {
	// Name of server
	Name string
	// Description of server
	Description string
	// Services list the services hosted by the server.
	Services []string
	// Hosts list the server hosts.
	Hosts []*HostExpr
	// Meta is a set of key/value pairs.
	Meta MetaExpr
}

ServerExpr contains a single API host information.

func (*ServerExpr) AddMeta

func (s *ServerExpr) AddMeta(name string, value ...string)

AddMeta appends metadata values to the server expression.

func (*ServerExpr) DeleteMeta

func (s *ServerExpr) DeleteMeta(name string)

DeleteMeta removes a metadata entry from the server expression.

func (*ServerExpr) EvalName

func (s *ServerExpr) EvalName() string

EvalName is the qualified name of the expression.

func (*ServerExpr) Finalize

func (s *ServerExpr) Finalize()

Finalize initializes the server services and/or host with default values if not set explicitly in the design.

func (*ServerExpr) Schemes

func (s *ServerExpr) Schemes() []string

Schemes returns the list of transport schemes used by all the server endpoints. The possible values for the elements of the returned slice are "http", "https", "grpc" and "grpcs".

func (*ServerExpr) Validate

func (s *ServerExpr) Validate() error

Validate validates the server and server hosts.

type ServiceExpr

type ServiceExpr struct {
	// DSLFunc contains the DSL used to initialize the expression.
	eval.DSLFunc
	// Name of service.
	Name string
	// Description of service used in documentation.
	Description string
	// Docs points to external documentation
	Docs *DocsExpr
	// Methods is the list of service methods.
	Methods []*MethodExpr
	// Errors list the errors common to all the service methods.
	Errors []*ErrorExpr
	// Requirements contains the security requirements that apply to
	// all the service methods. One requirement is composed of
	// potentially multiple schemes. Incoming requests must validate
	// at least one requirement to be authorized.
	Requirements []*SecurityExpr
	// SessionAuths contains the multi-transport session auth contracts that
	// apply to all service methods.
	SessionAuths []*SessionAuthExpr
	// ClientInterceptors is the list of client interceptors.
	ClientInterceptors []*InterceptorExpr
	// ServerInterceptors is the list of server interceptors.
	ServerInterceptors []*InterceptorExpr
	// StrictAuthorization requires every method to declare access or an exemption.
	StrictAuthorization bool
	// Meta is a set of key/value pairs with semantic that is
	// specific to each generator.
	Meta MetaExpr
}

ServiceExpr describes a set of related methods.

func (*ServiceExpr) AddMeta

func (s *ServiceExpr) AddMeta(name string, value ...string)

AddMeta appends metadata values to the service expression.

func (*ServiceExpr) DeleteMeta

func (s *ServiceExpr) DeleteMeta(name string)

DeleteMeta removes a metadata entry from the service expression.

func (*ServiceExpr) Error

func (s *ServiceExpr) Error(name string) *ErrorExpr

Error returns the error with the given name if any.

func (*ServiceExpr) EvalName

func (s *ServiceExpr) EvalName() string

EvalName returns the generic expression name used in error messages.

func (*ServiceExpr) Finalize

func (s *ServiceExpr) Finalize()

Finalize finalizes all the service methods and errors.

func (*ServiceExpr) Hash

func (s *ServiceExpr) Hash() string

Hash returns a unique hash value for s.

func (*ServiceExpr) Method

func (s *ServiceExpr) Method(n string) *MethodExpr

Method returns the method expression with the given name, nil if there isn't one.

func (*ServiceExpr) Validate

func (s *ServiceExpr) Validate() error

Validate validates the service methods and errors.

type SessionAuthExpr

type SessionAuthExpr struct {
	// Name is the session auth contract name.
	Name string
	// Description describes the session auth contract.
	Description string
	// Transports lists the accepted auth transports.
	Transports []*SessionTransportExpr
}

SessionAuthExpr defines a logical auth contract backed by one or more transport alternatives.

func (*SessionAuthExpr) EvalName

func (s *SessionAuthExpr) EvalName() string

EvalName returns the generic definition name used in error messages.

func (*SessionAuthExpr) SetDescription

func (s *SessionAuthExpr) SetDescription(d string)

SetDescription sets the session auth description.

func (*SessionAuthExpr) Validate

func (s *SessionAuthExpr) Validate() *eval.ValidationErrors

Validate validates the session auth contract.

type SessionTransportExpr

type SessionTransportExpr struct {
	// Kind identifies the transport kind.
	Kind SessionTransportKind
	// Scheme is the underlying security scheme used by this transport.
	Scheme *SchemeExpr
	// FieldName is the payload field name associated with the transport.
	FieldName string
	// HTTPName is the inferred HTTP transport element name if any.
	HTTPName string
	// Description describes the transport.
	Description string
}

SessionTransportExpr defines one accepted transport for a session auth contract.

func (*SessionTransportExpr) EvalName

func (s *SessionTransportExpr) EvalName() string

EvalName returns the generic definition name used in error messages.

func (*SessionTransportExpr) PayloadOwned added in v1.0.5

func (s *SessionTransportExpr) PayloadOwned() bool

PayloadOwned returns true when the transport credential is modeled as a payload field.

func (*SessionTransportExpr) SetDescription

func (s *SessionTransportExpr) SetDescription(d string)

SetDescription sets the transport description.

func (*SessionTransportExpr) TransportAttributeName added in v1.0.5

func (s *SessionTransportExpr) TransportAttributeName() string

TransportAttributeName returns the attribute name used for transport metadata when the credential is not payload-owned.

func (*SessionTransportExpr) Validate

Validate validates the session transport.

type SessionTransportKind

type SessionTransportKind int

SessionTransportKind identifies the transport used by a session auth contract.

const (
	// SessionBearerTransportKind identifies a bearer token transport.
	SessionBearerTransportKind SessionTransportKind = iota + 1
	// SessionCookieTransportKind identifies a cookie transport.
	SessionCookieTransportKind
)

func (SessionTransportKind) String

func (k SessionTransportKind) String() string

type StreamKind

type StreamKind int

StreamKind is a type denoting the kind of stream.

const (
	// NoStreamKind represents no payload or result stream in method.
	NoStreamKind StreamKind = iota + 1
	// ClientStreamKind represents client sends a streaming payload to
	// method.
	ClientStreamKind
	// ServerStreamKind represents server sends a streaming result from
	// method.
	ServerStreamKind
	// BidirectionalStreamKind represents client and server sending payload
	// and result respectively via a stream.
	BidirectionalStreamKind
)

type TimeoutHolder

type TimeoutHolder interface {
	SetTimeout(string) error
}

TimeoutHolder is an interface that allows expression types to receive a timeout duration. Types implementing this interface can use the Timeout() DSL function to set a timeout.

type TitleHolder

type TitleHolder interface {
	SetTitle(string)
}

TitleHolder is an interface that allows expression types to receive a title. Types implementing this interface can use the Title() DSL function to set a title.

type TypeMap

type TypeMap struct {
	// User is the user type being converted or created.
	User UserType

	// External is an instance of the type being converted from or to.
	External any
}

TypeMap defines a user to external type mapping.

type URIExpr

type URIExpr string

URIExpr represents a parameterized URI.

func (URIExpr) Params

func (u URIExpr) Params() []string

Params return the names of the parameters used in URI if any.

func (URIExpr) Scheme

func (u URIExpr) Scheme() string

Scheme returns the URI scheme. Possible values are http, https, grpc, and grpcs.

type URLHolder

type URLHolder interface {
	SetURL(string)
}

URLHolder is an interface that allows expression types to receive a URL. Types implementing this interface can use the URL() DSL function to set a URL.

type Union

type Union struct {
	TypeName string
	Values   []*NamedAttributeExpr
	// Untagged encodes the selected branch directly instead of wrapping it in
	// the canonical discriminator/value object.
	Untagged bool
	// ExplicitTypeName is true when the union type name was set explicitly
	// via DSL metadata and should not be recomputed from derived variants.
	ExplicitTypeName bool
	// TypeKey is the discriminator field name for JSON marshaling (defaults to "type")
	TypeKey string
	// ValueKey is the value field name for JSON marshaling (defaults to "value")
	ValueKey string
}

Union is the type used to describe unions.

func AsUnion

func AsUnion(dt DataType) *Union

AsUnion returns the type underlying union if any, nil otherwise.

func (*Union) Example

func (u *Union) Example(r *ExampleGenerator) any

Example returns a random example value.

func (*Union) GetTypeKey

func (u *Union) GetTypeKey() string

GetTypeKey returns the discriminator field name for JSON marshaling. Defaults to "type" if not explicitly set via Meta("oneof:type:field").

func (*Union) GetValueKey

func (u *Union) GetValueKey() string

GetValueKey returns the value field name for JSON marshaling. Defaults to "value" if not explicitly set via Meta("oneof:value:field").

func (*Union) Hash

func (u *Union) Hash() string

Hash returns a unique hash value for m.

func (*Union) IsCompatible

func (u *Union) IsCompatible(val any) bool

IsCompatible returns true if u describes the (Go) type of val.

func (*Union) Kind

func (*Union) Kind() Kind

Kind implements DataKind.

func (*Union) Name

func (u *Union) Name() string

Name returns the type name.

type UserType

type UserType interface {
	DataType
	eval.Expression
	// Finalizes the underlying type.
	eval.Finalizer
	// Provides the underlying type and validations.
	CompositeExpr
	// ID returns the identifier for the user type.
	ID() string
	// Rename changes the type name to the given value.
	Rename(string)
	// SetAttribute updates the underlying attribute.
	SetAttribute(*AttributeExpr)
	// Dup makes a shallow copy of the type and assigns its
	// attribute with att.
	Dup(att *AttributeExpr) UserType
	// Validate checks that the user type expression is consistent.
	Validate(ctx string, parent eval.Expression) *eval.ValidationErrors
}

UserType is the interface implemented by all user type implementations. Plugins may leverage this interface to introduce their own types.

type UserTypeExpr

type UserTypeExpr struct {
	// The embedded attribute expression.
	*AttributeExpr
	// Name of type
	TypeName string
	// UID of type
	UID string
	// contains filtered or unexported fields
}

UserTypeExpr describes user defined types. While a given design must ensure that the names are unique the code used to generate code can create multiple user types that share the same name (for example because generated in different packages). UID is always unique and makes it possible to avoid infinite recursions when traversing the data structures described by the attribute expression e.g. when computing example values.

func (*UserTypeExpr) Attribute

func (u *UserTypeExpr) Attribute() *AttributeExpr

Attribute returns the embedded attribute.

func (*UserTypeExpr) Dup

func (u *UserTypeExpr) Dup(att *AttributeExpr) UserType

Dup creates a deep copy of the user type given a deep copy of its attribute.

func (*UserTypeExpr) Example

func (u *UserTypeExpr) Example(r *ExampleGenerator) any

Example produces an example for the user type which is JSON serialization compatible.

func (*UserTypeExpr) Hash

func (u *UserTypeExpr) Hash() string

Hash returns a unique hash value for u.

func (*UserTypeExpr) ID

func (u *UserTypeExpr) ID() string

ID returns the unique identifier for the user type.

func (*UserTypeExpr) IsCompatible

func (u *UserTypeExpr) IsCompatible(val any) bool

IsCompatible returns true if u describes the (Go) type of val.

func (*UserTypeExpr) Kind

func (*UserTypeExpr) Kind() Kind

Kind implements DataKind.

func (*UserTypeExpr) Name

func (u *UserTypeExpr) Name() string

Name returns the type name.

func (*UserTypeExpr) Rename

func (u *UserTypeExpr) Rename(n string)

Rename changes the type name to the given value.

func (*UserTypeExpr) SetAttribute

func (u *UserTypeExpr) SetAttribute(att *AttributeExpr)

SetAttribute sets the embedded attribute.

type UserTypeRegistry

type UserTypeRegistry struct {
	// contains filtered or unexported fields
}

UserTypeRegistry stores named temporary user types for synthesized expression trees and returns them in deterministic order.

func NewUserTypeRegistry

func NewUserTypeRegistry() *UserTypeRegistry

NewUserTypeRegistry creates an empty registry for temporary named user types.

func (*UserTypeRegistry) Attribute

func (r *UserTypeRegistry) Attribute(name string, builder func() *AttributeExpr) *AttributeExpr

Attribute returns an attribute that references the named user type.

func (*UserTypeRegistry) Collect

func (r *UserTypeRegistry) Collect() []UserType

Collect returns all registered user types sorted by name.

func (*UserTypeRegistry) GetOrCreate

func (r *UserTypeRegistry) GetOrCreate(name string, builder func() *AttributeExpr) *UserTypeExpr

GetOrCreate returns the named user type, creating it with builder on the first call only.

type Val

type Val map[string]any

Val is the type used to provide the value of examples for attributes that are objects.

type ValidationExpr

type ValidationExpr struct {
	// Values represents an enum validation as described at
	// http://json-schema.org/latest/json-schema-validation.html#anchor76.
	// Values contains the enum authored at this declaration.
	Values []any
	// EnumClauses contains additional enum membership predicates. Each
	// inner slice is conjoined with Values and the other clauses. A nil
	// outer slice adds no predicate; an empty inner slice is an empty-domain
	// predicate. EffectiveValidation.Lowered uses this field so a selected
	// inherited enum remains distinct from a newly authored enum.
	EnumClauses [][]any
	// Format represents a format validation as described at
	// http://json-schema.org/latest/json-schema-validation.html#anchor104.
	Format ValidationFormat
	// Pattern represents a pattern validation as
	// described at
	// http://json-schema.org/latest/json-schema-validation.html#anchor33
	Pattern string
	// PatternClauses contains additional pattern validations conjoined
	// after Pattern in slice order. Exact duplicates are ignored by
	// semantic consumers.
	PatternClauses []string
	// FormatClauses contains additional format validations conjoined after
	// Format in slice order. Exact duplicates are ignored by semantic
	// consumers.
	FormatClauses []ValidationFormat
	// ExclusiveMinimum represents an exclusiveMinimum value validation as described
	// at
	// http://json-schema.org/draft/2019-09/json-schema-validation.html#rfc.section.6.2.5.
	ExclusiveMinimum *float64
	// Minimum represents an minimum value validation as described
	// at
	// http://json-schema.org/latest/json-schema-validation.html#anchor21.
	Minimum *float64
	// Maximum represents a maximum value validation as described at
	// http://json-schema.org/latest/json-schema-validation.html#anchor17.
	Maximum *float64
	// ExclusiveMaximum represents an exclusiveMaximum value validation as described
	// at
	// http://json-schema.org/draft/2019-09/json-schema-validation.html#rfc.section.6.2.3.
	ExclusiveMaximum *float64
	// MinLength represents an minimum length validation as
	// described at
	// http://json-schema.org/latest/json-schema-validation.html#anchor29.
	MinLength *int
	// MaxLength represents an maximum length validation as
	// described at
	// http://json-schema.org/latest/json-schema-validation.html#anchor26.
	MaxLength *int
	// Required list the required fields of object attributes as
	// described at
	// http://json-schema.org/latest/json-schema-validation.html#anchor61.
	Required []string
}

ValidationExpr contains validation rules for an attribute.

func (*ValidationExpr) AddRequired

func (v *ValidationExpr) AddRequired(required ...string)

AddRequired merges the required fields into v.

func (*ValidationExpr) Debug

func (v *ValidationExpr) Debug(title, prefix, indent string)

Debug dumps the validation to STDOUT in a Loom developer friendly way.

func (*ValidationExpr) Dup

func (v *ValidationExpr) Dup() *ValidationExpr

Dup makes a shallow dup of the validation.

func (*ValidationExpr) Enums

func (v *ValidationExpr) Enums() [][]any

Enums returns every enum membership predicate in authored-then-clause order. The returned outer and inner slices are detached. Exact duplicate predicates are returned once. An explicit empty predicate is preserved.

func (*ValidationExpr) Formats

func (v *ValidationExpr) Formats() []ValidationFormat

Formats returns the conjoined format validations in current-then-clause order with exact duplicates removed.

func (*ValidationExpr) HasRequiredOnly

func (v *ValidationExpr) HasRequiredOnly() bool

HasRequiredOnly returns true if the validation only has the Required field with a non-zero value.

func (*ValidationExpr) Merge

func (v *ValidationExpr) Merge(other *ValidationExpr)

Merge merges other into v so that v enforces the constraints of both: the result accepts a value only if both v and other accept it. Numeric and length bounds keep the tighter value (the larger lower bound and the smaller upper bound), inclusive and exclusive bounds are kept independently, pattern and format clauses are conjoined with exact duplicates removed, and required fields are unioned. When v has no enum predicate, other's authored enum is adopted. Otherwise incoming authored values are added as a conjoined clause, followed by the additional clauses. Existing receiver clauses retain their order and authorship distinction. Merge never mutates other.

func (*ValidationExpr) Patterns

func (v *ValidationExpr) Patterns() []string

Patterns returns the conjoined pattern validations in current-then-clause order with exact duplicates removed.

func (*ValidationExpr) RemoveRequired

func (v *ValidationExpr) RemoveRequired(required string)

RemoveRequired removes the given field from the list of required fields.

func (*ValidationExpr) Validate

func (v *ValidationExpr) Validate(ctx string, parent eval.Expression) *eval.ValidationErrors

Validate validates the validation expression.

type ValidationFormat

type ValidationFormat string

ValidationFormat is the type used to enumerate the possible string formats.

type ValueBranch

type ValueBranch struct {
	// ID identifies the branch edge independently of its payload shape.
	ID ValueIdentity
	// Name is the authored alternative name.
	Name string
	// Tag is the declared discriminator value.
	Tag string
	// Occurrence carries the branch's effective contract.
	Occurrence ValueOccurrence
}

ValueBranch is a copied descriptor of a declared union alternative.

type ValueCodec

type ValueCodec uint8

ValueCodec identifies an actual serialization owner.

const (
	// ValueCodecJSON is Loom's JSON-v2 codec, including JSONValue materialization.
	ValueCodecJSON ValueCodec = iota + 1
	// ValueCodecProtoJSON is the protobuf JSON codec.
	ValueCodecProtoJSON
	// ValueCodecText is the selected text codec for a body or transport location.
	ValueCodecText
	// ValueCodecRaw is an unencoded binary body.
	ValueCodecRaw
	// ValueCodecMultipart is the multipart body encoder.
	ValueCodecMultipart
	// ValueCodecForm is the form body encoder.
	ValueCodecForm
	// ValueCodecCustom is an explicitly selected external codec boundary.
	ValueCodecCustom
)

type ValueCodecPolicy

type ValueCodecPolicy struct {
	// Target identifies the occurrence before capture, not a type-name lookup.
	Target *AttributeExpr
	// Codec is the actual encoding owner for this node and its descendants.
	Codec ValueCodec
}

ValueCodecPolicy binds an encoding owner to one exact finalized target occurrence.

type ValueContainerPolicy

type ValueContainerPolicy struct {
	// Target is the finalized object or union attribute before capture.
	Target *AttributeExpr
	// RejectUnknownMembers selects rejection instead of ignoring extra wire members.
	RejectUnknownMembers bool
	// PreserveAdditional reports whether the encoder retains undeclared semantic members.
	PreserveAdditional bool
}

ValueContainerPolicy describes the actual decoder of one target container.

type ValueContext

type ValueContext struct {
	// contains filtered or unexported fields
}

ValueContext owns semantic values for one generation. Handles from different contexts cannot be mixed. Builtin source data and all returned slices are copied.

func NewValueContext

func NewValueContext() *ValueContext

NewValueContext creates a generation-scoped semantic owner with no global cache.

func (*ValueContext) ContainsExampleSource

func (c *ValueContext) ContainsExampleSource(occurrence ValueOccurrence, source ValueSource) bool

ContainsExampleSource reports whether a supplied authored example belongs to any node in this semantic graph, including selected-body children. It compares provenance identities only and never selects, resolves or materializes data.

func (*ValueContext) DeclaredJSONValue

func (c *ValueContext) DeclaredJSONValue(result ValueResult, plan ValuePlan) (any, bool)

DeclaredJSONValue returns the retained declared value selected by a captured plan. It checks context and semantic ownership, then follows the plan's retained member identities without resolving or synthesizing again. Bytes remain []byte and scalar precision is preserved; no target codec, field renaming, presence filtering or wire validation is applied. Explicit null returns nil with true; absent, invalid, suppressed, foreign or schema-only inputs return false. Opaque leaves retain the same eligibility and borrowing rules as ValueResult.DeclaredJSONValue. Use ProjectJSON for checked target wire output.

func (*ValueContext) NewOccurrence

func (c *ValueContext) NewOccurrence(finalized *AttributeExpr) (ValueOccurrence, error)

NewOccurrence captures an effective finalized attribute and returns a new semantic root even when another root uses the same named type. It preserves finite recursive declarations. Malformed graphs and invalid authored enums or defaults fail construction; examples remain deferred sources until selected.

func (*ValueContext) NewValuePlan

func (c *ValueContext) NewValuePlan(source ValueOccurrence, request ValuePlanRequest) (ValuePlan, error)

NewValuePlan captures a finalized target and maps it to a supplied semantic root using structural copy ancestry. It rejects foreign contexts, unrelated targets, ambiguous mappings and incomplete runtime field policies. It never interns by type hash or takes ownership of a mutable caller attribute.

func (*ValueContext) ProjectJSON

func (c *ValueContext) ProjectJSON(result ValueResult, plan ValuePlan) ProjectionResult

ProjectJSON observes target visibility and presence before constructing one canonical wire. Schema checks and runtime decoding consume that same wire; neither may change the semantic union branch. Documentation plans make no runtime-decoder claim.

func (*ValueContext) Resolve

func (c *ValueContext) Resolve(occurrence ValueOccurrence, source ValueSource, role ValueRole) ValueResult

Resolve interprets one immutable source against its effective semantic occurrence. It never receives a target, reselects an already selected branch, or substitutes generated data for an authored failure.

func (*ValueContext) ResolveDeclaredShape

func (c *ValueContext) ResolveDeclaredShape(occurrence ValueOccurrence, source ValueSource) ValueResult

ResolveDeclaredShape interprets one immutable source against its declared shape without establishing that the source is admitted by the occurrence. Validation and enum predicates are suppressed only for the root occurrence and its named ancestry. Child and member constraints, required nested data, and union branch selection remain enforced. Explicit opaque codec leaves may be retained without invoking their codecs. The source and occurrence must belong to this context. Shape resolutions do not read or populate Resolve's semantic result cache.

func (*ValueContext) SelectExample

func (c *ValueContext) SelectExample(occurrence ValueOccurrence, policy ExamplePolicy) ExampleSelection

SelectExample chooses the last authored example from the first extracted group, using local/reference/base/type precedence. It never resolves, synthesizes or invokes custom materialization.

func (*ValueContext) SupplyValue

func (c *ValueContext) SupplyValue(input ValueInput) ValueSource

SupplyValue captures source data without validating a semantic contract or invoking a custom codec. Capture errors remain deferred until Resolve.

func (*ValueContext) Synthesize

func (c *ValueContext) Synthesize(selection ExampleSelection, generator *ExampleGenerator) ValueResult

Synthesize attempts an example only for an absent, reachable selection. Repeated calls for that occurrence return the same retained choice. Authored failures are never replaced, and LegacyValue uses this exact sampling attempt.

type ValueDiagnostic

type ValueDiagnostic struct {
	// Code is a stable machine-readable failure category.
	Code string
	// Path is an ordered authored member/index path.
	Path []string
	// Message describes the violated contract.
	Message string
}

ValueDiagnostic reports a source or projection failure without a null sentinel.

type ValueFieldPolicy

type ValueFieldPolicy struct {
	// Parent is the object attribute that owns the field.
	Parent *AttributeExpr
	// Target is the field occurrence, not its reusable declaration.
	Target *AttributeExpr
	// Name is its full authored name, disambiguating reused attribute pointers.
	Name string
	// WireName is the actual encoded member name.
	WireName string
	// Visible reports whether the target emits this member.
	Visible bool
	// Required reports whether the target contract requires the member.
	Required bool
	// Presence is the actual emitted field omission/default policy.
	Presence ValueFieldPresence
	// NumericKind is the effective scalar precision, or zero for a
	// nonnumeric member. It must agree with the finalized target type.
	NumericKind Kind
	// ImplicitDefault is the codec-owned scalar default when Presence is
	// ValueFieldImplicitDefault. Other policies must leave it nil.
	ImplicitDefault any
}

ValueFieldPolicy records the emitted representation of one target member. Parent and Target are exact finalized attribute identities, before copying.

type ValueFieldPresence

type ValueFieldPresence uint8

ValueFieldPresence identifies field-local observation and emission rules.

const (
	// ValueFieldRetain preserves present values, including empty and null.
	ValueFieldRetain ValueFieldPresence = iota + 1
	// ValueFieldOmitEmpty omits a field empty after child observation.
	ValueFieldOmitEmpty
	// ValueFieldOmitAbsent preserves explicit null/empty and omits only absence.
	ValueFieldOmitAbsent
	// ValueFieldImplicitDefault follows a codec's implicit default presence.
	ValueFieldImplicitDefault
)

type ValueIdentity

type ValueIdentity struct {
	// contains filtered or unexported fields
}

ValueIdentity is a comparable opaque identity within a generation. Its zero value identifies nothing; it is never a content hash or a generation seed.

type ValueInput

type ValueInput struct {
	// Raw is the authored value, including nil when explicitly supplied.
	Raw any
	// ExplicitNull preserves DSL null provenance rather than implying absence.
	ExplicitNull bool
	// Origin describes the authored location for diagnostics, never cache identity.
	Origin string
}

ValueInput supplies a source. Raw is copied for finite builtin values; custom values remain borrowed until target materialization. Origin is diagnostic only.

type ValueKind

type ValueKind uint8

ValueKind describes a resolved node independently of its Go representation.

const (
	// ValueKindScalar is a boolean, number, string or byte scalar.
	ValueKindScalar ValueKind = iota + 1
	// ValueKindArray is an ordered collection.
	ValueKindArray
	// ValueKindObject contains declared fields and named extras.
	ValueKindObject
	// ValueKindMap contains typed key-value entries.
	ValueKindMap
	// ValueKindUnion carries the already selected semantic branch.
	ValueKindUnion
	// ValueKindAny retains raw builtin meaning until codec materialization.
	ValueKindAny
)

type ValueMember

type ValueMember struct {
	// ID identifies the member edge within its occurrence graph.
	ID ValueIdentity
	// Name is the full authored member spelling.
	Name string
	// WireName is the expression's JSON alias, before a target policy is applied.
	WireName string
	// Occurrence carries this member's effective constraints and presence.
	Occurrence ValueOccurrence
}

ValueMember is a copied descriptor of a declared semantic object member.

type ValueOccurrence

type ValueOccurrence struct {
	// contains filtered or unexported fields
}

ValueOccurrence identifies an immutable, finalized semantic occurrence in one ValueContext. Its zero value is invalid. Named declaration reuse does not merge the validation, presence or sources of different occurrences.

func (ValueOccurrence) Branches

func (o ValueOccurrence) Branches() []ValueBranch

Branches returns ordered union alternatives, transparently following named declarations.

func (ValueOccurrence) EffectiveConstraints

func (o ValueOccurrence) EffectiveConstraints() EffectiveConstraints

EffectiveConstraints returns the immutable constraints for this occurrence.

func (ValueOccurrence) Element

func (o ValueOccurrence) Element() ValueOccurrence

Element returns the array element or map value occurrence, following named declarations.

func (ValueOccurrence) ID

ID returns a generation-local identity for this occurrence. It is not a public type name, content hash, or stable synthesis seed.

func (ValueOccurrence) Key

Key returns the map key occurrence, following named declarations.

func (ValueOccurrence) Members

func (o ValueOccurrence) Members() []ValueMember

Members returns ordered declared members. Named declarations are transparent; mutating the returned slice cannot change the captured occurrence.

func (ValueOccurrence) Underlying

func (o ValueOccurrence) Underlying() ValueOccurrence

Underlying returns the immediate underlying occurrence of a named declaration. The zero occurrence means that the receiver is not a named declaration.

type ValueOutcome

type ValueOutcome uint8

ValueOutcome distinguishes semantic success, partial examples and failures.

const (
	// ValueResolved is a successful complete semantic value.
	ValueResolved ValueOutcome = iota + 1
	// ValueIncomplete retains an example with missing required members.
	ValueIncomplete
	// ValueAmbiguous has multiple viable semantic alternatives.
	ValueAmbiguous
	// ValueInvalid violates a source contract.
	ValueInvalid
	// ValueUnsupported lies outside builtin semantic interpretation.
	ValueUnsupported
	// ValueSuppressed was excluded before resolution or synthesis.
	ValueSuppressed
)

type ValuePlan

type ValuePlan struct {
	// contains filtered or unexported fields
}

ValuePlan is an immutable target representation of a semantic occurrence. Its zero value is invalid. Codec ownership is independent of media labels.

func (ValuePlan) ForOccurrence

func (p ValuePlan) ForOccurrence(source ValueOccurrence, target ValuePlanNode) (ValuePlan, error)

ForOccurrence returns the already-captured representation associated with an exact semantic occurrence and target node. It never rebuilds a plan or infers ownership from copied attributes. Foreign, missing and ambiguous pairs are rejected.

func (ValuePlan) JSONShape

func (p ValuePlan) JSONShape() (*loom.JSONShape, error)

JSONShape lowers the captured JSON representation into a detached matching description for generated untagged codecs. It rejects opaque codecs and shapes outside the supported object/array/primitive grammar. Enum values are projected through this exact plan, retaining effective constraints and wire identity.

func (ValuePlan) MatchJSONSchema

func (p ValuePlan) MatchJSONSchema(wire jsontext.Value) (bool, error)

MatchJSONSchema checks wire membership against the captured JSON schema projection, independently of source selection and concrete Go decoding.

func (ValuePlan) Root

func (p ValuePlan) Root() ValuePlanNode

Root returns the target root after the plan's semantic member selection.

type ValuePlanBranch

type ValuePlanBranch struct {
	// Tag is the actual wire discriminator value.
	Tag string
	// Node is the immutable alternative representation.
	Node ValuePlanNode
}

ValuePlanBranch describes a target union alternative without reselecting it.

type ValuePlanMember

type ValuePlanMember struct {
	// Name is the full authored target name.
	Name string
	// WireName is the actual emitted name.
	WireName string
	// Visible reports whether the representation emits this member.
	Visible bool
	// Required reports the representation's requiredness.
	Required bool
	// Presence describes field-local omission behavior.
	Presence ValueFieldPresence
	// Node is the immutable child representation.
	Node ValuePlanNode
}

ValuePlanMember describes an actual target member, including invisible members.

type ValuePlanNode

type ValuePlanNode struct {
	// contains filtered or unexported fields
}

ValuePlanNode is an immutable representation node. Handles are comparable within a captured plan and preserve recursive graph identity. The zero handle denotes an absent child; allocation identity is not a public schema name.

func (ValuePlanNode) Attribute

func (n ValuePlanNode) Attribute() *AttributeExpr

Attribute returns an owned copy of the finalized target declaration details. Editing it cannot alter the plan. Child identity must be read through the node queries, not inferred from pointers in this copy.

func (ValuePlanNode) Branches

func (n ValuePlanNode) Branches() []ValuePlanBranch

Branches returns an owned list of target union alternatives.

func (ValuePlanNode) Codec

func (n ValuePlanNode) Codec() ValueCodec

Codec returns the actual representation owner, or zero for an absent node.

func (ValuePlanNode) Element

func (n ValuePlanNode) Element() ValuePlanNode

Element returns the array or map value representation, or an absent handle.

func (ValuePlanNode) Key

func (n ValuePlanNode) Key() ValuePlanNode

Key returns the map key representation, or an absent handle.

func (ValuePlanNode) Members

func (n ValuePlanNode) Members() []ValuePlanMember

Members returns an owned list of target object members.

func (ValuePlanNode) TargetDeclarationID

func (n ValuePlanNode) TargetDeclarationID() string

TargetDeclarationID returns the captured authored declaration identity of this target node. Controlled transport copies retain that identity when their Go names change. It is independent of the semantic source cursor, which may move through aliases at a different depth. An unnamed target returns an empty string.

func (ValuePlanNode) Underlying

func (n ValuePlanNode) Underlying() ValuePlanNode

Underlying returns the child of a named declaration, or an absent handle.

func (ValuePlanNode) UnderlyingReusesSource

func (n ValuePlanNode) UnderlyingReusesSource() bool

UnderlyingReusesSource reports whether the named-declaration edge introduces only a target representation wrapper. Its child matches the current source ancestry without consuming an authored alias. Structural target children may subsequently descend to the source's underlying shape for member identities. The role belongs to this edge, not to the potentially shared child handle.

func (ValuePlanNode) Valid

func (n ValuePlanNode) Valid() bool

Valid reports whether the handle denotes a captured target node.

type ValuePlanRequest

type ValuePlanRequest struct {
	// Target is the finalized view, body or location attribute.
	Target *AttributeExpr
	// Selection is an authored member path from the semantic root, for a
	// selected body or location. An empty path selects the root itself.
	Selection []string
	// Codec identifies the actual encoding owner, not a documentation MIME.
	Codec ValueCodec
	// Use distinguishes runtime-backed targets from documentation alone.
	Use ValuePlanUse
	// Fields supplies the actual emitter policy for every runtime object
	// member, including hidden fields. Documentation plans may omit it.
	Fields []ValueFieldPolicy
	// Containers supplies actual runtime unknown-member policy for each
	// object or union envelope, independently of schema acceptance.
	Containers []ValueContainerPolicy
	// Codecs records node-local encoding boundaries selected by the actual
	// representation owner. Unspecified descendants inherit their parent codec.
	Codecs []ValueCodecPolicy
}

ValuePlanRequest describes an already finalized effective target. It does not authorize resolving a source again or selecting a different union.

type ValuePlanUse

type ValuePlanUse uint8

ValuePlanUse identifies which target guarantees a plan must establish.

const (
	// ValuePlanRuntime requires same-wire runtime decoding guarantees.
	ValuePlanRuntime ValuePlanUse = iota + 1
	// ValuePlanDocumentation requires schema/media validity without a decoder claim.
	ValuePlanDocumentation
	// ValuePlanSchema captures structure and owned constraint declarations only.
	// It does not resolve enum values, select examples or authorize value projection.
	ValuePlanSchema
)

type ValuePresence

type ValuePresence uint8

ValuePresence distinguishes absent, null, typed nil and concrete values.

const (
	// ValueAbsent marks an unsupplied member.
	ValueAbsent ValuePresence = iota
	// ValueNull marks an explicit null.
	ValueNull
	// ValueNil marks a typed nil collection, distinguished by Kind.
	ValueNil
	// ValuePresent marks a concrete value, including zero and empty containers.
	ValuePresent
)

type ValueResult

type ValueResult struct {
	// contains filtered or unexported fields
}

ValueResult contains either a retained resolved graph or a failure outcome. Incomplete examples retain their graph and exact missing member paths.

func (ValueResult) DeclaredJSONValue

func (r ValueResult) DeclaredJSONValue() (any, bool)

DeclaredJSONValue returns the retained semantic graph as a JSON-shaped host value without encoding it. Scalars retain their declared Go precision, Bytes remain []byte, objects use finalized wire names, map keys use their JSON member spelling, and unions retain their selected tagged or untagged shape. Explicit null returns nil with true. Complete and incomplete results preserve their distinct Outcome; invalid and absent results return false. An unsupported result succeeds only when it retains a structurally known value with opaque codec leaves and no independently checkable failure. Built-in values are detached, opaque custom leaves remain borrowed, and no codec is invoked. ProjectJSON remains the API for checked target wire emission.

func (ValueResult) Diagnostics

func (r ValueResult) Diagnostics() []ValueDiagnostic

Diagnostics returns an owned copy of all diagnostic records and paths.

func (ValueResult) LegacyValue

func (r ValueResult) LegacyValue() (any, bool)

LegacyValue returns copied raw data from the same source or synthesis attempt. Its presence does not assert semantic success; compatibility callers may still observe authored values rejected by the builtin pipeline.

func (ValueResult) Missing

func (r ValueResult) Missing() [][]ValueIdentity

Missing returns copied ordered paths of required semantic member identities.

func (ValueResult) OccurrenceID

func (r ValueResult) OccurrenceID() ValueIdentity

OccurrenceID identifies the effective occurrence used for resolution.

func (ValueResult) Outcome

func (r ValueResult) Outcome() ValueOutcome

Outcome returns the semantic outcome; zero denotes an uninitialized result.

func (ValueResult) Role

func (r ValueResult) Role() ValueRole

Role returns the source completeness policy used for this resolution.

func (ValueResult) SourceID

func (r ValueResult) SourceID() ValueIdentity

SourceID preserves source identity even when semantic resolution failed.

func (ValueResult) Synthesized

func (r ValueResult) Synthesized() bool

Synthesized distinguishes generated examples from supplied authored values.

func (ValueResult) Value

func (r ValueResult) Value() (ResolvedValue, bool)

Value returns retained complete or incomplete semantic data.

type ValueRole

type ValueRole uint8

ValueRole selects the source completeness contract.

const (
	// ValueRoleExample allows partial authored documentation values.
	ValueRoleExample ValueRole = iota + 1
	// ValueRoleEnum requires a complete, valid enum member.
	ValueRoleEnum
	// ValueRoleDefault requires a complete, valid default.
	ValueRoleDefault
)

type ValueSource

type ValueSource struct {
	// contains filtered or unexported fields
}

ValueSource identifies one supplied value without assigning target semantics.

func (ValueSource) ExplicitNull

func (s ValueSource) ExplicitNull() bool

ExplicitNull reports authored DSL null provenance without conflating absence.

func (ValueSource) ID

func (s ValueSource) ID() ValueIdentity

ID returns this source's opaque identity, or zero for an absent handle.

func (ValueSource) Origin

func (s ValueSource) Origin() string

Origin returns the copied diagnostic source description, never a cache key.

type VersionHolder

type VersionHolder interface {
	SetVersion(string)
}

VersionHolder is an interface that allows expression types to receive a version. Types implementing this interface can use the Version() DSL function to set a version.

type ViewExpr

type ViewExpr struct {
	// Set of properties included in view
	*AttributeExpr
	// Name of view
	Name string
	// Parent result Type
	Parent *ResultTypeExpr
	// RequiredOverrides lists selected fields explicitly required by the view.
	RequiredOverrides []string
	// OptionalOverrides lists selected fields explicitly optional in the view.
	OptionalOverrides []string
}

ViewExpr defines which fields to render when building a response. The view is an object whose field names must match the names of the parent result type field names. The field definitions are inherited from the parent result type but may be overridden.

func (*ViewExpr) EvalName

func (v *ViewExpr) EvalName() string

EvalName returns the generic definition name used in error messages.

func (*ViewExpr) FinalizeRequiredness

func (v *ViewExpr) FinalizeRequiredness()

FinalizeRequiredness computes selected fields' effective requirements from the parent result type and the view's authored overrides. It preserves field definitions and changes only the view validation.

Source Files

Jump to

Keyboard shortcuts

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