tygorgen

package
v0.8.3 Latest Latest
Warning

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

Go to latest
Published: Dec 5, 2025 License: MIT Imports: 12 Imported by: 0

README

tygorgen

Go to TypeScript code generator. Generates TypeScript types and Zod schemas from Go structs.

Features

  • Zod schema generation from Go validate tags
  • Nullable vs optional correctly distinguished (*T vs omitempty)
  • Enum support from Go const groups with iota
  • Doc comments preserved in TypeScript output
  • Custom type mappings for time.Time, uuid.UUID, etc.

Usage

With tygor app
tygorgen.FromApp(app).
	WithFlavor(tygorgen.FlavorZod).
	ToDir("./client/src/rpc")
Standalone type generation

Generate TypeScript from Go types without the full RPC framework:

tygorgen.FromTypes(
	User{},
	CreateUserRequest{},
	ListUsersResponse{},
).ToDir("./client/src/types")
With Zod schemas
tygorgen.FromTypes(User{}).
	WithFlavor(tygorgen.FlavorZod).
	ToDir("./client/src/types")

Example

Go input:

type User struct {
	ID        int64     `json:"id"`
	Name      string    `json:"name" validate:"required,min=2"`
	Email     string    `json:"email" validate:"required,email"`
	Avatar    *string   `json:"avatar"` // nullable
	CreatedAt time.Time `json:"created_at"`
}

TypeScript output:

export interface User {
  id: number;
  name: string;
  email: string;
  avatar: string | null;
  created_at: string;
}

Zod output:

export const UserSchema = z.object({
  id: z.number().int(),
  name: z.string().min(1).min(2),
  email: z.string().min(1).email(),
  avatar: z.nullable(z.string()),
  created_at: z.string().datetime(),
});

Configuration

tygorgen.FromApp(app).
	WithFlavor(tygorgen.FlavorZod).     // Generate Zod schemas
	WithFlavor(tygorgen.FlavorZodMini). // Or use zod/mini for smaller bundles
	SingleFile().                       // All types in one file
	EnumStyle("enum").                  // "union" | "enum" | "const"
	OptionalType("null").               // "undefined" | "null"
	TypeMapping("time.Time", "Date").   // Custom type mappings
	PreserveComments("types").          // "default" | "types" | "none"
	ToDir("./client/src/rpc")

Providers

Two extraction strategies are available:

Provider Speed Enums Comments Use case
source (default) Slower Yes Yes Production builds
reflection Fast No No Development iteration
tygorgen.FromTypes(User{}).
	Provider("reflection"). // Fast mode
	ToDir("./client/src/types")

See also

Other Go to TypeScript generators:

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	// OutDir is the directory where generated files will be written.
	// e.g. "./client/src/rpc"
	OutDir string

	// Provider selects the type extraction strategy.
	// "source" (default) - uses go/packages for full type info including enums and comments
	// "reflection" - uses runtime reflection (faster, but no enum values or comments)
	Provider string

	// Packages are additional Go package paths to analyze when using source provider.
	// By default, packages are inferred from the types registered in routes.
	// Use this to include additional packages not directly referenced in endpoints.
	// e.g. []string{"github.com/myorg/myapp/shared"}
	Packages []string

	// TypeMappings allows overriding type mappings for tygo.
	// e.g. map[string]string{"time.Time": "Date", "CustomType": "string"}
	TypeMappings map[string]string

	// PreserveComments controls whether Go doc comments are preserved in TypeScript output.
	// Supported values: "default" (preserve package and type comments), "types" (only type comments), "none".
	// Default: "default"
	PreserveComments string

	// EnumStyle controls how Go const groups are generated in TypeScript.
	// Supported values: "union" (type unions), "enum" (TS enums), "const" (individual consts).
	// Default: "union"
	EnumStyle string

	// OptionalType controls how optional fields (Go pointers) are typed in TypeScript.
	// Supported values: "undefined" (T | undefined), "null" (T | null).
	// Default: "undefined"
	OptionalType string

	// Frontmatter is content added to the top of each generated TypeScript file.
	// Useful for custom type definitions or imports.
	// e.g. "export type DateTime = string & { __brand: 'DateTime' };"
	Frontmatter string

	// StripPackagePrefix removes this prefix from package paths when qualifying type names.
	// Use this when you have same-named types in different packages (e.g., v1.User and v2.User).
	// Example: "github.com/myorg/myrepo/" makes "github.com/myorg/myrepo/api/v1.User" → "v1_User"
	// Without this, types from different packages with the same name will collide.
	StripPackagePrefix string

	// SingleFile emits all types in a single types.ts file.
	// Default (false) generates one file per Go package with a barrel types.ts that re-exports all.
	SingleFile bool

	// Flavors lists which additional output flavors to generate.
	// Each enabled flavor produces its own output file alongside or instead of types.ts.
	// Use FlavorZod, FlavorZodMini constants or the ConfigBuilder.WithFlavor() method.
	// Example: []Flavor{FlavorZod} generates schemas.zod.ts with Zod schemas
	Flavors []Flavor

	// EmitTypes controls whether base types.ts is generated.
	// Default (nil/true): generate types.ts. Set to false to only emit flavor outputs.
	// When false with Zod flavor, types are exported via z.infer<typeof Schema>.
	EmitTypes *bool

	// EmitDiscovery controls whether discovery.json is generated.
	// When true, outputs a JSON file containing the full IR schema for runtime introspection.
	// This enables API browsers and tooling to introspect services and types.
	EmitDiscovery bool
}

Config holds the configuration for code generation.

type Flavor

type Flavor string

