client

package
v0.1.7 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2025 License: MIT Imports: 13 Imported by: 0

README

Forge Client Generator

An elegant, extensible client code generator that introspects Forge routes and generates type-safe clients for multiple languages.

Features

  • Multi-Language Support: Currently supports Go and TypeScript, extensible to Rust and other languages
  • Comprehensive API Coverage: Generates clients for REST, WebSocket, and SSE endpoints
  • Smart Auth Integration: Detects and generates proper authentication code (Bearer, API Key, Basic, OAuth2)
  • Advanced Streaming: Includes reconnection, heartbeat, and connection state management for WebSocket/SSE
  • Type-Safe: Generates fully typed clients from OpenAPI/AsyncAPI specifications
  • Clean API: Modern, idiomatic code generation for each target language
  • Extensible: Plugin-based architecture for adding new language generators

Architecture

Core Components
  • ir.go: Intermediate Representation - Language-agnostic API spec data structures
  • introspector.go: Extracts route information from Forge Router (runtime introspection)
  • spec_parser.go: Parses OpenAPI 3.1.0 and AsyncAPI 3.0.0 specifications from files
  • generator.go: Central orchestration and language generator registry
  • auth.go: Authentication scheme detection and code generation utilities
  • streaming.go: Streaming features (reconnection, heartbeat, state management)
  • config.go: Generator configuration with feature flags
  • output.go: File writing and README generation
Language Generators
Go Generator (generators/golang/)
  • generator.go: Main generator with client struct and auth config
  • types.go: Type definitions from schemas
  • rest.go: REST endpoint methods
  • websocket.go: WebSocket clients with goroutines and channels
  • sse.go: Server-Sent Events clients

Features:

  • Idiomatic Go code with context support
  • Graceful error handling
  • Connection pooling and reconnection
  • Structured with proper package layout
TypeScript Generator (generators/typescript/)
  • generator.go: Main generator with Axios-based client
  • Type-safe interfaces from OpenAPI schemas
  • Modern async/await patterns
  • NPM package generation with package.json and tsconfig.json

Usage

CLI Commands
Generate Client
# Generate from OpenAPI/AsyncAPI spec file
forge client generate --from-spec ./api/openapi.yaml --language go --output ./sdk

# With full options
forge client generate \
  --from-spec ./api/openapi.yaml \
  --language typescript \
  --output ./clients/typescript \
  --package "@myorg/api-client" \
  --base-url "https://api.example.com" \
  --auth \
  --streaming \
  --reconnection \
  --heartbeat \
  --state-management
List Endpoints
# List all endpoints from spec
forge client list --from-spec ./api/openapi.yaml

# Filter by type
forge client list --from-spec ./api/openapi.yaml --type rest
forge client list --from-spec ./api/openapi.yaml --type ws
forge client list --from-spec ./api/openapi.yaml --type sse
Initialize Config
# Interactive configuration wizard
forge client init

Creates .forge-client.yaml:

clients:
  - language: go
    output: clients/go
    package: apiclient
    base_url: https://api.example.com
    features:
      reconnection: true
      heartbeat: true
      state_management: true
Programmatic API
import (
    "context"
    "github.com/xraph/forge/internal/client"
    "github.com/xraph/forge/internal/client/generators/golang"
)

// Create generator
gen := client.NewGenerator()

// Register language generators
gen.Register(golang.NewGenerator())

// Configure generation
config := client.GeneratorConfig{
    Language:         "go",
    OutputDir:        "./sdk",
    PackageName:      "apiclient",
    BaseURL:          "https://api.example.com",
    IncludeAuth:      true,
    IncludeStreaming: true,
    Features: client.Features{
        Reconnection:    true,
        Heartbeat:       true,
        StateManagement: true,
        TypedErrors:     true,
    },
}

// Generate from spec file
generatedClient, err := gen.GenerateFromFile(context.Background(), "./openapi.yaml", config)
if err != nil {
    log.Fatal(err)
}

