command

package
v1.0.90 Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package command defines the public contract for build-time command extensions.

Business command authors use Definition, Define, the CommandContext helpers, and high-level effects such as Download. The Host* types, InspectCommand, InspectDomain and CloneSets are the erased read side that lark-cli's host adapter and commandtest consume. They stay exported because a Command holds its declaration unexported and Go gives a sibling package no way to reach it; business commands never call them.

Index

Constants

View Source
const (
	// IdentityUser executes with a user access token.
	IdentityUser Identity = "user"
	// IdentityBot executes with a tenant access token.
	IdentityBot Identity = "bot"

	// RiskRead declares a read-only command.
	RiskRead Risk = "read"
	// RiskWrite declares a command that changes remote state.
	RiskWrite Risk = "write"
	// RiskHighRiskWrite declares a command that requires explicit confirmation.
	RiskHighRiskWrite Risk = "high-risk-write"
)
View Source
const (
	// AliasNormalize maps the alias value to the canonical field.
	AliasNormalize FlagAliasMode = "normalize"
	// AliasIndependent keeps the alias as a separate compatibility input.
	AliasIndependent FlagAliasMode = "independent"

	// AliasCanonicalWins prefers the canonical flag when both spellings appear.
	AliasCanonicalWins AliasConflictPolicy = "canonical_wins"
	// AliasErrorIfBoth rejects simultaneous canonical and alias values.
	AliasErrorIfBoth AliasConflictPolicy = "error_if_both"
	// AliasTrimmedEqualOrError accepts both spellings only when trimmed values match.
	AliasTrimmedEqualOrError AliasConflictPolicy = "trimmed_equal_or_error"
)
View Source
const (
	// RelationExactlyOne requires exactly one field.
	RelationExactlyOne RelationKind = "exactly_one"
	// RelationAtLeastOne requires one or more fields.
	RelationAtLeastOne RelationKind = "at_least_one"
	// RelationCoOccur requires all named fields to appear together.
	RelationCoOccur RelationKind = "co_occur"
	// RelationRequires makes the first field require the remaining fields.
	RelationRequires RelationKind = "requires"
	// RelationConflicts rejects fields used together.
	RelationConflicts RelationKind = "conflicts"

	// PresenceExplicit counts only values supplied by the caller.
	PresenceExplicit PresenceMode = "explicit"
	// PresenceNonZero counts non-zero values after normalization.
	PresenceNonZero PresenceMode = "non_zero"

	// StageSourcePreRun checks source presence before hooks run.
	StageSourcePreRun RelationStage = "source_pre_run"
	// StageAfterPrepare checks prepared values after Normalize.
	StageAfterPrepare RelationStage = "after_prepare"
)

Variables

This section is empty.

Functions

func CallJSON

func CallJSON[T any](ctx context.Context, command CommandContext, request Request) (T, error)

CallJSON executes one request and decodes its data object into T.

func CollectAllPages

func CollectAllPages[T any](ctx context.Context, command CommandContext, request Request) ([]T, error)

CollectAllPages fetches until the endpoint is exhausted and ignores CLI paging flags.

func InternalErrorf

func InternalErrorf(format string, args ...any) *errs.InternalError

InternalErrorf creates a typed internal error for an invariant failure.

func InvalidResponseErrorf

func InvalidResponseErrorf(format string, args ...any) *errs.InternalError

InvalidResponseErrorf creates a typed malformed-response error.

func PaginationInterruptedError

func PaginationInterruptedError(cause error) *errs.NetworkError

PaginationInterruptedError converts context cancellation into a typed network error.

func PaginationLimitError

func PaginationLimitError(pages int, nextToken string) *errs.InternalError

PaginationLimitError reports an incomplete all-pages read with a resume token.

func PathSegment

func PathSegment(s string) string

PathSegment escapes one user-provided value for use as a single OpenAPI path segment. Every variable concatenated into a request path must be wrapped with it, mirroring the host convention (internal/validate EncodePathSegment); an unescaped separator or dot sequence would otherwise change the request target.

func PreflightScopes

func PreflightScopes(command CommandContext, scopes ...string) error

