defkit

package
v1.11.0 Latest Latest
Warning

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

Go to latest
Published: Jul 17, 2026 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Overview

Package defkit provides a Go SDK for authoring KubeVela X-Definitions. It enables platform engineers to write ComponentDefinition, TraitDefinition, PolicyDefinition, and WorkflowStepDefinition using fluent Go APIs that compile transparently to CUE.

Index

Constants

This section is empty.

Variables

View Source
var CUEImports = struct {
	Strconv  string
	Strings  string
	List     string
	Math     string
	Regexp   string
	Time     string
	Struct   string
	Encoding string
}{
	Strconv:  "strconv",
	Strings:  "strings",
	List:     "list",
	Math:     "math",
	Regexp:   "regexp",
	Time:     "time",
	Struct:   "struct",
	Encoding: "encoding/json",
}

CUEImports defines standard imports that may be needed in CUE definitions.

Functions

func Clear

func Clear()

Clear resets the registry. This is primarily useful for testing.

func Count

func Count() int

Count returns the number of registered definitions.

func CustomStatusExpr

func CustomStatusExpr(expr StatusExpression) string

CustomStatusExpr is a convenience function for component definitions. It creates a StatusBuilder with the given expression and returns it for use with CustomStatus(). Example: CustomStatusExpr(Status().Concat("Ready: ", s.Field("status.ready")))

func HealthPolicy

func HealthPolicy(expr HealthExpression) string

HealthPolicy wraps a HealthExpression and generates the complete healthPolicy CUE block.

func Register

func Register(def Definition)

Register adds a definition to the global registry. This is typically called from init() functions in definition packages.

Register validates placement constraints and panics if they are conflicting (e.g., the same condition in both RunOn and NotRunOn). This ensures configuration errors are caught early during initialization.

Example usage:

func init() {
    defkit.Register(Webservice())
}

func RewriteRawCUEName

func RewriteRawCUEName(rawCUE, newName string) string

RewriteRawCUEName rewrites the first definition name in a raw CUE string to use the specified name. This handles patterns like:

  • "old-name": { ... } -> "new-name": { ... }
  • "old-name.v1": { ... } -> "new-name": { ... }

The function finds the first quoted string followed by a colon and replaces it.

func StatusAnd

func StatusAnd(conditions ...string) string

StatusAnd combines conditions with &&.

func StatusEq

func StatusEq(left, right string) string

StatusEq is a helper for equality conditions in status expressions. Usage: .HealthyWhen(StatusEq("desired.replicas", "ready.replicas"))

func StatusGte

func StatusGte(left, right string) string

StatusGte is a helper for >= conditions in status expressions.

func StatusOr

func StatusOr(conditions ...string) string

StatusOr combines conditions with ||.

func StatusPolicy

func StatusPolicy(expr StatusExpression) string

StatusPolicy wraps a StatusExpression and generates the complete customStatus CUE block.

Switch and HealthAware expressions need the multi-branch rendering produced by their BuildFull() methods — emitting only the default through the generic `message: <expr>` path would silently drop every case / unhealthy branch. CustomStatusExpr applies the same special-casing; keeping them aligned means the two entry points always render identical CUE for the same expression.

func ToJSON

func ToJSON() ([]byte, error)

ToJSON serializes all registered definitions to JSON. This is used by the generated main program to output definitions.

Types

type AbsentOrEmptyCondition

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

AbsentOrEmptyCondition fires when a collection parameter is either absent (parameter["X"] == _|_) or set and empty (len(parameter["X"]) == 0).

CUE cannot express "absent OR empty" as a single boolean expression: `||` is strict in both operands, and `len(_|_)` propagates bottom. The condition is therefore expanded at render time into two separate if blocks, each emitting the same body — CUE unifies same-path/same-value writes.

func (*AbsentOrEmptyCondition) Branches

func (c *AbsentOrEmptyCondition) Branches() []Condition

Branches returns the two simpler conditions equivalent to this OR:

  1. field absent (Not(IsSet))
  2. field set and empty (LenCondition == 0)

Render paths that handle compound emission expand into both branches; paths that don't (e.g. unknown contexts) fall back to conditionToCUE which renders only the "set and empty" branch.

func (*AbsentOrEmptyCondition) ParamName

func (c *AbsentOrEmptyCondition) ParamName() string

ParamName returns the parameter name being checked.

type AllConditionsCondition

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

AllConditionsCondition is a compound condition that requires all sub-conditions to be true.

func AllConditions

func AllConditions(conditions ...Condition) *AllConditionsCondition

AllConditions creates a compound condition that requires all sub-conditions to be true. This generates CUE: if cond1 if cond2 if cond3 { ... }

Example:

// Apply only if cpu AND memory are set AND requests AND limits are NOT set
tpl.Patch().
    SetIf(defkit.AllConditions(
        defkit.ParamIsSet("cpu"),
        defkit.ParamIsSet("memory"),
        defkit.ParamNotSet("requests"),
        defkit.ParamNotSet("limits"),
    ), "spec.resources", resourceStruct)

func (*AllConditionsCondition) Conditions

func (a *AllConditionsCondition) Conditions() []Condition

Conditions returns the list of sub-conditions.

type AndCondition

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

AndCondition represents a binary logical AND of two conditions. This is an internal IR type used by cuegen to combine conditions during code generation. For the user-facing API, use And() which accepts variadic conditions via LogicalExpr.

type ArrayBuilder

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

ArrayBuilder builds CUE arrays with static items, conditional items, and for-each items. This is the core type for building arrays where some items are always present, some are conditional, and some come from iteration.

Example:

NewArray().
    Item(cpuMetric).
    ItemIf(mem.IsSet(), memMetric).
    ForEachGuarded(podCustomMetrics.IsSet(), podCustomMetrics, customMetric)

func NewArray

func NewArray() *ArrayBuilder

NewArray creates a new ArrayBuilder.

func (*ArrayBuilder) Entries

func (a *ArrayBuilder) Entries() []arrayEntry

Entries returns all entries in the array builder.

func (*ArrayBuilder) ForEach

func (a *ArrayBuilder) ForEach(source Value, elem *ArrayElement) *ArrayBuilder

ForEach adds an iterated item to the array. For each element in source, an item is created using the element template. In the element template, use Reference("m.field") to reference iteration variable fields.

func (*ArrayBuilder) ForEachGuarded

func (a *ArrayBuilder) ForEachGuarded(guard Condition, source Value, elem *ArrayElement) *ArrayBuilder

ForEachGuarded adds a guarded iterated item to the array. The guard condition (typically source.IsSet()) wraps the for loop. Generates: if guard for m in source { item }

func (*ArrayBuilder) ForEachWith

func (a *ArrayBuilder) ForEachWith(source Value, fn func(item *ItemBuilder)) *ArrayBuilder

ForEachWith adds a complex iterated item to the array, using an ItemBuilder callback for per-item operations like conditionals, let bindings, and defaults. Uses "v" as the default iteration variable name.

func (*ArrayBuilder) ForEachWithGuardedFiltered

func (a *ArrayBuilder) ForEachWithGuardedFiltered(guard Condition, filter Predicate, source Value, fn func(item *ItemBuilder)) *ArrayBuilder

ForEachWithGuardedFiltered adds a guarded and filtered complex iterated item to the array. The guard condition wraps the for loop, and the filter predicate filters iteration items. Generates: if guard for v in source if filter { ... }

func (*ArrayBuilder) ForEachWithGuardedFilteredVar

func (a *ArrayBuilder) ForEachWithGuardedFilteredVar(varName string, guard Condition, filter Predicate, source Value, fn func(item *ItemBuilder)) *ArrayBuilder

ForEachWithGuardedFilteredVar is like ForEachWithGuardedFiltered but allows specifying the iteration variable name.

func (*ArrayBuilder) ForEachWithVar

func (a *ArrayBuilder) ForEachWithVar(varName string, source Value, fn func(item *ItemBuilder)) *ArrayBuilder

ForEachWithVar is like ForEachWith but allows specifying the iteration variable name.

func (*ArrayBuilder) Item

func (a *ArrayBuilder) Item(elem *ArrayElement) *ArrayBuilder

Item adds an always-present item to the array.

func (*ArrayBuilder) ItemIf

func (a *ArrayBuilder) ItemIf(cond Condition, elem *ArrayElement) *ArrayBuilder

ItemIf adds a conditional item to the array. The item is only included when the condition is true.

type ArrayConcatValue

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

ArrayConcatValue represents an array concatenation. Renders as list.Concat([left, right]) so it remains evaluatable on CUE v0.11+, which removed the list-addition `+` operator. Used for expressions like list.Concat([[items], parameter.extraVolumeMounts]).

func ArrayConcat

func ArrayConcat(left, right Value) *ArrayConcatValue

ArrayConcat creates an array concatenation expression. Generates CUE: list.Concat([left, right])

