client

package
v0.8.6 Latest Latest
Warning

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

Go to latest
Published: Jan 3, 2026 License: Apache-2.0 Imports: 15 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

	// Streaming extension features
	Streaming *StreamingSpec
}

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) HasChannels added in v0.8.0

func (spec *APISpec) HasChannels() bool

HasChannels returns true if pub/sub channels are enabled.

func (*APISpec) HasHistory added in v0.8.0

func (spec *APISpec) HasHistory() bool

HasHistory returns true if message history is enabled.

func (*APISpec) HasPresence added in v0.8.0

func (spec *APISpec) HasPresence() bool

HasPresence returns true if presence tracking is enabled.

func (*APISpec) HasRooms added in v0.8.0

func (spec *APISpec) HasRooms() bool

HasRooms returns true if room support is enabled.

func (*APISpec) HasStreamingFeatures added in v0.8.0

func (spec *APISpec) HasStreamingFeatures() bool

HasStreamingFeatures returns true if any streaming features are enabled.

func (*APISpec) HasTyping added in v0.8.0

func (spec *APISpec) HasTyping() bool

HasTyping returns true if typing indicators are enabled.

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

	// Streaming features
	HasRooms    bool
	HasPresence bool
	HasTyping   bool
	HasChannels bool
	HasHistory  bool
}

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 ChannelClientConfig added in v0.8.0

type ChannelClientConfig struct {
	// MaxChannelsPerUser is the default max channels a user can subscribe to
	MaxChannelsPerUser int

	// SupportPatterns enables wildcard/pattern subscriptions
	SupportPatterns bool
}

ChannelClientConfig configures channel client generation.

type ChannelFeatureConfig added in v0.8.0

type ChannelFeatureConfig struct {
	// Maximum channels a user can subscribe to
	MaxChannelsPerUser int

	// Whether to support channel patterns/wildcards
	SupportPatterns bool
}

ChannelFeatureConfig configures pub/sub channels for a WebSocket endpoint.

type ChannelOperations added in v0.8.0

type ChannelOperations struct {
	// Path for the channel WebSocket endpoint
	Path string

	// Parameters for the path (e.g., channelId)
	Parameters []Parameter

	// Subscribe schema
	SubscribeSchema *Schema

	// Unsubscribe schema
	UnsubscribeSchema *Schema

	// Publish schema
	PublishSchema *Schema

	// Message received schema
	MessageSchema *Schema
}

ChannelOperations defines pub/sub channel schemas and operations.

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]any
}

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       any
}

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 any, 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

	// Streaming contains streaming-specific configuration
	Streaming StreamingConfig

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

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

	// Enhanced features
	UseFetch        bool // Use fetch instead of axios (TypeScript)
	DualPackage     bool // Generate ESM + CJS (TypeScript)
	GenerateTests   bool // Generate test setup
	GenerateLinting bool // Generate linting setup
	GenerateCI      bool // Generate CI config
	ErrorTaxonomy   bool // Generate typed error classes
	Interceptors    bool // Generate interceptor support
	Pagination      bool // Generate pagination helpers

	// Output control
	ClientOnly bool // Generate only client source files (no package.json, tsconfig, etc.)
}

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) HasAnyStreamingFeature added in v0.8.0

func (c *GeneratorConfig) HasAnyStreamingFeature() bool

HasAnyStreamingFeature returns true if any streaming feature is enabled.

func (*GeneratorConfig) ShouldGenerateChannelClient added in v0.8.0

func (c *GeneratorConfig) ShouldGenerateChannelClient() bool

ShouldGenerateChannelClient returns true if channel client should be generated.

func (*GeneratorConfig) ShouldGeneratePresenceClient added in v0.8.0

func (c *GeneratorConfig) ShouldGeneratePresenceClient() bool

ShouldGeneratePresenceClient returns true if presence client should be generated.

func (*GeneratorConfig) ShouldGenerateRoomClient added in v0.8.0

func (c *GeneratorConfig) ShouldGenerateRoomClient() bool

ShouldGenerateRoomClient returns true if room client should be generated.

func (*GeneratorConfig) ShouldGenerateTypingClient added in v0.8.0

func (c *GeneratorConfig) ShouldGenerateTypingClient() bool

ShouldGenerateTypingClient returns true if typing client should be generated.

func (*GeneratorConfig) ShouldGenerateUnifiedStreamingClient added in v0.8.0

func (c *GeneratorConfig) ShouldGenerateUnifiedStreamingClient() bool