PreflightScopes checks declared conditional scopes before a branch starts side effects.

func ValidateHostResult

func ValidateHostResult(definition HostDefinition, result HostResult) error

ValidateHostResult checks one erased Execute result against the protocol the framework depends on. Both lark-cli's host adapter and commandtest call it, so a Result the real CLI refuses can no longer pass a business command's own tests -- the divergence that mattered was a zero-value Result reading as a successful call in commandtest while every real invocation failed.

func ValidateRequestView

func ValidateRequestView(request RequestView) error

ValidateRequestView checks the same-origin OpenAPI boundary for host adapters and tests.

func ValidationErrorf

func ValidationErrorf(format string, args ...any) *errs.ValidationError

ValidationErrorf creates a typed invalid-argument error.

Types

type AliasConflictPolicy

type AliasConflictPolicy string

AliasConflictPolicy defines how canonical and alias values interact.

type ArrayShape

type ArrayShape struct {
	Items    ValueShape
	MinItems *int
	MaxItems *int
}

ArrayShape describes a JSON array.

type Artifact

type Artifact struct {
	Name        string `json:"name" schema:"required" doc:"logical artifact name"`
	Location    string `json:"location" schema:"required" doc:"host-resolved saved location"`
	Size        int64  `json:"size_bytes" schema:"required;minimum=0" doc:"committed byte count"`
	ContentType string `json:"content_type,omitempty" schema:"optional" doc:"response media type"`
	// contains filtered or unexported fields
}

Artifact is one file committed by the active host FileIO provider. It can be returned directly as typed command data.

func Download

func Download(ctx context.Context, command CommandContext, request Request, target FileTarget, options ...DownloadOptions) (Artifact, error)

Download streams one authenticated OpenAPI GET response into the active invocation-scoped FileIO provider. The host owns range probing, bounded retries, response validation, body closure, provider-owned saving, and error typing. It is an Execute-hook capability and does not declare or register a CLI command.

func DownloadURL

func DownloadURL(ctx context.Context, command CommandContext, rawURL string, target FileTarget, options ...DownloadOptions) (Artifact, error)

DownloadURL streams one HTTPS URL into the active invocation-scoped FileIO provider. The host applies external-request routing, SSRF protection, DNS/IP pinning, redirect validation, and the same multipart engine as Download. It is an Execute-hook capability, not a command definition.

type AuthorizationDefinition

type AuthorizationDefinition struct {
	Identities    map[Identity]IdentityAuthorization
	IdentityOrder []Identity
}

AuthorizationDefinition declares supported identities and their scopes.

type BooleanShape

type BooleanShape struct{ Enum []bool }

BooleanShape describes a JSON boolean.

type CLIEncoding

type CLIEncoding string

CLIEncoding defines how repeated or structured values are parsed.

const (
	// EncodingRepeated accepts repeated flag occurrences.
	EncodingRepeated CLIEncoding = "repeated"
	// EncodingCommaOrRepeated accepts comma-separated or repeated values.
	EncodingCommaOrRepeated CLIEncoding = "comma_or_repeated"
	// EncodingJSON accepts a JSON-encoded value.
	EncodingJSON CLIEncoding = "json"
)

type CLIInput

type CLIInput struct {
	Aliases      []FlagAlias
	ValueSources []ValueSource
	Encoding     CLIEncoding
	Hidden       bool
	Deprecated   string
}

CLIInput controls aliases, accepted value sources, encoding, and help visibility.

type Command

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

Command is an immutable typed command declaration returned by Define.

func Define

func Define[Args any, Data any](definition Definition[Args, Data]) Command

Define captures a typed command declaration for later host compilation.

type CommandContext

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

CommandContext is an opaque, invocation-scoped set of safe host capabilities.

func NewCommandContext

func NewCommandContext(options ContextOptions) CommandContext

NewCommandContext creates a restricted context from host callbacks.

func (CommandContext) Identity

func (c CommandContext) Identity() Identity

Identity returns the selected execution identity.

type CommandMetadata

type CommandMetadata struct {
	Service       DomainName
	Command       string
	Description   string
	Risk          Risk
	Hidden        bool
	Authorization AuthorizationDefinition
}

