-
-
Notifications
You must be signed in to change notification settings - Fork 380
Expand file tree
/
Copy pathschema.ts
More file actions
1376 lines (1203 loc) · 34.6 KB
/
schema.ts
File metadata and controls
1376 lines (1203 loc) · 34.6 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
import type { OpenAPIV3 } from '@hey-api/spec-types';
import type { Context } from '../../../ir/context';
import type { IR } from '../../../ir/types';
import { addItemsToSchema } from '../../../ir/utils';
import type {
SchemaState,
SchemaType,
SchemaWithRequired,
} from '../../../openApi/shared/types/schema';
import {
convertDiscriminatorValue,
type DiscriminatorPropertyType,
discriminatorValues,
} from '../../../openApi/shared/utils/discriminator';
import { isTopLevelComponent, refToName } from '../../../utils/ref';
export const getSchemaType = ({
schema,
}: {
schema: OpenAPIV3.SchemaObject;
}): SchemaType<OpenAPIV3.SchemaObject> | undefined => {
if (schema.type) {
return schema.type;
}
// infer object based on the presence of properties
if (schema.properties) {
return 'object';
}
return;
};
/**
* Finds the type of a discriminator property by looking it up in the provided schemas.
* Searches through properties and allOf chains to find the property definition.
*/
const findDiscriminatorPropertyType = ({
context,
propertyName,
schemas,
}: {
context: Context;
propertyName: string;
schemas: ReadonlyArray<OpenAPIV3.SchemaObject | OpenAPIV3.ReferenceObject>;
}): DiscriminatorPropertyType => {
for (const schema of schemas) {
const resolved =
'$ref' in schema ? context.resolveRef<OpenAPIV3.SchemaObject>(schema.$ref) : schema;
// Check direct properties
const property = resolved.properties?.[propertyName];
if (property) {
const resolvedProperty =
'$ref' in property ? context.resolveRef<OpenAPIV3.SchemaObject>(property.$ref) : property;
if (
resolvedProperty.type === 'boolean' ||
resolvedProperty.type === 'integer' ||
resolvedProperty.type === 'number'
) {
return resolvedProperty.type;
}
}
// Check allOf chains
if (resolved.allOf) {
const foundType = findDiscriminatorPropertyType({
context,
propertyName,
schemas: resolved.allOf,
});
if (foundType !== 'string') {
return foundType;
}
}
}
return 'string';
};
/**
* Recursively finds discriminators in a schema, including nested allOf compositions.
* This is needed when a schema extends another schema via allOf, and that parent
* schema is itself an allOf composition with discriminators in inline schemas.
*/
const findDiscriminatorsInSchema = ({
context,
discriminators = [],
schema,
}: {
context: Context;
discriminators?: Array<{
discriminator: NonNullable<OpenAPIV3.SchemaObject['discriminator']>;
oneOf?: OpenAPIV3.SchemaObject['oneOf'];
}>;
schema: OpenAPIV3.SchemaObject;
}): Array<{
discriminator: NonNullable<OpenAPIV3.SchemaObject['discriminator']>;
oneOf?: OpenAPIV3.SchemaObject['oneOf'];
}> => {
// Check if this schema has a discriminator
if (schema.discriminator) {
discriminators.push({
discriminator: schema.discriminator,
oneOf: schema.oneOf,
});
}
// If this schema is an allOf composition, recursively search in its components
if (schema.allOf) {
for (const compositionSchema of schema.allOf) {
let resolvedSchema: OpenAPIV3.SchemaObject;
if ('$ref' in compositionSchema) {
resolvedSchema = context.resolveRef<OpenAPIV3.SchemaObject>(compositionSchema.$ref);
} else {
resolvedSchema = compositionSchema;
}
findDiscriminatorsInSchema({
context,
discriminators,
schema: resolvedSchema,
});
}
}
return discriminators;
};
/**
* Gets the discriminator value for a schema.
* Returns only the schema's own discriminator value, not child values.
*/
const getAllDiscriminatorValues = ({
discriminator,
schemaRef,
}: {
discriminator: NonNullable<OpenAPIV3.SchemaObject['discriminator']>;
schemaRef: string;
}): Array<string> => {
const values: Array<string> = [];
// Check each entry in the discriminator mapping
for (const [value, mappedSchemaRef] of Object.entries(discriminator.mapping || {})) {
if (mappedSchemaRef === schemaRef) {
// This is the current schema's own value
values.push(value);
}
}
return values;
};
const parseSchemaJsDoc = ({
irSchema,
schema,
}: {
irSchema: IR.SchemaObject;
schema: OpenAPIV3.SchemaObject;
}) => {
if (schema.deprecated !== undefined) {
irSchema.deprecated = schema.deprecated;
}
if (schema.example) {
irSchema.example = schema.example;
}
if (schema.description) {
irSchema.description = schema.description;
}
if (schema.title) {
irSchema.title = schema.title;
}
};
const parseSchemaMeta = ({
irSchema,
schema,
}: {
irSchema: IR.SchemaObject;
schema: OpenAPIV3.SchemaObject;
}) => {
if (schema.default !== undefined) {
irSchema.default = schema.default;
}
if (schema.exclusiveMaximum) {
if (schema.maximum !== undefined) {
irSchema.exclusiveMaximum = schema.maximum;
}
} else if (schema.maximum !== undefined) {
irSchema.maximum = schema.maximum;
}
if (schema.exclusiveMinimum) {
if (schema.minimum !== undefined) {
irSchema.exclusiveMinimum = schema.minimum;
}
} else if (schema.minimum !== undefined) {
irSchema.minimum = schema.minimum;
}
if (schema.format) {
irSchema.format = schema.format;
}
if (schema.maxItems !== undefined) {
irSchema.maxItems = schema.maxItems;
}
if (schema.maxLength !== undefined) {
irSchema.maxLength = schema.maxLength;
}
if (schema.minItems !== undefined) {
irSchema.minItems = schema.minItems;
}
if (schema.minLength !== undefined) {
irSchema.minLength = schema.minLength;
}
if (schema.pattern) {
irSchema.pattern = schema.pattern;
}
if (schema.readOnly) {
irSchema.accessScope = 'read';
} else if (schema.writeOnly) {
irSchema.accessScope = 'write';
}
};
const parseArray = ({
context,
irSchema = {},
schema,
state,
}: {
context: Context;
irSchema?: IR.SchemaObject;
schema: OpenAPIV3.SchemaObject;
state: SchemaState;
}): IR.SchemaObject => {
if (schema.maxItems && schema.maxItems === schema.minItems) {
irSchema.type = 'tuple';
} else {
irSchema.type = 'array';
}
let schemaItems: Array<IR.SchemaObject> = [];
if (schema.items) {
const irItemsSchema = schemaToIrSchema({
context,
schema: schema.items,
state,
});
if (!schemaItems.length && schema.maxItems && schema.maxItems === schema.minItems) {
schemaItems = Array(schema.maxItems).fill(irItemsSchema);
} else {
if ('$ref' in schema.items) {
schemaItems.push(irItemsSchema);
} else {
const ofArray = schema.items.allOf || schema.items.anyOf || schema.items.oneOf;
if (ofArray && ofArray.length > 1 && !schema.items.nullable) {
// bring composition up to avoid incorrectly nested arrays
irSchema = {
...irSchema,
...irItemsSchema,
};
} else {
schemaItems.push(irItemsSchema);
}
}
}
}
irSchema = addItemsToSchema({
items: schemaItems,
schema: irSchema,
});
return irSchema;
};
const parseBoolean = ({
irSchema = {},
}: {
context: Context;
irSchema?: IR.SchemaObject;
schema: OpenAPIV3.SchemaObject;
state: SchemaState;
}): IR.SchemaObject => {
irSchema.type = 'boolean';
return irSchema;
};
const parseNumber = ({
irSchema = {},
schema,
}: {
context: Context;
irSchema?: IR.SchemaObject;
schema: SchemaWithRequired<OpenAPIV3.SchemaObject, 'type'>;
state: SchemaState;
}): IR.SchemaObject => {
irSchema.type = schema.type;
return irSchema;
};
const parseObject = ({
context,
irSchema = {},
schema,
state,
}: {
context: Context;
irSchema?: IR.SchemaObject;
schema: OpenAPIV3.SchemaObject;
state: SchemaState;
}): IR.SchemaObject => {
irSchema.type = 'object';
const schemaProperties: Record<string, IR.SchemaObject> = {};
for (const name in schema.properties) {
const property = schema.properties[name]!;
if (typeof property === 'boolean') {
// TODO: parser - handle boolean properties
} else {
schemaProperties[name] = schemaToIrSchema({
context,
schema: property,
state,
});
}
}
if (Object.keys(schemaProperties).length) {
irSchema.properties = schemaProperties;
}
if (schema.additionalProperties === undefined) {
if (!irSchema.properties) {
irSchema.additionalProperties = {
type: 'unknown',
};
}
} else if (typeof schema.additionalProperties === 'boolean') {
// Avoid [key: string]: never for empty objects with additionalProperties: false inside allOf
// This would override inherited properties from other schemas in the composition
const isEmptyObjectInAllOf =
state.inAllOf &&
schema.additionalProperties === false &&
(!schema.properties || !Object.keys(schema.properties).length);
if (!isEmptyObjectInAllOf) {
irSchema.additionalProperties = {
type: schema.additionalProperties ? 'unknown' : 'never',
};
}
} else {
const irAdditionalPropertiesSchema = schemaToIrSchema({
context,
schema: schema.additionalProperties,
state,
});
irSchema.additionalProperties = irAdditionalPropertiesSchema;
}
if (schema.required) {
irSchema.required = schema.required;
}
if (schema.discriminator && state.$ref) {
const values = getAllDiscriminatorValues({
discriminator: schema.discriminator,
schemaRef: state.$ref,
});
if (values.length) {
const propertyType = findDiscriminatorPropertyType({
context,
propertyName: schema.discriminator.propertyName,
schemas: [schema],
});
const valueSchemas: ReadonlyArray<IR.SchemaObject> = values.map((value) =>
convertDiscriminatorValue(value, propertyType),
);
if (!irSchema.properties) {
irSchema.properties = {};
}
irSchema.properties[schema.discriminator.propertyName] =
valueSchemas.length > 1
? {
items: valueSchemas,
logicalOperator: 'or',
}
: valueSchemas[0]!;
}
}
return irSchema;
};
const parseString = ({
irSchema = {},
}: {
context: Context;
irSchema?: IR.SchemaObject;
schema: OpenAPIV3.SchemaObject;
state: SchemaState;
}): IR.SchemaObject => {
irSchema.type = 'string';
return irSchema;
};
export const parseExtensions = ({ source, target }: { source: object; target: object }) => {
for (const key in source) {
if (key.startsWith('x-')) {
(target as Record<string, unknown>)[key] = (source as Record<string, unknown>)[key];
}
}
};
const initIrSchema = ({ schema }: { schema: OpenAPIV3.SchemaObject }): IR.SchemaObject => {
const irSchema: IR.SchemaObject = {};
parseSchemaJsDoc({
irSchema,
schema,
});
parseExtensions({
source: schema,
target: irSchema,
});
return irSchema;
};
const parseAllOf = ({
context,
schema,
state,
}: {
context: Context;
schema: SchemaWithRequired<OpenAPIV3.SchemaObject, 'allOf'>;
state: SchemaState;
}): IR.SchemaObject => {
let irSchema = initIrSchema({ schema });
const schemaItems: Array<IR.SchemaObject> = [];
const schemaType = getSchemaType({ schema });
const compositionSchemas = schema.allOf;
// Collect discriminator information to add after all compositions are processed
type DiscriminatorInfo = {
discriminator: NonNullable<OpenAPIV3.SchemaObject['discriminator']>;
isExplicitMapping: boolean;
isRequired: boolean;
values: ReadonlyArray<string>;
};
const discriminatorsToAdd: Array<DiscriminatorInfo> = [];
for (const compositionSchema of compositionSchemas) {
const originalInAllOf = state.inAllOf;
// Don't propagate inAllOf flag to $ref schemas to avoid issues with reusable components
if (!('$ref' in compositionSchema)) {
state.inAllOf = true;
}
const irCompositionSchema = schemaToIrSchema({
context,
schema: compositionSchema,
state,
});
state.inAllOf = originalInAllOf;
if (state.inAllOf === undefined) {
delete state.inAllOf;
}
if (schema.required) {
if (irCompositionSchema.required) {
irCompositionSchema.required = [...irCompositionSchema.required, ...schema.required];
} else {
irCompositionSchema.required = schema.required;
}
}
schemaItems.push(irCompositionSchema);
if ('$ref' in compositionSchema) {
const ref = context.resolveRef<OpenAPIV3.SchemaObject>(compositionSchema.$ref);
// `$ref` should be passed from the root `parseSchema()` call
if (state.$ref) {
// Find all discriminators in the referenced schema, including nested allOf compositions
const discriminators = findDiscriminatorsInSchema({
context,
schema: ref,
});
for (const { discriminator, oneOf } of discriminators) {
const values = discriminatorValues(
state.$ref,
discriminator.mapping,
// If the ref has oneOf, we only use the schema name as the value
// only if current schema is part of the oneOf. Else it is extending
// the ref schema
oneOf ? () => oneOf.some((o) => '$ref' in o && o.$ref === state.$ref) : undefined,
);
if (!values.length) {
continue;
}
// True when state.$ref appears directly in the mapping; false when the
// value fell back to the schema name because no mapping entry matched.
const isExplicitMapping =
discriminator.mapping !== undefined &&
Object.values(discriminator.mapping).includes(state.$ref);
// An explicit mapping always beats a same-property fallback collected
// earlier (e.g. from a grandparent discriminator that doesn't list this
// schema). Replace it; otherwise skip the duplicate.
const existingIndex = discriminatorsToAdd.findIndex(
(d) => d.discriminator.propertyName === discriminator.propertyName,
);
if (existingIndex !== -1) {
if (isExplicitMapping && !discriminatorsToAdd[existingIndex]!.isExplicitMapping) {
discriminatorsToAdd.splice(existingIndex, 1);
} else {
continue;
}
}
const isRequired = discriminators.some(
(d) =>
d.discriminator.propertyName === discriminator.propertyName &&
(ref.required?.includes(d.discriminator.propertyName) ||
(ref.allOf &&
ref.allOf.some((item) => {
const resolvedItem =
'$ref' in item ? context.resolveRef<OpenAPIV3.SchemaObject>(item.$ref) : item;
return resolvedItem.required?.includes(d.discriminator.propertyName);
}))),
);
discriminatorsToAdd.push({
discriminator,
isExplicitMapping,
isRequired,
values,
});
}
}
}
}
// Now add discriminators after all compositions have been processed
for (const { discriminator, isRequired, values } of discriminatorsToAdd) {
// Get all discriminator values including children for union types
const allValues = getAllDiscriminatorValues({
discriminator,
schemaRef: state.$ref!,
});
// Use allValues if we found children, otherwise use the original values
const finalValues = allValues.length ? allValues : values;
// Detect the actual type of the discriminator property
const propertyType = findDiscriminatorPropertyType({
context,
propertyName: discriminator.propertyName,
schemas: compositionSchemas,
});
const valueSchemas: ReadonlyArray<IR.SchemaObject> = finalValues.map((value) =>
convertDiscriminatorValue(value, propertyType),
);
const discriminatorProperty: IR.SchemaObject =
valueSchemas.length > 1
? {
items: valueSchemas,
logicalOperator: 'or',
}
: valueSchemas[0]!;
// Check if any $ref schemas in schemaItems have this discriminator property
// If yes, mark them to omit it to avoid conflicts
for (const item of schemaItems) {
if (item.$ref || item.symbolRef) {
// Check if the referenced schema has this property
const hasProperty = (() => {
if (!item.$ref) return false;
try {
const refSchema = context.resolveRef<OpenAPIV3.SchemaObject>(item.$ref);
// Check if the discriminator property exists in the ref schema
return (
refSchema.properties?.[discriminator.propertyName] !== undefined ||
(refSchema.allOf &&
refSchema.allOf.some((allOfItem) => {
const resolved =
'$ref' in allOfItem
? context.resolveRef<OpenAPIV3.SchemaObject>(allOfItem.$ref)
: allOfItem;
return resolved.properties?.[discriminator.propertyName] !== undefined;
}))
);
} catch {
return false;
}
})();
if (hasProperty) {
// Mark this ref to omit the discriminator property
if (!item.omit) {
item.omit = [discriminator.propertyName];
} else if (!item.omit.includes(discriminator.propertyName)) {
item.omit = [...item.omit, discriminator.propertyName];
}
}
}
}
// Find the inline schema (non-$ref) to merge the discriminator property into
// The inline schema should be the last non-$ref item in schemaItems
let inlineSchema: IR.SchemaObject | undefined;
for (let i = schemaItems.length - 1; i >= 0; i--) {
const item = schemaItems[i]!;
// Check if this is not a $ref schema by looking for properties or checking if it came from an inline schema
if (item.type === 'object' || item.properties) {
inlineSchema = item;
break;
}
}
// If we found an inline schema, add the discriminator property to it
if (inlineSchema) {
if (!inlineSchema.properties) {
inlineSchema.properties = {};
}
inlineSchema.properties[discriminator.propertyName] = discriminatorProperty;
if (isRequired) {
if (!inlineSchema.required) {
inlineSchema.required = [];
}
if (!inlineSchema.required.includes(discriminator.propertyName)) {
inlineSchema.required = [...inlineSchema.required, discriminator.propertyName];
}
}
} else {
// Fallback: create a separate discriminator schema if no inline schema found
const irDiscriminatorSchema: IR.SchemaObject = {
properties: {
[discriminator.propertyName]: discriminatorProperty,
},
type: 'object',
};
if (isRequired) {
irDiscriminatorSchema.required = [discriminator.propertyName];
}
schemaItems.push(irDiscriminatorSchema);
}
}
if (schemaType === 'object') {
const irObjectSchema = parseOneType({
context,
schema: {
...schema,
type: 'object',
},
state,
});
if (irObjectSchema.properties) {
for (const requiredProperty of irObjectSchema.required ?? []) {
if (!irObjectSchema.properties[requiredProperty]) {
for (const compositionSchema of compositionSchemas) {
// TODO: parser - this could be probably resolved more accurately
const finalCompositionSchema =
'$ref' in compositionSchema
? context.resolveRef<OpenAPIV3.SchemaObject>(compositionSchema.$ref)
: compositionSchema;
if (getSchemaType({ schema: finalCompositionSchema }) === 'object') {
const irCompositionSchema = parseOneType({
context,
schema: {
...finalCompositionSchema,
type: 'object',
},
state,
});
if (irCompositionSchema.properties?.[requiredProperty]) {
irObjectSchema.properties[requiredProperty] =
irCompositionSchema.properties[requiredProperty];
break;
}
}
}
}
}
schemaItems.push(irObjectSchema);
}
}
irSchema = addItemsToSchema({
items: schemaItems,
logicalOperator: 'and',
mutateSchemaOneItem: true,
schema: irSchema,
});
if (schema.nullable) {
// nest composition to avoid producing an intersection with null
const nestedItems: Array<IR.SchemaObject> = [
{
type: 'null',
},
];
if (schemaItems.length) {
nestedItems.unshift(irSchema);
}
irSchema = {
items: nestedItems,
logicalOperator: 'or',
};
// TODO: parser - this is a hack to bring back up meta fields
// without it, some schemas were missing original deprecated
if (nestedItems[0]!.deprecated) {
irSchema.deprecated = nestedItems[0]!.deprecated;
}
// TODO: parser - this is a hack to bring back up meta fields
// without it, some schemas were missing original description
if (nestedItems[0]!.description) {
irSchema.description = nestedItems[0]!.description;
}
}
return irSchema;
};
const parseAnyOf = ({
context,
schema,
state,
}: {
context: Context;
schema: SchemaWithRequired<OpenAPIV3.SchemaObject, 'anyOf'>;
state: SchemaState;
}): IR.SchemaObject => {
let irSchema = initIrSchema({ schema });
const schemaItems: Array<IR.SchemaObject> = [];
const schemaType = getSchemaType({ schema });
const compositionSchemas = schema.anyOf;
const discriminatorPropertyType = schema.discriminator
? findDiscriminatorPropertyType({
context,
propertyName: schema.discriminator.propertyName,
schemas: compositionSchemas,
})
: undefined;
for (const compositionSchema of compositionSchemas) {
let irCompositionSchema = schemaToIrSchema({
context,
schema: compositionSchema,
state,
});
// `$ref` should be defined with discriminators
if (schema.discriminator && irCompositionSchema.$ref) {
const values = discriminatorValues(irCompositionSchema.$ref, schema.discriminator.mapping);
const valueSchemas: ReadonlyArray<IR.SchemaObject> = values.map((value) =>
convertDiscriminatorValue(value, discriminatorPropertyType!),
);
const irDiscriminatorSchema: IR.SchemaObject = {
properties: {
[schema.discriminator.propertyName]:
valueSchemas.length > 1
? {
items: valueSchemas,
logicalOperator: 'or',
}
: valueSchemas[0]!,
},
type: 'object',
};
irCompositionSchema = {
items: [irDiscriminatorSchema, irCompositionSchema],
logicalOperator: 'and',
};
}
schemaItems.push(irCompositionSchema);
}
if (schema.nullable) {
schemaItems.push({ type: 'null' });
}
irSchema = addItemsToSchema({
items: schemaItems,
mutateSchemaOneItem: true,
schema: irSchema,
});
if (schemaType === 'object') {
// nest composition to avoid producing a union with object properties
const irObjectSchema = parseOneType({
context,
schema: {
...schema,
type: 'object',
},
state,
});
if (irObjectSchema.properties) {
irSchema = {
items: [irSchema, irObjectSchema],
logicalOperator: 'and',
};
}
}
return irSchema;
};
const parseEnum = ({
context,
schema,
state,
}: {
context: Context;
schema: SchemaWithRequired<OpenAPIV3.SchemaObject, 'enum'>;
state: SchemaState;
}): IR.SchemaObject => {
let irSchema = initIrSchema({ schema });
irSchema.type = 'enum';
const schemaItems: Array<IR.SchemaObject> = [];
for (const [index, enumValue] of schema.enum.entries()) {
const typeOfEnumValue = typeof enumValue;
let enumType: SchemaType<OpenAPIV3.SchemaObject> | 'null' | undefined;
if (
typeOfEnumValue === 'string' ||
typeOfEnumValue === 'number' ||
typeOfEnumValue === 'boolean'
) {
enumType = typeOfEnumValue;
} else if (typeOfEnumValue === 'object' && Array.isArray(enumValue)) {
enumType = 'array';
} else if (enumValue === null) {
// nullable must be true
if (schema.nullable) {
enumType = 'null';
}
} else {
console.warn(
'🚨',
`unhandled "${typeOfEnumValue}" typeof value "${enumValue}" for enum`,
schema.enum,
);
}
if (!enumType) {
continue;
}
const irTypeSchema = parseOneType({
context,
schema: {
description: schema['x-enum-descriptions']?.[index],
title: schema['x-enum-varnames']?.[index] ?? schema['x-enumNames']?.[index],
// cast enum to string temporarily
type: enumType === 'null' ? 'string' : enumType,
},
state,
});
irTypeSchema.const = enumValue;
// cast enum back
if (enumType === 'null') {
irTypeSchema.type = enumType;
}
if (irTypeSchema.type === 'array') {
irTypeSchema.type = 'tuple';
}
schemaItems.push(irTypeSchema);
}
irSchema = addItemsToSchema({
items: schemaItems,
schema: irSchema,
});
return irSchema;
};
const parseOneOf = ({
context,
schema,
state,
}: {
context: Context;
schema: SchemaWithRequired<OpenAPIV3.SchemaObject, 'oneOf'>;
state: SchemaState;
}): IR.SchemaObject => {
let irSchema = initIrSchema({ schema });
let schemaItems: Array<IR.SchemaObject> = [];
const schemaType = getSchemaType({ schema });
const compositionSchemas = schema.oneOf;
const discriminatorPropertyType = schema.discriminator
? findDiscriminatorPropertyType({
context,
propertyName: schema.discriminator.propertyName,
schemas: compositionSchemas,
})
: undefined;
for (const compositionSchema of compositionSchemas) {
let irCompositionSchema = schemaToIrSchema({
context,
schema: compositionSchema,
state,
});
// `$ref` should be defined with discriminators
if (schema.discriminator && irCompositionSchema.$ref) {
const values = discriminatorValues(irCompositionSchema.$ref, schema.discriminator.mapping);
const valueSchemas: ReadonlyArray<IR.SchemaObject> = values.map((value) =>
convertDiscriminatorValue(value, discriminatorPropertyType!),
);
const irDiscriminatorSchema: IR.SchemaObject = {
properties: {
[schema.discriminator.propertyName]:
valueSchemas.length > 1
? {
items: valueSchemas,
logicalOperator: 'or',
}
: valueSchemas[0]!,
},
required: [schema.discriminator.propertyName],
type: 'object',
};
irCompositionSchema = {
items: [irDiscriminatorSchema, irCompositionSchema],
logicalOperator: 'and',
};
}
// since we know oneOf will be using "or" logical operator, if the parsed
// composition schema also has an "or" operator, we can bring it up
// to avoid unnecessary brackets
if (
irCompositionSchema.logicalOperator === 'or' &&
irCompositionSchema.type !== 'array' &&
irCompositionSchema.items
) {
schemaItems = schemaItems.concat(irCompositionSchema.items);
} else {
schemaItems.push(irCompositionSchema);
}
}