// Write to disk
outputMgr := client.NewOutputManager()
err = outputMgr.WriteClient(generatedClient, config.OutputDir)

Generated Client Structure

Go
sdk/
├── go.mod              # Go module file
├── README.md           # Usage instructions
├── client.go           # Main client with auth config
├── types.go            # Generated type definitions
├── rest.go             # REST endpoint methods
├── websocket.go        # WebSocket clients
├── sse.go              # SSE clients
└── errors.go           # Error types

Example usage:

import "your-module/sdk"

client := sdk.NewClient(
    sdk.WithBaseURL("https://api.example.com"),
    sdk.WithAuth(sdk.AuthConfig{
        BearerToken: "your-token",
    }),
)

// REST call
result, err := client.GetUser(ctx, "user-123")

// WebSocket
ws := client.NewChatWSClient()
ws.Connect(ctx)
ws.OnMessage(func(msg ChatMessage) {
    fmt.Println("Received:", msg)
})
ws.Send(ChatMessage{Text: "Hello"})

// SSE
sse := client.NewNotificationSSEClient()
sse.Connect(ctx)
sse.OnNotification(func(notif Notification) {
    fmt.Println("Notification:", notif)
})
TypeScript
client/
├── package.json        # NPM package config
├── tsconfig.json       # TypeScript config
├── README.md           # Usage instructions
└── src/
    ├── index.ts        # Barrel exports
    ├── types.ts        # Type definitions
    ├── client.ts       # Main client class
    ├── rest.ts         # REST methods
    ├── websocket.ts    # WebSocket clients
    └── sse.ts          # SSE clients

Example usage:

import { Client } from '@myorg/api-client';

const client = new Client({
  baseURL: 'https://api.example.com',
  auth: {
    bearerToken: 'your-token',
  },
});

// REST call
const user = await client.getUser('user-123');

// WebSocket
const ws = new ChatWSClient();
await ws.connect();
ws.onMessage((msg) => {
  console.log('Received:', msg);
});
ws.send({ text: 'Hello' });

Authentication Support

The client generator automatically detects and generates appropriate auth code for:

  • Bearer Token (JWT)
  • API Key (header or query parameter)
  • Basic Auth
  • OAuth 2.0 (all flows)
  • Custom Headers

Detection is based on OpenAPI security schemes in the specification.

Streaming Features

Reconnection
  • Exponential backoff strategy
  • Configurable max attempts and delays
  • Automatic resume with last event ID (SSE)
Heartbeat
  • Periodic ping messages for WebSocket
  • Configurable intervals
  • Connection health monitoring
State Management
  • Connection state tracking (disconnected, connecting, connected, reconnecting, closed, error)
  • State change callbacks
  • Thread-safe state access

Extension Guide

Adding a New Language Generator
  1. Create a new package: generators/<language>/

  2. Implement the LanguageGenerator interface:

type LanguageGenerator interface {
    Name() string
    SupportedFeatures() []string
    Generate(ctx context.Context, spec APISpec, config GeneratorConfig) (*GeneratedClient, error)
    Validate(spec APISpec) error
}
  1. Create generator files:

    • generator.go - Main generator and client structure
    • types.go - Type system mapping
    • rest.go - REST endpoint generation
    • websocket.go - WebSocket client generation (if supported)
    • sse.go - SSE client generation (if supported)
  2. Register the generator:

gen.Register(yourlang.NewGenerator())
Type Mapping

Each language generator must map OpenAPI/JSON Schema types to native types:

JSON Schema Go TypeScript Rust
string string string String
integer int number i32/i64
number float64 number f64
boolean bool boolean bool
array []T T[] Vec
object struct interface struct

Configuration Options

GeneratorConfig
  • Language: Target language (go, typescript, rust)
  • OutputDir: Where to write generated files
  • PackageName: Package/module name
  • APIName: Main client class/struct name
  • BaseURL: Default API base URL
  • IncludeAuth: Generate authentication configuration
  • IncludeStreaming: Generate WebSocket/SSE clients
  • Module: Go module path (Go only)
  • Version: Generated client version
