generate

package
v2.932.0 Latest Latest
Warning

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

Go to latest
Published: Aug 17, 2026 License: AGPL-3.0 Imports: 106 Imported by: 0

Documentation

Index

Constants

View Source
const MAX_CODE_SCORE = 999

Variables

View Source
var ErrMissingGenerationAccess = errors.New("generation access state is required; use generation-context/access.WithDirect or WithAuthenticated")
View Source
var ProgressMessages = map[ProgressStepID]string{
	ProgressStepSetup:             "Setup Environment",
	ProgressStepValidate:          "Load and Validate Document",
	ProgressStepGenSDK:            "Generate SDK",
	ProgressStepGenMockServer:     "Generate Mock Server",
	ProgressStepCleanup:           "Cleanup Orphaned Files",
	ProgressStepLockFile:          "Update Lock File",
	ProgressStepCompileSDK:        "Compile SDK",
	ProgressStepCompileTests:      "Compile Tests",
	ProgressStepLintSDK:           "Lint SDK",
	ProgressStepCompileUsage:      "Compile Usage Snippets",
	ProgressStepCompileMockServer: "Compile Mock Server",
	ProgressStepLintMockServer:    "Lint Mock Server",
	ProgressStepDone:              "Done",
	ProgressStepCancel:            "Cancelled",

	ProgressStepMergeStart:        "Custom Code",
	ProgressStepMergeSkipped:      "Custom Code (skipped)",
	ProgressStepMergeFetch:        "Fetching custom code history",
	ProgressStepMergeSnapshot:     "Creating generation snapshot",
	ProgressStepMerge:             "Merging custom edits",
	ProgressStepMergeStepSkipped:  "Merging custom edits (skipped)",
	ProgressStepMergePush:         "Pushing snapshot to remote",
	ProgressStepMergePushSkipped:  "Pushing snapshot to remote (skipped)",
	ProgressStepMergeApply:        "Applying merged files",
	ProgressStepMergeApplySkipped: "Applying merged files (skipped)",
}

Functions

func CheckLanguageSupported deprecated

func CheckLanguageSupported(lang string) bool

Deprecated: Use CheckTargetNameSupported or CheckSDKTargetNameSupported instead.

func CheckMCPTargetNameSupported

func CheckMCPTargetNameSupported(targetName string) bool

Returns true if the target name is a supported MCP target name. Target names for MCP always include a "mcp-" prefix, such as "mcp-typescript". Version-suffixed template names return false, such as a theoretical "mcp-typescriptv2".

func CheckSDKTargetNameSupported

func CheckSDKTargetNameSupported(targetName string) bool

Returns true if the target name is a supported SDK target name. Target names are equivalent to language names for SDKs and do not include any version-suffixed template names. For example, "typescript" will return true while "typescriptv2" will return false.

func CheckTargetNameSupported

func CheckTargetNameSupported(targetName string) bool

Returns true if the target name is a supported target name, including SDK, MCP, and terraform. Target names for SDKs are equivalent to language names and MCP always includes a "mcp-" prefix. Version-suffixed template names are not included, such as "typescriptv2" or a theoretical "mcp-typescriptv2".

func CompareCodePredicates

func CompareCodePredicates(i, j []string) int

func CompareMediaRanges

func CompareMediaRanges(i, j string) int

CompareMediaRanges is used to order a list of media ranges such that wildcards (`*/*`) are pushed to th end, preceded by ranges (e.g. `text/*`) and finally preceded by exact media types (e.g. `application/json`) which maintain their document order. This comparator is useful to apply on a list of subresponses so that response matching logic attempts the most specific media types first.

func GetConfigUsageFromType

func GetConfigUsageFromType(s any, parent string) map[string]any

func GetGenerationConfigFields

func GetGenerationConfigFields(newSDK bool) []config.SDKGenConfigField

Replacement for generate.GetCommonConfigFields

func GetLanguageConfigDefaults

func GetLanguageConfigDefaults(target string, newSDK bool) (*config.LanguageConfig, error)

func GetLanguageConfigFields

func GetLanguageConfigFields(target types.Target, newSDK bool) ([]config.SDKGenConfigField, error)

func GetSupportedLanguages deprecated

func GetSupportedLanguages() []string

Deprecated: Use GetSupportedTargetNames or GetSupportedSDKTargetNames instead.

