forked from microsoft/typespec
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathschema-emitter-3-0.ts
284 lines (255 loc) · 9.13 KB
/
schema-emitter-3-0.ts
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
import {
AssetEmitter,
createAssetEmitter,
EmitterOutput,
ObjectBuilder,
Placeholder,
TypeEmitter,
} from "@typespec/asset-emitter";
import {
compilerAssert,
Enum,
getDiscriminatedUnion,
getExamples,
getMaxValueExclusive,
getMinValueExclusive,
IntrinsicType,
isNullType,
Model,
ModelProperty,
Scalar,
serializeValueAsJson,
Type,
Union,
} from "@typespec/compiler";
import { MetadataInfo } from "@typespec/http";
import { shouldInline } from "@typespec/openapi";
import { getOneOf } from "./decorators.js";
import { JsonSchemaModule } from "./json-schema.js";
import { OpenAPI3EmitterOptions, reportDiagnostic } from "./lib.js";
import { applyEncoding, getRawBinarySchema } from "./openapi-helpers-3-0.js";
import { CreateSchemaEmitter } from "./openapi-spec-mappings.js";
import { ResolvedOpenAPI3EmitterOptions } from "./openapi.js";
import { Builders, OpenAPI3SchemaEmitterBase } from "./schema-emitter.js";
import { JsonType, OpenAPI3Schema } from "./types.js";
import { isBytesKeptRaw, isLiteralType, literalType } from "./util.js";
import { VisibilityUsageTracker } from "./visibility-usage.js";
import { XmlModule } from "./xml-module.js";
function createWrappedSchemaEmitterClass(
metadataInfo: MetadataInfo,
visibilityUsage: VisibilityUsageTracker,
options: ResolvedOpenAPI3EmitterOptions,
optionalDependencies: { jsonSchemaModule?: JsonSchemaModule; xmlModule?: XmlModule },
): typeof TypeEmitter<Record<string, any>, OpenAPI3EmitterOptions> {
return class extends OpenAPI3SchemaEmitter {
constructor(emitter: AssetEmitter<Record<string, any>, OpenAPI3EmitterOptions>) {
super(emitter, metadataInfo, visibilityUsage, options, optionalDependencies);
}
};
}
export const createSchemaEmitter3_0: CreateSchemaEmitter = ({ program, context, ...rest }) => {
return createAssetEmitter(
program,
createWrappedSchemaEmitterClass(
rest.metadataInfo,
rest.visibilityUsage,
rest.options,
rest.optionalDependencies,
),
context,
);
};
/**
* OpenAPI 3.0 schema emitter. Deals with emitting content of `components/schemas` section.
*/
export class OpenAPI3SchemaEmitter extends OpenAPI3SchemaEmitterBase<OpenAPI3Schema> {
#applySchemaExamples(
type: Model | Scalar | Union | Enum | ModelProperty,
target: ObjectBuilder<any>,
) {
const program = this.emitter.getProgram();
const examples = getExamples(program, type);
if (examples.length > 0) {
target.set("example", serializeValueAsJson(program, examples[0].value, type));
}
}
applyCustomConstraints(
type: Scalar | Model | ModelProperty | Union | Enum,
target: ObjectBuilder<OpenAPI3Schema>,
refSchema?: OpenAPI3Schema,
) {
const program = this.emitter.getProgram();
const minValueExclusive = getMinValueExclusive(program, type);
if (minValueExclusive !== undefined) {
target.minimum = minValueExclusive;
target.exclusiveMinimum = true;
}
const maxValueExclusive = getMaxValueExclusive(program, type);
if (maxValueExclusive !== undefined) {
target.maximum = maxValueExclusive;
target.exclusiveMaximum = true;
}
this.#applySchemaExamples(type, target);
}
applyEncoding(
typespecType: Scalar | ModelProperty,
target: OpenAPI3Schema | Placeholder<OpenAPI3Schema>,
): OpenAPI3Schema {
return applyEncoding(this.emitter.getProgram(), typespecType, target as any, this._options);
}
getRawBinarySchema(): OpenAPI3Schema {
return getRawBinarySchema();
}
enumSchema(en: Enum): OpenAPI3Schema {
const program = this.emitter.getProgram();
if (en.members.size === 0) {
reportDiagnostic(program, { code: "empty-enum", target: en });
return {};
}
const enumTypes = new Set<JsonType>();
const enumValues = new Set<string | number>();
for (const member of en.members.values()) {
enumTypes.add(typeof member.value === "number" ? "number" : "string");
enumValues.add(member.value ?? member.name);
}
if (enumTypes.size > 1) {
reportDiagnostic(program, { code: "enum-unique-type", target: en });
}
const schema: OpenAPI3Schema = {
type: enumTypes.values().next().value!,
enum: [...enumValues],
};
return this.applyConstraints(en, schema);
}
unionSchema(union: Union): ObjectBuilder<OpenAPI3Schema> {
const program = this.emitter.getProgram();
const [discriminated] = getDiscriminatedUnion(program, union);
if (discriminated) {
return this.discriminatedUnion(discriminated);
}
if (union.variants.size === 0) {
reportDiagnostic(program, { code: "empty-union", target: union });
return new ObjectBuilder({});
}
const variants = Array.from(union.variants.values());
const literalVariantEnumByType: Record<string, any[]> = {};
const ofType = getOneOf(program, union) ? "oneOf" : "anyOf";
const schemaMembers: { schema: any; type: Type | null }[] = [];
let nullable = false;
const isMultipart = this.getContentType().startsWith("multipart/");
for (const variant of variants) {
if (isNullType(variant.type)) {
nullable = true;
continue;
}
if (isMultipart && isBytesKeptRaw(program, variant.type)) {
schemaMembers.push({ schema: this.getRawBinarySchema(), type: variant.type });
continue;
}
if (isLiteralType(variant.type)) {
if (!literalVariantEnumByType[variant.type.kind]) {
const enumValue: any[] = [variant.type.value];
literalVariantEnumByType[variant.type.kind] = enumValue;
schemaMembers.push({
schema: { type: literalType(variant.type), enum: enumValue },
type: null,
});
} else {
literalVariantEnumByType[variant.type.kind].push(variant.type.value);
}
} else {
const enumSchema = this.emitter.emitTypeReference(variant.type, {
referenceContext: isMultipart ? { contentType: "application/json" } : {},
});
compilerAssert(enumSchema.kind === "code", "Unexpected enum schema. Should be kind: code");
schemaMembers.push({ schema: enumSchema.value, type: variant.type });
}
}
const wrapWithObjectBuilder = (
schemaMember: { schema: any; type: Type | null },
{ mergeUnionWideConstraints }: { mergeUnionWideConstraints: boolean },
): ObjectBuilder<OpenAPI3Schema> => {
// we can just return the single schema member after applying nullable
const schema = schemaMember.schema;
const type = schemaMember.type;
const additionalProps: Partial<OpenAPI3Schema> = mergeUnionWideConstraints
? this.applyConstraints(union, {})
: {};
if (mergeUnionWideConstraints && nullable) {
additionalProps.nullable = true;
}
if (Object.keys(additionalProps).length === 0) {
return new ObjectBuilder(schema);
} else {
if (
(schema instanceof Placeholder || "$ref" in schema) &&
!(type && shouldInline(program, type))
) {
if (type && (type.kind === "Model" || type.kind === "Scalar")) {
return new ObjectBuilder({
type: "object",
allOf: Builders.array([schema]),
...additionalProps,
});
} else {
return new ObjectBuilder({ allOf: Builders.array([schema]), ...additionalProps });
}
} else {
const merged = new ObjectBuilder<OpenAPI3Schema>(schema);
for (const [key, value] of Object.entries(additionalProps)) {
merged.set(key, value);
}
return merged;
}
}
};
const checkMerge = (schemaMembers: { schema: any; type: Type | null }[]): boolean => {
if (nullable) {
for (const m of schemaMembers) {
if (m.schema instanceof Placeholder || "$ref" in m.schema) {
return true;
}
}
}
return false;
};
if (schemaMembers.length === 0) {
if (nullable) {
// This union is equivalent to just `null` but OA3 has no way to specify
// null as a value, so we throw an error.
reportDiagnostic(program, { code: "union-null", target: union });
return new ObjectBuilder({});
} else {
// completely empty union can maybe only happen with bugs?
compilerAssert(false, "Attempting to emit an empty union");
}
}
if (schemaMembers.length === 1) {
return wrapWithObjectBuilder(schemaMembers[0], { mergeUnionWideConstraints: true });
}
const isMerge = checkMerge(schemaMembers);
const schema: OpenAPI3Schema = {
[ofType]: schemaMembers.map((m) =>
wrapWithObjectBuilder(m, { mergeUnionWideConstraints: isMerge }),
),
};
if (!isMerge && nullable) {
schema.nullable = true;
}
return this.applyConstraints(union, schema);
}
intrinsic(intrinsic: IntrinsicType, name: string): EmitterOutput<object> {
switch (name) {
case "unknown":
return {};
case "null":
return { nullable: true };
}
reportDiagnostic(this.emitter.getProgram(), {
code: "invalid-schema",
format: { type: name },
target: intrinsic,
});
return {};
}
}