-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathschema_merge.go
More file actions
1087 lines (961 loc) · 35.1 KB
/
Copy pathschema_merge.go
File metadata and controls
1087 lines (961 loc) · 35.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2025 DoorDash, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
package codegen
import (
"fmt"
"reflect"
"slices"
"strings"
"github.com/pb33f/libopenapi/datamodel/high/base"
"github.com/pb33f/libopenapi/orderedmap"
"go.yaml.in/yaml/v4"
)
func createFromCombinator(schema *base.Schema, options ParseOptions) (GoSchema, error) {
if schema == nil {
return GoSchema{}, nil
}
path := options.path
hasAllOf := len(schema.AllOf) > 0
hasAnyOf := len(schema.AnyOf) > 0
hasOneOf := len(schema.OneOf) > 0
hasIfThenElse := schema.Then != nil || schema.Else != nil
if !hasAllOf && !hasAnyOf && !hasOneOf && !hasIfThenElse {
return GoSchema{}, nil
}
// If the schema has an explicit primitive type alongside oneOf/anyOf,
// the primitive type takes precedence. This is common in specs where
// oneOf/anyOf is used to constrain values (e.g., enum refs) rather than
// define a true union. Example:
// type: integer
// oneOf:
// - $ref: '#/components/schemas/ZeroOneEnum'
// - $ref: '#/components/schemas/NullEnum'
// In this case, the field should be an integer, not a union struct.
// TODO: Extract validation constraints (e.g., enum values) from oneOf/anyOf
// elements and merge them into the primitive type's validation tags.
if hasPrimitiveType(schema.Type) && !hasAllOf {
return GoSchema{}, nil
}
// If the schema has type: array alongside allOf/anyOf/oneOf, skip combinator processing.
// This is a malformed spec pattern where the combinator should be inside items, not at
// the same level as type: array. We let the array processing in schema_oapi.go handle
// this case by treating the combinator as defining the array items type.
if slices.Contains(schema.Type, "array") {
return GoSchema{}, nil
}
var (
out GoSchema
allOfSchema GoSchema
anyOfSchema GoSchema
oneOfSchema GoSchema
additionalTypes []TypeDefinition
)
if hasAllOf {
// When the schema has its own properties alongside allOf, the allOf must
// be fully resolved (not collapsed to a type alias) so its properties can
// be merged with the sibling properties in enhanceSchema.
hasSiblingProperties := schema.Properties != nil && schema.Properties.Len() > 0
var err error
allOfSchema, err = mergeAllOfSchemas(schema.AllOf, options, hasSiblingProperties)
if err != nil {
return GoSchema{}, fmt.Errorf("error merging allOf: %w", err)
}
// If the allOf resulted in a simple type (no properties), return it directly
// This handles cases like allOf with a description-only schema and a $ref.
// Exception: when the parent schema declares its own object type, the
// outer type wins over a conflicting primitive from allOf (a malformed
// spec pattern: `type: object, nullable: true, allOf: [SomeEnum]`).
// Falling through lets createObjectSchema produce an object the
// validator accepts; the allOf becomes metadata-only.
if len(allOfSchema.Properties) == 0 && !hasAnyOf && !hasOneOf {
if !parentTypeConflictsWithAllOf(schema, allOfSchema) {
return allOfSchema, nil
}
}
out.Properties = append(out.Properties, allOfSchema.Properties...)
additionalTypes = append(additionalTypes, allOfSchema.AdditionalTypes...)
}
if hasAnyOf {
anyOfPath := append(path, "anyOf")
var err error
anyOfSchema, err = generateUnion(schema.AnyOf, nil, options.WithPath(anyOfPath))
if err != nil {
return GoSchema{}, fmt.Errorf("error resolving anyOf: %w", err)
}
// If generateUnion returned a simple type (not a union), return it directly
// This happens when there's only 1 element, or when filtering null leaves 1 element
if len(anyOfSchema.UnionElements) == 0 && !hasAllOf && !hasOneOf {
return anyOfSchema, nil
}
anyOfFields := genFieldsFromProperties(anyOfSchema.Properties, options)
anyOfSchema.GoType = anyOfSchema.createGoStruct(anyOfFields)
anyOfSchema.IsUnionWrapper = len(anyOfSchema.UnionElements) > 0
anyOfName := pathToTypeName(anyOfPath)
td := TypeDefinition{
Name: anyOfName,
Schema: anyOfSchema,
SpecLocation: SpecLocationUnion,
JsonName: "-",
NeedsMarshaler: needsMarshaler(anyOfSchema),
HasSensitiveData: hasSensitiveData(anyOfSchema),
}
additionalTypes = append(additionalTypes, td)
options.typeTracker.register(td, "")
out.Properties = append(out.Properties, Property{
GoName: anyOfName,
Schema: GoSchema{RefType: anyOfName},
Constraints: Constraints{Nullable: ptr(true)},
})
}
if hasOneOf {
oneOfPath := append(path, "oneOf")
var err error
oneOfSchema, err = generateUnion(schema.OneOf, schema.Discriminator, options.WithPath(oneOfPath))
if err != nil {
return GoSchema{}, fmt.Errorf("error resolving oneOf: %w", err)
}
// If generateUnion returned a simple type (not a union), return it directly
// This happens when there's only 1 element, or when filtering null leaves 1 element
if len(oneOfSchema.UnionElements) == 0 && !hasAllOf && !hasAnyOf {
return oneOfSchema, nil
}
oneOfFields := genFieldsFromProperties(oneOfSchema.Properties, options)
oneOfSchema.GoType = oneOfSchema.createGoStruct(oneOfFields)
oneOfSchema.IsUnionWrapper = len(oneOfSchema.UnionElements) > 0
oneOfName := pathToTypeName(oneOfPath)
td := TypeDefinition{
Name: oneOfName,
Schema: oneOfSchema,
SpecLocation: SpecLocationUnion,
JsonName: "-",
NeedsMarshaler: needsMarshaler(oneOfSchema),
HasSensitiveData: hasSensitiveData(oneOfSchema),
}
additionalTypes = append(additionalTypes, td)
options.typeTracker.register(td, "")
out.Properties = append(out.Properties, Property{
GoName: oneOfName,
Schema: GoSchema{RefType: oneOfName},
Constraints: Constraints{Nullable: ptr(true)},
})
}
if hasIfThenElse {
// The if schema is a validation concern and does not contribute
// structural properties. We process then/else as union variants
// with named path segments so the generated types are called
// _Then/_Else instead of opaque _0/_1.
type branchDef struct {
name string
proxy *base.SchemaProxy
}
var branchList []branchDef
if schema.Then != nil {
branchList = append(branchList, branchDef{"then", schema.Then})
}
if schema.Else != nil {
branchList = append(branchList, branchDef{"else", schema.Else})
}
// Single branch (only then or only else): flat merge into parent
// via single-element generateUnion optimization.
if len(branchList) == 1 {
branch := branchList[0]
branchPath := append(path, branch.name)
branchSchema, err := generateUnion(
[]*base.SchemaProxy{branch.proxy}, nil, options.WithPath(branchPath),
)
if err != nil {
return GoSchema{}, fmt.Errorf("error resolving if/%s: %w", branch.name, err)
}
if !hasAllOf && !hasAnyOf && !hasOneOf {
return branchSchema, nil
}
out.Properties = append(out.Properties, branchSchema.Properties...)
additionalTypes = append(additionalTypes, branchSchema.AdditionalTypes...)
} else {
// Both branches: resolve each independently with its own named
// path, then assemble a union wrapper. This gives types like
// Resource_Then and Resource_Else instead of _0 and _1.
var ifThenElseSchema GoSchema
for _, branch := range branchList {
branchPath := append(path, branch.name)
ref := branch.proxy.GoLow().GetReference()
resolved, err := GenerateGoSchema(branch.proxy, options.WithReference(ref).WithPath(branchPath))
if err != nil {
return GoSchema{}, fmt.Errorf("error resolving if/%s: %w", branch.name, err)
}
typeName := resolved.GoType
// For non-primitive inline types, register a named type definition
if ref == "" && !isPrimitiveType(typeName) {
elementName := pathToTypeName(branchPath)
td := TypeDefinition{
Schema: resolved,
Name: elementName,
SpecLocation: SpecLocationUnion,
JsonName: "-",
NeedsMarshaler: needsMarshaler(resolved),
}
options.typeTracker.register(td, "")
ifThenElseSchema.AdditionalTypes = append(ifThenElseSchema.AdditionalTypes, td)
ifThenElseSchema.AdditionalTypes = append(ifThenElseSchema.AdditionalTypes, resolved.AdditionalTypes...)
typeName = elementName
} else if ref != "" && !isPrimitiveType(typeName) {
ifThenElseSchema.AdditionalTypes = append(ifThenElseSchema.AdditionalTypes, resolved.AdditionalTypes...)
}
if typeName != "struct{}" {
ifThenElseSchema.UnionElements = append(ifThenElseSchema.UnionElements, UnionElement{
TypeName: typeName,
Schema: resolved,
})
}
}
ifThenElseSchema.IsConditional = true
ifThenElseFields := genFieldsFromProperties(ifThenElseSchema.Properties, options)
ifThenElseSchema.GoType = ifThenElseSchema.createGoStruct(ifThenElseFields)
ifThenElseSchema.IsUnionWrapper = len(ifThenElseSchema.UnionElements) > 0
ifThenElsePath := append(path, "ifThenElse")
ifThenElseName := pathToTypeName(ifThenElsePath)
td := TypeDefinition{
Name: ifThenElseName,
Schema: ifThenElseSchema,
SpecLocation: SpecLocationUnion,
JsonName: "-",
NeedsMarshaler: needsMarshaler(ifThenElseSchema),
HasSensitiveData: hasSensitiveData(ifThenElseSchema),
}
additionalTypes = append(additionalTypes, td)
additionalTypes = append(additionalTypes, ifThenElseSchema.AdditionalTypes...)
options.typeTracker.register(td, "")
out.Properties = append(out.Properties, Property{
GoName: ifThenElseName,
Schema: GoSchema{RefType: ifThenElseName},
Constraints: Constraints{Nullable: ptr(true)},
})
}
}
fields := genFieldsFromProperties(out.Properties, options)
out.GoType = out.createGoStruct(fields)
out.AdditionalTypes = append(out.AdditionalTypes, additionalTypes...)
return out, nil
}
// isMetadataOnlySchema checks if a schema contains only metadata fields
// (description, title, examples, etc.) and no actual type/property definitions
func isMetadataOnlySchema(schema *base.Schema) bool {
if schema == nil {
return true
}
// If it has any of these, it's not metadata-only
if len(schema.Type) > 0 {
return false
}
if schema.Properties != nil && schema.Properties.Len() > 0 {
return false
}
if schema.Items != nil {
return false
}
if schema.AdditionalProperties != nil {
return false
}
if len(schema.AllOf) > 0 || len(schema.AnyOf) > 0 || len(schema.OneOf) > 0 {
return false
}
if schema.Not != nil {
return false
}
if schema.Then != nil || schema.Else != nil {
return false
}
// It only has metadata fields like description, title, examples, etc.
return true
}
// parentTypeConflictsWithAllOf reports whether the parent schema declares
// `type: object` while the merged allOf result resolves to a non-object
// primitive (e.g. an integer enum). In that case the allOf must not be
// returned as the schema's effective type — the outer object wins. Only
// the object/primitive direction is checked here; primitive-vs-primitive
// mismatches are rejected by mergeOpenapiSchemas already.
func parentTypeConflictsWithAllOf(parent *base.Schema, allOfSchema GoSchema) bool {
if parent == nil || !slices.Contains(parent.Type, "object") {
return false
}
if allOfSchema.GoType == "" {
return false
}
if strings.HasPrefix(allOfSchema.GoType, "map[") || strings.HasPrefix(allOfSchema.GoType, "[]") {
return false
}
if isPrimitiveType(allOfSchema.GoType) || len(allOfSchema.EnumValues) > 0 {
return true
}
if allOfSchema.OpenAPISchema != nil {
for _, t := range allOfSchema.OpenAPISchema.Type {
if t != "object" && t != "null" {
return true
}
}
}
return false
}
// mergeAllOfSchemas merges all allOf elements into a single GoSchema.
// When hasSiblingProperties is true, the parent schema has its own properties
// alongside allOf, so the single-ref alias optimization is skipped to ensure
// the ref's properties are resolved and can be merged with the siblings.
func mergeAllOfSchemas(allOf []*base.SchemaProxy, options ParseOptions, hasSiblingProperties bool) (GoSchema, error) {
if len(allOf) == 0 {
return GoSchema{}, nil
}
path := options.path
// Derive the current type's reference from the path (e.g., ["VendorDetails"] -> "#/components/schemas/VendorDetails")
var currentTypeRef string
if len(path) == 1 {
currentTypeRef = "#/components/schemas/" + path[0]
}
// Filter out discriminated unions that include the current type to avoid circular references.
// This handles patterns like:
// CounterParty:
// discriminator: { propertyName: type, mapping: { VENDOR: VendorDetails } }
// oneOf: [VendorDetails, BookTransferDetails]
// VendorDetails:
// allOf: [CounterParty, ...] # <- circular reference
// In this case, we should NOT embed CounterParty because it would create
// an infinite loop during JSON unmarshaling.
filteredAllOf := allOf
if currentTypeRef != "" {
filteredAllOf = make([]*base.SchemaProxy, 0, len(allOf))
for _, schemaProxy := range allOf {
if isDiscriminatedUnionWithChild(schemaProxy.Schema(), currentTypeRef) {
// Skip this parent type - it's a discriminated union that includes us
continue
}
filteredAllOf = append(filteredAllOf, schemaProxy)
}
}
// If all elements were filtered out, return empty schema
if len(filteredAllOf) == 0 {
return GoSchema{}, nil
}
// First, resolve all elements to determine if they result in unions.
// A single-element oneOf/anyOf flattens to just that element, so we need
// to check the resolved result, not the raw schema.
type resolvedElement struct {
schemaProxy *base.SchemaProxy
resolved GoSchema
subPath []string
isUnion bool
}
resolvedElements := make([]resolvedElement, 0, len(filteredAllOf))
for i, schemaProxy := range filteredAllOf {
subPath := append(path, fmt.Sprintf("allOf_%d", i))
resolved, err := GenerateGoSchema(schemaProxy, options.WithPath(subPath))
if err != nil {
return GoSchema{}, fmt.Errorf("error resolving allOf[%d]: %w", i, err)
}
resolvedElements = append(resolvedElements, resolvedElement{
schemaProxy: schemaProxy,
resolved: resolved,
subPath: subPath,
isUnion: isResolvedUnion(resolved),
})
}
// Check if all resolved elements are mergeable (no unions)
allMergeable := true
for _, elem := range resolvedElements {
if elem.isUnion {
allMergeable = false
break
}
}
if allMergeable {
// Check if allOf contains only a single $ref with metadata (description, title, etc.)
// If so, use the reference directly to avoid infinite recursion
var refSchema *base.SchemaProxy
var refCount int
var metadataOnlyCount int
for _, schemaProxy := range filteredAllOf {
s := schemaProxy.Schema()
ref := schemaProxy.GetReference()
if ref != "" {
refSchema = schemaProxy
refCount++
} else if isMetadataOnlySchema(s) {
metadataOnlyCount++
}
}
// If we have exactly one $ref and the rest are metadata-only schemas,
// use the reference directly. Skip this optimization when the parent
// schema has sibling properties that need the ref's fields resolved.
if !hasSiblingProperties && refSchema != nil && refCount == 1 && refCount+metadataOnlyCount == len(filteredAllOf) {
return GenerateGoSchema(refSchema, options.WithReference(refSchema.GetReference()))
}
var merged *base.Schema
var lastRef string
for _, schemaProxy := range filteredAllOf {
s := schemaProxy.Schema()
ref := schemaProxy.GetReference()
// Track the last non-empty reference
if ref != "" {
lastRef = ref
}
// If this is a single-element oneOf/anyOf, resolve it to get the actual schema.
// A single-element union flattens to just that element.
schemaToMerge := s
if s != nil {
if len(s.OneOf) == 1 && len(s.AnyOf) == 0 {
schemaToMerge = s.OneOf[0].Schema()
if r := s.OneOf[0].GetReference(); r != "" {
lastRef = r
}
} else if len(s.AnyOf) == 1 && len(s.OneOf) == 0 {
schemaToMerge = s.AnyOf[0].Schema()
if r := s.AnyOf[0].GetReference(); r != "" {
lastRef = r
}
}
}
var err error
merged, err = mergeOpenapiSchemas(merged, schemaToMerge)
if err != nil {
return GoSchema{}, fmt.Errorf("error merging schemas for allOf: %w at path %v", err, path)
}
}
schemaProxy := base.CreateSchemaProxy(merged)
opts := options
if low := schemaProxy.GoLow(); low != nil {
opts = options.WithReference(low.GetReference())
}
// If we have a reference from one of the allOf elements and the merged schema
// has no properties (i.e., it's a simple reference), use the reference.
// This handles cases like allOf with a description-only schema and a $ref.
if lastRef != "" && (merged == nil || merged.Properties == nil) {
opts = options.WithReference(lastRef)
}
return GenerateGoSchema(schemaProxy, opts)
}
// Use the already-resolved elements from above
var (
out GoSchema
additionalTypes []TypeDefinition
)
for _, elem := range resolvedElements {
schemaProxy := elem.schemaProxy
resolved := elem.resolved
subPath := elem.subPath
ref := schemaProxy.GoLow().GetReference()
if ref != "" {
typeName, err := refPathToGoType(ref)
if err != nil {
return GoSchema{}, fmt.Errorf("error converting reference to type name: %w", err)
}
// For path-based references (not component refs), we need to ensure the type is generated
if !isStandardComponentReference(ref) {
// Check if the type definition for the schema itself exists in additionalTypes
typeExists := false
for _, at := range resolved.AdditionalTypes {
if at.Name == typeName {
typeExists = true
break
}
}
// If the type doesn't exist, we need to create it
if !typeExists && resolved.TypeDecl() != typeName {
// The resolved schema has a different type name, so we need to create an alias or copy
td := TypeDefinition{
Name: typeName,
Schema: resolved,
SpecLocation: SpecLocationUnion,
NeedsMarshaler: needsMarshaler(resolved),
HasSensitiveData: hasSensitiveData(resolved),
}
// Add to type tracker if available
if options.typeTracker != nil {
options.typeTracker.register(td, "")
}
additionalTypes = append(additionalTypes, td)
}
// Add the additional types from the resolved schema
additionalTypes = append(additionalTypes, resolved.AdditionalTypes...)
}
out.Properties = append(out.Properties, Property{
GoName: typeName,
Schema: GoSchema{RefType: typeName},
Constraints: Constraints{Nullable: ptr(false)},
})
continue
}
// Skip empty/zero schemas (e.g., schemas with only metadata)
if resolved.IsZero() {
continue
}
// Skip metadata-only schemas that resolve to empty structs
// These are schemas with only description/title but no actual type definition
if isMetadataOnlySchema(schemaProxy.Schema()) {
continue
}
fieldName := pathToTypeName(subPath)
out.Properties = append(out.Properties, Property{
GoName: fieldName,
Schema: GoSchema{RefType: fieldName},
Constraints: Constraints{Nullable: ptr(true)},
})
td := TypeDefinition{
Name: fieldName,
Schema: resolved,
SpecLocation: SpecLocationUnion,
NeedsMarshaler: needsMarshaler(resolved),
HasSensitiveData: hasSensitiveData(resolved),
}
// Register allOf element types with the type tracker so they can be looked up
if options.typeTracker != nil {
options.typeTracker.register(td, "")
}
additionalTypes = append(additionalTypes, td)
additionalTypes = append(additionalTypes, resolved.AdditionalTypes...)
}
out.GoType = out.createGoStruct(genFieldsFromProperties(out.Properties, options))
// Don't create a type definition here - let the caller handle it via replaceInlineTypes.
// We just need to pass along the additional types from the allOf elements.
out.AdditionalTypes = append(out.AdditionalTypes, additionalTypes...)
return out, nil
}
// flattenAllOf resolves s.AllOf and merges back the parent's structural
// fields. Annotation fields (format, description, title) are excluded to
// avoid merge conflicts with the allOf elements.
func flattenAllOf(s *base.Schema) *base.Schema {
if s == nil || s.AllOf == nil {
return s
}
merged, err := mergeAllOf(s.AllOf)
if err != nil {
return s
}
ownFields := &base.Schema{
Type: s.Type,
Properties: s.Properties,
Required: s.Required,
Extensions: s.Extensions,
Nullable: s.Nullable,
AdditionalProperties: s.AdditionalProperties,
ReadOnly: s.ReadOnly,
WriteOnly: s.WriteOnly,
Enum: s.Enum,
Default: s.Default,
}
result, err := mergeOpenapiSchemas(merged, ownFields)
if err != nil {
return s
}
return result
}
func mergeAllOf(allOf []*base.SchemaProxy) (*base.Schema, error) {
var schema *base.Schema
for _, schemaRef := range allOf {
var err error
schema, err = mergeOpenapiSchemas(schema, schemaRef.Schema())
if err != nil {
return nil, fmt.Errorf("error merging schemas for AllOf: %w", err)
}
}
return schema, nil
}
// mergeOpenapiSchemas merges two openAPI schemas and returns the schema
// all of whose fields are composed.
func mergeOpenapiSchemas(s1, s2 *base.Schema) (*base.Schema, error) {
if s1 == nil {
// First schema, nothing to merge yet
return s2, nil
}
// Must flatten before the type-presence checks. A bare allOf wrapper
// has no own `type`; without flattening, the `len(t1) == 0` branch
// below would discard its contents and return s2 alone.
s1 = flattenAllOf(s1)
s2 = flattenAllOf(s2)
result := &base.Schema{}
t1 := getSchemaType(s1)
t2 := getSchemaType(s2)
// If a schema has no type, ignore it in the merge (e.g., description-only schemas)
if len(t2) == 0 {
return s1, nil
}
if len(t1) == 0 {
return s2, nil
}
if !slices.Equal(t1, t2) {
return nil, fmt.Errorf("can not merge incompatible types: %v, %v", t1, t2)
}
if s2.Extensions != nil && s2.Extensions.Len() > 0 {
result.Extensions = orderedmap.New[string, *yaml.Node]()
for k, v := range s2.Extensions.FromOldest() {
// TODO: Check for collisions
result.Extensions.Set(k, v)
}
}
result.OneOf = append(s1.OneOf, s2.OneOf...)
// We are going to make AllOf transitive, so that merging an AllOf that
// contains AllOf's will result in a flat object. When a schema has sibling
// structural fields alongside allOf (properties, required, extensions,
// additionalProperties, nullable), merge them into the allOf result so
// they are not lost. Annotation-only fields (format, description, title)
// are not merged because they can conflict with the allOf elements.
result.AllOf = append(s1.AllOf, s2.AllOf...)
result.Type = t1
if s1.Format != s2.Format {
return nil, ErrMergingSchemasWithDifferentFormats
}
result.Format = s1.Format
// For Enums, do we union, or intersect? This is a bit vague. I choose to be more permissive and union.
result.Enum = append(s1.Enum, s2.Enum...)
// Handle defaults: error only if both have different defaults
if s1.Default != nil && s2.Default != nil {
// Both have defaults - check if they're the same
if !reflect.DeepEqual(s1.Default, s2.Default) {
return nil, ErrMergingSchemasWithDifferentDefaults
}
result.Default = s1.Default
} else if s1.Default != nil {
result.Default = s1.Default
} else if s2.Default != nil {
result.Default = s2.Default
}
// If two schemas disagree on any of these flags, we error out.
if s1.UniqueItems != s2.UniqueItems {
return nil, ErrMergingSchemasWithDifferentUniqueItems
}
result.UniqueItems = s1.UniqueItems
if s1.ExclusiveMinimum != s2.ExclusiveMinimum {
return nil, ErrMergingSchemasWithDifferentExclusiveMin
}
result.ExclusiveMinimum = s1.ExclusiveMinimum
if s1.ExclusiveMaximum != s2.ExclusiveMaximum {
return nil, ErrMergingSchemasWithDifferentExclusiveMax
}
result.ExclusiveMaximum = s1.ExclusiveMaximum
// For Nullable, we take the union (more permissive) approach:
// - If either is true, result is true
// - If both are false (or nil, which defaults to false), result is false
// This allows merging schemas where one specifies nullable and another doesn't
result.Nullable = mergeNullable(s1.Nullable, s2.Nullable)
// ReadOnly/WriteOnly are annotations, not constraints — the validator
// doesn't enforce per-branch agreement. Take the union (true if any
// branch is true): if one branch marks the property response-only, the
// merged property is response-only.
result.ReadOnly = mergeBoolPtrOr(s1.ReadOnly, s2.ReadOnly)
result.WriteOnly = mergeBoolPtrOr(s1.WriteOnly, s2.WriteOnly)
// Required. We merge these.
result.Required = append(s1.Required, s2.Required...)
// On property collision, an annotation-only override (just
// `example` or `description`) must not overwrite a sibling that
// shapes the Go type. Otherwise s2 wins, matching prior behavior.
// We keep the original SchemaProxy rather than fabricating one via
// CreateSchemaProxy: downstream reads GoLow().GetReference() to
// attribute properties back to the spec.
for k, v := range s1.Properties.FromOldest() {
if result.Properties == nil {
result.Properties = orderedmap.New[string, *base.SchemaProxy]()
}
result.Properties.Set(k, v)
}
for k, v := range s2.Properties.FromOldest() {
if result.Properties == nil {
result.Properties = orderedmap.New[string, *base.SchemaProxy]()
}
if existing, exists := result.Properties.Get(k); exists {
if isAnnotationOnlySchema(v.Schema()) && !isAnnotationOnlySchema(existing.Schema()) {
continue
}
if merged, ok := mergePropertyProxies(existing, v); ok {
result.Properties.Set(k, merged)
continue
}
}
result.Properties.Set(k, v)
}
// Merge array Items. Without this, two array schemas with `items` on
// both sides produce a result with no Items, and downstream type
// inference falls back to string.
result.Items = mergeItems(s1.Items, s2.Items)
if isAdditionalPropertiesExplicitFalse(s1) || isAdditionalPropertiesExplicitFalse(s2) {
result.AdditionalProperties = &base.DynamicValue[*base.SchemaProxy, bool]{
A: nil,
B: false,
}
} else if s1.AdditionalProperties != nil && s1.AdditionalProperties.IsA() && s1.AdditionalProperties.A != nil {
if s2.AdditionalProperties != nil && s2.AdditionalProperties.A != nil {
return nil, ErrMergingSchemasWithAdditionalProperties
} else {
result.AdditionalProperties = &base.DynamicValue[*base.SchemaProxy, bool]{
A: s1.AdditionalProperties.A,
B: true,
}
}
} else {
if s2.AdditionalProperties != nil && s2.AdditionalProperties.A != nil {
result.AdditionalProperties = &base.DynamicValue[*base.SchemaProxy, bool]{
A: s2.AdditionalProperties.A,
B: true,
}
} else {
if (s1.AdditionalProperties != nil && s1.AdditionalProperties.A != nil) ||
(s2.AdditionalProperties != nil && s2.AdditionalProperties.A != nil) {
result.AdditionalProperties = &base.DynamicValue[*base.SchemaProxy, bool]{
A: nil,
B: false,
}
}
}
}
return result, nil
}
// mergePropertyProxies merges two colliding property schemas so that
// constraints from either side (enum, pattern, format, etc.) survive
// the allOf merge instead of being clobbered by the second declaration.
// Reports ok=false if the merge isn't safe (e.g. incompatible types);
// caller should fall back to s2-wins. Returned proxy is synthetic
// (no GoLow().GetReference()), which is acceptable for property
// collisions where the type itself stays inline.
func mergePropertyProxies(a, b *base.SchemaProxy) (*base.SchemaProxy, bool) {
sa := a.Schema()
sb := b.Schema()
if sa == nil || sb == nil {
return nil, false
}
saCopy := *sa
sbCopy := *sb
// Propagate type when one side has it and the other doesn't, so the
// `len(tX) == 0` short-circuits in mergeOpenapiSchemas don't drop
// the typeless side's constraints (enum, pattern, ...) on the floor.
if len(saCopy.Type) > 0 && len(sbCopy.Type) == 0 {
sbCopy.Type = saCopy.Type
} else if len(sbCopy.Type) > 0 && len(saCopy.Type) == 0 {
saCopy.Type = sbCopy.Type
}
// Relax flags that mergeOpenapiSchemas rejects outright. Property
// overrides commonly omit readOnly/writeOnly/exclusive*; treating
// the mismatch as "inherit from the typed side" is safer than
// dropping the override entirely.
sbCopy.ReadOnly = saCopy.ReadOnly
sbCopy.WriteOnly = saCopy.WriteOnly
sbCopy.UniqueItems = saCopy.UniqueItems
sbCopy.ExclusiveMinimum = saCopy.ExclusiveMinimum
sbCopy.ExclusiveMaximum = saCopy.ExclusiveMaximum
if sbCopy.Format == "" {
sbCopy.Format = saCopy.Format
}
merged, err := mergeOpenapiSchemas(&saCopy, &sbCopy)
if err != nil || merged == nil {
return nil, false
}
if sa.Example != nil && merged.Example == nil {
merged.Example = sa.Example
}
if sb.Example != nil && merged.Example == nil {
merged.Example = sb.Example
}
return base.CreateSchemaProxy(merged), true
}
// isAdditionalPropertiesExplicitFalse determines whether an Schema is explicitly defined as `additionalProperties: false`
func isAdditionalPropertiesExplicitFalse(s *base.Schema) bool {
if s.AdditionalProperties == nil {
return false
}
return !s.AdditionalProperties.IsB()
}
func getSchemaType(schema *base.Schema) []string {
if schema == nil {
return nil
}
if schema.Type != nil {
return schema.Type
}
if schema.Properties != nil {
return []string{"object"}
}
if schema.Items != nil {
return []string{"array"}
}
return nil
}
// isAnnotationOnlySchema reports whether a schema only has metadata
// (description, example) and no fields that shape the generated type.
func isAnnotationOnlySchema(s *base.Schema) bool {
if s == nil {
return true
}
if len(s.Type) > 0 {
return false
}
if len(s.AllOf) > 0 || len(s.OneOf) > 0 || len(s.AnyOf) > 0 {
return false
}
if s.If != nil || s.Then != nil || s.Else != nil || s.Not != nil {
return false
}
if s.Properties != nil && s.Properties.Len() > 0 {
return false
}
if s.PatternProperties != nil && s.PatternProperties.Len() > 0 {
return false
}
if s.Items != nil {
return false
}
if len(s.Enum) > 0 {
return false
}
if s.AdditionalProperties != nil {
return false
}
if s.Const != nil {
return false
}
return true
}
// mergeNullable merges two nullable pointers using a union (more permissive) approach.
// If either is true, the result is true. If both are false or nil, the result is nil.
// This allows merging schemas where one specifies nullable and another doesn't.
func mergeNullable(a, b *bool) *bool {
return mergeBoolPtrOr(a, b)
}
// mergeItems combines the array `items` constraint from two allOf branches.
// In 3.1, `items` can be either a schema or `false` (forbidding items); if
// either side forbids items, the merged result does too. For schema items,
// the later branch wins, mirroring the property-override semantics in
// `mergeOpenapiSchemas`: a later allOf branch specializes the items
// declaration from an earlier branch. We don't attempt true element-wise
// composition because one side can be a wrapper like `anyOf: [...]` with
// no own type, which `mergeOpenapiSchemas` would short-circuit and drop.
func mergeItems(a, b *base.DynamicValue[*base.SchemaProxy, bool]) *base.DynamicValue[*base.SchemaProxy, bool] {
if a == nil {
return b
}
if b == nil {
return a
}
if !a.IsA() {
if !a.B {
return a
}
return b
}
if !b.IsA() {
if !b.B {
return b
}
return a
}
// Annotation-only override (no shape, just description/example) must
// not clobber a typed sibling - same rule as property collisions.
if a.A != nil && b.A != nil {
sa := a.A.Schema()
sb := b.A.Schema()
if sa != nil && sb != nil {
if isAnnotationOnlySchema(sb) && !isAnnotationOnlySchema(sa) {
return a
}
if isAnnotationOnlySchema(sa) && !isAnnotationOnlySchema(sb) {
return b
}
}
}
return b
}
// mergeBoolPtrOr returns the logical OR of two optional booleans, preserving
// the "unset" state (nil) when both inputs are nil or false. Used to merge
// annotation flags (Nullable, ReadOnly, WriteOnly) across allOf branches:
// if any branch sets the flag, the merged result has it set.
func mergeBoolPtrOr(a, b *bool) *bool {
if (a != nil && *a) || (b != nil && *b) {
return ptr(true)
}
return nil
}
// isDiscriminatedUnionWithChild checks if a schema is a discriminated union (oneOf with discriminator)
// that includes the given childRef in its oneOf elements.
// This is used to detect circular allOf patterns like:
//
// CounterParty:
// discriminator: { propertyName: type, mapping: { VENDOR: VendorDetails } }