Features
  • Reconnection: Auto-reconnect for streaming
  • Heartbeat: Connection health checks
  • StateManagement: Track connection state
  • TypedErrors: Generate typed error responses
  • RequestRetry: Auto-retry failed requests
  • Timeout: Request timeout configuration
  • Middleware: Request/response interceptors
  • Logging: Built-in logging support

Testing

The client generator includes comprehensive tests:

  • Unit tests: Test IR conversion, type mapping, code generation
  • Integration tests: Generate clients and verify compilation
  • Fixture tests: Test against sample OpenAPI/AsyncAPI specs

Run tests:

cd v2/internal/client
go test ./...

Performance Considerations

  • Lazy initialization: Clients are created on-demand
  • Connection pooling: Reuse HTTP connections
  • Streaming efficiency: Goroutines/async for concurrent processing
  • Memory management: Proper cleanup and resource disposal

Roadmap

  • Rust generator
  • Python generator
  • gRPC support
  • GraphQL support
  • Code formatting integration (gofmt, prettier, rustfmt)
  • Validation middleware generation
  • Rate limiting client-side
  • Circuit breaker patterns
  • Metrics and telemetry hooks
  • Mock client generation for testing

Contributing

When adding features or fixing bugs:

  1. Update IR types if needed (ir.go)
  2. Update language generators
  3. Add tests
  4. Update documentation
  5. Run linters: golangci-lint run

License

Part of the Forge v2 framework. See main project license.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func EnsureDirectory

func EnsureDirectory(path string) error

EnsureDirectory ensures a directory exists

func FileExists

func FileExists(path string) bool

FileExists checks if a file exists

func FormatCode

func FormatCode(code string, language string) string

FormatCode formats generated code (basic formatting)

func GenerateSSEClientName

func GenerateSSEClientName(endpoint SSEEndpoint) string

GenerateSSEClientName generates a name for an SSE client struct/class

func GenerateStreamingFeatureDocs

func GenerateStreamingFeatureDocs(features Features) string

GenerateStreamingFeatureDocs generates documentation for streaming features

func GenerateWebSocketClientName

func GenerateWebSocketClientName(endpoint WebSocketEndpoint) string

GenerateWebSocketClientName generates a name for a WebSocket client struct/class

func GetStreamingEndpointCount

func GetStreamingEndpointCount(spec *APISpec) (websockets, sse int)

GetStreamingEndpointCount returns the count of streaming endpoints

func HasSSE

func HasSSE(spec *APISpec) bool

HasSSE checks if the API spec has SSE endpoints

func HasStreamingEndpoints

func HasStreamingEndpoints(spec *APISpec) bool

HasStreamingEndpoints checks if the API spec has any streaming endpoints

func HasWebSockets

func HasWebSockets(spec *APISpec) bool

HasWebSockets checks if the API spec has WebSocket endpoints

func NeedsAuthConfig

func NeedsAuthConfig(spec *APISpec) bool

NeedsAuthConfig determines if any endpoints need authentication

Types

type APIInfo

type APIInfo struct {
	Title       string
	Version     string
	Description string
	Contact     *Contact
	License     *License
}

APIInfo contains metadata about the API

type APISpec

type APISpec struct {
	Info          APIInfo
	Servers       []Server
	Endpoints     []Endpoint
	WebSockets    []WebSocketEndpoint
	SSEs          []SSEEndpoint
	WebTransports []WebTransportEndpoint
	Schemas       map[string]*Schema
	Security      []SecurityScheme
	Tags          []Tag
}

APISpec represents the complete API specification in an intermediate representation

func (*APISpec) GetStats

func (spec *APISpec) GetStats() APIStats

GetStats returns statistics about the API spec

func (*APISpec) ResolveSchemaRef

func (spec *APISpec) ResolveSchemaRef(ref string) *Schema

ResolveSchemaRef resolves a schema reference in the spec

func (*APISpec) Validate