CommandMetadata describes the command name, help, risk, and authorization.

type ConditionalScope

type ConditionalScope struct {
	Scopes      []string         `json:"scopes"`
	When        string           `json:"when,omitempty"`
	Params      []string         `json:"params,omitempty"`
	Requirement ScopeRequirement `json:"requirement"`
}

ConditionalScope describes scopes required by only some execution branches.

type ConstShape

type ConstShape struct{ Value JSONValue }

ConstShape describes one exact JSON value.

type ContextOptions

type ContextOptions struct {
	Identity Identity
	DryRun   bool

	// InputStage marks a context serving Normalize or Validate. Those hooks
	// run before the high-risk confirmation gate, so the design gives them no
	// network: Validate is specified as parameter checking that issues no
	// request, and a command that reached out from there would produce remote
	// side effects the user was never asked to confirm.
	InputStage bool

	CallJSON        func(context.Context, Request) (map[string]any, error)
	Download        func(context.Context, Request, FileTarget, DownloadOptions) (Artifact, error)
	DownloadURL     func(context.Context, string, FileTarget, DownloadOptions) (Artifact, error)
	PreflightScopes func(...string) error
	CollectPages    func(context.Context, Request, bool) ([]map[string]any, HostPagination, error)
}

ContextOptions supplies safe callbacks when a host creates a CommandContext. It is intended for the lark-cli host adapter and commandtest.

type DataDefinition

type DataDefinition struct {
	Shape     ValueShape
	Overrides []DataField
}

DataDefinition supplements the schema inferred from Data.

type DataField

type DataField struct {
	Path        string
	Description string
	Shape       ValueShape
}

DataField overrides one output field selected by a JSON pointer.

type Definition

type Definition[Args any, Data any] struct {
	Metadata CommandMetadata
	Input    InputDefinition
	Output   OutputDefinition
	Hooks    Hooks[Args, Data]
}

Definition declares one typed command extension.

type Domain

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

Domain is an opaque declaration of where a command set is mounted.

func ExtendDomain

func ExtendDomain(name DomainName) Domain

ExtendDomain declares that a set adds commands to an existing domain. V1 mounts business commands into existing domains only; declaring a brand new domain is not part of this surface, so no constructor for one is exported.

type DomainName

type DomainName string

DomainName is the name of an existing Lark business domain.

const (
	// DomainApplication is the Application domain.
	DomainApplication DomainName = "application"
	// DomainApproval is the Approval domain.
	DomainApproval DomainName = "approval"
	// DomainApps is the Apps domain.
	DomainApps DomainName = "apps"
	// DomainAttendance is the Attendance domain.
	DomainAttendance DomainName = "attendance"
	// DomainBase is the Base domain.
	DomainBase DomainName = "base"
	// DomainCalendar is the Calendar domain.
	DomainCalendar DomainName = "calendar"
	// DomainContact is the Contacts domain.
	DomainContact DomainName = "contact"
	// DomainDocs is the Docs domain.
	DomainDocs DomainName = "docs"
	// DomainDrive is the Drive domain.
	DomainDrive DomainName = "drive"
	// DomainEvent is the Event domain.
	DomainEvent DomainName = "event"
	// DomainIm is the Messenger domain.
	DomainIm DomainName = "im"
	// DomainMail is the Mail domain.
	DomainMail DomainName = "mail"
	// DomainMarkdown is the Markdown domain.
	DomainMarkdown DomainName = "markdown"
	// DomainMindnotes is the Mindnote domain.
	DomainMindnotes DomainName = "mindnotes"
	// DomainMinutes is the Minutes domain.
	DomainMinutes DomainName = "minutes"
	// DomainNote is the Note domain.
	DomainNote DomainName = "note"
	// DomainOkr is the OKR domain.
	DomainOkr DomainName = "okr"
	// DomainSheets is the Sheets domain.
	DomainSheets DomainName = "sheets"
	// DomainSlides is the Slides domain.
	DomainSlides DomainName = "slides"
	// DomainTask is the Task domain.
	DomainTask DomainName = "task"
	// DomainVc is the VC domain.
	DomainVc DomainName = "vc"
	// DomainWhiteboard is the Whiteboard domain.
	DomainWhiteboard DomainName = "whiteboard"
	// DomainWiki is the Wiki domain.
	DomainWiki DomainName = "wiki"
)