func GetSupportedMCPTargetNames

func GetSupportedMCPTargetNames() []string

Returns all supported MCP target names. Target names for MCP always include a "mcp-" prefix, such as "mcp-typescript". Version-suffixed template names are not included, such as a theoretical "mcp-typescriptv2".

func GetSupportedMCPTargets

func GetSupportedMCPTargets() []types.Target

Returns all supported MCP targets.

func GetSupportedSDKTargetNames

func GetSupportedSDKTargetNames() []string

Returns all supported SDK target names. Target names for SDKs are equivalent language names and do not include any version-suffixed template names. For example, "typescript" will return true while "typescriptv2" will return false.

func GetSupportedSDKTargets

func GetSupportedSDKTargets() []types.Target

Returns all supported SDK targets.

func GetSupportedTargetNames

func GetSupportedTargetNames() []string

Returns all supported target names, including SDK, MCP, and terraform. Target names for SDKs are equivalent to language names and MCP always includes a "mcp-" prefix. Version-suffixed template names are not included, such as "typescripv2" or a theoretical "mcp-typescriptv2".

func GetSupportedTargets deprecated

func GetSupportedTargets() []types.Target

Deprecated: Use GetSupportedSDKTargets instead.

func GetSupportedTerraformTargetNames

func GetSupportedTerraformTargetNames() []string

Returns all supported Terraform target names. Version-suffixed template names are not included, such as a theoretical "terraformv2".

func GetSupportedTerraformTargets

func GetSupportedTerraformTargets() []types.Target

Returns all supported Terraform targets.

func GetTargetFromTargetString

func GetTargetFromTargetString(target string) (types.Target, error)

func GetTargetNameMaturity

func GetTargetNameMaturity(targetName string) string

Returns the target maturity level based on the target name. Returns an empty string if the target name is not found.

func IsBinaryContent

func IsBinaryContent(data []byte) bool

IsBinaryContent detects if content is binary by checking for null bytes (same as git)

Types

type Container

type Container interface {
	Endpoint(ctx context.Context, s string) (string, error)
	Terminate(ctx context.Context, opts ...testcontainers.TerminateOption) error
}

Container defines the interface needed by mockServerProcess Implementations are in the platform-specific files

type Generator

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

Generator is the central tool for handling all things related to SDK generation and contains all configuration and options for customizing and holding state of the process.

func New

func New(opts ...GeneratorOptions) (*Generator, error)

New constructs a new Generator with some default values and then applies all the given options and returns it.

It returns an no generator and an error if the given options are invalid. The following situations are considered an error:

* Either a WriteFileFunc must be provided or the validation only setting must be set

func TestResolveAST

func TestResolveAST(input TestResolveASTInput) (*Generator, *ast.AST, error)

TestResolveAST loads a spec, sets up the generator config, and returns the resulting AST. This is a test helper function that can be used across different test files.

func (*Generator) ExecuteInterTemplateFunction

func (g *Generator) ExecuteInterTemplateFunction(ctx context.Context, call easytemplate.CallContext, target types.Target, a *ast.AST, method string, args ...any) goja.Value

func (*Generator) ExecuteInterTemplateTarget

func (g *Generator) ExecuteInterTemplateTarget(ctx context.Context, target string, outDir string, a *ast.AST, cfg map[string]any, enabledFeatures map[string]bool) error

func (*Generator) Generate

func (g *Generator) Generate(ctx context.Context, schema []byte, schemaPath, target, outDir string, isRemote, compileOutput bool) []error

Generate generates the SDK. It takes the content of the schema file and the path to that file. This performs generation for the single language templates named and writes all files to the given output directory.

ctx must contain explicit generation access state from generation-context/access: use WithDirect for direct invocation or WithAuthenticated for authenticated invocation.

It returns a slice of errors that occurred during generation.

func (*Generator) GenerateAST

func (g *Generator) GenerateAST(ctx context.Context, docInfo *document.DocumentInfo, ad *analytics.Data) (*ast.AST, error)

func (*Generator) GenerateWithCancel

func (g *Generator) GenerateWithCancel(cancelCtx context.Context, schema []byte, schemaPath, target, outDir string, isRemote, compileOutput bool) (bool, []error)

Thin wrapper around Generate that checks if the context was cancelled.