func (spec *APISpec) Validate(opts ValidationOptions) []ValidationError

Validate validates the API spec

type APIStats

type APIStats struct {
	TotalEndpoints   int
	RESTEndpoints    int
	WebSocketCount   int
	SSECount         int
	SecuredEndpoints int
	Tags             []string
	UpdatedAt        time.Time
}

Stats returns statistics about the API spec

type AuthCodeGenerator

type AuthCodeGenerator struct{}

AuthCodeGenerator generates authentication-related code

func NewAuthCodeGenerator

func NewAuthCodeGenerator() *AuthCodeGenerator

NewAuthCodeGenerator creates a new auth code generator

func (*AuthCodeGenerator) DetectAuthSchemes

func (a *AuthCodeGenerator) DetectAuthSchemes(spec *APISpec) []DetectedAuthScheme

DetectAuthSchemes detects authentication schemes from the API spec

func (*AuthCodeGenerator) GenerateAuthDocumentation

func (a *AuthCodeGenerator) GenerateAuthDocumentation(schemes []DetectedAuthScheme) string

GenerateAuthDocumentation generates documentation for authentication

func (*AuthCodeGenerator) GetAuthConfigType

func (a *AuthCodeGenerator) GetAuthConfigType(schemes []DetectedAuthScheme) string

GetAuthConfigType determines the appropriate auth config type

func (*AuthCodeGenerator) GetAuthHeaderName

func (a *AuthCodeGenerator) GetAuthHeaderName(scheme DetectedAuthScheme) string

GetAuthHeaderName returns the header name for an auth scheme

func (*AuthCodeGenerator) GetAuthPrefix

func (a *AuthCodeGenerator) GetAuthPrefix(scheme DetectedAuthScheme) string

GetAuthPrefix returns the prefix for an auth value (e.g., "Bearer ")

func (*AuthCodeGenerator) GetEndpointAuthRequirements

func (a *AuthCodeGenerator) GetEndpointAuthRequirements(endpoint Endpoint, spec *APISpec) []AuthRequirement

GetEndpointAuthRequirements returns auth requirements for an endpoint

type AuthRequirement

type AuthRequirement struct {
	SchemeName string
	Required   bool
	Scopes     []string
}

AuthRequirement represents an authentication requirement for a specific endpoint

type BackoffCalculator

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

BackoffCalculator calculates backoff delays

func NewBackoffCalculator

func NewBackoffCalculator(config ReconnectionConfig) *BackoffCalculator

NewBackoffCalculator creates a new backoff calculator

func (*BackoffCalculator) Calculate

func (b *BackoffCalculator) Calculate(attempt int) time.Duration

Calculate calculates the delay for a given attempt number

type ConnectionState

type ConnectionState string

ConnectionState represents the state of a streaming connection

const (
	// ConnectionStateDisconnected means not connected
	ConnectionStateDisconnected ConnectionState = "disconnected"

	// ConnectionStateConnecting means attempting to connect
	ConnectionStateConnecting ConnectionState = "connecting"

	// ConnectionStateConnected means successfully connected
	ConnectionStateConnected ConnectionState = "connected"

	// ConnectionStateReconnecting means attempting to reconnect
	ConnectionStateReconnecting ConnectionState = "reconnecting"

	// ConnectionStateClosed means connection is closed and won't reconnect
	ConnectionStateClosed ConnectionState = "closed"

	// ConnectionStateError means connection error occurred
	ConnectionStateError ConnectionState = "error"
)

type Contact

type Contact struct {
	Name  string
	URL   string
	Email string
}

Contact represents contact information

type DetectedAuthScheme

type DetectedAuthScheme struct {
	Name          string
	Type          string
	In            string
	Scheme        string
	BearerFormat  string
	RequiresScope bool
}

DetectedAuthScheme represents a detected authentication scheme

func MergeAuthSchemes

func MergeAuthSchemes(schemes []DetectedAuthScheme) []DetectedAuthScheme