The Lark business domains a command set may extend. The list is maintained by hand rather than generated from the shortcut registry: a domain exists once the CLI publishes it under `lark-cli --help`, which includes domains served only by typed and raw API commands. Generating from shortcuts.AllShortcuts would silently drop those. TestDomainConstantsCoverEveryService in internal/commandhost guards this list against the service registry.

type DownloadOptions

type DownloadOptions struct {
	Representation download.Representation
	Transfer       download.Options
	// contains filtered or unexported fields
}

DownloadOptions selects the source-stability contract and the shared multipart engine settings. The zero value uses Mutable with production transfer defaults.

type DryRun

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

DryRun is an opaque ordered description of requests that execution may send.

func NewDryRun

func NewDryRun(requests ...Request) *DryRun

NewDryRun creates a dry-run request list from shared Request values. Passing no requests creates an empty list to fill in with the chained methods below.

func (*DryRun) Add

func (d *DryRun) Add(request Request) *DryRun

Add appends a shared request description.

func (*DryRun) Body

func (d *DryRun) Body(body any) *DryRun

Body sets the body on the most recently appended request.

func (*DryRun) DELETE

func (d *DryRun) DELETE(apiPath string) *DryRun

DELETE appends a DELETE request.

func (*DryRun) Desc

func (d *DryRun) Desc(description string) *DryRun

Desc sets a call description, or the top-level description before any call exists.

func (*DryRun) File

func (d *DryRun) File(intent FileIntent) *DryRun

File appends one logical file effect. It does not inspect the destination or create storage; conflict and final-location decisions remain live-only.

func (*DryRun) GET

func (d *DryRun) GET(apiPath string) *DryRun

GET appends a GET request.

func (*DryRun) PATCH

func (d *DryRun) PATCH(apiPath string) *DryRun

PATCH appends a PATCH request.

func (*DryRun) POST

func (d *DryRun) POST(apiPath string) *DryRun

POST appends a POST request.

func (*DryRun) PUT

func (d *DryRun) PUT(apiPath string) *DryRun

PUT appends a PUT request.

func (*DryRun) Params

func (d *DryRun) Params(params map[string]any) *DryRun

Params replaces query parameters on the most recently appended request.

func (*DryRun) Set

func (d *DryRun) Set(name string, value any) *DryRun

Set adds a query parameter to the most recently appended request.

type DryRunView

type DryRunView struct {
	Description string
	Requests    []RequestView
	Files       []FileIntent
}

DryRunView is a copied host and test projection of DryRun.

func InspectDryRun

func InspectDryRun(dryRun *DryRun) DryRunView

InspectDryRun returns a copied dry-run projection for host adapters and tests.

type Failure

type Failure struct {
	Type      string `json:"type" schema:"required" doc:"error category"`
	Subtype   string `json:"subtype,omitempty" schema:"optional" doc:"error subtype"`
	Code      int    `json:"code,omitempty" schema:"optional" doc:"remote error code"`
	Message   string `json:"message" schema:"required" doc:"safe error message"`
	Hint      string `json:"hint,omitempty" schema:"optional" doc:"recovery hint"`
	LogID     string `json:"log_id,omitempty" schema:"optional" doc:"remote request log identifier"`
	Retryable bool   `json:"retryable,omitempty" schema:"optional" doc:"whether retry may succeed"`
}

Failure is a stable snapshot suitable for embedding in partial result data.

func SnapshotFailure

func SnapshotFailure(err error) Failure

SnapshotFailure copies safe typed error fields into result data.

type FileIntent

type FileIntent struct {
	Name     string         `json:"name"`
	IfExists IfExistsPolicy `json:"if_exists"`
	Content  string         `json:"content,omitempty"`
	// contains filtered or unexported fields
}

FileIntent describes a file effect in dry-run output without opening a stream or writing bytes.

type FileTarget

