Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ jobs:
with:
go-version-file: go.mod
cache: false
- uses: dart-lang/setup-dart@v1
with:
sdk: '3.13.4'
- name: Restore Go modules, compiler, and linter caches
id: go-cache
uses: actions/cache@v6
Expand Down
29 changes: 28 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ surface of a general-purpose OpenAPI generator.
| `types` | `go` | Go models |
| `client` | `go` | Go models and HTTP client |
| `client` | `typescript` | TypeScript types and HTTP client |
| `types` | `typescript` | TypeScript types |
| `types` | `rust` | Serde models in `mod.rs` |
| `client` | `rust` | Serde models and a Reqwest client in `mod.rs` |
| `types` | `dart` | Dart JSON models in `models.dart` |
Expand Down Expand Up @@ -43,12 +44,31 @@ Every invocation requires:

- `--openapi`: input OpenAPI YAML or JSON document;
- `--mode`: `types` or `client`;
- `--lang`: `go`, `typescript`, `rust`, or `dart`, subject to the supported pairs above;
- `--lang`: `go`, `typescript`, `rust`, or `dart`;
- `--out`: generated output directory.

JSON input is supported alongside YAML. The document syntax is accepted
directly, so `.json` and `.yaml` file names work with the same command.

Generated JSON models default to HTTP compatibility: extra object fields do not
break decoding when a server adds response data. For configuration, add `--strict`
to reject unknown fields in objects declared with `additionalProperties: false`,
including nested objects, array items and tagged union payloads. Explicitly open
objects remain open. The flag applies to every language in both generation modes;
it is independent of emitting HTTP operations. It controls unknown-field handling,
not full JSON Schema validation.

```sh
oasmith --openapi public.yaml --mode client --lang rust --out src/api
oasmith --openapi config.yaml --mode types --lang rust --strict --out src/config
```

Strict Go models enforce this through `UnmarshalJSON`; Rust uses Serde; Dart
uses `fromJson`. Strict TypeScript output exports `decode<Type>(value)` for
configuration and validates ordinary JSON responses in generated HTTP operations.
TypeScript interfaces alone cannot validate parsed JSON; use the generated decoder
when loading configuration.

TypeScript output is written directly from the embedded templates without
external tools.

Expand Down Expand Up @@ -224,6 +244,13 @@ Use `--mode client --lang rust --out src/api`, then `mod api;`. Add `serde` 1
(with `json`) to Cargo dependencies.
Choose the Reqwest TLS features appropriate to your application.

Rust JSON models ignore unknown object fields by default, including nested
objects and tagged union payloads. This lets an older HTTP client read responses
after an API adds fields. Required fields, field types, enum values and
discriminator values still have to match the generated contract.

For configuration, add `--strict` as described above.

Construct `api::Client::new(http, base_url, bearer_token)` with your configured
`reqwest_middleware::ClientWithMiddleware`. For a client without middleware,
construct it with `reqwest_middleware::ClientBuilder::new(http).build()`.
Expand Down
23 changes: 12 additions & 11 deletions internal/cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ type Options struct {
Mode string
Lang string
Out string
Strict bool
}

// Run parses args, loads the OpenAPI document, and emits requested outputs.
Expand All @@ -32,17 +33,17 @@ func Run(args []string) error {
}
switch {
case opts.Lang == "dart":
return dartemit.Emit(doc, dartemit.Options{OutDir: opts.Out}, opts.Mode == "client")
return dartemit.Emit(doc, dartemit.Options{OutDir: opts.Out, Strict: opts.Strict}, opts.Mode == "client")
case opts.Lang == "rust":
return rustemit.Emit(doc, rustemit.Options{OutDir: opts.Out}, opts.Mode == "client")
return rustemit.Emit(doc, rustemit.Options{OutDir: opts.Out, StrictJSON: opts.Strict}, opts.Mode == "client")
case opts.Mode == "types" && opts.Lang == "go":
return goemit.Emit(doc, goemit.Options{OutDir: opts.Out, SourcePath: opts.OpenAPI})
return goemit.Emit(doc, goemit.Options{OutDir: opts.Out, SourcePath: opts.OpenAPI, Strict: opts.Strict})
case opts.Mode == "client" && opts.Lang == "go":
return goemit.EmitClient(doc, goemit.Options{OutDir: opts.Out, SourcePath: opts.OpenAPI})
case opts.Mode == "client" && opts.Lang == "typescript":
return tsemit.Emit(doc, tsemit.Options{OutDir: opts.Out})
return goemit.EmitClient(doc, goemit.Options{OutDir: opts.Out, SourcePath: opts.OpenAPI, Strict: opts.Strict})
case opts.Lang == "typescript":
return tsemit.Emit(doc, tsemit.Options{OutDir: opts.Out, Strict: opts.Strict, TypesOnly: opts.Mode == "types"})
default:
return fmt.Errorf("unsupported --mode/--lang pair %q/%q; valid pairs are types/go, client/go, client/typescript, types/rust, client/rust, types/dart, and client/dart", opts.Mode, opts.Lang)
return fmt.Errorf("unsupported --mode/--lang pair %q/%q; valid modes are types and client; valid languages are go, typescript, rust, and dart", opts.Mode, opts.Lang)
}
}