func (*Generator) GetRenderedUsageSnippets

func (g *Generator) GetRenderedUsageSnippets() *RenderedUsageSnippets

GetRenderedUsageSnippets returns pre-rendered standalone usage snippets if WithRenderUsageSnippets was enabled and generation succeeded. Returns nil otherwise.

func (*Generator) GetSubsystem

func (g *Generator) GetSubsystem() *subsystem.Subsystem

GetSubsystem returns the generator's subsystem

func (*Generator) GetTarget

func (g *Generator) GetTarget(ctx context.Context, target, outDir string) (types.Target, error)

func (*Generator) GetTargetDefaultTemplateConfig

func (g *Generator) GetTargetDefaultTemplateConfig(ctx context.Context, target types.Target) (map[string]any, error)

func (*Generator) GetWarnings

func (g *Generator) GetWarnings() []error

func (*Generator) Init

func (g *Generator) Init(ctx context.Context, target, outDir string) error

func (*Generator) LoadAndValidateDoc

func (g *Generator) LoadAndValidateDoc(ctx context.Context, docInfo *document.DocumentInfo, ad *analytics.Data, workingDir string, validationOnly bool) (*validationResult, error)

func (*Generator) LoadConfig

func (g *Generator) LoadConfig(ctx context.Context, outDir string, targets ...string) (*config.Config, error)

LoadConfig loads the configuration, usually from a gen.yaml file, and returns it.

func (*Generator) MkdirAll

func (g *Generator) MkdirAll(path string, perm os.FileMode) error

func (*Generator) Open

func (g *Generator) Open(name string) (fs.File, error)

func (*Generator) OpenFile

func (g *Generator) OpenFile(name string, flag int, perm fs.FileMode) (filesystem.File, error)

func (*Generator) ReadDir

func (g *Generator) ReadDir(name string) ([]fs.DirEntry, error)

func (*Generator) ReadFile

func (g *Generator) ReadFile(name string) ([]byte, error)

func (*Generator) Remove

func (g *Generator) Remove(name string) error

func (*Generator) RunTargetTesting

func (g *Generator) RunTargetTesting(ctx context.Context, target string, outDir string) error

Runs target testing only. This assumes that the target has been previously generated into the outDir.

func (*Generator) ScanForGeneratedIDs

func (g *Generator) ScanForGeneratedIDs() (map[string]string, error)

func (*Generator) Stat

func (g *Generator) Stat(name string) (fs.FileInfo, error)

func (*Generator) Validate

func (g *Generator) Validate(ctx context.Context, schema []byte, schemaPath string, isRemote bool, workingDir string) (*validation.Result, error)

Validate and ValidateWithOpts validates the schema. It takes the content of the schema file and the path to that file. It performs validation for the languages found in the default configuration. ctx must contain explicit generation access state from generation-context/access; use WithDirect or WithAuthenticated.

It returns a slice of validation errors that are found in the schema. Validate method was kept to support backward compatibility with snapshot testing.

func (*Generator) ValidateWithOpts

func (g *Generator) ValidateWithOpts(ctx context.Context, opts ValidateOpts) (*validation.Result, error)

func (*Generator) WriteFile

func (g *Generator) WriteFile(name string, data []byte, perm fs.FileMode) error

type GeneratorOptions

type GeneratorOptions func(g *Generator)

func WithAnalytics

func WithAnalytics(client posthog.Client) GeneratorOptions

func WithCLIVersion

func WithCLIVersion(version string) GeneratorOptions

func WithChangelogReleaseNotes

func WithChangelogReleaseNotes(releaseNotes string) GeneratorOptions

func WithCompileEnv

func WithCompileEnv(env map[string]string) GeneratorOptions

WithCompileEnv sets extra environment variables on compile and lint child processes. This is useful for isolating per-invocation tool state (e.g. GEM_HOME, BUNDLE_PATH) when multiple generations run in parallel.

func WithCustomerID

func WithCustomerID(id string) GeneratorOptions

func WithDebuggingEnabled

func WithDebuggingEnabled() GeneratorOptions

func WithDisableMockServer

func WithDisableMockServer() GeneratorOptions

func WithDontWrite

func WithDontWrite() GeneratorOptions

func WithFileSystem

func WithFileSystem(fs filesystem.FileSystem) GeneratorOptions