type FileTarget struct {
	Name     string
	IfExists IfExistsPolicy
	// contains filtered or unexported fields
}

FileTarget names one invocation-scoped download destination. Name is passed through the active FileIO provider and must not be treated as an absolute local path.

func (FileTarget) Intent

func (t FileTarget) Intent(content string) FileIntent

Intent creates the matching dry-run file effect.

type FlagAlias

type FlagAlias struct {
	Name       string
	Mode       FlagAliasMode
	Conflict   AliasConflictPolicy
	Hidden     bool
	Deprecated bool
}

FlagAlias declares a compatibility spelling for a flag.

type FlagAliasMode

type FlagAliasMode string

FlagAliasMode defines whether an alias normalizes into the canonical flag.

type Hooks

type Hooks[Args any, Data any] struct {
	// Normalize folds legacy input spellings into current semantics. It runs
	// first and only when a legacy form exists.
	//
	// Normalize and Validate both run before the high-risk confirmation gate,
	// so their CommandContext carries no network: CallJSON and CollectPages
	// refuse there. A check that needs the API belongs in Execute, after the
	// user has confirmed.
	Normalize func(context.Context, CommandContext, *Args) error

	// Validate checks format, range and field combinations. Requirements the
	// schema tag already states are enforced by the framework; this hook is for
	// the rules a tag cannot express. It issues no request -- see Normalize.
	Validate func(context.Context, CommandContext, *Args) error

	// DryRun returns the requests the command would send, which the framework
	// prints instead of executing. Validate has already run, so the requests
	// follow from Args alone and the hook reports nothing back.
	DryRun func(context.Context, CommandContext, *Args) *DryRun

	// Execute carries the business logic and returns Success. It is
	// the only hook that may call the API, and it must not write to stdout --
	// the framework owns the envelope, format and exit code.
	Execute func(context.Context, CommandContext, *Args) (Result[Data], error)

	// PrettyRenderer customizes --format pretty. It is a single hook rather than
	// a map keyed by format name because pretty is the only format a business
	// command may render itself: JSON, table, CSV and NDJSON are produced by the
	// framework formatters, and a map would let a command declare an entry the
	// compiler can only reject.
	PrettyRenderer Renderer[Data]
}

Hooks contains the optional preparation hooks and required Execute hook.

type HostDefinition

type HostDefinition struct {
	Metadata   CommandMetadata
	Input      InputDefinition
	Output     OutputDefinition
	ArgsType   reflect.Type
	DataType   reflect.Type
	NewArgs    func() any
	Hooks      HostHooks
	PageOutput bool
}

HostDefinition is the erased, copied declaration consumed by lark-cli's host adapter. Business command implementations should use Definition and Define instead.

func InspectCommand

func InspectCommand(command Command) HostDefinition

InspectCommand returns a deep-copied declaration for lark-cli's host adapter.

type HostDomain

type HostDomain struct {
	Name string
}

HostDomain is the copied domain declaration consumed by lark-cli's host adapter.

func InspectDomain

func InspectDomain(domain Domain) HostDomain

InspectDomain returns a copied declaration for lark-cli's host adapter.

type HostHooks

type HostHooks struct {
	Normalize func(context.Context, CommandContext, any) error
	Validate  func(context.Context, CommandContext, any) error
	DryRun    func(context.Context, CommandContext, any) *DryRun
	Execute   func(context.Context, CommandContext, any) (HostResult, error)
	Renderers map[string]func(io.Writer, any) error
}

HostHooks is the erased hook set consumed by lark-cli's host adapter.

type HostPagination

type HostPagination struct {
	Complete  bool
	Pages     int
	Items     int
	NextToken string
}

HostPagination is the copied pagination metadata consumed by lark-cli's host adapter. It also appears in ContextOptions and commandtest, which supply the page-collection callback a CommandContext exposes to business commands.

type HostResult

type HostResult struct {
	Data       any
	Outcome    string
	Pagination *HostPagination
}

HostResult is the erased result projection consumed by lark-cli's host adapter.

type Identity

type Identity string

Identity selects a supported Lark identity.

type IdentityAuthorization