Expand All @@ -54,16 +55,16 @@ func Parse(args []string) (Options, error) {
fs.StringVar(&opts.Mode, "mode", "", "generation mode")
fs.StringVar(&opts.Lang, "lang", "", "output language")
fs.StringVar(&opts.Out, "out", "", "output directory")
fs.BoolVar(&opts.Strict, "strict", false, "reject unknown JSON object fields where additionalProperties is false (for configuration)")
if err := fs.Parse(args); err != nil {
return Options{}, fmt.Errorf("usage: oasmith --openapi <openapidoc> --mode <types|client> --lang <go|typescript|rust|dart> --out <dir>")
}
if opts.OpenAPI == "" || opts.Mode == "" || opts.Lang == "" || opts.Out == "" {
return Options{}, fmt.Errorf("usage: oasmith --openapi <openapidoc> --mode <types|client> --lang <go|typescript|rust|dart> --out <dir>")
}
if ((opts.Mode == "types" || opts.Mode == "client") && (opts.Lang == "rust" || opts.Lang == "dart")) ||
(opts.Mode == "types" && opts.Lang == "go") ||
(opts.Mode == "client" && (opts.Lang == "go" || opts.Lang == "typescript")) {
if (opts.Mode == "types" || opts.Mode == "client") &&
(opts.Lang == "rust" || opts.Lang == "dart" || opts.Lang == "go" || opts.Lang == "typescript") {
return opts, nil
}
return Options{}, fmt.Errorf("unsupported --mode/--lang pair %q/%q; valid pairs are types/go, client/go, client/typescript, types/rust, client/rust, types/dart, and client/dart", opts.Mode, opts.Lang)
return Options{}, fmt.Errorf("unsupported --mode/--lang pair %q/%q; valid modes are types and client; valid languages are go, typescript, rust, and dart", opts.Mode, opts.Lang)
}
4 changes: 2 additions & 2 deletions internal/cli/cli_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,14 @@ func TestParseRejectsInvalidModeLangPair(t *testing.T) {

_, err := cli.Parse([]string{
"--openapi", "doc.yaml",
"--mode", "types",
"--mode", "invalid",
"--lang", "typescript",
"--out", "out",
})
if err == nil {
t.Fatal("Parse invalid mode/lang succeeded")
}
if !strings.Contains(err.Error(), "valid pairs are types/go, client/go, client/typescript, types/rust, client/rust, types/dart, and client/dart") {
if !strings.Contains(err.Error(), "valid modes are types and client; valid languages are go, typescript, rust, and dart") {
t.Fatalf("Parse error = %q, want valid pair message", err.Error())
}
}
Expand Down
8 changes: 6 additions & 2 deletions internal/dartemit/dartemit.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,23 @@ import (
)

// Options configures Dart output emission.
type Options struct{ OutDir string }
type Options struct {
OutDir string
Strict bool
}

type emitter struct {
doc *openapi.Document
names map[*openapi.Schema]string
definitions map[string]*openapi.Schema
implemented map[string][]string
strict bool
err error
}

// Emit writes Dart models and, in client mode, operation methods for doc.
func Emit(doc *openapi.Document, opts Options, client bool) error {
e := &emitter{doc: doc, names: map[*openapi.Schema]string{}, definitions: map[string]*openapi.Schema{}, implemented: map[string][]string{}}
e := &emitter{doc: doc, names: map[*openapi.Schema]string{}, definitions: map[string]*openapi.Schema{}, implemented: map[string][]string{}, strict: opts.Strict}
for _, name := range doc.SchemaNames() {
if name == "string" || name == "String" {
continue
Expand Down
2 changes: 1 addition & 1 deletion internal/dartemit/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ func (e *emitter) writeObject(out *strings.Builder, name string, schema *openapi
}
out.WriteString("});\n")
fmt.Fprintf(out, " factory %s.fromJson(Object? raw) {\n final map = expectPublicMap(raw);\n", name)
if strict, ok := schema.AdditionalProperties.(bool); ok && !strict {
if allowed, ok := schema.AdditionalProperties.(bool); e.strict && ok && !allowed {
out.WriteString(" for (final key in map.keys) {\n if (!const <String>{")
for _, key := range keys {
fmt.Fprintf(out, "%s,", quote(key))
Expand Down
28 changes: 21 additions & 7 deletions internal/goemit/goemit.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,10 @@ import (
type Options struct {
OutDir string
SourcePath string
Strict bool
}

type emitter struct{}
type emitter struct{ strict bool }

//go:embed templates/*.gotmpl
var templateFS embed.FS
Expand All @@ -31,7 +32,7 @@ func Emit(doc *openapi.Document, opts Options) error {
if err := os.MkdirAll(opts.OutDir, 0o755); err != nil {
return fmt.Errorf("create go output directory %q: %w", opts.OutDir, err)
}
raw, err := executeTemplate("models.go", goModelsTemplateData(doc, opts.SourcePath))
raw, err := executeTemplate("models.go", goModelsTemplateData(doc, opts))
if err != nil {
return err
}
Expand Down Expand Up @@ -128,6 +129,7 @@ type goEnumValueData struct {
type goObjectData struct {
TypeName string
Fields []goFieldData
Strict bool
}

type goFieldData struct {
Expand Down Expand Up @@ -155,11 +157,11 @@ type goOneOfMappingData struct {
FieldName string
}

func goModelsTemplateData(doc *openapi.Document, sourcePath string) goModelsData {
e := emitter{}
func goModelsTemplateData(doc *openapi.Document, opts Options) goModelsData {
e := emitter{strict: opts.Strict}
data := goModelsData{
PackageName: packageName(doc, sourcePath),
Imports: goImports(doc),
PackageName: packageName(doc, opts.SourcePath),
Imports: goImports(doc, opts.Strict),
NeedsDurationHelpers: needsDurationHelpers(doc),
}
for _, name := range doc.SchemaNames() {
Expand Down Expand Up @@ -225,6 +227,9 @@ func (e *emitter) objectTemplateData(name string, schema *openapi.Schema) *goObj
data := goObjectData{
TypeName: typeName,
}
if allowed, ok := schema.AdditionalProperties.(bool); e.strict && ok && !allowed {
data.Strict = true
}
for _, propName := range keys {
prop := schema.Properties[propName]
goType := e.goType(prop)
Expand Down Expand Up @@ -330,8 +335,17 @@ func needsJSONHelpers(doc *openapi.Document) bool {
return false
}

func goImports(doc *openapi.Document) []string {
func goImports(doc *openapi.Document, strict bool) []string {
imports := map[string]bool{}
if strict {
for _, schema := range doc.Components.Schemas {
if allowed, ok := schema.AdditionalProperties.(bool); schema.IsObject() && ok && !allowed {
imports["bytes"] = true
imports["encoding/json"] = true
imports["fmt"] = true
}
}
}
if needsJSONHelpers(doc) {
imports["encoding/json"] = true
imports["fmt"] = true
Expand Down
14 changes: 13 additions & 1 deletion internal/goemit/templates/models.go.gotmpl
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,19 @@ const (
{{define "object"}}type {{.TypeName}} struct {
{{range .Fields}} {{.Name}} {{.Type}} `json:"{{.JSONName}}{{.JSONOmit}}"`
{{end}}}
{{end}}
{{if .Strict}}
func (dst *{{.TypeName}}) UnmarshalJSON(data []byte) error {
type wire {{.TypeName}}
var decoded wire
decoder := json.NewDecoder(bytes.NewReader(data))
decoder.DisallowUnknownFields()
if err := decoder.Decode(&decoded); err != nil {
return fmt.Errorf("decode {{.TypeName}}: %w", err)
}
*dst = {{.TypeName}}(decoded)
return nil
}
{{end}}{{end}}

{{define "one_of"}}// {{.TypeName}} is generated from an OpenAPI oneOf schema.
{{range .Refs}}// oneOf variant: {{.TypeName}}
Expand Down
12 changes: 8 additions & 4 deletions internal/rustemit/rustemit.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,22 @@ import (
)

// Options configures Rust source emission.
type Options struct{ OutDir string }
type Options struct {
OutDir string
StrictJSON bool
}

type emitter struct {
schemas map[string]*openapi.Schema
definitions map[string]string
serdeModels bool
strictJSON bool
err error
}

// Emit writes Rust serde models, optionally including a reqwest client.
func Emit(doc *openapi.Document, opts Options, client bool) error {
e := &emitter{schemas: doc.Components.Schemas, definitions: map[string]string{}}
e := &emitter{schemas: doc.Components.Schemas, definitions: map[string]string{}, strictJSON: opts.StrictJSON}
for _, name := range doc.SchemaNames() {
e.define(typeName(name), doc.Components.Schemas[name])
}
Expand Down Expand Up @@ -235,7 +239,7 @@ func (e *emitter) taggedUnion(out *strings.Builder, name string, schema *openapi
variants = append(variants, variant{value, variantName, resolved})
}
}
strict := true
strict := e.strictJSON
for _, item := range variants {
allowed, ok := item.schema.AdditionalProperties.(bool)
strict = strict && ok && !allowed
Expand Down Expand Up @@ -313,7 +317,7 @@ func (e *emitter) fields(out *strings.Builder, name string, schema *openapi.Sche
func (e *emitter) object(out *strings.Builder, name string, schema *openapi.Schema) {
e.serdeModels = true
out.WriteString("#[derive(Clone, Debug, Serialize, Deserialize)]\n")
if allowed, ok := schema.AdditionalProperties.(bool); ok && !allowed {
if allowed, ok := schema.AdditionalProperties.(bool); e.strictJSON && ok && !allowed {
out.WriteString("#[serde(deny_unknown_fields)]\n")
}
out.WriteString("pub struct " + name + " {\n")
Expand Down
86 changes: 86 additions & 0 deletions internal/tsemit/strict.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package tsemit

import (
"encoding/json"
"fmt"

"github.com/responsibleapi/oasmith/internal/openapi"
)

func jsonShape(schema *openapi.Schema) map[string]any {
shape := map[string]any{}
if schema == nil {
return shape
}
if schema.Ref != "" {
shape["ref"] = openapi.RefName(schema.Ref)
return shape
}
if len(schema.Type) > 0 {
shape["type"] = schema.Type
}
if schema.Const != nil {
shape["const"] = schema.Const
}
if len(schema.Enum) > 0 {
shape["enum"] = schema.Enum
}
if schema.AdditionalProperties != nil {
shape["additionalProperties"] = schema.AdditionalProperties
}
if len(schema.Properties) > 0 {
properties := map[string]any{}
for key, property := range schema.Properties {
properties[key] = jsonShape(property)
}
shape["properties"] = properties
}
if len(schema.Required) > 0 {
shape["required"] = schema.Required
}
if schema.Items != nil {
shape["items"] = jsonShape(schema.Items)
}
if len(schema.OneOf) > 0 {
variants := []any{}
for _, variant := range schema.OneOf {
variants = append(variants, jsonShape(variant))
}
shape["oneOf"] = variants
}
if schema.Discriminator != nil {
mapping := map[string]string{}
for tag, ref := range schema.Discriminator.Mapping {
mapping[tag] = openapi.RefName(ref)
}
shape["discriminator"] = map[string]any{"propertyName": schema.Discriminator.PropertyName, "mapping": mapping}
}
return shape
}

func jsonSchemaSource(schema *openapi.Schema) (string, error) {
raw, err := json.Marshal(jsonShape(schema))
if err != nil {
return "", fmt.Errorf("encode TypeScript JSON schema: %w", err)
}
return string(raw), nil
}

func strictJSONSource(doc *openapi.Document) (string, error) {
schemas := map[string]any{}
for _, name := range doc.SchemaNames() {
schema := doc.Components.Schemas[name]
if payload := doc.SSEPayloadSchema(name); payload != nil {
schema = payload
}
schemas[name] = jsonShape(schema)
}
raw, err := json.Marshal(schemas)
if err != nil {
return "", fmt.Errorf("encode TypeScript JSON schemas: %w", err)
}
return executeTemplate("strict-json.ts", struct {
SchemasJSON string
Models []modelData
}{string(raw), modelsTemplateData(doc).Schemas})
}
Loading