func WithForceGeneration

func WithForceGeneration() GeneratorOptions

func WithGenVersion

func WithGenVersion(version string) GeneratorOptions

func WithGit

func WithGit(git merge.Git) GeneratorOptions

WithGit injects the Git interface for all Git operations (blobbing, tree creation, commits). This is required for the 3-way merge / persistentEdits feature.

func WithInstallationURL

func WithInstallationURL(installationURL string) GeneratorOptions

func WithLogger

func WithLogger(log logging.Logger) GeneratorOptions

func WithOutputTestGroup

func WithOutputTestGroup(testGroup string) GeneratorOptions

func WithOutputTests

func WithOutputTests() GeneratorOptions

func WithOutputUsageGroup

func WithOutputUsageGroup(usageGroup string) GeneratorOptions

func WithParseValidOperations

func WithParseValidOperations() GeneratorOptions

func WithProgressUpdates

func WithProgressUpdates(targetID string, onProgressUpdate func(ProgressUpdate), updateGenSteps, updateFileStatus bool) GeneratorOptions

func WithPublished

func WithPublished(published bool) GeneratorOptions

func WithRenderUsageSnippets

func WithRenderUsageSnippets() GeneratorOptions

func WithRepoDetails

func WithRepoDetails(repoURL, subDirectory string) GeneratorOptions

func WithRunLocation

func WithRunLocation(location string) GeneratorOptions

func WithSkipVersioning

func WithSkipVersioning(skipVersioning bool) GeneratorOptions

func WithSplitModelThreshold

func WithSplitModelThreshold(threshold, chunkSize int) GeneratorOptions

WithSplitModelThreshold overrides the default large-model splitting thresholds. Models with more than `threshold` types are split into chunks of `chunkSize`. This is useful in tests to exercise splitting logic without needing hundreds of types.

func WithStandaloneReadme

func WithStandaloneReadme(filename string, headersOnly bool) GeneratorOptions

func WithTracer

func WithTracer(tracer trace.Tracer) GeneratorOptions

func WithUsageSnippetArgsByNamespace

func WithUsageSnippetArgsByNamespace(namespace string) GeneratorOptions

func WithUsageSnippetArgsByOperationID

func WithUsageSnippetArgsByOperationID(operationIDs string) GeneratorOptions

WithUsageSnippetArgsByOperationID is used to generate usage snippets for a specific operation ID or list of operation IDs We keep the string parameter to maintain backwards compatibility in the CLI

func WithUsageSnippetArgsByRootExample

func WithUsageSnippetArgsByRootExample() GeneratorOptions

func WithUsageSnippetArgsGenerateAll

func WithUsageSnippetArgsGenerateAll() GeneratorOptions

func WithUsageSnippetExampleParams

func WithUsageSnippetExampleParams(paramNameToExampleValue map[string]string) GeneratorOptions

func WithUsageSnippetExampleRequestBody

func WithUsageSnippetExampleRequestBody(requestBodyJSON string) GeneratorOptions

func WithValidationRuleset

func WithValidationRuleset(ruleset string) GeneratorOptions

func WithVerboseOutput

func WithVerboseOutput(verbose bool) GeneratorOptions

func WithWarningLoggerDisabled

func WithWarningLoggerDisabled() GeneratorOptions

func WithWatchTemplatesLocation

func WithWatchTemplatesLocation(location string) GeneratorOptions

func WithWorkspaceID

func WithWorkspaceID(id string) GeneratorOptions

func WithWorkspaceUri

func WithWorkspaceUri(uri string) GeneratorOptions

type GlobalContext

type GlobalContext struct {
	Config                  map[string]any
	AST                     *ast.AST
	EnabledTemplateFeatures map[string]bool
}

type Progress

type Progress struct {
	TargetID         string               // identifier for the target being processed
	StepID           ProgressStepID       // ID of the current step
	OnProgressUpdate func(ProgressUpdate) // callback for progress updates
	UpdateGenSteps   bool                 // whether to send updates before each generation step
	UpdateFileStatus bool                 // whether to send file status updates
}

type ProgressFile

type ProgressFile struct {
	Path         string
	Status       ProgressFileStatus
	Content      *bytes.Buffer
	IsMainReadme bool
}

type ProgressFileStatus