CUE v0.11 removed the list-addition `+` operator (see https://cuelang.org/e/v0.11-list-arithmetic); modern KubeVela runtimes reject `[a] + [b]` and require list.Concat instead.

func (*ArrayConcatValue) Left

func (a *ArrayConcatValue) Left() Value

Left returns the left operand.

func (*ArrayConcatValue) RequiredImports

func (a *ArrayConcatValue) RequiredImports() []string

RequiredImports returns the CUE imports required by ArrayConcatValue. ArrayConcatValue renders as list.Concat([left, right]) which needs "list".

func (*ArrayConcatValue) Right

func (a *ArrayConcatValue) Right() Value

Right returns the right operand.

type ArrayContainsCondition

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

ArrayContainsCondition checks if an array parameter contains a specific value. Generates: list.Contains(parameter.name, value)

func (*ArrayContainsCondition) ParamName

func (c *ArrayContainsCondition) ParamName() string

ParamName returns the parameter name being checked.

func (*ArrayContainsCondition) RequiredImports

func (c *ArrayContainsCondition) RequiredImports() []string

RequiredImports returns the CUE imports required by ArrayContainsCondition. list.Contains requires the "list" package.

func (*ArrayContainsCondition) Value

func (c *ArrayContainsCondition) Value() any

Value returns the value to check for.

type ArrayElement

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

ArrayElement represents a single element in an array patch. Used for building array values with struct elements.

func NewArrayElement

func NewArrayElement() *ArrayElement

NewArrayElement creates a new array element builder.

func (*ArrayElement) FieldOrder

func (a *ArrayElement) FieldOrder() []string

FieldOrder returns field names in insertion order.

func (*ArrayElement) Fields

func (a *ArrayElement) Fields() map[string]Value

Fields returns all fields set on this element.

func (*ArrayElement) Ops

func (a *ArrayElement) Ops() []ResourceOp

Ops returns any conditional operations.

func (*ArrayElement) PatchKeyField

func (a *ArrayElement) PatchKeyField(field string, key string, value Value) *ArrayElement

PatchKeyField adds a patchKey-annotated array field to the array element. This generates within the element:

// +patchKey=key
field: value

Used for nested patchKey annotations inside array elements, e.g., volumeMounts with patchKey=name inside a containers element.

func (*ArrayElement) PatchKeyFields

func (a *ArrayElement) PatchKeyFields() []patchKeyField

PatchKeyFields returns the patchKey-annotated fields.

func (*ArrayElement) Set

func (a *ArrayElement) Set(key string, value Value) *ArrayElement

Set sets a field on the array element.

func (*ArrayElement) SetIf

func (a *ArrayElement) SetIf(cond Condition, key string, value Value) *ArrayElement

SetIf conditionally sets a field on the array element.

type ArrayParam

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

ArrayParam represents an array/list parameter.

func Array

func Array(name string) *ArrayParam

Array creates a new array parameter with the given name.

func IntList

func IntList(name string) *ArrayParam

IntList creates an integer array parameter.

func List

func List(name string) *ArrayParam

List creates a generic list parameter (array of any).

func StringList

func StringList(name string) *ArrayParam

StringList creates a string array parameter.

func (*ArrayParam) Contains

func (p *ArrayParam) Contains(val any) Condition

Contains creates a condition that checks if this array contains a specific value. Example: tags.Contains("gpu") generates: parameter["tags"] != _|_ if list.Contains(parameter["tags"], "gpu")

func (*ArrayParam) Default

func (p *ArrayParam) Default(value []any) *ArrayParam

Default sets a default value for the parameter.

func (*ArrayParam) Description

func (p *ArrayParam) Description(desc string) *ArrayParam

Description sets the parameter description.

func (*ArrayParam) ElementType

func (p *ArrayParam) ElementType() ParamType

ElementType returns the array element type.

func (*ArrayParam) Eq

func (p *ArrayParam) Eq(val any) Condition

Eq creates a condition that compares this parameter to a literal value. Example: replicas.Eq(3) generates: parameter.replicas == 3

func (*ArrayParam) GetDefault

func (p *ArrayParam) GetDefault() any

func (*ArrayParam) GetDescription

func (p *ArrayParam) GetDescription() string

func (*ArrayParam) GetFields

func (p *ArrayParam) GetFields() []Param

GetFields returns the field definitions for array elements.

func (*ArrayParam) GetMaxItems

func (p *ArrayParam) GetMaxItems() *int

GetMaxItems returns the maximum items constraint, or nil if not set.

func (*ArrayParam) GetMinItems

func (p *ArrayParam) GetMinItems() *int

GetMinItems returns the minimum items constraint, or nil if not set.

func (*ArrayParam) GetSchema

func (p *ArrayParam) GetSchema() string

GetSchema returns the raw CUE schema for array elements.

func (*ArrayParam) GetSchemaRef

func (p *ArrayParam) GetSchemaRef() string

GetSchemaRef returns the schema reference for this parameter.

func (*ArrayParam) GetShort

func (p *ArrayParam) GetShort() string

func (*ArrayParam) GetValidators

func (p *ArrayParam) GetValidators() []*Validator

GetValidators returns the validators for this array parameter.

func (*ArrayParam) Gt

func (p *ArrayParam) Gt(val any) Condition

Gt creates a condition that checks if this parameter is greater than a value. Example: replicas.Gt(1) generates: parameter.replicas > 1

func (*ArrayParam) Gte

func (p *ArrayParam) Gte(val any) Condition

Gte creates a condition that checks if this parameter is greater than or equal to a value. Example: replicas.Gte(1) generates: parameter.replicas >= 1

func (*ArrayParam) HasDefault

func (p *ArrayParam) HasDefault() bool

func (*ArrayParam) HasNotEmpty

func (p *ArrayParam) HasNotEmpty() bool

HasNotEmpty returns true if elements must be non-empty.

func (*ArrayParam) IsEmpty

func (p *ArrayParam) IsEmpty() Condition

IsEmpty creates a condition that checks if this array is absent or empty. Renders as two separate if blocks: one for `parameter["X"] == _|_` (absent) and one for `parameter["X"] != _|_ if len(parameter["X"]) == 0` (set and empty). Both blocks emit the same body; CUE unifies same-path writes.

func (*ArrayParam) IsIgnore

func (p *ArrayParam) IsIgnore() bool

func (*ArrayParam) IsNotEmpty

func (p *ArrayParam) IsNotEmpty() Condition

IsNotEmpty creates a condition that checks if this array is set and non-empty. Example: tags.IsNotEmpty() generates: parameter["tags"] != _|_ if len(parameter["tags"]) > 0

func (*ArrayParam) IsOptional

func (p *ArrayParam) IsOptional() bool

func (*ArrayParam) IsRequired

func (p *ArrayParam) IsRequired() bool

func (*ArrayParam) IsSet

func (p *ArrayParam) IsSet() Condition

IsSet returns a condition that checks if the parameter has a value. This is used with SetIf for conditional field assignment.

func (*ArrayParam) LenEq

func (p *ArrayParam) LenEq(n int) Condition

LenEq creates a condition that checks if this array has exactly n elements. Example: tags.LenEq(5) generates: parameter["tags"] != _|_ if len(parameter["tags"]) == 5

LenEq(0) is treated as "absent OR empty" — equivalent to IsEmpty(). It returns an AbsentOrEmptyCondition that the renderer expands into two if blocks (one for absent, one for set-and-empty).

func (*ArrayParam) LenGt

func (p *ArrayParam) LenGt(n int) Condition

LenGt creates a condition that checks if this array has more than n elements. Example: tags.LenGt(0) generates: parameter["tags"] != _|_ if len(parameter["tags"]) > 0

func (*ArrayParam) LenGte

func (p *ArrayParam) LenGte(n int) Condition

LenGte creates a condition that checks if this array has n or more elements. Example: tags.LenGte(1) generates: parameter["tags"] != _|_ if len(parameter["tags"]) >= 1

func (*ArrayParam) LenLt

func (p *ArrayParam) LenLt(n int) Condition

LenLt creates a condition that checks if this array has fewer than n elements. Example: tags.LenLt(10) generates: parameter["tags"] != _|_ if len(parameter["tags"]) < 10

func (*ArrayParam) LenLte

func (p *ArrayParam) LenLte(n int) Condition

LenLte creates a condition that checks if this array has n or fewer elements. Example: tags.LenLte(10) generates: parameter["tags"] != _|_ if len(parameter["tags"]) <= 10

func (*ArrayParam) Lt

func (p *ArrayParam) Lt(val any) Condition

Lt creates a condition that checks if this parameter is less than a value. Example: replicas.Lt(10) generates: parameter.replicas < 10

func (*ArrayParam) Lte

func (p *ArrayParam) Lte(val any) Condition

Lte creates a condition that checks if this parameter is less than or equal to a value. Example: replicas.Lte(10) generates: parameter.replicas <= 10

func (*ArrayParam) MaxItems

func (p *ArrayParam) MaxItems(n int) *ArrayParam

MaxItems sets the maximum number of items constraint for the array. This generates CUE like: list.MaxItems(n)

func (*ArrayParam) MinItems

func (p *ArrayParam) MinItems(n int) *ArrayParam

MinItems sets the minimum number of items constraint for the array. This generates CUE like: list.MinItems(n)

func (*ArrayParam) Name

func (p *ArrayParam) Name() string

func (*ArrayParam) Ne

func (p *ArrayParam) Ne(val any) Condition

Ne creates a condition that checks if this parameter is not equal to a value. Example: status.Ne("error") generates: parameter.status != "error"

func (*ArrayParam) NotEmpty

func (p *ArrayParam) NotEmpty() *ArrayParam

NotEmpty adds a !="" constraint to each string element of the array. Changes [...string] to [...(string & !="")]. Only applies to string-typed arrays; silently ignored for other element types. Consistent with StringParam.NotEmpty(). Example: StringList("x").NotEmpty() produces [...(string & !="")]

func (*ArrayParam) NotSet

func (p *ArrayParam) NotSet() Condition

NotSet returns a condition that checks if the parameter is not set. This generates `if parameter["name"] == _|_` in CUE.

func (*ArrayParam) Of

func (p *ArrayParam) Of(elemType ParamType) *ArrayParam

Of specifies the element type for the array.

func (*ArrayParam) OfEnum

func (p *ArrayParam) OfEnum(values ...string) *ArrayParam

OfEnum is a convenience method for arrays of enum values. It sets the schema to [...("val1" | "val2" | ...)]. Example: Array("methods").OfEnum("GET", "POST") emits: [...("GET" | "POST")]

func (*ArrayParam) Optional

func (p *ArrayParam) Optional() *ArrayParam

Optional marks the parameter as optional, emitting the "?" CUE marker.

func (*ArrayParam) Required

func (p *ArrayParam) Required() *ArrayParam

Required marks the parameter as required in input, emitting the "!" CUE marker.

func (*ArrayParam) RequiredImports

func (p *ArrayParam) RequiredImports() []string

RequiredImports returns the CUE imports needed by this parameter's constraints. MinItems/MaxItems generate list.MinItems()/list.MaxItems() which require "list".

func (*ArrayParam) Validators

func (p *ArrayParam) Validators(validators ...*Validator) *ArrayParam

Validators adds validation rules to this array parameter. Validators are emitted inside each array element struct as _validate* blocks.

func (*ArrayParam) WithFields

func (p *ArrayParam) WithFields(fields ...Param) *ArrayParam

WithFields adds field definitions for structured array elements. This allows defining the schema for objects within the array.

func (*ArrayParam) WithSchema

func (p *ArrayParam) WithSchema(schema string) *ArrayParam

WithSchema sets a raw CUE schema for the array elements. This takes precedence over WithFields for schema generation.

func (*ArrayParam) WithSchemaRef

func (p *ArrayParam) WithSchemaRef(ref string) *ArrayParam

WithSchemaRef sets a reference to a helper type definition (e.g., "#HealthProbe"). This is used when the schema is defined elsewhere as a helper definition.

type BoolParam

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

BoolParam represents a boolean parameter.

func Bool

func Bool(name string) *BoolParam

Bool creates a new boolean parameter with the given name.

func (*BoolParam) Default

func (p *BoolParam) Default(value bool) *BoolParam

Default sets a default value for the parameter.

func (*BoolParam) Description

func (p *BoolParam) Description(desc string) *BoolParam

Description sets the parameter description.

func (*BoolParam) Eq

func (p *BoolParam) Eq(val any) Condition

Eq creates a condition that compares this parameter to a literal value. Example: replicas.Eq(3) generates: parameter.replicas == 3

func (*BoolParam) GetDefault

func (p *BoolParam) GetDefault() any

func (*BoolParam) GetDescription

func (p *BoolParam) GetDescription() string

func (*BoolParam) GetShort

func (p *BoolParam) GetShort() string

func (*BoolParam) Gt

func (p *BoolParam) Gt(val any) Condition

Gt creates a condition that checks if this parameter is greater than a value. Example: replicas.Gt(1) generates: parameter.replicas > 1

func (*BoolParam) Gte

func (p *BoolParam) Gte(val any) Condition

Gte creates a condition that checks if this parameter is greater than or equal to a value. Example: replicas.Gte(1) generates: parameter.replicas >= 1

func (*BoolParam) HasDefault

func (p *BoolParam) HasDefault() bool

func (*BoolParam) Ignore

func (p *BoolParam) Ignore() *BoolParam

Ignore marks the parameter as ignored by the UI. This generates a // +ignore directive in the CUE output.

func (*BoolParam) IsFalse

func (p *BoolParam) IsFalse() Condition

IsFalse returns a condition that checks if the bool parameter is falsy. In CUE, this generates `if !parameter.name` instead of `if parameter.name == false`.

func (*BoolParam) IsIgnore

func (p *BoolParam) IsIgnore() bool

func (*BoolParam) IsOptional

func (p *BoolParam) IsOptional() bool

func (*BoolParam) IsRequired

func (p *BoolParam) IsRequired() bool

func (*BoolParam) IsSet

func (p *BoolParam) IsSet() Condition

IsSet returns a condition that checks if the parameter has a value. This is used with SetIf for conditional field assignment.

func (*BoolParam) IsTrue

func (p *BoolParam) IsTrue() Condition

IsTrue returns a condition that checks if the bool parameter is truthy. In CUE, this generates `if parameter.name` instead of `if parameter.name == true`.

func (*BoolParam) Lt

func (p *BoolParam) Lt(val any) Condition

Lt creates a condition that checks if this parameter is less than a value. Example: replicas.Lt(10) generates: parameter.replicas < 10

func (*BoolParam) Lte

func (p *BoolParam) Lte(val any) Condition

Lte creates a condition that checks if this parameter is less than or equal to a value. Example: replicas.Lte(10) generates: parameter.replicas <= 10

func (*BoolParam) Name

func (p *BoolParam) Name() string

func (*BoolParam) Ne

func (p *BoolParam) Ne(val any) Condition

Ne creates a condition that checks if this parameter is not equal to a value. Example: status.Ne("error") generates: parameter.status != "error"

func (*BoolParam) NotSet

func (p *BoolParam) NotSet() Condition

NotSet returns a condition that checks if the parameter is not set. This generates `if parameter["name"] == _|_` in CUE.

func (*BoolParam) Optional

func (p *BoolParam) Optional() *BoolParam

Optional marks the parameter as optional, emitting the "?" CUE marker.

func (*BoolParam) Required

func (p *BoolParam) Required() *BoolParam

Required marks the parameter as required in input, emitting the "!" CUE marker.

func (*BoolParam) Short

func (p *BoolParam) Short(s string) *BoolParam

Short sets a short flag alias for the parameter. This generates a // +short=X directive in the CUE output.

type BuiltinAction

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

BuiltinAction represents a call to a vela builtin.

type BuiltinActionBuilder

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

BuiltinActionBuilder builds a builtin action.

func (*BuiltinActionBuilder) Build

Build finalizes the action and adds it to the template.

func (*BuiltinActionBuilder) If

If makes this action conditional.

func (*BuiltinActionBuilder) WithDirectFields

func (b *BuiltinActionBuilder) WithDirectFields() *BuiltinActionBuilder

WithDirectFields renders fields directly on the struct without the $params wrapper. This is used for op.# operations (e.g., op.#ShareCloudResource, op.#DeployCloudResource) that take fields as direct struct members rather than inside $params.

func (*BuiltinActionBuilder) WithFullParameter

func (b *BuiltinActionBuilder) WithFullParameter() *BuiltinActionBuilder

WithFullParameter passes the entire parameter object as $params. This generates: $params: parameter Useful for builtins (e.g., builtin.#Suspend) that accept all step parameters directly.

func (*BuiltinActionBuilder) WithParams

func (b *BuiltinActionBuilder) WithParams(params map[string]Value) *BuiltinActionBuilder

WithParams sets parameters for the builtin.

type CUEConditionRenderer

type CUEConditionRenderer interface {
	RenderCUEWithCondition(renderValue func(Value) string, renderCondition func(Condition) string) string
}

CUEConditionRenderer extends CUERenderer with condition rendering support. Builders that need to render Condition values should implement this interface. The CUE generator will prefer this over CUERenderer when available.

type CUEFunc

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

CUEFunc represents a call to a CUE standard library function.

func ListConcat

func ListConcat(lists ...Value) *CUEFunc

ListConcat creates a list.Concat(lists...) expression. In CUE: list.Concat([list1, list2, ...])

func StrconvFormatInt

func StrconvFormatInt(v Value, base int) *CUEFunc

StrconvFormatInt creates a strconv.FormatInt(v, base) expression. In CUE: strconv.FormatInt(v, 10)

func StringsHasPrefix

func StringsHasPrefix(s Value, prefix string) *CUEFunc

StringsHasPrefix creates a strings.HasPrefix(s, prefix) expression. In CUE: strings.HasPrefix(s, prefix)

func StringsHasSuffix

func StringsHasSuffix(s Value, suffix string) *CUEFunc

StringsHasSuffix creates a strings.HasSuffix(s, suffix) expression. In CUE: strings.HasSuffix(s, suffix)

func StringsToLower

func StringsToLower(v Value) *CUEFunc

StringsToLower creates a strings.ToLower(v) expression. In CUE: strings.ToLower(v)

func StringsToUpper

func StringsToUpper(v Value) *CUEFunc

StringsToUpper creates a strings.ToUpper(v) expression. In CUE: strings.ToUpper(v)

func (*CUEFunc) Args

func (c *CUEFunc) Args() []Value

Args returns the function arguments.

func (*CUEFunc) Function

func (c *CUEFunc) Function() string

Function returns the function name.

func (*CUEFunc) Package

func (c *CUEFunc) Package() string

Package returns the CUE package name.

func (*CUEFunc) RequiredImports

func (c *CUEFunc) RequiredImports() []string

RequiredImports returns the CUE imports required by this function call.

type CUEGenerator

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

CUEGenerator generates CUE definitions from Go component definitions.

func NewCUEGenerator

func NewCUEGenerator() *CUEGenerator

NewCUEGenerator creates a new CUE generator.

func (*CUEGenerator) GenerateFullDefinition

func (g *CUEGenerator) GenerateFullDefinition(c *ComponentDefinition) string

GenerateFullDefinition generates the complete CUE definition from a component.

func (*CUEGenerator) GenerateParameterSchema

func (g *CUEGenerator) GenerateParameterSchema(c *ComponentDefinition) string

GenerateParameterSchema generates the CUE parameter schema from a component definition. This generates only the `parameter: { ... }` block for comparison with original CUE.

func (*CUEGenerator) GenerateTemplate

func (g *CUEGenerator) GenerateTemplate(c *ComponentDefinition) string

GenerateTemplate generates the CUE template block from a component's template function. The template block contains: helpers, output, outputs, parameter, and helper definitions. The order follows KubeVela conventions:

  1. Primary helpers (before output) - mountsArray, volumesList, deDupVolumesList
  2. output: block - the main resource
  3. Auxiliary helpers (after output) - exposePorts and similar helpers used by outputs
  4. outputs: block - auxiliary resources like Service
  5. parameter: block - parameter schema
  6. Helper type definitions - #HealthProbe and similar

func (*CUEGenerator) WithImports

func (g *CUEGenerator) WithImports(imports ...string) *CUEGenerator

WithImports adds CUE imports to the generator. Usage: gen.WithImports(CUEImports.Strconv, CUEImports.Strings)

func (*CUEGenerator) WriteHelperDefinition

func (g *CUEGenerator) WriteHelperDefinition(sb *strings.Builder, def HelperDefinition, depth int)

WriteHelperDefinition writes a CUE helper type definition like #HealthProbe. This method is exported so it can be used by policy and workflow step generators.

type CUERenderer

type CUERenderer interface {
	RenderCUE(renderValue func(Value) string) string
}

CUERenderer is implemented by builder types that can render themselves to CUE. The renderValue function is provided by the CUE generator to render nested Value types.

type ClosedStructOption

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

ClosedStructOption represents one option in a closed struct disjunction. It holds a set of struct fields that will be wrapped in close({...}).

func ClosedStruct

func ClosedStruct() *ClosedStructOption

ClosedStruct creates a new closed struct option for use in ClosedUnion.

func (*ClosedStructOption) GetFields

func (c *ClosedStructOption) GetFields() []*StructField

GetFields returns the fields of this closed struct option.

func (*ClosedStructOption) WithFields

func (c *ClosedStructOption) WithFields(fields ...*StructField) *ClosedStructOption

WithFields adds fields to the closed struct option.

type ClosedUnionParam

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

ClosedUnionParam represents a closed struct disjunction parameter. It generates CUE of the form: close({...}) | close({...})

func ClosedUnion

func ClosedUnion(name string) *ClosedUnionParam

ClosedUnion creates a new closed struct disjunction parameter.

func (*ClosedUnionParam) Description

func (p *ClosedUnionParam) Description(desc string) *ClosedUnionParam

Description sets the parameter description.

func (*ClosedUnionParam) Eq

func (p *ClosedUnionParam) Eq(val any) Condition

Eq creates a condition that compares this parameter to a literal value. Example: replicas.Eq(3) generates: parameter.replicas == 3

func (*ClosedUnionParam) GetDefault

func (p *ClosedUnionParam) GetDefault() any

func (*ClosedUnionParam) GetDescription

func (p *ClosedUnionParam) GetDescription() string

func (*ClosedUnionParam) GetOptions

func (p *ClosedUnionParam) GetOptions() []*ClosedStructOption

GetOptions returns the closed struct options.

func (*ClosedUnionParam) GetShort

func (p *ClosedUnionParam) GetShort() string

func (*ClosedUnionParam) Gt

func (p *ClosedUnionParam) Gt(val any) Condition

Gt creates a condition that checks if this parameter is greater than a value. Example: replicas.Gt(1) generates: parameter.replicas > 1

func (*ClosedUnionParam) Gte

func (p *ClosedUnionParam) Gte(val any) Condition

Gte creates a condition that checks if this parameter is greater than or equal to a value. Example: replicas.Gte(1) generates: parameter.replicas >= 1

func (*ClosedUnionParam) HasDefault

func (p *ClosedUnionParam) HasDefault() bool

func (*ClosedUnionParam) IsIgnore

func (p *ClosedUnionParam) IsIgnore() bool

func (*ClosedUnionParam) IsOptional

func (p *ClosedUnionParam) IsOptional() bool

func (*ClosedUnionParam) IsRequired

func (p *ClosedUnionParam) IsRequired() bool

func (*ClosedUnionParam) IsSet

func (p *ClosedUnionParam) IsSet() Condition

IsSet returns a condition that checks if the parameter has a value. This is used with SetIf for conditional field assignment.

func (*ClosedUnionParam) Lt

func (p *ClosedUnionParam) Lt(val any) Condition

Lt creates a condition that checks if this parameter is less than a value. Example: replicas.Lt(10) generates: parameter.replicas < 10

func (*ClosedUnionParam) Lte

func (p *ClosedUnionParam) Lte(val any) Condition

Lte creates a condition that checks if this parameter is less than or equal to a value. Example: replicas.Lte(10) generates: parameter.replicas <= 10

func (*ClosedUnionParam) Name

func (p *ClosedUnionParam) Name() string

func (*ClosedUnionParam) Ne

func (p *ClosedUnionParam) Ne(val any) Condition

Ne creates a condition that checks if this parameter is not equal to a value. Example: status.Ne("error") generates: parameter.status != "error"

func (*ClosedUnionParam) NotSet

func (p *ClosedUnionParam) NotSet() Condition

NotSet returns a condition that checks if the parameter is not set. This generates `if parameter["name"] == _|_` in CUE.

func (*ClosedUnionParam) Optional

func (p *ClosedUnionParam) Optional() *ClosedUnionParam

Optional marks the parameter as optional.

func (*ClosedUnionParam) Options

func (p *ClosedUnionParam) Options(options ...*ClosedStructOption) *ClosedUnionParam

Options sets the closed struct alternatives for the disjunction.

func (*ClosedUnionParam) Required

func (p *ClosedUnionParam) Required() *ClosedUnionParam

Required marks the parameter as required.

type ClusterVersionRef

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

ClusterVersionRef provides access to cluster version components.

func (*ClusterVersionRef) GitVersion

func (c *ClusterVersionRef) GitVersion() *ContextRef

GitVersion returns the full git version string.

func (*ClusterVersionRef) Major

func (c *ClusterVersionRef) Major() *ContextRef

Major returns the major version component.

func (*ClusterVersionRef) Minor

func (c *ClusterVersionRef) Minor() *ContextRef

Minor returns the minor version component.

func (*ClusterVersionRef) Patch

func (c *ClusterVersionRef) Patch() *ContextRef

Patch returns the patch version component.

func (*ClusterVersionRef) Path

func (c *ClusterVersionRef) Path() string

Path returns the base path for cluster version.

type CollectionOp

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

CollectionOp represents an operation on a collection (array/list).

func Each

func Each(source Value) *CollectionOp

Each creates a collection operation pipeline from a list parameter. Usage: ports.Each().Filter(...).Map(...).Pick(...)

func From

func From(source Value) *CollectionOp

From creates a collection operation pipeline from a source value. This is an alias for Each, providing a more readable API for transformations. Usage: From(volumes).Map(FieldMap{"mountPath": F("path"), "name": F("name")})

func (*CollectionOp) All

func (c *CollectionOp) All(items []any) iter.Seq[map[string]any]

All returns an iterator over all items after applying operations. This is a Go 1.23 range-over-function iterator that can be used in for-range loops. Example: for item := range col.All() { ... }

func (*CollectionOp) AllPairs

func (c *CollectionOp) AllPairs(items []any) iter.Seq2[int, map[string]any]

AllPairs returns a key-value iterator with index and item. This is a Go 1.23 iter.Seq2 that provides (index, item) pairs. Example: for i, item := range col.AllPairs() { ... }

func (*CollectionOp) Collect

func (c *CollectionOp) Collect(items []any) []map[string]any

Collect materializes the iterator into a slice. Uses Go 1.23 slices.Collect for efficient collection.

func (*CollectionOp) Count

func (c *CollectionOp) Count(items []any) int

Count returns the number of items after applying operations.

func (*CollectionOp) Dedupe

func (c *CollectionOp) Dedupe(keyField string) *CollectionOp

Dedupe removes duplicate items by a key field, keeping the first occurrence.

func (*CollectionOp) DefaultField

func (c *CollectionOp) DefaultField(field string, defaultVal FieldValue) *CollectionOp

DefaultField sets a default value for a field if not present. Usage: .DefaultField("name", Format("port-%d", Field("port")))

func (*CollectionOp) Filter

func (c *CollectionOp) Filter(pred Predicate) *CollectionOp

Filter keeps only items matching the predicate. Usage: .Filter(Field("expose").Eq(true))

func (*CollectionOp) FilterCond

func (c *CollectionOp) FilterCond(cond Condition) *CollectionOp

FilterCond keeps only items matching a Condition expression. The condition is used for CUE generation (generates an `if condition` guard); runtime apply is a passthrough since Condition is a CUE-level concept.

func (*CollectionOp) First

func (c *CollectionOp) First(items []any) map[string]any

First returns the first item after applying operations, or nil if empty.

func (*CollectionOp) Flatten

func (c *CollectionOp) Flatten() *CollectionOp

Flatten flattens nested collections from multiple sources. Used for volumeMounts which has pvc, configMap, secret, etc.

func (*CollectionOp) GetGuard

func (c *CollectionOp) GetGuard() Condition

GetGuard returns the guard condition, if any.

func (*CollectionOp) Guard

func (c *CollectionOp) Guard(cond Condition) *CollectionOp

Guard adds a guard condition that wraps the entire comprehension. When the guard is set, the generated CUE is:

[if guard for v in source if filter {v}]

This is used when the source may not exist and needs a protective condition (e.g., if parameter.privileges != _|_).

func (*CollectionOp) Map

func (c *CollectionOp) Map(mappings FieldMap) *CollectionOp

Map transforms each item using the given field mappings. Usage: .Map(Fields{"containerPort": Field("port"), "name": Field("name")})

func (*CollectionOp) MapVariant

func (c *CollectionOp) MapVariant(discriminator, variantName string, mappings FieldMap) *CollectionOp

MapVariant adds a conditional field mapping that only applies when the iteration variable's discriminator field equals the given variant name. Generates: if v.discriminator == "variantName" { ...mappings... } Usage: .MapVariant("type", "pvc", FieldMap{"persistentVolumeClaim.claimName": FieldRef("claimName")})

func (*CollectionOp) Operations

func (c *CollectionOp) Operations() []collectionOperation

Operations returns the operations to apply.

func (*CollectionOp) Pick

func (c *CollectionOp) Pick(fields ...string) *CollectionOp

Pick selects only the specified fields from each item. Usage: .Pick("name", "mountPath")

func (*CollectionOp) Rename

func (c *CollectionOp) Rename(from, to string) *CollectionOp

Rename renames a field in each item. Usage: .Rename("port", "containerPort")

func (*CollectionOp) Source

func (c *CollectionOp) Source() Value

Source returns the source value.

func (*CollectionOp) Wrap

func (c *CollectionOp) Wrap(key string) *CollectionOp

Wrap wraps each item value under a new key. Usage: .Wrap("name") transforms "secret1" to {name: "secret1"}

type CompOp

type CompOp string

CompOp represents a comparison operator.

const (
	// OpEq represents equality (==)
	OpEq CompOp = "=="
	// OpNe represents inequality (!=)
	OpNe CompOp = "!="
	// OpLt represents less than (<)
	OpLt CompOp = "<"
	// OpLe represents less than or equal (<=)
	OpLe CompOp = "<="
	// OpGt represents greater than (>)
	OpGt CompOp = ">"
	// OpGe represents greater than or equal (>=)
	OpGe CompOp = ">="
)

type Comparison

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

Comparison represents a comparison between two expressions.

func Eq

func Eq(left, right Expr) *Comparison

Eq creates an equality comparison.

func Ge

func Ge(left, right Expr) *Comparison

Ge creates a greater-than-or-equal comparison.

func Gt

func Gt(left, right Expr) *Comparison

Gt creates a greater-than comparison.

func Le

func Le(left, right Expr) *Comparison

Le creates a less-than-or-equal comparison.

func Lt

func Lt(left, right Expr) *Comparison

Lt creates a less-than comparison.

func Ne

func Ne(left, right Expr) *Comparison

Ne creates an inequality comparison.

func (*Comparison) Left

func (c *Comparison) Left() Expr

Left returns the left-hand side expression.

func (*Comparison) Op

func (c *Comparison) Op() CompOp

Op returns the comparison operator.

func (*Comparison) Right

func (c *Comparison) Right() Expr

Right returns the right-hand side expression.

type ComponentDefinition

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

ComponentDefinition represents a KubeVela ComponentDefinition.

ComponentDefinition embeds baseDefinition for common fields and methods shared with TraitDefinition and other definition types.

func Components

func Components() []*ComponentDefinition

Components returns all registered ComponentDefinitions.

func NewComponent

func NewComponent(name string) *ComponentDefinition

NewComponent creates a new ComponentDefinition builder.

func (*ComponentDefinition) Annotations

func (c *ComponentDefinition) Annotations(annotations map[string]string) *ComponentDefinition

Annotations sets metadata annotations on the component definition.

func (*ComponentDefinition) AutodetectWorkload

func (c *ComponentDefinition) AutodetectWorkload() *ComponentDefinition

AutodetectWorkload sets the workload type to "autodetects.core.oam.dev". This is used for components where the workload type is auto-detected at runtime rather than being statically defined.

func (*ComponentDefinition) ChildResourceKind

func (c *ComponentDefinition) ChildResourceKind(apiVersion, kind string, selector map[string]string) *ComponentDefinition

ChildResourceKind adds a child resource kind entry to the component definition. Multiple calls accumulate entries.

func (*ComponentDefinition) ConditionalParams

func (c *ComponentDefinition) ConditionalParams(block *ConditionalParamBlock) *ComponentDefinition

ConditionalParams adds a conditional parameter block to the component. This allows parameters to change shape based on a discriminator value.

func (*ComponentDefinition) CustomStatus

func (c *ComponentDefinition) CustomStatus(expr string) *ComponentDefinition

CustomStatus sets the custom status CUE expression for the component. This expression is used to compute a human-readable status message.

func (*ComponentDefinition) DefName

func (c *ComponentDefinition) DefName() string

DefName implements Definition.DefName - returns the definition name.

func (*ComponentDefinition) DefType

func (c *ComponentDefinition) DefType() DefinitionType

DefType implements Definition.DefType - returns the definition type.

func (*ComponentDefinition) Description

func (c *ComponentDefinition) Description(desc string) *ComponentDefinition

Description sets the component description.

func (*ComponentDefinition) GetAnnotations

func (b *ComponentDefinition) GetAnnotations() map[string]string

GetAnnotations returns the annotations map.

func (*ComponentDefinition) GetChildResourceKinds

func (c *ComponentDefinition) GetChildResourceKinds() []common.ChildResourceKind

GetChildResourceKinds returns all accumulated child resource kind entries.

func (*ComponentDefinition) GetConditionalParamBlocks

func (b *ComponentDefinition) GetConditionalParamBlocks() []*ConditionalParamBlock

GetConditionalParamBlocks returns the conditional parameter blocks.

func (*ComponentDefinition) GetCustomStatus

func (b *ComponentDefinition) GetCustomStatus() string

GetCustomStatus returns the custom status CUE expression.

func (*ComponentDefinition) GetDescription

func (b *ComponentDefinition) GetDescription() string

GetDescription returns the definition description.

func (*ComponentDefinition) GetHealthPolicy

func (b *ComponentDefinition) GetHealthPolicy() string

GetHealthPolicy returns the health policy CUE expression.

func (*ComponentDefinition) GetHelperDefinitions

func (b *ComponentDefinition) GetHelperDefinitions() []HelperDefinition

GetHelperDefinitions returns all helper type definitions.

func (*ComponentDefinition) GetImports

func (b *ComponentDefinition) GetImports() []string

GetImports returns the CUE imports.

func (*ComponentDefinition) GetLabels

func (c *ComponentDefinition) GetLabels() map[string]string

GetLabels returns the component's metadata labels.

func (*ComponentDefinition) GetName

func (b *ComponentDefinition) GetName() string

GetName returns the definition name.

func (*ComponentDefinition) GetNotRunOn

func (b *ComponentDefinition) GetNotRunOn() []placement.Condition

GetNotRunOn returns the NotRunOn placement conditions.

func (*ComponentDefinition) GetParams

func (b *ComponentDefinition) GetParams() []Param

GetParams returns all parameter definitions.

func (*ComponentDefinition) GetPlacement

func (b *ComponentDefinition) GetPlacement() placement.PlacementSpec

GetPlacement returns the complete placement spec for this definition.

func (*ComponentDefinition) GetPodSpecPath

func (c *ComponentDefinition) GetPodSpecPath() string

GetPodSpecPath returns the pod spec path.

func (*ComponentDefinition) GetRawCUE

func (b *ComponentDefinition) GetRawCUE() string

GetRawCUE returns the raw CUE template if set.

func (*ComponentDefinition) GetRawCUEWithName

func (b *ComponentDefinition) GetRawCUEWithName() string

GetRawCUEWithName returns the raw CUE with the definition name rewritten to match the name set via NewComponent/NewTrait/etc. This ensures the name passed to the fluent builder takes precedence over any name embedded in the raw CUE string.

func (*ComponentDefinition) GetRunOn

func (b *ComponentDefinition) GetRunOn() []placement.Condition

GetRunOn returns the RunOn placement conditions.

func (*ComponentDefinition) GetStatusDetails

func (b *ComponentDefinition) GetStatusDetails() string

GetStatusDetails returns the status details CUE expression.

func (*ComponentDefinition) GetTemplate

func (b *ComponentDefinition) GetTemplate() func(tpl *Template)

GetTemplate returns the template function.

func (*ComponentDefinition) GetValidators

func (b *ComponentDefinition) GetValidators() []*Validator

GetValidators returns the top-level validators.

func (*ComponentDefinition) GetVersion

func (b *ComponentDefinition) GetVersion() string

GetVersion returns the version string.

func (*ComponentDefinition) GetWorkload

func (c *ComponentDefinition) GetWorkload() WorkloadType

GetWorkload returns the workload type.

func (*ComponentDefinition) HasPlacement

func (b *ComponentDefinition) HasPlacement() bool

HasPlacement returns true if the definition has any placement constraints.

func (*ComponentDefinition) HasRawCUE

func (b *ComponentDefinition) HasRawCUE() bool

HasRawCUE returns true if raw CUE is set.

func (*ComponentDefinition) HasTemplate

func (b *ComponentDefinition) HasTemplate() bool

HasTemplate returns true if the definition has a template function set.

func (*ComponentDefinition) HealthPolicy

func (c *ComponentDefinition) HealthPolicy(expr string) *ComponentDefinition

HealthPolicy sets the health policy CUE expression for the component. This expression determines whether the component is healthy. For raw CUE strings, use this method directly. For composable health expressions, use HealthPolicyExpr with Health().

func (*ComponentDefinition) HealthPolicyExpr

func (c *ComponentDefinition) HealthPolicyExpr(expr HealthExpression) *ComponentDefinition

HealthPolicyExpr sets the health policy using a composable HealthExpression. This allows building health checks programmatically using primitives like Condition, Field, Phase, Exists, And, Or, Not via Health().

Example:

h := defkit.Health()
def.HealthPolicyExpr(h.Condition("Ready").IsTrue())
def.HealthPolicyExpr(h.AllTrue("Ready", "Synced"))
def.HealthPolicyExpr(h.And(
    h.Condition("Ready").IsTrue(),
    h.Field("status.replicas").Gt(0),
))

func (*ComponentDefinition) Helper

func (c *ComponentDefinition) Helper(name string, param Param) *ComponentDefinition

Helper adds a helper type definition using fluent API. The param defines the schema for the helper type. Example:

Helper("HealthProbe", defkit.Object("probe").WithFields(...))

func (*ComponentDefinition) IsOmitWorkloadType

func (c *ComponentDefinition) IsOmitWorkloadType() bool

IsOmitWorkloadType returns whether workload type should be suppressed in CUE output.

func (*ComponentDefinition) Labels

func (c *ComponentDefinition) Labels(labels map[string]string) *ComponentDefinition

Labels sets metadata labels on the component definition. Usage: component.Labels(map[string]string{"ui-hidden": "true"})

func (*ComponentDefinition) NotRunOn

func (c *ComponentDefinition) NotRunOn(conditions ...placement.Condition) *ComponentDefinition

NotRunOn adds placement conditions specifying which clusters this definition should NOT run on. Use the placement package's fluent API to build conditions.

Example:

defkit.NewComponent("no-vclusters").
    NotRunOn(placement.Label("cluster-type").Eq("vcluster"))

If any NotRunOn condition matches, the definition is ineligible for that cluster.

func (*ComponentDefinition) OmitWorkloadType

func (c *ComponentDefinition) OmitWorkloadType() *ComponentDefinition

OmitWorkloadType suppresses the auto-generated workload.type field in the CUE output. Use this when the vela source CUE does not include a workload type field.

func (*ComponentDefinition) Param

Param adds a single parameter definition to the component. This provides a more fluent API when adding parameters one at a time.

func (*ComponentDefinition) Params

func (c *ComponentDefinition) Params(params ...Param) *ComponentDefinition

Params adds multiple parameter definitions to the component.

func (*ComponentDefinition) PodSpecPath

func (c *ComponentDefinition) PodSpecPath(path string) *ComponentDefinition

PodSpecPath sets the pod spec path for the component definition.

func (*ComponentDefinition) RawCUE

RawCUE sets raw CUE for complex component definitions that don't fit the builder pattern. When set, this bypasses all other template settings and outputs the raw CUE directly.

func (*ComponentDefinition) Render

Render executes the component template with the given test context and returns the rendered primary output resource.

func (*ComponentDefinition) RenderAll

RenderAll executes the component template and returns all outputs.

func (*ComponentDefinition) RunOn

RunOn adds placement conditions specifying which clusters this definition should run on. Use the placement package's fluent API to build conditions.

Example:

defkit.NewComponent("eks-only").
    RunOn(placement.Label("provider").Eq("aws")).
    RunOn(placement.Label("cluster-type").NotEq("vcluster"))

Multiple RunOn calls are combined with AND semantics (all conditions must match).

func (*ComponentDefinition) StatusDetails

func (c *ComponentDefinition) StatusDetails(details string) *ComponentDefinition

StatusDetails sets the status details CUE expression for the component.

func (*ComponentDefinition) Template

func (c *ComponentDefinition) Template(fn func(tpl *Template)) *ComponentDefinition

Template sets the template function for the component.

func (*ComponentDefinition) ToCue

func (c *ComponentDefinition) ToCue() string

ToCue generates the complete CUE definition string for this component. This is a convenience method that creates a CUEGenerator and calls GenerateFullDefinition.

func (*ComponentDefinition) ToCueWithImports

func (c *ComponentDefinition) ToCueWithImports(imports ...string) string

ToCueWithImports generates the CUE definition with the specified imports. Use this when the definition requires CUE standard library imports. Example: component.ToCueWithImports(CUEImports.Strconv, CUEImports.List)

func (*ComponentDefinition) ToParameterSchema

func (c *ComponentDefinition) ToParameterSchema() string

ToParameterSchema generates only the parameter schema block. This is useful for testing or comparing parameter schemas.

func (*ComponentDefinition) ToYAML

func (c *ComponentDefinition) ToYAML() ([]byte, error)

ToYAML generates the Kubernetes YAML representation of the ComponentDefinition. This produces a ComponentDefinition custom resource that can be applied to a cluster. Note: The CUE template is embedded in the spec.schematic.cue field.

func (*ComponentDefinition) Validators

func (c *ComponentDefinition) Validators(validators ...*Validator) *ComponentDefinition

Validators adds top-level parameter validators to the component. These validators are emitted inside the parameter: { ... } block as _validate* variables.

func (*ComponentDefinition) Version

Version sets the version string for the component definition.

func (*ComponentDefinition) WithImports

func (c *ComponentDefinition) WithImports(imports ...string) *ComponentDefinition

WithImports adds CUE imports to the component definition. Usage: component.WithImports("strconv", "strings", "list")

func (*ComponentDefinition) Workload

func (c *ComponentDefinition) Workload(apiVersion, kind string) *ComponentDefinition

Workload sets the workload type for this component.

type CompoundOptionalField

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

CompoundOptionalField includes a field value only if the field exists AND an additional condition is met. Generates CUE: if v.field != _|_ if additionalCond { fieldName: v.field }

func OptionalFieldWithCond

func OptionalFieldWithCond(field string, cond Condition) *CompoundOptionalField

OptionalFieldWithCond creates a field reference that includes the field only when both the field exists and the additional condition is satisfied. Generates CUE: if v.field != _|_ if cond { fieldName: v.field }

type ConcatExprValue

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

ConcatExprValue represents a concatenation expression for array helpers. This is used for generating: mountsArray.pvc + mountsArray.configMap + ...

func ConcatExpr

func ConcatExpr(source *StructArrayHelper, fields ...string) *ConcatExprValue

ConcatExpr creates a concatenation expression from a struct array helper. This generates CUE like: mountsArray.pvc + mountsArray.configMap + mountsArray.secret + ... Used when setting volumeMounts on containers.

Usage:

SetIf(volumeMounts.IsSet(), "spec.containers[0].volumeMounts",
    defkit.ConcatExpr(mountsArray, "pvc", "configMap", "secret", "emptyDir", "hostPath"))

func (*ConcatExprValue) Fields

func (c *ConcatExprValue) Fields() []string

Fields returns the field names to concatenate.

func (*ConcatExprValue) Source

func (c *ConcatExprValue) Source() *StructArrayHelper

Source returns the source struct array helper.

type ConcatHelper

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

ConcatHelper represents a list.Concat helper that combines arrays from a struct.

func (*ConcatHelper) FieldRefs

func (c *ConcatHelper) FieldRefs() []string

FieldRefs returns the field references to concatenate.

func (*ConcatHelper) HelperName

func (c *ConcatHelper) HelperName() string

HelperName returns the helper name.

func (*ConcatHelper) RequiredImports

func (c *ConcatHelper) RequiredImports() []string

RequiredImports returns the CUE imports required by ConcatHelper. ConcatHelper uses list.Concat which requires the "list" import.

func (*ConcatHelper) Source

func (c *ConcatHelper) Source() *StructArrayHelper

Source returns the source struct helper.

type ConcatHelperBuilder

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

ConcatHelperBuilder provides a fluent API for building list.Concat helpers.

func (*ConcatHelperBuilder) Build

func (b *ConcatHelperBuilder) Build() *ConcatHelper

Build finalizes the concat helper and registers it with the template.

func (*ConcatHelperBuilder) Fields

func (b *ConcatHelperBuilder) Fields(fields ...string) *ConcatHelperBuilder

Fields adds field references to concatenate.

type Condition

type Condition interface {
	Expr
	// contains filtered or unexported methods
}

Condition represents a boolean expression used in conditionals. Conditions can be composed using And(), Or(), and Not().

func HasExposedPorts

func HasExposedPorts(ports Value) Condition

HasExposedPorts creates a condition that checks if any port has expose=true. This is used to conditionally create Service outputs.

func ItemFieldIsSet

func ItemFieldIsSet(field string) Condition

ItemFieldIsSet returns a condition that checks if a field is set in the current iteration item. This generates CUE: v.fieldName != _|_ Used with PickIf for conditionally including fields.

Example:

.Pick("name", "mountPath").
.PickIf(ItemFieldIsSet("subPath"), "subPath")

type ConditionExpr

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

ConditionExpr checks a condition in status.conditions[] array.

func (*ConditionExpr) Exists

func (c *ConditionExpr) Exists() HealthExpression

Exists checks if the condition exists (regardless of status).

func (*ConditionExpr) Is

func (c *ConditionExpr) Is(status string) HealthExpression

Is checks if the condition status matches the expected value.

func (*ConditionExpr) IsFalse

func (c *ConditionExpr) IsFalse() HealthExpression

IsFalse checks if the condition status is "False".

func (*ConditionExpr) IsTrue

func (c *ConditionExpr) IsTrue() HealthExpression

IsTrue checks if the condition status is "True".

func (*ConditionExpr) Preamble

func (c *ConditionExpr) Preamble() string

func (*ConditionExpr) ReasonIs

func (c *ConditionExpr) ReasonIs(reason string) HealthExpression

ReasonIs checks if the condition has a specific reason.

func (*ConditionExpr) ToCUE

func (c *ConditionExpr) ToCUE() string

type ConditionalAction

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

ConditionalAction represents a conditional workflow action.

type ConditionalBranch

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

ConditionalBranch represents a single branch in a conditional parameter block. It contains a guard condition, parameters to emit when active, and optional validators.

func WhenParam

func WhenParam(cond Condition) *ConditionalBranch

WhenParam creates a new conditional branch with the given guard condition.

func (*ConditionalBranch) Condition

func (b *ConditionalBranch) Condition() Condition

Condition returns the branch's guard condition.

func (*ConditionalBranch) GetParams

func (b *ConditionalBranch) GetParams() []Param

GetParams returns the branch's parameters.

func (*ConditionalBranch) GetValidators

func (b *ConditionalBranch) GetValidators() []*Validator

GetValidators returns the branch's validators.

func (*ConditionalBranch) Params

func (b *ConditionalBranch) Params(params ...Param) *ConditionalBranch

Params sets the parameters emitted when this branch's condition is true.

func (*ConditionalBranch) Validators

func (b *ConditionalBranch) Validators(validators ...*Validator) *ConditionalBranch

Validators adds validators emitted inside this branch's conditional block.

type ConditionalOrFieldRef

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

ConditionalOrFieldRef represents a field reference with a conditional fallback. Instead of generating CUE default syntax (*v.field | fallback), it generates two if/else blocks for the field.

type ConditionalParamBlock

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

ConditionalParamBlock represents a set of conditional parameter branches. Each branch has a guard condition and emits different parameters when active.

Example:

ConditionalParams(
    WhenParam(existingResources.Eq(false)).Params(
        defkit.Bool("forceDestroy").Default(false),
    ),
    WhenParam(existingResources.Eq(true)).Params(
        defkit.Bool("forceDestroy").Optional(),
    ),
)

Emits:

if existingResources == false {
    forceDestroy: *false | bool
}
if existingResources == true {
    forceDestroy?: bool
}

func ConditionalParams

func ConditionalParams(branches ...*ConditionalBranch) *ConditionalParamBlock

ConditionalParams creates a new conditional parameter block from branches.

func (*ConditionalParamBlock) Branches

func (b *ConditionalParamBlock) Branches() []*ConditionalBranch

Branches returns all conditional branches.

type ConditionalStructOp

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

ConditionalStructOp represents a conditional struct block emitted in the output. When the condition is true, the struct builder function is called to generate CUE fields at the given path.

Example:

output.ConditionalStruct(replConfig.IsSet(), "spec.replicationConfiguration", func(b *OutputStructBuilder) {
    b.Set("role", defkit.Ref("parameter.replicationConfiguration.role"))
})

Emits:

if parameter["replicationConfiguration"] != _|_ {
    spec: replicationConfiguration: {
        role: parameter.replicationConfiguration.role
    }
}

func (*ConditionalStructOp) Builder

func (c *ConditionalStructOp) Builder() func(b *OutputStructBuilder)

Builder returns the struct builder function.

func (*ConditionalStructOp) Cond

func (c *ConditionalStructOp) Cond() Condition

Cond returns the condition.

func (*ConditionalStructOp) Path

func (c *ConditionalStructOp) Path() string

Path returns the output path.

type ContextOutputExistsCondition

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

ContextOutputExistsCondition checks if a path exists in context.output.

func ContextOutputExists

func ContextOutputExists(path string) *ContextOutputExistsCondition

ContextOutputExists creates a condition that checks if a path exists in context.output. This generates CUE: context.output.path != _|_

Example:

// Only patch if workload has spec.template (Deployment/StatefulSet)
tpl.Patch().
    SetIf(defkit.ContextOutputExists("spec.template"), "spec.template.spec.replicas", defkit.ParamRef("replicas"))

func (*ContextOutputExistsCondition) Path

Path returns the path being checked.

type ContextOutputRef

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

ContextOutputRef represents a reference to context.output for trait introspection. Traits can use this to conditionally apply patches based on the workload's structure.

func ContextOutput

func ContextOutput() *ContextOutputRef

ContextOutput returns a reference to the component's output (context.output). Use this in traits to introspect the workload being modified.

Example:

// Check if workload has spec.template (like Deployment)
hasTemplate := ContextOutput().HasPath("spec.template")
tpl.Patch().
    If(hasTemplate).
        Set("spec.template.metadata.labels", labels).
    EndIf()

func (*ContextOutputRef) Field

func (c *ContextOutputRef) Field(path string) *ContextOutputRef

Field returns a reference to a specific field in context.output. Example: ContextOutput().Field("spec.template.spec.containers")

func (*ContextOutputRef) HasPath

func (c *ContextOutputRef) HasPath(path string) Condition

HasPath returns a condition that checks if a path exists in context.output. This generates CUE: context.output.path != _|_

Example:

hasTemplate := ContextOutput().HasPath("spec.template")

func (*ContextOutputRef) IsSet

func (c *ContextOutputRef) IsSet() Condition

IsSet returns a condition that checks if this context path exists.

func (*ContextOutputRef) Path

func (c *ContextOutputRef) Path() string

Path returns the full CUE path for this reference.

type ContextPathExistsCondition

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

ContextPathExistsCondition checks if a path exists in context.output.

func (*ContextPathExistsCondition) BasePath

func (c *ContextPathExistsCondition) BasePath() string

BasePath returns the base path (e.g., "context.output").

func (*ContextPathExistsCondition) FieldPath

func (c *ContextPathExistsCondition) FieldPath() string

FieldPath returns the field path being checked.

func (*ContextPathExistsCondition) FullPath

func (c *ContextPathExistsCondition) FullPath() string

FullPath returns the complete path.

type ContextRef

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

ContextRef represents a reference to a context value. Context values are runtime values provided by KubeVela.

func (*ContextRef) Path

func (c *ContextRef) Path() string

Path returns the CUE path for this context reference.

func (*ContextRef) String

func (c *ContextRef) String() string

String returns the path as a placeholder string for template building. This is used when building raw values that need context references.

type ConvertStringBuilder

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

ConvertStringBuilder builds a util.#ConvertString operation fluently.

func ConvertString

func ConvertString(input Value) *ConvertStringBuilder

ConvertString creates a new util.#ConvertString builder.

func (*ConvertStringBuilder) RenderCUE

func (b *ConvertStringBuilder) RenderCUE(rv func(Value) string) string

RenderCUE renders the builder to a CUE string.

type DedupeHelper

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

DedupeHelper represents a deduplication helper that removes duplicates by key.

func (*DedupeHelper) HelperName

func (d *DedupeHelper) HelperName() string

HelperName returns the helper name.

func (*DedupeHelper) KeyField

func (d *DedupeHelper) KeyField() string

KeyField returns the field to dedupe by.

func (*DedupeHelper) Source

func (d *DedupeHelper) Source() Value

Source returns the source to deduplicate.

type DedupeHelperBuilder

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

DedupeHelperBuilder provides a fluent API for building deduplication helpers.

func (*DedupeHelperBuilder) Build

func (b *DedupeHelperBuilder) Build() *DedupeHelper

Build finalizes the dedupe helper and registers it with the template.

func (*DedupeHelperBuilder) ByKey

ByKey sets the key field to deduplicate by.

type Definition

type Definition interface {
	// DefName returns the definition's name (e.g., "webservice", "scaler").
	DefName() string
	// DefType returns the definition type (component, trait, policy, workflow-step).
	DefType() DefinitionType
	// ToCue generates the complete CUE template for this definition.
	ToCue() string
	// ToYAML generates the Kubernetes CR YAML for this definition.
	ToYAML() ([]byte, error)
	// GetPlacement returns the placement constraints for this definition.
	GetPlacement() placement.PlacementSpec
	// HasPlacement returns true if the definition has placement constraints.
	HasPlacement() bool
}

Definition is the interface that all KubeVela X-Definitions implement. This interface enables runtime discovery and registry-based loading.

func All

func All() []Definition

All returns all registered definitions.

type DefinitionOutput

type DefinitionOutput struct {
	Name      string           `json:"name"`
	Type      DefinitionType   `json:"type"`
	CUE       string           `json:"cue"`
	Placement *PlacementOutput `json:"placement,omitempty"`
}

DefinitionOutput represents a single definition in the registry output.

type DefinitionType

type DefinitionType string

DefinitionType represents the type of a KubeVela definition.

const (
	// DefinitionTypeComponent is a ComponentDefinition
	DefinitionTypeComponent DefinitionType = "component"
	// DefinitionTypeTrait is a TraitDefinition
	DefinitionTypeTrait DefinitionType = "trait"
	// DefinitionTypePolicy is a PolicyDefinition
	DefinitionTypePolicy DefinitionType = "policy"
	// DefinitionTypeWorkflowStep is a WorkflowStepDefinition
	DefinitionTypeWorkflowStep DefinitionType = "workflow-step"
)

type DirectiveOp

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

DirectiveOp records a CUE directive annotation on a field path. The directive string (e.g. "patchKey=ip") is rendered as // +patchKey=ip.

func (*DirectiveOp) GetDirective

func (d *DirectiveOp) GetDirective() string

GetDirective returns the directive string.

func (*DirectiveOp) Path

func (d *DirectiveOp) Path() string

Path returns the field path.

type DynamicMapParam

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

DynamicMapParam represents a parameter where the parameter itself is a dynamic map. In CUE: parameter: [string]: T (where T is the value type) This is used for traits like labels where all user values become map keys.

func DynamicMap

func DynamicMap() *DynamicMapParam

DynamicMap creates a new dynamic map parameter. This is used when the entire parameter schema is a map with dynamic keys. Generates CUE like: parameter: [string]: string | null

Example usage:

defkit.DynamicMap().ValueType(defkit.ParamTypeString)  // parameter: [string]: string
defkit.DynamicMap().ValueTypeUnion("string | null")   // parameter: [string]: string | null

func (*DynamicMapParam) Description

func (p *DynamicMapParam) Description(desc string) *DynamicMapParam

Description sets the parameter description.

func (*DynamicMapParam) Eq

func (p *DynamicMapParam) Eq(val any) Condition

Eq creates a condition that compares this parameter to a literal value. Example: replicas.Eq(3) generates: parameter.replicas == 3

func (*DynamicMapParam) GetDefault

func (p *DynamicMapParam) GetDefault() any

func (*DynamicMapParam) GetDescription

func (p *DynamicMapParam) GetDescription() string

func (*DynamicMapParam) GetShort

func (p *DynamicMapParam) GetShort() string

func (*DynamicMapParam) GetValueType

func (p *DynamicMapParam) GetValueType() ParamType

GetValueType returns the value type for this dynamic map.

func (*DynamicMapParam) GetValueTypeUnion

func (p *DynamicMapParam) GetValueTypeUnion() string

GetValueTypeUnion returns the union type string if set.

func (*DynamicMapParam) Gt

func (p *DynamicMapParam) Gt(val any) Condition

Gt creates a condition that checks if this parameter is greater than a value. Example: replicas.Gt(1) generates: parameter.replicas > 1

func (*DynamicMapParam) Gte

func (p *DynamicMapParam) Gte(val any) Condition

Gte creates a condition that checks if this parameter is greater than or equal to a value. Example: replicas.Gte(1) generates: parameter.replicas >= 1

func (*DynamicMapParam) HasDefault

func (p *DynamicMapParam) HasDefault() bool

func (*DynamicMapParam) IsDynamicMap

func (p *DynamicMapParam) IsDynamicMap() bool

IsDynamicMap returns true (used for type detection).

func (*DynamicMapParam) IsIgnore

func (p *DynamicMapParam) IsIgnore() bool

func (*DynamicMapParam) IsOptional

func (p *DynamicMapParam) IsOptional() bool

func (*DynamicMapParam) IsRequired

func (p *DynamicMapParam) IsRequired() bool

func (*DynamicMapParam) IsSet

func (p *DynamicMapParam) IsSet() Condition

IsSet returns a condition that checks if the parameter has a value. This is used with SetIf for conditional field assignment.

func (*DynamicMapParam) Lt

func (p *DynamicMapParam) Lt(val any) Condition

Lt creates a condition that checks if this parameter is less than a value. Example: replicas.Lt(10) generates: parameter.replicas < 10

func (*DynamicMapParam) Lte

func (p *DynamicMapParam) Lte(val any) Condition

Lte creates a condition that checks if this parameter is less than or equal to a value. Example: replicas.Lte(10) generates: parameter.replicas <= 10

func (*DynamicMapParam) Name

func (p *DynamicMapParam) Name() string

func (*DynamicMapParam) Ne

func (p *DynamicMapParam) Ne(val any) Condition

Ne creates a condition that checks if this parameter is not equal to a value. Example: status.Ne("error") generates: parameter.status != "error"

func (*DynamicMapParam) NotSet

func (p *DynamicMapParam) NotSet() Condition

NotSet returns a condition that checks if the parameter is not set. This generates `if parameter["name"] == _|_` in CUE.

func (*DynamicMapParam) ValueType

func (p *DynamicMapParam) ValueType(t ParamType) *DynamicMapParam

ValueType sets the value type for the dynamic map.

func (*DynamicMapParam) ValueTypeUnion

func (p *DynamicMapParam) ValueTypeUnion(union string) *DynamicMapParam

ValueTypeUnion sets a union type for the values (e.g., "string | null").

type EnumParam

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

EnumParam represents an enumeration parameter with allowed values.

func Enum

func Enum(name string) *EnumParam

Enum creates a new enum parameter with the given name.

func (*EnumParam) Default

func (p *EnumParam) Default(value string) *EnumParam

Default sets a default value for the parameter.

func (*EnumParam) Description

func (p *EnumParam) Description(desc string) *EnumParam

Description sets the parameter description.

func (*EnumParam) Eq

func (p *EnumParam) Eq(val any) Condition

Eq creates a condition that compares this parameter to a literal value. Example: replicas.Eq(3) generates: parameter.replicas == 3

func (*EnumParam) GetDefault

func (p *EnumParam) GetDefault() any

func (*EnumParam) GetDescription

func (p *EnumParam) GetDescription() string

func (*EnumParam) GetShort

func (p *EnumParam) GetShort() string

func (*EnumParam) GetValues

func (p *EnumParam) GetValues() []string

GetValues returns the allowed enum values.

func (*EnumParam) Gt

func (p *EnumParam) Gt(val any) Condition

Gt creates a condition that checks if this parameter is greater than a value. Example: replicas.Gt(1) generates: parameter.replicas > 1

func (*EnumParam) Gte

func (p *EnumParam) Gte(val any) Condition

Gte creates a condition that checks if this parameter is greater than or equal to a value. Example: replicas.Gte(1) generates: parameter.replicas >= 1

func (*EnumParam) HasDefault

func (p *EnumParam) HasDefault() bool

func (*EnumParam) Ignore

func (p *EnumParam) Ignore() *EnumParam

Ignore marks the parameter as ignored by the UI. This generates a // +ignore directive in the CUE output.

func (*EnumParam) IsIgnore

func (p *EnumParam) IsIgnore() bool

func (*EnumParam) IsOptional

func (p *EnumParam) IsOptional() bool

func (*EnumParam) IsRequired

func (p *EnumParam) IsRequired() bool

func (*EnumParam) IsSet

func (p *EnumParam) IsSet() Condition

IsSet returns a condition that checks if the parameter has a value. This is used with SetIf for conditional field assignment.

func (*EnumParam) Lt

func (p *EnumParam) Lt(val any) Condition

Lt creates a condition that checks if this parameter is less than a value. Example: replicas.Lt(10) generates: parameter.replicas < 10

func (*EnumParam) Lte

func (p *EnumParam) Lte(val any) Condition

Lte creates a condition that checks if this parameter is less than or equal to a value. Example: replicas.Lte(10) generates: parameter.replicas <= 10

func (*EnumParam) Name

func (p *EnumParam) Name() string

func (*EnumParam) Ne

func (p *EnumParam) Ne(val any) Condition

Ne creates a condition that checks if this parameter is not equal to a value. Example: status.Ne("error") generates: parameter.status != "error"

func (*EnumParam) NotSet

func (p *EnumParam) NotSet() Condition

NotSet returns a condition that checks if the parameter is not set. This generates `if parameter["name"] == _|_` in CUE.

func (*EnumParam) Optional

func (p *EnumParam) Optional() *EnumParam

Optional marks the parameter as optional, emitting the "?" CUE marker.

func (*EnumParam) Required

func (p *EnumParam) Required() *EnumParam

Required marks the parameter as required in input, emitting the "!" CUE marker.

func (*EnumParam) Short

func (p *EnumParam) Short(s string) *EnumParam

Short sets a short flag alias for the parameter. This generates a // +short=X directive in the CUE output.

func (*EnumParam) Values

func (p *EnumParam) Values(values ...string) *EnumParam

Values sets the allowed enum values.

type Expr

type Expr interface {
	// contains filtered or unexported methods
}

Expr represents any expression that can be used in a template. This includes parameter references, context references, literals, and compound expressions.

type FailBuilder

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

FailBuilder builds a builtin.#Fail operation fluently.

func Fail

func Fail(message Value) *FailBuilder

Fail creates a new builtin.#Fail builder with the given message.

func (*FailBuilder) RenderCUE

func (b *FailBuilder) RenderCUE(rv func(Value) string) string

RenderCUE renders the builder to a CUE string.

type FalsyCondition

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

FalsyCondition represents a falsy check on a boolean parameter. In CUE, this generates `if !parameter.name`.

func (*FalsyCondition) ParamName

func (f *FalsyCondition) ParamName() string

ParamName returns the parameter name being checked.

type FieldEq

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

FieldEq checks if a field equals a value.

func FieldEquals

func FieldEquals(field string, value any) FieldEq

FieldEquals creates a field equality predicate.

type FieldIsSet

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

FieldIsSet checks if a field is set (not nil).

func FieldExists

func FieldExists(field string) FieldIsSet

FieldExists creates a field-is-set predicate.

type FieldMap

type FieldMap map[string]FieldValue

FieldMap defines field mappings for Map operation.

func (FieldMap) All

func (fm FieldMap) All() iter.Seq2[string, FieldValue]

All returns an iterator over all key-value pairs using Go 1.23 maps.All. Example: for key, val := range fm.All() { ... }

func (FieldMap) Keys

func (fm FieldMap) Keys() iter.Seq[string]

Keys returns an iterator over all keys using Go 1.23 maps.Keys. Example: for key := range fm.Keys() { ... }

func (FieldMap) Values

func (fm FieldMap) Values() iter.Seq[FieldValue]

Values returns an iterator over all values using Go 1.23 maps.Values. Example: for val := range fm.Values() { ... }

type FieldRef

type FieldRef string

FieldRef references a field from the current item in collection operations.

func F

func F(name string) FieldRef

F creates a field reference for use in Map operations. This is a convenience function that creates a FieldRef. Usage: From(volumes).Map(FieldMap{"mountPath": F("path")})

func (FieldRef) Or

func (f FieldRef) Or(fallback FieldValue) *OrFieldRef

Or provides a fallback if the field is nil or empty. Generates CUE like: *v.field | fallback

func (FieldRef) OrConditional

func (f FieldRef) OrConditional(fallback FieldValue) *ConditionalOrFieldRef

OrConditional provides a fallback using if/else blocks instead of default syntax. Generates CUE like:

if v.field != _|_ { name: v.field }
if v.field == _|_ { name: fallbackExpr }

type FieldValue

type FieldValue interface {
	// contains filtered or unexported methods
}

FieldValue represents a value to use in field mapping.

type FloatParam

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

FloatParam represents a floating-point number parameter.

func Float

func Float(name string) *FloatParam

Float creates a new float parameter with the given name.

func (*FloatParam) Default

func (p *FloatParam) Default(value float64) *FloatParam

Default sets a default value for the parameter.

func (*FloatParam) Description

func (p *FloatParam) Description(desc string) *FloatParam

Description sets the parameter description.

func (*FloatParam) Eq

func (p *FloatParam) Eq(val any) Condition

Eq creates a condition that compares this parameter to a literal value. Example: replicas.Eq(3) generates: parameter.replicas == 3

func (*FloatParam) GetDefault

func (p *FloatParam) GetDefault() any

func (*FloatParam) GetDescription

func (p *FloatParam) GetDescription() string

func (*FloatParam) GetMax

func (p *FloatParam) GetMax() *float64

GetMax returns the maximum value constraint, or nil if not set.

func (*FloatParam) GetMin

func (p *FloatParam) GetMin() *float64

GetMin returns the minimum value constraint, or nil if not set.

func (*FloatParam) GetShort

func (p *FloatParam) GetShort() string

func (*FloatParam) Gt

func (p *FloatParam) Gt(val any) Condition

Gt creates a condition that checks if this parameter is greater than a value. Example: replicas.Gt(1) generates: parameter.replicas > 1

func (*FloatParam) Gte

func (p *FloatParam) Gte(val any) Condition

Gte creates a condition that checks if this parameter is greater than or equal to a value. Example: replicas.Gte(1) generates: parameter.replicas >= 1

func (*FloatParam) HasDefault

func (p *FloatParam) HasDefault() bool

func (*FloatParam) Ignore

func (p *FloatParam) Ignore() *FloatParam

Ignore marks the parameter as ignored by the UI. This generates a // +ignore directive in the CUE output.

func (*FloatParam) In

func (p *FloatParam) In(values ...float64) Condition

In creates a condition that checks if this float parameter is one of the given values. Example: ratio.In(0.5, 1.0, 2.0) generates: parameter.ratio == 0.5 || parameter.ratio == 1.0 || parameter.ratio == 2.0

func (*FloatParam) IsIgnore

func (p *FloatParam) IsIgnore() bool

func (*FloatParam) IsOptional

func (p *FloatParam) IsOptional() bool

func (*FloatParam) IsRequired

func (p *FloatParam) IsRequired() bool

func (*FloatParam) IsSet

func (p *FloatParam) IsSet() Condition

IsSet returns a condition that checks if the parameter has a value. This is used with SetIf for conditional field assignment.

func (*FloatParam) Lt

func (p *FloatParam) Lt(val any) Condition

Lt creates a condition that checks if this parameter is less than a value. Example: replicas.Lt(10) generates: parameter.replicas < 10

func (*FloatParam) Lte

func (p *FloatParam) Lte(val any) Condition

Lte creates a condition that checks if this parameter is less than or equal to a value. Example: replicas.Lte(10) generates: parameter.replicas <= 10

func (*FloatParam) Max

func (p *FloatParam) Max(n float64) *FloatParam

Max sets the maximum value constraint for the parameter. This generates CUE like: number & <=n

func (*FloatParam) Min

func (p *FloatParam) Min(n float64) *FloatParam

Min sets the minimum value constraint for the parameter. This generates CUE like: number & >=n

func (*FloatParam) Name

func (p *FloatParam) Name() string

func (*FloatParam) Ne

func (p *FloatParam) Ne(val any) Condition

Ne creates a condition that checks if this parameter is not equal to a value. Example: status.Ne("error") generates: parameter.status != "error"

func (*FloatParam) NotSet

func (p *FloatParam) NotSet() Condition

NotSet returns a condition that checks if the parameter is not set. This generates `if parameter["name"] == _|_` in CUE.

func (*FloatParam) Optional

func (p *FloatParam) Optional() *FloatParam

Optional marks the parameter as optional, emitting the "?" CUE marker.

func (*FloatParam) Required

func (p *FloatParam) Required() *FloatParam

Required marks the parameter as required in input, emitting the "!" CUE marker.

func (*FloatParam) Short

func (p *FloatParam) Short(s string) *FloatParam

Short sets a short flag alias for the parameter. This generates a // +short=X directive in the CUE output.

type ForEachMapOp

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

ForEachMapOp represents a for comprehension over a map. Generates: for k, v in source { (k): v } or custom expressions

func ForEachMap

func ForEachMap() *ForEachMapOp

ForEachMap creates a for comprehension over the parameter map. This generates: for k, v in parameter { (k): v }

func (*ForEachMapOp) Body

func (f *ForEachMapOp) Body() []ResourceOp

Body returns nested operations.

func (*ForEachMapOp) KeyExpr

func (f *ForEachMapOp) KeyExpr() string

KeyExpr returns the key expression.

func (*ForEachMapOp) KeyVar

func (f *ForEachMapOp) KeyVar() string

KeyVar returns the key variable name.

func (*ForEachMapOp) Over

func (f *ForEachMapOp) Over(source string) *ForEachMapOp

Over specifies the source to iterate over.

func (*ForEachMapOp) Source

func (f *ForEachMapOp) Source() string

Source returns the iteration source.

func (*ForEachMapOp) ValExpr

func (f *ForEachMapOp) ValExpr() string

ValExpr returns the value expression.

func (*ForEachMapOp) ValVar

func (f *ForEachMapOp) ValVar() string

ValVar returns the value variable name.

func (*ForEachMapOp) WithBody

func (f *ForEachMapOp) WithBody(ops ...ResourceOp) *ForEachMapOp

WithBody adds nested operations to the for body.

func (*ForEachMapOp) WithKeyExpr

func (f *ForEachMapOp) WithKeyExpr(expr string) *ForEachMapOp

WithKeyExpr specifies a custom key expression.

func (*ForEachMapOp) WithValExpr

func (f *ForEachMapOp) WithValExpr(expr string) *ForEachMapOp

WithValExpr specifies a custom value expression.

func (*ForEachMapOp) WithVars

func (f *ForEachMapOp) WithVars(keyVar, valVar string) *ForEachMapOp

WithVars specifies the key and value variable names.

type ForEachOp

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

ForEachOp represents a for-each spread operation in a patch. This generates CUE like: for k, v in source { (k): v }

func (*ForEachOp) Path

func (f *ForEachOp) Path() string

Path returns the parent path for the for-each operation.

func (*ForEachOp) Source

func (f *ForEachOp) Source() Value

Source returns the source value to iterate over.

type FormatField

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

FormatField formats a string using item fields. Usage: FormatField("port-%v", Field("port"))

func Format

func Format(format string, args ...FieldValue) *FormatField

Format creates a formatted string field value.

func (*FormatField) RequiredImports

func (f *FormatField) RequiredImports() []string

RequiredImports returns the CUE imports required by FormatField. FormatField typically uses strconv.FormatInt for numeric formatting.

type GuardedBlockAction

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

GuardedBlockAction represents a field that always exists with a guard condition inside. Generates: name: { if cond { ...contents... } } Unlike ConditionalAction which generates: if cond { name: { ...contents... } }

type HTTPPostBuilder

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

HTTPPostBuilder builds an http.#HTTPDo POST operation fluently.

func HTTPPost

func HTTPPost(url Value) *HTTPPostBuilder

HTTPPost creates a new http.#HTTPDo builder for a POST request.

func (*HTTPPostBuilder) Body

Body sets the request body.

func (*HTTPPostBuilder) Header

func (b *HTTPPostBuilder) Header(key, value string) *HTTPPostBuilder

Header adds a request header.

func (*HTTPPostBuilder) RenderCUE

func (b *HTTPPostBuilder) RenderCUE(rv func(Value) string) string

RenderCUE renders the builder to a CUE string.

type HasExposedPortsCondition

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

HasExposedPortsCondition checks if a ports parameter has any exposed ports.

func (*HasExposedPortsCondition) Ports

func (h *HasExposedPortsCondition) Ports() Value

Ports returns the ports value being checked.

type HealthBuilder

type HealthBuilder struct {
	*StatusBuilder
	// contains filtered or unexported fields
}

HealthBuilder provides a fluent API for building health policy expressions.

func CronJobHealth

func CronJobHealth() *HealthBuilder

CronJobHealth returns a pre-configured health builder for CronJob.

func DaemonSetHealth

func DaemonSetHealth() *HealthBuilder

DaemonSetHealth returns a pre-configured health builder for DaemonSet.

func DeploymentHealth

func DeploymentHealth() *HealthBuilder

DeploymentHealth returns a pre-configured health builder for Deployment. Uses consolidated structure with all fields in a single "ready" block, the _isHealth intermediate pattern, and annotation-based health disable.

func Health

func Health() *HealthBuilder

Health creates a new health policy builder. It embeds StatusBuilder so you can add fields the same way.

func JobHealth

func JobHealth() *HealthBuilder

JobHealth returns a pre-configured health builder for Job.

func StatefulSetHealth

func StatefulSetHealth() *HealthBuilder

StatefulSetHealth returns a pre-configured health builder for StatefulSet.

func (*HealthBuilder) AllTrue

func (h *HealthBuilder) AllTrue(condTypes ...string) HealthExpression

AllTrue checks if all specified conditions have status "True". Example: Health().AllTrue("Ready", "Synced")

func (*HealthBuilder) Always

func (h *HealthBuilder) Always() HealthExpression

Always returns a health expression that is always true. Use this when resource existence is the only health criteria. Example: Health().Always()

func (*HealthBuilder) And

And combines multiple health expressions with AND. All expressions must be true for the health check to pass. Example: Health().And(expr1, expr2, expr3)

func (*HealthBuilder) AnyTrue

func (h *HealthBuilder) AnyTrue(condTypes ...string) HealthExpression

AnyTrue checks if any of the specified conditions have status "True". Example: Health().AnyTrue("Ready", "Available")

func (*HealthBuilder) Build

func (h *HealthBuilder) Build() string

Build generates the CUE expression for healthPolicy.

func (*HealthBuilder) Condition

func (h *HealthBuilder) Condition(condType string) *ConditionExpr

Condition creates an expression to check a status condition. Example: Health().Condition("Ready").IsTrue()

func (*HealthBuilder) Exists

func (h *HealthBuilder) Exists(path string) HealthExpression

Exists checks if a field exists (is not _|_). Example: Health().Exists("status.loadBalancer.ingress")

func (*HealthBuilder) Field

func (h *HealthBuilder) Field(path string) *HealthFieldExpr

Field creates an expression builder for a field path. Example: Health().Field("status.replicas").Gt(0)

func (*HealthBuilder) FieldRef

func (h *HealthBuilder) FieldRef(path string) *HealthFieldRefExpr

FieldRef creates a reference to another field for field-to-field comparisons. Example: Health().Field("status.readyReplicas").Eq(Health().FieldRef("spec.replicas"))

func (*HealthBuilder) HealthyWhen

func (h *HealthBuilder) HealthyWhen(conditions ...string) *HealthBuilder

HealthyWhen adds health conditions. Usage: .HealthyWhen("desired.replicas == ready.replicas", "updated.replicas == desired.replicas")

func (*HealthBuilder) HealthyWhenExpr

func (h *HealthBuilder) HealthyWhenExpr(expr HealthExpression) *HealthBuilder

HealthyWhenExpr sets the health condition using a composable HealthExpression. This generates the appropriate preamble and isHealth expression. Example: Health().HealthyWhenExpr(Health().Condition("Ready").IsTrue())

func (*HealthBuilder) IntField

func (h *HealthBuilder) IntField(name, sourcePath string, defaultVal int) *HealthBuilder

IntField adds an integer field (delegates to StatusBuilder).

func (*HealthBuilder) MetadataField

func (h *HealthBuilder) MetadataField(name, sourcePath string) *HealthBuilder

MetadataField adds a field from metadata (e.g., generation).

func (*HealthBuilder) Not

Not negates a health expression. Example: Health().Not(Health().Condition("Stalled").IsTrue())

func (*HealthBuilder) NotExists

func (h *HealthBuilder) NotExists(path string) HealthExpression

NotExists checks if a field does not exist (is _|_). Example: Health().NotExists("status.error")

func (*HealthBuilder) Or

Or combines multiple health expressions with OR. Any expression being true makes the health check pass. Example: Health().Or(expr1, expr2)

func (*HealthBuilder) Phase

func (h *HealthBuilder) Phase(phases ...string) HealthExpression

Phase creates an expression to check if status.phase matches any of the given phases. Example: Health().Phase("Running", "Succeeded")

func (*HealthBuilder) PhaseField

func (h *HealthBuilder) PhaseField(path string, phases ...string) HealthExpression

PhaseField creates an expression to check a custom phase field path. Example: Health().PhaseField("status.currentPhase", "Active", "Ready")

func (*HealthBuilder) Policy

func (h *HealthBuilder) Policy(expr HealthExpression) string

Policy generates a complete healthPolicy CUE block from a HealthExpression. This is useful for generating standalone health policies without setting them on the builder. Example: Health().Policy(Health().Condition("Ready").IsTrue())

func (*HealthBuilder) RawCUE

func (h *HealthBuilder) RawCUE(cue string) *HealthBuilder

RawCUE sets raw CUE for complex health policies that don't fit the builder pattern.

func (*HealthBuilder) StringField

func (h *HealthBuilder) StringField(name, sourcePath string, defaultVal string) *HealthBuilder

StringField adds a string field (delegates to StatusBuilder).

func (*HealthBuilder) WithDefault

func (h *HealthBuilder) WithDefault() *HealthBuilder

WithDefault enables the _isHealth intermediate pattern. Generates: _isHealth: (expr) + isHealth: *_isHealth | bool instead of: isHealth: expr

func (*HealthBuilder) WithDisableAnnotation

func (h *HealthBuilder) WithDisableAnnotation(annotation string) *HealthBuilder

WithDisableAnnotation adds an annotation-based health-check disable override. Generates CUE that checks for the given annotation and sets isHealth: true if present.

type HealthExpression

type HealthExpression interface {
	// ToCUE generates the CUE expression for this health check.
	// The expression should evaluate to a boolean.
	ToCUE() string

	// Preamble returns any CUE definitions needed before the isHealth expression.
	// For example, condition checks need helper variables to extract conditions.
	Preamble() string
}

HealthExpression is the composable unit for building health policies. All health primitives implement this interface and can be combined using Health().And(), Health().Or(), and Health().Not().

type HealthFieldExpr

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

HealthFieldExpr provides comparison operations on a status field.

func (*HealthFieldExpr) Contains

func (f *HealthFieldExpr) Contains(substr string) HealthExpression

Contains checks if the string field contains the given substring.

func (*HealthFieldExpr) Eq

func (f *HealthFieldExpr) Eq(value any) HealthExpression

Eq checks if the field equals the given value.

func (*HealthFieldExpr) Gt

func (f *HealthFieldExpr) Gt(value any) HealthExpression

Gt checks if the field is greater than the given value.

func (*HealthFieldExpr) Gte

func (f *HealthFieldExpr) Gte(value any) HealthExpression

Gte checks if the field is greater than or equal to the given value.

func (*HealthFieldExpr) In

func (f *HealthFieldExpr) In(values ...any) HealthExpression

In checks if the field value is one of the given values.

func (*HealthFieldExpr) Lt

func (f *HealthFieldExpr) Lt(value any) HealthExpression

Lt checks if the field is less than the given value.

func (*HealthFieldExpr) Lte

func (f *HealthFieldExpr) Lte(value any) HealthExpression

Lte checks if the field is less than or equal to the given value.

func (*HealthFieldExpr) Ne

func (f *HealthFieldExpr) Ne(value any) HealthExpression

Ne checks if the field does not equal the given value.

type HealthFieldRefExpr

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

HealthFieldRefExpr represents a reference to another field (for comparisons).

func (*HealthFieldRefExpr) Preamble

func (f *HealthFieldRefExpr) Preamble() string

func (*HealthFieldRefExpr) ToCUE

func (f *HealthFieldRefExpr) ToCUE() string

type HelperBuilder

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

HelperBuilder provides a fluent API for building template helpers.

func (*HelperBuilder) AfterOutput

func (hb *HelperBuilder) AfterOutput() *HelperBuilder

AfterOutput marks this helper to appear after the output: block in generated CUE. Use this for helpers that are primarily used by outputs: (auxiliary resources) rather than the main output: resource.

In KubeVela CUE definitions, the structure is typically:

template: {
    mountsArray: [...]   // Primary helpers
    volumesList: [...]
    output: {...}         // Main resource
    exposePorts: [...]    // Auxiliary helpers (AfterOutput)
    outputs: {...}        // Auxiliary resources
    parameter: {...}
}

Example:

exposePorts := tpl.Helper("exposePorts").
    From(ports).
    Filter(FieldEquals("expose", true)).
    Map(...).
    AfterOutput().  // Place after output:
    Build()

func (*HelperBuilder) Build

func (hb *HelperBuilder) Build() *HelperVar

Build finalizes the helper and registers it with the template. Returns a type-safe HelperVar that can be used in Resource.Set() calls.

func (*HelperBuilder) Dedupe

func (hb *HelperBuilder) Dedupe(keyField string) *HelperBuilder

Dedupe removes duplicate items by a key field.

Example:

.Dedupe("name")

func (*HelperBuilder) DefaultField

func (hb *HelperBuilder) DefaultField(field string, defaultVal FieldValue) *HelperBuilder

DefaultField sets a default value for a field if not present.

Example:

.DefaultField("name", Format("port-%d", FieldRef("port")))

func (*HelperBuilder) Each

func (hb *HelperBuilder) Each(fn func(Value) Value) *HelperBuilder

Each applies a transformation function to each element. The function receives a Value representing the current item and returns a transformed Value.

Example:

mounts := tpl.Helper("mountsArray").
    FromFields(Param("volumeMounts"), "pvc", "configMap").
    Each(func(v Value) Value {
        return Struct(
            Field("name", v.Get("name")),
            Field("mountPath", v.Get("mountPath")),
        )
    }).
    Build()

func (*HelperBuilder) Filter

func (hb *HelperBuilder) Filter(pred Predicate) *HelperBuilder

Filter keeps only items matching the predicate.

func (*HelperBuilder) FilterCond

func (hb *HelperBuilder) FilterCond(cond Condition) *HelperBuilder

FilterCond keeps only items matching the condition.

Example:

exposedPorts := tpl.Helper("exposedPorts").
    From(Param("ports")).
    FilterCond(Eq(Field("expose"), true)).
    Build()

func (*HelperBuilder) From

func (hb *HelperBuilder) From(source Value) *HelperBuilder

From sets a single source for the helper.

Example:

ports := tpl.Helper("portsArray").
    From(Param("ports")).
    Pick("port", "name", "protocol").
    Build()

func (*HelperBuilder) FromArray

func (hb *HelperBuilder) FromArray(ab *ArrayBuilder) *HelperBuilder

FromArray uses a pre-built ArrayBuilder as the helper source. This enables complex iteration patterns (ForEachWithGuardedFiltered) that can't be expressed through the standard From/Filter/Map pipeline.

func (*HelperBuilder) FromFields

func (hb *HelperBuilder) FromFields(source Value, fields ...string) *HelperBuilder

FromFields sets multiple named fields as the source. This is used for patterns like volumeMounts where items come from multiple sub-fields (pvc, configMap, secret, emptyDir, hostPath).

Example:

mounts := tpl.Helper("mountsArray").
    FromFields(Param("volumeMounts"), "pvc", "configMap", "secret", "emptyDir", "hostPath").
    Pick("name", "mountPath").
    Build()

func (*HelperBuilder) FromHelper

func (hb *HelperBuilder) FromHelper(helper *HelperVar) *HelperBuilder

FromHelper references another helper as the source. This enables helper chaining for patterns like deduplication.

Example:

dedupedVolumes := tpl.Helper("deDupVolumesArray").
    FromHelper(volumesList).
    Dedupe("name").
    Build()

func (*HelperBuilder) Guard

func (hb *HelperBuilder) Guard(cond Condition) *HelperBuilder

Guard sets an outer condition that wraps the for comprehension. This generates `if condition for v in source` pattern in CUE.

Example:

exposePorts := tpl.Helper("exposePorts").
    From(ports).
    Guard(ports.IsSet()). // generates: if parameter.ports != _|_ for v in ...
    Filter(FieldEquals("expose", true)).
    Build()

func (*HelperBuilder) Map

func (hb *HelperBuilder) Map(mappings FieldMap) *HelperBuilder

Map transforms each element using the given field mappings.

Example:

.Map(FieldMap{"containerPort": FieldRef("port"), "name": FieldRef("name")})

func (*HelperBuilder) MapBySource

func (hb *HelperBuilder) MapBySource(mappings map[string]FieldMap) *HelperBuilder

MapBySource applies different field mappings based on the source field name. This is essential for volumeMounts where pvc, configMap, secret each have different output structures.

Example:

volumes := tpl.Helper("volumesList").
    FromFields(Param("volumeMounts"), "pvc", "configMap", "secret", "emptyDir", "hostPath").
    MapBySource(map[string]FieldMap{
        "pvc":       {"name": FieldRef("name"), "persistentVolumeClaim.claimName": FieldRef("claimName")},
        "configMap": {"name": FieldRef("name"), "configMap.name": FieldRef("cmName")},
        "secret":    {"name": FieldRef("name"), "secret.secretName": FieldRef("secretName")},
        "emptyDir":  {"name": FieldRef("name"), "emptyDir.medium": FieldRef("medium")},
        "hostPath":  {"name": FieldRef("name"), "hostPath.path": FieldRef("path")},
    }).
    Build()

func (*HelperBuilder) Pick

func (hb *HelperBuilder) Pick(fields ...string) *HelperBuilder

Pick selects only the specified fields from each element.

Example:

.Pick("name", "mountPath", "subPath")

func (*HelperBuilder) PickIf

func (hb *HelperBuilder) PickIf(cond Condition, field string) *HelperBuilder

PickIf conditionally includes a field if the condition is true.

Example:

.PickIf(IsSet(Field("subPath")), "subPath")

func (*HelperBuilder) Rename

func (hb *HelperBuilder) Rename(from, to string) *HelperBuilder

Rename renames a field in each item.

Example:

.Rename("port", "containerPort")

func (*HelperBuilder) Wrap

func (hb *HelperBuilder) Wrap(key string) *HelperBuilder

Wrap wraps each item value under a new key.

Example:

// Transforms ["secret1", "secret2"] to [{name: "secret1"}, {name: "secret2"}]
.Wrap("name")

type HelperDefinition

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

HelperDefinition represents a CUE helper type definition like #HealthProbe.

func (HelperDefinition) GetName

func (h HelperDefinition) GetName() string

GetName returns the helper definition name.

func (HelperDefinition) GetParam

func (h HelperDefinition) GetParam() Param

GetParam returns the Param for this helper definition.

func (HelperDefinition) GetSchema

func (h HelperDefinition) GetSchema() string

GetSchema returns the raw CUE schema.

func (HelperDefinition) HasParam

func (h HelperDefinition) HasParam() bool

HasParam returns true if this helper definition uses a Param.

type HelperVar

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

HelperVar is a type-safe reference to a template-level helper definition. When used in a Resource.Set() call, the CUE generator will emit a reference to the helper name rather than inlining the collection.

func (*HelperVar) Collection

func (h *HelperVar) Collection() Value

Collection returns the underlying collection for inspection and CUE generation.

func (*HelperVar) Guard

func (h *HelperVar) Guard() Condition

Guard returns the outer guard condition, if any.

func (*HelperVar) IsAfterOutput

func (h *HelperVar) IsAfterOutput() bool

IsAfterOutput returns true if this helper should be placed after the output: block.

func (*HelperVar) Name

func (h *HelperVar) Name() string

Name returns the helper name.

func (*HelperVar) NotEmpty

func (h *HelperVar) NotEmpty() Condition

NotEmpty returns a condition that checks if len(helper) != 0. This is used for conditional outputs like Service which should only be created when there are exposed ports.

Example:

exposePorts := tpl.Helper("exposePorts").
    From(ports).
    Filter(...).
    Build()
tpl.OutputsIf(exposePorts.NotEmpty(), "service", svc)

func (*HelperVar) String

func (h *HelperVar) String() string

String implements Stringer for debugging.

type IfBlock

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

IfBlock represents a conditional block of operations.

func (*IfBlock) Cond

func (i *IfBlock) Cond() Condition

Cond returns the block condition.

func (*IfBlock) Ops

func (i *IfBlock) Ops() []ResourceOp

Ops returns the operations within the block.

type ImportRequirer

type ImportRequirer interface {
	// RequiredImports returns the list of CUE imports this type requires.
	RequiredImports() []string
}

ImportRequirer is implemented by types that require CUE imports. This allows the CUE generator to automatically detect and add required imports.

type InCondition

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

InCondition represents a check if a parameter value is in a set of values. Generates: parameter.name == val1 || parameter.name == val2 || ...

func (*InCondition) ParamName

func (c *InCondition) ParamName() string

ParamName returns the parameter name being checked.

func (*InCondition) Values

func (c *InCondition) Values() []any

Values returns the set of values to check against.

type InlineArrayValue

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

InlineArrayValue represents an inline array literal containing struct elements. This generates CUE like: [{field1: value1, field2: value2}] Used for deprecated parameter fallbacks that create a single-element array.

func InlineArray

func InlineArray(fields map[string]Value) *InlineArrayValue

InlineArray creates an inline array value with a single struct element. Example: InlineArray(map[string]Value{"containerPort": port}) Generates: [{containerPort: parameter.port}]

func (*InlineArrayValue) Fields

func (a *InlineArrayValue) Fields() map[string]Value

Fields returns the field mappings.

type IntParam

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

IntParam represents an integer parameter.

func Int

func Int(name string) *IntParam

Int creates a new integer parameter with the given name.

func (*IntParam) Add

func (p *IntParam) Add(val int) Value

Add creates an arithmetic expression that adds a value to this parameter. Example: replicas.Add(1) generates: parameter.replicas + 1

func (*IntParam) Default

func (p *IntParam) Default(value int) *IntParam

Default sets a default value for the parameter.

func (*IntParam) Description

func (p *IntParam) Description(desc string) *IntParam

Description sets the parameter description.

func (*IntParam) Div

func (p *IntParam) Div(val int) Value

Div creates an arithmetic expression that divides this parameter by a value. Example: replicas.Div(2) generates: parameter.replicas / 2

func (*IntParam) Eq

func (p *IntParam) Eq(val any) Condition

Eq creates a condition that compares this parameter to a literal value. Example: replicas.Eq(3) generates: parameter.replicas == 3

func (*IntParam) GetDefault

func (p *IntParam) GetDefault() any

func (*IntParam) GetDescription

func (p *IntParam) GetDescription() string

func (*IntParam) GetMax

func (p *IntParam) GetMax() *int

GetMax returns the maximum value constraint, or nil if not set.

func (*IntParam) GetMin

func (p *IntParam) GetMin() *int

GetMin returns the minimum value constraint, or nil if not set.

func (*IntParam) GetShort

func (p *IntParam) GetShort() string

func (*IntParam) Gt

func (p *IntParam) Gt(val any) Condition

Gt creates a condition that checks if this parameter is greater than a value. Example: replicas.Gt(1) generates: parameter.replicas > 1

func (*IntParam) Gte

func (p *IntParam) Gte(val any) Condition

Gte creates a condition that checks if this parameter is greater than or equal to a value. Example: replicas.Gte(1) generates: parameter.replicas >= 1

func (*IntParam) HasDefault

func (p *IntParam) HasDefault() bool

func (*IntParam) Ignore

func (p *IntParam) Ignore() *IntParam

Ignore marks the parameter as ignored by the UI. This generates a // +ignore directive in the CUE output.

func (*IntParam) In

func (p *IntParam) In(values ...int) Condition

In creates a condition that checks if this int parameter is one of the given values. Example: port.In(80, 443, 8080) generates: parameter.port == 80 || parameter.port == 443 || parameter.port == 8080

func (*IntParam) IsIgnore

func (p *IntParam) IsIgnore() bool

func (*IntParam) IsOptional

func (p *IntParam) IsOptional() bool

func (*IntParam) IsRequired

func (p *IntParam) IsRequired() bool

func (*IntParam) IsSet

func (p *IntParam) IsSet() Condition

IsSet returns a condition that checks if the parameter has a value. This is used with SetIf for conditional field assignment.

func (*IntParam) Lt

func (p *IntParam) Lt(val any) Condition

Lt creates a condition that checks if this parameter is less than a value. Example: replicas.Lt(10) generates: parameter.replicas < 10

func (*IntParam) Lte

func (p *IntParam) Lte(val any) Condition

Lte creates a condition that checks if this parameter is less than or equal to a value. Example: replicas.Lte(10) generates: parameter.replicas <= 10

func (*IntParam) Max

func (p *IntParam) Max(n int) *IntParam

Max sets the maximum value constraint for the parameter. This generates CUE like: int & <=n

func (*IntParam) Min

func (p *IntParam) Min(n int) *IntParam

Min sets the minimum value constraint for the parameter. This generates CUE like: int & >=n

func (*IntParam) Mul

func (p *IntParam) Mul(val int) Value

Mul creates an arithmetic expression that multiplies this parameter by a value. Example: replicas.Mul(2) generates: parameter.replicas * 2

func (*IntParam) Name

func (p *IntParam) Name() string

func (*IntParam) Ne

func (p *IntParam) Ne(val any) Condition

Ne creates a condition that checks if this parameter is not equal to a value. Example: status.Ne("error") generates: parameter.status != "error"

func (*IntParam) NotSet

func (p *IntParam) NotSet() Condition

NotSet returns a condition that checks if the parameter is not set. This generates `if parameter["name"] == _|_` in CUE.

func (*IntParam) Optional

func (p *IntParam) Optional() *IntParam

Optional marks the parameter as optional, emitting the "?" CUE marker.

func (*IntParam) Required

func (p *IntParam) Required() *IntParam

Required marks the parameter as required in input, emitting the "!" CUE marker.

func (*IntParam) Short

func (p *IntParam) Short(s string) *IntParam

Short sets a short flag alias for the parameter. This generates a // +short=X directive in the CUE output.

func (*IntParam) Sub

func (p *IntParam) Sub(val int) Value

Sub creates an arithmetic expression that subtracts a value from this parameter. Example: replicas.Sub(1) generates: parameter.replicas - 1

type InterpolatedString

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

InterpolatedString represents a CUE string interpolation expression. Literal string parts are inlined, Value parts are wrapped in \(...).

Example:

Interpolation(vela.Namespace(), Lit(":"), name)
// Generates: "\(context.namespace):\(parameter.name)"

func Interpolation

func Interpolation(parts ...Value) *InterpolatedString

Interpolation creates a CUE string interpolation expression. Literal string values are inlined directly. All other values are wrapped in \(...) interpolation syntax.

func (*InterpolatedString) Parts

func (i *InterpolatedString) Parts() []Value

Parts returns the interpolation parts.

type IsSetCondition

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

IsSetCondition represents a check for whether a parameter is set.

func ParamIsSet

func ParamIsSet(name string) *IsSetCondition

ParamIsSet creates a condition that checks if a parameter is set. This generates CUE: parameter.name != _|_

This is a convenience wrapper around IsSetCondition.

Example:

tpl.Patch().
    SetIf(defkit.ParamIsSet("replicas"), "spec.replicas", defkit.ParamRef("replicas"))

func (*IsSetCondition) ParamName

func (i *IsSetCondition) ParamName() string

ParamName returns the parameter name being checked.

type ItemBuilder

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

ItemBuilder records per-item operations for complex ForEach iterations. It supports field assignment, conditionals, let bindings, and CUE default values.

func (*ItemBuilder) FieldExists

func (b *ItemBuilder) FieldExists(field string) Condition

FieldExists returns a Condition that checks if the iteration variable's field is set. Generates CUE: v.field != _|_

func (*ItemBuilder) FieldNotExists

func (b *ItemBuilder) FieldNotExists(field string) Condition

FieldNotExists returns a Condition that checks if the iteration variable's field is NOT set. Generates CUE: v.field == _|_

func (*ItemBuilder) If

func (b *ItemBuilder) If(cond Condition, fn func())

If records a conditional block of operations.

func (*ItemBuilder) IfNotSet

func (b *ItemBuilder) IfNotSet(field string, fn func())

IfNotSet records a conditional block that executes when the iteration variable's field is NOT set. Generates CUE: if v.field == _|_ { ... }

func (*ItemBuilder) IfSet

func (b *ItemBuilder) IfSet(field string, fn func())

IfSet records a conditional block that executes when the iteration variable's field is set. Generates CUE: if v.field != _|_ { ... }

func (*ItemBuilder) Let

func (b *ItemBuilder) Let(name string, value Value) Value

Let records a private field binding and returns a reference to it. Generates CUE: _name: value

func (*ItemBuilder) Ops

func (b *ItemBuilder) Ops() []itemOp

Ops returns the recorded operations.

func (*ItemBuilder) Set

func (b *ItemBuilder) Set(field string, value Value)

Set records an unconditional field assignment.

func (*ItemBuilder) SetDefault

func (b *ItemBuilder) SetDefault(field string, defValue Value, typeName string)

SetDefault records a CUE default value assignment. Generates CUE: field: *defValue | typeName

func (*ItemBuilder) Var

func (b *ItemBuilder) Var() *IterVarBuilder

Var returns a reference builder for the iteration variable. Use v.Field("port") to reference v.port in CUE.

func (*ItemBuilder) VarName

func (b *ItemBuilder) VarName() string

VarName returns the iteration variable name.

type ItemValue

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

ItemValue represents a reference to the current item in an Each transform.

func Item

func Item() *ItemValue

Item returns a value representing the current item in an Each transform.

func (*ItemValue) Field

func (i *ItemValue) Field() string

Field returns the field name being accessed (empty for whole item).

func (*ItemValue) Get

func (i *ItemValue) Get(field string) *ItemValue

Get returns a reference to a field of this item.

type IterFieldExistsCondition

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

IterFieldExistsCondition checks if an iteration variable field exists. Generates CUE: v.field != _|_ (or v.field == _|_ when negated).

func (*IterFieldExistsCondition) FieldName

func (c *IterFieldExistsCondition) FieldName() string

FieldName returns the field name.

func (*IterFieldExistsCondition) IsNegated

func (c *IterFieldExistsCondition) IsNegated() bool

IsNegated returns true if this is a "not exists" check.

func (*IterFieldExistsCondition) VarName

func (c *IterFieldExistsCondition) VarName() string

VarName returns the iteration variable name.

type IterFieldRef

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

IterFieldRef references a field on the iteration variable. Generates CUE: v.fieldName (where v is the iteration variable).

func (*IterFieldRef) FieldName

func (r *IterFieldRef) FieldName() string

FieldName returns the field name.

func (*IterFieldRef) VarName

func (r *IterFieldRef) VarName() string

VarName returns the iteration variable name.

type IterLetRef

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

IterLetRef references a let binding defined inside an iteration body. Generates CUE: _name (a private CUE identifier).

func (*IterLetRef) RefName

func (r *IterLetRef) RefName() string

RefName returns the binding name.

type IterVarBuilder

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

IterVarBuilder provides access to iteration variable fields.

func (*IterVarBuilder) Field

func (v *IterVarBuilder) Field(name string) *IterFieldRef

Field returns a Value referencing the iteration variable's field. v.Field("port") generates CUE: v.port

func (*IterVarBuilder) Ref

func (v *IterVarBuilder) Ref() *IterVarRef

Ref returns a Value referencing the iteration variable itself. Generates CUE: v (or whatever the variable name is). Useful when iterating over primitive arrays (e.g., [...int]).

type IterVarRef

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

IterVarRef references the iteration variable itself (not a field on it). Generates CUE: v (where v is the iteration variable).

func (*IterVarRef) VarName

func (r *IterVarRef) VarName() string

VarName returns the iteration variable name.

type KubeApplyBuilder

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

KubeApplyBuilder builds a kube.#Apply operation fluently.

func KubeApply

func KubeApply(objectValue Value) *KubeApplyBuilder

KubeApply creates a new kube.#Apply builder with the given object value.

func (*KubeApplyBuilder) Cluster

func (b *KubeApplyBuilder) Cluster(v Value) *KubeApplyBuilder

Cluster sets the optional cluster parameter.

func (*KubeApplyBuilder) RenderCUE

func (b *KubeApplyBuilder) RenderCUE(rv func(Value) string) string

RenderCUE renders the builder to a CUE string.

type KubeReadBuilder

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

KubeReadBuilder builds a kube.#Read operation fluently.

func KubeRead

func KubeRead(apiVersion, kind string) *KubeReadBuilder

KubeRead creates a new kube.#Read builder for the given apiVersion and kind.

func (*KubeReadBuilder) Cluster

func (b *KubeReadBuilder) Cluster(v Value) *KubeReadBuilder

Cluster sets the optional cluster parameter for multi-cluster reads.

func (*KubeReadBuilder) Name

Name sets the metadata.name value.

func (*KubeReadBuilder) Namespace

func (b *KubeReadBuilder) Namespace(v Value) *KubeReadBuilder

Namespace sets the metadata.namespace value.

func (*KubeReadBuilder) NamespaceIf

func (b *KubeReadBuilder) NamespaceIf(cond Condition, v Value) *KubeReadBuilder

NamespaceIf sets the metadata.namespace conditionally.

func (*KubeReadBuilder) RenderCUE

func (b *KubeReadBuilder) RenderCUE(rv func(Value) string) string

RenderCUE renders the builder to a CUE string.

func (*KubeReadBuilder) RenderCUEWithCondition

func (b *KubeReadBuilder) RenderCUEWithCondition(rv func(Value) string, rc func(Condition) string) string

RenderCUEWithCondition renders the builder to a CUE string with condition support.

type LenCondition

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

LenCondition checks the length of a parameter (string, array, or map). Generates: parameter["name"] != _|_ if len(parameter["name"]) op n

CUE chained-if guard form. The bracket-existence guard handles strict mode on optional fields (dot syntax `parameter.X` errors on `_|_`). The second `if` only evaluates when the first passes, so `len()` never references an absent (`_|_`) value. For required fields the outer guard always passes.

func (*LenCondition) Length

func (c *LenCondition) Length() int

Length returns the length to compare against.

func (*LenCondition) Op

func (c *LenCondition) Op() string

Op returns the comparison operator.

func (*LenCondition) ParamName

func (c *LenCondition) ParamName() string

ParamName returns the parameter name being checked.

type LenNotZeroCondition

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

LenNotZeroCondition checks if len(value) != 0.

func (*LenNotZeroCondition) Source

func (l *LenNotZeroCondition) Source() Value

Source returns the value being checked for non-zero length.

type LenOfExpr

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

LenOfExpr wraps a Value expression and provides comparison methods that produce Conditions. It emits len(<value>) in CUE. Reuses upstream LenValueCondition.

Example: LenOf(Plus(Lit("tenant-"), Reference("parameter.governance.tenantName"), Lit("-"), name)).Gt(63) generates: len("tenant-" + parameter.governance.tenantName + "-" + parameter.name) > 63

func LenOf

func LenOf(v Value) *LenOfExpr

LenOf creates a length expression wrapper around any Value.

func (*LenOfExpr) Eq

func (l *LenOfExpr) Eq(n int) Condition

Eq creates a condition: len(inner) == n. Returns upstream *LenValueCondition.

func (*LenOfExpr) Gt

func (l *LenOfExpr) Gt(n int) Condition

Gt creates a condition: len(inner) > n. Returns upstream *LenValueCondition.

func (*LenOfExpr) Gte

func (l *LenOfExpr) Gte(n int) Condition

Gte creates a condition: len(inner) >= n. Returns upstream *LenValueCondition.

type LenValueCondition

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

LenValueCondition checks the length of an arbitrary Value (not just a parameter). This extends LenCondition to work with let variables and other expressions. Generates: len(source) op n

func LenEq

func LenEq(source Value, n int) *LenValueCondition

LenEq creates a condition: len(source) == n.

func LenGe

func LenGe(source Value, n int) *LenValueCondition

LenGe creates a condition: len(source) >= n.

func LenGt

func LenGt(source Value, n int) *LenValueCondition

LenGt creates a condition: len(source) > n.

func (*LenValueCondition) Length

func (c *LenValueCondition) Length() int

Length returns the length to compare against.

func (*LenValueCondition) Op

func (c *LenValueCondition) Op() string

Op returns the comparison operator.

func (*LenValueCondition) Source

func (c *LenValueCondition) Source() Value

Source returns the source value being measured.

type LetBinding

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

LetBinding represents a CUE let binding for local variables. This generates: let varName = expression

Usage:

tpl.AddLetBinding("resourceContent", defkit.Struct(...))
tpl.AddLetBinding("_baseContainers", defkit.ContextOutput().Field("spec.template.spec.containers"))

func NewLetBinding

func NewLetBinding(name string, expr Value) *LetBinding

NewLetBinding creates a new let binding.

func (*LetBinding) Expr

func (l *LetBinding) Expr() Value

Expr returns the bound expression.

func (*LetBinding) Name

func (l *LetBinding) Name() string

Name returns the binding name.

type LetRef

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

LetRef references a let binding by name. This generates: varName in CUE expressions.

func LetVariable

func LetVariable(name string) *LetRef

LetVariable creates a reference to a let binding. Use this to reference a variable created with AddLetBinding.

Example:

tpl.AddLetBinding("resourceContent", defkit.Struct(...))
// Later in template:
defkit.LetVariable("resourceContent")

func (*LetRef) Name

func (l *LetRef) Name() string

Name returns the variable name.

type ListComprehension

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

ListComprehension represents a CUE list comprehension. This generates: [for v in source { ... if v.field != _|_ { field: v.field } }]

Usage:

defkit.ForEachIn(defkit.Param("constraints")).
    MapFields(defkit.FieldMap{
        "maxSkew":     defkit.FieldRef("maxSkew"),         // always included
        "minDomains":  defkit.Optional("minDomains"),      // only if set
    })

func ForEachIn

func ForEachIn(source Value) *ListComprehension

ForEachIn creates a list comprehension from a source collection. This is the starting point for building list comprehensions.

Example:

defkit.ForEachIn(defkit.ParamRef("constraints")).
    MapFields(defkit.FieldMap{...})

func (*ListComprehension) ConditionalFields

func (l *ListComprehension) ConditionalFields() []string

ConditionalFields returns fields that should be conditionally included.

func (*ListComprehension) FilterCondition

func (l *ListComprehension) FilterCondition() ListPredicate

FilterCondition returns the filter condition.

func (*ListComprehension) MapFields

func (l *ListComprehension) MapFields(mappings FieldMap) *ListComprehension

MapFields sets the field mappings for each item in the comprehension. Use FieldRef for always-included fields and Optional for conditional fields.

func (*ListComprehension) Mappings

func (l *ListComprehension) Mappings() FieldMap

Mappings returns the field mappings.

func (*ListComprehension) Source

func (l *ListComprehension) Source() Value

Source returns the source value.

func (*ListComprehension) WithFilter

func (l *ListComprehension) WithFilter(pred ListPredicate) *ListComprehension

WithFilter adds a filter condition to the comprehension. Only items matching the filter will be included in the output.

func (*ListComprehension) WithOptionalFields

func (l *ListComprehension) WithOptionalFields(fields ...string) *ListComprehension

WithOptionalFields marks additional fields that should only appear if set. This is an alternative to using Optional in the FieldMap.

type ListFieldExistsPredicate

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

ListFieldExistsPredicate checks if a field exists (is not bottom) in list items.

func ListFieldExists

func ListFieldExists(field string) *ListFieldExistsPredicate

ListFieldExists creates a predicate that checks if a field exists in list items. This generates CUE: if v.field != _|_

Example:

defkit.ForEachIn(source).
    WithFilter(defkit.ListFieldExists("optionalField"))

func (*ListFieldExistsPredicate) GetField

func (p *ListFieldExistsPredicate) GetField() string

GetField returns the field name being checked.

type ListPredicate

type ListPredicate interface {
	// contains filtered or unexported methods
}

ListPredicate represents a condition used to filter list comprehension items. Unlike Predicate in collections.go (which is for runtime filtering), ListPredicate generates CUE conditional expressions.

type LitVal

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

LitVal is a literal value for field mapping.

func LitField

func LitField(val any) LitVal

LitField creates a literal field value.

type Literal

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

Literal represents a literal value in an expression.

func Lit

func Lit(v any) *Literal

Lit creates a literal value from any Go value.

func (*Literal) Val

func (l *Literal) Val() any

Val returns the underlying value.

type LocalFieldRef

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

LocalFieldRef represents a reference to a field within the current scope. It implements Value so it can be used with upstream Comparison, LenValueCondition, etc. It provides ergonomic condition builder methods: Matches(), Eq(), IsSet(), LenEq(), Gte(), etc.

func LocalField

func LocalField(name string) *LocalFieldRef

LocalField creates a reference to a field in the current CUE scope (no "parameter." prefix). Used inside validators for condition-building on sibling fields. The name is emitted verbatim — supports dot-paths ("Principal.AWS") and array indexing ("expiration[0].date").

Compare with defkit.String("name") / defkit.Bool("name") which reference top-level parameters and emit "parameter.name" in CUE.

Example: LocalField("tenantName").Matches(".*-$")

func (*LocalFieldRef) Eq

func (s *LocalFieldRef) Eq(val any) Condition

Eq creates a condition comparing this field to a value. Example: LocalField("type").Eq("aws") generates: type == "aws" Reuses upstream Comparison type.

func (*LocalFieldRef) Gte

func (s *LocalFieldRef) Gte(other *LocalFieldRef) Condition

Gte creates a condition comparing this field >= another local field. Example: LocalField("days").Gte(LocalField("expiration[0].days")) generates: days >= expiration[0].days Reuses upstream Comparison type via Ge().

func (*LocalFieldRef) IsEmpty

func (s *LocalFieldRef) IsEmpty() Condition

IsEmpty creates a condition that checks if this field has length 0.

func (*LocalFieldRef) IsSet

func (s *LocalFieldRef) IsSet() Condition

IsSet creates a condition that checks if this field has a value (not bottom). Example: LocalField("role").IsSet() generates: role != _|_ Reuses upstream PathExistsCondition.

func (*LocalFieldRef) LenEq

func (s *LocalFieldRef) LenEq(n int) Condition

LenEq creates a condition that checks if this field's length equals n. Example: LocalField("Principal.AWS").LenEq(0) generates: len(Principal.AWS) == 0 Reuses upstream LenValueCondition via LenEq().

func (*LocalFieldRef) LenGt

func (s *LocalFieldRef) LenGt(n int) Condition

LenGt creates a condition that checks if this field's length is greater than n. Reuses upstream LenValueCondition via LenGt().

func (*LocalFieldRef) Matches

func (s *LocalFieldRef) Matches(pattern string) Condition

Matches creates a condition that checks if this field matches a regex pattern. Example: LocalField("tenantName").Matches(".*-$") generates: tenantName =~ ".*-$" Reuses upstream RegexMatchCondition.

func (*LocalFieldRef) Name

func (s *LocalFieldRef) Name() string

Name returns the field name.

func (*LocalFieldRef) Ne

func (s *LocalFieldRef) Ne(val any) Condition

Ne creates a condition checking this field is not equal to a value. Reuses upstream Comparison type.

func (*LocalFieldRef) NotSet

func (s *LocalFieldRef) NotSet() Condition

NotSet creates a condition that checks if this field is not set (is bottom). Example: LocalField("role").NotSet() generates: role == _|_

type LogicalExpr

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

LogicalExpr represents a logical combination of conditions.

func And

func And(conditions ...Condition) *LogicalExpr

And creates a logical AND of multiple conditions.

func Or

func Or(conditions ...Condition) *LogicalExpr

Or creates a logical OR of multiple conditions.

func (*LogicalExpr) Conditions

func (l *LogicalExpr) Conditions() []Condition

Conditions returns the list of combined conditions.

func (*LogicalExpr) Op

func (l *LogicalExpr) Op() LogicalOp

Op returns the logical operator.

type LogicalOp

type LogicalOp string

LogicalOp represents a logical operator.

const (
	// OpAnd represents logical AND (&&)
	OpAnd LogicalOp = "&&"
	// OpOr represents logical OR (||)
	OpOr LogicalOp = "||"
)

type MapHasKeyCondition

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

MapHasKeyCondition checks if a map parameter has a specific key. Generates: parameter.name.key != _|_

func (*MapHasKeyCondition) Key

func (c *MapHasKeyCondition) Key() string

Key returns the key to check for.

func (*MapHasKeyCondition) ParamName

func (c *MapHasKeyCondition) ParamName() string

ParamName returns the parameter name being checked.

type MapParam

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

MapParam represents a map/dictionary parameter.

func Map

func Map(name string) *MapParam

Map creates a new map parameter with the given name.

func Object

func Object(name string) *MapParam

Object creates a generic object/struct parameter. This is useful when the structure is complex or dynamic.

func (*MapParam) Closed

func (p *MapParam) Closed() *MapParam

Closed marks the map as a closed struct, preventing extra fields. This generates CUE like: close({...})

func (*MapParam) ConditionalFields

func (p *MapParam) ConditionalFields(branches ...*ConditionalBranch) *MapParam

ConditionalFields adds conditional field branches inside this struct. Fields within each branch are emitted conditionally based on the guard.

func (*MapParam) Default

func (p *MapParam) Default(value map[string]any) *MapParam

Default sets a default value for the parameter.

func (*MapParam) Description

func (p *MapParam) Description(desc string) *MapParam

Description sets the parameter description.

func (*MapParam) Eq

func (p *MapParam) Eq(val any) Condition

Eq creates a condition that compares this parameter to a literal value. Example: replicas.Eq(3) generates: parameter.replicas == 3

func (*MapParam) Field

func (p *MapParam) Field(fieldPath string) *ParamFieldRef

Field returns a reference to a nested field within this map parameter. This allows map parameters to be used as variables with field access. Example: requests := Map("requests").WithSchema(...); requests.Field("cpu") => parameter.requests.cpu

func (*MapParam) GetConditionalFields

func (p *MapParam) GetConditionalFields() []*ConditionalBranch

GetConditionalFields returns the conditional field branches.

func (*MapParam) GetDefault

func (p *MapParam) GetDefault() any

func (*MapParam) GetDescription

func (p *MapParam) GetDescription() string

func (*MapParam) GetFields

func (p *MapParam) GetFields() []Param

GetFields returns the field definitions for map values.

func (*MapParam) GetSchema

func (p *MapParam) GetSchema() string

GetSchema returns the raw CUE schema for the map.

func (*MapParam) GetSchemaRef

func (p *MapParam) GetSchemaRef() string

GetSchemaRef returns the schema reference for this parameter.

func (*MapParam) GetShort

func (p *MapParam) GetShort() string

func (*MapParam) GetValidators

func (p *MapParam) GetValidators() []*Validator

GetValidators returns the validators for this map parameter.

func (*MapParam) Gt

func (p *MapParam) Gt(val any) Condition

Gt creates a condition that checks if this parameter is greater than a value. Example: replicas.Gt(1) generates: parameter.replicas > 1

func (*MapParam) Gte

func (p *MapParam) Gte(val any) Condition

Gte creates a condition that checks if this parameter is greater than or equal to a value. Example: replicas.Gte(1) generates: parameter.replicas >= 1

func (*MapParam) HasDefault

func (p *MapParam) HasDefault() bool

func (*MapParam) HasKey

func (p *MapParam) HasKey(key string) Condition

HasKey creates a condition that checks if this map has a specific key. Example: config.HasKey("debug") generates: parameter.config.debug != _|_

func (*MapParam) IsClosed

func (p *MapParam) IsClosed() bool

IsClosed returns whether the map is a closed struct.

func (*MapParam) IsEmpty

func (p *MapParam) IsEmpty() Condition

IsEmpty creates a condition that checks if this map is absent or empty. Renders as two if blocks (absent + set-and-empty). See AbsentOrEmptyCondition.

func (*MapParam) IsIgnore

func (p *MapParam) IsIgnore() bool

func (*MapParam) IsNotEmpty

func (p *MapParam) IsNotEmpty() Condition

IsNotEmpty creates a condition that checks if this map is set and non-empty. Example: config.IsNotEmpty() generates: parameter["config"] != _|_ if len(parameter["config"]) > 0

func (*MapParam) IsOptional

func (p *MapParam) IsOptional() bool

func (*MapParam) IsRequired

func (p *MapParam) IsRequired() bool

func (*MapParam) IsSet

func (p *MapParam) IsSet() Condition

IsSet returns a condition that checks if the parameter has a value. This is used with SetIf for conditional field assignment.

func (*MapParam) LenEq

func (p *MapParam) LenEq(n int) Condition

LenEq creates a condition that checks if this map has exactly n entries. Example: config.LenEq(5) generates: parameter["config"] != _|_ if len(parameter["config"]) == 5

LenEq(0) is treated as "absent OR empty" — equivalent to IsEmpty().

func (*MapParam) LenGt

func (p *MapParam) LenGt(n int) Condition

LenGt creates a condition that checks if this map has more than n entries. Example: config.LenGt(0) generates: parameter["config"] != _|_ if len(parameter["config"]) > 0

func (*MapParam) Lt

func (p *MapParam) Lt(val any) Condition

Lt creates a condition that checks if this parameter is less than a value. Example: replicas.Lt(10) generates: parameter.replicas < 10

func (*MapParam) Lte

func (p *MapParam) Lte(val any) Condition

Lte creates a condition that checks if this parameter is less than or equal to a value. Example: replicas.Lte(10) generates: parameter.replicas <= 10

func (*MapParam) Name

func (p *MapParam) Name() string

func (*MapParam) Ne

func (p *MapParam) Ne(val any) Condition

Ne creates a condition that checks if this parameter is not equal to a value. Example: status.Ne("error") generates: parameter.status != "error"

func (*MapParam) NotSet

func (p *MapParam) NotSet() Condition

NotSet returns a condition that checks if the parameter is not set. This generates `if parameter["name"] == _|_` in CUE.

func (*MapParam) Of

func (p *MapParam) Of(valueType ParamType) *MapParam

Of specifies the value type for the map.

func (*MapParam) Optional

func (p *MapParam) Optional() *MapParam

Optional marks the parameter as optional, emitting the "?" CUE marker.

func (*MapParam) Required

func (p *MapParam) Required() *MapParam

Required marks the parameter as required in input, emitting the "!" CUE marker.

func (*MapParam) Validators

func (p *MapParam) Validators(validators ...*Validator) *MapParam

Validators adds validation rules to this map parameter. Validators are emitted inside the struct as _validate* blocks.

func (*MapParam) ValueType

func (p *MapParam) ValueType() ParamType

ValueType returns the map value type.

func (*MapParam) WithFields

func (p *MapParam) WithFields(fields ...Param) *MapParam

WithFields adds field definitions for structured map values. This allows defining the schema for objects within the map.

func (*MapParam) WithSchema

func (p *MapParam) WithSchema(schema string) *MapParam

WithSchema sets a raw CUE schema for the map structure. This takes precedence over WithFields for schema generation.

func (*MapParam) WithSchemaRef

func (p *MapParam) WithSchemaRef(ref string) *MapParam

WithSchemaRef sets a reference to a helper type definition (e.g., "#HealthProbe"). This is used when the schema is defined elsewhere as a helper definition.

type MultiSource

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

MultiSource combines items from multiple named sources.

func FromFields

func FromFields(source Value, fields ...string) *MultiSource

FromFields creates a multi-source collection from named fields of an object. Usage: FromFields(volumeMounts, "pvc", "configMap", "secret", "emptyDir", "hostPath")

func (*MultiSource) All

func (m *MultiSource) All(sourceData map[string]any) iter.Seq[map[string]any]

All returns an iterator over all items from all sources after applying operations. Items are collected from each source field and transformed according to MapBySource mappings. Example: for item := range ms.All(sourceData) { ... }

func (*MultiSource) AllPairs

func (m *MultiSource) AllPairs(sourceData map[string]any) iter.Seq2[int, map[string]any]

AllPairs returns a key-value iterator with index and item from all sources. Example: for i, item := range ms.AllPairs(sourceData) { ... }

func (*MultiSource) Collect

func (m *MultiSource) Collect(sourceData map[string]any) []map[string]any

Collect materializes the iterator into a slice. Uses Go 1.23 slices.Collect for efficient collection.

func (*MultiSource) Count

func (m *MultiSource) Count(sourceData map[string]any) int

Count returns the number of items from all sources after applying operations.

func (*MultiSource) Dedupe

func (m *MultiSource) Dedupe(keyField string) *MultiSource

Dedupe removes duplicate items by a key field.

func (*MultiSource) Filter

func (m *MultiSource) Filter(pred Predicate) *MultiSource

Filter keeps only items matching the predicate.

func (*MultiSource) FilterCond

func (m *MultiSource) FilterCond(cond Condition) *MultiSource

FilterCond keeps only items matching a Condition expression. The condition is used for CUE generation; runtime apply is a passthrough.

func (*MultiSource) MapBySource

func (m *MultiSource) MapBySource(mappings map[string]FieldMap) *MultiSource

MapBySource applies different field mappings based on the source field name. This is useful for volumeMounts where pvc, configMap, secret each have different output formats.

Usage:

FromFields(volumeMounts, "pvc", "configMap", "secret", "emptyDir", "hostPath").
    MapBySource(map[string]FieldMap{
        "pvc": {"name": FieldRef("name"), "persistentVolumeClaim": Nested(FieldMap{"claimName": FieldRef("claimName")})},
        "configMap": {"name": FieldRef("name"), "configMap": Nested(FieldMap{"name": FieldRef("cmName"), "defaultMode": FieldRef("defaultMode")})},
        ...
    }).
    Dedupe("name")

func (*MultiSource) MapBySourceMappings

func (m *MultiSource) MapBySourceMappings() map[string]FieldMap

MapBySourceMappings returns the per-source-type field mappings.

func (*MultiSource) Operations

func (m *MultiSource) Operations() []collectionOperation

Operations returns the operations.

func (*MultiSource) Pick

func (m *MultiSource) Pick(fields ...string) *MultiSource

Pick selects only specified fields from each item.

func (*MultiSource) Source

func (m *MultiSource) Source() Value

Source returns the source value.

func (*MultiSource) Sources

func (m *MultiSource) Sources() []string

Sources returns the source field names.

type NestedField

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

NestedField creates a nested object with the given field mappings. Usage: Map(FieldMap{"persistentVolumeClaim": Nested(FieldMap{"claimName": FieldRef("claimName")})})

func Nested

func Nested(mapping FieldMap) *NestedField

Nested creates a nested object from field mappings. Usage: "persistentVolumeClaim": Nested(FieldMap{"claimName": FieldRef("claimName")})

func NestedFieldMap

func NestedFieldMap(mapping FieldMap) *NestedField

NestedFieldMap creates a nested object from field mappings. This is an alias for Nested, providing a clearer name for struct array helpers. Usage: defkit.NestedFieldMap(defkit.FieldMap{"claimName": defkit.FieldRef("claimName")})

type NotExpr

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

NotExpr represents a logical negation of a condition.

func Not

func Not(cond Condition) *NotExpr

Not creates a logical NOT of a condition.

func ParamNotSet

func ParamNotSet(name string) *NotExpr

ParamNotSet creates a condition that checks if a parameter is NOT set. This generates CUE: parameter.name == _|_

This is a convenience wrapper around Not(IsSetCondition).

Example:

// Set default only if not explicitly specified
tpl.Patch().
    SetIf(defkit.ParamNotSet("replicas"), "spec.replicas", defkit.Literal(1))

func (*NotExpr) Cond

func (n *NotExpr) Cond() Condition

Cond returns the negated condition.

type OneOfParam

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

OneOfParam represents a discriminated union parameter.

func OneOf

func OneOf(name string) *OneOfParam

OneOf creates a new discriminated union parameter with the given name.

func (*OneOfParam) Default

func (p *OneOfParam) Default(value string) *OneOfParam

Default sets the default variant name for the discriminator.

func (*OneOfParam) Description

func (p *OneOfParam) Description(desc string) *OneOfParam

Description sets the parameter description.

func (*OneOfParam) Discriminator

func (p *OneOfParam) Discriminator(field string) *OneOfParam

Discriminator sets the field name used to distinguish variants.

func (*OneOfParam) Eq

func (p *OneOfParam) Eq(val any) Condition

Eq creates a condition that compares this parameter to a literal value. Example: replicas.Eq(3) generates: parameter.replicas == 3

func (*OneOfParam) GetDefault

func (p *OneOfParam) GetDefault() any

func (*OneOfParam) GetDescription

func (p *OneOfParam) GetDescription() string

func (*OneOfParam) GetDiscriminator

func (p *OneOfParam) GetDiscriminator() string

GetDiscriminator returns the discriminator field name.

func (*OneOfParam) GetShort

func (p *OneOfParam) GetShort() string

func (*OneOfParam) GetVariant

func (p *OneOfParam) GetVariant(name string) *OneOfVariant

GetVariant returns a variant by name, or nil if not found.

func (*OneOfParam) GetVariants

func (p *OneOfParam) GetVariants() []*OneOfVariant

GetVariants returns all variant definitions.

func (*OneOfParam) Gt

func (p *OneOfParam) Gt(val any) Condition

Gt creates a condition that checks if this parameter is greater than a value. Example: replicas.Gt(1) generates: parameter.replicas > 1

func (*OneOfParam) Gte

func (p *OneOfParam) Gte(val any) Condition

Gte creates a condition that checks if this parameter is greater than or equal to a value. Example: replicas.Gte(1) generates: parameter.replicas >= 1

func (*OneOfParam) HasDefault

func (p *OneOfParam) HasDefault() bool

func (*OneOfParam) IsIgnore

func (p *OneOfParam) IsIgnore() bool

func (*OneOfParam) IsOptional

func (p *OneOfParam) IsOptional() bool

func (*OneOfParam) IsRequired

func (p *OneOfParam) IsRequired() bool

func (*OneOfParam) IsSet

func (p *OneOfParam) IsSet() Condition

IsSet returns a condition that checks if the parameter has a value. This is used with SetIf for conditional field assignment.

func (*OneOfParam) Lt

func (p *OneOfParam) Lt(val any) Condition

Lt creates a condition that checks if this parameter is less than a value. Example: replicas.Lt(10) generates: parameter.replicas < 10

func (*OneOfParam) Lte

func (p *OneOfParam) Lte(val any) Condition

Lte creates a condition that checks if this parameter is less than or equal to a value. Example: replicas.Lte(10) generates: parameter.replicas <= 10

func (*OneOfParam) Name

func (p *OneOfParam) Name() string

func (*OneOfParam) Ne

func (p *OneOfParam) Ne(val any) Condition

Ne creates a condition that checks if this parameter is not equal to a value. Example: status.Ne("error") generates: parameter.status != "error"

func (*OneOfParam) NotSet

func (p *OneOfParam) NotSet() Condition

NotSet returns a condition that checks if the parameter is not set. This generates `if parameter["name"] == _|_` in CUE.

func (*OneOfParam) Optional

func (p *OneOfParam) Optional() *OneOfParam

Optional marks the parameter as optional, emitting the "?" CUE marker.

func (*OneOfParam) Required

func (p *OneOfParam) Required() *OneOfParam

Required marks the parameter as required in input, emitting the "!" CUE marker.

func (*OneOfParam) Variants

func (p *OneOfParam) Variants(variants ...*OneOfVariant) *OneOfParam

Variants adds variant definitions to the union.

type OneOfVariant

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

OneOfVariant represents a variant in a discriminated union.

func Variant

func Variant(name string) *OneOfVariant

Variant creates a new variant for a OneOf parameter.

func (*OneOfVariant) GetFields

func (v *OneOfVariant) GetFields() []*StructField

GetFields returns the variant's field definitions.

func (*OneOfVariant) Name

func (v *OneOfVariant) Name() string

Name returns the variant name.

func (*OneOfVariant) WithFields

func (v *OneOfVariant) WithFields(fields ...*StructField) *OneOfVariant

WithFields adds field definitions to the variant.

type OpenArrayParam

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

OpenArrayParam represents an open array parameter that accepts any elements. This generates CUE like: operations: [...{...}] Used for json-patch trait where operations array accepts any operations.

func OpenArray

func OpenArray(name string) *OpenArrayParam

OpenArray creates a new open array parameter. This is used when the parameter schema should accept any array elements. Generates CUE like: name: [...{...}]

Example usage:

defkit.OpenArray("operations") // generates: operations: [...{...}]

func (*OpenArrayParam) Description

func (p *OpenArrayParam) Description(desc string) *OpenArrayParam

Description sets the parameter description.

func (*OpenArrayParam) Eq

func (p *OpenArrayParam) Eq(val any) Condition

Eq creates a condition that compares this parameter to a literal value. Example: replicas.Eq(3) generates: parameter.replicas == 3

func (*OpenArrayParam) GetDefault

func (p *OpenArrayParam) GetDefault() any

GetDefault returns nil (open arrays don't have defaults).

func (*OpenArrayParam) GetDescription

func (p *OpenArrayParam) GetDescription() string

GetDescription returns the parameter description.

func (*OpenArrayParam) GetShort

func (p *OpenArrayParam) GetShort() string

func (*OpenArrayParam) GetType

func (p *OpenArrayParam) GetType() ParamType

GetType returns the parameter type.

func (*OpenArrayParam) Gt

func (p *OpenArrayParam) Gt(val any) Condition

Gt creates a condition that checks if this parameter is greater than a value. Example: replicas.Gt(1) generates: parameter.replicas > 1

func (*OpenArrayParam) Gte

func (p *OpenArrayParam) Gte(val any) Condition

Gte creates a condition that checks if this parameter is greater than or equal to a value. Example: replicas.Gte(1) generates: parameter.replicas >= 1

func (*OpenArrayParam) HasDefault

func (p *OpenArrayParam) HasDefault() bool

func (*OpenArrayParam) IsIgnore

func (p *OpenArrayParam) IsIgnore() bool

func (*OpenArrayParam) IsOptional

func (p *OpenArrayParam) IsOptional() bool

func (*OpenArrayParam) IsRequired

func (p *OpenArrayParam) IsRequired() bool

IsRequired returns false (open arrays are inherently optional).

func (*OpenArrayParam) IsSet

func (p *OpenArrayParam) IsSet() Condition

IsSet returns a condition that checks if the parameter has a value. This is used with SetIf for conditional field assignment.

func (*OpenArrayParam) Lt

func (p *OpenArrayParam) Lt(val any) Condition

Lt creates a condition that checks if this parameter is less than a value. Example: replicas.Lt(10) generates: parameter.replicas < 10

func (*OpenArrayParam) Lte

func (p *OpenArrayParam) Lte(val any) Condition

Lte creates a condition that checks if this parameter is less than or equal to a value. Example: replicas.Lte(10) generates: parameter.replicas <= 10

func (*OpenArrayParam) Name

func (p *OpenArrayParam) Name() string

func (*OpenArrayParam) Ne

func (p *OpenArrayParam) Ne(val any) Condition

Ne creates a condition that checks if this parameter is not equal to a value. Example: status.Ne("error") generates: parameter.status != "error"

func (*OpenArrayParam) NotSet

func (p *OpenArrayParam) NotSet() Condition

NotSet returns a condition that checks if the parameter is not set. This generates `if parameter["name"] == _|_` in CUE.

type OpenStructParam

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

OpenStructParam represents an open struct parameter that accepts any fields. This generates CUE like: parameter: {...} Used for json-patch and json-merge-patch traits where the entire parameter is passed through as the patch content.

func OpenStruct

func OpenStruct() *OpenStructParam

OpenStruct creates a new open struct parameter. This is used when the parameter schema should accept any fields. Generates CUE like: parameter: {...}

Example usage:

defkit.OpenStruct() // generates: parameter: {...}

func (*OpenStructParam) Description

func (p *OpenStructParam) Description(desc string) *OpenStructParam

Description sets the parameter description.

func (*OpenStructParam) Eq

func (p *OpenStructParam) Eq(val any) Condition

Eq creates a condition that compares this parameter to a literal value. Example: replicas.Eq(3) generates: parameter.replicas == 3

func (*OpenStructParam) GetDefault

func (p *OpenStructParam) GetDefault() any

GetDefault returns nil (open structs don't have defaults).

func (*OpenStructParam) GetDescription

func (p *OpenStructParam) GetDescription() string

GetDescription returns the parameter description.

func (*OpenStructParam) GetName

func (p *OpenStructParam) GetName() string

GetName returns an empty string (open structs don't have names).

func (*OpenStructParam) GetShort

func (p *OpenStructParam) GetShort() string

func (*OpenStructParam) GetType

func (p *OpenStructParam) GetType() ParamType

GetType returns the parameter type.

func (*OpenStructParam) Gt

func (p *OpenStructParam) Gt(val any) Condition

Gt creates a condition that checks if this parameter is greater than a value. Example: replicas.Gt(1) generates: parameter.replicas > 1

func (*OpenStructParam) Gte

func (p *OpenStructParam) Gte(val any) Condition

Gte creates a condition that checks if this parameter is greater than or equal to a value. Example: replicas.Gte(1) generates: parameter.replicas >= 1

func (*OpenStructParam) HasDefault

func (p *OpenStructParam) HasDefault() bool

func (*OpenStructParam) IsIgnore

func (p *OpenStructParam) IsIgnore() bool

func (*OpenStructParam) IsOpen

func (p *OpenStructParam) IsOpen() bool

IsOpen returns true (used for type detection).

func (*OpenStructParam) IsOptional

func (p *OpenStructParam) IsOptional() bool

func (*OpenStructParam) IsRequired

func (p *OpenStructParam) IsRequired() bool

IsRequired returns false (open structs are inherently optional).

func (*OpenStructParam) IsSet

func (p *OpenStructParam) IsSet() Condition

IsSet returns a condition that checks if the parameter has a value. This is used with SetIf for conditional field assignment.

func (*OpenStructParam) Lt

func (p *OpenStructParam) Lt(val any) Condition

Lt creates a condition that checks if this parameter is less than a value. Example: replicas.Lt(10) generates: parameter.replicas < 10

func (*OpenStructParam) Lte

func (p *OpenStructParam) Lte(val any) Condition

Lte creates a condition that checks if this parameter is less than or equal to a value. Example: replicas.Lte(10) generates: parameter.replicas <= 10

func (*OpenStructParam) Name

func (p *OpenStructParam) Name() string

func (*OpenStructParam) Ne

func (p *OpenStructParam) Ne(val any) Condition

Ne creates a condition that checks if this parameter is not equal to a value. Example: status.Ne("error") generates: parameter.status != "error"

func (*OpenStructParam) NotSet

func (p *OpenStructParam) NotSet() Condition

NotSet returns a condition that checks if the parameter is not set. This generates `if parameter["name"] == _|_` in CUE.

type OptionalField

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

OptionalField includes a field value only if it exists and is not nil.

func Optional

func Optional(field string) *OptionalField

Optional creates a field reference that returns nil if the field doesn't exist. This is useful for optional fields that should only appear in output if present.

func OptionalFieldRef

func OptionalFieldRef(field string) *OptionalField

OptionalFieldRef is an alias for Optional, providing a clearer name for the pattern. Usage: defkit.OptionalFieldRef("subPath")

type OrFieldRef

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

OrFieldRef represents a field reference with a fallback value.

type OutputGroup

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

OutputGroup is a builder for adding outputs within a grouped condition.

func (*OutputGroup) Add

func (g *OutputGroup) Add(name string, r *Resource) *OutputGroup

Add adds a named resource to the output group.

type OutputStructBuilder

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

OutputStructBuilder collects field operations for building a conditional struct.

func (*OutputStructBuilder) Ops

func (b *OutputStructBuilder) Ops() []structBuilderOp

Ops returns all operations recorded in the struct builder.

func (*OutputStructBuilder) Set

func (b *OutputStructBuilder) Set(field string, value Value)

Set adds an unconditional field assignment to the struct.

func (*OutputStructBuilder) SetIf

func (b *OutputStructBuilder) SetIf(cond Condition, field string, value Value)

SetIf adds a conditional field assignment to the struct.

type Param

type Param interface {
	Value
	// Name returns the parameter name
	Name() string
	// IsRequired returns true if the parameter emits the "!" CUE marker — user must explicitly provide it
	IsRequired() bool
	// IsOptional returns true if the parameter was explicitly marked optional (emits "?" marker)
	IsOptional() bool
	// HasDefault returns true if the parameter has a default value
	HasDefault() bool
	// GetDefault returns the default value, or nil if none
	GetDefault() any
	// GetDescription returns the parameter description
	GetDescription() string
}

Param represents a parameter definition with its schema and constraints. Parameters are created using typed constructors like String(), Int(), etc.

type ParamArithExpr

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

ParamArithExpr represents an arithmetic expression on a parameter. Example: parameter.replicas + 1

func (*ParamArithExpr) ArithValue

func (e *ParamArithExpr) ArithValue() any

ArithValue returns the value for the arithmetic operation.

func (*ParamArithExpr) Op

func (e *ParamArithExpr) Op() string

Op returns the arithmetic operator.

func (*ParamArithExpr) ParamName

func (e *ParamArithExpr) ParamName() string

ParamName returns the parameter name.

type ParamCompareCondition

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

ParamCompareCondition represents a comparison between a parameter and a value.

func (*ParamCompareCondition) CompareValue

func (c *ParamCompareCondition) CompareValue() any

CompareValue returns the comparison value.

func (*ParamCompareCondition) Op

func (c *ParamCompareCondition) Op() string

Op returns the comparison operator.

func (*ParamCompareCondition) ParamName

func (c *ParamCompareCondition) ParamName() string

ParamName returns the parameter name being compared.

type ParamConcatExpr

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

ParamConcatExpr represents a string concatenation expression on a parameter. Example: parameter.name + "-suffix"

func (*ParamConcatExpr) ParamName

func (e *ParamConcatExpr) ParamName() string

ParamName returns the parameter name.

func (*ParamConcatExpr) Prefix

func (e *ParamConcatExpr) Prefix() string

Prefix returns the prefix to prepend.

func (*ParamConcatExpr) Suffix

func (e *ParamConcatExpr) Suffix() string

Suffix returns the suffix to append.

type ParamFieldRef

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

ParamFieldRef represents a reference to a field within a struct parameter. Example: parameter.config.name

func (*ParamFieldRef) Eq

func (r *ParamFieldRef) Eq(val any) Condition

Eq creates a condition that compares this field to a value.

func (*ParamFieldRef) FieldPath

func (r *ParamFieldRef) FieldPath() string

FieldPath returns the field path within the struct.

func (*ParamFieldRef) IsSet

func (r *ParamFieldRef) IsSet() Condition

IsSet returns a condition that checks if this field is set.

func (*ParamFieldRef) Ne

func (r *ParamFieldRef) Ne(val any) Condition

Ne creates a condition that checks inequality.

func (*ParamFieldRef) ParamName

func (r *ParamFieldRef) ParamName() string

ParamName returns the parameter name.

type ParamPathIsSetCondition

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

ParamPathIsSetCondition checks if a parameter path has a value.

func (*ParamPathIsSetCondition) Path

func (c *ParamPathIsSetCondition) Path() string

Path returns the parameter path being checked.

type ParamPathRef

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

ParamPathRef represents a reference to a nested parameter path. This is used to reference nested parameter values like "podAffinity.required". It generates CUE like `parameter.podAffinity.required`.

func ParamPath

func ParamPath(path string) *ParamPathRef

ParamPath creates a reference to a nested parameter path. This is used for accessing nested parameters in conditions and expressions.

Usage:

defkit.ParamPath("podAffinity.required").IsSet() // generates: if parameter.podAffinity.required != _|_
defkit.From(defkit.ParamPath("podAffinity.required")).Map(...) // generates: [for v in parameter.podAffinity.required {...}]

func (*ParamPathRef) IsSet

func (p *ParamPathRef) IsSet() Condition

IsSet returns a condition that checks if this parameter path has a value. This is used with SetIf for conditional field assignment. Generates: if parameter.path != _|_

func (*ParamPathRef) Path

func (p *ParamPathRef) Path() string

Path returns the parameter path.

type ParamType

type ParamType string

ParamType represents the type of a parameter

const (
	// ParamTypeString represents a string parameter
	ParamTypeString ParamType = "string"
	// ParamTypeInt represents an integer parameter
	ParamTypeInt ParamType = "int"
	// ParamTypeBool represents a boolean parameter
	ParamTypeBool ParamType = "bool"
	// ParamTypeFloat represents a float/number parameter
	ParamTypeFloat ParamType = "float"
	// ParamTypeArray represents an array parameter
	ParamTypeArray ParamType = "array"
	// ParamTypeMap represents a map parameter
	ParamTypeMap ParamType = "map"
	// ParamTypeStruct represents a struct parameter
	ParamTypeStruct ParamType = "struct"
	// ParamTypeEnum represents an enum parameter
	ParamTypeEnum ParamType = "enum"
	// ParamTypeOneOf represents a discriminated union parameter
	ParamTypeOneOf ParamType = "oneof"
	// ParamTypeClosedUnion represents a closed struct disjunction parameter
	ParamTypeClosedUnion ParamType = "closedunion"
)

type PassthroughOp

type PassthroughOp struct{}

PassthroughOp represents a passthrough operation where the parameter becomes the patch.

type PatchContainerConfig

type PatchContainerConfig struct {
	ContainerNameParam        string                // parameter for container name
	DefaultToContextName      bool                  // default container name to context.name
	PatchFields               []PatchContainerField // flat fields to patch directly on container
	Groups                    []PatchContainerGroup // grouped fields (e.g., startupProbe: { ... })
	AllowMultiple             bool                  // if true, allow patching multiple containers
	ContainersParam           string                // for multi-container mode, the array param name
	ContainersDescription     string                // +usage description for the containers param (auto-generated if empty)
	CustomParamsBlock         string                // custom CUE block for #PatchParams (for complex types)
	MultiContainerParam       string                // alternate name for multi-container param (default: "probes" for probes, "containers" for others)
	MultiContainerCheckField  string                // field name for multi-container error check (default: "containerName")
	MultiContainerErrMsg      string                // custom error message for multi-container mode (default: "container name must be set for %s")
	CustomPatchContainerBlock string                // custom CUE block for PatchContainer body (for complex merge logic)
	CustomPatchBlock          string                // custom CUE block for the patch: spec: template: spec: { ... } body
	CustomParameterBlock      string                // custom CUE block for the parameter definition
	PatchStrategy             string                // if set, emitted as // +patchStrategy=<value> before the patch block (e.g., "open")
	ParamsTypeName            string                // custom name for the #PatchParams helper (default: "PatchParams")
	NoDefaultDisjunction      bool                  // if true, omit the * default marker on parameter disjunction
}

PatchContainerConfig configures the PatchContainer helper.

type PatchContainerField

type PatchContainerField struct {
	ParamName     string // the parameter name (e.g., "command", "args")
	TargetField   string // the container field to patch (e.g., "command", "args")
	PatchStrategy string // the patch strategy (e.g., "replace", "merge")
	Condition     string // optional CUE condition (e.g., "!= null")
	ParamType     string // explicit CUE type (e.g., "string", "[...string]", "{...}")
	ParamDefault  string // explicit default value (e.g., "0", "\"\"", "false")
	Description   string // optional +usage description (auto-generated if empty)
}

PatchContainerField defines a field to be patched in the container.

func PatchFields

func PatchFields(builders ...*PatchFieldBuilder) []PatchContainerField

PatchFields builds a slice of PatchContainerField from builders. This eliminates the need to call .Build() on each field individually.

Example:

Fields: defkit.PatchFields(
    defkit.PatchField("exec").IsSet(),
    defkit.PatchField("initialDelaySeconds").Int().IsSet().Default("0"),
)

type PatchContainerGroup

type PatchContainerGroup struct {
	TargetField string                // the parent field name (e.g., "startupProbe", "securityContext")
	Fields      []PatchContainerField // fields within this group
	SubGroups   []PatchContainerGroup // nested groups (e.g., securityContext.capabilities)
}

PatchContainerGroup defines a group of fields under a common parent field. This generates CUE like:

startupProbe: {
    if _params.exec != _|_ { exec: _params.exec }
    if _params.httpGet != _|_ { httpGet: _params.httpGet }
}

type PatchFieldBuilder

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

PatchFieldBuilder provides a fluent API for constructing PatchContainerField values. Use PatchField() to start building.

Example:

defkit.PatchField("exec").IsSet().Build()
defkit.PatchField("initialDelaySeconds").Int().IsSet().Default("0").Build()
defkit.PatchField("image").Strategy("retainKeys").Description("Specify the image").Build()

func PatchField

func PatchField(name string) *PatchFieldBuilder

PatchField starts building a PatchContainerField with the given parameter name. The TargetField defaults to the same as the parameter name.

func (*PatchFieldBuilder) Bool

Bool is shorthand for Type("bool").

func (*PatchFieldBuilder) Build

Build returns the constructed PatchContainerField.

func (*PatchFieldBuilder) Default

func (b *PatchFieldBuilder) Default(val string) *PatchFieldBuilder

Default sets an explicit default value for the parameter.

func (*PatchFieldBuilder) Description

func (b *PatchFieldBuilder) Description(d string) *PatchFieldBuilder

Description sets the +usage description for this field.

func (*PatchFieldBuilder) Eq

Eq sets a condition that checks the field equals the given value.

func (*PatchFieldBuilder) Gt

Gt sets a condition that checks the field is greater than the given value.

func (*PatchFieldBuilder) Gte

Gte sets a condition that checks the field is greater than or equal to the given value.

func (*PatchFieldBuilder) Int

Int is shorthand for Type("int").

func (*PatchFieldBuilder) IsSet

IsSet guards the field with an existence check (CUE: != _|_). Use this for optional fields that should only be patched when provided.

func (*PatchFieldBuilder) Lt

Lt sets a condition that checks the field is less than the given value.

func (*PatchFieldBuilder) Lte

Lte sets a condition that checks the field is less than or equal to the given value.

func (*PatchFieldBuilder) Ne

Ne sets a condition that checks the field is not equal to the given value.

func (*PatchFieldBuilder) NotEmpty

func (b *PatchFieldBuilder) NotEmpty() *PatchFieldBuilder

NotEmpty guards the field with a non-empty string check (CUE: != ""). Use this for string fields that should only be patched when non-empty.

func (*PatchFieldBuilder) RawCondition

func (b *PatchFieldBuilder) RawCondition(c string) *PatchFieldBuilder

RawCondition sets a raw CUE condition string. Use this as an escape hatch for non-standard conditions not covered by the typed API.

func (*PatchFieldBuilder) Str

Str is shorthand for Type("string").

func (*PatchFieldBuilder) Strategy

func (b *PatchFieldBuilder) Strategy(s string) *PatchFieldBuilder

Strategy sets the patch strategy (e.g., "replace", "retainKeys").

func (*PatchFieldBuilder) StringArray

func (b *PatchFieldBuilder) StringArray() *PatchFieldBuilder

StringArray is shorthand for Type("[...string]").

func (*PatchFieldBuilder) Target

Target sets the container field to patch, if different from the parameter name.

func (*PatchFieldBuilder) Type

Type sets an explicit CUE type string (e.g., "string", "[...string]", "{...}").

type PatchKeyOp

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

PatchKeyOp represents a patch operation with a // +patchKey=name annotation. This is used for array merging strategies in Kubernetes strategic merge patch.

func (*PatchKeyOp) Elements

func (p *PatchKeyOp) Elements() []Value

Elements returns the array elements to patch.

func (*PatchKeyOp) Key

func (p *PatchKeyOp) Key() string

Key returns the patch key for array merging.

func (*PatchKeyOp) Path

func (p *PatchKeyOp) Path() string

Path returns the path being patched.

type PatchResource

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

PatchResource represents a patch being built for traits. It uses the same fluent API as Resource but generates a patch: block.

func NewPatchResource

func NewPatchResource() *PatchResource

NewPatchResource creates a new patch resource builder.

func (*PatchResource) EndIf

func (p *PatchResource) EndIf() *PatchResource

EndIf ends the current conditional block.

func (*PatchResource) ForEach

func (p *PatchResource) ForEach(source Value, path string) *PatchResource

ForEach adds a for-each spread operation to the patch. This generates: for k, v in parameter { (k): v } Used for traits like labels that spread map keys dynamically.

Example:

tpl.Patch().ForEach(labels, "metadata.labels")
// Generates: metadata: labels: { for k, v in parameter { (k): v } }

func (*PatchResource) If

func (p *PatchResource) If(cond Condition) *PatchResource

If starts a conditional block. Operations until EndIf are conditional.

func (*PatchResource) Ops

func (p *PatchResource) Ops() []ResourceOp

Ops returns all recorded operations.

func (*PatchResource) Passthrough

func (p *PatchResource) Passthrough() *PatchResource

Passthrough sets the patch to pass through the entire parameter. This generates CUE like: patch: parameter Used for json-patch and json-merge-patch traits where the parameter IS the patch.

func (*PatchResource) PatchKey

func (p *PatchResource) PatchKey(path string, key string, elements ...Value) *PatchResource

PatchKey adds an array patch with a merge key annotation. This generates: // +patchKey=key

path: [element1, element2, ...]

Used for merging arrays by key (e.g., containers by name).

Example:

tpl.Patch().PatchKey("spec.template.spec.containers", "name", container)

func (*PatchResource) PatchStrategyAnnotation

func (p *PatchResource) PatchStrategyAnnotation(path string, strategy string) *PatchResource

PatchStrategyAnnotation annotates a specific field path with // +patchStrategy=strategy. This generates a CUE comment annotation before the field. Example: p.PatchStrategyAnnotation("spec.strategy", "retainKeys") Generates: // +patchStrategy=retainKeys

strategy: { ... }

func (*PatchResource) Set

func (p *PatchResource) Set(path string, value Value) *PatchResource

Set records a field assignment in the patch. Example: p.Set("spec.replicas", replicas)

func (*PatchResource) SetIf

func (p *PatchResource) SetIf(cond Condition, path string, value Value) *PatchResource

SetIf records a conditional field assignment in the patch. Example: p.SetIf(cpu.IsSet(), "spec.resources.limits.cpu", cpu)

func (*PatchResource) SpreadAll

func (p *PatchResource) SpreadAll(path string, elements ...Value) *PatchResource

SpreadAll adds a spread constraint that applies to all array elements. This generates: path: [...{element1}, ...{element2}] Used for applying the same patch to every element in an array.

Example:

lifecycleObj := defkit.NewArrayElement().
    SetIf(postStart.IsSet(), "lifecycle.postStart", postStart)
tpl.Patch().SpreadAll("spec.template.spec.containers", lifecycleObj)
// Generates: containers: [...{lifecycle: { if ... { postStart: ... } }}]

func (*PatchResource) SpreadIf

func (p *PatchResource) SpreadIf(cond Condition, path string, value Value) *PatchResource

SpreadIf records a conditional spread operation inside a struct block in the patch. Example: p.SpreadIf(labels.IsSet(), "metadata.labels", labels)

type PatchStrategyAnnotationOp

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

PatchStrategyAnnotationOp records a patchStrategy annotation on a field path.

func (*PatchStrategyAnnotationOp) Path

Path returns the path being annotated.

func (*PatchStrategyAnnotationOp) Strategy

func (p *PatchStrategyAnnotationOp) Strategy() string

Strategy returns the patch strategy value.

type PathExistsCondition

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

PathExistsCondition checks if a path exists in CUE (path != _|_).

func PathExists

func PathExists(path string) *PathExistsCondition

PathExists creates a condition that checks if a path exists. In CUE: path != _|_

func (*PathExistsCondition) Path

func (p *PathExistsCondition) Path() string

Path returns the path being checked.

type PlacementConditionOutput

type PlacementConditionOutput struct {
	Key      string   `json:"key"`
	Operator string   `json:"operator"`
	Values   []string `json:"values,omitempty"`
}

PlacementConditionOutput represents a single placement condition in the output.

type PlacementOutput

type PlacementOutput struct {
	RunOn    []PlacementConditionOutput `json:"runOn,omitempty"`
	NotRunOn []PlacementConditionOutput `json:"notRunOn,omitempty"`
}

PlacementOutput represents placement constraints in the registry output.

type PlusExpr

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

PlusExpr represents a + operator between multiple values. Generates CUE: a + b + c Works for string concatenation, array concatenation, etc.

func Plus

func Plus(parts ...Value) *PlusExpr

Plus creates a + expression between values. Generates CUE: parts[0] + parts[1] + ...

func (*PlusExpr) Parts

func (p *PlusExpr) Parts() []Value

Parts returns the operands.

type PolicyCUEGenerator

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

PolicyCUEGenerator generates CUE definitions for policies.

func NewPolicyCUEGenerator

func NewPolicyCUEGenerator() *PolicyCUEGenerator

NewPolicyCUEGenerator creates a new policy CUE generator.

func (*PolicyCUEGenerator) GenerateFullDefinition

func (g *PolicyCUEGenerator) GenerateFullDefinition(p *PolicyDefinition) string

GenerateFullDefinition generates the complete CUE definition for a policy.

func (*PolicyCUEGenerator) GenerateTemplate

func (g *PolicyCUEGenerator) GenerateTemplate(p *PolicyDefinition) string

GenerateTemplate generates the template block for a policy.

func (*PolicyCUEGenerator) WithImports

func (g *PolicyCUEGenerator) WithImports(imports ...string) *PolicyCUEGenerator

WithImports adds CUE imports.

type PolicyDefinition

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

PolicyDefinition represents a KubeVela PolicyDefinition. Policies define application-level behaviors such as topology (where to deploy), override (how to customize components), and health (how to check application health).

func NewPolicy

func NewPolicy(name string) *PolicyDefinition

NewPolicy creates a new PolicyDefinition builder.

func Policies

func Policies() []*PolicyDefinition

Policies returns all registered PolicyDefinitions.

func (*PolicyDefinition) Annotations

func (p *PolicyDefinition) Annotations(annotations map[string]string) *PolicyDefinition

Annotations sets metadata annotations on the policy definition.

func (*PolicyDefinition) CustomStatus

func (p *PolicyDefinition) CustomStatus(expr string) *PolicyDefinition

CustomStatus sets the custom status CUE expression for the policy. This provides status visibility in the application status.

func (*PolicyDefinition) DefName

func (p *PolicyDefinition) DefName() string

DefName implements Definition.DefName.

func (*PolicyDefinition) DefType

func (p *PolicyDefinition) DefType() DefinitionType

DefType implements Definition.DefType.

func (*PolicyDefinition) Description

func (p *PolicyDefinition) Description(desc string) *PolicyDefinition

Description sets the policy description.

func (*PolicyDefinition) GetAnnotations

func (b *PolicyDefinition) GetAnnotations() map[string]string

GetAnnotations returns the annotations map.

func (*PolicyDefinition) GetConditionalParamBlocks

func (b *PolicyDefinition) GetConditionalParamBlocks() []*ConditionalParamBlock

GetConditionalParamBlocks returns the conditional parameter blocks.

func (*PolicyDefinition) GetCustomStatus

func (b *PolicyDefinition) GetCustomStatus() string

GetCustomStatus returns the custom status CUE expression.

func (*PolicyDefinition) GetDescription

func (b *PolicyDefinition) GetDescription() string

GetDescription returns the definition description.

func (*PolicyDefinition) GetHealthPolicy

func (b *PolicyDefinition) GetHealthPolicy() string

GetHealthPolicy returns the health policy CUE expression.

func (*PolicyDefinition) GetHelperDefinitions

func (b *PolicyDefinition) GetHelperDefinitions() []HelperDefinition

GetHelperDefinitions returns all helper type definitions.

func (*PolicyDefinition) GetImports

func (b *PolicyDefinition) GetImports() []string

GetImports returns the CUE imports.

func (*PolicyDefinition) GetLabels

func (p *PolicyDefinition) GetLabels() map[string]string

GetLabels returns the policy's metadata labels.

func (*PolicyDefinition) GetName

func (b *PolicyDefinition) GetName() string

GetName returns the definition name.

func (*PolicyDefinition) GetNotRunOn

func (b *PolicyDefinition) GetNotRunOn() []placement.Condition

GetNotRunOn returns the NotRunOn placement conditions.

func (*PolicyDefinition) GetParams

func (b *PolicyDefinition) GetParams() []Param

GetParams returns all parameter definitions.

func (*PolicyDefinition) GetPlacement

func (b *PolicyDefinition) GetPlacement() placement.PlacementSpec

GetPlacement returns the complete placement spec for this definition.

func (*PolicyDefinition) GetRawCUE

func (b *PolicyDefinition) GetRawCUE() string

GetRawCUE returns the raw CUE template if set.

func (*PolicyDefinition) GetRawCUEWithName

func (b *PolicyDefinition) GetRawCUEWithName() string

GetRawCUEWithName returns the raw CUE with the definition name rewritten to match the name set via NewComponent/NewTrait/etc. This ensures the name passed to the fluent builder takes precedence over any name embedded in the raw CUE string.

func (*PolicyDefinition) GetRunOn

func (b *PolicyDefinition) GetRunOn() []placement.Condition

GetRunOn returns the RunOn placement conditions.

func (*PolicyDefinition) GetStatusDetails

func (b *PolicyDefinition) GetStatusDetails() string

GetStatusDetails returns the status details CUE expression.

func (*PolicyDefinition) GetTemplate

func (b *PolicyDefinition) GetTemplate() func(tpl *Template)

GetTemplate returns the template function.

func (*PolicyDefinition) GetValidators

func (b *PolicyDefinition) GetValidators() []*Validator

GetValidators returns the top-level validators.

func (*PolicyDefinition) GetVersion

func (b *PolicyDefinition) GetVersion() string

GetVersion returns the version string.

func (*PolicyDefinition) HasPlacement

func (b *PolicyDefinition) HasPlacement() bool

HasPlacement returns true if the definition has any placement constraints.

func (*PolicyDefinition) HasRawCUE

func (b *PolicyDefinition) HasRawCUE() bool

HasRawCUE returns true if raw CUE is set.

func (*PolicyDefinition) HasTemplate

func (b *PolicyDefinition) HasTemplate() bool

HasTemplate returns true if the definition has a template function set.

func (*PolicyDefinition) HealthPolicy

func (p *PolicyDefinition) HealthPolicy(expr string) *PolicyDefinition

HealthPolicy sets the health policy CUE expression for the policy. This defines how the policy's health is determined.

func (*PolicyDefinition) HealthPolicyExpr

func (p *PolicyDefinition) HealthPolicyExpr(expr HealthExpression) *PolicyDefinition

HealthPolicyExpr sets the health policy using a composable HealthExpression.

func (*PolicyDefinition) Helper

func (p *PolicyDefinition) Helper(name string, param Param) *PolicyDefinition

Helper adds a helper type definition using fluent API. The param defines the schema for the helper type. Example:

Helper("RuleSelector", defkit.Struct("selector").Fields(...))

func (*PolicyDefinition) IsManageHealthCheck

func (p *PolicyDefinition) IsManageHealthCheck() bool

IsManageHealthCheck returns whether this policy manages health checks.

func (*PolicyDefinition) Labels

func (p *PolicyDefinition) Labels(labels map[string]string) *PolicyDefinition

Labels sets metadata labels for the policy definition.

func (*PolicyDefinition) ManageHealthCheck

func (p *PolicyDefinition) ManageHealthCheck() *PolicyDefinition

ManageHealthCheck marks this policy as managing health checks.

func (*PolicyDefinition) NotRunOn

func (p *PolicyDefinition) NotRunOn(conditions ...placement.Condition) *PolicyDefinition

NotRunOn adds placement conditions specifying which clusters this policy should NOT run on. Use the placement package's fluent API to build conditions.

Example:

defkit.NewPolicy("no-vclusters").
    NotRunOn(placement.Label("cluster-type").Eq("vcluster"))

If any NotRunOn condition matches, the policy is ineligible for that cluster.

func (*PolicyDefinition) Param

func (p *PolicyDefinition) Param(param Param) *PolicyDefinition

Param adds a single parameter definition to the policy. This provides a more fluent API when adding parameters one at a time.

func (*PolicyDefinition) Params

func (p *PolicyDefinition) Params(params ...Param) *PolicyDefinition

Params adds multiple parameter definitions to the policy.

func (*PolicyDefinition) RawCUE

func (p *PolicyDefinition) RawCUE(cue string) *PolicyDefinition

RawCUE sets raw CUE for complex policy definitions that don't fit the builder pattern.

func (*PolicyDefinition) RunOn

func (p *PolicyDefinition) RunOn(conditions ...placement.Condition) *PolicyDefinition

RunOn adds placement conditions specifying which clusters this policy should run on. Use the placement package's fluent API to build conditions.

Example:

defkit.NewPolicy("eks-topology").
    RunOn(placement.Label("provider").Eq("aws"))

Multiple RunOn calls are combined with AND semantics (all conditions must match).

func (*PolicyDefinition) StatusDetails

func (p *PolicyDefinition) StatusDetails(details string) *PolicyDefinition

StatusDetails sets the status details CUE expression for the policy.

func (*PolicyDefinition) Template

func (p *PolicyDefinition) Template(fn func(tpl *PolicyTemplate)) *PolicyDefinition

Template sets the template function for the policy. Most policies only need parameters, but this allows for computed values.

func (*PolicyDefinition) ToCue

func (p *PolicyDefinition) ToCue() string

ToCue generates the complete CUE definition string for this policy.

func (*PolicyDefinition) ToYAML

func (p *PolicyDefinition) ToYAML() ([]byte, error)

ToYAML generates the Kubernetes YAML representation of the PolicyDefinition.

func (*PolicyDefinition) Version

func (p *PolicyDefinition) Version(v string) *PolicyDefinition

Version sets the version string for the policy definition.

func (*PolicyDefinition) WithImports

func (p *PolicyDefinition) WithImports(imports ...string) *PolicyDefinition

WithImports adds CUE imports to the policy definition.

type PolicyTemplate

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

PolicyTemplate provides the building context for policy templates. Policies typically just define parameters and let the vela runtime handle the logic.

func NewPolicyTemplate

func NewPolicyTemplate() *PolicyTemplate

NewPolicyTemplate creates a new policy template.

func (*PolicyTemplate) GetComputedFields

func (pt *PolicyTemplate) GetComputedFields() map[string]Value

GetComputedFields returns all computed fields.

func (*PolicyTemplate) Set

func (pt *PolicyTemplate) Set(name string, value Value) *PolicyTemplate

Set sets a computed field value.

type Predicate

type Predicate interface {
	// contains filtered or unexported methods
}

Predicate represents a filter condition.

type RawCUECondition

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

RawCUECondition wraps a raw CUE expression string as a Condition. Use this for expressions too complex to model with the fluent API.

Example: CUEExpr(`len("tenant-"+parameter.governance.tenantName+"-"+name) > 63`)

func CUEExpr

func CUEExpr(rawExpr string) *RawCUECondition

CUEExpr creates a condition from a raw CUE expression string. The expression is emitted verbatim in the generated CUE.

func (*RawCUECondition) Expr

func (c *RawCUECondition) Expr() string

Expr returns the raw CUE expression.

type Ref

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

Ref creates a raw reference expression. Use this for referencing CUE variables like "v.protocol" or "context.output".

func ParamRef

func ParamRef(field string) *Ref

ParamRef creates a reference to a parameter field for use in expressions. This is more explicit than ParameterField and is intended for use with list comprehensions and other value expressions. Example: ParamRef("constraints") generates "parameter.constraints"

func Parameter

func Parameter() *Ref

Parameter creates a reference to a parameter value. This generates "parameter" or "parameter.fieldName" in CUE.

func ParameterField

func ParameterField(field string) *Ref

ParameterField creates a reference to a field within parameter. Example: ParameterField("replicas") generates "parameter.replicas"

func Reference

func Reference(path string) *Ref

Reference creates a raw reference to a CUE path. Example: Reference("v.protocol") for use in comprehensions

func (*Ref) Path

func (r *Ref) Path() string

Path returns the reference path.

type RegexMatchCondition

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

RegexMatchCondition checks if any Value matches a regex pattern. Generates: <value> =~ "pattern" Used by both LocalFieldRef.Matches() and StringParam.Matches().

func RegexMatch

func RegexMatch(source Value, pattern string) *RegexMatchCondition

RegexMatch creates a condition that checks if a value matches a regex pattern.

func (*RegexMatchCondition) Pattern

func (c *RegexMatchCondition) Pattern() string

Pattern returns the regex pattern.

func (*RegexMatchCondition) Source

func (c *RegexMatchCondition) Source() Value

Source returns the value being matched.

type RegistryOutput

type RegistryOutput struct {
	Definitions []DefinitionOutput `json:"definitions"`
}

RegistryOutput is the JSON structure output by the generated main program. It contains all registered definitions in a format the CLI can parse.

type RenderedOutputs

type RenderedOutputs struct {
	Primary   *RenderedResource
	Auxiliary map[string]*RenderedResource
}

RenderedOutputs contains all rendered resources from a template.

type RenderedResource

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

RenderedResource represents a fully rendered Kubernetes resource with all parameter values resolved.

func (*RenderedResource) APIVersion

func (r *RenderedResource) APIVersion() string

APIVersion returns the resource's API version.

func (*RenderedResource) Data

func (r *RenderedResource) Data() map[string]any

Data returns the full rendered resource data.

func (*RenderedResource) Get

func (r *RenderedResource) Get(path string) any

Get retrieves a value at the given path (e.g., "spec.replicas").

func (*RenderedResource) Kind

func (r *RenderedResource) Kind() string

Kind returns the resource's kind.

type Resource

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

Resource represents a Kubernetes resource being built.

func FromTyped

func FromTyped(obj runtime.Object) (*Resource, error)

FromTyped converts a typed Kubernetes object to a Resource. This provides compile-time type safety when building resources.

Example:

import appsv1 "k8s.io/api/apps/v1"

deployment := &appsv1.Deployment{
    ObjectMeta: metav1.ObjectMeta{Name: "my-app"},
    Spec: appsv1.DeploymentSpec{
        Replicas: ptr.To(int32(3)),
        // ... other fields
    },
}
return defkit.FromTyped(deployment)

The returned Resource contains Set operations for all fields in the object. You can chain additional Set operations on the returned Resource.

func MustFromTyped

func MustFromTyped(obj runtime.Object) *Resource

MustFromTyped is like FromTyped but panics on error. Use this when you're confident the object is valid.

func NewResource

func NewResource(apiVersion, kind string) *Resource

NewResource creates a new resource builder with API version and kind.

func NewResourceWithConditionalVersion

func NewResourceWithConditionalVersion(kind string) *Resource

NewResourceWithConditionalVersion creates a resource with conditional apiVersion. This is used when the apiVersion depends on runtime conditions like cluster version.

Example:

vela := defkit.VelaCtx()
cronjob := defkit.NewResourceWithConditionalVersion("CronJob").
    VersionIf(Lt(vela.ClusterVersion().Minor(), 25), "batch/v1beta1").
    VersionIf(Gte(vela.ClusterVersion().Minor(), 25), "batch/v1")

func (*Resource) APIVersion

func (r *Resource) APIVersion() string

APIVersion returns the resource's API version.

func (*Resource) ConditionalStruct

func (r *Resource) ConditionalStruct(cond Condition, path string, fn func(b *OutputStructBuilder)) *Resource

ConditionalStruct records a conditional struct block in the output. When the condition is true, the fields built by fn are emitted at the given path.

func (*Resource) Directive

func (r *Resource) Directive(path string, directive string) *Resource

Directive records a CUE directive annotation on a field path. The directive string should be like "patchKey=ip" and will be rendered as // +patchKey=ip.

func (*Resource) EndIf

func (r *Resource) EndIf() *Resource

EndIf ends the current conditional block.

func (*Resource) HasVersionConditionals

func (r *Resource) HasVersionConditionals() bool

HasVersionConditionals returns true if the resource has conditional apiVersion.

func (*Resource) If

func (r *Resource) If(cond Condition) *Resource

If starts a conditional block. Operations until EndIf are conditional.

func (*Resource) Kind

func (r *Resource) Kind() string

Kind returns the resource's kind.

func (*Resource) Ops

func (r *Resource) Ops() []ResourceOp

Ops returns all recorded operations.

func (*Resource) Set

func (r *Resource) Set(path string, value Value) *Resource

Set records a field assignment operation.

func (*Resource) SetIf

func (r *Resource) SetIf(cond Condition, path string, value Value) *Resource

SetIf records a conditional field assignment.

func (*Resource) SpreadIf

func (r *Resource) SpreadIf(cond Condition, path string, value Value) *Resource

SpreadIf records a conditional spread operation inside a struct block. Unlike SetIf which wraps the entire field in a conditional, SpreadIf spreads the value inside the block only when the condition is true, while the block itself always exists with its other fields.

Example usage:

Set("spec.template.metadata.labels[app.oam.dev/name]", vela.AppName()).
SpreadIf(labels.IsSet(), "spec.template.metadata.labels", labels)

Generates:

labels: {
    "app.oam.dev/name": context.appName
    if parameter.labels != _|_ {
        parameter.labels
    }
}

func (*Resource) VersionConditionals

func (r *Resource) VersionConditionals() []VersionConditional

VersionConditionals returns all conditional apiVersion settings.

func (*Resource) VersionIf

func (r *Resource) VersionIf(cond Condition, apiVersion string) *Resource

VersionIf adds a conditional apiVersion to the resource. When the condition is true, this apiVersion will be used.

type ResourceOp

type ResourceOp interface {
	// contains filtered or unexported methods
}

ResourceOp represents an operation recorded during resource building.

type SetIfOp

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

SetIfOp represents a conditional Set operation.

func (*SetIfOp) Cond

func (s *SetIfOp) Cond() Condition

Cond returns the condition for the operation.

func (*SetIfOp) Path

func (s *SetIfOp) Path() string

Path returns the field path.

func (*SetIfOp) Value

func (s *SetIfOp) Value() Value

Value returns the value being set.

type SetOp

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

SetOp represents a Set operation on a resource field.

func (*SetOp) Path

func (s *SetOp) Path() string

Path returns the field path.

func (*SetOp) Value

func (s *SetOp) Value() Value

Value returns the value being set.

type SpreadAllOp

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

SpreadAllOp represents a patch operation that constrains all array elements. This generates: path: [...{element}] Used for applying the same patch to every element in an array (e.g., all containers).

func (*SpreadAllOp) Elements

func (s *SpreadAllOp) Elements() []Value

Elements returns the array elements to constrain.

func (*SpreadAllOp) Path

func (s *SpreadAllOp) Path() string

Path returns the path being patched.

type SpreadIfOp

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

SpreadIfOp represents a conditional spread operation inside a block. Instead of conditionally setting a whole field, it spreads a value inside a block when a condition is met. Example: labels: { if param.labels != _|_ { parameter.labels } ... }

func (*SpreadIfOp) Cond

func (s *SpreadIfOp) Cond() Condition

Cond returns the condition for the spread.

func (*SpreadIfOp) Path

func (s *SpreadIfOp) Path() string

Path returns the parent field path.

func (*SpreadIfOp) Value

func (s *SpreadIfOp) Value() Value

Value returns the value being spread.

type StatusBuilder

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

StatusBuilder provides a fluent API for building component status expressions.

func DaemonSetStatus

func DaemonSetStatus() *StatusBuilder

DaemonSetStatus returns a pre-configured status builder for DaemonSet.

func DeploymentStatus

func DeploymentStatus() *StatusBuilder

DeploymentStatus returns a pre-configured status builder for Deployment. Matches the original CUE structure which uses spec.replicas for desired count.

func StatefulSetStatus

func StatefulSetStatus() *StatusBuilder

StatefulSetStatus returns a pre-configured status builder for StatefulSet.

func Status

func Status() *StatusBuilder

Status creates a new status builder.

func (*StatusBuilder) Build

func (s *StatusBuilder) Build() string

Build generates the CUE expression for customStatus.

func (*StatusBuilder) Case

func (s *StatusBuilder) Case(condition StatusCondition, message any) *StatusCase

Case creates a case for use in Switch. Example: s.Case(s.Field("status.phase").Eq("Running"), "Service is running")

func (*StatusBuilder) Concat

func (s *StatusBuilder) Concat(parts ...any) StatusExpression

Concat creates a concatenation of multiple expressions or strings. Example: Status().Concat("Ready: ", s.Field("status.ready"), "/", s.Field("status.total"))

func (*StatusBuilder) Condition

func (s *StatusBuilder) Condition(condType string) *StatusConditionAccessor

Condition creates an accessor for a status condition. Example: Status().Condition("Ready").Message()

func (*StatusBuilder) Default

func (s *StatusBuilder) Default(message any) StatusExpression

Default creates a default case for Switch. Example: s.Default("Unknown status")

func (*StatusBuilder) Detail

func (s *StatusBuilder) Detail(key string, value StatusExpression) *StatusDetail

Detail creates a detail entry for use with WithDetails. Example: s.Detail("endpoint", s.Field("status.endpoint"))

func (*StatusBuilder) Exists

func (s *StatusBuilder) Exists(path string) *statusExistsExpr

Exists creates an expression to check if a field exists. Example: Status().Exists("status.endpoint")

func (*StatusBuilder) Field

func (s *StatusBuilder) Field(path string) *StatusFieldExpr

Field creates an expression to extract a status field value. Example: Status().Field("status.readyReplicas").Default(0)

func (*StatusBuilder) Format

func (s *StatusBuilder) Format(template string, args ...StatusExpression) StatusExpression

Format creates a printf-style formatted message. Example: Status().Format("Ready: %v/%v", readyField, totalField)

func (*StatusBuilder) HealthAware

func (s *StatusBuilder) HealthAware(healthyMsg, unhealthyMsg any) StatusExpression

HealthAware creates a message that differs based on health status. Example: Status().HealthAware("All systems operational", "Service degraded")

func (*StatusBuilder) IntField

func (s *StatusBuilder) IntField(name, sourcePath string, defaultVal int) *StatusBuilder

IntField adds an integer field derived from output status. Usage: .IntField("ready.replicas", "status.numberReady", 0)

func (*StatusBuilder) Literal

func (s *StatusBuilder) Literal(value string) StatusExpression

Literal creates a literal string expression. Example: Status().Literal("Service is running")

func (*StatusBuilder) Message

func (s *StatusBuilder) Message(msg string) *StatusBuilder

Message sets the status message template. Use \(fieldName) for field interpolation (CUE syntax). Usage: .Message("Ready:\\(ready.replicas)/\\(desired.replicas)")

func (*StatusBuilder) NotExists

func (s *StatusBuilder) NotExists(path string) *statusExistsExpr

NotExists creates an expression to check if a field does not exist. Example: Status().NotExists("status.error")

func (*StatusBuilder) RawCUE

func (s *StatusBuilder) RawCUE(cue string) *StatusBuilder

RawCUE sets raw CUE for complex status expressions that don't fit the builder pattern.

func (*StatusBuilder) SpecField

func (s *StatusBuilder) SpecField(path string) *StatusFieldExpr

SpecField creates an expression to extract a spec field value. Example: Status().SpecField("spec.replicas")

func (*StatusBuilder) StatusExpr

func (s *StatusBuilder) StatusExpr(expr StatusExpression) *StatusBuilder

StatusExpr sets the status expression using a composable StatusExpression. This generates the complete customStatus CUE block. Example: Status().StatusExpr(s.Concat("Ready: ", s.Field("status.ready")))

func (*StatusBuilder) StringField

func (s *StatusBuilder) StringField(name, sourcePath string, defaultVal string) *StatusBuilder

StringField adds a string field derived from output status.

func (*StatusBuilder) Switch

func (s *StatusBuilder) Switch(casesAndDefault ...any) StatusExpression

Switch creates a conditional message selection. Example: Status().Switch(case1, case2, s.Default("Unknown"))

func (*StatusBuilder) WithDetails

func (s *StatusBuilder) WithDetails(message StatusExpression, details ...*StatusDetail) StatusExpression

WithDetails creates a status expression that includes structured details alongside the message. The details are key-value pairs that provide additional context.

Example:

s := Status()
CustomStatusExpr(s.WithDetails(
    s.Format("Ready: %v/%v", s.Field("status.readyReplicas").Default(0), s.SpecField("spec.replicas")),
    s.Detail("endpoint", s.Field("status.endpoint")),
    s.Detail("version", s.Field("status.version")),
))

type StatusCase

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

StatusCase represents a case in a Switch expression.

type StatusCondition

type StatusCondition interface {
	// ToCUECondition generates the CUE boolean expression.
	ToCUECondition() string
	// Preamble returns any CUE definitions needed.
	Preamble() string
}

StatusCondition represents a boolean condition for use in Switch cases.

type StatusConditionAccessor

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

StatusConditionAccessor provides methods to access different fields of a condition.

func (*StatusConditionAccessor) Is

Is checks if the condition's status equals a value (for use in Switch).

func (*StatusConditionAccessor) Message

Message returns an expression for the condition's message field.

func (*StatusConditionAccessor) Reason

Reason returns an expression for the condition's reason field.

func (*StatusConditionAccessor) StatusValue

StatusValue returns an expression for the condition's status field.

type StatusConditionFieldExpr

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

StatusConditionFieldExpr provides access to fields within a status condition.

func (*StatusConditionFieldExpr) Is

Is checks if the condition field equals a value.

func (*StatusConditionFieldExpr) IsStringExpr

func (c *StatusConditionFieldExpr) IsStringExpr() bool

func (*StatusConditionFieldExpr) Preamble

func (c *StatusConditionFieldExpr) Preamble() string

func (*StatusConditionFieldExpr) ToCUE

func (c *StatusConditionFieldExpr) ToCUE() string

type StatusDetail

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

StatusDetail represents a key-value detail.

type StatusExpression

type StatusExpression interface {
	// ToCUE generates the CUE expression for this status component.
	// The expression should evaluate to a string for the message.
	ToCUE() string

	// Preamble returns any CUE definitions needed before the message expression.
	// For example, field extractions need helper variables.
	Preamble() string

	// IsStringExpr returns true if this expression produces a string value
	// that can be used directly in CUE interpolation.
	IsStringExpr() bool
}

StatusExpression is the composable unit for building custom status messages. All status primitives implement this interface and can be combined to create dynamic status messages.

type StatusField

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

StatusField represents a status field derived from the output.

type StatusFieldExpr

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

StatusFieldExpr extracts a field value from the output status.

func (*StatusFieldExpr) Default

func (f *StatusFieldExpr) Default(value any) *StatusFieldExpr

Default sets a default value if the field doesn't exist.

func (*StatusFieldExpr) Eq

func (f *StatusFieldExpr) Eq(value any) StatusCondition

Eq checks if the field equals a value (returns a StatusConditionExpr for use in Switch).

func (*StatusFieldExpr) Gt

func (f *StatusFieldExpr) Gt(value any) StatusCondition

Gt checks if the field is greater than a value.

func (*StatusFieldExpr) Gte

func (f *StatusFieldExpr) Gte(value any) StatusCondition

Gte checks if the field is greater than or equal to a value.

func (*StatusFieldExpr) IsStringExpr

func (f *StatusFieldExpr) IsStringExpr() bool

func (*StatusFieldExpr) Lt

func (f *StatusFieldExpr) Lt(value any) StatusCondition

Lt checks if the field is less than a value.

func (*StatusFieldExpr) Lte

func (f *StatusFieldExpr) Lte(value any) StatusCondition

Lte checks if the field is less than or equal to a value.

func (*StatusFieldExpr) Ne

func (f *StatusFieldExpr) Ne(value any) StatusCondition

Ne checks if the field does not equal a value.

func (*StatusFieldExpr) Preamble

func (f *StatusFieldExpr) Preamble() string

func (*StatusFieldExpr) ToCUE

func (f *StatusFieldExpr) ToCUE() string

type StringContainsCondition

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

StringContainsCondition checks if a string parameter contains a substring. Generates: strings.Contains(parameter.name, "substr")

func (*StringContainsCondition) ParamName

func (c *StringContainsCondition) ParamName() string

ParamName returns the parameter name being checked.

func (*StringContainsCondition) Substr

func (c *StringContainsCondition) Substr() string

Substr returns the substring to check for.

type StringEndsWithCondition

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

StringEndsWithCondition checks if a string parameter ends with a suffix. Generates: strings.HasSuffix(parameter.name, "suffix")

func (*StringEndsWithCondition) ParamName

func (c *StringEndsWithCondition) ParamName() string

ParamName returns the parameter name being checked.

func (*StringEndsWithCondition) Suffix

func (c *StringEndsWithCondition) Suffix() string

Suffix returns the suffix to check for.

type StringKeyMapParam

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

StringKeyMapParam represents a map with string keys and string values. In CUE: [string]: string

func StringKeyMap

func StringKeyMap(name string) *StringKeyMapParam

StringKeyMap creates a new string-to-string map parameter. Generates CUE like: labels?: [string]: string

func (*StringKeyMapParam) Default

func (p *StringKeyMapParam) Default(value map[string]string) *StringKeyMapParam

Default sets a default value for the parameter.

func (*StringKeyMapParam) Description

func (p *StringKeyMapParam) Description(desc string) *StringKeyMapParam

Description sets the parameter description.

func (*StringKeyMapParam) Eq

func (p *StringKeyMapParam) Eq(val any) Condition

Eq creates a condition that compares this parameter to a literal value. Example: replicas.Eq(3) generates: parameter.replicas == 3

func (*StringKeyMapParam) GetDefault

func (p *StringKeyMapParam) GetDefault() any

func (*StringKeyMapParam) GetDescription

func (p *StringKeyMapParam) GetDescription() string

func (*StringKeyMapParam) GetShort

func (p *StringKeyMapParam) GetShort() string

func (*StringKeyMapParam) GetType

func (p *StringKeyMapParam) GetType() ParamType

GetType returns the parameter type.

func (*StringKeyMapParam) Gt

func (p *StringKeyMapParam) Gt(val any) Condition

Gt creates a condition that checks if this parameter is greater than a value. Example: replicas.Gt(1) generates: parameter.replicas > 1

func (*StringKeyMapParam) Gte

func (p *StringKeyMapParam) Gte(val any) Condition

Gte creates a condition that checks if this parameter is greater than or equal to a value. Example: replicas.Gte(1) generates: parameter.replicas >= 1

func (*StringKeyMapParam) HasDefault

func (p *StringKeyMapParam) HasDefault() bool

func (*StringKeyMapParam) HasKey

func (p *StringKeyMapParam) HasKey(key string) Condition

HasKey creates a condition that checks if this map has a specific key. Example: labels.HasKey("app") generates: parameter.labels.app != _|_

func (*StringKeyMapParam) IsEmpty

func (p *StringKeyMapParam) IsEmpty() Condition

IsEmpty creates a condition that checks if this map is absent or empty. Renders as two if blocks (absent + set-and-empty). See AbsentOrEmptyCondition.

func (*StringKeyMapParam) IsIgnore

func (p *StringKeyMapParam) IsIgnore() bool

func (*StringKeyMapParam) IsNotEmpty

func (p *StringKeyMapParam) IsNotEmpty() Condition

IsNotEmpty creates a condition that checks if this map is set and non-empty. Example: labels.IsNotEmpty() generates: parameter["labels"] != _|_ if len(parameter["labels"]) > 0

func (*StringKeyMapParam) IsOptional

func (p *StringKeyMapParam) IsOptional() bool

func (*StringKeyMapParam) IsRequired

func (p *StringKeyMapParam) IsRequired() bool

func (*StringKeyMapParam) IsSet

func (p *StringKeyMapParam) IsSet() Condition

IsSet returns a condition that checks if the parameter has a value. This is used with SetIf for conditional field assignment.

func (*StringKeyMapParam) LenEq

func (p *StringKeyMapParam) LenEq(n int) Condition

LenEq creates a condition that checks if this map has exactly n entries. Example: labels.LenEq(3) generates: parameter["labels"] != _|_ if len(parameter["labels"]) == 3

LenEq(0) is treated as "absent OR empty" — equivalent to IsEmpty().

func (*StringKeyMapParam) LenGt

func (p *StringKeyMapParam) LenGt(n int) Condition

LenGt creates a condition that checks if this map has more than n entries. Example: labels.LenGt(0) generates: parameter["labels"] != _|_ if len(parameter["labels"]) > 0

func (*StringKeyMapParam) Lt

func (p *StringKeyMapParam) Lt(val any) Condition

Lt creates a condition that checks if this parameter is less than a value. Example: replicas.Lt(10) generates: parameter.replicas < 10

func (*StringKeyMapParam) Lte

func (p *StringKeyMapParam) Lte(val any) Condition

Lte creates a condition that checks if this parameter is less than or equal to a value. Example: replicas.Lte(10) generates: parameter.replicas <= 10

func (*StringKeyMapParam) Name

func (p *StringKeyMapParam) Name() string

func (*StringKeyMapParam) Ne

func (p *StringKeyMapParam) Ne(val any) Condition

Ne creates a condition that checks if this parameter is not equal to a value. Example: status.Ne("error") generates: parameter.status != "error"

func (*StringKeyMapParam) NotSet

func (p *StringKeyMapParam) NotSet() Condition

NotSet returns a condition that checks if the parameter is not set. This generates `if parameter["name"] == _|_` in CUE.

func (*StringKeyMapParam) Optional

func (p *StringKeyMapParam) Optional() *StringKeyMapParam

Optional marks the parameter as optional, emitting the "?" CUE marker.

func (*StringKeyMapParam) Required

func (p *StringKeyMapParam) Required() *StringKeyMapParam

Required marks the parameter as required in input, emitting the "!" CUE marker.

type StringParam

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

StringParam represents a string parameter.

func String

func String(name string) *StringParam

String creates a new string parameter with the given name.

func (*StringParam) Concat

func (p *StringParam) Concat(suffix string) Value

Concat creates a string concatenation expression. Example: name.Concat("-suffix") generates: parameter.name + "-suffix"

func (*StringParam) Contains

func (p *StringParam) Contains(substr string) Condition

Contains creates a condition that checks if this string parameter contains a substring. Example: name.Contains("prod") generates: strings.Contains(parameter.name, "prod")

func (*StringParam) Default

func (p *StringParam) Default(value string) *StringParam

Default sets a default value for the parameter.

func (*StringParam) Description

func (p *StringParam) Description(desc string) *StringParam

Description sets the parameter description.

func (*StringParam) EndsWith

func (p *StringParam) EndsWith(suffix string) Condition

EndsWith creates a condition that checks if this string parameter ends with a suffix. Example: name.EndsWith("-prod") generates: strings.HasSuffix(parameter.name, "-prod")

func (*StringParam) Eq

func (p *StringParam) Eq(val any) Condition

Eq creates a condition that compares this parameter to a literal value. Example: replicas.Eq(3) generates: parameter.replicas == 3

func (*StringParam) GetDefault

func (p *StringParam) GetDefault() any

func (*StringParam) GetDescription

func (p *StringParam) GetDescription() string

func (*StringParam) GetEnumValues

func (p *StringParam) GetEnumValues() []string

GetEnumValues returns the allowed enum values.

func (*StringParam) GetMaxLen

func (p *StringParam) GetMaxLen() *int

GetMaxLen returns the maximum length constraint, or nil if not set.

func (*StringParam) GetMinLen

func (p *StringParam) GetMinLen() *int

GetMinLen returns the minimum length constraint, or nil if not set.

func (*StringParam) GetNotEmpty

func (p *StringParam) GetNotEmpty() bool

GetNotEmpty returns whether the non-empty constraint is set.

func (*StringParam) GetPattern

func (p *StringParam) GetPattern() string

GetPattern returns the regex pattern constraint.

func (*StringParam) GetShort

func (p *StringParam) GetShort() string

func (*StringParam) Gt

func (p *StringParam) Gt(val any) Condition

Gt creates a condition that checks if this parameter is greater than a value. Example: replicas.Gt(1) generates: parameter.replicas > 1

func (*StringParam) Gte

func (p *StringParam) Gte(val any) Condition

Gte creates a condition that checks if this parameter is greater than or equal to a value. Example: replicas.Gte(1) generates: parameter.replicas >= 1

func (*StringParam) HasDefault

func (p *StringParam) HasDefault() bool

func (*StringParam) Ignore

func (p *StringParam) Ignore() *StringParam

Ignore marks the parameter as ignored by the UI. This generates a // +ignore directive in the CUE output.

func (*StringParam) In

func (p *StringParam) In(values ...string) Condition

In creates a condition that checks if this string parameter is one of the given values. Example: name.In("api", "web", "worker") generates: parameter.name == "api" || parameter.name == "web" || parameter.name == "worker"

func (*StringParam) IsIgnore

func (p *StringParam) IsIgnore() bool

func (*StringParam) IsOpenEnum

func (p *StringParam) IsOpenEnum() bool

IsOpenEnum returns whether the enum allows arbitrary strings beyond the listed values.

func (*StringParam) IsOptional

func (p *StringParam) IsOptional() bool

func (*StringParam) IsRequired

func (p *StringParam) IsRequired() bool

func (*StringParam) IsSet

func (p *StringParam) IsSet() Condition

IsSet returns a condition that checks if the parameter has a value. This is used with SetIf for conditional field assignment.

func (*StringParam) LenEq

func (p *StringParam) LenEq(n int) Condition

LenEq creates a condition that checks if this string parameter has exactly n characters. Example: name.LenEq(5) generates: parameter["name"] != _|_ if len(parameter["name"]) == 5

func (*StringParam) LenGt

func (p *StringParam) LenGt(n int) Condition

LenGt creates a condition that checks if this string parameter has more than n characters. Example: name.LenGt(5) generates: parameter["name"] != _|_ if len(parameter["name"]) > 5

func (*StringParam) LenGte

func (p *StringParam) LenGte(n int) Condition

LenGte creates a condition that checks if this string parameter has n or more characters. Example: name.LenGte(5) generates: parameter["name"] != _|_ if len(parameter["name"]) >= 5

func (*StringParam) LenLt

func (p *StringParam) LenLt(n int) Condition

LenLt creates a condition that checks if this string parameter has fewer than n characters. Example: name.LenLt(5) generates: parameter["name"] != _|_ if len(parameter["name"]) < 5

func (*StringParam) LenLte

func (p *StringParam) LenLte(n int) Condition

LenLte creates a condition that checks if this string parameter has n or fewer characters. Example: name.LenLte(5) generates: parameter["name"] != _|_ if len(parameter["name"]) <= 5

func (*StringParam) Lt

func (p *StringParam) Lt(val any) Condition

Lt creates a condition that checks if this parameter is less than a value. Example: replicas.Lt(10) generates: parameter.replicas < 10

func (*StringParam) Lte

func (p *StringParam) Lte(val any) Condition

Lte creates a condition that checks if this parameter is less than or equal to a value. Example: replicas.Lte(10) generates: parameter.replicas <= 10

func (*StringParam) Matches

func (p *StringParam) Matches(pattern string) Condition

Matches creates a condition that checks if this string parameter matches a regex pattern. Example: name.Matches("^prod-") generates: parameter.name =~ "^prod-"

func (*StringParam) MaxLen

func (p *StringParam) MaxLen(n int) *StringParam

MaxLen sets the maximum length constraint for the parameter. This generates CUE like: strings.MaxRunes(n)

func (*StringParam) MinLen

func (p *StringParam) MinLen(n int) *StringParam

MinLen sets the minimum length constraint for the parameter. This generates CUE like: strings.MinRunes(n)

func (*StringParam) Name

func (p *StringParam) Name() string

func (*StringParam) Ne

func (p *StringParam) Ne(val any) Condition

Ne creates a condition that checks if this parameter is not equal to a value. Example: status.Ne("error") generates: parameter.status != "error"

func (*StringParam) NotEmpty

func (p *StringParam) NotEmpty() *StringParam

NotEmpty adds a non-empty string constraint. This generates CUE like: string & !=""

func (*StringParam) NotSet

func (p *StringParam) NotSet() Condition

NotSet returns a condition that checks if the parameter is not set. This generates `if parameter["name"] == _|_` in CUE.

func (*StringParam) OpenEnum

func (p *StringParam) OpenEnum() *StringParam

OpenEnum marks the enum as open, allowing any string in addition to the enumerated values. This generates CUE like: "value1" | "value2" | string

func (*StringParam) Optional

func (p *StringParam) Optional() *StringParam

Optional marks the parameter as optional, emitting the "?" CUE marker. The field may be absent from input entirely.

func (*StringParam) Pattern

func (p *StringParam) Pattern(regex string) *StringParam

Pattern sets a regex pattern constraint for the parameter. This generates CUE like: string & =~"pattern"

func (*StringParam) Prepend

func (p *StringParam) Prepend(prefix string) Value

Prepend creates a string concatenation expression with a prefix. Example: name.Prepend("prefix-") generates: "prefix-" + parameter.name

func (*StringParam) Required

func (p *StringParam) Required() *StringParam

Required marks the parameter as required in input, emitting the "!" CUE marker. The user must explicitly provide this field — even if a default value exists.

func (*StringParam) RequiredImports

func (p *StringParam) RequiredImports() []string

RequiredImports returns the CUE imports needed by this parameter's constraints. MinLen/MaxLen generate strings.MinRunes()/strings.MaxRunes() which require "strings".

func (*StringParam) Short

func (p *StringParam) Short(s string) *StringParam

Short sets a short flag alias for the parameter. This generates a // +short=X directive in the CUE output.

func (*StringParam) StartsWith

func (p *StringParam) StartsWith(prefix string) Condition

StartsWith creates a condition that checks if this string parameter starts with a prefix. Example: name.StartsWith("prod-") generates: strings.HasPrefix(parameter.name, "prod-")

func (*StringParam) Values

func (p *StringParam) Values(values ...string) *StringParam

Values restricts the parameter to specific allowed values.

type StringStartsWithCondition

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

StringStartsWithCondition checks if a string parameter starts with a prefix. Generates: strings.HasPrefix(parameter.name, "prefix")

func (*StringStartsWithCondition) ParamName

func (c *StringStartsWithCondition) ParamName() string

ParamName returns the parameter name being checked.

func (*StringStartsWithCondition) Prefix

func (c *StringStartsWithCondition) Prefix() string

Prefix returns the prefix to check for.

type StructArrayBuilder

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

StructArrayBuilder provides a fluent API for building struct-based array helpers.

func (*StructArrayBuilder) Build

Build finalizes the struct array helper and registers it with the template.

func (*StructArrayBuilder) Field

func (b *StructArrayBuilder) Field(name string, mappings FieldMap) *StructArrayBuilder

Field adds a field to the struct array helper.

type StructArrayField

type StructArrayField struct {
	Name     string   // field name (e.g., "pvc", "configMap")
	Mappings FieldMap // how to map input fields to output
}

StructArrayField defines a field in a struct array helper.

type StructArrayHelper

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

StructArrayHelper represents a struct-based helper where each field is an array with a default empty value pattern: pvc: *[...] | [] This pattern is used in cron-task and other components for mountsArray/volumesArray.

func (*StructArrayHelper) Fields

func (s *StructArrayHelper) Fields() []StructArrayField

Fields returns all field definitions.

func (*StructArrayHelper) HelperName

func (s *StructArrayHelper) HelperName() string

HelperName returns the helper name.

func (*StructArrayHelper) Source

func (s *StructArrayHelper) Source() Value

Source returns the source parameter.

type StructBuilder

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

StructBuilder builds a struct value from fields.

func HelperStruct

func HelperStruct(fields ...StructFieldDef) *StructBuilder

HelperStruct creates a new struct builder with the given fields.

Example:

HelperStruct(
    HelperField("name", v.Get("name")),
    HelperField("mountPath", v.Get("mountPath")),
    HelperFieldIf(IsSet(v.Get("subPath")), "subPath", v.Get("subPath")),
)

func (*StructBuilder) Fields

func (s *StructBuilder) Fields() []StructFieldDef

Fields returns the struct fields for CUE generation.

type StructField

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

StructField represents a field within a struct parameter.

func Field

func Field(name string, fieldType ParamType) *StructField

Field creates a new struct field definition.

func (*StructField) Default

func (f *StructField) Default(value any) *StructField

Default sets a default value for the field.

func (*StructField) Description

func (f *StructField) Description(desc string) *StructField

Description sets the field description.

func (*StructField) FieldType

func (f *StructField) FieldType() ParamType

FieldType returns the field type.

func (*StructField) GetDefault

func (f *StructField) GetDefault() any

GetDefault returns the default value.

func (*StructField) GetDescription

func (f *StructField) GetDescription() string

GetDescription returns the field description.

func (*StructField) GetElementType

func (f *StructField) GetElementType() ParamType

GetElementType returns the element type for array fields.

func (*StructField) GetEnumValues

func (f *StructField) GetEnumValues() []string

GetEnumValues returns the allowed enum values.

func (*StructField) GetNested

func (f *StructField) GetNested() *StructParam

GetNested returns the nested struct definition, if any.

func (*StructField) GetSchemaRef

func (f *StructField) GetSchemaRef() string

GetSchemaRef returns the schema reference for this field.

func (*StructField) HasDefault

func (f *StructField) HasDefault() bool

HasDefault returns true if the field has a default value.

func (*StructField) IsOptional

func (f *StructField) IsOptional() bool

IsOptional returns true if the field emits the "?" CUE marker — field may be absent from input.

func (*StructField) IsRequired

func (f *StructField) IsRequired() bool

IsRequired returns true if the field emits the "!" CUE marker — user must explicitly provide it.

func (*StructField) Name

func (f *StructField) Name() string

Name returns the field name.

func (*StructField) Nested

func (f *StructField) Nested(s *StructParam) *StructField

Nested sets a nested struct definition for this field. For ParamTypeStruct fields, this defines the struct's shape. For ParamTypeArray fields, this defines the array element struct shape (generates [...{fields}]).

func (*StructField) Of

func (f *StructField) Of(elemType ParamType) *StructField

Of sets the element type for array fields (e.g., ParamTypeString for [...string]).

func (*StructField) Optional

func (f *StructField) Optional() *StructField

Optional marks the field as optional, emitting the "?" CUE marker. The field may be absent from input entirely.

func (*StructField) Required

func (f *StructField) Required() *StructField

Required marks the field as required in input, emitting the "!" CUE marker. The user must explicitly provide this field — even if a default value exists.

func (*StructField) Values

func (f *StructField) Values(values ...string) *StructField

Values restricts the field to specific allowed values. This is only meaningful for string fields.

func (*StructField) WithSchemaRef

func (f *StructField) WithSchemaRef(ref string) *StructField

WithSchemaRef sets a reference to a helper type definition (e.g., "#RuleSelector"). This is used when the field type is defined elsewhere as a helper definition.

type StructFieldDef

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

StructFieldDef defines a field in a struct.

func HelperField

func HelperField(name string, value Value) StructFieldDef

HelperField creates an unconditional struct field.

func HelperFieldIf

func HelperFieldIf(cond Condition, name string, value Value) StructFieldDef

HelperFieldIf creates a conditional struct field.

func (StructFieldDef) Cond

func (f StructFieldDef) Cond() Condition

Cond returns the condition (nil if unconditional).

func (StructFieldDef) Name

func (f StructFieldDef) Name() string

Name returns the field name.

func (StructFieldDef) Value

func (f StructFieldDef) Value() Value

Value returns the field value.

type StructParam

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

StructParam represents a structured parameter with named fields.

func Struct

func Struct(name string) *StructParam

Struct creates a new struct parameter with the given name.

func (*StructParam) Description

func (p *StructParam) Description(desc string) *StructParam

Description sets the parameter description.

func (*StructParam) Eq

func (p *StructParam) Eq(val any) Condition

Eq creates a condition that compares this parameter to a literal value. Example: replicas.Eq(3) generates: parameter.replicas == 3

func (*StructParam) Field

func (p *StructParam) Field(fieldPath string) *ParamFieldRef

Field returns a reference to a nested field within this struct parameter. This allows struct parameters to be used as variables with field access. Example: config := Struct("config").WithFields(...); config.Field("port") => parameter.config.port

func (*StructParam) GetDefault

func (p *StructParam) GetDefault() any

func (*StructParam) GetDescription

func (p *StructParam) GetDescription() string

func (*StructParam) GetField

func (p *StructParam) GetField(name string) *StructField

GetField returns a field by name, or nil if not found.

func (*StructParam) GetFields

func (p *StructParam) GetFields() []*StructField

GetFields returns all field definitions.

func (*StructParam) GetSchemaRef

func (p *StructParam) GetSchemaRef() string

GetSchemaRef returns the schema reference for this struct.

func (*StructParam) GetShort

func (p *StructParam) GetShort() string

func (*StructParam) Gt

func (p *StructParam) Gt(val any) Condition

Gt creates a condition that checks if this parameter is greater than a value. Example: replicas.Gt(1) generates: parameter.replicas > 1

func (*StructParam) Gte

func (p *StructParam) Gte(val any) Condition

Gte creates a condition that checks if this parameter is greater than or equal to a value. Example: replicas.Gte(1) generates: parameter.replicas >= 1

func (*StructParam) HasDefault

func (p *StructParam) HasDefault() bool

func (*StructParam) IsIgnore

func (p *StructParam) IsIgnore() bool

func (*StructParam) IsOptional

func (p *StructParam) IsOptional() bool

func (*StructParam) IsRequired

func (p *StructParam) IsRequired() bool

func (*StructParam) IsSet

func (p *StructParam) IsSet() Condition

IsSet returns a condition that checks if the parameter has a value. This is used with SetIf for conditional field assignment.

func (*StructParam) Lt

func (p *StructParam) Lt(val any) Condition

Lt creates a condition that checks if this parameter is less than a value. Example: replicas.Lt(10) generates: parameter.replicas < 10

func (*StructParam) Lte

func (p *StructParam) Lte(val any) Condition

Lte creates a condition that checks if this parameter is less than or equal to a value. Example: replicas.Lte(10) generates: parameter.replicas <= 10

func (*StructParam) Name

func (p *StructParam) Name() string

func (*StructParam) Ne

func (p *StructParam) Ne(val any) Condition

Ne creates a condition that checks if this parameter is not equal to a value. Example: status.Ne("error") generates: parameter.status != "error"

func (*StructParam) NotSet

func (p *StructParam) NotSet() Condition

NotSet returns a condition that checks if the parameter is not set. This generates `if parameter["name"] == _|_` in CUE.

func (*StructParam) Optional

func (p *StructParam) Optional() *StructParam

Optional marks the parameter as optional, emitting the "?" CUE marker.

func (*StructParam) Required

func (p *StructParam) Required() *StructParam

Required marks the parameter as required in input, emitting the "!" CUE marker.

func (*StructParam) WithFields

func (p *StructParam) WithFields(fields ...*StructField) *StructParam

WithFields adds field definitions to the struct.

func (*StructParam) WithSchemaRef

func (p *StructParam) WithSchemaRef(ref string) *StructParam

WithSchemaRef sets a reference to a helper type definition (e.g., "#RuleSelector"). This is used when the struct type is defined elsewhere as a helper definition.

type Template

type Template struct {
	*VelaContext // Embedded to provide tpl.Name(), tpl.AppName(), etc.
	// contains filtered or unexported fields
}

Template provides the building context for component and trait templates. It embeds VelaContext to provide access to runtime context values (Name, AppName, Namespace, Revision, etc.) directly on tpl.

For components: Use Output() and Outputs() to define resources. For traits: Use Patch() to modify workloads or Outputs() for auxiliary resources.

func NewTemplate

func NewTemplate() *Template

NewTemplate creates a new template context.

func (*Template) AddLetBinding

func (t *Template) AddLetBinding(name string, expr Value) *Template

AddLetBinding adds a let binding to the template. Let bindings create local variables in the CUE template.

Example:

tpl.AddLetBinding("resourceContent", defkit.Struct(
    defkit.Field("cpu", defkit.ParamTypeString),
    defkit.Field("memory", defkit.ParamTypeString),
))

func (*Template) ConcatHelper

func (t *Template) ConcatHelper(name string, source *StructArrayHelper) *ConcatHelperBuilder

ConcatHelper starts building a list.Concat helper. This creates helpers like volumesList that concatenate arrays from a struct helper.

Example:

volumesList := tpl.ConcatHelper("volumesList", volumesArray).
    Fields("pvc", "configMap", "secret", "emptyDir", "hostPath").
    Build()

func (*Template) DedupeHelper

func (t *Template) DedupeHelper(name string, source Value) *DedupeHelperBuilder

DedupeHelper starts building a deduplication helper. This creates helpers like deDupVolumesArray that remove duplicates by a key field.

Example:

deDupVolumes := tpl.DedupeHelper("deDupVolumesArray", volumesList).
    ByKey("name").
    Build()

func (*Template) GetConcatHelpers

func (t *Template) GetConcatHelpers() []*ConcatHelper

GetConcatHelpers returns all list.Concat helpers.

func (*Template) GetDedupeHelpers

func (t *Template) GetDedupeHelpers() []*DedupeHelper

GetDedupeHelpers returns all deduplication helpers.

func (*Template) GetHelpers

func (t *Template) GetHelpers() []*HelperVar

GetHelpers returns all registered helpers.

func (*Template) GetHelpersAfterOutput

func (t *Template) GetHelpersAfterOutput() []*HelperVar

GetHelpersAfterOutput returns helpers that should appear after the output: block. These helpers are typically used by auxiliary outputs and should be placed between output: and outputs: in the generated CUE.

func (*Template) GetHelpersBeforeOutput

func (t *Template) GetHelpersBeforeOutput() []*HelperVar

GetHelpersBeforeOutput returns helpers that should appear before the output: block.

func (*Template) GetLetBindings

func (t *Template) GetLetBindings() []*LetBinding

GetLetBindings returns all let bindings.

func (*Template) GetOutput

func (t *Template) GetOutput() *Resource

GetOutput returns the primary output resource.

func (*Template) GetOutputGroups

func (t *Template) GetOutputGroups() []*outputGroup

GetOutputGroups returns all output groups.

func (*Template) GetOutputs

func (t *Template) GetOutputs() map[string]*Resource

GetOutputs returns all auxiliary resources.

func (*Template) GetPatch

func (t *Template) GetPatch() *PatchResource

GetPatch returns the patch resource if set.

func (*Template) GetPatchContainerConfig

func (t *Template) GetPatchContainerConfig() *PatchContainerConfig

GetPatchContainerConfig returns the PatchContainer configuration.

func (*Template) GetPatchStrategy

func (t *Template) GetPatchStrategy() string

GetPatchStrategy returns the patch strategy.

func (*Template) GetRawHeaderBlock

func (t *Template) GetRawHeaderBlock() string

GetRawHeaderBlock returns the raw header block.

func (*Template) GetRawOutputsBlock

func (t *Template) GetRawOutputsBlock() string

GetRawOutputsBlock returns the raw outputs block.

func (*Template) GetRawParameterBlock

func (t *Template) GetRawParameterBlock() string

GetRawParameterBlock returns the raw parameter block.

func (*Template) GetRawPatchBlock

func (t *Template) GetRawPatchBlock() string

GetRawPatchBlock returns the raw patch block.

func (*Template) GetStructArrayHelpers

func (t *Template) GetStructArrayHelpers() []*StructArrayHelper

GetStructArrayHelpers returns all struct-based array helpers.

func (*Template) HasPatch

func (t *Template) HasPatch() bool

HasPatch returns true if this template has patch operations.

func (*Template) Helper

func (t *Template) Helper(name string) *HelperBuilder

Helper starts building a named helper. The returned HelperBuilder provides a fluent API for defining the helper's source and operations.

Example:

mounts := tpl.Helper("mountsArray").
    FromFields(Param("volumeMounts"), "pvc", "configMap", "secret").
    Pick("name", "mountPath").
    PickIf(IsSet(Field("subPath")), "subPath").
    Build()

func (*Template) Output

func (t *Template) Output(r ...*Resource) *Resource

Output sets or returns the primary output resource.

func (*Template) Outputs

func (t *Template) Outputs(name string, r ...*Resource) *Resource

Outputs sets or returns a named auxiliary resource.

func (*Template) OutputsGroupIf

func (t *Template) OutputsGroupIf(cond Condition, fn func(g *OutputGroup))

OutputsGroupIf groups multiple outputs under a single condition. This generates one `if cond { ... }` block containing all grouped outputs.

func (*Template) OutputsIf

func (t *Template) OutputsIf(cond Condition, name string, r *Resource)

OutputsIf conditionally sets a named auxiliary resource. The resource is only added if the condition evaluates to true.

func (*Template) Patch

func (t *Template) Patch() *PatchResource

Patch returns the PatchResource builder for traits. If no patch has been created yet, this creates one. Use this to modify the workload resource in trait templates.

Example:

tpl.Patch().
    Set("spec.replicas", replicas).
    SetIf(cpu.IsSet(), "spec.template.spec.containers[0].resources.limits.cpu", cpu)

func (*Template) PatchStrategy

func (t *Template) PatchStrategy(strategy string) *Template

PatchStrategy sets the patch strategy for trait patches. Common strategies: "retainKeys", "jsonMergePatch", "jsonPatch"

Example:

tpl.PatchStrategy("retainKeys").
    Patch().Set("spec.replicas", replicas)

func (*Template) SetRawHeaderBlock

func (t *Template) SetRawHeaderBlock(block string) *Template

SetRawHeaderBlock sets a raw CUE block for let bindings and pre-output declarations. This allows traits to define local variables and helper expressions in CUE. Use this for let bindings, helper lists, and other declarations that come before outputs.

func (*Template) SetRawOutputsBlock

func (t *Template) SetRawOutputsBlock(block string) *Template

SetRawOutputsBlock sets a raw CUE block for the outputs section. This allows traits to define K8s resources to create directly in CUE. Use this for traits that generate Services, Ingresses, HPAs, PVCs, etc.

func (*Template) SetRawParameterBlock

func (t *Template) SetRawParameterBlock(block string) *Template

SetRawParameterBlock sets a raw CUE block for the parameter section. This allows traits to define complex parameter schemas directly in CUE.

func (*Template) SetRawPatchBlock

func (t *Template) SetRawPatchBlock(block string) *Template

SetRawPatchBlock sets a raw CUE block for the patch section. This allows traits to define complex patch structures directly in CUE.

func (*Template) StructArrayHelper

func (t *Template) StructArrayHelper(name string, source Value) *StructArrayBuilder

StructArrayHelper starts building a struct-based array helper. This creates helpers like mountsArray or volumesArray where each source type is a separate field in a struct.

Example:

mountsArray := tpl.StructArrayHelper("mountsArray", Param("volumeMounts")).
    Field("pvc", FieldMap{"name": FieldRef("name"), "mountPath": FieldRef("mountPath")}).
    Field("configMap", FieldMap{"name": FieldRef("name"), "mountPath": FieldRef("mountPath")}).
    Build()

func (*Template) UsePatchContainer

func (t *Template) UsePatchContainer(config PatchContainerConfig) *Template

UsePatchContainer configures the template to use the PatchContainer pattern.

type TestContextBuilder

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

TestContextBuilder provides a fluent API for creating mock contexts in tests. This enables unit testing of definitions without a Kubernetes cluster.

func TestContext

func TestContext() *TestContextBuilder

TestContext creates a new test context builder for unit testing definitions.

func (*TestContextBuilder) AppName

func (t *TestContextBuilder) AppName() string

AppName returns the application name.

func (*TestContextBuilder) Build

Build creates the test context. This is called internally by Render/Validate.

func (*TestContextBuilder) ClusterVersion

func (t *TestContextBuilder) ClusterVersion() (int, int)

ClusterVersion returns major, minor version.

func (*TestContextBuilder) Name

func (t *TestContextBuilder) Name() string

Name returns the component name.

func (*TestContextBuilder) Namespace

func (t *TestContextBuilder) Namespace() string

Namespace returns the namespace.

func (*TestContextBuilder) Params

func (t *TestContextBuilder) Params() map[string]any

Params returns all parameter values.

func (*TestContextBuilder) WithAppName

func (t *TestContextBuilder) WithAppName(appName string) *TestContextBuilder

WithAppName sets the application name (context.appName).

func (*TestContextBuilder) WithAppRevision

func (t *TestContextBuilder) WithAppRevision(revision string) *TestContextBuilder

WithAppRevision sets the application revision (context.appRevision).

func (*TestContextBuilder) WithClusterVersion

func (t *TestContextBuilder) WithClusterVersion(major, minor int) *TestContextBuilder

WithClusterVersion sets the target cluster version (context.clusterVersion).

func (*TestContextBuilder) WithName

func (t *TestContextBuilder) WithName(name string) *TestContextBuilder

WithName sets the component name (context.name).

func (*TestContextBuilder) WithNamespace

func (t *TestContextBuilder) WithNamespace(namespace string) *TestContextBuilder

WithNamespace sets the target namespace (context.namespace).

func (*TestContextBuilder) WithOutputStatus

func (t *TestContextBuilder) WithOutputStatus(status map[string]any) *TestContextBuilder

WithOutputStatus sets the output status for health policy testing. This simulates runtime status like readyReplicas.

func (*TestContextBuilder) WithOutputsStatus

func (t *TestContextBuilder) WithOutputsStatus(name string, status map[string]any) *TestContextBuilder

WithOutputsStatus sets status for a named auxiliary output.

func (*TestContextBuilder) WithParam

func (t *TestContextBuilder) WithParam(name string, value any) *TestContextBuilder

WithParam sets a parameter value for the test context.

func (*TestContextBuilder) WithParams

func (t *TestContextBuilder) WithParams(params map[string]any) *TestContextBuilder

WithParams sets multiple parameter values at once.

func (*TestContextBuilder) WithWorkload

func (t *TestContextBuilder) WithWorkload(workload *Resource) *TestContextBuilder

WithWorkload sets a workload resource for trait testing.

type TestRuntimeContext

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

TestRuntimeContext holds the built test context values.

func (*TestRuntimeContext) AppName

func (c *TestRuntimeContext) AppName() string

AppName returns the application name.

func (*TestRuntimeContext) AppRevision

func (c *TestRuntimeContext) AppRevision() string

AppRevision returns the application revision.

func (*TestRuntimeContext) ClusterMinor

func (c *TestRuntimeContext) ClusterMinor() int

ClusterMinor returns just the minor version (common check).

func (*TestRuntimeContext) ClusterVersion

func (c *TestRuntimeContext) ClusterVersion() (int, int)

ClusterVersion returns the cluster version.

func (*TestRuntimeContext) GetParam

func (c *TestRuntimeContext) GetParam(name string) (any, bool)

GetParam returns a parameter value by name.

func (*TestRuntimeContext) GetParamOr

func (c *TestRuntimeContext) GetParamOr(name string, defaultValue any) any

GetParamOr returns a parameter value or a default.

func (*TestRuntimeContext) IsParamSet

func (c *TestRuntimeContext) IsParamSet(name string) bool

IsParamSet returns true if the parameter has a value.

func (*TestRuntimeContext) Name

func (c *TestRuntimeContext) Name() string

Name returns the component name.

func (*TestRuntimeContext) Namespace

func (c *TestRuntimeContext) Namespace() string

Namespace returns the namespace.

func (*TestRuntimeContext) OutputStatus

func (c *TestRuntimeContext) OutputStatus() map[string]any

OutputStatus returns the simulated output status.

func (*TestRuntimeContext) OutputsStatus

func (c *TestRuntimeContext) OutputsStatus(name string) map[string]any

OutputsStatus returns status for a named output.

func (*TestRuntimeContext) Workload

func (c *TestRuntimeContext) Workload() *Resource

Workload returns the workload for trait testing.

type TimeParseExpr

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

TimeParseExpr represents a time.Parse() call in CUE.

func TimeParse

func TimeParse(layout string, field *LocalFieldRef) *TimeParseExpr

TimeParse creates a Value representing time.Parse(layout, expr) in CUE. Used for date comparison validators.

Example: TimeParse("2006-01-02T15:04:05Z", LocalField("date")) generates: time.Parse("2006-01-02T15:04:05Z", date)

func (*TimeParseExpr) FieldName

func (t *TimeParseExpr) FieldName() string

FieldName returns the field name passed to time.Parse.

func (*TimeParseExpr) Gte

func (t *TimeParseExpr) Gte(other *TimeParseExpr) Condition

Gte creates a condition: time.Parse(layout, fieldA) >= time.Parse(layout, fieldB) Reuses upstream Comparison type via Ge().

func (*TimeParseExpr) Layout

func (t *TimeParseExpr) Layout() string

Layout returns the time layout string.

type TraitCUEGenerator

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

TraitCUEGenerator generates CUE definitions for traits.

func NewTraitCUEGenerator

func NewTraitCUEGenerator() *TraitCUEGenerator

NewTraitCUEGenerator creates a new trait CUE generator.

func (*TraitCUEGenerator) GenerateDefinitionWithRawTemplate

func (g *TraitCUEGenerator) GenerateDefinitionWithRawTemplate(t *TraitDefinition, rawTemplate string) string

GenerateDefinitionWithRawTemplate generates a trait definition with fluent API header and raw CUE template. This combines the best of both worlds: - Header (name, type, description, labels, attributes) from fluent API - Template content (patch, outputs, parameter) from raw CUE string

func (*TraitCUEGenerator) GenerateFullDefinition

func (g *TraitCUEGenerator) GenerateFullDefinition(t *TraitDefinition) string

GenerateFullDefinition generates the complete CUE definition for a trait.

func (*TraitCUEGenerator) GenerateTemplate

func (g *TraitCUEGenerator) GenerateTemplate(t *TraitDefinition) string

GenerateTemplate generates the template block for a trait.

func (*TraitCUEGenerator) WithImports

func (g *TraitCUEGenerator) WithImports(imports ...string) *TraitCUEGenerator

WithImports adds CUE imports.

type TraitDefinition

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

TraitDefinition represents a KubeVela TraitDefinition. Traits modify or enhance components by either patching the workload resource or creating additional auxiliary resources.

TraitDefinition embeds baseDefinition for common fields and methods shared with ComponentDefinition and other definition types.

func NewTrait

func NewTrait(name string) *TraitDefinition

NewTrait creates a new TraitDefinition builder.

func Traits

func Traits() []*TraitDefinition

Traits returns all registered TraitDefinitions.

func (*TraitDefinition) Annotations

func (t *TraitDefinition) Annotations(annotations map[string]string) *TraitDefinition

Annotations sets metadata annotations on the trait definition.

func (*TraitDefinition) AppliesTo

func (t *TraitDefinition) AppliesTo(workloads ...string) *TraitDefinition

AppliesTo specifies which workload types this trait can be applied to. Common values: "deployments.apps", "statefulsets.apps", "daemonsets.apps"

func (*TraitDefinition) ConflictsWith

func (t *TraitDefinition) ConflictsWith(traits ...string) *TraitDefinition

ConflictsWith specifies traits that cannot be used together with this trait.

func (*TraitDefinition) ControlPlaneOnly

func (t *TraitDefinition) ControlPlaneOnly() *TraitDefinition

ControlPlaneOnly marks this trait as running on the control plane only.

func (*TraitDefinition) CustomStatus

func (t *TraitDefinition) CustomStatus(expr string) *TraitDefinition

CustomStatus sets the custom status CUE expression for the trait.

func (*TraitDefinition) DefName

func (t *TraitDefinition) DefName() string

DefName implements Definition.DefName.

func (*TraitDefinition) DefType

func (t *TraitDefinition) DefType() DefinitionType

DefType implements Definition.DefType.

func (*TraitDefinition) Description

func (t *TraitDefinition) Description(desc string) *TraitDefinition

Description sets the trait description.

func (*TraitDefinition) GetAnnotations

func (b *TraitDefinition) GetAnnotations() map[string]string

GetAnnotations returns the annotations map.

func (*TraitDefinition) GetAppliesToWorkloads

func (t *TraitDefinition) GetAppliesToWorkloads() []string

GetAppliesToWorkloads returns the workload types this trait applies to.

func (*TraitDefinition) GetConditionalParamBlocks

func (b *TraitDefinition) GetConditionalParamBlocks() []*ConditionalParamBlock

GetConditionalParamBlocks returns the conditional parameter blocks.

func (*TraitDefinition) GetConflictsWith

func (t *TraitDefinition) GetConflictsWith() []string

GetConflictsWith returns traits that conflict with this one.

func (*TraitDefinition) GetCustomStatus

func (b *TraitDefinition) GetCustomStatus() string

GetCustomStatus returns the custom status CUE expression.

func (*TraitDefinition) GetDescription

func (b *TraitDefinition) GetDescription() string

GetDescription returns the definition description.

func (*TraitDefinition) GetHealthPolicy

func (b *TraitDefinition) GetHealthPolicy() string

GetHealthPolicy returns the health policy CUE expression.

func (*TraitDefinition) GetHelperDefinitions

func (b *TraitDefinition) GetHelperDefinitions() []HelperDefinition

GetHelperDefinitions returns all helper type definitions.

func (*TraitDefinition) GetImports

func (b *TraitDefinition) GetImports() []string

GetImports returns the CUE imports.

func (*TraitDefinition) GetLabels

func (t *TraitDefinition) GetLabels() map[string]string

GetLabels returns the trait's metadata labels.

func (*TraitDefinition) GetName

func (b *TraitDefinition) GetName() string

GetName returns the definition name.

func (*TraitDefinition) GetNotRunOn

func (b *TraitDefinition) GetNotRunOn() []placement.Condition

GetNotRunOn returns the NotRunOn placement conditions.

func (*TraitDefinition) GetParams

func (b *TraitDefinition) GetParams() []Param

GetParams returns all parameter definitions.

func (*TraitDefinition) GetPlacement

func (b *TraitDefinition) GetPlacement() placement.PlacementSpec

GetPlacement returns the complete placement spec for this definition.

func (*TraitDefinition) GetRawCUE

func (b *TraitDefinition) GetRawCUE() string

GetRawCUE returns the raw CUE template if set.

func (*TraitDefinition) GetRawCUEWithName

func (b *TraitDefinition) GetRawCUEWithName() string

GetRawCUEWithName returns the raw CUE with the definition name rewritten to match the name set via NewComponent/NewTrait/etc. This ensures the name passed to the fluent builder takes precedence over any name embedded in the raw CUE string.

func (*TraitDefinition) GetRunOn

func (b *TraitDefinition) GetRunOn() []placement.Condition

GetRunOn returns the RunOn placement conditions.

func (*TraitDefinition) GetStage

func (t *TraitDefinition) GetStage() string

GetStage returns the trait stage.

func (*TraitDefinition) GetStatusDetails

func (b *TraitDefinition) GetStatusDetails() string

GetStatusDetails returns the status details CUE expression.

func (*TraitDefinition) GetTemplate

func (b *TraitDefinition) GetTemplate() func(tpl *Template)

GetTemplate returns the template function.

func (*TraitDefinition) GetTemplateBlock

func (t *TraitDefinition) GetTemplateBlock() string

GetTemplateBlock returns the raw CUE template block if set.

func (*TraitDefinition) GetValidators

func (b *TraitDefinition) GetValidators() []*Validator

GetValidators returns the top-level validators.

func (*TraitDefinition) GetVersion

func (b *TraitDefinition) GetVersion() string

GetVersion returns the version string.

func (*TraitDefinition) HasPlacement

func (b *TraitDefinition) HasPlacement() bool

HasPlacement returns true if the definition has any placement constraints.

func (*TraitDefinition) HasRawCUE

func (b *TraitDefinition) HasRawCUE() bool

HasRawCUE returns true if raw CUE is set.

func (*TraitDefinition) HasTemplate

func (b *TraitDefinition) HasTemplate() bool

HasTemplate returns true if the definition has a template function set.

func (*TraitDefinition) HasTemplateBlock

func (t *TraitDefinition) HasTemplateBlock() bool

HasTemplateBlock returns true if the trait has a raw CUE template block.

func (*TraitDefinition) HealthPolicy

func (t *TraitDefinition) HealthPolicy(expr string) *TraitDefinition

HealthPolicy sets the health policy CUE expression for the trait.

func (*TraitDefinition) HealthPolicyExpr

func (t *TraitDefinition) HealthPolicyExpr(expr HealthExpression) *TraitDefinition

HealthPolicyExpr sets the health policy using a composable HealthExpression.

func (*TraitDefinition) Helper

func (t *TraitDefinition) Helper(name string, param Param) *TraitDefinition

Helper adds a helper type definition like #HealthProbe or #labelSelector. The param can be a StructParam, MapParam, or ArrayParam that defines the schema. Usage: trait.Helper("HealthProbe", defkit.Struct("probe").Fields(...))

func (*TraitDefinition) IsControlPlaneOnly

func (t *TraitDefinition) IsControlPlaneOnly() bool

IsControlPlaneOnly returns whether this trait runs on the control plane only.

func (*TraitDefinition) IsManageWorkload

func (t *TraitDefinition) IsManageWorkload() bool

IsManageWorkload returns whether this trait manages the workload.

func (*TraitDefinition) IsPodDisruptive

func (t *TraitDefinition) IsPodDisruptive() bool

IsPodDisruptive returns whether this trait is pod-disruptive.

func (*TraitDefinition) IsRevisionEnabled

func (t *TraitDefinition) IsRevisionEnabled() bool

IsRevisionEnabled returns whether this trait has revision enabled.

func (*TraitDefinition) Labels

func (t *TraitDefinition) Labels(labels map[string]string) *TraitDefinition

Labels sets metadata labels for the trait definition. These labels appear in the definition's labels block. Usage: trait.Labels(map[string]string{"ui-hidden": "true"})

func (*TraitDefinition) ManageWorkload

func (t *TraitDefinition) ManageWorkload() *TraitDefinition

ManageWorkload marks this trait as managing the workload.

func (*TraitDefinition) NotRunOn

func (t *TraitDefinition) NotRunOn(conditions ...placement.Condition) *TraitDefinition

NotRunOn adds placement conditions specifying which clusters this trait should NOT run on. Use the placement package's fluent API to build conditions.

Example:

defkit.NewTrait("no-vclusters").
    NotRunOn(placement.Label("cluster-type").Eq("vcluster"))

If any NotRunOn condition matches, the trait is ineligible for that cluster.

func (*TraitDefinition) Param

func (t *TraitDefinition) Param(param Param) *TraitDefinition

Param adds a single parameter definition to the trait.

func (*TraitDefinition) Params

func (t *TraitDefinition) Params(params ...Param) *TraitDefinition

Params adds parameter definitions to the trait.

func (*TraitDefinition) PodDisruptive

func (t *TraitDefinition) PodDisruptive(disruptive bool) *TraitDefinition

PodDisruptive marks whether applying this trait causes pod restarts.

func (*TraitDefinition) RawCUE

func (t *TraitDefinition) RawCUE(cue string) *TraitDefinition

RawCUE sets raw CUE for complex trait definitions that don't fit the builder pattern. When set, this bypasses all other template settings and outputs the raw CUE directly.

func (*TraitDefinition) RevisionEnabled

func (t *TraitDefinition) RevisionEnabled() *TraitDefinition

RevisionEnabled marks this trait as revision-enabled.

func (*TraitDefinition) RunOn

func (t *TraitDefinition) RunOn(conditions ...placement.Condition) *TraitDefinition

RunOn adds placement conditions specifying which clusters this trait should run on. Use the placement package's fluent API to build conditions.

Example:

defkit.NewTrait("eks-scaler").
    RunOn(placement.Label("provider").Eq("aws"))

Multiple RunOn calls are combined with AND semantics (all conditions must match).

func (*TraitDefinition) Stage

func (t *TraitDefinition) Stage(stage string) *TraitDefinition

Stage sets the trait application stage. Use "PreDispatch" for traits that must run before dispatch, "PostDispatch" for traits that run after (e.g., creating Services).

func (*TraitDefinition) StatusDetails

func (t *TraitDefinition) StatusDetails(details string) *TraitDefinition

StatusDetails sets the status details CUE expression for the trait.

func (*TraitDefinition) Template

func (t *TraitDefinition) Template(fn func(tpl *Template)) *TraitDefinition

Template sets the unified template function for the trait. This is the preferred way to define trait behavior. Use tpl.Patch() for modifying the workload, and tpl.Outputs() for creating auxiliary resources.

Example (patch-only):

defkit.NewTrait("scaler").
    Params(defkit.Int("replicas").Default(1)).
    Template(func(tpl *defkit.Template) {
        replicas := defkit.Int("replicas")
        tpl.PatchStrategy("retainKeys").
            Patch().Set("spec.replicas", replicas)
    })

Example (outputs-only):

defkit.NewTrait("expose").
    Params(defkit.Array("ports")...).
    Template(func(tpl *defkit.Template) {
        service := defkit.NewResource("v1", "Service").
            Set("spec.type", "ClusterIP")
        tpl.Outputs("service", service)
    })

Example (patch and outputs):

defkit.NewTrait("ingress").
    Template(func(tpl *defkit.Template) {
        // Patch the workload
        tpl.Patch().Set("metadata.annotations[ingress]", "enabled")
        // Create auxiliary resource
        ingress := defkit.NewResource("networking.k8s.io/v1", "Ingress")
        tpl.Outputs("ingress", ingress)
    })

func (*TraitDefinition) TemplateBlock

func (t *TraitDefinition) TemplateBlock(cue string) *TraitDefinition

TemplateBlock sets raw CUE for the template: block only. Unlike RawCUE which bypasses everything, TemplateBlock uses the fluent API for: - Trait header (name, type, description, annotations, labels) - Attributes (podDisruptive, appliesToWorkloads, conflictsWith, stage, status)

But uses raw CUE for the template: block content (patch, outputs, parameter, helpers). This is useful when the template logic is too complex for the fluent API but you still want type-safe metadata and attributes.

Example:

defkit.NewTrait("command").
    Description("Add command on K8s pod for your workload").
    AppliesTo("deployments.apps", "statefulsets.apps").
    TemplateBlock(`
        #PatchParams: {
            containerName: *"" | string
            command: *null | [...string]
        }
        PatchContainer: { ... }
        patch: spec: template: spec: { ... }
        parameter: #PatchParams
    `)

func (*TraitDefinition) ToCue

func (t *TraitDefinition) ToCue() string

ToCue generates the complete CUE definition string for this trait.

func (*TraitDefinition) ToYAML

func (t *TraitDefinition) ToYAML() ([]byte, error)

ToYAML generates the Kubernetes YAML representation of the TraitDefinition.

func (*TraitDefinition) Version

func (t *TraitDefinition) Version(v string) *TraitDefinition

Version sets the version string for the trait definition.

func (*TraitDefinition) WithImports

func (t *TraitDefinition) WithImports(imports ...string) *TraitDefinition

WithImports adds CUE imports to the trait definition. Usage: trait.WithImports("strconv", "strings")

func (*TraitDefinition) WorkloadRefPath

func (t *TraitDefinition) WorkloadRefPath(path string) *TraitDefinition

WorkloadRefPath sets the workloadRefPath attribute for the trait.

type TransformFunc

type TransformFunc func(any) any

TransformFunc is a function that transforms a value.

type TransformedValue

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

TransformedValue wraps a value with a transformation function.

func Transform

func Transform(source Value, fn TransformFunc) *TransformedValue

Transform creates a transformed value that applies the given function to the source value. This is useful for converting parameter values to different formats (e.g., port lists).

func (*TransformedValue) Source

func (t *TransformedValue) Source() Value

Source returns the source value being transformed.

func (*TransformedValue) TransformFn

func (t *TransformedValue) TransformFn() TransformFunc

TransformFn returns the transformation function.

type TruthyCondition

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

TruthyCondition represents a truthy check on a boolean parameter. In CUE, this generates `if parameter.name` instead of `if parameter.name == true`.

func (*TruthyCondition) ParamName

func (t *TruthyCondition) ParamName() string

ParamName returns the parameter name being checked.

type Validator

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

Validator represents a CUE _validate* block pattern used for cross-field validation. Validators emit blocks like:

_validateTenantName: {
    "tenantName must not end with a hyphen": true
    if tenantName =~ ".*-$" {
        "tenantName must not end with a hyphen": false
    }
}

Validators can be guarded (only active when a condition is true) and can be attached at different levels: top-level parameter, inside map/struct params, or inside array elements.

func Validate

func Validate(message string) *Validator

Validate creates a new Validator with the given error message. The message is used both as the CUE field key and as the error shown on failure.

func (*Validator) CUEName

func (v *Validator) CUEName() string

CUEName returns the CUE variable name for this validator.

func (*Validator) FailCondition

func (v *Validator) FailCondition() Condition

FailCondition returns the fail condition.

func (*Validator) FailWhen

func (v *Validator) FailWhen(cond Condition) *Validator

FailWhen sets the condition that causes validation to fail. When this condition evaluates to true, the validator emits false for the message key.

func (*Validator) GuardCondition

func (v *Validator) GuardCondition() Condition

GuardCondition returns the guard condition, or nil if not set.

func (*Validator) Message

func (v *Validator) Message() string

Message returns the validation message.

func (*Validator) OnlyWhen

func (v *Validator) OnlyWhen(guard Condition) *Validator

OnlyWhen sets a guard condition — the validator is only active when this condition is true. If the guard condition is false, the entire validator block is skipped.

func (*Validator) WithName

func (v *Validator) WithName(name string) *Validator

WithName overrides the CUE variable name for the validator block. By default, the name is derived from the message (e.g., "_validateTenantName").

type Value

type Value interface {
	Expr
	// contains filtered or unexported methods
}

Value represents a value that can be assigned to a field. This includes literals, parameter references, and expressions.

type ValueAction

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

ValueAction represents assigning a value to a template field.

type VelaContext

type VelaContext struct{}

VelaContext provides access to KubeVela runtime context values. These values are populated at runtime and generate CUE path references. Named VelaContext to avoid confusion with Go's context package.

func VelaCtx

func VelaCtx() *VelaContext

VelaCtx returns a new VelaContext instance for accessing runtime values. Usage: vela := defkit.VelaCtx()

deploy.Set("metadata.name", vela.Name())

func (*VelaContext) AppName

func (c *VelaContext) AppName() *ContextRef

AppName returns the application name from context.

func (*VelaContext) AppRevision

func (c *VelaContext) AppRevision() *ContextRef

AppRevision returns the application revision from context.

func (*VelaContext) AppRevisionNum

func (c *VelaContext) AppRevisionNum() *ContextRef

AppRevisionNum returns the application revision number from context.

func (*VelaContext) ClusterVersion

func (c *VelaContext) ClusterVersion() *ClusterVersionRef

ClusterVersion returns the Kubernetes cluster version from context.

func (*VelaContext) Name

func (c *VelaContext) Name() *ContextRef

Name returns the component/trait name from context.

func (*VelaContext) Namespace

func (c *VelaContext) Namespace() *ContextRef

Namespace returns the application namespace from context.

func (*VelaContext) Output

func (c *VelaContext) Output() *ContextRef

Output returns a reference to the primary output resource.

func (*VelaContext) Outputs

func (c *VelaContext) Outputs(name string) *ContextRef

Outputs returns a reference to auxiliary outputs by name.

func (*VelaContext) Revision

func (c *VelaContext) Revision() *ContextRef

Revision returns the component revision from context.

type VersionConditional

type VersionConditional struct {
	Condition  Condition
	ApiVersion string
}

VersionConditional represents a conditional apiVersion setting.

type WaitUntilBuilder

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

WaitUntilBuilder builds a builtin.#ConditionalWait operation fluently.

func WaitUntil

func WaitUntil(continueExpr Value) *WaitUntilBuilder

WaitUntil creates a new builtin.#ConditionalWait builder.

func (*WaitUntilBuilder) Guard

func (b *WaitUntilBuilder) Guard(guards ...Value) *WaitUntilBuilder

Guard adds guard conditions that must be true (not _|_) before the continue check is evaluated. Multiple guards are nested as chained if statements.

func (*WaitUntilBuilder) MessageIf

func (b *WaitUntilBuilder) MessageIf(cond Condition, val Value) *WaitUntilBuilder

MessageIf conditionally sets the message parameter.

func (*WaitUntilBuilder) RenderCUE

func (b *WaitUntilBuilder) RenderCUE(rv func(Value) string) string

RenderCUE renders the builder to a CUE string.

func (*WaitUntilBuilder) RenderCUEWithCondition

func (b *WaitUntilBuilder) RenderCUEWithCondition(rv func(Value) string, rc func(Condition) string) string

RenderCUEWithCondition renders the builder to a CUE string with condition support.

type WorkflowAction

type WorkflowAction interface {
	// contains filtered or unexported methods
}

WorkflowAction represents an action in a workflow step.

type WorkflowStepCUEGenerator

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

WorkflowStepCUEGenerator generates CUE definitions for workflow steps.

func NewWorkflowStepCUEGenerator

func NewWorkflowStepCUEGenerator() *WorkflowStepCUEGenerator

NewWorkflowStepCUEGenerator creates a new workflow step CUE generator.

func (*WorkflowStepCUEGenerator) GenerateFullDefinition

func (g *WorkflowStepCUEGenerator) GenerateFullDefinition(w *WorkflowStepDefinition) string

GenerateFullDefinition generates the complete CUE definition for a workflow step.

func (*WorkflowStepCUEGenerator) GenerateTemplate

func (g *WorkflowStepCUEGenerator) GenerateTemplate(w *WorkflowStepDefinition) string

GenerateTemplate generates the template block for a workflow step.

func (*WorkflowStepCUEGenerator) WithImports

func (g *WorkflowStepCUEGenerator) WithImports(imports ...string) *WorkflowStepCUEGenerator

WithImports adds CUE imports.

type WorkflowStepDefinition

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

WorkflowStepDefinition represents a KubeVela WorkflowStepDefinition. Workflow steps define operations in an application's deployment workflow, such as deploy, suspend, notification, approval, etc.

func NewWorkflowStep

func NewWorkflowStep(name string) *WorkflowStepDefinition

NewWorkflowStep creates a new WorkflowStepDefinition builder.

func WorkflowSteps

func WorkflowSteps() []*WorkflowStepDefinition

WorkflowSteps returns all registered WorkflowStepDefinitions.

func (*WorkflowStepDefinition) Alias

Alias sets an optional alias for the workflow step definition. This maps to metadata annotation `definition.oam.dev/alias` in generated YAML.

func (*WorkflowStepDefinition) Annotations

func (w *WorkflowStepDefinition) Annotations(annotations map[string]string) *WorkflowStepDefinition

Annotations sets metadata annotations on the workflow step definition.

func (*WorkflowStepDefinition) Category

func (w *WorkflowStepDefinition) Category(category string) *WorkflowStepDefinition

Category sets the workflow step category (shown in annotations). Common values: "Application Delivery", "Notification", "Approval"

func (*WorkflowStepDefinition) CustomStatus

func (w *WorkflowStepDefinition) CustomStatus(expr string) *WorkflowStepDefinition

CustomStatus sets the custom status CUE expression for the workflow step. This provides status visibility in the workflow execution.

func (*WorkflowStepDefinition) DefName

func (w *WorkflowStepDefinition) DefName() string

DefName implements Definition.DefName.

func (*WorkflowStepDefinition) DefType

DefType implements Definition.DefType.

func (*WorkflowStepDefinition) Description

Description sets the workflow step description.

func (*WorkflowStepDefinition) GetAlias

func (w *WorkflowStepDefinition) GetAlias() string

GetAlias returns the workflow step alias.

func (*WorkflowStepDefinition) GetAnnotations

func (b *WorkflowStepDefinition) GetAnnotations() map[string]string

GetAnnotations returns the annotations map.

func (*WorkflowStepDefinition) GetCategory

func (w *WorkflowStepDefinition) GetCategory() string

GetCategory returns the workflow step category.

func (*WorkflowStepDefinition) GetConditionalParamBlocks

func (b *WorkflowStepDefinition) GetConditionalParamBlocks() []*ConditionalParamBlock

GetConditionalParamBlocks returns the conditional parameter blocks.

func (*WorkflowStepDefinition) GetCustomStatus

func (b *WorkflowStepDefinition) GetCustomStatus() string

GetCustomStatus returns the custom status CUE expression.

func (*WorkflowStepDefinition) GetDescription

func (b *WorkflowStepDefinition) GetDescription() string

GetDescription returns the definition description.

func (*WorkflowStepDefinition) GetHealthPolicy

func (b *WorkflowStepDefinition) GetHealthPolicy() string

GetHealthPolicy returns the health policy CUE expression.

func (*WorkflowStepDefinition) GetHelperDefinitions

func (b *WorkflowStepDefinition) GetHelperDefinitions() []HelperDefinition

GetHelperDefinitions returns all helper type definitions.

func (*WorkflowStepDefinition) GetImports

func (b *WorkflowStepDefinition) GetImports() []string

GetImports returns the CUE imports.

func (*WorkflowStepDefinition) GetLabels

func (w *WorkflowStepDefinition) GetLabels() map[string]string

GetLabels returns the workflow step's metadata labels.

func (*WorkflowStepDefinition) GetName

func (b *WorkflowStepDefinition) GetName() string

GetName returns the definition name.

func (*WorkflowStepDefinition) GetNotRunOn

func (b *WorkflowStepDefinition) GetNotRunOn() []placement.Condition

GetNotRunOn returns the NotRunOn placement conditions.

func (*WorkflowStepDefinition) GetParams

func (b *WorkflowStepDefinition) GetParams() []Param

GetParams returns all parameter definitions.

func (*WorkflowStepDefinition) GetPlacement

func (b *WorkflowStepDefinition) GetPlacement() placement.PlacementSpec

GetPlacement returns the complete placement spec for this definition.

func (*WorkflowStepDefinition) GetRawCUE

func (b *WorkflowStepDefinition) GetRawCUE() string

GetRawCUE returns the raw CUE template if set.

func (*WorkflowStepDefinition) GetRawCUEWithName

func (b *WorkflowStepDefinition) GetRawCUEWithName() string

GetRawCUEWithName returns the raw CUE with the definition name rewritten to match the name set via NewComponent/NewTrait/etc. This ensures the name passed to the fluent builder takes precedence over any name embedded in the raw CUE string.

func (*WorkflowStepDefinition) GetRawTemplateBody

func (w *WorkflowStepDefinition) GetRawTemplateBody() string

GetRawTemplateBody returns the raw CUE template body.

func (*WorkflowStepDefinition) GetRunOn

func (b *WorkflowStepDefinition) GetRunOn() []placement.Condition

GetRunOn returns the RunOn placement conditions.

func (*WorkflowStepDefinition) GetScope

func (w *WorkflowStepDefinition) GetScope() string

GetScope returns the workflow step scope.

func (*WorkflowStepDefinition) GetStatusDetails

func (b *WorkflowStepDefinition) GetStatusDetails() string

GetStatusDetails returns the status details CUE expression.

func (*WorkflowStepDefinition) GetTemplate

func (b *WorkflowStepDefinition) GetTemplate() func(tpl *Template)

GetTemplate returns the template function.

func (*WorkflowStepDefinition) GetValidators

func (b *WorkflowStepDefinition) GetValidators() []*Validator

GetValidators returns the top-level validators.

func (*WorkflowStepDefinition) GetVersion

func (b *WorkflowStepDefinition) GetVersion() string

GetVersion returns the version string.

func (*WorkflowStepDefinition) HasAlias

func (w *WorkflowStepDefinition) HasAlias() bool

HasAlias returns true if alias was explicitly set.

func (*WorkflowStepDefinition) HasPlacement

func (b *WorkflowStepDefinition) HasPlacement() bool

HasPlacement returns true if the definition has any placement constraints.

func (*WorkflowStepDefinition) HasRawCUE

func (b *WorkflowStepDefinition) HasRawCUE() bool

HasRawCUE returns true if raw CUE is set.

func (*WorkflowStepDefinition) HasRawTemplateBody

func (w *WorkflowStepDefinition) HasRawTemplateBody() bool

HasRawTemplateBody returns true if a raw template body is set.

func (*WorkflowStepDefinition) HasTemplate

func (b *WorkflowStepDefinition) HasTemplate() bool

HasTemplate returns true if the definition has a template function set.

func (*WorkflowStepDefinition) HealthPolicy

func (w *WorkflowStepDefinition) HealthPolicy(expr string) *WorkflowStepDefinition

HealthPolicy sets the health policy CUE expression for the workflow step. This defines how the step's health is determined.

func (*WorkflowStepDefinition) HealthPolicyExpr

HealthPolicyExpr sets the health policy using a composable HealthExpression.

func (*WorkflowStepDefinition) Helper

Helper adds a helper type definition using fluent API. The param defines the schema for the helper type. Example:

Helper("Placement", defkit.Struct("placement").Fields(...))

func (*WorkflowStepDefinition) Labels

Labels sets arbitrary metadata labels for the workflow step definition. These labels appear in the definition's labels block alongside scope.

func (*WorkflowStepDefinition) NotRunOn

NotRunOn adds placement conditions specifying which clusters this workflow step should NOT run on. Use the placement package's fluent API to build conditions.

Example:

defkit.NewWorkflowStep("no-vclusters").
    NotRunOn(placement.Label("cluster-type").Eq("vcluster"))

If any NotRunOn condition matches, the workflow step is ineligible for that cluster.

func (*WorkflowStepDefinition) Param

Param adds a single parameter definition to the workflow step. This provides a more fluent API when adding parameters one at a time.

func (*WorkflowStepDefinition) Params

func (w *WorkflowStepDefinition) Params(params ...Param) *WorkflowStepDefinition

Params adds multiple parameter definitions to the workflow step.

func (*WorkflowStepDefinition) RawCUE

RawCUE sets raw CUE for complex workflow step definitions that don't fit the builder pattern.

func (*WorkflowStepDefinition) RunOn

RunOn adds placement conditions specifying which clusters this workflow step should run on. Use the placement package's fluent API to build conditions.

Example:

defkit.NewWorkflowStep("eks-deploy").
    RunOn(placement.Label("provider").Eq("aws"))

Multiple RunOn calls are combined with AND semantics (all conditions must match).

func (*WorkflowStepDefinition) Scope

Scope sets the workflow step scope (shown in labels). Common values: "Application", "Workflow"

func (*WorkflowStepDefinition) StatusDetails

func (w *WorkflowStepDefinition) StatusDetails(details string) *WorkflowStepDefinition

StatusDetails sets the status details CUE expression for the workflow step.

func (*WorkflowStepDefinition) Template

Template sets the template function for the workflow step.

func (*WorkflowStepDefinition) TemplateBody

func (w *WorkflowStepDefinition) TemplateBody(body string) *WorkflowStepDefinition

TemplateBody sets raw CUE that is embedded inside the template: { ... } block, between any builder-generated actions and the parameter block. This allows complex workflow logic (array comprehensions, context variables, etc.) while still using the builder API for metadata (description, category, scope, imports) and parameter schema definitions. The body should be provided at zero indentation; one tab indent is added per line when embedded.

func (*WorkflowStepDefinition) ToCue

func (w *WorkflowStepDefinition) ToCue() string

ToCue generates the complete CUE definition string for this workflow step.

func (*WorkflowStepDefinition) ToYAML

func (w *WorkflowStepDefinition) ToYAML() ([]byte, error)

ToYAML generates the Kubernetes YAML representation of the WorkflowStepDefinition.

func (*WorkflowStepDefinition) Version

Version sets the version string for the workflow step definition.

func (*WorkflowStepDefinition) WithImports

func (w *WorkflowStepDefinition) WithImports(imports ...string) *WorkflowStepDefinition

WithImports adds CUE imports to the workflow step definition. Common imports: "vela/multicluster", "vela/builtin"

type WorkflowStepTemplate

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

WorkflowStepTemplate provides the building context for workflow step templates. Workflow steps typically use vela builtins and may have conditional logic.

func NewWorkflowStepTemplate

func NewWorkflowStepTemplate() *WorkflowStepTemplate

NewWorkflowStepTemplate creates a new workflow step template.

func (*WorkflowStepTemplate) Builtin

func (wt *WorkflowStepTemplate) Builtin(name, builtinRef string) *BuiltinActionBuilder

Builtin adds a call to a vela builtin. Example: tpl.Builtin("deploy", "multicluster.#Deploy").WithParams(...)

func (*WorkflowStepTemplate) GetActions

func (wt *WorkflowStepTemplate) GetActions() []WorkflowAction

GetActions returns all actions.

func (*WorkflowStepTemplate) GetSuspendMessage

func (wt *WorkflowStepTemplate) GetSuspendMessage() string

GetSuspendMessage returns the suspend message.

func (*WorkflowStepTemplate) Set

func (wt *WorkflowStepTemplate) Set(name string, value Value) *WorkflowStepTemplate

Set assigns a value to a top-level field in the workflow template. Example: tpl.Set("object", someValue)

func (*WorkflowStepTemplate) SetGuardedBlock

func (wt *WorkflowStepTemplate) SetGuardedBlock(cond Condition, name string, value Value) *WorkflowStepTemplate

SetGuardedBlock assigns a value to a field with the guard condition placed inside the field block, so the field always exists (possibly empty). Generates: name: { if cond { ...contents... } } Unlike SetIf which generates: if cond { name: { ...contents... } }

func (*WorkflowStepTemplate) SetIf

func (wt *WorkflowStepTemplate) SetIf(cond Condition, name string, value Value) *WorkflowStepTemplate

SetIf conditionally assigns a value to a top-level field in the workflow template. Example: tpl.SetIf(param.IsSet(), "object", someValue)

func (*WorkflowStepTemplate) Suspend

func (wt *WorkflowStepTemplate) Suspend(message string) *WorkflowStepTemplate

Suspend adds a suspend action. Example: tpl.Suspend("Waiting for approval")

func (*WorkflowStepTemplate) SuspendIf

func (wt *WorkflowStepTemplate) SuspendIf(cond Condition, message string) *WorkflowStepTemplate

SuspendIf adds a conditional suspend action. Example: tpl.SuspendIf(param.Eq(false), "Waiting for approval")

type WorkloadType

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

WorkloadType represents the workload type for a component.

func (WorkloadType) APIVersion

func (w WorkloadType) APIVersion() string

APIVersion returns the workload API version.

func (WorkloadType) IsAutodetect

func (w WorkloadType) IsAutodetect() bool

IsAutodetect returns true if the workload type is auto-detected at runtime.

func (WorkloadType) Kind

func (w WorkloadType) Kind() string

Kind returns the workload kind.

Directories

Path Synopsis
testing
matchers
Package matchers provides custom Gomega matchers for testing defkit definitions.
Package matchers provides custom Gomega matchers for testing defkit definitions.

Jump to

Keyboard shortcuts

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