ShouldGenerateUnifiedStreamingClient returns true if unified streaming client should be generated.

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 WithAllStreamingFeatures added in v0.8.0

func WithAllStreamingFeatures() GeneratorOption

WithAllStreamingFeatures enables all streaming features.

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 WithChannels added in v0.8.0

func WithChannels(enabled bool) GeneratorOption

WithChannels enables/disables channel client generation.

func WithClientOnly added in v0.8.0

func WithClientOnly(enabled bool) GeneratorOption

WithClientOnly enables generating only client source files without package config.

func WithFeatures

func WithFeatures(features Features) GeneratorOption

WithFeatures sets the features.

func WithHistory added in v0.8.0

func WithHistory(enabled bool) GeneratorOption

WithHistory enables/disables message history support.

func WithLanguage

func WithLanguage(lang string) GeneratorOption

WithLanguage sets the target language.

func WithModularClients added in v0.8.0

func WithModularClients(enabled bool) GeneratorOption

WithModularClients enables/disables modular streaming client generation.

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 WithPresence added in v0.8.0

func WithPresence(enabled bool) GeneratorOption

WithPresence enables/disables presence client generation.

func WithRooms added in v0.8.0

func WithRooms(enabled bool) GeneratorOption

WithRooms enables/disables room client generation.

func WithStreaming

func WithStreaming(enabled bool) GeneratorOption

WithStreaming enables/disables streaming generation.

func WithStreamingConfig added in v0.8.0

func WithStreamingConfig(streaming StreamingConfig) GeneratorOption

WithStreamingConfig sets the streaming configuration.

func WithTyping added in v0.8.0

func WithTyping(enabled bool) GeneratorOption

WithTyping enables/disables typing indicator client generation.

func WithUnifiedClient added in v0.8.0

func WithUnifiedClient(enabled bool) GeneratorOption

WithUnifiedClient enables/disables unified streaming client 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  any
	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     any
}

Parameter represents a request parameter.

type PresenceClientConfig added in v0.8.0

type PresenceClientConfig struct {
	// Statuses are the available presence statuses
	Statuses []string

	// HeartbeatIntervalMs is the default heartbeat interval
	HeartbeatIntervalMs int

	// IdleTimeoutMs is the default idle timeout before auto-away
	IdleTimeoutMs int

	// IncludeCustomStatus enables custom status message support
	IncludeCustomStatus bool
}

PresenceClientConfig configures presence client generation.

type PresenceFeatureConfig added in v0.8.0

type PresenceFeatureConfig struct {
	// Heartbeat interval in milliseconds
	HeartbeatIntervalMs int

	// Idle timeout before marking as away (in milliseconds)
	IdleTimeoutMs int
}

PresenceFeatureConfig configures presence tracking for a WebSocket endpoint.

type PresenceOperations added in v0.8.0

type PresenceOperations struct {
	// Path for the presence WebSocket endpoint
	Path string

	// Status update schema (client -> server)
	UpdateSchema *Schema

	// Presence event schema (server -> client)
	EventSchema *Schema

	// Available statuses
	Statuses []string // e.g., ["online", "away", "busy", "offline"]
}

PresenceOperations defines presence tracking schemas and operations.

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 RoomClientConfig added in v0.8.0

type RoomClientConfig struct {
	// MaxRoomsPerUser is the default max rooms a user can join (for docs/validation)
	MaxRoomsPerUser int

	// IncludeMemberEvents generates handlers for member join/leave events
	IncludeMemberEvents bool

	// IncludeRoomMetadata generates room metadata support
	IncludeRoomMetadata bool
}

RoomClientConfig configures room client generation.

type RoomFeatureConfig added in v0.8.0

type RoomFeatureConfig struct {
	// Maximum rooms a user can join
	MaxRoomsPerUser int

	// Maximum members per room
	MaxMembersPerRoom int

	// Whether to broadcast member events
	BroadcastMemberEvents bool
}

RoomFeatureConfig configures room-related features for a WebSocket endpoint.

type RoomOperations added in v0.8.0

type RoomOperations struct {
	// Path for the room WebSocket endpoint
	Path string

	// Parameters for the path (e.g., roomId)
	Parameters []Parameter

	// Message schemas
	JoinSchema    *Schema // Client request to join room
	LeaveSchema   *Schema // Client request to leave room
	SendSchema    *Schema // Client message to room
	ReceiveSchema *Schema // Server message from room

	// Member event schemas
	MemberJoinSchema  *Schema // Member joined notification
	MemberLeaveSchema *Schema // Member left notification

	// History configuration
	HistoryEnabled bool
	HistorySchema  *Schema // History query/response schema
}

