Documentation
¶
Overview ¶
Package types defines the core data types for api-style-spec.
These Go types are the source of truth for the api-style-spec format. JSON Schema is generated from these types using invopop/jsonschema.
Main types:
- APIStyleSpec: Root type for a style specification
- Rule: Individual style rule with enforcement and judge criteria
- LintReport: Results from deterministic linting
- Violation: A single rule violation
Index ¶
- Constants
- func DefaultConformanceLevels() map[string]ConformanceLevel
- func ScoreEmoji(score int) string
- func SeverityEmoji(severity string) string
- type APIStyleSpec
- func (s *APIStyleSpec) GetCategory(categoryID string) *Category
- func (s *APIStyleSpec) GetPattern(patternID string) *Pattern
- func (s *APIStyleSpec) GetRule(ruleID string) *Rule
- func (s *APIStyleSpec) GetSection(sectionID string) *Section
- func (s *APIStyleSpec) RulesForCategory(categoryID string) []Rule
- type ActionItem
- type CasingRules
- type Category
- type CategoryCounts
- type CategoryResult
- type CodeAnnotation
- type Condition
- type ConformanceBlocker
- type ConformanceLevel
- type ConformancePath
- type DecisionRow
- type DecisionTable
- type DeprecationInfo
- type DesignCheck
- type DesignCheckItem
- type DetailedExample
- type Diagram
- type Enforcement
- type EnforcementOptions
- type EnforcementType
- type EvaluationDecision
- type EvaluationFinding
- type EvaluationMetadata
- type EvaluationReport
- type Examples
- type Exception
- type ExceptionScope
- type FileLintReport
- type FindingCounts
- type FindingLimits
- type FixReport
- type FixSuggestion
- type ForbiddenTerm
- type GenerationExample
- type GenerationGuidance
- type GivenPaths
- type GlossaryTerm
- type JudgeCriteria
- type JudgeExample
- type JudgeExamples
- type Lexicon
- type LintReport
- type MigrationGuidance
- type MigrationStep
- type MultiLintReport
- type NextSteps
- type PassCriteria
- type PatchOperation
- type Pattern
- type Principle
- type Reference
- type ReportMetadata
- type ReportStatus
- type Rule
- type RuleApplicability
- type RuleOverride
- type RuleRelation
- type Scope
- type Section
- type Severity
- type SpecMetadata
- type SpectralThen
- type Status
- type Violation
- type ViolationSummary
Constants ¶
const ( ReportStatusPass = StatusPass ReportStatusFail = StatusFail )
Deprecated aliases for backwards compatibility.
Variables ¶
This section is empty.
Functions ¶
func DefaultConformanceLevels ¶
func DefaultConformanceLevels() map[string]ConformanceLevel
DefaultConformanceLevels returns the standard bronze/silver/gold levels.
func ScoreEmoji ¶ added in v0.5.0
ScoreEmoji returns an emoji representing the numeric score.
func SeverityEmoji ¶ added in v0.5.0
SeverityEmoji returns an emoji representing finding severity.
Types ¶
type APIStyleSpec ¶
type APIStyleSpec struct {
// Schema is the JSON Schema URI for validation.
Schema string `json:"$schema,omitempty"`
// Version is the semantic version of this specification.
Version string `json:"version"`
// Name is a unique identifier for this style spec.
Name string `json:"name"`
// Description provides context about this style specification.
Description string `json:"description,omitempty"`
// Introduction provides detailed introductory content (Markdown).
Introduction string `json:"introduction,omitempty"`
// Extends lists parent profiles to inherit rules from.
Extends []string `json:"extends,omitempty"`
// Rules are the style rules defined in this specification.
Rules []Rule `json:"rules"`
// Overrides modify inherited rules from extended profiles.
Overrides map[string]RuleOverride `json:"overrides,omitempty"`
// Lexicon defines approved and forbidden terminology.
Lexicon *Lexicon `json:"lexicon,omitempty"`
// ConformanceLevels define graduated compliance tiers.
ConformanceLevels map[string]ConformanceLevel `json:"conformanceLevels,omitempty"`
// Exceptions are approved rule waivers.
Exceptions []Exception `json:"exceptions,omitempty"`
// Categories defines available rule categories with metadata.
Categories []Category `json:"categories,omitempty"`
// Patterns defines reusable API design patterns.
Patterns []Pattern `json:"patterns,omitempty"`
// Sections defines document structure for navigation.
Sections []Section `json:"sections,omitempty"`
// Glossary defines terminology used in the specification.
Glossary []GlossaryTerm `json:"glossary,omitempty"`
// Principles defines high-level design principles.
Principles []Principle `json:"principles,omitempty"`
// Metadata contains additional specification information.
Metadata *SpecMetadata `json:"metadata,omitempty"`
}
APIStyleSpec is the root type for an API style specification. This is the source of truth from which JSON Schema is generated.
func (*APIStyleSpec) GetCategory ¶ added in v0.3.0
func (s *APIStyleSpec) GetCategory(categoryID string) *Category
GetCategory returns a category by ID, or nil if not found.
func (*APIStyleSpec) GetPattern ¶ added in v0.3.0
func (s *APIStyleSpec) GetPattern(patternID string) *Pattern
GetPattern returns a pattern by ID, or nil if not found.
func (*APIStyleSpec) GetRule ¶ added in v0.3.0
func (s *APIStyleSpec) GetRule(ruleID string) *Rule
GetRule returns a rule by ID, or nil if not found.
func (*APIStyleSpec) GetSection ¶ added in v0.3.0
func (s *APIStyleSpec) GetSection(sectionID string) *Section
GetSection returns a section by ID, or nil if not found.
func (*APIStyleSpec) RulesForCategory ¶ added in v0.3.0
func (s *APIStyleSpec) RulesForCategory(categoryID string) []Rule
RulesForCategory returns all rules with the given category ID.
type ActionItem ¶ added in v0.5.0
type ActionItem struct {
// Action is what should be done.
Action string `json:"action"`
// Category is which evaluation category this relates to.
Category string `json:"category,omitempty"`
// Effort estimates the work required (low, medium, high).
Effort string `json:"effort,omitempty"`
// Priority indicates urgency (1 = most urgent).
Priority int `json:"priority,omitempty"`
}
ActionItem is a single recommended action.
type CasingRules ¶
type CasingRules struct {
// Paths defines casing for URL paths (e.g., "kebab-case").
Paths string `json:"paths,omitempty"`
// Parameters defines casing for query/path parameters.
Parameters string `json:"parameters,omitempty"`
// Properties defines casing for JSON properties.
Properties string `json:"properties,omitempty"`
// Headers defines casing for HTTP headers.
Headers string `json:"headers,omitempty"`
}
CasingRules defines naming conventions for different API elements.
type Category ¶
type Category struct {
// ID is the category identifier (e.g., "uri-design").
ID string `json:"id"`
// Title is the display name.
Title string `json:"title"`
// Description explains what this category covers.
Description string `json:"description,omitempty"`
// Order determines display ordering (lower = first).
Order int `json:"order,omitempty"`
}
Category defines a grouping for related rules.
type CategoryCounts ¶ added in v0.5.0
type CategoryCounts struct {
Pass int `json:"pass"`
Partial int `json:"partial"`
Fail int `json:"fail"`
Total int `json:"total"`
}
CategoryCounts tallies category results.
type CategoryResult ¶ added in v0.5.0
type CategoryResult struct {
// Category is the name of the evaluation category.
Category string `json:"category"`
// Score is the categorical score (pass, partial, fail).
Score string `json:"score"`
// NumericScore is the numeric score (typically 1-5).
NumericScore int `json:"numericScore"`
// Weight is the category's weight in overall scoring (0.0-1.0).
Weight float64 `json:"weight,omitempty"`
// Required indicates if this category must pass.
Required bool `json:"required,omitempty"`
// Reasoning explains why this score was given.
Reasoning string `json:"reasoning"`
// Findings are issues specific to this category.
Findings []EvaluationFinding `json:"findings,omitempty"`
}
CategoryResult contains the evaluation result for a single category.
type CodeAnnotation ¶ added in v0.3.0
type CodeAnnotation struct {
// Line is the starting line number (1-indexed).
Line int `json:"line"`
// EndLine is the ending line number (optional, for multi-line annotations).
EndLine int `json:"endLine,omitempty"`
// Text is the annotation message.
Text string `json:"text"`
// Type indicates the annotation severity or purpose.
Type string `json:"type,omitempty"` // "info", "warning", "error"
}
CodeAnnotation highlights a specific part of code in an example.
type Condition ¶ added in v0.3.0
type Condition struct {
// When is a natural language description of when this condition applies.
When string `json:"when"`
// Expression is a JSONPath or CEL expression for evaluation.
Expression string `json:"expression,omitempty"`
// Then describes what should happen when the condition is met.
Then string `json:"then"`
// Unless describes exceptions to the condition.
Unless string `json:"unless,omitempty"`
}
Condition defines if/then/unless logic for rule application.
type ConformanceBlocker ¶ added in v0.5.0
type ConformanceBlocker struct {
// RuleID is the blocking rule.
RuleID string `json:"ruleId"`
// Count is how many violations of this rule exist.
Count int `json:"count"`
// Priority is the fix order (1 = fix first).
Priority int `json:"priority"`
// FixInstructions provides guidance for resolution.
FixInstructions string `json:"fixInstructions"`
}
ConformanceBlocker describes a barrier to conformance.
type ConformanceLevel ¶
type ConformanceLevel struct {
// Description explains what this level represents.
Description string `json:"description,omitempty"`
// RequiredCategories lists category IDs that must pass.
RequiredCategories []string `json:"requiredCategories,omitempty"`
// RequiredRules lists specific rule IDs that must pass.
RequiredRules []string `json:"requiredRules,omitempty"`
// MaxErrors is the maximum allowed error-severity violations.
MaxErrors int `json:"maxErrors"`
// MaxWarnings is the maximum allowed warning-severity violations.
MaxWarnings int `json:"maxWarnings"`
// Extends inherits requirements from another level.
Extends string `json:"extends,omitempty"`
}
ConformanceLevel defines a graduated compliance tier.
type ConformancePath ¶ added in v0.5.0
type ConformancePath struct {
// CurrentLevel is the current conformance level (or "none").
CurrentLevel string `json:"currentLevel"`
// TargetLevel is the requested conformance level.
TargetLevel string `json:"targetLevel"`
// Blockers are errors that must be fixed to reach target.
Blockers []ConformanceBlocker `json:"blockers"`
// Warnings are issues that should be addressed.
Warnings []ConformanceBlocker `json:"warnings,omitempty"`
// ProgressToTarget is a percentage (0.0-1.0) of completion.
ProgressToTarget float64 `json:"progressToTarget"`
// EstimatedFixes is the count of changes needed.
EstimatedFixes int `json:"estimatedFixes"`
}
ConformancePath shows the path to reach a conformance level.
type DecisionRow ¶ added in v0.3.0
type DecisionRow struct {
// Values are the cell values in order.
Values []string `json:"values"`
// Highlight indicates if this row should be emphasized.
Highlight bool `json:"highlight,omitempty"`
}
DecisionRow is a single row in a decision table.
type DecisionTable ¶ added in v0.3.0
type DecisionTable struct {
// Title is the table title.
Title string `json:"title"`
// Description explains the table's purpose.
Description string `json:"description,omitempty"`
// Headers are the column headers.
Headers []string `json:"headers"`
// Rows are the table data rows.
Rows []DecisionRow `json:"rows"`
}
DecisionTable provides structured decision guidance.
type DeprecationInfo ¶ added in v0.3.0
type DeprecationInfo struct {
// Version is when the rule was deprecated.
Version string `json:"version"`
// Message explains why the rule is deprecated.
Message string `json:"message"`
// ReplacedBy lists rule IDs that replace this rule.
ReplacedBy []string `json:"replacedBy,omitempty"`
// RemovalVersion indicates when the rule will be removed.
RemovalVersion string `json:"removalVersion,omitempty"`
}
DeprecationInfo tracks when and why a rule was deprecated.
type DesignCheck ¶ added in v0.5.0
type DesignCheck struct {
// Checklist is ordered rules to follow.
Checklist []DesignCheckItem `json:"checklist"`
// Template is an OpenAPI skeleton to use.
Template map[string]any `json:"template,omitempty"`
// Warnings are potential issues to consider.
Warnings []string `json:"warnings,omitempty"`
}
DesignCheck provides pre-generation guidance.
type DesignCheckItem ¶ added in v0.5.0
type DesignCheckItem struct {
// RuleID is the relevant rule.
RuleID string `json:"ruleId"`
// Instruction is what to do.
Instruction string `json:"instruction"`
// Priority determines order (100 = first).
Priority int `json:"priority"`
// Required indicates if this is mandatory.
Required bool `json:"required"`
}
DesignCheckItem is a single design guidance item.
type DetailedExample ¶ added in v0.3.0
type DetailedExample struct {
// Title is a brief description of the example.
Title string `json:"title"`
// Description provides additional context for the example.
Description string `json:"description,omitempty"`
// Type indicates whether this is a good, bad, or context example.
Type string `json:"type"` // "good", "bad", "context"
// Language specifies the code language (e.g., "openapi", "json", "http").
Language string `json:"language,omitempty"`
// Code is the example code or content.
Code string `json:"code"`
// Annotations highlight specific parts of the code.
Annotations []CodeAnnotation `json:"annotations,omitempty"`
// Before shows the state before migration (for migration examples).
Before string `json:"before,omitempty"`
// After shows the state after migration (for migration examples).
After string `json:"after,omitempty"`
}
DetailedExample provides a rich example with annotations and context.
type Diagram ¶ added in v0.3.0
type Diagram struct {
// Title is the diagram title.
Title string `json:"title"`
// Type specifies the diagram format.
Type string `json:"type"` // "mermaid", "plantuml", "url"
// Content is the diagram content (code for mermaid/plantuml, URL for url type).
Content string `json:"content"`
// Alt is alternative text for accessibility.
Alt string `json:"alt,omitempty"`
}
Diagram provides visual representation of a concept.
type Enforcement ¶
type Enforcement struct {
// Type is the enforcement mechanism.
Type EnforcementType `json:"type"`
// Function is the Spectral function name (for type=spectral).
Function string `json:"function,omitempty"`
// Options are function-specific configuration options.
Options *EnforcementOptions `json:"options,omitempty"`
// Given is the JSONPath expression(s) for targeting nodes (Spectral-style).
// Can be a single string or array of strings.
Given *GivenPaths `json:"given,omitempty"`
// Then defines the assertion to apply (Spectral-style).
Then *SpectralThen `json:"then,omitempty"`
// Pattern is the regex pattern (for type=regex).
Pattern string `json:"pattern,omitempty"`
// CustomFunction is the name of a custom Go function (for type=custom).
CustomFunction string `json:"customFunction,omitempty"`
}
Enforcement defines deterministic rule checking configuration.
type EnforcementOptions ¶
type EnforcementOptions struct {
// Match is a regex pattern to match against (for pattern function).
Match string `json:"match,omitempty"`
// NotMatch is a regex pattern that should not match.
NotMatch string `json:"notMatch,omitempty"`
// Min is a minimum value (for length function).
Min *int `json:"min,omitempty"`
// Max is a maximum value (for length function).
Max *int `json:"max,omitempty"`
// Values is a list of allowed values (for enumeration function).
Values []string `json:"values,omitempty"`
// Type specifies the expected casing type (for casing function).
// Values: flat, camel, pascal, kebab, cobol, snake, macro
Type string `json:"type,omitempty"`
// Separator is used for casing validation.
Separator string `json:"separator,omitempty"`
// Schema is a JSON Schema for validation (for schema function).
Schema string `json:"schema,omitempty"`
}
EnforcementOptions contains common options for enforcement functions.
type EnforcementType ¶
type EnforcementType string
EnforcementType defines how a rule is enforced.
const ( // EnforcementSpectral uses Spectral/vacuum for linting. EnforcementSpectral EnforcementType = "spectral" // EnforcementCustom uses a custom Go function. EnforcementCustom EnforcementType = "custom" // EnforcementRegex uses regular expression matching. EnforcementRegex EnforcementType = "regex" // EnforcementNone means the rule is LLM-only (no deterministic check). EnforcementNone EnforcementType = "none" )
type EvaluationDecision ¶ added in v0.5.0
type EvaluationDecision struct {
// Status is the overall decision (pass, fail, partial).
Status string `json:"status"`
// Reasoning explains why this decision was made.
Reasoning string `json:"reasoning"`
// CategoryCounts summarizes category results.
CategoryCounts *CategoryCounts `json:"categoryCounts"`
// FindingCounts summarizes findings by severity.
FindingCounts *FindingCounts `json:"findingCounts"`
}
EvaluationDecision contains the final pass/fail determination.
type EvaluationFinding ¶ added in v0.5.0
type EvaluationFinding struct {
// Severity is the importance of this finding.
Severity string `json:"severity"` // critical, high, medium, low
// Category is which evaluation category this finding belongs to.
Category string `json:"category"`
// Finding is the description of what was found.
Finding string `json:"finding"`
// Recommendation is how to address this finding.
Recommendation string `json:"recommendation,omitempty"`
// Location is where in the document this finding applies.
Location string `json:"location,omitempty"`
// RuleID links to a specific rule if applicable.
RuleID string `json:"ruleId,omitempty"`
}
EvaluationFinding represents a single finding from evaluation.
type EvaluationMetadata ¶ added in v0.5.0
type EvaluationMetadata struct {
// Document is the path or identifier of the evaluated document.
Document string `json:"document"`
// DocumentTitle is the human-readable title of the document.
DocumentTitle string `json:"documentTitle,omitempty"`
// GeneratedAt is when the evaluation was performed.
GeneratedAt time.Time `json:"generatedAt"`
// GeneratedBy identifies who/what performed the evaluation.
GeneratedBy string `json:"generatedBy,omitempty"`
// ToolVersion is the api-style-spec version.
ToolVersion string `json:"toolVersion,omitempty"`
}
EvaluationMetadata contains context about the evaluation run.
type EvaluationReport ¶ added in v0.5.0
type EvaluationReport struct {
// Schema is the JSON Schema URI for validation.
Schema string `json:"$schema,omitempty"`
// Metadata contains context about the evaluation.
Metadata *EvaluationMetadata `json:"metadata"`
// ReviewType identifies the type of review performed.
ReviewType string `json:"reviewType"`
// RubricID is the identifier of the evaluation rubric used.
RubricID string `json:"rubricId"`
// RubricVersion is the version of the rubric.
RubricVersion string `json:"rubricVersion"`
// Categories contains scored results for each evaluation category.
Categories []CategoryResult `json:"categories"`
// Findings lists all issues found during evaluation.
Findings []EvaluationFinding `json:"findings"`
// PassCriteria defines what constitutes a passing evaluation.
PassCriteria *PassCriteria `json:"passCriteria,omitempty"`
// Decision is the overall pass/fail determination.
Decision *EvaluationDecision `json:"decision"`
// OverallDecision is a simple pass/fail string for quick access.
OverallDecision string `json:"overallDecision"`
// NextSteps provides recommended actions.
NextSteps *NextSteps `json:"nextSteps,omitempty"`
// Summary is a brief textual summary of the evaluation.
Summary string `json:"summary,omitempty"`
}
EvaluationReport contains the results of LLM-based style guide evaluation. This matches the structured-evaluation JSON format.
func NewEvaluationReport ¶ added in v0.5.0
func NewEvaluationReport() *EvaluationReport
NewEvaluationReport creates a new EvaluationReport with initialized fields.
func (*EvaluationReport) AddCategory ¶ added in v0.5.0
func (r *EvaluationReport) AddCategory(cat CategoryResult)
AddCategory adds a category result and updates counts.
func (*EvaluationReport) AddFinding ¶ added in v0.5.0
func (r *EvaluationReport) AddFinding(f EvaluationFinding)
AddFinding adds a finding and updates counts.
func (*EvaluationReport) IsPassing ¶ added in v0.5.0
func (r *EvaluationReport) IsPassing() bool
IsPassing returns true if the evaluation passed.
type Examples ¶
type Examples struct {
// Good shows correct usage patterns.
Good []string `json:"good,omitempty"`
// Bad shows incorrect usage patterns.
Bad []string `json:"bad,omitempty"`
// Detailed provides rich examples with annotations and context.
Detailed []DetailedExample `json:"detailed,omitempty"`
}
Examples provides good and bad usage patterns for a rule.
type Exception ¶
type Exception struct {
// ID is a unique identifier for this exception.
ID string `json:"id"`
// RuleID is the rule being waived.
RuleID string `json:"ruleId"`
// AppliesTo defines the scope of the exception.
AppliesTo *ExceptionScope `json:"appliesTo,omitempty"`
// Reason explains why this exception was granted.
Reason string `json:"reason"`
// ApprovedBy identifies who approved the exception.
ApprovedBy string `json:"approvedBy,omitempty"`
// ApprovedOn is when the exception was granted.
ApprovedOn *time.Time `json:"approvedOn,omitempty"`
// ExpiresOn is when the exception expires (nil = never).
ExpiresOn *time.Time `json:"expiresOn,omitempty"`
// Ticket links to an issue tracker for tracking.
Ticket string `json:"ticket,omitempty"`
}
Exception defines an approved waiver for a specific rule violation.
type ExceptionScope ¶
type ExceptionScope struct {
// API limits the exception to a specific API name.
API string `json:"api,omitempty"`
// Path limits the exception to specific paths (glob supported).
Path string `json:"path,omitempty"`
// Operation limits the exception to specific operations.
Operation string `json:"operation,omitempty"`
// Paths lists multiple paths (alternative to single Path).
Paths []string `json:"paths,omitempty"`
}
ExceptionScope defines where an exception applies.
type FileLintReport ¶ added in v0.2.0
type FileLintReport struct {
// File is the path to the linted specification.
File string `json:"file"`
// Report contains the lint results for this file.
*LintReport
}
FileLintReport wraps a LintReport with file path information.
type FindingCounts ¶ added in v0.5.0
type FindingCounts struct {
Critical int `json:"critical"`
High int `json:"high"`
Medium int `json:"medium"`
Low int `json:"low"`
Total int `json:"total"`
}
FindingCounts tallies findings by severity.
type FindingLimits ¶ added in v0.5.0
type FindingLimits struct {
Critical int `json:"critical,omitempty"`
High int `json:"high,omitempty"`
Medium int `json:"medium,omitempty"`
Low int `json:"low,omitempty"`
}
FindingLimits specifies maximum allowed findings per severity.
type FixReport ¶ added in v0.5.0
type FixReport struct {
// Suggestions are the proposed fixes.
Suggestions []FixSuggestion `json:"suggestions"`
// PatchOperations are JSON Patch operations (RFC 6902).
PatchOperations []PatchOperation `json:"patchOperations,omitempty"`
// FixedCount is how many violations have suggestions.
FixedCount int `json:"fixedCount"`
// UnfixedCount is how many violations could not be auto-fixed.
UnfixedCount int `json:"unfixedCount"`
// UnfixedRules lists rules that couldn't be auto-fixed.
UnfixedRules []string `json:"unfixedRules,omitempty"`
}
FixReport contains all fix suggestions for a spec.
type FixSuggestion ¶ added in v0.5.0
type FixSuggestion struct {
// RuleID is the rule this fix addresses.
RuleID string `json:"ruleId"`
// Path is the JSONPath to the element to fix.
Path string `json:"path"`
// CurrentValue is the existing value (may be empty for missing fields).
CurrentValue string `json:"currentValue,omitempty"`
// SuggestedValue is the proposed replacement.
SuggestedValue string `json:"suggestedValue"`
// Diff shows the change in unified diff format.
Diff string `json:"diff,omitempty"`
// Confidence indicates certainty that this fix is correct (0.0-1.0).
Confidence float64 `json:"confidence"`
// Reasoning explains why this fix is suggested.
Reasoning string `json:"reasoning,omitempty"`
// Breaking indicates if this fix could break existing clients.
Breaking bool `json:"breaking,omitempty"`
// BreakingReason explains why the fix is breaking.
BreakingReason string `json:"breakingReason,omitempty"`
}
FixSuggestion represents a proposed fix for a violation.
type ForbiddenTerm ¶
type ForbiddenTerm struct {
// Term is the forbidden word or phrase.
Term string `json:"term"`
// ReplaceWith suggests the preferred alternative.
ReplaceWith string `json:"replaceWith,omitempty"`
// Reason explains why this term is forbidden.
Reason string `json:"reason,omitempty"`
}
ForbiddenTerm defines a term that should not be used.
type GenerationExample ¶ added in v0.5.0
type GenerationExample struct {
// Description explains what this example demonstrates.
Description string `json:"description"`
// OpenAPI is a YAML/JSON snippet showing correct usage.
OpenAPI string `json:"openapi"`
// Context explains when this pattern applies.
Context string `json:"context,omitempty"`
}
GenerationExample shows correct OpenAPI usage for a rule.
type GenerationGuidance ¶ added in v0.5.0
type GenerationGuidance struct {
// Prompt is the instruction for an LLM when generating spec content.
// Written as a positive directive (e.g., "Use plural nouns for collections").
Prompt string `json:"prompt"`
// Template is a URI or schema pattern to follow.
// Variables use {placeholder} syntax.
Template string `json:"template,omitempty"`
// Priority determines generation order (100 = apply first, 1 = last).
// Used to ensure foundational rules are followed before details.
Priority int `json:"priority,omitempty"`
// Examples show OpenAPI snippets demonstrating correct usage.
Examples []GenerationExample `json:"examples,omitempty"`
// Checklist provides bullet points to verify compliance.
Checklist []string `json:"checklist,omitempty"`
}
GenerationGuidance provides instructions for AI agents generating OpenAPI specs.
type GivenPaths ¶
type GivenPaths struct {
// Paths contains one or more JSONPath expressions.
Paths []string `json:"paths"`
}
GivenPaths represents JSONPath expressions for Spectral rules. Can be marshaled as a single string or array of strings.
func NewGivenPath ¶
func NewGivenPath(path string) *GivenPaths
NewGivenPath creates a GivenPaths with a single path.
func NewGivenPaths ¶
func NewGivenPaths(paths ...string) *GivenPaths
NewGivenPaths creates a GivenPaths with multiple paths.
type GlossaryTerm ¶ added in v0.3.0
type GlossaryTerm struct {
// Term is the word or phrase being defined.
Term string `json:"term"`
// Definition explains the term.
Definition string `json:"definition"`
// Aliases are alternative names for the term.
Aliases []string `json:"aliases,omitempty"`
}
GlossaryTerm defines a term in the API style glossary.
type JudgeCriteria ¶
type JudgeCriteria struct {
// Prompt is the evaluation instruction for the LLM.
Prompt string `json:"prompt"`
// Weight influences scoring (0.0-1.0, default 1.0).
Weight float64 `json:"weight,omitempty"`
// RequiresContext indicates if broader context is needed for evaluation.
RequiresContext bool `json:"requiresContext,omitempty"`
// Category overrides the rule's category for evaluation grouping.
Category string `json:"category,omitempty"`
// PassCriteria lists requirements for a "pass" score.
PassCriteria []string `json:"passCriteria,omitempty"`
// PartialCriteria lists requirements for a "partial" score.
PartialCriteria []string `json:"partialCriteria,omitempty"`
// FailCriteria lists requirements for a "fail" score.
FailCriteria []string `json:"failCriteria,omitempty"`
// Examples provides few-shot examples for LLM evaluation.
Examples *JudgeExamples `json:"examples,omitempty"`
// ScaleType defines the scoring scale type.
ScaleType string `json:"scaleType,omitempty"` // "categorical", "binary", "checklist"
}
JudgeCriteria defines LLM evaluation parameters for a rule.
type JudgeExample ¶ added in v0.3.0
type JudgeExample struct {
// Excerpt is the example API content or snippet.
Excerpt string `json:"excerpt"`
// Reasoning explains why this example gets this score (chain-of-thought).
Reasoning string `json:"reasoning"`
}
JudgeExample is a single few-shot example for LLM evaluation.
type JudgeExamples ¶ added in v0.3.0
type JudgeExamples struct {
// Pass is an example that demonstrates passing.
Pass *JudgeExample `json:"pass,omitempty"`
// Partial is an example that demonstrates partial compliance.
Partial *JudgeExample `json:"partial,omitempty"`
// Fail is an example that demonstrates failure.
Fail *JudgeExample `json:"fail,omitempty"`
}
JudgeExamples provides few-shot examples aligned with structured-evaluation.
type Lexicon ¶
type Lexicon struct {
// Approved lists terms that should be used.
Approved []string `json:"approved,omitempty"`
// Forbidden lists terms that should not be used, with replacements.
Forbidden []ForbiddenTerm `json:"forbidden,omitempty"`
// Aliases maps equivalent terms.
Aliases map[string]string `json:"aliases,omitempty"`
// CasingRules defines naming conventions for different contexts.
CasingRules *CasingRules `json:"casingRules,omitempty"`
}
Lexicon defines approved and forbidden terminology for API design.
type LintReport ¶
type LintReport struct {
// Status is the overall pass/fail result.
Status ReportStatus `json:"status"`
// ConformanceLevel is the highest level achieved (if levels are defined).
ConformanceLevel string `json:"conformanceLevel,omitempty"`
// Summary provides violation counts by severity.
Summary *ViolationSummary `json:"summary"`
// Violations lists all findings.
Violations []Violation `json:"violations"`
// IgnoredViolations lists violations that were suppressed by exceptions.
IgnoredViolations []Violation `json:"ignoredViolations,omitempty"`
// Metadata includes timing, versions, and other context.
Metadata *ReportMetadata `json:"metadata,omitempty"`
}
LintReport contains the results of deterministic linting.
func NewLintReport ¶
func NewLintReport() *LintReport
NewLintReport creates a new LintReport with initialized fields.
func (*LintReport) AddViolation ¶
func (r *LintReport) AddViolation(v Violation)
AddViolation adds a violation and updates the summary.
func (*LintReport) HasBlockingViolations ¶
func (r *LintReport) HasBlockingViolations() bool
HasBlockingViolations returns true if there are error-level violations.
type MigrationGuidance ¶ added in v0.3.0
type MigrationGuidance struct {
// Summary is a brief description of the migration.
Summary string `json:"summary"`
// Steps are ordered migration steps.
Steps []MigrationStep `json:"steps,omitempty"`
// AutoFixAvailable indicates if an automated fix is available.
AutoFixAvailable bool `json:"autoFixAvailable,omitempty"`
// Effort estimates the work required.
Effort string `json:"effort,omitempty"` // "low", "medium", "high"
// BreakingChange indicates if this migration is a breaking change.
BreakingChange bool `json:"breakingChange,omitempty"`
}
MigrationGuidance provides instructions for fixing rule violations.
type MigrationStep ¶ added in v0.3.0
type MigrationStep struct {
// Order is the step sequence number.
Order int `json:"order"`
// Description explains what to do in this step.
Description string `json:"description"`
// Code provides example code for the step.
Code string `json:"code,omitempty"`
// Language specifies the code language.
Language string `json:"language,omitempty"`
}
MigrationStep is a single step in a migration process.
type MultiLintReport ¶ added in v0.2.0
type MultiLintReport struct {
// Status is the overall pass/fail result across all files.
Status Status `json:"status"`
// Summary provides aggregate violation counts across all files.
Summary *ViolationSummary `json:"summary"`
// FileReports contains individual reports for each file.
FileReports []FileLintReport `json:"fileReports"`
// Metadata includes timing, versions, and other context.
Metadata *ReportMetadata `json:"metadata,omitempty"`
}
MultiLintReport contains results from linting multiple files.
func NewMultiLintReport ¶ added in v0.2.0
func NewMultiLintReport() *MultiLintReport
NewMultiLintReport creates a new MultiLintReport with initialized fields.
func (*MultiLintReport) AddFileReport ¶ added in v0.2.0
func (r *MultiLintReport) AddFileReport(file string, report *LintReport)
AddFileReport adds a file report and updates the aggregate summary.
func (*MultiLintReport) FailedFileCount ¶ added in v0.2.0
func (r *MultiLintReport) FailedFileCount() int
FailedFileCount returns the number of files that failed linting.
func (*MultiLintReport) FileCount ¶ added in v0.2.0
func (r *MultiLintReport) FileCount() int
FileCount returns the number of files that were linted.
func (*MultiLintReport) HasBlockingViolations ¶ added in v0.2.0
func (r *MultiLintReport) HasBlockingViolations() bool
HasBlockingViolations returns true if any file has error-level violations.
type NextSteps ¶ added in v0.5.0
type NextSteps struct {
// Immediate are actions that must be taken before proceeding.
Immediate []ActionItem `json:"immediate,omitempty"`
// Recommended are suggested improvements.
Recommended []ActionItem `json:"recommended,omitempty"`
}
NextSteps provides recommended actions after evaluation.
type PassCriteria ¶ added in v0.5.0
type PassCriteria struct {
// MinCategoriesPassing is how many categories must pass.
// Can be a number or "all_required".
MinCategoriesPassing string `json:"minCategoriesPassing,omitempty"`
// MaxFindings is the maximum allowed findings by severity.
MaxFindings *FindingLimits `json:"maxFindings,omitempty"`
}
PassCriteria defines what constitutes a passing evaluation.
type PatchOperation ¶ added in v0.5.0
type PatchOperation struct {
// Op is the operation: "add", "remove", "replace", "move", "copy", "test".
Op string `json:"op"`
// Path is the JSON Pointer to the target location.
Path string `json:"path"`
// From is the source location for move/copy operations.
From string `json:"from,omitempty"`
// Value is the value for add/replace/test operations.
Value any `json:"value,omitempty"`
}
PatchOperation represents a JSON Patch operation (RFC 6902).
type Pattern ¶ added in v0.3.0
type Pattern struct {
// ID is a unique identifier for the pattern.
ID string `json:"id"`
// Name is the human-readable name.
Name string `json:"name"`
// Category groups related patterns (e.g., "collections", "errors", "versioning").
Category string `json:"category,omitempty"`
// Summary is a brief one-line description.
Summary string `json:"summary"`
// Description provides extended prose explanation (Markdown).
Description string `json:"description,omitempty"`
// Problem describes what issue this pattern addresses.
Problem string `json:"problem,omitempty"`
// Solution describes how the pattern solves the problem.
Solution string `json:"solution,omitempty"`
// When describes when to use this pattern.
When string `json:"when,omitempty"`
// Examples provides detailed usage examples.
Examples []DetailedExample `json:"examples,omitempty"`
// RelatedRules lists rule IDs that implement or relate to this pattern.
RelatedRules []string `json:"relatedRules,omitempty"`
// RelatedPatterns lists other pattern IDs that work with this one.
RelatedPatterns []string `json:"relatedPatterns,omitempty"`
// References links to external documentation.
References []Reference `json:"references,omitempty"`
// Diagrams provides visual representations of the pattern.
Diagrams []Diagram `json:"diagrams,omitempty"`
}
Pattern defines a reusable API design pattern.
type Principle ¶ added in v0.3.0
type Principle struct {
// ID is a unique identifier for the principle.
ID string `json:"id"`
// Title is the principle name.
Title string `json:"title"`
// Description explains the principle in detail (Markdown).
Description string `json:"description"`
// RelatedRules lists rule IDs that implement this principle.
RelatedRules []string `json:"relatedRules,omitempty"`
}
Principle defines a high-level design principle.
type Reference ¶
type Reference struct {
// Title is the display text for the reference.
Title string `json:"title"`
// URL is the link to the external resource.
URL string `json:"url"`
}
Reference links to external documentation.
type ReportMetadata ¶
type ReportMetadata struct {
// SpecFile is the path to the linted specification.
SpecFile string `json:"specFile,omitempty"`
// SpecVersion is the OpenAPI version of the spec.
SpecVersion string `json:"specVersion,omitempty"`
// Profile is the style profile used.
Profile string `json:"profile,omitempty"`
// ProfileVersion is the version of the profile.
ProfileVersion string `json:"profileVersion,omitempty"`
// Duration is how long linting took.
Duration time.Duration `json:"duration,omitempty"`
// DurationMS is duration in milliseconds (for JSON serialization).
DurationMS int64 `json:"durationMs,omitempty"`
// Timestamp is when linting was performed.
Timestamp time.Time `json:"timestamp"`
// ToolVersion is the api-style-spec version.
ToolVersion string `json:"toolVersion,omitempty"`
// RulesEvaluated is the count of rules that were checked.
RulesEvaluated int `json:"rulesEvaluated,omitempty"`
}
ReportMetadata contains context about the linting run.
type ReportStatus ¶
type ReportStatus = Status
ReportStatus is an alias for Status (deprecated, use Status).
type Rule ¶
type Rule struct {
// ID is a unique identifier for the rule (e.g., "URI-001").
ID string `json:"id"`
// Title is a short, descriptive name for the rule.
Title string `json:"title"`
// Category groups related rules (e.g., "uri-design", "naming", "security").
Category string `json:"category"`
// Severity indicates the importance of violations.
Severity Severity `json:"severity"`
// Scope defines what part of the spec this rule applies to.
Scope Scope `json:"scope,omitempty"`
// Rationale explains why this rule exists and its benefits.
Rationale string `json:"rationale,omitempty"`
// Description provides extended prose explanation (Markdown).
Description string `json:"description,omitempty"`
// Background provides historical or industry context.
Background string `json:"background,omitempty"`
// SectionRef links to a document section ID.
SectionRef string `json:"sectionRef,omitempty"`
// Priority determines ordering within category (lower = higher priority).
Priority int `json:"priority,omitempty"`
// Version indicates when this rule was added or last changed.
Version string `json:"version,omitempty"`
// Deprecated provides deprecation information if the rule is deprecated.
Deprecated *DeprecationInfo `json:"deprecated,omitempty"`
// Examples provides good and bad usage patterns.
Examples *Examples `json:"examples,omitempty"`
// Enforcement defines deterministic checking configuration.
Enforcement *Enforcement `json:"enforcement,omitempty"`
// Judge defines LLM evaluation criteria for this rule.
Judge *JudgeCriteria `json:"judge,omitempty"`
// References links to external documentation.
References []Reference `json:"references,omitempty"`
// Tags are labels for filtering and grouping rules.
Tags []string `json:"tags,omitempty"`
// Recommended indicates if this rule is part of the recommended set.
Recommended bool `json:"recommended,omitempty"`
// Applicability defines when this rule applies.
Applicability *RuleApplicability `json:"applicability,omitempty"`
// Conditions are if/then/unless logic for rule application.
Conditions []Condition `json:"conditions,omitempty"`
// Relations define dependencies on other rules.
Relations []RuleRelation `json:"relations,omitempty"`
// DecisionTables provide structured decision guidance.
DecisionTables []DecisionTable `json:"decisionTables,omitempty"`
// Migration provides guidance for fixing violations.
Migration *MigrationGuidance `json:"migration,omitempty"`
// Generate provides instructions for AI agents generating OpenAPI specs.
Generate *GenerationGuidance `json:"generate,omitempty"`
}
Rule defines a single API style guideline.
type RuleApplicability ¶ added in v0.3.0
type RuleApplicability struct {
// APITypes specifies which API types this rule applies to.
APITypes []string `json:"apiTypes,omitempty"` // "rest", "graphql", "grpc"
// OpenAPIVersions specifies which OpenAPI versions this rule applies to.
OpenAPIVersions []string `json:"openAPIVersions,omitempty"` // "3.0", "3.1"
// HTTPMethods specifies which HTTP methods this rule applies to.
HTTPMethods []string `json:"httpMethods,omitempty"` // "GET", "POST", "PUT", "DELETE", etc.
// Contexts specifies which contexts this rule applies to.
Contexts []string `json:"contexts,omitempty"` // "public", "internal", "partner"
// IncludePatterns are JSONPath expressions for targeted application.
IncludePatterns []string `json:"includePatterns,omitempty"`
// ExcludePatterns are JSONPath expressions for exclusion.
ExcludePatterns []string `json:"excludePatterns,omitempty"`
}
RuleApplicability defines when a rule applies.
type RuleOverride ¶
type RuleOverride struct {
// Severity overrides the rule's severity.
Severity *Severity `json:"severity,omitempty"`
// Disabled completely disables the rule.
Disabled bool `json:"disabled,omitempty"`
// Rationale provides context for the override.
Rationale string `json:"rationale,omitempty"`
}
RuleOverride modifies an inherited rule.
type RuleRelation ¶ added in v0.3.0
type RuleRelation struct {
// RuleID is the related rule identifier.
RuleID string `json:"ruleId"`
// Type specifies the relationship type.
Type string `json:"type"` // "requires", "conflicts", "supersedes", "related"
// Description explains the relationship.
Description string `json:"description,omitempty"`
}
RuleRelation defines relationships between rules.
type Scope ¶
type Scope string
Scope defines what part of an OpenAPI specification a rule applies to.
const ( // ScopePath applies to path definitions. ScopePath Scope = "path" // ScopeOperation applies to individual operations (GET, POST, etc.). ScopeOperation Scope = "operation" // ScopeParameter applies to parameters. ScopeParameter Scope = "parameter" // ScopeSchema applies to schema definitions. ScopeSchema Scope = "schema" // ScopeResponse applies to response definitions. ScopeResponse Scope = "response" // ScopeInfo applies to the info section. ScopeInfo Scope = "info" // ScopeSecurity applies to security definitions. ScopeSecurity Scope = "security" // ScopeGlobal applies to the entire specification. ScopeGlobal Scope = "global" )
type Section ¶ added in v0.3.0
type Section struct {
// ID is a unique identifier for the section.
ID string `json:"id"`
// Title is the section heading.
Title string `json:"title"`
// Description provides a brief summary of the section.
Description string `json:"description,omitempty"`
// Order determines display ordering (lower = first).
Order int `json:"order,omitempty"`
// ParentID references a parent section for hierarchy.
ParentID string `json:"parentId,omitempty"`
// Rules lists rule IDs contained in this section.
Rules []string `json:"rules,omitempty"`
// Patterns lists pattern IDs contained in this section.
Patterns []string `json:"patterns,omitempty"`
// Introduction is introductory content for the section (Markdown).
Introduction string `json:"introduction,omitempty"`
// Content is the main section content (Markdown).
Content string `json:"content,omitempty"`
}
Section represents a document section for navigation and organization.
type Severity ¶
type Severity string
Severity represents the severity level of a rule violation.
const ( // SeverityError indicates a critical violation that should block approval. SeverityError Severity = "error" // SeverityWarn indicates a significant issue that should be addressed. SeverityWarn Severity = "warn" // SeverityInfo indicates an informational finding. SeverityInfo Severity = "info" // SeverityHint indicates a suggestion for improvement. SeverityHint Severity = "hint" )
func (Severity) IsBlocking ¶
IsBlocking returns true if this severity level blocks approval.
type SpecMetadata ¶
type SpecMetadata struct {
// Author is the creator of this specification.
Author string `json:"author,omitempty"`
// License is the license for this specification.
License string `json:"license,omitempty"`
// Repository is the source repository URL.
Repository string `json:"repository,omitempty"`
// Website is a documentation website URL.
Website string `json:"website,omitempty"`
// URL is an alias for website/repository for external reference.
URL string `json:"url,omitempty"`
// Contact is contact information.
Contact string `json:"contact,omitempty"`
// LastUpdated is when the specification was last modified.
LastUpdated string `json:"lastUpdated,omitempty"`
}
SpecMetadata contains additional specification information.
type SpectralThen ¶
type SpectralThen struct {
// Field is the field to check within the matched node.
Field string `json:"field,omitempty"`
// Function is the assertion function to apply.
Function string `json:"function,omitempty"`
// FunctionOptions are options for the function.
FunctionOptions map[string]string `json:"functionOptions,omitempty"`
}
SpectralThen defines a Spectral-compatible assertion.
type Violation ¶
type Violation struct {
// RuleID is the identifier of the violated rule.
RuleID string `json:"ruleId"`
// Severity indicates the importance of this violation.
Severity Severity `json:"severity"`
// Message describes what went wrong.
Message string `json:"message"`
// Path is the JSONPath to the violation location.
Path string `json:"path"`
// Line is the line number in the source file (1-indexed).
Line int `json:"line,omitempty"`
// Column is the column number in the source file (1-indexed).
Column int `json:"column,omitempty"`
// EndLine is the ending line for multi-line issues.
EndLine int `json:"endLine,omitempty"`
// EndColumn is the ending column for multi-line issues.
EndColumn int `json:"endColumn,omitempty"`
// Suggestion provides guidance for fixing the violation.
Suggestion string `json:"suggestion,omitempty"`
// RuleTitle is the human-readable rule name.
RuleTitle string `json:"ruleTitle,omitempty"`
// Category is the rule's category.
Category string `json:"category,omitempty"`
// ExampleFix shows a code snippet demonstrating the fix.
// Format matches the input spec format (YAML or JSON).
ExampleFix string `json:"exampleFix,omitempty"`
// RuleURL links to the rule's documentation page.
RuleURL string `json:"ruleUrl,omitempty"`
// Confidence indicates certainty of this violation (0.0-1.0).
// 1.0 = deterministic match, <1.0 = heuristic or LLM-based.
Confidence float64 `json:"confidence,omitempty"`
// RelatedRules lists rule IDs that should be addressed first
// or are commonly fixed together with this violation.
RelatedRules []string `json:"relatedRules,omitempty"`
// FixPriority indicates the recommended fix order (1 = fix first).
// Derived from rule priority and dependencies.
FixPriority int `json:"fixPriority,omitempty"`
}
Violation represents a single rule violation.
type ViolationSummary ¶
type ViolationSummary struct {
// Errors is the count of error-severity violations.
Errors int `json:"errors"`
// Warnings is the count of warning-severity violations.
Warnings int `json:"warnings"`
// Infos is the count of info-severity violations.
Infos int `json:"infos"`
// Hints is the count of hint-severity violations.
Hints int `json:"hints"`
// Total is the sum of all violations.
Total int `json:"total"`
}
ViolationSummary counts violations by severity.