type ProgressFileStatus string
const (
	ProgressFileStatusCreated   ProgressFileStatus = "created"
	ProgressFileStatusUnchanged ProgressFileStatus = "unchanged"
	ProgressFileStatusDeleted   ProgressFileStatus = "deleted"
	ProgressFileStatusModified  ProgressFileStatus = "modified"
)

type ProgressStep

type ProgressStep struct {
	ID      ProgressStepID
	Message string
}

type ProgressStepID

type ProgressStepID string
const (
	ProgressStepSetup             ProgressStepID = "setup"
	ProgressStepValidate          ProgressStepID = "validate"
	ProgressStepGenSDK            ProgressStepID = "genSDK"
	ProgressStepGenMockServer     ProgressStepID = "genMockServer"
	ProgressStepCleanup           ProgressStepID = "cleanup"
	ProgressStepLockFile          ProgressStepID = "lockFile"
	ProgressStepCompileSDK        ProgressStepID = "compileSDK"
	ProgressStepCompileTests      ProgressStepID = "compileTests"
	ProgressStepLintSDK           ProgressStepID = "lintSDK"
	ProgressStepCompileUsage      ProgressStepID = "compileUsage"
	ProgressStepCompileMockServer ProgressStepID = "compileMockServer"
	ProgressStepLintMockServer    ProgressStepID = "lintMockServer"
	ProgressStepDone              ProgressStepID = "done"
	ProgressStepCancel            ProgressStepID = "cancel"

	// Custom code / persistent edits merge steps
	ProgressStepMergeStart        ProgressStepID = "mergeStart"
	ProgressStepMergeSkipped      ProgressStepID = "mergeSkipped"
	ProgressStepMergeFetch        ProgressStepID = "mergeFetch"
	ProgressStepMergeSnapshot     ProgressStepID = "mergeSnapshot"
	ProgressStepMerge             ProgressStepID = "merge"
	ProgressStepMergeStepSkipped  ProgressStepID = "mergeStepSkipped"
	ProgressStepMergePush         ProgressStepID = "mergePush"
	ProgressStepMergePushSkipped  ProgressStepID = "mergePushSkipped"
	ProgressStepMergeApply        ProgressStepID = "mergeApply"
	ProgressStepMergeApplySkipped ProgressStepID = "mergeApplySkipped"
)

type ProgressUpdate

type ProgressUpdate struct {
	TargetID string
	Step     *ProgressStep
	File     *ProgressFile
	Merge    *patches.MergeProgress // Custom code merge events (conflicts, push warnings)
}

type RenderedUsageSnippets

type RenderedUsageSnippets struct {
	RawOutput string // Concatenated snippet files in the "// Usage snippet provided for ..." format
}

RenderedUsageSnippets holds pre-rendered standalone usage snippets produced as a side effect of main SDK generation, avoiding a separate AST resolution pass.

type SyncMap

type SyncMap[K comparable, V any] struct {
	// contains filtered or unexported fields
}

SyncMap is a generic type-safe wrapper around sync.Map.

func (*SyncMap[K, V]) Delete

func (s *SyncMap[K, V]) Delete(key K)

Delete removes the value for a key.

func (*SyncMap[K, V]) Load

func (s *SyncMap[K, V]) Load(key K) (V, bool)

Load returns the value stored in the map for a key, or the zero value if no value is present.

func (*SyncMap[K, V]) Range

func (s *SyncMap[K, V]) Range(f func(key K, value V) bool)

Range calls f sequentially for each key and value present in the map.

func (*SyncMap[K, V]) Store

func (s *SyncMap[K, V]) Store(key K, value V)

Store sets the value for a key.

type TestResolveASTInput

type TestResolveASTInput struct {
	OpenAPIContents  []byte
	OpenAPIPath      string
	Target           string
	AdditionalConfig *map[string]any
}

type UsageDirs

type UsageDirs struct {
	AbsoluteOutputDir string // Absolute path of the testproject output directory
	RelativeOutputDir string // Path of the testproject relative to the SDK outDir
	RelativeSourceDir string // Path of the SDK outDir relative to the testproject
}

type ValidateOpts

type ValidateOpts struct {
	Schema     []byte
	SchemaPath string
	IsRemote   bool
	WorkingDir string
	Target     string
}

Directories

Path Synopsis
snapshots

Jump to

Keyboard shortcuts

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