RoomOperations defines room-related message schemas and operations.

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]any
}

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        []any   // For enum types
	Default     any
	Example     any
	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 any // 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 StreamingConfig added in v0.8.0

type StreamingConfig struct {
	// EnableRooms generates room management client (join/leave/broadcast)
	EnableRooms bool

	// EnableChannels generates pub/sub channel client
	EnableChannels bool

	// EnablePresence generates presence tracking client
	EnablePresence bool

	// EnableTyping generates typing indicator client
	EnableTyping bool

	// EnableHistory generates message history support
	EnableHistory bool

	// RoomConfig contains room-specific configuration
	RoomConfig RoomClientConfig

	// PresenceConfig contains presence-specific configuration
	PresenceConfig PresenceClientConfig

	// TypingConfig contains typing indicator configuration
	TypingConfig TypingClientConfig

	// ChannelConfig contains channel-specific configuration
	ChannelConfig ChannelClientConfig

	// GenerateUnifiedClient generates a unified StreamingClient that composes all features
	GenerateUnifiedClient bool

	// GenerateModularClients generates separate clients for each feature
	GenerateModularClients bool
}

StreamingConfig configures streaming client generation features.

func DefaultStreamingConfig added in v0.8.0

func DefaultStreamingConfig() StreamingConfig

DefaultStreamingConfig returns sensible defaults for streaming configuration.

type StreamingFeatures

type StreamingFeatures struct {
	Reconnection    bool
	Heartbeat       bool
	StateManagement bool
}

StreamingFeatures defines common streaming features and utilities.

type StreamingSpec added in v0.8.0

type StreamingSpec struct {
	// Feature flags indicating what's available
	EnableRooms    bool
	EnableChannels bool
	EnablePresence bool
	EnableTyping   bool
	EnableHistory  bool

	// Room operations and schemas
	Rooms *RoomOperations

	// Presence tracking
	Presence *PresenceOperations

	// Typing indicators
	Typing *TypingOperations

	// Pub/sub channels
	Channels *ChannelOperations
}

StreamingSpec represents streaming extension features extracted from AsyncAPI.

type Tag

type Tag struct {
	Name        string
	Description string
}

Tag represents an API tag for grouping.

type TypingClientConfig added in v0.8.0

type TypingClientConfig struct {
	// TimeoutMs is the auto-stop timeout in milliseconds
	TimeoutMs int

	// DebounceMs is the debounce interval for typing events
	DebounceMs int
}

TypingClientConfig configures typing indicator client generation.

type TypingFeatureConfig added in v0.8.0

type TypingFeatureConfig struct {
	// Auto-stop timeout in milliseconds
	TimeoutMs int

	// Debounce interval in milliseconds
	DebounceMs int
}

TypingFeatureConfig configures typing indicators for a WebSocket endpoint.

type TypingOperations added in v0.8.0

type TypingOperations struct {
	// Path for the typing WebSocket endpoint
	Path string

	// Parameters for the path (e.g., roomId)
	Parameters []Parameter

	// Typing start schema
	StartSchema *Schema

	// Typing stop schema
	StopSchema *Schema

	// Timeout duration for auto-stop (in milliseconds)
	TimeoutMs int
}

TypingOperations defines typing indicator schemas and operations.

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

	// Path parameters (e.g., roomId, channelId)
	Parameters []Parameter

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

	// Additional message types for multiplexed connections
	MessageTypes map[string]*Schema // message type -> schema

	// Security
	Security []SecurityRequirement

	// Metadata
	Metadata map[string]any

	// Streaming extension features (if this endpoint supports them)
	StreamingFeatures *WebSocketStreamingFeatures
}

WebSocketEndpoint represents a WebSocket endpoint.

func (*WebSocketEndpoint) GetType

func (e *WebSocketEndpoint) GetType() EndpointType

GetEndpointType returns the type of endpoint.

type WebSocketStreamingFeatures added in v0.8.0

type WebSocketStreamingFeatures struct {
	// Feature flags
	SupportsRooms    bool
	SupportsPresence bool
	SupportsTyping   bool
	SupportsChannels bool
	SupportsHistory  bool

	// Feature-specific configurations
	RoomConfig     *RoomFeatureConfig
	PresenceConfig *PresenceFeatureConfig
	TypingConfig   *TypingFeatureConfig
	ChannelConfig  *ChannelFeatureConfig
}

WebSocketStreamingFeatures indicates which streaming features this endpoint supports.

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]any
}

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