type IdentityAuthorization struct {
	RequiredScopes    []string           `json:"required_scopes"`
	ConditionalScopes []ConditionalScope `json:"conditional_scopes"`
}

IdentityAuthorization declares required and conditional scopes for one identity.

type IfExistsPolicy

type IfExistsPolicy string

IfExistsPolicy controls an existing download target.

const (
	// IfExistsFail preserves an existing file. It is also the zero-value policy.
	IfExistsFail IfExistsPolicy = "fail"
	// IfExistsOverwrite explicitly allows the provider to replace an existing file.
	IfExistsOverwrite IfExistsPolicy = "overwrite"
)

type InputDefault

type InputDefault struct {
	Set   bool
	Value JSONValue
}

InputDefault distinguishes an omitted default from a JSON zero value.

type InputDefinition

type InputDefinition struct {
	Fields    []InputField
	Relations []Relation
}

InputDefinition supplements tags on Args with aliases, sources, and relations.

type InputField

type InputField struct {
	Name        string
	Description string
	Shape       ValueShape
	Default     InputDefault
	CLI         CLIInput
}

InputField supplements one field declared by a flag tag.

type IntegerShape

type IntegerShape struct {
	Enum    []int64
	Minimum *int64
	Maximum *int64
}

IntegerShape describes a JSON integer.

type JSONValue

type JSONValue = any

JSONValue is a value representable by JSON encoding.

type NullShape

type NullShape struct{}

NullShape describes JSON null.

type NumberShape

type NumberShape struct {
	Enum    []float64
	Minimum *float64
	Maximum *float64
}

NumberShape describes a JSON number.

type ObjectShape

type ObjectShape struct {
	Fields                    []ValueField
	AdditionalProperties      bool
	AdditionalPropertiesShape ValueShape
}

ObjectShape describes a JSON object.

type OneOfShape

type OneOfShape struct{ Variants []ValueShape }

OneOfShape describes a value matching one of several shapes.

type OutputDefinition

type OutputDefinition struct {
	Data DataDefinition
	Meta ResultMetaDefinition
	Mode OutputMode

	DisableHTMLEscaping bool
}

OutputDefinition declares result formats.

type OutputMode

type OutputMode string

OutputMode selects the framework output behavior.

const (
	// OutputGeneric uses the selected framework formatter.
	OutputGeneric OutputMode = ""
	// OutputFixedJSON always emits the standard JSON envelope.
	OutputFixedJSON OutputMode = "fixed_json"
)

type Page

type Page[T any] struct {
	Items []T `json:"items" schema:"required;nonnullable" doc:"items returned by the API"`
	// contains filtered or unexported fields
}

Page contains items and host-owned pagination state.

func CollectPages

func CollectPages[T any](ctx context.Context, command CommandContext, request Request) (Page[T], error)

CollectPages fetches one page by default or follows standard pagination flags.

func (Page[T]) Complete

func (p Page[T]) Complete() bool

Complete reports whether the API had no remaining page.

func (Page[T]) NextToken

func (p Page[T]) NextToken() string

NextToken returns the next page token for an incomplete result.

func (Page[T]) Pages

func (p Page[T]) Pages() int

Pages returns the number of API pages collected.

type PaginationOptions

type PaginationOptions struct {
	All      bool
	MaxPages int
	Delay    time.Duration
}

PaginationOptions carries host-owned pagination controls to the public helpers. It is intended for host adapters and commandtest.

type PresenceMode

type PresenceMode string

PresenceMode defines how a field counts as present.

type Provided

type Provided[T any] struct {
	Value T
	Set   bool
}

Provided preserves whether the caller explicitly supplied a value.

type Relation

type Relation struct {
	Kind     RelationKind  `json:"kind"`
	Params   []string      `json:"params"`
	Presence PresenceMode  `json:"presence"`
	Stage    RelationStage `json:"stage"`
}

Relation declares a presence relationship among input fields.

type RelationKind

type RelationKind string

RelationKind identifies the relationship among fields.

type RelationStage

type RelationStage string

RelationStage selects when a relation is checked.

type Renderer

type Renderer[Data any] func(io.Writer, Data) error

Renderer renders one successful result in a supported custom format.