MergeAuthSchemes merges authentication schemes, removing duplicates

type Discriminator

type Discriminator struct {
	PropertyName string
	Mapping      map[string]string // value -> schema reference
}

Discriminator supports polymorphism

type Endpoint

type Endpoint struct {
	ID          string
	Method      string
	Path        string
	Summary     string
	Description string
	Tags        []string
	OperationID string
	Deprecated  bool

	// Parameters
	PathParams   []Parameter
	QueryParams  []Parameter
	HeaderParams []Parameter

	// Request/Response
	RequestBody  *RequestBody
	Responses    map[int]*Response
	DefaultError *Response

	// Security
	Security []SecurityRequirement

	// Metadata
	Metadata map[string]interface{}
}

Endpoint represents a REST API endpoint

func (*Endpoint) GetType

func (e *Endpoint) GetType() EndpointType

GetEndpointType returns the type of endpoint

type EndpointType

type EndpointType string

EndpointType represents the type of endpoint

const (
	EndpointTypeREST         EndpointType = "REST"
	EndpointTypeWebSocket    EndpointType = "WebSocket"
	EndpointTypeSSE          EndpointType = "SSE"
	EndpointTypeWebTransport EndpointType = "WebTransport"
)

type Example

type Example struct {
	Summary     string
	Description string
	Value       interface{}
}

Example represents an example value

type Features

type Features struct {
	// Reconnection enables automatic reconnection for streaming endpoints
	Reconnection bool

	// Heartbeat enables heartbeat/ping for maintaining connections
	Heartbeat bool

	// StateManagement enables connection state tracking
	StateManagement bool

	// TypedErrors generates typed error responses
	TypedErrors bool

	// RequestRetry enables automatic request retry with exponential backoff
	RequestRetry bool

	// Timeout enables request timeout configuration
	Timeout bool

	// Middleware enables request/response middleware/interceptors
	Middleware bool

	// Logging enables built-in logging support
	Logging bool
}

Features contains feature flags for client generation

type Generator

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

Generator orchestrates client code generation

func DefaultGenerator

func DefaultGenerator() *Generator

DefaultGenerator returns a generator with all built-in generators registered

func NewGenerator

func NewGenerator() *Generator

NewGenerator creates a new generator with registered language generators

func (*Generator) Generate

func (g *Generator) Generate(ctx context.Context, spec *APISpec, config GeneratorConfig) (*generators.GeneratedClient, error)

Generate generates a client for the specified language

func (*Generator) GenerateFromFile

func (g *Generator) GenerateFromFile(ctx context.Context, filePath string, config GeneratorConfig) (*generators.GeneratedClient, error)

GenerateFromFile generates a client from a spec file

func (*Generator) GenerateFromRouter

func (g *Generator) GenerateFromRouter(ctx context.Context, r interface{}, config GeneratorConfig) (*generators.GeneratedClient, error)

GenerateFromRouter generates a client by introspecting a router

func (*Generator) GetGeneratorInfo

func (g *Generator) GetGeneratorInfo(language string) (GeneratorInfo, error)

GetGeneratorInfo returns information about a specific generator

func (*Generator) ListGenerators

func (g *Generator) ListGenerators() []string

ListGenerators returns all registered generators

func (*Generator) Register

func (g *Generator) Register(gen generators.LanguageGenerator) error

Register registers a language generator

type GeneratorConfig

type GeneratorConfig struct {
	// Language specifies the target language (go, typescript, rust)
	Language string

	// OutputDir is the directory where generated files will be written
	OutputDir string

	// PackageName is the name of the generated package/module
	PackageName string

	// APIName is the name of the main client struct/class
	APIName string

	// BaseURL is the default base URL for the API
	BaseURL string

	// IncludeAuth determines if auth configuration should be generated
	IncludeAuth bool

	// IncludeStreaming determines if WebSocket/SSE clients should be generated
	IncludeStreaming bool

	// Features contains feature flags for generation
	Features Features

	// Module is the Go module path (for Go only)
	Module string

	// Version is the version of the generated client
	Version string
}