Flavor represents a code generation output flavor. Flavors produce alternative TypeScript outputs like Zod schemas.

const (
	// FlavorZod generates Zod schemas for runtime validation.
	// Output: schemas.zod.ts with z.object() schemas matching Go validate tags.
	FlavorZod Flavor = "zod"

	// FlavorZodMini generates Zod schemas using zod/mini for smaller bundle size.
	// Output: schemas.zod-mini.ts with z.object() schemas.
	FlavorZodMini Flavor = "zod-mini"
)

func (Flavor) String

func (f Flavor) String() string

String returns the flavor name.

type GenerateResult

type GenerateResult struct {
	// Files contains generated file contents when OutDir is empty.
	// When OutDir is set, files are written to disk and this is nil.
	Files []GeneratedFile

	// Warnings contains non-fatal issues encountered during generation.
	Warnings []Warning

	// Schema is the validated IR schema (available for inspection/check mode).
	Schema *ir.Schema
}

GenerateResult contains the output from code generation.

func Generate

func Generate(app *tygor.App, cfg *Config) (*GenerateResult, error)

Generate generates the TypeScript types and manifest for the registered services. If OutDir is set, files are written to disk. Otherwise, files are returned in the result.

func GenerateTypes

func GenerateTypes(types []any, cfg *Config) (*GenerateResult, error)

GenerateTypes generates TypeScript types from Go types without a tygor app. This is the standalone equivalent of Generate() for use with FromTypes(). No manifest is generated since there are no RPC endpoints.

type GeneratedFile

type GeneratedFile struct {
	Path    string
	Content []byte
}

GeneratedFile represents a generated output file.

type Generator

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

Generator provides a fluent API for code generation. Create with FromApp() or FromTypes() and configure with method chaining.

Example:

tygorgen.FromApp(app).
    WithFlavor(tygorgen.FlavorZod).
    ToDir("./client/src/rpc")

func FromApp

func FromApp(app *tygor.App) *Generator

FromApp creates a new Generator for the given app. This is the entry point for the fluent API.

func FromTypes

func FromTypes(types ...any) *Generator

FromTypes creates a Generator for standalone type generation without a tygor app. Pass zero values of the types you want to generate TypeScript for.

Example:

tygorgen.FromTypes(
    User{},
    CreateUserRequest{},
    ListUsersResponse{},
).ToDir("./client/src/types")

By default, this uses the source provider for full enum and comment support. Use .Provider("reflection") for faster generation without source analysis.

func (*Generator) EnumStyle

func (g *Generator) EnumStyle(style string) *Generator

EnumStyle controls how Go const groups are generated. Valid values: "union" (default), "enum", "const".

func (*Generator) Frontmatter

func (g *Generator) Frontmatter(content string) *Generator

Frontmatter adds content to the top of generated TypeScript files.

func (*Generator) Generate

func (g *Generator) Generate() (*GenerateResult, error)

Generate returns generated files in memory without writing to disk. Use ToDir() to write files to disk instead.

func (*Generator) OptionalType

func (g *Generator) OptionalType(t string) *Generator

OptionalType controls how optional fields are typed. Valid values: "undefined" (default), "null".

func (*Generator) Packages

func (g *Generator) Packages(pkgs ...string) *Generator

Packages adds additional Go packages to analyze.

func (*Generator) PreserveComments

func (g *Generator) PreserveComments(mode string) *Generator

PreserveComments controls whether Go doc comments are preserved. Valid values: "default", "types", "none".

func (*Generator) Provider

func (g *Generator) Provider(p string) *Generator

Provider sets the type extraction strategy. Valid values: "source" (default), "reflection".

func (*Generator) SingleFile

func (g *Generator) SingleFile() *Generator

SingleFile emits all types in a single types.ts file.

func (*Generator) StripPackagePrefix

func (g *Generator) StripPackagePrefix(prefix string) *Generator

StripPackagePrefix sets the prefix to remove from package paths.

func (*Generator) ToDir

func (g *Generator) ToDir(dir string) (*GenerateResult, error)

ToDir generates files to the specified directory. This is a terminal operation that writes files to disk.

func (*Generator) TypeMapping

func (g *Generator) TypeMapping(goType, tsType string) *Generator

TypeMapping adds a Go type to TypeScript type mapping.

func (*Generator) WithDiscovery

func (g *Generator) WithDiscovery() *Generator

WithDiscovery enables discovery.json output. The discovery document contains the full API schema for runtime introspection.

func (*Generator) WithFlavor

func (g *Generator) WithFlavor(f Flavor) *Generator

WithFlavor adds a flavor to the generation output. Can be called multiple times to add multiple flavors.

func (*Generator) WithoutTypes

func (g *Generator) WithoutTypes() *Generator

WithoutTypes disables base types.ts generation. When disabled with Zod flavor, types are exported via z.infer<typeof Schema>.

type Warning

type Warning struct {
	Code    string
	Message string
}

Warning represents a non-fatal issue encountered during generation.

Directories

Path Synopsis
Package ir defines the Intermediate Representation for Go type descriptors.
Package ir defines the Intermediate Representation for Go type descriptors.
Package provider implements input providers for extracting type information from Go code.
Package provider implements input providers for extracting type information from Go code.
Package sink provides output destinations for generated code.
Package sink provides output destinations for generated code.
Package typescript generates TypeScript type definitions from IR schemas.
Package typescript generates TypeScript type definitions from IR schemas.
flavor
Package flavor provides the interface and utilities for TypeScript output flavors.
Package flavor provides the interface and utilities for TypeScript output flavors.

Jump to

Keyboard shortcuts

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