type Request

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

Request is an opaque same-origin OpenAPI request description.

func DELETE

func DELETE(apiPath string) Request

DELETE creates a DELETE OpenAPI request.

func GET

func GET(apiPath string) Request

GET creates a GET OpenAPI request.

func PATCH

func PATCH(apiPath string) Request

PATCH creates a PATCH OpenAPI request.

func POST

func POST(apiPath string) Request

POST creates a POST OpenAPI request.

func PUT

func PUT(apiPath string) Request

PUT creates a PUT OpenAPI request.

func (Request) Body

func (r Request) Body(body any) Request

Body sets the JSON request body and returns a copied request.

func (Request) Desc

func (r Request) Desc(description string) Request

Desc adds a dry-run explanation and returns a copied request.

func (Request) Params

func (r Request) Params(params map[string]any) Request

Params replaces all query parameters and returns a copied request.

func (Request) Set

func (r Request) Set(name string, value any) Request

Set adds or replaces one query parameter and returns a copied request.

type RequestView

type RequestView struct {
	Method      string
	Path        string
	Query       map[string]any
	Body        any
	Description string
}

RequestView is the immutable host and test projection of a Request.

func InspectRequest

func InspectRequest(request Request) RequestView

InspectRequest returns a copied projection for host adapters and tests.

type Result

type Result[Data any] struct {
	// contains filtered or unexported fields
}

Result is an opaque command result created with Success.

func Success

func Success[Data any](data Data) Result[Data]

Success creates a complete successful result.

type ResultMetaDefinition

type ResultMetaDefinition struct {
	Pagination bool
}

ResultMetaDefinition declares standard metadata a command may return.

Only Pagination is declarable here. A count field would be unproducible: the opaque Result carries data, outcome and pagination, and exposes no way to set a count, so declaring one would make schema advertise a field the runtime can never emit.

type Risk

type Risk string

Risk classifies the side effects of a command.

type ScopeRequirement

type ScopeRequirement string

ScopeRequirement defines whether a conditional scope is mandatory.

const (
	// ScopeRequired fails the selected execution branch when the scope is absent.
	ScopeRequired ScopeRequirement = "required"
	// ScopeBestEffort allows the primary operation to continue without the scope.
	ScopeBestEffort ScopeRequirement = "best_effort"
)

type Set

type Set struct {
	Domain   Domain
	Commands []Command
	// contains filtered or unexported fields
}

Set groups commands mounted into one domain.

func CloneSets

func CloneSets(sets []Set) []Set

CloneSets copies set slices and immutable command declarations for BuildOption capture. It is intended for the lark-cli host adapter, not for business commands.

type StringShape

type StringShape struct {
	Enum      []string
	Format    string
	MinLength *int
	MaxLength *int
}

StringShape describes a JSON string.

type ValueField

type ValueField struct {
	Name        string
	Description string
	Required    bool
	Shape       ValueShape
}

ValueField describes one property of an ObjectShape.

type ValueShape

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

ValueShape is the closed set of JSON shapes accepted by command definitions.

type ValueSource

type ValueSource string

ValueSource identifies where a CLI input value may come from.

const (
	// SourceFlag accepts a literal flag value.
	SourceFlag ValueSource = "flag"
	// SourceFile accepts an @path value and substitutes the file content. The
	// path goes through the invocation's FileIO provider, so it stays relative
	// to the working directory; @@ passes a literal leading @.
	SourceFile ValueSource = "file"
	// SourceStdin accepts a single dash and reads standard input. A process has
	// one stdin, so at most one flag per invocation may use it -- declare
	// SourceFile alongside it to keep the remaining values passable.
	SourceStdin ValueSource = "stdin"
)

Directories

Path Synopsis
Package commandtest supplies an isolated runtime for business command tests.
Package commandtest supplies an isolated runtime for business command tests.
examples
chat-brief command
Command chat-brief is a runnable lark-cli distribution that contributes two business commands to the existing im domain via WithCommandSets:
Command chat-brief is a runnable lark-cli distribution that contributes two business commands to the existing im domain via WithCommandSets:

Jump to

Keyboard shortcuts

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