GeneratorConfig configures client generation

func DefaultConfig

func DefaultConfig() GeneratorConfig

DefaultConfig returns a default generator configuration

func NewConfig

func NewConfig(opts ...GeneratorOption) GeneratorConfig

NewConfig creates a new generator config with options

func (*GeneratorConfig) Validate

func (c *GeneratorConfig) Validate() error

Validate validates the configuration

type GeneratorInfo

type GeneratorInfo struct {
	Name              string
	SupportedFeatures []string
}

GeneratorInfo provides information about a language generator

type GeneratorOption

type GeneratorOption func(*GeneratorConfig)

GeneratorOptions provides functional options for generator config

func WithAPIName

func WithAPIName(name string) GeneratorOption

WithAPIName sets the API client name

func WithAuth

func WithAuth(enabled bool) GeneratorOption

WithAuth enables/disables auth generation

func WithBaseURL

func WithBaseURL(url string) GeneratorOption

WithBaseURL sets the base URL

func WithFeatures

func WithFeatures(features Features) GeneratorOption

WithFeatures sets the features

func WithLanguage

func WithLanguage(lang string) GeneratorOption

WithLanguage sets the target language

func WithModule

func WithModule(module string) GeneratorOption

WithModule sets the Go module path

func WithOutputDir

func WithOutputDir(dir string) GeneratorOption

WithOutputDir sets the output directory

func WithPackageName

func WithPackageName(name string) GeneratorOption

WithPackageName sets the package name

func WithStreaming

func WithStreaming(enabled bool) GeneratorOption

WithStreaming enables/disables streaming generation

func WithVersion

func WithVersion(version string) GeneratorOption

WithVersion sets the client version

type HeartbeatConfig

type HeartbeatConfig struct {
	Enabled  bool
	Interval time.Duration
	Timeout  time.Duration
}

HeartbeatConfig configures heartbeat/ping behavior

func DefaultHeartbeatConfig

func DefaultHeartbeatConfig() HeartbeatConfig

DefaultHeartbeatConfig returns a sensible default heartbeat config

type Introspector

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

Introspector extracts API specification from a Forge Router

func NewIntrospector

func NewIntrospector(r router.Router) *Introspector

NewIntrospector creates a new introspector for a router

func (*Introspector) Introspect

func (i *Introspector) Introspect(ctx context.Context) (*APISpec, error)

Introspect extracts the complete API specification from the router

type License

type License struct {
	Name string
	URL  string
}

License represents license information

type MediaType

type MediaType struct {
	Schema   *Schema
	Example  interface{}
	Examples map[string]*Example
}

MediaType represents a media type with schema

type OAuthFlow

type OAuthFlow struct {
	AuthorizationURL string
	TokenURL         string
	RefreshURL       string
	Scopes           map[string]string
}

OAuthFlow defines a single OAuth 2.0 flow

type OAuthFlows

type OAuthFlows struct {
	Implicit          *OAuthFlow
	Password          *OAuthFlow
	ClientCredentials *OAuthFlow
	AuthorizationCode *OAuthFlow
}

OAuthFlows defines OAuth 2.0 flows

type OutputManager

type OutputManager struct{}

OutputManager handles writing generated client files to disk

func NewOutputManager

func NewOutputManager() *OutputManager

NewOutputManager creates a new output manager

func (*OutputManager) GenerateREADME

func (m *OutputManager) GenerateREADME(config GeneratorConfig, spec *APISpec, authDocs string) string

GenerateREADME generates a README for the client

func (*OutputManager) WriteClient

func (m *OutputManager) WriteClient(client *generators.GeneratedClient, outputDir string) error

WriteClient writes the generated client to disk

type Parameter

type Parameter struct {
	Name        string
	In          string // "path", "query", "header"
	Description string
	Required    bool
	Deprecated  bool
	Schema      *Schema
	Example     interface{}
}

Parameter represents a request parameter

type ReconnectionConfig

type ReconnectionConfig struct {
	Strategy      ReconnectionStrategy
	InitialDelay  time.Duration
	MaxDelay      time.Duration
	MaxAttempts   int
	BackoffFactor float64 // For exponential strategy
	JitterEnabled bool    // Add random jitter to delays
}

ReconnectionConfig configures reconnection behavior

func DefaultReconnectionConfig

func DefaultReconnectionConfig() ReconnectionConfig

DefaultReconnectionConfig returns a sensible default reconnection config

type ReconnectionStrategy

type ReconnectionStrategy string

ReconnectionStrategy defines the strategy for reconnection

const (
	// ReconnectionStrategyExponential uses exponential backoff
	ReconnectionStrategyExponential ReconnectionStrategy = "exponential"

	// ReconnectionStrategyLinear uses linear backoff
	ReconnectionStrategyLinear ReconnectionStrategy = "linear"

	// ReconnectionStrategyFixed uses fixed delay
	ReconnectionStrategyFixed ReconnectionStrategy = "fixed"
)

type RequestBody

type RequestBody struct {
	Description string
	Required    bool
	Content     map[string]*MediaType // content-type -> media type
}

RequestBody represents a request body

type Response

type Response struct {
	Description string
	Content     map[string]*MediaType // content-type -> media type
	Headers     map[string]*Parameter
}

Response represents an API response

type SSEClientTemplate

type SSEClientTemplate struct {
	EndpointID      string
	Path            string
	EventSchemas    map[string]*Schema
	Features        StreamingFeatures
	ReconnectConfig ReconnectionConfig
}

SSEClientTemplate represents a template for SSE client generation

type SSEEndpoint

type SSEEndpoint struct {
	ID          string
	Path        string
	Summary     string
	Description string
	Tags        []string

	// Event schemas (event name -> schema)
	EventSchemas map[string]*Schema

	// Security
	Security []SecurityRequirement

	// Metadata
	Metadata map[string]interface{}
}

SSEEndpoint represents a Server-Sent Events endpoint

func (*SSEEndpoint) GetType

func (e *SSEEndpoint) GetType() EndpointType

GetEndpointType returns the type of endpoint

type Schema

type Schema struct {
	Type        string // "object", "array", "string", "number", "integer", "boolean", "null"
	Format      string // "date-time", "email", "uuid", etc.
	Description string
	Required    []string // For object types
	Properties  map[string]*Schema
	Items       *Schema       // For array types
	Enum        []interface{} // For enum types
	Default     interface{}
	Example     interface{}
	Nullable    bool
	ReadOnly    bool
	WriteOnly   bool
	MinLength   *int
	MaxLength   *int
	Minimum     *float64
	Maximum     *float64
	Pattern     string
	Ref         string // Reference to another schema (e.g., "#/components/schemas/User")

	// Polymorphism
	OneOf         []*Schema
	AnyOf         []*Schema
	AllOf         []*Schema
	Discriminator *Discriminator

	// Additional properties
	AdditionalProperties interface{} // bool or *Schema
}

Schema represents a data schema

type SecurityRequirement

type SecurityRequirement struct {
	SchemeName string
	Scopes     []string
}

SecurityRequirement represents a security requirement for an operation

type SecurityScheme

type SecurityScheme struct {
	Type             string // "apiKey", "http", "oauth2", "openIdConnect"
	Name             string // Scheme name
	Description      string
	In               string            // "query", "header", "cookie" (for apiKey)
	Scheme           string            // "bearer", "basic" (for http)
	BearerFormat     string            // "JWT" (for http bearer)
	Flows            *OAuthFlows       // For oauth2
	OpenIDConnectURL string            // For openIdConnect
	CustomHeaders    map[string]string // Custom headers
}

SecurityScheme represents an authentication/authorization scheme

type Server

type Server struct {
	URL         string
	Description string
	Variables   map[string]ServerVariable
}

Server represents an API server

type ServerVariable

type ServerVariable struct {
	Default     string
	Description string
	Enum        []string
}

ServerVariable represents a variable in server URL

type SpecParser

type SpecParser struct{}

SpecParser parses OpenAPI and AsyncAPI specification files

func NewSpecParser

func NewSpecParser() *SpecParser

NewSpecParser creates a new spec parser

func (*SpecParser) ParseFile

func (p *SpecParser) ParseFile(ctx context.Context, filePath string) (*APISpec, error)

ParseFile parses a specification file (OpenAPI or AsyncAPI)

type StreamSchema

type StreamSchema struct {
	SendSchema    *Schema // Client -> Server
	ReceiveSchema *Schema // Server -> Client
}

StreamSchema represents a streaming data schema

type StreamingCodeHelper

type StreamingCodeHelper struct{}

StreamingCodeHelper provides helper methods for generating streaming code

func NewStreamingCodeHelper

func NewStreamingCodeHelper() *StreamingCodeHelper

NewStreamingCodeHelper creates a new streaming code helper

func (*StreamingCodeHelper) GenerateHeartbeatDocs

func (h *StreamingCodeHelper) GenerateHeartbeatDocs() string

GenerateHeartbeatDocs generates documentation for heartbeat

func (*StreamingCodeHelper) GenerateReconnectionDocs

func (h *StreamingCodeHelper) GenerateReconnectionDocs() string

GenerateReconnectionDocs generates documentation for reconnection

func (*StreamingCodeHelper) GenerateStateManagementDocs

func (h *StreamingCodeHelper) GenerateStateManagementDocs() string

GenerateStateManagementDocs generates documentation for state management

type StreamingFeatures

type StreamingFeatures struct {
	Reconnection    bool
	Heartbeat       bool
	StateManagement bool
}

StreamingFeatures defines common streaming features and utilities

type Tag

type Tag struct {
	Name        string
	Description string
}

Tag represents an API tag for grouping

type ValidationError

type ValidationError struct {
	Type    string
	Path    string
	Message string
	Index   int
}

ValidationError represents a validation error

func (ValidationError) Error

func (e ValidationError) Error() string

Error implements error interface

type ValidationOptions

type ValidationOptions struct {
	RequireOperationIDs bool
	RequireDescriptions bool
	RequireExamples     bool
	RequireSecurity     bool
}

ValidationOptions for API spec validation

type WebSocketClientTemplate

type WebSocketClientTemplate struct {
	EndpointID      string
	Path            string
	SendSchema      *Schema
	ReceiveSchema   *Schema
	Features        StreamingFeatures
	ReconnectConfig ReconnectionConfig
	HeartbeatConfig HeartbeatConfig
}

WebSocketClientTemplate represents a template for WebSocket client generation

type WebSocketEndpoint

type WebSocketEndpoint struct {
	ID          string
	Path        string
	Summary     string
	Description string
	Tags        []string

	// Message schemas
	SendSchema    *Schema // Client -> Server
	ReceiveSchema *Schema // Server -> Client

	// Security
	Security []SecurityRequirement

	// Metadata
	Metadata map[string]interface{}
}

WebSocketEndpoint represents a WebSocket endpoint

func (*WebSocketEndpoint) GetType

func (e *WebSocketEndpoint) GetType() EndpointType

GetEndpointType returns the type of endpoint

type WebTransportEndpoint

type WebTransportEndpoint struct {
	ID          string
	Path        string
	Summary     string
	Description string
	Tags        []string

	// Stream schemas
	UniStreamSchema *StreamSchema // Unidirectional streams
	BiStreamSchema  *StreamSchema // Bidirectional streams
	DatagramSchema  *Schema       // Unreliable datagrams

	// Security
	Security []SecurityRequirement

	// Metadata
	Metadata map[string]interface{}
}

WebTransportEndpoint represents a WebTransport endpoint

func (*WebTransportEndpoint) GetType

func (e *WebTransportEndpoint) GetType() EndpointType

GetEndpointType returns the type of endpoint

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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